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) ?? [];
}
}
Binary file not shown.
+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[];
}