From 315c80eb4004fa13e496e70316827a3bd84f96bd Mon Sep 17 00:00:00 2001 From: Julien Oculi Date: Mon, 5 Feb 2024 17:35:19 +0100 Subject: [PATCH] ci: cache remote url in css files --- plugins/css_bundler/src/builder.ts | 18 +++++++++++++++++- plugins/css_bundler/src/middleware.ts | 21 ++++++++++++++++++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/plugins/css_bundler/src/builder.ts b/plugins/css_bundler/src/builder.ts index b7150d2..7a9c902 100644 --- a/plugins/css_bundler/src/builder.ts +++ b/plugins/css_bundler/src/builder.ts @@ -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)) +} \ No newline at end of file diff --git a/plugins/css_bundler/src/middleware.ts b/plugins/css_bundler/src/middleware.ts index f1d34c5..cb23944 100644 --- a/plugins/css_bundler/src/middleware.ts +++ b/plugins/css_bundler/src/middleware.ts @@ -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 } }