diff --git a/src/build/deps.ts b/src/build/deps.ts new file mode 100644 index 00000000..e96bc119 --- /dev/null +++ b/src/build/deps.ts @@ -0,0 +1,20 @@ +// -- $std -- +export { + fromFileUrl, + toFileUrl, +} from "https://deno.land/std@0.189.0/path/mod.ts"; +export { escape as regexpEscape } from "https://deno.land/std@0.189.0/regexp/escape.ts"; + +// -- esbuild -- +// @deno-types="https://deno.land/x/esbuild@v0.17.11/mod.d.ts" +import * as esbuildWasm from "https://deno.land/x/esbuild@v0.17.11/wasm.js"; +import * as esbuildNative from "https://deno.land/x/esbuild@v0.17.11/mod.js"; +// @ts-ignore trust me +// deno-lint-ignore no-deprecated-deno-api +const esbuild: typeof esbuildWasm = Deno.run === undefined + ? esbuildWasm + : esbuildNative; +const esbuildWasmURL = new URL("./esbuild_v0.17.11.wasm", import.meta.url).href; +export { esbuild, esbuildWasm as esbuildTypes, esbuildWasmURL }; + +export { denoPlugins } from "https://deno.land/x/esbuild_deno_loader@0.7.0/mod.ts"; diff --git a/src/build/esbuild.ts b/src/build/esbuild.ts new file mode 100644 index 00000000..af721152 --- /dev/null +++ b/src/build/esbuild.ts @@ -0,0 +1,189 @@ +import { + denoPlugins, + esbuild, + esbuildTypes, + esbuildWasmURL, + fromFileUrl, + regexpEscape, + toFileUrl, +} from "./deps.ts"; +import { Builder, BuildSnapshot } from "./mod.ts"; + +export interface EsbuildBuilderOptions { + /** The build ID. */ + buildID: string; + /** The entrypoints, mapped from name to URL. */ + entrypoints: Record; + /** Whether or not this is a dev build. */ + dev: boolean; + /** The import map URL. */ + importMapURL: URL; + /** The JSX configuration. */ + jsxConfig: JSXConfig; +} + +export interface JSXConfig { + jsx: "react" | "react-jsx"; + jsxImportSource?: string; +} + +export class EsbuildBuilder implements Builder { + #options: EsbuildBuilderOptions; + + constructor(options: EsbuildBuilderOptions) { + this.#options = options; + } + + async build(): Promise { + const opts = this.#options; + try { + await initEsbuild(); + + const absWorkingDir = Deno.cwd(); + + // In dev-mode we skip identifier minification to be able to show proper + // component names in Preact DevTools instead of single characters. + const minifyOptions: Partial = opts.dev + ? { + minifyIdentifiers: false, + minifySyntax: true, + minifyWhitespace: true, + } + : { minify: true }; + + const bundle = await esbuild.build({ + entryPoints: opts.entrypoints, + + platform: "neutral", + target: ["chrome99", "firefox99", "safari15"], + + format: "esm", + bundle: true, + splitting: true, + treeShaking: true, + sourcemap: opts.dev ? "linked" : false, + ...minifyOptions, + + jsx: JSX_RUNTIME_MODE[opts.jsxConfig.jsx], + jsxImportSource: opts.jsxConfig.jsxImportSource, + + absWorkingDir, + outdir: ".", + write: false, + metafile: true, + + plugins: [ + buildIdPlugin(opts.buildID), + ...denoPlugins({ importMapURL: opts.importMapURL.href }), + ], + }); + + const files = new Map(); + const dependencies = new Map(); + + const absWorkingDirLen = toFileUrl(absWorkingDir).href.length + 1; + + for (const file of bundle.outputFiles) { + const path = toFileUrl(file.path).href.slice(absWorkingDirLen); + files.set(path, file.contents); + } + + const metaOutputs = new Map(Object.entries(bundle.metafile.outputs)); + + // deno-lint-ignore no-inner-declarations + function walk(path: string, seen: Set) { + if (seen.has(path)) return; + seen.add(path); + const entry = metaOutputs.get(path); + if (entry === undefined) return; + for (const dep of entry.imports) { + if (dep.kind === "import-statement") { + walk(dep.path, seen); + } + } + } + + for (const [path, entry] of metaOutputs.entries()) { + if (entry.entryPoint === undefined) continue; + const seen = new Set(); + walk(path, seen); + dependencies.set(path, [...seen]); + } + + return new EsbuildSnapshot(files, dependencies); + } finally { + stopEsbuild(); + } + } +} + +const JSX_RUNTIME_MODE = { + "react": "transform", + "react-jsx": "automatic", +} as const; + +async function initEsbuild() { + // deno-lint-ignore no-deprecated-deno-api + if (Deno.run === undefined) { + await esbuild.initialize({ + wasmURL: esbuildWasmURL, + worker: false, + }); + } else { + await esbuild.initialize({}); + } +} + +function stopEsbuild() { + esbuild.stop(); +} + +function buildIdPlugin(buildId: string): esbuildTypes.Plugin { + const file = import.meta.resolve("../runtime/build_id.ts"); + const url = new URL(file); + let options: esbuildTypes.OnLoadOptions; + if (url.protocol === "file:") { + const path = fromFileUrl(url); + const filter = new RegExp(`^${regexpEscape(path)}$`); + options = { filter, namespace: "file" }; + } else { + const namespace = url.protocol.slice(0, -1); + const path = url.href.slice(namespace.length + 1); + const filter = new RegExp(`^${regexpEscape(path)}$`); + options = { filter, namespace }; + } + return { + name: "fresh-build-id", + setup(build) { + build.onLoad( + options, + () => ({ contents: `export const BUILD_ID = "${buildId}";` }), + ); + }, + }; +} + +export class EsbuildSnapshot implements BuildSnapshot { + #files: Map; + #dependencies: Map; + + constructor( + files: Map, + dependencies: Map, + ) { + this.#files = files; + this.#dependencies = dependencies; + } + + get paths(): string[] { + return Object.keys(this.#files); + } + + read(path: string): Uint8Array | null { + return this.#files.get(path) ?? null; + } + + dependencies(path: string): string[] { + return this.#dependencies.get(path) ?? []; + } +} diff --git a/src/server/esbuild_v0.17.11.wasm b/src/build/esbuild_v0.17.11.wasm similarity index 100% rename from src/server/esbuild_v0.17.11.wasm rename to src/build/esbuild_v0.17.11.wasm diff --git a/src/build/mod.ts b/src/build/mod.ts new file mode 100644 index 00000000..a23a58af --- /dev/null +++ b/src/build/mod.ts @@ -0,0 +1,23 @@ +export { + EsbuildBuilder, + type EsbuildBuilderOptions, + EsbuildSnapshot, + type JSXConfig, +} from "./esbuild.ts"; +export interface Builder { + build(): Promise; +} + +export interface BuildSnapshot { + /** The list of files contained in this snapshot, not prefixed by a slash. */ + readonly paths: string[]; + + /** For a given file, return it's contents. + * @throws If the file is not contained in this snapshot. */ + read(path: string): ReadableStream | Uint8Array | null; + + /** For a given entrypoint, return it's list of dependencies. + * + * Returns an empty array if the entrypoint does not exist. */ + dependencies(path: string): string[]; +} diff --git a/src/server/bundle.ts b/src/server/bundle.ts deleted file mode 100644 index e0beaaed..00000000 --- a/src/server/bundle.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { - denoPlugins, - esbuild, - esbuildTypes, - escape, - fromFileUrl, - toFileUrl, -} from "./deps.ts"; -import { Island, Plugin } from "./types.ts"; -import { BUILD_ID } from "./build_id.ts"; - -export interface JSXConfig { - jsx: "react" | "react-jsx"; - jsxImportSource?: string; -} - -let esbuildInitialized: boolean | Promise = false; -async function ensureEsbuildInitialized() { - if (esbuildInitialized === false) { - // deno-lint-ignore no-deprecated-deno-api - if (Deno.run === undefined) { - const wasmURL = new URL("./esbuild_v0.17.11.wasm", import.meta.url).href; - esbuildInitialized = fetch(wasmURL).then(async (r) => { - const resp = new Response(r.body, { - headers: { "Content-Type": "application/wasm" }, - }); - const wasmModule = await WebAssembly.compileStreaming(resp); - await esbuild.initialize({ - wasmModule, - worker: false, - }); - }); - } else { - esbuild.initialize({}); - } - await esbuildInitialized; - esbuildInitialized = true; - } else if (esbuildInitialized instanceof Promise) { - await esbuildInitialized; - } -} - -const JSX_RUNTIME_MODE = { - "react": "transform", - "react-jsx": "automatic", -} as const; - -export class Bundler { - #importMapURL: URL; - #jsxConfig: JSXConfig; - #islands: Island[]; - #plugins: Plugin[]; - #cache: Map | Promise | undefined = undefined; - #dev: boolean; - dependencyMap = new Map(); - - constructor( - islands: Island[], - plugins: Plugin[], - importMapURL: URL, - jsxConfig: JSXConfig, - dev: boolean, - ) { - this.#islands = islands; - this.#plugins = plugins; - this.#importMapURL = importMapURL; - this.#jsxConfig = jsxConfig; - this.#dev = dev; - } - - async bundle() { - const entrypointBase = "../../src/runtime/entrypoints"; - const entryPoints: Record = { - main: this.#dev - ? import.meta.resolve(`${entrypointBase}/main_dev.ts`) - : import.meta.resolve(`${entrypointBase}/main.ts`), - deserializer: import.meta.resolve(`${entrypointBase}/deserializer.ts`), - }; - - try { - import.meta.resolve("@preact/signals"); - entryPoints.signals = import.meta.resolve(`${entrypointBase}/signals.ts`); - } catch { - // @preact/signals is not in the import map - } - - for (const island of this.#islands) { - entryPoints[`island-${island.id}`] = island.url; - } - - for (const plugin of this.#plugins) { - for (const [name, url] of Object.entries(plugin.entrypoints ?? {})) { - entryPoints[`plugin-${plugin.name}-${name}`] = url; - } - } - - const absWorkingDir = Deno.cwd(); - await ensureEsbuildInitialized(); - // In dev-mode we skip identifier minification to be able to show proper - // component names in Preact DevTools instead of single characters. - const minifyOptions: Partial = this.#dev - ? { minifyIdentifiers: false, minifySyntax: true, minifyWhitespace: true } - : { minify: true }; - const bundle = await esbuild.build({ - bundle: true, - entryPoints, - format: "esm", - metafile: true, - ...minifyOptions, - outdir: ".", - // This is requried to ensure the format of the outputFiles path is the same - // between windows and linux - absWorkingDir, - outfile: "", - platform: "neutral", - plugins: [ - buildIdPlugin(BUILD_ID), - ...denoPlugins({ importMapURL: this.#importMapURL.href }), - ], - sourcemap: this.#dev ? "linked" : false, - splitting: true, - target: ["chrome99", "firefox99", "safari15"], - treeShaking: true, - write: false, - jsx: JSX_RUNTIME_MODE[this.#jsxConfig.jsx], - jsxImportSource: this.#jsxConfig.jsxImportSource, - }); - const metafileOutputs = bundle.metafile!.outputs; - - for (const path in metafileOutputs) { - const meta = metafileOutputs[path]; - const imports = meta.imports - .filter(({ kind }) => kind === "import-statement") - .map(({ path }) => `/${path}`); - this.dependencyMap.set(`/${path}`, imports); - } - - const cache = new Map(); - const absDirUrlLength = toFileUrl(absWorkingDir).href.length; - for (const file of bundle.outputFiles) { - cache.set( - toFileUrl(file.path).href.substring(absDirUrlLength), - file.contents, - ); - } - this.#cache = cache; - - return; - } - - async cache(): Promise> { - if (this.#cache === undefined) { - this.#cache = this.bundle(); - } - if (this.#cache instanceof Promise) { - await this.#cache; - } - return this.#cache as Map; - } - - async get(path: string): Promise { - const cache = await this.cache(); - return cache.get(path) ?? null; - } -} - -function buildIdPlugin(buildId: string): esbuildTypes.Plugin { - const file = import.meta.resolve("../runtime/build_id.ts"); - const url = new URL(file); - let options: esbuildTypes.OnLoadOptions; - if (url.protocol === "file:") { - const path = fromFileUrl(url); - options = { filter: new RegExp(escape(path)), namespace: "file" }; - } else { - const namespace = url.protocol.slice(0, -1); - const path = url.href.slice(namespace.length + 1); - options = { filter: new RegExp(escape(path)), namespace }; - } - return { - name: "fresh-build-id", - setup(build) { - build.onLoad( - options, - () => ({ contents: `export const BUILD_ID = "${buildId}";` }), - ); - }, - }; -} diff --git a/src/server/context.ts b/src/server/context.ts index ff15666e..82d7f014 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -11,7 +11,6 @@ import { import { h } from "preact"; import * as router from "./router.ts"; import { Manifest } from "./mod.ts"; -import { Bundler, JSXConfig } from "./bundle.ts"; import { ALIVE_URL, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts"; import { BUILD_ID } from "./build_id.ts"; import DefaultErrorHandler from "./default_error_page.ts"; @@ -37,6 +36,13 @@ import { import { render as internalRender } from "./render.ts"; import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts"; import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts"; +import { + Builder, + BuildSnapshot, + EsbuildBuilder, + JSXConfig, +} from "../build/mod.ts"; + interface RouterState { state: Record; } @@ -59,13 +65,13 @@ export class ServerContext { #routes: Route[]; #islands: Island[]; #staticFiles: StaticFile[]; - #bundler: Bundler; #renderFn: RenderFunction; #middlewares: MiddlewareRoute[]; #app: AppModule; #notFound: UnknownPage; #error: ErrorPage; #plugins: Plugin[]; + #builder: Builder | Promise | BuildSnapshot; constructor( routes: Route[], @@ -90,13 +96,13 @@ export class ServerContext { this.#error = error; this.#plugins = plugins; this.#dev = typeof Deno.env.get("DENO_DEPLOYMENT_ID") !== "string"; // Env var is only set in prod (on Deploy). - this.#bundler = new Bundler( - this.#islands, - this.#plugins, + this.#builder = new EsbuildBuilder({ + buildID: BUILD_ID, + entrypoints: collectEntrypoints(this.#dev, this.#islands, this.#plugins), importMapURL, + dev: this.#dev, jsxConfig, - this.#dev, - ); + }); } /** @@ -347,6 +353,28 @@ export class ServerContext { }; } + #maybeBuildSnapshot(): BuildSnapshot | null { + if ("build" in this.#builder || this.#builder instanceof Promise) { + return null; + } + return this.#builder; + } + + async #buildSnapshot() { + if ("build" in this.#builder) { + const builder = this.#builder; + this.#builder = builder.build(); + try { + const snapshot = await this.#builder; + this.#builder = snapshot; + } catch (err) { + this.#builder = builder; + throw err; + } + } + return this.#builder; + } + /** * Identify which middlewares should be applied for a request, * chain them and return a handler response @@ -509,7 +537,10 @@ export class ServerContext { plugins: this.#plugins, app: this.#app, imports, - dependencyMap: this.#bundler.dependencyMap, + dependenciesFn: (path) => { + const snapshot = this.#maybeBuildSnapshot(); + return snapshot?.dependencies(path) ?? []; + }, renderFn: this.#renderFn, url: new URL(req.url), params, @@ -699,27 +730,20 @@ export class ServerContext { */ #bundleAssetRoute = (): router.MatchHandler => { return async (_req, _ctx, params) => { - const path = `/${params.path}`; - const file = await this.#bundler.get(path); - let res; - if (file) { - const headers = new Headers({ - "Cache-Control": "public, max-age=604800, immutable", - }); + const snapshot = await this.#buildSnapshot(); + const contents = snapshot.read(params.path); + if (!contents) return new Response(null, { status: 404 }); - const contentType = typeByExtension(extname(path)); - if (contentType) { - headers.set("Content-Type", contentType); - } + const headers: Record = { + "Cache-Control": "public, max-age=604800, immutable", + }; - res = new Response(file, { - status: 200, - headers, - }); - } + const contentType = typeByExtension(extname(params.path)); + if (contentType) headers["Content-Type"] = contentType; - return res ?? new Response(null, { - status: 404, + return new Response(contents, { + status: 200, + headers, }); }; }; @@ -880,3 +904,36 @@ es.addEventListener("message", function listener(e) { } });`; } + +function collectEntrypoints( + dev: boolean, + islands: Island[], + plugins: Plugin[], +): Record { + const entrypointBase = "../runtime/entrypoints"; + const entryPoints: Record = { + main: dev + ? import.meta.resolve(`${entrypointBase}/main_dev.ts`) + : import.meta.resolve(`${entrypointBase}/main.ts`), + deserializer: import.meta.resolve(`${entrypointBase}/deserializer.ts`), + }; + + try { + import.meta.resolve("@preact/signals"); + entryPoints.signals = import.meta.resolve(`${entrypointBase}/signals.ts`); + } catch { + // @preact/signals is not in the import map + } + + for (const island of islands) { + entryPoints[`island-${island.id}`] = island.url; + } + + for (const plugin of plugins) { + for (const [name, url] of Object.entries(plugin.entrypoints ?? {})) { + entryPoints[`plugin-${plugin.name}-${name}`] = url; + } + } + + return entryPoints; +} diff --git a/src/server/render.ts b/src/server/render.ts index 20d054c0..9f5910b1 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -26,7 +26,7 @@ export interface RenderOptions { plugins: Plugin[]; app: AppModule; imports: string[]; - dependencyMap: Map; + dependenciesFn: (path: string) => string[]; url: URL; params: Record; renderFn: RenderFunction; @@ -221,8 +221,8 @@ export async function render( const url = bundleAssetUrl(path); imports.push([url, randomNonce]); preloadSet.add(url); - for (const depPath of opts.dependencyMap.get(path) ?? []) { - const url = bundleAssetUrl(depPath); + for (const depPath of opts.dependenciesFn(path)) { + const url = bundleAssetUrl(`/${depPath}`); preloadSet.add(url); } return url;