@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 131 lines 5.07 KB
Raw
1 import * as NodePath from "node:path";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import type * as Esbuild from "esbuild";
5
6 export class BundleError extends Data.TaggedError<"BundleError">("BundleError")<{
7 readonly message: string;
8 readonly cause?: unknown;
9 }> {}
10
11 /** The entry module name the final bundle pass emits. */
12 export const WORKER_ENTRY_NAME = "worker.js";
13
14 /**
15 * The per-output-file banner wrangler also injects: CJS-converted code inside
16 * the bundle (Next's compiled server) calls `require("fs")` etc. for
17 * externalized node builtins, and esbuild's `__require` shim throws
18 * `Dynamic require of "fs" is not supported` unless a real `require` is in
19 * scope. workerd's `nodejs_compat` implements `node:module.createRequire`.
20 *
21 * The `?? "file:///"` fallback is load-bearing: `import.meta.url` is
22 * `undefined` inside workerd modules, and a plain
23 * `createRequire(import.meta.url)` crashes the worker at startup.
24 */
25 export const CREATE_REQUIRE_BANNER = [
26 `import { createRequire as __distilled_createRequire } from "node:module";`,
27 `const require = /* @__PURE__ */ __distilled_createRequire(import.meta.url ?? "file:///");`,
28 ].join("\n");
29
30 /**
31 * OpenNext's `setWranglerExternal` esbuild plugin leaves `.wasm`/`.bin`
32 * imports in the server handler as ABSOLUTE paths (optionally with a
33 * `?module` suffix) "for wrangler to bundle". This plugin strips the suffix
34 * and routes them through esbuild's `copy` loader so they become relative
35 * file imports that can be registered as CompiledWasm/Data modules.
36 */
37 export const makeWranglerExternalsPlugin = (): Esbuild.Plugin => ({
38 name: "distilled-nextjs:wrangler-externals",
39 setup(build) {
40 build.onResolve({ filter: /\.(wasm|bin)(\?module)?$/ }, (args) => {
41 const clean = args.path.replace(/\?module$/, "");
42 return {
43 path: NodePath.isAbsolute(clean) ? clean : NodePath.resolve(args.resolveDir, clean),
44 };
45 });
46 },
47 });
48
49 export interface BundleWorkerOptions {
50 /** The `.open-next` directory produced by the OpenNext build pipeline. */
51 readonly openNextDirectory: string;
52 /** Directory the finished module set is written to. */
53 readonly outDirectory: string;
54 /** Minify the emitted modules. @default false */
55 readonly minify?: boolean | undefined;
56 }
57
58 export interface BundleWorkerResult {
59 /** The esbuild metafile of the pass. */
60 readonly metafile: Esbuild.Metafile;
61 }
62
63 /**
64 * The "final bundle pass" wrangler normally performs at deploy time:
65 * `.open-next/worker.js` (and its deliberately-unresolved relative imports —
66 * `cloudflare/*.js`, `middleware/handler.mjs`, `.build/durable-objects/*.js`)
67 * is bundled into a self-contained ESM module set.
68 *
69 * The four load-bearing rules (each discovered by a boot failure, not docs):
70 *
71 * 1. `format: "esm"` + `splitting: true` keeps the upstream
72 * `await import("./server-functions/default/handler.mjs")` a lazy chunk.
73 * 2. `conditions: ["workerd", "worker"]` resolves workerd-flavored exports.
74 * 3. `external: ["cloudflare:*", "node:*"]` — provided by workerd and
75 * `nodejs_compat` respectively.
76 * 4. {@link CREATE_REQUIRE_BANNER} per output file (see its doc).
77 *
78 * Plus the `.wasm`/`.bin` `?module` copy rule
79 * ({@link makeWranglerExternalsPlugin}).
80 */
81 export const bundleWorker = (
82 options: BundleWorkerOptions,
83 ): Effect.Effect<BundleWorkerResult, BundleError> =>
84 Effect.gen(function* () {
85 const esbuild = yield* Effect.tryPromise({
86 try: async () => await import("esbuild"),
87 catch: (cause) => new BundleError({ message: "Failed to load esbuild", cause }),
88 });
89 const result = yield* Effect.tryPromise({
90 try: () =>
91 esbuild.build({
92 // Pin the build's working directory: without it, esbuild uses its
93 // long-lived shared service process's cwd, which is captured when
94 // the service first spawns — under a concurrent engine that can be
95 // another build's transient chdir target (possibly deleted by the
96 // time this build runs), which fails resolution of even absolute
97 // entry paths.
98 absWorkingDir: options.openNextDirectory,
99 plugins: [makeWranglerExternalsPlugin()],
100 entryPoints: [NodePath.join(options.openNextDirectory, WORKER_ENTRY_NAME)],
101 outdir: options.outDirectory,
102 bundle: true,
103 format: "esm",
104 platform: "node",
105 target: "es2022",
106 conditions: ["workerd", "worker"],
107 splitting: true,
108 minify: options.minify ?? false,
109 sourcemap: false,
110 metafile: true,
111 external: ["cloudflare:*", "node:*"],
112 loader: {
113 ".wasm": "copy",
114 ".bin": "copy",
115 },
116 entryNames: "[name]",
117 chunkNames: "chunks/[name]-[hash]",
118 assetNames: "[name]-[hash]",
119 banner: {
120 js: CREATE_REQUIRE_BANNER,
121 },
122 logLevel: "silent",
123 }),
124 catch: (cause) =>
125 new BundleError({
126 message: "The final worker bundle pass failed",
127 cause,
128 }),
129 });
130 return { metafile: result.metafile };
131 });