The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeFs from "node:fs"; |
| 2 | import * as NodePath from "node:path"; |
| 3 | /** |
| 4 | * `@alchemy.run/frontend-frameworks/sveltekit/node` — the Node container |
| 5 | * deploy target for `@alchemy.run/frontend-frameworks/sveltekit`. |
| 6 | * |
| 7 | * SvelteKit's Node story mirrors adapter-node: kit's server graph |
| 8 | * (`.svelte-kit/output/server`) is Node-flavored ESM. The finishing pass |
| 9 | * re-bundles that graph with rolldown into `dist/server`, then writes a |
| 10 | * Node HTTP program that serves `clientDirectory` first, then falls |
| 11 | * through to kit's `Server.respond` on `PORT` (default 3000), and answers |
| 12 | * `GET /health`. |
| 13 | * |
| 14 | * - **`adapter(context)`** — an in-memory kit `Adapter` that writes client |
| 15 | * assets + prerendered pages and an unbundled fetch-handler entry. |
| 16 | * - **`finish(output, context)`** — re-bundles the entry for Node, writes |
| 17 | * the HTTP serve entry, pins it as `serverModules[0]`. |
| 18 | * - **`bundle`** — Node resolve conditions (no `workerd`, no `@aws-sdk/`). |
| 19 | */ |
| 20 | import type { Builder } from "@sveltejs/kit"; |
| 21 | import * as Effect from "effect/Effect"; |
| 22 | import * as FileSystem from "effect/FileSystem"; |
| 23 | import * as Path from "effect/Path"; |
| 24 | import { rolldown } from "rolldown"; |
| 25 | import { runBuildChild } from "../core/BuildChild.ts"; |
| 26 | import * as FrameworkCore from "../core/index.ts"; |
| 27 | import { DeployTargetError, makeDeployTarget } from "../core/index.ts"; |
| 28 | import { |
| 29 | NODE_BUNDLE_CONDITIONS, |
| 30 | NODE_SERVE_ENTRY_FILE_NAME, |
| 31 | relativeClientDirExpression, |
| 32 | writeNodeServeEntry, |
| 33 | } from "../core/NodeServe.ts"; |
| 34 | import { |
| 35 | make, |
| 36 | type SvelteKitAdapter, |
| 37 | type SvelteKitAdapterResult, |
| 38 | type SvelteKitTarget, |
| 39 | type SvelteKitTargetConfig, |
| 40 | } from "./SvelteKit.ts"; |
| 41 | |
| 42 | const fail = (message: string, cause?: unknown) => |
| 43 | new DeployTargetError({ platform: "node", message, cause }); |
| 44 | |
| 45 | export interface SvelteKitNodeTargetConfig extends SvelteKitTargetConfig {} |
| 46 | |
| 47 | /** The bundled fetch-handler module the finishing pass writes. */ |
| 48 | export const SERVER_ENTRY_NAME = "server/index.mjs"; |
| 49 | |
| 50 | const generateFetchEntry = (options: { readonly serverImport: string }): string => |
| 51 | /* js */ ` |
| 52 | import { server } from ${JSON.stringify(options.serverImport)}; |
| 53 | |
| 54 | const initialized = server.init({ env: process.env }); |
| 55 | |
| 56 | export const handler = async (request) => { |
| 57 | await initialized; |
| 58 | return await server.respond(request, { |
| 59 | getClientAddress: () => |
| 60 | request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? '127.0.0.1', |
| 61 | }); |
| 62 | }; |
| 63 | `.trimStart(); |
| 64 | |
| 65 | export const makeNodeAdapter = (): SvelteKitAdapter => { |
| 66 | const result: { current?: SvelteKitAdapterResult | undefined } = {}; |
| 67 | return { |
| 68 | name: "@alchemy.run/frontend-frameworks/sveltekit/node", |
| 69 | result, |
| 70 | async adapt(builder: Builder) { |
| 71 | const dest = builder.getBuildDirectory("node"); |
| 72 | const tmp = builder.getBuildDirectory("node-tmp"); |
| 73 | |
| 74 | builder.rimraf(dest); |
| 75 | builder.rimraf(tmp); |
| 76 | builder.mkdirp(dest); |
| 77 | builder.mkdirp(tmp); |
| 78 | |
| 79 | const assetsDest = dest + builder.config.paths.base; |
| 80 | builder.mkdirp(assetsDest); |
| 81 | builder.writeClient(assetsDest); |
| 82 | builder.writePrerendered(assetsDest); |
| 83 | |
| 84 | // pre-built server instance: kit 3.0 no longer exposes the internal |
| 85 | // SSR manifest (`generateManifest` throws), so `generateServerInstance` |
| 86 | // writes `export const server = new Server(manifest)` straight to |
| 87 | // disk itself instead of returning a manifest string to embed. The |
| 88 | // Node serve entry checks the filesystem for static assets, so unlike |
| 89 | // the Cloudflare worker shim there's no route manifest to build. |
| 90 | builder.generateServerInstance(NodePath.join(tmp, "server.js")); |
| 91 | |
| 92 | const workerEntry = NodePath.join(tmp, "entry.js"); |
| 93 | NodeFs.writeFileSync( |
| 94 | workerEntry, |
| 95 | generateFetchEntry({ |
| 96 | serverImport: "./server.js", |
| 97 | }), |
| 98 | ); |
| 99 | if ( |
| 100 | typeof builder.hasServerInstrumentationFile === "function" && |
| 101 | builder.hasServerInstrumentationFile() |
| 102 | ) { |
| 103 | // kit 3.0 requires an explicit initializer module that populates |
| 104 | // `$env/dynamic/private` before instrumentation runs; the default |
| 105 | // (`process.env`) is correct for the Node runtime. |
| 106 | const initializer = builder.createInstrumentationInitializer({ |
| 107 | outputDirectory: tmp, |
| 108 | }); |
| 109 | builder.instrument({ |
| 110 | entrypoint: workerEntry, |
| 111 | instrumentation: NodePath.join(builder.getServerDirectory(), "instrumentation.server.js"), |
| 112 | initializer, |
| 113 | }); |
| 114 | } |
| 115 | |
| 116 | result.current = { dest, workerEntry }; |
| 117 | }, |
| 118 | dispose: async () => {}, |
| 119 | }; |
| 120 | }; |
| 121 | |
| 122 | const makeNodeAdapterTarget = (config: SvelteKitNodeTargetConfig = {}): SvelteKitTarget => |
| 123 | makeDeployTarget({ |
| 124 | platform: "node", |
| 125 | config, |
| 126 | bundle: { |
| 127 | conditions: [...NODE_BUNDLE_CONDITIONS], |
| 128 | }, |
| 129 | adapter: (_context) => makeNodeAdapter(), |
| 130 | finish: (output, context) => |
| 131 | Effect.gen(function* () { |
| 132 | const fs = yield* FileSystem.FileSystem; |
| 133 | const path = yield* Path.Path; |
| 134 | const entry = context.entry; |
| 135 | if (entry === undefined) { |
| 136 | return yield* fail( |
| 137 | "The SvelteKit build produced no on-disk server entry for the finishing pass " + |
| 138 | "(context.entry is missing)", |
| 139 | ); |
| 140 | } |
| 141 | const root = context.root; |
| 142 | const distDirectory = output.distDirectory ?? path.resolve(root, "dist"); |
| 143 | if (output.clientDirectory === undefined) { |
| 144 | return yield* fail( |
| 145 | "The SvelteKit build produced no client directory for the Node serve entry", |
| 146 | ); |
| 147 | } |
| 148 | // Container hosts package only distDirectory. Keep the assets beside |
| 149 | // the server so the output remains runnable after it is relocated. |
| 150 | const clientDirectory = path.join(distDirectory, "client"); |
| 151 | yield* fs.remove(clientDirectory, { recursive: true, force: true }).pipe( |
| 152 | Effect.andThen(fs.copy(output.clientDirectory, clientDirectory)), |
| 153 | Effect.mapError((error) => fail("Failed to package the SvelteKit client assets", error)), |
| 154 | ); |
| 155 | const serverOutDir = path.join(distDirectory, "server"); |
| 156 | yield* fs |
| 157 | .remove(serverOutDir, { recursive: true, force: true }) |
| 158 | .pipe(Effect.mapError((error) => fail("Failed to clean dist/server", error))); |
| 159 | |
| 160 | yield* Effect.tryPromise({ |
| 161 | try: async () => { |
| 162 | const bundle = await rolldown({ |
| 163 | cwd: root, |
| 164 | input: entry, |
| 165 | platform: "node", |
| 166 | resolve: { |
| 167 | conditionNames: [...NODE_BUNDLE_CONDITIONS], |
| 168 | }, |
| 169 | external: [/^node:/], |
| 170 | }); |
| 171 | try { |
| 172 | await bundle.write({ |
| 173 | dir: serverOutDir, |
| 174 | format: "esm", |
| 175 | entryFileNames: "index.mjs", |
| 176 | chunkFileNames: "chunks/[name].mjs", |
| 177 | sourcemap: false, |
| 178 | }); |
| 179 | } finally { |
| 180 | await bundle.close(); |
| 181 | } |
| 182 | }, |
| 183 | catch: (error) => fail("Failed to bundle the Node server", error), |
| 184 | }); |
| 185 | |
| 186 | const modules = yield* FrameworkCore.readServerModulesFromDisk({ |
| 187 | directory: serverOutDir, |
| 188 | prefix: "server", |
| 189 | }).pipe(Effect.mapError((error) => fail(error.message, error.cause))); |
| 190 | const bundled: FrameworkCore.BuildOutput = { |
| 191 | ...output, |
| 192 | distDirectory, |
| 193 | clientDirectory, |
| 194 | serverModules: FrameworkCore.sortServerModules(modules, SERVER_ENTRY_NAME), |
| 195 | }; |
| 196 | const servePath = path.join(serverOutDir, NODE_SERVE_ENTRY_FILE_NAME); |
| 197 | return yield* writeNodeServeEntry({ |
| 198 | output: bundled, |
| 199 | servePath, |
| 200 | serveModuleName: path.join("server", NODE_SERVE_ENTRY_FILE_NAME).replaceAll("\\", "/"), |
| 201 | clientDirExpression: relativeClientDirExpression(servePath, clientDirectory), |
| 202 | htmlHandling: "drop-trailing-slash", |
| 203 | handler: { |
| 204 | kind: "fetch", |
| 205 | imports: `import { handler } from "./index.mjs";`, |
| 206 | expr: "handler", |
| 207 | }, |
| 208 | notFoundHandling: |
| 209 | config.adapter?.notFoundHandling === "single-page-application" |
| 210 | ? "spa" |
| 211 | : config.adapter?.notFoundHandling === "404-page" |
| 212 | ? "404-page" |
| 213 | : "none", |
| 214 | platform: "node", |
| 215 | }); |
| 216 | }), |
| 217 | }); |
| 218 | |
| 219 | export interface SvelteKitNodeBuildChildConfig { |
| 220 | readonly rootDir: string; |
| 221 | readonly config: SvelteKitNodeTargetConfig; |
| 222 | } |
| 223 | |
| 224 | export const buildInChild = (config: SvelteKitNodeBuildChildConfig) => |
| 225 | Effect.gen(function* () { |
| 226 | const framework = yield* make({ |
| 227 | root: config.rootDir, |
| 228 | target: makeNodeAdapterTarget(config.config), |
| 229 | compatibilityDate: config.config.compatibilityDate, |
| 230 | compatibilityFlags: |
| 231 | config.config.compatibilityFlags !== undefined |
| 232 | ? [...config.config.compatibilityFlags] |
| 233 | : undefined, |
| 234 | kit: config.config.kit, |
| 235 | adapter: config.config.adapter, |
| 236 | }); |
| 237 | return yield* framework.build({ root: config.rootDir }); |
| 238 | }); |
| 239 | |
| 240 | export const makeNodeTarget = (config: SvelteKitNodeTargetConfig = {}): SvelteKitTarget => ({ |
| 241 | ...makeNodeAdapterTarget(config), |
| 242 | build: (context) => |
| 243 | runBuildChild({ |
| 244 | module: import.meta.url, |
| 245 | rootDir: context.root, |
| 246 | env: context.env, |
| 247 | framework: "sveltekit", |
| 248 | config: { |
| 249 | rootDir: context.root, |
| 250 | config, |
| 251 | } satisfies SvelteKitNodeBuildChildConfig, |
| 252 | }).pipe(Effect.mapError((error) => fail(error.message, error.cause))), |
| 253 | }); |
| 254 | |
| 255 | export const target = makeNodeTarget; |
| 256 | |
| 257 | export default makeNodeTarget; |