@supacloud/elysia 0.27.0 → 0.28.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.
@@ -0,0 +1,29 @@
1
+ import * as Effect from "effect/Effect";
2
+ import * as Exit from "effect/Exit";
3
+ import type * as Layer from "effect/Layer";
4
+ export interface CompiledEffectError {
5
+ readonly tag: string;
6
+ readonly status: number;
7
+ readonly code: string;
8
+ readonly message?: string;
9
+ }
10
+ export interface CompiledEffectDescriptor {
11
+ readonly required: true;
12
+ readonly errors?: readonly CompiledEffectError[];
13
+ readonly dependencies?: readonly string[];
14
+ readonly retry?: "none" | "explicit";
15
+ readonly maxAttempts?: number;
16
+ readonly timeoutMs?: number;
17
+ }
18
+ export interface SupaCloudEffectRuntime {
19
+ run(program: Effect.Effect<unknown, unknown, unknown>): Promise<Exit.Exit<unknown, unknown>>;
20
+ }
21
+ export declare class EffectApplicationError extends Error {
22
+ readonly status: number;
23
+ readonly code: string;
24
+ readonly expose: true;
25
+ constructor(message: string, status: number, code: string);
26
+ }
27
+ export declare function createDefaultEffectRuntime(): SupaCloudEffectRuntime;
28
+ export declare function createEffectRuntimeFromLayer<Services>(layer: Layer.Layer<Services, never, never>): SupaCloudEffectRuntime;
29
+ export declare function runCompiledEffect(value: unknown, descriptor?: CompiledEffectDescriptor, runtime?: SupaCloudEffectRuntime): Promise<unknown>;
package/dist/index.d.ts CHANGED
@@ -16,10 +16,13 @@ export type { HttpTelemetryEvent, HttpTelemetryObserver } from "./http-telemetry
16
16
  import { type ExecutionObserver } from "./execution";
17
17
  import { SchemaContractError } from "./schema_contract";
18
18
  import { type ApplicationDocumentationOptions } from "./documentation";
19
+ import { type CompiledEffectDescriptor, type SupaCloudEffectRuntime } from "./effect";
19
20
  export type { ExecutionEvent, ExecutionObserver } from "./execution";
20
21
  export { bindCompiledCommand } from "./command-binding";
21
22
  export type { CompiledCommandBinding, CompiledCommandBindingOptions, CompiledCommandCallContext, } from "./command-binding";
22
23
  export { createSchemaDecoder, assertResponseStatusDeclared, defineElysiaRoute, defineJsonContract, defineRouteContract, registerElysiaRoute, responseSchemaForStatus, responseStatusDeclared, responseStatusOf, SchemaContractError, toElysiaRouteSchema, } from "./schema_contract";
24
+ export { createDefaultEffectRuntime, createEffectRuntimeFromLayer, EffectApplicationError, runCompiledEffect, } from "./effect";
25
+ export type { CompiledEffectDescriptor, SupaCloudEffectRuntime } from "./effect";
23
26
  export type { ElysiaRouteContext, ElysiaRouteDefinition, ElysiaRouteHandler, ElysiaRouteSchema, ResponseMapSelector, RouteContractSchemas, SchemaDecoderOptions, SchemaNormalizeMode, } from "./schema_contract";
24
27
  export { createPersistentCommandAdapter, type PersistentCommandHandler } from "./persistent-command";
25
28
  export { createDocumentationPlugin } from "./documentation";
