@rotorsoft/act-http 1.2.0 → 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.
Files changed (60) hide show
  1. package/README.md +44 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/@types/api/errors.d.ts.map +1 -1
  4. package/dist/@types/receiver/start.d.ts +1 -1
  5. package/dist/@types/sse/apply-patch.d.ts +3 -3
  6. package/dist/@types/sse/broadcast.d.ts +6 -6
  7. package/dist/@types/sse/broadcast.d.ts.map +1 -1
  8. package/dist/@types/sse/presence.d.ts +7 -7
  9. package/dist/@types/sse/presence.d.ts.map +1 -1
  10. package/dist/@types/trpc/index.d.ts +168 -0
  11. package/dist/@types/trpc/index.d.ts.map +1 -0
  12. package/dist/@types/webhook/classify.d.ts +6 -6
  13. package/dist/@types/webhook/classify.d.ts.map +1 -1
  14. package/dist/@types/webhook/index.d.ts +1 -1
  15. package/dist/@types/webhook/index.d.ts.map +1 -1
  16. package/dist/@types/webhook/sign.d.ts +1 -1
  17. package/dist/@types/webhook/sign.d.ts.map +1 -1
  18. package/dist/api/index.cjs +2 -2
  19. package/dist/api/index.cjs.map +1 -1
  20. package/dist/api/index.js +4 -55
  21. package/dist/api/index.js.map +1 -1
  22. package/dist/{chunk-NOIXOF2I.js → chunk-4CGAUB5H.js} +13 -13
  23. package/dist/chunk-4CGAUB5H.js.map +1 -0
  24. package/dist/{chunk-F7VWYZ37.js → chunk-K4HAOBRF.js} +4 -4
  25. package/dist/{chunk-F7VWYZ37.js.map → chunk-K4HAOBRF.js.map} +1 -1
  26. package/dist/chunk-Z6FVXDDU.js +63 -0
  27. package/dist/chunk-Z6FVXDDU.js.map +1 -0
  28. package/dist/receiver/express/index.cjs +14 -14
  29. package/dist/receiver/express/index.cjs.map +1 -1
  30. package/dist/receiver/express/index.js +3 -3
  31. package/dist/receiver/express/index.js.map +1 -1
  32. package/dist/receiver/fastify/index.cjs +12 -12
  33. package/dist/receiver/fastify/index.cjs.map +1 -1
  34. package/dist/receiver/fastify/index.js +1 -1
  35. package/dist/receiver/hono/index.cjs +14 -14
  36. package/dist/receiver/hono/index.cjs.map +1 -1
  37. package/dist/receiver/hono/index.js +2 -2
  38. package/dist/receiver/index.cjs +19 -2746
  39. package/dist/receiver/index.cjs.map +1 -1
  40. package/dist/receiver/index.js +5 -2077
  41. package/dist/receiver/index.js.map +1 -1
  42. package/dist/receiver/trpc/index.cjs +12 -12
  43. package/dist/receiver/trpc/index.cjs.map +1 -1
  44. package/dist/receiver/trpc/index.js +1 -1
  45. package/dist/sse/index.cjs +21 -21
  46. package/dist/sse/index.cjs.map +1 -1
  47. package/dist/sse/index.js +24 -24
  48. package/dist/sse/index.js.map +1 -1
  49. package/dist/trpc/index.cjs +169 -0
  50. package/dist/trpc/index.cjs.map +1 -0
  51. package/dist/trpc/index.js +95 -0
  52. package/dist/trpc/index.js.map +1 -0
  53. package/dist/webhook/index.cjs +14 -34
  54. package/dist/webhook/index.cjs.map +1 -1
  55. package/dist/webhook/index.js +14 -32
  56. package/dist/webhook/index.js.map +1 -1
  57. package/package.json +52 -30
  58. package/dist/chunk-NOIXOF2I.js.map +0 -1
  59. package/dist/dist-NWMJQI4E.js +0 -647
  60. package/dist/dist-NWMJQI4E.js.map +0 -1
package/dist/sse/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { patch } from "@rotorsoft/act-patch";
3
3
 
4
4
  // src/sse/apply-patch.ts
