@classytic/arc 2.48.0 → 2.49.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 (213) hide show
  1. package/dist/{EventTransport-BWwg5YAU.mjs → EventTransport-DbHZK230.mjs} +2 -2
  2. package/dist/{HookSystem-B9x-Y_k7.mjs → HookSystem-DMoeJ6Do.mjs} +2 -2
  3. package/dist/{QueryCache-DdvrGG8Q.d.mts → QueryCache-BE47tmlO.d.mts} +36 -1
  4. package/dist/{ResourceRegistry-BcvEJoZd.mjs → ResourceRegistry-CP-iTcKy.mjs} +2 -2
  5. package/dist/{acquire-D2yj6Zzl.mjs → acquire-CB0va87C.mjs} +1 -1
  6. package/dist/audit/index.d.mts +1 -1
  7. package/dist/audit/index.mjs +4 -4
  8. package/dist/auth/audit.mjs +1 -1
  9. package/dist/auth/index.d.mts +2 -2
  10. package/dist/auth/index.mjs +53 -15
  11. package/dist/auth/redis-session.mjs +1 -1
  12. package/dist/{authorizationDecision-BZSJcPNE.mjs → authorizationDecision-DHO94aV2.mjs} +4 -4
  13. package/dist/{boundedMap-o2KZDCWy.mjs → boundedMap-C51EUUOm.mjs} +1 -1
  14. package/dist/{buildHandler-G3k59KY2.mjs → buildHandler-9DuwEKvr.mjs} +23 -16
  15. package/dist/cache/index.d.mts +2 -2
  16. package/dist/cache/index.mjs +4 -4
  17. package/dist/{caching-CJIDPZOv.mjs → caching-COTX3sDa.mjs} +3 -6
  18. package/dist/{claimed-D0A43wjT.mjs → claimed-C7T1nHlo.mjs} +1 -1
  19. package/dist/cleanup/index.d.mts +2 -2
  20. package/dist/cleanup/index.mjs +4 -4
  21. package/dist/cli/commands/describe.d.mts +1 -1
  22. package/dist/cli/commands/describe.mjs +3 -3
  23. package/dist/cli/commands/docs.mjs +3 -3
  24. package/dist/cli/commands/doctor.mjs +1 -1
  25. package/dist/cli/commands/generate.mjs +2 -2
  26. package/dist/cli/commands/init.mjs +2 -2
  27. package/dist/cli/commands/introspect.mjs +2 -2
  28. package/dist/cli/index.mjs +3 -3
  29. package/dist/{constants-D-faL5SX.mjs → constants-DOnfMd7i.mjs} +1 -1
  30. package/dist/context/index.mjs +5 -5
  31. package/dist/core/index.d.mts +3 -3
  32. package/dist/core/index.mjs +7 -7
  33. package/dist/{core-NSu1peyq.mjs → core-BoEdFDDw.mjs} +3 -3
  34. package/dist/{createActionRouter-DTSVv1VK.mjs → createActionRouter-CpTn15dm.mjs} +54 -18
  35. package/dist/{createAggregationRouter-zEasm-ax.mjs → createAggregationRouter-CD_Hydp0.mjs} +13 -11
  36. package/dist/{createApp-CjqhkX1x.mjs → createApp-Be6XTGD9.mjs} +332 -40
  37. package/dist/{createMcpServer-hSFeqRUb.d.mts → createMcpServer-CS2KOVP6.d.mts} +1 -1
  38. package/dist/{defineAggregation-DH2L6_v9.mjs → defineAggregation-BI5pRb8c.mjs} +1 -1
  39. package/dist/{defineResource-zYCrhNaN.mjs → defineResource-BAzNu5Um.mjs} +8 -8
  40. package/dist/discovery/index.mjs +1 -1
  41. package/dist/docs/index.d.mts +1 -1
  42. package/dist/docs/index.mjs +3 -3
  43. package/dist/{elevation-z--rFcZ5.mjs → elevation-DupGuM41.mjs} +6 -9
  44. package/dist/encryption/index.mjs +3 -3
  45. package/dist/{errorHandler-3_3oN-Uc.mjs → errorHandler-DA03vRqp.mjs} +4 -7
  46. package/dist/{errors-DyY48oRi.mjs → errors-BpYV859Y.mjs} +1 -1
  47. package/dist/{eventPlugin-Co9sABCg.mjs → eventPlugin-D7LYtYzL.mjs} +9 -13
  48. package/dist/{eventTypes-HmAFyJmJ.mjs → eventTypes-BqA-N-Uz.mjs} +2 -2
  49. package/dist/events/index.d.mts +18 -5
  50. package/dist/events/index.mjs +8 -8
  51. package/dist/events/transports/redis-stream-entry.mjs +4 -4
  52. package/dist/events/transports/redis.d.mts +35 -0
  53. package/dist/events/transports/redis.mjs +87 -11
  54. package/dist/factory/index.d.mts +4 -4
  55. package/dist/factory/index.mjs +6 -6
  56. package/dist/{fastify-augmentation-bzkWPt1f.d.mts → fastify-augmentation-baQc3MaO.d.mts} +2 -2
  57. package/dist/fieldTypes-EFWxCkZ5.mjs +80 -0
  58. package/dist/{fields-rfsl26Ov.mjs → fields-CT1Erg7o.mjs} +1 -1
  59. package/dist/{filter-merge-8glLr7Dk.mjs → filter-merge-B1eJ1pMx.mjs} +1 -1
  60. package/dist/{generate-BOfBueRt.mjs → generate-Cr0ULavs.mjs} +2 -2
  61. package/dist/{headers-CHSOqpcY.mjs → headers-D4bncIOf.mjs} +2 -2
  62. package/dist/{health-ezwTHQh2.mjs → health-BoFxrkJE.mjs} +1 -1
  63. package/dist/{health-DHvAIVmM.mjs → health-DN_pUVMX.mjs} +1 -1
  64. package/dist/hooks/index.d.mts +1 -1
  65. package/dist/hooks/index.mjs +2 -2
  66. package/dist/http-cache/index.d.mts +2 -2
  67. package/dist/http-cache/index.mjs +4 -4
  68. package/dist/http-cache/purgers/cloudflare.mjs +2 -2
  69. package/dist/http-cache/purgers/fastly.mjs +2 -2
  70. package/dist/http-cache/testing/index.mjs +1 -1
  71. package/dist/idempotency/index.d.mts +1 -1
  72. package/dist/idempotency/index.mjs +10 -8
  73. package/dist/idempotency/redis.mjs +2 -2
  74. package/dist/{index-B5i9-vuP.d.mts → index-CMNpMBtW.d.mts} +1 -1
  75. package/dist/{index-BxZS-8So.d.mts → index-DKM2p5w5.d.mts} +48 -23
  76. package/dist/{index-Cy2-QffW.d.mts → index-DLCcLUQT.d.mts} +69 -6
  77. package/dist/{index-DFCCQ9AE.d.mts → index-DexdFs1a.d.mts} +1 -1
  78. package/dist/{index-D1X_C_qz.d.mts → index-Dhrks-hM.d.mts} +60 -10
  79. package/dist/index.d.mts +4 -4
  80. package/dist/index.mjs +11 -11
  81. package/dist/{init-MoE3eZNR.mjs → init-C4a24wD2.mjs} +1 -1
  82. package/dist/integrations/event-gateway.mjs +2 -2
  83. package/dist/integrations/index.d.mts +2 -2
  84. package/dist/integrations/index.mjs +1 -1
  85. package/dist/integrations/jobs/index.mjs +3 -3
  86. package/dist/integrations/mcp/index.d.mts +5 -5
  87. package/dist/integrations/mcp/index.mjs +2 -2
  88. package/dist/integrations/mcp/testing.d.mts +2 -2
  89. package/dist/integrations/mcp/testing.mjs +2 -2
  90. package/dist/integrations/streamline.mjs +3 -3
  91. package/dist/integrations/webhooks.d.mts +1 -1
  92. package/dist/integrations/webhooks.mjs +4 -4
  93. package/dist/integrations/websocket-pushref-redis.mjs +1 -1
  94. package/dist/integrations/websocket-redis.mjs +1 -1
  95. package/dist/integrations/websocket.mjs +2 -2
  96. package/dist/{jsonBody-DZGiCawf.mjs → jsonBody-DoTt5BS6.mjs} +2 -2
  97. package/dist/{keys-CrMOZuk6.mjs → keys--l9n7aOC.mjs} +1 -1
  98. package/dist/{loadResources-CVQvYUhN.mjs → loadResources-rygByIQA.mjs} +3 -3
  99. package/dist/{loadResourcesFromEntry-D0naccV2.mjs → loadResourcesFromEntry-ItNBIQ5w.mjs} +2 -2
  100. package/dist/logger/index.mjs +2 -2
  101. package/dist/{logger-VyMcSmVG.mjs → logger-UbknHqHy.mjs} +1 -1
  102. package/dist/{mcpPlugin-DQACaqVu.mjs → mcpPlugin-CTkk4RP8.mjs} +29 -26
  103. package/dist/{memory-Lpfu8Hga.mjs → memory-C47xVsjX.mjs} +3 -3
  104. package/dist/{metrics-DjVj1sg5.mjs → metrics-TJyAb1Xk.mjs} +4 -7
  105. package/dist/middleware/index.d.mts +1 -1
  106. package/dist/middleware/index.mjs +3 -3
  107. package/dist/migrations/index.mjs +2 -2
  108. package/dist/{module-BqPJpZ_L.mjs → module-CWiqsXnh.mjs} +1 -1
  109. package/dist/{multiTenant-KZj8j1uJ.d.mts → multiTenant-QtDzxx_K.d.mts} +1 -1
  110. package/dist/{multipartBody-BNgNv7r0.mjs → multipartBody-BdG1qbn1.mjs} +1 -1
  111. package/dist/{observeSend-BKJHibJz.mjs → observeSend-DrA3ADFN.mjs} +1 -1
  112. package/dist/{openapi-T90KrPR6.mjs → openapi-D6MAbYpv.mjs} +7 -7
  113. package/dist/outbox-admin/index.d.mts +1 -1
  114. package/dist/outbox-admin/index.mjs +5 -5
  115. package/dist/{outbox-module-C874VgBr.mjs → outbox-module-D5QABFQW.mjs} +197 -28
  116. package/dist/{outbox-module-5Mnwcycy.d.mts → outbox-module-DzW6zwWJ.d.mts} +103 -10
  117. package/dist/permissions/index.d.mts +2 -2
  118. package/dist/permissions/index.mjs +7 -7
  119. package/dist/{permissions-R9T2G1PH.mjs → permissions-CFsmdYUt.mjs} +9 -9
  120. package/dist/{pipe-DzqbsZy-.mjs → pipe-B_05AgGt.mjs} +2 -2
  121. package/dist/pipeline/index.d.mts +1 -1
  122. package/dist/pipeline/index.mjs +2 -2
  123. package/dist/{plan-C0gkeABY.mjs → plan-BnlNJhrj.mjs} +1 -1
  124. package/dist/{plugin-BJcVOX5r.mjs → plugin-CrMPYbdj.mjs} +94 -50
  125. package/dist/plugins/index.d.mts +6 -5
  126. package/dist/plugins/index.mjs +19 -18
  127. package/dist/plugins/response-cache.mjs +4 -4
  128. package/dist/plugins/tracing-entry.mjs +2 -2
  129. package/dist/{pluralize-CrCpyoZs.mjs → pluralize-oVIxJ4CY.mjs} +1 -1
  130. package/dist/presets/filesUpload.d.mts +1 -1
  131. package/dist/presets/filesUpload.mjs +5 -5
  132. package/dist/presets/index.d.mts +2 -2
  133. package/dist/presets/index.mjs +2 -2
  134. package/dist/presets/multiTenant.d.mts +1 -1
  135. package/dist/presets/multiTenant.mjs +5 -5
  136. package/dist/presets/search.d.mts +1 -1
  137. package/dist/presets/search.mjs +2 -2
  138. package/dist/{presets-CNDvNYsz.mjs → presets-CUd3L7v6.mjs} +4 -4
  139. package/dist/{projection-CIUe8b59.mjs → projection-DowJlIto.mjs} +2 -2
  140. package/dist/{purger.types-f83fTzGy.mjs → purger.types-BjKy8869.mjs} +1 -1
  141. package/dist/{queryCachePlugin-B2jpwFcv.mjs → queryCachePlugin-BvB3k_Fh.mjs} +114 -14
  142. package/dist/{queryCachePlugin-DYQUyeJ9.d.mts → queryCachePlugin-DrQNnGws.d.mts} +1 -1
  143. package/dist/{rateLimitKey-BWx-qep0.mjs → rateLimitKey-56nH1cWN.mjs} +1 -1
  144. package/dist/{realtime-D2tqi3d2.mjs → realtime-DXGBPtYK.mjs} +19 -22
  145. package/dist/registry/index.d.mts +2 -2
  146. package/dist/registry/index.mjs +3 -3
  147. package/dist/{registry-Dl0k6UXy.mjs → registry-Biz-6sEZ.mjs} +2 -2
  148. package/dist/{relay-ZYvS4xyW.mjs → relay-DEIoMntZ.mjs} +200 -99
  149. package/dist/{renewingLease-DT4yLb29.mjs → renewingLease-BCJpW9-u.mjs} +1 -1
  150. package/dist/{replyHelpers-BJFN5AW7.mjs → replyHelpers-DliJNb0-.mjs} +2 -2
  151. package/dist/{requestContext-Ct5la-SA.mjs → requestContext-tUgLt9Ky.mjs} +1 -1
  152. package/dist/{requirement-CxDxjB6V.mjs → requirement-0l2DApiQ.mjs} +1 -1
  153. package/dist/{resourceRateLimit-DCWglD7V.d.mts → resourceRateLimit-BPiESPtG.d.mts} +4 -0
  154. package/dist/{resourceRateLimit-D1oH2obv.mjs → resourceRateLimit-iSXF8rLH.mjs} +19 -4
  155. package/dist/{rolldown-runtime-BdTN42uL.mjs → rolldown-runtime-gKJR3o-6.mjs} +1 -1
  156. package/dist/{routeValidator-DclDl5WJ.mjs → routeValidator-xNYA4rr1.mjs} +47 -5
  157. package/dist/{runtimeCapabilities-ClWr60El.mjs → runtimeCapabilities-BQK-GrYe.mjs} +1 -1
  158. package/dist/{schedules-gVkRcs-9.mjs → schedules-D9iMVFhF.mjs} +6 -9
  159. package/dist/{schemaConverter-CIwB5wPO.mjs → schemaConverter-cIh4oX9a.mjs} +2 -2
  160. package/dist/{actionPermissions-Dha8sAz2.mjs → schemaIR-BsY4y9VP.mjs} +184 -16
  161. package/dist/schemas/index.mjs +1 -1
  162. package/dist/scim/index.mjs +2 -2
  163. package/dist/scope/index.d.mts +1 -1
  164. package/dist/scope/index.mjs +5 -5
  165. package/dist/{scope-VMZhdkbT.mjs → scope-QyhM9w8z.mjs} +4 -4
  166. package/dist/{shutdown-Bi19vH0z.mjs → shutdown-BM7Q0h4B.mjs} +1 -1
  167. package/dist/{sse-BqM359f1.mjs → sse-ofvlcTQQ.mjs} +9 -35
  168. package/dist/sseStats-DQqNN385.d.mts +112 -0
  169. package/dist/sseStream-BxQW7hPq.mjs +166 -0
  170. package/dist/{store-helpers-rx-F2ZGR.mjs → store-helpers-_FRhHDyv.mjs} +1 -1
  171. package/dist/{simpleEqualityMatcher-CaCS09fh.mjs → streamFrames-B3ZJfI02.mjs} +19 -2
  172. package/dist/{streaming-CPChx3A7.mjs → streaming-HZr63UiM.mjs} +1 -1
  173. package/dist/{subscriberIdentity-CYNYw8p_.mjs → subscriberIdentity-DSgnoT_D.mjs} +1 -1
  174. package/dist/{tenancy-BoWImS3K.mjs → tenancy-_ukT0oBt.mjs} +2 -2
  175. package/dist/{tenantPreparation-oqKCZQZM.mjs → tenantPreparation-DSlQI53c.mjs} +4 -4
  176. package/dist/testing/cleanupStoreContract.mjs +1 -1
  177. package/dist/testing/index.d.mts +4 -4
  178. package/dist/testing/index.mjs +324 -17
  179. package/dist/testing/outboxStoreContract.mjs +2 -2
  180. package/dist/testing/requiredPorts.mjs +2 -2
  181. package/dist/testing/storageContract.mjs +1 -1
  182. package/dist/{timing-Dsteq59c.mjs → timing-Z8p-Zlw1.mjs} +1 -1
  183. package/dist/{transactionContext-C1OgH-hW.mjs → transactionContext-DBbSTfY3.mjs} +1 -1
  184. package/dist/{typeGuards-DNlpASzd.mjs → typeGuards-_6nNQqgq.mjs} +1 -1
  185. package/dist/types/index.d.mts +1 -1
  186. package/dist/types/index.mjs +1 -1
  187. package/dist/types/storage.mjs +1 -1
  188. package/dist/{types-DduBiYaI.d.mts → types-B4E0sc6D.d.mts} +2 -2
  189. package/dist/{types-HFFSwF_K.mjs → types-CrOlZ4rY.mjs} +4 -4
  190. package/dist/usage/index.d.mts +1 -1
  191. package/dist/usage/index.mjs +7 -7
  192. package/dist/{userHelpers-N-k-8dNF.mjs → userHelpers-CBKx3XJN.mjs} +1 -1
  193. package/dist/utils/index.d.mts +239 -34
  194. package/dist/utils/index.mjs +13 -13
  195. package/dist/{utils-C7w_RVlx.mjs → utils--HE8R8sH.mjs} +761 -8
  196. package/dist/{validate-Brr4b_fH.mjs → validate-BUeE2MLR.mjs} +3 -3
  197. package/dist/{versioning-S18y2-0C.d.mts → versioning-B07RgD27.d.mts} +2 -13
  198. package/dist/{versioning-CE5kdWOY.mjs → versioning-qYgqwOhL.mjs} +4 -7
  199. package/dist/{workScope-A3XBpYTa.mjs → workScope-C-1QHNmV.mjs} +2 -2
  200. package/llms.txt +2 -2
  201. package/package.json +34 -34
  202. package/skills/arc/references/api-reference.md +2 -2
  203. package/skills/arc/references/auth-better-auth.md +1 -0
  204. package/skills/arc/references/events-outbox.md +7 -4
  205. package/skills/arc/references/events.md +2 -2
  206. package/skills/arc/references/production-api.md +4 -0
  207. package/skills/arc/references/production-boot.md +2 -0
  208. package/skills/arc/references/production-idempotency.md +1 -1
  209. package/skills/arc/references/production-realtime.md +28 -2
  210. package/skills/arc/references/validation.md +4 -0
  211. package/skills/arc/references/writes-hooks-errors.md +1 -0
  212. package/dist/schemaIR-A0IoD05P.mjs +0 -108
  213. package/dist/sseStream-qSa-F2Qm.mjs +0 -57
