@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,6 +1,6 @@
1
1
 
2
2
  import { a as EventTransport, n as DomainEvent } from "../EventTransport-CYEoCJGe.mjs";
3
- import { i as createOutboxModule, r as OutboxModuleOptions } from "../outbox-module-5Mnwcycy.mjs";
3
+ import { a as createOutboxModule, i as OutboxModuleOptions } from "../outbox-module-DzW6zwWJ.mjs";
4
4
  import { FastifyPluginAsync } from "fastify";
5
5
  import { OutboxFailurePolicy, OutboxStore } from "@classytic/primitives/outbox";
6
6
  export interface WebhookSubscription {
@@ -1,7 +1,7 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { n as declareRuntimeCapability } from "../runtimeCapabilities-ClWr60El.mjs";
3
- import { r as exponentialBackoff } from "../relay-ZYvS4xyW.mjs";
4
- import { t as createOutboxModule } from "../outbox-module-C874VgBr.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { r as exponentialBackoff } from "../relay-DEIoMntZ.mjs";
3
+ import { t as createOutboxModule } from "../outbox-module-D5QABFQW.mjs";
4
+ import { n as declareRuntimeCapability } from "../runtimeCapabilities-BQK-GrYe.mjs";
5
5
  import { createHmac, timingSafeEqual } from "node:crypto";
6
6
  import fp from "fastify-plugin";
7
7
  import { createChildEvent, matchEventPattern } from "@classytic/primitives/events";
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
2
  // src/integrations/websocket-pushref-redis.ts
3
3
  /**
4
4
  * Lua script for atomic claim. Runs server-side, single-roundtrip.
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
2
  // src/integrations/websocket-redis.ts
3
3
  /**
4
4
  * Redis Pub/Sub adapter for cross-instance WebSocket broadcast.
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { n as declareRuntimeCapability } from "../runtimeCapabilities-ClWr60El.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { n as declareRuntimeCapability } from "../runtimeCapabilities-BQK-GrYe.mjs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import sjson from "secure-json-parse";
5
5
  import fp from "fastify-plugin";
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as ArcError } from "./errors-DyY48oRi.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { t as ArcError } from "./errors-BpYV859Y.mjs";
3
3
  import sjson from "secure-json-parse";
4
4
  // src/utils/jsonBody.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
2
  import { contentHash } from "@classytic/repo-core/hash";
3
3
  // src/cache/keys.ts
4
4
  /**
@@ -1,6 +1,6 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as __exportAll } from "./rolldown-runtime-BdTN42uL.mjs";
3
- import { t as arcLog } from "./logger-VyMcSmVG.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { t as __exportAll } from "./rolldown-runtime-gKJR3o-6.mjs";
3
+ import { t as arcLog } from "./logger-UbknHqHy.mjs";
4
4
  import { readdir } from "node:fs/promises";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as ResourceRegistry } from "./ResourceRegistry-BcvEJoZd.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { t as ResourceRegistry } from "./ResourceRegistry-CP-iTcKy.mjs";
3
3
  import { resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  // src/cli/utils/loadResourcesFromEntry.ts
@@ -1,2 +1,2 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- export { t as arcLog, n as configureArcLogger, r as createPinoWriter, i as runWithArcLogger } from "../logger-VyMcSmVG.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ export { t as arcLog, n as configureArcLogger, r as createPinoWriter, i as runWithArcLogger } from "../logger-UbknHqHy.mjs";
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  // src/logger/scope.ts
4
4
  /**
@@ -1,24 +1,24 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as arcLog } from "./logger-VyMcSmVG.mjs";
3
- import { i as NotFoundError, p as isArcError, t as ArcError } from "./errors-DyY48oRi.mjs";
4
- import { f as BaseController, n as normalizeActionsToRouterConfig, r as resolveActionTargetFence } from "./plugin-BJcVOX5r.mjs";
5
- import { b as isElevated, c as getOrgId, g as getUserId, x as isMember } from "./types-HFFSwF_K.mjs";
6
- import { a as resolveEffectiveRoles, t as applyFieldReadPermissions } from "./fields-rfsl26Ov.mjs";
7
- import { o as toJsonSchema } from "./schemaConverter-CIwB5wPO.mjs";
8
- import { t as buildRequestScopeProjection } from "./projection-CIUe8b59.mjs";
9
- import { l as resolvePipelineSteps, t as resolveActionPermission } from "./actionPermissions-Dha8sAz2.mjs";
10
- import { a as withoutTenantInjection, r as prepareTenantContext } from "./tenantPreparation-oqKCZQZM.mjs";
11
- import { r as evaluatePermissionDecision } from "./authorizationDecision-BZSJcPNE.mjs";
12
- import { n as declareRuntimeCapability } from "./runtimeCapabilities-ClWr60El.mjs";
13
- import { t as executePipeline } from "./pipe-DzqbsZy-.mjs";
14
- import { a as resourceRateLimitWindowMs, i as resolveResourceRateLimiter, t as createMemoryResourceRateLimiter } from "./resourceRateLimit-D1oH2obv.mjs";
15
- import { n as evictToSize, r as touch, t as assertCapacity } from "./boundedMap-o2KZDCWy.mjs";
16
- import { t as pluralize } from "./pluralize-CrCpyoZs.mjs";
17
- import { n as createIdempotencyResult, r as operationIdentity, t as resolveIdempotencyTiming } from "./timing-Dsteq59c.mjs";
18
- import { n as acquireIdempotencyKey, r as releaseIdempotencyLock } from "./acquire-D2yj6Zzl.mjs";
19
- import { r as shouldRejectAdditionalProperties, t as normalizeSchemaIR } from "./schemaIR-A0IoD05P.mjs";
20
- import { n as validateAggregations } from "./validate-Brr4b_fH.mjs";
21
- import { n as executeAggregation } from "./buildHandler-G3k59KY2.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { a as resourceRateLimitWindowMs, i as resolveResourceRateLimiter, t as createMemoryResourceRateLimiter } from "./resourceRateLimit-iSXF8rLH.mjs";
3
+ import { n as declareRuntimeCapability } from "./runtimeCapabilities-BQK-GrYe.mjs";
4
+ import { n as evictToSize, r as touch, t as assertCapacity } from "./boundedMap-C51EUUOm.mjs";
5
+ import { i as NotFoundError, p as isArcError, t as ArcError } from "./errors-BpYV859Y.mjs";
6
+ import { a as resolveActionPermission, i as shouldRejectAdditionalProperties, n as normalizeSchemaIR, p as resolvePipelineSteps, t as actionSchemaIR } from "./schemaIR-BsY4y9VP.mjs";
7
+ import { n as fieldTypesFromOpenApiSchemas } from "./fieldTypes-EFWxCkZ5.mjs";
8
+ import { f as BaseController, n as normalizeActionsToRouterConfig, r as resolveActionTargetFence } from "./plugin-CrMPYbdj.mjs";
9
+ import { a as withoutTenantInjection, r as prepareTenantContext } from "./tenantPreparation-DSlQI53c.mjs";
10
+ import { b as isElevated, c as getOrgId, g as getUserId, x as isMember } from "./types-CrOlZ4rY.mjs";
11
+ import { t as pluralize } from "./pluralize-oVIxJ4CY.mjs";
12
+ import { t as buildRequestScopeProjection } from "./projection-DowJlIto.mjs";
13
+ import { n as acquireIdempotencyKey, r as releaseIdempotencyLock } from "./acquire-CB0va87C.mjs";
14
+ import { n as createIdempotencyResult, r as operationIdentity, t as resolveIdempotencyTiming } from "./timing-Z8p-Zlw1.mjs";
15
+ import { t as arcLog } from "./logger-UbknHqHy.mjs";
16
+ import { r as evaluatePermissionDecision } from "./authorizationDecision-DHO94aV2.mjs";
17
+ import { a as resolveEffectiveRoles, t as applyFieldReadPermissions } from "./fields-CT1Erg7o.mjs";
18
+ import { n as executeAggregation } from "./buildHandler-9DuwEKvr.mjs";
19
+ import { n as validateAggregations } from "./validate-BUeE2MLR.mjs";
20
+ import { o as toJsonSchema } from "./schemaConverter-cIh4oX9a.mjs";
21
+ import { t as executePipeline } from "./pipe-B_05AgGt.mjs";
22
22
  import { ARC_ERROR_CODES, isHttpError, toErrorContract } from "@classytic/repo-core/errors";
23
23
  import { createHash, randomUUID } from "node:crypto";
24
24
  import fp from "fastify-plugin";
@@ -1358,7 +1358,7 @@ function jsonSchemaPropToZod(schema) {
1358
1358
  * format can't express strict mode natively — see [./types.ts]).
1359
1359
  */
1360
1360
  function convertActionSchemaToZod(raw) {
1361
- return schemaIRToZodShape(normalizeSchemaIR(raw));
1361
+ return schemaIRToZodShape(actionSchemaIR(raw));
1362
1362
  }
1363
1363
  /**
1364
1364
  * Build an MCP tool handler for a declarative action.
@@ -1390,7 +1390,7 @@ function createActionToolHandler(actionName, handler, permissions, resourceName,
1390
1390
  log: wiring.log
1391
1391
  }
1392
1392
  } : { tenantMiddlewares: extras?.tenantMiddlewares };
1393
- const ir = rawSchema ? normalizeSchemaIR(rawSchema) : void 0;
1393
+ const ir = rawSchema ? actionSchemaIR(rawSchema) : void 0;
1394
1394
  const strict = ir ? shouldRejectAdditionalProperties(ir) : false;
1395
1395
  const allowedBaseKeys = [...idLess ? [] : ["id"], ...parity?.keyRequired ? ["_idempotencyKey"] : []];
1396
1396
  const allowedKeys = strict && ir ? /* @__PURE__ */ new Set([...allowedBaseKeys, ...Object.keys(ir.properties)]) : void 0;
@@ -1515,7 +1515,8 @@ function buildAggregationTools(args) {
1515
1515
  repo,
1516
1516
  buildOptionsFromSession,
1517
1517
  fields,
1518
- tenantMiddlewares: args.tenantMiddlewares
1518
+ tenantMiddlewares: args.tenantMiddlewares,
1519
+ fieldTypes: args.fieldTypes
1519
1520
  })
