appflare 0.0.28 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/cli/commands/index.ts +140 -0
  2. package/cli/generate.ts +149 -0
  3. package/cli/index.ts +56 -447
  4. package/cli/load-config.ts +182 -0
  5. package/cli/schema-compiler.ts +657 -0
  6. package/cli/templates/auth/README.md +156 -0
  7. package/cli/templates/auth/config.ts +61 -0
  8. package/cli/templates/auth/route-config.ts +18 -0
  9. package/cli/templates/auth/route-handler.ts +18 -0
  10. package/cli/templates/auth/route-request-utils.ts +55 -0
  11. package/cli/templates/auth/route.ts +14 -0
  12. package/cli/templates/core/README.md +266 -0
  13. package/cli/templates/core/app-creation.ts +19 -0
  14. package/cli/templates/core/client/appflare.ts +37 -0
  15. package/cli/templates/core/client/index.ts +6 -0
  16. package/cli/templates/core/client/storage.ts +100 -0
  17. package/cli/templates/core/client/types.ts +54 -0
  18. package/cli/templates/core/client-modules/appflare.ts +112 -0
  19. package/cli/templates/core/client-modules/handlers/index.ts +747 -0
  20. package/cli/templates/core/client-modules/handlers.ts +1 -0
  21. package/cli/templates/core/client-modules/index.ts +7 -0
  22. package/cli/templates/core/client-modules/storage.ts +180 -0
  23. package/cli/templates/core/client-modules/types.ts +145 -0
  24. package/cli/templates/core/client.ts +39 -0
  25. package/cli/templates/core/drizzle.ts +15 -0
  26. package/cli/templates/core/export.ts +14 -0
  27. package/cli/templates/core/handlers-route.ts +23 -0
  28. package/cli/templates/core/handlers.ts +1 -0
  29. package/cli/templates/core/imports.ts +8 -0
  30. package/cli/templates/core/server.ts +38 -0
  31. package/cli/templates/core/types.ts +6 -0
  32. package/cli/templates/core/wrangler.ts +109 -0
  33. package/cli/templates/handlers/README.md +353 -0
  34. package/cli/templates/handlers/auth.ts +37 -0
  35. package/cli/templates/handlers/execution.ts +39 -0
  36. package/cli/templates/handlers/generators/context/context-creation.ts +80 -0
  37. package/cli/templates/handlers/generators/context/error-helpers.ts +11 -0
  38. package/cli/templates/handlers/generators/context/scheduler.ts +24 -0
  39. package/cli/templates/handlers/generators/context/storage-api.ts +112 -0
  40. package/cli/templates/handlers/generators/context/storage-helpers.ts +59 -0
  41. package/cli/templates/handlers/generators/context/types.ts +18 -0
  42. package/cli/templates/handlers/generators/context.ts +43 -0
  43. package/cli/templates/handlers/generators/execution.ts +15 -0
  44. package/cli/templates/handlers/generators/handlers.ts +13 -0
  45. package/cli/templates/handlers/generators/registration/modules/cron.ts +30 -0
  46. package/cli/templates/handlers/generators/registration/modules/realtime.ts +631 -0
  47. package/cli/templates/handlers/generators/registration/modules/scheduler.ts +56 -0
  48. package/cli/templates/handlers/generators/registration/modules/storage.ts +194 -0
  49. package/cli/templates/handlers/generators/registration/sections.ts +210 -0
  50. package/cli/templates/handlers/generators/types/context.ts +64 -0
  51. package/cli/templates/handlers/generators/types/core.ts +101 -0
  52. package/cli/templates/handlers/generators/types/operations.ts +135 -0
  53. package/cli/templates/handlers/generators/types/query-definitions.ts +1029 -0
  54. package/cli/templates/handlers/generators/types/query-runtime.ts +417 -0
  55. package/cli/templates/handlers/index.ts +43 -0
  56. package/cli/templates/handlers/operations.ts +116 -0
  57. package/cli/templates/handlers/registration.ts +83 -0
  58. package/cli/templates/handlers/types.ts +15 -0
  59. package/cli/templates/handlers/utils.ts +48 -0
  60. package/cli/types.ts +108 -0
  61. package/cli/utils/handler-discovery.ts +366 -0
  62. package/cli/utils/json-utils.ts +24 -0
  63. package/cli/utils/path-utils.ts +19 -0
  64. package/cli/utils/schema-discovery.ts +390 -0
  65. package/index.ts +27 -4
  66. package/package.json +23 -20
  67. package/react/index.ts +5 -3
  68. package/react/use-infinite-query.ts +190 -0
  69. package/react/use-mutation.ts +54 -0
  70. package/react/use-query.ts +158 -0
  71. package/schema.ts +262 -0
  72. package/tsconfig.json +2 -4
  73. package/cli/README.md +0 -108
  74. package/cli/core/build.ts +0 -187
  75. package/cli/core/config.ts +0 -92
  76. package/cli/core/discover-handlers.ts +0 -143
  77. package/cli/core/handlers.ts +0 -7
  78. package/cli/core/index.ts +0 -205
  79. package/cli/generators/generate-api-client/client.ts +0 -163
  80. package/cli/generators/generate-api-client/extract-configuration.ts +0 -121
  81. package/cli/generators/generate-api-client/index.ts +0 -973
  82. package/cli/generators/generate-api-client/types.ts +0 -164
  83. package/cli/generators/generate-api-client/utils.ts +0 -22
  84. package/cli/generators/generate-api-client.ts +0 -1
  85. package/cli/generators/generate-cloudflare-worker/helpers.ts +0 -24
  86. package/cli/generators/generate-cloudflare-worker/index.ts +0 -2
  87. package/cli/generators/generate-cloudflare-worker/worker.ts +0 -148
  88. package/cli/generators/generate-cloudflare-worker/wrangler.ts +0 -108
  89. package/cli/generators/generate-cloudflare-worker.ts +0 -4
  90. package/cli/generators/generate-cron-handlers/cron-handlers-block.ts +0 -2
  91. package/cli/generators/generate-cron-handlers/handler-entries.ts +0 -29
  92. package/cli/generators/generate-cron-handlers/index.ts +0 -61
  93. package/cli/generators/generate-cron-handlers/runtime-block.ts +0 -49
  94. package/cli/generators/generate-cron-handlers/type-helpers-block.ts +0 -60
  95. package/cli/generators/generate-db-handlers/index.ts +0 -33
  96. package/cli/generators/generate-db-handlers/prepare.ts +0 -24
  97. package/cli/generators/generate-db-handlers/templates.ts +0 -189
  98. package/cli/generators/generate-db-handlers.ts +0 -1
  99. package/cli/generators/generate-hono-server/auth.ts +0 -97
  100. package/cli/generators/generate-hono-server/imports.ts +0 -55
  101. package/cli/generators/generate-hono-server/index.ts +0 -52
  102. package/cli/generators/generate-hono-server/routes.ts +0 -115
  103. package/cli/generators/generate-hono-server/template.ts +0 -371
  104. package/cli/generators/generate-hono-server.ts +0 -1
  105. package/cli/generators/generate-scheduler-handlers/constants.ts +0 -8
  106. package/cli/generators/generate-scheduler-handlers/handler-entries.ts +0 -22
  107. package/cli/generators/generate-scheduler-handlers/index.ts +0 -51
  108. package/cli/generators/generate-scheduler-handlers/runtime-block.ts +0 -68
  109. package/cli/generators/generate-scheduler-handlers/scheduler-handlers-block.ts +0 -2
  110. package/cli/generators/generate-scheduler-handlers/type-helpers-block.ts +0 -68
  111. package/cli/generators/generate-scheduler-handlers.ts +0 -1
  112. package/cli/generators/generate-websocket-durable-object/auth.ts +0 -30
  113. package/cli/generators/generate-websocket-durable-object/imports.ts +0 -55
  114. package/cli/generators/generate-websocket-durable-object/index.ts +0 -41
  115. package/cli/generators/generate-websocket-durable-object/query-handlers.ts +0 -18
  116. package/cli/generators/generate-websocket-durable-object/template.ts +0 -714
  117. package/cli/generators/generate-websocket-durable-object.ts +0 -1
  118. package/cli/schema/schema-static-types.ts +0 -702
  119. package/cli/schema/schema.ts +0 -151
  120. package/cli/utils/tsc.ts +0 -54
  121. package/cli/utils/utils.ts +0 -190
  122. package/cli/utils/zod-utils.ts +0 -121
  123. package/lib/README.md +0 -50
  124. package/lib/db.ts +0 -19
  125. package/lib/location.ts +0 -110
  126. package/lib/values.ts +0 -27
  127. package/react/README.md +0 -67
  128. package/react/hooks/useMutation.ts +0 -89
  129. package/react/hooks/usePaginatedQuery.ts +0 -213
  130. package/react/hooks/useQuery.ts +0 -106
  131. package/react/shared/queryShared.ts +0 -174
  132. package/server/README.md +0 -218
  133. package/server/auth.ts +0 -107
  134. package/server/database/builders.ts +0 -83
  135. package/server/database/context.ts +0 -327
  136. package/server/database/populate.ts +0 -234
  137. package/server/database/query-builder.ts +0 -161
  138. package/server/database/query-utils.ts +0 -25
  139. package/server/db.ts +0 -2
  140. package/server/storage/auth.ts +0 -16
  141. package/server/storage/bucket.ts +0 -22
  142. package/server/storage/context.ts +0 -34
  143. package/server/storage/index.ts +0 -38
  144. package/server/storage/operations.ts +0 -149
  145. package/server/storage/route-handler.ts +0 -60
  146. package/server/storage/types.ts +0 -55
  147. package/server/storage/utils.ts +0 -47
  148. package/server/storage.ts +0 -6
  149. package/server/types/schema-refs.ts +0 -66
  150. package/server/types/types.ts +0 -633
  151. package/server/utils/id-utils.ts +0 -230