@@ -1,12 +1,14 @@
1
1
 
2
+ import { a as NotFoundError, c as RateLimitError, d as ValidationError, f as createDomainError, i as ForbiddenError, l as ServiceUnavailableError, m as isArcError, n as ConflictError, o as OrgAccessDeniedError, p as createError, r as ErrorOptions, s as OrgRequiredError, t as ArcError, u as UnauthorizedError } from "../errors-DTo0me1o.mjs";
3
+ import { n as ErrorMapper } from "../errorHandler-B9r88jZV.mjs";
2
4
  import { F as getHeader, I as requireSingleHeaderValue, P as ArcHeaders } from "../types-DnkIALZ8.mjs";
5
+ import { Y as OpenApiSchemas, h as QueryParserInterface, p as ParsedQuery } from "../index-DLCcLUQT.mjs";
6
+ import { a as SSE_DEFAULT_DRAIN_TIMEOUT_MS, c as SseStreamOptions, i as registerSseStats, l as openSseStream, n as SseConnectionGauge, o as SSE_DEFAULT_MAX_BUFFERED_BYTES, r as createSseConnectionGauge, s as SseStream, t as SSEStats } from "../sseStats-DQqNN385.mjs";
3
7
  import { f as getUserId, m as normalizeRoles, p as getUserRoles, t as AnyRecord } from "../base-HXNgPQww.mjs";
