@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, 06:00 UTC

main
ts 179 lines 5.89 KB
Raw
1 import * as AppSync from "@alchemy.run/aws/AppSync";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Result from "effect/Result";
9 import * as Stream from "effect/Stream";
10 import path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "bindings-handler.ts");
13
14 const SCHEMA = `
15 type Query {
16 add(a: Int!, b: Int!): Int!
17 greeting: String
18 }
19 schema { query: Query }
20 `;
21
22 /** NONE data source: compute the sum locally in the resolver. */
23 const ADD_RESOLVER = `
24 export function request(ctx) {
25 return { payload: ctx.args.a + ctx.args.b };
26 }
27 export function response(ctx) {
28 return ctx.result;
29 }
30 `;
31
32 /** Reads the API's environment variables (ctx.env) at resolve time. */
33 const GREETING_RESOLVER = `
34 export function request(ctx) {
35 return { payload: null };
36 }
37 export function response(ctx) {
38 return ctx.env.GREETING;
39 }
40 `;
41
42 export class AppSyncBindingsFunction extends Lambda.Function<Lambda.Function>()(
43 "AppSyncBindingsFunction",
44 ) {}
45
46 export default AppSyncBindingsFunction.make(
47 {
48 main,
49 functionUrl: true,
50 // The GraphQL round-trip fans out a signed HTTP call; AWS's 3s default
51 // intermittently times out on a cold start.
52 timeout: Duration.seconds(30),
53 },
54 Effect.gen(function* () {
55 const api = yield* AppSync.GraphqlApi("BindingsApi", {
56 authenticationType: "AWS_IAM",
57 schema: SCHEMA,
58 environmentVariables: { GREETING: "hello from ctx.env" },
59 });
60 const local = yield* AppSync.DataSource("LocalDS", {
61 api,
62 type: "NONE",
63 });
64 yield* AppSync.Resolver("AddResolver", {
65 api,
66 typeName: "Query",
67 fieldName: "add",
68 dataSource: local,
69 code: ADD_RESOLVER,
70 });
71 yield* AppSync.Resolver("GreetingResolver", {
72 api,
73 typeName: "Query",
74 fieldName: "greeting",
75 dataSource: local,
76 code: GREETING_RESOLVER,
77 });
78
79 const graphql = yield* AppSync.GraphQL(api);
80 const flushCache = yield* AppSync.FlushApiCache(api);
81 const getSchema = yield* AppSync.GetIntrospectionSchema(api);
82 const evaluateCode = yield* AppSync.EvaluateCode();
83 const evaluateTemplate = yield* AppSync.EvaluateMappingTemplate();
84
85 return {
86 fetch: Effect.gen(function* () {
87 const request = yield* HttpServerRequest;
88 const pathname = new URL(request.originalUrl).pathname;
89
90 if (request.method === "POST" && pathname === "/graphql") {
91 const body = (yield* request.json) as unknown as {
92 query: string;
93 variables?: Record<string, unknown>;
94 };
95 const result = yield* graphql.execute({
96 query: body.query,
97 variables: body.variables,
98 });
99 return yield* HttpServerResponse.json(result);
100 }
101
102 if (request.method === "POST" && pathname === "/flush") {
103 // Surface the typed outcome tag to the test — the API has no
104 // cache provisioned, so the expected result is the typed
105 // NotFoundException (which proves the call executed with the
106 // granted appsync:FlushApiCache).
107 const outcome = yield* Effect.result(flushCache());
108 return yield* HttpServerResponse.json(
109 Result.isSuccess(outcome)
110 ? { flushed: true }
111 : {
112 flushed: false,
113 reason: outcome.failure._tag,
114 message: String((outcome.failure as { message?: string }).message ?? ""),
115 },
116 );
117 }
118
119 if (request.method === "GET" && pathname === "/schema") {
120 // The introspected schema arrives as a streaming body.
121 const response = yield* getSchema({ format: "SDL" });
122 const sdl = yield* Stream.mkString(Stream.decodeText(response.schema!));
123 return yield* HttpServerResponse.json({ sdl });
124 }
125
126 if (request.method === "POST" && pathname === "/evaluate") {
127 // Evaluate the add resolver's request function against a mock
128 // context — evaluation errors surface on `result.error`.
129 const result = yield* evaluateCode({
130 runtime: AppSync.APPSYNC_JS,
131 code: ADD_RESOLVER,
132 context: JSON.stringify({ arguments: { a: 2, b: 3 } }),
133 function: "request",
134 });
135 return yield* HttpServerResponse.json({
136 evaluationResult: result.evaluationResult,
137 error: result.error,
138 });
139 }
140
141 if (request.method === "POST" && pathname === "/evaluate-template") {
142 // Render a VTL template against a mock context — template
143 // evaluation errors surface on `result.error`.
144 const result = yield* evaluateTemplate({
145 // VTL only allows arithmetic inside #set directives.
146 template: [
147 `#set($sum = $ctx.args.a + $ctx.args.b)`,
148 `{ "sum": $util.toJson($sum) }`,
149 ].join("\n"),
150 context: JSON.stringify({ arguments: { a: 2, b: 3 } }),
151 });
152 return yield* HttpServerResponse.json({
153 evaluationResult: result.evaluationResult,
154 error: result.error,
155 });
156 }
157
158 if (request.method === "GET" && pathname === "/ping") {
159 return yield* HttpServerResponse.json({ ok: true });
160 }
161
162 return yield* HttpServerResponse.json(
163 { error: "Not found", method: request.method, pathname },
164 { status: 404 },
165 );
166 }).pipe(Effect.orDie),
167 };
168 }).pipe(
169 Effect.provide(
170 Layer.mergeAll(
171 AppSync.GraphQLHttp,
172 AppSync.FlushApiCacheHttp,
173 AppSync.GetIntrospectionSchemaHttp,
174 AppSync.EvaluateCodeHttp,
175 AppSync.EvaluateMappingTemplateHttp,
176 ),
177 ),
178 ),
179 );