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

main
ts 833 lines 27.8 KB
Raw
1 import { createRequire } from "node:module";
2 import * as Bundle from "alchemy/Bundle/Bundle";
3 import {
4 matchesPackageRoot,
5 normalizeInstallTargets,
6 parsePackageRootFromSpecifier,
7 resolvePackageInstallIdentity,
8 type PackageInstall,
9 } from "alchemy/Bundle/InstalledPackages";
10 import { findCwdForBundle, getStableContextDir, resolveMainPath } from "alchemy/Bundle/TempRoot";
11 import { safeHttpEffect } from "alchemy/Http";
12 import type { ResourceBinding } from "alchemy/Resource";
13 import { createContainerRuntimeContext, type HostRuntimeContext } from "alchemy/Runtime/Process";
14 import { Self } from "alchemy/Self";
15 import {
16 copyExtraFiles,
17 contextRootOf,
18 extraFileDestination,
19 hashExtraFiles,
20 isContextRootDest,
21 posixRelUnder,
22 resolveExtraSource,
23 type ExtraFile,
24 } from "alchemy/Util/extraFiles";
25 import { sha256, sha256Object } from "alchemy/Util/sha256";
26 import * as Data from "effect/Data";
27 import * as Effect from "effect/Effect";
28 import * as FileSystem from "effect/FileSystem";
29 import * as HttpServerRequest from "effect/http/HttpServerRequest";
30 import * as HttpServerResponse from "effect/http/HttpServerResponse";
31 import * as Path from "effect/Path";
32 import * as Redacted from "effect/Redacted";
33 import type * as rolldown from "rolldown";
34 import type { MountSpec, ServiceBinding } from "./MountVolume.ts";
35
36 export type RailwayHostRuntimeContext = HostRuntimeContext;
37
38 /**
39 * Container host. RPC wrapping lives in `Service.ts` so canvas Functions
40 * do not pay for `rpc-server.ts` in the 96KB start command. The generated
41 * Service entry is a shim that imports `@alchemy.run/railway/Bootstrap`
42 * (Node HTTP) plus the user's `main` — see that module for why.
43 */
44 export const createRailwayHostRuntimeContext = createContainerRuntimeContext;
45
46 /**
47 * Function runtime: register the fetch handler on `globalThis` instead of
48 * booting an HTTP server. The canvas wrapper `Bun.serve`s first so a
49 * failed Effect import cannot 502 before the process is bound.
50 */
51 export const createRailwayFunctionRuntimeContext =
52 (type: string) =>
53 (id: string): HostRuntimeContext => {
54 const base = createContainerRuntimeContext(type)(id);
55 return {
56 ...base,
57 serve: ((handler, options) =>
58 Effect.sync(() => {
59 if (!globalThis.__ALCHEMY_RUNTIME__) return;
60 const run = safeHttpEffect((globalThis as any).__R?.(options?.shape, handler) ?? handler);
61 (
62 globalThis as typeof globalThis & {
63 __aFF?: (request: Request) => Promise<Response>;
64 }
65 ).__aFF = async (request: Request) => {
66 try {
67 const response = await Effect.runPromise(
68 run.pipe(
69 Effect.provideService(
70 HttpServerRequest.HttpServerRequest,
71 HttpServerRequest.fromWeb(request),
72 ),
73 Effect.scoped,
74 ),
75 );
76 return HttpServerResponse.toWeb(response);
77 } catch (error) {
78 return new Response(String(error), { status: 500 });
79 }
80 };
81 })) as HostRuntimeContext["serve"],
82 exports: Effect.sync(() => ({
83 program: Effect.void,
84 })),
85 } as HostRuntimeContext;
86 };
87
88 export const DEFAULT_BASE_IMAGE = "node:26-slim";
89 export const DEFAULT_PORT = 3000;
90
91 export interface RailwayBuildOptions extends Bundle.BundleConfig {
92 /**
93 * Native or Node-only packages to install into the image with
94 * `npm install` instead of bundling them. `pg` is CommonJS: Rolldown's
95 * interop turns `Client` into a namespace (`The superclass is not a
96 * constructor`). Same `build.install` shape as Lambda / Fly.
97 *
98 * @example
99 * ```typescript
100 * build: { install: ["pg"] }
101 * ```
102 */
103 readonly install?: PackageInstall;
104 }
105
106 export type { ExtraFile };
107
108 export interface HostedProgramProps {
109 main: string;
110 handler?: string;
111 port?: number;
112 /**
113 * Dockerfile `FROM` for the Effect-native image. Ignored for the
114 * public-image path (`props.image` without `main`).
115 *
116 * @default "node:26-slim"
117 */
118 image?: string;
119 env?: Record<string, any>;
120 isExternal?: boolean;
121 build?: RailwayBuildOptions;
122 /**
123 * Extra files/directories copied into `/app` after the bundled entry.
124 * Hashed into `code.hash` so asset-only changes rebuild the image.
125 */
126 extraFiles?: ReadonlyArray<ExtraFile>;
127 }
128
129 const matchesConfiguredExternal = (
130 external: rolldown.InputOptions["external"],
131 moduleId: string,
132 parentId: string | undefined,
133 isResolved: boolean,
134 ): boolean => {
135 if (external === undefined) return false;
136 if (typeof external === "function") {
137 return external(moduleId, parentId, isResolved) === true;
138 }
139 const matchers = Array.isArray(external) ? external : [external];
140 return matchers.some((matcher) =>
141 typeof matcher === "string" ? matcher === moduleId : matcher.test(moduleId),
142 );
143 };
144
145 export class ExtraFileMissing extends Data.TaggedError("Railway.ExtraFileMissing")<{
146 source: string;
147 dest: string;
148 }> {}
149
150 const dockerfileCopyLines = (files: ReadonlyArray<ExtraFile> | undefined) =>
151 (files ?? []).flatMap((file) => {
152 const dest = extraFileDestination(file.dest);
153 if (isContextRootDest(dest)) return [];
154 return [`COPY ${dest} /app/${dest}`];
155 });
156
157 /**
158 * The generated entry for `Railway.Service` containers: a shim importing
159 * only `@alchemy.run/railway/Bootstrap` plus the user's `main` — see
160 * that module for why the entry never imports alchemy's own dependencies.
161 */
162 const makeNodeBootstrap =
163 (handler: string) =>
164 (importPath: string): string =>
165 `
166 import { bootstrap } from "@alchemy.run/railway/Bootstrap";
167
168 globalThis.__ALCHEMY_RUNTIME__ = true;
169 const { ${handler}: entrypoint } = await import(${JSON.stringify(importPath)});
170
171 await bootstrap(entrypoint);
172 `;
173
174 /**
175 * Inner Function module: builds the class layer so `serve` registers
176 * `globalThis.__aFF`. The canvas wrapper listens first, then import()s
177 * this file.
178 */
179 const makeFunctionBootstrap =
180 (handler: string) =>
181 (importPath: string): string =>
182 `
183 import { makeEntrypointLayer, reifyBoundConfigProvider } from "alchemy/Runtime";
184 import { Stack } from "alchemy/Stack";
185 import * as Config from "effect/Config";
186 import * as ConfigProvider from "effect/ConfigProvider";
187 import * as Context from "effect/Context";
188 import * as Effect from "effect/Effect";
189 import * as Layer from "effect/Layer";
190 import * as FetchHttpClient from "effect/http/FetchHttpClient";
191
192 globalThis.__ALCHEMY_RUNTIME__ = true;
193 const { ${handler}: entrypoint } = await import(${JSON.stringify(importPath)});
194 const tag = Context.Service(${JSON.stringify(Self.key)});
195 const layer = makeEntrypointLayer(tag, entrypoint);
196 const platform = FetchHttpClient.layer;
197 const stack = Layer.effect(
198 Stack,
199 Effect.all([
200 Config.String("ALCHEMY_STACK_NAME"),
201 Config.String("ALCHEMY_STAGE")
202 ]).pipe(
203 Effect.map(([name, stage]) => ({
204 name,
205 stage,
206 bindings: {},
207 resources: {}
208 }))
209 )
210 );
211 await Effect.runPromise(
212 tag.pipe(
213 Effect.provide(
214 layer.pipe(
215 Layer.provideMerge(stack),
216 Layer.provideMerge(platform),
217 Layer.provideMerge(
218 Layer.succeed(
219 ConfigProvider.ConfigProvider,
220 reifyBoundConfigProvider(ConfigProvider.fromEnv(), process.env)
221 )
222 ),
223 )
224 )
225 )
226 );
227 `;
228
229 /** Flatten a binding/env leaf into an env string. Unwraps Redacted. */
230 export const plainEnvValue = (value: unknown): string | undefined => {
231 if (value === undefined || value === null) return undefined;
232 if (Redacted.isRedacted(value)) return value.pipe(Redacted.value, plainEnvValue);
233 if (typeof value === "string") {
234 if (value.startsWith("{")) {
235 try {
236 const parsed: unknown = JSON.parse(value);
237 if (
238 typeof parsed === "object" &&
239 parsed !== null &&
240 (parsed as { _tag?: unknown })._tag === "Redacted" &&
241 typeof (parsed as { value?: unknown }).value === "string"
242 ) {
243 const inner = (parsed as { value: string }).value;
244 return inner.length > 0 ? inner : undefined;
245 }
246 } catch {
247 // plain string that happens to start with `{`
248 }
249 }
250 return value.length > 0 ? value : undefined;
251 }
252 if (typeof value === "number" || typeof value === "boolean") {
253 return String(value);
254 }
255 return undefined;
256 };
257
258 export const toEnvRecord = (env: Record<string, any> | undefined): Record<string, string> =>
259 Object.fromEntries(
260 Object.entries(env ?? {}).flatMap(([key, value]) => {
261 const raw = plainEnvValue(value);
262 return raw === undefined ? [] : [[key, raw]];
263 }),
264 );
265
266 const coerceBindingId = (value: unknown): string | undefined => {
267 const direct = plainEnvValue(value);
268 if (direct !== undefined) return direct;
269 if (value != null && typeof value === "object") {
270 const record = value as { volumeId?: unknown; id?: unknown };
271 return coerceBindingId(record.volumeId) ?? coerceBindingId(record.id);
272 }
273 return undefined;
274 };
275
276 export const collectBindingState = (bindings: readonly ResourceBinding<ServiceBinding>[]) => {
277 const active = bindings.filter(
278 (binding: ResourceBinding<ServiceBinding> & { action?: string }) => binding.action !== "delete",
279 );
280 const env = toEnvRecord(
281 active
282 .map((binding) => binding?.data?.env)
283 .reduce<Record<string, any>>((acc, value) => ({ ...acc, ...value }), {}),
284 );
285 const mounts: MountSpec[] = [];
286 const seen = new Set<string>();
287 for (const binding of active) {
288 for (const mount of binding?.data?.mounts ?? []) {
289 const volumeId = coerceBindingId(mount.volumeId);
290 if (volumeId === undefined) continue;
291 const key = `${volumeId}:${mount.path}`;
292 if (seen.has(key)) continue;
293 seen.add(key);
294 mounts.push({ volumeId, path: mount.path });
295 }
296 }
297 return { env, mounts };
298 };
299
300 export class FunctionBundleNotSingleFile extends Data.TaggedError(
301 "Railway.FunctionBundleNotSingleFile",
302 )<{
303 files: readonly string[];
304 }> {}
305
306 const decodeBundleText = (content: string | Uint8Array): string =>
307 typeof content === "string" ? content : new TextDecoder().decode(content);
308
309 const IMPORT_SPEC = /(?:from|import)\s*\(\s*["']([^"']+)["']|(?:from|import)\s+["']([^"']+)["']/g;
310
311 const CANVAS_PINNED = new Set(["effect", "@effect/platform-bun"]);
312
313 /** Packages Railway must install; `@effect/platform-node` is stubbed. */
314 const skipCanvasPin = (root: string): boolean =>
315 CANVAS_PINNED.has(root) ||
316 root === "alchemy" ||
317 root.startsWith("@effect/platform-node") ||
318 root.startsWith("@distilled.cloud/");
319
320 const collectCanvasPackageRoots = (
321 source: string,
322 install: Readonly<Record<string, string>>,
323 ): string[] => {
324 const roots = new Set<string>(Object.keys(install));
325 for (const match of source.matchAll(IMPORT_SPEC)) {
326 const spec = match[1] ?? match[2];
327 if (spec === undefined) continue;
328 const root = parsePackageRootFromSpecifier(spec);
329 if (root !== undefined && !skipCanvasPin(root)) roots.add(root);
330 }
331 return [...roots].sort();
332 };
333
334 const readPackageVersion = (name: string): string | undefined => {
335 try {
336 const req = createRequire(import.meta.url);
337 const version = (req(`${name}/package.json`) as { version?: string }).version;
338 return typeof version === "string" && version.length > 0 ? version : undefined;
339 } catch {
340 return undefined;
341 }
342 };
343
344 const pinImport = (name: string, version?: string): string => {
345 const spec =
346 version !== undefined && version.length > 0 && version !== "*" ? `${name}@${version}` : name;
347 return `import ${JSON.stringify(spec)};`;
348 };
349
350 /**
351 * Canvas wrapper that listens first, then import()s the bundled module.
352 * Static `import "pkg@version"` pins are for Railway's AST installer —
353 * `effect` is 4.x here, 3.x on npm without a pin. Extra pins come from
354 * remaining external imports (`pg`, `drizzle-orm`, `@effect/sql-pg`).
355 */
356 const wrapCanvasListener = (inner: string, install: Readonly<Record<string, string>> = {}) =>
357 Effect.sync(() => {
358 const effectVersion = readPackageVersion("effect") ?? "latest";
359 const bunVersion = readPackageVersion("@effect/platform-bun") ?? "latest";
360 const extraPins = collectCanvasPackageRoots(inner, install).map((name) => {
361 const requested = install[name];
362 const version =
363 requested !== undefined && requested !== "*" ? requested : readPackageVersion(name);
364 return pinImport(name, version);
365 });
366 const pins = [
367 pinImport("effect", effectVersion),
368 ...(inner.includes("@effect/platform-bun")
369 ? [pinImport("@effect/platform-bun", bunVersion)]
370 : []),
371 ...extraPins,
372 ].join("\n");
373 return `${pins}
374 const g=globalThis,port=Number(process.env.PORT??3000);
375 g.__aFF??=async()=>new Response("");
376 Bun.serve({hostname:"0.0.0.0",port,fetch:r=>g.__aFF(r)});
377 try{
378 const u=new URL("./i.mjs",import.meta.url);
379 await Bun.write(u,${JSON.stringify(inner)});
380 await import(u.href);
381 }catch(e){
382 g.__aFF=async()=>new Response(String(e),{status:500});
383 }
384 `;
385 });
386
387 /**
388 * Canvas wrapper for async (non-Effect) Functions. No Effect pin, no
389 * `__aFF` bridge — the user's `export default { fetch }` is the handler,
390 * with `process.env` as the second argument (Cloudflare `env`).
391 */
392 const wrapAsyncCanvasListener = (
393 inner: string,
394 handler: string,
395 install: Readonly<Record<string, string>> = {},
396 ) =>
397 Effect.sync(() => {
398 const extraPins = collectCanvasPackageRoots(inner, install).map((name) => {
399 const requested = install[name];
400 const version =
401 requested !== undefined && requested !== "*" ? requested : readPackageVersion(name);
402 return pinImport(name, version);
403 });
404 const pins = extraPins.join("\n");
405 const handlerLit = JSON.stringify(handler);
406 return `${pins}
407 const port=Number(process.env.PORT??3000);
408 const fail=e=>new Response(String(e),{status:500});
409 try{
410 const u=new URL("./i.mjs",import.meta.url);
411 await Bun.write(u,${JSON.stringify(inner)});
412 const m=await import(u.href);
413 const e=m[${handlerLit}];
414 const f=typeof e==="function"?e:e?.fetch;
415 if(typeof f!=="function")throw new Error("async Function missing fetch");
416 Bun.serve({hostname:"0.0.0.0",port,fetch:r=>f(r,process.env)});
417 }catch(e){
418 Bun.serve({hostname:"0.0.0.0",port,fetch:()=>fail(e)});
419 }
420 `;
421 });
422
423 const isCanvasFunctionExternal = (moduleId: string): boolean => {
424 if (moduleId.startsWith("@effect/platform-node")) return false;
425 if (moduleId === "node:os") return false;
426 return (
427 moduleId === "effect" ||
428 moduleId.startsWith("effect/") ||
429 moduleId.startsWith("@effect/") ||
430 moduleId.startsWith("node:") ||
431 moduleId === "bun" ||
432 moduleId.startsWith("bun:")
433 );
434 };
435
436 const STUB_PLATFORM_NODE = "virtual:alchemy-stub-platform-node";
437
438 /** Functions run on Bun. Drop `@effect/platform-node` so Railway does not install it. */
439 const stubPlatformNodePlugin = (): rolldown.Plugin => ({
440 name: "alchemy:stub-platform-node",
441 resolveId: {
442 filter: { id: /^@effect\/platform-node/ },
443 handler() {
444 return { id: STUB_PLATFORM_NODE, moduleSideEffects: false };
445 },
446 },
447 load: {
448 filter: { id: /^virtual:alchemy-stub-platform-node$/ },
449 handler() {
450 return { code: "export default {};\n", moduleType: "js" };
451 },
452 },
453 });
454
455 const STUB_NODE_OS = "virtual:alchemy-stub-node-os";
456
457 const stubNodeOsPlugin = (): rolldown.Plugin => ({
458 name: "alchemy:stub-node-os",
459 resolveId: {
460 filter: { id: /^node:os$/ },
461 handler() {
462 return { id: STUB_NODE_OS, moduleSideEffects: false };
463 },
464 },
465 load: {
466 filter: { id: /^virtual:alchemy-stub-node-os$/ },
467 handler() {
468 return {
469 code: [
470 "export const homedir = () => '/';",
471 "export const cpus = () => [];",
472 "export const platform = () => 'linux';",
473 "export const arch = () => 'x64';",
474 "export const tmpdir = () => '/tmp';",
475 "export const hostname = () => 'railway';",
476 "export const type = () => 'Linux';",
477 "export const release = () => '';",
478 "export const endianness = () => 'LE';",
479 "export default { homedir, cpus, platform, arch, tmpdir, hostname, type, release, endianness };",
480 "",
481 ].join("\n"),
482 moduleType: "js",
483 };
484 },
485 },
486 });
487
488 const createBundleProgram = (
489 virtualEntryPlugin: (content: (importPath: string) => string) => rolldown.Plugin,
490 options?: {
491 output?: Partial<rolldown.OutputOptions>;
492 /**
493 * Extra unresolved specifiers to leave as imports. Canvas Functions
494 * auto-install npm packages; leaving `effect` external keeps the
495 * encoded start command under 96KB.
496 */
497 canvasExternals?: boolean;
498 bootstrap?: (handler: string) => (importPath: string) => string;
499 /**
500 * Bundle `main` as the entry with no virtual bootstrap. Used for
501 * async (non-Effect) canvas Functions (`isExternal`).
502 */
503 skipVirtualEntry?: boolean;
504 },
505 ) =>
506 Effect.fn(function* (props: HostedProgramProps) {
507 const handler = props.handler ?? "default";
508 const realMain = yield* resolveMainPath(props.main);
509 const cwd = yield* findCwdForBundle(realMain);
510 const bootstrap = (options?.bootstrap ?? makeNodeBootstrap)(handler);
511 const requested = yield* normalizeInstallTargets(props.build?.install);
512 const installRoots = new Set(Object.keys(requested));
513 const configuredExternal = props.build?.input?.external;
514 const output = options?.output;
515 const canvasExternals = options?.canvasExternals === true;
516
517 const buildBundle = Effect.fn(function* (
518 entry: string,
519 plugins?: rolldown.RolldownPluginOption,
520 ) {
521 return yield* Bundle.build(
522 {
523 ...props.build?.input,
524 input: entry,
525 cwd,
526 platform: "node",
527 external: (moduleId, parentId, isResolved) => {
528 if (moduleId === "bun" || moduleId.startsWith("bun:")) return true;
529 if (canvasExternals && isCanvasFunctionExternal(moduleId)) {
530 return true;
531 }
532 for (const root of installRoots) {
533 if (matchesPackageRoot(moduleId, root)) return true;
534 }
535 return matchesConfiguredExternal(configuredExternal, moduleId, parentId, isResolved);
536 },
537 resolve: {
538 // Hosted images run on Node but must still match the `bun`
539 // export of workspace packages (`@distilled.cloud/*`, alchemy).
540 // Those maps have no `node` condition — only `bun`/`worker`/
541 // `default` — and `default` is `lib/` which is absent in a
542 // source checkout. Leaving the specifier unresolved makes
543 // rolldown treat it as external, so the container dies with
544 // `ERR_MODULE_NOT_FOUND` (the Volume tutorial's FAILED deploy).
545 conditionNames: canvasExternals
546 ? ["bun", "import", "module", "default"]
547 : [...Bundle.BUN_CONDITION_NAMES],
548 ...props.build?.input?.resolve,
549 },
550 plugins: [
551 canvasExternals ? stubPlatformNodePlugin() : undefined,
552 canvasExternals ? stubNodeOsPlugin() : undefined,
553 props.build?.input?.plugins,
554 plugins,
555 ],
556 },
557 {
558 ...props.build?.output,
559 ...output,
560 format: "esm",
561 sourcemap: output?.sourcemap ?? props.build?.output?.sourcemap ?? false,
562 entryFileNames: "index.mjs",
563 strictExecutionOrder: true,
564 keepNames: !canvasExternals,
565 },
566 props.build,
567 );
568 });
569
570 if (props.isExternal === true && options?.skipVirtualEntry !== true) {
571 const fs = yield* FileSystem.FileSystem;
572 const path = yield* Path.Path;
573 const bytes = yield* fs.readFile(realMain);
574 const hash = yield* sha256(bytes);
575 return {
576 files: [{ path: path.basename(realMain), content: bytes }],
577 hash,
578 };
579 }
580
581 const bundleOutput = yield* buildBundle(
582 realMain,
583 options?.skipVirtualEntry === true ? undefined : virtualEntryPlugin(bootstrap),
584 );
585
586 const files = bundleOutput.files.map((file) => ({
587 path: file.path,
588 content:
589 typeof file.content === "string" ? new TextEncoder().encode(file.content) : file.content,
590 }));
591
592 return { files, hash: bundleOutput.hash };
593 });
594
595 /**
596 * Bundle an Effect-native Railway.Function into a single TypeScript/JS
597 * file for the canvas function runtime. No Docker. No registry.
598 */
599 export const createRailwayFunctionSupport = ({
600 stackName,
601 stage,
602 virtualEntryPlugin,
603 }: {
604 stackName: string;
605 stage: string;
606 virtualEntryPlugin: (content: (importPath: string) => string) => rolldown.Plugin;
607 }) => {
608 const alchemyEnv = {
609 ALCHEMY_STACK_NAME: stackName,
610 ALCHEMY_STAGE: stage,
611 ALCHEMY_PHASE: "runtime",
612 HOST: "0.0.0.0",
613 };
614
615 const bundleProgram = createBundleProgram(virtualEntryPlugin, {
616 canvasExternals: true,
617 bootstrap: makeFunctionBootstrap,
618 output: {
619 // dce-only (Bundle.build default) keeps `import … from "effect/…"`
620 // readable so Railway's AST installer sees Effect 4 pins. Full
621 // minify still 502s: npm `effect` is 3.x without those subpaths.
622 codeSplitting: false,
623 },
624 });
625
626 const asyncBundleProgram = createBundleProgram(virtualEntryPlugin, {
627 canvasExternals: true,
628 skipVirtualEntry: true,
629 output: { codeSplitting: false },
630 });
631
632 const bundleToSource = Effect.fn(function* (props: HostedProgramProps) {
633 const bundled =
634 props.isExternal === true ? yield* asyncBundleProgram(props) : yield* bundleProgram(props);
635 if (bundled.files.length !== 1) {
636 return yield* new FunctionBundleNotSingleFile({
637 files: bundled.files.map((file) => file.path),
638 });
639 }
640 const inner = decodeBundleText(bundled.files[0]!.content);
641 const install = yield* normalizeInstallTargets(props.build?.install);
642 const source =
643 props.isExternal === true
644 ? yield* wrapAsyncCanvasListener(inner, props.handler ?? "default", install)
645 : yield* wrapCanvasListener(inner, install);
646 const hash = yield* sha256(source);
647 return { source, hash };
648 });
649
650 const hash = Effect.fn(function* (props: HostedProgramProps) {
651 const bundled = yield* bundleToSource(props);
652 return bundled.hash;
653 });
654
655 return { alchemyEnv, bundleProgram, bundleToSource, hash };
656 };
657
658 const generateDockerfile = (
659 props: HostedProgramProps,
660 hasChunks: boolean,
661 install?: Record<string, string>,
662 entryRel?: string,
663 ) => {
664 const port = props.port ?? DEFAULT_PORT;
665 const lines = [`FROM ${props.image ?? DEFAULT_BASE_IMAGE}`, `WORKDIR /app`];
666 if (install !== undefined && Object.keys(install).length > 0) {
667 lines.push(
668 `COPY package.json /app/package.json`,
669 `RUN npm install --omit=dev --no-fund --no-audit`,
670 );
671 }
672 if (props.isExternal === true) {
673 lines.push(`COPY . /app`);
674 const entry = entryRel !== undefined && entryRel.length > 0 ? entryRel : "serve-node.mjs";
675 lines.push(
676 `ENV PORT=${String(port)}`,
677 `ENV HOST=0.0.0.0`,
678 `EXPOSE ${String(port)}`,
679 `ENTRYPOINT ["node", ${JSON.stringify(`/app/${entry}`)}]`,
680 );
681 return `${lines.join("\n")}\n`;
682 }
683 lines.push(`COPY index.mjs /app/index.mjs`);
684 if (hasChunks) {
685 lines.push(`COPY *.js /app/`);
686 }
687 lines.push(...dockerfileCopyLines(props.extraFiles));
688 lines.push(
689 `ENV PORT=${String(port)}`,
690 `ENV HOST=0.0.0.0`,
691 `EXPOSE ${String(port)}`,
692 `ENTRYPOINT ["node", "/app/index.mjs"]`,
693 );
694 return `${lines.join("\n")}\n`;
695 };
696
697 const installManifest = (dependencies: Record<string, string>) =>
698 `${JSON.stringify({ private: true, type: "module", dependencies }, null, 2)}\n`;
699
700 export const createRailwayHostedSupport = ({
701 stackName,
702 stage,
703 virtualEntryPlugin,
704 dotAlchemy,
705 }: {
706 stackName: string;
707 stage: string;
708 virtualEntryPlugin: (content: (importPath: string) => string) => rolldown.Plugin;
709 dotAlchemy: string;
710 }) => {
711 const alchemyEnv = {
712 ALCHEMY_STACK_NAME: stackName,
713 ALCHEMY_STAGE: stage,
714 ALCHEMY_PHASE: "runtime",
715 HOST: "0.0.0.0",
716 };
717
718 const bundleProgram = createBundleProgram(virtualEntryPlugin);
719
720 const computeCodeHash = Effect.fn(function* (props: HostedProgramProps) {
721 const bundled = yield* bundleProgram(props);
722 const realMain = yield* resolveMainPath(props.main);
723 const cwd = yield* findCwdForBundle(realMain);
724 const requested = yield* normalizeInstallTargets(props.build?.install);
725 const identity =
726 Object.keys(requested).length > 0
727 ? yield* resolvePackageInstallIdentity({ cwd, requested })
728 : undefined;
729 const install =
730 identity !== undefined && Object.keys(identity.resolved).length > 0
731 ? identity.resolved
732 : undefined;
733 const packageJson = install === undefined ? undefined : installManifest(install);
734 const path = yield* Path.Path;
735 const extras = props.extraFiles ?? [];
736 const root = contextRootOf(realMain, extras, path, (source) =>
737 resolveExtraSource(source, path),
738 );
739 const entryRel =
740 props.isExternal === true
741 ? (posixRelUnder(root, realMain, path) ?? path.basename(realMain))
742 : undefined;
743 const dockerfile = generateDockerfile(props, bundled.files.length > 1, install, entryRel);
744 const extraFiles = yield* hashExtraFiles(props.extraFiles);
745 const codeHash = (yield* sha256Object({
746 bundleHash: bundled.hash,
747 dockerfile,
748 packageJson,
749 extraFiles,
750 extraFilesIncludesNodeModules: true,
751 })).slice(0, 16);
752 return { bundled, dockerfile, codeHash, packageJson };
753 });
754
755 /**
756 * Write the generated Dockerfile + bundled entry + extraFiles into a
757 * stable context directory. Railway builds this; Alchemy does not.
758 */
759 const writeContext = Effect.fn(function* (input: {
760 id: string;
761 props: HostedProgramProps;
762 hashed: {
763 bundled: {
764 files: ReadonlyArray<{ path: string; content: string | Uint8Array }>;
765 };
766 dockerfile: string;
767 packageJson: string | undefined;
768 };
769 }) {
770 const fs = yield* FileSystem.FileSystem;
771 const path = yield* Path.Path;
772 const realMain = yield* resolveMainPath(input.props.main);
773 const contextDir = yield* getStableContextDir(realMain, dotAlchemy, `${input.id}-image`);
774 if (yield* fs.exists(contextDir)) {
775 yield* fs.remove(contextDir, { recursive: true });
776 }
777 yield* fs.makeDirectory(contextDir, { recursive: true });
778 const files: Array<{ path: string; content: string | Uint8Array }> = [
779 { path: "Dockerfile", content: input.hashed.dockerfile },
780 ...(input.props.isExternal === true
781 ? []
782 : input.hashed.bundled.files.map((file, index) => ({
783 path: index === 0 ? "index.mjs" : file.path,
784 content: file.content,
785 }))),
786 ];
787 if (input.hashed.packageJson !== undefined) {
788 files.push({
789 path: "package.json",
790 content: input.hashed.packageJson,
791 });
792 }
793 for (const file of files) {
794 const fullPath = path.join(contextDir, file.path);
795 yield* fs.makeDirectory(path.dirname(fullPath), { recursive: true });
796 if (typeof file.content === "string") {
797 yield* fs.writeFileString(fullPath, file.content);
798 } else {
799 yield* fs.writeFile(fullPath, file.content);
800 }
801 }
802 yield* copyExtraFiles(contextDir, input.props.extraFiles, {
803 onMissing: (file) => new ExtraFileMissing(file),
804 });
805 if (input.props.isExternal === true) {
806 const extras = input.props.extraFiles ?? [];
807 const root = contextRootOf(realMain, extras, path, (source) =>
808 resolveExtraSource(source, path),
809 );
810 const entryRel = posixRelUnder(root, realMain, path) ?? path.basename(realMain);
811 const dest = path.join(contextDir, entryRel);
812 if (!(yield* fs.exists(dest))) {
813 yield* fs.makeDirectory(path.dirname(dest), { recursive: true });
814 const contents = yield* fs.readFile(realMain);
815 yield* fs.writeFile(dest, contents);
816 }
817 }
818 return contextDir;
819 });
820
821 const hash = Effect.fn(function* (props: HostedProgramProps) {
822 const { codeHash } = yield* computeCodeHash(props);
823 return codeHash;
824 });
825
826 return {
827 alchemyEnv,
828 bundleProgram,
829 computeCodeHash,
830 writeContext,
831 hash,
832 };
833 };