@supacloud/elysia 0.38.0 → 0.38.2

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.
@@ -0,0 +1,3252 @@
1
+ // src/index.ts
2
+ import { Elysia as Elysia3, setupTypebox, Validator as Validator2 } from "elysia";
3
+ import { requireFeatureRequestContext } from "@supacloud/app";
4
+ import { PendingWorkRegistry as PendingWorkRegistry2, PendingWorkTimeoutError, PendingWorkCapacityError } from "@supacloud/app/runtime";
5
+ import { commandFailureMetadata as commandFailureMetadata3, decodeCommandPreview } from "@supacloud/contracts";
6
+
7
+ // src/command-errors.ts
8
+ function commandErrorCode(error) {
9
+ if (!(error instanceof Error) || error.name !== "CommandError" || !("code" in error))
10
+ return;
11
+ switch (error.code) {
12
+ case "COMMAND_INPUT_INVALID":
13
+ case "COMMAND_REJECTED":
14
+ case "COMMAND_IDEMPOTENCY_CONFLICT":
15
+ case "COMMAND_INPUT_EXPIRED":
16
+ case "COMMAND_UNAVAILABLE":
17
+ case "COMMAND_RECEIPT_INVALID":
18
+ case "COMMAND_OUTCOME_UNKNOWN":
19
+ return error.code;
20
+ default:
21
+ return;
22
+ }
23
+ }
24
+ function commandErrorStatus(code) {
25
+ switch (code) {
26
+ case "COMMAND_INPUT_INVALID":
27
+ return 400;
28
+ case "COMMAND_REJECTED":
29
+ return 403;
30
+ case "COMMAND_IDEMPOTENCY_CONFLICT":
31
+ return 409;
32
+ case "COMMAND_INPUT_EXPIRED":
33
+ return 410;
34
+ case "COMMAND_UNAVAILABLE":
35
+ case "COMMAND_RECEIPT_INVALID":
36
+ case "COMMAND_OUTCOME_UNKNOWN":
37
+ return 503;
38
+ }
39
+ }
40
+
41
+ // src/http-policy.ts
42
+ class HttpPolicyConfigurationError extends Error {
43
+ code = "HTTP_POLICY_CONFIGURATION_INVALID";
44
+ }
45
+ function compileHttpPolicies(route, path, registry = {}) {
46
+ const declarations = route.data?.httpPolicies;
47
+ if (declarations === undefined)
48
+ return [];
49
+ const fail = () => {
50
+ throw new HttpPolicyConfigurationError(`Invalid HTTP policy configuration for ${route.method} ${path}`);
51
+ };
52
+ if (!Array.isArray(declarations))
53
+ return fail();
54
+ return Array.from(declarations, (value, index) => {
55
+ if (!value || typeof value !== "object" || Array.isArray(value))
56
+ return fail();
57
+ const declaration = value;
58
+ if (typeof declaration.name !== "string" || Object.keys(declaration).some((key) => key !== "name" && key !== "options") || !Object.hasOwn(registry, declaration.name))
59
+ return fail();
60
+ const factory = registry[declaration.name];
61
+ if (typeof factory !== "function")
62
+ return fail();
63
+ const policy = factory(declaration.options, Object.freeze({
64
+ method: route.method,
65
+ path,
66
+ ...route.command === undefined ? {} : { command: route.command }
67
+ }));
68
+ if (typeof policy !== "function")
69
+ return fail();
70
+ if (policy.terminal && index !== declarations.length - 1)
71
+ return fail();
72
+ if (policy.afterResponse !== undefined && typeof policy.afterResponse !== "function")
73
+ return fail();
74
+ if (policy.mapResponse !== undefined && typeof policy.mapResponse !== "function")
75
+ return fail();
76
+ return policy;
77
+ });
78
+ }
79
+
80
+ // src/http-telemetry.ts
81
+ import { Elysia, StatusMap } from "elysia";
82
+ var requestIds = new WeakMap;
83
+ function httpRequestId(request) {
84
+ return requestIds.get(request);
85
+ }
86
+ function createHttpTelemetry(observe) {
87
+ const starts = new WeakMap;
88
+ return new Elysia().onRequest(({ request, set }) => {
89
+ const supplied = request.headers.get("x-request-id");
90
+ const requestId = supplied && /^[A-Za-z0-9._:-]{1,128}$/.test(supplied) ? supplied : crypto.randomUUID();
91
+ starts.set(request, { time: performance.now(), requestId });
92
+ requestIds.set(request, requestId);
93
+ set.headers["x-request-id"] = requestId;
94
+ }).onError(() => {
95
+ return;
96
+ }).onAfterResponse(async ({ request, responseValue: response, set, route }) => {
97
+ const start = starts.get(request);
98
+ if (!start)
99
+ return;
100
+ starts.delete(request);
101
+ const status = response instanceof Response ? response.status : typeof set.status === "number" ? set.status : StatusMap[set.status ?? "OK"];
102
+ try {
103
+ await observe(Object.freeze({
104
+ requestId: start.requestId,
105
+ method: request.method,
106
+ route: route ?? "<unmatched>",
107
+ status,
108
+ durationMs: performance.now() - start.time
109
+ }));
110
+ } catch {}
111
+ }).as("global");
112
+ }
113
+ // src/identity.ts
114
+ import { createRemoteJWKSet, jwtVerify, errors } from "jose";
115
+ function httpsUrl(value) {
116
+ const url = new URL(value);
117
+ if (url.protocol !== "https:" || url.username || url.password || url.hash) {
118
+ throw new TypeError("Identity endpoints must be HTTPS URLs without credentials or fragments");
119
+ }
120
+ return url;
121
+ }
122
+ function createSupAuthRequestContext(options) {
123
+ httpsUrl(options.issuer);
124
+ const jwksUrl = httpsUrl(options.jwksUrl);
125
+ if (!options.audience.trim() || !options.projectId.trim() || !options.clientId?.trim()) {
126
+ throw new TypeError("SupAuth audience, clientId and projectId are required");
127
+ }
128
+ const algorithms = [...options.algorithms ?? ["ES256", "RS256"]];
129
+ if (!algorithms.length || algorithms.some((value) => value !== "ES256" && value !== "RS256")) {
130
+ throw new TypeError("SupAuth requires ES256 or RS256");
131
+ }
132
+ const { issuer, audience, clientId, projectId, resolveAccess } = options;
133
+ const keyResolver = options.keyResolver ?? createRemoteJWKSet(jwksUrl, { timeoutDuration: 5000 });
134
+ return async (request) => {
135
+ const match = request.headers.get("authorization")?.match(/^Bearer ([^\s]+)$/i);
136
+ const token = match?.[1];
137
+ if (!token || token.length > 16384)
138
+ throw unauthenticated();
139
+ let subject;
140
+ try {
141
+ const { payload } = await jwtVerify(token, keyResolver, {
142
+ issuer,
143
+ audience,
144
+ algorithms,
145
+ requiredClaims: ["sub", "exp", "iat"]
146
+ });
147
+ if (typeof payload.sub !== "string" || !payload.sub.trim() || payload.sub.length > 1024 || /[\u0000-\u001f\u007f]/.test(payload.sub)) {
148
+ throw unauthenticated();
149
+ }
150
+ const application = payload.client_id ?? payload.azp;
151
+ if (application !== clientId || payload.role !== "authenticated" || payload.client_id !== undefined && payload.client_id !== clientId || payload.azp !== undefined && payload.azp !== clientId) {
152
+ throw unauthenticated();
153
+ }
154
+ subject = payload.sub;
155
+ } catch (error) {
156
+ if (error instanceof ApplicationError || error instanceof errors.JWTClaimValidationFailed || error instanceof errors.JWTExpired || error instanceof errors.JWTInvalid || error instanceof errors.JWSInvalid || error instanceof errors.JWSSignatureVerificationFailed || error instanceof errors.JOSEAlgNotAllowed || error instanceof errors.JOSENotSupported || error instanceof errors.JWKSNoMatchingKey)
157
+ throw unauthenticated();
158
+ throw new ApplicationError("Identity verification service unavailable", {
159
+ status: 503,
160
+ code: "AUTHENTICATION_UNAVAILABLE"
161
+ });
162
+ }
163
+ const identity = { authenticated: true, subject, issuer, clientId };
164
+ Object.defineProperty(identity, "accessToken", { value: token, enumerable: false });
165
+ Object.freeze(identity);
166
+ let access;
167
+ try {
168
+ access = await resolveAccess(identity, request);
169
+ } catch {
170
+ throw new ApplicationError("Application access service unavailable", {
171
+ status: 503,
172
+ code: "APPLICATION_ACCESS_UNAVAILABLE"
173
+ });
174
+ }
175
+ if (!access || access.projectId !== projectId || typeof access.tenantId !== "string" || !access.tenantId.trim() || !Array.isArray(access.permissions) || access.permissions.some((permission) => typeof permission !== "string" || !permission.trim())) {
176
+ throw new ApplicationError("Application access denied", { status: 403, code: "APPLICATION_ACCESS_DENIED" });
177
+ }
178
+ const context = createSupaCloudRequestContext(request);
179
+ return {
180
+ ...context,
181
+ identity,
182
+ access: Object.freeze({
183
+ projectId,
184
+ tenantId: access.tenantId,
185
+ permissions: Object.freeze([...new Set(access.permissions)])
186
+ })
187
+ };
188
+ };
189
+ }
190
+ function unauthenticated() {
191
+ return new ApplicationError("Authenticated user context is required", {
192
+ status: 401,
193
+ code: "AUTHENTICATION_REQUIRED"
194
+ });
195
+ }
196
+
197
+ // src/http-response-cache.ts
198
+ import { WebStandardAdapter } from "elysia/adapter/web-standard";
199
+ function mayStore({ http, response }) {
200
+ if (response === null || typeof response !== "object" || response instanceof Response || !Array.isArray(response) && Object.getPrototypeOf(response) !== Object.prototype)
201
+ return false;
202
+ if (http.set.status !== undefined && http.set.status !== 200 && http.set.status !== "OK")
203
+ return false;
204
+ if (http.set.cookie && Object.keys(http.set.cookie).length)
205
+ return false;
206
+ const headers = new Headers(http.set.headers);
207
+ for (const name of headers.keys()) {
208
+ if (!["content-type", "x-request-id", "ratelimit-limit", "ratelimit-remaining"].includes(name))
209
+ return false;
210
+ }
211
+ return !headers.has("content-type") || headers.get("content-type").split(";")[0].trim() === "application/json";
212
+ }
213
+ async function boundedBody(response, maxBytes) {
214
+ const reader = response.body?.getReader();
215
+ if (!reader)
216
+ return;
217
+ const chunks = [];
218
+ let size = 0;
219
+ try {
220
+ while (true) {
221
+ const next = await reader.read();
222
+ if (next.done)
223
+ break;
224
+ size += next.value.byteLength;
225
+ if (size > maxBytes) {
226
+ reader.cancel().catch(() => {});
227
+ return;
228
+ }
229
+ chunks.push(next.value);
230
+ }
231
+ } finally {
232
+ reader.releaseLock();
233
+ }
234
+ const bytes = new Uint8Array(size);
235
+ let offset = 0;
236
+ for (const chunk of chunks) {
237
+ bytes.set(chunk, offset);
238
+ offset += chunk.byteLength;
239
+ }
240
+ return new TextDecoder().decode(bytes);
241
+ }
242
+ function createCachePolicy(options) {
243
+ const misses = new WeakMap;
244
+ const snapshots = new WeakMap;
245
+ const policy = async ({ http }) => {
246
+ const context = options.requireAccess(http.request);
247
+ if (http.request.headers.has("range") || http.request.headers.has("if-none-match") || http.request.headers.has("if-modified-since") || /(?:no-cache|no-store|max-age\s*=\s*0)/i.test(http.request.headers.get("cache-control") ?? ""))
248
+ return;
249
+ const headers = [...http.request.headers].filter(([name]) => name !== "x-request-id").sort(([a], [b]) => a.localeCompare(b));
250
+ const key = await policyKey([
251
+ "cache",
252
+ options.namespace,
253
+ options.route,
254
+ ...principalKey(context),
255
+ [...context.access.permissions].sort(),
256
+ http.request.url,
257
+ headers
258
+ ]);
259
+ let entry, generation;
260
+ try {
261
+ generation = await options.store.generation();
262
+ if (typeof generation !== "string" || !generation.length || generation.length > 128)
263
+ throw new Error("Invalid cache generation");
264
+ entry = await options.store.get(key, generation);
265
+ } catch {
266
+ throw new ApplicationError("Cache service unavailable", { status: 503, code: "HTTP_CACHE_UNAVAILABLE" });
267
+ }
268
+ if (entry && entry.expiresAt > Date.now()) {
269
+ if (typeof entry.body !== "string" || entry.contentType !== "application/json" || new TextEncoder().encode(entry.body).byteLength > options.maxBodyBytes) {
270
+ throw new ApplicationError("Cache service unavailable", { status: 503, code: "HTTP_CACHE_UNAVAILABLE" });
271
+ }
272
+ return new Response(entry.body, {
273
+ headers: { "content-type": "application/json", "cache-control": "private, no-store" }
274
+ });
275
+ }
276
+ misses.set(http.request, { key, generation });
277
+ };
278
+ policy.terminal = true;
279
+ policy.mapResponse = async (context) => {
280
+ if (!misses.has(context.http.request) || !mayStore(context))
281
+ return;
282
+ const value = context.encodeResponse ? await context.encodeResponse(context.response) : context.response;
283
+ const response = await WebStandardAdapter.response.map(value, context.http.set, context.http.request);
284
+ if (!(response instanceof Response))
285
+ throw new Error("HTTP response mapping did not return a Response");
286
+ const body = boundedBody(response.clone(), options.maxBodyBytes).catch(() => {
287
+ try {
288
+ options.onWriteError();
289
+ } catch {}
290
+ return;
291
+ });
292
+ snapshots.set(context.http.request, { response, body });
293
+ return response;
294
+ };
295
+ policy.afterResponse = async (context) => {
296
+ const miss = misses.get(context.http.request);
297
+ const snapshot = snapshots.get(context.http.request);
298
+ misses.delete(context.http.request);
299
+ snapshots.delete(context.http.request);
300
+ if (!miss || !snapshot || context.response !== snapshot.response || snapshot.response.status !== 200)
301
+ return;
302
+ const headers = snapshot.response.headers;
303
+ if ([...headers.keys()].some((name) => !["content-type", "x-request-id", "ratelimit-limit", "ratelimit-remaining"].includes(name)))
304
+ return;
305
+ try {
306
+ const body = await snapshot.body;
307
+ if (body === undefined)
308
+ return;
309
+ await options.store.set(miss.key, { body, contentType: "application/json", expiresAt: Date.now() + options.ttlMs }, miss.generation);
310
+ } catch {
311
+ try {
312
+ options.onWriteError();
313
+ } catch {}
314
+ }
315
+ };
316
+ return policy;
317
+ }
318
+
319
+ // src/http-policy-suite.ts
320
+ function policyOptions(value, allowed) {
321
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !allowed.includes(key))) {
322
+ throw new HttpPolicyConfigurationError("Invalid built-in HTTP policy options");
323
+ }
324
+ return value;
325
+ }
326
+ function positiveInteger(value, max) {
327
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0 || value > max) {
328
+ throw new HttpPolicyConfigurationError("HTTP policy numeric option is out of range");
329
+ }
330
+ return value;
331
+ }
332
+ async function policyKey(parts) {
333
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(parts)));
334
+ return Array.from(new Uint8Array(digest), (value) => value.toString(16).padStart(2, "0")).join("");
335
+ }
336
+ function principalKey(context) {
337
+ return [
338
+ context.identity.issuer,
339
+ context.identity.clientId,
340
+ context.identity.subject,
341
+ context.access.projectId,
342
+ context.access.tenantId
343
+ ];
344
+ }
345
+ function createHttpPolicySuite(options) {
346
+ const verify = createSupAuthRequestContext(options.auth);
347
+ const verified = new WeakMap;
348
+ const requestContext = async (request) => {
349
+ verified.delete(request);
350
+ if (!request.headers.has("authorization")) {
351
+ const base = createSupaCloudRequestContext(request);
352
+ return { ...base, identity: Object.freeze({ authenticated: false }) };
353
+ }
354
+ const context = await verify(request);
355
+ verified.set(request, context);
356
+ return context;
357
+ };
358
+ const requireAccess = (request) => {
359
+ const context = verified.get(request);
360
+ if (!context)
361
+ throw new ApplicationError("Authentication required", {
362
+ status: 401,
363
+ code: "AUTHENTICATION_REQUIRED"
364
+ });
365
+ return context;
366
+ };
367
+ const registry = {
368
+ authenticated: (value) => {
369
+ if (value !== undefined)
370
+ throw new HttpPolicyConfigurationError("authenticated does not accept options");
371
+ return ({ http }) => {
372
+ requireAccess(http.request);
373
+ };
374
+ },
375
+ tenant: (value) => {
376
+ const { param } = policyOptions(value, ["param"]);
377
+ if (typeof param !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(param)) {
378
+ throw new HttpPolicyConfigurationError("tenant requires a route parameter name");
379
+ }
380
+ return ({ http }) => {
381
+ const context = requireAccess(http.request);
382
+ if (http.params[param] !== context.access.tenantId) {
383
+ throw new ApplicationError("Tenant access denied", { status: 403, code: "TENANT_ACCESS_DENIED" });
384
+ }
385
+ };
386
+ },
387
+ permission: (value) => {
388
+ const { allOf } = policyOptions(value, ["allOf"]);
389
+ if (!Array.isArray(allOf) || !allOf.length || Array.from(allOf).some((permission) => typeof permission !== "string" || !permission.trim())) {
390
+ throw new HttpPolicyConfigurationError("permission requires non-empty allOf permissions");
391
+ }
392
+ const required = [...new Set(allOf)];
393
+ return ({ http }) => {
394
+ const access = requireAccess(http.request).access;
395
+ if (!required.every((permission) => access.permissions.includes(permission))) {
396
+ throw new ApplicationError("Permission denied", { status: 403, code: "PERMISSION_DENIED" });
397
+ }
398
+ };
399
+ },
400
+ rateLimit: (value, route) => {
401
+ const config = policyOptions(value, ["limit", "windowMs"]);
402
+ const limit = positiveInteger(config.limit, 1e9);
403
+ const windowMs = positiveInteger(config.windowMs, 86400000);
404
+ const store = options.rateLimitStore;
405
+ if (!store)
406
+ throw new HttpPolicyConfigurationError("rateLimit requires an explicit store");
407
+ return async ({ http }) => {
408
+ const context = requireAccess(http.request);
409
+ const key = await policyKey(["rate", route.method, route.path, ...principalKey(context), limit, windowMs]);
410
+ let result;
411
+ try {
412
+ result = await store.consume(key, limit, windowMs);
413
+ } catch {
414
+ throw new ApplicationError("Rate limit service unavailable", { status: 503, code: "RATE_LIMIT_UNAVAILABLE" });
415
+ }
416
+ if (typeof result?.allowed !== "boolean" || !Number.isSafeInteger(result.remaining) || result.remaining < 0 || result.remaining > limit || !Number.isFinite(result.resetAt)) {
417
+ throw new ApplicationError("Rate limit service unavailable", { status: 503, code: "RATE_LIMIT_UNAVAILABLE" });
418
+ }
419
+ http.set.headers["ratelimit-limit"] = String(limit);
420
+ http.set.headers["ratelimit-remaining"] = String(result.remaining);
421
+ if (!result.allowed) {
422
+ const retryAfter = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1000));
423
+ return new Response("Too Many Requests", { status: 429, headers: { "retry-after": String(retryAfter) } });
424
+ }
425
+ };
426
+ },
427
+ cache: (value, route) => {
428
+ if (route.method !== "GET" || route.command) {
429
+ throw new HttpPolicyConfigurationError("cache is restricted to GET queries, never commands");
430
+ }
431
+ const config = policyOptions(value, ["ttlMs", "maxBodyBytes"]);
432
+ const ttlMs = positiveInteger(config.ttlMs, 86400000);
433
+ const maxBodyBytes = positiveInteger(config.maxBodyBytes ?? 262144, 16777216);
434
+ if (!options.cacheStore)
435
+ throw new HttpPolicyConfigurationError("cache requires an explicit store");
436
+ if (typeof options.cacheNamespace !== "string" || !/^[A-Za-z0-9._:-]{1,128}$/.test(options.cacheNamespace)) {
437
+ throw new HttpPolicyConfigurationError("cache requires an explicit deployment cacheNamespace");
438
+ }
439
+ return createCachePolicy({
440
+ store: options.cacheStore,
441
+ requireAccess,
442
+ ttlMs,
443
+ maxBodyBytes,
444
+ route: `${route.method} ${route.path}`,
445
+ namespace: options.cacheNamespace,
446
+ onWriteError: options.onCacheWriteError ?? (() => console.warn("supacloud: HTTP cache write failed"))
447
+ });
448
+ }
449
+ };
450
+ return { requestContext, httpPolicies: registry };
451
+ }
452
+ // src/http-policy-stores.ts
453
+ function capacity(value) {
454
+ if (!Number.isSafeInteger(value) || value <= 0)
455
+ throw new TypeError("Store capacity must be a positive integer");
456
+ }
457
+ function createMemoryHttpRateLimitStore(options = {}) {
458
+ const maxEntries = options.maxEntries ?? 1e4;
459
+ capacity(maxEntries);
460
+ const now = options.now ?? Date.now;
461
+ const entries = new Map;
462
+ return {
463
+ consume(key, limit, windowMs) {
464
+ capacity(limit);
465
+ capacity(windowMs);
466
+ const time = now();
467
+ let entry = entries.get(key);
468
+ if (!entry || entry.resetAt <= time) {
469
+ if (!entry && entries.size >= maxEntries) {
470
+ for (const [expiredKey, value] of entries) {
471
+ if (value.resetAt <= time)
472
+ entries.delete(expiredKey);
473
+ }
474
+ if (entries.size >= maxEntries)
475
+ throw new Error("Rate limit store capacity exhausted");
476
+ }
477
+ entry = { used: 0, resetAt: time + windowMs };
478
+ entries.set(key, entry);
479
+ }
480
+ const allowed = entry.used < limit;
481
+ if (allowed)
482
+ entry.used++;
483
+ return { allowed, remaining: Math.max(0, limit - entry.used), resetAt: entry.resetAt };
484
+ }
485
+ };
486
+ }
487
+ function createMemoryHttpCacheStore(options = {}) {
488
+ const maxEntries = options.maxEntries ?? 1000, maxBytes = options.maxBytes ?? 8 * 1024 * 1024;
489
+ capacity(maxEntries);
490
+ capacity(maxBytes);
491
+ const now = options.now ?? Date.now;
492
+ const entries = new Map;
493
+ let generation = crypto.randomUUID();
494
+ let bytes = 0;
495
+ const remove = (key) => {
496
+ bytes -= entries.get(key)?.bytes ?? 0;
497
+ entries.delete(key);
498
+ };
499
+ return {
500
+ generation: () => generation,
501
+ get(key, expected) {
502
+ if (expected !== generation)
503
+ return;
504
+ const entry = entries.get(key);
505
+ if (!entry)
506
+ return;
507
+ if (entry.value.expiresAt <= now()) {
508
+ remove(key);
509
+ return;
510
+ }
511
+ entries.delete(key);
512
+ entries.set(key, entry);
513
+ return { ...entry.value };
514
+ },
515
+ set(key, value, expected) {
516
+ if (expected !== generation)
517
+ return;
518
+ const size = new TextEncoder().encode(key + value.body + value.contentType).byteLength;
519
+ if (size > maxBytes || value.expiresAt <= now())
520
+ return;
521
+ remove(key);
522
+ while (entries.size >= maxEntries || bytes + size > maxBytes) {
523
+ const oldest = entries.keys().next().value;
524
+ if (oldest === undefined)
525
+ break;
526
+ remove(oldest);
527
+ }
528
+ entries.set(key, { value: { ...value }, bytes: size });
529
+ bytes += size;
530
+ },
531
+ clear() {
532
+ generation = crypto.randomUUID();
533
+ entries.clear();
534
+ bytes = 0;
535
+ }
536
+ };
537
+ }
538
+ // src/http-policy-postgres.ts
539
+ var HTTP_POLICY_STORE_SQL = `
540
+ CREATE SCHEMA IF NOT EXISTS supacloud_http;
541
+ REVOKE ALL ON SCHEMA supacloud_http FROM PUBLIC;
542
+ CREATE TABLE IF NOT EXISTS supacloud_http.rate_limits (
543
+ key text PRIMARY KEY CHECK (key ~ '^[a-f0-9]{64}$'),
544
+ used bigint NOT NULL CHECK (used > 0),
545
+ reset_at timestamptz NOT NULL
546
+ );
547
+ CREATE INDEX IF NOT EXISTS http_rate_limit_expiry ON supacloud_http.rate_limits(reset_at);
548
+ CREATE TABLE IF NOT EXISTS supacloud_http.response_cache (
549
+ key text PRIMARY KEY CHECK (key ~ '^[a-f0-9]{64}$'),
550
+ body text NOT NULL CHECK (octet_length(body) <= 16777216),
551
+ expires_at timestamptz NOT NULL,
552
+ generation uuid NOT NULL
553
+ );
554
+ ALTER TABLE supacloud_http.response_cache ADD COLUMN IF NOT EXISTS generation uuid
555
+ NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000';
556
+ CREATE TABLE IF NOT EXISTS supacloud_http.cache_generation (
557
+ singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
558
+ generation uuid NOT NULL DEFAULT gen_random_uuid()
559
+ );
560
+ INSERT INTO supacloud_http.cache_generation(singleton) VALUES (true) ON CONFLICT DO NOTHING;
561
+ CREATE INDEX IF NOT EXISTS http_response_cache_expiry ON supacloud_http.response_cache(expires_at);
562
+ REVOKE ALL ON ALL TABLES IN SCHEMA supacloud_http FROM PUBLIC;
563
+ CREATE OR REPLACE FUNCTION supacloud_http.consume_rate_limit(p_key text, p_limit bigint, p_window_ms integer)
564
+ RETURNS TABLE(allowed boolean, remaining bigint, reset_at_ms numeric)
565
+ LANGUAGE plpgsql SET search_path = pg_catalog, supacloud_http AS $rate$
566
+ DECLARE
567
+ entry supacloud_http.rate_limits%ROWTYPE;
568
+ observed_at timestamptz;
569
+ BEGIN
570
+ IF p_limit < 1 OR p_limit > 1000000000 OR p_window_ms < 1 OR p_window_ms > 86400000 THEN
571
+ RAISE EXCEPTION 'Invalid rate limit window';
572
+ END IF;
573
+ LOOP
574
+ INSERT INTO supacloud_http.rate_limits(key, used, reset_at)
575
+ VALUES (p_key, 1, '-infinity') ON CONFLICT DO NOTHING;
576
+ SELECT key, used, reset_at INTO entry FROM supacloud_http.rate_limits WHERE key=p_key FOR UPDATE;
577
+ EXIT WHEN FOUND;
578
+ -- Expiry pruning may remove a conflicting row before we acquire its lock.
579
+ END LOOP;
580
+ observed_at := clock_timestamp();
581
+ IF entry.reset_at <= observed_at THEN
582
+ entry.used := 1;
583
+ entry.reset_at := observed_at + p_window_ms * interval '1 millisecond';
584
+ ELSE
585
+ entry.used := least(entry.used + 1, p_limit + 1);
586
+ END IF;
587
+ UPDATE supacloud_http.rate_limits SET used=entry.used, reset_at=entry.reset_at WHERE key=p_key;
588
+ RETURN QUERY SELECT entry.used <= p_limit, greatest(p_limit-entry.used,0),
589
+ extract(epoch FROM entry.reset_at)*1000;
590
+ END
591
+ $rate$;
592
+ REVOKE ALL ON FUNCTION supacloud_http.consume_rate_limit(text,bigint,integer) FROM PUBLIC;
593
+ `;
594
+ function validKey(key) {
595
+ if (!/^[a-f0-9]{64}$/.test(key))
596
+ throw new TypeError("HTTP store keys must be SHA-256 digests");
597
+ }
598
+ function createPostgresHttpPolicyStores(database) {
599
+ const rateLimitStore = {
600
+ async consume(key, limit, windowMs) {
601
+ validKey(key);
602
+ if (!Number.isSafeInteger(limit) || limit <= 0 || limit > 1e9 || !Number.isSafeInteger(windowMs) || windowMs <= 0 || windowMs > 86400000) {
603
+ throw new TypeError("Invalid rate limit window");
604
+ }
605
+ const [row] = await database.query("SELECT allowed, remaining, reset_at_ms FROM supacloud_http.consume_rate_limit($1,$2,$3)", [key, limit, windowMs]);
606
+ if (!row || typeof row.allowed !== "boolean")
607
+ throw new Error("Invalid rate limit storage result");
608
+ return { allowed: row.allowed, remaining: Number(row.remaining), resetAt: Number(row.reset_at_ms) };
609
+ }
610
+ };
611
+ const cacheStore = {
612
+ async generation() {
613
+ const [row] = await database.query("SELECT generation FROM supacloud_http.cache_generation WHERE singleton", []);
614
+ if (!row || typeof row.generation !== "string")
615
+ throw new Error("Invalid cache generation");
616
+ return row.generation;
617
+ },
618
+ async get(key, generation) {
619
+ validKey(key);
620
+ const [row] = await database.query(`
621
+ SELECT body, extract(epoch FROM expires_at) * 1000 AS expires_at_ms
622
+ FROM supacloud_http.response_cache AS cache
623
+ JOIN supacloud_http.cache_generation AS current ON cache.generation = current.generation
624
+ WHERE key = $1 AND cache.generation = $2::uuid AND expires_at > clock_timestamp()
625
+ `, [key, generation]);
626
+ if (!row)
627
+ return;
628
+ if (typeof row.body !== "string")
629
+ throw new Error("Invalid cache storage result");
630
+ return { body: row.body, contentType: "application/json", expiresAt: Number(row.expires_at_ms) };
631
+ },
632
+ async set(key, value, generation) {
633
+ validKey(key);
634
+ if (value.contentType !== "application/json" || typeof value.body !== "string" || new TextEncoder().encode(value.body).byteLength > 16777216 || !Number.isSafeInteger(value.expiresAt) || value.expiresAt <= 0) {
635
+ throw new TypeError("Invalid cache entry");
636
+ }
637
+ await database.query(`
638
+ WITH current AS MATERIALIZED (
639
+ SELECT generation FROM supacloud_http.cache_generation
640
+ WHERE singleton AND generation=$4::uuid FOR SHARE
641
+ )
642
+ INSERT INTO supacloud_http.response_cache (key, body, expires_at, generation)
643
+ SELECT $1, $2, to_timestamp($3 / 1000.0), generation FROM current
644
+ ON CONFLICT (key) DO UPDATE SET body = excluded.body,
645
+ expires_at = excluded.expires_at, generation = excluded.generation
646
+ `, [key, value.body, value.expiresAt, generation]);
647
+ },
648
+ async clear() {
649
+ await database.query(`
650
+ WITH advanced AS (
651
+ UPDATE supacloud_http.cache_generation SET generation=gen_random_uuid() WHERE singleton RETURNING generation
652
+ )
653
+ DELETE FROM supacloud_http.response_cache WHERE EXISTS(SELECT 1 FROM advanced)
654
+ `, []);
655
+ }
656
+ };
657
+ return {
658
+ rateLimitStore,
659
+ cacheStore,
660
+ async prune() {
661
+ await database.query("DELETE FROM supacloud_http.rate_limits WHERE reset_at <= clock_timestamp()", []);
662
+ await database.query("DELETE FROM supacloud_http.response_cache WHERE expires_at <= clock_timestamp()", []);
663
+ }
664
+ };
665
+ }
666
+ // src/execution.ts
667
+ import {
668
+ executionRequestId,
669
+ executionTrace,
670
+ observeExecution
671
+ } from "@supacloud/app/execution";
672
+
673
+ // src/schema_contract.ts
674
+ import {
675
+ Validator,
676
+ t,
677
+ StatusMap as StatusMap2,
678
+ ElysiaStatus
679
+ } from "elysia";
680
+ function defineRouteContract(schemas) {
681
+ return Object.freeze({ ...schemas });
682
+ }
683
+ var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
684
+ var RESPONSE_STATUS_MIN = 100;
685
+ var RESPONSE_STATUS_MAX = 599;
686
+ var RESPONSE_FAMILY_PATTERN = /^([1-5])(?:xx|XX)$/;
687
+ var RESPONSE_STATUS_PATTERN = /^[1-5]\d{2}$/;
688
+ function isSchema(value) {
689
+ return value !== null && typeof value === "object" && ((TYPEBOX_KIND in value) || ("~kind" in value) || ("~standard" in value));
690
+ }
691
+ function isJsonSchemaObject(value) {
692
+ if (value === null || typeof value !== "object" || Array.isArray(value))
693
+ return false;
694
+ return [
695
+ "$schema",
696
+ "$id",
697
+ "$ref",
698
+ "$defs",
699
+ "definitions",
700
+ "type",
701
+ "properties",
702
+ "patternProperties",
703
+ "required",
704
+ "items",
705
+ "prefixItems",
706
+ "contains",
707
+ "allOf",
708
+ "anyOf",
709
+ "oneOf",
710
+ "not",
711
+ "enum",
712
+ "const",
713
+ "additionalProperties",
714
+ "minLength",
715
+ "maxLength",
716
+ "minimum",
717
+ "maximum",
718
+ "format",
719
+ "pattern"
720
+ ].some((key) => (key in value));
721
+ }
722
+ function invalidResponseSelector(selector) {
723
+ throw new TypeError(`Unsupported response selector "${selector}". Use an HTTP status (100-599), ` + "a status family such as 4XX/5XX, or default.");
724
+ }
725
+ function conflictingResponseSchemas() {
726
+ throw new TypeError("Route contracts cannot declare both response and responses. " + "Remove response and use responses: { 200: Schema }.");
727
+ }
728
+ function duplicateResponseSelector(selector, existing) {
729
+ throw new TypeError(`Duplicate response selectors "${existing}" and "${selector}" differ only by case. ` + `Keep one ${selector.toUpperCase()} selector.`);
730
+ }
731
+ function responseSchemaForStatus(responses, status) {
732
+ const exact = Object.hasOwn(responses, status) ? responses[status] : Object.hasOwn(responses, String(status)) ? responses[String(status)] : undefined;
733
+ if (exact !== undefined || Object.hasOwn(responses, status) || Object.hasOwn(responses, String(status))) {
734
+ return exact;
735
+ }
736
+ const family = `${Math.floor(status / 100)}XX`;
737
+ if (Object.hasOwn(responses, family))
738
+ return responses[family];
739
+ const lowerFamily = family.toLowerCase();
740
+ if (Object.hasOwn(responses, lowerFamily))
741
+ return responses[lowerFamily];
742
+ return Object.hasOwn(responses, "default") ? responses.default : undefined;
743
+ }
744
+ function responseStatusDeclared(responses, status) {
745
+ return responseSchemaForStatus(responses, status) !== undefined || Object.hasOwn(responses, status) || Object.hasOwn(responses, String(status));
746
+ }
747
+ function responseStatusOf(value, configuredStatus) {
748
+ if (value instanceof Response)
749
+ return value.status;
750
+ if (value instanceof ElysiaStatus) {
751
+ const code = value.status;
752
+ if (typeof code === "number" && Number.isInteger(code) && code >= RESPONSE_STATUS_MIN && code <= RESPONSE_STATUS_MAX) {
753
+ return code;
754
+ }
755
+ }
756
+ if (typeof configuredStatus === "number")
757
+ return configuredStatus;
758
+ if (typeof configuredStatus === "string") {
759
+ const mapped = StatusMap2[configuredStatus];
760
+ if (typeof mapped === "number")
761
+ return mapped;
762
+ }
763
+ return 200;
764
+ }
765
+ function assertResponseStatusDeclared(responses, status) {
766
+ if (responseStatusDeclared(responses, status))
767
+ return;
768
+ throw new TypeError("Response validation failed");
769
+ }
770
+ function toElysiaResponseMap(responses) {
771
+ const exact = new Map;
772
+ const families = new Map;
773
+ const familySelectors = new Map;
774
+ let defaultSchema;
775
+ let hasDefault = false;
776
+ let requiresExpansion = false;
777
+ for (const [selector, schema] of Object.entries(responses)) {
778
+ if (RESPONSE_STATUS_PATTERN.test(selector)) {
779
+ exact.set(Number(selector), schema);
780
+ continue;
781
+ }
782
+ if (selector === "default") {
783
+ defaultSchema = schema;
784
+ hasDefault = true;
785
+ requiresExpansion = true;
786
+ continue;
787
+ }
788
+ const family = RESPONSE_FAMILY_PATTERN.exec(selector);
789
+ if (family) {
790
+ const canonicalSelector = selector.toLowerCase();
791
+ const existingSelector = familySelectors.get(canonicalSelector);
792
+ if (existingSelector !== undefined)
793
+ duplicateResponseSelector(selector, existingSelector);
794
+ familySelectors.set(canonicalSelector, selector);
795
+ families.set(Number(family[1]), schema);
796
+ requiresExpansion = true;
797
+ continue;
798
+ }
799
+ invalidResponseSelector(selector);
800
+ }
801
+ if (!requiresExpansion)
802
+ return responses;
803
+ const expanded = {};
804
+ if (hasDefault) {
805
+ for (let status = RESPONSE_STATUS_MIN;status <= RESPONSE_STATUS_MAX; status++) {
806
+ expanded[status] = defaultSchema;
807
+ }
808
+ }
809
+ for (const [family, schema] of families) {
810
+ const first = family * 100;
811
+ for (let status = first;status < first + 100; status++)
812
+ expanded[status] = schema;
813
+ }
814
+ for (const [status, schema] of exact)
815
+ expanded[status] = schema;
816
+ return expanded;
817
+ }
818
+ function toElysiaResponseSchema(response) {
819
+ if (typeof response === "string" || isSchema(response) || isJsonSchemaObject(response))
820
+ return response;
821
+ if (response === null || typeof response !== "object" || Array.isArray(response))
822
+ return response;
823
+ return toElysiaResponseMap(response);
824
+ }
825
+ function toElysiaRouteSchema(contract) {
826
+ if (contract.response !== undefined && contract.responses !== undefined) {
827
+ conflictingResponseSchemas();
828
+ }
829
+ const schema = {};
830
+ if (contract.body !== undefined)
831
+ schema.body = contract.body;
832
+ if (contract.params !== undefined)
833
+ schema.params = contract.params;
834
+ if (contract.query !== undefined)
835
+ schema.query = contract.query;
836
+ if (contract.headers !== undefined)
837
+ schema.headers = contract.headers;
838
+ if (contract.cookie !== undefined)
839
+ schema.cookie = contract.cookie;
840
+ if (contract.responses !== undefined)
841
+ schema.response = toElysiaResponseMap(contract.responses);
842
+ else if (contract.response !== undefined)
843
+ schema.response = toElysiaResponseSchema(contract.response);
844
+ return schema;
845
+ }
846
+ function defineElysiaRoute(method, path, contract, handler) {
847
+ toElysiaRouteSchema(contract);
848
+ const stableContract = Object.isFrozen(contract) ? contract : Object.freeze(contract);
849
+ return Object.freeze({
850
+ method,
851
+ path,
852
+ contract: stableContract,
853
+ handler
854
+ });
855
+ }
856
+ function registerElysiaRoute(app, route) {
857
+ const handler = async (context) => {
858
+ const value = await route.handler(context);
859
+ if (route.contract.responses !== undefined) {
860
+ const status = responseStatusOf(value, context.set.status);
861
+ assertResponseStatusDeclared(route.contract.responses, status);
862
+ }
863
+ return value;
864
+ };
865
+ app.route(route.method, route.path, { ...toElysiaRouteSchema(route.contract) }, handler);
866
+ return app;
867
+ }
868
+
869
+ class SchemaContractError extends Error {
870
+ code = "SCHEMA_CONTRACT_INVALID";
871
+ constructor() {
872
+ super("Schema contract validation failed");
873
+ this.name = "SchemaContractError";
874
+ }
875
+ }
876
+ function createSchemaDecoder(schema, options = {}) {
877
+ const validator = Validator.create(schema, {
878
+ ...options.coerce ? { coerces: [[[
879
+ ["number", (value) => t.Numeric(value)],
880
+ ["integer", (value) => t.IntegerString(value)],
881
+ ["boolean", (value) => t.BooleanString(value)]
882
+ ]]] } : {},
883
+ normalize: options.normalize ?? true
884
+ });
885
+ return (value) => {
886
+ try {
887
+ if (validator.isAsync)
888
+ throw new SchemaContractError;
889
+ return validator.FromSync(value);
890
+ } catch {
891
+ throw new SchemaContractError;
892
+ }
893
+ };
894
+ }
895
+ function defineJsonContract(schemas, request, options = {}) {
896
+ return Object.freeze({
897
+ ...schemas,
898
+ input: createSchemaDecoder(schemas.body, options),
899
+ result: createSchemaDecoder(schemas.response, options),
900
+ request
901
+ });
902
+ }
903
+
904
+ // src/documentation.ts
905
+ import { Elysia as Elysia2 } from "elysia";
906
+ function normalizePath(value, fallback) {
907
+ const path = value ?? fallback;
908
+ if (!path.trim() || !path.startsWith("/") || path.includes("?") || path.includes("#")) {
909
+ throw new Error(`Documentation path must be an absolute path without query or fragment: ${path}`);
910
+ }
911
+ return path.length > 1 ? path.replace(/\/+$/, "") : path;
912
+ }
913
+ function resolveSource(source) {
914
+ if (typeof source === "function") {
915
+ return Promise.resolve(source());
916
+ }
917
+ return Promise.resolve(source);
918
+ }
919
+ function jsonResponse(document) {
920
+ if (document === null || typeof document !== "object" || Array.isArray(document)) {
921
+ throw new Error("OpenAPI documentation must be a JSON object");
922
+ }
923
+ const serialized = JSON.stringify(document);
924
+ if (serialized === undefined)
925
+ throw new Error("OpenAPI documentation must be JSON-serializable");
926
+ return new Response(serialized, {
927
+ headers: { "content-type": "application/json; charset=utf-8" }
928
+ });
929
+ }
930
+ function textResponse(schema) {
931
+ return new Response(schema, {
932
+ headers: { "content-type": "text/plain; charset=utf-8" }
933
+ });
934
+ }
935
+ function escapeHtml(value) {
936
+ return value.replace(/[&<>"']/g, (character) => ({
937
+ "&": "&amp;",
938
+ "<": "&lt;",
939
+ ">": "&gt;",
940
+ '"': "&quot;",
941
+ "'": "&#39;"
942
+ })[character] ?? character);
943
+ }
944
+ function scriptString(value) {
945
+ return JSON.stringify(value).replace(/</g, "\\u003c");
946
+ }
947
+ function renderViewerPage(title, resourcePath, mode) {
948
+ const parse = mode === "json" ? "const value = await response.json(); output.textContent = JSON.stringify(value, null, 2);" : "output.textContent = await response.text();";
949
+ const safeTitle = escapeHtml(title);
950
+ const safeResourcePath = escapeHtml(resourcePath);
951
+ return `<!doctype html>
952
+ <html lang="en">
953
+ <head>
954
+ <meta charset="utf-8">
955
+ <meta name="viewport" content="width=device-width, initial-scale=1">
956
+ <title>${safeTitle}</title>
957
+ <style>
958
+ :root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
959
+ body { margin: 0; padding: 24px; background: Canvas; color: CanvasText; }
960
+ header { display: flex; gap: 16px; align-items: baseline; flex-wrap: wrap; }
961
+ h1 { font: 600 20px system-ui, sans-serif; margin: 0; }
962
+ a { color: LinkText; }
963
+ pre { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.5; }
964
+ </style>
965
+ </head>
966
+ <body>
967
+ <header><h1>${safeTitle}</h1><a href="${safeResourcePath}">${safeResourcePath}</a></header>
968
+ <pre id="output">Loading...</pre>
969
+ <script>
970
+ const output = document.getElementById("output");
971
+ fetch(${scriptString(resourcePath)}, { headers: { "accept": "${mode === "json" ? "application/json" : "text/plain"}" } })
972
+ .then(async (response) => {
973
+ if (!response.ok) throw new Error("HTTP " + response.status);
974
+ ${parse}
975
+ })
976
+ .catch((error) => { output.textContent = "Unable to load documentation: " + error.message; });
977
+ </script>
978
+ </body>
979
+ </html>`;
980
+ }
981
+ function createDocumentationPlugin(options = {}) {
982
+ const app = new Elysia2({ name: "supacloud:documentation" });
983
+ const paths = new Set;
984
+ const reserve = (path) => {
985
+ if (paths.has(path))
986
+ throw new Error(`Duplicate documentation path: ${path}`);
987
+ paths.add(path);
988
+ };
989
+ if (options.openApi) {
990
+ const specPath = normalizePath(options.openApi.specPath, "/openapi.json");
991
+ const uiPath = normalizePath(options.openApi.uiPath, "/docs");
992
+ reserve(specPath);
993
+ reserve(uiPath);
994
+ const title = options.openApi.title ?? "OpenAPI Documentation";
995
+ app.get(specPath, {
996
+ detail: { hide: true }
997
+ }, async () => jsonResponse(await resolveSource(options.openApi.document)));
998
+ app.get(uiPath, { detail: { hide: true } }, () => new Response(renderViewerPage(title, specPath, "json"), {
999
+ headers: { "content-type": "text/html; charset=utf-8" }
1000
+ }));
1001
+ }
1002
+ if (options.graphql) {
1003
+ const schemaPath = normalizePath(options.graphql.schemaPath, "/graphql/schema.graphql");
1004
+ const uiPath = normalizePath(options.graphql.uiPath, "/graphql/docs");
1005
+ reserve(schemaPath);
1006
+ reserve(uiPath);
1007
+ const title = options.graphql.title ?? "GraphQL Schema";
1008
+ app.get(schemaPath, {
1009
+ detail: { hide: true }
1010
+ }, async () => textResponse(await resolveSource(options.graphql.schema)));
1011
+ app.get(uiPath, { detail: { hide: true } }, () => new Response(renderViewerPage(title, schemaPath, "text"), {
1012
+ headers: { "content-type": "text/html; charset=utf-8" }
1013
+ }));
1014
+ }
1015
+ return app;
1016
+ }
1017
+
1018
+ // src/effect.ts
1019
+ import { Cause, Duration, Effect, Exit, ManagedRuntime } from "effect";
1020
+ var DEFAULT_EFFECT_RETRY = "none";
1021
+
1022
+ class EffectApplicationError extends Error {
1023
+ status;
1024
+ code;
1025
+ expose = true;
1026
+ constructor(message, status, code) {
1027
+ super(message);
1028
+ this.status = status;
1029
+ this.code = code;
1030
+ this.name = "EffectApplicationError";
1031
+ }
1032
+ }
1033
+ function createDefaultEffectRuntime() {
1034
+ return {
1035
+ run(program) {
1036
+ return Effect.runPromiseExit(program);
1037
+ }
1038
+ };
1039
+ }
1040
+ function createEffectRuntimeFromLayer(layer) {
1041
+ const managedRuntime = ManagedRuntime.make(layer);
1042
+ return {
1043
+ run(program) {
1044
+ return managedRuntime.runPromiseExit(program);
1045
+ },
1046
+ dispose: () => managedRuntime.dispose()
1047
+ };
1048
+ }
1049
+ function isRecord(value) {
1050
+ return value !== null && typeof value === "object";
1051
+ }
1052
+ function effectErrorTag(error) {
1053
+ if (isRecord(error)) {
1054
+ for (const key of ["_tag", "tag", "code", "name"]) {
1055
+ const value = error[key];
1056
+ if (typeof value === "string" && value.length > 0)
1057
+ return value;
1058
+ }
1059
+ }
1060
+ if (error instanceof Error && error.constructor.name)
1061
+ return error.constructor.name;
1062
+ return;
1063
+ }
1064
+ function boundedString(value, key, maxLength) {
1065
+ if (!isRecord(value))
1066
+ return;
1067
+ const candidate = value[key];
1068
+ if (typeof candidate !== "string")
1069
+ return;
1070
+ const trimmed = candidate.trim();
1071
+ return trimmed.length === 0 ? undefined : trimmed.slice(0, maxLength);
1072
+ }
1073
+ function boundedStatus(value) {
1074
+ if (!isRecord(value))
1075
+ return;
1076
+ const candidate = value["status"];
1077
+ return typeof candidate === "number" && Number.isInteger(candidate) && candidate >= 400 && candidate <= 599 ? candidate : undefined;
1078
+ }
1079
+ function isFrameworkRetryable(error, descriptor) {
1080
+ const tag = effectErrorTag(error);
1081
+ if (!tag)
1082
+ return false;
1083
+ const mapping = descriptor.errors?.find((entry) => entry.tag === tag);
1084
+ return mapping?.retryable === true && mapping.outcomeUnknown !== true && mapping.statusFromError !== true && mapping.status >= 500 && mapping.status <= 599;
1085
+ }
1086
+ function mapEffectFailure(error, descriptor) {
1087
+ const tag = effectErrorTag(error);
1088
+ const mapping = tag && descriptor?.errors?.find((entry) => entry.tag === tag);
1089
+ if (mapping) {
1090
+ const instanceCode = mapping.codeFromError ? boundedString(error, "code", 120) : undefined;
1091
+ const instanceMessage = mapping.messageFromError ? boundedString(error, "message", 500) : undefined;
1092
+ const instanceStatus = mapping.statusFromError ? boundedStatus(error) : undefined;
1093
+ return new EffectApplicationError(instanceMessage ?? mapping.message ?? mapping.code, instanceStatus ?? mapping.status, instanceCode ?? mapping.code);
1094
+ }
1095
+ if (tag === "TimeoutException" || tag === "TimeoutError") {
1096
+ return new EffectApplicationError("Effect execution timed out", 504, "EFFECT_TIMEOUT");
1097
+ }
1098
+ return new EffectApplicationError("Effect execution failed", 500, descriptor?.required ? "EFFECT_UNMAPPED_ERROR" : "EFFECT_RUNTIME_ERROR");
1099
+ }
1100
+ async function runCompiledEffect(value, descriptor, runtime = createDefaultEffectRuntime()) {
1101
+ if (!Effect.isEffect(value)) {
1102
+ if (descriptor?.required) {
1103
+ throw new EffectApplicationError("Route declared an Effect contract but returned a non-Effect value", 500, "EFFECT_PROGRAM_REQUIRED");
1104
+ }
1105
+ return value;
1106
+ }
1107
+ let program = value;
1108
+ if (descriptor?.timeoutMs !== undefined) {
1109
+ program = Effect.timeout(program, Duration.millis(descriptor.timeoutMs));
1110
+ }
1111
+ const retry = descriptor?.retry ?? DEFAULT_EFFECT_RETRY;
1112
+ const maxAttempts = descriptor?.maxAttempts;
1113
+ if (retry === "explicit" && maxAttempts !== undefined && maxAttempts > 1 && descriptor) {
1114
+ program = Effect.retry(program, {
1115
+ times: maxAttempts - 1,
1116
+ while: (error) => isFrameworkRetryable(error, descriptor)
1117
+ });
1118
+ }
1119
+ const exit = await runtime.run(program);
1120
+ if (Exit.isSuccess(exit))
1121
+ return exit.value;
1122
+ throw mapEffectFailure(Cause.squash(exit.cause), descriptor);
1123
+ }
1124
+
1125
+ // src/command-binding.ts
1126
+ function bindCompiledCommand(options) {
1127
+ const { module, command, governance, observer, handler, decode, preview } = options;
1128
+ return {
1129
+ execute: (input, context) => executeCompiledCommand({
1130
+ module,
1131
+ command,
1132
+ governance,
1133
+ observer,
1134
+ decode,
1135
+ input,
1136
+ request: context.request,
1137
+ requestContext: context.requestContext,
1138
+ services: context.services,
1139
+ scope: context.scope,
1140
+ handler: (value) => handler(value, context)
1141
+ }),
1142
+ ...preview ? {
1143
+ preview: (input, context) => previewCompiledCommand({
1144
+ module,
1145
+ command,
1146
+ governance,
1147
+ input,
1148
+ request: context.request,
1149
+ requestContext: context.requestContext,
1150
+ services: context.services,
1151
+ scope: context.scope,
1152
+ preview: (value) => preview(value, context)
1153
+ })
1154
+ } : {}
1155
+ };
1156
+ }
1157
+ // src/persistent-command.ts
1158
+ import {
1159
+ CommandError,
1160
+ commandFailureMetadata,
1161
+ decodeCommandIdentity
1162
+ } from "@supacloud/contracts";
1163
+ function createPersistentCommandAdapter(command, options) {
1164
+ return {
1165
+ capabilities: {
1166
+ audit: true,
1167
+ idempotency: true,
1168
+ transaction: command.kind === "transactional",
1169
+ boundary: command.kind === "transactional" ? "database" : "external"
1170
+ },
1171
+ async execute(invocation) {
1172
+ try {
1173
+ const identity = decodeCommandIdentity(await options.identity(invocation));
1174
+ return await command.execute(identity, requireIdempotencyKey(invocation), options.input(invocation), invocation.request.signal);
1175
+ } catch (error) {
1176
+ if (!(error instanceof CommandError))
1177
+ throw error;
1178
+ const status = commandErrorStatus(error.code);
1179
+ throw new ApplicationError(error.code, { code: error.code, status, metadata: commandFailureMetadata(error.code) });
1180
+ }
1181
+ }
1182
+ };
1183
+ }
1184
+ // src/transactional-command.ts
1185
+ import { AsyncLocalStorage } from "node:async_hooks";
1186
+ import { createTransactionalCommand } from "@supacloud/commands";
1187
+ import {
1188
+ CommandError as CommandError2,
1189
+ commandFailureMetadata as commandFailureMetadata2,
1190
+ decodeCommandIdentity as decodeCommandIdentity2
1191
+ } from "@supacloud/contracts";
1192
+ function createTransactionalCommandGovernance(options) {
1193
+ const { definition, permission, identity, input, rejection } = options;
1194
+ const { name, audit } = definition;
1195
+ if (!permission.trim())
1196
+ throw new TypeError("Command permission is required");
1197
+ const calls = new AsyncLocalStorage;
1198
+ function current(invocation) {
1199
+ const call = calls.getStore();
1200
+ if (!call?.active || call.transaction === undefined || invocation !== undefined && call.invocation !== invocation) {
1201
+ throw new Error("Command transaction is not active for this invocation");
1202
+ }
1203
+ return { ...call, transaction: call.transaction };
1204
+ }
1205
+ function assertBinding(invocation) {
1206
+ const command = invocation.command;
1207
+ if (command.name !== name || command.permission !== permission || command.audit !== audit.event || command.transaction !== "required" || command.idempotency !== "required" || command.rpc !== undefined) {
1208
+ throw new ApplicationError("Unsupported transactional command", { status: 501, code: "COMMAND_BINDING_MISMATCH" });
1209
+ }
1210
+ }
1211
+ function failure(error) {
1212
+ const code = commandErrorCode(error);
1213
+ if (!code)
1214
+ throw error;
1215
+ throw new ApplicationError(code, {
1216
+ code,
1217
+ status: commandErrorStatus(code),
1218
+ metadata: commandFailureMetadata2(code)
1219
+ });
1220
+ }
1221
+ const command = createTransactionalCommand({
1222
+ ...definition,
1223
+ async execute(transaction) {
1224
+ const call = calls.getStore();
1225
+ if (!call || call.active)
1226
+ throw new Error("Command continuation is not available");
1227
+ call.transaction = transaction;
1228
+ call.active = true;
1229
+ try {
1230
+ return await call.next();
1231
+ } catch (error) {
1232
+ throw rejection?.(error) ?? error;
1233
+ } finally {
1234
+ call.active = false;
1235
+ call.transaction = undefined;
1236
+ }
1237
+ }
1238
+ });
1239
+ return {
1240
+ transaction: () => current().transaction,
1241
+ async lookup(invocation) {
1242
+ assertBinding(invocation);
1243
+ try {
1244
+ const actor = decodeCommandIdentity2(await identity(invocation));
1245
+ return await command.lookup(actor, requireIdempotencyKey(invocation), input(invocation));
1246
+ } catch (error) {
1247
+ return failure(error);
1248
+ }
1249
+ },
1250
+ governance: {
1251
+ async authorize(invocation) {
1252
+ assertBinding(invocation);
1253
+ decodeCommandIdentity2(await identity(invocation));
1254
+ },
1255
+ async idempotency(invocation, next) {
1256
+ assertBinding(invocation);
1257
+ try {
1258
+ const actor = decodeCommandIdentity2(await identity(invocation));
1259
+ const key = requireIdempotencyKey(invocation);
1260
+ const value = input(invocation);
1261
+ const receipt = await calls.run({ invocation, next, active: false }, () => command.execute(actor, key, value, invocation.request.signal));
1262
+ if (receipt.status !== "confirmed")
1263
+ throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
1264
+ return receipt.result;
1265
+ } catch (error) {
1266
+ return failure(error);
1267
+ }
1268
+ },
1269
+ transaction(invocation, next) {
1270
+ current(invocation);
1271
+ return next();
1272
+ },
1273
+ audit: { succeeded(invocation) {
1274
+ current(invocation);
1275
+ }, failed() {} }
1276
+ }
1277
+ };
1278
+ }
1279
+ // src/framework.ts
1280
+ function createSupaCloudFramework(options) {
1281
+ return createApplication({
1282
+ ...options,
1283
+ normalize: options.normalize ?? false,
1284
+ modules: options.modules ?? []
1285
+ });
1286
+ }
1287
+ // src/feature.ts
1288
+ function assertFeatureTransition(spec, state, event) {
1289
+ const transition = Object.hasOwn(spec.transitions, event) ? spec.transitions[event] : undefined;
1290
+ if (!transition || !spec.states.includes(state) || transition.from !== state) {
1291
+ throw new ApplicationError("Feature transition is not allowed", {
1292
+ status: 409,
1293
+ code: "FEATURE_TRANSITION_CONFLICT"
1294
+ });
1295
+ }
1296
+ if (!spec.states.includes(transition.to)) {
1297
+ throw new ApplicationError("Feature transition references an undeclared state", {
1298
+ code: "FEATURE_SPEC_INVALID"
1299
+ });
1300
+ }
1301
+ return transition.to;
1302
+ }
1303
+ // src/memory.ts
1304
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
1305
+
1306
+ // src/memory_policy.ts
1307
+ function createMemoryPolicy() {
1308
+ const permissions = new Map;
1309
+ const receipts = new Map;
1310
+ return {
1311
+ grant(subject, permission) {
1312
+ const values = permissions.get(subject) ?? new Set;
1313
+ values.add(permission);
1314
+ permissions.set(subject, values);
1315
+ },
1316
+ revoke(subject, permission) {
1317
+ permissions.get(subject)?.delete(permission);
1318
+ },
1319
+ can(subject, permission) {
1320
+ return permissions.get(subject)?.has(permission) ?? false;
1321
+ },
1322
+ claimIdempotency(subject, key) {
1323
+ const id = JSON.stringify([subject, key]);
1324
+ if (receipts.has(id))
1325
+ return false;
1326
+ receipts.set(id, { input: "", result: Promise.resolve(undefined) });
1327
+ return true;
1328
+ },
1329
+ subject(context) {
1330
+ if (typeof context === "object" && context !== null && "identity" in context) {
1331
+ const identity = context.identity;
1332
+ if (typeof identity === "object" && identity !== null && "authenticated" in identity && identity.authenticated === true && "subject" in identity && typeof identity.subject === "string" && identity.subject.length > 0)
1333
+ return identity.subject;
1334
+ }
1335
+ throw new ApplicationError("Memory authenticated identity required", { status: 401, code: "MEMORY_IDENTITY_REQUIRED" });
1336
+ },
1337
+ async runOnce(subject, command, key, input, work) {
1338
+ if (!subject || !command || !key)
1339
+ throw new Error("Memory receipt requires subject, command and key");
1340
+ const id = JSON.stringify([subject, command, key]);
1341
+ const fingerprint = stableStringify(input);
1342
+ const existing = receipts.get(id);
1343
+ if (existing) {
1344
+ if (existing.input !== fingerprint) {
1345
+ throw new ApplicationError("Idempotency input conflict", { status: 409, code: "MEMORY_IDEMPOTENCY_CONFLICT" });
1346
+ }
1347
+ return structuredClone(await existing.result);
1348
+ }
1349
+ const result = Promise.resolve().then(work).then((value) => structuredClone(value));
1350
+ const entry = { input: fingerprint, result };
1351
+ receipts.set(id, entry);
1352
+ try {
1353
+ return structuredClone(await result);
1354
+ } catch (error) {
1355
+ if (receipts.get(id) === entry)
1356
+ receipts.delete(id);
1357
+ throw error;
1358
+ }
1359
+ },
1360
+ clear() {
1361
+ permissions.clear();
1362
+ receipts.clear();
1363
+ }
1364
+ };
1365
+ }
1366
+ function stableStringify(value) {
1367
+ if (value === null || typeof value !== "object")
1368
+ return JSON.stringify(value);
1369
+ if (Array.isArray(value))
1370
+ return `[${value.map(stableStringify).join(",")}]`;
1371
+ const record = value;
1372
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
1373
+ }
1374
+
1375
+ // src/memory.ts
1376
+ class DefaultMemoryDatabase {
1377
+ tables = new Map;
1378
+ version = 0;
1379
+ current = new AsyncLocalStorage2;
1380
+ get(table, key) {
1381
+ if (this.current.getStore())
1382
+ return this.current.getStore()?.get(table, key);
1383
+ const value = this.tables.get(table)?.get(key);
1384
+ return value === undefined ? undefined : cloneValue(value);
1385
+ }
1386
+ set(table, key, value) {
1387
+ const current = this.current.getStore();
1388
+ if (current)
1389
+ return current.set(table, key, value);
1390
+ const rows = this.tables.get(table) ?? new Map;
1391
+ rows.set(key, cloneValue(value));
1392
+ this.tables.set(table, rows);
1393
+ this.version += 1;
1394
+ }
1395
+ delete(table, key) {
1396
+ const current = this.current.getStore();
1397
+ if (current)
1398
+ return current.delete(table, key);
1399
+ const deleted = this.tables.get(table)?.delete(key) ?? false;
1400
+ if (deleted)
1401
+ this.version += 1;
1402
+ return deleted;
1403
+ }
1404
+ list(table) {
1405
+ const current = this.current.getStore();
1406
+ if (current)
1407
+ return current.list(table);
1408
+ return [...this.tables.get(table)?.entries() ?? []].map(([key, value]) => ({ key, value: cloneValue(value) })).sort((left, right) => left.key.localeCompare(right.key));
1409
+ }
1410
+ clear() {
1411
+ const current = this.current.getStore();
1412
+ if (current)
1413
+ return current.clear();
1414
+ this.tables.clear();
1415
+ this.version += 1;
1416
+ }
1417
+ async transaction(work) {
1418
+ if (this.current.getStore())
1419
+ throw new Error("Nested memory transactions are not supported");
1420
+ const baseVersion = this.version;
1421
+ const snapshot = cloneTables(this.tables);
1422
+ const transaction = new SnapshotMemoryDatabase(snapshot);
1423
+ try {
1424
+ const result = await this.current.run(transaction, () => work(transaction));
1425
+ if (this.version !== baseVersion) {
1426
+ throw new Error("Memory transaction conflict: state changed during transaction");
1427
+ }
1428
+ const committed = cloneTables(transaction.tables);
1429
+ this.tables.clear();
1430
+ for (const [table, rows] of committed)
1431
+ this.tables.set(table, rows);
1432
+ this.version += 1;
1433
+ return result;
1434
+ } finally {
1435
+ transaction.close();
1436
+ }
1437
+ }
1438
+ }
1439
+
1440
+ class SnapshotMemoryDatabase {
1441
+ tables;
1442
+ closed = false;
1443
+ constructor(tables) {
1444
+ this.tables = tables;
1445
+ }
1446
+ close() {
1447
+ this.closed = true;
1448
+ }
1449
+ assertOpen() {
1450
+ if (this.closed)
1451
+ throw new Error("Memory transaction is closed");
1452
+ }
1453
+ get(table, key) {
1454
+ this.assertOpen();
1455
+ const value = this.tables.get(table)?.get(key);
1456
+ return value === undefined ? undefined : cloneValue(value);
1457
+ }
1458
+ set(table, key, value) {
1459
+ this.assertOpen();
1460
+ const rows = this.tables.get(table) ?? new Map;
1461
+ rows.set(key, cloneValue(value));
1462
+ this.tables.set(table, rows);
1463
+ }
1464
+ delete(table, key) {
1465
+ this.assertOpen();
1466
+ return this.tables.get(table)?.delete(key) ?? false;
1467
+ }
1468
+ list(table) {
1469
+ this.assertOpen();
1470
+ return [...this.tables.get(table)?.entries() ?? []].map(([key, value]) => ({ key, value: cloneValue(value) })).sort((left, right) => left.key.localeCompare(right.key));
1471
+ }
1472
+ clear() {
1473
+ this.assertOpen();
1474
+ this.tables.clear();
1475
+ }
1476
+ transaction() {
1477
+ return Promise.reject(new Error("Nested memory transactions are not supported"));
1478
+ }
1479
+ }
1480
+
1481
+ class DefaultMemoryStorage {
1482
+ objects = new Map;
1483
+ pendingFailure;
1484
+ policy;
1485
+ put(bucket, key, body, options = {}) {
1486
+ this.check("put", bucket, key);
1487
+ this.objects.set(storageKey(bucket, key), {
1488
+ bucket,
1489
+ key,
1490
+ body: typeof body === "string" ? new TextEncoder().encode(body) : new Uint8Array(body),
1491
+ contentType: options.contentType,
1492
+ metadata: { ...options.metadata ?? {} }
1493
+ });
1494
+ }
1495
+ get(bucket, key) {
1496
+ this.check("get", bucket, key);
1497
+ const object = this.objects.get(storageKey(bucket, key));
1498
+ return object ? cloneObject(object) : undefined;
1499
+ }
1500
+ delete(bucket, key) {
1501
+ this.check("delete", bucket, key);
1502
+ return this.objects.delete(storageKey(bucket, key));
1503
+ }
1504
+ list(bucket, prefix = "") {
1505
+ this.check("list", bucket, prefix);
1506
+ return [...this.objects.values()].filter((object) => object.bucket === bucket && object.key.startsWith(prefix)).filter((object) => !this.policy || this.policy("get", object.bucket, object.key)).sort((left, right) => left.key.localeCompare(right.key)).map(cloneObject);
1507
+ }
1508
+ clear() {
1509
+ this.objects.clear();
1510
+ this.pendingFailure = undefined;
1511
+ }
1512
+ failNext(error = new Error("Memory storage failure")) {
1513
+ this.pendingFailure = error;
1514
+ }
1515
+ setPolicy(policy) {
1516
+ this.policy = policy;
1517
+ }
1518
+ check(operation, bucket, key) {
1519
+ if (this.pendingFailure) {
1520
+ const error = this.pendingFailure;
1521
+ this.pendingFailure = undefined;
1522
+ throw error;
1523
+ }
1524
+ if (this.policy && !this.policy(operation, bucket, key)) {
1525
+ throw new ApplicationError("Memory storage access denied", { status: 403, code: "MEMORY_STORAGE_DENIED" });
1526
+ }
1527
+ }
1528
+ }
1529
+ function createMemorySandbox(options = {}) {
1530
+ const db = new DefaultMemoryDatabase;
1531
+ const storage = new DefaultMemoryStorage;
1532
+ const policy = createMemoryPolicy();
1533
+ const audit = [];
1534
+ const governance = {
1535
+ authorize(invocation) {
1536
+ const subject = policy.subject(invocation.requestContext);
1537
+ if (!invocation.command.permission || !policy.can(subject, invocation.command.permission)) {
1538
+ throw new ApplicationError("Memory permission denied", { status: 403, code: "MEMORY_PERMISSION_DENIED" });
1539
+ }
1540
+ },
1541
+ idempotency(invocation, next) {
1542
+ return policy.runOnce(policy.subject(invocation.requestContext), invocation.command.name, requireIdempotencyKey(invocation), memoryCommandInput(invocation), next);
1543
+ },
1544
+ transaction(_invocation, next) {
1545
+ const count = audit.length;
1546
+ return db.transaction(() => next()).catch((error) => {
1547
+ audit.splice(count);
1548
+ throw error;
1549
+ });
1550
+ },
1551
+ audit: {
1552
+ succeeded(invocation) {
1553
+ audit.push({ command: invocation.command.name, outcome: "succeeded" });
1554
+ },
1555
+ failed(invocation) {
1556
+ audit.push({ command: invocation.command.name, outcome: "failed" });
1557
+ }
1558
+ }
1559
+ };
1560
+ const identity = options.identity ?? { authenticated: false };
1561
+ const requestId = options.requestId ?? "memory-request";
1562
+ const configuredContext = options.requestContext;
1563
+ const app = createApplication({
1564
+ ...options,
1565
+ commandGovernance: options.commandGovernance ?? (options.memoryGovernance ? governance : undefined),
1566
+ deps: {
1567
+ ...options.deps ?? {},
1568
+ dbClient: db,
1569
+ memoryDb: db,
1570
+ storage,
1571
+ memoryStorage: storage,
1572
+ memoryPolicy: policy
1573
+ },
1574
+ requestContext: configuredContext ?? ((request) => ({
1575
+ requestId: request.headers.get("x-request-id") ?? requestId,
1576
+ request,
1577
+ identity
1578
+ }))
1579
+ });
1580
+ return {
1581
+ app,
1582
+ db,
1583
+ storage,
1584
+ policy,
1585
+ audit,
1586
+ identity,
1587
+ request(path, init = {}) {
1588
+ const url = path.startsWith("http://") || path.startsWith("https://") ? path : `http://memory.local${path.startsWith("/") ? path : `/${path}`}`;
1589
+ return app.handle(new Request(url, init));
1590
+ },
1591
+ reset() {
1592
+ db.clear();
1593
+ storage.clear();
1594
+ policy.clear();
1595
+ audit.length = 0;
1596
+ }
1597
+ };
1598
+ }
1599
+ function memoryCommandInput(invocation) {
1600
+ const input = invocation.input;
1601
+ if (typeof input !== "object" || input === null)
1602
+ return input;
1603
+ const ignoredHeaders = new Set(["authorization", "idempotency-key", "x-request-id", "traceparent", "tracestate"]);
1604
+ const headers = Object.fromEntries([...invocation.request.headers.entries()].filter(([name]) => !ignoredHeaders.has(name)));
1605
+ return {
1606
+ method: invocation.request.method,
1607
+ path: new URL(invocation.request.url).pathname,
1608
+ body: "body" in input ? input.body : undefined,
1609
+ params: "params" in input ? input.params : undefined,
1610
+ query: "query" in input ? input.query : undefined,
1611
+ headers
1612
+ };
1613
+ }
1614
+ function storageKey(bucket, key) {
1615
+ return JSON.stringify([bucket, key]);
1616
+ }
1617
+ function cloneObject(object) {
1618
+ return {
1619
+ ...object,
1620
+ body: new Uint8Array(object.body),
1621
+ metadata: { ...object.metadata }
1622
+ };
1623
+ }
1624
+ function cloneTables(tables) {
1625
+ return new Map([...tables.entries()].map(([table, rows]) => [
1626
+ table,
1627
+ new Map([...rows.entries()].map(([key, value]) => [key, cloneValue(value)]))
1628
+ ]));
1629
+ }
1630
+ function cloneValue(value) {
1631
+ return structuredClone(value);
1632
+ }
1633
+ // src/worker.ts
1634
+ import { PendingWorkRegistry } from "@supacloud/app/runtime";
1635
+ function workerFailureMessage(error) {
1636
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "Worker job failed";
1637
+ const normalized = message.replace(/[\u0000-\u001f\u007f]/g, " ").trim();
1638
+ return (normalized || "Worker job failed").slice(0, 4096);
1639
+ }
1640
+ function createQueueWorkerTransport(options) {
1641
+ if (!options.queue || typeof options.queue.receive !== "function" || typeof options.queue.ack !== "function" || typeof options.queue.fail !== "function" || typeof options.decodeClaim !== "function" || typeof options.messageId !== "function") {
1642
+ throw new TypeError("Queue worker transport requires queue, decodeClaim and messageId");
1643
+ }
1644
+ const receiveOptions = options.receive === undefined ? undefined : { ...options.receive };
1645
+ return {
1646
+ claim: async (signal) => {
1647
+ signal.throwIfAborted();
1648
+ const message = await options.queue.receive(receiveOptions);
1649
+ signal.throwIfAborted();
1650
+ return message === null ? null : options.decodeClaim(message);
1651
+ },
1652
+ ack: (claim) => options.queue.ack(options.messageId(claim)),
1653
+ fail: (claim, error) => options.queue.fail(options.messageId(claim), {
1654
+ error: workerFailureMessage(error)
1655
+ })
1656
+ };
1657
+ }
1658
+
1659
+ class WorkerRegistrationError extends Error {
1660
+ code;
1661
+ constructor(code, message) {
1662
+ super(message);
1663
+ this.name = "WorkerRegistrationError";
1664
+ this.code = code;
1665
+ }
1666
+ }
1667
+
1668
+ class WorkerReceiptUnconfirmedError extends Error {
1669
+ operation;
1670
+ claimId;
1671
+ code = "WORKER_RECEIPT_UNCONFIRMED";
1672
+ mutationMayHaveApplied = true;
1673
+ constructor(operation, claimId) {
1674
+ super(`Worker ${operation} receipt could not be confirmed for claim "${claimId}"`);
1675
+ this.operation = operation;
1676
+ this.claimId = claimId;
1677
+ this.name = "WorkerReceiptUnconfirmedError";
1678
+ }
1679
+ }
1680
+ function safeWorkerId(value) {
1681
+ const workerId = value ?? `worker-${crypto.randomUUID()}`;
1682
+ if (workerId.length === 0 || workerId.length > 256 || /[\u0000-\u001f\u007f]/.test(workerId)) {
1683
+ throw new TypeError("Worker workerId must be a safe non-empty string");
1684
+ }
1685
+ return workerId;
1686
+ }
1687
+ function safeDescriptorText(value, maxLength) {
1688
+ return typeof value === "string" && value.trim().length > 0 && value.length <= maxLength && !/[\u0000-\u001f\u007f]/.test(value);
1689
+ }
1690
+ function validJobScope(value) {
1691
+ return value === "application" || value === "request" || value === "job";
1692
+ }
1693
+ function validJobMode(value) {
1694
+ return value === "task" || value === "workflow";
1695
+ }
1696
+ function validJobIdempotency(value) {
1697
+ return value === "required" || value === "none";
1698
+ }
1699
+ function validPositiveInteger(value) {
1700
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1701
+ }
1702
+ function safeClaim(claim) {
1703
+ if (!claim || typeof claim !== "object") {
1704
+ throw new WorkerRegistrationError("WORKER_INVALID_JOB", "Worker claim is invalid");
1705
+ }
1706
+ if (typeof claim.id !== "string" || claim.id.length === 0 || claim.id.length > 512 || /[\u0000-\u001f\u007f]/.test(claim.id) || typeof claim.jobName !== "string" || claim.jobName.length === 0 || claim.jobName.length > 256 || /[\u0000-\u001f\u007f]/.test(claim.jobName)) {
1707
+ throw new WorkerRegistrationError("WORKER_INVALID_JOB", "Worker claim identity is invalid");
1708
+ }
1709
+ const attempt = claim.attempt ?? 1;
1710
+ if (!Number.isSafeInteger(attempt) || attempt < 1) {
1711
+ throw new WorkerRegistrationError("WORKER_INVALID_JOB", "Worker claim attempt is invalid");
1712
+ }
1713
+ return { ...claim, attempt };
1714
+ }
1715
+ function delay(milliseconds, signal) {
1716
+ if (milliseconds <= 0)
1717
+ return Promise.resolve();
1718
+ return new Promise((resolve, reject) => {
1719
+ let settled = false;
1720
+ const finish = (callback) => {
1721
+ if (settled)
1722
+ return;
1723
+ settled = true;
1724
+ clearTimeout(timer);
1725
+ signal.removeEventListener("abort", onAbort);
1726
+ callback();
1727
+ };
1728
+ const onAbort = () => finish(() => reject(signal.reason ?? new DOMException("Aborted", "AbortError")));
1729
+ const timer = setTimeout(() => finish(resolve), milliseconds);
1730
+ signal.addEventListener("abort", onAbort, { once: true });
1731
+ if (signal.aborted)
1732
+ onAbort();
1733
+ });
1734
+ }
1735
+ async function destroyServiceValues(services) {
1736
+ const errors = [];
1737
+ const seen = new Set;
1738
+ for (const value of Object.values(services).reverse()) {
1739
+ if (seen.has(value) || !value || typeof value !== "object")
1740
+ continue;
1741
+ seen.add(value);
1742
+ const candidate = value;
1743
+ const hook = typeof candidate.onDestroy === "function" ? candidate.onDestroy : typeof candidate.ngOnDestroy === "function" ? candidate.ngOnDestroy : undefined;
1744
+ if (!hook)
1745
+ continue;
1746
+ try {
1747
+ await Reflect.apply(hook, value, []);
1748
+ } catch (error) {
1749
+ errors.push(error);
1750
+ }
1751
+ }
1752
+ if (errors.length > 0)
1753
+ throw new AggregateError(errors, "Worker service destruction failed");
1754
+ }
1755
+
1756
+ class SupaCloudWorker {
1757
+ registry = new Map;
1758
+ modules = [];
1759
+ moduleServices = new Map;
1760
+ deps;
1761
+ transport;
1762
+ mapClaim;
1763
+ requestContextFactory;
1764
+ workerId;
1765
+ concurrency;
1766
+ pollIntervalMs;
1767
+ shutdownTimeoutMs;
1768
+ work = new PendingWorkRegistry;
1769
+ get pendingWork() {
1770
+ return this.work;
1771
+ }
1772
+ executor;
1773
+ observer;
1774
+ onError;
1775
+ destroyServices;
1776
+ stateValue = "idle";
1777
+ claimController;
1778
+ loopPromise;
1779
+ startPromise;
1780
+ stopPromise;
1781
+ stopRequested = false;
1782
+ inFlight = new Set;
1783
+ services = {};
1784
+ imported = {};
1785
+ constructor(options) {
1786
+ if (!options.transport || typeof options.transport.claim !== "function" || typeof options.transport.fail !== "function" || typeof options.transport.ack !== "function" && typeof options.transport.acknowledge !== "function") {
1787
+ throw new WorkerRegistrationError("WORKER_TRANSPORT_INVALID", "Worker transport must provide claim, ack and fail");
1788
+ }
1789
+ this.transport = options.transport;
1790
+ this.deps = options.deps ?? {};
1791
+ this.workerId = safeWorkerId(options.workerId);
1792
+ this.mapClaim = options.mapClaim ?? ((claim) => claim);
1793
+ this.requestContextFactory = options.requestContext ?? ((claim, signal) => ({
1794
+ workerId: this.workerId,
1795
+ jobId: claim.id,
1796
+ jobName: claim.jobName,
1797
+ attempt: claim.attempt,
1798
+ signal
1799
+ }));
1800
+ this.concurrency = this.capturePositiveInteger(options.concurrency, 1, 1000, "concurrency");
1801
+ this.pollIntervalMs = this.captureNonNegativeInteger(options.pollIntervalMs, 1000, 300000, "pollIntervalMs");
1802
+ this.shutdownTimeoutMs = this.captureNonNegativeInteger(options.shutdownTimeoutMs, 5000, 2147483647, "shutdownTimeoutMs");
1803
+ this.executor = options.executor;
1804
+ this.observer = options.onExecution;
1805
+ this.onError = options.onError;
1806
+ this.destroyServices = options.destroyServices;
1807
+ for (const module of options.modules ?? [])
1808
+ this.registerModule(module);
1809
+ }
1810
+ get state() {
1811
+ return this.stateValue;
1812
+ }
1813
+ get id() {
1814
+ return this.workerId;
1815
+ }
1816
+ get jobNames() {
1817
+ return Object.freeze([...this.registry.keys()]);
1818
+ }
1819
+ get jobs() {
1820
+ return Object.freeze([...this.registry.values()].map((entry) => entry.job));
1821
+ }
1822
+ registerModule(module) {
1823
+ if (this.stateValue !== "idle" && this.stateValue !== "stopped") {
1824
+ throw new WorkerRegistrationError("WORKER_INVALID_JOB", "Jobs cannot be registered while the worker is active");
1825
+ }
1826
+ if (!module || typeof module !== "object" || typeof module.name !== "string" || module.name.length === 0 || module.name.length > 256 || /[\u0000-\u001f\u007f]/.test(module.name) || typeof module.createServices !== "function" || module.jobs !== undefined && !Array.isArray(module.jobs)) {
1827
+ throw new WorkerRegistrationError("WORKER_INVALID_JOB", "A registered module is invalid");
1828
+ }
1829
+ if (this.modules.some((candidate) => candidate.name === module.name)) {
1830
+ throw new WorkerRegistrationError("WORKER_DUPLICATE_MODULE", `Module "${module.name}" is registered more than once`);
1831
+ }
1832
+ const jobs = module.jobs ?? [];
1833
+ const names = new Set;
1834
+ for (const job of jobs) {
1835
+ if (!job || typeof job !== "object" || !safeDescriptorText(job.className, 256) || !safeDescriptorText(job.name, 256) || !safeDescriptorText(job.serviceKey, 256) || !validJobScope(job.scope) || job.mode !== undefined && !validJobMode(job.mode) || job.idempotency !== undefined && !validJobIdempotency(job.idempotency) || job.timeoutSec !== undefined && !validPositiveInteger(job.timeoutSec) || job.maxAttempts !== undefined && !validPositiveInteger(job.maxAttempts)) {
1836
+ throw new WorkerRegistrationError("WORKER_INVALID_JOB", "A registered Job has invalid identity or execution metadata");
1837
+ }
1838
+ if (this.registry.has(job.name) || names.has(job.name)) {
1839
+ throw new WorkerRegistrationError("WORKER_DUPLICATE_JOB", `Job "${job.name}" is registered more than once`);
1840
+ }
1841
+ names.add(job.name);
1842
+ }
1843
+ this.modules.push(module);
1844
+ for (const job of jobs)
1845
+ this.registry.set(job.name, { module, job });
1846
+ }
1847
+ register(module) {
1848
+ this.registerModule(module);
1849
+ }
1850
+ async start() {
1851
+ if (this.stateValue === "running")
1852
+ return;
1853
+ if (this.stateValue === "starting" && this.startPromise)
1854
+ return this.startPromise;
1855
+ if (this.stateValue === "stopping")
1856
+ await this.stop();
1857
+ this.stopRequested = false;
1858
+ if (this.work.closed)
1859
+ this.work = new PendingWorkRegistry;
1860
+ this.stateValue = "starting";
1861
+ const startPromise = this.work.run({ name: "worker.startup", kind: "startup" }, () => Promise.resolve().then(() => this.initialize())).then(async () => {
1862
+ if (this.stopRequested || this.stateValue !== "starting") {
1863
+ await this.releaseServices();
1864
+ return;
1865
+ }
1866
+ this.claimController = new AbortController;
1867
+ this.stateValue = "running";
1868
+ this.loopPromise = this.pollLoop(this.claimController.signal);
1869
+ }).catch(async (error) => {
1870
+ this.stateValue = "stopped";
1871
+ await this.releaseServices();
1872
+ throw error;
1873
+ });
1874
+ this.startPromise = startPromise;
1875
+ return startPromise;
1876
+ }
1877
+ async stop() {
1878
+ if (this.stateValue === "idle" || this.stateValue === "stopped")
1879
+ return;
1880
+ if (this.stopPromise)
1881
+ return this.stopPromise;
1882
+ this.stopRequested = true;
1883
+ this.stateValue = "stopping";
1884
+ this.work.close();
1885
+ const startPromise = this.startPromise;
1886
+ this.stopPromise = Promise.resolve().then(async () => {
1887
+ this.claimController?.abort(new DOMException("Worker stopped", "AbortError"));
1888
+ this.work.dispose();
1889
+ await this.work.waitForIdle({ timeoutMs: this.shutdownTimeoutMs });
1890
+ await startPromise?.catch(() => {
1891
+ return;
1892
+ });
1893
+ await this.loopPromise?.catch((error) => this.reportError(error));
1894
+ await Promise.allSettled([...this.inFlight]);
1895
+ await this.releaseServices();
1896
+ this.stateValue = "stopped";
1897
+ this.claimController = undefined;
1898
+ this.loopPromise = undefined;
1899
+ this.startPromise = undefined;
1900
+ this.stopPromise = undefined;
1901
+ }).catch((error) => {
1902
+ this.stopPromise = undefined;
1903
+ throw error;
1904
+ });
1905
+ return this.stopPromise;
1906
+ }
1907
+ async runOnce() {
1908
+ if (this.stateValue !== "running") {
1909
+ throw new WorkerRegistrationError("WORKER_NOT_STARTED", "Worker must be started before runOnce");
1910
+ }
1911
+ const controller = this.claimController;
1912
+ if (!controller)
1913
+ throw new WorkerRegistrationError("WORKER_NOT_STARTED", "Worker claim lifecycle is unavailable");
1914
+ controller.signal.throwIfAborted();
1915
+ return this.work.run({ name: "worker.claim", kind: "job" }, async (signal) => {
1916
+ const claim = await this.transport.claim(controller.signal);
1917
+ return claim === null ? null : this.executeClaim(claim, signal);
1918
+ });
1919
+ }
1920
+ async processClaim(rawClaim) {
1921
+ return this.work.run({ name: "worker.job", kind: "job" }, (signal) => this.executeClaim(rawClaim, signal));
1922
+ }
1923
+ async executeClaim(rawClaim, signal) {
1924
+ const claim = safeClaim(this.mapClaim(rawClaim));
1925
+ const entry = this.registry.get(claim.jobName);
1926
+ const context = Object.freeze({
1927
+ jobId: claim.id,
1928
+ jobName: claim.jobName,
1929
+ attempt: claim.attempt ?? 1,
1930
+ signal: new AbortController().signal
1931
+ });
1932
+ if (!entry) {
1933
+ const receipt = await this.failClaim(rawClaim, claim, new WorkerRegistrationError("WORKER_INVALID_JOB", `Job "${claim.jobName}" is not registered`), context);
1934
+ return { claimId: claim.id, jobName: claim.jobName, status: "failed", receipt };
1935
+ }
1936
+ let output;
1937
+ try {
1938
+ if (this.stateValue !== "running" && this.stateValue !== "stopping") {
1939
+ throw new WorkerRegistrationError("WORKER_NOT_STARTED", "Worker is not active");
1940
+ }
1941
+ const requestContext = claim.requestContext ?? await this.requestContextFactory(claim, signal);
1942
+ const moduleServices = this.moduleServices.get(entry.module.name);
1943
+ if (!moduleServices)
1944
+ throw new WorkerRegistrationError("WORKER_NOT_STARTED", "Worker services are unavailable");
1945
+ output = await executeJob(entry.module, moduleServices, entry.job, claim.input, requestContext, this.imported, this.executor, this.observer);
1946
+ } catch (error) {
1947
+ const receipt = await this.failClaim(rawClaim, claim, error, context);
1948
+ return { claimId: claim.id, jobName: claim.jobName, status: "failed", receipt };
1949
+ }
1950
+ const acknowledge = this.transport.ack ?? this.transport.acknowledge;
1951
+ if (!acknowledge)
1952
+ throw new WorkerRegistrationError("WORKER_TRANSPORT_INVALID", "Worker acknowledgement is unavailable");
1953
+ try {
1954
+ const receipt = await acknowledge(rawClaim, output, context);
1955
+ return { claimId: claim.id, jobName: claim.jobName, status: "acknowledged", receipt };
1956
+ } catch {
1957
+ throw new WorkerReceiptUnconfirmedError("ack", claim.id);
1958
+ }
1959
+ }
1960
+ async failClaim(rawClaim, claim, error, context) {
1961
+ try {
1962
+ return await this.transport.fail(rawClaim, error, context);
1963
+ } catch {
1964
+ throw new WorkerReceiptUnconfirmedError("fail", claim.id);
1965
+ }
1966
+ }
1967
+ async initialize() {
1968
+ this.services = {};
1969
+ this.imported = {};
1970
+ this.moduleServices.clear();
1971
+ for (const module of this.modules) {
1972
+ const services = module.createServices(this.deps, this.imported);
1973
+ this.moduleServices.set(module.name, services);
1974
+ this.services = { ...this.services, ...services };
1975
+ this.imported[module.name] = services;
1976
+ }
1977
+ }
1978
+ async releaseServices() {
1979
+ const services = this.services;
1980
+ const imported = this.imported;
1981
+ this.services = {};
1982
+ this.imported = {};
1983
+ this.moduleServices.clear();
1984
+ if (Object.keys(services).length === 0)
1985
+ return;
1986
+ try {
1987
+ if (this.destroyServices)
1988
+ await this.destroyServices(services, imported);
1989
+ else
1990
+ await destroyServiceValues(services);
1991
+ } catch (error) {
1992
+ await this.reportError(error);
1993
+ }
1994
+ }
1995
+ async pollLoop(signal) {
1996
+ while (!signal.aborted && this.stateValue === "running") {
1997
+ if (this.inFlight.size >= this.concurrency) {
1998
+ await Promise.race(this.inFlight).catch((error) => this.reportError(error));
1999
+ continue;
2000
+ }
2001
+ const complete = this.work.add({ name: "worker.claim", kind: "job" });
2002
+ let claim;
2003
+ try {
2004
+ claim = await this.transport.claim(signal);
2005
+ } catch (error) {
2006
+ complete();
2007
+ if (signal.aborted)
2008
+ break;
2009
+ await this.reportError(error);
2010
+ await delay(this.pollIntervalMs, signal).catch(() => {
2011
+ return;
2012
+ });
2013
+ continue;
2014
+ }
2015
+ if (claim === null) {
2016
+ complete();
2017
+ await delay(this.pollIntervalMs, signal).catch(() => {
2018
+ return;
2019
+ });
2020
+ continue;
2021
+ }
2022
+ const execution = this.executeClaim(claim, this.work.signal).catch((error) => this.reportError(error)).finally(complete);
2023
+ this.inFlight.add(execution);
2024
+ execution.finally(() => this.inFlight.delete(execution));
2025
+ }
2026
+ }
2027
+ async reportError(error) {
2028
+ try {
2029
+ await this.onError?.(error);
2030
+ } catch {}
2031
+ }
2032
+ capturePositiveInteger(value, fallback, max, name) {
2033
+ const result = value ?? fallback;
2034
+ if (!Number.isSafeInteger(result) || result < 1 || result > max)
2035
+ throw new TypeError(`Worker ${name} is invalid`);
2036
+ return result;
2037
+ }
2038
+ captureNonNegativeInteger(value, fallback, max, name) {
2039
+ const result = value ?? fallback;
2040
+ if (!Number.isSafeInteger(result) || result < 0 || result > max)
2041
+ throw new TypeError(`Worker ${name} is invalid`);
2042
+ return result;
2043
+ }
2044
+ }
2045
+ function createWorker(options) {
2046
+ return new SupaCloudWorker(options);
2047
+ }
2048
+
2049
+ // src/index.ts
2050
+ setupTypebox();
2051
+ var VERIFIED_JWT_SUBJECT_HEADER = "x-supacloud-jwt-sub";
2052
+ var EXECUTION_ID_HEADER = "x-sb-execution-id";
2053
+ var IDEMPOTENCY_KEY_HEADER = "idempotency-key";
2054
+ var idempotencyKeyPattern = /^[A-Za-z0-9._:-]{1,512}$/;
2055
+ function composeAspects(...aspects) {
2056
+ const active = aspects.filter((aspect) => typeof aspect === "function");
2057
+ if (active.length === 0)
2058
+ return (_context, next) => next();
2059
+ return (context, next) => {
2060
+ let index = -1;
2061
+ const dispatch = (current) => {
2062
+ if (current <= index) {
2063
+ return Promise.reject(new Error("next() called multiple times"));
2064
+ }
2065
+ index = current;
2066
+ const aspect = active[current];
2067
+ if (!aspect)
2068
+ return Promise.resolve(next());
2069
+ return Promise.resolve(aspect(context, () => dispatch(current + 1)));
2070
+ };
2071
+ return dispatch(0);
2072
+ };
2073
+ }
2074
+ function observedAspects(aspects, boundary, observer) {
2075
+ return composeAspects(...aspects.map((aspect, index) => (context, next) => observeExecution(observer, {
2076
+ kind: context.kind,
2077
+ operation: context.name,
2078
+ stage: `${boundary}.aspect[${index}]:${aspect.name || "anonymous"}`,
2079
+ ...executionTrace(context.requestContext)
2080
+ }, () => aspect(context, next))));
2081
+ }
2082
+ function descriptorPipeline(descriptor, boundary, observer) {
2083
+ const pipeline = descriptor.aspectPipeline;
2084
+ if (!pipeline)
2085
+ return observedAspects(descriptor.aspects ?? [], boundary, observer);
2086
+ return (context, next) => pipeline(context, next, observer ? (stage, run) => observeExecution(observer, {
2087
+ kind: context.kind,
2088
+ operation: context.name,
2089
+ stage: `${boundary}.${stage}`,
2090
+ ...executionTrace(context.requestContext)
2091
+ }, run) : undefined);
2092
+ }
2093
+ function createCommandAuthorizationAdapter(options) {
2094
+ return async (invocation) => {
2095
+ const permission = invocation.command.permission;
2096
+ if (!permission || !/^[a-z][a-z0-9._-]*:[a-z][a-z0-9._-]*$/.test(permission)) {
2097
+ throw new ApplicationError("Command permission must use resource:action syntax", {
2098
+ status: 500,
2099
+ code: "COMMAND_PERMISSION_INVALID"
2100
+ });
2101
+ }
2102
+ const context = invocation.requestContext;
2103
+ const identity = isRecord2(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
2104
+ if (!isAuthenticatedTrustedIdentity(identity)) {
2105
+ throw new ApplicationError("Authentication required", { status: 401, code: "AUTHENTICATION_REQUIRED" });
2106
+ }
2107
+ const request = {
2108
+ principal: { kind: "user", issuer: options.issuer, subject: identity.subject },
2109
+ applicationId: options.applicationId,
2110
+ domain: options.domain(invocation)
2111
+ };
2112
+ let resolved;
2113
+ try {
2114
+ resolved = await options.resolve(request);
2115
+ } catch {
2116
+ throw new ApplicationError("Authorization is unavailable", { status: 503, code: "AUTHORIZATION_UNAVAILABLE" });
2117
+ }
2118
+ if (!isRecord2(resolved) || !Array.isArray(resolved.permissions) || !resolved.permissions.every((value) => typeof value === "string") || resolved.permissionCatalogVersion !== undefined && typeof resolved.permissionCatalogVersion !== "string" || resolved.permissionCatalogDigest !== undefined && typeof resolved.permissionCatalogDigest !== "string" || resolved.applicationId !== options.applicationId || options.catalog !== undefined && (resolved.permissionCatalogVersion !== options.catalog.version || options.catalog.digest !== undefined && resolved.permissionCatalogDigest !== options.catalog.digest)) {
2119
+ throw new ApplicationError("Authorization context is not bound to this application", {
2120
+ status: 503,
2121
+ code: "AUTHORIZATION_CONTEXT_INVALID"
2122
+ });
2123
+ }
2124
+ if (!resolved.permissions.includes(permission)) {
2125
+ throw new ApplicationError("Permission denied", { status: 403, code: "PERMISSION_DENIED" });
2126
+ }
2127
+ };
2128
+ }
2129
+ function composeCommandExecutors(...executors) {
2130
+ const active = executors.filter((e) => typeof e === "function");
2131
+ if (active.length === 0)
2132
+ return (_inv, next) => next();
2133
+ return (invocation, next) => {
2134
+ let index = -1;
2135
+ const dispatch = (i) => {
2136
+ if (i <= index) {
2137
+ return Promise.reject(new Error("next() called multiple times"));
2138
+ }
2139
+ index = i;
2140
+ if (i === active.length) {
2141
+ return Promise.resolve(next());
2142
+ }
2143
+ const fn = active[i];
2144
+ if (!fn) {
2145
+ return Promise.resolve(next());
2146
+ }
2147
+ return Promise.resolve(fn(invocation, () => dispatch(i + 1)));
2148
+ };
2149
+ return dispatch(0);
2150
+ };
2151
+ }
2152
+
2153
+ class ApplicationError extends Error {
2154
+ expose = true;
2155
+ status;
2156
+ code;
2157
+ details;
2158
+ metadata;
2159
+ constructor(message, options = {}) {
2160
+ super(message);
2161
+ this.name = "ApplicationError";
2162
+ this.status = options.status ?? 500;
2163
+ this.code = options.code ?? "INTERNAL_ERROR";
2164
+ this.details = options.details;
2165
+ this.metadata = options.metadata;
2166
+ }
2167
+ }
2168
+ function validatedJsonResponse(validate, value, init) {
2169
+ if (init?.status === 204 || init?.status === 205 || init?.status === 304) {
2170
+ throw new TypeError("JSON responses cannot use a null-body status");
2171
+ }
2172
+ let body;
2173
+ try {
2174
+ const serialized = JSON.stringify(value);
2175
+ if (serialized === undefined || validate(JSON.parse(serialized)) !== true) {
2176
+ throw new Error("Invalid JSON response");
2177
+ }
2178
+ body = serialized;
2179
+ } catch {
2180
+ throw new ApplicationError("Response validation failed", {
2181
+ status: 500,
2182
+ code: "RESPONSE_VALIDATION_ERROR"
2183
+ });
2184
+ }
2185
+ const headers = new Headers(init?.headers);
2186
+ if (!headers.has("content-type"))
2187
+ headers.set("content-type", "application/json");
2188
+ return new Response(body, { ...init, headers });
2189
+ }
2190
+ var applicationErrorDictionary = {
2191
+ ApplicationError,
2192
+ SchemaContractError
2193
+ };
2194
+ function frameworkErrorCode(error) {
2195
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code.toUpperCase().replaceAll("-", "_") : "UNKNOWN";
2196
+ }
2197
+ var httpPluginIds = new WeakMap;
2198
+ var nextHttpPluginId = 0;
2199
+ function contextPlugin(http) {
2200
+ let seed = http ? httpPluginIds.get(http) : 0;
2201
+ if (http && seed === undefined) {
2202
+ seed = ++nextHttpPluginId;
2203
+ httpPluginIds.set(http, seed);
2204
+ }
2205
+ return new Elysia3({ name: "supacloud:http-context", seed }).use(http ?? new Elysia3).as("plugin");
2206
+ }
2207
+ function mountHttp(http, name, normalize = true) {
2208
+ return new Elysia3({ name, normalize }).use(contextPlugin(http));
2209
+ }
2210
+ function resolveCompiledCommand(module, reference) {
2211
+ const matches = (module.commands ?? []).filter((command) => command.className === reference || command.name === reference);
2212
+ return matches.length === 1 ? matches[0] : undefined;
2213
+ }
2214
+ function decodeJobContract(schema, value, boundary) {
2215
+ if (schema === undefined)
2216
+ return value;
2217
+ try {
2218
+ return createSchemaDecoder(schema)(value);
2219
+ } catch {
2220
+ const input = boundary === "input";
2221
+ throw new ApplicationError(input ? "Job input contract validation failed" : "Job output contract validation failed", {
2222
+ status: input ? 422 : 500,
2223
+ code: input ? "JOB_INPUT_VALIDATION_ERROR" : "JOB_OUTPUT_VALIDATION_ERROR"
2224
+ });
2225
+ }
2226
+ }
2227
+ function safeHeaderValue(value, maxLength) {
2228
+ if (!value || value.length > maxLength || /[\u0000-\u001f\u007f]/.test(value)) {
2229
+ return;
2230
+ }
2231
+ return value;
2232
+ }
2233
+ function isRecord2(value) {
2234
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2235
+ }
2236
+ function isPromiseLike(value) {
2237
+ return value instanceof Promise;
2238
+ }
2239
+ function isTrustedIdentity(value) {
2240
+ return isRecord2(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2241
+ }
2242
+ function isAuthenticatedTrustedIdentity(value) {
2243
+ return value?.authenticated === true && typeof value.subject === "string" && value.subject.length > 0 && typeof value.accessToken === "string" && value.accessToken.length > 0;
2244
+ }
2245
+ function bearerToken(request) {
2246
+ const authorization = request.headers.get("authorization");
2247
+ const match = authorization?.match(/^Bearer\s+(.+)$/i);
2248
+ return match?.[1] ? safeHeaderValue(match[1], 16384) : undefined;
2249
+ }
2250
+ var createSupaCloudRequestContext = (request) => {
2251
+ const subject = safeHeaderValue(request.headers.get(VERIFIED_JWT_SUBJECT_HEADER), 1024);
2252
+ const accessToken = subject ? bearerToken(request) : undefined;
2253
+ const requestId = httpRequestId(request) ?? safeHeaderValue(request.headers.get(EXECUTION_ID_HEADER), 256) ?? safeHeaderValue(request.headers.get("x-request-id"), 256) ?? crypto.randomUUID();
2254
+ const idempotencyKey = safeHeaderValue(request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2255
+ const identity = {
2256
+ authenticated: subject !== undefined,
2257
+ ...subject === undefined ? {} : { subject }
2258
+ };
2259
+ if (accessToken !== undefined) {
2260
+ Object.defineProperty(identity, "accessToken", {
2261
+ value: accessToken,
2262
+ enumerable: false,
2263
+ configurable: false
2264
+ });
2265
+ }
2266
+ return {
2267
+ requestId,
2268
+ request,
2269
+ identity,
2270
+ ...idempotencyKey === undefined ? {} : { idempotencyKey }
2271
+ };
2272
+ };
2273
+ var defaultRequestContext = createSupaCloudRequestContext;
2274
+ function missingGovernanceAdapter(command, adapter) {
2275
+ const codes = {
2276
+ idempotency: "COMMAND_IDEMPOTENCY_UNAVAILABLE",
2277
+ transaction: "COMMAND_TRANSACTION_UNAVAILABLE",
2278
+ audit: "COMMAND_AUDIT_UNAVAILABLE"
2279
+ };
2280
+ return new ApplicationError(`Command "${command.name}" requires a ${adapter} adapter`, {
2281
+ status: 501,
2282
+ code: codes[adapter]
2283
+ });
2284
+ }
2285
+ function selectCommandBranch(command, input) {
2286
+ if (!command.branches || command.branches.length === 0)
2287
+ return command;
2288
+ if (command.rpc !== undefined) {
2289
+ throw new ApplicationError(`Command "${command.name}" declares both rpc and branches`, {
2290
+ code: "COMMAND_BRANCHES_CONFLICT"
2291
+ });
2292
+ }
2293
+ for (const branch of command.branches) {
2294
+ const match = /^(?:([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*))\s*===\s*(["'])(.*)\2$/.exec(branch.when);
2295
+ if (!match) {
2296
+ throw new ApplicationError(`Command "${command.name}" has an invalid branch selector`, {
2297
+ code: "COMMAND_BRANCH_SELECTOR_INVALID"
2298
+ });
2299
+ }
2300
+ const path = match[1] ?? "";
2301
+ const parts = path.split(".");
2302
+ const root = parts[0];
2303
+ let value = root === "body" || root === "params" || root === "query" ? input[root] : input.body;
2304
+ for (const part of root === "body" || root === "params" || root === "query" ? parts.slice(1) : parts) {
2305
+ if (!isRecord2(value)) {
2306
+ value = undefined;
2307
+ break;
2308
+ }
2309
+ value = value[part];
2310
+ }
2311
+ if (value === match[3]) {
2312
+ return {
2313
+ ...command,
2314
+ rpc: branch.rpc,
2315
+ transaction: branch.transaction ?? "none",
2316
+ audit: branch.audit,
2317
+ idempotency: branch.idempotency ?? "none"
2318
+ };
2319
+ }
2320
+ }
2321
+ throw new ApplicationError(`Command "${command.name}" has no matching RPC branch`, {
2322
+ status: 422,
2323
+ code: "COMMAND_BRANCH_UNMATCHED"
2324
+ });
2325
+ }
2326
+ function validCommandBranchSelector(value) {
2327
+ return /^(?:[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*===\s*(["'])(.*)\1$/.test(value);
2328
+ }
2329
+ function createCommandExecutor(governance, observer) {
2330
+ return async (invocation, next) => {
2331
+ const command = selectCommandBranch(invocation.command, invocation.input);
2332
+ const selectedInvocation = command === invocation.command ? invocation : { ...invocation, command };
2333
+ for (const mode of [command.transaction, command.idempotency, command.tenantScope]) {
2334
+ if (mode !== undefined && mode !== "required" && mode !== "none") {
2335
+ throw new ApplicationError("Invalid command governance mode", { code: "COMMAND_MODE_INVALID" });
2336
+ }
2337
+ }
2338
+ if (command.tenantScope === "required") {
2339
+ try {
2340
+ requireFeatureRequestContext(invocation.requestContext);
2341
+ } catch {
2342
+ throw new ApplicationError("Feature request context is required for this command", {
2343
+ status: 401,
2344
+ code: "COMMAND_TENANT_CONTEXT_REQUIRED"
2345
+ });
2346
+ }
2347
+ }
2348
+ if (command.rpc !== undefined) {
2349
+ const adapter = Object.hasOwn(governance.rpc ?? {}, command.rpc) ? governance.rpc?.[command.rpc] : undefined;
2350
+ if (!adapter)
2351
+ throw new ApplicationError("RPC governance adapter unavailable", { code: "COMMAND_RPC_UNAVAILABLE", status: 501 });
2352
+ for (const capability of ["audit", "transaction", "idempotency"]) {
2353
+ const required = capability === "audit" ? !!command.audit : command[capability] === "required";
2354
+ if (required && adapter.capabilities[capability] !== true)
2355
+ throw missingGovernanceAdapter(command, capability);
2356
+ }
2357
+ const event = {
2358
+ kind: "command",
2359
+ operation: command.name,
2360
+ ...executionTrace(invocation.requestContext)
2361
+ };
2362
+ await observeExecution(observer, { ...event, stage: "authorize" }, () => governance.authorize(selectedInvocation));
2363
+ return observeExecution(observer, { ...event, stage: `rpc:${command.rpc}` }, () => adapter.execute(selectedInvocation, once(next)));
2364
+ }
2365
+ const audit = command.audit ? governance.audit : undefined;
2366
+ const transaction = command.transaction === "required" ? governance.transaction : undefined;
2367
+ const idempotency = command.idempotency === "required" ? governance.idempotency : undefined;
2368
+ if (command.audit && !audit) {
2369
+ throw missingGovernanceAdapter(command, "audit");
2370
+ }
2371
+ if (command.transaction === "required" && !transaction) {
2372
+ throw missingGovernanceAdapter(command, "transaction");
2373
+ }
2374
+ if (command.idempotency === "required" && !idempotency) {
2375
+ throw missingGovernanceAdapter(command, "idempotency");
2376
+ }
2377
+ try {
2378
+ const observe = (stage, next) => observeExecution(observer, {
2379
+ kind: "command",
2380
+ operation: command.name,
2381
+ stage,
2382
+ ...executionTrace(invocation.requestContext)
2383
+ }, next);
2384
+ await observe("authorize", () => governance.authorize(selectedInvocation));
2385
+ let execute = async () => {
2386
+ const result = await observe("handler", invokeOnce);
2387
+ if (audit)
2388
+ await observe("audit", () => audit.succeeded.call(audit, selectedInvocation, result));
2389
+ return result;
2390
+ };
2391
+ const invokeOnce = once(next);
2392
+ if (command.transaction === "required") {
2393
+ if (!transaction)
2394
+ throw missingGovernanceAdapter(command, "transaction");
2395
+ const inner = execute;
2396
+ execute = () => observe("transaction", () => transaction.call(governance, selectedInvocation, once(inner)));
2397
+ }
2398
+ if (command.idempotency === "required") {
2399
+ if (!idempotency)
2400
+ throw missingGovernanceAdapter(command, "idempotency");
2401
+ const inner = execute;
2402
+ execute = () => observe("idempotency", () => idempotency.call(governance, selectedInvocation, once(inner)));
2403
+ }
2404
+ return await execute();
2405
+ } catch (error) {
2406
+ if (audit)
2407
+ await audit.failed.call(audit, selectedInvocation, error);
2408
+ throw error;
2409
+ }
2410
+ };
2411
+ }
2412
+ async function executeCompiledCommand(options) {
2413
+ const command = resolveCompiledCommand(options.module, options.command);
2414
+ if (!command)
2415
+ throw new ApplicationError("Command descriptor missing or ambiguous", { code: "COMMAND_NOT_REGISTERED" });
2416
+ const invocation = {
2417
+ command,
2418
+ input: { body: options.input, params: {}, query: {} },
2419
+ request: options.request,
2420
+ requestContext: options.requestContext,
2421
+ services: options.services ?? {},
2422
+ ...options.scope ? { scope: options.scope } : {}
2423
+ };
2424
+ const aspects = composeAspects(descriptorPipeline(options.module, `module:${options.module.name}`, options.observer), descriptorPipeline(command, "command", options.observer));
2425
+ const value = await createCommandExecutor(options.governance, options.observer)(invocation, once(() => aspects({
2426
+ kind: "command",
2427
+ name: command.name,
2428
+ input: options.input,
2429
+ request: options.request,
2430
+ requestContext: options.requestContext,
2431
+ services: invocation.services,
2432
+ ...invocation.scope ? { scope: invocation.scope } : {},
2433
+ metadata: command
2434
+ }, once(() => options.handler(options.input)))));
2435
+ return options.decode(value);
2436
+ }
2437
+ async function previewCompiledCommand(options) {
2438
+ const command = resolveCompiledCommand(options.module, options.command);
2439
+ if (!command)
2440
+ throw new ApplicationError("Command descriptor missing or ambiguous", { code: "COMMAND_NOT_REGISTERED" });
2441
+ const invocation = {
2442
+ command,
2443
+ input: { body: options.input, params: {}, query: {} },
2444
+ request: options.request,
2445
+ requestContext: options.requestContext,
2446
+ services: options.services ?? {},
2447
+ ...options.scope ? { scope: options.scope } : {}
2448
+ };
2449
+ try {
2450
+ await options.governance.authorize(invocation);
2451
+ } catch (error) {
2452
+ if (error instanceof ApplicationError && (error.status === 401 || error.status === 403)) {
2453
+ return decodeCommandPreview({
2454
+ command: command.name,
2455
+ allowed: false,
2456
+ blockers: [{ code: error.code, message: error.message }]
2457
+ });
2458
+ }
2459
+ throw error;
2460
+ }
2461
+ const preview = decodeCommandPreview(await options.preview(options.input));
2462
+ if (preview.command !== command.name && preview.command !== command.className) {
2463
+ throw new TypeError("Mismatched command identity");
2464
+ }
2465
+ return preview;
2466
+ }
2467
+ function once(next) {
2468
+ let called = false;
2469
+ return () => {
2470
+ if (called) {
2471
+ return Promise.reject(new ApplicationError("Command continuation called multiple times", {
2472
+ code: "COMMAND_CONTINUATION_REUSED"
2473
+ }));
2474
+ }
2475
+ called = true;
2476
+ try {
2477
+ return next();
2478
+ } catch (error) {
2479
+ return Promise.reject(error);
2480
+ }
2481
+ };
2482
+ }
2483
+ function requireTrustedIdentity(requestContext) {
2484
+ const context = isRecord2(requestContext) ? requestContext : {};
2485
+ const identity = isTrustedIdentity(context.identity) ? context.identity : undefined;
2486
+ if (!isAuthenticatedTrustedIdentity(identity)) {
2487
+ throw new ApplicationError("Authenticated user context is required", {
2488
+ status: 401,
2489
+ code: "AUTHENTICATION_REQUIRED"
2490
+ });
2491
+ }
2492
+ return identity;
2493
+ }
2494
+ function requireIdempotencyKey(invocation) {
2495
+ const context = isRecord2(invocation.requestContext) ? invocation.requestContext : {};
2496
+ const key = (typeof context.idempotencyKey === "string" ? context.idempotencyKey : undefined) ?? safeHeaderValue(invocation.request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2497
+ if (!key || !idempotencyKeyPattern.test(key)) {
2498
+ throw new ApplicationError("A valid Idempotency-Key header is required", {
2499
+ status: 400,
2500
+ code: "IDEMPOTENCY_KEY_REQUIRED"
2501
+ });
2502
+ }
2503
+ return key;
2504
+ }
2505
+ function requireRouteIdempotencyKey(request) {
2506
+ const key = safeHeaderValue(request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2507
+ if (!key || !idempotencyKeyPattern.test(key)) {
2508
+ throw new ApplicationError("A valid Idempotency-Key header is required", {
2509
+ status: 400,
2510
+ code: "IDEMPOTENCY_KEY_REQUIRED"
2511
+ });
2512
+ }
2513
+ return key;
2514
+ }
2515
+ function assertCommandGovernanceReady(compiled, governance, executor) {
2516
+ if ((compiled.commands ?? []).length === 0)
2517
+ return;
2518
+ if (executor !== undefined && typeof executor !== "function") {
2519
+ throw new ApplicationError(`Module "${compiled.name}" has no callable command executor`, {
2520
+ code: "COMMAND_EXECUTOR_UNCONFIGURED"
2521
+ });
2522
+ }
2523
+ if (!governance && !executor) {
2524
+ throw new ApplicationError(`Module "${compiled.name}" has commands but no command governance`, {
2525
+ code: "COMMAND_GOVERNANCE_UNCONFIGURED"
2526
+ });
2527
+ }
2528
+ if (!governance)
2529
+ return;
2530
+ if (typeof governance.authorize !== "function") {
2531
+ throw new ApplicationError(`Module "${compiled.name}" has no authorization adapter`, {
2532
+ code: "COMMAND_AUTHORIZATION_UNCONFIGURED"
2533
+ });
2534
+ }
2535
+ for (const command of compiled.commands ?? []) {
2536
+ if (command.rpc !== undefined && command.branches !== undefined) {
2537
+ throw new ApplicationError(`Command "${command.name}" declares both rpc and branches`, {
2538
+ code: "COMMAND_BRANCHES_CONFLICT"
2539
+ });
2540
+ }
2541
+ for (const branch of command.branches ?? []) {
2542
+ if (!validCommandBranchSelector(branch.when)) {
2543
+ throw new ApplicationError(`Command "${command.name}" has an invalid branch selector`, {
2544
+ code: "COMMAND_BRANCH_SELECTOR_INVALID"
2545
+ });
2546
+ }
2547
+ const adapter = Object.hasOwn(governance.rpc ?? {}, branch.rpc) ? governance.rpc?.[branch.rpc] : undefined;
2548
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2549
+ throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no RPC governance adapter`, {
2550
+ code: "COMMAND_RPC_UNCONFIGURED"
2551
+ });
2552
+ }
2553
+ if (branch.audit && adapter.capabilities.audit !== true) {
2554
+ throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no audit capability`, {
2555
+ code: "COMMAND_AUDIT_UNCONFIGURED"
2556
+ });
2557
+ }
2558
+ if (branch.idempotency === "required" && adapter.capabilities.idempotency !== true) {
2559
+ throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no idempotency capability`, {
2560
+ code: "COMMAND_IDEMPOTENCY_UNCONFIGURED"
2561
+ });
2562
+ }
2563
+ if (branch.transaction === "required" && adapter.capabilities.transaction !== true) {
2564
+ throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no transaction capability`, {
2565
+ code: "COMMAND_TRANSACTION_UNCONFIGURED"
2566
+ });
2567
+ }
2568
+ if (branch.boundary === "external" && (branch.transaction === "required" || adapter.capabilities.transaction === true)) {
2569
+ throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" claims an external transaction`, {
2570
+ code: "COMMAND_EXTERNAL_TRANSACTION"
2571
+ });
2572
+ }
2573
+ }
2574
+ if (command.audit && command.rpc === undefined && (typeof governance.audit?.succeeded !== "function" || typeof governance.audit?.failed !== "function")) {
2575
+ throw new ApplicationError(`Command "${command.name}" has no audit adapter`, {
2576
+ code: "COMMAND_AUDIT_UNCONFIGURED"
2577
+ });
2578
+ }
2579
+ if (command.idempotency === "required" && typeof governance.idempotency !== "function" && command.rpc === undefined) {
2580
+ throw new ApplicationError(`Command "${command.name}" has no idempotency adapter`, {
2581
+ code: "COMMAND_IDEMPOTENCY_UNCONFIGURED"
2582
+ });
2583
+ }
2584
+ if (command.transaction === "required" && typeof governance.transaction !== "function" && command.rpc === undefined) {
2585
+ throw new ApplicationError(`Command "${command.name}" has no transaction adapter`, {
2586
+ code: "COMMAND_TRANSACTION_UNCONFIGURED"
2587
+ });
2588
+ }
2589
+ if (command.rpc !== undefined) {
2590
+ const adapter = Object.hasOwn(governance.rpc ?? {}, command.rpc) ? governance.rpc?.[command.rpc] : undefined;
2591
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2592
+ throw new ApplicationError(`Command "${command.name}" has no RPC governance adapter`, {
2593
+ code: "COMMAND_RPC_UNCONFIGURED"
2594
+ });
2595
+ }
2596
+ if (command.audit && adapter.capabilities.audit !== true) {
2597
+ throw new ApplicationError(`Command "${command.name}" RPC adapter has no audit capability`, {
2598
+ code: "COMMAND_AUDIT_UNCONFIGURED"
2599
+ });
2600
+ }
2601
+ if (command.idempotency === "required" && adapter.capabilities.idempotency !== true) {
2602
+ throw new ApplicationError(`Command "${command.name}" RPC adapter has no idempotency capability`, {
2603
+ code: "COMMAND_IDEMPOTENCY_UNCONFIGURED"
2604
+ });
2605
+ }
2606
+ if (command.transaction === "required" && adapter.capabilities.transaction !== true) {
2607
+ throw new ApplicationError(`Command "${command.name}" RPC adapter has no transaction capability`, {
2608
+ code: "COMMAND_TRANSACTION_UNCONFIGURED"
2609
+ });
2610
+ }
2611
+ }
2612
+ }
2613
+ }
2614
+ function joinPaths(prefix, path) {
2615
+ const joined = `${prefix}/${path}`.replace(/\/{2,}/g, "/");
2616
+ return joined.length > 1 ? joined.replace(/\/+$/, "") : joined;
2617
+ }
2618
+ function controllerInstance(value) {
2619
+ return isRecord2(value) ? value : undefined;
2620
+ }
2621
+ function canUseDirectRoute(compiled, controller, route) {
2622
+ return route.executionMode === "direct" && route.directInvoker !== undefined && controller.scope === "application" && compiled.createRequestScope === undefined && compiled.aspectPipeline === undefined && (compiled.aspects?.length ?? 0) === 0 && route.aspectPipeline === undefined && (route.aspects?.length ?? 0) === 0 && route.command === undefined && route.effect === undefined && route.responses === undefined;
2623
+ }
2624
+ function cookieValues(value) {
2625
+ if (!isRecord2(value))
2626
+ return;
2627
+ const result = {};
2628
+ for (const [name, entry] of Object.entries(value)) {
2629
+ result[name] = isRecord2(entry) && "value" in entry ? entry.value : entry;
2630
+ }
2631
+ return result;
2632
+ }
2633
+ function assertDeclaredResponseStatus(route, value, configuredStatus) {
2634
+ if (route.responses === undefined)
2635
+ return;
2636
+ const status = responseStatusOf(value, configuredStatus);
2637
+ if (responseStatusDeclared(route.responses, status))
2638
+ return;
2639
+ const transport = route.contract?.response;
2640
+ if ((transport === "binary" || transport === "stream") && status >= 200 && status < 300)
2641
+ return;
2642
+ throw new ApplicationError("Response validation failed", { status: 500, code: "RESPONSE_CONTRACT_UNDECLARED" });
2643
+ }
2644
+ function createModulePlugin(compiled, services, ctxFactory = defaultRequestContext, options = {}, imported = {}, pendingWork) {
2645
+ const supportedMethods = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]);
2646
+ const supportedFields = new Set([
2647
+ "method",
2648
+ "path",
2649
+ "handler",
2650
+ "body",
2651
+ "params",
2652
+ "query",
2653
+ "headers",
2654
+ "cookie",
2655
+ "response",
2656
+ "responses",
2657
+ "contract",
2658
+ "schemaKinds",
2659
+ "nativeResponse",
2660
+ "invoker",
2661
+ "effect",
2662
+ "directInvoker",
2663
+ "directInvokerFast",
2664
+ "executionMode",
2665
+ "command",
2666
+ "aspects",
2667
+ "aspectPipeline",
2668
+ "paramTransforms",
2669
+ "paramDefaults",
2670
+ "queryTransforms",
2671
+ "queryDefaults",
2672
+ "title",
2673
+ "data",
2674
+ "idempotency",
2675
+ "input",
2676
+ "result",
2677
+ "request",
2678
+ "parse",
2679
+ "allowDeleteBody"
2680
+ ]);
2681
+ for (const controller of compiled.controllers) {
2682
+ for (const route of controller.routes) {
2683
+ const unsupported = Object.keys(route).filter((field) => !supportedFields.has(field));
2684
+ if (!supportedMethods.has(route.method) || unsupported.length > 0) {
2685
+ throw new ApplicationError(`Unsupported compiled route ${route.method} ${controller.path}${route.path}` + (unsupported.length > 0 ? `: ${unsupported.join(", ")}` : ""), { code: "ROUTE_DESCRIPTOR_UNSUPPORTED" });
2686
+ }
2687
+ if (route.parse !== undefined && route.parse !== "none" || route.parse === "none" && (route.body !== undefined || route.contract?.body !== "domain" || !route.contract.evidence?.trim()) || route.allowDeleteBody !== undefined && (route.allowDeleteBody !== true || route.method !== "DELETE" || route.body === undefined)) {
2688
+ throw new ApplicationError(`Invalid compiled body policy on ${route.method} ${controller.path}${route.path}`, { code: "ROUTE_DESCRIPTOR_UNSUPPORTED" });
2689
+ }
2690
+ if (route.idempotency !== undefined && route.idempotency !== "required" && route.idempotency !== "none") {
2691
+ throw new ApplicationError(`Invalid idempotency policy on ${route.method} ${controller.path}${route.path}`, { code: "ROUTE_IDEMPOTENCY_INVALID" });
2692
+ }
2693
+ if (route.idempotency === "required" && ["GET", "HEAD", "OPTIONS"].includes(route.method)) {
2694
+ throw new ApplicationError(`Route ${route.method} ${controller.path}${route.path} cannot require idempotency`, { code: "ROUTE_IDEMPOTENCY_INVALID" });
2695
+ }
2696
+ }
2697
+ }
2698
+ const hasCommandRoutes = compiled.controllers.some((controller) => controller.routes.some((route) => route.command !== undefined));
2699
+ if (hasCommandRoutes && !options.commandGovernance && !options.commandExecutor) {
2700
+ throw new ApplicationError(`Module "${compiled.name}" has command routes but no commandGovernance`, { code: "COMMAND_GOVERNANCE_UNCONFIGURED" });
2701
+ }
2702
+ assertCommandGovernanceReady(compiled, options.commandGovernance, options.commandExecutor);
2703
+ const commandsByClassName = new Map((compiled.commands ?? []).map((command) => [command.className, command]));
2704
+ for (const controller of compiled.controllers) {
2705
+ for (const route of controller.routes) {
2706
+ const command = route.command === undefined ? undefined : resolveCompiledCommand(compiled, route.command);
2707
+ if (route.command && !command) {
2708
+ throw new ApplicationError(`Command "${route.command}" is not registered`, {
2709
+ code: "COMMAND_NOT_REGISTERED"
2710
+ });
2711
+ }
2712
+ if (route.effect?.retry === "explicit" && route.command) {
2713
+ if (command && command.idempotency !== "required") {
2714
+ throw new ApplicationError(`Effect retry is not allowed for non-idempotent command "${command.name}"`, { code: "EFFECT_RETRY_IDEMPOTENCY_REQUIRED" });
2715
+ }
2716
+ }
2717
+ if (route.effect?.dependencies && route.effect.dependencies.length > 0 && !options.effectRuntime) {
2718
+ throw new ApplicationError(`Route ${route.method} ${controller.path}${route.path} declares Effect dependencies without an effectRuntime`, { code: "EFFECT_RUNTIME_UNCONFIGURED" });
2719
+ }
2720
+ }
2721
+ }
2722
+ const requestContexts = new WeakMap;
2723
+ const requestCompletions = new WeakMap;
2724
+ const governanceExecutor = options.commandGovernance ? createCommandExecutor(options.commandGovernance, options.onExecution) : undefined;
2725
+ const commandExecutor = options.commandExecutor && governanceExecutor ? composeCommandExecutors(options.commandExecutor, governanceExecutor) : options.commandExecutor ?? governanceExecutor;
2726
+ const modulePipeline = descriptorPipeline(compiled, `module:${compiled.name}`, options.onExecution);
2727
+ const needsRequestState = ctxFactory !== defaultRequestContext || pendingWork !== undefined || options.httpPolicies !== undefined || options.onExecution !== undefined || compiled.createRequestScope !== undefined || compiled.aspectPipeline !== undefined || (compiled.aspects?.length ?? 0) > 0 || options.errorMapper !== undefined || compiled.controllers.some((controller) => controller.routes.some((route) => !canUseDirectRoute(compiled, controller, route)));
2728
+ const basePlugin = mountHttp(options.http, `supacloud:${compiled.name}`, options.normalize ?? true);
2729
+ const servicesContext = { services };
2730
+ const servicesPlugin = basePlugin.derive(() => servicesContext);
2731
+ const plugin = needsRequestState ? servicesPlugin.derive((context) => {
2732
+ if (pendingWork?.closed)
2733
+ throw new ApplicationError("Application is stopping", { status: 503, code: "APPLICATION_STOPPING" });
2734
+ let complete;
2735
+ try {
2736
+ complete = pendingWork?.add({ name: "http.request", kind: "request" });
2737
+ } catch (error) {
2738
+ if (!(error instanceof PendingWorkCapacityError))
2739
+ throw error;
2740
+ throw new ApplicationError("Application work capacity exceeded", { status: 503, code: error.code });
2741
+ }
2742
+ if (complete)
2743
+ requestCompletions.set(context.request, complete);
2744
+ const signal = pendingWork ? AbortSignal.any([context.request.signal, pendingWork.signal]) : context.request.signal;
2745
+ const finish = (requestContext) => {
2746
+ requestContexts.set(context.request, requestContext);
2747
+ return { requestContext };
2748
+ };
2749
+ const requestContext = ctxFactory(context.request, context, signal);
2750
+ return isPromiseLike(requestContext) ? requestContext.then(finish) : finish(requestContext);
2751
+ }) : servicesPlugin;
2752
+ const createRequestScope = compiled.createRequestScope;
2753
+ const requestScopes = new WeakMap;
2754
+ if (needsRequestState)
2755
+ plugin.onAfterResponse(async ({ request }) => {
2756
+ const scope = requestScopes.get(request);
2757
+ requestScopes.delete(request);
2758
+ try {
2759
+ if (scope)
2760
+ await compiled.destroyRequestScope?.(scope);
2761
+ } catch (error) {
2762
+ console.error(`supacloud: request scope cleanup failed for "${compiled.name}"`, error);
2763
+ } finally {
2764
+ requestCompletions.get(request)?.();
2765
+ requestCompletions.delete(request);
2766
+ }
2767
+ });
2768
+ const mapError = async (error, frameworkCode, request) => {
2769
+ const context = {
2770
+ request,
2771
+ requestContext: requestContexts.get(request),
2772
+ frameworkCode
2773
+ };
2774
+ const mapped = await options.errorMapper?.(error, context);
2775
+ return mapped ?? defaultErrorResponse(error, frameworkCode);
2776
+ };
2777
+ plugin.onError(ApplicationError, ({ error, request }) => mapError(error, frameworkErrorCode(error), request));
2778
+ plugin.onError(SchemaContractError, ({ error, request }) => mapError(error, frameworkErrorCode(error), request));
2779
+ plugin.onError(({ error, request }) => mapError(error, frameworkErrorCode(error), request));
2780
+ const routeRegistrar = plugin;
2781
+ for (const controller of compiled.controllers) {
2782
+ for (const route of controller.routes) {
2783
+ const path = joinPaths(controller.path, route.path);
2784
+ const documentation = route.data?.openapi;
2785
+ const hidden = documentation !== null && typeof documentation === "object" && "hide" in documentation && documentation.hide === true;
2786
+ const tags = documentation !== null && typeof documentation === "object" && "tags" in documentation && Array.isArray(documentation.tags) ? documentation.tags.filter((tag) => typeof tag === "string") : undefined;
2787
+ const schema = {
2788
+ ...toElysiaRouteSchema(route),
2789
+ ...route.parse === "none" ? { parse: "none" } : {},
2790
+ ...route.title || hidden || tags ? { detail: {
2791
+ ...route.title ? { summary: route.title } : {},
2792
+ ...hidden ? { hide: true } : {},
2793
+ ...tags ? { tags } : {}
2794
+ } } : {}
2795
+ };
2796
+ const policies = compileHttpPolicies(route, path, options.httpPolicies);
2797
+ if (policies.length > 0) {
2798
+ Object.assign(schema, {
2799
+ beforeHandle: async (context) => {
2800
+ for (const policy of policies) {
2801
+ const result = await policy({
2802
+ http: context,
2803
+ requestContext: requestContexts.get(context.request)
2804
+ });
2805
+ if (result instanceof Response)
2806
+ return result;
2807
+ if (result !== undefined) {
2808
+ throw new Error("HTTP policies must return Response or undefined");
2809
+ }
2810
+ }
2811
+ if (route.idempotency === "required") {
2812
+ requireRouteIdempotencyKey(context.request);
2813
+ }
2814
+ }
2815
+ });
2816
+ } else if (route.idempotency === "required") {
2817
+ Object.assign(schema, {
2818
+ beforeHandle: (context) => {
2819
+ requireRouteIdempotencyKey(context.request);
2820
+ }
2821
+ });
2822
+ }
2823
+ const responsePolicies = policies.filter((policy) => policy.afterResponse);
2824
+ const mappingPolicies = policies.filter((policy) => policy.mapResponse);
2825
+ const routePipeline = descriptorPipeline(route, "route", options.onExecution);
2826
+ const command = route.command ? commandsByClassName.get(route.command) : undefined;
2827
+ const commandPipeline = route.command ? descriptorPipeline(command ?? {}, "command", options.onExecution) : undefined;
2828
+ const routeInvoker = route.invoker;
2829
+ if (mappingPolicies.length > 0) {
2830
+ const responseValidators = Validator2.response(schema.response, { normalize: options.normalize ?? true });
2831
+ Object.assign(schema, {
2832
+ mapResponse: async (context) => {
2833
+ let response = context.responseValue;
2834
+ let mapped;
2835
+ for (const policy of mappingPolicies) {
2836
+ const result = await policy.mapResponse({
2837
+ http: context,
2838
+ requestContext: requestContexts.get(context.request),
2839
+ response,
2840
+ encodeResponse: (value) => {
2841
+ const validator = responseValidators?.get(responseStatusOf(value, context.set.status));
2842
+ if (!validator)
2843
+ return value;
2844
+ if (!("EncodeFrom" in validator) || typeof validator.EncodeFrom !== "function") {
2845
+ throw new ApplicationError("Response validation failed", { code: "RESPONSE_VALIDATION_FAILED" });
2846
+ }
2847
+ if ("mayReturnPromise" in validator && validator.mayReturnPromise && "From" in validator && typeof validator.From === "function") {
2848
+ return validator.From.call(validator, value, "response", true);
2849
+ }
2850
+ return validator.EncodeFrom.call(validator, value, "response");
2851
+ }
2852
+ });
2853
+ if (result !== undefined) {
2854
+ if (!(result instanceof Response))
2855
+ throw new Error("HTTP response policies must return Response or undefined");
2856
+ mapped = result;
2857
+ response = result;
2858
+ }
2859
+ }
2860
+ return mapped;
2861
+ }
2862
+ });
2863
+ }
2864
+ if (responsePolicies.length > 0) {
2865
+ Object.assign(schema, {
2866
+ afterResponse: async (context) => {
2867
+ for (const policy of responsePolicies) {
2868
+ await policy.afterResponse({
2869
+ http: context,
2870
+ requestContext: requestContexts.get(context.request),
2871
+ response: context.responseValue
2872
+ });
2873
+ }
2874
+ }
2875
+ });
2876
+ }
2877
+ const directRoute = canUseDirectRoute(compiled, controller, route) && options.onExecution === undefined && policies.length === 0 && responsePolicies.length === 0 && mappingPolicies.length === 0;
2878
+ const directController = directRoute && route.directInvokerFast !== undefined ? controllerInstance(services[controller.serviceKey]) : undefined;
2879
+ const directMethod = directController?.[route.handler];
2880
+ const directInvokerFast = route.directInvokerFast;
2881
+ const directHandler = directController && typeof directMethod === "function" && directInvokerFast ? (ctx) => directInvokerFast(directController, directMethod, ctx) : (ctx) => route.directInvoker(services[controller.serviceKey], ctx);
2882
+ const handler = directRoute ? directHandler : async (ctx) => {
2883
+ const requestContext = requestContexts.get(ctx.request);
2884
+ const execute = async () => {
2885
+ const requestScope = createRequestScope ? await createRequestScope(services, requestContext, imported) : undefined;
2886
+ if (requestScope && compiled.destroyRequestScope)
2887
+ requestScopes.set(ctx.request, requestScope);
2888
+ const source = controller.scope === "request" ? requestScope : services;
2889
+ const instance = source?.[controller.serviceKey];
2890
+ const normalizedCookie = ctx.cookie === undefined ? undefined : cookieValues(ctx.cookie);
2891
+ const input = {
2892
+ body: ctx.body,
2893
+ params: ctx.params,
2894
+ query: ctx.query,
2895
+ headers: ctx.headers ?? Object.fromEntries(ctx.request.headers.entries()),
2896
+ ...normalizedCookie === undefined ? {} : { cookie: normalizedCookie },
2897
+ context: requestContext,
2898
+ request: ctx.request,
2899
+ ...requestScope ? { scope: requestScope } : {},
2900
+ requestContext
2901
+ };
2902
+ const handlerCall = () => {
2903
+ if (route.invoker)
2904
+ return route.invoker(instance, input);
2905
+ if (!isRecord2(instance))
2906
+ throw new TypeError("Route controller is not an object");
2907
+ const method = instance[route.handler];
2908
+ if (typeof method !== "function")
2909
+ throw new TypeError(`Route handler ${route.handler} is not callable`);
2910
+ return method.call(instance, input);
2911
+ };
2912
+ const invokeHandler = async () => runCompiledEffect(await handlerCall(), route.effect, options.effectRuntime);
2913
+ const invoke = once(() => route.command && options.commandGovernance ? invokeHandler() : options.onExecution ? observeExecution(options.onExecution, {
2914
+ kind: route.command ? "command" : "route",
2915
+ operation: route.command ?? `${route.method} ${path}`,
2916
+ stage: "handler",
2917
+ ...executionTrace(requestContext)
2918
+ }, invokeHandler) : invokeHandler());
2919
+ const routeContext = {
2920
+ kind: "route",
2921
+ name: `${route.method} ${path}`,
2922
+ input,
2923
+ request: ctx.request,
2924
+ requestContext,
2925
+ ...requestScope ? { scope: requestScope } : {},
2926
+ services,
2927
+ metadata: route
2928
+ };
2929
+ const command = route.command === undefined ? undefined : resolveCompiledCommand(compiled, route.command);
2930
+ const commandContext = route.command === undefined ? routeContext : {
2931
+ kind: "command",
2932
+ name: command?.name ?? route.command,
2933
+ input,
2934
+ request: ctx.request,
2935
+ requestContext,
2936
+ ...requestScope ? { scope: requestScope } : {},
2937
+ services,
2938
+ metadata: command ?? route
2939
+ };
2940
+ const invokeRoute = () => modulePipeline(route.command ? commandContext : routeContext, once(() => routePipeline(routeContext, once(() => route.command ? commandPipeline(commandContext, once(invoke)) : invoke()))));
2941
+ const invokeCommand = () => {
2942
+ if (!route.command)
2943
+ return invokeRoute();
2944
+ if (!command) {
2945
+ throw new ApplicationError(`Command "${route.command}" is not registered`, {
2946
+ code: "COMMAND_NOT_REGISTERED"
2947
+ });
2948
+ }
2949
+ if (!commandExecutor) {
2950
+ throw new ApplicationError(`Command "${command.name}" has no executor`, {
2951
+ status: 501,
2952
+ code: "COMMAND_EXECUTOR_UNAVAILABLE"
2953
+ });
2954
+ }
2955
+ const invocation = {
2956
+ command,
2957
+ input,
2958
+ request: ctx.request,
2959
+ requestContext,
2960
+ ...requestScope ? { scope: requestScope } : {},
2961
+ services
2962
+ };
2963
+ return observeExecution(options.onExecution, {
2964
+ kind: "command",
2965
+ operation: command.name,
2966
+ stage: "commandExecutor",
2967
+ ...executionTrace(requestContext)
2968
+ }, () => commandExecutor(invocation, once(invokeRoute)));
2969
+ };
2970
+ return invokeCommand();
2971
+ };
2972
+ const result = await execute();
2973
+ assertDeclaredResponseStatus(route, result, ctx.set.status);
2974
+ return result;
2975
+ };
2976
+ switch (route.method) {
2977
+ case "GET":
2978
+ routeRegistrar.get(path, schema, handler);
2979
+ break;
2980
+ case "POST":
2981
+ routeRegistrar.post(path, schema, handler);
2982
+ break;
2983
+ case "PUT":
2984
+ routeRegistrar.put(path, schema, handler);
2985
+ break;
2986
+ case "PATCH":
2987
+ routeRegistrar.patch(path, schema, handler);
2988
+ break;
2989
+ case "DELETE":
2990
+ routeRegistrar.delete(path, schema, handler);
2991
+ break;
2992
+ case "HEAD":
2993
+ routeRegistrar.head(path, schema, handler);
2994
+ break;
2995
+ case "OPTIONS":
2996
+ routeRegistrar.options(path, schema, handler);
2997
+ break;
2998
+ }
2999
+ }
3000
+ }
3001
+ return plugin;
3002
+ }
3003
+ async function executeJob(compiled, services, job, input, requestContext, imported = {}, executor, observer) {
3004
+ if (job.tenantScope === "required") {
3005
+ try {
3006
+ requireFeatureRequestContext(requestContext);
3007
+ } catch {
3008
+ throw new ApplicationError("Feature request context is required for this job", {
3009
+ status: 401,
3010
+ code: "JOB_TENANT_CONTEXT_REQUIRED"
3011
+ });
3012
+ }
3013
+ }
3014
+ const decodedInput = decodeJobContract(job.input, input, "input");
3015
+ const jobScope = job.scope === "job" && compiled.createJobScope ? await compiled.createJobScope(services, requestContext, imported) : undefined;
3016
+ try {
3017
+ const source = job.scope === "job" ? jobScope : services;
3018
+ const instance = controllerInstance(source?.[job.serviceKey]);
3019
+ const method = instance?.run ?? instance?.execute;
3020
+ if (typeof method !== "function") {
3021
+ throw new ApplicationError(`Job "${job.name}" has no run(input) or execute(input) handler`, { code: "JOB_HANDLER_UNAVAILABLE" });
3022
+ }
3023
+ const invocation = {
3024
+ job,
3025
+ input: decodedInput,
3026
+ requestContext,
3027
+ ...jobScope ? { scope: jobScope } : {},
3028
+ services
3029
+ };
3030
+ const context = {
3031
+ kind: "job",
3032
+ name: job.name,
3033
+ input: decodedInput,
3034
+ requestContext,
3035
+ ...jobScope ? { scope: jobScope } : {},
3036
+ services,
3037
+ metadata: job
3038
+ };
3039
+ const invoke = once(() => observeExecution(observer, {
3040
+ kind: "job",
3041
+ operation: job.name,
3042
+ stage: "handler",
3043
+ ...executionTrace(requestContext)
3044
+ }, () => Reflect.apply(method, instance, [decodedInput])));
3045
+ const pipeline = descriptorPipeline(compiled, `module:${compiled.name}`, observer);
3046
+ const jobPipeline = descriptorPipeline(job, "job", observer);
3047
+ const result = await pipeline(context, () => jobPipeline(context, () => observeExecution(observer, {
3048
+ kind: "job",
3049
+ operation: job.name,
3050
+ stage: "jobExecutor",
3051
+ ...executionTrace(requestContext)
3052
+ }, executor ? () => executor(invocation, invoke) : invoke)));
3053
+ return decodeJobContract(job.output, result, "output");
3054
+ } finally {
3055
+ if (jobScope && compiled.destroyJobScope) {
3056
+ await compiled.destroyJobScope(jobScope);
3057
+ }
3058
+ }
3059
+ }
3060
+ function defaultErrorResponse(error, frameworkCode) {
3061
+ const protocolCode = commandErrorCode(error);
3062
+ if (protocolCode) {
3063
+ return Response.json({
3064
+ ok: false,
3065
+ code: protocolCode,
3066
+ message: protocolCode,
3067
+ metadata: commandFailureMetadata3(protocolCode)
3068
+ }, {
3069
+ status: commandErrorStatus(protocolCode)
3070
+ });
3071
+ }
3072
+ if (isPublicApplicationError(error)) {
3073
+ return Response.json({
3074
+ ok: false,
3075
+ code: error.code,
3076
+ message: error.message,
3077
+ ...error.details === undefined ? {} : { details: error.details },
3078
+ ...error.metadata === undefined ? {} : { metadata: error.metadata }
3079
+ }, { status: error.status });
3080
+ }
3081
+ if (frameworkCode === "PARSE") {
3082
+ return Response.json({
3083
+ ok: false,
3084
+ code: "PARSE_ERROR",
3085
+ message: "Request body could not be parsed"
3086
+ }, { status: 400 });
3087
+ }
3088
+ if (frameworkCode === "VALIDATION") {
3089
+ if (isRecord2(error) && error.type === "response") {
3090
+ return Response.json({
3091
+ ok: false,
3092
+ code: "RESPONSE_VALIDATION_ERROR",
3093
+ message: "Response validation failed"
3094
+ }, { status: 500 });
3095
+ }
3096
+ return Response.json({
3097
+ ok: false,
3098
+ code: "VALIDATION_ERROR",
3099
+ message: "Request validation failed"
3100
+ }, { status: 422 });
3101
+ }
3102
+ return Response.json({
3103
+ ok: false,
3104
+ code: "INTERNAL_ERROR",
3105
+ message: "Internal Server Error"
3106
+ }, { status: 500 });
3107
+ }
3108
+ function isPublicApplicationError(error) {
3109
+ if (!(error instanceof Error) || !isRecord2(error))
3110
+ return false;
3111
+ return error.expose === true && typeof error.status === "number" && Number.isInteger(error.status) && error.status >= 400 && error.status <= 599 && typeof error.code === "string" && error.code.length > 0;
3112
+ }
3113
+ function createApplication(options) {
3114
+ const pendingWork = new PendingWorkRegistry2(options.pendingWork ? { capacity: options.pendingWork.capacity } : {});
3115
+ const app = new Elysia3({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
3116
+ if (options.documentation)
3117
+ app.use(createDocumentationPlugin(options.documentation));
3118
+ const ctxFactory = options.requestContext === undefined ? defaultRequestContext : (() => {
3119
+ const contextCache = new WeakMap;
3120
+ return (request, context, signal) => {
3121
+ if (contextCache.has(request))
3122
+ return contextCache.get(request);
3123
+ const value = options.requestContext(request, context, signal);
3124
+ const cached = isPromiseLike(value) ? Promise.resolve(value) : value;
3125
+ contextCache.set(request, cached);
3126
+ return cached;
3127
+ };
3128
+ })();
3129
+ const imported = {};
3130
+ const moduleServices = [];
3131
+ for (const module of options.modules ?? []) {
3132
+ const services = module.createServices(options.deps ?? {}, imported);
3133
+ imported[module.name] = services;
3134
+ moduleServices.push({ module, services });
3135
+ const moduleNeedsRequestState = options.pendingWork !== undefined || options.requestContext !== undefined || options.httpPolicies !== undefined || options.onExecution !== undefined || module.createRequestScope !== undefined || module.aspectPipeline !== undefined || module.controllers.some((controller) => controller.routes.some((route) => !canUseDirectRoute(module, controller, route)));
3136
+ app.use(createModulePlugin(module, services, ctxFactory, { ...options, http: undefined }, imported, moduleNeedsRequestState ? pendingWork : undefined));
3137
+ }
3138
+ let initialized = false;
3139
+ let destroyed = false;
3140
+ let initializationPromise;
3141
+ let destructionPromise;
3142
+ const lifecycle = {
3143
+ get initialized() {
3144
+ return initialized;
3145
+ },
3146
+ get destroyed() {
3147
+ return destroyed;
3148
+ },
3149
+ pendingWork,
3150
+ waitForIdle(options) {
3151
+ return pendingWork.waitForIdle(options);
3152
+ },
3153
+ initialize() {
3154
+ if (destroyed)
3155
+ return Promise.reject(new Error("Application has already been destroyed"));
3156
+ if (initializationPromise)
3157
+ return initializationPromise;
3158
+ const startup = pendingWork.run({ name: "application.startup", kind: "startup" }, () => Promise.resolve().then(async () => {
3159
+ for (const { module, services } of moduleServices) {
3160
+ await module.initializeServices?.(services);
3161
+ }
3162
+ initialized = !destroyed;
3163
+ })).catch(async (error) => {
3164
+ try {
3165
+ await lifecycle.destroy();
3166
+ } catch (cleanupError) {
3167
+ throw new AggregateError([error, cleanupError], "Application initialization failed and cleanup failed");
3168
+ }
3169
+ throw error;
3170
+ });
3171
+ initializationPromise = startup;
3172
+ return startup;
3173
+ },
3174
+ destroy() {
3175
+ if (destructionPromise)
3176
+ return destructionPromise;
3177
+ destroyed = true;
3178
+ pendingWork.close();
3179
+ destructionPromise = Promise.resolve().then(async () => {
3180
+ pendingWork.dispose();
3181
+ const errors = [];
3182
+ try {
3183
+ await pendingWork.waitForIdle({ timeoutMs: options.pendingWork?.shutdownTimeoutMs ?? 5000 });
3184
+ } catch (error) {
3185
+ if (error instanceof PendingWorkTimeoutError)
3186
+ destructionPromise = undefined;
3187
+ throw error;
3188
+ }
3189
+ pendingWork.dispose();
3190
+ for (const { module, services } of [...moduleServices].reverse()) {
3191
+ try {
3192
+ await module.destroyServices?.(services);
3193
+ } catch (error) {
3194
+ errors.push(error);
3195
+ }
3196
+ }
3197
+ try {
3198
+ await options.effectRuntime?.dispose?.();
3199
+ } catch (error) {
3200
+ errors.push(error);
3201
+ }
3202
+ if (errors.length > 0) {
3203
+ throw new AggregateError(errors, "Application destruction failed");
3204
+ }
3205
+ });
3206
+ return destructionPromise;
3207
+ }
3208
+ };
3209
+ Object.defineProperties(app, {
3210
+ initialized: { enumerable: true, configurable: false, get: () => lifecycle.initialized },
3211
+ destroyed: { enumerable: true, configurable: false, get: () => lifecycle.destroyed },
3212
+ pendingWork: { enumerable: true, configurable: false, value: pendingWork },
3213
+ waitForIdle: { enumerable: true, configurable: false, value: lifecycle.waitForIdle },
3214
+ initialize: { enumerable: true, configurable: false, value: lifecycle.initialize },
3215
+ destroy: { enumerable: true, configurable: false, value: lifecycle.destroy }
3216
+ });
3217
+ return app;
3218
+ }
3219
+ function createTestApp(options) {
3220
+ return createApplication(options);
3221
+ }
3222
+
3223
+ // src/bun-aot.ts
3224
+ function bunServe() {
3225
+ const runtime = globalThis.Bun;
3226
+ if (!runtime?.serve)
3227
+ throw new Error("SupaCloud Bun AOT adapter requires Bun.serve");
3228
+ return runtime.serve.bind(runtime);
3229
+ }
3230
+ function createBunAotApplication(options) {
3231
+ const app = createApplication(options);
3232
+ const fetch = app.fetch;
3233
+ return {
3234
+ app,
3235
+ fetch,
3236
+ start: ({ hostname = "127.0.0.1", port }) => {
3237
+ const server = bunServe()({ hostname, port, fetch });
3238
+ let stopPromise;
3239
+ return {
3240
+ url: String(server.url),
3241
+ stop: (closeActiveConnections = true) => {
3242
+ stopPromise ??= Promise.resolve(server.stop(closeActiveConnections)).then(() => app.destroy());
3243
+ return stopPromise;
3244
+ }
3245
+ };
3246
+ },
3247
+ destroy: () => app.destroy()
3248
+ };
3249
+ }
3250
+ export {
3251
+ createBunAotApplication
3252
+ };