@@ -46,6 +49,7 @@ export interface CompiledRoute {
46
49
  /** @deprecated Use `responses` with an explicit HTTP status map. */
47
50
  response?: unknown;
48
51
  responses?: Record<string | number, unknown>;
52
+ effect?: CompiledEffectDescriptor;
49
53
  /** Compile-time ownership and transport classification for the route boundary. */
50
54
  contract?: {
51
55
  body?: "framework" | "domain";
@@ -292,6 +296,8 @@ export interface ApplicationOptions<Http extends AnyElysia = Elysia, RequestCont
292
296
  commandExecutor?: CommandExecutor;
293
297
  /** Maps framework or application failures to the public HTTP contract. */
294
298
  errorMapper?: ErrorMapper;
299
+ /** Runs Effect route programs and provides their environment at the HTTP boundary. */
300
+ effectRuntime?: SupaCloudEffectRuntime;
295
301
  /** Best-effort execution metadata only; durable audit belongs to governance. */
296
302
  onExecution?: ExecutionObserver;
297
303
  /** Optional read-only OpenAPI and GraphQL documentation endpoints. */
@@ -383,7 +389,7 @@ interface HttpContext {
383
389
  * and passed to the controller input as `scope`. Request-scoped controllers
384
390
  * are looked up on that scope, everything else on `services`.
385
391
  */
386
- export declare function createModulePlugin<const Services extends Record<string, unknown>, const Http extends AnyElysia = Elysia>(compiled: CompiledModule, services: Services, ctxFactory?: HttpRequestContextFactory<Http>, options?: Pick<ApplicationOptions<Http>, "http" | "httpPolicies" | "commandGovernance" | "commandExecutor" | "errorMapper" | "onExecution" | "normalize">, imported?: Record<string, Record<string, unknown>>, pendingWork?: PendingWorkRegistry): import("elysia/types").LocalHookReturn<"", "local", {
392
+ export declare function createModulePlugin<const Services extends Record<string, unknown>, const Http extends AnyElysia = Elysia>(compiled: CompiledModule, services: Services, ctxFactory?: HttpRequestContextFactory<Http>, options?: Pick<ApplicationOptions<Http>, "http" | "httpPolicies" | "commandGovernance" | "commandExecutor" | "errorMapper" | "effectRuntime" | "onExecution" | "normalize">, imported?: Record<string, Record<string, unknown>>, pendingWork?: PendingWorkRegistry): import("elysia/types").LocalHookReturn<"", "local", {
387
393
  decorator: {} & Http["~Singleton"]["decorator"];
388
394
  store: ({} & Http["~Singleton"]["store"] extends infer T_1 ? { [K_1 in keyof T_1]: T_1[K_1]; } : never) extends infer T ? { [K in keyof T]: T[K]; } : never;
389
395
  derive: {} & Http["~Singleton"]["derive"];
package/dist/index.js CHANGED
@@ -1014,6 +1014,96 @@ function createDocumentationPlugin(options = {}) {
1014
1014
  return app;
1015
1015
  }
1016
1016
 
1017
+ // src/effect.ts
1018
+ import * as Duration from "effect/Duration";
1019
+ import * as Effect from "effect/Effect";
1020
+ import * as Schedule from "effect/Schedule";
1021
+ import * as Cause from "effect/Cause";
1022
+ import * as Exit from "effect/Exit";
1023
+ import * as Runtime from "effect/Runtime";
1024
+
1025
+ class EffectApplicationError extends Error {
1026
+ status;
1027
+ code;
1028
+ expose = true;
1029
+ constructor(message, status, code) {
1030
+ super(message);
1031
+ this.status = status;
1032
+ this.code = code;
1033
+ this.name = "EffectApplicationError";
1034
+ }
1035
+ }
1036
+ function createDefaultEffectRuntime() {
1037
+ return {
1038
+ run(program) {
1039
+ return Effect.runPromiseExit(program);
1040
+ }
1041
+ };
1042
+ }
1043
+ function createEffectRuntimeFromLayer(layer) {
1044
+ return {
1045
+ run(program) {
1046
+ const provided = Effect.provide(layer)(program);
1047
+ return Effect.runPromiseExit(provided);
1048
+ }
1049
+ };
1050
+ }
1051
+ function isRecord(value) {
1052
+ return value !== null && typeof value === "object";
1053
+ }
1054
+ function effectErrorTag(error) {
1055
+ if (isRecord(error)) {
1056
+ for (const key of ["_tag", "tag", "code", "name"]) {
1057
+ const value = error[key];
1058
+ if (typeof value === "string" && value.length > 0)
1059
+ return value;
1060
+ }
1061
+ }
1062
+ if (error instanceof Error && error.constructor.name)
1063
+ return error.constructor.name;
1064
+ return;
1065
+ }
1066
+ function unwrapFiberFailure(error) {
1067
+ let current = error;
1068
+ const seen = new Set;
1069
+ while (Runtime.isFiberFailure(current) && !seen.has(current)) {
1070
+ seen.add(current);
1071
+ current = Cause.squash(current[Runtime.FiberFailureCauseId]);
1072
+ }
1073
+ return current;
1074
+ }
1075
+ function mapEffectFailure(error, descriptor) {
1076
+ error = unwrapFiberFailure(error);
1077
+ const tag = effectErrorTag(error);
1078
+ const mapping = tag && descriptor?.errors?.find((entry) => entry.tag === tag);
1079
+ if (mapping) {
1080
+ return new EffectApplicationError(mapping.message ?? mapping.code, mapping.status, mapping.code);
1081
+ }
1082
+ if (tag === "TimeoutException" || tag === "TimeoutError") {
1083
+ return new EffectApplicationError("Effect execution timed out", 504, "EFFECT_TIMEOUT");
1084
+ }
1085
+ return new EffectApplicationError("Effect execution failed", 500, descriptor?.required ? "EFFECT_UNMAPPED_ERROR" : "EFFECT_RUNTIME_ERROR");
1086
+ }
1087
+ async function runCompiledEffect(value, descriptor, runtime = createDefaultEffectRuntime()) {
1088
+ if (!Effect.isEffect(value)) {
1089
+ if (descriptor?.required) {
1090
+ throw new EffectApplicationError("Route declared an Effect contract but returned a non-Effect value", 500, "EFFECT_PROGRAM_REQUIRED");
1091
+ }
1092
+ return value;
1093
+ }
1094
+ let program = value;
1095
+ if (descriptor?.timeoutMs !== undefined) {
1096
+ program = Effect.timeout(program, Duration.millis(descriptor.timeoutMs));
1097
+ }
1098
+ if (descriptor?.retry === "explicit" && descriptor.maxAttempts !== undefined && descriptor.maxAttempts > 1) {
1099
+ program = Effect.retry(program, Schedule.recurs(descriptor.maxAttempts - 1));
1100
+ }
1101
+ const exit = await runtime.run(program);
1102
+ if (Exit.isSuccess(exit))
1103
+ return exit.value;
1104
+ throw mapEffectFailure(Cause.squash(exit.cause), descriptor);
1105
+ }
1106
+
1017
1107
  // src/command-binding.ts
1018
1108
  function bindCompiledCommand(options) {
1019
1109
  const { module, command, governance, observer, handler, decode, preview } = options;
@@ -1893,7 +1983,7 @@ function createCommandAuthorizationAdapter(options) {
1893
1983
  });
1894
1984
  }
1895
1985
  const context = invocation.requestContext;
1896
- const identity = isRecord(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
1986
+ const identity = isRecord2(context) && isTrustedIdentity(context.identity) ? context.identity : undefined;
1897
1987
  if (!isAuthenticatedTrustedIdentity(identity)) {
1898
1988
  throw new ApplicationError("Authentication required", { status: 401, code: "AUTHENTICATION_REQUIRED" });
1899
1989
  }
@@ -1908,7 +1998,7 @@ function createCommandAuthorizationAdapter(options) {
1908
1998
  } catch {
1909
1999
  throw new ApplicationError("Authorization is unavailable", { status: 503, code: "AUTHORIZATION_UNAVAILABLE" });
1910
2000
  }
1911
- if (!isRecord(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)) {
2001
+ 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)) {
1912
2002
  throw new ApplicationError("Authorization context is not bound to this application", {
1913
2003
  status: 503,
1914
2004
  code: "AUTHORIZATION_CONTEXT_INVALID"
@@ -2017,11 +2107,11 @@ function safeHeaderValue(value, maxLength) {
2017
2107
  }
2018
2108
  return value;
2019
2109
  }
2020
- function isRecord(value) {
2110
+ function isRecord2(value) {
2021
2111
  return value !== null && typeof value === "object" && !Array.isArray(value);
2022
2112
  }
2023
2113
  function isTrustedIdentity(value) {
2024
- return isRecord(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2114
+ return isRecord2(value) && typeof value.authenticated === "boolean" && (value.subject === undefined || typeof value.subject === "string") && (value.accessToken === undefined || typeof value.accessToken === "string");
2025
2115
  }
2026
2116
  function isAuthenticatedTrustedIdentity(value) {
2027
2117
  return value?.authenticated === true && typeof value.subject === "string" && value.subject.length > 0 && typeof value.accessToken === "string" && value.accessToken.length > 0;
@@ -2212,7 +2302,7 @@ function once(next) {
2212
2302
  };
2213
2303
  }
2214
2304
  function requireTrustedIdentity(requestContext) {
2215
- const context = isRecord(requestContext) ? requestContext : {};
2305
+ const context = isRecord2(requestContext) ? requestContext : {};
2216
2306
  const identity = isTrustedIdentity(context.identity) ? context.identity : undefined;
2217
2307
  if (!isAuthenticatedTrustedIdentity(identity)) {
2218
2308
  throw new ApplicationError("Authenticated user context is required", {
@@ -2223,7 +2313,7 @@ function requireTrustedIdentity(requestContext) {
2223
2313
  return identity;
2224
2314
  }
2225
2315
  function requireIdempotencyKey(invocation) {
2226
- const context = isRecord(invocation.requestContext) ? invocation.requestContext : {};
2316
+ const context = isRecord2(invocation.requestContext) ? invocation.requestContext : {};
2227
2317
  const key = (typeof context.idempotencyKey === "string" ? context.idempotencyKey : undefined) ?? safeHeaderValue(invocation.request.headers.get(IDEMPOTENCY_KEY_HEADER), 512);
2228
2318
  if (!key) {
2229
2319
  throw new ApplicationError("Idempotency-Key header is required", {
@@ -2271,7 +2361,7 @@ function assertCommandGovernanceReady(compiled, governance, executor) {
2271
2361
  }
2272
2362
  if (command.rpc !== undefined) {
2273
2363
  const adapter = Object.hasOwn(governance.rpc ?? {}, command.rpc) ? governance.rpc?.[command.rpc] : undefined;
2274
- if (!adapter || typeof adapter.execute !== "function" || !isRecord(adapter.capabilities)) {
2364
+ if (!adapter || typeof adapter.execute !== "function" || !isRecord2(adapter.capabilities)) {
2275
2365
  throw new ApplicationError(`Command "${command.name}" has no RPC governance adapter`, {
2276
2366
  code: "COMMAND_RPC_UNCONFIGURED"
2277
2367
  });
@@ -2299,14 +2389,14 @@ function joinPaths(prefix, path) {
2299
2389
  return joined.length > 1 ? joined.replace(/\/+$/, "") : joined;
2300
2390
  }
2301
2391
  function controllerInstance(value) {
2302
- return isRecord(value) ? value : undefined;
2392
+ return isRecord2(value) ? value : undefined;
2303
2393
  }
2304
2394
  function cookieValues(value) {
2305
- if (!isRecord(value))
2395
+ if (!isRecord2(value))
2306
2396
  return;
2307
2397
  const result = {};
2308
2398
  for (const [name, entry] of Object.entries(value)) {
2309
- result[name] = isRecord(entry) && "value" in entry ? entry.value : entry;
2399
+ result[name] = isRecord2(entry) && "value" in entry ? entry.value : entry;
2310
2400
  }
2311
2401
  return result;
2312
2402
  }
@@ -2338,6 +2428,7 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2338
2428
  "schemaKinds",
2339
2429
  "nativeResponse",
2340
2430
  "invoker",
2431
+ "effect",
2341
2432
  "command",
2342
2433
  "aspects",
2343
2434
  "aspectPipeline",
@@ -2377,6 +2468,15 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2377
2468
  code: "COMMAND_NOT_REGISTERED"
2378
2469
  });
2379
2470
  }
2471
+ if (route.effect?.retry === "explicit" && route.command) {
2472
+ const command = commandsByClassName.get(route.command);
2473
+ if (command && command.idempotency !== "required") {
2474
+ throw new ApplicationError(`Effect retry is not allowed for non-idempotent command "${command.name}"`, { code: "EFFECT_RETRY_IDEMPOTENCY_REQUIRED" });
2475
+ }
2476
+ }
2477
+ if (route.effect?.dependencies && route.effect.dependencies.length > 0 && !options.effectRuntime) {
2478
+ throw new ApplicationError(`Route ${route.method} ${controller.path}${route.path} declares Effect dependencies without an effectRuntime`, { code: "EFFECT_RUNTIME_UNCONFIGURED" });
2479
+ }
2380
2480
  }
2381
2481
  }
2382
2482
  const requestContexts = new WeakMap;
@@ -2537,12 +2637,13 @@ function createModulePlugin(compiled, services, ctxFactory = defaultRequestConte
2537
2637
  requestContext
2538
2638
  };
2539
2639
  const handlerCall = () => route.invoker ? route.invoker(instance, input) : Reflect.apply(method, instance, [input]);
2540
- const invoke = once(() => route.command && options.commandGovernance ? handlerCall() : observeExecution(options.onExecution, {
2640
+ const invokeHandler = async () => runCompiledEffect(await handlerCall(), route.effect, options.effectRuntime);
2641
+ const invoke = once(() => route.command && options.commandGovernance ? invokeHandler() : observeExecution(options.onExecution, {
2541
2642
  kind: route.command ? "command" : "route",
2542
2643
  operation: route.command ?? `${route.method} ${path}`,
2543
2644
  stage: "handler",
2544
2645
  ...executionTrace(requestContext)
2545
- }, handlerCall));
2646
+ }, invokeHandler));
2546
2647
  const routeContext = {
2547
2648
  kind: "route",
2548
2649
  name: `${route.method} ${path}`,
@@ -2700,7 +2801,7 @@ function defaultErrorResponse(error, frameworkCode) {
2700
2801
  }, { status: 400 });
2701
2802
  }
2702
2803
  if (frameworkCode === "VALIDATION") {
2703
- if (isRecord(error) && error.type === "response") {
2804
+ if (isRecord2(error) && error.type === "response") {
2704
2805
  return Response.json({
2705
2806
  ok: false,
2706
2807
  code: "RESPONSE_VALIDATION_ERROR",
@@ -2720,7 +2821,7 @@ function defaultErrorResponse(error, frameworkCode) {
2720
2821
  }, { status: 500 });
2721
2822
  }
2722
2823
  function isPublicApplicationError(error) {
2723
- if (!(error instanceof Error) || !isRecord(error))
2824
+ if (!(error instanceof Error) || !isRecord2(error))
2724
2825
  return false;
2725
2826
  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;
2726
2827
  }
@@ -2829,6 +2930,7 @@ function createTestApp(options) {
2829
2930
  export {
2830
2931
  ApplicationError,
2831
2932
  EXECUTION_ID_HEADER,
2933
+ EffectApplicationError,
2832
2934
  HTTP_POLICY_STORE_SQL,
2833
2935
  HttpPolicyConfigurationError,
2834
2936
  IDEMPOTENCY_KEY_HEADER,
@@ -2846,7 +2948,9 @@ export {
2846
2948
  createApplication,
2847
2949
  createCommandAuthorizationAdapter,
2848
2950
  createCommandExecutor,
2951
+ createDefaultEffectRuntime,
2849
2952
  createDocumentationPlugin,
2953
+ createEffectRuntimeFromLayer,
2850
2954
  createHttpPolicySuite,
2851
2955
  createHttpTelemetry,
2852
2956
  createMemoryHttpCacheStore,
@@ -2877,6 +2981,7 @@ export {
2877
2981
  responseSchemaForStatus,
2878
2982
  responseStatusDeclared,
2879
2983
  responseStatusOf,
2984
+ runCompiledEffect,
2880
2985
  toElysiaRouteSchema,
2881
2986
  validatedJsonResponse
2882
2987
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/elysia",
3
- "version": "0.27.0",
3
+ "version": "0.28.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",
@@ -23,7 +23,7 @@
23
23
  "scripts": {
24
24
  "generate:example": "bun src/generate-webhook-example.ts",
25
25
  "build": "bun run clean && bun run build:js && bun run build:types",
26
- "build:js": "bun build src/index.ts --outdir dist --target node --external elysia --external jose --external @supacloud/app --external @supacloud/db --external @supacloud/contracts",
26
+ "build:js": "bun build src/index.ts --outdir dist --target node --external elysia --external effect --external jose --external @supacloud/app --external @supacloud/db --external @supacloud/contracts",
27
27
  "build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
28
28
  "clean": "rm -rf dist",
29
29
  "prepublishOnly": "bun run build",
@@ -49,8 +49,9 @@
49
49
  "directory": "packages/elysia"
50
50
  },
51
51
  "dependencies": {
52
- "@supacloud/app": "0.23.0",
52
+ "@supacloud/app": "0.24.0",
53
53
  "@supacloud/contracts": "0.8.0",
54
+ "effect": "3.22.1",
54
55
  "exact-mirror": "1.2.6",
55
56
  "jose": "^6.2.11",
56
57
  "typebox": "1.3.34"
@@ -65,10 +66,10 @@
65
66
  "elysia": "2.0.0-beta.21"
66
67
  },
67
68
  "devDependencies": {
68
- "@supacloud/compiler": "0.40.0",
69
+ "@supacloud/compiler": "0.41.0",
69
70
  "@supacloud/delivery": "0.8.0",
70
71
  "@supacloud/commands": "0.9.1",
71
- "@supacloud/db": "0.13.1",
72
+ "@supacloud/db": "0.14.0",
72
73
  "@types/bun": "^1.4.2",
73
74
  "elysia": "2.0.0-beta.21",
74
75
  "typescript": "^7.0.2"