1520
1521
  });
1521
1522
  }
@@ -1580,7 +1581,8 @@ function createAggregationToolHandler(args) {
1580
1581
  };
1581
1582
  const result = await executeAggregation(normalized, {
1582
1583
  repo,
1583
- buildOptions: () => tenantOptions
1584
+ buildOptions: () => tenantOptions,
1585
+ ...args.fieldTypes ? { fieldTypes: args.fieldTypes } : {}
1584
1586
  }, {
1585
1587
  query: filterInput,
1586
1588
  tenantOptions,
@@ -2341,7 +2343,8 @@ function resourceToTools(resource, config = {}) {
2341
2343
  buildOptionsFromSession,
2342
2344
  tenantMiddlewares: resource.middlewares?.aggregations,
2343
2345
  prefix,
2344
- fields: resource.fields
2346
+ fields: resource.fields,
2347
+ fieldTypes: fieldTypesFromOpenApiSchemas(resource._registryMeta?.openApiSchemas)
2345
2348
  }));
2346
2349
  }
2347
2350
  return tools;
@@ -1,6 +1,6 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as __exportAll } from "./rolldown-runtime-BdTN42uL.mjs";
3
- import { n as evictToSize } from "./boundedMap-o2KZDCWy.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { t as __exportAll } from "./rolldown-runtime-gKJR3o-6.mjs";
3
+ import { n as evictToSize } from "./boundedMap-C51EUUOm.mjs";
4
4
  // src/cache/memory.ts
