effect-orpc 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +391 -0
  2. package/package.json +3 -3
package/README.md ADDED
@@ -0,0 +1,391 @@
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
+ Runnable demos live in the repository's `examples/` directory.
27
+
28
+ ## Demo
29
+
30
+ ```ts
31
+ import { os } from "@orpc/server";
32
+ import { Effect, ManagedRuntime } from "effect";
33
+ import { makeEffectORPC, ORPCTaggedError } from "effect-orpc";
34
+
35
+ interface User {
36
+ id: number;
37
+ name: string;
38
+ }
39
+
40
+ let users: User[] = [
41
+ { id: 1, name: "John Doe" },
42
+ { id: 2, name: "Jane Doe" },
43
+ { id: 3, name: "James Dane" },
44
+ ];
45
+
46
+ // Authenticated os with initial context & errors set
47
+ const authedOs = os
48
+ .errors({ UNAUTHORIZED: { status: 401 } })
49
+ .$context<{ userId?: number }>()
50
+ .use(({ context, errors, next }) => {
51
+ if (context.userId === undefined) throw errors.UNAUTHORIZED();
52
+ return next({ context: { ...context, userId: context.userId } });
53
+ });
54
+
55
+ // Define your services
56
+ class UsersRepo extends Effect.Service<UsersRepo>()("UsersRepo", {
57
+ accessors: true,
58
+ sync: () => ({
59
+ get: (id: number) => users.find((u) => u.id === id),
60
+ }),
61
+ }) {}
62
+
63
+ // Special yieldable oRPC error class
64
+ class UserNotFoundError extends ORPCTaggedError("UserNotFoundError", {
65
+ status: 404,
66
+ }) {}
67
+
68
+ // Create runtime with your services
69
+ const runtime = ManagedRuntime.make(UsersRepo.Default);
70
+ // Create Effect-aware oRPC builder from an other (optional) base oRPC builder and provide tagged errors
71
+ const effectOs = makeEffectORPC(runtime, authedOs).errors({
72
+ UserNotFoundError,
73
+ });
74
+
75
+ // Create the router with mixed procedures
76
+ export const router = {
77
+ health: os.handler(() => "ok"),
78
+ users: {
79
+ me: effectOs.effect(function* ({ context: { userId } }) {
80
+ const user = yield* UsersRepo.get(userId);
81
+ if (!user) {
82
+ return yield* new UserNotFoundError();
83
+ }
84
+ return user;
85
+ }),
86
+ },
87
+ };
88
+
89
+ export type Router = typeof router;
90
+ ```
91
+
92
+ ## Type Safety
93
+
94
+ 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:
95
+
96
+ ```ts
97
+ import { Context, Effect, Layer, ManagedRuntime } from "effect";
98
+ import { makeEffectORPC } from "effect-orpc";
99
+
100
+ class ProvidedService extends Context.Tag("ProvidedService")<
101
+ ProvidedService,
102
+ { doSomething: () => Effect.Effect<string> }
103
+ >() {}
104
+
105
+ class MissingService extends Context.Tag("MissingService")<
106
+ MissingService,
107
+ { doSomething: () => Effect.Effect<string> }
108
+ >() {}
109
+
110
+ const runtime = ManagedRuntime.make(
111
+ Layer.succeed(ProvidedService, {
112
+ doSomething: () => Effect.succeed("ok"),
113
+ }),
114
+ );
115
+
116
+ const effectOs = makeEffectORPC(runtime);
117
+
118
+ // ✅ This compiles - ProvidedService is in the runtime
119
+ const works = effectOs.effect(function* () {
120
+ const service = yield* ProvidedService;
121
+ return yield* service.doSomething();
122
+ });
123
+
124
+ // ❌ This fails to compile - MissingService is not in the runtime
125
+ const fails = effectOs.effect(function* () {
126
+ const service = yield* MissingService; // Type error!
127
+ return yield* service.doSomething();
128
+ });
129
+ ```
130
+
131
+ ## Error Handling
132
+
133
+ `ORPCTaggedError` lets you create Effect-native error classes that integrate seamlessly with oRPC. These errors:
134
+
135
+ - Can be yielded in Effect generators (`yield* new MyError()` or `yield* Effect.fail(errors.MyError)`)
136
+ - Can be used in Effect builder's `.errors()` maps for type-safe error handling alongside regular oRPC errors
137
+ - Automatically convert to ORPCError when thrown
138
+
139
+ 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.
140
+
141
+ ```ts
142
+ const getUser = effectOs
143
+ // Mixed error maps
144
+ .errors({
145
+ // Regular oRPC error
146
+ NOT_FOUND: {
147
+ message: "User not found",
148
+ data: z.object({ id: z.string() }),
149
+ },
150
+ // Effect oRPC tagged error
151
+ UserNotFoundError,
152
+ // Note: The key of an oRPC error is not used as the error code
153
+ // So the following will only change the key of the error when accessing it
154
+ // from the errors object passed to the handler, but not the actual error code itself.
155
+ // To change the error's code, please see the next section on creating tagged errors.
156
+ USER_NOT_FOUND: UserNotFoundError,
157
+ // ^^^ same code as the `UserNotFoundError` error key, defined at the class level
158
+ })
159
+ .effect(function* ({ input, errors }) {
160
+ const user = yield* UsersRepo.findById(input.id);
161
+ if (!user) {
162
+ return yield* new UserNotFoundError();
163
+ // or return `yield* Effect.fail(errors.USER_NOT_FOUND())`
164
+ }
165
+ return user;
166
+ });
167
+ ```
168
+
169
+ ### Creating Tagged Errors
170
+
171
+ ```ts
172
+ import { ORPCTaggedError } from "effect-orpc";
173
+
174
+ // Basic tagged error - code defaults to 'USER_NOT_FOUND' (CONSTANT_CASE of tag)
175
+ class UserNotFound extends ORPCTaggedError("UserNotFound") {}
176
+
177
+ // With explicit code
178
+ class NotFound extends ORPCTaggedError("NotFound", { code: "NOT_FOUND" }) {}
179
+
180
+ // With default options (code defaults to 'VALIDATION_ERROR') (CONSTANT_CASE of tag)
181
+ class ValidationError extends ORPCTaggedError("ValidationError", {
182
+ status: 400,
183
+ message: "Validation failed",
184
+ }) {}
185
+
186
+ // With all options
187
+ class ForbiddenError extends ORPCTaggedError("ForbiddenError", {
188
+ code: "FORBIDDEN",
189
+ status: 403,
190
+ message: "Access denied",
191
+ schema: z.object({
192
+ reason: z.string(),
193
+ }),
194
+ }) {}
195
+
196
+ // With typed data using Standard Schema
197
+ class UserNotFoundWithData extends ORPCTaggedError("UserNotFoundWithData", {
198
+ schema: z.object({ userId: z.string() }),
199
+ }) {}
200
+ ```
201
+
202
+ ## Traceable Spans
203
+
204
+ All Effect procedures are automatically traced with `Effect.withSpan`. By default, the span name is the procedure path (e.g., `users.getUser`):
205
+
206
+ ```ts
207
+ // Router structure determines span names automatically
208
+ const router = {
209
+ users: {
210
+ // Span name: "users.get"
211
+ get: effectOs.input(z.object({ id: z.string() })).effect(function* ({
212
+ input,
213
+ }) {
214
+ const userService = yield* UserService;
215
+ return yield* userService.findById(input.id);
216
+ }),
217
+ // Span name: "users.create"
218
+ create: effectOs.input(z.object({ name: z.string() })).effect(function* ({
219
+ input,
220
+ }) {
221
+ const userService = yield* UserService;
222
+ return yield* userService.create(input.name);
223
+ }),
224
+ },
225
+ };
226
+ ```
227
+
228
+ Use `.traced()` to override the default span name:
229
+
230
+ ```ts
231
+ const getUser = effectOs
232
+ .input(z.object({ id: z.string() }))
233
+ .traced("custom.span.name") // Override the default path-based name
234
+ .effect(function* ({ input }) {
235
+ const userService = yield* UserService;
236
+ return yield* userService.findById(input.id);
237
+ });
238
+ ```
239
+
240
+ ### Enabling OpenTelemetry
241
+
242
+ To enable tracing, include the OpenTelemetry layer in your runtime:
243
+
244
+ ```ts
245
+ import { NodeSdk } from "@effect/opentelemetry";
246
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
247
+ import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
248
+
249
+ const TracingLive = NodeSdk.layer(
250
+ Effect.sync(() => ({
251
+ resource: { serviceName: "my-service" },
252
+ spanProcessor: [new SimpleSpanProcessor(new OTLPTraceExporter())],
253
+ })),
254
+ );
255
+
256
+ const AppLive = Layer.mergeAll(UserServiceLive, TracingLive);
257
+
258
+ const runtime = ManagedRuntime.make(AppLive);
259
+ const effectOs = makeEffectORPC(runtime);
260
+ ```
261
+
262
+ ### Error Stack Traces
263
+
264
+ When an Effect procedure fails, the span includes a properly formatted stack trace pointing to the definition site:
265
+
266
+ ```
267
+ MyCustomError: Something went wrong
268
+ at <anonymous> (/app/src/procedures.ts:42:28)
269
+ at users.getById (/app/src/procedures.ts:41:35)
270
+ ```
271
+
272
+ ## Request-Scoped Fiber Context
273
+
274
+ If you run `effect-orpc` inside a framework such as Hono, the handler executes
275
+ through the runtime boundary and will not automatically inherit request-local
276
+ `FiberRef` state from outer middleware.
277
+
278
+ To preserve request-scoped logs, tracing annotations, and
279
+ other fiber-local state, wrap the framework continuation with `withFiberContext` from
280
+ `effect-orpc/node`.
281
+
282
+ ```ts
283
+ import { Hono } from "hono";
284
+ import { Effect, ManagedRuntime } from "effect";
285
+ import { makeEffectORPC } from "effect-orpc";
286
+ import { withFiberContext } from "effect-orpc/node";
287
+
288
+ const runtime = ManagedRuntime.make(AppLive);
289
+ const effectOs = makeEffectORPC(runtime);
290
+ const app = new Hono();
291
+
292
+ app.use("*", async (c, next) => {
293
+ await Effect.runPromise(
294
+ Effect.gen(function* () {
295
+ yield* Effect.annotateLogsScoped({
296
+ requestId: c.get("requestId"),
297
+ });
298
+
299
+ yield* withFiberContext(() => next());
300
+ }),
301
+ );
302
+ });
303
+ ```
304
+
305
+ When a captured fiber context and the `ManagedRuntime` both provide the same
306
+ service, `effect-orpc` prioritizes the captured context. The runtime is treated
307
+ as the application-wide base layer, while `withFiberContext` preserves the
308
+ more specific request-scoped values from outer middleware. This prevents
309
+ request-local references such as request IDs, logging annotations, tracing
310
+ context, or scoped overrides from being replaced by runtime defaults when the
311
+ handler crosses the runtime boundary.
312
+
313
+ The reason for the separate `/node` entrypoint is that `withFiberContext` relies
314
+ on Node/Bun's `AsyncLocalStorage` from `node:async_hooks` to carry Effect
315
+ `FiberRef` state across framework async boundaries. The main package stays
316
+ runtime-agnostic.
317
+
318
+ If you do not need framework-to-handler fiber propagation, you do not need the
319
+ `/node` entrypoint at all.
320
+
321
+ ## API Reference
322
+
323
+ ### `makeEffectORPC(runtime, builder?)`
324
+
325
+ Creates an Effect-aware procedure builder.
326
+
327
+ - `runtime` - A `ManagedRuntime<R, E>` instance that provides services for Effect procedures
328
+ - `builder` (optional) - An oRPC Builder instance to wrap. Defaults to `os` from `@orpc/server`
329
+
330
+ Returns an `EffectBuilder` instance.
331
+
332
+ ```ts
333
+ // With default builder
334
+ const effectOs = makeEffectORPC(runtime);
335
+
336
+ // With customized builder
337
+ const effectAuthedOs = makeEffectORPC(runtime, authedBuilder);
338
+ ```
339
+
340
+ ### `EffectBuilder`
341
+
342
+ Wraps an oRPC Builder with Effect support. Available methods:
343
+
344
+ | Method | Description |
345
+ | ------------------- | ------------------------------------------------------------------------------- |
346
+ | `.$config(config)` | Set or override the builder config |
347
+ | `.$context<U>()` | Set or override the initial context type |
348
+ | `.$meta(meta)` | Set or override the initial metadata |
349
+ | `.$route(route)` | Set or override the initial route configuration |
350
+ | `.$input(schema)` | Set or override the initial input schema |
351
+ | `.errors(map)` | Add type-safe custom errors |
352
+ | `.meta(meta)` | Set procedure metadata (merged with existing) |
353
+ | `.route(route)` | Configure OpenAPI route (merged with existing) |
354
+ | `.input(schema)` | Define input validation schema |
355
+ | `.output(schema)` | Define output validation schema |
356
+ | `.use(middleware)` | Add middleware |
357
+ | `.traced(name)` | Add a traceable span for telemetry (optional, defaults to the procedure's path) |
358
+ | `.handler(handler)` | Define a non-Effect handler (standard oRPC handler) |
359
+ | `.effect(handler)` | Define the Effect handler |
360
+ | `.prefix(prefix)` | Prefix all procedures in the router (for OpenAPI) |
361
+ | `.tag(...tags)` | Add tags to all procedures in the router (for OpenAPI) |
362
+ | `.router(router)` | Apply all options to a router |
363
+ | `.lazy(loader)` | Create and apply options to a lazy-loaded router |
364
+
365
+ ### `EffectDecoratedProcedure`
366
+
367
+ The result of calling `.effect()`. Extends standard oRPC `DecoratedProcedure` with Effect type preservation.
368
+
369
+ | Method | Description |
370
+ | ----------------------- | --------------------------------------------- |
371
+ | `.errors(map)` | Add more custom errors |
372
+ | `.meta(meta)` | Update metadata (merged with existing) |
373
+ | `.route(route)` | Update route configuration (merged) |
374
+ | `.use(middleware)` | Add middleware |
375
+ | `.callable(options?)` | Make procedure directly invocable |
376
+ | `.actionable(options?)` | Make procedure compatible with server actions |
377
+
378
+ ### `ORPCTaggedError(tag, options?)`
379
+
380
+ Factory function to create Effect-native tagged error classes.
381
+
382
+ The options is an optional object containing:
383
+
384
+ - `schema?` - Optional Standard Schema for the error's data payload (e.g., `z.object({ userId: z.string() })`)
385
+ - `code?` - Optional ORPCErrorCode, defaults to CONSTANT_CASE of the tag (e.g., `UserNotFoundError` → `USER_NOT_FOUND_ERROR`).
386
+ - `status?` - Sets the default status of the error
387
+ - `message` - Sets the default message of the error
388
+
389
+ ## License
390
+
391
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-orpc",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "keywords": [
5
5
  "effect",
6
6
  "orpc",
@@ -36,7 +36,7 @@
36
36
  }
37
37
  },
38
38
  "scripts": {
39
- "build": "tsup",
39
+ "build": "tsup && bun run sync:readme",
40
40
  "build:watch": "bun run build --watch",
41
41
  "type:check": "tsc -b",
42
42
  "lint:check": "oxlint",
@@ -44,7 +44,7 @@
44
44
  "check": "bun run format:check && bun run lint:check && bun run type:check",
45
45
  "format": "oxfmt",
46
46
  "test": "vitest ./src/tests",
47
- "prepack": "bun ../../scripts/sync-package-readme.ts"
47
+ "sync:readme": "bun ../../scripts/sync-package-readme.ts"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@types/bun": "latest",