The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as LocalProvider from "alchemy/Local/LocalProvider"; |
| 2 | import { Stack } from "alchemy/Stack"; |
| 3 | import { Stage } from "alchemy/Stage"; |
| 4 | import { moduleExtension } from "alchemy/Util/Node"; |
| 5 | import { sha256 } from "alchemy/Util/sha256"; |
| 6 | import * as Deferred from "effect/Deferred"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as FileSystem from "effect/FileSystem"; |
| 9 | import * as Path from "effect/Path"; |
| 10 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 11 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 12 | import * as Result from "effect/Result"; |
| 13 | import * as SemVer from "effect/SemVer"; |
| 14 | import * as Stream from "effect/Stream"; |
| 15 | import { branchScopeOf, Function } from "./Function.ts"; |
| 16 | import { buildFunctionArtifact, validateFunctionZip } from "./FunctionArtifact.ts"; |
| 17 | import { FunctionConfigurationError, functionEnvironment, functionSlug } from "./FunctionConfig.ts"; |
| 18 | |
| 19 | export const LocalFunctionProvider = () => |
| 20 | LocalProvider.make( |
| 21 | Function, |
| 22 | import.meta.resolve(`./LocalFunction${moduleExtension(import.meta.url)}`), |
| 23 | Effect.gen(function* () { |
| 24 | const fs = yield* FileSystem.FileSystem; |
| 25 | const path = yield* Path.Path; |
| 26 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 27 | return { |
| 28 | resolveConfig: Effect.fn(function* ({ news, bindings }) { |
| 29 | const source = news.main |
| 30 | ? news.main.startsWith("file:") |
| 31 | ? yield* path.fromFileUrl(new URL(news.main)) |
| 32 | : news.main |
| 33 | : news.artifact?.zip; |
| 34 | const hash = source |
| 35 | ? yield* fs.readFile(source).pipe(Effect.flatMap(sha256)) |
| 36 | : (yield* buildFunctionArtifact(news)).codeHash; |
| 37 | return { news, bindings, hash }; |
| 38 | }), |
| 39 | start: Effect.fn(function* ({ id, instanceId, news, bindings, invalidate }) { |
| 40 | const command = news.dev?.command ?? "neon"; |
| 41 | const version = yield* spawner.string(ChildProcess.make(command, ["--version"])).pipe( |
| 42 | Effect.timeout("5 seconds"), |
| 43 | Effect.mapError( |
| 44 | (cause) => |
| 45 | new FunctionConfigurationError({ |
| 46 | message: |
| 47 | cause._tag === "PlatformError" && cause.reason._tag === "NotFound" |
| 48 | ? `Neon CLI executable '${command}' was not found. Install Neon CLI >=2.45.0: https://neon.com/cli . Ensure '${command}' is on PATH, or set Function.dev.command to its executable path. Local Functions also require Node 24.` |
| 49 | : `Could not run '${command} --version': ${cause.message}`, |
| 50 | cause, |
| 51 | }), |
| 52 | ), |
| 53 | ); |
| 54 | const cliVersion = Result.getOrUndefined( |
| 55 | SemVer.parse(version.match(/\d+\.\d+\.\d+/)?.[0] ?? ""), |
| 56 | ); |
| 57 | if ( |
| 58 | cliVersion === undefined || |
| 59 | SemVer.isLessThan(cliVersion, SemVer.parseUnsafe("2.45.0")) |
| 60 | ) |
| 61 | return yield* new FunctionConfigurationError({ |
| 62 | message: "Local Function WebSockets require Neon CLI >=2.45.0", |
| 63 | }); |
| 64 | const nodeVersion = yield* spawner.string(ChildProcess.make("node", ["--version"])); |
| 65 | if (!nodeVersion.trim().startsWith("v24.")) |
| 66 | return yield* new FunctionConfigurationError({ |
| 67 | message: "Local Functions require Node 24", |
| 68 | }); |
| 69 | const root = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-neon-function-" }); |
| 70 | const writeArtifact = Effect.gen(function* () { |
| 71 | const artifact = yield* buildFunctionArtifact(news); |
| 72 | const files = yield* validateFunctionZip(artifact.archive); |
| 73 | for (const [name, content] of Object.entries(files)) { |
| 74 | if (name.endsWith("/")) continue; |
| 75 | const file = path.join(root, name); |
| 76 | yield* fs.makeDirectory(path.dirname(file), { recursive: true }); |
| 77 | yield* fs.writeFile(file, content); |
| 78 | } |
| 79 | return artifact.codeHash; |
| 80 | }); |
| 81 | const codeHash = yield* writeArtifact; |
| 82 | const slug = yield* functionSlug(id, news.slug); |
| 83 | const env = yield* functionEnvironment(news, bindings); |
| 84 | const stack = yield* Stack; |
| 85 | const stage = yield* Stage; |
| 86 | const base = yield* Effect.sync(() => |
| 87 | Object.fromEntries( |
| 88 | ["PATH", "HOME", "TMPDIR", "SystemRoot"].flatMap((key) => |
| 89 | process.env[key] ? [[key, process.env[key]!]] : [], |
| 90 | ), |
| 91 | ), |
| 92 | ); |
| 93 | const child = yield* spawner.spawn( |
| 94 | ChildProcess.make( |
| 95 | command, |
| 96 | [ |
| 97 | "dev", |
| 98 | "--source", |
| 99 | path.join(root, "index.mjs"), |
| 100 | ...(news.dev?.port ? ["--port", String(news.dev.port)] : []), |
| 101 | ], |
| 102 | { |
| 103 | cwd: root, |
| 104 | env: { |
| 105 | ...base, |
| 106 | ...env, |
| 107 | ALCHEMY_STACK_NAME: stack.name, |
| 108 | ALCHEMY_STAGE: stage, |
| 109 | ALCHEMY_PHASE: "runtime", |
| 110 | }, |
| 111 | extendEnv: false, |
| 112 | stdin: "ignore", |
| 113 | stdout: "pipe", |
| 114 | stderr: "pipe", |
| 115 | }, |
| 116 | ), |
| 117 | ); |
| 118 | const ready = yield* Deferred.make<string>(); |
| 119 | const capture = ( |
| 120 | stream: Stream.Stream<Uint8Array, import("effect/PlatformError").PlatformError>, |
| 121 | ) => |
| 122 | stream.pipe( |
| 123 | Stream.decodeText, |
| 124 | Stream.runForEach((text) => { |
| 125 | const url = text.match(/http:\/\/(?:localhost|127\.0\.0\.1):\d+/)?.[0]; |
| 126 | return url ? Deferred.succeed(ready, url) : Effect.void; |
| 127 | }), |
| 128 | Effect.forkScoped, |
| 129 | ); |
| 130 | yield* capture(child.stdout); |
| 131 | yield* capture(child.stderr); |
| 132 | const url = yield* Effect.raceAllFirst([ |
| 133 | Deferred.await(ready).pipe(Effect.timeout("15 seconds")), |
| 134 | child.exitCode.pipe( |
| 135 | Effect.flatMap( |
| 136 | () => |
| 137 | new FunctionConfigurationError({ |
| 138 | message: |
| 139 | "Neon local runtime exited before readiness; install Neon CLI >=2.45.0 and Node 24", |
| 140 | }), |
| 141 | ), |
| 142 | ), |
| 143 | ]); |
| 144 | yield* child.exitCode.pipe(Effect.exit, Effect.andThen(invalidate), Effect.forkScoped); |
| 145 | const watched = news.main ?? news.artifact?.directory ?? news.artifact?.zip; |
| 146 | if (watched) { |
| 147 | const source = watched.startsWith("file:") |
| 148 | ? yield* path.fromFileUrl(new URL(watched)) |
| 149 | : path.resolve(watched); |
| 150 | const directory = news.artifact?.directory ? source : path.dirname(source); |
| 151 | yield* fs.watch(directory, { recursive: true }).pipe( |
| 152 | Stream.runForEach(() => |
| 153 | writeArtifact.pipe( |
| 154 | Effect.ignoreCause({ log: "Error", message: "Neon Function rebuild failed" }), |
| 155 | ), |
| 156 | ), |
| 157 | Effect.forkScoped, |
| 158 | ); |
| 159 | } |
| 160 | const scope = branchScopeOf(news); |
| 161 | const projectId = scope.branch?.projectId ?? scope.project?.projectId ?? "local"; |
| 162 | const branchId = scope.branch?.branchId ?? "local"; |
| 163 | return { |
| 164 | projectId, |
| 165 | branchId, |
| 166 | functionId: `dev:${instanceId}`, |
| 167 | slug, |
| 168 | name: news.name ?? slug, |
| 169 | url, |
| 170 | currentDeploymentId: undefined, |
| 171 | activeDeploymentId: undefined, |
| 172 | status: "local", |
| 173 | codeHash, |
| 174 | environment: Object.keys(env), |
| 175 | }; |
| 176 | }), |
| 177 | }; |
| 178 | }), |
| 179 | ); |