import type { BundleResult } from "./bundle.ts"; import JSON5 from "./vendor/json5.ts"; import { Redis } from "@upstash/redis"; import { dirname, fromFileUrl, join, extname, basename } from "@std/path/posix"; import { decodeBase64 } from "@std/encoding/base64"; import { dispatchEvent, LOGGER_INFO, BUILD_CONFIG } from "@bundle/core"; import { generateHTMLMessages, generateResult } from "./generate-result.ts"; import { deleteFile, deleteFile as deleteGist, listFiles } from "./gist.ts"; import { executePreparedBundle } from "./execute.ts"; import { prepareBundleRequest } from "./request.ts"; import { getPackageResultKey, headers } from "./constants.ts"; export type { Config } from "./types.ts"; export { headers } from "./constants.ts"; let redis: Redis | undefined | null; const __dirname = dirname(fromFileUrl(import.meta.url)) // Define the directory where the .well-known files are stored const wellKnownDir = "./.well-known/"; export default { async fetch(req: Request) { try { // Note: request parsing + esbuild execution is shared with Workers. // Storage/caching here remains Deno-specific (Upstash Redis + gists), // and we intentionally preserve the existing Deno Deploy behavior. const referer = req.headers.get("Referer") || req.headers.get("Referrer"); const url = new URL(req.url); console.log(url.href) if (url.pathname === "/favicon.ico") return Response.redirect("https://bundlejs.com/favicon/favicon-api.ico"); if (url.pathname === "/apple-touch-icon.png" || url.pathname === "/apple-touch-icon-precomposed.png") return Response.redirect("https://bundlejs.com/favicon/apple-touch-icon.png"); if (url.pathname === "/sw.js" || url.pathname === "/robots.txt" || url.pathname === "/llms.txt") return Response.json({ "message": "no" }); if (url.pathname.startsWith("/.well-known/")) { const ext = extname(url.pathname); const fileName = basename(url.pathname); return new Response(await Deno.readFile(join(__dirname, wellKnownDir, fileName)), { status: 200, headers: [ ...headers, ['Cache-Control', 'max-age=180, public'], ['Content-Type', ext === ".png" ? "image/png" : (ext === ".yaml" ? "text/yaml" : "application/json")] ], }) } const docsQuery = url.searchParams.has("docs"); if (docsQuery) { return Response.redirect("https://blog.okikio.dev/documenting-an-online-bundler-bundlejs#heading-configuration"); } const badgeQuery = url.searchParams.has("badge") || ["/badge", "/badge/raster", "/badge-raster"].includes(url.pathname); const badgeResult = url.searchParams.get("badge"); const badgeStyle = url.searchParams.get("badge-style"); const badgeRasterQuery = url.searchParams.has("badge-raster") || url.searchParams.has("png") || ["/badge/raster", "/badge-raster"].includes(url.pathname); const fileCheck = url.searchParams.has("file") || url.pathname === "/file"; const prepared = await prepareBundleRequest(url); const { badgeID, badgeKey, exportAll, initialValue, jsonKey, modules, mutationQueries, query, shareQuery, textQuery, versions, } = prepared; try { if (!redis) { redis = new Redis({ url: Deno.env.get('UPSTASH_URL') ?? "", token: Deno.env.get('UPSTASH_TOKEN') ?? "", }) } } catch (e) { console.warn(e) } if (url.pathname === "/clear-all-cache-123") { const clearGists = url.searchParams.has("gist") || url.searchParams.has("gists"); if (clearGists) { let breakIteration = false; const body = new ReadableStream({ async start(controller) { controller.enqueue("Started clearing cache including gists!\n") await redis?.flushall() for await (const gists of listFiles()) { const files = gists.data; if (!files || files.length <= 0 || breakIteration) break; let log = ''; await Promise.all( files.map(async (file: { id: string; }) => { const id = file.id; await deleteFile(id); log += `Deleted ${id}\n`; }) ) console.log(log) controller.enqueue(log); } controller.enqueue("\nCleared entire cache + gists...careful now.") controller.close(); }, cancel() { breakIteration = true; }, }); return new Response(body .pipeThrough(new TextEncoderStream()), { headers: { "Content-Type": "text/plain", "x-content-type-options": "nosniff" }, }); } else { if (redis) await redis.flushdb({ async: true }) return new Response(`Started clearing cache!\n${!redis ? "Redis is unavailable, try again at a later date!" : "Cleared entire cache"}`, { headers: { "Content-Type": "text/plain", "x-content-type-options": "nosniff" }, }); } } try { if (!redis) throw new Error("Redis not available"); if (url.pathname === "/delete-cache") { try { console.log(`Deleting ${badgeKey}\n`) const JSONResultString = await redis.get(jsonKey); const JSONResult = JSONResultString ? JSON5.parse(JSONResultString) : null; const [moduleName] = modules[0]; const PackageResultKey = getPackageResultKey(moduleName) + "/" + jsonKey; const PackageResultString = await redis.get(PackageResultKey); const PackageResult = PackageResultString ? JSON5.parse(PackageResultString) : null; await redis.del(jsonKey, badgeKey, PackageResultKey); console.log(`Deleting "${getPackageResultKey(moduleName)}" and ${jsonKey}\n`) if (JSONResult && JSONResult.fileId) { await deleteGist(JSONResult.fileId); console.log("Deleting `jsonKey` gist") } if ( JSONResult && PackageResult && PackageResult.fileId && JSONResult.fileId && JSONResult?.fileId !== PackageResult?.fileId ) { await deleteGist(PackageResult.fileId); console.log("Deleting `packageResult` gist") } console.log(`Deleted ${badgeKey}`) return new Response("Deleted from cache!"); } catch (e) { console.warn(e); return new Response("Error, deleting from cache"); } } if (url.pathname !== "/no-cache") { const BADGEResult = await redis.hget(badgeKey, badgeID); const JSONStringValue = await redis.get(jsonKey); const JSONResult = JSONStringValue ? JSON5.parse(JSONStringValue) : null; if (badgeQuery && BADGEResult && JSONResult) { dispatchEvent(LOGGER_INFO, { badgeResult, badgeQuery, badgeStyle, badgeRasterQuery }) console.log("Respond with Cached Badge") return new Response(badgeRasterQuery ? decodeBase64(BADGEResult) : BADGEResult, { status: 200, headers: [ ...headers, ['Cache-Control', 'max-age=36, public'], ['Content-Type', badgeRasterQuery ? "image/png" : 'image/svg+xml'] ], }) } else if (badgeQuery && !JSONResult) { // Pre-emptively delete badges to avoid them becoming stale await redis.del(badgeKey); } const start = Date.now(); const fileCheck = url.searchParams.has("file") || url.pathname === "/file"; const fileQuery = fileCheck ? JSONResult?.fileId : true; if (JSONResult && fileQuery) { console.log("Respond with Cached JSON Response") return await generateResult([badgeKey, badgeID], [JSONResult, undefined], url, true, Date.now() - start, redis); } else if (modules.length === 1 && exportAll && !mutationQueries) { const [moduleName, mode] = modules[0]; if (mode === "export") { const PackageResultKey = getPackageResultKey(moduleName) + "/" + jsonKey; const PackageResultString = await redis.get(PackageResultKey); const PackageResult = PackageResultString ? JSON5.parse(PackageResultString) : null; const fileQuery = fileCheck ? PackageResult?.fileId : true; if (PackageResult && fileQuery) { console.log("Respond with Module Response from Permanent Cache", getPackageResultKey(moduleName), PackageResultKey) return await generateResult([badgeKey, badgeID], [PackageResult, undefined], url, true, Date.now() - start, redis); } } } } } catch (e) { console.warn('error-using-cache: ', e) } const start = Date.now(); const [response, resultText] = await executePreparedBundle(url, prepared); if (!response.ok) { const headers = response.headers; const status = response.status; return new Response(await response.arrayBuffer(), { headers, status }); } const value: BundleResult = await response.json(); try { if (!redis) throw new Error("Redis not available"); const prevValueString = await redis.get(jsonKey) await redis.set(jsonKey, JSON5.stringify(value), { ex: 86400 }); if (modules.length === 1 && exportAll && !(shareQuery || textQuery)) { const [moduleName, mode] = modules[0]; if (mode === "export") { const PackageResultKey = getPackageResultKey(moduleName) + "/" + jsonKey; await redis.set(PackageResultKey, JSON5.stringify(value)); } } await redis.del(badgeKey); if (prevValueString) { const jsonPrevValue = prevValueString ? JSON5.parse(prevValueString) : null; if (jsonPrevValue && typeof jsonPrevValue === "object" && jsonPrevValue.fileId) { await deleteGist(jsonPrevValue.fileId) } } } catch (e) { console.warn(e) } console.log("Respond with New Bundle Result") return await generateResult([badgeKey, badgeID], [value, resultText], url, false, Date.now() - start, redis); } catch (e) { if ("msgs" in (e as Error) && (e as Record).msgs) { try { return new Response( generateHTMLMessages((e as Record).msgs as string[]), { status: 404, headers: [ ['Content-Type', 'text/html'] ] } ) } catch (e) { console.warn({ msgsError: e }) } } console.error(e) return new Response( JSON.stringify({ error: (e as Error).toString() }), { status: 400, } ) } } }