@@ -0,0 +1,631 @@
1
+ export const realtimeModule = `
2
+ type RealtimeSubscription = {
3
+ token: string;
4
+ signature: string;
5
+ queryName: string;
6
+ args: Record<string, unknown>;
7
+ authToken: string;
8
+ userId: string;
9
+ createdAt: number;
10
+ };
11
+
12
+ type RealtimeEmitPayload = {
13
+ token: string;
14
+ event: string;
15
+ payload: unknown;
16
+ };
17
+
18
+ type RealtimeStub = {
19
+ fetch: (request: Request) => Promise<Response>;
20
+ };
21
+
22
+ type RealtimeDurableObjectNamespace = {
23
+ idFromName: (name: string) => unknown;
24
+ get: (id: unknown) => RealtimeStub;
25
+ };
26
+
27
+ type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
28
+ ? string
29
+ : Extract<keyof typeof realtimeQueryHandlers, string>;
30
+
31
+ function isRecord(value: unknown): value is Record<string, unknown> {
32
+ return typeof value === "object" && value !== null;
33
+ }
34
+
35
+ function stableStringify(value: unknown): string {
36
+ if (Array.isArray(value)) {
37
+ return "[" + value.map((entry) => stableStringify(entry)).join(",") + "]";
38
+ }
39
+
40
+ if (value instanceof Date) {
41
+ return JSON.stringify(value.toISOString());
42
+ }
43
+
44
+ if (isRecord(value)) {
45
+ const keys = Object.keys(value).sort((a, b) => a.localeCompare(b));
46
+ return (
47
+ "{" +
48
+ keys
49
+ .map((key) => JSON.stringify(key) + ":" + stableStringify(value[key]))
50
+ .join(",") +
51
+ "}"
52
+ );
53
+ }
54
+
55
+ return JSON.stringify(value ?? null);
56
+ }
57
+
58
+ function normalizeComparableValue(value: unknown): unknown {
59
+ if (Array.isArray(value)) {
60
+ return value.map((entry) => normalizeComparableValue(entry));
61
+ }
62
+
63
+ if (value instanceof Date) {
64
+ return value.toISOString();
65
+ }
66
+
67
+ if (isRecord(value)) {
68
+ return Object.entries(value)
69
+ .sort(([a], [b]) => a.localeCompare(b))
70
+ .reduce<Record<string, unknown>>((accumulator, [key, entry]) => {
71
+ accumulator[key] = normalizeComparableValue(entry);
72
+ return accumulator;
73
+ }, {});
74
+ }
75
+
76
+ return value;
77
+ }
78
+
79
+ function createSubscriptionSignature(
80
+ queryName: string,
81
+ args: Record<string, unknown>,
82
+ ): string {
83
+ const normalizedArgs = normalizeComparableValue(args);
84
+ return queryName + "::" + stableStringify(normalizedArgs);
85
+ }
86
+
87
+ function normalizeSubscriptionFilter(args: Record<string, unknown>): unknown {
88
+ const where = args.where;
89
+ if (isRecord(where)) {
90
+ return where;
91
+ }
92
+
93
+ return args;
94
+ }
95
+
96
+ function hasPartialOverlap(left: unknown, right: unknown): boolean {
97
+ if (left === null || left === undefined || right === null || right === undefined) {
98
+ return false;
99
+ }
100
+
101
+ if (Array.isArray(left) && Array.isArray(right)) {
102
+ return left.some((leftValue) => {
103
+ return right.some((rightValue) => hasPartialOverlap(leftValue, rightValue));
104
+ });
105
+ }
106
+
107
+ if (Array.isArray(left)) {
108
+ return left.some((leftValue) => hasPartialOverlap(leftValue, right));
109
+ }
110
+
111
+ if (Array.isArray(right)) {
112
+ return right.some((rightValue) => hasPartialOverlap(left, rightValue));
113
+ }
114
+
115
+ if (isRecord(left) && isRecord(right)) {
116
+ const keys = Object.keys(left);
117
+ for (const key of keys) {
118
+ if (!(key in right)) {
119
+ continue;
120
+ }
121
+
122
+ if (hasPartialOverlap(left[key], right[key])) {
123
+ return true;
124
+ }
125
+ }
126
+
127
+ return false;
128
+ }
129
+
130
+ return left === right;
131
+ }
132
+
133
+ function doesSubscriptionMatchMutation(
134
+ subscriptionArgs: Record<string, unknown>,
135
+ event: DbMutationEvent,
136
+ ): boolean {
137
+ const filter = normalizeSubscriptionFilter(subscriptionArgs);
138
+ if (!filter) {
139
+ return true;
140
+ }
141
+
142
+ if (hasPartialOverlap(filter, event.args)) {
143
+ return true;
144
+ }
145
+
146
+ return event.rows.some((row) => hasPartialOverlap(filter, row));
147
+ }
148
+
149
+ function getRealtimeStub(
150
+ env: Record<string, unknown>,
151
+ options: RegisterHandlersOptions,
152
+ ): RealtimeStub | null {
153
+ const binding = options.realtimeBinding ?? "APPFLARE_REALTIME";
154
+ const namespace = env[binding] as RealtimeDurableObjectNamespace | undefined;
155
+ if (!namespace) {
156
+ return null;
157
+ }
158
+
159
+ const objectName = options.realtimeObjectName ?? "global";
160
+ const objectId = namespace.idFromName(objectName);
161
+ return namespace.get(objectId);
162
+ }
163
+
164
+ async function validateAuthToken(
165
+ request: Request,
166
+ env: Record<string, unknown>,
167
+ options: RegisterHandlersOptions,
168
+ authToken: string,
169
+ ): Promise<{ user: unknown; session: unknown } | null> {
170
+ const database = env[options.databaseBinding] as D1Database | undefined;
171
+ if (!database) {
172
+ return null;
173
+ }
174
+
175
+ const kvNamespace = options.kvBinding
176
+ ? (env[options.kvBinding] as KVNamespace | undefined)
177
+ : undefined;
178
+ const headers = new Headers(request.headers);
179
+ headers.set("authorization", "Bearer " + authToken);
180
+ headers.delete("upgrade");
181
+ headers.delete("connection");
182
+ for (const key of [...headers.keys()]) {
183
+ if (key.toLowerCase().startsWith("sec-websocket")) {
184
+ headers.delete(key);
185
+ }
186
+ }
187
+ const tokenRequest = new Request(request.url, {
188
+ method: "GET",
189
+ headers,
190
+ });
191
+
192
+ const session = await resolveSession(
193
+ tokenRequest,
194
+ database,
195
+ kvNamespace,
196
+ request.cf as IncomingRequestCfProperties | undefined,
197
+ );
198
+
199
+ if (!session?.user) {
200
+ return null;
201
+ }
202
+
203
+ return session;
204
+ }
205
+
206
+ function extractUserId(user: unknown): string {
207
+ if (!isRecord(user)) {
208
+ return "unknown";
209
+ }
210
+
211
+ const id = user.id;
212
+ return typeof id === "string" && id.length > 0 ? id : "unknown";
213
+ }
214
+
215
+ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
216
+ const url = new URL(requestUrl);
217
+ url.pathname = websocketPath;
218
+ url.search = "";
219
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
220
+ return url.toString();
221
+ }
222
+
223
+ async function publishMutationEvents(
224
+ c: { req: { raw: Request }; env: Record<string, unknown> },
225
+ options: RegisterHandlersOptions,
226
+ mutationEvents: DbMutationEvent[],
227
+ ): Promise<void> {
228
+ if (mutationEvents.length === 0) {
229
+ return;
230
+ }
231
+
232
+ const stub = getRealtimeStub(c.env, options);
233
+ if (!stub) {
234
+ return;
235
+ }
236
+
237
+ const subscriptionsResponse = await stub.fetch(
238
+ new Request("https://realtime.internal/subscriptions", {
239
+ method: "POST",
240
+ headers: {
241
+ "content-type": "application/json",
242
+ },
243
+ }),
244
+ );
245
+ if (!subscriptionsResponse.ok) {
246
+ return;
247
+ }
248
+
249
+ const payload = (await subscriptionsResponse.json()) as {
250
+ subscriptions?: RealtimeSubscription[];
251
+ };
252
+ const subscriptions = Array.isArray(payload.subscriptions)
253
+ ? payload.subscriptions
254
+ : [];
255
+
256
+ for (const subscription of subscriptions) {
257
+ const operation = (realtimeQueryHandlers as Record<
258
+ string,
259
+ {
260
+ definition: {
261
+ handler: (ctx: AppflareContext, args: unknown) => Promise<unknown> | unknown;
262
+ };
263
+ schema: z.ZodTypeAny;
264
+ }
265
+ >)[subscription.queryName];
266
+ if (!operation) {
267
+ continue;
268
+ }
269
+
270
+ const shouldPublish = mutationEvents.some((event) => {
271
+ return doesSubscriptionMatchMutation(subscription.args, event);
272
+ });
273
+ if (!shouldPublish) {
274
+ continue;
275
+ }
276
+
277
+ const authSession = await validateAuthToken(
278
+ c.req.raw,
279
+ c.env,
280
+ options,
281
+ subscription.authToken,
282
+ );
283
+ if (!authSession) {
284
+ continue;
285
+ }
286
+
287
+ const subscriberCtx = await createExecutionContext(c as never, options);
288
+ subscriberCtx.user = authSession.user as never;
289
+ subscriberCtx.session = authSession.session as never;
290
+
291
+ try {
292
+ const parsedArgs = operation.schema.parse(subscription.args);
293
+ const result = await operation.definition.handler(subscriberCtx, parsedArgs);
294
+ const emitPayload: RealtimeEmitPayload = {
295
+ token: subscription.token,
296
+ event: "query:update",
297
+ payload: {
298
+ queryName: subscription.queryName,
299
+ signature: subscription.signature,
300
+ data: result,
301
+ },
302
+ };
303
+
304
+ await stub.fetch(
305
+ new Request("https://realtime.internal/emit", {
306
+ method: "POST",
307
+ headers: {
308
+ "content-type": "application/json",
309
+ },
310
+ body: JSON.stringify(emitPayload),
311
+ }),
312
+ );
313
+ } catch (error) {
314
+ console.warn("Failed to publish realtime update", subscription.queryName, error);
315
+ }
316
+ }
317
+ }
318
+
319
+ function registerRealtimeRoutes(
320
+ app: Hono<WorkerEnv>,
321
+ options: RegisterHandlersOptions,
322
+ ): void {
323
+ const subscribePath = options.realtimeSubscribePath ?? "/realtime/subscribe";
324
+ const unsubscribePath = "/realtime/unsubscribe";
325
+ const websocketPath = options.realtimeWebsocketPath ?? "/realtime/ws";
326
+ const protocol = options.realtimeProtocol ?? "appflare.realtime.v1";
327
+
328
+ app.post(subscribePath, async (c) => {
329
+ const body = await c.req.json().catch(() => ({} as Record<string, unknown>));
330
+ const queryName = typeof body.queryName === "string" ? body.queryName : "";
331
+ const authToken = typeof body.authToken === "string" ? body.authToken : "";
332
+ const rawArgs = isRecord(body.args) ? body.args : {};
333
+
334
+ if (!queryName || !authToken) {
335
+ return c.json({ message: "queryName and authToken are required" }, 400);
336
+ }
337
+
338
+ const operation = (realtimeQueryHandlers as Record<
339
+ string,
340
+ {
341
+ definition: unknown;
342
+ schema: z.ZodTypeAny;
343
+ }
344
+ >)[queryName as RealtimeQueryName];
345
+ if (!operation) {
346
+ return c.json({ message: "Unknown queryName" }, 404);
347
+ }
348
+
349
+ const authSession = await validateAuthToken(
350
+ c.req.raw,
351
+ c.env,
352
+ options,
353
+ authToken,
354
+ );
355
+ if (!authSession) {
356
+ return c.json({ message: "Invalid auth token" }, 401);
357
+ }
358
+
359
+ let args: Record<string, unknown>;
360
+ try {
361
+ args = operation.schema.parse(rawArgs) as Record<string, unknown>;
362
+ } catch (error) {
363
+ if (error instanceof ZodError) {
364
+ return c.json({ message: "Invalid query args", issues: error.issues }, 400);
365
+ }
366
+ return c.json({ message: "Invalid query args" }, 400);
367
+ }
368
+
369
+ const token = crypto.randomUUID();
370
+ const signature = createSubscriptionSignature(queryName, args);
371
+ const stub = getRealtimeStub(c.env, options);
372
+ if (!stub) {
373
+ return c.json({ message: "Realtime binding is not configured" }, 500);
374
+ }
375
+
376
+ await stub.fetch(
377
+ new Request("https://realtime.internal/subscribe", {
378
+ method: "POST",
379
+ headers: {
380
+ "content-type": "application/json",
381
+ },
382
+ body: JSON.stringify({
383
+ token,
384
+ signature,
385
+ queryName,
386
+ args,
387
+ authToken,
388
+ userId: extractUserId(authSession.user),
389
+ createdAt: Date.now(),
390
+ }),
391
+ }),
392
+ );
393
+
394
+ const websocketUrl = buildRealtimeWsUrl(c.req.raw.url, websocketPath);
395
+ return c.json(
396
+ {
397
+ token,
398
+ signature,
399
+ websocket: {
400
+ url: websocketUrl,
401
+ protocol,
402
+ params: {
403
+ tokenParam: "token",
404
+ authTokenParam: "authToken",
405
+ },
406
+ },
407
+ },
408
+ 200,
409
+ );
410
+ });
411
+
412
+ app.post(unsubscribePath, async (c) => {
413
+ const body = await c.req.json().catch(() => ({} as Record<string, unknown>));
414
+ const token = typeof body.token === "string" ? body.token : "";
415
+ const authToken = typeof body.authToken === "string" ? body.authToken : "";
416
+
417
+ if (!token || !authToken) {
418
+ return c.json({ message: "token and authToken are required" }, 400);
419
+ }
420
+
421
+ const authSession = await validateAuthToken(
422
+ c.req.raw,
423
+ c.env,
424
+ options,
425
+ authToken,
426
+ );
427
+ if (!authSession) {
428
+ return c.json({ message: "Invalid auth token" }, 401);
429
+ }
430
+
431
+ const stub = getRealtimeStub(c.env, options);
432
+ if (!stub) {
433
+ return c.json({ message: "Realtime binding is not configured" }, 500);
434
+ }
435
+
436
+ const response = await stub.fetch(
437
+ new Request("https://realtime.internal/unsubscribe", {
438
+ method: "POST",
439
+ headers: {
440
+ "content-type": "application/json",
441
+ },
442
+ body: JSON.stringify({
443
+ token,
444
+ authToken,
445
+ }),
446
+ }),
447
+ );
448
+
449
+ if (!response.ok) {
450
+ const payload = (await response.json().catch(() => null)) as {
451
+ message?: string;
452
+ } | null;
453
+ return c.json(
454
+ { message: payload?.message ?? "Unable to remove subscription" },
455
+ response.status,
456
+ );
457
+ }
458
+
459
+ return c.json({ ok: true }, 200);
460
+ });
461
+
462
+ app.get(websocketPath, async (c) => {
463
+ const token = c.req.query("token") ?? "";
464
+ const authToken = c.req.query("authToken") ?? "";
465
+
466
+ if (!token || !authToken) {
467
+ return c.json({ message: "token and authToken are required" }, 400);
468
+ }
469
+
470
+ const authSession = await validateAuthToken(
471
+ c.req.raw,
472
+ c.env,
473
+ options,
474
+ authToken,
475
+ );
476
+ if (!authSession) {
477
+ return c.json({ message: "Invalid auth token" }, 401);
478
+ }
479
+
480
+ const stub = getRealtimeStub(c.env, options);
481
+ if (!stub) {
482
+ return c.json({ message: "Realtime binding is not configured" }, 500);
483
+ }
484
+
485
+ return stub.fetch(c.req.raw);
486
+ });
487
+ }
488
+
489
+ export class AppflareRealtimeDurableObject {
490
+ private readonly subscriptions = new Map<string, RealtimeSubscription>();
491
+ private readonly sockets = new Map<string, WebSocket>();
492
+
493
+ public constructor(_state: unknown) {}
494
+
495
+ public async fetch(request: Request): Promise<Response> {
496
+ const url = new URL(request.url);
497
+
498
+ if (request.method === "POST" && url.pathname === "/subscribe") {
499
+ const payload = (await request.json().catch(() => null)) as RealtimeSubscription | null;
500
+ if (!payload?.token || !payload.queryName || !payload.authToken) {
501
+ return new Response(JSON.stringify({ message: "Invalid subscription payload" }), {
502
+ status: 400,
503
+ headers: { "content-type": "application/json" },
504
+ });
505
+ }
506
+
507
+ this.subscriptions.set(payload.token, payload);
508
+ return new Response(JSON.stringify({ ok: true }), {
509
+ status: 200,
510
+ headers: { "content-type": "application/json" },
511
+ });
512
+ }
513
+
514
+ if (request.method === "POST" && url.pathname === "/subscriptions") {
515
+ return new Response(
516
+ JSON.stringify({ subscriptions: Array.from(this.subscriptions.values()) }),
517
+ {
518
+ status: 200,
519
+ headers: { "content-type": "application/json" },
520
+ },
521
+ );
522
+ }
523
+
524
+ if (request.method === "POST" && url.pathname === "/unsubscribe") {
525
+ const payload = (await request.json().catch(() => null)) as {
526
+ token?: unknown;
527
+ authToken?: unknown;
528
+ } | null;
529
+ const token = typeof payload?.token === "string" ? payload.token : "";
530
+ const authToken =
531
+ typeof payload?.authToken === "string" ? payload.authToken : "";
532
+
533
+ if (!token || !authToken) {
534
+ return new Response(
535
+ JSON.stringify({ message: "token and authToken are required" }),
536
+ {
537
+ status: 400,
538
+ headers: { "content-type": "application/json" },
539
+ },
540
+ );
541
+ }
542
+
543
+ const existing = this.subscriptions.get(token);
544
+ if (!existing || existing.authToken !== authToken) {
545
+ return new Response(JSON.stringify({ message: "Subscription not found" }), {
546
+ status: 404,
547
+ headers: { "content-type": "application/json" },
548
+ });
549
+ }
550
+
551
+ const socket = this.sockets.get(token);
552
+ if (socket && socket.readyState === 1) {
553
+ socket.close();
554
+ }
555
+
556
+ this.sockets.delete(token);
557
+ this.subscriptions.delete(token);
558
+
559
+ return new Response(JSON.stringify({ ok: true }), {
560
+ status: 200,
561
+ headers: { "content-type": "application/json" },
562
+ });
563
+ }
564
+
565
+ if (request.method === "POST" && url.pathname === "/emit") {
566
+ const payload = (await request.json().catch(() => null)) as RealtimeEmitPayload | null;
567
+ if (!payload?.token || !payload.event) {
568
+ return new Response(JSON.stringify({ message: "Invalid emit payload" }), {
569
+ status: 400,
570
+ headers: { "content-type": "application/json" },
571
+ });
572
+ }
573
+
574
+ const socket = this.sockets.get(payload.token);
575
+ if (socket && socket.readyState === 1) {
576
+ socket.send(
577
+ JSON.stringify({
578
+ event: payload.event,
579
+ payload: payload.payload,
580
+ }),
581
+ );
582
+ }
583
+
584
+ return new Response(JSON.stringify({ ok: true }), {
585
+ status: 200,
586
+ headers: { "content-type": "application/json" },
587
+ });
588
+ }
589
+
590
+ if (request.method === "GET" && (url.pathname === "/ws" || url.pathname.endsWith("/ws"))) {
591
+ const token = url.searchParams.get("token") ?? "";
592
+ const authToken = url.searchParams.get("authToken") ?? "";
593
+ const subscription = this.subscriptions.get(token);
594
+ if (!subscription || !authToken || subscription.authToken !== authToken) {
595
+ return new Response("Unauthorized", { status: 401 });
596
+ }
597
+
598
+ const pair = new WebSocketPair();
599
+ const [clientSocket, serverSocket] = Object.values(pair);
600
+ serverSocket.accept();
601
+ this.sockets.set(token, serverSocket);
602
+
603
+ const release = () => {
604
+ this.sockets.delete(token);
605
+ };
606
+
607
+ serverSocket.addEventListener("close", release);
608
+ serverSocket.addEventListener("error", release);
609
+ serverSocket.addEventListener("message", (event) => {
610
+ if (String(event.data ?? "").trim() === "ping") {
611
+ serverSocket.send(JSON.stringify({ event: "pong" }));
612
+ }
613
+ });
614
+
615
+ const requestedProtocol = request.headers.get("Sec-WebSocket-Protocol");
616
+ const headers = new Headers();
617
+ if (requestedProtocol) {
618
+ headers.set("Sec-WebSocket-Protocol", requestedProtocol);
619
+ }
620
+
621
+ return new Response(null, {
622
+ status: 101,
623
+ webSocket: clientSocket,
624
+ headers,
625
+ } as ResponseInit & { webSocket: WebSocket });
626
+ }
627
+
628
+ return new Response("Not found", { status: 404 });
629
+ }
630
+ }
631
+ `;
@@ -0,0 +1,56 @@
1
+ export const schedulerModule = `
2
+ type SchedulerTaskName = keyof typeof schedulerHandlers extends never
3
+ ? string
4
+ : keyof typeof schedulerHandlers;
5
+
6
+ type QueueMessageBody = {
7
+ task?: string;
8
+ payload?: unknown;
9
+ };
10
+
11
+ export async function executeScheduledBatch(
12
+ batch: { messages?: Array<{ body?: unknown }> },
13
+ env: Record<string, unknown>,
14
+ options: RegisterHandlersOptions,
15
+ ): Promise<void> {
16
+ if (!batch?.messages || batch.messages.length === 0) {
17
+ return;
18
+ }
19
+
20
+ const ctx = createSchedulerExecutionContext(env, options);
21
+
22
+ for (const message of batch.messages) {
23
+ const body = (message?.body ?? {}) as QueueMessageBody;
24
+ const task = body.task;
25
+ if (!task) {
26
+ console.warn("Scheduler message missing task field");
27
+ continue;
28
+ }
29
+
30
+ const operation = (schedulerHandlers as Record<string, {
31
+ definition: {
32
+ handler: (ctx: typeof ctx, args: unknown) => Promise<void> | void;
33
+ };
34
+ schema: z.ZodTypeAny;
35
+ }>)[task];
36
+
37
+ if (!operation) {
38
+ console.warn("Unknown scheduler task", task);
39
+ continue;
40
+ }
41
+
42
+ try {
43
+ const payloadValue = body.payload === null ? undefined : body.payload;
44
+ const parsed = operation.schema.parse(payloadValue);
45
+ await operation.definition.handler(ctx, parsed);
46
+ } catch (error) {
47
+ if (error instanceof ZodError) {
48
+ console.error("Invalid scheduler payload", task, error.issues);
49
+ continue;
50
+ }
51
+
52
+ console.error("Scheduler task failed", task, error);
53
+ }
54
+ }
55
+ }
56
+ `;