@supacloud/elysia 0.33.5 → 0.35.0

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.
@@ -9,7 +9,7 @@ export interface CompiledCommandCallContext {
9
9
  }
10
10
  export interface CompiledCommandBindingOptions<Input, Result> {
11
11
  module: Pick<CompiledModule, "name" | "commands" | "aspects" | "aspectPipeline">;
12
- /** Compiled command class name, as required by executeCompiledCommand. */
12
+ /** Compiled command class name or logical name. */
13
13
  command: string;
14
14
  governance: CommandGovernance;
15
15
  observer?: ExecutionObserver;
package/dist/index.d.ts CHANGED
@@ -73,22 +73,34 @@ export interface CompiledRoute {
73
73
  }) => Promise<unknown> | unknown;
74
74
  /** Class name of the @Command explicitly bound to this route. */
75
75
  command?: string;
76
+ /** Transport-level idempotency contract, independent of route command binding. */
77
+ idempotency?: "required" | "none";
76
78
  /** Statically generated route aspects. */
77
79
  aspects?: ApplicationAspect[];
78
80
  aspectPipeline?: ApplicationAspectPipeline;
79
81
  }
80
82
  export interface CompiledCommand {
81
83
  rpc?: string;
84
+ branches?: readonly CompiledCommandBranch[];
82
85
  className: string;
83
86
  name: string;
84
87
  permission?: string;
85
88
  transaction?: "required" | "none" | string;
86
89
  audit?: string;
87
90
  idempotency?: "required" | "none" | string;
91
+ tenantScope?: "required" | "none" | string;
88
92
  /** Statically generated command aspects. */
89
93
  aspects?: ApplicationAspect[];
90
94
  aspectPipeline?: ApplicationAspectPipeline;
91
95
  }
