chore: clean up esbuild builder logic (#1231)

This will allow us to add various caches and similar around the esbuild
builder easily in follow up PRs.

It also makes doing an AOT build-step + load assets from disk much
simpler.
This commit is contained in:
Luca Casonato
2023-06-03 10:24:15 +02:00
committed by GitHub
parent 736c5524d5
commit 3857a49f1c
7 changed files with 318 additions and 217 deletions
+20
View File
@@ -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";
+189
View File
@@ -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<string, string>;
/** 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<EsbuildSnapshot> {
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<esbuildTypes.BuildOptions> = 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<string, Uint8Array>();
const dependencies = new Map<string, string[]>();
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<string>) {
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<string>();
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<string, Uint8Array>;
#dependencies: Map<string, string[]>;
constructor(
files: Map<string, Uint8Array>,
dependencies: Map<string, string[]>,
) {
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) ?? [];
}
}
+23
View File
@@ -0,0 +1,23 @@
export {
EsbuildBuilder,
type EsbuildBuilderOptions,
EsbuildSnapshot,
type JSXConfig,
} from "./esbuild.ts";
export interface Builder {
build(): Promise<BuildSnapshot>;
}
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> | 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[];
}
-188
View File
@@ -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<void> = 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<string, Uint8Array> | Promise<void> | undefined = undefined;
#dev: boolean;
dependencyMap = new Map<string, string[]>();
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<string, string> = {
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<esbuildTypes.BuildOptions> = 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<string, Uint8Array>();
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<Map<string, Uint8Array>> {
if (this.#cache === undefined) {
this.#cache = this.bundle();
}
if (this.#cache instanceof Promise) {
await this.#cache;
}
return this.#cache as Map<string, Uint8Array>;
}
async get(path: string): Promise<Uint8Array | null> {
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}";` }),
);
},
};
}
+83 -26
View File
@@ -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<string, unknown>;
}
@@ -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> | 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<string, string> = {
"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<string, string> {
const entrypointBase = "../runtime/entrypoints";
const entryPoints: Record<string, string> = {
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;
}
+3 -3
View File
@@ -26,7 +26,7 @@ export interface RenderOptions<Data> {
plugins: Plugin[];
app: AppModule;
imports: string[];
dependencyMap: Map<string, string[]>;
dependenciesFn: (path: string) => string[];
url: URL;
params: Record<string, string | string[]>;
renderFn: RenderFunction;
@@ -221,8 +221,8 @@ export async function render<Data>(
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;