-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathassets.ts
More file actions
53 lines (46 loc) · 1.98 KB
/
Copy pathassets.ts
File metadata and controls
53 lines (46 loc) · 1.98 KB
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
import type { FontFaceData } from 'unifont'
import type { RawFontFaceData } from './types'
import { hash } from 'ohash'
import { extname } from 'pathe'
import { filename } from 'pathe/utils'
import { hasProtocol, joinRelativeURL, joinURL } from 'ufo'
import { formatToExtension, parseFont } from './css/render'
function toArray<T>(value?: T | T[]): T[] {
return !value || Array.isArray(value) ? value as T[] : [value]
}
export interface NormalizeFontDataContext {
dev: boolean
renderedFontURLs: Map<string, string>
assetsBaseURL: string
callback?: (filename: string, url: string) => void | Promise<void>
}
export async function normalizeFontData(context: NormalizeFontDataContext, faces: RawFontFaceData | FontFaceData[]): Promise<FontFaceData[]> {
const data: FontFaceData[] = []
for (const face of toArray(faces)) {
data.push({
...face,
unicodeRange: toArray(face.unicodeRange),
src: await Promise.all(toArray(face.src).map(async (src) => {
const source = typeof src === 'string' ? parseFont(src) : src
if ('url' in source && hasProtocol(source.url, { acceptRelative: true })) {
source.url = source.url.replace(/^\/\//, 'https://')
const _url = source.url.replace(/\?.*/, '')
const MAX_FILENAME_PREFIX_LENGTH = 50
const file = [
// TODO: investigate why negative ignore pattern below is being ignored
hash(filename(_url) || _url).replace(/^-+/, '').slice(0, MAX_FILENAME_PREFIX_LENGTH),
hash(source).replace(/-/, '_') + (extname(source.url) || formatToExtension(source.format) || ''),
].filter(Boolean).join('-')
context.renderedFontURLs.set(file, source.url)
source.originalURL = source.url
source.url = context.dev
? joinRelativeURL(context.assetsBaseURL, file)
: joinURL(context.assetsBaseURL, file)
await context.callback?.(file, source.url)
}
return source
})),
})
}
return data
}