@classytic/arc 2.31.0 → 2.33.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 (194) hide show
  1. package/README.md +1 -1
  2. package/bin/arc.js +58 -17
  3. package/dist/{BaseController-De7GqHck.mjs → BaseController-CaQC5EXX.mjs} +298 -35
  4. package/dist/{EventTransport-2uVV34WU.d.mts → EventTransport-BEVP50ka.d.mts} +16 -0
  5. package/dist/{EventTransport-9mlTgqzE.mjs → EventTransport-tq4CEB-q.mjs} +39 -2
  6. package/dist/{HookSystem-BcmPyq5I.mjs → HookSystem-DqXkMXkB.mjs} +2 -2
  7. package/dist/{ResourceRegistry-qq0mn2s9.mjs → ResourceRegistry-DoALUlOO.mjs} +18 -15
  8. package/dist/{actionPermissions-BE5NwaQk.mjs → actionPermissions-CUeCmpUd.mjs} +1 -1
  9. package/dist/audit/index.d.mts +2 -2
  10. package/dist/audit/index.mjs +2 -2
  11. package/dist/auth/audit.mjs +1 -1
  12. package/dist/auth/index.d.mts +2 -2
  13. package/dist/auth/index.mjs +44 -11
  14. package/dist/auth/redis-session.mjs +1 -1
  15. package/dist/{authorizationDecision-ChvUQGG1.mjs → authorizationDecision-B3mP_QTy.mjs} +2 -2
  16. package/dist/{types-B7XeLEgK.d.mts → base-Csjc2oF-.d.mts} +74 -74
  17. package/dist/{buildHandler-CDrCJzmB.mjs → buildHandler-DLE9xX-V.mjs} +6 -5
  18. package/dist/cache/index.mjs +4 -4
  19. package/dist/{caching-BFHA6Scf.mjs → caching-BcGmvnHh.mjs} +2 -2
  20. package/dist/cleanup/index.d.mts +52 -18
  21. package/dist/cleanup/index.mjs +281 -32
  22. package/dist/cli/commands/describe.d.mts +1 -1
  23. package/dist/cli/commands/describe.mjs +4 -6
  24. package/dist/cli/commands/docs.mjs +3 -3
  25. package/dist/cli/commands/doctor.mjs +1 -1
  26. package/dist/cli/commands/generate.mjs +2 -2
  27. package/dist/cli/commands/init.mjs +2 -2
  28. package/dist/cli/commands/introspect.mjs +2 -2
  29. package/dist/cli/index.mjs +3 -3
  30. package/dist/{constants-D3Dv4LAV.mjs → constants-BxCoxmiN.mjs} +1 -1
  31. package/dist/context/index.mjs +3 -3
  32. package/dist/core/index.d.mts +2 -2
  33. package/dist/core/index.mjs +7 -7
  34. package/dist/{core-BGpIxINN.mjs → core-dxhcHhUD.mjs} +3 -3
  35. package/dist/{createActionRouter-CDXEdasl.mjs → createActionRouter-DVpoA0do.mjs} +14 -11
  36. package/dist/{createAggregationRouter-KrQDzx-k.mjs → createAggregationRouter-B_B48JZ-.mjs} +10 -8
  37. package/dist/{createApp-Df89BEni.mjs → createApp-CLGegqiG.mjs} +287 -62
  38. package/dist/{defineAggregation-DbPPS8RI.mjs → defineAggregation-Nv-DwfOf.mjs} +1 -1
  39. package/dist/{defineResource-Bv6EtN1x.mjs → defineResource-DR9vsUYy.mjs} +318 -35
  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-D2l1mh4g.mjs → elevation-B0tlY8y1.mjs} +4 -4
  44. package/dist/encryption/index.mjs +5 -4
  45. package/dist/{errorHandler-C5NeD6bT.mjs → errorHandler-C7xBqHsI.mjs} +42 -5
  46. package/dist/{errorHandler-CpYUJmPA.d.mts → errorHandler-DI5AN2b5.d.mts} +14 -3
  47. package/dist/{errors-Cj42AntO.mjs → errors-Cd_yy7aW.mjs} +1 -1
  48. package/dist/{eventPlugin-GF5nnBIq.d.mts → eventPlugin-DSNEZWfV.d.mts} +29 -1
  49. package/dist/{eventPlugin-CkffEihm.mjs → eventPlugin-Dar8qRaj.mjs} +68 -11
  50. package/dist/events/index.d.mts +18 -297
  51. package/dist/events/index.mjs +7 -758
  52. package/dist/events/transports/redis-stream-entry.d.mts +1 -1
  53. package/dist/events/transports/redis-stream-entry.mjs +14 -10
  54. package/dist/events/transports/redis.d.mts +1 -1
  55. package/dist/events/transports/redis.mjs +1 -1
  56. package/dist/factory/index.d.mts +20 -5
  57. package/dist/factory/index.mjs +131 -8
  58. package/dist/fastify-augmentation-DVsTAy6X.d.mts +179 -0
  59. package/dist/{fields-CB5Cuzk9.mjs → fields-CojeUkS4.mjs} +6 -11
  60. package/dist/{generate-EcA6ui4i.mjs → generate-DiB0nHPR.mjs} +2 -2
  61. package/dist/{headers-3zvE0rM3.mjs → headers-CveNO9gR.mjs} +2 -2
  62. package/dist/{health-DjZYjM7H.mjs → health-CasG2A28.mjs} +1 -1
  63. package/dist/hooks/index.d.mts +1 -1
  64. package/dist/hooks/index.mjs +2 -2
  65. package/dist/idempotency/index.d.mts +45 -1
  66. package/dist/idempotency/index.mjs +95 -11
  67. package/dist/idempotency/redis.mjs +1 -1
  68. package/dist/{index-CEJNZFtX.d.mts → index-B-DvUzsr.d.mts} +82 -3
  69. package/dist/{index-CpzxqePp.d.mts → index-BcR2bFZQ.d.mts} +707 -373
  70. package/dist/{index-Bc2ox8_U.d.mts → index-Brin0ODU.d.mts} +4 -4
  71. package/dist/{index-CFThn1K9.d.mts → index-C5NnMEKF.d.mts} +70 -4
  72. package/dist/{index-C-481Zf2.d.mts → index-ugr1tQlW.d.mts} +17 -1
  73. package/dist/index.d.mts +6 -6
  74. package/dist/index.mjs +11 -11
  75. package/dist/{init-BEiNZBsJ.mjs → init-mdJ-v4Xp.mjs} +24 -16
  76. package/dist/integrations/event-gateway.d.mts +1 -1
  77. package/dist/integrations/event-gateway.mjs +2 -2
  78. package/dist/integrations/index.d.mts +2 -2
  79. package/dist/integrations/index.mjs +1 -1
  80. package/dist/integrations/jobs/index.d.mts +1 -1
  81. package/dist/integrations/jobs/index.mjs +100 -98
  82. package/dist/integrations/mcp/index.d.mts +12 -3
  83. package/dist/integrations/mcp/index.mjs +2 -2
  84. package/dist/integrations/mcp/testing.d.mts +1 -1
  85. package/dist/integrations/mcp/testing.mjs +2 -2
  86. package/dist/integrations/streamline.mjs +3 -3
  87. package/dist/integrations/webhooks.d.mts +124 -1
  88. package/dist/integrations/webhooks.mjs +180 -2
  89. package/dist/integrations/websocket-pushref-redis.mjs +1 -1
  90. package/dist/integrations/websocket-redis.mjs +1 -1
  91. package/dist/integrations/websocket.mjs +38 -35
  92. package/dist/{interface-DYzM0q-u.mjs → interface-DznJrm9R.mjs} +1 -1
  93. package/dist/{jsonBody-BYbLDi5D.mjs → jsonBody-CfGH-GxO.mjs} +2 -2
  94. package/dist/{keys-C0_pa1tY.mjs → keys-WeKvY1dE.mjs} +1 -1
  95. package/dist/{loadResources-yawi9tAE.mjs → loadResources-Bj-aSsXi.mjs} +4 -3
  96. package/dist/{loadResourcesFromEntry-BAjYZonx.mjs → loadResourcesFromEntry-DwaxNcE2.mjs} +2 -2
  97. package/dist/logger/index.mjs +1 -1
  98. package/dist/{mcpPlugin-B_es0hiF.mjs → mcpPlugin-aJg5TqHi.mjs} +76 -36
  99. package/dist/{memory-DR6wpa9F.mjs → memory-qYSB7rMQ.mjs} +5 -5
  100. package/dist/{metrics-CUdw_wLB.mjs → metrics-D7uchLjN.mjs} +2 -2
  101. package/dist/middleware/index.d.mts +1 -1
  102. package/dist/middleware/index.mjs +3 -3
  103. package/dist/migrations/index.mjs +3 -3
  104. package/dist/{module-0pFJA6YW.mjs → module-CwKsgZXp.mjs} +1 -1
  105. package/dist/{multipartBody-wOgj_fnj.mjs → multipartBody-4w-S3-PU.mjs} +3 -3
  106. package/dist/{openapi-B2L4js1v.mjs → openapi-BN5cQaO2.mjs} +6 -6
  107. package/dist/outbox-admin/index.d.mts +85 -0
  108. package/dist/outbox-admin/index.mjs +115 -0
  109. package/dist/outbox-module-CXB79bvt.mjs +839 -0
  110. package/dist/outbox-module-D-VFq37T.d.mts +368 -0
  111. package/dist/permissions/index.d.mts +3 -3
  112. package/dist/permissions/index.mjs +6 -6
  113. package/dist/{permissions-L--QDAir.mjs → permissions-BAfwgBxc.mjs} +120 -8
  114. package/dist/{pipe-DRDNsI2T.mjs → pipe-BzzoEhHj.mjs} +3 -5
  115. package/dist/pipeline/index.d.mts +1 -1
  116. package/dist/pipeline/index.mjs +2 -2
  117. package/dist/{pipeline-UPQFatit.mjs → pipeline-q69DZzgG.mjs} +17 -15
  118. package/dist/plugins/index.d.mts +6 -6
  119. package/dist/plugins/index.mjs +16 -16
  120. package/dist/plugins/response-cache.mjs +2 -2
  121. package/dist/plugins/tracing-entry.mjs +2 -2
  122. package/dist/{pluralize-O0FZgESl.mjs → pluralize-B7xf8qZF.mjs} +1 -1
  123. package/dist/{preloadResources-Dz6BjzM6.mjs → preloadResources-BkyqeTDz.mjs} +1 -1
  124. package/dist/{preloadResources-CyoJMSiO.d.mts → preloadResources-g07ldtzh.d.mts} +30 -7
  125. package/dist/presets/filesUpload.d.mts +2 -2
  126. package/dist/presets/filesUpload.mjs +6 -6
  127. package/dist/presets/index.d.mts +2 -2
  128. package/dist/presets/index.mjs +2 -2
  129. package/dist/presets/multiTenant.d.mts +1 -1
  130. package/dist/presets/multiTenant.mjs +3 -3
  131. package/dist/presets/search.d.mts +2 -2
  132. package/dist/presets/search.mjs +2 -2
  133. package/dist/{presets-C4-g4_4P.mjs → presets-D-h0uWtP.mjs} +6 -5
  134. package/dist/projection-BKM0Ui-s.mjs +42 -0
  135. package/dist/{queryCachePlugin-BZr8v46E.mjs → queryCachePlugin-DhsZ0ZIc.mjs} +50 -8
  136. package/dist/{rateLimit-CMPY5Qms.mjs → rateLimit-D4-ASwsI.mjs} +2 -2
  137. package/dist/{rateLimitKey-Dn5JNmkj.mjs → rateLimitKey-XngqVNEV.mjs} +1 -1
  138. package/dist/{realtime-C5NoxWFY.mjs → realtime-CTkv3O59.mjs} +10 -10
  139. package/dist/{redis-stream-qN6A-RFv.d.mts → redis-stream-mwLWlfHG.d.mts} +1 -1
  140. package/dist/{registerRoute-CBN84fc7.mjs → registerRoute-DNnd3vkz.mjs} +10 -8
  141. package/dist/registry/index.d.mts +3 -3
  142. package/dist/registry/index.mjs +3 -3
  143. package/dist/{registry-4213U4zb.mjs → registry-CLxCR5LF.mjs} +2 -2
  144. package/dist/{renewingLease-Dll8mGgc.mjs → renewingLease-BnWtbA2U.mjs} +1 -1
  145. package/dist/{replyHelpers-DIiZKGUt.mjs → replyHelpers-BSBVCwL3.mjs} +2 -2
  146. package/dist/{repositoryFilter-f9eAfq_l.mjs → repositoryFilter-DKny7PDn.mjs} +1 -1
  147. package/dist/{requestContext-2TxXOJ7T.mjs → requestContext-uYE35JxI.mjs} +1 -1
  148. package/dist/{rolldown-runtime-CUsjNX9R.mjs → rolldown-runtime-DNg-KNCk.mjs} +1 -1
  149. package/dist/runtimeCapabilities-Dm88DaTW.mjs +49 -0
  150. package/dist/{schedules-DdtlICTf.mjs → schedules-CAcZgia0.mjs} +3 -3
  151. package/dist/{schemaConverter-D--wdJM-.mjs → schemaConverter-XH1RZRyu.mjs} +1 -1
  152. package/dist/{schemaIR-Bm2enbnh.mjs → schemaIR-CDvclAew.mjs} +2 -2
  153. package/dist/schemas/index.mjs +1 -1
  154. package/dist/scim/index.mjs +2 -2
  155. package/dist/scope/index.mjs +5 -5
  156. package/dist/{scope-DHx5Fous.mjs → scope-BaWcqBvr.mjs} +4 -4
  157. package/dist/{simpleEqualityMatcher-DjQJ7FKA.mjs → simpleEqualityMatcher-Se8VrsaP.mjs} +1 -1
  158. package/dist/{sse-CUTo9y0X.mjs → sse-Cf0jUHsh.mjs} +7 -6
  159. package/dist/{sseStream-B_5XcVVd.mjs → sseStream-Bvpi-UXQ.mjs} +2 -2
  160. package/dist/{store-helpers-D1MP_gRG.mjs → store-helpers-B88p99Z2.mjs} +1 -1
  161. package/dist/{streaming-PSZwi8JV.mjs → streaming-DsT1B5zJ.mjs} +1 -1
  162. package/dist/{subscribe-helpers-C0Tb2aUp.mjs → subscribe-helpers-CLIOHsOK.mjs} +2 -2
  163. package/dist/sync/changelog.mjs +1 -1
  164. package/dist/testing/cleanupStoreContract.d.mts +1 -1
  165. package/dist/testing/cleanupStoreContract.mjs +12 -6
  166. package/dist/testing/index.d.mts +52 -13
  167. package/dist/testing/index.mjs +110 -40
  168. package/dist/testing/outboxStoreContract.d.mts +11 -2
  169. package/dist/testing/outboxStoreContract.mjs +110 -21
  170. package/dist/testing/storageContract.mjs +11 -6
  171. package/dist/{transactionContext-dAfBVUrk.mjs → transactionContext-BYtWnwAS.mjs} +1 -1
  172. package/dist/{typeGuards-B0ryPo3I.mjs → typeGuards-jjKJDN13.mjs} +1 -1
  173. package/dist/types/index.d.mts +3 -3
  174. package/dist/types/index.mjs +1 -1
  175. package/dist/types/storage.mjs +1 -1
  176. package/dist/{types-CBgvkp8O.d.mts → types-BcTumAz_.d.mts} +128 -18
  177. package/dist/{types-CwcUQ610.d.mts → types-BfC83KsP.d.mts} +15 -1
  178. package/dist/{types-Cys0ko9Z.mjs → types-CoqIRrkY.mjs} +4 -4
  179. package/dist/{types-C4QE8qnm.d.mts → types-DVLddu2q.d.mts} +144 -1
  180. package/dist/usage/index.d.mts +1 -1
  181. package/dist/usage/index.mjs +0 -0
  182. package/dist/{userHelpers-ChYJ6CdK.mjs → userHelpers-CWF5pbZD.mjs} +1 -1
  183. package/dist/utils/index.d.mts +57 -5
  184. package/dist/utils/index.mjs +12 -11
  185. package/dist/{utils-vL8BrDE2.mjs → utils-h1V_sT-t.mjs} +38 -7
  186. package/dist/{validate-_KbifpHF.mjs → validate-CdQlz52F.mjs} +2 -2
  187. package/dist/{versioning-D_rhHfZm.d.mts → versioning-DEs-_hFi.d.mts} +1 -1
  188. package/dist/{versioning-CHDTor3P.mjs → versioning-rZbyLVD-.mjs} +4 -4
  189. package/package.json +31 -20
  190. package/skills/arc/SKILL.md +96 -4
  191. package/skills/arc/references/api-reference.md +19 -0
  192. package/skills/arc/references/production.md +2 -2
  193. package/dist/fastify-augmentation-zh0_AYHa.d.mts +0 -85
  194. package/dist/projection-BHw6xlOQ.mjs +0 -18
