ci: cache remote url in css files

This commit is contained in:
Julien Oculi 2024-02-05 17:35:19 +01:00
parent 4a51b54095
commit 315c80eb40
2 changed files with 37 additions and 2 deletions

View file

@ -1,6 +1,6 @@
import { join, parse, resolve, toFileUrl } from '$std/path/mod.ts'
import { bundleAsync } from 'lightningcss'
import { cssImports, Logger, uInt8ArrayConcat } from './helpers.ts'
import { Logger, cssImports, uInt8ArrayConcat } from './helpers.ts'
export async function builder(
{ filename, dev, assetDir, remote }: {
@ -85,7 +85,23 @@ export async function builder(
return url.toString()
},
},
visitor: {
Url({ loc, url }) {
if (remote && !url.startsWith('data:')) {
cache(url, remote, assetDir)
}
return { loc, url }
}
}
})
return { code, map }
}
async function cache(url: string, base: string, assetDir: string) {
const fullUrl = new URL(url, base)
const response = await fetch(fullUrl)
const file = await response.arrayBuffer()
const filepath = join(assetDir, url.split('?')[0])
await Deno.writeFile(filepath, new Uint8Array(file))
}

View file

@ -1,6 +1,7 @@
import { MiddlewareHandler } from '$fresh/server.ts'
import { contentType } from '$fresh/src/server/deps.ts'
import { ensureDir } from '$std/fs/ensure_dir.ts'
import { join } from '$std/path/mod.ts'
import { join, parse } from '$std/path/mod.ts'
import { bundleCss } from './bundler.ts'
export function cssHandler(sourceDir: string): MiddlewareHandler {
@ -32,7 +33,25 @@ export function cssHandler(sourceDir: string): MiddlewareHandler {
})
}
}
const resp = await ctx.next()
if (resp.status === 404) {
try {
const file = await Deno.readFile(join(assetDir, ctx.url.pathname))
const { ext } = parse(ctx.url.pathname)
return new Response(file, {
headers: {
'Content-Type': contentType(ext) ?? 'text/plain; charset=utf-8'
}
})
} catch {
return resp
}
}
//anyway
return resp
}
}