@classytic/arc 2.15.4 → 2.16.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 (158) hide show
  1. package/README.md +1 -0
  2. package/bin/arc.js +12 -0
  3. package/dist/{BaseController-dx3m2J8V.mjs → BaseController-DlCCTIxJ.mjs} +61 -19
  4. package/dist/{HookSystem-Iiebom92.mjs → HookSystem-Cmf7-Etp.mjs} +8 -4
  5. package/dist/{QueryCache-D41bfdBB.d.mts → QueryCache-SvmT_9ti.d.mts} +1 -1
  6. package/dist/{ResourceRegistry-CTERg_2x.mjs → ResourceRegistry-f48hFk3m.mjs} +52 -9
  7. package/dist/audit/index.d.mts +1 -1
  8. package/dist/audit/index.mjs +4 -2
  9. package/dist/auth/index.d.mts +4 -4
  10. package/dist/auth/index.mjs +4 -4
  11. package/dist/auth/redis-session.d.mts +1 -1
  12. package/dist/{betterAuthOpenApi--M_i87dQ.mjs → betterAuthOpenApi-ClWxaceA.mjs} +10 -6
  13. package/dist/buildHandler-BZX6zzDM.mjs +300 -0
  14. package/dist/cache/index.d.mts +3 -3
  15. package/dist/cache/index.mjs +3 -3
  16. package/dist/{caching-SM8gghN6.mjs → caching-TeHE8G-v.mjs} +1 -1
  17. package/dist/cli/commands/describe.d.mts +35 -1
  18. package/dist/cli/commands/describe.mjs +52 -12
  19. package/dist/cli/commands/docs.d.mts +1 -4
  20. package/dist/cli/commands/docs.mjs +4 -16
  21. package/dist/cli/commands/generate.d.mts +2 -20
  22. package/dist/cli/commands/generate.mjs +1 -546
  23. package/dist/cli/commands/init.d.mts +2 -40
  24. package/dist/cli/commands/init.mjs +1 -3045
  25. package/dist/cli/commands/introspect.mjs +53 -64
  26. package/dist/cli/index.d.mts +2 -2
  27. package/dist/cli/index.mjs +2 -2
  28. package/dist/{constants-Cxde4rpC.mjs → constants-TrJVIJl0.mjs} +7 -0
  29. package/dist/core/index.d.mts +3 -3
  30. package/dist/core/index.mjs +5 -5
  31. package/dist/{core-CvmOqEms.mjs → core-DBJ_j6rX.mjs} +222 -44
  32. package/dist/createActionRouter-DUpN3Dd1.mjs +288 -0
  33. package/dist/{createAggregationRouter-B0bPDf5b.mjs → createAggregationRouter-Dq-TUCuY.mjs} +3 -2
  34. package/dist/{createApp-PFegs47-.mjs → createApp-DNccuhyI.mjs} +16 -14
  35. package/dist/{defineEvent-D5h7EvAx.mjs → defineEvent-DRwY0fYm.mjs} +1 -1
  36. package/dist/docs/index.d.mts +2 -2
  37. package/dist/docs/index.mjs +1 -1
  38. package/dist/{errorHandler-Bk-AGhkU.mjs → errorHandler-DpoXQHZ9.mjs} +17 -14
  39. package/dist/errors-C1lX_jlm.d.mts +91 -0
  40. package/dist/{eventPlugin-CaKTYkYM.mjs → eventPlugin-C2cGqtRO.mjs} +1 -1
  41. package/dist/{eventPlugin-qXpqTebY.d.mts → eventPlugin-CtHC_av1.d.mts} +1 -1
  42. package/dist/events/index.d.mts +3 -3
  43. package/dist/events/index.mjs +5 -5
  44. package/dist/events/transports/redis-stream-entry.d.mts +1 -1
  45. package/dist/events/transports/redis.d.mts +1 -1
  46. package/dist/factory/index.d.mts +1 -1
  47. package/dist/factory/index.mjs +2 -2
  48. package/dist/{fields-COhcH3fk.d.mts → fields-Anj0xdih.d.mts} +1 -1
  49. package/dist/generate-BWFwgcCM.d.mts +38 -0
  50. package/dist/generate-CYac-OLv.mjs +654 -0
  51. package/dist/hooks/index.d.mts +1 -1
  52. package/dist/hooks/index.mjs +1 -1
  53. package/dist/idempotency/index.d.mts +2 -2
  54. package/dist/idempotency/index.mjs +1 -1
  55. package/dist/idempotency/redis.d.mts +1 -1
  56. package/dist/{index-BTqLEvhu.d.mts → index-3oIimXQn.d.mts} +12 -12
  57. package/dist/{index-BstGxcc3.d.mts → index-B-ulKx5P.d.mts} +55 -4
  58. package/dist/{index-BswOSJCE.d.mts → index-CkW0flkU.d.mts} +355 -16
  59. package/dist/index.d.mts +6 -6
  60. package/dist/index.mjs +7 -8
  61. package/dist/init-Dv71MsJr.d.mts +71 -0
  62. package/dist/init-HDvoO9L5.mjs +3098 -0
  63. package/dist/integrations/event-gateway.d.mts +2 -2
  64. package/dist/integrations/event-gateway.mjs +1 -1
  65. package/dist/integrations/index.d.mts +2 -2
  66. package/dist/integrations/jobs.mjs +3 -3
  67. package/dist/integrations/mcp/index.d.mts +239 -7
  68. package/dist/integrations/mcp/index.mjs +2 -528
  69. package/dist/integrations/mcp/testing.d.mts +2 -2
  70. package/dist/integrations/mcp/testing.mjs +6 -10
  71. package/dist/integrations/streamline.mjs +26 -1
  72. package/dist/integrations/websocket-redis.d.mts +1 -1
  73. package/dist/integrations/websocket.d.mts +1 -1
  74. package/dist/integrations/websocket.mjs +1 -0
  75. package/dist/loadResourcesFromEntry-BLMEI2Xa.mjs +51 -0
  76. package/dist/{resourceToTools-tFYUNmM0.mjs → mcpPlugin-7vGV51ED.mjs} +1021 -318
  77. package/dist/{memory-UBydS5ku.mjs → memory-QOLe11D5.mjs} +2 -0
  78. package/dist/middleware/index.d.mts +1 -1
  79. package/dist/middleware/index.mjs +1 -1
  80. package/dist/{openapi-BHXhoX8O.mjs → openapi-34T9yNwd.mjs} +47 -36
  81. package/dist/permissions/index.d.mts +2 -2
  82. package/dist/permissions/index.mjs +1 -1
  83. package/dist/{permissions-ohQyv50e.mjs → permissions-CTxMrreC.mjs} +2 -2
  84. package/dist/{pipe-Zr0KXjQe.mjs → pipe-DiCyvyPN.mjs} +1 -0
  85. package/dist/pipeline/index.d.mts +1 -1
  86. package/dist/pipeline/index.mjs +1 -1
  87. package/dist/plugins/index.d.mts +5 -5
  88. package/dist/plugins/index.mjs +10 -10
  89. package/dist/plugins/response-cache.mjs +5 -5
  90. package/dist/plugins/tracing-entry.d.mts +1 -1
  91. package/dist/plugins/tracing-entry.mjs +1 -1
  92. package/dist/{pluralize-DQgqgifU.mjs → pluralize-B9M8xvy-.mjs} +2 -1
  93. package/dist/presets/filesUpload.d.mts +4 -4
  94. package/dist/presets/filesUpload.mjs +2 -2
  95. package/dist/presets/index.d.mts +1 -1
  96. package/dist/presets/index.mjs +1 -1
  97. package/dist/presets/multiTenant.d.mts +1 -1
  98. package/dist/presets/multiTenant.mjs +4 -3
  99. package/dist/presets/search.d.mts +2 -2
  100. package/dist/presets/search.mjs +1 -1
  101. package/dist/{presets-BbkjdPeH.mjs → presets-C9BE6WaZ.mjs} +2 -2
  102. package/dist/{queryCachePlugin-m1XsgAIJ.mjs → queryCachePlugin-B4XMSSe7.mjs} +2 -2
  103. package/dist/{queryCachePlugin-CqMdLI2-.d.mts → queryCachePlugin-Biqzfbi5.d.mts} +2 -2
  104. package/dist/{redis-DiMkdHEl.d.mts → redis-Cyzrz6SX.d.mts} +1 -1
  105. package/dist/{redis-stream-D6HzR1Z_.d.mts → redis-stream-DT-YjzrB.d.mts} +1 -1
  106. package/dist/registry/index.d.mts +319 -2
  107. package/dist/registry/index.mjs +3 -3
  108. package/dist/registry-BBE23CDj.mjs +576 -0
  109. package/dist/{routerShared-DrOa-26E.mjs → routerShared-CZV5aabX.mjs} +3 -3
  110. package/dist/scope/index.d.mts +3 -3
  111. package/dist/scope/index.mjs +3 -3
  112. package/dist/{sse-Bz-5ZeTt.mjs → sse-BY6sTy4P.mjs} +1 -1
  113. package/dist/testing/index.d.mts +2 -2
  114. package/dist/testing/index.mjs +16 -7
  115. package/dist/testing/storageContract.d.mts +1 -1
  116. package/dist/types/index.d.mts +5 -5
  117. package/dist/types/storage.d.mts +1 -1
  118. package/dist/{types-C_s5moIu.mjs → types-Bi0r0vjG.mjs} +53 -1
  119. package/dist/{types-BQsjgQzS.d.mts → types-BsJMEQ4D.d.mts} +106 -12
  120. package/dist/{types-DrBaUwyV.d.mts → types-D-fYtKjb.d.mts} +33 -10
  121. package/dist/{types-CTYvcwHe.d.mts → types-DVfpSfx2.d.mts} +42 -1
  122. package/dist/utils/index.d.mts +1286 -2
  123. package/dist/utils/index.mjs +1 -1
  124. package/dist/{utils-_h9B3c57.mjs → utils-DC5ycPfr.mjs} +89 -40
  125. package/dist/{buildHandler-CcFOpJLh.mjs → validate-By96rH0r.mjs} +8 -299
  126. package/dist/{versioning-hmkPcDlX.d.mts → versioning-ZwX9tmbS.d.mts} +1 -1
  127. package/package.json +21 -28
  128. package/skills/arc/SKILL.md +300 -706
  129. package/skills/arc/references/auth.md +19 -7
  130. package/skills/arc-code-review/SKILL.md +1 -1
  131. package/skills/arc-code-review/references/arc-cheatsheet.md +100 -322
  132. package/dist/createActionRouter-S3MLVYot.mjs +0 -220
  133. package/dist/index-bRjYu21O.d.mts +0 -1320
  134. package/dist/org/index.d.mts +0 -66
  135. package/dist/org/index.mjs +0 -486
  136. package/dist/org/types.d.mts +0 -82
  137. package/dist/org/types.mjs +0 -1
  138. package/dist/registry-I-ogLgL9.mjs +0 -46
  139. /package/dist/{EventTransport-CT_52aWU.d.mts → EventTransport-C-2oAHtw.d.mts} +0 -0
  140. /package/dist/{EventTransport-DLWoUMHy.mjs → EventTransport-Hxvv5QQz.mjs} +0 -0
  141. /package/dist/{actionPermissions-CyUkQu6O.mjs → actionPermissions-Bjmvn7Eb.mjs} +0 -0
  142. /package/dist/{elevation-BXOWoGCF.d.mts → elevation-0YBpa663.d.mts} +0 -0
  143. /package/dist/{elevation-DgoeTyfX.mjs → elevation-Dci0AYLT.mjs} +0 -0
  144. /package/dist/{errorHandler-DFr45ZG4.d.mts → errorHandler-mHuyWzZE.d.mts} +0 -0
  145. /package/dist/{externalPaths-BD5nw6St.d.mts → externalPaths-DFg-2KTp.d.mts} +0 -0
  146. /package/dist/{interface-beEtJyWM.d.mts → interface-CH0OQudo.d.mts} +0 -0
  147. /package/dist/{interface-DfLGcus7.d.mts → interface-NwJ_qPlY.d.mts} +0 -0
  148. /package/dist/{keys-CGcCbNyu.mjs → keys-DopsCuyQ.mjs} +0 -0
  149. /package/dist/{loadResources-DBMQg_Aj.mjs → loadResources-ChQEj8ih.mjs} +0 -0
  150. /package/dist/{metrics-Qnvwc-LQ.mjs → metrics-TuOmguhi.mjs} +0 -0
  151. /package/dist/{replyHelpers-CK-FNO8E.mjs → replyHelpers-C-gD32oF.mjs} +0 -0
  152. /package/dist/{schemaIR-lYhC2gE5.mjs → schemaIR-Ctc89DSn.mjs} +0 -0
  153. /package/dist/{sessionManager-C4Le_UB3.d.mts → sessionManager-BqFegc0W.d.mts} +0 -0
  154. /package/dist/{storage-Dfzt4VTl.d.mts → storage-D2KZJAmn.d.mts} +0 -0
  155. /package/dist/{store-helpers-BkIN9-vu.mjs → store-helpers-B0sunfZZ.mjs} +0 -0
  156. /package/dist/{tracing-QJVprktp.d.mts → tracing-Dm8n7Cnn.d.mts} +0 -0
  157. /package/dist/{versioning-BUrT5aP4.mjs → versioning-B6mimogM.mjs} +0 -0
  158. /package/dist/{websocket-ChC2rqe1.d.mts → websocket-BkjeGZRn.d.mts} +0 -0
