From a35a65aac4af82fb4b530e07ddc818e94a9fc10c Mon Sep 17 00:00:00 2001 From: Ricardo Gobbo de Souza Date: Tue, 5 Dec 2023 18:20:59 -0300 Subject: [PATCH] fix: avoid downloading existing fonts (#60) --- src/downloader.ts | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/downloader.ts b/src/downloader.ts index 5da0c10..2b32ae7 100644 --- a/src/downloader.ts +++ b/src/downloader.ts @@ -90,8 +90,7 @@ export class Downloader extends Hookable { await this.callHook('download-css:done', this.url, cssContent, fontsFromCss) // download fonts from css - const fonts = (await Promise.all(this.downloadFonts(fontsFromCss))) - .filter(font => font.inputText) + const fonts = await this.downloadFonts(fontsFromCss) // write css await this.callHook('write-css:before', cssPath, cssContent, fonts) @@ -103,17 +102,33 @@ export class Downloader extends Hookable { return true } - private downloadFonts (fonts: FontInputOutput[]) { + private async downloadFonts (fonts: FontInputOutput[]) { const { headers, base64, outputDir, fontsDir } = this.config + const downloadedFonts: FontInputOutput[] = [] + const _fonts:FontInputOutput[] = [] + + for (const font of fonts) { + const downloadedFont = downloadedFonts.find(f => f.inputFont === font.inputFont) + + if (downloadedFont) { + font.outputText = downloadedFont.outputText + + _fonts.push(font) + + continue + } - return fonts.map(async (font) => { await this.callHook('download-font:before', font) const response = await ofetch.raw(font.inputFont, { headers, responseType: 'arrayBuffer' }) + /* v8 ignore start */ if (!response?._data) { - return {} as FontInputOutput + _fonts.push(font) + + continue } + /* v8 ignore stop */ const buffer = Buffer.from(response?._data) @@ -128,10 +143,14 @@ export class Downloader extends Hookable { writeFileSync(fontPath, buffer, 'utf-8') } + _fonts.push(font) + await this.callHook('download-font:done', font) - return font - }) + downloadedFonts.push(font) + } + + return _fonts } private writeCss (path: string, content: string, fonts: FontInputOutput[]) { @@ -171,7 +190,6 @@ function parseFontsFromCss (content: string, fontsPath: string): FontInputOutput const urlPathname = new URL(url).pathname const ext = extname(urlPathname) if (ext.length < 2) { continue } - if (fonts.find(font => font.inputFont === url)) { continue } const filename = basename(urlPathname, ext) || '' const newFilename = formatFontFileName('{_family}-{weight}-{i}.{ext}', {