@@ -0,0 +1,368 @@
1
+
2
+ import { a as EventTransport, n as DomainEvent, t as DeadLetteredEvent } from "./EventTransport-BEVP50ka.mjs";
3
+ import { t as ArcModule } from "./types-BcTumAz_.mjs";
4
+ import { FastifyInstance } from "fastify";
5
+ import { MemoryOutboxStore } from "@classytic/primitives/memory-outbox";
6
+ import { OutboxFailurePolicy, OutboxStore, OutboxWriteOptions } from "@classytic/primitives/outbox";
7
+ import { RepositoryLike } from "@classytic/repo-core/adapter";
8
+ //#region src/events/outbox/relay.d.ts
9
+ /** Reason codes passed to {@link EventOutboxOptions.onError}. */
10
+ type OutboxRelayErrorKind = "publish_failed" | "acknowledge_failed" | "fail_failed" | "ownership_mismatch" | "malformed_event";
11
+ /**
12
+ * Rich per-batch outcome returned by {@link EventOutbox.relayBatch}.
13
+ *
14
+ * Useful for operational dashboards, alerting thresholds, and test assertions.
15
+ * The simpler {@link EventOutbox.relay} returns just the `relayed` count for
16
+ * backward compatibility.
17
+ */
18
+ interface RelayResult {
19
+ /** Number of events successfully published AND acknowledged */
20
+ readonly relayed: number;
21
+ /** Number of events claimed and attempted in this batch */
22
+ readonly attempted: number;
23
+ /** Number of publish failures (transport rejected the event) */
24
+ readonly publishFailed: number;
25
+ /** Number of acknowledge failures after successful publish (at-least-once replay risk) */
26
+ readonly ackFailed: number;
27
+ /** Number of ownership mismatches (our lease expired mid-flight) */
28
+ readonly ownershipMismatches: number;
29
+ /** Number of malformed events encountered (aborts the batch) */
30
+ readonly malformed: number;
31
+ /** Number of fail() calls that themselves threw (store bugs / contention) */
32
+ readonly failHookErrors: number;
33
+ /**
34
+ * Number of events moved to dead-letter state this batch via the configured
35
+ * {@link OutboxFailurePolicy}. Zero when no policy is set or no failure
36
+ * tripped the `deadLetter` branch.
37
+ */
38
+ readonly deadLettered: number;
39
+ /** Whether `publishMany` was used (true) or per-event `publish` (false) */
40
+ readonly usedPublishMany: boolean;
41
+ /**
42
+ * Wall-clock ms spent claiming this batch from the store. With the
43
+ * portable repository adapter this is ~2 DB round trips; a persistently
44
+ * high value under low batch sizes points at store latency, not volume.
45
+ */
46
+ readonly claimMs?: number;
47
+ /** Wall-clock ms spent publishing + acknowledging the batch. */
48
+ readonly publishMs?: number;
49
+ }
50
+ /**
51
+ * Called by {@link EventOutbox.relay} when a non-fatal error occurs during
52
+ * a batch. Used for logging and metrics. Must not throw.
53
+ */
54
+ type OutboxRelayErrorHandler = (info: {
55
+ readonly kind: OutboxRelayErrorKind;
56
+ readonly event?: DomainEvent;
57
+ readonly error: Error;
58
+ }) => void;
59
+ interface EventOutboxOptions {
60
+ /**
61
+ * Repository managing the outbox collection. Arc consumes it directly —
62
+ * no wrapper classes. Requires `create`, `getOne`, `findAll`,
63
+ * `deleteMany`, and `findOneAndUpdate` from `RepositoryLike` (mongokit
64
+ * ≥3.8 satisfies all of these). Takes precedence over `store` when both
65
+ * are passed.
66
+ *
67
+ * Use this for the common path where the outbox lives in your primary
68
+ * database. Use `store` for non-repository backends (memory / custom).
69
+ */
70
+ readonly repository?: RepositoryLike;
71
+ /**
72
+ * Non-repository outbox store. Use when your backend isn't a repository
73
+ * (memory for tests, Kafka, DynamoDB, custom). Ignored if `repository`
74
+ * is also passed.
75
+ */
76
+ readonly store?: OutboxStore;
77
+ /** Transport to relay events to (optional — can relay later) */
78
+ readonly transport?: EventTransport;
79
+ /** Max events per relay batch (default: 100) */
80
+ readonly batchSize?: number;
81
+ /**
82
+ * Unique identifier for this relay worker. Used when the store supports
83
+ * `claimPending`/`fail` to enforce lease ownership. Defaults to a random ID.
84
+ */
85
+ readonly consumerId?: string;
86
+ /**
87
+ * Lease duration in ms for claimed events. Only used when the store
88
+ * supports `claimPending`. Default: 30 seconds.
89
+ */
90
+ readonly leaseMs?: number;
91
+ /**
92
+ * Callback for non-fatal errors during relay: publish failures,
93
+ * ownership mismatches, ack/fail errors, malformed events. Use this for
94
+ * logging and metrics. Must not throw — exceptions are swallowed.
95
+ */
96
+ readonly onError?: OutboxRelayErrorHandler;
97
+ /**
98
+ * Enable {@link EventTransport.publishMany} when the transport implements it.
99
+ * Default: `true`. Set to `false` to force per-event `publish()` — useful
100
+ * for transports where strict event-order observability matters more than
101
+ * throughput, or to debug batch-specific issues.
102
+ */
103
+ readonly usePublishMany?: boolean;
104
+ /**
105
+ * Retry/DLQ decision policy. When set, {@link EventOutbox.relayBatch}
106
+ * invokes this on every failure and uses the returned options for
107
+ * `store.fail()`. Centralises the "after N fails, dead-letter" rule so
108
+ * apps don't recompute `exponentialBackoff` + escalation thresholds on
109
+ * every failure site.
110
+ *
111
+ * Without a policy, `fail()` is called with `{}` (immediate re-visibility
112
+ * on next poll) — legacy behaviour, unchanged.
113
+ */
114
+ readonly failurePolicy?: OutboxFailurePolicy;
115
+ /**
116
+ * Unit-of-Work session provider (AsyncLocalStorage integration).
117
+ *
118
+ * When set, `store()` calls this to get the active DB session and uses
119
+ * it as `OutboxWriteOptions.session` — **only when the caller has not
120
+ * already passed an explicit `options.session`**. This eliminates the
121
+ * boilerplate of threading the transaction handle from the controller
122
+ * through every service layer down to the outbox call site.
123
+ *
124
+ * Wire up with arc's `transactionContext`:
125
+ * ```typescript
126
+ * import { transactionContext } from '@classytic/arc/context';
127
+ *
128
+ * const outbox = new EventOutbox({
129
+ * store: myOutboxStore,
130
+ * sessionProvider: () => transactionContext.get(),
131
+ * });
132
+ *
133
+ * // In your service layer — session is auto-picked up:
134
+ * await transactionContext.run(mongooseSession, async () => {
135
+ * await orders.insertOne(order, { session: mongooseSession });
136
+ * await outbox.store(orderCreatedEvent); // no session arg needed
137
+ * });
138
+ * ```
139
+ */
140
+ readonly sessionProvider?: () => unknown;
141
+ /**
142
+ * W3C Trace Context provider.
143
+ *
144
+ * When set, `store()` calls this and merges the returned headers into
145
+ * `OutboxWriteOptions.headers` — only when `traceparent` is not already
146
+ * present in the caller-supplied headers. Downstream relay workers can
147
+ * then forward the headers to the transport, preserving the distributed
148
+ * trace tree across service boundaries.
149
+ *
150
+ * Wire up with arc's `getTraceHeaders`:
151
+ * ```typescript
152
+ * import { getTraceHeaders } from '@classytic/arc/context';
153
+ *
154
+ * const outbox = new EventOutbox({
155
+ * store: myOutboxStore,
156
+ * traceContextProvider: getTraceHeaders,
157
+ * });
158
+ * ```
159
+ */
160
+ readonly traceContextProvider?: () => Record<string, string> | undefined;
161
+ }
162
+ declare class EventOutbox {
163
+ private readonly _store;
164
+ private readonly _transport?;
165
+ private readonly _batchSize;
166
+ private readonly _consumerId;
167
+ private readonly _leaseMs;
168
+ private readonly _onError?;
169
+ private readonly _usePublishMany;
170
+ private readonly _sessionProvider?;
171
+ private readonly _traceContextProvider?;
172
+ private readonly _failurePolicy?;
173
+ /**
174
+ * In-process attempt counter per event id. Accurate within this relay
175
+ * process; resets on restart. Populated as failures occur and cleared on
176
+ * successful ack or dead-letter transition; additionally hard-capped at
177
+ * {@link MAX_TRACKED_ATTEMPTS} (oldest-write evicted first) so events
178
+ * resolved by another relay worker can't accumulate forever. For durable
179
+ * authoritative counts, apps can query the store directly inside
180
+ * {@link OutboxFailurePolicy}.
181
+ */
182
+ private readonly _attempts;
183
+ constructor(opts: EventOutboxOptions);
184
+ /** Unique consumer ID used for lease ownership when the store supports claims */
185
+ get consumerId(): string;
186
+ /**
187
+ * Store event in outbox.
188
+ *
189
+ * Validates that `event.type` and `event.meta.id` are present — throws
190
+ * {@link InvalidOutboxEventError} otherwise, so corrupt rows can never
191
+ * be persisted via this API.
192
+ *
193
+ * Pass `options.session` to participate in a host-managed DB transaction
194
+ * (store must support session-aware writes). Other options (`visibleAt`,
195
+ * `dedupeKey`, `partitionKey`, `headers`) are forwarded to stores that
196
+ * implement them and ignored otherwise.
197
+ */
198
+ store(event: DomainEvent, options?: OutboxWriteOptions): Promise<void>;
199
+ private _reportError;
200
+ /**
201
+ * Relay pending events to transport and return the number of successful
202
+ * publish+acknowledge pairs.
203
+ *
204
+ * For richer observability (per-kind counts, publishMany detection, etc.)
205
+ * use {@link relayBatch} which returns a {@link RelayResult}. This method
206
+ * is the backward-compatible shortcut that returns just the count.
207
+ *
208
+ * @returns Number of successfully published AND acknowledged events
209
+ */
210
+ relay(): Promise<number>;
211
+ /**
212
+ * Relay a batch of pending events to the transport and return a rich
213
+ * {@link RelayResult} describing the outcome of each event.
214
+ *
215
+ * Behavior summary:
216
+ *
217
+ * - **Claim path**: uses {@link OutboxStore.claimPending} when the store
218
+ * supports it (safe for multi-worker relay) or falls back to
219
+ * {@link OutboxStore.getPending} (single-worker only).
220
+ *
221
+ * - **Publish path**: if the transport implements
222
+ * {@link EventTransport.publishMany} and `usePublishMany` is not disabled,
223
+ * the entire batch is sent in one call. Otherwise each event is published
224
+ * individually. Either way, per-event outcomes are tracked.
225
+ *
226
+ * - **Failure path**: if the store implements `fail`, per-event failures
227
+ * are reported via `store.fail(...)` and the batch continues. Without
228
+ * `fail`, the batch stops on the first failure (legacy behavior).
229
+ *
230
+ * - **Malformed events**: events missing `type` or `meta.id` abort the
231
+ * batch — a well-behaved store must never return them (see
232
+ * {@link OutboxStore} semantics #6). The error is reported via `onError`.
233
+ *
234
+ * - **Ownership mismatches**: if `acknowledge`/`fail` throws
235
+ * {@link OutboxOwnershipError} (our lease expired and another worker
236
+ * claimed the event), the event is NOT counted as relayed. The other
237
+ * worker will re-publish — at-least-once semantics preserved.
238
+ *
239
+ * @returns Per-kind outcome counts for the batch
240
+ */
241
+ relayBatch(): Promise<RelayResult>;
242
+ /**
243
+ * Fetch current dead-lettered events as typed {@link DeadLetteredEvent}
244
+ * envelopes. Delegates to {@link OutboxStore.getDeadLettered} — returns
245
+ * `[]` when the store doesn't implement it.
246
+ *
247
+ * Pairs with {@link OutboxFailurePolicy}: apps set a policy that routes to
248
+ * `deadLetter: true` after N attempts, then read back with this to alert,
249
+ * replay, or archive.
250
+ */
251
+ getDeadLettered(limit?: number): Promise<DeadLetteredEvent[]>;
252
+ /**
253
+ * Purge old **delivered** events from the outbox store.
254
+ * Delegates to `store.purge()` if implemented; no-op otherwise.
255
+ * @param olderThanMs - Remove events delivered more than this many ms ago (default: 7 days)
256
+ * @returns Number of purged events, or 0 if store doesn't support purge
257
+ */
258
+ purge(olderThanMs?: number): Promise<number>;
259
+ }
260
+ //#endregion
261
+ //#region src/events/outbox-module.d.ts
262
+ interface OutboxModuleOptions {
263
+ /**
264
+ * The durable store. Supply it directly, or as a factory when it needs the booted app
265
+ * (a mongoose connection decorated by an earlier plugin, for instance).
266
+ */
267
+ store: OutboxStore | ((fastify: FastifyInstance) => OutboxStore);
268
+ /**
269
+ * Where relayed events are published. Omit to use the app's OWN transport — the ordinary case;
270
+ * pass one only when the outbox must publish somewhere else.
271
+ *
272
+ * The default resolves the RAW `EventTransport` the events plugin registered, never the
273
+ * `fastify.events` facade. The facade takes `(type, payload, meta?)` and swallows publish
274
+ * errors under `failOpen` — both fatal here: the first makes every relayed event fail its
275
+ * non-empty-string type guard, the second makes a failure read as success and acknowledges
276
+ * the row. See `ARC_EVENT_TRANSPORT`.
277
+ */
278
+ transport?: EventTransport | ((fastify: FastifyInstance) => EventTransport);
279
+ /** Module name, and therefore the `dependsOn` key. Default `'outbox'`. */
280
+ name?: string;
281
+ /** Relay interval in ms. Default 5000. */
282
+ relayEveryMs?: number;
283
+ /**
284
+ * Rows per relay tick. Left to the store's own default when omitted — a batch size is a
285
+ * throughput tuning decision, not something this module should invent.
286
+ */
287
+ batchSize?: number;
288
+ /** Lease duration for a claimed batch, in ms. */
289
+ leaseMs?: number;
290
+ /**
291
+ * Consumer id recorded on the lease. Default:
292
+ * `<name>:<hostname>:<pid>:<random>` — UNIQUE PER RELAY INSTANCE.
293
+ *
294
+ * The lease is what stops two relays publishing the same event, and it can
295
+ * only do that if they are distinguishable. The pre-2.34 default was the
296
+ * shared literal `'arc-outbox-relay'`, which QUIETLY violated the rule the
297
+ * doc stated: every process — and every co-resident module — was the same
298
+ * logical owner, so a lease that expired and was re-claimed elsewhere looked
299
+ * to the store's ownership check like the original owner never lost it. The
300
+ * stale-owner protection was pinned open.
301
+ *
302
+ * Set this explicitly only to make lease ownership legible in ops tooling
303
+ * (e.g. `billing-relay:pod-7`); whatever you set MUST stay distinct per
304
+ * relay, not merely per deployment.
305
+ */
306
+ consumerId?: string;
307
+ /**
308
+ * Called for every non-fatal relay problem — publish failures, ownership mismatches,
309
+ * acknowledge failures.
310
+ *
311
+ * **Wire this.** Silence here is the failure mode that matters: the relay keeps ticking, rows
312
+ * keep failing, and the only symptom is revenue that never posted.
313
+ */
314
+ onError?: OutboxRelayErrorHandler;
315
+ /**
316
+ * Retry / dead-letter policy for a failed publish — `({ attempts }) => { retryAt } |
317
+ * { deadLetter: true }`.
318
+ *
319
+ * Omitting it takes `EventOutbox`'s default. Exposed because a real host had one and losing it
320
+ * on adoption would be a silent downgrade: without a policy a permanently-failing row either
321
+ * retries forever or dead-letters on the first blip, and both are wrong for money. A typical
322
+ * shape is exponential backoff up to N attempts, then dead-letter.
323
+ */
324
+ failurePolicy?: OutboxFailurePolicy;
325
+ /**
326
+ * Run one relay pass at boot. Default `true` — a process that restarts with a backlog should
327
+ * drain it immediately rather than waiting a full interval, because that backlog is precisely
328
+ * the events the previous process failed to publish.
329
+ */
330
+ runOnStart?: boolean;
331
+ }
332
+ /** What the module exports at `fastify.arc.modules.<name>`. */
333
+ interface OutboxModuleExports {
334
+ /** The store, for consumers that write events transactionally. */
335
+ store: OutboxStore;
336
+ /** The relay, for a host that wants to drain on demand (tests, admin actions). */
337
+ relay: EventOutbox;
338
+ }
339
+ /**
340
+ * Compose the outbox as a module.
341
+ *
342
+ * ```ts
343
+ * // host
344
+ * const model = createOutboxModel(connection, { visibleAtField: 'nextVisibleAt' });
345
+ * createApp({ modules: [
346
+ * createOutboxModule({
347
+ * store: repositoryAsOutboxStore(new Repository(model), { visibleAtField: 'nextVisibleAt' }),
348
+ * onError: (err, ctx) => app.log.error({ err, ...ctx }, 'outbox relay'),
349
+ * }),
350
+ * …
351
+ * ]});
352
+ *
353
+ * // consumer module
354
+ * defineModule({
355
+ * name: 'order',
356
+ * dependsOn: ['outbox'],
357
+ * bootstrap: (f) => createOrder({
358
+ * outbox: getModuleExports<OutboxModuleExports>(f, 'outbox').store,
359
+ * }),
360
+ * });
361
+ * ```
362
+ *
363
+ * `dependsOn` is doing real work there: it both orders the bootstraps and makes a missing outbox a
364
+ * boot error naming the module that needed it.
365
+ */
366
+ declare function createOutboxModule(options: OutboxModuleOptions): ArcModule<OutboxModuleExports>;
367
+ //#endregion
368
+ export { EventOutbox as a, OutboxRelayErrorKind as c, MemoryOutboxStore as i, RelayResult as l, OutboxModuleOptions as n, EventOutboxOptions as o, createOutboxModule as r, OutboxRelayErrorHandler as s, OutboxModuleExports as t };
@@ -1,5 +1,5 @@
1
1
 