@@ -1,2 +1,1286 @@
1
- import { $ as ValidateOptions, A as ArcQueryParserOptions, B as CompensationResult, C as keysetListResponse, D as queryParams, E as paginationSchema, F as defineGuard, G as CircuitBreakerError, H as defineCompensation, I as defineErrorMapper, J as CircuitBreakerStats, K as CircuitBreakerOptions, L as CompensationDefinition, M as handleRaw, N as Guard, O as responses, P as GuardConfig, Q as ConfigError, R as CompensationError, S as getListQueryParams, T as offsetListResponse, U as withCompensation, V as CompensationStep, W as CircuitBreaker, X as createCircuitBreaker, Y as CircuitState, Z as createCircuitBreakerRegistry, _ as bareListResponse, _t as isArcError, a as TransitionConfig, at as ConflictError, b as errorDetailSchema, c as JsonSchemaTarget, ct as NotFoundError, d as isJsonSchema, dt as RateLimitError, et as ValidationResult, f as isZodSchema, ft as ServiceUnavailableError, g as aggregateListResponse, gt as createError, h as JsonSchema, ht as createDomainError, i as StateMachine, it as ArcError, j as createQueryParser, k as ArcQueryParser, l as convertOpenApiSchemas, lt as OrgAccessDeniedError, m as scheduleBackground, mt as ValidationError, n as EventsDecorator, nt as formatValidationErrors, o as createStateMachine, ot as ErrorOptions, p as toJsonSchema, pt as UnauthorizedError, q as CircuitBreakerRegistry, r as hasEvents, rt as validateResourceConfig, s as simpleEqualityMatcher, st as ForbiddenError, t as getUserId, tt as assertValidConfig, u as convertRouteSchema, ut as OrgRequiredError, v as deleteResponse, w as listResponse, x as getDefaultCrudSchemas, y as errorContractSchema, z as CompensationHooks } from "../index-bRjYu21O.mjs";
2
- export { ArcError, ArcQueryParser, ArcQueryParserOptions, CircuitBreaker, CircuitBreakerError, CircuitBreakerOptions, CircuitBreakerRegistry, CircuitBreakerStats, CircuitState, CompensationDefinition, CompensationError, CompensationHooks, CompensationResult, CompensationStep, ConfigError, ConflictError, ErrorOptions, EventsDecorator, ForbiddenError, Guard, GuardConfig, JsonSchema, JsonSchemaTarget, NotFoundError, OrgAccessDeniedError, OrgRequiredError, RateLimitError, ServiceUnavailableError, StateMachine, TransitionConfig, UnauthorizedError, ValidateOptions, ValidationError, ValidationResult, aggregateListResponse, assertValidConfig, bareListResponse, convertOpenApiSchemas, convertRouteSchema, createCircuitBreaker, createCircuitBreakerRegistry, createDomainError, createError, createQueryParser, createStateMachine, defineCompensation, defineErrorMapper, defineGuard, deleteResponse, errorContractSchema, errorDetailSchema, formatValidationErrors, getDefaultCrudSchemas, getListQueryParams, getUserId, handleRaw, hasEvents, isArcError, isJsonSchema, isZodSchema, keysetListResponse, listResponse, offsetListResponse, paginationSchema, queryParams, responses, scheduleBackground, simpleEqualityMatcher, toJsonSchema, validateResourceConfig, withCompensation };
1
+ import { Kt as AnyRecord, S as QueryParserInterface, Zt as UserLike, b as ParsedQuery, et as OpenApiSchemas, st as ResourceConfig } from "../index-CkW0flkU.mjs";
2
+ import { n as ErrorMapper } from "../errorHandler-mHuyWzZE.mjs";
3
+ import { a as NotFoundError, c as RateLimitError, d as ValidationError, f as createDomainError, i as ForbiddenError, l as ServiceUnavailableError, m as isArcError, n as ConflictError, o as OrgAccessDeniedError, p as createError, r as ErrorOptions, s as OrgRequiredError, t as ArcError, u as UnauthorizedError } from "../errors-C1lX_jlm.mjs";
4
+ import { errorContractSchema, errorDetailSchema } from "@classytic/repo-core/errors";
5
+ import { FastifyInstance, FastifyReply, FastifyRequest, RouteHandlerMethod } from "fastify";
6
+
7
+ //#region src/core/validateResourceConfig.d.ts
8
+ interface ConfigError {
9
+ field: string;
10
+ message: string;
11
+ suggestion?: string;
12
+ }
13
+ interface ValidationResult {
14
+ valid: boolean;
15
+ errors: ConfigError[];
16
+ warnings: ConfigError[];
17
+ }
18
+ interface ValidateOptions {
19
+ /** Skip controller method validation (for testing) */
20
+ skipControllerCheck?: boolean;
21
+ /** Allow unknown preset names */
22
+ allowUnknownPresets?: boolean;
23
+ /** Custom valid permission keys beyond CRUD */
24
+ additionalPermissionKeys?: string[];
25
+ }
26
+ /**
27
+ * Validate a resource configuration
28
+ */
29
+ declare function validateResourceConfig(config: ResourceConfig, options?: ValidateOptions): ValidationResult;
30
+ /**
31
+ * Format validation errors for display
32
+ */
33
+ declare function formatValidationErrors(resourceName: string, result: ValidationResult): string;
34
+ /**
35
+ * Validate and throw if invalid
36
+ */
37
+ declare function assertValidConfig(config: ResourceConfig, options?: ValidateOptions): void;
38
+ //#endregion
39
+ //#region src/utils/circuitBreaker.d.ts
40
+ /**
41
+ * Circuit Breaker Pattern
42
+ *
43
+ * Wraps external service calls with failure protection.
44
+ * Prevents cascading failures by "opening" the circuit when
45
+ * a service is failing, allowing it time to recover.
46
+ *
47
+ * States:
48
+ * - CLOSED: Normal operation, requests pass through
49
+ * - OPEN: Too many failures, all requests fail fast
50
+ * - HALF_OPEN: Testing if service recovered, limited requests
51
+ *
52
+ * @example
53
+ * import { CircuitBreaker } from '@classytic/arc/utils';
54
+ *
55
+ * const paymentBreaker = new CircuitBreaker(async (amount) => {
56
+ * return await stripe.charges.create({ amount });
57
+ * }, {
58
+ * failureThreshold: 5,
59
+ * resetTimeout: 30000,
60
+ * timeout: 5000,
61
+ * });
62
+ *
63
+ * try {
64
+ * const result = await paymentBreaker.call(100);
65
+ * } catch (error) {
66
+ * // Handle failure or circuit open
67
+ * }
68
+ */
69
+ declare const CircuitState: {
70
+ readonly CLOSED: "CLOSED";
71
+ readonly OPEN: "OPEN";
72
+ readonly HALF_OPEN: "HALF_OPEN";
73
+ };
74
+ type CircuitState = (typeof CircuitState)[keyof typeof CircuitState];
75
+ /**
76
+ * Generic constraint for "any async function" that survives strict TS.
77
+ *
78
+ * `(...args: never[]) => Promise<unknown>` is the canonical modern pattern:
79
+ * `never` in the contravariant args position lets concrete signatures
80
+ * like `(amount: number) => Promise<Charge>` satisfy the constraint via
81
+ * function-parameter bivariance, while `unknown` in the covariant return
82
+ * position is the no-info-leak escape from `any`. `(...args: any[]) =>
83
+ * Promise<any>` would silently disable type checking everywhere `T` flows.
84
+ */
85
+ type AnyAsyncFn = (...args: never[]) => Promise<unknown>;
86
+ interface CircuitBreakerOptions {
87
+ /**
88
+ * Number of failures before opening circuit
89
+ * @default 5
90
+ */
91
+ failureThreshold?: number;
92
+ /**
93
+ * Time in ms before attempting to close circuit
94
+ * @default 60000 (60 seconds)
95
+ */
96
+ resetTimeout?: number;
97
+ /**
98
+ * Request timeout in ms
99
+ * @default 10000 (10 seconds)
100
+ */
101
+ timeout?: number;
102
+ /**
103
+ * Number of successful requests in HALF_OPEN before closing
104
+ * @default 1
105
+ */
106
+ successThreshold?: number;
107
+ /**
108
+ * Fallback function when circuit is open.
109
+ * Receives the same arguments as the wrapped function.
110
+ */
111
+ fallback?: (...args: unknown[]) => Promise<unknown>;
112
+ /**
113
+ * Callback when state changes
114
+ */
115
+ onStateChange?: (from: CircuitState, to: CircuitState) => void;
116
+ /**
117
+ * Callback on error
118
+ */
119
+ onError?: (error: Error) => void;
120
+ /**
121
+ * Name for logging/monitoring
122
+ */
123
+ name?: string;
124
+ }
125
+ interface CircuitBreakerStats {
126
+ name?: string;
127
+ state: CircuitState;
128
+ failures: number;
129
+ successes: number;
130
+ totalCalls: number;
131
+ openedAt: number | null;
132
+ lastCallAt: number | null;
133
+ }
134
+ declare class CircuitBreakerError extends Error {
135
+ state: CircuitState;
136
+ constructor(message: string, state: CircuitState);
137
+ }
138
+ declare class CircuitBreaker<T extends AnyAsyncFn> {
139
+ private state;
140
+ private failures;
141
+ private successes;
142
+ private totalCalls;
143
+ private nextAttempt;
144
+ private lastCallAt;
145
+ private openedAt;
146
+ private readonly failureThreshold;
147
+ private readonly resetTimeout;
148
+ private readonly timeout;
149
+ private readonly successThreshold;
150
+ private readonly fallback?;
151
+ private readonly onStateChange?;
152
+ private readonly onError?;
153
+ private readonly name;
154
+ private readonly fn;
155
+ constructor(fn: T, options?: CircuitBreakerOptions);
156
+ /**
157
+ * Call the wrapped function with circuit breaker protection
158
+ */
159
+ call(...args: Parameters<T>): Promise<ReturnType<T>>;
160
+ /**
161
+ * Execute function with timeout
162
+ */
163
+ private executeWithTimeout;
164
+ /**
165
+ * Handle successful call
166
+ */
167
+ private onSuccess;
168
+ /**
169
+ * Handle failed call
170
+ */
171
+ private onFailure;
172
+ /**
173
+ * Change circuit state
174
+ */
175
+ private setState;
176
+ /**
177
+ * Manually open the circuit
178
+ */
179
+ open(): void;
180
+ /**
181
+ * Manually close the circuit
182
+ */
183
+ close(): void;
184
+ /**
185
+ * Get current statistics
186
+ */
187
+ getStats(): CircuitBreakerStats;
188
+ /**
189
+ * Get current state
190
+ */
191
+ getState(): CircuitState;
192
+ /**
193
+ * Check if circuit is open
194
+ */
195
+ isOpen(): boolean;
196
+ /**
197
+ * Check if circuit is closed
198
+ */
199
+ isClosed(): boolean;
200
+ /**
201
+ * Reset statistics
202
+ */
203
+ reset(): void;
204
+ }
205
+ /**
206
+ * Create a circuit breaker with sensible defaults
207
+ *
208
+ * @example
209
+ * const emailBreaker = createCircuitBreaker(
210
+ * async (to, subject, body) => sendEmail(to, subject, body),
211
+ * { name: 'email-service' }
212
+ * );
213
+ */
214
+ declare function createCircuitBreaker<T extends AnyAsyncFn>(fn: T, options?: CircuitBreakerOptions): CircuitBreaker<T>;
215
+ /**
216
+ * Circuit breaker registry for managing multiple breakers
217
+ */
218
+ declare class CircuitBreakerRegistry {
219
+ private breakers;
220
+ /**
221
+ * Register a circuit breaker
222
+ */
223
+ register<T extends AnyAsyncFn>(name: string, fn: T, options?: Omit<CircuitBreakerOptions, "name">): CircuitBreaker<T>;
224
+ /**
225
+ * Get a circuit breaker by name
226
+ */
227
+ get(name: string): CircuitBreaker<AnyAsyncFn> | undefined;
228
+ /**
229
+ * Get all breakers
230
+ */
231
+ getAll(): Map<string, CircuitBreaker<AnyAsyncFn>>;
232
+ /**
233
+ * Get statistics for all breakers
234
+ */
235
+ getAllStats(): Record<string, CircuitBreakerStats>;
236
+ /**
237
+ * Reset all breakers
238
+ */
239
+ resetAll(): void;
240
+ /**
241
+ * Open all breakers
242
+ */
243
+ openAll(): void;
244
+ /**
245
+ * Close all breakers
246
+ */
247
+ closeAll(): void;
248
+ }
249
+ /**
250
+ * Create a new CircuitBreakerRegistry instance.
251
+ * Use this instead of a global singleton — attach to fastify.arc or pass explicitly.
252
+ */
253
+ declare function createCircuitBreakerRegistry(): CircuitBreakerRegistry;
254
+ //#endregion
255
+ //#region src/utils/compensation.d.ts
256
+ /**
257
+ * Compensating Transaction — In-Process Rollback Primitive
258
+ *
259
+ * Runs steps in order. If any step fails, runs compensating actions
260
+ * for already-completed steps in reverse. Zero dependencies.
261
+ *
262
+ * Type-safe: generic context type gives autocomplete across steps.
263
+ * Discriminated union result: compiler enforces checking success before
264
+ * accessing failedStep/error.
265
+ *
266
+ * For distributed sagas across services, use Temporal, Inngest, or Streamline.
267
+ *
268
+ * @example
269
+ * ```typescript
270
+ * interface CheckoutCtx {
271
+ * orderId: string;
272
+ * reservationId?: string;
273
+ * }
274
+ *
275
+ * const result = await withCompensation<CheckoutCtx>('checkout', [
276
+ * {
277
+ * name: 'reserve',
278
+ * execute: async (ctx) => {
279
+ * const res = await inventoryService.reserve(ctx.orderId);
280
+ * ctx.reservationId = res.id;
281
+ * return res;
282
+ * },
283
+ * compensate: async (ctx) => {
284
+ * await inventoryService.release(ctx.reservationId!);
285
+ * },
286
+ * },
287
+ * { name: 'notify', execute: sendEmail, fireAndForget: true },
288
+ * ], { orderId: 'ord-123' });
289
+ *
290
+ * if (result.success) {
291
+ * // result.results available, no failedStep
292
+ * } else {
293
+ * // result.failedStep and result.error guaranteed
294
+ * }
295
+ * ```
296
+ */
297
+ /** Step definition with typed context and typed result */
298
+ interface CompensationStep<TCtx = Record<string, unknown>, TResult = unknown> {
299
+ /** Step name — used in results, logs, and hooks */
300
+ readonly name: string;
301
+ /** Execute the step — return value stored in results[name] */
302
+ readonly execute: (ctx: TCtx) => Promise<TResult>;
303
+ /** Rollback on failure — receives context and this step's own result */
304
+ readonly compensate?: (ctx: TCtx, stepResult: TResult) => Promise<void>;
305
+ /** Fire-and-forget — don't await, don't block, swallow errors, skip in rollback */
306
+ readonly fireAndForget?: boolean;
307
+ }
308
+ /** Lifecycle hooks for observability — wire to Arc events, metrics, or logging */
309
+ interface CompensationHooks {
310
+ readonly onStepComplete?: (stepName: string, result: unknown) => void;
311
+ readonly onStepFailed?: (stepName: string, error: Error) => void;
312
+ readonly onCompensate?: (stepName: string) => void;
313
+ }
314
+ /** Error from a compensation action that failed during rollback */
315
+ interface CompensationError {
316
+ readonly step: string;
317
+ readonly error: string;
318
+ }
319
+ /** Discriminated union — success and failure are mutually exclusive */
320
+ type CompensationResult = {
321
+ readonly success: true;
322
+ readonly completedSteps: readonly string[];
323
+ readonly results: Readonly<Record<string, unknown>>;
324
+ } | {
325
+ readonly success: false;
326
+ readonly completedSteps: readonly string[];
327
+ readonly results: Readonly<Record<string, unknown>>;
328
+ readonly failedStep: string;
329
+ readonly error: string;
330
+ readonly compensationErrors?: readonly CompensationError[];
331
+ };
332
+ /**
333
+ * Run steps in order with automatic compensation on failure.
334
+ *
335
+ * @typeParam TCtx - Context type shared across steps (defaults to Record<string, unknown>)
336
+ */
337
+ declare function withCompensation<TCtx extends Record<string, unknown> = Record<string, unknown>>(_name: string, steps: readonly CompensationStep<TCtx>[], initialContext?: TCtx, hooks?: CompensationHooks): Promise<CompensationResult>;
338
+ interface CompensationDefinition<TCtx extends Record<string, unknown> = Record<string, unknown>> {
339
+ readonly name: string;
340
+ readonly execute: (initialContext?: TCtx, hooks?: CompensationHooks) => Promise<CompensationResult>;
341
+ }
342
+ declare function defineCompensation<TCtx extends Record<string, unknown> = Record<string, unknown>>(name: string, steps: readonly CompensationStep<TCtx>[]): CompensationDefinition<TCtx>;
343
+ //#endregion
344
+ //#region src/utils/defineErrorMapper.d.ts
345
+ /**
346
+ * Register an `ErrorMapper` with its domain-specific generic argument and
347
+ * have it assign cleanly into `ErrorMapper[]` (no `as unknown as ErrorMapper`).
348
+ *
349
+ * The returned mapper is identical at runtime — `type` and `toResponse` are
350
+ * passed through untouched. Only the declared type widens from
351
+ * `ErrorMapper<T>` to `ErrorMapper` so the array inference works.
352
+ *
353
+ * Safety: the `errorHandlerPlugin` dispatches via `error instanceof mapper.type`
354
+ * before invoking `toResponse`, so the widened callback signature is never
355
+ * called with a non-`T` error at runtime. This helper codifies that invariant
356
+ * in one place.
357
+ */
358
+ declare function defineErrorMapper<T extends Error>(mapper: ErrorMapper<T>): ErrorMapper;
359
+ //#endregion
360
+ //#region src/utils/defineGuard.d.ts
361
+ interface GuardConfig<T> {
362
+ /** Unique name — used as the storage key on the request. */
363
+ readonly name: string;
364
+ /**
365
+ * Resolve the guard context from the request. Throw to abort the request
366
+ * (Fastify's error handler will produce the appropriate HTTP response).
367
+ * Return a value to stash it for `from()` extraction.
368
+ */
369
+ readonly resolve: (req: FastifyRequest, reply: FastifyReply) => T | Promise<T>;
370
+ }
371
+ interface Guard<T> {
372
+ /** Use in `routeGuards` or per-route `preHandler` arrays. */
373
+ readonly preHandler: RouteHandlerMethod;
374
+ /**
375
+ * Extract the resolved context from a request. Throws if the guard
376
+ * hasn't run yet (i.e. not in the preHandler chain).
377
+ */
378
+ from(req: FastifyRequest): T;
379
+ /** The guard name (for debugging). */
380
+ readonly name: string;
381
+ }
382
+ /**
383
+ * Create a typed guard. See module JSDoc for usage.
384
+ */
385
+ declare function defineGuard<T>(config: GuardConfig<T>): Guard<T>;
386
+ //#endregion
387
+ //#region src/utils/handleRaw.d.ts
388
+ /**
389
+ * Wrap a raw Fastify handler with Arc's response shape and error handling.
390
+ *
391
+ * @param handler - Async function that receives `(request, reply)` and returns data.
392
+ * The return value is sent raw (no envelope). If it returns `undefined`,
393
+ * the response body is empty (HTTP status only).
394
+ * @param statusCode - HTTP status code for successful responses (default: 200)
395
+ */
396
+ declare function handleRaw<T>(handler: (request: FastifyRequest, reply: FastifyReply) => Promise<T>, statusCode?: number): (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
397
+ //#endregion
398
+ //#region src/utils/queryParser.d.ts
399
+ interface ArcQueryParserOptions {
400
+ /** Maximum allowed limit value (default: 1000) */
401
+ maxLimit?: number;
402
+ /** Default limit for pagination (default: 20) */
403
+ defaultLimit?: number;
404
+ /** Maximum regex pattern length (default: 500) */
405
+ maxRegexLength?: number;
406
+ /** Maximum search query length (default: 200) */
407
+ maxSearchLength?: number;
408
+ /** Maximum filter nesting depth (default: 10) */
409
+ maxFilterDepth?: number;
410
+ /**
411
+ * Whitelist of fields that can be filtered on.
412
+ * When set, only these fields are accepted as filters — all others are silently dropped.
413
+ * Also used by MCP to auto-derive filterable fields in tool schemas.
414
+ */
415
+ allowedFilterFields?: string[];
416
+ /**
417
+ * Whitelist of fields that can be sorted on.
418
+ * When set, sort fields not in this list are silently dropped.
419
+ * Also used by MCP to describe available sort options.
420
+ */
421
+ allowedSortFields?: string[];
422
+ /**
423
+ * Whitelist of filter operators (e.g. ['eq', 'ne', 'gt', 'lt', 'in']).
424
+ * When set, only these operators are accepted — all others are dropped.
425
+ * Also used by MCP to enrich list tool descriptions.
426
+ */
427
+ allowedOperators?: string[];
428
+ }
429
+ /**
430
+ * Arc's default query parser
431
+ *
432
+ * Converts URL query parameters to a structured query format:
433
+ * - Pagination: ?page=1&limit=20
434
+ * - Sorting: ?sort=-createdAt,name (- prefix = descending)
435
+ * - Filtering — TWO supported forms (both produce identical output):
436
+ * - Bare (default, terse): `?status=active&price[gte]=100&price[lte]=500`
437
+ * - Bracket envelope: `?filter[status]=active&filter[price][gte]=100`
438
+ * The envelope form matches the convention used by JSON:API / Stripe /
439
+ * most modern REST style guides, and is the safe choice on busy URLs
440
+ * that might otherwise collide with reserved meta keys (`page`, `sort`,
441
+ * `select`, `populate`, etc.). Operator notation (`[gte]`, `[lte]`,
442
+ * `[ne]`, `[in]`, ...) works inside either form.
443
+ * - Search: ?search=keyword
444
+ * - Populate: ?populate=author,category
445
+ * - Field selection: ?select=name,price,status
446
+ * - Keyset pagination: ?after=cursor_value
447
+ *
448
+ * **NOTE on parser portability.** `ArcQueryParser` accepts both filter
449
+ * forms. Other parser implementations (`@classytic/mongokit`'s
450
+ * `QueryParser`, custom hosts-side parsers) may accept only one form —
451
+ * MongoKit historically only accepts the bare form. If your host swaps
452
+ * `queryParser` to a different implementation, double-check which forms
453
+ * it understands before publishing URLs that mix the two.
454
+ *
455
+ * For advanced MongoDB features ($lookup, aggregations), use MongoKit's QueryParser.
456
+ */
457
+ declare class ArcQueryParser implements QueryParserInterface {
458
+ private readonly maxLimit;
459
+ private readonly defaultLimit;
460
+ private readonly maxRegexLength;
461
+ private readonly maxSearchLength;
462
+ private readonly maxFilterDepth;
463
+ private readonly _allowedFilterFields?;
464
+ private readonly _allowedSortFields?;
465
+ private readonly _allowedOperators?;
466
+ /** Allowed filter fields (used by MCP for auto-derive) */
467
+ readonly allowedFilterFields?: readonly string[];
468
+ /** Allowed sort fields (used by MCP for sort descriptions) */
469
+ readonly allowedSortFields?: readonly string[];
470
+ /** Allowed operators (used by MCP for operator descriptions) */
471
+ readonly allowedOperators?: readonly string[];
472
+ /** Supported filter operators */
473
+ private readonly operators;
474
+ constructor(options?: ArcQueryParserOptions);
475
+ /**
476
+ * Parse URL query parameters into structured query options
477
+ */
478
+ parse(query: Record<string, unknown> | null | undefined): ParsedQuery;
479
+ private parseNumber;
480
+ private parseString;
481
+ /**
482
+ * Parse populate parameter — handles both simple string and bracket notation.
483
+ *
484
+ * Simple: ?populate=author,category → { populate: 'author,category' }
485
+ * Bracket: ?populate[author][select]=name,email → { populateOptions: [{ path: 'author', select: 'name email' }] }
486
+ */
487
+ private parsePopulate;
488
+ private parseSort;
489
+ private parseSearch;
490
+ private parseSelect;
491
+ /**
492
+ * Check if a value exceeds the maximum nesting depth.
493
+ * Prevents filter bombs where deeply nested objects consume excessive memory/CPU.
494
+ */
495
+ private exceedsDepth;
496
+ /**
497
+ * Parse all filter entries from the query, supporting BOTH the bare
498
+ * top-level form and the bracket-wrapped `filter[...]` envelope.
499
+ *
500
+ * Two equivalent ways to express the same query:
501
+ * - Bare (legacy, arc default): `?status=active&price[gte]=40`
502
+ * - Bracket envelope (REST convention): `?filter[status]=active&filter[price][gte]=40`
503
+ *
504
+ * Both forms parse to the same `filters: { status: 'active', price: { $gte: 40 } }`.
505
+ * The envelope form mirrors the convention used by most REST API style
506
+ * guides (JSON:API, Stripe API, etc.) and disambiguates filter fields
507
+ * from reserved meta params on busy URLs — a query string with a field
508
+ * literally named `page` or `sort` can't collide with the framework's
509
+ * meta keys when wrapped under `filter[...]`. The bare form stays as
510
+ * the default since it's the shortest path for simple queries; expect
511
+ * it to remain supported indefinitely.
512
+ *
513
+ * Precedence when the same key appears in both forms:
514
+ * `?status=closed&filter[status]=active` → bare wins (`status: closed`).
515
+ * Mixing should be rare; the deterministic rule avoids silent surprises.
516
+ */
517
+ private parseFilters;
518
+ /**
519
+ * Apply one filter entry — used by both the bracket-envelope branch and
520
+ * the bare top-level branch of `parseFilters`. Centralising the field-
521
+ * validation + operator-conversion logic keeps the two forms in
522
+ * lockstep; a future regex/security tweak only changes one place.
523
+ */
524
+ private applyFilterEntry;
525
+ private parseFilterValue;
526
+ private coerceValue;
527
+ /**
528
+ * Generate OpenAPI-compatible JSON Schema for query parameters.
529
+ * Arc's defineResource() auto-detects this method and uses it
530
+ * to document list endpoint query parameters in OpenAPI/Swagger.
531
+ */
532
+ getQuerySchema(): {
533
+ type: "object";
534
+ properties: Record<string, unknown>;
535
+ required?: string[];
536
+ };
537
+ private sanitizeRegex;
538
+ }
539
+ /**
540
+ * Create a new ArcQueryParser instance
541
+ */
542
+ declare function createQueryParser(options?: ArcQueryParserOptions): ArcQueryParser;
543
+ //#endregion
544
+ //#region src/utils/responseSchemas.d.ts
545
+ interface JsonSchema {
546
+ /**
547
+ * Optional because JSON Schema allows top-level combinator-only schemas
548
+ * (`{ oneOf: [...] }`, `{ anyOf: [...] }`, `{ allOf: [...] }`) — see
549
+ * `listResponse()`, which emits a `oneOf` of the four canonical list
550
+ * shapes with no top-level `type`.
551
+ */
552
+ type?: string | string[];
553
+ properties?: Record<string, JsonSchema | AnyRecord>;
554
+ required?: string[];
555
+ items?: JsonSchema | AnyRecord;
556
+ additionalProperties?: boolean | JsonSchema;
557
+ description?: string;
558
+ example?: unknown;
559
+ oneOf?: JsonSchema[];
560
+ anyOf?: JsonSchema[];
561
+ allOf?: JsonSchema[];
562
+ [key: string]: unknown;
563
+ }
564
+ /**
565
+ * Pagination schema - matches MongoKit/Arc runtime format
566
+ *
567
+ * Runtime format (flat fields):
568
+ * { page, limit, total, pages, hasNext, hasPrev }
569
+ */
570
+ declare const paginationSchema: JsonSchema;
571
+ /**
572
+ * List response schema — full union of every wire shape `toCanonicalList`
573
+ * can emit. Hosts who know their endpoint only ever produces one variant
574
+ * can pin to a narrower helper:
575
+ * - `offsetListResponse(item)` — `{ method: 'offset', data, page, limit, total, pages, hasNext, hasPrev }`
576
+ * - `keysetListResponse(item)` — `{ method: 'keyset', data, limit, hasMore, next: string|null }`
577
+ * - `aggregateListResponse(item)` — `{ method: 'aggregate', ...offset fields }`
578
+ * - `bareListResponse(item)` — `{ data }`
579
+ *
580
+ * The default `listResponse(item)` is the union (`oneOf`) of all four so
581
+ * Fastify validation accepts any canonical kit shape — pre-2.13 this only
582
+ * modelled offset and rejected keyset/aggregate/bare lists at the
583
+ * response-schema gate.
584
+ */
585
+ declare function listResponse(itemSchema: JsonSchema): JsonSchema;
586
+ /** Offset variant — `{ method: 'offset', data, page, limit, total, pages, hasNext, hasPrev }`. */
587
+ declare function offsetListResponse(itemSchema: JsonSchema): JsonSchema;
588
+ /** Keyset variant — `{ method: 'keyset', data, limit, hasMore, next: string | null }`. */
589
+ declare function keysetListResponse(itemSchema: JsonSchema): JsonSchema;
590
+ /** Aggregate variant — same shape as offset, discriminated by `method: 'aggregate'`. */
591
+ declare function aggregateListResponse(itemSchema: JsonSchema): JsonSchema;
592
+ /** Bare variant — `{ data }`, no `method` discriminant. */
593
+ declare function bareListResponse(itemSchema: JsonSchema): JsonSchema;
594
+ /** Delete response — flat shape mirroring the canonical delete envelope. */
595
+ declare function deleteResponse(): JsonSchema;
596
+ declare const responses: {
597
+ 200: (schema: JsonSchema) => {
598
+ description: string;
599
+ content: {
600
+ "application/json": {
601
+ schema: JsonSchema;
602
+ };
603
+ };
604
+ };
605
+ 201: (schema: JsonSchema) => {
606
+ description: string;
607
+ content: {
608
+ "application/json": {
609
+ schema: {
610
+ additionalProperties: boolean;
611
+ /**
612
+ * Optional because JSON Schema allows top-level combinator-only schemas
613
+ * (`{ oneOf: [...] }`, `{ anyOf: [...] }`, `{ allOf: [...] }`) — see
614
+ * `listResponse()`, which emits a `oneOf` of the four canonical list
615
+ * shapes with no top-level `type`.
616
+ */
617
+ type?: string | string[];
618
+ properties?: Record<string, JsonSchema | AnyRecord>;
619
+ required?: string[];
620
+ items?: JsonSchema | AnyRecord;
621
+ description?: string;
622
+ example?: unknown;
623
+ oneOf?: JsonSchema[];
624
+ anyOf?: JsonSchema[];
625
+ allOf?: JsonSchema[];
626
+ };
627
+ };
628
+ };
629
+ };
630
+ 400: {
631
+ description: string;
632
+ content: {
633
+ "application/json": {
634
+ schema: {
635
+ readonly type: "object";
636
+ readonly properties: {
637
+ readonly code: {
638
+ readonly type: "string";
639
+ readonly description: "Hierarchical machine-readable code (e.g. 'arc.not_found').";
640
+ };
641
+ readonly message: {
642
+ readonly type: "string";
643
+ readonly description: "Human-readable, safe-for-client message.";
644
+ };
645
+ readonly status: {
646
+ readonly type: "integer";
647
+ readonly description: "Suggested HTTP status code (hosts may override).";
648
+ };
649
+ readonly details: {
650
+ readonly type: "array";
651
+ readonly description: "Field-scoped structured details (validation failures, duplicate keys, multi-code domain errors).";
652
+ readonly items: {
653
+ readonly type: "object";
654
+ readonly properties: {
655
+ readonly path: {
656
+ readonly type: "string";
657
+ readonly description: "Dot-path to the offending field, e.g. 'lines.0.quantity'.";
658
+ };
659
+ readonly code: {
660
+ readonly type: "string";
661
+ };
662
+ readonly message: {
663
+ readonly type: "string";
664
+ };
665
+ readonly meta: {
666
+ readonly type: "object";
667
+ readonly description: "Non-PII per-detail diagnostics (safe to log + return).";
668
+ };
669
+ };
670
+ readonly required: readonly ["code", "message"];
671
+ };
672
+ };
673
+ readonly correlationId: {
674
+ readonly type: "string";
675
+ readonly description: "Request id for support lookups.";
676
+ };
677
+ readonly meta: {
678
+ readonly type: "object";
679
+ readonly description: "Non-PII diagnostics (safe to log + return).";
680
+ };
681
+ };
682
+ readonly required: readonly ["code", "message"];
683
+ };
684
+ };
685
+ };
686
+ };
687
+ 401: {
688
+ description: string;
689
+ content: {
690
+ "application/json": {
691
+ schema: {
692
+ readonly type: "object";
693
+ readonly properties: {
694
+ readonly code: {
695
+ readonly type: "string";
696
+ readonly description: "Hierarchical machine-readable code (e.g. 'arc.not_found').";
697
+ };
698
+ readonly message: {
699
+ readonly type: "string";
700
+ readonly description: "Human-readable, safe-for-client message.";
701
+ };
702
+ readonly status: {
703
+ readonly type: "integer";
704
+ readonly description: "Suggested HTTP status code (hosts may override).";
705
+ };
706
+ readonly details: {
707
+ readonly type: "array";
708
+ readonly description: "Field-scoped structured details (validation failures, duplicate keys, multi-code domain errors).";
709
+ readonly items: {
710
+ readonly type: "object";
711
+ readonly properties: {
712
+ readonly path: {
713
+ readonly type: "string";
714
+ readonly description: "Dot-path to the offending field, e.g. 'lines.0.quantity'.";
715
+ };
716
+ readonly code: {
717
+ readonly type: "string";
718
+ };
719
+ readonly message: {
720
+ readonly type: "string";
721
+ };
722
+ readonly meta: {
723
+ readonly type: "object";
724
+ readonly description: "Non-PII per-detail diagnostics (safe to log + return).";
725
+ };
726
+ };
727
+ readonly required: readonly ["code", "message"];
728
+ };
729
+ };
730
+ readonly correlationId: {
731
+ readonly type: "string";
732
+ readonly description: "Request id for support lookups.";
733
+ };
734
+ readonly meta: {
735
+ readonly type: "object";
736
+ readonly description: "Non-PII diagnostics (safe to log + return).";
737
+ };
738
+ };
739
+ readonly required: readonly ["code", "message"];
740
+ };
741
+ };
742
+ };
743
+ };
744
+ 403: {
745
+ description: string;
746
+ content: {
747
+ "application/json": {
748
+ schema: {
749
+ readonly type: "object";
750
+ readonly properties: {
751
+ readonly code: {
752
+ readonly type: "string";
753
+ readonly description: "Hierarchical machine-readable code (e.g. 'arc.not_found').";
754
+ };
755
+ readonly message: {
756
+ readonly type: "string";
757
+ readonly description: "Human-readable, safe-for-client message.";
758
+ };
759
+ readonly status: {
760
+ readonly type: "integer";
761
+ readonly description: "Suggested HTTP status code (hosts may override).";
762
+ };
763
+ readonly details: {
764
+ readonly type: "array";
765
+ readonly description: "Field-scoped structured details (validation failures, duplicate keys, multi-code domain errors).";
766
+ readonly items: {
767
+ readonly type: "object";
768
+ readonly properties: {
769
+ readonly path: {
770
+ readonly type: "string";
771
+ readonly description: "Dot-path to the offending field, e.g. 'lines.0.quantity'.";
772
+ };
773
+ readonly code: {
774
+ readonly type: "string";
775
+ };
776
+ readonly message: {
777
+ readonly type: "string";
778
+ };
779
+ readonly meta: {
780
+ readonly type: "object";
781
+ readonly description: "Non-PII per-detail diagnostics (safe to log + return).";
782
+ };
783
+ };
784
+ readonly required: readonly ["code", "message"];
785
+ };
786
+ };
787
+ readonly correlationId: {
788
+ readonly type: "string";
789
+ readonly description: "Request id for support lookups.";
790
+ };
791
+ readonly meta: {
792
+ readonly type: "object";
793
+ readonly description: "Non-PII diagnostics (safe to log + return).";
794
+ };
795
+ };
796
+ readonly required: readonly ["code", "message"];
797
+ };
798
+ };
799
+ };
800
+ };
801
+ 404: {
802
+ description: string;
803
+ content: {
804
+ "application/json": {
805
+ schema: {
806
+ readonly type: "object";
807
+ readonly properties: {
808
+ readonly code: {
809
+ readonly type: "string";
810
+ readonly description: "Hierarchical machine-readable code (e.g. 'arc.not_found').";
811
+ };
812
+ readonly message: {
813
+ readonly type: "string";
814
+ readonly description: "Human-readable, safe-for-client message.";
815
+ };
816
+ readonly status: {
817
+ readonly type: "integer";
818
+ readonly description: "Suggested HTTP status code (hosts may override).";
819
+ };
820
+ readonly details: {
821
+ readonly type: "array";
822
+ readonly description: "Field-scoped structured details (validation failures, duplicate keys, multi-code domain errors).";
823
+ readonly items: {
824
+ readonly type: "object";
825
+ readonly properties: {
826
+ readonly path: {
827
+ readonly type: "string";
828
+ readonly description: "Dot-path to the offending field, e.g. 'lines.0.quantity'.";
829
+ };
830
+ readonly code: {
831
+ readonly type: "string";
832
+ };
833
+ readonly message: {
834
+ readonly type: "string";
835
+ };
836
+ readonly meta: {
837
+ readonly type: "object";
838
+ readonly description: "Non-PII per-detail diagnostics (safe to log + return).";
839
+ };
840
+ };
841
+ readonly required: readonly ["code", "message"];
842
+ };
843
+ };
844
+ readonly correlationId: {
845
+ readonly type: "string";
846
+ readonly description: "Request id for support lookups.";
847
+ };
848
+ readonly meta: {
849
+ readonly type: "object";
850
+ readonly description: "Non-PII diagnostics (safe to log + return).";
851
+ };
852
+ };
853
+ readonly required: readonly ["code", "message"];
854
+ };
855
+ };
856
+ };
857
+ };
858
+ 409: {
859
+ description: string;
860
+ content: {
861
+ "application/json": {
862
+ schema: {
863
+ readonly type: "object";
864
+ readonly properties: {
865
+ readonly code: {
866
+ readonly type: "string";
867
+ readonly description: "Hierarchical machine-readable code (e.g. 'arc.not_found').";
868
+ };
869
+ readonly message: {
870
+ readonly type: "string";
871
+ readonly description: "Human-readable, safe-for-client message.";
872
+ };
873
+ readonly status: {
874
+ readonly type: "integer";
875
+ readonly description: "Suggested HTTP status code (hosts may override).";
876
+ };
877
+ readonly details: {
878
+ readonly type: "array";
879
+ readonly description: "Field-scoped structured details (validation failures, duplicate keys, multi-code domain errors).";
880
+ readonly items: {
881
+ readonly type: "object";
882
+ readonly properties: {
883
+ readonly path: {
884
+ readonly type: "string";
885
+ readonly description: "Dot-path to the offending field, e.g. 'lines.0.quantity'.";
886
+ };
887
+ readonly code: {
888
+ readonly type: "string";
889
+ };
890
+ readonly message: {
891
+ readonly type: "string";
892
+ };
893
+ readonly meta: {
894
+ readonly type: "object";
895
+ readonly description: "Non-PII per-detail diagnostics (safe to log + return).";
896
+ };
897
+ };
898
+ readonly required: readonly ["code", "message"];
899
+ };
900
+ };
901
+ readonly correlationId: {
902
+ readonly type: "string";
903
+ readonly description: "Request id for support lookups.";
904
+ };
905
+ readonly meta: {
906
+ readonly type: "object";
907
+ readonly description: "Non-PII diagnostics (safe to log + return).";
908
+ };
909
+ };
910
+ readonly required: readonly ["code", "message"];
911
+ };
912
+ };
913
+ };
914
+ };
915
+ 500: {
916
+ description: string;
917
+ content: {
918
+ "application/json": {
919
+ schema: {
920
+ readonly type: "object";
921
+ readonly properties: {
922
+ readonly code: {
923
+ readonly type: "string";
924
+ readonly description: "Hierarchical machine-readable code (e.g. 'arc.not_found').";
925
+ };
926
+ readonly message: {
927
+ readonly type: "string";
928
+ readonly description: "Human-readable, safe-for-client message.";
929
+ };
930
+ readonly status: {
931
+ readonly type: "integer";
932
+ readonly description: "Suggested HTTP status code (hosts may override).";
933
+ };
934
+ readonly details: {
935
+ readonly type: "array";
936
+ readonly description: "Field-scoped structured details (validation failures, duplicate keys, multi-code domain errors).";
937
+ readonly items: {
938
+ readonly type: "object";
939
+ readonly properties: {
940
+ readonly path: {
941
+ readonly type: "string";
942
+ readonly description: "Dot-path to the offending field, e.g. 'lines.0.quantity'.";
943
+ };
944
+ readonly code: {
945
+ readonly type: "string";
946
+ };
947
+ readonly message: {
948
+ readonly type: "string";
949
+ };
950
+ readonly meta: {
951
+ readonly type: "object";
952
+ readonly description: "Non-PII per-detail diagnostics (safe to log + return).";
953
+ };
954
+ };
955
+ readonly required: readonly ["code", "message"];
956
+ };
957
+ };
958
+ readonly correlationId: {
959
+ readonly type: "string";
960
+ readonly description: "Request id for support lookups.";
961
+ };
962
+ readonly meta: {
963
+ readonly type: "object";
964
+ readonly description: "Non-PII diagnostics (safe to log + return).";
965
+ };
966
+ };
967
+ readonly required: readonly ["code", "message"];
968
+ };
969
+ };
970
+ };
971
+ };
972
+ };
973
+ declare const queryParams: {
974
+ pagination: {
975
+ page: {
976
+ type: string;
977
+ minimum: number;
978
+ default: number;
979
+ description: string;
980
+ };
981
+ limit: {
982
+ type: string;
983
+ minimum: number;
984
+ maximum: number;
985
+ default: number;
986
+ description: string;
987
+ };
988
+ };
989
+ sorting: {
990
+ sort: {
991
+ type: string;
992
+ description: string;
993
+ example: string;
994
+ };
995
+ };
996
+ filtering: {
997
+ select: {
998
+ description: string;
999
+ example: string;
1000
+ };
1001
+ populate: {
1002
+ description: string;
1003
+ example: string;
1004
+ };
1005
+ };
1006
+ };
1007
+ /**
1008
+ * Get standard list query parameters schema
1009
+ */
1010
+ declare function getListQueryParams(): AnyRecord;
1011
+ /**
1012
+ * Get default response schemas for all CRUD operations.
1013
+ *
1014
+ * When routes have response schemas, Fastify compiles them with
1015
+ * fast-json-stringify for 2-3x faster serialization and prevents
1016
+ * accidental field disclosure.
1017
+ *
1018
+ * These defaults use `additionalProperties: true` so all fields pass through.
1019
+ * Override with specific schemas for full serialization performance + safety.
1020
+ *
1021
+ * Note: `example` properties are stripped from defaults so they work with
1022
+ * any Fastify instance (not just createApp which adds `keywords: ['example']`).
1023
+ */
1024
+ declare function getDefaultCrudSchemas(): Record<string, Record<string, unknown>>;
1025
+ //#endregion
1026
+ //#region src/utils/runtime.d.ts
1027
+ /**
1028
+ * Portable "run on next tick" scheduler. `setImmediate` is Node-only — not
1029
+ * available in Bun workers, Deno, Cloudflare Workers, or edge runtimes.
1030
+ */
1031
+ declare const scheduleBackground: (cb: () => void) => void;
1032
+ //#endregion
1033
+ //#region src/utils/schemaConverter.d.ts
1034
+ /**
1035
+ * Supported JSON Schema output targets for Zod v4's `toJSONSchema()`.
1036
+ * - `draft-7`: Fastify/AJV validation (default)
1037
+ * - `draft-2020-12`: AJV 2020 (opt-in, requires ajv/dist/2020)
1038
+ * - `openapi-3.0`: OpenAPI 3.0 document generation
1039
+ * - `openapi-3.1`: OpenAPI 3.1 document generation
1040
+ */
1041
+ type JsonSchemaTarget = "draft-7" | "draft-2020-12" | "openapi-3.0" | "openapi-3.1";
1042
+ /**
1043
+ * Check if an object is already a plain JSON Schema.
1044
+ * Returns true if it has JSON Schema markers (`type`, `properties`, `$ref`,
1045
+ * `allOf`, `anyOf`, `oneOf`, `items`, `enum`) and does NOT have Zod markers.
1046
+ */
1047
+ declare function isJsonSchema(input: unknown): input is Record<string, unknown>;
1048
+ /**
1049
+ * Check if an object is a Zod schema (has `_zod` marker from Zod v4).
1050
+ */
1051
+ declare function isZodSchema(input: unknown): boolean;
1052
+ /**
1053
+ * Convert any schema input to JSON Schema.
1054
+ *
1055
+ * Detection order:
1056
+ * 1. `null`/`undefined` → `undefined`
1057
+ * 2. Already JSON Schema → pass through as-is (zero overhead)
1058
+ * 3. Zod v4 schema → `z.toJSONSchema(schema, { target })`
1059
+ * 4. Unrecognized object → return as-is (treat as opaque schema)
1060
+ *
1061
+ * @param input Schema (Zod, plain JSON Schema, or opaque object)
1062
+ * @param target Output target — defaults to `draft-7` for Fastify compatibility.
1063
+ * Pass `openapi-3.0`/`openapi-3.1` for OpenAPI document generation.
1064
+ */
1065
+ declare function toJsonSchema(input: unknown, target?: JsonSchemaTarget): Record<string, unknown> | undefined;
1066
+ /**
1067
+ * Convert all schema fields in an OpenApiSchemas object.
1068
+ * JSON Schema values pass through unchanged. Only Zod schemas are converted.
1069
+ *
1070
+ * Defaults to the `openapi-3.0` target since this function feeds OpenAPI doc
1071
+ * generation, not Fastify route validation.
1072
+ */
1073
+ declare function convertOpenApiSchemas(schemas: OpenApiSchemas, target?: JsonSchemaTarget): OpenApiSchemas;
1074
+ /**
1075
+ * Convert schema values in a Fastify route schema record.
1076
+ *
1077
+ * Handles `body`, `querystring`, `params`, `headers` (top-level conversion)
1078
+ * and `response` (iterates by status code — each value converted individually).
1079
+ *
1080
+ * JSON Schema values pass through unchanged. Only Zod schemas are converted.
1081
+ *
1082
+ * Used for both custom routes and customSchemas (CRUD overrides).
1083
+ *
1084
+ * Defaults to `draft-7` so Fastify v5's bundled AJV 8 accepts the output.
1085
+ * Pass `openapi-3.0` (or `openapi-3.1`) when generating OpenAPI documents.
1086
+ */
1087
+ declare function convertRouteSchema(schema: Record<string, unknown>, target?: JsonSchemaTarget): Record<string, unknown>;
1088
+ //#endregion
1089
+ //#region src/utils/simpleEqualityMatcher.d.ts
1090
+ /**
1091
+ * `simpleEqualityMatcher` — a minimal, dialect-agnostic flat-key equality
1092
+ * matcher for `DataAdapter.matchesFilter` / `BaseController({ matchesFilter })`.
1093
+ *
1094
+ * **What it does:** for each `[key, expected]` in the filter, compares
1095
+ * `item[key]` to `expected` via string coercion (so Mongo `ObjectId` values
1096
+ * match their string representation) and returns `true` only if every
1097
+ * filter entry matches. Array item values are matched implicitly (contains).
1098
+ *
1099
+ * **What it does NOT do:**
1100
+ * - No `$eq` / `$ne` / `$in` / `$nin` / `$gt` / `$lt` / `$regex` / `$exists`
1101
+ * - No `$and` / `$or`
1102
+ * - No dot-path traversal (`"owner.id"`)
1103
+ * - No schema-specific coercion
1104
+ *
1105
+ * **Why it exists:** 95%+ of arc's `_policyFilters` are produced by built-in
1106
+ * permission helpers and are shaped like `{ ownerId: "u1" }` or
1107
+ * `{ organizationId: "org_x" }` — flat equality. For that common shape,
1108
+ * this helper is a safe, tested, 15-line defense-in-depth matcher that
1109
+ * hosts using minimal repos (no `getOne(compoundFilter)` DB path) can opt
1110
+ * into without arc shipping a full Mongo-syntax engine.
1111
+ *
1112
+ * **When to use:**
1113
+ * - Your adapter/repo doesn't natively filter on `getOne(compoundFilter)`
1114
+ * - Your `_policyFilters` are flat equality (from arc's built-in permission helpers)
1115
+ * - You want defense-in-depth on `validateItemAccess` / `fetchDetailed`'s `getById` fallback
1116
+ *
1117
+ * **When NOT to use:**
1118
+ * - Your `_policyFilters` use operators (`$in`, `$ne`, etc.) — supply a
1119
+ * native matcher (mongokit's repo does the filter at the DB layer; for
1120
+ * custom repos, wrap the kit's own predicate engine).
1121
+ * - You're a mongokit / sqlitekit / Prisma user — the DB-level filter
1122
+ * applied by `getOne(compoundFilter)` already covers this.
1123
+ *
1124
+ * @example
1125
+ * ```ts
1126
+ * import { simpleEqualityMatcher } from '@classytic/arc/utils';
1127
+ *
1128
+ * // On a custom adapter
1129
+ * const adapter: DataAdapter = {
1130
+ * repository,
1131
+ * type: 'custom',
1132
+ * name: 'in-memory',
1133
+ * matchesFilter: simpleEqualityMatcher,
1134
+ * };
1135
+ *
1136
+ * // Or directly on BaseController for ad-hoc controllers
1137
+ * new BaseController(repo, { matchesFilter: simpleEqualityMatcher });
1138
+ * ```
1139
+ */
1140
+ declare function simpleEqualityMatcher(item: unknown, filters: Record<string, unknown>): boolean;
1141
+ //#endregion
1142
+ //#region src/utils/stateMachine.d.ts
1143
+ /**
1144
+ * State Machine Utility
1145
+ *
1146
+ * Pure utility for validating state transitions in workflow systems.
1147
+ * Zero dependencies, framework-agnostic.
1148
+ *
1149
+ * @example
1150
+ * const orderState = createStateMachine('Order', {
1151
+ * approve: ['pending', 'draft'],
1152
+ * cancel: ['pending', 'approved'],
1153
+ * fulfill: ['approved'],
1154
+ * });
1155
+ *
1156
+ * // Check if transition is allowed
1157
+ * if (orderState.can('approve', currentStatus)) {
1158
+ * // Perform approval
1159
+ * }
1160
+ *
1161
+ * // Assert transition (throws if invalid)
1162
+ * orderState.assert('approve', currentStatus, ValidationError);
1163
+ */
1164
+ interface StateMachine {
1165
+ /**
1166
+ * Synchronously check if action can be performed from current status.
1167
+ * Only checks the transition map — does NOT evaluate guards.
1168
+ * Use `canAsync()` when guards need to be evaluated.
1169
+ */
1170
+ can(action: string, status: string | null | undefined): boolean;
1171
+ /**
1172
+ * Asynchronously check if action can be performed, including guard evaluation.
1173
+ * Falls back to simple transition check when no guard is defined.
1174
+ */
1175
+ canAsync(action: string, status: string | null | undefined, context?: Record<string, unknown>): Promise<boolean>;
1176
+ /**
1177
+ * Assert action can be performed, throw error if invalid
1178
+ * @param action - Action to perform
1179
+ * @param status - Current status
1180
+ * @param errorFactory - Optional error constructor
1181
+ * @param message - Optional custom error message
1182
+ */
1183
+ assert(action: string, status: string | null | undefined, errorFactory?: (msg: string) => Error, message?: string): void;
1184
+ /**
1185
+ * Get transition history
1186
+ */
1187
+ getHistory?(): TransitionHistoryEntry[];
1188
+ /**
1189
+ * Record a transition
1190
+ */
1191
+ recordTransition?(from: string, to: string, action: string, metadata?: Record<string, unknown>): void;
1192
+ /**
1193
+ * Clear history
1194
+ */
1195
+ clearHistory?(): void;
1196
+ /**
1197
+ * Get available actions for current status
1198
+ */
1199
+ getAvailableActions?(status: string): string[];
1200
+ }
1201
+ interface TransitionHistoryEntry {
1202
+ from: string;
1203
+ to: string;
1204
+ action: string;
1205
+ timestamp: Date;
1206
+ metadata?: Record<string, unknown>;
1207
+ }
1208
+ /** Context passed to transition guards and actions */
1209
+ interface TransitionContext {
1210
+ from: string;
1211
+ to: string;
1212
+ action: string;
1213
+ data?: Record<string, unknown>;
1214
+ }
1215
+ type TransitionGuard = (context: TransitionContext) => boolean | Promise<boolean>;
1216
+ type TransitionAction = (context: TransitionContext) => void | Promise<void>;
1217
+ type TransitionConfig = Record<string, string[] | {
1218
+ from: string[];
1219
+ to?: string;
1220
+ guard?: TransitionGuard;
1221
+ before?: TransitionAction;
1222
+ after?: TransitionAction;
1223
+ }>;
1224
+ /**
1225
+ * Create a state machine for validating transitions
1226
+ *
1227
+ * @param name - Name of the state machine (used in error messages)
1228
+ * @param transitions - Map of actions to allowed source statuses
1229
+ * @param options - Additional options (history, guards, actions)
1230
+ * @returns State machine with can() and assert() methods
1231
+ *
1232
+ * @example
1233
+ * // Basic usage
1234
+ * const transferState = createStateMachine('Transfer', {
1235
+ * approve: ['draft'],
1236
+ * dispatch: ['approved'],
1237
+ * receive: ['dispatched', 'in_transit'],
1238
+ * cancel: ['draft', 'approved'],
1239
+ * });
1240
+ *
1241
+ * @example
1242
+ * // With guards and actions
1243
+ * const orderState = createStateMachine('Order', {
1244
+ * approve: {
1245
+ * from: ['pending'],
1246
+ * to: 'approved',
1247
+ * guard: ({ data }) => data.paymentConfirmed,
1248
+ * before: ({ from, to }) => console.log(`Approving order from ${from} to ${to}`),
1249
+ * after: ({ data }) => sendApprovalEmail(data.customerId),
1250
+ * },
1251
+ * }, { trackHistory: true });
1252
+ */
1253
+ declare function createStateMachine(name: string, transitions?: TransitionConfig, options?: {
1254
+ trackHistory?: boolean;
1255
+ }): StateMachine;
1256
+ //#endregion
1257
+ //#region src/utils/typeGuards.d.ts
1258
+ interface EventsDecorator {
1259
+ publish: <T>(type: string, payload: T, meta?: Record<string, unknown>) => Promise<void>;
1260
+ subscribe: (pattern: string, handler: (event: {
1261
+ type: string;
1262
+ payload: unknown;
1263
+ meta: Record<string, unknown>;
1264
+ }) => Promise<void>) => Promise<() => void>;
1265
+ transportName: string;
1266
+ }
1267
+ /** Check if fastify has the events plugin registered */
1268
+ declare function hasEvents(instance: FastifyInstance): instance is FastifyInstance & {
1269
+ events: EventsDecorator;
1270
+ };
1271
+ //#endregion
1272
+ //#region src/utils/userHelpers.d.ts
1273
+ /**
1274
+ * Extract a user ID from a user object. Accepts `id` or `_id` — returns
1275
+ * `undefined` when neither is present. Used by arc's controllers to
1276
+ * populate `createdBy` / `updatedBy` fields and for cache scoping.
1277
+ *
1278
+ * @example
1279
+ * ```ts
1280
+ * import { getUserId } from '@classytic/arc/utils';
1281
+ * const uid = getUserId(request.user);
1282
+ * ```
1283
+ */
1284
+ declare function getUserId(user: UserLike | null | undefined): string | undefined;
1285
+ //#endregion
1286
+ export { ArcError, ArcQueryParser, type ArcQueryParserOptions, CircuitBreaker, CircuitBreakerError, type CircuitBreakerOptions, CircuitBreakerRegistry, type CircuitBreakerStats, CircuitState, type CompensationDefinition, type CompensationError, type CompensationHooks, type CompensationResult, type CompensationStep, type ConfigError, ConflictError, type ErrorOptions, type EventsDecorator, ForbiddenError, type Guard, type GuardConfig, type JsonSchema, type JsonSchemaTarget, NotFoundError, OrgAccessDeniedError, OrgRequiredError, RateLimitError, ServiceUnavailableError, type StateMachine, type TransitionConfig, UnauthorizedError, type ValidateOptions, ValidationError, type ValidationResult, aggregateListResponse, assertValidConfig, bareListResponse, convertOpenApiSchemas, convertRouteSchema, createCircuitBreaker, createCircuitBreakerRegistry, createDomainError, createError, createQueryParser, createStateMachine, defineCompensation, defineErrorMapper, defineGuard, deleteResponse, errorContractSchema, errorDetailSchema, formatValidationErrors, getDefaultCrudSchemas, getListQueryParams, getUserId, handleRaw, hasEvents, isArcError, isJsonSchema, isZodSchema, keysetListResponse, listResponse, offsetListResponse, paginationSchema, queryParams, responses, scheduleBackground, simpleEqualityMatcher, toJsonSchema, validateResourceConfig, withCompensation };