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

main
ts 76 lines 2.66 KB
Raw
1 import { CurrentRuntimeContext, sanitizeKey } from "alchemy/RuntimeContext";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import type { Function } from "./Function.ts";
5 import { InvokeFunction, InvokeFunctionError } from "./InvokeFunction.ts";
6
7 /**
8 * URL-only HTTP client. Does not provision an invocation credential or private route.
9 *
10 * ### Invoke a Function
11 * **Example:** Provide the HTTP implementation
12 * ```typescript
13 * const application = Effect.gen(function* () {
14 * const api = yield* Neon.InvokeFunction(target);
15 * return {
16 * fetch: Effect.gen(function* () {
17 * const response = yield* api.fetch("/health").pipe(Effect.orDie);
18 * return HttpServerResponse.text(String(response.status));
19 * }),
20 * };
21 * }).pipe(Effect.provide(Neon.InvokeFunctionHttp));
22 * ```
23 *
24 * @layer
25 * @product Function
26 * @provides Neon.InvokeFunction
27 */
28 export const InvokeFunctionHttp = Layer.effect(
29 InvokeFunction,
30 Effect.gen(function* () {
31 const host = yield* CurrentRuntimeContext;
32 if (!host) return yield* Effect.die(new Error("Neon.InvokeFunction requires a Platform host"));
33 return Effect.fn(function* (fn: Function) {
34 const key = sanitizeKey(
35 `NEON_FUNCTION_${Array.from(fn.FQN, (character) => character.codePointAt(0)!.toString(16)).join("_")}_URL`,
36 );
37 if (!globalThis.__ALCHEMY_RUNTIME__) yield* host.set(key, fn.url);
38 const url = host
39 .get<string>(key)
40 .pipe(
41 Effect.flatMap((url) =>
42 url ? Effect.succeed(url) : Effect.die(new Error("Missing Neon Function URL binding")),
43 ),
44 );
45 return {
46 url,
47 fetch: (path = "/", init?: RequestInit) =>
48 Effect.gen(function* () {
49 const base = yield* url;
50 const target = yield* Effect.try({
51 try: () => new URL(path, base),
52 catch: () =>
53 new InvokeFunctionError({
54 message: "Invalid Function request path",
55 }),
56 });
57 if (target.origin !== new URL(base).origin)
58 return yield* new InvokeFunctionError({
59 message: "Function invocation must remain on the bound origin",
60 });
61 return yield* Effect.tryPromise({
62 try: (signal) =>
63 fetch(target, {
64 ...init,
65 signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal,
66 }),
67 catch: () =>
68 new InvokeFunctionError({
69 message: "Neon Function HTTP request failed",
70 }),
71 });
72 }),
73 };
74 });
75 }),
76 );