2
- import { a as UserBase, c as normalizeRoles, i as PermissionContext, n as DataPolicy, r as PermissionCheck, s as getUserRoles, t as AuthorizationDecision } from "../types-B7XeLEgK.mjs";
2
+ import { c as DataPolicy, d as UserBase, l as PermissionCheck, m as normalizeRoles, p as getUserRoles, s as AuthorizationDecision, u as PermissionContext } from "../base-Csjc2oF-.mjs";
3
3
  import { a as applyFieldWritePermissions, i as applyFieldReadPermissions, n as FieldPermissionMap, o as fields, r as FieldPermissionType, s as resolveEffectiveRoles, t as FieldPermission } from "../fields-I_EeRWND.mjs";
4
- import { $ as evaluatePermissionDecision, A as explainAccess, B as anyOf, C as requireGrant, D as collectPublicSurface, E as PermissionRequirement, F as createDynamicPermissionMatrix, G as requireOwnership, H as denyAll, I as createOrgPermissions, J as roles, K as requirePlatformRole, L as allOf, M as DynamicPermissionMatrix, N as DynamicPermissionMatrixConfig, O as describePermission, P as PermissionEventBus, Q as applyAuthorizationDecision, R as allow, S as modeSatisfies, T as AccessExplanation, U as not, V as deny, W as requireAuth, X as scopeOf, Y as when, Z as PermissionCheckReturn, _ as createRoleHierarchy, a as permissionMatrix, at as requireMandate, b as GrantResolution, c as publicReadAdminWrite, d as requireOrgMembership, et as normalizeToDecision, f as requireOrgRole, g as RoleHierarchy, h as requireTeamMembership, i as ownerWithAdminBypass, it as requireDPoP, j as ConnectEventsOptions, k as describePermissionMap, l as readOnly, m as requireServiceScope, n as authenticated, nt as RequireMandateOptions, o as presets_d_exports, p as requireScopeContext, q as requireRoles, r as fullPublic, rt as requireAgentScope, s as publicRead, t as adminOnly, tt as RequireAgentScopeOptions, u as requireOrgInScope, v as GRANT_MODES, w as conjoinPolicyFilters, x as RequireGrantOptions, y as GrantMode, z as allowPublic } from "../index-CEJNZFtX.mjs";
5
- export { type AccessExplanation, type AuthorizationDecision, type ConnectEventsOptions, type DataPolicy, type DynamicPermissionMatrix, type DynamicPermissionMatrixConfig, type FieldPermission, type FieldPermissionMap, type FieldPermissionType, GRANT_MODES, type GrantMode, type GrantResolution, type PermissionCheck, type PermissionCheckReturn, type PermissionContext, type PermissionEventBus, type PermissionRequirement, type RequireAgentScopeOptions, type RequireGrantOptions, type RequireMandateOptions, type RoleHierarchy, type UserBase, adminOnly, allOf, allow, allowPublic, anyOf, applyAuthorizationDecision, applyFieldReadPermissions, applyFieldWritePermissions, authenticated, collectPublicSurface, conjoinPolicyFilters, createDynamicPermissionMatrix, createOrgPermissions, createRoleHierarchy, deny, denyAll, describePermission, describePermissionMap, evaluatePermissionDecision, explainAccess, fields, fullPublic, getUserRoles, modeSatisfies, normalizeRoles, normalizeToDecision, not, ownerWithAdminBypass, permissionMatrix, presets_d_exports as permissions, publicRead, publicReadAdminWrite, readOnly, requireAgentScope, requireAuth, requireDPoP, requireGrant, requireMandate, requireOrgInScope, requireOrgMembership, requireOrgRole, requireOwnership, requirePlatformRole, requireRoles, requireScopeContext, requireServiceScope, requireTeamMembership, resolveEffectiveRoles, roles, scopeOf, when };
4
+ import { $ as requireAuth, A as RequireGrantOptions, B as ConnectEventsOptions, C as requireServiceScope, D as GRANT_MODES, E as createRoleHierarchy, F as PermissionRequirement, G as createOrgPermissions, H as DynamicPermissionMatrixConfig, I as collectPublicSurface, J as allowPublic, K as allOf, L as describePermission, M as requireGrant, N as conjoinPolicyFilters, O as GrantMode, P as AccessExplanation, Q as not, R as describePermissionMap, S as requireScopeContext, T as RoleHierarchy, U as PermissionEventBus, V as DynamicPermissionMatrix, W as createDynamicPermissionMatrix, X as deny, Y as anyOf, Z as denyAll, _ as publicReadAdminWrite, a as PermissionMatrixRegistry, at as scopeOf, b as requireOrgMembership, c as introspectModule, ct as evaluatePermissionDecision, d as authenticated, dt as RequireMandateOptions, et as requireOwnership, f as fullPublic, ft as requireAgentScope, g as publicRead, h as presets_d_exports, i as PermissionMatrixOptions, it as when, j as modeSatisfies, k as GrantResolution, l as introspectRegistry, lt as normalizeToDecision, m as permissionMatrix, mt as requireMandate, n as PermissionEntryType, nt as requireRoles, o as buildPermissionMatrix, ot as PermissionCheckReturn, p as ownerWithAdminBypass, pt as requireDPoP, q as allow, r as PermissionMatrix, rt as roles, s as introspectCheck, st as applyAuthorizationDecision, t as PermissionEntry, tt as requirePlatformRole, u as adminOnly, ut as RequireAgentScopeOptions, v as readOnly, w as requireTeamMembership, x as requireOrgRole, y as requireOrgInScope, z as explainAccess } from "../index-B-DvUzsr.mjs";
5
+ export { type AccessExplanation, type AuthorizationDecision, type ConnectEventsOptions, type DataPolicy, type DynamicPermissionMatrix, type DynamicPermissionMatrixConfig, type FieldPermission, type FieldPermissionMap, type FieldPermissionType, GRANT_MODES, type GrantMode, type GrantResolution, type PermissionCheck, type PermissionCheckReturn, type PermissionContext, type PermissionEntry, type PermissionEntryType, type PermissionEventBus, type PermissionMatrix, type PermissionMatrixOptions, type PermissionMatrixRegistry, type PermissionRequirement, type RequireAgentScopeOptions, type RequireGrantOptions, type RequireMandateOptions, type RoleHierarchy, type UserBase, adminOnly, allOf, allow, allowPublic, anyOf, applyAuthorizationDecision, applyFieldReadPermissions, applyFieldWritePermissions, authenticated, buildPermissionMatrix, collectPublicSurface, conjoinPolicyFilters, createDynamicPermissionMatrix, createOrgPermissions, createRoleHierarchy, deny, denyAll, describePermission, describePermissionMap, evaluatePermissionDecision, explainAccess, fields, fullPublic, getUserRoles, introspectCheck, introspectModule, introspectRegistry, modeSatisfies, normalizeRoles, normalizeToDecision, not, ownerWithAdminBypass, permissionMatrix, presets_d_exports as permissions, publicRead, publicReadAdminWrite, readOnly, requireAgentScope, requireAuth, requireDPoP, requireGrant, requireMandate, requireOrgInScope, requireOrgMembership, requireOrgRole, requireOwnership, requirePlatformRole, requireRoles, requireScopeContext, requireServiceScope, requireTeamMembership, resolveEffectiveRoles, roles, scopeOf, when };
@@ -1,6 +1,6 @@
1
- /*! @classytic/arc v2.31.0 | MIT | https://classytic.com */
2
- import { a as conjoinPolicyFilters, i as normalizeToDecision, r as evaluatePermissionDecision, t as applyAuthorizationDecision } from "../authorizationDecision-ChvUQGG1.mjs";
3
- import { n as getUserRoles, r as normalizeRoles } from "../userHelpers-ChYJ6CdK.mjs";
4
- import { i as resolveEffectiveRoles, n as applyFieldWritePermissions, r as fields, t as applyFieldReadPermissions } from "../fields-CB5Cuzk9.mjs";
5
- import { A as allow, B as roles, C as requireScopeContext, D as requireDPoP, E as requireAgentScope, F as not, H as scopeOf, I as requireAuth, L as requireOwnership, M as anyOf, N as deny, O as requireMandate, P as denyAll, R as requirePlatformRole, S as requireOrgRole, T as requireTeamMembership, V as when, _ as explainAccess, a as permissionMatrix, b as requireOrgInScope, c as publicReadAdminWrite, d as GRANT_MODES, f as modeSatisfies, g as describePermissionMap, h as describePermission, i as ownerWithAdminBypass, j as allowPublic, k as allOf, l as readOnly, m as collectPublicSurface, n as authenticated, o as presets_exports, p as requireGrant, r as fullPublic, s as publicRead, t as adminOnly, u as createRoleHierarchy, v as createDynamicPermissionMatrix, w as requireServiceScope, x as requireOrgMembership, y as createOrgPermissions, z as requireRoles } from "../permissions-L--QDAir.mjs";
6
- export { GRANT_MODES, adminOnly, allOf, allow, allowPublic, anyOf, applyAuthorizationDecision, applyFieldReadPermissions, applyFieldWritePermissions, authenticated, collectPublicSurface, conjoinPolicyFilters, createDynamicPermissionMatrix, createOrgPermissions, createRoleHierarchy, deny, denyAll, describePermission, describePermissionMap, evaluatePermissionDecision, explainAccess, fields, fullPublic, getUserRoles, modeSatisfies, normalizeRoles, normalizeToDecision, not, ownerWithAdminBypass, permissionMatrix, presets_exports as permissions, publicRead, publicReadAdminWrite, readOnly, requireAgentScope, requireAuth, requireDPoP, requireGrant, requireMandate, requireOrgInScope, requireOrgMembership, requireOrgRole, requireOwnership, requirePlatformRole, requireRoles, requireScopeContext, requireServiceScope, requireTeamMembership, resolveEffectiveRoles, roles, scopeOf, when };
1
+ /*! @classytic/arc v2.34.0 | MIT | https://classytic.com */
2
+ import { a as conjoinPolicyFilters, i as normalizeToDecision, r as evaluatePermissionDecision, t as applyAuthorizationDecision } from "../authorizationDecision-B3mP_QTy.mjs";
3
+ import { n as getUserRoles, r as normalizeRoles } from "../userHelpers-CWF5pbZD.mjs";
4
+ import { i as resolveEffectiveRoles, n as applyFieldWritePermissions, r as fields, t as applyFieldReadPermissions } from "../fields-CojeUkS4.mjs";
5
+ import { A as requireAgentScope, B as requireAuth, C as createOrgPermissions, D as requireScopeContext, E as requireOrgRole, F as allowPublic, G as when, H as requirePlatformRole, I as anyOf, K as scopeOf, L as deny, M as requireMandate, N as allOf, O as requireServiceScope, P as allow, R as denyAll, S as createDynamicPermissionMatrix, T as requireOrgMembership, U as requireRoles, V as requireOwnership, W as roles, _ as requireGrant, a as adminOnly, b as describePermissionMap, c as ownerWithAdminBypass, d as publicRead, f as publicReadAdminWrite, g as modeSatisfies, h as GRANT_MODES, i as introspectRegistry, j as requireDPoP, k as requireTeamMembership, l as permissionMatrix, m as createRoleHierarchy, n as introspectCheck, o as authenticated, p as readOnly, r as introspectModule, s as fullPublic, t as buildPermissionMatrix, u as presets_exports, v as collectPublicSurface, w as requireOrgInScope, x as explainAccess, y as describePermission, z as not } from "../permissions-BAfwgBxc.mjs";
6
+ export { GRANT_MODES, adminOnly, allOf, allow, allowPublic, anyOf, applyAuthorizationDecision, applyFieldReadPermissions, applyFieldWritePermissions, authenticated, buildPermissionMatrix, collectPublicSurface, conjoinPolicyFilters, createDynamicPermissionMatrix, createOrgPermissions, createRoleHierarchy, deny, denyAll, describePermission, describePermissionMap, evaluatePermissionDecision, explainAccess, fields, fullPublic, getUserRoles, introspectCheck, introspectModule, introspectRegistry, modeSatisfies, normalizeRoles, normalizeToDecision, not, ownerWithAdminBypass, permissionMatrix, presets_exports as permissions, publicRead, publicReadAdminWrite, readOnly, requireAgentScope, requireAuth, requireDPoP, requireGrant, requireMandate, requireOrgInScope, requireOrgMembership, requireOrgRole, requireOwnership, requirePlatformRole, requireRoles, requireScopeContext, requireServiceScope, requireTeamMembership, resolveEffectiveRoles, roles, scopeOf, when };
@@ -1,10 +1,10 @@
1
- /*! @classytic/arc v2.31.0 | MIT | https://classytic.com */
2
- import { t as __exportAll } from "./rolldown-runtime-CUsjNX9R.mjs";
1
+ /*! @classytic/arc v2.34.0 | MIT | https://classytic.com */
2
+ import { t as __exportAll } from "./rolldown-runtime-DNg-KNCk.mjs";
3
3
  import { arcLog } from "./logger/index.mjs";
