effect-orpc 0.1.0 → 0.1.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.
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  fallbackConfig,
18
18
  lazy as lazy2
19
19
  } from "@orpc/server";
20
- import { Cause as Cause2, Effect, Exit } from "effect";
20
+ import { Cause as Cause2, Effect, Exit, FiberRefs } from "effect";
21
21
 
22
22
  // src/effect-enhance-router.ts
23
23
  import {
@@ -601,8 +601,13 @@ var EffectBuilder = class _EffectBuilder {
601
601
  captureStackTrace
602
602
  });
603
603
  const parentFiberRefs = getCurrentFiberRefs();
604
- const effectWithRefs = parentFiberRefs ? Effect.setFiberRefs(parentFiberRefs).pipe(
605
- Effect.andThen(tracedEffect)
604
+ const effectWithRefs = parentFiberRefs ? Effect.fiberIdWith(
605
+ (fiberId) => Effect.flatMap(
606
+ Effect.getFiberRefs,
607
+ (fiberRefs) => Effect.setFiberRefs(
608
+ FiberRefs.joinAs(fiberRefs, fiberId, parentFiberRefs)
609
+ ).pipe(Effect.andThen(tracedEffect))
610
+ )
606
611
  ) : tracedEffect;
607
612
  const exit = await runtime.runPromiseExit(effectWithRefs, {
608
613
  signal: opts.signal
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/effect-builder.ts","../src/effect-enhance-router.ts","../src/effect-procedure.ts","../src/tagged-error.ts"],"sourcesContent":["import type {\n AnySchema,\n ContractRouter,\n ErrorMap,\n HTTPPath,\n InferSchemaOutput,\n Meta,\n Route,\n Schema,\n} from \"@orpc/contract\";\nimport type {\n AnyMiddleware,\n BuilderConfig,\n BuilderDef,\n Context,\n Lazy,\n MapInputMiddleware,\n MergedCurrentContext,\n MergedInitialContext,\n Middleware,\n ProcedureHandler,\n ProcedureHandlerOptions,\n Router,\n} from \"@orpc/server\";\nimport type { IntersectPick } from \"@orpc/shared\";\nimport type { ManagedRuntime } from \"effect\";\n\nimport {\n mergeMeta,\n mergePrefix,\n mergeRoute,\n mergeTags,\n ORPCError,\n} from \"@orpc/contract\";\nimport {\n addMiddleware,\n Builder,\n decorateMiddleware,\n fallbackConfig,\n lazy,\n} from \"@orpc/server\";\nimport { Cause, Effect, Exit } from \"effect\";\n\nimport type {\n EffectErrorConstructorMap,\n EffectErrorMap,\n MergedEffectErrorMap,\n} from \"./tagged-error\";\nimport type {\n AnyBuilderLike,\n EffectBuilderDef,\n EffectErrorMapToErrorMap,\n EffectProcedureBuilderWithInput,\n EffectProcedureBuilderWithOutput,\n EffectProcedureHandler,\n EffectRouterBuilder,\n EnhancedEffectRouter,\n InferBuilderCurrentContext,\n InferBuilderErrorMap,\n InferBuilderInitialContext,\n InferBuilderInputSchema,\n InferBuilderMeta,\n InferBuilderOutputSchema,\n} from \"./types\";\n\nimport { enhanceEffectRouter } from \"./effect-enhance-router\";\nimport { EffectDecoratedProcedure } from \"./effect-procedure\";\nimport { getCurrentFiberRefs } from \"./fiber-context-bridge\";\nimport {\n createEffectErrorConstructorMap,\n effectErrorMapToErrorMap,\n isORPCTaggedError,\n} from \"./tagged-error\";\n\n/**\n * Captures the stack trace at the call site for better error reporting in spans.\n * This is called at procedure definition time to capture where the procedure was defined.\n *\n * @returns A function that lazily extracts the relevant stack frame\n */\nexport function addSpanStackTrace(): () => string | undefined {\n const ErrorConstructor = Error as typeof Error & {\n stackTraceLimit?: number;\n };\n const limit = ErrorConstructor.stackTraceLimit;\n ErrorConstructor.stackTraceLimit = 3;\n const traceError = new Error();\n ErrorConstructor.stackTraceLimit = limit;\n let cache: false | string = false;\n return () => {\n if (cache !== false) {\n return cache;\n }\n if (traceError.stack !== undefined) {\n const stack = traceError.stack.split(\"\\n\");\n if (stack[3] !== undefined) {\n cache = stack[3].trim();\n return cache;\n }\n }\n };\n}\n\n/**\n * Effect-native procedure builder that wraps an oRPC Builder instance\n * and adds Effect-specific capabilities while preserving Effect error\n * and requirements types.\n */\nexport class EffectBuilder<\n TInitialContext extends Context,\n TCurrentContext extends Context,\n TInputSchema extends AnySchema,\n TOutputSchema extends AnySchema,\n TEffectErrorMap extends EffectErrorMap,\n TMeta extends Meta,\n TRequirementsProvided,\n TRuntimeError,\n> {\n /**\n * This property holds the defined options and the effect-specific properties.\n */\n declare \"~effect\": EffectBuilderDef<\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n declare \"~orpc\": BuilderDef<\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta\n >;\n\n constructor(\n def: EffectBuilderDef<\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >,\n ) {\n const { runtime, spanConfig, effectErrorMap, ...orpcDef } = def;\n this[\"~orpc\"] = orpcDef;\n this[\"~effect\"] = { runtime, spanConfig, effectErrorMap, ...orpcDef };\n }\n\n /**\n * Sets or overrides the config.\n *\n * @see {@link https://orpc.dev/docs/client/server-side#middlewares-order Middlewares Order Docs}\n * @see {@link https://orpc.dev/docs/best-practices/dedupe-middleware#configuration Dedupe Middleware Docs}\n */\n $config(\n config: BuilderConfig,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n const inputValidationCount =\n this[\"~effect\"].inputValidationIndex -\n fallbackConfig(\n \"initialInputValidationIndex\",\n this[\"~effect\"].config.initialInputValidationIndex,\n );\n const outputValidationCount =\n this[\"~effect\"].outputValidationIndex -\n fallbackConfig(\n \"initialOutputValidationIndex\",\n this[\"~effect\"].config.initialOutputValidationIndex,\n );\n\n return new EffectBuilder({\n ...this[\"~effect\"],\n config,\n dedupeLeadingMiddlewares: fallbackConfig(\n \"dedupeLeadingMiddlewares\",\n config.dedupeLeadingMiddlewares,\n ),\n inputValidationIndex:\n fallbackConfig(\n \"initialInputValidationIndex\",\n config.initialInputValidationIndex,\n ) + inputValidationCount,\n outputValidationIndex:\n fallbackConfig(\n \"initialOutputValidationIndex\",\n config.initialOutputValidationIndex,\n ) + outputValidationCount,\n });\n }\n\n /**\n * Set or override the initial context.\n *\n * @see {@link https://orpc.dev/docs/context Context Docs}\n */\n $context<U extends Context>(): EffectBuilder<\n U & Record<never, never>,\n U,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n /**\n * We need `& Record<never, never>` to deal with `has no properties in common with type` error\n */\n\n return new EffectBuilder({\n ...this[\"~effect\"],\n middlewares: [],\n inputValidationIndex: fallbackConfig(\n \"initialInputValidationIndex\",\n this[\"~effect\"].config.initialInputValidationIndex,\n ),\n outputValidationIndex: fallbackConfig(\n \"initialOutputValidationIndex\",\n this[\"~effect\"].config.initialOutputValidationIndex,\n ),\n });\n }\n\n /**\n * Sets or overrides the initial meta.\n *\n * @see {@link https://orpc.dev/docs/metadata Metadata Docs}\n */\n $meta<U extends Meta>(\n initialMeta: U,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n U & Record<never, never>,\n TRequirementsProvided,\n TRuntimeError\n > {\n /**\n * We need `& Record<never, never>` to deal with `has no properties in common with type` error\n */\n\n return new EffectBuilder({\n ...this[\"~effect\"],\n meta: initialMeta,\n });\n }\n\n /**\n * Sets or overrides the initial route.\n * This option is typically relevant when integrating with OpenAPI.\n *\n * @see {@link https://orpc.dev/docs/openapi/routing OpenAPI Routing Docs}\n * @see {@link https://orpc.dev/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}\n */\n $route(\n initialRoute: Route,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n route: initialRoute,\n });\n }\n\n /**\n * Sets or overrides the initial input schema.\n *\n * @see {@link https://orpc.dev/docs/procedure#initial-configuration Initial Procedure Configuration Docs}\n */\n $input<U extends AnySchema>(\n initialInputSchema?: U,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n U,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n inputSchema: initialInputSchema,\n });\n }\n\n /**\n * Adds type-safe custom errors.\n * Supports both traditional oRPC error definitions and ORPCTaggedError classes.\n *\n * @example\n * ```ts\n * // Traditional format\n * builder.errors({ BAD_REQUEST: { status: 400, message: 'Bad request' } })\n *\n * // Tagged error class\n * builder.errors({ USER_NOT_FOUND: UserNotFoundError })\n *\n * // Mixed\n * builder.errors({\n * BAD_REQUEST: { status: 400 },\n * USER_NOT_FOUND: UserNotFoundError,\n * })\n * ```\n *\n * @see {@link https://orpc.dev/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}\n */\n errors<U extends EffectErrorMap>(\n errors: U,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n MergedEffectErrorMap<TEffectErrorMap, U>,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n const newEffectErrorMap: MergedEffectErrorMap<TEffectErrorMap, U> = {\n ...this[\"~effect\"].effectErrorMap,\n ...errors,\n };\n return new EffectBuilder({\n ...this[\"~effect\"],\n errorMap: effectErrorMapToErrorMap(newEffectErrorMap),\n effectErrorMap: newEffectErrorMap,\n });\n }\n\n /**\n * Uses a middleware to modify the context or improve the pipeline.\n *\n * @info Supports both normal middleware and inline middleware implementations.\n * @note The current context must be satisfy middleware dependent-context\n * @see {@link https://orpc.dev/docs/middleware Middleware Docs}\n */\n use<\n UOutContext extends IntersectPick<TCurrentContext, UOutContext>,\n UInContext extends Context = TCurrentContext,\n >(\n middleware: Middleware<\n UInContext | TCurrentContext,\n UOutContext,\n InferSchemaOutput<TInputSchema>,\n unknown,\n EffectErrorConstructorMap<TEffectErrorMap>,\n TMeta\n >,\n ): EffectBuilder<\n MergedInitialContext<TInitialContext, UInContext, TCurrentContext>,\n MergedCurrentContext<TCurrentContext, UOutContext>,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n\n use(\n middleware: AnyMiddleware,\n mapInput?: MapInputMiddleware<any, any>,\n ): EffectBuilder<any, any, any, any, any, any, any, any> {\n const mapped = mapInput\n ? decorateMiddleware(middleware).mapInput(mapInput)\n : middleware;\n\n return new EffectBuilder({\n ...this[\"~effect\"],\n middlewares: addMiddleware(this[\"~effect\"].middlewares, mapped),\n });\n }\n\n /**\n * Sets or updates the metadata.\n * The provided metadata is spared-merged with any existing metadata.\n *\n * @see {@link https://orpc.dev/docs/metadata Metadata Docs}\n */\n meta(\n meta: TMeta,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n meta: mergeMeta(this[\"~effect\"].meta, meta),\n });\n }\n\n /**\n * Sets or updates the route definition.\n * The provided route is spared-merged with any existing route.\n * This option is typically relevant when integrating with OpenAPI.\n *\n * @see {@link https://orpc.dev/docs/openapi/routing OpenAPI Routing Docs}\n * @see {@link https://orpc.dev/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}\n */\n route(\n route: Route,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n route: mergeRoute(this[\"~effect\"].route, route),\n });\n }\n\n /**\n * Defines the input validation schema.\n *\n * @see {@link https://orpc.dev/docs/procedure#input-output-validation Input Validation Docs}\n */\n input<USchema extends AnySchema>(\n schema: USchema,\n ): EffectProcedureBuilderWithInput<\n TInitialContext,\n TCurrentContext,\n USchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n inputSchema: schema,\n inputValidationIndex:\n fallbackConfig(\n \"initialInputValidationIndex\",\n this[\"~effect\"].config.initialInputValidationIndex,\n ) + this[\"~effect\"].middlewares.length,\n // we cast to any because EffectProcedureBuilderWithInput is expecting\n // use() input type to be defined, and EffectBuilder types its use() input\n // to unknown to allow any middleware to be passed\n // ---\n // note: the original implentation of the builder also uses any for the same reason\n }) as any;\n }\n\n /**\n * Defines the output validation schema.\n *\n * @see {@link https://orpc.dev/docs/procedure#input-output-validation Output Validation Docs}\n */\n output<USchema extends AnySchema>(\n schema: USchema,\n ): EffectProcedureBuilderWithOutput<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n USchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n // We cast to any because EffectProcedureBuilderWithOutput narrows\n // handler/effect output typing based on the declared output schema.\n return new EffectBuilder({\n ...this[\"~effect\"],\n outputSchema: schema,\n outputValidationIndex:\n fallbackConfig(\n \"initialOutputValidationIndex\",\n this[\"~effect\"].config.initialOutputValidationIndex,\n ) + this[\"~effect\"].middlewares.length,\n }) as any;\n }\n\n /**\n * Adds a traceable span to the procedure for telemetry.\n * The span name is used for Effect tracing via `Effect.withSpan`.\n * Stack trace is captured at the call site for better error reporting.\n *\n * @param spanName - The name of the span for telemetry (e.g., 'users.getUser')\n * @returns An EffectBuilder with span tracing configured\n *\n * @example\n * ```ts\n * const getUser = effectOs\n * .input(z.object({ id: z.string() }))\n * .traced('users.getUser')\n * .effect(function* ({ input }) {\n * const userService = yield* UserService\n * return yield* userService.findById(input.id)\n * })\n * ```\n */\n traced(\n spanName: string,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n spanConfig: {\n name: spanName,\n captureStackTrace: addSpanStackTrace(),\n },\n });\n }\n\n handler<UFuncOutput>(\n handler: ProcedureHandler<\n TCurrentContext,\n InferSchemaOutput<TInputSchema>,\n UFuncOutput,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta\n >,\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n Schema<UFuncOutput, UFuncOutput>,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n handler,\n });\n }\n\n /**\n * Defines the handler of the procedure using an Effect.\n * The Effect is executed using the ManagedRuntime provided during builder creation.\n * The effect is automatically wrapped with `Effect.withSpan`.\n *\n * @see {@link https://orpc.dev/docs/procedure Procedure Docs}\n */\n effect<UFuncOutput>(\n effectFn: EffectProcedureHandler<\n TCurrentContext,\n TInputSchema,\n UFuncOutput,\n TEffectErrorMap,\n TRequirementsProvided,\n TMeta\n >,\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n Schema<UFuncOutput, UFuncOutput>,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n const { runtime, spanConfig } = this[\"~effect\"];\n // Capture stack trace at definition time for default tracing\n const defaultCaptureStackTrace = addSpanStackTrace();\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n handler: async (opts) => {\n const effectOpts: ProcedureHandlerOptions<\n TCurrentContext,\n InferSchemaOutput<TInputSchema>,\n EffectErrorConstructorMap<TEffectErrorMap>,\n TMeta\n > = {\n context: opts.context,\n input: opts.input,\n path: opts.path,\n procedure: opts.procedure,\n signal: opts.signal,\n lastEventId: opts.lastEventId,\n errors: createEffectErrorConstructorMap(\n this[\"~effect\"].effectErrorMap,\n ),\n };\n const spanName = spanConfig?.name ?? opts.path.join(\".\");\n const captureStackTrace =\n spanConfig?.captureStackTrace ?? defaultCaptureStackTrace;\n const resolver = Effect.fnUntraced(effectFn);\n const tracedEffect = Effect.withSpan(resolver(effectOpts), spanName, {\n captureStackTrace,\n });\n const parentFiberRefs = getCurrentFiberRefs();\n const effectWithRefs = parentFiberRefs\n ? Effect.setFiberRefs(parentFiberRefs).pipe(\n Effect.andThen(tracedEffect),\n )\n : tracedEffect;\n const exit = await runtime.runPromiseExit(effectWithRefs, {\n signal: opts.signal,\n });\n\n if (Exit.isFailure(exit)) {\n throw Cause.match(exit.cause, {\n onDie(defect) {\n return new ORPCError(\"INTERNAL_SERVER_ERROR\", {\n cause: defect,\n });\n },\n onFail(error) {\n if (isORPCTaggedError(error)) {\n return error.toORPCError();\n }\n if (error instanceof ORPCError) {\n return error;\n }\n return new ORPCError(\"INTERNAL_SERVER_ERROR\", {\n cause: error,\n });\n },\n onInterrupt(fiberId) {\n return new ORPCError(\"INTERNAL_SERVER_ERROR\", {\n cause: new Error(`${fiberId} Interrupted`),\n });\n },\n onSequential(left) {\n return left;\n },\n onEmpty: new ORPCError(\"INTERNAL_SERVER_ERROR\", {\n cause: new Error(\"Unknown error\"),\n }),\n onParallel(left) {\n return left;\n },\n });\n }\n\n return exit.value;\n },\n });\n }\n\n /**\n * Prefixes all procedures in the router.\n * The provided prefix is post-appended to any existing router prefix.\n *\n * @note This option does not affect procedures that do not define a path in their route definition.\n *\n * @see {@link https://orpc.dev/docs/openapi/routing#route-prefixes OpenAPI Route Prefixes Docs}\n */\n prefix(\n prefix: HTTPPath,\n ): EffectRouterBuilder<\n TInitialContext,\n TCurrentContext,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n prefix: mergePrefix(this[\"~effect\"].prefix, prefix),\n }) as any;\n }\n\n /**\n * Adds tags to all procedures in the router.\n * This helpful when you want to group procedures together in the OpenAPI specification.\n *\n * @see {@link https://orpc.dev/docs/openapi/openapi-specification#operation-metadata OpenAPI Operation Metadata Docs}\n */\n tag(\n ...tags: string[]\n ): EffectRouterBuilder<\n TInitialContext,\n TCurrentContext,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n tags: mergeTags(this[\"~effect\"].tags, tags),\n }) as any;\n }\n\n /**\n * Applies all of the previously defined options to the specified router.\n *\n * @see {@link https://orpc.dev/docs/router#extending-router Extending Router Docs}\n */\n router<U extends Router<ContractRouter<TMeta>, TCurrentContext>>(\n router: U,\n ): EnhancedEffectRouter<\n U,\n TInitialContext,\n TCurrentContext,\n TEffectErrorMap\n > {\n return enhanceEffectRouter(router, {\n ...this[\"~effect\"],\n }) as any; // Type instantiation is excessively deep and possibly infinite\n }\n\n /**\n * Create a lazy router\n * And applies all of the previously defined options to the specified router.\n *\n * @see {@link https://orpc.dev/docs/router#extending-router Extending Router Docs}\n */\n lazy<U extends Router<ContractRouter<TMeta>, TCurrentContext>>(\n loader: () => Promise<{ default: U }>,\n ): EnhancedEffectRouter<\n Lazy<U>,\n TInitialContext,\n TCurrentContext,\n TEffectErrorMap\n > {\n return enhanceEffectRouter(lazy(loader), {\n ...this[\"~effect\"],\n }) as any; // Type instantiation is excessively deep and possibly infinite\n }\n}\n\n/**\n * Creates an Effect-aware procedure builder with the specified ManagedRuntime.\n * Uses the default `os` builder from `@orpc/server`.\n *\n * @param runtime - The ManagedRuntime that provides services for Effect procedures\n * @returns An EffectBuilder instance for creating Effect-native procedures\n *\n * @example\n * ```ts\n * import { makeEffectORPC } from '@orpc/effect'\n * import { Effect, Layer, ManagedRuntime } from 'effect'\n *\n * const runtime = ManagedRuntime.make(Layer.empty)\n * const effectOs = makeEffectORPC(runtime)\n *\n * const hello = effectOs.effect(() => Effect.succeed('Hello!'))\n * ```\n */\nexport function makeEffectORPC<TRequirementsProvided, TRuntimeError>(\n runtime: ManagedRuntime.ManagedRuntime<TRequirementsProvided, TRuntimeError>,\n): EffectBuilder<\n Context,\n Context,\n Schema<unknown, unknown>,\n Schema<unknown, unknown>,\n Record<never, never>,\n Record<never, never>,\n TRequirementsProvided,\n TRuntimeError\n>;\n\n/**\n * Creates an Effect-aware procedure builder by wrapping an existing oRPC Builder\n * with the specified ManagedRuntime.\n *\n * @param runtime - The ManagedRuntime that provides services for Effect procedures\n * @param builder - The oRPC Builder instance to wrap (e.g., a customized `os`)\n * @returns An EffectBuilder instance that extends the original builder with Effect support\n *\n * @example\n * ```ts\n * import { makeEffectORPC } from '@orpc/effect'\n * import { os } from '@orpc/server'\n * import { Effect, Layer, ManagedRuntime } from 'effect'\n *\n * // Create a customized builder\n * const authedOs = os.use(authMiddleware)\n *\n * // Wrap it with Effect support\n * const runtime = ManagedRuntime.make(UserServiceLive)\n * const effectOs = makeEffectORPC(runtime, authedOs)\n *\n * const getUser = effectOs\n * .input(z.object({ id: z.string() }))\n * .effect(\n * Effect.fn(function* ({ input }) {\n * const userService = yield* UserService\n * return yield* userService.findById(input.id)\n * })\n * )\n * ```\n */\nexport function makeEffectORPC<\n TBuilder extends AnyBuilderLike<\n TInputSchema,\n TOutputSchema,\n TErrorMap,\n TMeta\n >,\n TInputSchema extends AnySchema,\n TOutputSchema extends AnySchema,\n TErrorMap extends ErrorMap,\n TMeta extends Meta,\n TRequirementsProvided,\n TRuntimeError,\n>(\n runtime: ManagedRuntime.ManagedRuntime<TRequirementsProvided, TRuntimeError>,\n builder: TBuilder,\n): EffectBuilder<\n InferBuilderInitialContext<TBuilder>,\n InferBuilderCurrentContext<TBuilder>,\n InferBuilderInputSchema<TBuilder>,\n InferBuilderOutputSchema<TBuilder>,\n InferBuilderErrorMap<TBuilder>,\n InferBuilderMeta<TBuilder>,\n TRequirementsProvided,\n TRuntimeError\n>;\n\nexport function makeEffectORPC<TRequirementsProvided, TRuntimeError>(\n runtime: ManagedRuntime.ManagedRuntime<TRequirementsProvided, TRuntimeError>,\n builder?: AnyBuilderLike,\n): EffectBuilder<\n any,\n any,\n any,\n any,\n any,\n any,\n TRequirementsProvided,\n TRuntimeError\n> {\n const resolvedBuilder = builder ?? emptyBuilder();\n return new EffectBuilder({\n ...resolvedBuilder[\"~orpc\"],\n errorMap: effectErrorMapToErrorMap(resolvedBuilder[\"~orpc\"].errorMap),\n effectErrorMap: resolvedBuilder[\"~orpc\"].errorMap,\n runtime,\n });\n}\n\nfunction emptyBuilder(): AnyBuilderLike {\n return new Builder({\n config: {},\n route: {},\n meta: {},\n errorMap: {},\n inputValidationIndex: fallbackConfig(\"initialInputValidationIndex\"),\n outputValidationIndex: fallbackConfig(\"initialOutputValidationIndex\"),\n middlewares: [],\n dedupeLeadingMiddlewares: true,\n });\n}\n","import type { ManagedRuntime } from \"effect/ManagedRuntime\";\n\nimport {\n enhanceRoute,\n mergePrefix,\n type EnhanceRouteOptions,\n} from \"@orpc/contract\";\nimport {\n createAccessibleLazyRouter,\n getLazyMeta,\n isLazy,\n isProcedure,\n lazy,\n mergeMiddlewares,\n unlazy,\n type AnyMiddleware,\n type AnyRouter,\n type Context,\n type Lazyable,\n} from \"@orpc/server\";\n\nimport type { EffectErrorMapToErrorMap, EnhancedEffectRouter } from \"./types\";\n\nimport { EffectProcedure } from \"./effect-procedure\";\nimport { effectErrorMapToErrorMap, type EffectErrorMap } from \"./tagged-error\";\n\ninterface EnhanceEffectRouterOptions<\n TEffectErrorMap extends EffectErrorMap,\n TRequirementsProvided,\n TRuntimeError,\n> extends EnhanceRouteOptions {\n middlewares: readonly AnyMiddleware[];\n errorMap: TEffectErrorMap;\n dedupeLeadingMiddlewares: boolean;\n runtime: ManagedRuntime<TRequirementsProvided, TRuntimeError>;\n}\n\nexport function enhanceEffectRouter<\n T extends Lazyable<AnyRouter>,\n TInitialContext extends Context,\n TCurrentContext extends Context,\n TEffectErrorMap extends EffectErrorMap,\n TRequirementsProvided,\n TRuntimeError,\n>(\n router: T,\n options: EnhanceEffectRouterOptions<\n TEffectErrorMap,\n TRequirementsProvided,\n TRuntimeError\n >,\n): EnhancedEffectRouter<T, TInitialContext, TCurrentContext, TEffectErrorMap> {\n if (isLazy(router)) {\n const laziedMeta = getLazyMeta(router);\n const enhancedPrefix = laziedMeta?.prefix\n ? mergePrefix(options.prefix, laziedMeta?.prefix)\n : options.prefix;\n\n const enhanced = lazy(\n async () => {\n const { default: unlaziedRouter } = await unlazy(router);\n const enhanced = enhanceEffectRouter(unlaziedRouter, options);\n return unlazy(enhanced);\n },\n {\n ...laziedMeta,\n prefix: enhancedPrefix,\n },\n );\n\n const accessible = createAccessibleLazyRouter(enhanced);\n\n return accessible as any;\n }\n\n if (isProcedure(router)) {\n const newMiddlewares = mergeMiddlewares(\n options.middlewares,\n router[\"~orpc\"].middlewares,\n { dedupeLeading: options.dedupeLeadingMiddlewares },\n );\n const newMiddlewareAdded =\n newMiddlewares.length - router[\"~orpc\"].middlewares.length;\n\n const effectErrorMap = {\n ...options.errorMap,\n ...router[\"~orpc\"].errorMap,\n };\n const errorMap: EffectErrorMapToErrorMap<typeof effectErrorMap> =\n effectErrorMapToErrorMap(effectErrorMap);\n const enhanced = new EffectProcedure({\n ...router[\"~orpc\"],\n route: enhanceRoute(router[\"~orpc\"].route, options),\n effectErrorMap,\n errorMap: errorMap as EffectErrorMapToErrorMap<typeof effectErrorMap>,\n middlewares: newMiddlewares,\n inputValidationIndex:\n router[\"~orpc\"].inputValidationIndex + newMiddlewareAdded,\n outputValidationIndex:\n router[\"~orpc\"].outputValidationIndex + newMiddlewareAdded,\n runtime: options.runtime,\n });\n\n return enhanced as any;\n }\n\n const enhanced = {} as Record<string, any>;\n\n for (const key in router) {\n enhanced[key] = enhanceEffectRouter(router[key]!, options);\n }\n\n return enhanced as any;\n}\n","import type { ClientContext } from \"@orpc/client\";\nimport type {\n AnySchema,\n InferSchemaInput,\n InferSchemaOutput,\n Meta,\n Route,\n} from \"@orpc/contract\";\nimport type {\n AnyMiddleware,\n Context,\n CreateProcedureClientOptions,\n MapInputMiddleware,\n MergedCurrentContext,\n MergedInitialContext,\n Middleware,\n ProcedureActionableClient,\n ProcedureClient,\n ProcedureDef,\n} from \"@orpc/server\";\nimport type { IntersectPick, MaybeOptionalOptions } from \"@orpc/shared\";\n\nimport { mergeMeta, mergeRoute } from \"@orpc/contract\";\nimport {\n addMiddleware,\n createActionableClient,\n createProcedureClient,\n decorateMiddleware,\n Procedure,\n} from \"@orpc/server\";\n\nimport type {\n EffectErrorConstructorMap,\n EffectErrorMap,\n MergedEffectErrorMap,\n} from \"./tagged-error\";\nimport type { EffectErrorMapToErrorMap, EffectProcedureDef } from \"./types\";\n\nimport { effectErrorMapToErrorMap } from \"./tagged-error\";\n\nexport class EffectProcedure<\n TInitialContext extends Context,\n TCurrentContext extends Context,\n TInputSchema extends AnySchema,\n TOutputSchema extends AnySchema,\n TEffectErrorMap extends EffectErrorMap,\n TMeta extends Meta,\n TRequirementsProvided,\n TRuntimeError,\n> extends Procedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta\n> {\n /**\n * This property holds the defined options and the effect-specific properties.\n */\n declare \"~effect\": EffectProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n /**\n * This property holds the defined options.\n */\n declare \"~orpc\": ProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta\n >;\n\n constructor(\n def: EffectProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >,\n ) {\n super(def);\n this[\"~effect\"] = def;\n }\n}\n\n/**\n * An Effect-native decorated procedure that preserves Effect error and requirements types.\n *\n * This class extends Procedure with additional type parameters for Effect-specific\n * type information, allowing full type inference of Effect errors and requirements.\n */\nexport class EffectDecoratedProcedure<\n TInitialContext extends Context,\n TCurrentContext extends Context,\n TInputSchema extends AnySchema,\n TOutputSchema extends AnySchema,\n TEffectErrorMap extends EffectErrorMap,\n TMeta extends Meta,\n TRequirementsProvided,\n TRuntimeError,\n> extends EffectProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n> {\n /**\n * This property holds the defined options and the effect-specific properties.\n */\n declare \"~effect\": EffectProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n declare \"~orpc\": ProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta\n >;\n\n constructor(\n def: EffectProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >,\n ) {\n super(def);\n this[\"~effect\"] = def;\n }\n\n /**\n * Adds type-safe custom errors.\n * Supports both traditional oRPC error definitions and ORPCTaggedError classes.\n *\n * @see {@link https://orpc.dev/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}\n */\n errors<U extends EffectErrorMap>(\n errors: U,\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n MergedEffectErrorMap<TEffectErrorMap, U>,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n const newEffectErrorMap: MergedEffectErrorMap<TEffectErrorMap, U> = {\n ...this[\"~effect\"].effectErrorMap,\n ...errors,\n };\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n effectErrorMap: newEffectErrorMap,\n errorMap: effectErrorMapToErrorMap(newEffectErrorMap),\n });\n }\n\n /**\n * Sets or updates the metadata.\n * The provided metadata is spared-merged with any existing metadata.\n *\n * @see {@link https://orpc.dev/docs/metadata Metadata Docs}\n */\n meta(\n meta: TMeta,\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n meta: mergeMeta(this[\"~effect\"].meta, meta),\n });\n }\n\n /**\n * Sets or updates the route definition.\n * The provided route is spared-merged with any existing route.\n * This option is typically relevant when integrating with OpenAPI.\n *\n * @see {@link https://orpc.dev/docs/openapi/routing OpenAPI Routing Docs}\n * @see {@link https://orpc.dev/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}\n */\n route(\n route: Route,\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n route: mergeRoute(this[\"~effect\"].route, route),\n });\n }\n\n /**\n * Uses a middleware to modify the context or improve the pipeline.\n *\n * @info Supports both normal middleware and inline middleware implementations.\n * @info Pass second argument to map the input.\n * @note The current context must be satisfy middleware dependent-context\n * @see {@link https://orpc.dev/docs/middleware Middleware Docs}\n */\n use<\n UOutContext extends IntersectPick<TCurrentContext, UOutContext>,\n UInContext extends Context = TCurrentContext,\n >(\n middleware: Middleware<\n UInContext | TCurrentContext,\n UOutContext,\n InferSchemaOutput<TInputSchema>,\n InferSchemaInput<TOutputSchema>,\n EffectErrorConstructorMap<TEffectErrorMap>,\n TMeta\n >,\n ): EffectDecoratedProcedure<\n MergedInitialContext<TInitialContext, UInContext, TCurrentContext>,\n MergedCurrentContext<TCurrentContext, UOutContext>,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n\n /**\n * Uses a middleware to modify the context or improve the pipeline.\n *\n * @info Supports both normal middleware and inline middleware implementations.\n * @info Pass second argument to map the input.\n * @note The current context must be satisfy middleware dependent-context\n * @see {@link https://orpc.dev/docs/middleware Middleware Docs}\n */\n use<\n UOutContext extends IntersectPick<TCurrentContext, UOutContext>,\n UInput,\n UInContext extends Context = TCurrentContext,\n >(\n middleware: Middleware<\n UInContext | TCurrentContext,\n UOutContext,\n UInput,\n InferSchemaInput<TOutputSchema>,\n EffectErrorConstructorMap<TEffectErrorMap>,\n TMeta\n >,\n mapInput: MapInputMiddleware<InferSchemaOutput<TInputSchema>, UInput>,\n ): EffectDecoratedProcedure<\n MergedInitialContext<TInitialContext, UInContext, TCurrentContext>,\n MergedCurrentContext<TCurrentContext, UOutContext>,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n\n use(\n middleware: AnyMiddleware,\n mapInput?: MapInputMiddleware<any, any>,\n ): EffectDecoratedProcedure<any, any, any, any, any, any, any, any> {\n const mapped = mapInput\n ? decorateMiddleware(middleware).mapInput(mapInput)\n : middleware;\n\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n middlewares: addMiddleware(this[\"~effect\"].middlewares, mapped),\n });\n }\n\n /**\n * Make this procedure callable (works like a function while still being a procedure).\n *\n * @see {@link https://orpc.dev/docs/client/server-side Server-side Client Docs}\n */\n callable<TClientContext extends ClientContext>(\n ...rest: MaybeOptionalOptions<\n CreateProcedureClientOptions<\n TInitialContext,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta,\n TClientContext\n >\n >\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > &\n ProcedureClient<\n TClientContext,\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>\n > {\n const client: ProcedureClient<\n TClientContext,\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>\n > = createProcedureClient(this, ...rest);\n\n return new Proxy(client, {\n get: (target, key) => {\n return Reflect.has(this, key)\n ? Reflect.get(this, key)\n : Reflect.get(target, key);\n },\n has: (target, key) => {\n return Reflect.has(this, key) || Reflect.has(target, key);\n },\n }) as any;\n }\n\n /**\n * Make this procedure compatible with server action.\n *\n * @see {@link https://orpc.dev/docs/server-action Server Action Docs}\n */\n actionable(\n ...rest: MaybeOptionalOptions<\n CreateProcedureClientOptions<\n TInitialContext,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta,\n Record<never, never>\n >\n >\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > &\n ProcedureActionableClient<\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>\n > {\n const action: ProcedureActionableClient<\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>\n > = createActionableClient(createProcedureClient(this, ...rest));\n\n return new Proxy(action, {\n get: (target, key) => {\n return Reflect.has(this, key)\n ? Reflect.get(this, key)\n : Reflect.get(target, key);\n },\n has: (target, key) => {\n return Reflect.has(this, key) || Reflect.has(target, key);\n },\n }) as any;\n }\n}\n","import type {\n ORPCErrorCode,\n ORPCErrorJSON,\n ORPCErrorOptions,\n} from \"@orpc/client\";\nimport type {\n AnySchema,\n ErrorMap,\n ErrorMapItem,\n InferSchemaOutput,\n} from \"@orpc/contract\";\nimport type { ORPCErrorConstructorMap } from \"@orpc/server\";\nimport type { MaybeOptionalOptions } from \"@orpc/shared\";\nimport type { Pipeable } from \"effect\";\n\nimport {\n fallbackORPCErrorMessage,\n fallbackORPCErrorStatus,\n isORPCErrorStatus,\n ORPCError,\n} from \"@orpc/client\";\nimport { resolveMaybeOptionalOptions } from \"@orpc/shared\";\nimport * as Cause from \"effect/Cause\";\nimport * as Data from \"effect/Data\";\n\nimport type { EffectErrorMapToErrorMap } from \"./types\";\n\n/**\n * Symbol to access the underlying ORPCError instance\n */\nexport const ORPCErrorSymbol: unique symbol = Symbol.for(\n \"@orpc/effect/ORPCTaggedError\",\n);\n\n/**\n * Instance type for ORPCTaggedError that combines YieldableError with ORPCError properties\n */\nexport interface ORPCTaggedErrorInstance<\n TTag extends string,\n TCode extends ORPCErrorCode,\n TSchema extends AnySchema = AnySchema,\n>\n extends Cause.YieldableError, Pipeable.Pipeable {\n readonly _tag: TTag;\n readonly code: TCode;\n readonly status: number;\n readonly schema: TSchema;\n readonly data: InferSchemaOutput<TSchema>;\n readonly defined: boolean;\n readonly [ORPCErrorSymbol]: ORPCError<TCode, InferSchemaOutput<TSchema>>;\n\n toJSON(): ORPCErrorJSON<TCode, InferSchemaOutput<TSchema>> & { _tag: TTag };\n toORPCError(): ORPCError<TCode, InferSchemaOutput<TSchema>>;\n}\n\n/**\n * Options for creating an ORPCTaggedError\n */\nexport type ORPCTaggedErrorOptions<TData> = Omit<\n ORPCErrorOptions<TData>,\n \"defined\"\n> & { defined?: boolean };\n\n/**\n * Constructor type for ORPCTaggedError classes\n */\nexport interface ORPCTaggedErrorClass<\n TTag extends string,\n TCode extends ORPCErrorCode,\n TSchema extends AnySchema = AnySchema,\n> {\n readonly _tag: TTag;\n readonly code: TCode;\n new (\n ...args: MaybeOptionalOptions<\n ORPCTaggedErrorOptions<InferSchemaOutput<TSchema>>\n >\n ): ORPCTaggedErrorInstance<TTag, TCode, TSchema>;\n}\n\n/**\n * Type helper to infer the ORPCError type from an ORPCTaggedError\n */\nexport type InferORPCError<T> =\n T extends ORPCTaggedErrorInstance<string, infer TCode, infer TSchema>\n ? ORPCError<TCode, InferSchemaOutput<TSchema>>\n : never;\n\n/**\n * Any ORPCTaggedErrorClass\n * Uses `...args: any[]` for the constructor to accept any tagged error class,\n * regardless of whether TData requires options to be provided.\n */\nexport type AnyORPCTaggedErrorClass = {\n readonly _tag: string;\n readonly code: ORPCErrorCode;\n new (\n ...args: any[]\n ): ORPCTaggedErrorInstance<string, ORPCErrorCode, AnySchema>;\n};\n\n/**\n * Check if a value is an ORPCTaggedErrorClass (constructor)\n */\nexport function isORPCTaggedErrorClass(\n value: unknown,\n): value is AnyORPCTaggedErrorClass {\n return (\n typeof value === \"function\" &&\n \"_tag\" in value &&\n \"code\" in value &&\n typeof value._tag === \"string\" &&\n typeof value.code === \"string\"\n );\n}\n\n/**\n * Check if a value is an ORPCTaggedError instance\n */\nexport function isORPCTaggedError(\n value: unknown,\n): value is ORPCTaggedErrorInstance<string, ORPCErrorCode, AnySchema> {\n return (\n typeof value === \"object\" && value !== null && ORPCErrorSymbol in value\n );\n}\n\n/**\n * Converts a PascalCase or camelCase string to CONSTANT_CASE.\n * e.g., \"UserNotFoundError\" -> \"USER_NOT_FOUND_ERROR\"\n */\nfunction toConstantCase<T extends string>(str: T): ToConstantCase<T> {\n return str\n .replace(/([a-z])([A-Z])/g, \"$1_$2\")\n .replace(/([A-Z])([A-Z][a-z])/g, \"$1_$2\")\n .toUpperCase() as ToConstantCase<T>;\n}\n/**\n * Checks if a character is an uppercase letter (A-Z)\n */\ntype IsUpperLetter<C extends string> =\n C extends Uppercase<C>\n ? C extends Lowercase<C>\n ? false // Not a letter (number, special char)\n : true\n : false;\n\n/**\n * Checks if a character is a lowercase letter (a-z)\n */\ntype IsLowerLetter<C extends string> =\n C extends Lowercase<C>\n ? C extends Uppercase<C>\n ? false // Not a letter (number, special char)\n : true\n : false;\n\n/**\n * Converts PascalCase or camelCase to CONSTANT_CASE.\n * Handles consecutive uppercase letters correctly.\n *\n * @example\n * type T1 = ToConstantCase<\"ABCCode\">; // \"ABC_CODE\"\n * type T2 = ToConstantCase<\"UserCode\">; // \"USER_CODE\"\n * type T3 = ToConstantCase<\"XMLHttpRequest\">; // \"XML_HTTP_REQUEST\"\n */\ntype ToConstantCase<\n S extends string,\n Acc extends string = \"\",\n PrevChar extends string = \"\",\n InUpperSequence extends boolean = false,\n> = S extends `${infer Head}${infer Tail}`\n ? IsUpperLetter<Head> extends true\n ? Acc extends \"\"\n ? // First character - no underscore\n ToConstantCase<Tail, Head, Head, false>\n : PrevChar extends \"\"\n ? // Shouldn't happen, but handle gracefully\n ToConstantCase<Tail, Head, Head, false>\n : IsUpperLetter<PrevChar> extends true\n ? // We're in an uppercase sequence\n Tail extends `${infer Next}${infer _}`\n ? IsLowerLetter<Next> extends true\n ? // Next char is lowercase, so Head starts a new word - insert underscore\n ToConstantCase<Tail, `${Acc}_${Head}`, Head, false>\n : // Next char is uppercase or non-letter - continue sequence\n ToConstantCase<Tail, `${Acc}${Head}`, Head, true>\n : // Tail is empty - just append\n ToConstantCase<Tail, `${Acc}${Head}`, Head, true>\n : // Transition from lowercase to uppercase - insert underscore\n ToConstantCase<Tail, `${Acc}_${Head}`, Head, false>\n : IsLowerLetter<Head> extends true\n ? InUpperSequence extends true\n ? // End of uppercase sequence (2+) - insert underscore before lowercase\n ToConstantCase<Tail, `${Acc}_${Uppercase<Head>}`, Head, false>\n : // Single uppercase or no uppercase - no underscore\n ToConstantCase<Tail, `${Acc}${Uppercase<Head>}`, Head, false>\n : // Non-letter character - reset sequence\n ToConstantCase<Tail, `${Acc}${Head}`, Head, false>\n : Acc;\n\n/**\n * Converts a tag name to an error code in CONSTANT_CASE.\n */\nexport type TagToCode<TTag extends string> = ToConstantCase<TTag>;\n\n/**\n * Creates a tagged error class that combines Effect's YieldableError with ORPCError.\n *\n * This allows you to create errors that:\n * - Can be yielded in Effect generators (`yield* myError`)\n * - Have all ORPCError properties (code, status, data, defined)\n * - Can be converted to a plain ORPCError for oRPC handlers\n *\n * The returned factory function takes:\n * - `tag` - The unique tag for this error type (used for discriminated unions)\n * - `codeOrOptions` - Optional ORPC error code or options. If omitted, code defaults to CONSTANT_CASE of tag\n * - `defaultOptions` - Optional default options for status and message (when code is provided)\n *\n * @example\n * ```ts\n * import { ORPCTaggedError } from '@orpc/effect'\n * import { Effect } from 'effect'\n *\n * // Define a custom error (code defaults to 'USER_NOT_FOUND_ERROR')\n * class UserNotFoundError extends ORPCTaggedError<UserNotFoundError>()('UserNotFoundError') {}\n *\n * // With explicit code\n * class NotFoundError extends ORPCTaggedError<NotFoundError>()('NotFoundError', 'NOT_FOUND') {}\n *\n * // Use in an Effect\n * const getUser = (id: string) => Effect.gen(function* () {\n * const user = yield* findUser(id)\n * if (!user) {\n * return yield* new UserNotFoundError({ data: { userId: id } })\n * }\n * return user\n * })\n *\n * // With custom data type\n * class ValidationError extends ORPCTaggedError<ValidationError, { fields: string[] }>()('ValidationError', 'BAD_REQUEST') {}\n *\n * // With options only (code defaults to 'VALIDATION_ERROR')\n * class ValidationError2 extends ORPCTaggedError<ValidationError2, { fields: string[] }>()(\n * 'ValidationError2',\n * { message: 'Validation failed' }\n * ) {}\n * ```\n */\nexport function ORPCTaggedError<\n TTag extends string,\n TSchema extends AnySchema = AnySchema,\n TCode extends ORPCErrorCode = ToConstantCase<TTag>,\n>(\n tag: TTag,\n props?: {\n schema?: TSchema;\n status?: number;\n message?: string;\n code?: TCode;\n },\n): ORPCTaggedErrorClass<TTag, TCode, TSchema> {\n const code: TCode = props?.code ?? (toConstantCase(tag) as any);\n class ORPCTaggedErrorBase\n extends Data.TaggedError(tag)\n implements ORPCTaggedErrorInstance<TTag, TCode, TSchema>\n {\n readonly status: number;\n readonly defined: boolean;\n readonly data: InferSchemaOutput<TSchema>;\n readonly code: TCode = code;\n readonly schema = props?.schema as TSchema;\n readonly [ORPCErrorSymbol]: ORPCError<TCode, InferSchemaOutput<TSchema>>;\n\n constructor(\n ...rest: MaybeOptionalOptions<\n ORPCTaggedErrorOptions<InferSchemaOutput<TSchema>>\n >\n ) {\n super();\n\n const opts = resolveMaybeOptionalOptions(rest);\n const status = opts.status ?? props?.status;\n\n if (status !== undefined && !isORPCErrorStatus(status)) {\n throw new globalThis.Error(\n \"[ORPCTaggedError] Invalid error status code.\",\n );\n }\n\n this.status = fallbackORPCErrorStatus(code, status);\n this.defined = opts.defined ?? true;\n this.data = opts.data as InferSchemaOutput<TSchema>;\n this.message = fallbackORPCErrorMessage(\n this.code,\n opts.message ?? props?.message,\n );\n this.cause = opts.cause;\n\n this[ORPCErrorSymbol] = new ORPCError<TCode, InferSchemaOutput<TSchema>>(\n this.code,\n {\n status: this.status,\n message: this.message,\n data: this.data,\n defined: this.defined,\n cause: this.cause,\n },\n );\n }\n\n /**\n * Converts this error to a plain ORPCError.\n * Useful when you need to return from an oRPC handler.\n */\n toORPCError(): ORPCError<TCode, InferSchemaOutput<TSchema>> {\n return this[ORPCErrorSymbol];\n }\n\n override toJSON(): ORPCErrorJSON<TCode, InferSchemaOutput<TSchema>> & {\n _tag: TTag;\n } {\n return {\n _tag: this._tag,\n defined: this[ORPCErrorSymbol].defined,\n code: this[ORPCErrorSymbol].code,\n status: this[ORPCErrorSymbol].status,\n message: this[ORPCErrorSymbol].message,\n data: this[ORPCErrorSymbol].data,\n };\n }\n }\n\n return Object.assign(ORPCTaggedErrorBase, {\n _tag: tag,\n code,\n } as const);\n}\n\n/**\n * Converts an ORPCTaggedError to a plain ORPCError.\n * Useful in handlers that need to throw ORPCError.\n *\n * @example\n * ```ts\n * const handler = effectOs.effect(function* () {\n * const result = yield* someOperation.pipe(\n * Effect.catchTag('UserNotFoundError', (e) =>\n * Effect.fail(toORPCError(e))\n * )\n * )\n * return result\n * })\n * ```\n */\nexport function toORPCError<\n TCode extends ORPCErrorCode,\n TSchema extends AnySchema = AnySchema,\n>(\n error: ORPCTaggedErrorInstance<string, TCode, TSchema>,\n): ORPCError<TCode, InferSchemaOutput<TSchema>> {\n return error[ORPCErrorSymbol];\n}\n\n// ============================================================================\n// Extended Error Map Types for Effect\n// ============================================================================\n\n/**\n * An item in the EffectErrorMap - can be either a traditional ErrorMapItem or an ORPCTaggedErrorClass\n */\nexport type EffectErrorMapItem =\n | ErrorMapItem<AnySchema>\n | AnyORPCTaggedErrorClass;\n\nexport type ORPCTaggedErrorClassToErrorMapItem<T> =\n T extends ORPCTaggedErrorClass<any, any, infer TData>\n ? {\n status?: number;\n message?: string;\n data?: TData;\n }\n : never;\n\n/**\n * Extended error map that supports both traditional oRPC errors and ORPCTaggedError classes.\n *\n * @example\n * ```ts\n * const errorMap = {\n * // Traditional format\n * BAD_REQUEST: { status: 400, message: 'Bad request' },\n *\n * // Tagged error class reference\n * USER_NOT_FOUND: UserNotFoundError,\n * } satisfies EffectErrorMap\n * ```\n */\nexport type EffectErrorMap = {\n [key in ORPCErrorCode]?: EffectErrorMapItem;\n};\n\n/**\n * Merges two EffectErrorMaps, with the second map taking precedence.\n */\nexport type MergedEffectErrorMap<\n T1 extends EffectErrorMap,\n T2 extends EffectErrorMap,\n> = Omit<T1, keyof T2> & T2;\n\n/**\n * Extracts the instance type from an EffectErrorMapItem\n */\nexport type EffectErrorMapItemToInstance<\n TCode extends ORPCErrorCode,\n T extends EffectErrorMapItem,\n> = T extends AnyORPCTaggedErrorClass\n ? InstanceType<T>\n : T extends { data?: infer TData }\n ? ORPCError<TCode, TData>\n : ORPCError<TCode, unknown>;\n\n/**\n * Converts an EffectErrorMap to a union of error instances.\n */\nexport type EffectErrorMapToUnion<T extends EffectErrorMap> = {\n [K in keyof T]: K extends ORPCErrorCode\n ? T[K] extends EffectErrorMapItem\n ? EffectErrorMapItemToInstance<K, T[K]>\n : never\n : never;\n}[keyof T];\n\n/**\n * Constructor map for EffectErrorMap - provides typed error constructors for handlers.\n */\nexport type EffectErrorConstructorMap<T extends EffectErrorMap> =\n ORPCErrorConstructorMap<EffectErrorMapToErrorMap<T>>;\n\n/**\n * Creates an error constructor map from an EffectErrorMap.\n * Tagged error classes are passed through directly.\n * Traditional error items become ORPCError factory functions.\n */\nexport function createEffectErrorConstructorMap<T extends EffectErrorMap>(\n errors: T | undefined,\n): EffectErrorConstructorMap<T> {\n const target = errors ?? ({} as T);\n const proxy = new Proxy(target, {\n get(proxyTarget, code) {\n if (typeof code !== \"string\") {\n return Reflect.get(proxyTarget, code);\n }\n\n const config = target[code];\n\n // If it's a tagged error class, create a class constructor function\n if (isORPCTaggedErrorClass(config)) {\n return (\n ...opts: MaybeOptionalOptions<ORPCTaggedErrorOptions<unknown>>\n ) => new config(...opts);\n }\n\n // Otherwise, create a factory function for ORPCError\n return (\n ...rest: MaybeOptionalOptions<\n Omit<ORPCErrorOptions<unknown>, \"defined\" | \"status\">\n >\n ) => {\n const options = resolveMaybeOptionalOptions(rest);\n return new ORPCError(code, {\n defined: Boolean(config),\n status: config?.status,\n message: options.message ?? config?.message,\n data: options.data,\n cause: options.cause,\n });\n };\n },\n });\n\n return proxy as EffectErrorConstructorMap<T>;\n}\n\n/**\n * Converts an EffectErrorMap to a standard oRPC ErrorMap for interop.\n * Tagged error classes are converted to their equivalent ErrorMapItem format.\n */\nexport function effectErrorMapToErrorMap<T extends EffectErrorMap>(\n errorMap: T | undefined,\n): EffectErrorMapToErrorMap<T> {\n const result: ErrorMap = {};\n\n if (!errorMap) {\n return result as ErrorMap & EffectErrorMapToErrorMap<T>;\n }\n\n for (const [code, ClassOrErrorItem] of Object.entries(errorMap)) {\n if (!ClassOrErrorItem) {\n continue;\n }\n\n if (isORPCTaggedErrorClass(ClassOrErrorItem)) {\n const classInstance = new ClassOrErrorItem();\n result[classInstance.code] = {\n status: classInstance.status,\n message: classInstance.message,\n data: classInstance.schema,\n };\n } else {\n result[code] = ClassOrErrorItem;\n }\n }\n\n return result as ErrorMap & EffectErrorMapToErrorMap<T>;\n}\n"],"mappings":";;;;;AA2BA;AAAA,EACE,aAAAA;AAAA,EACA,eAAAC;AAAA,EACA,cAAAC;AAAA,EACA;AAAA,EACA,aAAAC;AAAA,OACK;AACP;AAAA,EACE,iBAAAC;AAAA,EACA;AAAA,EACA,sBAAAC;AAAA,EACA;AAAA,EACA,QAAAC;AAAA,OACK;AACP,SAAS,SAAAC,QAAO,QAAQ,YAAY;;;ACvCpC;AAAA,EACE;AAAA,E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O,IAAI,eAAc;AAAA,MACvB,GAAG,KAAK,SAAS;AAAA,MACjB,MAAM,UAAU,KAAK,SAAS,EAAE,MAAM,IAAI;AAAA,IAC5C,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OACE,QAMA;AACA,WAAO,oBAAoB,QAAQ;AAAA,MACjC,GAAG,KAAK,SAAS;AAAA,IACnB,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,KACE,QAMA;AACA,WAAO,oBAAoBC,MAAK,MAAM,GAAG;AAAA,MACvC,GAAG,KAAK,SAAS;AAAA,IACnB,CAAC;AAAA,EACH;AACF;AA2FO,SAAS,eACd,SACA,SAUA;AACA,QAAM,kBAAkB,WAAW,aAAa;AAChD,SAAO,IAAI,cAAc;AAAA,IACvB,GAAG,gBAAgB,OAAO;AAAA,IAC1B,UAAU,yBAAyB,gBAAgB,OAAO,EAAE,QAAQ;AAAA,IACpE,gBAAgB,gBAAgB,OAAO,EAAE;AAAA,IACzC;AAAA,EACF,CAAC;AACH;AAEA,SAAS,eAA+B;AACtC,SAAO,IAAI,QAAQ;AAAA,IACjB,QAAQ,CAAC;AAAA,IACT,OAAO,CAAC;AAAA,IACR,MAAM,CAAC;AAAA,IACP,UAAU,CAAC;AAAA,IACX,sBAAsB,eAAe,6BAA6B;AAAA,IAClE,uBAAuB,eAAe,8BAA8B;AAAA,IACpE,aAAa,CAAC;AAAA,IACd,0BAA0B;AAAA,EAC5B,CAAC;AACH;","names":["mergeMeta","mergePrefix","mergeRoute","ORPCError","addMiddleware","decorateMiddleware","lazy","Cause","enhanced","decorateMiddleware","addMiddleware","mergeMeta","mergeRoute","Cause","ORPCError","mergePrefix","lazy"]}
1
+ {"version":3,"sources":["../src/effect-builder.ts","../src/effect-enhance-router.ts","../src/effect-procedure.ts","../src/tagged-error.ts"],"sourcesContent":["import type {\n AnySchema,\n ContractRouter,\n ErrorMap,\n HTTPPath,\n InferSchemaOutput,\n Meta,\n Route,\n Schema,\n} from \"@orpc/contract\";\nimport type {\n AnyMiddleware,\n BuilderConfig,\n BuilderDef,\n Context,\n Lazy,\n MapInputMiddleware,\n MergedCurrentContext,\n MergedInitialContext,\n Middleware,\n ProcedureHandler,\n ProcedureHandlerOptions,\n Router,\n} from \"@orpc/server\";\nimport type { IntersectPick } from \"@orpc/shared\";\nimport type { ManagedRuntime } from \"effect\";\n\nimport {\n mergeMeta,\n mergePrefix,\n mergeRoute,\n mergeTags,\n ORPCError,\n} from \"@orpc/contract\";\nimport {\n addMiddleware,\n Builder,\n decorateMiddleware,\n fallbackConfig,\n lazy,\n} from \"@orpc/server\";\nimport { Cause, Effect, Exit, FiberRefs } from \"effect\";\n\nimport type {\n EffectErrorConstructorMap,\n EffectErrorMap,\n MergedEffectErrorMap,\n} from \"./tagged-error\";\nimport type {\n AnyBuilderLike,\n EffectBuilderDef,\n EffectErrorMapToErrorMap,\n EffectProcedureBuilderWithInput,\n EffectProcedureBuilderWithOutput,\n EffectProcedureHandler,\n EffectRouterBuilder,\n EnhancedEffectRouter,\n InferBuilderCurrentContext,\n InferBuilderErrorMap,\n InferBuilderInitialContext,\n InferBuilderInputSchema,\n InferBuilderMeta,\n InferBuilderOutputSchema,\n} from \"./types\";\n\nimport { enhanceEffectRouter } from \"./effect-enhance-router\";\nimport { EffectDecoratedProcedure } from \"./effect-procedure\";\nimport { getCurrentFiberRefs } from \"./fiber-context-bridge\";\nimport {\n createEffectErrorConstructorMap,\n effectErrorMapToErrorMap,\n isORPCTaggedError,\n} from \"./tagged-error\";\n\n/**\n * Captures the stack trace at the call site for better error reporting in spans.\n * This is called at procedure definition time to capture where the procedure was defined.\n *\n * @returns A function that lazily extracts the relevant stack frame\n */\nexport function addSpanStackTrace(): () => string | undefined {\n const ErrorConstructor = Error as typeof Error & {\n stackTraceLimit?: number;\n };\n const limit = ErrorConstructor.stackTraceLimit;\n ErrorConstructor.stackTraceLimit = 3;\n const traceError = new Error();\n ErrorConstructor.stackTraceLimit = limit;\n let cache: false | string = false;\n return () => {\n if (cache !== false) {\n return cache;\n }\n if (traceError.stack !== undefined) {\n const stack = traceError.stack.split(\"\\n\");\n if (stack[3] !== undefined) {\n cache = stack[3].trim();\n return cache;\n }\n }\n };\n}\n\n/**\n * Effect-native procedure builder that wraps an oRPC Builder instance\n * and adds Effect-specific capabilities while preserving Effect error\n * and requirements types.\n */\nexport class EffectBuilder<\n TInitialContext extends Context,\n TCurrentContext extends Context,\n TInputSchema extends AnySchema,\n TOutputSchema extends AnySchema,\n TEffectErrorMap extends EffectErrorMap,\n TMeta extends Meta,\n TRequirementsProvided,\n TRuntimeError,\n> {\n /**\n * This property holds the defined options and the effect-specific properties.\n */\n declare \"~effect\": EffectBuilderDef<\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n declare \"~orpc\": BuilderDef<\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta\n >;\n\n constructor(\n def: EffectBuilderDef<\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >,\n ) {\n const { runtime, spanConfig, effectErrorMap, ...orpcDef } = def;\n this[\"~orpc\"] = orpcDef;\n this[\"~effect\"] = { runtime, spanConfig, effectErrorMap, ...orpcDef };\n }\n\n /**\n * Sets or overrides the config.\n *\n * @see {@link https://orpc.dev/docs/client/server-side#middlewares-order Middlewares Order Docs}\n * @see {@link https://orpc.dev/docs/best-practices/dedupe-middleware#configuration Dedupe Middleware Docs}\n */\n $config(\n config: BuilderConfig,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n const inputValidationCount =\n this[\"~effect\"].inputValidationIndex -\n fallbackConfig(\n \"initialInputValidationIndex\",\n this[\"~effect\"].config.initialInputValidationIndex,\n );\n const outputValidationCount =\n this[\"~effect\"].outputValidationIndex -\n fallbackConfig(\n \"initialOutputValidationIndex\",\n this[\"~effect\"].config.initialOutputValidationIndex,\n );\n\n return new EffectBuilder({\n ...this[\"~effect\"],\n config,\n dedupeLeadingMiddlewares: fallbackConfig(\n \"dedupeLeadingMiddlewares\",\n config.dedupeLeadingMiddlewares,\n ),\n inputValidationIndex:\n fallbackConfig(\n \"initialInputValidationIndex\",\n config.initialInputValidationIndex,\n ) + inputValidationCount,\n outputValidationIndex:\n fallbackConfig(\n \"initialOutputValidationIndex\",\n config.initialOutputValidationIndex,\n ) + outputValidationCount,\n });\n }\n\n /**\n * Set or override the initial context.\n *\n * @see {@link https://orpc.dev/docs/context Context Docs}\n */\n $context<U extends Context>(): EffectBuilder<\n U & Record<never, never>,\n U,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n /**\n * We need `& Record<never, never>` to deal with `has no properties in common with type` error\n */\n\n return new EffectBuilder({\n ...this[\"~effect\"],\n middlewares: [],\n inputValidationIndex: fallbackConfig(\n \"initialInputValidationIndex\",\n this[\"~effect\"].config.initialInputValidationIndex,\n ),\n outputValidationIndex: fallbackConfig(\n \"initialOutputValidationIndex\",\n this[\"~effect\"].config.initialOutputValidationIndex,\n ),\n });\n }\n\n /**\n * Sets or overrides the initial meta.\n *\n * @see {@link https://orpc.dev/docs/metadata Metadata Docs}\n */\n $meta<U extends Meta>(\n initialMeta: U,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n U & Record<never, never>,\n TRequirementsProvided,\n TRuntimeError\n > {\n /**\n * We need `& Record<never, never>` to deal with `has no properties in common with type` error\n */\n\n return new EffectBuilder({\n ...this[\"~effect\"],\n meta: initialMeta,\n });\n }\n\n /**\n * Sets or overrides the initial route.\n * This option is typically relevant when integrating with OpenAPI.\n *\n * @see {@link https://orpc.dev/docs/openapi/routing OpenAPI Routing Docs}\n * @see {@link https://orpc.dev/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}\n */\n $route(\n initialRoute: Route,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n route: initialRoute,\n });\n }\n\n /**\n * Sets or overrides the initial input schema.\n *\n * @see {@link https://orpc.dev/docs/procedure#initial-configuration Initial Procedure Configuration Docs}\n */\n $input<U extends AnySchema>(\n initialInputSchema?: U,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n U,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n inputSchema: initialInputSchema,\n });\n }\n\n /**\n * Adds type-safe custom errors.\n * Supports both traditional oRPC error definitions and ORPCTaggedError classes.\n *\n * @example\n * ```ts\n * // Traditional format\n * builder.errors({ BAD_REQUEST: { status: 400, message: 'Bad request' } })\n *\n * // Tagged error class\n * builder.errors({ USER_NOT_FOUND: UserNotFoundError })\n *\n * // Mixed\n * builder.errors({\n * BAD_REQUEST: { status: 400 },\n * USER_NOT_FOUND: UserNotFoundError,\n * })\n * ```\n *\n * @see {@link https://orpc.dev/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}\n */\n errors<U extends EffectErrorMap>(\n errors: U,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n MergedEffectErrorMap<TEffectErrorMap, U>,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n const newEffectErrorMap: MergedEffectErrorMap<TEffectErrorMap, U> = {\n ...this[\"~effect\"].effectErrorMap,\n ...errors,\n };\n return new EffectBuilder({\n ...this[\"~effect\"],\n errorMap: effectErrorMapToErrorMap(newEffectErrorMap),\n effectErrorMap: newEffectErrorMap,\n });\n }\n\n /**\n * Uses a middleware to modify the context or improve the pipeline.\n *\n * @info Supports both normal middleware and inline middleware implementations.\n * @note The current context must be satisfy middleware dependent-context\n * @see {@link https://orpc.dev/docs/middleware Middleware Docs}\n */\n use<\n UOutContext extends IntersectPick<TCurrentContext, UOutContext>,\n UInContext extends Context = TCurrentContext,\n >(\n middleware: Middleware<\n UInContext | TCurrentContext,\n UOutContext,\n InferSchemaOutput<TInputSchema>,\n unknown,\n EffectErrorConstructorMap<TEffectErrorMap>,\n TMeta\n >,\n ): EffectBuilder<\n MergedInitialContext<TInitialContext, UInContext, TCurrentContext>,\n MergedCurrentContext<TCurrentContext, UOutContext>,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n\n use(\n middleware: AnyMiddleware,\n mapInput?: MapInputMiddleware<any, any>,\n ): EffectBuilder<any, any, any, any, any, any, any, any> {\n const mapped = mapInput\n ? decorateMiddleware(middleware).mapInput(mapInput)\n : middleware;\n\n return new EffectBuilder({\n ...this[\"~effect\"],\n middlewares: addMiddleware(this[\"~effect\"].middlewares, mapped),\n });\n }\n\n /**\n * Sets or updates the metadata.\n * The provided metadata is spared-merged with any existing metadata.\n *\n * @see {@link https://orpc.dev/docs/metadata Metadata Docs}\n */\n meta(\n meta: TMeta,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n meta: mergeMeta(this[\"~effect\"].meta, meta),\n });\n }\n\n /**\n * Sets or updates the route definition.\n * The provided route is spared-merged with any existing route.\n * This option is typically relevant when integrating with OpenAPI.\n *\n * @see {@link https://orpc.dev/docs/openapi/routing OpenAPI Routing Docs}\n * @see {@link https://orpc.dev/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}\n */\n route(\n route: Route,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n route: mergeRoute(this[\"~effect\"].route, route),\n });\n }\n\n /**\n * Defines the input validation schema.\n *\n * @see {@link https://orpc.dev/docs/procedure#input-output-validation Input Validation Docs}\n */\n input<USchema extends AnySchema>(\n schema: USchema,\n ): EffectProcedureBuilderWithInput<\n TInitialContext,\n TCurrentContext,\n USchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n inputSchema: schema,\n inputValidationIndex:\n fallbackConfig(\n \"initialInputValidationIndex\",\n this[\"~effect\"].config.initialInputValidationIndex,\n ) + this[\"~effect\"].middlewares.length,\n // we cast to any because EffectProcedureBuilderWithInput is expecting\n // use() input type to be defined, and EffectBuilder types its use() input\n // to unknown to allow any middleware to be passed\n // ---\n // note: the original implentation of the builder also uses any for the same reason\n }) as any;\n }\n\n /**\n * Defines the output validation schema.\n *\n * @see {@link https://orpc.dev/docs/procedure#input-output-validation Output Validation Docs}\n */\n output<USchema extends AnySchema>(\n schema: USchema,\n ): EffectProcedureBuilderWithOutput<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n USchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n // We cast to any because EffectProcedureBuilderWithOutput narrows\n // handler/effect output typing based on the declared output schema.\n return new EffectBuilder({\n ...this[\"~effect\"],\n outputSchema: schema,\n outputValidationIndex:\n fallbackConfig(\n \"initialOutputValidationIndex\",\n this[\"~effect\"].config.initialOutputValidationIndex,\n ) + this[\"~effect\"].middlewares.length,\n }) as any;\n }\n\n /**\n * Adds a traceable span to the procedure for telemetry.\n * The span name is used for Effect tracing via `Effect.withSpan`.\n * Stack trace is captured at the call site for better error reporting.\n *\n * @param spanName - The name of the span for telemetry (e.g., 'users.getUser')\n * @returns An EffectBuilder with span tracing configured\n *\n * @example\n * ```ts\n * const getUser = effectOs\n * .input(z.object({ id: z.string() }))\n * .traced('users.getUser')\n * .effect(function* ({ input }) {\n * const userService = yield* UserService\n * return yield* userService.findById(input.id)\n * })\n * ```\n */\n traced(\n spanName: string,\n ): EffectBuilder<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n spanConfig: {\n name: spanName,\n captureStackTrace: addSpanStackTrace(),\n },\n });\n }\n\n handler<UFuncOutput>(\n handler: ProcedureHandler<\n TCurrentContext,\n InferSchemaOutput<TInputSchema>,\n UFuncOutput,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta\n >,\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n Schema<UFuncOutput, UFuncOutput>,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n handler,\n });\n }\n\n /**\n * Defines the handler of the procedure using an Effect.\n * The Effect is executed using the ManagedRuntime provided during builder creation.\n * The effect is automatically wrapped with `Effect.withSpan`.\n *\n * @see {@link https://orpc.dev/docs/procedure Procedure Docs}\n */\n effect<UFuncOutput>(\n effectFn: EffectProcedureHandler<\n TCurrentContext,\n TInputSchema,\n UFuncOutput,\n TEffectErrorMap,\n TRequirementsProvided,\n TMeta\n >,\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n Schema<UFuncOutput, UFuncOutput>,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n const { runtime, spanConfig } = this[\"~effect\"];\n // Capture stack trace at definition time for default tracing\n const defaultCaptureStackTrace = addSpanStackTrace();\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n handler: async (opts) => {\n const effectOpts: ProcedureHandlerOptions<\n TCurrentContext,\n InferSchemaOutput<TInputSchema>,\n EffectErrorConstructorMap<TEffectErrorMap>,\n TMeta\n > = {\n context: opts.context,\n input: opts.input,\n path: opts.path,\n procedure: opts.procedure,\n signal: opts.signal,\n lastEventId: opts.lastEventId,\n errors: createEffectErrorConstructorMap(\n this[\"~effect\"].effectErrorMap,\n ),\n };\n const spanName = spanConfig?.name ?? opts.path.join(\".\");\n const captureStackTrace =\n spanConfig?.captureStackTrace ?? defaultCaptureStackTrace;\n const resolver = Effect.fnUntraced(effectFn);\n const tracedEffect = Effect.withSpan(resolver(effectOpts), spanName, {\n captureStackTrace,\n });\n const parentFiberRefs = getCurrentFiberRefs();\n const effectWithRefs = parentFiberRefs\n ? Effect.fiberIdWith((fiberId) =>\n Effect.flatMap(Effect.getFiberRefs, (fiberRefs) =>\n Effect.setFiberRefs(\n FiberRefs.joinAs(fiberRefs, fiberId, parentFiberRefs),\n ).pipe(Effect.andThen(tracedEffect)),\n ),\n )\n : tracedEffect;\n const exit = await runtime.runPromiseExit(effectWithRefs, {\n signal: opts.signal,\n });\n\n if (Exit.isFailure(exit)) {\n throw Cause.match(exit.cause, {\n onDie(defect) {\n return new ORPCError(\"INTERNAL_SERVER_ERROR\", {\n cause: defect,\n });\n },\n onFail(error) {\n if (isORPCTaggedError(error)) {\n return error.toORPCError();\n }\n if (error instanceof ORPCError) {\n return error;\n }\n return new ORPCError(\"INTERNAL_SERVER_ERROR\", {\n cause: error,\n });\n },\n onInterrupt(fiberId) {\n return new ORPCError(\"INTERNAL_SERVER_ERROR\", {\n cause: new Error(`${fiberId} Interrupted`),\n });\n },\n onSequential(left) {\n return left;\n },\n onEmpty: new ORPCError(\"INTERNAL_SERVER_ERROR\", {\n cause: new Error(\"Unknown error\"),\n }),\n onParallel(left) {\n return left;\n },\n });\n }\n\n return exit.value;\n },\n });\n }\n\n /**\n * Prefixes all procedures in the router.\n * The provided prefix is post-appended to any existing router prefix.\n *\n * @note This option does not affect procedures that do not define a path in their route definition.\n *\n * @see {@link https://orpc.dev/docs/openapi/routing#route-prefixes OpenAPI Route Prefixes Docs}\n */\n prefix(\n prefix: HTTPPath,\n ): EffectRouterBuilder<\n TInitialContext,\n TCurrentContext,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n prefix: mergePrefix(this[\"~effect\"].prefix, prefix),\n }) as any;\n }\n\n /**\n * Adds tags to all procedures in the router.\n * This helpful when you want to group procedures together in the OpenAPI specification.\n *\n * @see {@link https://orpc.dev/docs/openapi/openapi-specification#operation-metadata OpenAPI Operation Metadata Docs}\n */\n tag(\n ...tags: string[]\n ): EffectRouterBuilder<\n TInitialContext,\n TCurrentContext,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectBuilder({\n ...this[\"~effect\"],\n tags: mergeTags(this[\"~effect\"].tags, tags),\n }) as any;\n }\n\n /**\n * Applies all of the previously defined options to the specified router.\n *\n * @see {@link https://orpc.dev/docs/router#extending-router Extending Router Docs}\n */\n router<U extends Router<ContractRouter<TMeta>, TCurrentContext>>(\n router: U,\n ): EnhancedEffectRouter<\n U,\n TInitialContext,\n TCurrentContext,\n TEffectErrorMap\n > {\n return enhanceEffectRouter(router, {\n ...this[\"~effect\"],\n }) as any; // Type instantiation is excessively deep and possibly infinite\n }\n\n /**\n * Create a lazy router\n * And applies all of the previously defined options to the specified router.\n *\n * @see {@link https://orpc.dev/docs/router#extending-router Extending Router Docs}\n */\n lazy<U extends Router<ContractRouter<TMeta>, TCurrentContext>>(\n loader: () => Promise<{ default: U }>,\n ): EnhancedEffectRouter<\n Lazy<U>,\n TInitialContext,\n TCurrentContext,\n TEffectErrorMap\n > {\n return enhanceEffectRouter(lazy(loader), {\n ...this[\"~effect\"],\n }) as any; // Type instantiation is excessively deep and possibly infinite\n }\n}\n\n/**\n * Creates an Effect-aware procedure builder with the specified ManagedRuntime.\n * Uses the default `os` builder from `@orpc/server`.\n *\n * @param runtime - The ManagedRuntime that provides services for Effect procedures\n * @returns An EffectBuilder instance for creating Effect-native procedures\n *\n * @example\n * ```ts\n * import { makeEffectORPC } from '@orpc/effect'\n * import { Effect, Layer, ManagedRuntime } from 'effect'\n *\n * const runtime = ManagedRuntime.make(Layer.empty)\n * const effectOs = makeEffectORPC(runtime)\n *\n * const hello = effectOs.effect(() => Effect.succeed('Hello!'))\n * ```\n */\nexport function makeEffectORPC<TRequirementsProvided, TRuntimeError>(\n runtime: ManagedRuntime.ManagedRuntime<TRequirementsProvided, TRuntimeError>,\n): EffectBuilder<\n Context,\n Context,\n Schema<unknown, unknown>,\n Schema<unknown, unknown>,\n Record<never, never>,\n Record<never, never>,\n TRequirementsProvided,\n TRuntimeError\n>;\n\n/**\n * Creates an Effect-aware procedure builder by wrapping an existing oRPC Builder\n * with the specified ManagedRuntime.\n *\n * @param runtime - The ManagedRuntime that provides services for Effect procedures\n * @param builder - The oRPC Builder instance to wrap (e.g., a customized `os`)\n * @returns An EffectBuilder instance that extends the original builder with Effect support\n *\n * @example\n * ```ts\n * import { makeEffectORPC } from '@orpc/effect'\n * import { os } from '@orpc/server'\n * import { Effect, Layer, ManagedRuntime } from 'effect'\n *\n * // Create a customized builder\n * const authedOs = os.use(authMiddleware)\n *\n * // Wrap it with Effect support\n * const runtime = ManagedRuntime.make(UserServiceLive)\n * const effectOs = makeEffectORPC(runtime, authedOs)\n *\n * const getUser = effectOs\n * .input(z.object({ id: z.string() }))\n * .effect(\n * Effect.fn(function* ({ input }) {\n * const userService = yield* UserService\n * return yield* userService.findById(input.id)\n * })\n * )\n * ```\n */\nexport function makeEffectORPC<\n TBuilder extends AnyBuilderLike<\n TInputSchema,\n TOutputSchema,\n TErrorMap,\n TMeta\n >,\n TInputSchema extends AnySchema,\n TOutputSchema extends AnySchema,\n TErrorMap extends ErrorMap,\n TMeta extends Meta,\n TRequirementsProvided,\n TRuntimeError,\n>(\n runtime: ManagedRuntime.ManagedRuntime<TRequirementsProvided, TRuntimeError>,\n builder: TBuilder,\n): EffectBuilder<\n InferBuilderInitialContext<TBuilder>,\n InferBuilderCurrentContext<TBuilder>,\n InferBuilderInputSchema<TBuilder>,\n InferBuilderOutputSchema<TBuilder>,\n InferBuilderErrorMap<TBuilder>,\n InferBuilderMeta<TBuilder>,\n TRequirementsProvided,\n TRuntimeError\n>;\n\nexport function makeEffectORPC<TRequirementsProvided, TRuntimeError>(\n runtime: ManagedRuntime.ManagedRuntime<TRequirementsProvided, TRuntimeError>,\n builder?: AnyBuilderLike,\n): EffectBuilder<\n any,\n any,\n any,\n any,\n any,\n any,\n TRequirementsProvided,\n TRuntimeError\n> {\n const resolvedBuilder = builder ?? emptyBuilder();\n return new EffectBuilder({\n ...resolvedBuilder[\"~orpc\"],\n errorMap: effectErrorMapToErrorMap(resolvedBuilder[\"~orpc\"].errorMap),\n effectErrorMap: resolvedBuilder[\"~orpc\"].errorMap,\n runtime,\n });\n}\n\nfunction emptyBuilder(): AnyBuilderLike {\n return new Builder({\n config: {},\n route: {},\n meta: {},\n errorMap: {},\n inputValidationIndex: fallbackConfig(\"initialInputValidationIndex\"),\n outputValidationIndex: fallbackConfig(\"initialOutputValidationIndex\"),\n middlewares: [],\n dedupeLeadingMiddlewares: true,\n });\n}\n","import type { ManagedRuntime } from \"effect/ManagedRuntime\";\n\nimport {\n enhanceRoute,\n mergePrefix,\n type EnhanceRouteOptions,\n} from \"@orpc/contract\";\nimport {\n createAccessibleLazyRouter,\n getLazyMeta,\n isLazy,\n isProcedure,\n lazy,\n mergeMiddlewares,\n unlazy,\n type AnyMiddleware,\n type AnyRouter,\n type Context,\n type Lazyable,\n} from \"@orpc/server\";\n\nimport type { EffectErrorMapToErrorMap, EnhancedEffectRouter } from \"./types\";\n\nimport { EffectProcedure } from \"./effect-procedure\";\nimport { effectErrorMapToErrorMap, type EffectErrorMap } from \"./tagged-error\";\n\ninterface EnhanceEffectRouterOptions<\n TEffectErrorMap extends EffectErrorMap,\n TRequirementsProvided,\n TRuntimeError,\n> extends EnhanceRouteOptions {\n middlewares: readonly AnyMiddleware[];\n errorMap: TEffectErrorMap;\n dedupeLeadingMiddlewares: boolean;\n runtime: ManagedRuntime<TRequirementsProvided, TRuntimeError>;\n}\n\nexport function enhanceEffectRouter<\n T extends Lazyable<AnyRouter>,\n TInitialContext extends Context,\n TCurrentContext extends Context,\n TEffectErrorMap extends EffectErrorMap,\n TRequirementsProvided,\n TRuntimeError,\n>(\n router: T,\n options: EnhanceEffectRouterOptions<\n TEffectErrorMap,\n TRequirementsProvided,\n TRuntimeError\n >,\n): EnhancedEffectRouter<T, TInitialContext, TCurrentContext, TEffectErrorMap> {\n if (isLazy(router)) {\n const laziedMeta = getLazyMeta(router);\n const enhancedPrefix = laziedMeta?.prefix\n ? mergePrefix(options.prefix, laziedMeta?.prefix)\n : options.prefix;\n\n const enhanced = lazy(\n async () => {\n const { default: unlaziedRouter } = await unlazy(router);\n const enhanced = enhanceEffectRouter(unlaziedRouter, options);\n return unlazy(enhanced);\n },\n {\n ...laziedMeta,\n prefix: enhancedPrefix,\n },\n );\n\n const accessible = createAccessibleLazyRouter(enhanced);\n\n return accessible as any;\n }\n\n if (isProcedure(router)) {\n const newMiddlewares = mergeMiddlewares(\n options.middlewares,\n router[\"~orpc\"].middlewares,\n { dedupeLeading: options.dedupeLeadingMiddlewares },\n );\n const newMiddlewareAdded =\n newMiddlewares.length - router[\"~orpc\"].middlewares.length;\n\n const effectErrorMap = {\n ...options.errorMap,\n ...router[\"~orpc\"].errorMap,\n };\n const errorMap: EffectErrorMapToErrorMap<typeof effectErrorMap> =\n effectErrorMapToErrorMap(effectErrorMap);\n const enhanced = new EffectProcedure({\n ...router[\"~orpc\"],\n route: enhanceRoute(router[\"~orpc\"].route, options),\n effectErrorMap,\n errorMap: errorMap as EffectErrorMapToErrorMap<typeof effectErrorMap>,\n middlewares: newMiddlewares,\n inputValidationIndex:\n router[\"~orpc\"].inputValidationIndex + newMiddlewareAdded,\n outputValidationIndex:\n router[\"~orpc\"].outputValidationIndex + newMiddlewareAdded,\n runtime: options.runtime,\n });\n\n return enhanced as any;\n }\n\n const enhanced = {} as Record<string, any>;\n\n for (const key in router) {\n enhanced[key] = enhanceEffectRouter(router[key]!, options);\n }\n\n return enhanced as any;\n}\n","import type { ClientContext } from \"@orpc/client\";\nimport type {\n AnySchema,\n InferSchemaInput,\n InferSchemaOutput,\n Meta,\n Route,\n} from \"@orpc/contract\";\nimport type {\n AnyMiddleware,\n Context,\n CreateProcedureClientOptions,\n MapInputMiddleware,\n MergedCurrentContext,\n MergedInitialContext,\n Middleware,\n ProcedureActionableClient,\n ProcedureClient,\n ProcedureDef,\n} from \"@orpc/server\";\nimport type { IntersectPick, MaybeOptionalOptions } from \"@orpc/shared\";\n\nimport { mergeMeta, mergeRoute } from \"@orpc/contract\";\nimport {\n addMiddleware,\n createActionableClient,\n createProcedureClient,\n decorateMiddleware,\n Procedure,\n} from \"@orpc/server\";\n\nimport type {\n EffectErrorConstructorMap,\n EffectErrorMap,\n MergedEffectErrorMap,\n} from \"./tagged-error\";\nimport type { EffectErrorMapToErrorMap, EffectProcedureDef } from \"./types\";\n\nimport { effectErrorMapToErrorMap } from \"./tagged-error\";\n\nexport class EffectProcedure<\n TInitialContext extends Context,\n TCurrentContext extends Context,\n TInputSchema extends AnySchema,\n TOutputSchema extends AnySchema,\n TEffectErrorMap extends EffectErrorMap,\n TMeta extends Meta,\n TRequirementsProvided,\n TRuntimeError,\n> extends Procedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta\n> {\n /**\n * This property holds the defined options and the effect-specific properties.\n */\n declare \"~effect\": EffectProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n /**\n * This property holds the defined options.\n */\n declare \"~orpc\": ProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta\n >;\n\n constructor(\n def: EffectProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >,\n ) {\n super(def);\n this[\"~effect\"] = def;\n }\n}\n\n/**\n * An Effect-native decorated procedure that preserves Effect error and requirements types.\n *\n * This class extends Procedure with additional type parameters for Effect-specific\n * type information, allowing full type inference of Effect errors and requirements.\n */\nexport class EffectDecoratedProcedure<\n TInitialContext extends Context,\n TCurrentContext extends Context,\n TInputSchema extends AnySchema,\n TOutputSchema extends AnySchema,\n TEffectErrorMap extends EffectErrorMap,\n TMeta extends Meta,\n TRequirementsProvided,\n TRuntimeError,\n> extends EffectProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n> {\n /**\n * This property holds the defined options and the effect-specific properties.\n */\n declare \"~effect\": EffectProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n declare \"~orpc\": ProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta\n >;\n\n constructor(\n def: EffectProcedureDef<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >,\n ) {\n super(def);\n this[\"~effect\"] = def;\n }\n\n /**\n * Adds type-safe custom errors.\n * Supports both traditional oRPC error definitions and ORPCTaggedError classes.\n *\n * @see {@link https://orpc.dev/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}\n */\n errors<U extends EffectErrorMap>(\n errors: U,\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n MergedEffectErrorMap<TEffectErrorMap, U>,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n const newEffectErrorMap: MergedEffectErrorMap<TEffectErrorMap, U> = {\n ...this[\"~effect\"].effectErrorMap,\n ...errors,\n };\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n effectErrorMap: newEffectErrorMap,\n errorMap: effectErrorMapToErrorMap(newEffectErrorMap),\n });\n }\n\n /**\n * Sets or updates the metadata.\n * The provided metadata is spared-merged with any existing metadata.\n *\n * @see {@link https://orpc.dev/docs/metadata Metadata Docs}\n */\n meta(\n meta: TMeta,\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n meta: mergeMeta(this[\"~effect\"].meta, meta),\n });\n }\n\n /**\n * Sets or updates the route definition.\n * The provided route is spared-merged with any existing route.\n * This option is typically relevant when integrating with OpenAPI.\n *\n * @see {@link https://orpc.dev/docs/openapi/routing OpenAPI Routing Docs}\n * @see {@link https://orpc.dev/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}\n */\n route(\n route: Route,\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > {\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n route: mergeRoute(this[\"~effect\"].route, route),\n });\n }\n\n /**\n * Uses a middleware to modify the context or improve the pipeline.\n *\n * @info Supports both normal middleware and inline middleware implementations.\n * @info Pass second argument to map the input.\n * @note The current context must be satisfy middleware dependent-context\n * @see {@link https://orpc.dev/docs/middleware Middleware Docs}\n */\n use<\n UOutContext extends IntersectPick<TCurrentContext, UOutContext>,\n UInContext extends Context = TCurrentContext,\n >(\n middleware: Middleware<\n UInContext | TCurrentContext,\n UOutContext,\n InferSchemaOutput<TInputSchema>,\n InferSchemaInput<TOutputSchema>,\n EffectErrorConstructorMap<TEffectErrorMap>,\n TMeta\n >,\n ): EffectDecoratedProcedure<\n MergedInitialContext<TInitialContext, UInContext, TCurrentContext>,\n MergedCurrentContext<TCurrentContext, UOutContext>,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n\n /**\n * Uses a middleware to modify the context or improve the pipeline.\n *\n * @info Supports both normal middleware and inline middleware implementations.\n * @info Pass second argument to map the input.\n * @note The current context must be satisfy middleware dependent-context\n * @see {@link https://orpc.dev/docs/middleware Middleware Docs}\n */\n use<\n UOutContext extends IntersectPick<TCurrentContext, UOutContext>,\n UInput,\n UInContext extends Context = TCurrentContext,\n >(\n middleware: Middleware<\n UInContext | TCurrentContext,\n UOutContext,\n UInput,\n InferSchemaInput<TOutputSchema>,\n EffectErrorConstructorMap<TEffectErrorMap>,\n TMeta\n >,\n mapInput: MapInputMiddleware<InferSchemaOutput<TInputSchema>, UInput>,\n ): EffectDecoratedProcedure<\n MergedInitialContext<TInitialContext, UInContext, TCurrentContext>,\n MergedCurrentContext<TCurrentContext, UOutContext>,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n >;\n\n use(\n middleware: AnyMiddleware,\n mapInput?: MapInputMiddleware<any, any>,\n ): EffectDecoratedProcedure<any, any, any, any, any, any, any, any> {\n const mapped = mapInput\n ? decorateMiddleware(middleware).mapInput(mapInput)\n : middleware;\n\n return new EffectDecoratedProcedure({\n ...this[\"~effect\"],\n middlewares: addMiddleware(this[\"~effect\"].middlewares, mapped),\n });\n }\n\n /**\n * Make this procedure callable (works like a function while still being a procedure).\n *\n * @see {@link https://orpc.dev/docs/client/server-side Server-side Client Docs}\n */\n callable<TClientContext extends ClientContext>(\n ...rest: MaybeOptionalOptions<\n CreateProcedureClientOptions<\n TInitialContext,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta,\n TClientContext\n >\n >\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > &\n ProcedureClient<\n TClientContext,\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>\n > {\n const client: ProcedureClient<\n TClientContext,\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>\n > = createProcedureClient(this, ...rest);\n\n return new Proxy(client, {\n get: (target, key) => {\n return Reflect.has(this, key)\n ? Reflect.get(this, key)\n : Reflect.get(target, key);\n },\n has: (target, key) => {\n return Reflect.has(this, key) || Reflect.has(target, key);\n },\n }) as any;\n }\n\n /**\n * Make this procedure compatible with server action.\n *\n * @see {@link https://orpc.dev/docs/server-action Server Action Docs}\n */\n actionable(\n ...rest: MaybeOptionalOptions<\n CreateProcedureClientOptions<\n TInitialContext,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>,\n TMeta,\n Record<never, never>\n >\n >\n ): EffectDecoratedProcedure<\n TInitialContext,\n TCurrentContext,\n TInputSchema,\n TOutputSchema,\n TEffectErrorMap,\n TMeta,\n TRequirementsProvided,\n TRuntimeError\n > &\n ProcedureActionableClient<\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>\n > {\n const action: ProcedureActionableClient<\n TInputSchema,\n TOutputSchema,\n EffectErrorMapToErrorMap<TEffectErrorMap>\n > = createActionableClient(createProcedureClient(this, ...rest));\n\n return new Proxy(action, {\n get: (target, key) => {\n return Reflect.has(this, key)\n ? Reflect.get(this, key)\n : Reflect.get(target, key);\n },\n has: (target, key) => {\n return Reflect.has(this, key) || Reflect.has(target, key);\n },\n }) as any;\n }\n}\n","import type {\n ORPCErrorCode,\n ORPCErrorJSON,\n ORPCErrorOptions,\n} from \"@orpc/client\";\nimport type {\n AnySchema,\n ErrorMap,\n ErrorMapItem,\n InferSchemaOutput,\n} from \"@orpc/contract\";\nimport type { ORPCErrorConstructorMap } from \"@orpc/server\";\nimport type { MaybeOptionalOptions } from \"@orpc/shared\";\nimport type { Pipeable } from \"effect\";\n\nimport {\n fallbackORPCErrorMessage,\n fallbackORPCErrorStatus,\n isORPCErrorStatus,\n ORPCError,\n} from \"@orpc/client\";\nimport { resolveMaybeOptionalOptions } from \"@orpc/shared\";\nimport * as Cause from \"effect/Cause\";\nimport * as Data from \"effect/Data\";\n\nimport type { EffectErrorMapToErrorMap } from \"./types\";\n\n/**\n * Symbol to access the underlying ORPCError instance\n */\nexport const ORPCErrorSymbol: unique symbol = Symbol.for(\n \"@orpc/effect/ORPCTaggedError\",\n);\n\n/**\n * Instance type for ORPCTaggedError that combines YieldableError with ORPCError properties\n */\nexport interface ORPCTaggedErrorInstance<\n TTag extends string,\n TCode extends ORPCErrorCode,\n TSchema extends AnySchema = AnySchema,\n>\n extends Cause.YieldableError, Pipeable.Pipeable {\n readonly _tag: TTag;\n readonly code: TCode;\n readonly status: number;\n readonly schema: TSchema;\n readonly data: InferSchemaOutput<TSchema>;\n readonly defined: boolean;\n readonly [ORPCErrorSymbol]: ORPCError<TCode, InferSchemaOutput<TSchema>>;\n\n toJSON(): ORPCErrorJSON<TCode, InferSchemaOutput<TSchema>> & { _tag: TTag };\n toORPCError(): ORPCError<TCode, InferSchemaOutput<TSchema>>;\n}\n\n/**\n * Options for creating an ORPCTaggedError\n */\nexport type ORPCTaggedErrorOptions<TData> = Omit<\n ORPCErrorOptions<TData>,\n \"defined\"\n> & { defined?: boolean };\n\n/**\n * Constructor type for ORPCTaggedError classes\n */\nexport interface ORPCTaggedErrorClass<\n TTag extends string,\n TCode extends ORPCErrorCode,\n TSchema extends AnySchema = AnySchema,\n> {\n readonly _tag: TTag;\n readonly code: TCode;\n new (\n ...args: MaybeOptionalOptions<\n ORPCTaggedErrorOptions<InferSchemaOutput<TSchema>>\n >\n ): ORPCTaggedErrorInstance<TTag, TCode, TSchema>;\n}\n\n/**\n * Type helper to infer the ORPCError type from an ORPCTaggedError\n */\nexport type InferORPCError<T> =\n T extends ORPCTaggedErrorInstance<string, infer TCode, infer TSchema>\n ? ORPCError<TCode, InferSchemaOutput<TSchema>>\n : never;\n\n/**\n * Any ORPCTaggedErrorClass\n * Uses `...args: any[]` for the constructor to accept any tagged error class,\n * regardless of whether TData requires options to be provided.\n */\nexport type AnyORPCTaggedErrorClass = {\n readonly _tag: string;\n readonly code: ORPCErrorCode;\n new (\n ...args: any[]\n ): ORPCTaggedErrorInstance<string, ORPCErrorCode, AnySchema>;\n};\n\n/**\n * Check if a value is an ORPCTaggedErrorClass (constructor)\n */\nexport function isORPCTaggedErrorClass(\n value: unknown,\n): value is AnyORPCTaggedErrorClass {\n return (\n typeof value === \"function\" &&\n \"_tag\" in value &&\n \"code\" in value &&\n typeof value._tag === \"string\" &&\n typeof value.code === \"string\"\n );\n}\n\n/**\n * Check if a value is an ORPCTaggedError instance\n */\nexport function isORPCTaggedError(\n value: unknown,\n): value is ORPCTaggedErrorInstance<string, ORPCErrorCode, AnySchema> {\n return (\n typeof value === \"object\" && value !== null && ORPCErrorSymbol in value\n );\n}\n\n/**\n * Converts a PascalCase or camelCase string to CONSTANT_CASE.\n * e.g., \"UserNotFoundError\" -> \"USER_NOT_FOUND_ERROR\"\n */\nfunction toConstantCase<T extends string>(str: T): ToConstantCase<T> {\n return str\n .replace(/([a-z])([A-Z])/g, \"$1_$2\")\n .replace(/([A-Z])([A-Z][a-z])/g, \"$1_$2\")\n .toUpperCase() as ToConstantCase<T>;\n}\n/**\n * Checks if a character is an uppercase letter (A-Z)\n */\ntype IsUpperLetter<C extends string> =\n C extends Uppercase<C>\n ? C extends Lowercase<C>\n ? false // Not a letter (number, special char)\n : true\n : false;\n\n/**\n * Checks if a character is a lowercase letter (a-z)\n */\ntype IsLowerLetter<C extends string> =\n C extends Lowercase<C>\n ? C extends Uppercase<C>\n ? false // Not a letter (number, special char)\n : true\n : false;\n\n/**\n * Converts PascalCase or camelCase to CONSTANT_CASE.\n * Handles consecutive uppercase letters correctly.\n *\n * @example\n * type T1 = ToConstantCase<\"ABCCode\">; // \"ABC_CODE\"\n * type T2 = ToConstantCase<\"UserCode\">; // \"USER_CODE\"\n * type T3 = ToConstantCase<\"XMLHttpRequest\">; // \"XML_HTTP_REQUEST\"\n */\ntype ToConstantCase<\n S extends string,\n Acc extends string = \"\",\n PrevChar extends string = \"\",\n InUpperSequence extends boolean = false,\n> = S extends `${infer Head}${infer Tail}`\n ? IsUpperLetter<Head> extends true\n ? Acc extends \"\"\n ? // First character - no underscore\n ToConstantCase<Tail, Head, Head, false>\n : PrevChar extends \"\"\n ? // Shouldn't happen, but handle gracefully\n ToConstantCase<Tail, Head, Head, false>\n : IsUpperLetter<PrevChar> extends true\n ? // We're in an uppercase sequence\n Tail extends `${infer Next}${infer _}`\n ? IsLowerLetter<Next> extends true\n ? // Next char is lowercase, so Head starts a new word - insert underscore\n ToConstantCase<Tail, `${Acc}_${Head}`, Head, false>\n : // Next char is uppercase or non-letter - continue sequence\n ToConstantCase<Tail, `${Acc}${Head}`, Head, true>\n : // Tail is empty - just append\n ToConstantCase<Tail, `${Acc}${Head}`, Head, true>\n : // Transition from lowercase to uppercase - insert underscore\n ToConstantCase<Tail, `${Acc}_${Head}`, Head, false>\n : IsLowerLetter<Head> extends true\n ? InUpperSequence extends true\n ? // End of uppercase sequence (2+) - insert underscore before lowercase\n ToConstantCase<Tail, `${Acc}_${Uppercase<Head>}`, Head, false>\n : // Single uppercase or no uppercase - no underscore\n ToConstantCase<Tail, `${Acc}${Uppercase<Head>}`, Head, false>\n : // Non-letter character - reset sequence\n ToConstantCase<Tail, `${Acc}${Head}`, Head, false>\n : Acc;\n\n/**\n * Converts a tag name to an error code in CONSTANT_CASE.\n */\nexport type TagToCode<TTag extends string> = ToConstantCase<TTag>;\n\n/**\n * Creates a tagged error class that combines Effect's YieldableError with ORPCError.\n *\n * This allows you to create errors that:\n * - Can be yielded in Effect generators (`yield* myError`)\n * - Have all ORPCError properties (code, status, data, defined)\n * - Can be converted to a plain ORPCError for oRPC handlers\n *\n * The returned factory function takes:\n * - `tag` - The unique tag for this error type (used for discriminated unions)\n * - `codeOrOptions` - Optional ORPC error code or options. If omitted, code defaults to CONSTANT_CASE of tag\n * - `defaultOptions` - Optional default options for status and message (when code is provided)\n *\n * @example\n * ```ts\n * import { ORPCTaggedError } from '@orpc/effect'\n * import { Effect } from 'effect'\n *\n * // Define a custom error (code defaults to 'USER_NOT_FOUND_ERROR')\n * class UserNotFoundError extends ORPCTaggedError<UserNotFoundError>()('UserNotFoundError') {}\n *\n * // With explicit code\n * class NotFoundError extends ORPCTaggedError<NotFoundError>()('NotFoundError', 'NOT_FOUND') {}\n *\n * // Use in an Effect\n * const getUser = (id: string) => Effect.gen(function* () {\n * const user = yield* findUser(id)\n * if (!user) {\n * return yield* new UserNotFoundError({ data: { userId: id } })\n * }\n * return user\n * })\n *\n * // With custom data type\n * class ValidationError extends ORPCTaggedError<ValidationError, { fields: string[] }>()('ValidationError', 'BAD_REQUEST') {}\n *\n * // With options only (code defaults to 'VALIDATION_ERROR')\n * class ValidationError2 extends ORPCTaggedError<ValidationError2, { fields: string[] }>()(\n * 'ValidationError2',\n * { message: 'Validation failed' }\n * ) {}\n * ```\n */\nexport function ORPCTaggedError<\n TTag extends string,\n TSchema extends AnySchema = AnySchema,\n TCode extends ORPCErrorCode = ToConstantCase<TTag>,\n>(\n tag: TTag,\n props?: {\n schema?: TSchema;\n status?: number;\n message?: string;\n code?: TCode;\n },\n): ORPCTaggedErrorClass<TTag, TCode, TSchema> {\n const code: TCode = props?.code ?? (toConstantCase(tag) as any);\n class ORPCTaggedErrorBase\n extends Data.TaggedError(tag)\n implements ORPCTaggedErrorInstance<TTag, TCode, TSchema>\n {\n readonly status: number;\n readonly defined: boolean;\n readonly data: InferSchemaOutput<TSchema>;\n readonly code: TCode = code;\n readonly schema = props?.schema as TSchema;\n readonly [ORPCErrorSymbol]: ORPCError<TCode, InferSchemaOutput<TSchema>>;\n\n constructor(\n ...rest: MaybeOptionalOptions<\n ORPCTaggedErrorOptions<InferSchemaOutput<TSchema>>\n >\n ) {\n super();\n\n const opts = resolveMaybeOptionalOptions(rest);\n const status = opts.status ?? props?.status;\n\n if (status !== undefined && !isORPCErrorStatus(status)) {\n throw new globalThis.Error(\n \"[ORPCTaggedError] Invalid error status code.\",\n );\n }\n\n this.status = fallbackORPCErrorStatus(code, status);\n this.defined = opts.defined ?? true;\n this.data = opts.data as InferSchemaOutput<TSchema>;\n this.message = fallbackORPCErrorMessage(\n this.code,\n opts.message ?? props?.message,\n );\n this.cause = opts.cause;\n\n this[ORPCErrorSymbol] = new ORPCError<TCode, InferSchemaOutput<TSchema>>(\n this.code,\n {\n status: this.status,\n message: this.message,\n data: this.data,\n defined: this.defined,\n cause: this.cause,\n },\n );\n }\n\n /**\n * Converts this error to a plain ORPCError.\n * Useful when you need to return from an oRPC handler.\n */\n toORPCError(): ORPCError<TCode, InferSchemaOutput<TSchema>> {\n return this[ORPCErrorSymbol];\n }\n\n override toJSON(): ORPCErrorJSON<TCode, InferSchemaOutput<TSchema>> & {\n _tag: TTag;\n } {\n return {\n _tag: this._tag,\n defined: this[ORPCErrorSymbol].defined,\n code: this[ORPCErrorSymbol].code,\n status: this[ORPCErrorSymbol].status,\n message: this[ORPCErrorSymbol].message,\n data: this[ORPCErrorSymbol].data,\n };\n }\n }\n\n return Object.assign(ORPCTaggedErrorBase, {\n _tag: tag,\n code,\n } as const);\n}\n\n/**\n * Converts an ORPCTaggedError to a plain ORPCError.\n * Useful in handlers that need to throw ORPCError.\n *\n * @example\n * ```ts\n * const handler = effectOs.effect(function* () {\n * const result = yield* someOperation.pipe(\n * Effect.catchTag('UserNotFoundError', (e) =>\n * Effect.fail(toORPCError(e))\n * )\n * )\n * return result\n * })\n * ```\n */\nexport function toORPCError<\n TCode extends ORPCErrorCode,\n TSchema extends AnySchema = AnySchema,\n>(\n error: ORPCTaggedErrorInstance<string, TCode, TSchema>,\n): ORPCError<TCode, InferSchemaOutput<TSchema>> {\n return error[ORPCErrorSymbol];\n}\n\n// ============================================================================\n// Extended Error Map Types for Effect\n// ============================================================================\n\n/**\n * An item in the EffectErrorMap - can be either a traditional ErrorMapItem or an ORPCTaggedErrorClass\n */\nexport type EffectErrorMapItem =\n | ErrorMapItem<AnySchema>\n | AnyORPCTaggedErrorClass;\n\nexport type ORPCTaggedErrorClassToErrorMapItem<T> =\n T extends ORPCTaggedErrorClass<any, any, infer TData>\n ? {\n status?: number;\n message?: string;\n data?: TData;\n }\n : never;\n\n/**\n * Extended error map that supports both traditional oRPC errors and ORPCTaggedError classes.\n *\n * @example\n * ```ts\n * const errorMap = {\n * // Traditional format\n * BAD_REQUEST: { status: 400, message: 'Bad request' },\n *\n * // Tagged error class reference\n * USER_NOT_FOUND: UserNotFoundError,\n * } satisfies EffectErrorMap\n * ```\n */\nexport type EffectErrorMap = {\n [key in ORPCErrorCode]?: EffectErrorMapItem;\n};\n\n/**\n * Merges two EffectErrorMaps, with the second map taking precedence.\n */\nexport type MergedEffectErrorMap<\n T1 extends EffectErrorMap,\n T2 extends EffectErrorMap,\n> = Omit<T1, keyof T2> & T2;\n\n/**\n * Extracts the instance type from an EffectErrorMapItem\n */\nexport type EffectErrorMapItemToInstance<\n TCode extends ORPCErrorCode,\n T extends EffectErrorMapItem,\n> = T extends AnyORPCTaggedErrorClass\n ? InstanceType<T>\n : T extends { data?: infer TData }\n ? ORPCError<TCode, TData>\n : ORPCError<TCode, unknown>;\n\n/**\n * Converts an EffectErrorMap to a union of error instances.\n */\nexport type EffectErrorMapToUnion<T extends EffectErrorMap> = {\n [K in keyof T]: K extends ORPCErrorCode\n ? T[K] extends EffectErrorMapItem\n ? EffectErrorMapItemToInstance<K, T[K]>\n : never\n : never;\n}[keyof T];\n\n/**\n * Constructor map for EffectErrorMap - provides typed error constructors for handlers.\n */\nexport type EffectErrorConstructorMap<T extends EffectErrorMap> =\n ORPCErrorConstructorMap<EffectErrorMapToErrorMap<T>>;\n\n/**\n * Creates an error constructor map from an EffectErrorMap.\n * Tagged error classes are passed through directly.\n * Traditional error items become ORPCError factory functions.\n */\nexport function createEffectErrorConstructorMap<T extends EffectErrorMap>(\n errors: T | undefined,\n): EffectErrorConstructorMap<T> {\n const target = errors ?? ({} as T);\n const proxy = new Proxy(target, {\n get(proxyTarget, code) {\n if (typeof code !== \"string\") {\n return Reflect.get(proxyTarget, code);\n }\n\n const config = target[code];\n\n // If it's a tagged error class, create a class constructor function\n if (isORPCTaggedErrorClass(config)) {\n return (\n ...opts: MaybeOptionalOptions<ORPCTaggedErrorOptions<unknown>>\n ) => new config(...opts);\n }\n\n // Otherwise, create a factory function for ORPCError\n return (\n ...rest: MaybeOptionalOptions<\n Omit<ORPCErrorOptions<unknown>, \"defined\" | \"status\">\n >\n ) => {\n const options = resolveMaybeOptionalOptions(rest);\n return new ORPCError(code, {\n defined: Boolean(config),\n status: config?.status,\n message: options.message ?? config?.message,\n data: options.data,\n cause: options.cause,\n });\n };\n },\n });\n\n return proxy as EffectErrorConstructorMap<T>;\n}\n\n/**\n * Converts an EffectErrorMap to a standard oRPC ErrorMap for interop.\n * Tagged error classes are converted to their equivalent ErrorMapItem format.\n */\nexport function effectErrorMapToErrorMap<T extends EffectErrorMap>(\n errorMap: T | undefined,\n): EffectErrorMapToErrorMap<T> {\n const result: ErrorMap = {};\n\n if (!errorMap) {\n return result as ErrorMap & EffectErrorMapToErrorMap<T>;\n }\n\n for (const [code, ClassOrErrorItem] of Object.entries(errorMap)) {\n if (!ClassOrErrorItem) {\n continue;\n }\n\n if (isORPCTaggedErrorClass(ClassOrErrorItem)) {\n const classInstance = new ClassOrErrorItem();\n result[classInstance.code] = {\n status: classInstance.status,\n message: classInstance.message,\n data: classInstance.schema,\n };\n } else {\n result[code] = ClassOrErrorItem;\n }\n }\n\n return result as ErrorMap & EffectErrorMapToErrorMap<T>;\n}\n"],"mappings":";;;;;AA2BA;AAAA,EACE,aAAAA;AAAA,EACA,eAAAC;AAAA,EACA,cAAAC;AAAA,EACA;AAAA,EACA,aAAAC;AAAA,OACK;AACP;AAAA,EACE,iBAAAC;AAAA,EACA;AAAA,EACA,sBAAAC;AAAA,EACA;AAAA,EACA,QAAAC;AAAA,OACK;AACP,SAAS,SAAAC,QAAO,QAAQ,MAAM,iBAAiB;;;ACvC/C;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;;;ACGP,SAAS,WAAW,kBAAkB;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACdP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mCAAmC;AAC5C,OAAuB;AACvB,YAAY,UAAU;AAOf,IAAM,kBAAiC,uBAAO;AAAA,EACnD;AACF;AAwEO,SAAS,uBACd,OACkC;AAClC,SACE,OAAO,UAAU,cACjB,UAAU,SACV,UAAU,SACV,OAAO,MAAM,SAAS,YACtB,OAAO,MAAM,SAAS;AAE1B;AAKO,SAAS,kBACd,OACoE;AACpE,SACE,OAAO,UAAU,YAAY,UAAU,QAAQ,mBAAmB;AAEtE;AAMA,SAAS,eAAiC,KAA2B;AACnE,SAAO,IACJ,QAAQ,mBAAmB,OAAO,EAClC,QAAQ,wBAAwB,OAAO,EACvC,YAAY;AACjB;AAiHO,SAAS,gBAKd,KACA,OAM4C;AAC5C,QAAM,OAAc,OAAO,QAAS,eAAe,GAAG;AAAA,EACtD,MAAM,4BACS,iBAAY,GAAG,EAE9B;AAAA,IACW;AAAA,IACA;AAAA,IAC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IAAI,QAAQ;AAAA,IACjB,QAAQ,CAAC;AAAA,IACT,OAAO,CAAC;AAAA,IACR,MAAM,CAAC;AAAA,IACP,UAAU,CAAC;AAAA,IACX,sBAAsB,eAAe,6BAA6B;AAAA,IAClE,uBAAuB,eAAe,8BAA8B;AAAA,IACpE,aAAa,CAAC;AAAA,IACd,0BAA0B;AAAA,EAC5B,CAAC;AACH;","names":["mergeMeta","mergePrefix","mergeRoute","ORPCError","addMiddleware","decorateMiddleware","lazy","Cause","enhanced","decorateMiddleware","addMiddleware","mergeMeta","mergeRoute","Cause","ORPCError","mergePrefix","lazy"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-orpc",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "keywords": [
5
5
  "effect",
6
6
  "orpc",
@@ -39,7 +39,7 @@ import {
39
39
  fallbackConfig,
40
40
  lazy,
41
41
  } from "@orpc/server";
42
- import { Cause, Effect, Exit } from "effect";
42
+ import { Cause, Effect, Exit, FiberRefs } from "effect";
43
43
 
44
44
  import type {
45
45
  EffectErrorConstructorMap,
@@ -630,8 +630,12 @@ export class EffectBuilder<
630
630
  });
631
631
  const parentFiberRefs = getCurrentFiberRefs();
632
632
  const effectWithRefs = parentFiberRefs
633
- ? Effect.setFiberRefs(parentFiberRefs).pipe(
634
- Effect.andThen(tracedEffect),
633
+ ? Effect.fiberIdWith((fiberId) =>
634
+ Effect.flatMap(Effect.getFiberRefs, (fiberRefs) =>
635
+ Effect.setFiberRefs(
636
+ FiberRefs.joinAs(fiberRefs, fiberId, parentFiberRefs),
637
+ ).pipe(Effect.andThen(tracedEffect)),
638
+ ),
635
639
  )
636
640
  : tracedEffect;
637
641
  const exit = await runtime.runPromiseExit(effectWithRefs, {
@@ -130,7 +130,6 @@ describe("effectBuilder", () => {
130
130
  });
131
131
 
132
132
  it(".effect", () => {
133
- // oxlint-disable-next-line require-yield
134
133
  const effectFn = vi.fn(function* () {
135
134
  return { result: "test" };
136
135
  });
@@ -142,7 +141,6 @@ describe("effectBuilder", () => {
142
141
  });
143
142
 
144
143
  it(".effect runs effect with runtime", async () => {
145
- // oxlint-disable-next-line require-yield
146
144
  const effectFn = vi.fn(function* ({ input }: { input: any }) {
147
145
  return { output: `processed-${input}` };
148
146
  });
@@ -214,6 +212,52 @@ describe("effectBuilder", () => {
214
212
 
215
213
  expect(result).toBe("req-123");
216
214
  });
215
+
216
+ it(".effect merges context FiberRefs with runtime FiberRefs, prioritizing context FiberRefs", async () => {
217
+ const requestIdRef = FiberRef.unsafeMake("missing");
218
+
219
+ class Counter extends Effect.Tag("Counter")<
220
+ Counter,
221
+ { increment: (n: number) => Effect.Effect<number> }
222
+ >() {}
223
+
224
+ const CounterLive = Layer.succeed(Counter, {
225
+ increment: (n: number) => Effect.succeed(n + 1),
226
+ });
227
+ const serviceRuntime = ManagedRuntime.make(CounterLive);
228
+ const effectBuilder = makeEffectORPC(serviceRuntime);
229
+ const procedure = effectBuilder.input(z.number()).effect(function* ({
230
+ input,
231
+ }) {
232
+ const requestId = yield* FiberRef.get(requestIdRef);
233
+ const value = yield* Counter.increment(input as number);
234
+
235
+ return { requestId, value };
236
+ });
237
+
238
+ try {
239
+ const result = await Effect.runPromise(
240
+ Effect.gen(function* () {
241
+ yield* FiberRef.set(requestIdRef, "req-123");
242
+ return yield* withFiberContext(() =>
243
+ procedure["~effect"].handler({
244
+ context: {},
245
+ input: 5,
246
+ path: ["test"],
247
+ procedure: procedure as any,
248
+ signal: undefined,
249
+ lastEventId: undefined,
250
+ errors: {},
251
+ }),
252
+ );
253
+ }),
254
+ );
255
+
256
+ expect(result).toEqual({ requestId: "req-123", value: 6 });
257
+ } finally {
258
+ await serviceRuntime.dispose();
259
+ }
260
+ });
217
261
  });
218
262
 
219
263
  describe("makeEffectORPC factory", () => {
@@ -247,7 +291,6 @@ describe("makeEffectORPC factory", () => {
247
291
  it("creates working procedure with default os", async () => {
248
292
  const effectBuilder = makeEffectORPC(runtime);
249
293
 
250
- // oxlint-disable-next-line require-yield
251
294
  const procedure = effectBuilder.effect(function* () {
252
295
  return "hello";
253
296
  });
@@ -297,7 +340,6 @@ describe("makeEffectORPC factory", () => {
297
340
  .route({ path: "/test" })
298
341
  .input(z.object({ id: z.string() }))
299
342
  .output(z.object({ name: z.string() }))
300
- // oxlint-disable-next-line require-yield
301
343
  .effect(function* () {
302
344
  return { name: "test" };
303
345
  });
@@ -384,7 +426,6 @@ describe(".traced", () => {
384
426
  const procedure = effectBuilder
385
427
  .input(z.object({ id: z.string() }))
386
428
  .traced("users.getUser")
387
- // oxlint-disable-next-line require-yield
388
429
  .effect(function* () {
389
430
  return { name: "test" };
390
431
  });
@@ -399,7 +440,6 @@ describe(".traced", () => {
399
440
  const procedure = effectBuilder
400
441
  .input(z.object({ id: z.string() }))
401
442
  .traced("users.getUser")
402
- // oxlint-disable-next-line require-yield
403
443
  .effect(function* ({ input }) {
404
444
  return { id: input.id, name: "Alice" };
405
445
  });
@@ -461,7 +501,6 @@ describe("default tracing (without .traced())", () => {
461
501
  // No .traced() call - should still work and use path as span name
462
502
  const procedure = effectBuilder
463
503
  .input(z.object({ id: z.string() }))
464
- // oxlint-disable-next-line require-yield
465
504
  .effect(function* ({ input }) {
466
505
  return { id: input.id, name: "Bob" };
467
506
  });
@@ -483,7 +522,6 @@ describe("default tracing (without .traced())", () => {
483
522
  const effectBuilder = makeEffectORPC(runtime);
484
523
 
485
524
  // Without .traced(), the span name should be derived from path
486
- // oxlint-disable-next-line require-yield
487
525
  const procedure = effectBuilder.effect(function* () {
488
526
  return "hello";
489
527
  });
@@ -505,14 +543,11 @@ describe("default tracing (without .traced())", () => {
505
543
  it("default tracing works with Effect.fn generator", async () => {
506
544
  const effectBuilder = makeEffectORPC(runtime);
507
545
 
508
- const procedure = effectBuilder.effect(
509
- // oxlint-disable-next-line require-yield
510
- function* () {
511
- const x = 5;
512
- const y = 10;
513
- return x * y;
514
- },
515
- );
546
+ const procedure = effectBuilder.effect(function* () {
547
+ const x = 5;
548
+ const y = 10;
549
+ return x * y;
550
+ });
516
551
 
517
552
  const result = await procedure["~effect"].handler({
518
553
  context: {},
@@ -579,7 +614,6 @@ describe("default tracing (without .traced())", () => {
579
614
  .output(declaredOutputSchema)
580
615
  .effect(
581
616
  // @ts-expect-error input().output() should constrain the effect return type
582
- // oxlint-disable-next-line require-yield
583
617
  function* () {
584
618
  return { count: 1 };
585
619
  },
@@ -588,7 +622,6 @@ describe("default tracing (without .traced())", () => {
588
622
  const procedure = makeEffectORPC(runtime)
589
623
  .output(declaredOutputSchema)
590
624
  // @ts-expect-error output() should constrain the effect return type
591
- // oxlint-disable-next-line require-yield
592
625
  .effect(function* () {
593
626
  return { count: 1 };
594
627
  });
@@ -233,7 +233,6 @@ describe("effectBuilder with EffectErrorMap", () => {
233
233
  BAD_REQUEST: { status: 400 },
234
234
  })
235
235
  .input(z.object({ id: z.string() }))
236
- // oxlint-disable-next-line require-yield
237
236
  .effect(function* ({ input, errors }) {
238
237
  // errors.USER_NOT_FOUND_ERROR is the class
239
238
  expect(errors.USER_NOT_FOUND_ERROR).toBe(UserNotFoundError);
@@ -255,7 +254,6 @@ describe("effectBuilder with EffectErrorMap", () => {
255
254
  USER_NOT_FOUND_ERROR: UserNotFoundError,
256
255
  })
257
256
  .input(z.object({ id: z.string() }))
258
- // oxlint-disable-next-line require-yield
259
257
  .effect(function* ({ input, errors }) {
260
258
  if (input.id === "not-found") {
261
259
  return yield* Effect.fail(
@@ -299,7 +297,6 @@ describe("effectDecoratedProcedure.errors()", () => {
299
297
  it("should support adding errors to procedure", () => {
300
298
  const procedure = effectOs
301
299
  .input(z.object({ id: z.string() }))
302
- // oxlint-disable-next-line require-yield
303
300
  .effect(function* ({ input }) {
304
301
  return { id: input.id };
305
302
  })
@@ -314,7 +311,6 @@ describe("effectDecoratedProcedure.errors()", () => {
314
311
  const procedure = effectOs
315
312
  .errors({ BAD_REQUEST: { status: 400 } })
316
313
  .input(z.object({ id: z.string() }))
317
- // oxlint-disable-next-line require-yield
318
314
  .effect(function* ({ input }) {
319
315
  return { id: input.id };
320
316
  })
package/README.md DELETED
@@ -1,385 +0,0 @@
1
- # effect-orpc
2
-
3
- A type-safe integration between [oRPC](https://orpc.dev/) and [Effect](https://effect.website/), enabling Effect-native procedures with full service injection support, OpenTelemetry tracing support and typesafe Effect errors support.
4
-
5
- Inspired by [effect-trpc](https://github.com/mikearnaldi/effect-trpc).
6
-
7
- ## Features
8
-
9
- - **Effect-native procedures** - Write oRPC procedures using generators with `yield*` syntax
10
- - **Type-safe service injection** - Use `ManagedRuntime<R>` to provide services to procedures with compile-time safety
11
- - **Tagged errors** - Create Effect-native error classes with `ORPCTaggedError` that integrate with oRPC's error handling
12
- - **Full oRPC compatibility** - Mix Effect procedures with standard oRPC procedures in the same router
13
- - **Telemetry support with automatic tracing** - Procedures are automatically traced with OpenTelemetry-compatible spans. Customize span names with `.traced()`.
14
- - **Builder pattern preserved** - oRPC builder methods (`.errors()`, `.meta()`, `.route()`, `.input()`, `.output()`, `.use()`) work seamlessly
15
-
16
- ## Installation
17
-
18
- ```bash
19
- npm install effect-orpc
20
- # or
21
- pnpm add effect-orpc
22
- # or
23
- bun add effect-orpc
24
- ```
25
-
26
- `makeEffectORPC` stays on the main `effect-orpc` entrypoint. Only import
27
- `withFiberContext` from `effect-orpc/node`.
28
-
29
- The reason for the separate `/node` entrypoint is that `withFiberContext` relies
30
- on Node/Bun's `AsyncLocalStorage` from `node:async_hooks` to carry Effect
31
- `FiberRef` state across framework async boundaries. The main package stays
32
- runtime-agnostic.
33
-
34
- Runnable demos live in the repository's `examples/` directory.
35
-
36
- ## Demo
37
-
38
- ```ts
39
- import { os } from "@orpc/server";
40
- import { Effect, ManagedRuntime } from "effect";
41
- import { makeEffectORPC, ORPCTaggedError } from "effect-orpc";
42
-
43
- interface User {
44
- id: number;
45
- name: string;
46
- }
47
-
48
- let users: User[] = [
49
- { id: 1, name: "John Doe" },
50
- { id: 2, name: "Jane Doe" },
51
- { id: 3, name: "James Dane" },
52
- ];
53
-
54
- // Authenticated os with initial context & errors set
55
- const authedOs = os
56
- .errors({ UNAUTHORIZED: { status: 401 } })
57
- .$context<{ userId?: number }>()
58
- .use(({ context, errors, next }) => {
59
- if (context.userId === undefined) throw errors.UNAUTHORIZED();
60
- return next({ context: { ...context, userId: context.userId } });
61
- });
62
-
63
- // Define your services
64
- class UsersRepo extends Effect.Service<UsersRepo>()("UsersRepo", {
65
- accessors: true,
66
- sync: () => ({
67
- get: (id: number) => users.find((u) => u.id === id),
68
- }),
69
- }) {}
70
-
71
- // Special yieldable oRPC error class
72
- class UserNotFoundError extends ORPCTaggedError("UserNotFoundError", {
73
- status: 404,
74
- }) {}
75
-
76
- // Create runtime with your services
77
- const runtime = ManagedRuntime.make(UsersRepo.Default);
78
- // Create Effect-aware oRPC builder from an other (optional) base oRPC builder and provide tagged errors
79
- const effectOs = makeEffectORPC(runtime, authedOs).errors({
80
- UserNotFoundError,
81
- });
82
-
83
- // Create the router with mixed procedures
84
- export const router = {
85
- health: os.handler(() => "ok"),
86
- users: {
87
- me: effectOs.effect(function* ({ context: { userId } }) {
88
- const user = yield* UsersRepo.get(userId);
89
- if (!user) {
90
- return yield* new UserNotFoundError();
91
- }
92
- return user;
93
- }),
94
- },
95
- };
96
-
97
- export type Router = typeof router;
98
- ```
99
-
100
- ## Request-Scoped Fiber Context
101
-
102
- If you run `effect-orpc` inside a framework such as Hono, the handler executes
103
- through the runtime boundary and will not automatically inherit request-local
104
- `FiberRef` state from outer middleware. Import `makeEffectORPC` from the main
105
- package, and wrap the framework continuation with `withFiberContext` from
106
- `effect-orpc/node` to preserve request-scoped logs, tracing annotations, and
107
- other fiber-local state.
108
-
109
- ```ts
110
- import { Hono } from "hono";
111
- import { Effect, ManagedRuntime } from "effect";
112
- import { makeEffectORPC } from "effect-orpc";
113
- import { withFiberContext } from "effect-orpc/node";
114
-
115
- const runtime = ManagedRuntime.make(AppLive);
116
- const effectOs = makeEffectORPC(runtime);
117
- const app = new Hono();
118
-
119
- app.use("*", async (c, next) => {
120
- await Effect.runPromise(
121
- Effect.gen(function* () {
122
- yield* Effect.annotateLogsScoped({
123
- requestId: c.get("requestId"),
124
- });
125
-
126
- yield* withFiberContext(() => next());
127
- }),
128
- );
129
- });
130
- ```
131
-
132
- If you do not need framework-to-handler fiber propagation, you do not need the
133
- `/node` entrypoint at all.
134
-
135
- ## Type Safety
136
-
137
- The wrapper enforces that Effect procedures only use services provided by the `ManagedRuntime`. If you try to use a service that isn't in the runtime, you'll get a compile-time error:
138
-
139
- ```ts
140
- import { Context, Effect, Layer, ManagedRuntime } from "effect";
141
- import { makeEffectORPC } from "effect-orpc";
142
-
143
- class ProvidedService extends Context.Tag("ProvidedService")<
144
- ProvidedService,
145
- { doSomething: () => Effect.Effect<string> }
146
- >() {}
147
-
148
- class MissingService extends Context.Tag("MissingService")<
149
- MissingService,
150
- { doSomething: () => Effect.Effect<string> }
151
- >() {}
152
-
153
- const runtime = ManagedRuntime.make(
154
- Layer.succeed(ProvidedService, {
155
- doSomething: () => Effect.succeed("ok"),
156
- }),
157
- );
158
-
159
- const effectOs = makeEffectORPC(runtime);
160
-
161
- // ✅ This compiles - ProvidedService is in the runtime
162
- const works = effectOs.effect(function* () {
163
- const service = yield* ProvidedService;
164
- return yield* service.doSomething();
165
- });
166
-
167
- // ❌ This fails to compile - MissingService is not in the runtime
168
- const fails = effectOs.effect(function* () {
169
- const service = yield* MissingService; // Type error!
170
- return yield* service.doSomething();
171
- });
172
- ```
173
-
174
- ## Error Handling
175
-
176
- `ORPCTaggedError` lets you create Effect-native error classes that integrate seamlessly with oRPC. These errors:
177
-
178
- - Can be yielded in Effect generators (`yield* new MyError()` or `yield* Effect.fail(errors.MyError)`)
179
- - Can be used in Effect builder's `.errors()` maps for type-safe error handling alongside regular oRPC errors
180
- - Automatically convert to ORPCError when thrown
181
-
182
- Make sure the tagged error class is passed to the effect `.errors()` to be able to yield the error class directly and make the client recognize it as defined.
183
-
184
- ```ts
185
- const getUser = effectOs
186
- // Mixed error maps
187
- .errors({
188
- // Regular oRPC error
189
- NOT_FOUND: {
190
- message: "User not found",
191
- data: z.object({ id: z.string() }),
192
- },
193
- // Effect oRPC tagged error
194
- UserNotFoundError,
195
- // Note: The key of an oRPC error is not used as the error code
196
- // So the following will only change the key of the error when accessing it
197
- // from the errors object passed to the handler, but not the actual error code itself.
198
- // To change the error's code, please see the next section on creating tagged errors.
199
- USER_NOT_FOUND: UserNotFoundError,
200
- // ^^^ same code as the `UserNotFoundError` error key, defined at the class level
201
- })
202
- .effect(function* ({ input, errors }) {
203
- const user = yield* UsersRepo.findById(input.id);
204
- if (!user) {
205
- return yield* new UserNotFoundError();
206
- // or return `yield* Effect.fail(errors.USER_NOT_FOUND())`
207
- }
208
- return user;
209
- });
210
- ```
211
-
212
- ### Creating Tagged Errors
213
-
214
- ```ts
215
- import { ORPCTaggedError } from "effect-orpc";
216
-
217
- // Basic tagged error - code defaults to 'USER_NOT_FOUND' (CONSTANT_CASE of tag)
218
- class UserNotFound extends ORPCTaggedError("UserNotFound") {}
219
-
220
- // With explicit code
221
- class NotFound extends ORPCTaggedError("NotFound", { code: "NOT_FOUND" }) {}
222
-
223
- // With default options (code defaults to 'VALIDATION_ERROR') (CONSTANT_CASE of tag)
224
- class ValidationError extends ORPCTaggedError("ValidationError", {
225
- status: 400,
226
- message: "Validation failed",
227
- }) {}
228
-
229
- // With all options
230
- class ForbiddenError extends ORPCTaggedError("ForbiddenError", {
231
- code: "FORBIDDEN",
232
- status: 403,
233
- message: "Access denied",
234
- schema: z.object({
235
- reason: z.string(),
236
- }),
237
- }) {}
238
-
239
- // With typed data using Standard Schema
240
- class UserNotFoundWithData extends ORPCTaggedError("UserNotFoundWithData", {
241
- schema: z.object({ userId: z.string() }),
242
- }) {}
243
- ```
244
-
245
- ## Traceable Spans
246
-
247
- All Effect procedures are automatically traced with `Effect.withSpan`. By default, the span name is the procedure path (e.g., `users.getUser`):
248
-
249
- ```ts
250
- // Router structure determines span names automatically
251
- const router = {
252
- users: {
253
- // Span name: "users.get"
254
- get: effectOs.input(z.object({ id: z.string() })).effect(function* ({
255
- input,
256
- }) {
257
- const userService = yield* UserService;
258
- return yield* userService.findById(input.id);
259
- }),
260
- // Span name: "users.create"
261
- create: effectOs.input(z.object({ name: z.string() })).effect(function* ({
262
- input,
263
- }) {
264
- const userService = yield* UserService;
265
- return yield* userService.create(input.name);
266
- }),
267
- },
268
- };
269
- ```
270
-
271
- Use `.traced()` to override the default span name:
272
-
273
- ```ts
274
- const getUser = effectOs
275
- .input(z.object({ id: z.string() }))
276
- .traced("custom.span.name") // Override the default path-based name
277
- .effect(function* ({ input }) {
278
- const userService = yield* UserService;
279
- return yield* userService.findById(input.id);
280
- });
281
- ```
282
-
283
- ### Enabling OpenTelemetry
284
-
285
- To enable tracing, include the OpenTelemetry layer in your runtime:
286
-
287
- ```ts
288
- import { NodeSdk } from "@effect/opentelemetry";
289
- import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
290
- import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
291
-
292
- const TracingLive = NodeSdk.layer(
293
- Effect.sync(() => ({
294
- resource: { serviceName: "my-service" },
295
- spanProcessor: [new SimpleSpanProcessor(new OTLPTraceExporter())],
296
- })),
297
- );
298
-
299
- const AppLive = Layer.mergeAll(UserServiceLive, TracingLive);
300
-
301
- const runtime = ManagedRuntime.make(AppLive);
302
- const effectOs = makeEffectORPC(runtime);
303
- ```
304
-
305
- ### Error Stack Traces
306
-
307
- When an Effect procedure fails, the span includes a properly formatted stack trace pointing to the definition site:
308
-
309
- ```
310
- MyCustomError: Something went wrong
311
- at <anonymous> (/app/src/procedures.ts:42:28)
312
- at users.getById (/app/src/procedures.ts:41:35)
313
- ```
314
-
315
- ## API Reference
316
-
317
- ### `makeEffectORPC(runtime, builder?)`
318
-
319
- Creates an Effect-aware procedure builder.
320
-
321
- - `runtime` - A `ManagedRuntime<R, E>` instance that provides services for Effect procedures
322
- - `builder` (optional) - An oRPC Builder instance to wrap. Defaults to `os` from `@orpc/server`
323
-
324
- Returns an `EffectBuilder` instance.
325
-
326
- ```ts
327
- // With default builder
328
- const effectOs = makeEffectORPC(runtime);
329
-
330
- // With customized builder
331
- const effectAuthedOs = makeEffectORPC(runtime, authedBuilder);
332
- ```
333
-
334
- ### `EffectBuilder`
335
-
336
- Wraps an oRPC Builder with Effect support. Available methods:
337
-
338
- | Method | Description |
339
- | ------------------- | ------------------------------------------------------------------------------- |
340
- | `.$config(config)` | Set or override the builder config |
341
- | `.$context<U>()` | Set or override the initial context type |
342
- | `.$meta(meta)` | Set or override the initial metadata |
343
- | `.$route(route)` | Set or override the initial route configuration |
344
- | `.$input(schema)` | Set or override the initial input schema |
345
- | `.errors(map)` | Add type-safe custom errors |
346
- | `.meta(meta)` | Set procedure metadata (merged with existing) |
347
- | `.route(route)` | Configure OpenAPI route (merged with existing) |
348
- | `.input(schema)` | Define input validation schema |
349
- | `.output(schema)` | Define output validation schema |
350
- | `.use(middleware)` | Add middleware |
351
- | `.traced(name)` | Add a traceable span for telemetry (optional, defaults to the procedure's path) |
352
- | `.handler(handler)` | Define a non-Effect handler (standard oRPC handler) |
353
- | `.effect(handler)` | Define the Effect handler |
354
- | `.prefix(prefix)` | Prefix all procedures in the router (for OpenAPI) |
355
- | `.tag(...tags)` | Add tags to all procedures in the router (for OpenAPI) |
356
- | `.router(router)` | Apply all options to a router |
357
- | `.lazy(loader)` | Create and apply options to a lazy-loaded router |
358
-
359
- ### `EffectDecoratedProcedure`
360
-
361
- The result of calling `.effect()`. Extends standard oRPC `DecoratedProcedure` with Effect type preservation.
362
-
363
- | Method | Description |
364
- | ----------------------- | --------------------------------------------- |
365
- | `.errors(map)` | Add more custom errors |
366
- | `.meta(meta)` | Update metadata (merged with existing) |
367
- | `.route(route)` | Update route configuration (merged) |
368
- | `.use(middleware)` | Add middleware |
369
- | `.callable(options?)` | Make procedure directly invocable |
370
- | `.actionable(options?)` | Make procedure compatible with server actions |
371
-
372
- ### `ORPCTaggedError(tag, options?)`
373
-
374
- Factory function to create Effect-native tagged error classes.
375
-
376
- The options is an optional object containing:
377
-
378
- - `schema?` - Optional Standard Schema for the error's data payload (e.g., `z.object({ userId: z.string() })`)
379
- - `code?` - Optional ORPCErrorCode, defaults to CONSTANT_CASE of the tag (e.g., `UserNotFoundError` → `USER_NOT_FOUND_ERROR`).
380
- - `status?` - Sets the default status of the error
381
- - `message` - Sets the default message of the error
382
-
383
- ## License
384
-
385
- MIT