()
| 15 | export { inlineHtmlLocalAssets }; |
| 16 | |
| 17 | export function createHtmlAssetRegistry() { |
| 18 | const rootsByToken = new Map<string, string>(); |
| 19 | const tokensByRoot = new Map<string, string>(); |
| 20 | |
| 21 | function register(baseDir: string): string { |
| 22 | const root = resolvePath(baseDir); |
| 23 | const existing = tokensByRoot.get(root); |
| 24 | if (existing) return existing; |
| 25 | const token = crypto.randomUUID().replace(/-/g, "").slice(0, 16); |
| 26 | tokensByRoot.set(root, token); |
| 27 | rootsByToken.set(token, root); |
| 28 | return token; |
| 29 | } |
| 30 | |
| 31 | function rewriteHtml(html: string, htmlFilePath: string): string { |
| 32 | if (/^https?:\/\//i.test(htmlFilePath)) return html; |
| 33 | try { |
| 34 | const token = register(dirname(resolvePath(htmlFilePath))); |
| 35 | return rewriteHtmlAssetReferences( |
| 36 | html, |
| 37 | (assetPath) => `${HTML_ASSET_ROUTE_PREFIX}/${token}/${encodeHtmlAssetPath(assetPath)}`, |
| 38 | ); |
| 39 | } catch { |
| 40 | return html; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | function inlineHtml(html: string, htmlFilePath: string): string { |
| 45 | return inlineHtmlLocalAssets(html, htmlFilePath); |
| 46 | } |
| 47 | |
| 48 | async function handle(_req: Request, url: URL): Promise<Response | null> { |
| 49 | const prefix = `${HTML_ASSET_ROUTE_PREFIX}/`; |
| 50 | if (!url.pathname.startsWith(prefix)) return null; |
| 51 | |
| 52 | const rest = url.pathname.slice(prefix.length); |
| 53 | const slash = rest.indexOf("/"); |
| 54 | if (slash <= 0) { |
| 55 | return Response.json({ error: "Missing asset token or path" }, { status: 404 }); |
| 56 | } |
| 57 | |
| 58 | const token = rest.slice(0, slash); |
| 59 | const root = rootsByToken.get(token); |
| 60 | if (!root) { |
| 61 | return Response.json({ error: "Unknown asset root" }, { status: 404 }); |
| 62 | } |
| 63 | |
| 64 | const assetPath = normalizeHtmlAssetRoutePath(rest.slice(slash + 1)); |
| 65 | if (!assetPath) { |
| 66 | return Response.json({ error: "Invalid asset path" }, { status: 400 }); |
| 67 | } |
| 68 | |
| 69 | const contentType = htmlAssetContentType(assetPath); |
| 70 | if (!contentType) { |
| 71 | return Response.json({ error: "Unsupported asset type" }, { status: 415 }); |
| 72 | } |
| 73 | |
| 74 | const resolved = resolvePath(root, assetPath); |
no outgoing calls
no test coverage detected