@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 @@
1
+ {"version":3,"sources":["../../src/trpc/index.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"],"mappings":";;;;;;AAsDA,SAAS,UAAU,iBAAiB;AA0F7B,SAAS,cAAc,WAAgC;AAC5D,SAAO,eAAe,iBAAiB;AAAA,IACrC;AAAA,IACA;AAAA,EACF,GAGG;AACD,UAAM,QAAQ,MAAM,UAAU,GAAG;AACjC,WAAO,KAAK,EAAE,KAAK,EAAE,GAAG,KAAK,MAAM,EAAE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BAAM,IAAI,UAAU;AAAA,cAClB,MAAM;AAAA,cACN,SAAS;AAAA,YACX,CAAC;AAAA,UACH;AACA,gBAAM,UAAU,MAAM;AAAA,YACpB,QAAQ,YAAY;AAAA,YACpB;AAAA,YACA,MACE,IAAI,GAAG,aAAsB,QAAiB,KAAc;AAAA,UAChE;AACA,cAAI,QAAQ,SAAS;AACnB,kBAAM,IAAI,UAAU;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,UAAW,OAAM;AACpC,cAAM,cAAc,GAAG;AAAA,MACzB;AAAA,IACF,CAAC;AAAA,EACL;AAEA,SAAO,EAAE,OAAO,QAAiB;AACnC;","names":[]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rotorsoft/act-http",
3
3
  "type": "module",
4
- "version": "1.2.1",
4
+ "version": "1.3.0",
5
5
  "description": "HTTP integrations for act apps — webhooks and SSE",
6
6
  "keywords": [
7
7
  "typescript",
@@ -26,26 +26,16 @@
26
26
  "dist"
27
27
  ],
28
28
  "exports": {
29
- "./webhook": {
30
- "types": "./dist/@types/webhook/index.d.ts",
31
- "import": "./dist/webhook/index.js",
32
- "require": "./dist/webhook/index.cjs"
33
- },
34
- "./sse": {
35
- "types": "./dist/@types/sse/index.d.ts",
36
- "import": "./dist/sse/index.js",
37
- "require": "./dist/sse/index.cjs"
29
+ "./api": {
30
+ "types": "./dist/@types/api/index.d.ts",
31
+ "import": "./dist/api/index.js",
32
+ "require": "./dist/api/index.cjs"
38
33
  },
39
34
  "./receiver": {
40
35
  "types": "./dist/@types/receiver/index.d.ts",
41
36
  "import": "./dist/receiver/index.js",
42
37
  "require": "./dist/receiver/index.cjs"
43
38
  },
44
- "./receiver/trpc": {
45
- "types": "./dist/@types/receiver/trpc/index.d.ts",
46
- "import": "./dist/receiver/trpc/index.js",
47
- "require": "./dist/receiver/trpc/index.cjs"
48
- },
49
39
  "./receiver/express": {
50
40
  "types": "./dist/@types/receiver/express/index.d.ts",
51
41
  "import": "./dist/receiver/express/index.js",
@@ -61,10 +51,25 @@
61
51
  "import": "./dist/receiver/hono/index.js",
62
52
  "require": "./dist/receiver/hono/index.cjs"
63
53
  },
64
- "./api": {
65
- "types": "./dist/@types/api/index.d.ts",
66
- "import": "./dist/api/index.js",
67
- "require": "./dist/api/index.cjs"
54
+ "./receiver/trpc": {
55
+ "types": "./dist/@types/receiver/trpc/index.d.ts",
56
+ "import": "./dist/receiver/trpc/index.js",
57
+ "require": "./dist/receiver/trpc/index.cjs"
58
+ },
59
+ "./sse": {
60
+ "types": "./dist/@types/sse/index.d.ts",
61
+ "import": "./dist/sse/index.js",
62
+ "require": "./dist/sse/index.cjs"
63
+ },
64
+ "./trpc": {
65
+ "types": "./dist/@types/trpc/index.d.ts",
66
+ "import": "./dist/trpc/index.js",
67
+ "require": "./dist/trpc/index.cjs"
68
+ },
69
+ "./webhook": {
70
+ "types": "./dist/@types/webhook/index.d.ts",
71
+ "import": "./dist/webhook/index.js",
72
+ "require": "./dist/webhook/index.cjs"
68
73
  }
69
74
  },
70
75
  "sideEffects": false,
@@ -80,8 +85,8 @@
80
85
  "express": "^5.2.1",
81
86
  "fastify": "^5.8.5",
82
87
  "hono": "^4.12.23",
83
- "@rotorsoft/act": "^1.10.1",
84
- "@rotorsoft/act-ops": "^0.2.0"
88
+ "@rotorsoft/act": "^1.10.2",
89
+ "@rotorsoft/act-ops": "^0.2.1"
85
90
  },
86
91
  "peerDependenciesMeta": {
87
92
  "@rotorsoft/act-ops": {
@@ -114,7 +119,7 @@
114
119
  "fastify": "^5.8.5",
115
120
  "hono": "^4.12.23",
116
121
  "zod": "^4.4.3",
117
- "@rotorsoft/act-ops": "^0.2.0"
122
+ "@rotorsoft/act-ops": "^0.2.1"
118
123
  },
119
124
  "scripts": {
120
125
  "clean": "rm -rf dist",