96
+ export interface CompiledCommandBranch {
97
+ when: string;
98
+ rpc: string;
99
+ transaction?: "required" | "none" | string;
100
+ audit?: string;
101
+ idempotency?: "required" | "none" | string;
102
+ boundary?: "database" | "external";
103
+ }
92
104
  export interface CompiledJob {
93
105
  className: string;
94
106
  name: string;
@@ -102,6 +114,7 @@ export interface CompiledJob {
102
114
  timeoutSec?: number;
103
115
  maxAttempts?: number;
104
116
  idempotency?: "required" | "none";
117
+ tenantScope?: "required" | "none" | string;
105
118
  aspects?: ApplicationAspect[];
106
119
  aspectPipeline?: ApplicationAspectPipeline;
107
120
  }
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // src/index.ts
2
2
  import { Elysia as Elysia3, setupTypebox, Validator as Validator2 } from "elysia";
3
+ import { requireFeatureRequestContext } from "@supacloud/app";
3
4
  import { PendingWorkRegistry as PendingWorkRegistry2, PendingWorkTimeoutError, PendingWorkCapacityError } from "@supacloud/app/runtime";
4
5
  import { commandFailureMetadata as commandFailureMetadata3, decodeCommandPreview } from "@supacloud/contracts";
5
6
 
@@ -2019,6 +2020,7 @@ setupTypebox();
2019
2020
  var VERIFIED_JWT_SUBJECT_HEADER = "x-supacloud-jwt-sub";
2020
2021
  var EXECUTION_ID_HEADER = "x-sb-execution-id";
2021
2022
  var IDEMPOTENCY_KEY_HEADER = "idempotency-key";
2023
+ var idempotencyKeyPattern = /^[A-Za-z0-9._:-]{1,512}$/;
2022
2024
  function composeAspects(...aspects) {
2023
2025
  const active = aspects.filter((aspect) => typeof aspect === "function");
2024
2026
  return (context, next) => {
@@ -2172,6 +2174,10 @@ function contextPlugin(http) {
2172
2174
  function mountHttp(http, name, normalize = true) {
2173
2175
  return new Elysia3({ name, normalize }).use(contextPlugin(http));
2174
2176
  }
2177
+ function resolveCompiledCommand(module, reference) {
2178
+ const matches = (module.commands ?? []).filter((command) => command.className === reference || command.name === reference);
2179
+ return matches.length === 1 ? matches[0] : undefined;
2180
+ }
2175
2181
  function decodeJobContract(schema, value, boundary) {
2176
2182
  if (schema === undefined)
2177
2183
  return value;
@@ -2240,14 +2246,69 @@ function missingGovernanceAdapter(command, adapter) {
2240
2246
  code: codes[adapter]
2241
2247
  });
2242
2248
  }
2249
+ function selectCommandBranch(command, input) {
2250
+ if (!command.branches || command.branches.length === 0)
2251
+ return command;
2252
+ if (command.rpc !== undefined) {
2253
+ throw new ApplicationError(`Command "${command.name}" declares both rpc and branches`, {
2254
+ code: "COMMAND_BRANCHES_CONFLICT"
2255
+ });
2256
+ }
2257
+ for (const branch of command.branches) {
2258
+ const match = /^(?:([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*))\s*===\s*(["'])(.*)\2$/.exec(branch.when);
2259
+ if (!match) {
2260
+ throw new ApplicationError(`Command "${command.name}" has an invalid branch selector`, {
2261
+ code: "COMMAND_BRANCH_SELECTOR_INVALID"
2262
+ });
2263
+ }
2264
+ const path = match[1] ?? "";
2265
+ const parts = path.split(".");
2266
+ const root = parts[0];
2267
+ let value = root === "body" || root === "params" || root === "query" ? input[root] : input.body;
2268
+ for (const part of root === "body" || root === "params" || root === "query" ? parts.slice(1) : parts) {
2269
+ if (!isRecord2(value)) {
2270
+ value = undefined;
2271
+ break;
2272
+ }
2273
+ value = value[part];
2274
+ }
2275
+ if (value === match[3]) {
2276
+ return {
2277
+ ...command,
2278
+ rpc: branch.rpc,
2279
+ transaction: branch.transaction ?? "none",
2280
+ audit: branch.audit,
2281
+ idempotency: branch.idempotency ?? "none"
2282
+ };
2283
+ }
2284
+ }
2285
+ throw new ApplicationError(`Command "${command.name}" has no matching RPC branch`, {
2286
+ status: 422,
2287
+ code: "COMMAND_BRANCH_UNMATCHED"
2288
+ });
2289
+ }
2290
+ function validCommandBranchSelector(value) {
2291
+ return /^(?:[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*===\s*(["'])(.*)\1$/.test(value);
2292
+ }
2243
2293
  function createCommandExecutor(governance, observer) {
2244
2294
  return async (invocation, next) => {
2245
- const { command } = invocation;
2246
- for (const mode of [command.transaction, command.idempotency]) {
2295
+ const command = selectCommandBranch(invocation.command, invocation.input);
2296
+ const selectedInvocation = command === invocation.command ? invocation : { ...invocation, command };
2297
+ for (const mode of [command.transaction, command.idempotency, command.tenantScope]) {
2247
2298
  if (mode !== undefined && mode !== "required" && mode !== "none") {
2248
2299
  throw new ApplicationError("Invalid command governance mode", { code: "COMMAND_MODE_INVALID" });
2249
2300
  }
2250
2301
  }
2302
+ if (command.tenantScope === "required") {
2303
+ try {
2304
+ requireFeatureRequestContext(invocation.requestContext);
2305
+ } catch {
2306
+ throw new ApplicationError("Feature request context is required for this command", {
2307
+ status: 401,
2308
+ code: "COMMAND_TENANT_CONTEXT_REQUIRED"
2309
+ });
2310
+ }
2311
+ }
2251
2312
  if (command.rpc !== undefined) {
2252
2313
  const adapter = Object.hasOwn(governance.rpc ?? {}, command.rpc) ? governance.rpc?.[command.rpc] : undefined;
2253
2314
  if (!adapter)
@@ -2262,8 +2323,8 @@ function createCommandExecutor(governance, observer) {
2262
2323
  operation: command.name,
2263
2324
  ...executionTrace(invocation.requestContext)
2264
2325
  };
2265
- await observeExecution(observer, { ...event, stage: "authorize" }, () => governance.authorize(invocation));
2266
- return observeExecution(observer, { ...event, stage: `rpc:${command.rpc}` }, () => adapter.execute(invocation, once(next)));
2326
+ await observeExecution(observer, { ...event, stage: "authorize" }, () => governance.authorize(selectedInvocation));
2327
+ return observeExecution(observer, { ...event, stage: `rpc:${command.rpc}` }, () => adapter.execute(selectedInvocation, once(next)));
2267
2328
  }
2268
2329
  const audit = command.audit ? governance.audit : undefined;
2269
2330
  const transaction = command.transaction === "required" ? governance.transaction : undefined;
@@ -2284,11 +2345,11 @@ function createCommandExecutor(governance, observer) {
2284
2345
  stage,
2285
2346
  ...executionTrace(invocation.requestContext)
2286
2347
  }, next);
2287
- await observe("authorize", () => governance.authorize(invocation));
2348
+ await observe("authorize", () => governance.authorize(selectedInvocation));
2288
2349
  let execute = async () => {
2289
2350
  const result = await observe("handler", invokeOnce);
2290
2351
  if (audit)
2291
- await observe("audit", () => audit.succeeded.call(audit, invocation, result));
2352
+ await observe("audit", () => audit.succeeded.call(audit, selectedInvocation, result));
2292
2353
  return result;
2293
2354
  };
2294
2355
  const invokeOnce = once(next);
@@ -2296,29 +2357,26 @@ function createCommandExecutor(governance, observer) {
2296
2357
  if (!transaction)
2297
2358
  throw missingGovernanceAdapter(command, "transaction");
2298
2359
  const inner = execute;
2299
- execute = () => observe("transaction", () => transaction.call(governance, invocation, once(inner)));
2360
+ execute = () => observe("transaction", () => transaction.call(governance, selectedInvocation, once(inner)));
2300
2361
  }
2301
2362
  if (command.idempotency === "required") {
2302
2363
  if (!idempotency)
2303
2364
  throw missingGovernanceAdapter(command, "idempotency");
2304
2365
  const inner = execute;
2305
- execute = () => observe("idempotency", () => idempotency.call(governance, invocation, once(inner)));
2366
+ execute = () => observe("idempotency", () => idempotency.call(governance, selectedInvocation, once(inner)));
2306
2367
  }
2307
2368
  return await execute();
2308
2369
  } catch (error) {
2309
2370
  if (audit)
2310
- await audit.failed.call(audit, invocation, error);
2371
+ await audit.failed.call(audit, selectedInvocation, error);
2311
2372
  throw error;
2312
2373
  }
2313
2374
  };
2314
2375
  }
2315
2376
  async function executeCompiledCommand(options) {
2316
- const matches = options.module.commands?.filter((item) => item.className === options.command) ?? [];
2317
- if (matches.length !== 1)
2318
- throw new ApplicationError("Command descriptor missing or ambiguous", { code: "COMMAND_NOT_REGISTERED" });
2319
- const command = matches[0];
2377
+ const command = resolveCompiledCommand(options.module, options.command);
2320
2378
  if (!command)
2321
- throw new Error(`Command not found: ${options.command}`);
2379
+ throw new ApplicationError("Command descriptor missing or ambiguous", { code: "COMMAND_NOT_REGISTERED" });
2322
2380
  const invocation = {
2323
2381
  command,
2324
2382
  input: { body: options.input, params: {}, query: {} },
@@ -2341,12 +2399,9 @@ async function executeCompiledCommand(options) {
2341
2399
  return options.decode(value);
2342
2400
  }
2343
2401
  async function previewCompiledCommand(options) {
2344
- const matches = options.module.commands?.filter((item) => item.className === options.command) ?? [];
2345
- if (matches.length !== 1)
2346
- throw new ApplicationError("Command descriptor missing or ambiguous", { code: "COMMAND_NOT_REGISTERED" });
2347
- const command = matches[0];
2402
+ const command = resolveCompiledCommand(options.module, options.command);
2348
2403
  if (!command)
2349
- throw new Error(`Command not found: ${options.command}`);
2404
+ throw new ApplicationError("Command descriptor missing or ambiguous", { code: "COMMAND_NOT_REGISTERED" });
2350
2405
  const invocation = {
2351
2406
  command,
2352
2407
  input: { body: options.input, params: {}, query: {} },
@@ -2399,8 +2454,18 @@ function requireTrustedIdentity(requestContext) {
2399
2454
  function requireIdempotencyKey(invocation) {
2400
2455
  const context = isRecord2(invocation.requestContext) ? invocation.requestContext : {};
2401
2456
  const key = (typeof context.idempotencyKey === "string" ? context.idempotencyKey : undefined) ?? safeHeaderValue(invocation.request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2402
- if (!key) {
2403
- throw new ApplicationError("Idempotency-Key header is required", {
2457
+ if (!key || !idempotencyKeyPattern.test(key)) {
2458
+ throw new ApplicationError("A valid Idempotency-Key header is required", {
2459
+ status: 400,
2460
+ code: "IDEMPOTENCY_KEY_REQUIRED"
2461
+ });
2462
+ }
2463
+ return key;
2464
+ }
2465
+ function requireRouteIdempotencyKey(request) {
2466
+ const key = safeHeaderValue(request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2467
+ if (!key || !idempotencyKeyPattern.test(key)) {
2468
+ throw new ApplicationError("A valid Idempotency-Key header is required", {
2404
2469
  status: 400,
2405
2470
  code: "IDEMPOTENCY_KEY_REQUIRED"
2406
2471
  });
@@ -2428,6 +2493,44 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2428
2493
  });
2429
2494
  }
2430
2495
  for (const command of compiled.commands ?? []) {
2496
+ if (command.rpc !== undefined && command.branches !== undefined) {
2497
+ throw new ApplicationError(`Command "${command.name}" declares both rpc and branches`, {
2498
+ code: "COMMAND_BRANCHES_CONFLICT"
2499
+ });
2500
+ }
2501
+ for (const branch of command.branches ?? []) {
2502
+ if (!validCommandBranchSelector(branch.when)) {
2503
+ throw new ApplicationError(`Command "${command.name}" has an invalid branch selector`, {
2504
+ code: "COMMAND_BRANCH_SELECTOR_INVALID"
2505
+ });
2506
+ }
2507
+ const adapter = Object.hasOwn(governance.rpc ?? {}, branch.rpc) ? governance.rpc?.[branch.rpc] : undefined;
2508
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2509
+ throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no RPC governance adapter`, {
2510
+ code: "COMMAND_RPC_UNCONFIGURED"
2511
+ });
2512
+ }
2513
+ if (branch.audit && adapter.capabilities.audit !== true) {
2514
+ throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no audit capability`, {
2515
+ code: "COMMAND_AUDIT_UNCONFIGURED"
2516
+ });
2517
+ }
2518
+ if (branch.idempotency === "required" && adapter.capabilities.idempotency !== true) {
2519
+ throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no idempotency capability`, {
2520
+ code: "COMMAND_IDEMPOTENCY_UNCONFIGURED"
2521
+ });
2522
+ }
2523
+ if (branch.transaction === "required" && adapter.capabilities.transaction !== true) {
2524
+ throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" has no transaction capability`, {
2525
+ code: "COMMAND_TRANSACTION_UNCONFIGURED"
2526
+ });
2527
+ }
2528
+ if (branch.boundary === "external" && (branch.transaction === "required" || adapter.capabilities.transaction === true)) {
2529
+ throw new ApplicationError(`Command "${command.name}" branch "${branch.when}" claims an external transaction`, {
2530
+ code: "COMMAND_EXTERNAL_TRANSACTION"
2531
+ });
2532
+ }
2533
+ }
2431
2534
  if (command.audit && command.rpc === undefined && (typeof governance.audit?.succeeded !== "function" || typeof governance.audit?.failed !== "function")) {
2432
2535
  throw new ApplicationError(`Command "${command.name}" has no audit adapter`, {
2433
2536
  code: "COMMAND_AUDIT_UNCONFIGURED"
@@ -2522,6 +2625,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2522
2625
  "queryDefaults",
2523
2626
  "title",
2524
2627
  "data",
2628
+ "idempotency",
2525
2629
  "input",
2526
2630
  "result",
2527
2631
  "request",
@@ -2537,6 +2641,12 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2537
2641
  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)) {
2538
2642
  throw new ApplicationError(`Invalid compiled body policy on ${route.method} ${controller.path}${route.path}`, { code: "ROUTE_DESCRIPTOR_UNSUPPORTED" });
2539
2643
  }
2644
+ if (route.idempotency !== undefined && route.idempotency !== "required" && route.idempotency !== "none") {
2645
+ throw new ApplicationError(`Invalid idempotency policy on ${route.method} ${controller.path}${route.path}`, { code: "ROUTE_IDEMPOTENCY_INVALID" });
2646
+ }
2647
+ if (route.idempotency === "required" && ["GET", "HEAD", "OPTIONS"].includes(route.method)) {
2648
+ throw new ApplicationError(`Route ${route.method} ${controller.path}${route.path} cannot require idempotency`, { code: "ROUTE_IDEMPOTENCY_INVALID" });
2649
+ }
2540
2650
  }
2541
2651
  }
2542
2652
  const hasCommandRoutes = compiled.controllers.some((controller) => controller.routes.some((route) => route.command !== undefined));
@@ -2544,16 +2654,15 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2544
2654
  throw new ApplicationError(`Module "${compiled.name}" has command routes but no commandGovernance`, { code: "COMMAND_GOVERNANCE_UNCONFIGURED" });
2545
2655
  }
2546
2656
  assertCommandGovernanceReady(compiled, options.commandGovernance, options.commandExecutor);
2547
- const commandsByClassName = new Map((compiled.commands ?? []).map((command) => [command.className, command]));
2548
2657
  for (const controller of compiled.controllers) {
2549
2658
  for (const route of controller.routes) {
2550
- if (route.command && !commandsByClassName.has(route.command)) {
2659
+ const command = route.command === undefined ? undefined : resolveCompiledCommand(compiled, route.command);
2660
+ if (route.command && !command) {
2551
2661
  throw new ApplicationError(`Command "${route.command}" is not registered`, {
2552
2662
  code: "COMMAND_NOT_REGISTERED"
2553
2663
  });
2554
2664
  }
2555
2665
  if (route.effect?.retry === "explicit" && route.command) {
2556
- const command = commandsByClassName.get(route.command);
2557
2666
  if (command && command.idempotency !== "required") {
2558
2667
  throw new ApplicationError(`Effect retry is not allowed for non-idempotent command "${command.name}"`, { code: "EFFECT_RETRY_IDEMPOTENCY_REQUIRED" });
2559
2668
  }
@@ -2643,6 +2752,15 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2643
2752
  throw new Error("HTTP policies must return Response or undefined");
2644
2753
  }
2645
2754
  }
2755
+ if (route.idempotency === "required") {
2756
+ requireRouteIdempotencyKey(context.request);
2757
+ }
2758
+ }
2759
+ });
2760
+ } else if (route.idempotency === "required") {
2761
+ Object.assign(schema, {
2762
+ beforeHandle: (context) => {
2763
+ requireRouteIdempotencyKey(context.request);
2646
2764
  }
2647
2765
  });
2648
2766
  }
@@ -2738,7 +2856,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2738
2856
  services,
2739
2857
  metadata: route
2740
2858
  };
2741
- const command = route.command ? commandsByClassName.get(route.command) : undefined;
2859
+ const command = route.command === undefined ? undefined : resolveCompiledCommand(compiled, route.command);
2742
2860
  const commandContext = {
2743
2861
  kind: "command",
2744
2862
  name: command?.name ?? route.command ?? `${route.method} ${path}`,
@@ -2816,6 +2934,16 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2816
2934
  return plugin;
2817
2935
  }
2818
2936
  async function executeJob(compiled, services, job, input, requestContext, imported = {}, executor, observer) {
2937
+ if (job.tenantScope === "required") {
2938
+ try {
2939
+ requireFeatureRequestContext(requestContext);
2940
+ } catch {
2941
+ throw new ApplicationError("Feature request context is required for this job", {
2942
+ status: 401,
2943
+ code: "JOB_TENANT_CONTEXT_REQUIRED"
2944
+ });
2945
+ }
2946
+ }
2819
2947
  const decodedInput = decodeJobContract(job.input, input, "input");
2820
2948
  const jobScope = job.scope === "job" && compiled.createJobScope ? await compiled.createJobScope(services, requestContext, imported) : undefined;
2821
2949
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/elysia",
3
- "version": "0.33.5",
3
+ "version": "0.35.0",
4
4
  "description": "Elysia runtime adapter for SupaCloud compiled modules: application/request scopes, route registration and validation",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -49,27 +49,27 @@
49
49
  "directory": "packages/elysia"
50
50
  },
51
51
  "dependencies": {
52
- "@supacloud/app": "0.28.3",
53
- "@supacloud/commands": "0.9.7",
54
- "@supacloud/contracts": "0.11.5",
52
+ "@supacloud/app": "0.30.0",
53
+ "@supacloud/commands": "0.11.0",
54
+ "@supacloud/contracts": "0.13.0",
55
55
  "effect": "4.0.5",
56
56
  "exact-mirror": "1.2.6",
57
57
  "jose": "^6.2.12",
58
58
  "typebox": "1.3.37"
59
59
  },
60
60
  "overrides": {
61
- "@supacloud/delivery": "0.19.4",
62
- "@supacloud/contracts": "0.11.5",
63
- "@supacloud/commands": "0.9.7",
61
+ "@supacloud/delivery": "0.21.0",
62
+ "@supacloud/contracts": "0.13.0",
63
+ "@supacloud/commands": "0.11.0",
64
64
  "@graphql-tools/utils": "^12.0.4"
65
65
  },
66
66
  "peerDependencies": {
67
67
  "elysia": "2.0.0-beta.32"
68
68
  },
69
69
  "devDependencies": {
70
- "@supacloud/compiler": "0.47.3",
71
- "@supacloud/delivery": "0.19.4",
72
- "@supacloud/db": "0.18.4",
70
+ "@supacloud/compiler": "0.49.0",
71
+ "@supacloud/delivery": "0.21.0",
72
+ "@supacloud/db": "0.20.0",
73
73
  "@types/bun": "^1.4.3",
74
74
  "elysia": "2.0.0-beta.32",
75
75
  "typescript": "^7.0.2"