5
5
  var memory_exports = /* @__PURE__ */ __exportAll({ MemoryCacheStore: () => MemoryCacheStore });
6
6
  /**
@@ -1,12 +1,9 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as __exportAll } from "./rolldown-runtime-BdTN42uL.mjs";
3
- import { a as MetricHistogram, i as DURATION_BUCKETS_SECONDS, o as MetricSeries, s as renderMetricSample } from "./health-ezwTHQh2.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { t as __exportAll } from "./rolldown-runtime-gKJR3o-6.mjs";
3
+ import { a as MetricHistogram, i as DURATION_BUCKETS_SECONDS, o as MetricSeries, s as renderMetricSample } from "./health-BoFxrkJE.mjs";
4
4
  import fp from "fastify-plugin";
5
5
  // src/plugins/metrics.ts
6
- var metrics_exports = /* @__PURE__ */ __exportAll({
7
- default: () => metrics_default,
8
- metricsPlugin: () => metricsPlugin
9
- });
6
+ var metrics_exports = /* @__PURE__ */ __exportAll({ default: () => metrics_default });
10
7
  var Counter = class {
11
8
  series;
12
9
  constructor(maxSeries) {
@@ -1,5 +1,5 @@
1
1
 
2
- import { A as RequestWithExtras, J as MiddlewareConfig, k as MiddlewareHandler } from "../index-Cy2-QffW.mjs";
2
+ import { A as RequestWithExtras, J as MiddlewareConfig, k as MiddlewareHandler } from "../index-DLCcLUQT.mjs";
3
3
  import { RouteHandlerMethod } from "fastify";
4
4
  interface NamedMiddleware {
5
5
  /** Unique name for debugging/introspection */
@@ -1,6 +1,6 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as CRUD_OPERATIONS } from "../constants-D-faL5SX.mjs";
3
- import { t as multipartBody } from "../multipartBody-BNgNv7r0.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { t as CRUD_OPERATIONS } from "../constants-DOnfMd7i.mjs";
3
+ import { t as multipartBody } from "../multipartBody-BdG1qbn1.mjs";
4
4
  // src/middleware/middleware.ts
5
5
  /**
6
6
  * Named Middleware — Priority-based, conditional middleware execution.
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as startRenewingLease } from "../renewingLease-DT4yLb29.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { t as startRenewingLease } from "../renewingLease-BCJpW9-u.mjs";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  // src/migrations/index.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
2
  // src/factory/module/index.ts
3
3
  /**
4
4
  * Identity helper for authoring a typed module — mirrors `defineResource`.
@@ -1,5 +1,5 @@
1
1
 
2
- import { G as CrudRouteKey, W as PresetResult } from "./index-Cy2-QffW.mjs";
2
+ import { G as CrudRouteKey, W as PresetResult } from "./index-DLCcLUQT.mjs";
3
3
  type TenantFieldSpec = {
4
4
  field: string;
5
5
  type: "org";
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
2
  import { ARC_ERROR_CODES } from "@classytic/repo-core/errors";
3
3
  import sjson from "secure-json-parse";
4
4
  // src/middleware/multipartBody.ts
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
2
  // src/utils/observeSend.ts
3
3
  /** Run `fn`, reporting whether it called `reply.send` (or the reply is already sent). */
4
4
  async function runObservingSend(reply, fn) {
@@ -1,9 +1,9 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { n as getUserRoles } from "./userHelpers-N-k-8dNF.mjs";
3
- import { n as convertRouteSchema } from "./schemaConverter-CIwB5wPO.mjs";
4
- import { t as resolveActionPermission } from "./actionPermissions-Dha8sAz2.mjs";
5
- import { t as pluralize } from "./pluralize-CrCpyoZs.mjs";
6
- import { t as buildActionBodySchema } from "./createActionRouter-DTSVv1VK.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { n as getUserRoles } from "./userHelpers-CBKx3XJN.mjs";
3
+ import { a as resolveActionPermission } from "./schemaIR-BsY4y9VP.mjs";
4
+ import { t as buildActionBodySchema } from "./createActionRouter-CpTn15dm.mjs";
5
+ import { t as pluralize } from "./pluralize-oVIxJ4CY.mjs";
6
+ import { n as convertRouteSchema } from "./schemaConverter-cIh4oX9a.mjs";
7
7
  import fp from "fastify-plugin";
8
8
  // src/docs/openapi/canonical-schemas.ts
9
9
  /**
@@ -572,7 +572,7 @@ function emitMount(paths, resource, basePath, additionalSecurity, subsetActions,
572
572
  const actionEnum = subsetActions.map((a) => a.name);
573
573
  const actionSchemas = {};
574
574
  for (const a of subsetActions) if (a.schema) actionSchemas[a.name] = a.schema;
575
- const bodySchema = buildActionBodySchema(actionEnum, actionSchemas);
575
+ const bodySchema = buildActionBodySchema(actionEnum, actionSchemas, { keepDefaults: true });
576
576
  const descLines = [
577
577
  hasId ? "Unified action endpoint for state transitions on an existing entity." : "Resource-root action endpoint (no `:id` — operates on the collection or creates new entities).",
578
578
  "",
@@ -1,6 +1,6 @@
1
1
 
2
- import { l as PermissionCheck } from "../base-HXNgPQww.mjs";
3
2
  import { n as ArcModule, u as ModuleName } from "../types-BeEJm-DV.mjs";
3
+ import { l as PermissionCheck } from "../base-HXNgPQww.mjs";
4
4
  import { OutboxStore } from "@classytic/primitives/outbox";
5
5
  /**
6
6
  * A store that can answer an operator's questions.
@@ -1,8 +1,8 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { i as NotFoundError, u as ValidationError } from "../errors-DyY48oRi.mjs";
3
- import { t as defineResource } from "../defineResource-zYCrhNaN.mjs";
4
- import { n as getModuleExports, t as defineModule } from "../module-BqPJpZ_L.mjs";
5
- import { r as readOutboxHealth } from "../health-DHvAIVmM.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { t as defineResource } from "../defineResource-BAzNu5Um.mjs";
3
+ import { r as readOutboxHealth } from "../health-DN_pUVMX.mjs";
4
+ import { n as getModuleExports, t as defineModule } from "../module-CWiqsXnh.mjs";
5
+ import { i as NotFoundError, u as ValidationError } from "../errors-BpYV859Y.mjs";
6
6
  // src/outbox-admin/module.ts
7
7
  /**
8
8
  * Strip the domain payload and the stack unless explicitly opted in.
@@ -1,10 +1,10 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as transactionContext } from "./transactionContext-C1OgH-hW.mjs";
3
- import { n as requestContext } from "./requestContext-Ct5la-SA.mjs";
4
- import { i as resolveEventTransport } from "./EventTransport-BWwg5YAU.mjs";
5
- import { t as EventOutbox } from "./relay-ZYvS4xyW.mjs";
6
- import { t as emitObserved } from "./eventPlugin-Co9sABCg.mjs";
7
- import { n as canReportHealth, r as readOutboxHealth } from "./health-DHvAIVmM.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { n as requestContext } from "./requestContext-tUgLt9Ky.mjs";
3
+ import { t as transactionContext } from "./transactionContext-DBbSTfY3.mjs";
4
+ import { i as resolveEventTransport } from "./EventTransport-DbHZK230.mjs";
5
+ import { t as emitObserved } from "./eventPlugin-D7LYtYzL.mjs";
6
+ import { n as canReportHealth, r as readOutboxHealth } from "./health-DN_pUVMX.mjs";
7
+ import { t as EventOutbox } from "./relay-DEIoMntZ.mjs";
8
8
  import { randomBytes } from "node:crypto";
9
9
  import { hostname } from "node:os";
10
10
  // src/events/outbox-module.ts
@@ -47,6 +47,9 @@ const DEFAULT_RELAY_EVERY_MS = 5e3;
47
47
  const DEFAULT_PROBE_CACHE_MS = 5e3;
48
48
  /** How often an unhealthy outbox is logged. See `health.alertEveryMs`. */
49
49
  const DEFAULT_HEALTH_ALERT_EVERY_MS = 3e5;
50
+ /** First pause after a pass that lost leases; doubles per consecutive losing pass. */
51
+ const LEASE_LOSS_BACKOFF_BASE_MS = 1e3;
52
+ const LEASE_LOSS_BACKOFF_MAX_MS = 3e4;
50
53
  /**
51
54
  * One relay identity per RELAY INSTANCE — `<name>:<hostname>:<pid>:<random>`.
52
55
  *
@@ -101,6 +104,8 @@ function mintConsumerId(name) {
101
104
  function createOutboxModule(options) {
102
105
  const name = options.name ?? "outbox";
103
106
  const relayEveryMs = options.relayEveryMs ?? DEFAULT_RELAY_EVERY_MS;
107
+ const maxPassesPerTick = options.maxPassesPerTick ?? 1;
108
+ if (!Number.isInteger(maxPassesPerTick) || maxPassesPerTick < 1) throw new Error(`Outbox module "${name}": maxPassesPerTick must be an integer >= 1, got ${String(options.maxPassesPerTick)}.`);
104
109
  const lagUnhealthyMs = (options.health === false ? void 0 : options.health?.relayLagUnhealthyMs) ?? 3e5;
105
110
  const probeCacheMs = (options.health === false ? void 0 : options.health?.probeCacheMs) ?? DEFAULT_PROBE_CACHE_MS;
106
111
  if (!Number.isFinite(probeCacheMs) || probeCacheMs < 0) throw new Error(`Outbox module "${name}": health.probeCacheMs must be a non-negative number, got ${String(probeCacheMs)}.`);
@@ -138,6 +143,8 @@ function createOutboxModule(options) {
138
143
  * depends on for exactly-once publishing.
139
144
  */
140
145
  let exports;
146
+ /** The untyped single-flight lane, built at bootstrap; the schedule runs in it too. */
147
+ let backlogLane;
141
148
  /** Passes THIS module started (nudge, schedule) that have not settled — `drain()` waits on them. */
142
149
  const inFlightPasses = /* @__PURE__ */ new Set();
143
150
  const trackPass = (pass) => {
@@ -148,6 +155,72 @@ function createOutboxModule(options) {
148
155
  pass.then(untrack, untrack);
149
156
  return pass;
150
157
  };
158
+ /**
159
+ * Up to `maxPassesPerTick` `relayBatch()` calls, continuing while the previous pass
160
+ * claimed rows AND relayed something. A pass of only failures stops the loop: those rows
161
+ * are backing off, and another pass would only re-claim the next batch into the same
162
+ * outage. A pass that claimed nothing ends it.
163
+ *
164
+ * "Fewer than `batchSize`" does NOT end it: a store may cap one claim below
165
+ * `batchSize` (a repository's page `maxLimit`, 100 by default in mongokit), and a
166
+ * clamped page would read as "backlog empty" and strand the rest until the next tick.
167
+ * The price is one empty claim after the backlog clears.
168
+ */
169
+ const relayPasses = async (relay, types) => {
170
+ if (backingOff()) return false;
171
+ let passes = 0;
172
+ for (;;) {
173
+ const r = await relay.relayBatch(types ? { types } : void 0);
174
+ passes++;
175
+ if (observeLeaseLoss(r)) return true;
176
+ if (passes >= maxPassesPerTick || !(r.attempted > 0) || r.relayed === 0) return true;
177
+ }
178
+ };
179
+ /**
180
+ * Lease-loss back-off. A pass whose ack or fail met an ownership mismatch lost
181
+ * rows to another claimant: relaying again at once only re-claims into the same
182
+ * contention. Passes pause for 1 s, doubling per consecutive losing pass up to
183
+ * 30 s, and the loss is logged ONCE per pass with counts — the default `onError`
184
+ * no longer logs it per row.
185
+ */
186
+ let leaseLossStreak = 0;
187
+ let backoffUntil = 0;
188
+ const backingOff = () => Date.now() < backoffUntil;
189
+ const observeLeaseLoss = (r) => {
190
+ const lost = r.ownershipMismatches ?? 0;
191
+ if (lost > 0) {
192
+ leaseLossStreak++;
193
+ const backoffMs = Math.min(LEASE_LOSS_BACKOFF_BASE_MS * 2 ** (leaseLossStreak - 1), LEASE_LOSS_BACKOFF_MAX_MS);
194
+ backoffUntil = Date.now() + backoffMs;
195
+ log?.warn({
196
+ marker: "OUTBOX_LEASE_LOST",
197
+ outbox: name,
198
+ ownershipMismatches: lost,
199
+ attempted: r.attempted,
200
+ relayed: r.relayed,
201
+ leaseDeferred: r.leaseDeferred ?? 0,
202
+ consecutivePasses: leaseLossStreak,
203
+ backoffMs
204
+ }, `outbox relay "${name}" lost ${lost} lease(s) to another claimant; backing off ${backoffMs} ms`);
205
+ return true;
206
+ }
207
+ if (r.attempted > 0) leaseLossStreak = 0;
208
+ return false;
209
+ };
210
+ /** A requested pass that met the back-off reruns when it ends (one timer per lane). */
211
+ const retryTimers = /* @__PURE__ */ new Set();
212
+ let closed = false;
213
+ const retryAfterBackoff = (lane, armed) => {
214
+ if (closed || armed.timer) return;
215
+ armed.timer = true;
216
+ const timer = setTimeout(() => {
217
+ retryTimers.delete(timer);
218
+ armed.timer = false;
219
+ lane.request();
220
+ }, Math.max(0, backoffUntil - Date.now()));
221
+ timer.unref?.();
222
+ retryTimers.add(timer);
223
+ };
151
224
  return {
152
225
  name,
153
226
  bootstrap: (fastify) => {
@@ -180,6 +253,13 @@ function createOutboxModule(options) {
180
253
  ...options.leaseMs !== void 0 ? { leaseMs: options.leaseMs } : {},
181
254
  consumerId: options.consumerId ?? mintConsumerId(name),
182
255
  onError: options.onError ?? ((info) => {
256
+ if (info.kind === "ownership_mismatch") {
257
+ fastify.log.debug({
258
+ kind: info.kind,
259
+ eventId: info.event?.meta.id
260
+ }, `outbox relay "${name}" lost a lease`);
261
+ return;
262
+ }
183
263
  fastify.log.error({
184
264
  err: info.error,
185
265
  kind: info.kind,
@@ -191,25 +271,52 @@ function createOutboxModule(options) {
191
271
  ...options.sessionProvider === false ? {} : { sessionProvider: options.sessionProvider ?? (() => transactionContext.get()) }
192
272
  });
193
273
  /**
194
- * One pass per burst of requests. `drainQueued` stays true from the
195
- * first request until the pass STARTS, so a request landing mid-pass
196
- * schedules the next one — a row written during a pass is never left
197
- * waiting for the interval.
274
+ * Two single-flight lanes: `backlog` (untyped nudges, the scheduled tick,
275
+ * `drain()`) and `priority` (typed nudges, so an alarm never waits behind
276
+ * a slow backlog pass). Each runs at most ONE pass at a time; a request
277
+ * during a pass queues exactly one follow-up that starts after it ends.
278
+ * Overlapping passes were the livelock: the newer one re-claimed the older
279
+ * one's expired rows, both ran the handlers, and the older ack failed.
280
+ *
281
+ * `exit` — NOT merely cosmetic. The lane's `setImmediate` preserves the
282
+ * caller's AsyncLocalStorage store, and the caller is a REQUEST (that is the
283
+ * documented use: drain the row I just committed). A pass drains whatever is
284
+ * pending, so without this every event in the batch — including rows written
285
+ * by other requests, for other tenants — dispatches inside the triggering
286
+ * request's scope: `runWorkScope` inherits it rather than opening the
287
+ * event's own, handlers read that request's `user`/`organizationId`/
288
+ * `requestScopedCache`, and a child event published from one is stamped
289
+ * with its `requestId` as `correlationId`. A relay pass belongs to no
290
+ * request; say so.
198
291
  */
199
- let drainQueued = false;
200
- const requestDrain = () => {
201
- if (drainQueued) return;
202
- drainQueued = true;
203
- let passDone = () => {};
204
- trackPass(new Promise((resolve) => passDone = resolve));
205
- setImmediate(() => {
206
- drainQueued = false;
207
- requestContext.storage.exit(() => {
208
- relay.relayBatch().catch((err) => {
209
- fastify.log.error({ err }, `outbox relay "${name}" requested drain failed`);
210
- }).finally(passDone);
211
- });
212
- });
292
+ const scopeFree = (fn) => requestContext.storage.exit(fn).catch((err) => {
293
+ fastify.log.error({ err }, `outbox relay "${name}" requested drain failed`);
294
+ });
295
+ const backlogArmed = { timer: false };
296
+ const backlog = createPassLane(() => scopeFree(async () => {
297
+ if (!await relayPasses(relay)) retryAfterBackoff(backlog, backlogArmed);
298
+ }), trackPass);
299
+ /** Types asked for by typed requests not yet taken by a priority pass. */
300
+ let typesQueued = null;
301
+ const priorityArmed = { timer: false };
302
+ const priority = createPassLane(() => scopeFree(async () => {
303
+ const typed = typesQueued ? [...typesQueued] : void 0;
304
+ typesQueued = null;
305
+ if (!typed) return;
306
+ if (!await relayPasses(relay, typed)) {
307
+ typesQueued ??= /* @__PURE__ */ new Set();
308
+ for (const t of typed) typesQueued.add(t);
309
+ retryAfterBackoff(priority, priorityArmed);
310
+ }
311
+ }), trackPass);
312
+ backlogLane = backlog;
313
+ const requestDrain = (options) => {
314
+ const types = Array.isArray(options?.types) ? options.types.filter((t) => typeof t === "string" && t.length > 0) : [];
315
+ if (types.length > 0) {
316
+ typesQueued ??= /* @__PURE__ */ new Set();
317
+ for (const t of types) typesQueued.add(t);
318
+ priority.request();
319
+ } else backlog.request();
213
320
  };
214
321
  const drain = ({ maxPasses = 100 } = {}) => requestContext.storage.exit(async () => {
215
322
  const total = {
@@ -219,15 +326,18 @@ function createOutboxModule(options) {
219
326
  deadLettered: 0,
220
327
  drained: false
221
328
  };
329
+ let deferred = false;
222
330
  while (total.passes < maxPasses) {
223
331
  if (inFlightPasses.size > 0) await Promise.allSettled([...inFlightPasses]);
224
- const r = await relay.relayBatch();
332
+ const r = await backlog.exclusive(() => relay.relayBatch());
333
+ observeLeaseLoss(r);
225
334
  total.passes++;
226
335
  total.relayed += r.relayed;
227
336
  total.publishFailed += r.publishFailed;
228
337
  total.deadLettered += r.deadLettered;
338
+ if ((r.leaseDeferred ?? 0) > 0) deferred = true;
229
339
  if (r.attempted === 0 && inFlightPasses.size === 0) {
230
- total.drained = true;
340
+ total.drained = !deferred;
231
341
  break;
232
342
  }
233
343
  }
@@ -246,6 +356,12 @@ function createOutboxModule(options) {
246
356
  };
247
357
  return exports;
248
358
  },
359
+ /** Stop back-off retries; a timer firing after close would relay into a closed store. */
360
+ onClose: () => {
361
+ closed = true;
362
+ for (const timer of retryTimers) clearTimeout(timer);
363
+ retryTimers.clear();
364
+ },
249
365
  ...options.health === false ? {} : { healthChecks: [{
250
366
  name: `${name}.relay`,
251
367
  critical: false,
@@ -261,7 +377,10 @@ function createOutboxModule(options) {
261
377
  every: relayEveryMs,
262
378
  runOnStart: options.runOnStart ?? true,
263
379
  handler: async () => {
264
- if (exports) await trackPass(exports.relay.relay());
380
+ if (exports && backlogLane) {
381
+ const relay = exports.relay;
382
+ await trackPass(backlogLane.exclusive(() => relayPasses(relay)));
383
+ }
265
384
  }
266
385
  }, ...alertEveryMs > 0 ? [{
267
386
  name: `${name}.health`,
@@ -294,4 +413,54 @@ function createOutboxModule(options) {
294
413
  }] : []]
295
414
  };
296
415
  }
416
+ /**
417
+ * `run` must not reject. A requested pass is tracked from the REQUEST, not from
418
+ * its start, so `drain()` called right after a nudge waits for that pass.
419
+ */
420
+ function createPassLane(run, track) {
421
+ let busy;
422
+ /** Resolves the tracked promise of the queued (not yet started) pass. */
423
+ let queuedDone;
424
+ let scheduled = false;
425
+ const schedule = () => {
426
+ if (scheduled) return;
427
+ scheduled = true;
428
+ setImmediate(start);
429
+ };
430
+ const release = () => {
431
+ busy = void 0;
432
+ if (queuedDone) schedule();
433
+ };
434
+ function start() {
435
+ scheduled = false;
436
+ if (busy !== void 0 || !queuedDone) return;
437
+ const done = queuedDone;
438
+ queuedDone = void 0;
439
+ busy = run().finally(() => {
440
+ done();
441
+ release();
442
+ });
443
+ }
444
+ return {
445
+ request() {
446
+ if (!queuedDone) {
447
+ let resolve = () => {};
448
+ track(new Promise((r) => resolve = r));
449
+ queuedDone = resolve;
450
+ }
451
+ if (busy === void 0) schedule();
452
+ },
453
+ async exclusive(fn) {
454
+ while (busy !== void 0) await busy.catch(() => {});
455
+ let done = () => {};
456
+ busy = new Promise((r) => done = r);
457
+ try {
458
+ return await fn();
459
+ } finally {
460
+ done();
461
+ release();
462
+ }
463
+ }
464
+ };
465
+ }
297
466
  export { createOutboxModule as t };