4
- import { a as conjoinPolicyFilters, i as normalizeToDecision } from "./authorizationDecision-ChvUQGG1.mjs";
5
- import { n as getUserRoles } from "./userHelpers-ChYJ6CdK.mjs";
6
- import { C as isService, S as isOrgInScope, a as getDPoPJkt, b as isElevated, d as getScopeContext, f as getScopeContextMap, g as getUserId, m as getTeamId, n as PUBLIC_SCOPE, o as getMandate, p as getServiceScopes, u as getRequestScope, v as hasOrgAccess, x as isMember } from "./types-Cys0ko9Z.mjs";
7
- import { t as MemoryCacheStore } from "./memory-DR6wpa9F.mjs";
4
+ import { a as conjoinPolicyFilters, i as normalizeToDecision } from "./authorizationDecision-B3mP_QTy.mjs";
5
+ import { n as getUserRoles } from "./userHelpers-CWF5pbZD.mjs";
6
+ import { C as isService, S as isOrgInScope, a as getDPoPJkt, b as isElevated, d as getScopeContext, f as getScopeContextMap, g as getUserId, m as getTeamId, n as PUBLIC_SCOPE, o as getMandate, p as getServiceScopes, u as getRequestScope, v as hasOrgAccess, x as isMember } from "./types-CoqIRrkY.mjs";
7
+ import { t as MemoryCacheStore } from "./memory-qYSB7rMQ.mjs";
8
8
  import { randomUUID } from "node:crypto";
