Skip to content

Commit

Permalink
fix: avoid downloading existing fonts (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardogobbosouza authored Dec 5, 2023
1 parent d4b72a2 commit a35a65a
Showing 1 changed file with 26 additions and 8 deletions.
34 changes: 26 additions & 8 deletions src/downloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,7 @@ export class Downloader extends Hookable<DownloaderHooks> {
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)
Expand All @@ -103,17 +102,33 @@ export class Downloader extends Hookable<DownloaderHooks> {
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)

Expand All @@ -128,10 +143,14 @@ export class Downloader extends Hookable<DownloaderHooks> {
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[]) {
Expand Down Expand Up @@ -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}', {
Expand Down

0 comments on commit a35a65a

Please sign in to comment.