-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
assets.ts
207 lines (192 loc) · 6.67 KB
/
assets.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { basename, extname, resolve } from 'node:path'
import { visit } from 'unist-util-visit'
import type { Element, Root as Hast } from 'hast'
import type { Root as Mdast, Node } from 'mdast'
import type { VFile } from 'vfile'
import type { Output } from './types'
/**
* Image object with metadata & blur image
*/
export interface Image {
/**
* public url of the image
*/
src: string
/**
* image width
*/
width: number
/**
* image height
*/
height: number
/**
* blurDataURL of the image
*/
blurDataURL: string
/**
* blur image width
*/
blurWidth: number
/**
* blur image height
*/
blurHeight: number
}
export const assets = new Map<string, string>()
// https://github.com/sindresorhus/is-absolute-url/blob/main/index.js
const ABS_URL_RE = /^[a-zA-Z][a-zA-Z\d+\-.]*?:/
const ABS_PATH_RE = /^(\/[^/\\]|[a-zA-Z]:\\)/
/**
* validate if a url is a relative path
* @param url url to validate
* @returns true if the url is a relative path
*/
export const isRelativePath = (url: string): boolean => {
if (url.startsWith('#')) return false // ignore hash anchor
if (url.startsWith('?')) return false // ignore query
if (url.startsWith('//')) return false // ignore protocol relative urlet name
if (ABS_URL_RE.test(url)) return false // ignore absolute url
if (ABS_PATH_RE.test(url)) return false // ignore absolute path
return true
}
/**
* get public directory
* @param buffer image buffer
* @returns image object with blurDataURL
*/
export const getImageMetadata = async (buffer: Buffer): Promise<Omit<Image, 'src'> | undefined> => {
const { default: sharp } = await import('sharp')
const img = sharp(buffer)
const { width, height } = await img.metadata()
if (width == null || height == null) return
const aspectRatio = width / height
const blurWidth = 8
const blurHeight = Math.round(blurWidth / aspectRatio)
const blurImage = await img.resize(blurWidth, blurHeight).webp({ quality: 1 }).toBuffer()
const blurDataURL = `data:image/webp;base64,${blurImage.toString('base64')}`
return { height, width, blurDataURL, blurWidth, blurHeight }
}
/**
* process referenced asset of a file
* @param input relative path of the asset
* @param from source file path
* @param filename output filename template
* @param baseUrl output public base url
* @param isImage process as image and return image object with blurDataURL
* @returns reference public url or image object
*/
export const processAsset = async <T extends true | undefined = undefined>(
input: string,
from: string,
filename: string,
baseUrl: string,
isImage?: T
): Promise<T extends true ? Image : string> => {
// e.g. input = '../assets/image.png?foo=bar#hash'
const queryIdx = input.indexOf('?')
const hashIdx = input.indexOf('#')
const index = Math.min(queryIdx >= 0 ? queryIdx : Infinity, hashIdx >= 0 ? hashIdx : Infinity)
const suffix = input.slice(index)
const path = resolve(from, '..', input.slice(0, index))
const ext = extname(path)
const buffer = await readFile(path)
const name = filename.replace(/\[(name|hash|ext)(:(\d+))?\]/g, (substring, ...groups) => {
const key = groups[0]
const length = groups[2] == null ? undefined : parseInt(groups[2])
switch (key) {
case 'name':
return basename(path, ext).slice(0, length)
case 'hash':
// TODO: md5 is slow and not-FIPS compliant, consider using sha256
// https://github.com/joshwiens/hash-perf
// https://stackoverflow.com/q/2722943
// https://stackoverflow.com/q/14139727
return createHash('md5').update(buffer).digest('hex').slice(0, length)
case 'ext':
return ext.slice(1, length)
}
return substring
})
const src = baseUrl + name + suffix
assets.set(name, path) // write to assets map waiting for copy
if (isImage !== true) return src as T extends true ? Image : string
const metadata = await getImageMetadata(buffer)
if (metadata == null) throw new Error(`invalid image: ${from}`)
return { src, ...metadata } as T extends true ? Image : string
}
export type CopyLinkedFilesOptions = Omit<Output, 'data' | 'clean'>
/**
* rehype (markdown) plugin to copy linked files to public path and replace their urls with public urls
*/
export const rehypeCopyLinkedFiles = (options: CopyLinkedFilesOptions) => async (tree: Hast, file: VFile) => {
const links = new Map<string, Element[]>()
const linkedPropertyNames = ['href', 'src', 'poster']
visit(tree, 'element', node => {
linkedPropertyNames.forEach(name => {
const value = node.properties[name]
if (typeof value === 'string' && isRelativePath(value)) {
const elements = links.get(value) ?? []
elements.push(node)
links.set(value, elements)
}
})
})
await Promise.all(
Array.from(links.entries()).map(async ([url, elements]) => {
const publicUrl = await processAsset(url, file.path, options.name, options.base)
if (publicUrl == null || publicUrl === url) return
elements.forEach(node => {
linkedPropertyNames.forEach(name => {
if (name in node.properties) {
node.properties[name] = publicUrl
}
})
})
})
)
}
/**
* remark (mdx) plugin to copy linked files to public path and replace their urls with public urls
*/
export const remarkCopyLinkedFiles = (options: CopyLinkedFilesOptions) => async (tree: Mdast, file: VFile) => {
const links = new Map<string, Node[]>()
const linkedPropertyNames = ['href', 'src', 'poster']
visit(tree, ['link', 'image', 'definition'], (node: any) => {
if (isRelativePath(node.url)) {
const nodes = links.get(node.url) || []
nodes.push(node)
links.set(node.url, nodes)
}
})
visit(tree, 'mdxJsxFlowElement', node => {
node.attributes.forEach((attr: any) => {
if (linkedPropertyNames.includes(attr.name) && typeof attr.value === 'string' && isRelativePath(attr.value)) {
const nodes = links.get(attr.value) || []
nodes.push(node)
links.set(attr.value, nodes)
}
})
})
await Promise.all(
Array.from(links.entries()).map(async ([url, nodes]) => {
const publicUrl = await processAsset(url, file.path, options.name, options.base)
if (publicUrl == null || publicUrl === url) return
nodes.forEach((node: any) => {
if (node.url === url) {
node.url = publicUrl
return
}
node.attributes.forEach((attr: any) => {
linkedPropertyNames.forEach(name => {
if (attr.name === name && attr.value === url) {
attr.value = publicUrl
}
})
})
})
})
)
}