@rotorsoft/act-http 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,168 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * @module act-http/trpc
4
+ *
5
+ * tRPC subpath for the auto-generated API epic (#835). Walks the
6
+ * registry of a built `Act` once at function call and emits a typed
7
+ * router that exposes every registered action as a flat `mutation`,
8
+ * matching the shape hand-written tRPC routers in the Act ecosystem
9
+ * already use.
10
+ *
11
+ * Usage:
12
+ *
13
+ * ```ts
14
+ * import { trpc } from "@rotorsoft/act-http/trpc";
15
+ *
16
+ * const router = trpc(app, {
17
+ * actor: (ctx) => ({ id: ctx.user.id, name: ctx.user.name }),
18
+ * stream: (action, input, ctx) => input.stream ?? ctx.tenant,
19
+ * });
20
+ *
21
+ * // Client sees:
22
+ * // appRouter.PressKey.mutate({ key: "5" })
23
+ * // appRouter.OpenTicket.mutate({ title: "..." })
24
+ * ```
25
+ *
26
+ * The route shape is flat: one procedure per registered action at
27
+ * the top level. Action names are the unique identifiers across
28
+ * the registry (the framework already enforces no duplicates), so
29
+ * an extra namespace tier would be overhead in the common case.
30
+ * Pure mutations for this slice; query/projection wiring lives in
31
+ * a follow-up. See `libs/act-http/README.md` for the full surface
32
+ * walkthrough.
33
+ *
34
+ * **Actor lives on the context.** The generator wires an internal
35
+ * tRPC middleware that runs the host's
36
+ * {@link TrpcOptions.actor | actor extractor} once per call and
37
+ * injects the resolved {@link Actor} onto the downstream context as
38
+ * `ctx.actor`. Every generated mutation reads from there — auth
39
+ * resolves at the procedure boundary, not inside each action body,
40
+ * and any composed middleware (logging, tracing) sees the same
41
+ * `ctx.actor`. The middleware factory is also exported as
42
+ * {@link authenticated} for hosts that need to compose it into
43
+ * their own procedure chain.
44
+ *
45
+ * Composes the shared utilities at `@rotorsoft/act-http/api`:
46
+ * {@link ActorExtractor} for the auth seam, {@link toApiError} for
47
+ * the uniform error→status/code mapping, {@link withIdempotency}
48
+ * for `Idempotency-Key` dedup. Three transports (this one, Hono,
49
+ * OpenAPI) ride the same utilities so a client talking to two
50
+ * transports never sees two error shapes for the same framework
51
+ * error.
52
+ */
53
+ import type { Act, Schema, Schemas } from "@rotorsoft/act";
54
+ import type { IdempotencyStore } from "@rotorsoft/act-ops/idempotency";
55
+ import { type ActorExtractor } from "../api/index.js";
56
+ /**
57
+ * Per-call options for {@link trpc}. The host supplies the three
58
+ * seams the package can't make decisions on:
59
+ *
60
+ * - `actor` — auth resolver. Receives the tRPC context, returns the
61
+ * `Actor` that flows onto `ctx.actor` for every generated
62
+ * procedure (via an internal {@link authenticated}).
63
+ * - `stream` — stream-id resolver. Receives the action name, the
64
+ * validated action input, and the original tRPC context; returns
65
+ * the target stream. Singleton aggregates return a constant;
66
+ * per-tenant aggregates pull from input or context.
67
+ * - `expectedVersion` (optional) — optimistic-concurrency resolver.
68
+ * When set, the procedure threads the resolved value through
69
+ * `target.expectedVersion` so `app.do` refuses to commit if the
70
+ * stream has moved. Hosts typically read it from an `If-Match`
71
+ * header on the underlying HTTP request, or pull it from the
72
+ * client's last-known snapshot. Returning `undefined` skips the
73
+ * check for that call — handy when only some actions are
74
+ * concurrency-sensitive.
75
+ * - `idempotency` (optional) — when set, the procedure honors
76
+ * `Idempotency-Key` via the shared
77
+ * {@link withIdempotency} helper. The host supplies the
78
+ * `IdempotencyStore` and a `keyFrom` extractor that reads the key
79
+ * out of the tRPC context (typically a header). On a duplicate
80
+ * claim, the procedure throws a `CONFLICT` `TRPCError` — the
81
+ * receiver-side convention of "ack the duplicate" doesn't carry
82
+ * over because the contract intentionally does not cache the
83
+ * original handler's result.
84
+ *
85
+ * @template Ctx The host's tRPC context shape. Flows end-to-end —
86
+ * procedures see this exact context type (plus `actor`) at
87
+ * runtime.
88
+ */
89
+ export type TrpcOptions<Ctx> = {
90
+ readonly actor: ActorExtractor;
91
+ readonly stream: (action_name: string, input: unknown, ctx: Ctx) => string | Promise<string>;
92
+ readonly expectedVersion?: (action_name: string, input: unknown, ctx: Ctx) => number | undefined | Promise<number | undefined>;
93
+ readonly idempotency?: {
94
+ readonly store: IdempotencyStore;
95
+ readonly keyFrom: (ctx: Ctx) => string | undefined;
96
+ };
97
+ };
98
+ /**
99
+ * Build a tRPC middleware that runs an {@link ActorExtractor} once
100
+ * per call and forwards the resolved {@link Actor} on the
101
+ * downstream context as `ctx.actor`. The generator at
102
+ * {@link trpc} uses this internally; it's also exported so hosts
103
+ * that want to compose their own procedure chain (logging,
104
+ * tracing, custom auth flavors) can wire it directly:
105
+ *
106
+ * ```ts
107
+ * import { initTRPC } from "@trpc/server";
108
+ * import { authenticated } from "@rotorsoft/act-http/trpc";
109
+ *
110
+ * type Ctx = { user?: { id: string; name: string } };
111
+ * const t = initTRPC.context<Ctx>().create();
112
+ *
113
+ * const authed = t.procedure.use(
114
+ * authenticated((ctx) => {
115
+ * if (!ctx.user) throw new Error("not authenticated");
116
+ * return { id: ctx.user.id, name: ctx.user.name };
117
+ * })
118
+ * );
119
+ *
120
+ * // Inside any procedure built off `authed`, `ctx.actor: Actor`.
121
+ * ```
122
+ *
123
+ * The middleware is unaware of the host's `t` instance — it returns
124
+ * a structurally-typed function that any tRPC `procedure.use(...)`
125
+ * accepts. Errors thrown by the extractor surface unchanged
126
+ * (typically wrap them as `TRPCError({ code: "UNAUTHORIZED" })`
127
+ * in the extractor body).
128
+ */
129
+ export declare function authenticated(extractor: ActorExtractor): any;
130
+ /**
131
+ * Build a typed tRPC router from a built `Act` instance.
132
+ *
133
+ * Walks `app.registry.actions` once and emits one flat mutation per
134
+ * action under `router.<actionName>`. The framework already enforces
135
+ * no duplicate action names across states, so a flat tier reads
136
+ * cleanly at the client and matches the hand-written router shape
137
+ * adopters already have. Each mutation:
138
+ *
139
+ * 1. Runs the internal {@link authenticated} — `options.actor`
140
+ * resolves the {@link Actor} once and injects it onto
141
+ * `ctx.actor`.
142
+ * 2. Resolves the target stream via `options.stream(name, input, ctx)`.
143
+ * 3. (Optionally) claims the `Idempotency-Key` via
144
+ * {@link withIdempotency} — throws `CONFLICT` on duplicate.
145
+ * 4. Calls `app.do(name, { stream, actor: ctx.actor }, input)`.
146
+ * 5. Maps any thrown framework error onto a `TRPCError` via
147
+ * {@link toApiError}.
148
+ *
149
+ * The returned router's procedure inputs come straight from each
150
+ * action's Zod schema; outputs are the framework's
151
+ * `Snapshot<TState, TEvents>[]` shape. Strong typing flows
152
+ * end-to-end via tRPC's normal inference path — the client sees
153
+ * `appRouter.Calculator.PressKey.mutate({ key: "5" })` as a typed
154
+ * call without any codegen.
155
+ *
156
+ * @template Ctx The tRPC context shape the host's runtime feeds in.
157
+ * Flows through `actor`, `stream`, and `idempotency.keyFrom` so
158
+ * the operator's existing context types just work. The internal
159
+ * middleware augments `Ctx` with `{ actor: Actor }` on the
160
+ * downstream procedure context.
161
+ *
162
+ * @param app A built `Act` orchestrator.
163
+ * @param options Auth, stream, and (optional) idempotency seams.
164
+ * @returns A tRPC router covering every registered action, grouped
165
+ * by owning state.
166
+ */
167
+ export declare function trpc<Ctx extends object = object>(app: Act<any, Schemas, Schemas, Record<string, Schema>>, options: TrpcOptions<Ctx>): never;
168
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/trpc/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AACH,OAAO,KAAK,EAAE,GAAG,EAAS,MAAM,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAEvE,OAAO,EACL,KAAK,cAAc,EAGpB,MAAM,iBAAiB,CAAC;AAEzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,MAAM,WAAW,CAAC,GAAG,IAAI;IAC7B,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;IAC/B,QAAQ,CAAC,MAAM,EAAE,CACf,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,OAAO,EACd,GAAG,EAAE,GAAG,KACL,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC9B,QAAQ,CAAC,eAAe,CAAC,EAAE,CACzB,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,OAAO,EACd,GAAG,EAAE,GAAG,KACL,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACtD,QAAQ,CAAC,WAAW,CAAC,EAAE;QACrB,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAC;QACjC,QAAQ,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,MAAM,GAAG,SAAS,CAAC;KACpD,CAAC;CACH,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,wBAAgB,aAAa,CAAC,SAAS,EAAE,cAAc,GAAG,GAAG,CAW5D;AA+CD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,wBAAgB,IAAI,CAAC,GAAG,SAAS,MAAM,GAAG,MAAM,EAE9C,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EACvD,OAAO,EAAE,WAAW,CAAC,GAAG,CAAC,SAkE1B"}
package/dist/api/index.js CHANGED
@@ -1,59 +1,8 @@
1
- // src/api/errors.ts
2
1
  import {
3
- ConcurrencyError,
4
- InvariantError,
5
- NonRetryableError,
6
- StreamClosedError,
7
- ValidationError
8
- } from "@rotorsoft/act";
9
- var ERROR_MAP = {
10
- ValidationError: { status: 422, code: "VALIDATION" },
11
- InvariantError: { status: 409, code: "INVARIANT" },
12
- ConcurrencyError: { status: 412, code: "CONCURRENCY" },
13
- StreamClosedError: { status: 410, code: "STREAM_CLOSED" },
14
- NonRetryableError: { status: 400, code: "NON_RETRYABLE" }
15
- };
16
- var lookup_known = (err) => {
17
- if (err instanceof ValidationError) return { name: "ValidationError" };
18
- if (err instanceof InvariantError) return { name: "InvariantError" };
19
- if (err instanceof ConcurrencyError) return { name: "ConcurrencyError" };
20
- if (err instanceof StreamClosedError) return { name: "StreamClosedError" };
21
- if (err instanceof NonRetryableError) return { name: "NonRetryableError" };
22
- return null;
23
- };
24
- function toApiError(err) {
25
- const known = lookup_known(err);
26
- if (known) {
27
- const entry = ERROR_MAP[known.name];
28
- return {
29
- status: entry.status,
30
- body: {
31
- error: known.name,
32
- detail: err.message,
33
- code: entry.code
34
- }
35
- };
36
- }
37
- if (err instanceof Error) {
38
- return {
39
- status: 500,
40
- body: { error: "InternalError", detail: err.message, code: "INTERNAL" }
41
- };
42
- }
43
- return {
44
- status: 500,
45
- body: { error: "InternalError", code: "INTERNAL" }
46
- };
47
- }
48
-
49
- // src/api/idempotency.ts
50
- async function withIdempotency(store, key, handler) {
51
- const fresh = await store.claim(key);
52
- if (!fresh) {
53
- return { deduped: true };
54
- }
55
- return { deduped: false, result: await handler() };
56
- }
2
+ ERROR_MAP,
3
+ toApiError,
4
+ withIdempotency
5
+ } from "../chunk-Z6FVXDDU.js";
57
6
  export {
58
7
  ERROR_MAP,
59
8
  toApiError,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/errors.ts","../../src/api/idempotency.ts"],"sourcesContent":["import {\n ConcurrencyError,\n InvariantError,\n NonRetryableError,\n StreamClosedError,\n ValidationError,\n} from \"@rotorsoft/act\";\n\n/**\n * Uniform error envelope shipped over the wire by every act-http\n * transport. Hosts get the same shape from REST, tRPC, and OpenAPI —\n * a client that talks to two transports doesn't have to invent two\n * error parsers.\n *\n * - `error` — the framework error name (`\"ValidationError\"`,\n * `\"InvariantError\"`, …). Stable identifier, safe to switch on.\n * - `detail` — the framework's message text. Human-readable; not\n * parsed by clients.\n * - `code` — a machine-readable status code from {@link ERROR_MAP}\n * for clients that prefer enum-style branching over name strings.\n */\nexport type ApiError = {\n error: string;\n detail?: string;\n code?: string;\n};\n\n/**\n * Status + code pair for one known framework error.\n */\nexport type ErrorMapEntry = {\n status: number;\n code: string;\n};\n\n/**\n * The single table that maps framework error types to HTTP status\n * codes and machine-readable codes. One table, three consumers\n * (Hono, tRPC, OpenAPI) — cross-transport consistency by\n * construction.\n *\n * Operators wanting different mappings wrap the generated transport\n * rather than mutating this — the consistency is the load-bearing\n * property, not the specific status codes.\n */\nexport const ERROR_MAP = {\n ValidationError: { status: 422, code: \"VALIDATION\" },\n InvariantError: { status: 409, code: \"INVARIANT\" },\n ConcurrencyError: { status: 412, code: \"CONCURRENCY\" },\n StreamClosedError: { status: 410, code: \"STREAM_CLOSED\" },\n NonRetryableError: { status: 400, code: \"NON_RETRYABLE\" },\n} as const satisfies Record<string, ErrorMapEntry>;\n\nconst lookup_known = (\n err: unknown\n): { name: keyof typeof ERROR_MAP } | null => {\n if (err instanceof ValidationError) return { name: \"ValidationError\" };\n if (err instanceof InvariantError) return { name: \"InvariantError\" };\n if (err instanceof ConcurrencyError) return { name: \"ConcurrencyError\" };\n if (err instanceof StreamClosedError) return { name: \"StreamClosedError\" };\n if (err instanceof NonRetryableError) return { name: \"NonRetryableError\" };\n return null;\n};\n\n/**\n * Translate an unknown thrown value into the canonical\n * {@link ApiError} envelope plus HTTP status. Each transport's error\n * boundary calls this once and forwards the result to the wire.\n *\n * Known framework errors map per {@link ERROR_MAP}. Everything else\n * surfaces as a 500 with `code: \"INTERNAL\"`; the `detail` field is\n * populated when the throw was an `Error` instance, omitted\n * otherwise (a thrown string or object doesn't get to leak its\n * payload to the client).\n */\nexport function toApiError(err: unknown): { status: number; body: ApiError } {\n const known = lookup_known(err);\n if (known) {\n const entry = ERROR_MAP[known.name];\n return {\n status: entry.status,\n body: {\n error: known.name,\n detail: (err as Error).message,\n code: entry.code,\n },\n };\n }\n if (err instanceof Error) {\n return {\n status: 500,\n body: { error: \"InternalError\", detail: err.message, code: \"INTERNAL\" },\n };\n }\n return {\n status: 500,\n body: { error: \"InternalError\", code: \"INTERNAL\" },\n };\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/**\n * Result of a {@link withIdempotency} call.\n *\n * - `{ deduped: false, result }` — the claim was fresh; the handler\n * ran and produced `result`.\n * - `{ deduped: true }` — the claim was already taken; the handler\n * was *not* invoked. The caller decides how to respond (typically\n * a 2xx with no body, matching the receiver-side convention).\n *\n * Note: the contract does not cache the previous response. A\n * duplicate call returns the deduped marker only — replaying the\n * original handler's output would require a response-caching\n * adapter, which is out of scope here. The receiver-side convention\n * (and the convention the generated transports follow) is \"ack the\n * duplicate; do nothing else.\"\n */\nexport type IdempotencyResult<T> =\n | { deduped: false; result: T }\n | { deduped: true };\n\n/**\n * Wrap an action handler so the framework honors `Idempotency-Key`\n * dedup. Acquires the key via {@link IdempotencyStore.claim}, runs\n * the handler exactly when the claim was fresh, and skips the\n * handler entirely on a duplicate.\n *\n * Reuses the contract `@rotorsoft/act-ops/idempotency` already\n * defines for the receiver-side `Idempotency-Key` story. A single\n * `IdempotencyStore` implementation covers both halves of the \"Act\n * over the wire\" surface — receiver and generated API.\n */\nexport async function withIdempotency<T>(\n store: IdempotencyStore,\n key: string,\n handler: () => Promise<T>\n): Promise<IdempotencyResult<T>> {\n const fresh = await store.claim(key);\n if (!fresh) {\n return { deduped: true };\n }\n return { deduped: false, result: await handler() };\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuCA,IAAM,YAAY;AAAA,EACvB,iBAAiB,EAAE,QAAQ,KAAK,MAAM,aAAa;AAAA,EACnD,gBAAgB,EAAE,QAAQ,KAAK,MAAM,YAAY;AAAA,EACjD,kBAAkB,EAAE,QAAQ,KAAK,MAAM,cAAc;AAAA,EACrD,mBAAmB,EAAE,QAAQ,KAAK,MAAM,gBAAgB;AAAA,EACxD,mBAAmB,EAAE,QAAQ,KAAK,MAAM,gBAAgB;AAC1D;AAEA,IAAM,eAAe,CACnB,QAC4C;AAC5C,MAAI,eAAe,gBAAiB,QAAO,EAAE,MAAM,kBAAkB;AACrE,MAAI,eAAe,eAAgB,QAAO,EAAE,MAAM,iBAAiB;AACnE,MAAI,eAAe,iBAAkB,QAAO,EAAE,MAAM,mBAAmB;AACvE,MAAI,eAAe,kBAAmB,QAAO,EAAE,MAAM,oBAAoB;AACzE,MAAI,eAAe,kBAAmB,QAAO,EAAE,MAAM,oBAAoB;AACzE,SAAO;AACT;AAaO,SAAS,WAAW,KAAkD;AAC3E,QAAM,QAAQ,aAAa,GAAG;AAC9B,MAAI,OAAO;AACT,UAAM,QAAQ,UAAU,MAAM,IAAI;AAClC,WAAO;AAAA,MACL,QAAQ,MAAM;AAAA,MACd,MAAM;AAAA,QACJ,OAAO,MAAM;AAAA,QACb,QAAS,IAAc;AAAA,QACvB,MAAM,MAAM;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACA,MAAI,eAAe,OAAO;AACxB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,MAAM,EAAE,OAAO,iBAAiB,QAAQ,IAAI,SAAS,MAAM,WAAW;AAAA,IACxE;AAAA,EACF;AACA,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,MAAM,EAAE,OAAO,iBAAiB,MAAM,WAAW;AAAA,EACnD;AACF;;;ACjEA,eAAsB,gBACpB,OACA,KACA,SAC+B;AAC/B,QAAM,QAAQ,MAAM,MAAM,MAAM,GAAG;AACnC,MAAI,CAAC,OAAO;AACV,WAAO,EAAE,SAAS,KAAK;AAAA,EACzB;AACA,SAAO,EAAE,SAAS,OAAO,QAAQ,MAAM,QAAQ,EAAE;AACnD;","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,63 @@
1
+ // src/api/errors.ts
2
+ import {
3
+ ConcurrencyError,
4
+ InvariantError,
5
+ NonRetryableError,
6
+ StreamClosedError,
7
+ ValidationError
8
+ } from "@rotorsoft/act";
9
+ var ERROR_MAP = {
10
+ ValidationError: { status: 422, code: "VALIDATION" },
11
+ InvariantError: { status: 409, code: "INVARIANT" },
12
+ ConcurrencyError: { status: 412, code: "CONCURRENCY" },
13
+ StreamClosedError: { status: 410, code: "STREAM_CLOSED" },
14
+ NonRetryableError: { status: 400, code: "NON_RETRYABLE" }
15
+ };
16
+ var lookup_known = (err) => {
17
+ if (err instanceof ValidationError) return { name: "ValidationError" };
18
+ if (err instanceof InvariantError) return { name: "InvariantError" };
19
+ if (err instanceof ConcurrencyError) return { name: "ConcurrencyError" };
20
+ if (err instanceof StreamClosedError) return { name: "StreamClosedError" };
21
+ if (err instanceof NonRetryableError) return { name: "NonRetryableError" };
22
+ return null;
23
+ };
24
+ function toApiError(err) {
25
+ const known = lookup_known(err);
26
+ if (known) {
27
+ const entry = ERROR_MAP[known.name];
28
+ return {
29
+ status: entry.status,
30
+ body: {
31
+ error: known.name,
32
+ detail: err.message,
33
+ code: entry.code
34
+ }
35
+ };
36
+ }
37
+ if (err instanceof Error) {
38
+ return {
39
+ status: 500,
40
+ body: { error: "InternalError", detail: err.message, code: "INTERNAL" }
41
+ };
42
+ }
43
+ return {
44
+ status: 500,
45
+ body: { error: "InternalError", code: "INTERNAL" }
46
+ };
47
+ }
48
+
49
+ // src/api/idempotency.ts
50
+ async function withIdempotency(store, key, handler) {
51
+ const fresh = await store.claim(key);
52
+ if (!fresh) {
53
+ return { deduped: true };
54
+ }
55
+ return { deduped: false, result: await handler() };
56
+ }
57
+
58
+ export {
59
+ ERROR_MAP,
60
+ toApiError,
61
+ withIdempotency
62
+ };
63
+ //# sourceMappingURL=chunk-Z6FVXDDU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/api/errors.ts","../src/api/idempotency.ts"],"sourcesContent":["import {\n ConcurrencyError,\n InvariantError,\n NonRetryableError,\n StreamClosedError,\n ValidationError,\n} from \"@rotorsoft/act\";\n\n/**\n * Uniform error envelope shipped over the wire by every act-http\n * transport. Hosts get the same shape from REST, tRPC, and OpenAPI —\n * a client that talks to two transports doesn't have to invent two\n * error parsers.\n *\n * - `error` — the framework error name (`\"ValidationError\"`,\n * `\"InvariantError\"`, …). Stable identifier, safe to switch on.\n * - `detail` — the framework's message text. Human-readable; not\n * parsed by clients.\n * - `code` — a machine-readable status code from {@link ERROR_MAP}\n * for clients that prefer enum-style branching over name strings.\n */\nexport type ApiError = {\n error: string;\n detail?: string;\n code?: string;\n};\n\n/**\n * Status + code pair for one known framework error.\n */\nexport type ErrorMapEntry = {\n status: number;\n code: string;\n};\n\n/**\n * The single table that maps framework error types to HTTP status\n * codes and machine-readable codes. One table, three consumers\n * (Hono, tRPC, OpenAPI) — cross-transport consistency by\n * construction.\n *\n * Operators wanting different mappings wrap the generated transport\n * rather than mutating this — the consistency is the load-bearing\n * property, not the specific status codes.\n */\nexport const ERROR_MAP = {\n ValidationError: { status: 422, code: \"VALIDATION\" },\n InvariantError: { status: 409, code: \"INVARIANT\" },\n ConcurrencyError: { status: 412, code: \"CONCURRENCY\" },\n StreamClosedError: { status: 410, code: \"STREAM_CLOSED\" },\n NonRetryableError: { status: 400, code: \"NON_RETRYABLE\" },\n} as const satisfies Record<string, ErrorMapEntry>;\n\nconst lookup_known = (\n err: unknown\n): { name: keyof typeof ERROR_MAP } | null => {\n if (err instanceof ValidationError) return { name: \"ValidationError\" };\n if (err instanceof InvariantError) return { name: \"InvariantError\" };\n if (err instanceof ConcurrencyError) return { name: \"ConcurrencyError\" };\n if (err instanceof StreamClosedError) return { name: \"StreamClosedError\" };\n if (err instanceof NonRetryableError) return { name: \"NonRetryableError\" };\n return null;\n};\n\n/**\n * Translate an unknown thrown value into the canonical\n * {@link ApiError} envelope plus HTTP status. Each transport's error\n * boundary calls this once and forwards the result to the wire.\n *\n * Known framework errors map per {@link ERROR_MAP}. Everything else\n * surfaces as a 500 with `code: \"INTERNAL\"`; the `detail` field is\n * populated when the throw was an `Error` instance, omitted\n * otherwise (a thrown string or object doesn't get to leak its\n * payload to the client).\n */\nexport function toApiError(err: unknown): { status: number; body: ApiError } {\n const known = lookup_known(err);\n if (known) {\n const entry = ERROR_MAP[known.name];\n return {\n status: entry.status,\n body: {\n error: known.name,\n detail: (err as Error).message,\n code: entry.code,\n },\n };\n }\n if (err instanceof Error) {\n return {\n status: 500,\n body: { error: \"InternalError\", detail: err.message, code: \"INTERNAL\" },\n };\n }\n return {\n status: 500,\n body: { error: \"InternalError\", code: \"INTERNAL\" },\n };\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/**\n * Result of a {@link withIdempotency} call.\n *\n * - `{ deduped: false, result }` — the claim was fresh; the handler\n * ran and produced `result`.\n * - `{ deduped: true }` — the claim was already taken; the handler\n * was *not* invoked. The caller decides how to respond (typically\n * a 2xx with no body, matching the receiver-side convention).\n *\n * Note: the contract does not cache the previous response. A\n * duplicate call returns the deduped marker only — replaying the\n * original handler's output would require a response-caching\n * adapter, which is out of scope here. The receiver-side convention\n * (and the convention the generated transports follow) is \"ack the\n * duplicate; do nothing else.\"\n */\nexport type IdempotencyResult<T> =\n | { deduped: false; result: T }\n | { deduped: true };\n\n/**\n * Wrap an action handler so the framework honors `Idempotency-Key`\n * dedup. Acquires the key via {@link IdempotencyStore.claim}, runs\n * the handler exactly when the claim was fresh, and skips the\n * handler entirely on a duplicate.\n *\n * Reuses the contract `@rotorsoft/act-ops/idempotency` already\n * defines for the receiver-side `Idempotency-Key` story. A single\n * `IdempotencyStore` implementation covers both halves of the \"Act\n * over the wire\" surface — receiver and generated API.\n */\nexport async function withIdempotency<T>(\n store: IdempotencyStore,\n key: string,\n handler: () => Promise<T>\n): Promise<IdempotencyResult<T>> {\n const fresh = await store.claim(key);\n if (!fresh) {\n return { deduped: true };\n }\n return { deduped: false, result: await handler() };\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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O;AACV,WAAO,EAAE,SAAS,KAAK;AAAA,EACzB;AACA,SAAO,EAAE,SAAS,OAAO,QAAQ,MAAM,QAAQ,EAAE;AACnD;","names":[]}
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/trpc/index.ts
21
+ var trpc_exports = {};
22
+ __export(trpc_exports, {
23
+ authenticated: () => authenticated,
24
+ trpc: () => trpc
25
+ });
26
+ module.exports = __toCommonJS(trpc_exports);
27
+ var import_server = require("@trpc/server");
28
+
29
+ // src/api/errors.ts
30
+ var import_act = require("@rotorsoft/act");
31
+ var ERROR_MAP = {
32
+ ValidationError: { status: 422, code: "VALIDATION" },
33
+ InvariantError: { status: 409, code: "INVARIANT" },
34
+ ConcurrencyError: { status: 412, code: "CONCURRENCY" },
35
+ StreamClosedError: { status: 410, code: "STREAM_CLOSED" },
36
+ NonRetryableError: { status: 400, code: "NON_RETRYABLE" }
37
+ };
38
+ var lookup_known = (err) => {
39
+ if (err instanceof import_act.ValidationError) return { name: "ValidationError" };
40
+ if (err instanceof import_act.InvariantError) return { name: "InvariantError" };
41
+ if (err instanceof import_act.ConcurrencyError) return { name: "ConcurrencyError" };
42
+ if (err instanceof import_act.StreamClosedError) return { name: "StreamClosedError" };
43
+ if (err instanceof import_act.NonRetryableError) return { name: "NonRetryableError" };
44
+ return null;
45
+ };
46
+ function toApiError(err) {
47
+ const known = lookup_known(err);
48
+ if (known) {
49
+ const entry = ERROR_MAP[known.name];
50
+ return {
51
+ status: entry.status,
52
+ body: {
53
+ error: known.name,
54
+ detail: err.message,
55
+ code: entry.code
56
+ }
57
+ };
58
+ }
59
+ if (err instanceof Error) {
60
+ return {
61
+ status: 500,
62
+ body: { error: "InternalError", detail: err.message, code: "INTERNAL" }
63
+ };
64
+ }
65
+ return {
66
+ status: 500,
67
+ body: { error: "InternalError", code: "INTERNAL" }
68
+ };
69
+ }
70
+
71
+ // src/api/idempotency.ts
72
+ async function withIdempotency(store, key, handler) {
73
+ const fresh = await store.claim(key);
74
+ if (!fresh) {
75
+ return { deduped: true };
76
+ }
77
+ return { deduped: false, result: await handler() };
78
+ }
79
+
80
+ // src/trpc/index.ts
81
+ function authenticated(extractor) {
82
+ return async function actor_middleware({
83
+ ctx,
84
+ next
85
+ }) {
86
+ const actor = await extractor(ctx);
87
+ return next({ ctx: { ...ctx, actor } });
88
+ };
89
+ }
90
+ function to_trpc_error(err) {
91
+ const { status, body } = toApiError(err);
92
+ const code = status_to_trpc_code(status);
93
+ return new import_server.TRPCError({
94
+ code,
95
+ message: body.detail ?? body.error,
96
+ cause: err instanceof Error ? err : void 0
97
+ });
98
+ }
99
+ function status_to_trpc_code(status) {
100
+ switch (status) {
101
+ case 400:
102
+ return "BAD_REQUEST";
103
+ case 409:
104
+ return "CONFLICT";
105
+ case 410:
106
+ return "PRECONDITION_FAILED";
107
+ case 412:
108
+ return "CONFLICT";
109
+ case 422:
110
+ return "UNPROCESSABLE_CONTENT";
111
+ default:
112
+ return "INTERNAL_SERVER_ERROR";
113
+ }
114
+ }
115
+ function trpc(app, options) {
116
+ const t = import_server.initTRPC.context().create();
117
+ const authed = t.procedure.use(authenticated(options.actor));
118
+ const handlers = {};
119
+ for (const [action_name, state] of Object.entries(app.registry.actions)) {
120
+ handlers[action_name] = authed.input(state.actions[action_name]).mutation(async ({ input, ctx }) => {
121
+ const host_ctx = ctx;
122
+ try {
123
+ const stream = await options.stream(action_name, input, host_ctx);
124
+ const expected_version = options.expectedVersion ? await options.expectedVersion(action_name, input, host_ctx) : void 0;
125
+ const target = expected_version === void 0 ? { stream, actor: host_ctx.actor } : {
126
+ stream,
127
+ actor: host_ctx.actor,
128
+ expectedVersion: expected_version
129
+ };
130
+ if (options.idempotency) {
131
+ const key = options.idempotency.keyFrom(host_ctx);
132
+ if (!key) {
133
+ throw new import_server.TRPCError({
134
+ code: "BAD_REQUEST",
135
+ message: "Idempotency-Key required"
136
+ });
137
+ }
138
+ const outcome = await withIdempotency(
139
+ options.idempotency.store,
140
+ key,
141
+ () => app.do(action_name, target, input)
142
+ );
143
+ if (outcome.deduped) {
144
+ throw new import_server.TRPCError({
145
+ code: "CONFLICT",
146
+ message: "Idempotency-Key already used; original result not cached"
147
+ });
148
+ }
149
+ return outcome.result;
150
+ }
151
+ return await app.do(
152
+ action_name,
153
+ target,
154
+ input
155
+ );
156
+ } catch (err) {
157
+ if (err instanceof import_server.TRPCError) throw err;
158
+ throw to_trpc_error(err);
159
+ }
160
+ });
161
+ }
162
+ return t.router(handlers);
163
+ }
164
+ // Annotate the CommonJS export names for ESM import in node:
165
+ 0 && (module.exports = {
166
+ authenticated,
167
+ trpc
168
+ });
169
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/trpc/index.ts","../../src/api/errors.ts","../../src/api/idempotency.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/trpc\n *\n * tRPC subpath for the auto-generated API epic (#835). Walks the\n * registry of a built `Act` once at function call and emits a typed\n * router that exposes every registered action as a flat `mutation`,\n * matching the shape hand-written tRPC routers in the Act ecosystem\n * already use.\n *\n * Usage:\n *\n * ```ts\n * import { trpc } from \"@rotorsoft/act-http/trpc\";\n *\n * const router = trpc(app, {\n * actor: (ctx) => ({ id: ctx.user.id, name: ctx.user.name }),\n * stream: (action, input, ctx) => input.stream ?? ctx.tenant,\n * });\n *\n * // Client sees:\n * // appRouter.PressKey.mutate({ key: \"5\" })\n * // appRouter.OpenTicket.mutate({ title: \"...\" })\n * ```\n *\n * The route shape is flat: one procedure per registered action at\n * the top level. Action names are the unique identifiers across\n * the registry (the framework already enforces no duplicates), so\n * an extra namespace tier would be overhead in the common case.\n * Pure mutations for this slice; query/projection wiring lives in\n * a follow-up. See `libs/act-http/README.md` for the full surface\n * walkthrough.\n *\n * **Actor lives on the context.** The generator wires an internal\n * tRPC middleware that runs the host's\n * {@link TrpcOptions.actor | actor extractor} once per call and\n * injects the resolved {@link Actor} onto the downstream context as\n * `ctx.actor`. Every generated mutation reads from there — auth\n * resolves at the procedure boundary, not inside each action body,\n * and any composed middleware (logging, tracing) sees the same\n * `ctx.actor`. The middleware factory is also exported as\n * {@link authenticated} for hosts that need to compose it into\n * their own procedure chain.\n *\n * Composes the shared utilities at `@rotorsoft/act-http/api`:\n * {@link ActorExtractor} for the auth seam, {@link toApiError} for\n * the uniform error→status/code mapping, {@link withIdempotency}\n * for `Idempotency-Key` dedup. Three transports (this one, Hono,\n * OpenAPI) ride the same utilities so a client talking to two\n * transports never sees two error shapes for the same framework\n * error.\n */\nimport type { Act, Actor, Schema, Schemas } from \"@rotorsoft/act\";\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport { initTRPC, TRPCError } from \"@trpc/server\";\nimport {\n type ActorExtractor,\n toApiError,\n withIdempotency,\n} from \"../api/index.js\";\n\n/**\n * Per-call options for {@link trpc}. The host supplies the three\n * seams the package can't make decisions on:\n *\n * - `actor` — auth resolver. Receives the tRPC context, returns the\n * `Actor` that flows onto `ctx.actor` for every generated\n * procedure (via an internal {@link authenticated}).\n * - `stream` — stream-id resolver. Receives the action name, the\n * validated action input, and the original tRPC context; returns\n * the target stream. Singleton aggregates return a constant;\n * per-tenant aggregates pull from input or context.\n * - `expectedVersion` (optional) — optimistic-concurrency resolver.\n * When set, the procedure threads the resolved value through\n * `target.expectedVersion` so `app.do` refuses to commit if the\n * stream has moved. Hosts typically read it from an `If-Match`\n * header on the underlying HTTP request, or pull it from the\n * client's last-known snapshot. Returning `undefined` skips the\n * check for that call — handy when only some actions are\n * concurrency-sensitive.\n * - `idempotency` (optional) — when set, the procedure honors\n * `Idempotency-Key` via the shared\n * {@link withIdempotency} helper. The host supplies the\n * `IdempotencyStore` and a `keyFrom` extractor that reads the key\n * out of the tRPC context (typically a header). On a duplicate\n * claim, the procedure throws a `CONFLICT` `TRPCError` — the\n * receiver-side convention of \"ack the duplicate\" doesn't carry\n * over because the contract intentionally does not cache the\n * original handler's result.\n *\n * @template Ctx The host's tRPC context shape. Flows end-to-end —\n * procedures see this exact context type (plus `actor`) at\n * runtime.\n */\nexport type TrpcOptions<Ctx> = {\n readonly actor: ActorExtractor;\n readonly stream: (\n action_name: string,\n input: unknown,\n ctx: Ctx\n ) => string | Promise<string>;\n readonly expectedVersion?: (\n action_name: string,\n input: unknown,\n ctx: Ctx\n ) => number | undefined | Promise<number | undefined>;\n readonly idempotency?: {\n readonly store: IdempotencyStore;\n readonly keyFrom: (ctx: Ctx) => string | undefined;\n };\n};\n\n/**\n * Build a tRPC middleware that runs an {@link ActorExtractor} once\n * per call and forwards the resolved {@link Actor} on the\n * downstream context as `ctx.actor`. The generator at\n * {@link trpc} uses this internally; it's also exported so hosts\n * that want to compose their own procedure chain (logging,\n * tracing, custom auth flavors) can wire it directly:\n *\n * ```ts\n * import { initTRPC } from \"@trpc/server\";\n * import { authenticated } from \"@rotorsoft/act-http/trpc\";\n *\n * type Ctx = { user?: { id: string; name: string } };\n * const t = initTRPC.context<Ctx>().create();\n *\n * const authed = t.procedure.use(\n * authenticated((ctx) => {\n * if (!ctx.user) throw new Error(\"not authenticated\");\n * return { id: ctx.user.id, name: ctx.user.name };\n * })\n * );\n *\n * // Inside any procedure built off `authed`, `ctx.actor: Actor`.\n * ```\n *\n * The middleware is unaware of the host's `t` instance — it returns\n * a structurally-typed function that any tRPC `procedure.use(...)`\n * accepts. Errors thrown by the extractor surface unchanged\n * (typically wrap them as `TRPCError({ code: \"UNAUTHORIZED\" })`\n * in the extractor body).\n */\n// biome-ignore lint/suspicious/noExplicitAny: tRPC's internal middleware shape lives behind `unstable-core-do-not-import`; structural typing carries the host's `t` validation.\nexport function authenticated(extractor: ActorExtractor): any {\n return async function actor_middleware({\n ctx,\n next,\n }: {\n ctx: object;\n next: (opts: { ctx: object }) => Promise<unknown>;\n }) {\n const actor = await extractor(ctx);\n return next({ ctx: { ...ctx, actor } });\n };\n}\n\n/**\n * Map a thrown framework error onto a `TRPCError`. Known errors get\n * their conventional tRPC code (`ConcurrencyError` → `CONFLICT`,\n * `ValidationError` → `UNPROCESSABLE_CONTENT`, etc.); unknown throws\n * surface as `INTERNAL_SERVER_ERROR`. Every transport in the\n * act-http epic passes through the same {@link toApiError} table,\n * so a client talking to both this subpath and the REST sibling\n * sees one envelope per framework error.\n *\n * @internal\n */\nfunction to_trpc_error(err: unknown): TRPCError {\n const { status, body } = toApiError(err);\n const code = status_to_trpc_code(status);\n return new TRPCError({\n code,\n message: body.detail ?? body.error,\n cause: err instanceof Error ? err : undefined,\n });\n}\n\n/**\n * Minimal status → tRPC code map. Only the statuses\n * {@link ERROR_MAP} produces (plus 500) appear here; anything else\n * collapses to `INTERNAL_SERVER_ERROR`.\n *\n * @internal\n */\nfunction status_to_trpc_code(status: number): TRPCError[\"code\"] {\n switch (status) {\n case 400:\n return \"BAD_REQUEST\";\n case 409:\n return \"CONFLICT\";\n case 410:\n return \"PRECONDITION_FAILED\";\n case 412:\n return \"CONFLICT\";\n case 422:\n return \"UNPROCESSABLE_CONTENT\";\n default:\n return \"INTERNAL_SERVER_ERROR\";\n }\n}\n\n/**\n * Build a typed tRPC router from a built `Act` instance.\n *\n * Walks `app.registry.actions` once and emits one flat mutation per\n * action under `router.<actionName>`. The framework already enforces\n * no duplicate action names across states, so a flat tier reads\n * cleanly at the client and matches the hand-written router shape\n * adopters already have. Each mutation:\n *\n * 1. Runs the internal {@link authenticated} — `options.actor`\n * resolves the {@link Actor} once and injects it onto\n * `ctx.actor`.\n * 2. Resolves the target stream via `options.stream(name, input, ctx)`.\n * 3. (Optionally) claims the `Idempotency-Key` via\n * {@link withIdempotency} — throws `CONFLICT` on duplicate.\n * 4. Calls `app.do(name, { stream, actor: ctx.actor }, input)`.\n * 5. Maps any thrown framework error onto a `TRPCError` via\n * {@link toApiError}.\n *\n * The returned router's procedure inputs come straight from each\n * action's Zod schema; outputs are the framework's\n * `Snapshot<TState, TEvents>[]` shape. Strong typing flows\n * end-to-end via tRPC's normal inference path — the client sees\n * `appRouter.Calculator.PressKey.mutate({ key: \"5\" })` as a typed\n * call without any codegen.\n *\n * @template Ctx The tRPC context shape the host's runtime feeds in.\n * Flows through `actor`, `stream`, and `idempotency.keyFrom` so\n * the operator's existing context types just work. The internal\n * middleware augments `Ctx` with `{ actor: Actor }` on the\n * downstream procedure context.\n *\n * @param app A built `Act` orchestrator.\n * @param options Auth, stream, and (optional) idempotency seams.\n * @returns A tRPC router covering every registered action, grouped\n * by owning state.\n */\nexport function trpc<Ctx extends object = object>(\n // biome-ignore lint/suspicious/noExplicitAny: erased — the generator walks the registry at runtime, not the typed surface\n app: Act<any, Schemas, Schemas, Record<string, Schema>>,\n options: TrpcOptions<Ctx>\n) {\n const t = initTRPC.context<Ctx>().create();\n const authed = t.procedure.use(authenticated(options.actor));\n\n const handlers: Record<string, ReturnType<typeof authed.mutation>> = {};\n for (const [action_name, state] of Object.entries(app.registry.actions)) {\n handlers[action_name] = authed\n .input(state.actions[action_name] as never)\n .mutation(async ({ input, ctx }) => {\n // tRPC's internal `Simplify<Ctx>` transform produces a type\n // that's structurally identical to `Ctx & { actor }` but not\n // assignable to the generic parameter. The cast restores the\n // link; the runtime ctx IS the augmented context.\n const host_ctx = ctx as unknown as Ctx & { actor: Actor };\n try {\n const stream = await options.stream(action_name, input, host_ctx);\n const expected_version = options.expectedVersion\n ? await options.expectedVersion(action_name, input, host_ctx)\n : undefined;\n const target =\n expected_version === undefined\n ? { stream, actor: host_ctx.actor }\n : {\n stream,\n actor: host_ctx.actor,\n expectedVersion: expected_version,\n };\n\n if (options.idempotency) {\n const key = options.idempotency.keyFrom(host_ctx);\n if (!key) {\n throw new TRPCError({\n code: \"BAD_REQUEST\",\n message: \"Idempotency-Key required\",\n });\n }\n const outcome = await withIdempotency(\n options.idempotency.store,\n key,\n () =>\n app.do(action_name as never, target as never, input as never)\n );\n if (outcome.deduped) {\n throw new TRPCError({\n code: \"CONFLICT\",\n message:\n \"Idempotency-Key already used; original result not cached\",\n });\n }\n return outcome.result;\n }\n\n return await app.do(\n action_name as never,\n target as never,\n input as never\n );\n } catch (err) {\n if (err instanceof TRPCError) throw err;\n throw to_trpc_error(err);\n }\n });\n }\n\n return t.router(handlers as never);\n}\n","import {\n ConcurrencyError,\n InvariantError,\n NonRetryableError,\n StreamClosedError,\n ValidationError,\n} from \"@rotorsoft/act\";\n\n/**\n * Uniform error envelope shipped over the wire by every act-http\n * transport. Hosts get the same shape from REST, tRPC, and OpenAPI —\n * a client that talks to two transports doesn't have to invent two\n * error parsers.\n *\n * - `error` — the framework error name (`\"ValidationError\"`,\n * `\"InvariantError\"`, …). Stable identifier, safe to switch on.\n * - `detail` — the framework's message text. Human-readable; not\n * parsed by clients.\n * - `code` — a machine-readable status code from {@link ERROR_MAP}\n * for clients that prefer enum-style branching over name strings.\n */\nexport type ApiError = {\n error: string;\n detail?: string;\n code?: string;\n};\n\n/**\n * Status + code pair for one known framework error.\n */\nexport type ErrorMapEntry = {\n status: number;\n code: string;\n};\n\n/**\n * The single table that maps framework error types to HTTP status\n * codes and machine-readable codes. One table, three consumers\n * (Hono, tRPC, OpenAPI) — cross-transport consistency by\n * construction.\n *\n * Operators wanting different mappings wrap the generated transport\n * rather than mutating this — the consistency is the load-bearing\n * property, not the specific status codes.\n */\nexport const ERROR_MAP = {\n ValidationError: { status: 422, code: \"VALIDATION\" },\n InvariantError: { status: 409, code: \"INVARIANT\" },\n ConcurrencyError: { status: 412, code: \"CONCURRENCY\" },\n StreamClosedError: { status: 410, code: \"STREAM_CLOSED\" },\n NonRetryableError: { status: 400, code: \"NON_RETRYABLE\" },\n} as const satisfies Record<string, ErrorMapEntry>;\n\nconst lookup_known = (\n err: unknown\n): { name: keyof typeof ERROR_MAP } | null => {\n if (err instanceof ValidationError) return { name: \"ValidationError\" };\n if (err instanceof InvariantError) return { name: \"InvariantError\" };\n if (err instanceof ConcurrencyError) return { name: \"ConcurrencyError\" };\n if (err instanceof StreamClosedError) return { name: \"StreamClosedError\" };\n if (err instanceof NonRetryableError) return { name: \"NonRetryableError\" };\n return null;\n};\n\n/**\n * Translate an unknown thrown value into the canonical\n * {@link ApiError} envelope plus HTTP status. Each transport's error\n * boundary calls this once and forwards the result to the wire.\n *\n * Known framework errors map per {@link ERROR_MAP}. Everything else\n * surfaces as a 500 with `code: \"INTERNAL\"`; the `detail` field is\n * populated when the throw was an `Error` instance, omitted\n * otherwise (a thrown string or object doesn't get to leak its\n * payload to the client).\n */\nexport function toApiError(err: unknown): { status: number; body: ApiError } {\n const known = lookup_known(err);\n if (known) {\n const entry = ERROR_MAP[known.name];\n return {\n status: entry.status,\n body: {\n error: known.name,\n detail: (err as Error).message,\n code: entry.code,\n },\n };\n }\n if (err instanceof Error) {\n return {\n status: 500,\n body: { error: \"InternalError\", detail: err.message, code: \"INTERNAL\" },\n };\n }\n return {\n status: 500,\n body: { error: \"InternalError\", code: \"INTERNAL\" },\n };\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/**\n * Result of a {@link withIdempotency} call.\n *\n * - `{ deduped: false, result }` — the claim was fresh; the handler\n * ran and produced `result`.\n * - `{ deduped: true }` — the claim was already taken; the handler\n * was *not* invoked. The caller decides how to respond (typically\n * a 2xx with no body, matching the receiver-side convention).\n *\n * Note: the contract does not cache the previous response. A\n * duplicate call returns the deduped marker only — replaying the\n * original handler's output would require a response-caching\n * adapter, which is out of scope here. The receiver-side convention\n * (and the convention the generated transports follow) is \"ack the\n * duplicate; do nothing else.\"\n */\nexport type IdempotencyResult<T> =\n | { deduped: false; result: T }\n | { deduped: true };\n\n/**\n * Wrap an action handler so the framework honors `Idempotency-Key`\n * dedup. Acquires the key via {@link IdempotencyStore.claim}, runs\n * the handler exactly when the claim was fresh, and skips the\n * handler entirely on a duplicate.\n *\n * Reuses the contract `@rotorsoft/act-ops/idempotency` already\n * defines for the receiver-side `Idempotency-Key` story. A single\n * `IdempotencyStore` implementation covers both halves of the \"Act\n * over the wire\" surface — receiver and generated API.\n */\nexport async function withIdempotency<T>(\n store: IdempotencyStore,\n key: string,\n handler: () => Promise<T>\n): Promise<IdempotencyResult<T>> {\n const fresh = await store.claim(key);\n if (!fresh) {\n return { deduped: true };\n }\n return { deduped: false, result: await handler() };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsDA,oBAAoC;;;ACtDpC,iBAMO;AAuCA,IAAM,YAAY;AAAA,EACvB,iBAAiB,EAAE,QAAQ,KAAK,MAAM,aAAa;AAAA,EACnD,gBAAgB,EAAE,QAAQ,KAAK,MAAM,YAAY;AAAA,EACjD,kBAAkB,EAAE,QAAQ,KAAK,MAAM,cAAc;AAAA,EACrD,mBAAmB,EAAE,QAAQ,KAAK,MAAM,gBAAgB;AAAA,EACxD,mBAAmB,EAAE,QAAQ,KAAK,MAAM,gBAAgB;AAC1D;AAEA,IAAM,eAAe,CACnB,QAC4C;AAC5C,MAAI,eAAe,2BAAiB,QAAO,EAAE,MAAM,kBAAkB;AACrE,MAAI,eAAe,0BAAgB,QAAO,EAAE,MAAM,iBAAiB;AACnE,MAAI,eAAe,4BAAkB,QAAO,EAAE,MAAM,mBAAmB;AACvE,MAAI,eAAe,6BAAmB,QAAO,EAAE,MAAM,oBAAoB;AACz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U;AAAA,cAClB,MAAM;AAAA,cACN,SACE;AAAA,YACJ,CAAC;AAAA,UACH;AACA,iBAAO,QAAQ;AAAA,QACjB;AAEA,eAAO,MAAM,IAAI;AAAA,UACf;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF,SAAS,KAAK;AACZ,YAAI,eAAe,wBAAW,OAAM;AACpC,cAAM,cAAc,GAAG;AAAA,MACzB;AAAA,IACF,CAAC;AAAA,EACL;AAEA,SAAO,EAAE,OAAO,QAAiB;AACnC;","names":[]}
@@ -0,0 +1,95 @@
1
+ import {
2
+ toApiError,
3
+ withIdempotency
4
+ } from "../chunk-Z6FVXDDU.js";
5
+
6
+ // src/trpc/index.ts
7
+ import { initTRPC, TRPCError } from "@trpc/server";
8
+ function authenticated(extractor) {
9
+ return async function actor_middleware({
10
+ ctx,
11
+ next
12
+ }) {
13
+ const actor = await extractor(ctx);
14
+ return next({ ctx: { ...ctx, actor } });
15
+ };
16
+ }
17
+ function to_trpc_error(err) {
18
+ const { status, body } = toApiError(err);
19
+ const code = status_to_trpc_code(status);
20
+ return new TRPCError({
21
+ code,
22
+ message: body.detail ?? body.error,
23
+ cause: err instanceof Error ? err : void 0
24
+ });
25
+ }
26
+ function status_to_trpc_code(status) {
27
+ switch (status) {
28
+ case 400:
29
+ return "BAD_REQUEST";
30
+ case 409:
31
+ return "CONFLICT";
32
+ case 410:
33
+ return "PRECONDITION_FAILED";
34
+ case 412:
35
+ return "CONFLICT";
36
+ case 422:
37
+ return "UNPROCESSABLE_CONTENT";
38
+ default:
39
+ return "INTERNAL_SERVER_ERROR";
40
+ }
41
+ }
42
+ function trpc(app, options) {
43
+ const t = initTRPC.context().create();
44
+ const authed = t.procedure.use(authenticated(options.actor));
45
+ const handlers = {};
46
+ for (const [action_name, state] of Object.entries(app.registry.actions)) {
47
+ handlers[action_name] = authed.input(state.actions[action_name]).mutation(async ({ input, ctx }) => {
48
+ const host_ctx = ctx;
49
+ try {
50
+ const stream = await options.stream(action_name, input, host_ctx);
51
+ const expected_version = options.expectedVersion ? await options.expectedVersion(action_name, input, host_ctx) : void 0;
52
+ const target = expected_version === void 0 ? { stream, actor: host_ctx.actor } : {
53
+ stream,
54
+ actor: host_ctx.actor,
55
+ expectedVersion: expected_version
56
+ };
57
+ if (options.idempotency) {
58
+ const key = options.idempotency.keyFrom(host_ctx);
59
+ if (!key) {
60
+ throw new TRPCError({
61
+ code: "BAD_REQUEST",
62
+ message: "Idempotency-Key required"
63
+ });
64
+ }
65
+ const outcome = await withIdempotency(
66
+ options.idempotency.store,
67
+ key,
68
+ () => app.do(action_name, target, input)
69
+ );
70
+ if (outcome.deduped) {
71
+ throw new TRPCError({
72
+ code: "CONFLICT",
73
+ message: "Idempotency-Key already used; original result not cached"
74
+ });
75
+ }
76
+ return outcome.result;
77
+ }
78
+ return await app.do(
79
+ action_name,
80
+ target,
81
+ input
82
+ );
83
+ } catch (err) {
84
+ if (err instanceof TRPCError) throw err;
85
+ throw to_trpc_error(err);
86
+ }
87
+ });
88
+ }
89
+ return t.router(handlers);
90
+ }
91
+ export {
92
+ authenticated,
93
+ trpc
94
+ };
95
+ //# sourceMappingURL=index.js.map