9
9
  //#region src/permissions/context.ts
10
10
  /**
@@ -578,7 +578,8 @@ function requireAgentScope(opts) {
578
578
  */
579
579
  function requireOrgMembership() {
580
580
  const check = (ctx) => {
581
- if (hasOrgAccess(scopeOf(ctx))) return true;
581
+ const scope = scopeOf(ctx);
582
+ if (hasOrgAccess(scope)) return true;
582
583
  if (!ctx.user) return deny("Authentication required");
583
584
  return deny("Organization membership required");
584
585
  };
@@ -1545,4 +1546,115 @@ function readOnly(overrides) {
1545
1546
  }, overrides);
1546
1547
  }
1547
1548
  //#endregion
1548
- export { allow as A, roles as B, requireScopeContext as C, requireDPoP as D, requireAgentScope as E, not as F, scopeOf as H, requireAuth as I, requireOwnership as L, anyOf as M, deny as N, requireMandate as O, denyAll as P, requirePlatformRole as R, requireOrgRole as S, requireTeamMembership as T, when as V, explainAccess as _, permissionMatrix as a, requireOrgInScope as b, publicReadAdminWrite as c, GRANT_MODES as d, modeSatisfies as f, describePermissionMap as g, describePermission as h, ownerWithAdminBypass as i, allowPublic as j, allOf as k, readOnly as l, collectPublicSurface as m, authenticated as n, presets_exports as o, requireGrant as p, fullPublic as r, publicRead as s, adminOnly as t, createRoleHierarchy as u, createDynamicPermissionMatrix as v, requireServiceScope as w, requireOrgMembership as x, createOrgPermissions as y, requireRoles as z };
1549
+ //#region src/permissions/matrix.ts
1550
+ /**
1551
+ * Permission MATRIX — what the caller may do, answered from the live registry.
1552
+ *
1553
+ * A permission-gated frontend has to decide which screens and buttons to render
1554
+ * before it issues a request. Without a server answer it keeps a hand-written
1555
+ * copy of the gates, and that copy drifts the moment a resource changes one —
1556
+ * silently, and in the dangerous direction: the UI offers an action the server
1557
+ * will refuse, or hides one the user is entitled to.
1558
+ *
1559
+ * This builds the answer from what arc ACTUALLY enforces. Every registered
1560
+ * resource contributes its CRUD gates, its state-transition `action:<verb>`
1561
+ * gates and its `agg:<name>` gates, introspected through `describePermission`.
1562
+ * A resource that exists therefore gates its own screen with no one adding it
1563
+ * anywhere — including resources unique to one deployment.
1564
+ *
1565
+ * ## Why it lives in arc
1566
+ *
1567
+ * Every input is arc's: `describePermission`, the resource registry, the shapes
1568
+ * of `actions` and `aggregations`. Nothing here knows what a domain is. Built
1569
+ * in a host, it is re-derived per deployment — and the known gap below is a
1570
+ * gap in arc's own introspection, which a host cannot close but arc can.
1571
+ *
1572
+ * ## Known gap
1573
+ *
1574
+ * `anyOf(a, b)` composes checks into a bare function with no aggregated meta,
1575
+ * so `anyOf(platformAdminOnly(), requireOrgRole(…))` introspects as
1576
+ * `authenticated` with no roles. Consumers must read `authenticated` as "the
1577
+ * server decides" rather than "any logged-in user", and fall back to an
1578
+ * explicit gate for those. Fixing it means teaching the combinators to
1579
+ * aggregate meta — an arc change, tracked here because this is where it shows.
1580
+ */
1581
+ /** Re-shape arc's typed requirement into the wire entry. */
1582
+ function introspectCheck(check) {
1583
+ const req = describePermission(check);
1584
+ if (req.kind === "public") return {
1585
+ type: "public",
1586
+ roles: []
1587
+ };
1588
+ if (req.kind === "roles") return {
1589
+ type: "roles",
1590
+ roles: [...req.roles]
1591
+ };
1592
+ if (req.kind === "scoped") return {
1593
+ type: "scoped",
1594
+ roles: req.roles ? [...req.roles] : [],
1595
+ scope: { ...req.scope }
1596
+ };
1597
+ return {
1598
+ type: "authenticated",
1599
+ roles: []
1600
+ };
1601
+ }
1602
+ /** Introspect a permission module, flattening nested groups to `a.b`. */
1603
+ function introspectModule(mod) {
1604
+ const result = {};
1605
+ for (const [action, check] of Object.entries(mod)) if (typeof check === "function") result[action] = introspectCheck(check);
1606
+ else if (typeof check === "object" && check !== null) for (const [nested, entry] of Object.entries(introspectModule(check))) result[`${action}.${nested}`] = entry;
1607
+ return result;
1608
+ }
1609
+ /** Every live resource's ACTUAL gates, keyed by arc resource name. */
1610
+ function introspectRegistry(registry) {
1611
+ const modules = {};
1612
+ for (const entry of registry.getAll()) {
1613
+ const map = {};
1614
+ for (const [action, check] of Object.entries(entry.permissions ?? {})) if (typeof check === "function") map[action] = introspectCheck(check);
1615
+ for (const a of entry.actions ?? []) if (typeof a.permissions === "function") map[`action:${a.name}`] = introspectCheck(a.permissions);
1616
+ for (const agg of entry.aggregations ?? []) if (typeof agg.permissions === "function") map[`agg:${agg.name}`] = introspectCheck(agg.permissions);
1617
+ /**
1618
+ * Custom routes that OPTED IN via `capability`.
1619
+ *
1620
+ * A route has no inherent name — only a method and a path — so it cannot be
1621
+ * keyed automatically, and a path is not an identity. Without this, a
1622
+ * resource whose gates live entirely on `routes[]` published nothing, was
1623
+ * absent from the matrix, and every `can()` against it answered `false`:
1624
+ * a UI gating on it hid the feature from everyone, admins included, and that
1625
+ * reads as broken permissions rather than an unpublished key.
1626
+ *
1627
+ * The key is BARE, alongside `list`/`get`/`create`, so a consumer never has
1628
+ * to know whether a verb is a route, an action or a CRUD slot.
1629
+ */
1630
+ for (const route of entry.customRoutes ?? []) {
1631
+ const key = route.capability;
1632
+ if (key === void 0 || typeof route.permissions !== "function") continue;
1633
+ if (map[key] !== void 0) throw new Error(`[arc] permission-matrix collision on resource "${entry.name}": route ${route.method} ${route.path} declares capability "${key}", which is already published by a CRUD slot, action or another route. Rename the route's \`capability\`.`);
1634
+ map[key] = introspectCheck(route.permissions);
1635
+ }
1636
+ if (Object.keys(map).length > 0) modules[entry.name] = map;
1637
+ }
1638
+ return modules;
1639
+ }
1640
+ function buildPermissionMatrix(options = {}) {
1641
+ const platform = [...options.platformRoles ?? []];
1642
+ const branch = [...options.orgRoles ?? []];
1643
+ const modules = {};
1644
+ for (const [name, mod] of Object.entries(options.curatedModules ?? {})) if (typeof mod === "object" && mod !== null) modules[name] = introspectModule(mod);
1645
+ for (const [name, mod] of Object.entries(options.fallbackModules ?? {})) {
1646
+ if (modules[name]) continue;
1647
+ if (typeof mod === "object" && mod !== null) modules[name] = introspectModule(mod);
1648
+ }
1649
+ if (options.registry) Object.assign(modules, introspectRegistry(options.registry));
1650
+ return {
1651
+ roles: [.../* @__PURE__ */ new Set([...platform, ...branch])],
1652
+ roleGroups: {
1653
+ platform,
1654
+ branch
1655
+ },
1656
+ modules
1657
+ };
1658
+ }
1659
+ //#endregion
1660
+ export { requireAgentScope as A, requireAuth as B, createOrgPermissions as C, requireScopeContext as D, requireOrgRole as E, allowPublic as F, when as G, requirePlatformRole as H, anyOf as I, scopeOf as K, deny as L, requireMandate as M, allOf as N, requireServiceScope as O, allow as P, denyAll as R, createDynamicPermissionMatrix as S, requireOrgMembership as T, requireRoles as U, requireOwnership as V, roles as W, requireGrant as _, adminOnly as a, describePermissionMap as b, ownerWithAdminBypass as c, publicRead as d, publicReadAdminWrite as f, modeSatisfies as g, GRANT_MODES as h, introspectRegistry as i, requireDPoP as j, requireTeamMembership as k, permissionMatrix as l, createRoleHierarchy as m, introspectCheck as n, authenticated as o, readOnly as p, introspectModule as r, fullPublic as s, buildPermissionMatrix as t, presets_exports as u, collectPublicSurface as v, requireOrgInScope as w, explainAccess as x, describePermission as y, not as z };
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.31.0 | MIT | https://classytic.com */
2
- import { r as ForbiddenError } from "./errors-Cj42AntO.mjs";
1
+ /*! @classytic/arc v2.34.0 | MIT | https://classytic.com */
2
+ import { r as ForbiddenError } from "./errors-Cd_yy7aW.mjs";
3
3
  //#region src/pipeline/pipe.ts