4
- import { Y as OpenApiSchemas, h as QueryParserInterface, p as ParsedQuery } from "../index-Cy2-QffW.mjs";
5
- import { n as ErrorMapper } from "../errorHandler-B9r88jZV.mjs";
6
- import { a as NotFoundError, c as RateLimitError, d as ValidationError, f as createDomainError, i as ForbiddenError, l as ServiceUnavailableError, m as isArcError, n as ConflictError, o as OrgAccessDeniedError, p as createError, r as ErrorOptions, s as OrgRequiredError, t as ArcError, u as UnauthorizedError } from "../errors-DTo0me1o.mjs";
7
8
  import { errorContractSchema } from "@classytic/repo-core/errors";
8
9
  import { FilterClause } from "@classytic/repo-core/query-parser";
9
10
  import { FastifyInstance, FastifyReply, FastifyRequest, RouteHandlerMethod } from "fastify";
11
+ import { ChangeEntry, ChangeLogStore, ChangesSinceOptions } from "@classytic/repo-core/sync";
10
12
  export declare const CircuitState: {
11
13
  readonly CLOSED: "CLOSED";
12
14
  readonly OPEN: "OPEN";
@@ -583,6 +585,239 @@ export declare class ArcQueryParser implements QueryParserInterface {
583
585
  }
584
586
  /** Create a new ArcQueryParser instance. */
585
587
  export declare function createQueryParser(options?: ArcQueryParserOptions): ArcQueryParser;
588
+ /**
589
+ * SSE control-frame vocabulary shared by every arc stream and `@classytic/arc-next/sse`.
590
+ *
591
+ * Kept apart from `replayStream.ts` so a feed that only names the frames
592
+ * (`realtimePlugin`) does not pull the replay hub, and `node:crypto`, into its chunk.
593
+ */
594
+ /**
595
+ * SSE control frame names. The same literals ship from `@classytic/arc-next/sse`;
596
+ * a test in each package pins them.
597
+ */
598
+ export declare const STREAM_FRAMES: {
599
+ readonly READY: "ready";
600
+ readonly RESYNC: "resync";
601
+ readonly REVOKED: "revoked";
602
+ readonly RETRY: "retry";
603
+ };
604
+ type StreamFrameName = (typeof STREAM_FRAMES)[keyof typeof STREAM_FRAMES];
605
+ type ResyncReason = "cursor_expired" | "gap_too_large" | "cursor_invalid";
606
+ /**
607
+ * `event: ready` (no `id:`). The first frame on every connection. `cursor` is
608
+ * present only on a replayable stream (the replay hub always sends it).
609
+ * `realtimePlugin` keeps its `resources` and `operations` fields next to these.
610
+ */
611
+ interface ReadyFrame {
612
+ cursor?: string;
613
+ resumed: boolean;
614
+ }
615
+ /** `event: resync` (no `id:`). The gap could not be replayed: reload the snapshot, then continue from `cursor`. */
616
+ interface ResyncFrame {
617
+ cursor: string;
618
+ reason: ResyncReason;
619
+ }
620
+ /** `event: revoked` (no `id:`). Access ended; the server closes the stream right after this frame. */
621
+ interface RevokedFrame {
622
+ reason: string;
623
+ }
624
+ /**
625
+ * `event: retry` (no `id:`). NOT final: the server closes right after, and the client
626
+ * should reconnect at once (no backoff) with its `Last-Event-ID`, so the stream is
627
+ * authorized afresh. Sent by the replay hub's `revalidate` (`{ close: 'retry' }` or
628
+ * `maxConsecutiveFailures`). A client that does not know the frame still reconnects
629
+ * with its normal backoff, so the frame is safe to send to older clients.
630
+ */
631
+ interface RetryFrame {
632
+ reason: string;
633
+ }
634
+ /**
635
+ * Identity keys a revoke matches on, e.g. `{ userId }`, `{ sessionId }`, `{ deviceId }`.
636
+ * Values are compared as strings (`String(value)`), so an ObjectId or a number
637
+ * returned by a loosely typed `identify` still matches.
638
+ */
639
+ type RevokeTarget = Readonly<Record<string, string>>;
640
+ /** The scope a partition tails with — passed to `store.since()` verbatim. */
641
+ type ReplayReadScope = Pick<ChangesSinceOptions, "tenantId" | "scopes" | "sharedScopes">;
642
+ /**
643
+ * A `revalidate.check` outcome that closes the stream with a stated frame:
644
+ *
645
+ * - `{ close: 'revoke', reason }` writes `revoked {reason}` (final; default reason
646
+ * `'access_ended'`, the same as returning `null`), e.g. `'mfa_required'`.
647
+ * - `{ close: 'retry', reason }` writes `retry {reason}` (NOT final; default reason
648
+ * `'retry'`) and closes, so the client reconnects at once and is authorized
649
+ * afresh, e.g. after a session lookup that could not be confirmed.
650
+ *
651
+ * Recognised only as an object with exactly these keys, so a ctx that happens to
652
+ * carry a `close` field is never mistaken for it.
653
+ */
654
+ interface ReplayCloseVerdict {
655
+ close: "retry" | "revoke";
656
+ reason?: string;
657
+ }
658
+ /** Injected timers (tests). Defaults to the global `setInterval` / `clearInterval`. */
659
+ interface ReplayHubTimers {
660
+ setInterval(fn: () => void, ms: number): unknown;
661
+ clearInterval(handle: unknown): void;
662
+ }
663
+ interface ReplayHubOptions<TDoc = unknown, TCtx = unknown> {
664
+ /** The change log frames are read from. */
665
+ store: ChangeLogStore<TDoc>;
666
+ /**
667
+ * Turn one log entry into the frame THIS subscriber sees (`data` is JSON-encoded).
668
+ * Return `null` to hide the entry from this subscriber; its cursor still advances
669
+ * (an id-only frame tells the client). A throw hides the entry too (logged).
670
+ */
671
+ toFrame(entry: ChangeEntry<TDoc>, ctx: TCtx): {
672
+ event: string;
673
+ data: unknown;
674
+ } | null;
675
+ /**
676
+ * The tail partition key and `since()` filter for a subscriber, e.g.
677
+ * `{ tenantId: ctx.orgId, scopes: ['alerts'] }`. Default `{}` (one partition, no filter).
678
+ * A platform-wide reader passes no `tenantId`.
679
+ */
680
+ readScope?(ctx: TCtx): ReplayReadScope;
681
+ /**
682
+ * Most log entries a reconnect replays; more than this is `resync 'gap_too_large'`.
683
+ * Entries hidden from the subscriber count too (the log is read before `toFrame`).
684
+ * Default 500.
685
+ */
686
+ maxReplay?: number;
687
+ /** Tail poll interval in ms. Default 1000; `0` = woken by `notify()` only. */
688
+ pollMs?: number;
689
+ /** `false` → `resync 'cursor_invalid'` without touching the store. */
690
+ isValidCursor?(cursor: string): boolean;
691
+ /**
692
+ * Cursor order (`< 0`, `0`, `> 0`). Lets the hub detect a cursor AHEAD of head
693
+ * (`'cursor_invalid'`) and skip tailed entries the client already holds by order.
694
+ */
695
+ compareCursors?(a: string, b: string): number;
696
+ /**
697
+ * Periodic access re-check, one hub-wide interval. Per subscriber `check` never
698
+ * overlaps itself. `null`, `undefined` or `false` → `revoked {reason: 'access_ended'}`
699
+ * and close; a {@link ReplayCloseVerdict} → `revoked {reason}` or `retry {reason}`
700
+ * and close; a ctx → it replaces the old one (a ctx whose `readScope` differs closes
701
+ * the stream, so the client reconnects into the right partition); a throw counts
702
+ * `revalidateFailures` and KEEPS the stream (an auth outage does not drop every
703
+ * viewer, so a revoked user keeps streaming until a check succeeds; pair with
704
+ * {@link ReplayHub.revoke} for immediate effect), up to `maxConsecutiveFailures`.
705
+ * `tick.memo` is shared by every check in one tick — cache per-user grants there.
706
+ */
707
+ revalidate?: {
708
+ everyMs: number;
709
+ check(ctx: TCtx, tick: {
710
+ memo: Map<string, unknown>;
711
+ }): Promise<TCtx | ReplayCloseVerdict | null | undefined | false>;
712
+ /**
713
+ * Throws in a row, per subscriber, after which the stream closes with
714
+ * `retry {reason: 'revalidate_failed'}` (the client reconnects at once and is
715
+ * authorized afresh) instead of streaming on unchecked. Any other outcome
716
+ * resets the count. Default: unset (a throw always keeps the stream).
717
+ */
718
+ maxConsecutiveFailures?: number;
719
+ };
720
+ /** Identity keys {@link ReplayHub.revoke} matches against. Without it, `revoke` matches nothing. */
721
+ identify?(ctx: TCtx): RevokeTarget;
722
+ /**
723
+ * Broadcast `revoke()` to every replica over `fastify.events` (needs arc's events
724
+ * plugin). The message is sealed with AES-256-GCM under a key derived from
725
+ * `secret`, so the bus, `ssePlugin` clients (its default `'*'` pattern) and webhook
726
+ * subscribers see only that a revoke happened — not who, nor the reason. Every
727
+ * replica must use the same `secret` (at least 16 characters); a message sealed
728
+ * under another secret is ignored. `type` defaults to `'arc.realtime.revoke'`.
729
+ */
730
+ revokeVia?: {
731
+ secret: string;
732
+ type?: string;
733
+ };
734
+ /** Injected timers (tests). */
735
+ timers?: ReplayHubTimers;
736
+ }
737
+ interface ReplaySubscription<TCtx> {
738
+ /** The subscriber's CURRENT ctx (revalidation may have replaced it). */
739
+ readonly ctx: TCtx;
740
+ /** `true` once the stream is closed (by the client, the hub, or a store failure at attach). */
741
+ readonly closed: boolean;
742
+ /** Detach and close the stream. Idempotent. */
743
+ close(): void;
744
+ }
745
+ interface ReplayHubStats {
746
+ subscribers: number;
747
+ partitions: number;
748
+ /** Entries replayed to reconnecting clients, cumulative. */
749
+ replayed: number;
750
+ /** `resync` frames sent, cumulative. */
751
+ resyncs: number;
752
+ /** `revoked` frames sent, cumulative. */
753
+ revoked: number;
754
+ /** Revalidate checks that threw, cumulative. */
755
+ revalidateFailures: number;
756
+ /** `retry` frames sent, cumulative. */
757
+ retried: number;
758
+ }
759
+ interface ReplayHub<TCtx> {
760
+ /**
761
+ * Attach an open stream. Writes `ready`, then the replay or one `resync`, then
762
+ * goes live. Resolves once the replay has been handed to the socket (a large
763
+ * replay to a slow reader waits for `drain`, see the module note). Never rejects
764
+ * for a store failure: the stream is closed with no frame (the client retries)
765
+ * and the returned subscription reads `closed`.
766
+ */
767
+ attach(stream: SseStream, ctx: TCtx, lastEventId: string | null): Promise<ReplaySubscription<TCtx>>;
768
+ /** Wake every partition's tail. Coalesced and single-flight per partition. */
769
+ notify(): void;
770
+ /**
771
+ * Close every local subscriber whose `identify(ctx)` matches all keys of `target`,
772
+ * after a `revoked {reason}` frame (default reason `'revoked'`). With `revokeVia`,
773
+ * also broadcast to the other replicas. Resolves with the LOCAL count.
774
+ *
775
+ * Local subscribers are closed before the broadcast, so a rejected publish still
776
+ * closed them. No record is kept: a connection authorized just before `revoke()`
777
+ * and attached just after it stays open until `revalidate` catches it — revoke the
778
+ * credential at the auth layer too.
779
+ */
780
+ revoke(target: RevokeTarget, reason?: string): Promise<number>;
781
+ stats(): ReplayHubStats;
782
+ /** Close every stream and stop all timers. Idempotent; also runs on `fastify.close()`. */
783
+ close(): void;
784
+ }
785
+ /**
786
+ * The resume cursor a client sent: the `last-event-id` header first, then the
787
+ * `queryParam` query parameter (default `'lastEventId'`; native `EventSource`
788
+ * cannot set headers on a fresh instance). `null` when absent, empty, longer than
789
+ * 256 chars, or containing control characters. Pass `queryParam: null` to read
790
+ * the header only.
791
+ */
792
+ export declare function lastEventIdOf(request: FastifyRequest, opts?: {
793
+ queryParam?: string | null;
794
+ }): string | null;
795
+ /**
796
+ * Create a replay hub. Call at boot, before `ready`: it registers the
797
+ * `fastify.sseStats()` provider, the cross-replica revoke subscription (with
798
+ * `revokeVia`) and an `onClose` hook.
799
+ *
800
+ * ```ts
801
+ * const hub = createReplayHub(app, {
802
+ * store: alertLog, // a ChangeLogStore
803
+ * readScope: (ctx) => ({ tenantId: ctx.orgId, scopes: ['alerts'] }),
804
+ * toFrame: (entry, ctx) => (sees(ctx, entry) ? { event: 'alert', data: forViewer(ctx, entry) } : null),
805
+ * isValidCursor: (c) => /^\d{16}$/.test(c),
806
+ * compareCursors: (a, b) => (a < b ? -1 : a > b ? 1 : 0),
807
+ * revalidate: { everyMs: 15_000, check: (ctx, { memo }) => stillAllowed(ctx, memo) },
808
+ * identify: (ctx) => ({ userId: ctx.userId, sessionId: ctx.sessionId }),
809
+ * revokeVia: { secret: process.env.REALTIME_REVOKE_SECRET! },
810
+ * });
811
+ * await app.events.subscribe('alert.*', () => hub.notify());
812
+ *
813
+ * app.get('/alerts/stream', async (req, reply) => {
814
+ * const ctx = await authorize(req); // every gate BEFORE the hijack
815
+ * const stream = openSseStream(req, reply);
816
+ * await hub.attach(stream, ctx, lastEventIdOf(req));
817
+ * });
818
+ * ```
819
+ */
820
+ export declare function createReplayHub<TDoc = unknown, TCtx = unknown>(fastify: FastifyInstance, options: ReplayHubOptions<TDoc, TCtx>): ReplayHub<TCtx>;
586
821
  interface JsonSchema {
587
822
  /**
588
823
  * Optional because JSON Schema allows top-level combinator-only schemas
@@ -1202,36 +1437,6 @@ export declare function registerShutdownParticipant(fastify: FastifyInstance, pa
1202
1437
  * ```
1203
1438
  */
1204
1439
  export declare function simpleEqualityMatcher(item: unknown, filters: Record<string, unknown>): boolean;
1205
- interface SseStreamOptions {
1206
- /** Heartbeat comment interval in ms (default: 30000). */
1207
- heartbeatMs?: number;
1208
- /**
1209
- * Reconnection-delay hint written once at connect as the standard SSE
1210
- * `retry:` field (WHATWG EventSource honors it natively). Omit to send
1211
- * no hint (browser default ~3s).
1212
- */
1213
- retryMs?: number;
1214
- }
1215
- interface SseStream {
1216
- /**
1217
- * Write one SSE frame. `id` (optional) becomes the standard SSE `id:`
1218
- * field — clients receive it as `lastEventId` (WHATWG), enabling
1219
- * client-side dedup/resume bookkeeping even when the server keeps no
1220
- * replay log. Returns `false` when the connection was destroyed
1221
- * (backpressure) — the stream is already cleaned up; stop writing.
1222
- */
1223
- write(eventName: string, data: string, id?: string): boolean;
1224
- /** Idempotent teardown: heartbeat cleared, cleanups run, socket ended. */
1225
- close(): void;
1226
- /** Register teardown work (unsubscribes etc.) — runs exactly once. */
1227
- onCleanup(fn: () => void): void;
1228
- }
1229
- /**
1230
- * Take over the reply socket and open an SSE stream. Call ONLY after every
1231
- * gate (auth, permissions, validation) has passed — after `hijack()` no
1232
- * JSON error can be sent.
1233
- */
1234
- export declare function openSseStream(request: FastifyRequest, reply: FastifyReply, options?: SseStreamOptions): SseStream;
1235
1440
  /**
1236
1441
  * State Machine Utility
1237
1442
  *
@@ -1469,4 +1674,4 @@ interface EventsDecorator {
1469
1674
  export declare function hasEvents(instance: FastifyInstance): instance is FastifyInstance & {
1470
1675
  events: EventsDecorator;
1471
1676
  };
1472
- export { type AnyAsyncFn, ArcError, type ArcHeaders, type ArcQueryParserOptions, type CircuitBreakerOptions, type CircuitBreakerRedisLike, type CircuitBreakerSharedState, type CircuitBreakerStats, type CompensationDefinition, type CompensationError, type CompensationHooks, type CompensationResult, type CompensationStep, ConflictError, type ErrorOptions, type EventsDecorator, type FilterDialect, ForbiddenError, type Guard, type GuardConfig, type JsonSchema, type JsonSchemaTarget, NotFoundError, OrgAccessDeniedError, OrgRequiredError, type PipeUIMessageStreamOptions, RateLimitError, type RedisCircuitBreakerStateOptions, type RuntimeCapabilityDeclaration, type SchemaIo, ServiceUnavailableError, type ShutdownParticipant, type SseStream, type SseStreamOptions, type StateMachine, type TransitionConfig, UnauthorizedError, type UnconvertibleMode, ValidationError, createDomainError, createError, errorContractSchema, getHeader, getUserId, getUserRoles, isArcError, normalizeRoles, requireSingleHeaderValue };
1677
+ export { type AnyAsyncFn, ArcError, type ArcHeaders, type ArcQueryParserOptions, type CircuitBreakerOptions, type CircuitBreakerRedisLike, type CircuitBreakerSharedState, type CircuitBreakerStats, type CompensationDefinition, type CompensationError, type CompensationHooks, type CompensationResult, type CompensationStep, ConflictError, type ErrorOptions, type EventsDecorator, type FilterDialect, ForbiddenError, type Guard, type GuardConfig, type JsonSchema, type JsonSchemaTarget, NotFoundError, OrgAccessDeniedError, OrgRequiredError, type PipeUIMessageStreamOptions, RateLimitError, type ReadyFrame, type RedisCircuitBreakerStateOptions, type ReplayCloseVerdict, type ReplayHub, type ReplayHubOptions, type ReplayHubStats, type ReplayHubTimers, type ReplayReadScope, type ReplaySubscription, type ResyncFrame, type ResyncReason, type RetryFrame, type RevokeTarget, type RevokedFrame, type RuntimeCapabilityDeclaration, type SSEStats, SSE_DEFAULT_DRAIN_TIMEOUT_MS, SSE_DEFAULT_MAX_BUFFERED_BYTES, type SchemaIo, ServiceUnavailableError, type ShutdownParticipant, type SseConnectionGauge, type SseStream, type SseStreamOptions, type StateMachine, type StreamFrameName, type TransitionConfig, UnauthorizedError, type UnconvertibleMode, ValidationError, createDomainError, createError, createSseConnectionGauge, errorContractSchema, getHeader, getUserId, getUserRoles, isArcError, normalizeRoles, openSseStream, registerSseStats, requireSingleHeaderValue };
@@ -1,13 +1,13 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { a as OrgAccessDeniedError, c as ServiceUnavailableError, d as createDomainError, f as createError, i as NotFoundError, l as UnauthorizedError, n as ConflictError, o as OrgRequiredError, p as isArcError, r as ForbiddenError, s as RateLimitError, t as ArcError, u as ValidationError } from "../errors-DyY48oRi.mjs";
3
- import { t as simpleEqualityMatcher } from "../simpleEqualityMatcher-CaCS09fh.mjs";
4
- import { n as requireSingleHeaderValue, t as getHeader } from "../headers-CHSOqpcY.mjs";
5
- import { n as getUserRoles, r as normalizeRoles, t as getUserId } from "../userHelpers-N-k-8dNF.mjs";
6
- import { C as paginationSchema, D as createQueryParser, E as ArcQueryParser, O as MONGO_DIALECT, S as offsetListResponse, T as responses, _ as errorContractSchema, a as defineCompensation, b as keysetListResponse, c as CircuitBreaker, d as CircuitState, f as createCircuitBreaker, g as deleteResponse, h as bareListResponse, i as defineErrorMapper, k as NEUTRAL_DIALECT, l as CircuitBreakerError, m as aggregateListResponse, n as handleRaw, o as withCompensation, p as createCircuitBreakerRegistry, r as defineGuard, s as RedisCircuitBreakerState, t as createStateMachine, u as CircuitBreakerRegistry, v as getDefaultCrudSchemas, w as queryParams, x as listResponse, y as getListQueryParams } from "../utils-C7w_RVlx.mjs";
7
- import { a as isZodSchema, i as isJsonSchema, n as convertRouteSchema, o as toJsonSchema, t as convertOpenApiSchemas } from "../schemaConverter-CIwB5wPO.mjs";
8
- import { a as promoteStreamTokenToHeader, i as pipeUIMessageStreamToReply, n as forwardedStreamHeaders, r as isReadableStream, t as UI_MESSAGE_STREAM_HEADERS } from "../streaming-CPChx3A7.mjs";
9
- import { n as declareRuntimeCapability } from "../runtimeCapabilities-ClWr60El.mjs";
10
- import { i as runAdmittedWork, r as registerShutdownParticipant } from "../shutdown-Bi19vH0z.mjs";
11
- import { t as openSseStream } from "../sseStream-qSa-F2Qm.mjs";
12
- import { t as hasEvents } from "../typeGuards-DNlpASzd.mjs";
13
- export { ArcError, ArcQueryParser, CircuitBreaker, CircuitBreakerError, CircuitBreakerRegistry, CircuitState, ConflictError, ForbiddenError, MONGO_DIALECT, NEUTRAL_DIALECT, NotFoundError, OrgAccessDeniedError, OrgRequiredError, RateLimitError, RedisCircuitBreakerState, ServiceUnavailableError, UI_MESSAGE_STREAM_HEADERS, UnauthorizedError, ValidationError, aggregateListResponse, bareListResponse, convertOpenApiSchemas, convertRouteSchema, createCircuitBreaker, createCircuitBreakerRegistry, createDomainError, createError, createQueryParser, createStateMachine, declareRuntimeCapability, defineCompensation, defineErrorMapper, defineGuard, deleteResponse, errorContractSchema, forwardedStreamHeaders, getDefaultCrudSchemas, getHeader, getListQueryParams, getUserId, getUserRoles, handleRaw, hasEvents, isArcError, isJsonSchema, isReadableStream, isZodSchema, keysetListResponse, listResponse, normalizeRoles, offsetListResponse, openSseStream, paginationSchema, pipeUIMessageStreamToReply, promoteStreamTokenToHeader, queryParams, registerShutdownParticipant, requireSingleHeaderValue, responses, runAdmittedWork, simpleEqualityMatcher, toJsonSchema, withCompensation };
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { a as OrgAccessDeniedError, c as ServiceUnavailableError, d as createDomainError, f as createError, i as NotFoundError, l as UnauthorizedError, n as ConflictError, o as OrgRequiredError, p as isArcError, r as ForbiddenError, s as RateLimitError, t as ArcError, u as ValidationError } from "../errors-BpYV859Y.mjs";
3
+ import { n as simpleEqualityMatcher, t as STREAM_FRAMES } from "../streamFrames-B3ZJfI02.mjs";
4
+ import { n as requireSingleHeaderValue, t as getHeader } from "../headers-D4bncIOf.mjs";
5
+ import { n as getUserRoles, r as normalizeRoles, t as getUserId } from "../userHelpers-CBKx3XJN.mjs";
6
+ import { A as MONGO_DIALECT, C as listResponse, D as responses, E as queryParams, O as ArcQueryParser, S as keysetListResponse, T as paginationSchema, _ as bareListResponse, a as defineGuard, b as getDefaultCrudSchemas, c as withCompensation, d as CircuitBreakerError, f as CircuitBreakerRegistry, g as aggregateListResponse, h as createCircuitBreakerRegistry, i as handleRaw, j as NEUTRAL_DIALECT, k as createQueryParser, l as RedisCircuitBreakerState, m as createCircuitBreaker, n as createReplayHub, o as defineErrorMapper, p as CircuitState, r as lastEventIdOf, s as defineCompensation, t as createStateMachine, u as CircuitBreaker, v as deleteResponse, w as offsetListResponse, x as getListQueryParams, y as errorContractSchema } from "../utils--HE8R8sH.mjs";
7
+ import { a as isZodSchema, i as isJsonSchema, n as convertRouteSchema, o as toJsonSchema, t as convertOpenApiSchemas } from "../schemaConverter-cIh4oX9a.mjs";
8
+ import { a as promoteStreamTokenToHeader, i as pipeUIMessageStreamToReply, n as forwardedStreamHeaders, r as isReadableStream, t as UI_MESSAGE_STREAM_HEADERS } from "../streaming-HZr63UiM.mjs";
9
+ import { a as registerSseStats, i as createSseConnectionGauge, n as SSE_DEFAULT_MAX_BUFFERED_BYTES, r as openSseStream, t as SSE_DEFAULT_DRAIN_TIMEOUT_MS } from "../sseStream-BxQW7hPq.mjs";
10
+ import { n as declareRuntimeCapability } from "../runtimeCapabilities-BQK-GrYe.mjs";
11
+ import { i as runAdmittedWork, r as registerShutdownParticipant } from "../shutdown-BM7Q0h4B.mjs";
12
+ import { t as hasEvents } from "../typeGuards-_6nNQqgq.mjs";
13
+ export { ArcError, ArcQueryParser, CircuitBreaker, CircuitBreakerError, CircuitBreakerRegistry, CircuitState, ConflictError, ForbiddenError, MONGO_DIALECT, NEUTRAL_DIALECT, NotFoundError, OrgAccessDeniedError, OrgRequiredError, RateLimitError, RedisCircuitBreakerState, SSE_DEFAULT_DRAIN_TIMEOUT_MS, SSE_DEFAULT_MAX_BUFFERED_BYTES, STREAM_FRAMES, ServiceUnavailableError, UI_MESSAGE_STREAM_HEADERS, UnauthorizedError, ValidationError, aggregateListResponse, bareListResponse, convertOpenApiSchemas, convertRouteSchema, createCircuitBreaker, createCircuitBreakerRegistry, createDomainError, createError, createQueryParser, createReplayHub, createSseConnectionGauge, createStateMachine, declareRuntimeCapability, defineCompensation, defineErrorMapper, defineGuard, deleteResponse, errorContractSchema, forwardedStreamHeaders, getDefaultCrudSchemas, getHeader, getListQueryParams, getUserId, getUserRoles, handleRaw, hasEvents, isArcError, isJsonSchema, isReadableStream, isZodSchema, keysetListResponse, lastEventIdOf, listResponse, normalizeRoles, offsetListResponse, openSseStream, paginationSchema, pipeUIMessageStreamToReply, promoteStreamTokenToHeader, queryParams, registerShutdownParticipant, registerSseStats, requireSingleHeaderValue, responses, runAdmittedWork, simpleEqualityMatcher, toJsonSchema, withCompensation };