@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 1,747 lines 57.3 KB
Raw
1 import * as ByteSize from "effect/ByteSize";
2 import * as Data from "effect/Data";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Option from "effect/Option";
7 import * as Path from "effect/Path";
8 import * as ChildProcess from "effect/process/ChildProcess";
9 import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner";
10 import * as Redacted from "effect/Redacted";
11 import type { Scope } from "effect/Scope";
12 import * as Stream from "effect/Stream";
13 import { normalizeEntrypoint } from "./ComputeArchive.ts";
14
15 export class ComputeBuildInvalidProps extends Data.TaggedError("ComputeBuildInvalidProps")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export class ComputeBuildError extends Data.TaggedError("ComputeBuildError")<{
21 readonly message: string;
22 readonly cause?: unknown;
23 }> {}
24
25 // `@vercel/nft` is an optional peer dependency — loaded lazily so importing
26 // the Prisma provider never requires it unless a NestJS artifact is traced.
27 const importNft = () =>
28 import("@vercel/nft").catch((cause) => {
29 throw new Error(
30 "Failed to load '@vercel/nft'. Install the optional peer dependency '@vercel/nft' to build NestJS apps for Prisma Compute.",
31 { cause },
32 );
33 });
34
35 export type ComputeAutoBuildFramework =
36 | "auto"
37 | "nextjs"
38 | "nuxt"
39 | "astro"
40 | "nestjs"
41 | "tanstack-start"
42 | "vite"
43 | "bun";
44
45 export interface ComputeAutoBuildOptions {
46 /**
47 * Application root.
48 */
49 appPath: string;
50 /**
51 * Entrypoint used by the Bun fallback strategy.
52 */
53 entrypoint?: string;
54 /**
55 * Framework to build. `auto` tries Next.js, Nuxt, Astro, TanStack Start,
56 * Vite, then Bun.
57 *
58 * @default "auto"
59 */
60 framework?: ComputeAutoBuildFramework;
61 /**
62 * Environment variables supplied to the build command.
63 * Ambient `PRISMA_SERVICE_TOKEN` and `PRISMA_API_TOKEN` credentials are not
64 * inherited; include one here explicitly only when the application build
65 * genuinely needs Prisma Management API access.
66 *
67 * Plain strings are persisted in Alchemy state when this is configured
68 * through `Prisma.Compute`. Wrap secrets with `Redacted.make(secret)`.
69 *
70 * ```typescript
71 * env: { NPM_TOKEN: Redacted.make(process.env.NPM_TOKEN!) }
72 * ```
73 */
74 env?: Record<string, string | Redacted.Redacted<string> | undefined>;
75 /**
76 * Maximum bytes retained from each build output stream.
77 *
78 * @default 1048576 (1 MiB)
79 */
80 outputLimitBytes?: number;
81 /**
82 * Maximum wall-clock time for the framework build command.
83 *
84 * @default 900 (15 minutes)
85 */
86 timeoutSeconds?: number;
87 }
88
89 export interface ComputeBuildArtifact {
90 /**
91 * Directory to archive and upload.
92 */
93 directory: string;
94 /**
95 * Entrypoint relative to `directory`.
96 */
97 entrypoint: string;
98 /**
99 * Default HTTP port for framework conventions.
100 */
101 defaultPort?: number;
102 /**
103 * Directory within the artifact that user-authored archive ignore patterns
104 * are relative to.
105 */
106 archiveIgnorePrefix?: string;
107 /**
108 * Artifact-relative files that must remain present after archiving.
109 */
110 requiredFiles?: readonly string[];
111 /**
112 * Removes temporary build output.
113 */
114 cleanup: Effect.Effect<void, never, FileSystem.FileSystem>;
115 }
116
117 export interface ComputeStaticBuildOptions {
118 /**
119 * Application root.
120 */
121 appPath: string;
122 /**
123 * Optional shell command that creates the static output directory.
124 */
125 command?: string;
126 /**
127 * Working directory for the build command and static output.
128 *
129 * @default appPath
130 */
131 cwd?: string;
132 /**
133 * Static output directory, relative to `cwd`.
134 */
135 outdir: string;
136 /**
137 * HTML file served at the root and for SPA fallbacks.
138 *
139 * @default "index.html"
140 */
141 indexPage?: string;
142 /**
143 * Serve the index page when no static file matches the request.
144 *
145 * @default false
146 */
147 spa?: boolean;
148 /**
149 * Environment variables supplied to the build command.
150 */
151 env?: Record<string, string | Redacted.Redacted<string> | undefined>;
152 /**
153 * Maximum bytes retained from each build output stream.
154 *
155 * @default 1048576 (1 MiB)
156 */
157 outputLimitBytes?: number;
158 /**
159 * Maximum wall-clock time for the build command.
160 *
161 * @default 900 (15 minutes)
162 */
163 timeoutSeconds?: number;
164 }
165
166 interface BuildStrategy {
167 name: Exclude<ComputeAutoBuildFramework, "auto">;
168 canBuild: (appPath: string) => Effect.Effect<boolean, unknown, BuildServices>;
169 execute: (
170 options: Required<Pick<ComputeAutoBuildOptions, "appPath">> &
171 Omit<ComputeAutoBuildOptions, "appPath">,
172 ) => Effect.Effect<ComputeBuildArtifact, unknown, BuildServices>;
173 }
174
175 interface DirectoryEntry {
176 name: string;
177 type: "Directory" | "File" | "SymbolicLink" | "Other";
178 }
179
180 type BuildServices = ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Scope;
181
182 export interface RunBuildCommandOptions {
183 command: string;
184 cwd?: string;
185 /**
186 * Explicit environment variables supplied to the build command. Ambient
187 * Prisma Management API credentials are withheld unless they are provided
188 * here intentionally.
189 */
190 env?: Record<string, string>;
191 /**
192 * Maximum bytes retained from each output stream before the build is
193 * interrupted. This prevents noisy build tools from exhausting memory.
194 *
195 * @default 1048576 (1 MiB)
196 */
197 outputLimitBytes?: number;
198 /**
199 * Maximum wall-clock time for the build command.
200 *
201 * @default 900 (15 minutes)
202 */
203 timeoutSeconds?: number;
204 }
205
206 const DEFAULT_BUILD_OUTPUT_LIMIT_BYTES = 1024 * 1024;
207 const DEFAULT_BUILD_TIMEOUT_SECONDS = 15 * 60;
208 const STAGING_MAX_ENTRIES = 50_000;
209 const STAGING_MAX_TOTAL_BYTES = 768 * 1024 * 1024;
210 const STAGING_MAX_FILE_BYTES = 128 * 1024 * 1024;
211 const STAGING_TIMEOUT_SECONDS = 2 * 60;
212 const PRISMA_MANAGEMENT_CREDENTIAL_ENV_NAMES = new Set([
213 "PRISMA_SERVICE_TOKEN",
214 "PRISMA_API_TOKEN",
215 ]);
216
217 interface StagingBudget {
218 entries: number;
219 totalBytes: number;
220 readonly deadline: number;
221 }
222
223 const collectBoundedOutput = (
224 stream: Stream.Stream<Uint8Array, unknown>,
225 label: string,
226 limit: number,
227 ) =>
228 Stream.runFoldEffect(
229 stream,
230 () => ({ chunks: [] as Uint8Array[], bytes: 0 }),
231 (state, chunk) => {
232 const bytes = state.bytes + chunk.byteLength;
233 return bytes > limit
234 ? Effect.fail(
235 new ComputeBuildError({
236 message: `Build ${label} exceeded the ${limit} byte output safety limit. Reduce build verbosity or raise outputLimitBytes explicitly.`,
237 }),
238 )
239 : Effect.sync(() => {
240 state.chunks.push(chunk);
241 return { chunks: state.chunks, bytes };
242 });
243 },
244 ).pipe(
245 Effect.map(({ chunks, bytes }) => {
246 const output = new Uint8Array(bytes);
247 let offset = 0;
248 for (const chunk of chunks) {
249 output.set(chunk, offset);
250 offset += chunk.byteLength;
251 }
252 return { text: new TextDecoder().decode(output), bytes };
253 }),
254 );
255
256 /**
257 * Run a shell build command, dying on non-zero exit. Local stand-in for the
258 * removed `Build/Command.ts` helper. Build commands inherit the ambient
259 * environment except for Prisma Management API credentials, which must be
260 * passed explicitly through `env` when a build genuinely needs them.
261 */
262 export const runBuildCommand = Effect.fn(function* ({
263 command,
264 cwd,
265 env,
266 outputLimitBytes = DEFAULT_BUILD_OUTPUT_LIMIT_BYTES,
267 timeoutSeconds = DEFAULT_BUILD_TIMEOUT_SECONDS,
268 }: RunBuildCommandOptions) {
269 if (!Number.isSafeInteger(outputLimitBytes) || outputLimitBytes <= 0) {
270 return yield* new ComputeBuildInvalidProps({
271 message: "outputLimitBytes must be a positive safe integer",
272 });
273 }
274 if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
275 return yield* new ComputeBuildInvalidProps({
276 message: "timeoutSeconds must be a positive finite number",
277 });
278 }
279 const spawner = yield* ChildProcessSpawner;
280 const path = yield* Path.Path;
281 const resultOption = yield* Effect.scoped(
282 Effect.gen(function* () {
283 const handle = yield* spawner.spawn(
284 ChildProcess.make(command, [], {
285 cwd: path.resolve(cwd ?? "."),
286 shell: true,
287 env: buildProcessEnvironment(env),
288 extendEnv: false,
289 stdin: "ignore",
290 stdout: "pipe",
291 stderr: "pipe",
292 killSignal: "SIGKILL",
293 }),
294 );
295 const result = yield* Effect.all(
296 {
297 exitCode: handle.exitCode,
298 stdout: collectBoundedOutput(handle.stdout, "stdout", outputLimitBytes),
299 stderr: collectBoundedOutput(handle.stderr, "stderr", outputLimitBytes),
300 },
301 { concurrency: "unbounded" },
302 );
303 // A successful build shell can still leave daemonized descendants in
304 // its detached process group. Always reap the group after output has
305 // closed; ESRCH is expected when no descendants remain.
306 yield* handle.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore);
307 return result;
308 }).pipe(Effect.timeoutOption(Duration.seconds(timeoutSeconds))),
309 );
310 if (Option.isNone(resultOption)) {
311 return yield* new ComputeBuildError({
312 message: `Build command timed out after ${timeoutSeconds} seconds.`,
313 });
314 }
315 const result = resultOption.value;
316
317 if (result.exitCode !== 0) {
318 return yield* new ComputeBuildError({
319 message: `Build command failed with exit code ${result.exitCode} (stdout: ${result.stdout.bytes} bytes; stderr: ${result.stderr.bytes} bytes).`,
320 });
321 }
322
323 yield* Effect.logDebug("Build command completed", {
324 stdoutBytes: result.stdout.bytes,
325 stderrBytes: result.stderr.bytes,
326 });
327
328 return {
329 exitCode: result.exitCode,
330 stdout: result.stdout.text,
331 stderr: result.stderr.text,
332 };
333 });
334
335 const buildProcessEnvironment = (
336 explicitEnv: Record<string, string> = {},
337 ): Record<string, string> => ({
338 ...Object.fromEntries(
339 Object.entries(process.env).filter(
340 (entry): entry is [string, string] =>
341 entry[1] !== undefined &&
342 !PRISMA_MANAGEMENT_CREDENTIAL_ENV_NAMES.has(entry[0].toUpperCase()),
343 ),
344 ),
345 ...explicitEnv,
346 });
347
348 const NEXT_CONFIG_FILENAMES = [
349 "next.config.js",
350 "next.config.mjs",
351 "next.config.ts",
352 "next.config.mts",
353 ] as const;
354
355 const NUXT_CONFIG_FILENAMES = [
356 "nuxt.config.js",
357 "nuxt.config.mjs",
358 "nuxt.config.cjs",
359 "nuxt.config.ts",
360 "nuxt.config.mts",
361 ] as const;
362
363 const ASTRO_CONFIG_FILENAMES = [
364 "astro.config.js",
365 "astro.config.mjs",
366 "astro.config.cjs",
367 "astro.config.ts",
368 "astro.config.mts",
369 ] as const;
370
371 const NEST_CLI_FILENAME = "nest-cli.json";
372 const NEST_TSCONFIG_FILENAMES = ["tsconfig.build.json", "tsconfig.json"] as const;
373 const NEST_DEFAULT_COMPILED_ENTRYPOINTS = ["dist/src/main.js", "dist/main.js"] as const;
374
375 const TANSTACK_START_PACKAGES = ["@tanstack/react-start", "@tanstack/solid-start"] as const;
376
377 const strategies: readonly BuildStrategy[] = [
378 {
379 name: "nextjs",
380 canBuild: (appPath) =>
381 Effect.gen(function* () {
382 return (
383 (yield* hasRootFile(appPath, NEXT_CONFIG_FILENAMES)) ||
384 (yield* hasPackageDependency(appPath, ["next"]))
385 );
386 }),
387 execute: (options) =>
388 buildFramework({
389 appPath: options.appPath,
390 env: options.env,
391 outputLimitBytes: options.outputLimitBytes,
392 timeoutSeconds: options.timeoutSeconds,
393 cliName: "next",
394 args: ["build"],
395 failurePrefix: "Next.js",
396 missingMessage:
397 "Could not find an installed Next.js CLI. Install `next` in the application or workspace before deploying.",
398 sourceDir: ".next/standalone",
399 entrypoint: "server.js",
400 defaultPort: 3000,
401 allowNestedEntrypoint: true,
402 extrasRelativeToEntrypoint: true,
403 missingOutputMessage:
404 'Next.js build did not produce standalone output. Add output: "standalone" to your next.config file.',
405 extras: [
406 { from: "public", to: "public" },
407 { from: ".next/static", to: ".next/static" },
408 ],
409 }),
410 },
411 {
412 name: "nuxt",
413 canBuild: (appPath) =>
414 Effect.gen(function* () {
415 return (
416 (yield* hasRootFile(appPath, NUXT_CONFIG_FILENAMES)) ||
417 (yield* hasPackageDependency(appPath, ["nuxt"]))
418 );
419 }),
420 execute: (options) =>
421 buildFramework({
422 appPath: options.appPath,
423 env: options.env,
424 outputLimitBytes: options.outputLimitBytes,
425 timeoutSeconds: options.timeoutSeconds,
426 cliName: "nuxt",
427 args: ["build"],
428 failurePrefix: "Nuxt",
429 missingMessage:
430 "Could not find an installed Nuxt CLI. Install `nuxt` in the application or workspace before deploying.",
431 sourceDir: ".output",
432 entrypoint: "server/index.mjs",
433 defaultPort: 3000,
434 requiredFile: ".output/server/index.mjs",
435 missingOutputMessage:
436 "Nuxt build did not produce a Nitro node server entrypoint at .output/server/index.mjs. Ensure nitro.preset is 'node-server' (the default).",
437 }),
438 },
439 {
440 name: "astro",
441 canBuild: (appPath) =>
442 Effect.gen(function* () {
443 return (
444 (yield* hasRootFile(appPath, ASTRO_CONFIG_FILENAMES)) ||
445 (yield* hasPackageDependency(appPath, ["astro"]))
446 );
447 }),
448 execute: (options) =>
449 buildFramework({
450 appPath: options.appPath,
451 env: options.env,
452 outputLimitBytes: options.outputLimitBytes,
453 timeoutSeconds: options.timeoutSeconds,
454 cliName: "astro",
455 args: ["build"],
456 failurePrefix: "Astro",
457 missingMessage:
458 "Could not find an installed Astro CLI. Install `astro` in the application or workspace before deploying.",
459 sourceDir: "dist",
460 entrypoint: "server/entry.mjs",
461 defaultPort: 4321,
462 requiredFile: "dist/server/entry.mjs",
463 missingOutputMessage:
464 'Astro build did not produce a standalone server entrypoint. Install @astrojs/node and configure it with adapter: node({ mode: "standalone" }) in your astro.config file.',
465 }),
466 },
467 {
468 name: "nestjs",
469 canBuild: (appPath) =>
470 Effect.gen(function* () {
471 return (
472 (yield* hasRootFile(appPath, [NEST_CLI_FILENAME])) ||
473 (yield* hasPackageDependency(appPath, ["@nestjs/core"]))
474 );
475 }),
476 execute: (options) => buildNestjs(options),
477 },
478 {
479 name: "tanstack-start",
480 canBuild: (appPath) => hasPackageDependency(appPath, TANSTACK_START_PACKAGES),
481 execute: (options) =>
482 buildFramework({
483 appPath: options.appPath,
484 env: options.env,
485 outputLimitBytes: options.outputLimitBytes,
486 timeoutSeconds: options.timeoutSeconds,
487 cliName: "vite",
488 args: ["build"],
489 failurePrefix: "TanStack Start",
490 missingMessage:
491 "Could not find an installed Vite CLI. Install `vite` in the application or workspace before deploying.",
492 sourceDir: ".output",
493 entrypoint: "server/index.mjs",
494 defaultPort: 3000,
495 requiredFile: ".output/server/index.mjs",
496 missingOutputMessage:
497 "TanStack Start build did not produce a Nitro node server entrypoint at .output/server/index.mjs. Ensure your vite.config includes the TanStack Start and Nitro plugins with the default node preset.",
498 }),
499 },
500 {
501 name: "vite",
502 canBuild: (appPath) => hasPackageDependency(appPath, ["vite"]),
503 execute: (options) =>
504 Effect.gen(function* () {
505 const command = yield* packageCliCommand(
506 options.appPath,
507 "vite",
508 ["build"],
509 "Could not find an installed Vite CLI. Install `vite` in the application or workspace before deploying.",
510 );
511 return yield* runComputeStaticBuild({
512 appPath: options.appPath,
513 command,
514 outdir: "dist",
515 spa: true,
516 env: options.env,
517 outputLimitBytes: options.outputLimitBytes,
518 timeoutSeconds: options.timeoutSeconds,
519 });
520 }),
521 },
522 {
523 name: "bun",
524 canBuild: () => Effect.succeed(true),
525 execute: (options) => buildBun(options),
526 },
527 ] as const;
528
529 export const runComputeAutoBuild = Effect.fn(function* (options: ComputeAutoBuildOptions) {
530 const requested = options.framework ?? "auto";
531 const candidates =
532 requested === "auto"
533 ? strategies
534 : strategies.filter((strategy) => strategy.name === requested);
535
536 for (const strategy of candidates) {
537 if (yield* strategy.canBuild(options.appPath)) {
538 return yield* strategy.execute(options);
539 }
540 }
541
542 return yield* new ComputeBuildError({
543 message: "No suitable Prisma Compute auto-build strategy found.",
544 });
545 });
546
547 export const runComputeStaticBuild = Effect.fn(function* (options: ComputeStaticBuildOptions) {
548 const fs = yield* FileSystem.FileSystem;
549 const path = yield* Path.Path;
550 const cwd = options.cwd ? path.resolve(options.cwd) : options.appPath;
551 const outdir = normalizeRelativePath(options.outdir);
552 if (outdir === undefined) {
553 return yield* new ComputeBuildInvalidProps({
554 message: "Static site outdir must be a relative path without parent segments.",
555 });
556 }
557 const indexPage = normalizeRelativePath(options.indexPage ?? "index.html");
558 if (indexPage === undefined || indexPage === ".") {
559 return yield* new ComputeBuildInvalidProps({
560 message: "Static site indexPage must be a relative file path without parent segments.",
561 });
562 }
563
564 if (options.command !== undefined) {
565 yield* runBuildCommand({
566 command: options.command,
567 cwd,
568 env: processBuildEnv(options.env),
569 outputLimitBytes: options.outputLimitBytes,
570 timeoutSeconds: options.timeoutSeconds,
571 });
572 }
573
574 const sourceDir = path.resolve(cwd, outdir);
575 if (!(yield* directoryExists(sourceDir))) {
576 return yield* new ComputeBuildError({
577 message: `Static site build did not produce an output directory at ${sourceDir}.`,
578 });
579 }
580 const indexStat = yield* fs
581 .stat(path.join(sourceDir, indexPage))
582 .pipe(Effect.orElseSucceed(() => undefined));
583 if (indexStat?.type !== "File") {
584 return yield* new ComputeBuildError({
585 message: `Static site build did not produce ${indexPage} inside ${sourceDir}.`,
586 });
587 }
588
589 const temp = yield* makeTempArtifactDir();
590 const budget = makeStagingBudget();
591 const build = withStagingDeadline(
592 Effect.gen(function* () {
593 const publicDir = path.join(temp.artifactDir, "public");
594 yield* copyDirectoryPreserveSymlinks(sourceDir, publicDir, temp.artifactDir, cwd, budget);
595 const entrypoint = "server.mjs";
596 const serverPath = path.join(temp.artifactDir, entrypoint);
597 const source = staticSiteServerSource({
598 indexPage,
599 spa: options.spa ?? false,
600 });
601 yield* accountStagingEntry(
602 budget,
603 serverPath,
604 yield* Effect.sync(() => new TextEncoder().encode(source).byteLength),
605 );
606 yield* fs.writeFileString(serverPath, source);
607 return {
608 directory: temp.artifactDir,
609 entrypoint,
610 defaultPort: 8080,
611 archiveIgnorePrefix: "public",
612 requiredFiles: [`public/${indexPage}`],
613 cleanup: temp.cleanup,
614 };
615 }),
616 budget,
617 );
618
619 return yield* build.pipe(Effect.tapError(() => temp.cleanup));
620 });
621
622 const staticSiteServerSource = (options: { indexPage: string; spa: boolean }) =>
623 [
624 'const publicRoot = new URL("./public/", import.meta.url);',
625 `const indexPage = ${JSON.stringify(options.indexPage)};`,
626 `const spa = ${JSON.stringify(options.spa)};`,
627 "",
628 'const encodePath = (value) => value.split("/").map(encodeURIComponent).join("/");',
629 "",
630 "const responseForFile = async (fileUrl, method) => {",
631 " const file = Bun.file(fileUrl);",
632 " if (!(await file.exists())) return undefined;",
633 ' if (method !== "HEAD") return new Response(file);',
634 " return new Response(null, {",
635 " headers: {",
636 ' "content-length": String(file.size),',
637 ' "content-type": file.type || "application/octet-stream",',
638 " },",
639 " });",
640 "};",
641 "",
642 "const resolvePublicPath = (pathname) => {",
643 " let decoded;",
644 " try {",
645 " decoded = decodeURIComponent(pathname);",
646 " } catch {",
647 " return undefined;",
648 " }",
649 ' if (decoded.includes("\\0")) return undefined;',
650 " const target = new URL(`.${encodePath(decoded)}`, publicRoot);",
651 " return target.href.startsWith(publicRoot.href) ? target : undefined;",
652 "};",
653 "",
654 "const server = Bun.serve({",
655 ' hostname: "0.0.0.0",',
656 ' port: Number(process.env.PORT ?? "8080"),',
657 " async fetch(request) {",
658 " const method = request.method;",
659 ' if (method !== "GET" && method !== "HEAD") {',
660 ' return new Response("Method Not Allowed", {',
661 " status: 405,",
662 ' headers: { allow: "GET, HEAD" },',
663 " });",
664 " }",
665 "",
666 " const url = new URL(request.url);",
667 " const pathname = url.pathname;",
668 " const target = resolvePublicPath(pathname);",
669 ' if (target === undefined) return new Response("Bad Request", { status: 400 });',
670 "",
671 " const exact = await responseForFile(target, method);",
672 " if (exact) return exact;",
673 ' const directoryUrl = target.href.endsWith("/") ? target : new URL(`${target.href}/`);',
674 ' const directoryIndexPage = pathname === "/" ? indexPage : "index.html";',
675 " const directoryIndex = await responseForFile(new URL(encodePath(directoryIndexPage), directoryUrl), method);",
676 " if (directoryIndex) {",
677 ' if (!pathname.endsWith("/")) {',
678 ' const location = `${pathname.replace(/^\\/+/, "/")}/${url.search}`;',
679 " return new Response(null, { status: 301, headers: { location } });",
680 " }",
681 " return directoryIndex;",
682 " }",
683 "",
684 " if (spa) {",
685 " const fallback = await responseForFile(new URL(encodePath(indexPage), publicRoot), method);",
686 " if (fallback) return fallback;",
687 " }",
688 ' return new Response("Not Found", { status: 404 });',
689 " },",
690 "});",
691 "",
692 "console.log(`Listening on ${server.url}`);",
693 "",
694 ].join("\n");
695
696 const buildFramework = Effect.fn(function* (options: {
697 appPath: string;
698 env?: Record<string, string | Redacted.Redacted<string> | undefined>;
699 outputLimitBytes?: number;
700 timeoutSeconds?: number;
701 cliName: string;
702 args: string[];
703 failurePrefix: string;
704 missingMessage: string;
705 sourceDir: string;
706 entrypoint: string;
707 defaultPort: number;
708 allowNestedEntrypoint?: boolean;
709 requiredFile?: string;
710 missingOutputMessage: string;
711 extrasRelativeToEntrypoint?: boolean;
712 extras?: ReadonlyArray<{ from: string; to: string }>;
713 }) {
714 const fs = yield* FileSystem.FileSystem;
715 const path = yield* Path.Path;
716 yield* runBuildCommand({
717 command: yield* packageCliCommand(
718 options.appPath,
719 options.cliName,
720 options.args,
721 options.missingMessage,
722 ),
723 cwd: options.appPath,
724 env: processBuildEnv(options.env),
725 outputLimitBytes: options.outputLimitBytes,
726 timeoutSeconds: options.timeoutSeconds,
727 });
728
729 const requiredPath = path.join(options.appPath, options.requiredFile ?? options.sourceDir);
730 if (!(yield* fs.exists(requiredPath))) {
731 return yield* new ComputeBuildError({ message: options.missingOutputMessage });
732 }
733
734 const temp = yield* makeTempArtifactDir();
735 const budget = makeStagingBudget();
736 const build = withStagingDeadline(
737 Effect.gen(function* () {
738 yield* copyDirectoryPreserveSymlinks(
739 path.join(options.appPath, options.sourceDir),
740 temp.artifactDir,
741 temp.artifactDir,
742 options.appPath,
743 budget,
744 );
745 yield* materializeBunNodeModuleAliases(
746 temp.artifactDir,
747 path.join(options.appPath, options.sourceDir),
748 budget,
749 );
750 const entrypoint = yield* resolveFrameworkEntrypoint(
751 temp.artifactDir,
752 options.entrypoint,
753 options.allowNestedEntrypoint ?? false,
754 );
755 const extrasBaseDir = options.extrasRelativeToEntrypoint
756 ? path.dirname(path.join(temp.artifactDir, entrypoint))
757 : temp.artifactDir;
758 for (const extra of options.extras ?? []) {
759 const extraSource = path.join(options.appPath, extra.from);
760 if (yield* directoryExists(extraSource)) {
761 const extraTarget = path.join(extrasBaseDir, extra.to);
762 yield* copyDirectoryPreserveSymlinks(
763 extraSource,
764 extraTarget,
765 temp.artifactDir,
766 options.appPath,
767 budget,
768 );
769 }
770 }
771 return {
772 directory: temp.artifactDir,
773 entrypoint,
774 defaultPort: options.defaultPort,
775 cleanup: temp.cleanup,
776 };
777 }),
778 budget,
779 );
780
781 return yield* build.pipe(Effect.tapError(() => temp.cleanup));
782 });
783
784 const buildNestjs = Effect.fn(function* (options: ComputeAutoBuildOptions) {
785 const fs = yield* FileSystem.FileSystem;
786 const path = yield* Path.Path;
787 const buildScript = yield* readPackageScript(options.appPath, "build");
788
789 yield* runBuildCommand({
790 command:
791 buildScript === undefined
792 ? yield* packageCliCommand(
793 options.appPath,
794 "nest",
795 ["build"],
796 "Could not find an installed Nest CLI. Add a `build` script to package.json or install `@nestjs/cli` in the application or workspace before deploying.",
797 )
798 : packageScriptCommand("build"),
799 cwd: options.appPath,
800 env: processBuildEnv(options.env),
801 outputLimitBytes: options.outputLimitBytes,
802 timeoutSeconds: options.timeoutSeconds,
803 });
804
805 const compiledEntry = yield* resolveNestjsCompiledEntrypoint(options.appPath);
806 const temp = yield* makeTempArtifactDir();
807 const budget = makeStagingBudget();
808 const build = Effect.gen(function* () {
809 const entrypoint = yield* withStagingDeadline(
810 stageTracedNestjsArtifact({
811 appPath: options.appPath,
812 artifactDir: temp.artifactDir,
813 compiledEntry,
814 budget,
815 }),
816 budget,
817 );
818 return {
819 directory: temp.artifactDir,
820 entrypoint,
821 defaultPort: 3000,
822 cleanup: temp.cleanup,
823 };
824 });
825
826 return yield* build.pipe(
827 Effect.tapError(() =>
828 fs.remove(path.dirname(temp.artifactDir), { recursive: true }).pipe(Effect.ignore),
829 ),
830 );
831 });
832
833 const resolveNestjsCompiledEntrypoint = Effect.fn(function* (appPath: string) {
834 const fs = yield* FileSystem.FileSystem;
835 const path = yield* Path.Path;
836 const candidates = [
837 yield* readPackageMain(appPath),
838 yield* configuredNestjsCompiledEntrypoint(appPath),
839 ...NEST_DEFAULT_COMPILED_ENTRYPOINTS,
840 ].flatMap((candidate) => {
841 if (candidate === undefined) return [];
842 const normalized = normalizeRelativePath(candidate);
843 return normalized === undefined ? [] : [normalized];
844 });
845
846 for (const candidate of candidates) {
847 const stat = yield* fs
848 .stat(path.join(appPath, candidate))
849 .pipe(Effect.orElseSucceed(() => undefined));
850 if (stat?.type === "File") return candidate;
851 }
852
853 return yield* new ComputeBuildError({
854 message: `NestJS build did not produce a compiled entrypoint. Looked for ${candidates.join(", ")} under ${appPath}. Ensure \`nest build\` ran and check package.json main, nest-cli.json, or tsconfig outDir.`,
855 });
856 });
857
858 const configuredNestjsCompiledEntrypoint = Effect.fn(function* (appPath: string) {
859 const path = yield* Path.Path;
860 const config = yield* readNestCliConfig(appPath);
861 const sourceRoot = normalizeRelativePath(config.sourceRoot ?? "src") ?? "src";
862 const entryFile = config.entryFile ?? "main";
863 const outDir = yield* readNestjsOutDir(appPath);
864 return sourceRoot === "."
865 ? path.join(outDir, `${entryFile}.js`)
866 : path.join(outDir, sourceRoot, `${entryFile}.js`);
867 });
868
869 const stageTracedNestjsArtifact = Effect.fn(function* (options: {
870 appPath: string;
871 artifactDir: string;
872 compiledEntry: string;
873 budget: StagingBudget;
874 }) {
875 const fs = yield* FileSystem.FileSystem;
876 const path = yield* Path.Path;
877 const sourceRoot = yield* resolveSourceRoot(options.appPath);
878 const realSourceRoot = yield* fs.realPath(sourceRoot);
879 const artifactRoot = path.resolve(options.artifactDir);
880 const entry = path.join(options.appPath, options.compiledEntry);
881 const entrypoint = path.relative(sourceRoot, entry).replaceAll("\\", "/");
882 const fileList = yield* Effect.tryPromise({
883 try: () =>
884 importNft()
885 .then(({ nodeFileTrace }) => nodeFileTrace([entry], { base: sourceRoot }))
886 .then((result) => Array.from(result.fileList)),
887 catch: (cause) =>
888 new ComputeBuildError({
889 message:
890 cause instanceof Error
891 ? cause.message
892 : `Failed to trace NestJS artifact: ${String(cause)}`,
893 cause,
894 }),
895 });
896
897 const sortedFiles = fileList.sort((a, b) => a.localeCompare(b));
898 if (sortedFiles.length > STAGING_MAX_ENTRIES) {
899 return yield* new ComputeBuildError({
900 message: `Compute artifact staging exceeded the ${STAGING_MAX_ENTRIES} entry safety limit while tracing NestJS dependencies.`,
901 });
902 }
903 for (const file of sortedFiles) {
904 const normalized = normalizeRelativePath(file);
905 if (normalized === undefined || normalized === ".") {
906 return yield* new ComputeBuildError({
907 message: `NestJS dependency trace returned an unsafe path: ${file}`,
908 });
909 }
910 yield* stageTracedPath(
911 path.join(sourceRoot, normalized),
912 path.join(options.artifactDir, normalized),
913 [realSourceRoot],
914 artifactRoot,
915 options.budget,
916 );
917 }
918
919 return entrypoint;
920 });
921
922 const copyDirectoryPreserveSymlinks = Effect.fn(function* (
923 sourceDir: string,
924 targetDir: string,
925 targetRoot: string,
926 sourceBoundary: string,
927 budget: StagingBudget,
928 ) {
929 const fs = yield* FileSystem.FileSystem;
930 const path = yield* Path.Path;
931 const realSourceRoot = yield* fs.realPath(sourceDir);
932 const realSourceBoundary = yield* fs.realPath(sourceBoundary);
933 yield* assertPathWithinRoots(realSourceRoot, [realSourceBoundary], sourceDir);
934 yield* copyDirectoryWithinRoots(
935 sourceDir,
936 targetDir,
937 [realSourceRoot],
938 path.resolve(targetRoot),
939 budget,
940 );
941 });
942
943 const copyDirectoryWithinRoots: (
944 sourceDir: string,
945 targetDir: string,
946 allowedRoots: readonly string[],
947 targetRoot: string,
948 budget: StagingBudget,
949 ) => Effect.Effect<void, unknown, FileSystem.FileSystem | Path.Path> = Effect.fn(
950 function* (sourceDir, targetDir, allowedRoots, targetRoot, budget) {
951 const fs = yield* FileSystem.FileSystem;
952 const path = yield* Path.Path;
953 yield* assertRealPathWithinRoots(sourceDir, allowedRoots);
954 yield* assertSafeStagingDestination(targetDir, targetRoot);
955 yield* fs.makeDirectory(targetDir, { recursive: true });
956
957 const entries = (yield* readDirectoryEntries(sourceDir)).sort((a, b) =>
958 a.name.localeCompare(b.name),
959 );
960 for (const entry of entries) {
961 const source = path.join(sourceDir, entry.name);
962 const target = path.join(targetDir, entry.name);
963 if (entry.type === "SymbolicLink") {
964 const symlinkTarget = yield* validateStagedSymlink(source, allowedRoots);
965 yield* accountStagingEntry(budget, source, 0);
966 yield* assertSafeStagingDestination(target, targetRoot);
967 yield* assertPathWithinRoots(
968 path.resolve(path.dirname(target), symlinkTarget),
969 [targetRoot],
970 target,
971 );
972 yield* fs.remove(target, { recursive: true, force: true });
973 yield* fs.symlink(symlinkTarget, target);
974 continue;
975 }
976
977 if (entry.type === "Directory") {
978 yield* assertRealPathWithinRoots(source, allowedRoots);
979 yield* accountStagingEntry(budget, source, 0);
980 yield* copyDirectoryWithinRoots(source, target, allowedRoots, targetRoot, budget);
981 continue;
982 }
983
984 if (entry.type === "File") {
985 yield* assertRealPathWithinRoots(source, allowedRoots);
986 const stat = yield* fs.stat(source);
987 const size = yield* safeFileSize(source, stat.size);
988 yield* accountStagingEntry(budget, source, size);
989 yield* assertSafeStagingDestination(target, targetRoot);
990 yield* fs.makeDirectory(path.dirname(target), { recursive: true });
991 yield* fs.copyFile(source, target);
992 const copied = yield* fs.stat(target);
993 if (copied.type !== "File" || Number(copied.size) !== size) {
994 yield* fs.remove(target, { force: true }).pipe(Effect.ignore);
995 return yield* new ComputeBuildError({
996 message: `Compute artifact file changed while staging: ${source}`,
997 });
998 }
999 yield* fs.chmod(target, stat.mode & 0o777);
1000 continue;
1001 }
1002
1003 yield* accountStagingEntry(budget, source, 0);
1004 return yield* new ComputeBuildError({
1005 message: `Unsupported filesystem entry in compute artifact: ${source}`,
1006 });
1007 }
1008 },
1009 );
1010
1011 const readDirectoryEntries = Effect.fn(function* (directory: string) {
1012 const fs = yield* FileSystem.FileSystem;
1013 const path = yield* Path.Path;
1014 const names = yield* fs.readDirectory(directory);
1015 if (names.length > STAGING_MAX_ENTRIES) {
1016 return yield* new ComputeBuildError({
1017 message: `Compute artifact directory exceeds the ${STAGING_MAX_ENTRIES} entry safety limit: ${directory}`,
1018 });
1019 }
1020 return yield* Effect.forEach(names, (name) =>
1021 Effect.gen(function* () {
1022 const file = path.join(directory, name);
1023 const isSymlink = yield* fs.readLink(file).pipe(
1024 Effect.as(true),
1025 Effect.orElseSucceed(() => false),
1026 );
1027 if (isSymlink) {
1028 return { name, type: "SymbolicLink" } satisfies DirectoryEntry;
1029 }
1030 const stat = yield* fs.stat(file);
1031 return {
1032 name,
1033 type: stat.type === "Directory" || stat.type === "File" ? stat.type : "Other",
1034 } satisfies DirectoryEntry;
1035 }),
1036 );
1037 });
1038
1039 const materializeBunNodeModuleAliases = Effect.fn(function* (
1040 artifactDir: string,
1041 sourceDir: string,
1042 budget: StagingBudget,
1043 ) {
1044 const fs = yield* FileSystem.FileSystem;
1045 const path = yield* Path.Path;
1046 const nodeModules = path.join(artifactDir, "node_modules");
1047 const aliasRoot = path.join(nodeModules, ".bun", "node_modules");
1048 if (!(yield* directoryExists(aliasRoot))) return;
1049 const allowedRoots = [yield* fs.realPath(artifactDir), yield* fs.realPath(sourceDir)];
1050 const targetRoot = path.resolve(artifactDir);
1051
1052 for (const entry of yield* fs.readDirectory(aliasRoot)) {
1053 const source = path.join(aliasRoot, entry);
1054 const stat = yield* fs.stat(source).pipe(Effect.orElseSucceed(() => undefined));
1055 if (stat?.type !== "Directory") continue;
1056
1057 if (entry.startsWith("@")) {
1058 const targetScope = path.join(nodeModules, entry);
1059 yield* assertSafeStagingDestination(targetScope, targetRoot);
1060 yield* fs.makeDirectory(targetScope, { recursive: true });
1061 for (const packageName of yield* fs.readDirectory(source)) {
1062 yield* copyAliasIfMissing(
1063 allowedRoots,
1064 path.join(source, packageName),
1065 path.join(targetScope, packageName),
1066 targetRoot,
1067 budget,
1068 );
1069 }
1070 } else {
1071 yield* copyAliasIfMissing(
1072 allowedRoots,
1073 source,
1074 path.join(nodeModules, entry),
1075 targetRoot,
1076 budget,
1077 );
1078 }
1079 }
1080 });
1081
1082 const copyAliasIfMissing = Effect.fn(function* (
1083 allowedRoots: readonly string[],
1084 source: string,
1085 target: string,
1086 targetRoot: string,
1087 budget: StagingBudget,
1088 ) {
1089 const fs = yield* FileSystem.FileSystem;
1090 if (yield* fs.exists(target)) return;
1091 const realSource = yield* fs.realPath(source);
1092 yield* assertPathWithinRoots(realSource, allowedRoots, source);
1093 const stat = yield* fs.stat(realSource);
1094 yield* assertSafeStagingDestination(target, targetRoot);
1095 if (stat.type === "Directory") {
1096 yield* accountStagingEntry(budget, source, 0);
1097 yield* copyDirectoryWithinRoots(realSource, target, allowedRoots, targetRoot, budget);
1098 return;
1099 }
1100 if (stat.type === "File") {
1101 const size = yield* safeFileSize(source, stat.size);
1102 yield* accountStagingEntry(budget, source, size);
1103 yield* fs.copyFile(realSource, target);
1104 const copied = yield* fs.stat(target);
1105 if (copied.type !== "File" || Number(copied.size) !== size) {
1106 yield* fs.remove(target, { force: true }).pipe(Effect.ignore);
1107 return yield* new ComputeBuildError({
1108 message: `Compute artifact file changed while staging: ${source}`,
1109 });
1110 }
1111 yield* fs.chmod(target, stat.mode & 0o777);
1112 return;
1113 }
1114 return yield* new ComputeBuildError({
1115 message: `Unsupported Bun package alias source: ${source}`,
1116 });
1117 });
1118
1119 const resolveFrameworkEntrypoint = Effect.fn(function* (
1120 artifactDir: string,
1121 entrypoint: string,
1122 allowNested: boolean,
1123 ) {
1124 const fs = yield* FileSystem.FileSystem;
1125 const path = yield* Path.Path;
1126 if (!allowNested) {
1127 return entrypoint;
1128 }
1129
1130 const entrypointFile = path.basename(entrypoint);
1131 const candidates = (yield* fs.readDirectory(artifactDir, { recursive: true }))
1132 .map((file) => file.replaceAll("\\", "/"))
1133 .filter((file) => {
1134 const parts = file.split("/");
1135 return (
1136 path.basename(file) === entrypointFile &&
1137 !parts.includes("node_modules") &&
1138 !parts.includes(".next")
1139 );
1140 })
1141 .sort((a, b) => {
1142 const depth = a.split(/[\\/]/).length - b.split(/[\\/]/).length;
1143 return depth === 0 ? a.localeCompare(b) : depth;
1144 });
1145
1146 if (candidates.length === 1) return candidates[0]!;
1147 if (candidates.length > 1) {
1148 return yield* new ComputeBuildError({
1149 message: `Next.js standalone output has multiple ${entrypointFile} files (${candidates.join(", ")}). Cannot determine the application entrypoint.`,
1150 });
1151 }
1152
1153 return yield* new ComputeBuildError({
1154 message: `Could not find framework entrypoint ${entrypoint} inside ${artifactDir}.`,
1155 });
1156 });
1157
1158 function buildBun(options: ComputeAutoBuildOptions) {
1159 return Effect.gen(function* () {
1160 const fs = yield* FileSystem.FileSystem;
1161 const path = yield* Path.Path;
1162 const entrypoint = yield* resolveBunEntrypoint(options.appPath, options.entrypoint);
1163 const absoluteEntrypoint = path.join(options.appPath, entrypoint);
1164 const temp = yield* makeTempArtifactDir("bundle");
1165
1166 const build = Effect.gen(function* () {
1167 yield* runBuildCommand({
1168 command: [
1169 "bun",
1170 "build",
1171 shellQuote(absoluteEntrypoint),
1172 "--outdir",
1173 shellQuote(temp.artifactDir),
1174 "--target",
1175 "bun",
1176 "--sourcemap=external",
1177 ].join(" "),
1178 cwd: options.appPath,
1179 env: processBuildEnv(options.env),
1180 outputLimitBytes: options.outputLimitBytes,
1181 timeoutSeconds: options.timeoutSeconds,
1182 });
1183
1184 const budget = makeStagingBudget();
1185 yield* withStagingDeadline(validateStagedDirectory(temp.artifactDir, budget), budget);
1186
1187 const outputFiles = (yield* fs.readDirectory(temp.artifactDir))
1188 .filter((file) => file.endsWith(".js"))
1189 .sort();
1190 if (outputFiles.length === 0) {
1191 return yield* new ComputeBuildError({
1192 message: "Bun build produced no JavaScript output.",
1193 });
1194 }
1195
1196 const expected = `${path.basename(absoluteEntrypoint, path.extname(absoluteEntrypoint))}.js`;
1197 return {
1198 directory: temp.artifactDir,
1199 entrypoint: outputFiles.includes(expected) ? expected : outputFiles[0]!,
1200 cleanup: temp.cleanup,
1201 };
1202 });
1203
1204 return yield* build.pipe(Effect.tapError(() => temp.cleanup));
1205 });
1206 }
1207
1208 const resolveBunEntrypoint = Effect.fn(function* (appPath: string, entrypoint: string | undefined) {
1209 const fs = yield* FileSystem.FileSystem;
1210 const path = yield* Path.Path;
1211 const candidate = entrypoint ?? (yield* readPackageMain(appPath));
1212 if (!candidate) {
1213 return yield* new ComputeBuildInvalidProps({
1214 message:
1215 "Prisma Compute auto-build needs an entrypoint for Bun apps. Set `entrypoint` or package.json `main`.",
1216 });
1217 }
1218 const normalized = yield* normalizeEntrypoint(candidate);
1219 const entrypointPath = path.join(appPath, normalized);
1220 if (!(yield* fs.exists(entrypointPath))) {
1221 return yield* new ComputeBuildInvalidProps({
1222 message: `Entrypoint file does not exist: ${entrypointPath}`,
1223 });
1224 }
1225 const realAppPath = yield* fs.realPath(appPath);
1226 const realEntrypointPath = yield* fs.realPath(entrypointPath);
1227 yield* assertPathWithinRoots(realEntrypointPath, [realAppPath], entrypointPath);
1228 return normalized;
1229 });
1230
1231 const makeTempArtifactDir = Effect.fn(function* (leaf = "app") {
1232 const fs = yield* FileSystem.FileSystem;
1233 const path = yield* Path.Path;
1234 const tempDir = yield* fs.makeTempDirectory({
1235 prefix: "alchemy-prisma-compute-build-",
1236 });
1237 const artifactDir = path.join(tempDir, leaf);
1238 yield* fs.makeDirectory(artifactDir, { recursive: true });
1239 return {
1240 artifactDir,
1241 cleanup: fs.remove(tempDir, { recursive: true }).pipe(Effect.ignore),
1242 };
1243 });
1244
1245 const hasRootFile = Effect.fn(function* (appPath: string, filenames: readonly string[]) {
1246 const fs = yield* FileSystem.FileSystem;
1247 const entries = yield* fs.readDirectory(appPath).pipe(Effect.orElseSucceed(() => [] as string[]));
1248 return entries.some((entry) => filenames.includes(entry));
1249 });
1250
1251 const hasPackageDependency = Effect.fn(function* (
1252 appPath: string,
1253 packageNames: readonly string[],
1254 ) {
1255 const parsed = yield* readPackageJson(appPath);
1256 if (!parsed) return false;
1257 const deps = isRecord(parsed.dependencies) ? parsed.dependencies : {};
1258 const devDeps = isRecord(parsed.devDependencies) ? parsed.devDependencies : {};
1259 return packageNames.some((name) => name in deps || name in devDeps);
1260 });
1261
1262 const readPackageMain = Effect.fn(function* (appPath: string) {
1263 const parsed = yield* readPackageJson(appPath);
1264 return typeof parsed?.main === "string" ? parsed.main : undefined;
1265 });
1266
1267 const readPackageScript = Effect.fn(function* (appPath: string, scriptName: string) {
1268 const parsed = yield* readPackageJson(appPath);
1269 const scripts = isRecord(parsed?.scripts) ? parsed.scripts : undefined;
1270 const script = scripts?.[scriptName];
1271 return typeof script === "string" && script.trim() !== "" ? script : undefined;
1272 });
1273
1274 const readPackageJson = Effect.fn(function* (appPath: string) {
1275 const fs = yield* FileSystem.FileSystem;
1276 const path = yield* Path.Path;
1277 const packagePath = path.join(appPath, "package.json");
1278 const text = yield* fs
1279 .readFileString(packagePath)
1280 .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined));
1281 if (!text) return undefined;
1282 return yield* Effect.try({
1283 try: () => JSON.parse(text) as Record<string, unknown>,
1284 catch: (cause) =>
1285 new ComputeBuildError({
1286 message: `Failed to parse package.json in ${appPath}: ${cause instanceof Error ? cause.message : String(cause)}`,
1287 cause,
1288 }),
1289 });
1290 });
1291
1292 const readNestCliConfig = Effect.fn(function* (appPath: string) {
1293 const parsed = yield* readJsonObjectFile(appPath, NEST_CLI_FILENAME);
1294 return {
1295 sourceRoot: typeof parsed?.sourceRoot === "string" ? parsed.sourceRoot : undefined,
1296 entryFile: typeof parsed?.entryFile === "string" ? parsed.entryFile : undefined,
1297 };
1298 });
1299
1300 const readNestjsOutDir = Effect.fn(function* (appPath: string) {
1301 const fs = yield* FileSystem.FileSystem;
1302 const path = yield* Path.Path;
1303 for (const fileName of NEST_TSCONFIG_FILENAMES) {
1304 const filePath = path.join(appPath, fileName);
1305 const text = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => undefined));
1306 if (text === undefined) continue;
1307 const outDir = yield* parseTsconfigOutDir(text);
1308 if (outDir !== undefined) return outDir;
1309 }
1310 return "dist";
1311 });
1312
1313 const parseTsconfigOutDir = Effect.fn(function* (content: string) {
1314 const parsed = yield* Effect.try({
1315 try: () =>
1316 JSON.parse(stripJsonComments(content)) as {
1317 compilerOptions?: { outDir?: unknown };
1318 },
1319 catch: (cause) =>
1320 new ComputeBuildError({
1321 message: cause instanceof Error ? cause.message : String(cause),
1322 cause,
1323 }),
1324 }).pipe(Effect.orElseSucceed(() => undefined));
1325 const outDir = parsed?.compilerOptions?.outDir;
1326 return typeof outDir === "string" ? normalizeRelativePath(outDir) : undefined;
1327 });
1328
1329 const readJsonObjectFile = Effect.fn(function* (directory: string, fileName: string) {
1330 const fs = yield* FileSystem.FileSystem;
1331 const path = yield* Path.Path;
1332 const text = yield* fs
1333 .readFileString(path.join(directory, fileName))
1334 .pipe(Effect.orElseSucceed(() => undefined));
1335 if (text === undefined) return undefined;
1336 return yield* Effect.try({
1337 try: () => {
1338 const parsed = JSON.parse(text) as unknown;
1339 return isRecord(parsed) ? parsed : undefined;
1340 },
1341 catch: (cause) =>
1342 new ComputeBuildError({
1343 message: cause instanceof Error ? cause.message : String(cause),
1344 cause,
1345 }),
1346 }).pipe(Effect.orElseSucceed(() => undefined));
1347 });
1348
1349 const directoryExists = Effect.fn(function* (dirPath: string) {
1350 const fs = yield* FileSystem.FileSystem;
1351 const stat = yield* fs.stat(dirPath).pipe(Effect.orElseSucceed(() => undefined));
1352 return stat?.type === "Directory";
1353 });
1354
1355 const stageTracedPath = Effect.fn(function* (
1356 sourcePath: string,
1357 destinationPath: string,
1358 allowedRoots: readonly string[],
1359 targetRoot: string,
1360 budget: StagingBudget,
1361 ) {
1362 const fs = yield* FileSystem.FileSystem;
1363 const path = yield* Path.Path;
1364 const symlinkTarget = yield* fs.readLink(sourcePath).pipe(Effect.orElseSucceed(() => undefined));
1365 const stat = yield* fs.stat(sourcePath).pipe(Effect.orElseSucceed(() => undefined));
1366 if (stat === undefined && symlinkTarget === undefined) {
1367 return yield* new ComputeBuildError({
1368 message: `NestJS dependency disappeared while staging: ${sourcePath}`,
1369 });
1370 }
1371
1372 yield* assertSafeStagingDestination(destinationPath, targetRoot);
1373 yield* fs.makeDirectory(path.dirname(destinationPath), { recursive: true });
1374 if (symlinkTarget !== undefined) {
1375 const validatedTarget = yield* validateStagedSymlink(sourcePath, allowedRoots);
1376 yield* accountStagingEntry(budget, sourcePath, 0);
1377 yield* assertPathWithinRoots(
1378 path.resolve(path.dirname(destinationPath), validatedTarget),
1379 [targetRoot],
1380 destinationPath,
1381 );
1382 yield* fs.remove(destinationPath, { recursive: true, force: true });
1383 yield* fs.symlink(validatedTarget, destinationPath);
1384 return;
1385 }
1386
1387 if (stat?.type === "File") {
1388 yield* assertRealPathWithinRoots(sourcePath, allowedRoots);
1389 const size = yield* safeFileSize(sourcePath, stat.size);
1390 yield* accountStagingEntry(budget, sourcePath, size);
1391 yield* fs.copyFile(sourcePath, destinationPath);
1392 const copied = yield* fs.stat(destinationPath);
1393 if (copied.type !== "File" || Number(copied.size) !== size) {
1394 yield* fs.remove(destinationPath, { force: true }).pipe(Effect.ignore);
1395 return yield* new ComputeBuildError({
1396 message: `Compute artifact file changed while staging: ${sourcePath}`,
1397 });
1398 }
1399 yield* fs.chmod(destinationPath, stat.mode & 0o777);
1400 return;
1401 }
1402
1403 yield* accountStagingEntry(budget, sourcePath, 0);
1404 return yield* new ComputeBuildError({
1405 message: `Unsupported filesystem entry in NestJS dependency trace: ${sourcePath}`,
1406 });
1407 });
1408
1409 const makeStagingBudget = (): StagingBudget => ({
1410 entries: 0,
1411 totalBytes: 0,
1412 deadline: Date.now() + STAGING_TIMEOUT_SECONDS * 1000,
1413 });
1414
1415 const withStagingDeadline = <A, E, R>(
1416 effect: Effect.Effect<A, E, R>,
1417 budget: StagingBudget,
1418 ): Effect.Effect<A, E | Error, R> =>
1419 effect.pipe(
1420 Effect.timeoutOption(Duration.millis(Math.max(1, budget.deadline - Date.now()))),
1421 Effect.flatMap((result) =>
1422 Effect.fromOption(
1423 result,
1424 () =>
1425 new ComputeBuildError({
1426 message: `Compute artifact staging timed out after ${STAGING_TIMEOUT_SECONDS} seconds.`,
1427 }),
1428 ),
1429 ),
1430 );
1431
1432 const accountStagingEntry = (budget: StagingBudget, source: string, size: number) => {
1433 if (Date.now() > budget.deadline) {
1434 return Effect.fail(
1435 new ComputeBuildError({
1436 message: `Compute artifact staging timed out after ${STAGING_TIMEOUT_SECONDS} seconds.`,
1437 }),
1438 );
1439 }
1440 if (size > STAGING_MAX_FILE_BYTES) {
1441 return Effect.fail(
1442 new ComputeBuildError({
1443 message: `Compute artifact file exceeds the ${STAGING_MAX_FILE_BYTES} byte per-file safety limit: ${source}`,
1444 }),
1445 );
1446 }
1447 const entries = budget.entries + 1;
1448 if (entries > STAGING_MAX_ENTRIES) {
1449 return Effect.fail(
1450 new ComputeBuildError({
1451 message: `Compute artifact staging exceeded the ${STAGING_MAX_ENTRIES} entry safety limit.`,
1452 }),
1453 );
1454 }
1455 const totalBytes = budget.totalBytes + size;
1456 if (!Number.isSafeInteger(totalBytes) || totalBytes > STAGING_MAX_TOTAL_BYTES) {
1457 return Effect.fail(
1458 new ComputeBuildError({
1459 message: `Compute artifact staging exceeded the ${STAGING_MAX_TOTAL_BYTES} byte total safety limit.`,
1460 }),
1461 );
1462 }
1463 budget.entries = entries;
1464 budget.totalBytes = totalBytes;
1465 return Effect.void;
1466 };
1467
1468 const safeFileSize = (source: string, rawSize: ByteSize.ByteSize) => {
1469 const size = ByteSize.toNumberUnsafe(rawSize);
1470 return Number.isSafeInteger(size) && size >= 0
1471 ? Effect.succeed(size)
1472 : Effect.fail(
1473 new ComputeBuildError({ message: `Compute artifact has an invalid file size: ${source}` }),
1474 );
1475 };
1476
1477 const assertRealPathWithinRoots = Effect.fn(function* (
1478 source: string,
1479 allowedRoots: readonly string[],
1480 ) {
1481 const fs = yield* FileSystem.FileSystem;
1482 const realSource = yield* fs.realPath(source);
1483 yield* assertPathWithinRoots(realSource, allowedRoots, source);
1484 return realSource;
1485 });
1486
1487 const assertSafeStagingDestination = Effect.fn(function* (destination: string, targetRoot: string) {
1488 const fs = yield* FileSystem.FileSystem;
1489 const path = yield* Path.Path;
1490 const absoluteDestination = path.resolve(destination);
1491 const absoluteTargetRoot = path.resolve(targetRoot);
1492 yield* assertPathWithinRoots(absoluteDestination, [absoluteTargetRoot], destination);
1493
1494 let existingAncestor = absoluteDestination;
1495 while (!(yield* fs.exists(existingAncestor))) {
1496 const isDanglingSymlink = yield* fs.readLink(existingAncestor).pipe(
1497 Effect.as(true),
1498 Effect.orElseSucceed(() => false),
1499 );
1500 if (isDanglingSymlink) {
1501 return yield* new ComputeBuildError({
1502 message: `Compute artifact destination contains a dangling symlink: ${existingAncestor}`,
1503 });
1504 }
1505 const parent = path.dirname(existingAncestor);
1506 if (parent === existingAncestor) {
1507 return yield* new ComputeBuildError({
1508 message: `Could not establish a safe compute artifact destination: ${destination}`,
1509 });
1510 }
1511 existingAncestor = parent;
1512 }
1513
1514 const realAncestor = yield* fs.realPath(existingAncestor);
1515 const realTargetRoot = yield* fs.realPath(absoluteTargetRoot);
1516 yield* assertPathWithinRoots(realAncestor, [realTargetRoot], destination);
1517 });
1518
1519 const assertPathWithinRoots = Effect.fn(function* (
1520 realSource: string,
1521 allowedRoots: readonly string[],
1522 displaySource: string,
1523 ) {
1524 const path = yield* Path.Path;
1525 if (
1526 allowedRoots.some((root) => {
1527 const relative = path.relative(root, realSource);
1528 return (
1529 relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)
1530 );
1531 })
1532 ) {
1533 return;
1534 }
1535 return yield* new ComputeBuildError({
1536 message: `Compute artifact path escapes its staging root: ${displaySource}`,
1537 });
1538 });
1539
1540 const validateStagedSymlink = Effect.fn(function* (
1541 source: string,
1542 allowedRoots: readonly string[],
1543 ) {
1544 const fs = yield* FileSystem.FileSystem;
1545 const path = yield* Path.Path;
1546 const target = yield* fs.readLink(source);
1547 if (path.isAbsolute(target) || /^[a-zA-Z]:[\\/]/.test(target)) {
1548 return yield* new ComputeBuildError({
1549 message: `Compute artifact contains an absolute symlink: ${source}`,
1550 });
1551 }
1552 yield* assertRealPathWithinRoots(source, allowedRoots);
1553 return target;
1554 });
1555
1556 const validateStagedDirectory = Effect.fn(function* (root: string, budget: StagingBudget) {
1557 const fs = yield* FileSystem.FileSystem;
1558 const path = yield* Path.Path;
1559 const realRoot = yield* fs.realPath(root);
1560
1561 const visit: (
1562 directory: string,
1563 ) => Effect.Effect<void, unknown, FileSystem.FileSystem | Path.Path> = Effect.fn(
1564 function* (directory) {
1565 yield* assertRealPathWithinRoots(directory, [realRoot]);
1566 const entries = (yield* readDirectoryEntries(directory)).sort((a, b) =>
1567 a.name.localeCompare(b.name),
1568 );
1569 for (const entry of entries) {
1570 const source = path.join(directory, entry.name);
1571 if (entry.type === "SymbolicLink") {
1572 yield* validateStagedSymlink(source, [realRoot]);
1573 yield* accountStagingEntry(budget, source, 0);
1574 continue;
1575 }
1576 if (entry.type === "Directory") {
1577 yield* assertRealPathWithinRoots(source, [realRoot]);
1578 yield* accountStagingEntry(budget, source, 0);
1579 yield* visit(source);
1580 continue;
1581 }
1582 if (entry.type === "File") {
1583 yield* assertRealPathWithinRoots(source, [realRoot]);
1584 const stat = yield* fs.stat(source);
1585 yield* accountStagingEntry(budget, source, yield* safeFileSize(source, stat.size));
1586 continue;
1587 }
1588 yield* accountStagingEntry(budget, source, 0);
1589 return yield* new ComputeBuildError({
1590 message: `Unsupported filesystem entry in compute artifact: ${source}`,
1591 });
1592 }
1593 },
1594 );
1595
1596 yield* visit(root);
1597 });
1598
1599 const resolveSourceRoot = Effect.fn(function* (startPath: string) {
1600 const fs = yield* FileSystem.FileSystem;
1601 const path = yield* Path.Path;
1602 const original = path.resolve(startPath);
1603 let current = original;
1604
1605 while (true) {
1606 if (
1607 (yield* fs.exists(path.join(current, ".git"))) ||
1608 (yield* fs.exists(path.join(current, "pnpm-workspace.yaml"))) ||
1609 (yield* fs.exists(path.join(current, "bun.lock"))) ||
1610 (yield* fs.exists(path.join(current, "bun.lockb"))) ||
1611 (yield* packageJsonDeclaresWorkspaces(current))
1612 ) {
1613 return current;
1614 }
1615
1616 const parent = path.dirname(current);
1617 if (parent === current) return original;
1618 current = parent;
1619 }
1620 });
1621
1622 const packageJsonDeclaresWorkspaces = Effect.fn(function* (directory: string) {
1623 const parsed = yield* readJsonObjectFile(directory, "package.json");
1624 return parsed?.workspaces !== undefined;
1625 });
1626
1627 const packageCliCommand = Effect.fn(function* (
1628 appPath: string,
1629 cliName: string,
1630 args: readonly string[],
1631 missingMessage: string,
1632 ) {
1633 const fs = yield* FileSystem.FileSystem;
1634 const path = yield* Path.Path;
1635 const sourceRoot = yield* resolveSourceRoot(appPath);
1636 const executable = process.platform === "win32" ? `${cliName}.cmd` : cliName;
1637 const candidates = Array.from(
1638 new Set(
1639 [appPath, sourceRoot].map((root) => path.join(root, "node_modules", ".bin", executable)),
1640 ),
1641 );
1642 for (const candidate of candidates) {
1643 const stat = yield* fs.stat(candidate).pipe(Effect.orElseSucceed(() => undefined));
1644 if (stat?.type === "File" && (process.platform === "win32" || (stat.mode & 0o111) !== 0)) {
1645 const argText = args.map(shellQuote).join(" ");
1646 // Package-manager shims resolve dependencies relative to their own path.
1647 // Resolve symlinked node_modules directories before invoking the shim.
1648 const executablePath = yield* fs.realPath(candidate);
1649 return `${shellQuote(executablePath)}${argText.length > 0 ? ` ${argText}` : ""}`;
1650 }
1651 }
1652 return yield* new ComputeBuildError({ message: missingMessage });
1653 });
1654
1655 const packageScriptCommand = (scriptName: string) =>
1656 [
1657 "if command -v bun >/dev/null 2>&1; then",
1658 `bun run ${shellQuote(scriptName)};`,
1659 "elif command -v npm >/dev/null 2>&1; then",
1660 `npm run ${shellQuote(scriptName)};`,
1661 "else",
1662 `echo ${shellQuote("Could not find bun or npm to run package scripts.")} >&2; exit 127;`,
1663 "fi",
1664 ].join(" ");
1665
1666 const processBuildEnv = (
1667 env: Record<string, string | Redacted.Redacted<string> | undefined> = {},
1668 ) =>
1669 Object.fromEntries(
1670 Object.entries(env).flatMap(([key, value]) =>
1671 value === undefined
1672 ? []
1673 : [[key, Redacted.isRedacted(value) ? Redacted.value(value) : value]],
1674 ),
1675 ) as Record<string, string>;
1676
1677 const isRecord = (value: unknown): value is Record<string, unknown> =>
1678 typeof value === "object" && value !== null;
1679
1680 const normalizeRelativePath = (value: string) => {
1681 const raw = value.trim().replaceAll("\\", "/");
1682 if (raw.length === 0 || raw.startsWith("/") || /^[a-zA-Z]:\//.test(raw)) {
1683 return undefined;
1684 }
1685 const parts: string[] = [];
1686 for (const part of raw.split("/")) {
1687 if (part === "" || part === ".") continue;
1688 if (part === "..") {
1689 if (parts.length === 0) return undefined;
1690 parts.pop();
1691 continue;
1692 }
1693 parts.push(part);
1694 }
1695 return parts.join("/") || ".";
1696 };
1697
1698 const stripJsonComments = (content: string) => {
1699 let result = "";
1700 let inString = false;
1701 let escaped = false;
1702
1703 for (let i = 0; i < content.length; i++) {
1704 const char = content[i];
1705
1706 if (inString) {
1707 result += char;
1708 if (escaped) {
1709 escaped = false;
1710 } else if (char === "\\") {
1711 escaped = true;
1712 } else if (char === '"') {
1713 inString = false;
1714 }
1715 continue;
1716 }
1717
1718 if (char === '"') {
1719 inString = true;
1720 result += char;
1721 continue;
1722 }
1723
1724 const next = content[i + 1];
1725 if (char === "/" && next === "/") {
1726 while (i < content.length && content[i] !== "\n") {
1727 i++;
1728 }
1729 if (i < content.length) result += content[i];
1730 continue;
1731 }
1732 if (char === "/" && next === "*") {
1733 i += 2;
1734 while (i < content.length && !(content[i] === "*" && content[i + 1] === "/")) {
1735 i++;
1736 }
1737 i++;
1738 continue;
1739 }
1740
1741 result += char;
1742 }
1743
1744 return result;
1745 };
1746
1747 const shellQuote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;