5
- import { patch as deepMerge } from "@rotorsoft/act-patch";
5
+ import { patch as deep_merge } from "@rotorsoft/act-patch";
6
6
  function applyPatchMessage(msg, cached) {
7
7
  const cachedV = cached?._v ?? 0;
8
8
  const versions = Object.keys(msg).map(Number).sort((a, b) => a - b);
@@ -14,13 +14,13 @@ function applyPatchMessage(msg, cached) {
14
14
  let state = cached;
15
15
  for (const v of versions) {
16
16
  if (v <= cachedV) continue;
17
- state = { ...deepMerge(state, msg[v]), _v: v };
17
+ state = { ...deep_merge(state, msg[v]), _v: v };
18
18
  }
19
19
  return { ok: true, state };
20
20
  }
21
21
 
22
22
  // src/sse/broadcast.ts
23
- import { patch as applyPatch } from "@rotorsoft/act-patch";
23
+ import { patch as apply_patch } from "@rotorsoft/act-patch";
24
24
 
25
25
  // src/sse/state-cache.ts
26
26
  var StateCache = class {
@@ -67,9 +67,9 @@ var StateCache = class {
67
67
  // src/sse/broadcast.ts
68
68
  var BroadcastChannel = class {
69
69
  channels = /* @__PURE__ */ new Map();
70
- stateCache;
70
+ state_cache;
71
71
  constructor(options) {
72
- this.stateCache = new StateCache(options?.cacheSize ?? 50);
72
+ this.state_cache = new StateCache(options?.cache_size ?? 50);
73
73
  }
74
74
  /**
75
75
  * Publish domain patches from a commit.
@@ -80,7 +80,7 @@ var BroadcastChannel = class {
80
80
  * @param patches - Array of domain patches, one per emitted event
81
81
  */
82
82
  publish(streamId, state, patches = []) {
83
- this.stateCache.set(streamId, state);
83
+ this.state_cache.set(streamId, state);
84
84
  const baseV = state._v - patches.length;
85
85
  const msg = {};
86
86
  patches.forEach((p, i) => {
@@ -97,12 +97,12 @@ var BroadcastChannel = class {
97
97
  * (e.g. presence overlay, computed field refresh).
98
98
  * Uses the same version as the cached state, single entry.
99
99
  */
100
- publishOverlay(streamId, overlayPatch) {
101
- const prev = this.stateCache.get(streamId);
100
+ publish_overlay(streamId, overlay_patch) {
101
+ const prev = this.state_cache.get(streamId);
102
102
  if (!prev) return void 0;
103
- const state = applyPatch(prev, overlayPatch);
104
- this.stateCache.set(streamId, state);
105
- const msg = { [state._v]: overlayPatch };
103
+ const state = apply_patch(prev, overlay_patch);
104
+ this.state_cache.set(streamId, state);
105
+ const msg = { [state._v]: overlay_patch };
106
106
  const subs = this.channels.get(streamId);
107
107
  if (subs?.size) {
108
108
  for (const cb of subs) cb(msg);
@@ -124,16 +124,16 @@ var BroadcastChannel = class {
124
124
  };
125
125
  }
126
126
  /** Get the number of subscribers for a stream. */
127
- getSubscriberCount(streamId) {
127
+ get_subscriber_count(streamId) {
128
128
  return this.channels.get(streamId)?.size ?? 0;
129
129
  }
130
130
  /** Get the cached state for a stream (for reconnects / initial SSE yield). */
131
- getState(streamId) {
132
- return this.stateCache.get(streamId);
131
+ get_state(streamId) {
132
+ return this.state_cache.get(streamId);
133
133
  }
134
134
  /** Direct access to the state cache (for app-specific reads like presence). */
135
135
  get cache() {
136
- return this.stateCache;
136
+ return this.state_cache;
137
137
  }
138
138
  };
139
139
 
@@ -141,28 +141,28 @@ var BroadcastChannel = class {
141
141
  var PresenceTracker = class {
142
142
  streams = /* @__PURE__ */ new Map();
143
143
  /** Increment ref count for an identity on a stream. */
144
- add(streamId, identityId) {
144
+ add(streamId, identity_id) {
145
145
  if (!this.streams.has(streamId)) this.streams.set(streamId, /* @__PURE__ */ new Map());
146
146
  const counts = this.streams.get(streamId);
147
- counts.set(identityId, (counts.get(identityId) ?? 0) + 1);
147
+ counts.set(identity_id, (counts.get(identity_id) ?? 0) + 1);
148
148
  }
149
149
  /** Decrement ref count. Removes the identity when count reaches 0. */
150
- remove(streamId, identityId) {
150
+ remove(streamId, identity_id) {
151
151
  const counts = this.streams.get(streamId);
152
152
  if (!counts) return;
153
- const n = (counts.get(identityId) ?? 1) - 1;
154
- if (n <= 0) counts.delete(identityId);
155
- else counts.set(identityId, n);
153
+ const n = (counts.get(identity_id) ?? 1) - 1;
154
+ if (n <= 0) counts.delete(identity_id);
155
+ else counts.set(identity_id, n);
156
156
  if (counts.size === 0) this.streams.delete(streamId);
157
157
  }
158
158
  /** Get the set of online identity IDs for a stream. */
159
- getOnline(streamId) {
159
+ get_online(streamId) {
160
160
  const counts = this.streams.get(streamId);
161
161
  return counts ? new Set(counts.keys()) : /* @__PURE__ */ new Set();
162
162
  }
163
163
  /** Check if a specific identity is online for a stream. */
164
- isOnline(streamId, identityId) {
165
- return (this.streams.get(streamId)?.get(identityId) ?? 0) > 0;
164
+ is_online(streamId, identity_id) {
165
+ return (this.streams.get(streamId)?.get(identity_id) ?? 0) > 0;
166
166
  }
167
167
  };
168
168
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sse/index.ts","../../src/sse/apply-patch.ts","../../src/sse/broadcast.ts","../../src/sse/state-cache.ts","../../src/sse/presence.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/sse\n *\n * Incremental state broadcast over SSE for act event-sourced apps.\n *\n * Server-side broadcast with domain patch forwarding, an LRU state cache,\n * presence tracking, and a client-side patch applicator with version\n * validation and resync detection.\n *\n * ## Architecture\n *\n * ```\n * app.do() → snapshots (each carries its domain patch)\n * │\n * ▼\n * deriveState(snap) ← app-specific (overlay presence, deadlines, etc.)\n * state._v = snap.event.version\n * │\n * ▼\n * broadcast.publish(streamId, state, patches)\n * │\n * ├── version-key each patch: { [baseV+1]: patch1, [baseV+2]: patch2 }\n * └── push to all SSE subscribers\n * │\n * ▼\n * Client: applyPatchMessage(msg, cached)\n * │\n * ├── contiguous → deep-merge patches in version order\n * ├── stale → skip (client already ahead)\n * └── behind → resync (client missed versions)\n * ```\n *\n * ## Version Contract\n *\n * `_v` is always the event store stream version (`snap.event.version`).\n * No separate version counters. The event store is the single source of truth.\n */\n\nexport { patch } from \"@rotorsoft/act-patch\";\nexport type { ApplyResult } from \"./apply-patch.js\";\nexport { applyPatchMessage } from \"./apply-patch.js\";\nexport { BroadcastChannel } from \"./broadcast.js\";\nexport { PresenceTracker } from \"./presence.js\";\nexport { StateCache } from \"./state-cache.js\";\nexport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n","import { patch as deepMerge } from \"@rotorsoft/act-patch\";\nimport type { BroadcastState, PatchMessage } from \"./types.js\";\n\n/**\n * Result of applying a patch message to cached client state.\n */\nexport type ApplyResult<S extends BroadcastState = BroadcastState> =\n | { ok: true; state: S }\n | { ok: false; reason: \"stale\" | \"behind\" };\n\n/**\n * Apply a version-keyed patch message to the client's cached state.\n *\n * ## Version logic\n *\n * - All patches older than cached → \"stale\" (client already ahead)\n * - Gap between cached version and first patch → \"behind\" (client missed versions, must resync)\n * - Contiguous from cached version → apply in order\n *\n * ## Usage (React Query)\n *\n * ```typescript\n * onData: (msg) => {\n * const cached = utils.getState.getData({ streamId });\n * const result = applyPatchMessage(msg, cached);\n * if (result.ok) {\n * utils.getState.setData({ streamId }, result.state);\n * } else if (result.reason === \"behind\") {\n * utils.getState.invalidate({ streamId }); // trigger full refetch\n * }\n * // \"stale\" → no-op, client already has newer state\n * }\n * ```\n */\nexport function applyPatchMessage<S extends BroadcastState>(\n msg: PatchMessage<S>,\n cached: S | null | undefined\n): ApplyResult<S> {\n const cachedV = cached?._v ?? 0;\n const versions = Object.keys(msg)\n .map(Number)\n .sort((a, b) => a - b);\n\n if (!versions.length) return { ok: false, reason: \"stale\" };\n\n const minV = versions[0];\n const maxV = versions[versions.length - 1];\n\n if (maxV <= cachedV) return { ok: false, reason: \"stale\" };\n if (!cached || minV > cachedV + 1) return { ok: false, reason: \"behind\" };\n\n let state = cached;\n for (const v of versions) {\n if (v <= cachedV) continue;\n state = { ...deepMerge(state, msg[v]), _v: v } as S;\n }\n return { ok: true, state };\n}\n","import { patch as applyPatch } from \"@rotorsoft/act-patch\";\nimport { StateCache } from \"./state-cache.js\";\nimport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n\n/**\n * Server-side broadcast channel for incremental state sync over SSE.\n *\n * Manages per-stream subscriber sets and an LRU state cache. When state\n * changes, forwards domain patches (from event handlers) to all subscribers\n * as version-keyed messages.\n *\n * ## Usage\n *\n * ```typescript\n * const broadcast = new BroadcastChannel<MyState>();\n *\n * // After every app.do():\n * const snaps = await app.do(...);\n * const patches = snaps.map(s => s.patch).filter(Boolean);\n * const state = deriveState(snaps.at(-1));\n * broadcast.publish(streamId, state, patches);\n *\n * // In SSE subscription:\n * const cleanup = broadcast.subscribe(streamId, (msg) => {\n * pending = msg;\n * resolve?.();\n * });\n *\n * // Initial state for reconnects:\n * const cached = broadcast.getState(streamId);\n * ```\n *\n * ## Version Contract\n *\n * The `_v` field on state MUST be set from `snap.event.version` (the event\n * store's monotonic stream version) BEFORE calling `publish()`. This is the\n * single source of truth for ordering — no separate version counters.\n */\nexport class BroadcastChannel<S extends BroadcastState = BroadcastState> {\n private channels = new Map<string, Set<Subscriber<S>>>();\n private stateCache: StateCache<S>;\n\n constructor(options?: { cacheSize?: number }) {\n this.stateCache = new StateCache<S>(options?.cacheSize ?? 50);\n }\n\n /**\n * Publish domain patches from a commit.\n * patches[i] corresponds to version baseV + i + 1.\n *\n * @param streamId - The event store stream ID\n * @param state - Full state with `_v` set from `snap.event.version`\n * @param patches - Array of domain patches, one per emitted event\n */\n publish(\n streamId: string,\n state: S,\n patches: Partial<S>[] = []\n ): PatchMessage<S> {\n this.stateCache.set(streamId, state);\n\n const baseV = state._v - patches.length;\n const msg: PatchMessage<S> = {};\n patches.forEach((p, i) => {\n msg[baseV + i + 1] = p;\n });\n\n const subs = this.channels.get(streamId);\n if (subs?.size) {\n for (const cb of subs) cb(msg);\n }\n return msg;\n }\n\n /**\n * Publish a state update that doesn't change the event version\n * (e.g. presence overlay, computed field refresh).\n * Uses the same version as the cached state, single entry.\n */\n publishOverlay(\n streamId: string,\n overlayPatch: Partial<S>\n ): PatchMessage<S> | undefined {\n const prev = this.stateCache.get(streamId);\n if (!prev) return undefined;\n\n const state = applyPatch(prev, overlayPatch) as S;\n this.stateCache.set(streamId, state);\n\n const msg: PatchMessage<S> = { [state._v]: overlayPatch };\n const subs = this.channels.get(streamId);\n if (subs?.size) {\n for (const cb of subs) cb(msg);\n }\n return msg;\n }\n\n /**\n * Subscribe to broadcast messages for a stream.\n * Returns a cleanup function that removes the subscription.\n */\n subscribe(streamId: string, cb: Subscriber<S>): () => void {\n if (!this.channels.has(streamId)) this.channels.set(streamId, new Set());\n this.channels.get(streamId)!.add(cb);\n return () => {\n this.channels.get(streamId)?.delete(cb);\n if (this.channels.get(streamId)?.size === 0) {\n this.channels.delete(streamId);\n }\n };\n }\n\n /** Get the number of subscribers for a stream. */\n getSubscriberCount(streamId: string): number {\n return this.channels.get(streamId)?.size ?? 0;\n }\n\n /** Get the cached state for a stream (for reconnects / initial SSE yield). */\n getState(streamId: string): S | undefined {\n return this.stateCache.get(streamId);\n }\n\n /** Direct access to the state cache (for app-specific reads like presence). */\n get cache(): StateCache<S> {\n return this.stateCache;\n }\n}\n","import type { BroadcastState } from \"./types.js\";\n\n/**\n * Generic LRU cache for aggregate state objects.\n *\n * Keyed by stream ID. Each entry stores the full state (with `_v` from the\n * event store). Used as the \"previous state\" baseline for computing patches,\n * and as the fast path for reconnects.\n *\n * The cache is shared between the broadcast hot path and read queries.\n * Projections should maintain their own cache to avoid double-apply bugs.\n */\nexport class StateCache<S extends BroadcastState = BroadcastState> {\n private cache = new Map<string, S>();\n private maxSize: number;\n\n constructor(maxSize = 50) {\n this.maxSize = maxSize;\n }\n\n /** Get a cached state, promoting it to MRU position. */\n get(key: string): S | undefined {\n const s = this.cache.get(key);\n if (s) {\n this.cache.delete(key);\n this.cache.set(key, s);\n }\n return s;\n }\n\n /** Set a cached state, evicting the LRU entry if at capacity. */\n set(key: string, state: S): void {\n this.cache.delete(key);\n this.cache.set(key, state);\n if (this.cache.size > this.maxSize) {\n this.cache.delete(this.cache.keys().next().value!);\n }\n }\n\n /** Remove a cached entry. */\n delete(key: string): void {\n this.cache.delete(key);\n }\n\n /** Check if a key exists in the cache. */\n has(key: string): boolean {\n return this.cache.has(key);\n }\n\n /** Current number of cached entries. */\n get size(): number {\n return this.cache.size;\n }\n\n /** Direct access to the underlying map (for iteration). */\n entries(): IterableIterator<[string, S]> {\n return this.cache.entries();\n }\n}\n","/**\n * Generic presence tracker — ref-counted online status per stream per identity.\n *\n * Supports multi-tab: each subscribe increments the ref count, each\n * unsubscribe decrements it. An identity is considered online when\n * ref count > 0.\n *\n * ## Usage\n *\n * ```typescript\n * const presence = new PresenceTracker();\n *\n * // On SSE connect:\n * presence.add(gameId, playerId);\n *\n * // On SSE disconnect:\n * presence.remove(gameId, playerId);\n *\n * // Query:\n * presence.getOnline(gameId); // Set<string>\n * ```\n */\nexport class PresenceTracker {\n private streams = new Map<string, Map<string, number>>();\n\n /** Increment ref count for an identity on a stream. */\n add(streamId: string, identityId: string): void {\n if (!this.streams.has(streamId)) this.streams.set(streamId, new Map());\n const counts = this.streams.get(streamId)!;\n counts.set(identityId, (counts.get(identityId) ?? 0) + 1);\n }\n\n /** Decrement ref count. Removes the identity when count reaches 0. */\n remove(streamId: string, identityId: string): void {\n const counts = this.streams.get(streamId);\n if (!counts) return;\n const n = (counts.get(identityId) ?? 1) - 1;\n if (n <= 0) counts.delete(identityId);\n else counts.set(identityId, n);\n if (counts.size === 0) this.streams.delete(streamId);\n }\n\n /** Get the set of online identity IDs for a stream. */\n getOnline(streamId: string): Set<string> {\n const counts = this.streams.get(streamId);\n return counts ? new Set(counts.keys()) : new Set();\n }\n\n /** Check if a specific identity is online for a stream. */\n isOnline(streamId: string, identityId: string): boolean {\n return (this.streams.get(streamId)?.get(identityId) ?? 0) > 0;\n }\n}\n"],"mappings":";AAuCA,SAAS,aAAa;;;ACvCtB,SAAS,SAAS,iBAAiB;AAkC5B,SAAS,kBACd,KACA,QACgB;AAChB,QAAM,UAAU,QAAQ,MAAM;AAC9B,QAAM,WAAW,OAAO,KAAK,GAAG,EAC7B,IAAI,MAAM,EACV,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAEvB,MAAI,CAAC,SAAS,OAAQ,QAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AAE1D,QAAM,OAAO,SAAS,CAAC;AACvB,QAAM,OAAO,SAAS,SAAS,SAAS,CAAC;AAEzC,MAAI,QAAQ,QAAS,QAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AACzD,MAAI,CAAC,UAAU,OAAO,UAAU,EAAG,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAExE,MAAI,QAAQ;AACZ,aAAW,KAAK,UAAU;AACxB,QAAI,KAAK,QAAS;AAClB,YAAQ,EAAE,GAAG,UAA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;AAAA;AAAA,EAGA,SAAS,UAAiC;AACxC,WAAO,KAAK,WAAW,IAAI,QAAQ;AAAA,EACrC;AAAA;AAAA,EAGA,IAAI,QAAuB;AACzB,WAAO,KAAK;AAAA,EACd;AACF;;;AExGO,IAAM,kBAAN,MAAsB;AAAA,EACnB,UAAU,oBAAI,IAAiC;AAAA;AAAA,EAGvD,IAAI,UAAkB,YAA0B;AAC9C,QAAI,CAAC,KAAK,QAAQ,IAAI,QAAQ,EAAG,MAAK,QAAQ,IAAI,UAAU,oBAAI,IAAI,CAAC;AACrE,UAAM,SAAS,KAAK,QAAQ,IAAI,QAAQ;AACxC,WAAO,IAAI,aAAa,OAAO,IAAI,UAAU,KAAK,KAAK,CAAC;AAAA,EAC1D;AAAA;AAAA,EAGA,OAAO,UAAkB,YAA0B;AACjD,UAAM,SAAS,KAAK,QAAQ,IAAI,QAAQ;AACxC,QAAI,CAAC,OAAQ;AACb,UAAM,KAAK,OAAO,IAAI,UAAU,KAAK,KAAK;AAC1C,QAAI,KAAK,EAAG,QAAO,OAAO,UAAU;AAAA,QAC/B,QAAO,IAAI,YAAY,CAAC;AAC7B,QAAI,OAAO,SAAS,EAAG,MAAK,QAAQ,OAAO,QAAQ;AAAA,EACrD;AAAA;AAAA,EAGA,UAAU,UAA+B;AACvC,UAAM,SAAS,KAAK,QAAQ,IAAI,QAAQ;AACxC,WAAO,SAAS,IAAI,IAAI,OAAO,KAAK,CAAC,IAAI,oBAAI,IAAI;AAAA,EACnD;AAAA;AAAA,EAGA,SAAS,UAAkB,YAA6B;AACtD,YAAQ,KAAK,QAAQ,IAAI,QAAQ,GAAG,IAAI,UAAU,KAAK,KAAK;AAAA,EAC9D;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/sse/index.ts","../../src/sse/apply-patch.ts","../../src/sse/broadcast.ts","../../src/sse/state-cache.ts","../../src/sse/presence.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/sse\n *\n * Incremental state broadcast over SSE for act event-sourced apps.\n *\n * Server-side broadcast with domain patch forwarding, an LRU state cache,\n * presence tracking, and a client-side patch applicator with version\n * validation and resync detection.\n *\n * ## Architecture\n *\n * ```\n * app.do() → snapshots (each carries its domain patch)\n * │\n * ▼\n * deriveState(snap) ← app-specific (overlay presence, deadlines, etc.)\n * state._v = snap.event.version\n * │\n * ▼\n * broadcast.publish(streamId, state, patches)\n * │\n * ├── version-key each patch: { [baseV+1]: patch1, [baseV+2]: patch2 }\n * └── push to all SSE subscribers\n * │\n * ▼\n * Client: applyPatchMessage(msg, cached)\n * │\n * ├── contiguous → deep-merge patches in version order\n * ├── stale → skip (client already ahead)\n * └── behind → resync (client missed versions)\n * ```\n *\n * ## Version Contract\n *\n * `_v` is always the event store stream version (`snap.event.version`).\n * No separate version counters. The event store is the single source of truth.\n */\n\nexport { patch } from \"@rotorsoft/act-patch\";\nexport type { ApplyResult } from \"./apply-patch.js\";\nexport { applyPatchMessage } from \"./apply-patch.js\";\nexport { BroadcastChannel } from \"./broadcast.js\";\nexport { PresenceTracker } from \"./presence.js\";\nexport { StateCache } from \"./state-cache.js\";\nexport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n","import { patch as deep_merge } from \"@rotorsoft/act-patch\";\nimport type { BroadcastState, PatchMessage } from \"./types.js\";\n\n/**\n * Result of applying a patch message to cached client state.\n */\nexport type ApplyResult<S extends BroadcastState = BroadcastState> =\n | { ok: true; state: S }\n | { ok: false; reason: \"stale\" | \"behind\" };\n\n/**\n * Apply a version-keyed patch message to the client's cached state.\n *\n * ## Version logic\n *\n * - All patches older than cached → \"stale\" (client already ahead)\n * - Gap between cached version and first patch → \"behind\" (client missed versions, must resync)\n * - Contiguous from cached version → apply in order\n *\n * ## Usage (React Query)\n *\n * ```typescript\n * onData: (msg) => {\n * const cached = utils.get_state.get_data({ streamId });\n * const result = applyPatchMessage(msg, cached);\n * if (result.ok) {\n * utils.get_state.setData({ streamId }, result.state);\n * } else if (result.reason === \"behind\") {\n * utils.get_state.invalidate({ streamId }); // trigger full refetch\n * }\n * // \"stale\" → no-op, client already has newer state\n * }\n * ```\n */\nexport function applyPatchMessage<S extends BroadcastState>(\n msg: PatchMessage<S>,\n cached: S | null | undefined\n): ApplyResult<S> {\n const cachedV = cached?._v ?? 0;\n const versions = Object.keys(msg)\n .map(Number)\n .sort((a, b) => a - b);\n\n if (!versions.length) return { ok: false, reason: \"stale\" };\n\n const minV = versions[0];\n const maxV = versions[versions.length - 1];\n\n if (maxV <= cachedV) return { ok: false, reason: \"stale\" };\n if (!cached || minV > cachedV + 1) return { ok: false, reason: \"behind\" };\n\n let state = cached;\n for (const v of versions) {\n if (v <= cachedV) continue;\n state = { ...deep_merge(state, msg[v]), _v: v } as S;\n }\n return { ok: true, state };\n}\n","import { patch as apply_patch } from \"@rotorsoft/act-patch\";\nimport { StateCache } from \"./state-cache.js\";\nimport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n\n/**\n * Server-side broadcast channel for incremental state sync over SSE.\n *\n * Manages per-stream subscriber sets and an LRU state cache. When state\n * changes, forwards domain patches (from event handlers) to all subscribers\n * as version-keyed messages.\n *\n * ## Usage\n *\n * ```typescript\n * const broadcast = new BroadcastChannel<MyState>();\n *\n * // After every app.do():\n * const snaps = await app.do(...);\n * const patches = snaps.map(s => s.patch).filter(Boolean);\n * const state = deriveState(snaps.at(-1));\n * broadcast.publish(streamId, state, patches);\n *\n * // In SSE subscription:\n * const cleanup = broadcast.subscribe(streamId, (msg) => {\n * pending = msg;\n * resolve?.();\n * });\n *\n * // Initial state for reconnects:\n * const cached = broadcast.get_state(streamId);\n * ```\n *\n * ## Version Contract\n *\n * The `_v` field on state MUST be set from `snap.event.version` (the event\n * store's monotonic stream version) BEFORE calling `publish()`. This is the\n * single source of truth for ordering — no separate version counters.\n */\nexport class BroadcastChannel<S extends BroadcastState = BroadcastState> {\n private channels = new Map<string, Set<Subscriber<S>>>();\n private state_cache: StateCache<S>;\n\n constructor(options?: { cache_size?: number }) {\n this.state_cache = new StateCache<S>(options?.cache_size ?? 50);\n }\n\n /**\n * Publish domain patches from a commit.\n * patches[i] corresponds to version baseV + i + 1.\n *\n * @param streamId - The event store stream ID\n * @param state - Full state with `_v` set from `snap.event.version`\n * @param patches - Array of domain patches, one per emitted event\n */\n publish(\n streamId: string,\n state: S,\n patches: Partial<S>[] = []\n ): PatchMessage<S> {\n this.state_cache.set(streamId, state);\n\n const baseV = state._v - patches.length;\n const msg: PatchMessage<S> = {};\n patches.forEach((p, i) => {\n msg[baseV + i + 1] = p;\n });\n\n const subs = this.channels.get(streamId);\n if (subs?.size) {\n for (const cb of subs) cb(msg);\n }\n return msg;\n }\n\n /**\n * Publish a state update that doesn't change the event version\n * (e.g. presence overlay, computed field refresh).\n * Uses the same version as the cached state, single entry.\n */\n publish_overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n const prev = this.state_cache.get(streamId);\n if (!prev) return undefined;\n\n const state = apply_patch(prev, overlay_patch) as S;\n this.state_cache.set(streamId, state);\n\n const msg: PatchMessage<S> = { [state._v]: overlay_patch };\n const subs = this.channels.get(streamId);\n if (subs?.size) {\n for (const cb of subs) cb(msg);\n }\n return msg;\n }\n\n /**\n * Subscribe to broadcast messages for a stream.\n * Returns a cleanup function that removes the subscription.\n */\n subscribe(streamId: string, cb: Subscriber<S>): () => void {\n if (!this.channels.has(streamId)) this.channels.set(streamId, new Set());\n this.channels.get(streamId)!.add(cb);\n return () => {\n this.channels.get(streamId)?.delete(cb);\n if (this.channels.get(streamId)?.size === 0) {\n this.channels.delete(streamId);\n }\n };\n }\n\n /** Get the number of subscribers for a stream. */\n get_subscriber_count(streamId: string): number {\n return this.channels.get(streamId)?.size ?? 0;\n }\n\n /** Get the cached state for a stream (for reconnects / initial SSE yield). */\n get_state(streamId: string): S | undefined {\n return this.state_cache.get(streamId);\n }\n\n /** Direct access to the state cache (for app-specific reads like presence). */\n get cache(): StateCache<S> {\n return this.state_cache;\n }\n}\n","import type { BroadcastState } from \"./types.js\";\n\n/**\n * Generic LRU cache for aggregate state objects.\n *\n * Keyed by stream ID. Each entry stores the full state (with `_v` from the\n * event store). Used as the \"previous state\" baseline for computing patches,\n * and as the fast path for reconnects.\n *\n * The cache is shared between the broadcast hot path and read queries.\n * Projections should maintain their own cache to avoid double-apply bugs.\n */\nexport class StateCache<S extends BroadcastState = BroadcastState> {\n private cache = new Map<string, S>();\n private maxSize: number;\n\n constructor(maxSize = 50) {\n this.maxSize = maxSize;\n }\n\n /** Get a cached state, promoting it to MRU position. */\n get(key: string): S | undefined {\n const s = this.cache.get(key);\n if (s) {\n this.cache.delete(key);\n this.cache.set(key, s);\n }\n return s;\n }\n\n /** Set a cached state, evicting the LRU entry if at capacity. */\n set(key: string, state: S): void {\n this.cache.delete(key);\n this.cache.set(key, state);\n if (this.cache.size > this.maxSize) {\n this.cache.delete(this.cache.keys().next().value!);\n }\n }\n\n /** Remove a cached entry. */\n delete(key: string): void {\n this.cache.delete(key);\n }\n\n /** Check if a key exists in the cache. */\n has(key: string): boolean {\n return this.cache.has(key);\n }\n\n /** Current number of cached entries. */\n get size(): number {\n return this.cache.size;\n }\n\n /** Direct access to the underlying map (for iteration). */\n entries(): IterableIterator<[string, S]> {\n return this.cache.entries();\n }\n}\n","/**\n * Generic presence tracker — ref-counted online status per stream per identity.\n *\n * Supports multi-tab: each subscribe increments the ref count, each\n * unsubscribe decrements it. An identity is considered online when\n * ref count > 0.\n *\n * ## Usage\n *\n * ```typescript\n * const presence = new PresenceTracker();\n *\n * // On SSE connect:\n * presence.add(game_id, player_id);\n *\n * // On SSE disconnect:\n * presence.remove(game_id, player_id);\n *\n * // Query:\n * presence.get_online(game_id); // Set<string>\n * ```\n */\nexport class PresenceTracker {\n private streams = new Map<string, Map<string, number>>();\n\n /** Increment ref count for an identity on a stream. */\n add(streamId: string, identity_id: string): void {\n if (!this.streams.has(streamId)) this.streams.set(streamId, new Map());\n const counts = this.streams.get(streamId)!;\n counts.set(identity_id, (counts.get(identity_id) ?? 0) + 1);\n }\n\n /** Decrement ref count. Removes the identity when count reaches 0. */\n remove(streamId: string, identity_id: string): void {\n const counts = this.streams.get(streamId);\n if (!counts) return;\n const n = (counts.get(identity_id) ?? 1) - 1;\n if (n <= 0) counts.delete(identity_id);\n else counts.set(identity_id, n);\n if (counts.size === 0) this.streams.delete(streamId);\n }\n\n /** Get the set of online identity IDs for a stream. */\n get_online(streamId: string): Set<string> {\n const counts = this.streams.get(streamId);\n return counts ? new Set(counts.keys()) : new Set();\n }\n\n /** Check if a specific identity is online for a stream. */\n is_online(streamId: string, identity_id: string): boolean {\n return (this.streams.get(streamId)?.get(identity_id) ?? 0) > 0;\n }\n}\n"],"mappings":";AAuCA,SAAS,aAAa;;;ACvCtB,SAAS,SAAS,kBAAkB;AAkC7B,SAAS,kBACd,KACA,QACgB;AAChB,QAAM,UAAU,QAAQ,MAAM;AAC9B,QAAM,WAAW,OAAO,KAAK,GAAG,EAC7B,IAAI,MAAM,EACV,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAEvB,MAAI,CAAC,SAAS,OAAQ,QAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AAE1D,QAAM,OAAO,SAAS,CAAC;AACvB,QAAM,OAAO,SAAS,SAAS,SAAS,CAAC;AAEzC,MAAI,QAAQ,QAAS,QAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AACzD,MAAI,CAAC,UAAU,OAAO,UAAU,EAAG,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAExE,MAAI,QAAQ;AACZ,aAAW,KAAK,UAAU;AACxB,QAAI,KAAK,QAAS;AAClB,YAAQ,EAAE,GAAG,WAAW,OAAO,IAAI,CAAC,CAAC,GAAG,IAAI,EAAE;AAAA,EAChD;AACA,SAAO,EAAE,IAAI,MAAM,MAAM;AAC3B;;;ACzDA,SAAS,SAAS,mBAAmB;;;ACY9B,IAAM,aAAN,MAA4D;AAAA,EACzD,QAAQ,oBAAI,IAAe;AAAA,EAC3B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AAiC;AAAA;AAAA,EAGvD,IAAI,UAAkB,aAA2B;AAC/C,QAAI,CAAC,KAAK,QAAQ,IAAI,QAAQ,EAAG,MAAK,QAAQ,IAAI,UAAU,oBAAI,IAAI,CAAC;AACrE,UAAM,SAAS,KAAK,QAAQ,IAAI,QAAQ;AACxC,WAAO,IAAI,cAAc,OAAO,IAAI,WAAW,KAAK,KAAK,CAAC;AAAA,EAC5D;AAAA;AAAA,EAGA,OAAO,UAAkB,aAA2B;AAClD,UAAM,SAAS,KAAK,QAAQ,IAAI,QAAQ;AACxC,QAAI,CAAC,OAAQ;AACb,UAAM,KAAK,OAAO,IAAI,WAAW,KAAK,KAAK;AAC3C,QAAI,KAAK,EAAG,QAAO,OAAO,WAAW;AAAA,QAChC,QAAO,IAAI,aAAa,CAAC;AAC9B,QAAI,OAAO,SAAS,EAAG,MAAK,QAAQ,OAAO,QAAQ;AAAA,EACrD;AAAA;AAAA,EAGA,WAAW,UAA+B;AACxC,UAAM,SAAS,KAAK,QAAQ,IAAI,QAAQ;AACxC,WAAO,SAAS,IAAI,IAAI,OAAO,KAAK,CAAC,IAAI,oBAAI,IAAI;AAAA,EACnD;AAAA;AAAA,EAGA,UAAU,UAAkB,aAA8B;AACxD,YAAQ,KAAK,QAAQ,IAAI,QAAQ,GAAG,IAAI,WAAW,KAAK,KAAK;AAAA,EAC/D;AACF;","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;AACzE,MAAI,eAAe,6BAAmB,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;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,OACrB,MAAM,MAAM,QAAQ,WAAW,CAAU,EACzC,SAAS,OAAO,EAAE,OAAO,IAAI,MAAM;AAKlC,YAAM,WAAW;AACjB,UAAI;AACF,cAAM,SAAS,MAAM,QAAQ,OAAO,aAAa,OAAO,QAAQ;AAChE,cAAM,mBAAmB,QAAQ,kBAC7B,MAAM,QAAQ,gBAAgB,aAAa,OAAO,QAAQ,IAC1D;AACJ,cAAM,SACJ,qBAAqB,SACjB,EAAE,QAAQ,OAAO,SAAS,MAAM,IAChC;AAAA,UACE;AAAA,UACA,OAAO,SAAS;AAAA,UAChB,iBAAiB;AAAA,QACnB;AAEN,YAAI,QAAQ,aAAa;AACvB,gBAAM,MAAM,QAAQ,YAAY,QAAQ,QAAQ;AAChD,cAAI,CAAC,KAAK;AACR,kBAAM,IAAI,wBAAU;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,wBAAU;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
@@ -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,I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;AAAA,QACnB;AAEN,YAAI,QAAQ,aAAa;AACvB,gBAAM,MAAM,QAAQ,YAAY,QAAQ,QAAQ;AAChD,cAAI,CAAC,KAAK;AACR,kBAAM,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":[]}
@@ -24,8 +24,6 @@ __export(webhook_exports, {
24
24
  NonRetryableWebhookError: () => NonRetryableWebhookError,
25
25
  RetryableHttpError: () => RetryableHttpError,
26
26
  WebhookError: () => WebhookError,
27
- classifyHttpResponse: () => classifyHttpResponse,
28
- tryOk: () => tryOk,
29
27
  webhook: () => webhook
30
28
  });
31
29
  module.exports = __toCommonJS(webhook_exports);
@@ -70,31 +68,15 @@ var NonRetryableWebhookError = class extends NonRetryableHttpError {
70
68
  };
71
69
 
72
70
  // src/webhook/classify.ts
73
- function classifyHttpResponse(response) {
71
+ function classify_http_response(response) {
74
72
  if (response.ok) return "ok";
75
73
  if (response.status >= 500) return "retry";
76
74
  return "block";
77
75
  }
78
- async function tryOk(response, options) {
79
- const disposition = classifyHttpResponse(response);
80
- if (disposition === "ok") return;
81
- let responseBody;
82
- try {
83
- responseBody = await response.text();
84
- } catch {
85
- }
86
- const label = options.label ?? "request";
87
- const ErrorClass = disposition === "retry" ? RetryableHttpError : NonRetryableHttpError;
88
- throw new ErrorClass(`${label} ${options.url} responded ${response.status}`, {
89
- status: response.status,
90
- url: options.url,
91
- responseBody
92
- });
93
- }
94
76
 
95
77
  // src/webhook/sign.ts
96
78
  var import_node_crypto = require("crypto");
97
- function signRequest(body, secret, now = Math.floor(Date.now() / 1e3)) {
79
+ function sign_request(body, secret, now = Math.floor(Date.now() / 1e3)) {
98
80
  const timestamp = String(now);
99
81
  const payload = `${timestamp}.${body}`;
100
82
  const hex = (0, import_node_crypto.createHmac)("sha256", secret).update(payload).digest("hex");
@@ -106,7 +88,7 @@ function resolve(resolver, event, fallback) {
106
88
  if (resolver === void 0) return fallback;
107
89
  return typeof resolver === "function" ? resolver(event) : resolver;
108
90
  }
109
- function hasHeader(headers, name) {
91
+ function has_header(headers, name) {
110
92
  const lower = name.toLowerCase();
111
93
  for (const k of Object.keys(headers)) {
112
94
  if (k.toLowerCase() === lower) return true;
@@ -116,28 +98,28 @@ function hasHeader(headers, name) {
116
98
  function webhook(config) {
117
99
  const timeoutMs = config.timeoutMs ?? 5e3;
118
100
  const method = config.method ?? "POST";
119
- const fetchImpl = config.fetch ?? globalThis.fetch;
120
- return async function webhookDeliver(event) {
101
+ const fetch_impl = config.fetch ?? globalThis.fetch;
102
+ return async function webhook_deliver(event) {
121
103
  const url = resolve(config.url, event, "");
122
- const customHeaders = resolve(
104
+ const custom_headers = resolve(
123
105
  config.headers,
124
106
  event,
125
107
  {}
126
108
  );
127
- const headers = { ...customHeaders };
128
- if (!hasHeader(headers, "content-type")) {
109
+ const headers = { ...custom_headers };
110
+ if (!has_header(headers, "content-type")) {
129
111
  headers["Content-Type"] = "application/json";
130
112
  }
131
- if (!hasHeader(headers, "idempotency-key")) {
113
+ if (!has_header(headers, "idempotency-key")) {
132
114
  const key = config.idempotencyKey ? config.idempotencyKey(event) : String(event.id);
133
115
  if (key !== null) headers["Idempotency-Key"] = key;
134
116
  }
135
117
  const rawBody = resolve(config.body, event, event);
136
118
  const body = typeof rawBody === "string" ? rawBody : JSON.stringify(rawBody);
137
- if (config.secret && !hasHeader(headers, "x-webhook-signature")) {
138
- const { signature, timestamp } = signRequest(body, config.secret);
119
+ if (config.secret && !has_header(headers, "x-webhook-signature")) {
120
+ const { signature, timestamp } = sign_request(body, config.secret);
139
121
  headers["X-Webhook-Signature"] = signature;
140
- if (!hasHeader(headers, "x-webhook-timestamp")) {
122
+ if (!has_header(headers, "x-webhook-timestamp")) {
141
123
  headers["X-Webhook-Timestamp"] = timestamp;
142
124
  }
143
125
  }
@@ -145,7 +127,7 @@ function webhook(config) {
145
127
  const timer = setTimeout(() => controller.abort(), timeoutMs);
146
128
  let response;
147
129
  try {
148
- response = await fetchImpl(url, {
130
+ response = await fetch_impl(url, {
149
131
  method,
150
132
  headers,
151
133
  body,
@@ -160,7 +142,7 @@ function webhook(config) {
160
142
  } finally {
161
143
  clearTimeout(timer);
162
144
  }
163
- const disposition = classifyHttpResponse(response);
145
+ const disposition = classify_http_response(response);
164
146
  if (disposition === "ok") return;
165
147
  let responseBody;
166
148
  try {
@@ -180,8 +162,6 @@ function webhook(config) {
180
162
  NonRetryableWebhookError,
181
163
  RetryableHttpError,
182
164
  WebhookError,
183
- classifyHttpResponse,
184
- tryOk,
185
165
  webhook
186
166
  });
187
167
  //# sourceMappingURL=index.cjs.map