@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 941 lines 32.6 KB
Raw
1 import * as NodeCrypto from "node:crypto";
2 import { createRequire } from "node:module";
3 import nodePath from "node:path";
4 import { pathToFileURL } from "node:url";
5 import type {
6 BindingHook,
7 BindingServices,
8 HyperdriveOrigin,
9 Assets as RuntimeAssets,
10 DurableObjectNamespace as RuntimeDurableObject,
11 QueueConsumer as RuntimeQueueConsumer,
12 RuntimeServices,
13 RuntimeWorker,
14 } from "@alchemy.run/cloudflare-runtime/core";
15 /**
16 * `@alchemy.run/frontend-frameworks/vinext/source` — alchemy Worker
17 * source provider for vinext. Implements the `WorkerSourceModule`
18 * contract structurally (no alchemy import).
19 *
20 * `build()` runs Vite's `createBuilder` in a child process with
21 * `@alchemy.run/cloudflare-runtime/vite` injected (the
22 * `vite-plugin-cloudflare:alchemy` presence plugin), then vinext prerender
23 * and a platform-agnostic cache seed (`putText` into KV HTTP).
24 * `hash()` is a project-tree memo. `dev()` is Vite's own server with
25 * the same plugin stack.
26 */
27 import cloudflare from "@alchemy.run/cloudflare-runtime/vite";
28 import type * as Context from "effect/Context";
29 import * as Data from "effect/Data";
30 import * as Effect from "effect/Effect";
31 import * as FileSystem from "effect/FileSystem";
32 import * as Path from "effect/Path";
33 import type { PlatformError } from "effect/PlatformError";
34 import * as Redacted from "effect/Redacted";
35 import type * as Scope from "effect/Scope";
36 import { resolveBuildEnv, runBuildChild } from "../core/BuildChild.ts";
37 import { toOutputFile, type BuildOutput } from "../core/BuildOutput.ts";
38 import { WORKER_ENTRY_PREFIX } from "../core/Collector.ts";
39 import { resolveViteDevPort } from "../core/DevPort.ts";
40 import { ModuleLoadError } from "../core/Loader.ts";
41 import { kvHttpNamespaceFromEnv, kvHttpSink } from "./cache/kv-http.ts";
42 import { makeVinextCachePlugin } from "./cache/plugin.ts";
43 import { seedPrerenderTo } from "./cache/seed.ts";
44 import {
45 ALCHEMY_CLOUDFLARE_VITE_INJECTED,
46 DEFAULT_WORKER_ENTRY,
47 makeVinextPluginOptions,
48 } from "./cloudflare.ts";
49 import { runVinextPrerenderIfConfigured } from "./Prerender.ts";
50 import { VINEXT_CACHE_BINDING, VINEXT_KV_CACHE_BINDING } from "./PrerenderCache.ts";
51
52 const PROVIDER = "@alchemy.run/frontend-frameworks/vinext/source";
53
54 const VINEXT_SERVER_ENTRIES = ["dist/server/index.js", "dist/server/ssr/index.js"] as const;
55
56 const RSC_MANIFEST = {
57 "virtual:vite-rsc/assets-manifest": "__vite_rsc_assets_manifest.js",
58 "virtual:vite-rsc/environment-imports": "__vite_rsc_env_imports_manifest.js",
59 } as const;
60
61 const PACKAGE_VERSION: string = (
62 createRequire(import.meta.url)("../../package.json") as { version: string }
63 ).version;
64
65 // ─────────────────────────────────────────────────────────────────────
66 // Structural mirror of alchemy's Worker source contract
67 // ─────────────────────────────────────────────────────────────────────
68
69 export interface SourceHash {
70 readonly bundle: string | undefined;
71 readonly assets: string | undefined;
72 readonly input: string | undefined;
73 readonly additionalWorkspaces: Array<string> | undefined;
74 }
75
76 export interface BundleFile {
77 readonly path: string;
78 readonly content: string | Uint8Array;
79 readonly hash: string;
80 }
81
82 export interface BundleOutput {
83 readonly files: [BundleFile, ...Array<BundleFile>];
84 readonly hash: string;
85 }
86
87 export interface AssetReadResult {
88 directory: string;
89 config: Record<string, unknown> | undefined;
90 manifest: Record<string, { hash: string; size: number }>;
91 _headers: string | undefined;
92 _redirects: string | undefined;
93 hash: string;
94 }
95
96 export interface SourceBuildOutput {
97 readonly bundle: BundleOutput | undefined;
98 readonly assets: AssetReadResult | undefined;
99 readonly hash: SourceHash;
100 }
101
102 export interface SourceContext {
103 readonly id: string;
104 readonly workerName: string;
105 readonly compatibility: {
106 readonly date: string;
107 readonly flags: Array<string>;
108 };
109 readonly entry:
110 | { readonly kind: "external" }
111 | { readonly kind: "effect"; readonly exports: Record<string, unknown> };
112 readonly stack: { readonly name: string; readonly stage: string };
113 readonly env: Record<string, unknown> | undefined;
114 readonly extraOptions: unknown;
115 readonly assets: unknown;
116 }
117
118 export interface DevContext extends SourceContext {
119 readonly worker: {
120 readonly bindings: Array<BindingHook<BindingServices>>;
121 readonly durableObjectNamespaces: Array<RuntimeDurableObject & { uniqueKey: string }>;
122 readonly hyperdrives: Record<string, Required<HyperdriveOrigin>>;
123 readonly queueConsumers: Effect.Effect<Array<RuntimeQueueConsumer>>;
124 readonly assets: RuntimeAssets | undefined;
125 /**
126 * The Worker's other runtime settings (crons, Workflows, tail consumers,
127 * Cache API, `request.cf`, zone, Access), spread whole into the runtime
128 * Worker.
129 */
130 readonly options: Pick<
131 RuntimeWorker,
132 "workflows" | "crons" | "tails" | "streamingTails" | "cache" | "cf" | "zone" | "access"
133 >;
134 };
135 readonly runtimeContext: Context.Context<RuntimeServices>;
136 }
137
138 export interface ServerDevHandle {
139 readonly mode: "server";
140 readonly url: URL;
141 }
142
143 export class SourceProviderError extends Data.TaggedError(
144 "Cloudflare.Workers.SourceProviderError",
145 )<{
146 readonly provider: string;
147 readonly message: string;
148 readonly cause?: unknown;
149 }> {}
150
151 export type VinextSourceError = SourceProviderError | PlatformError | ModuleLoadError;
152 export type SourceRequirements = FileSystem.FileSystem | Path.Path;
153
154 export interface SourceProvider {
155 readonly ownsAssets: boolean;
156 readonly devAssetsBinding?: boolean;
157 readonly build: (
158 ctx: SourceContext,
159 ) => Effect.Effect<SourceBuildOutput, VinextSourceError, SourceRequirements>;
160 readonly hash: (
161 ctx: SourceContext,
162 previous: SourceHash | undefined,
163 ) => Effect.Effect<Partial<SourceHash>, VinextSourceError, SourceRequirements>;
164 readonly dev: (
165 ctx: DevContext,
166 ) => Effect.Effect<ServerDevHandle, VinextSourceError, SourceRequirements | Scope.Scope>;
167 }
168
169 export interface VinextMemoOptions {
170 readonly include?: Array<string> | undefined;
171 readonly exclude?: Array<string> | undefined;
172 readonly lockfile?: boolean | undefined;
173 }
174
175 export interface VinextSourceOptions {
176 readonly rootDir?: string | undefined;
177 readonly main?: string | undefined;
178 readonly memo?: VinextMemoOptions | undefined;
179 readonly viteEnvironments?: {
180 readonly entry?: string;
181 readonly children?: ReadonlyArray<string>;
182 };
183 }
184
185 export interface VinextBuildChildConfig {
186 readonly rootDir: string;
187 readonly main: string | undefined;
188 readonly compatibilityDate: string;
189 readonly compatibilityFlags: Array<string>;
190 readonly viteEnvironments: { entry?: string; children?: ReadonlyArray<string> } | undefined;
191 }
192
193 const sha256 = (input: string | Uint8Array): string =>
194 NodeCrypto.createHash("sha256").update(input).digest("hex");
195
196 const stableValue = (value: unknown): unknown => {
197 if (Array.isArray(value)) return value.map(stableValue);
198 if (value !== null && typeof value === "object" && value.constructor === Object) {
199 return Object.fromEntries(
200 Object.entries(value as Record<string, unknown>)
201 .sort(([a], [b]) => a.localeCompare(b))
202 .map(([key, nested]) => [key, stableValue(nested)]),
203 );
204 }
205 return value;
206 };
207
208 const sha256Object = (value: unknown): string => sha256(JSON.stringify(stableValue(value)));
209
210 const isBindingMarker = (value: unknown): boolean =>
211 typeof value === "object" && value !== null && "~alchemy/Kind" in value;
212
213 // ─────────────────────────────────────────────────────────────────────
214 // Hash / assets (same contract as waku/source)
215 // ─────────────────────────────────────────────────────────────────────
216
217 const LOCKFILE_NAMES = [
218 "bun.lock",
219 "bun.lockb",
220 "package-lock.json",
221 "pnpm-lock.yaml",
222 "yarn.lock",
223 ];
224
225 const escapeRegExpChar = (char: string): string =>
226 /[.*+?^${}()|[\]\\]/.test(char) ? `\\${char}` : char;
227
228 const globBodyToRegExpSource = (glob: string): string => {
229 let source = "";
230 let i = 0;
231 while (i < glob.length) {
232 const char = glob[i]!;
233 if (char === "*") {
234 if (glob[i + 1] === "*") {
235 if (glob[i + 2] === "/") {
236 source += "(?:[^/]+/)*";
237 i += 3;
238 } else {
239 source += ".*";
240 i += 2;
241 }
242 } else {
243 source += "[^/]*";
244 i += 1;
245 }
246 } else if (char === "?") {
247 source += "[^/]";
248 i += 1;
249 } else {
250 source += escapeRegExpChar(char);
251 i += 1;
252 }
253 }
254 return source;
255 };
256
257 const compileIgnoreRule = (raw: string): RegExp | undefined => {
258 let rule = raw.trim();
259 if (rule.length === 0 || rule.startsWith("#") || rule.startsWith("!")) {
260 return undefined;
261 }
262 if (rule.endsWith("/")) rule = rule.slice(0, -1);
263 if (rule.length === 0) return undefined;
264 const anchored = rule.includes("/");
265 if (rule.startsWith("/")) rule = rule.slice(1);
266 const body = globBodyToRegExpSource(rule);
267 const prefix = anchored ? "^" : "^(?:.*/)?";
268 return new RegExp(`${prefix}${body}(?:/.*)?$`);
269 };
270
271 const compileIgnoreRules = (rules: ReadonlyArray<string>): Array<RegExp> =>
272 rules.map(compileIgnoreRule).filter((regex): regex is RegExp => regex !== undefined);
273
274 const compileIncludeGlobs = (globs: ReadonlyArray<string>): Array<RegExp> =>
275 globs.map((glob) => new RegExp(`^${globBodyToRegExpSource(glob)}$`));
276
277 const matchesAny = (regexes: ReadonlyArray<RegExp>, path: string): boolean =>
278 regexes.some((regex) => regex.test(path));
279
280 const findUp = Effect.fn(function* (startDir: string, filenames: ReadonlyArray<string>) {
281 const fs = yield* FileSystem.FileSystem;
282 const path = yield* Path.Path;
283 let dir = startDir;
284 for (;;) {
285 for (const filename of filenames) {
286 const candidate = path.join(dir, filename);
287 if (yield* fs.exists(candidate)) return candidate;
288 }
289 const parent = path.dirname(dir);
290 if (parent === dir) return undefined;
291 dir = parent;
292 }
293 });
294
295 const readGitIgnoreRules = Effect.fn(function* (rootDir: string) {
296 const fs = yield* FileSystem.FileSystem;
297 const path = yield* Path.Path;
298 const chain: Array<Array<string>> = [];
299 let dir = rootDir;
300 for (;;) {
301 const gitignore = path.join(dir, ".gitignore");
302 if (yield* fs.exists(gitignore)) {
303 chain.unshift((yield* fs.readFileString(gitignore)).split("\n"));
304 }
305 if (yield* fs.exists(path.join(dir, ".git"))) break;
306 const parent = path.dirname(dir);
307 if (parent === dir) break;
308 dir = parent;
309 }
310 return chain.flat();
311 });
312
313 interface ResolvedMemo {
314 readonly include: Array<RegExp> | undefined;
315 readonly exclude: Array<RegExp>;
316 readonly lockfile: boolean;
317 }
318
319 const resolveMemo = Effect.fn(function* (
320 rootDir: string,
321 distDir: string,
322 memo: VinextMemoOptions | undefined,
323 ) {
324 const exclude =
325 memo?.exclude !== undefined
326 ? compileIgnoreRules(memo.exclude)
327 : compileIgnoreRules(yield* readGitIgnoreRules(rootDir));
328 return {
329 include: memo?.include !== undefined ? compileIncludeGlobs(memo.include) : undefined,
330 exclude: [...compileIgnoreRules(["node_modules", ".git", `/${distDir}`]), ...exclude],
331 lockfile: memo?.lockfile ?? !(memo?.include || memo?.exclude),
332 } satisfies ResolvedMemo;
333 });
334
335 const hashDirectory = Effect.fn(function* (rootDir: string, memo: ResolvedMemo) {
336 const fs = yield* FileSystem.FileSystem;
337 const path = yield* Path.Path;
338 const files: Array<string> = [];
339 const walk: (dir: string, rel: string) => Effect.Effect<void, PlatformError> = Effect.fn(
340 function* (dir: string, rel: string) {
341 const entries = (yield* fs.readDirectory(dir)).sort();
342 for (const entry of entries) {
343 const relPath = rel === "" ? entry : `${rel}/${entry}`;
344 if (matchesAny(memo.exclude, relPath)) continue;
345 const absPath = path.join(dir, entry);
346 const stat = yield* fs.stat(absPath);
347 if (stat.type === "Directory") {
348 yield* walk(absPath, relPath);
349 } else if (stat.type === "File") {
350 if (memo.include !== undefined && !matchesAny(memo.include, relPath)) {
351 continue;
352 }
353 files.push(relPath);
354 }
355 }
356 },
357 );
358 yield* walk(rootDir, "");
359 if (memo.lockfile) {
360 const lockfile = yield* findUp(rootDir, LOCKFILE_NAMES);
361 if (lockfile !== undefined) {
362 const relative = path.relative(rootDir, lockfile).replaceAll("\\", "/");
363 if (!files.includes(relative)) files.push(relative);
364 }
365 }
366 const hashes = yield* Effect.forEach(
367 files.sort(),
368 Effect.fn(function* (file) {
369 return `${file}:${sha256(yield* fs.readFile(path.join(rootDir, file)))}`;
370 }),
371 { concurrency: 16 },
372 );
373 return sha256Object(hashes);
374 });
375
376 const hashVinextInput = Effect.fn(function* (params: {
377 rootDir: string;
378 memo: VinextMemoOptions | undefined;
379 options: VinextSourceOptions;
380 workspaces: Iterable<string>;
381 }) {
382 const path = yield* Path.Path;
383 const memo = yield* resolveMemo(params.rootDir, "dist", params.memo);
384 const workspaceMemo = yield* resolveMemo(params.rootDir, "dist", undefined);
385 const [root, ...workspaceHashes] = yield* Effect.all(
386 [
387 hashDirectory(params.rootDir, memo),
388 ...Array.from(params.workspaces).map((workspace) =>
389 Effect.gen(function* () {
390 const resolved = path.resolve(params.rootDir, workspace);
391 const rules = yield* readGitIgnoreRules(resolved);
392 const hash = yield* hashDirectory(resolved, {
393 ...workspaceMemo,
394 exclude: [...workspaceMemo.exclude, ...compileIgnoreRules(rules)],
395 });
396 return `${path.relative(params.rootDir, resolved).replaceAll("\\", "/")}:${hash}`;
397 }),
398 ),
399 ],
400 { concurrency: 4 },
401 );
402 return {
403 hash: sha256Object({
404 version: PACKAGE_VERSION,
405 root,
406 workspaces: workspaceHashes.sort(),
407 options: {
408 main: params.options.main,
409 viteEnvironments: params.options.viteEnvironments,
410 },
411 }),
412 workspaces: Array.from(params.workspaces).map((workspace) =>
413 path.relative(params.rootDir, path.resolve(params.rootDir, workspace)).replaceAll("\\", "/"),
414 ),
415 };
416 });
417
418 const SPECIAL_ASSET_FILES = [".assetsignore", "_headers", "_redirects"];
419
420 const maybeReadString = Effect.fn(function* (file: string) {
421 const fs = yield* FileSystem.FileSystem;
422 return yield* fs.readFileString(file).pipe(
423 Effect.catchIf(
424 (error) => error._tag === "PlatformError" && error.reason._tag === "NotFound",
425 () => Effect.undefined,
426 ),
427 );
428 });
429
430 const readClientAssets = Effect.fn(function* (
431 directory: string,
432 config: Record<string, unknown> | undefined,
433 ) {
434 const fs = yield* FileSystem.FileSystem;
435 const path = yield* Path.Path;
436 const [entries, ignoreFile, _headers, _redirects] = yield* Effect.all([
437 fs.readDirectory(directory, { recursive: true }),
438 maybeReadString(path.join(directory, ".assetsignore")),
439 maybeReadString(path.join(directory, "_headers")),
440 maybeReadString(path.join(directory, "_redirects")),
441 ]);
442 const ignores = compileIgnoreRules([...SPECIAL_ASSET_FILES, ...(ignoreFile?.split("\n") ?? [])]);
443 const manifest = new Map<string, { hash: string; size: number }>();
444 yield* Effect.forEach(
445 entries,
446 Effect.fn(function* (name) {
447 const relPath = name.replaceAll("\\", "/");
448 if (matchesAny(ignores, relPath)) return;
449 const file = path.join(directory, name);
450 const stat = yield* fs.stat(file);
451 if (stat.type !== "File") return;
452 const content = yield* fs.readFile(file);
453 manifest.set(relPath.startsWith("/") ? relPath : `/${relPath}`, {
454 hash: sha256(content).slice(0, 32),
455 size: Number(stat.size),
456 });
457 }),
458 { concurrency: 16 },
459 );
460 const sortedManifest = Object.fromEntries(
461 Array.from(manifest.entries()).sort((a, b) => a[0].localeCompare(b[0])),
462 );
463 return {
464 directory,
465 config,
466 manifest: sortedManifest,
467 _headers,
468 _redirects,
469 hash: sha256Object({
470 config,
471 manifest: sortedManifest,
472 _headers,
473 _redirects,
474 }),
475 } satisfies AssetReadResult;
476 });
477
478 const assetsConfigOf = (assets: unknown): Record<string, unknown> | undefined => {
479 if (assets === undefined || assets === null || typeof assets !== "object") {
480 return undefined;
481 }
482 const { directory: _d, hash: _h, ...config } = assets as Record<string, unknown>;
483 return Object.keys(config).length > 0 ? config : undefined;
484 };
485
486 // ─────────────────────────────────────────────────────────────────────
487 // Vite createBuilder + output collection
488 // ─────────────────────────────────────────────────────────────────────
489
490 type ViteModule = typeof import("vite");
491
492 const loadVite = async (projectRoot: string): Promise<ViteModule> => {
493 try {
494 const require = createRequire(nodePath.join(projectRoot, "package.json"));
495 return await import(/* @vite-ignore */ pathToFileURL(require.resolve("vite")).href);
496 } catch {
497 return await import("vite");
498 }
499 };
500
501 const getDefine = (env: Record<string, unknown>) =>
502 Object.fromEntries(
503 Object.entries(env).flatMap(([key, raw]) => {
504 if (!key.startsWith("VITE_")) return [];
505 const value = Redacted.isRedacted(raw) ? Redacted.value(raw) : raw;
506 return [[`import.meta.env.${key}`, JSON.stringify(value)] as const];
507 }),
508 );
509
510 const relativeJsImports = (code: string): readonly string[] => {
511 const specs = new Set<string>();
512 for (const match of code.matchAll(/(?:from|import)\s*["'](\.\.?\/[^"']+\.js)["']/g)) {
513 specs.add(match[1]!);
514 }
515 return [...specs];
516 };
517
518 interface EnvironmentLike {
519 readonly name: string;
520 readonly config: {
521 readonly base: string;
522 readonly root: string;
523 readonly build: { readonly outDir: string };
524 };
525 }
526
527 const makeOutputCollector = (entryEnvironment: string) => {
528 let clientDirectory: string | undefined;
529 let serverEntry: string | undefined;
530 const serverChunks = new Map<string, { content: string | Uint8Array }>();
531 const maybeExternalWorkspaces = new Set<string>();
532
533 const fileName = (name: string, environment: EnvironmentLike) => {
534 const outDir = environment.config.build.outDir;
535 const relativeOutDir = nodePath.isAbsolute(outDir)
536 ? nodePath.relative(environment.config.root, outDir)
537 : outDir;
538 return `${relativeOutDir.replaceAll("\\", "/")}/${name}`;
539 };
540
541 const plugin = {
542 name: "alchemy:vinext-build-output",
543 sharedDuringBuild: true,
544 async writeBundle(
545 this: {
546 environment: EnvironmentLike;
547 getModuleIds: () => Iterable<string>;
548 },
549 _opts: unknown,
550 bundle: Record<
551 string,
552 {
553 type: string;
554 fileName: string;
555 isEntry?: boolean;
556 facadeModuleId?: string | null;
557 code?: string;
558 source?: string | Uint8Array;
559 imports?: Array<string>;
560 }
561 >,
562 ) {
563 const root = nodePath.resolve(this.environment.config.root);
564 for (const id of this.getModuleIds()) {
565 if (!nodePath.isAbsolute(id) || id.includes("node_modules") || id.startsWith(root)) {
566 continue;
567 }
568 maybeExternalWorkspaces.add(nodePath.dirname(id));
569 }
570 if (this.environment.name === "client") {
571 clientDirectory = nodePath.resolve(root, this.environment.config.build.outDir);
572 return;
573 }
574 const files = Object.values(bundle);
575 if (this.environment.name === entryEnvironment) {
576 // Vinext's rsc environment can emit its own app entry alongside the
577 // wrapped Worker main; only the latter is a valid Worker module.
578 const entryChunk =
579 files.find(
580 (file) =>
581 file.type === "chunk" &&
582 file.isEntry &&
583 file.facadeModuleId?.startsWith(WORKER_ENTRY_PREFIX),
584 ) ?? files.find((file) => file.type === "chunk" && file.isEntry);
585 if (entryChunk) {
586 serverEntry = fileName(entryChunk.fileName, this.environment);
587 }
588 }
589 for (const file of files) {
590 if (file.type === "chunk") {
591 for (const spec of file.imports ?? []) {
592 if (spec in RSC_MANIFEST) {
593 const manifest = RSC_MANIFEST[spec as keyof typeof RSC_MANIFEST];
594 serverChunks.set(fileName(manifest, this.environment), {
595 content: "",
596 });
597 }
598 }
599 }
600 // Vite's build metadata (`.vite/manifest.json`), not a Worker module.
601 if (file.fileName.startsWith(".vite/")) continue;
602 const name = fileName(file.fileName, this.environment);
603 const content = file.type === "chunk" ? (file.code ?? "") : (file.source ?? "");
604 serverChunks.set(name, { content });
605 }
606 },
607 };
608
609 return {
610 plugin,
611 snapshot: () => ({
612 clientDirectory,
613 serverEntry,
614 serverChunks,
615 externalWorkspaces: maybeExternalWorkspaces,
616 }),
617 };
618 };
619
620 const readRscManifestsFromDisk = Effect.fn(function* (
621 root: string,
622 chunks: Map<string, { content: string | Uint8Array }>,
623 ) {
624 const fs = yield* FileSystem.FileSystem;
625 const path = yield* Path.Path;
626 for (const [name, chunk] of chunks) {
627 if (chunk.content !== "") continue;
628 const filePath = path.join(root, name);
629 if (yield* fs.exists(filePath)) {
630 chunks.set(name, { content: yield* fs.readFile(filePath) });
631 } else {
632 chunks.delete(name);
633 }
634 }
635 });
636
637 /**
638 * Vinext rewrites server chunks and writes sidecar modules (the action-owner
639 * manifest, `vinext-client-assets.js`) after `writeBundle`, so re-read every
640 * captured JS chunk from disk and follow its relative imports to pick up
641 * modules that were never part of a bundle.
642 */
643 const syncVinextServerModules = Effect.fn(function* (
644 root: string,
645 chunks: Map<string, { content: string | Uint8Array }>,
646 ) {
647 const fs = yield* FileSystem.FileSystem;
648 const path = yield* Path.Path;
649 const pending: string[] = [
650 ...VINEXT_SERVER_ENTRIES,
651 ...[...chunks.keys()].filter((name) => /\.[mc]?js$/.test(name)),
652 ];
653 const seen = new Set<string>();
654 while (pending.length > 0) {
655 const bundlePath = pending.pop()!;
656 if (seen.has(bundlePath)) continue;
657 seen.add(bundlePath);
658 const filePath = path.join(root, bundlePath);
659 if (!(yield* fs.exists(filePath))) continue;
660 const content = yield* fs.readFileString(filePath);
661 chunks.set(bundlePath, { content });
662 const dir = nodePath.posix.dirname(bundlePath);
663 for (const spec of relativeJsImports(content)) {
664 const next = nodePath.posix.normalize(nodePath.posix.join(dir, spec));
665 if (!next.startsWith("dist/server/") || chunks.has(next)) continue;
666 pending.push(next);
667 }
668 }
669 });
670
671 const collectExternalWorkspaces = Effect.fn(function* (dirs: Iterable<string>) {
672 const path = yield* Path.Path;
673 const found = yield* Effect.forEach(
674 dirs,
675 (directory) =>
676 findUp(directory, ["package.json"]).pipe(
677 Effect.map((file) => (file !== undefined ? path.dirname(file) : undefined)),
678 ),
679 { concurrency: "unbounded" },
680 );
681 return new Set(found.filter((dir): dir is string => dir !== undefined));
682 });
683
684 /**
685 * Child-process vinext production build. `runBuildChild` sets cwd to the
686 * project root before importing this module.
687 */
688 export const buildInChild = (config: VinextBuildChildConfig) =>
689 Effect.gen(function* () {
690 const path = yield* Path.Path;
691 const root = path.resolve(config.rootDir);
692 process.env[ALCHEMY_CLOUDFLARE_VITE_INJECTED] = "1";
693 const cachePlugin = yield* makeVinextCachePlugin(root, "kv");
694 const pluginOptions = makeVinextPluginOptions({
695 root,
696 main: config.main,
697 compatibilityDate: config.compatibilityDate,
698 compatibilityFlags: config.compatibilityFlags,
699 viteEnvironments: config.viteEnvironments,
700 });
701 const collector = makeOutputCollector(pluginOptions.viteEnvironments?.entry ?? "rsc");
702 const vite = yield* Effect.promise(() => loadVite(root));
703 yield* Effect.promise(async () => {
704 const builder = await vite.createBuilder(
705 {
706 root,
707 plugins: [cachePlugin, cloudflare(pluginOptions), collector.plugin as never],
708 logLevel: "warn",
709 },
710 null,
711 );
712 await builder.buildApp();
713 });
714 yield* runVinextPrerenderIfConfigured(root);
715 const snap = collector.snapshot();
716 yield* readRscManifestsFromDisk(root, snap.serverChunks);
717 yield* syncVinextServerModules(root, snap.serverChunks);
718 if (snap.serverChunks.size === 0) {
719 return {
720 distDirectory: path.join(root, "dist"),
721 clientDirectory: snap.clientDirectory,
722 serverModules: undefined,
723 externalWorkspaces: yield* collectExternalWorkspaces(snap.externalWorkspaces),
724 } satisfies BuildOutput;
725 }
726 const names = Array.from(snap.serverChunks.keys()).sort((a, b) => {
727 if (a === snap.serverEntry) return -1;
728 if (b === snap.serverEntry) return 1;
729 return a.localeCompare(b);
730 });
731 const serverModules = yield* Effect.forEach(names, (name) => {
732 const chunk = snap.serverChunks.get(name)!;
733 return toOutputFile(name, chunk.content);
734 });
735 return {
736 distDirectory: path.join(root, "dist"),
737 clientDirectory: snap.clientDirectory,
738 serverModules,
739 externalWorkspaces: yield* collectExternalWorkspaces(snap.externalWorkspaces),
740 } satisfies BuildOutput;
741 });
742
743 const resolveVinextCacheEnv = (env: Record<string, unknown>) =>
744 Effect.gen(function* () {
745 const resolved = { ...env };
746 for (const key of [VINEXT_KV_CACHE_BINDING, VINEXT_CACHE_BINDING]) {
747 const value = env[key];
748 if (value == null || isBindingMarker(value)) continue;
749 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- cache bindings are pre-resolved resource Effects
750 resolved[key] = Effect.isEffect(value) ? yield* value as Effect.Effect<unknown> : value;
751 }
752 return resolved;
753 });
754
755 /**
756 * Same `seedPrerenderTo(sink.putText)` as Redis / S3. The Worker provider
757 * layer supplies the distilled KV HTTP client. Closed as `Effect<void>`
758 * so the source contract stays `SourceRequirements`.
759 */
760 const seedVinextPrerenderCache = (
761 rootDir: string,
762 env: Record<string, unknown>,
763 ): Effect.Effect<void> =>
764 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- closed so the source contract stays SourceRequirements, see JSDoc
765 Effect.gen(function* () {
766 const namespace = kvHttpNamespaceFromEnv(env);
767 if (namespace === undefined) return;
768 const path = yield* Path.Path;
769 yield* seedPrerenderTo(kvHttpSink(namespace), {
770 rootDir: path.resolve(rootDir),
771 label: "Cloudflare KV",
772 }).pipe(
773 Effect.mapError(
774 (cause) =>
775 new SourceProviderError({
776 provider: PROVIDER,
777 message: "Failed to seed the vinext prerender cache.",
778 cause,
779 }),
780 ),
781 );
782 }) as Effect.Effect<void>;
783
784 export const makeVinextSourceProvider = (options: VinextSourceOptions): SourceProvider => {
785 const rootDirOf = (path: Path.Path): string =>
786 options.rootDir !== undefined ? path.resolve(options.rootDir) : process.cwd();
787
788 return {
789 ownsAssets: true,
790 // Dev runs the Worker in workerd with the Vite plugin's assets service.
791 devAssetsBinding: true,
792 build: Effect.fn(function* (ctx) {
793 const path = yield* Path.Path;
794 const rootDir = rootDirOf(path);
795 const output = yield* runBuildChild({
796 runtime: "node",
797 module: import.meta.url,
798 rootDir,
799 framework: "vinext",
800 env: resolveBuildEnv(ctx.env),
801 config: {
802 rootDir,
803 main: options.main,
804 compatibilityDate: ctx.compatibility.date,
805 compatibilityFlags: ctx.compatibility.flags,
806 viteEnvironments: options.viteEnvironments,
807 } satisfies VinextBuildChildConfig,
808 }).pipe(
809 Effect.mapError(
810 (error) =>
811 new SourceProviderError({
812 provider: PROVIDER,
813 message: "vinext build failed",
814 cause: error.cause ?? error,
815 }),
816 ),
817 );
818 if (output.serverModules === undefined || output.serverModules.length === 0) {
819 return yield* new SourceProviderError({
820 provider: PROVIDER,
821 message: "vinext build produced no server modules",
822 });
823 }
824 const files = output.serverModules.map((file) => ({
825 path: file.name.replaceAll("\\", "/"),
826 content: file.content,
827 hash: file.hash,
828 })) as [BundleFile, ...Array<BundleFile>];
829 const bundle: BundleOutput = {
830 files,
831 hash: sha256Object(files.map((file) => [file.path, file.hash])),
832 };
833 const [assets, input] = yield* Effect.all(
834 [
835 output.clientDirectory !== undefined
836 ? readClientAssets(output.clientDirectory, assetsConfigOf(ctx.assets))
837 : Effect.undefined,
838 hashVinextInput({
839 rootDir,
840 memo: options.memo,
841 options,
842 workspaces: output.externalWorkspaces,
843 }),
844 ],
845 { concurrency: "unbounded" },
846 );
847 yield* seedVinextPrerenderCache(rootDir, yield* resolveVinextCacheEnv(ctx.env ?? {}));
848 return {
849 bundle,
850 assets,
851 hash: {
852 bundle: bundle.hash,
853 assets: assets?.hash,
854 input: input.hash,
855 additionalWorkspaces: input.workspaces,
856 },
857 };
858 }),
859 hash: Effect.fn(function* (_ctx, previous) {
860 const path = yield* Path.Path;
861 const input = yield* hashVinextInput({
862 rootDir: rootDirOf(path),
863 memo: options.memo,
864 options,
865 workspaces: previous?.additionalWorkspaces ?? [],
866 });
867 return { input: input.hash, additionalWorkspaces: input.workspaces };
868 }),
869 dev: Effect.fn(function* (ctx) {
870 const path = yield* Path.Path;
871 const rootDir = rootDirOf(path);
872 process.env[ALCHEMY_CLOUDFLARE_VITE_INJECTED] = "1";
873 const cachePlugin = yield* makeVinextCachePlugin(rootDir, "kv");
874 const vite = yield* Effect.promise(() => loadVite(rootDir));
875 const port = yield* resolveViteDevPort(vite.version).pipe(
876 Effect.mapError(
877 (error) =>
878 new SourceProviderError({
879 provider: PROVIDER,
880 message: "Failed to allocate a vinext dev port",
881 cause: error,
882 }),
883 ),
884 );
885 const pluginOptions = makeVinextPluginOptions({
886 root: rootDir,
887 main: options.main ?? DEFAULT_WORKER_ENTRY,
888 compatibilityDate: ctx.compatibility.date,
889 compatibilityFlags: ctx.compatibility.flags,
890 viteEnvironments: options.viteEnvironments,
891 worker: {
892 ...ctx.worker.options,
893 name: ctx.workerName,
894 bindings: ctx.worker.bindings,
895 durableObjectNamespaces: ctx.worker.durableObjectNamespaces,
896 hyperdrives: ctx.worker.hyperdrives,
897 queueConsumers: yield* ctx.worker.queueConsumers,
898 assets: ctx.worker.assets,
899 },
900 context: ctx.runtimeContext,
901 });
902 const server = yield* Effect.acquireRelease(
903 Effect.promise(async () => {
904 const devServer = await vite.createServer({
905 root: rootDir,
906 define: getDefine(ctx.env ?? {}),
907 plugins: [cachePlugin, cloudflare(pluginOptions)],
908 server: { port, strictPort: false },
909 });
910 await devServer.listen();
911 return devServer;
912 }),
913 (devServer) => Effect.promise(() => devServer.close()),
914 );
915 const local = server.resolvedUrls?.local[0];
916 if (!local) {
917 return yield* new SourceProviderError({
918 provider: PROVIDER,
919 message: "vinext dev server started without a local URL",
920 });
921 }
922 return { mode: "server", url: new URL(local) } satisfies ServerDevHandle;
923 }),
924 };
925 };
926
927 const sourceModule = {
928 make: (options: unknown): Effect.Effect<SourceProvider, SourceProviderError> => {
929 if (options !== undefined && (typeof options !== "object" || options === null)) {
930 return Effect.fail(
931 new SourceProviderError({
932 provider: PROVIDER,
933 message: `Invalid options for ${PROVIDER}: expected an object, got ${typeof options}`,
934 }),
935 );
936 }
937 return Effect.succeed(makeVinextSourceProvider((options ?? {}) as VinextSourceOptions));
938 },
939 };
940
941 export default sourceModule;