4
4
  /**
5
5
  * Compose pipeline steps into an ordered array.
@@ -40,9 +40,7 @@ async function executePipeline(steps, ctx, handler, operation) {
40
40
  case "transform":
41
41
  transforms.push(step);
42
42
  break;
43
- case "interceptor":
44
- interceptors.push(step);
45
- break;
43
+ case "interceptor": interceptors.push(step);
46
44
  }
47
45
  }
48
46
  for (const g of guards) if (!await g.handler(ctx)) throw new ForbiddenError(`Guard '${g.name}' denied access`);
@@ -1,5 +1,5 @@
1
1
 
2
- import { Ct as PipelineStep, Rt as IControllerResponse, St as PipelineContext, _t as Guard, bt as OperationFilter, vt as Interceptor, wt as Transform, xt as PipelineConfig, yt as NextFunction } from "../index-CpzxqePp.mjs";
2
+ import { Ct as PipelineStep, Fn as IControllerResponse, St as PipelineContext, _t as Guard, bt as OperationFilter, vt as Interceptor, wt as Transform, xt as PipelineConfig, yt as NextFunction } from "../index-BcR2bFZQ.mjs";
3
3
  //#region src/pipeline/guard.d.ts
4
4
  interface GuardOptions {
5
5
  operations?: OperationFilter;
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.31.0 | MIT | https://classytic.com */
2
- import { n as pipe, t as executePipeline } from "../pipe-DRDNsI2T.mjs";
1
+ /*! @classytic/arc v2.34.0 | MIT | https://classytic.com */
2
+ import { n as pipe, t as executePipeline } from "../pipe-BzzoEhHj.mjs";
3
3
  //#region src/pipeline/guard.ts
4
4
  /**
5
5
  * Create a named guard.