@classytic/arc 2.21.0 → 2.22.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 (94) hide show
  1. package/dist/{BaseController-BnLYgE9A.mjs → BaseController-C6FlRWxF.mjs} +1 -1
  2. package/dist/audit/index.d.mts +2 -2
  3. package/dist/auth/index.d.mts +30 -2
  4. package/dist/auth/index.mjs +5 -2
  5. package/dist/cli/commands/describe.d.mts +1 -1
  6. package/dist/cli/commands/docs.mjs +1 -1
  7. package/dist/cli/commands/init.mjs +1 -1
  8. package/dist/cli/index.mjs +1 -1
  9. package/dist/core/index.d.mts +2 -2
  10. package/dist/core/index.mjs +2 -2
  11. package/dist/{core-DZ6Xe1jR.mjs → core-b6fgFgnd.mjs} +123 -66
  12. package/dist/{createActionRouter-BWMDW-dL.mjs → createActionRouter-h1cEEaEX.mjs} +9 -5
  13. package/dist/{createAggregationRouter-l5mNdYrZ.mjs → createAggregationRouter-B1C0kvTL.mjs} +3 -3
  14. package/dist/{createApp-Bi61XxqU.mjs → createApp-Ci7yG5gv.mjs} +242 -56
  15. package/dist/docs/index.d.mts +1 -1
  16. package/dist/docs/index.mjs +1 -1
  17. package/dist/encryption/index.mjs +9 -5
  18. package/dist/{errorHandler-Dxf6P_kV.mjs → errorHandler-BTzXSwIg.mjs} +24 -3
  19. package/dist/{errorHandler-B0e-bq-O.d.mts → errorHandler-C6yv4ZTW.d.mts} +13 -0
  20. package/dist/factory/index.d.mts +29 -8
  21. package/dist/factory/index.mjs +34 -3
  22. package/dist/{fastify-augmentation-DafigGQp.d.mts → fastify-augmentation-9_fuetB4.d.mts} +2 -2
  23. package/dist/fields-D3lhgzhD.d.mts +121 -0
  24. package/dist/health-ScyjIVo5.mjs +202 -0
  25. package/dist/hooks/index.d.mts +1 -1
  26. package/dist/idempotency/index.mjs +2 -0
  27. package/dist/{types-DpxoNX5v.d.mts → index-BEu4wjbL.d.mts} +187 -66
  28. package/dist/{index-B5N-NaHs.d.mts → index-D8MKYGDa.d.mts} +3 -3
  29. package/dist/{index-Dtrj6XZk.d.mts → index-DbtgCOCj.d.mts} +1287 -1225
  30. package/dist/{index-B5PoNbfu.d.mts → index-ogIHvOjo.d.mts} +1 -1
  31. package/dist/index.d.mts +6 -5
  32. package/dist/index.mjs +3 -3
  33. package/dist/{init-0YhHkXGk.mjs → init-DleK3p9f.mjs} +118 -2
  34. package/dist/integrations/index.d.mts +1 -1
  35. package/dist/integrations/mcp/index.d.mts +3 -3
  36. package/dist/integrations/mcp/index.mjs +1 -1
  37. package/dist/integrations/mcp/testing.d.mts +1 -1
  38. package/dist/integrations/mcp/testing.mjs +1 -1
  39. package/dist/integrations/webhooks.d.mts +8 -4
  40. package/dist/integrations/webhooks.mjs +9 -5
  41. package/dist/jsonBody-BlzAoGCe.mjs +43 -0
  42. package/dist/logger/index.d.mts +26 -1
  43. package/dist/logger/index.mjs +39 -1
  44. package/dist/{mcpPlugin-B9XjjNVG.mjs → mcpPlugin-ByA2tf6D.mjs} +6 -2
  45. package/dist/middleware/index.d.mts +1 -1
  46. package/dist/{module-WeuU5jfd.d.mts → module-B4u10iOJ.d.mts} +26 -1
  47. package/dist/{openapi-Kyod_di6.mjs → openapi-BRpMZD7C.mjs} +2 -2
  48. package/dist/permissions/index.d.mts +3 -2
  49. package/dist/pipeline/index.d.mts +1 -1
  50. package/dist/plugins/index.d.mts +22 -5
  51. package/dist/plugins/index.mjs +11 -280
  52. package/dist/plugins/response-cache.mjs +1 -0
  53. package/dist/plugins/tracing-entry.mjs +7 -4
  54. package/dist/presets/filesUpload.d.mts +2 -2
  55. package/dist/presets/index.d.mts +1 -1
  56. package/dist/presets/multiTenant.d.mts +1 -1
  57. package/dist/presets/search.d.mts +2 -2
  58. package/dist/rateLimitKey-BoWRH3e7.mjs +14 -0
  59. package/dist/{registerRoute-oGAl0oA8.mjs → registerRoute-xHc42fwB.mjs} +37 -17
  60. package/dist/registry/index.d.mts +2 -2
  61. package/dist/requestId-5BhTVzBv.mjs +113 -0
  62. package/dist/schemaConverter-Ds5reSGs.mjs +168 -0
  63. package/dist/{schemaIR-ajetw3Fv.mjs → schemaIR-B-6SPe7g.mjs} +2 -2
  64. package/dist/scim/index.mjs +6 -7
  65. package/dist/scope/index.mjs +2 -76
  66. package/dist/scope-k15RXfcq.mjs +64 -0
  67. package/dist/testing/index.d.mts +83 -3
  68. package/dist/testing/index.mjs +70 -3
  69. package/dist/types/index.d.mts +2 -2
  70. package/dist/{types-DRj-Ut4n.d.mts → types-Bc42CUyk.d.mts} +1 -1
  71. package/dist/{fields-BGqrAa_u.d.mts → types-Csxga7d3.d.mts} +1 -121
  72. package/dist/usage/index.d.mts +142 -0
  73. package/dist/usage/index.mjs +0 -0
  74. package/dist/utils/index.d.mts +40 -18
  75. package/dist/utils/index.mjs +2 -2
  76. package/dist/{utils-CO8a3B_1.mjs → utils-FhJ88TJE.mjs} +59 -13
  77. package/dist/{versioning-DQ4mCvg0.d.mts → versioning-DLwklPlG.d.mts} +0 -5
  78. package/llms.txt +39 -0
  79. package/package.json +453 -447
  80. package/skills/arc/SKILL.md +14 -8
  81. package/skills/arc/references/api-reference.md +34 -0
  82. package/skills/arc/references/auth.md +21 -4
  83. package/skills/arc/references/mcp.md +1 -1
  84. package/skills/arc/references/production.md +44 -2
  85. package/skills/arc-code-review/SKILL.md +1 -1
  86. package/skills/arc-code-review/references/anti-patterns.md +71 -18
  87. package/skills/arc-code-review/references/arc-cheatsheet.md +15 -2
  88. package/skills/arc-code-review/references/migration-recipes.md +7 -7
  89. package/skills/arc-code-review/references/mongokit-migration.md +4 -3
  90. package/skills/arc-module-publishing/SKILL.md +2 -1
  91. package/skills/arc-module-publishing/references/authoring-modules.md +55 -0
  92. package/skills/arc-module-publishing/references/package-manifest.md +4 -2
  93. package/dist/preloadResources-CHw3_oA_.mjs +0 -45
  94. package/dist/schemaConverter-U0MnO9vd.mjs +0 -110
@@ -1,7 +1,8 @@
1
1
  import { a as QueryCacheConfig } from "./QueryCache-Z1B38koh.mjs";
2
2
  import { i as RequestScope } from "./types-DH0GupI7.mjs";
3
- import { c as PermissionCheck, d as UserBase, n as FieldPermissionMap } from "./fields-BGqrAa_u.mjs";
3
+ import { i as UserBase, t as PermissionCheck } from "./types-Csxga7d3.mjs";
4
4
  import "./elevation-C9s5hFP_.mjs";
5
+ import { n as FieldPermissionMap } from "./fields-D3lhgzhD.mjs";
5
6
  import { n as EncryptionDirective } from "./types-Cc91nXuA.mjs";
6
7
  import { n as DomainEvent } from "./EventTransport-QmY7A258.mjs";
7
8
  import { KeysetPaginationResult, OffsetPaginationResult } from "@classytic/repo-core/pagination";
@@ -1305,1287 +1306,1070 @@ interface AuthPluginOptions {
1305
1306
  strictTokenType?: boolean;
1306
1307
  }
1307
1308
  //#endregion
1308
- //#region src/pipeline/types.d.ts
1309
- /**
1310
- * Pipeline context passed to guards, transforms, and interceptors.
1311
- * Extends IRequestContext with pipeline-specific metadata.
1312
- */
1313
- interface PipelineContext extends IRequestContext {
1314
- /** Resource name being accessed */
1315
- resource: string;
1316
- /** CRUD operation being performed */
1317
- operation: "list" | "get" | "create" | "update" | "delete" | string;
1318
- }
1319
- /**
1320
- * Which operations a pipeline step applies to.
1321
- * If omitted, applies to ALL operations.
1322
- */
1323
- type OperationFilter = Array<"list" | "get" | "create" | "update" | "delete" | string>;
1324
- /**
1325
- * Guard — boolean check that short-circuits on failure.
1326
- * Return true to proceed, throw to deny.
1327
- */
1328
- interface Guard {
1329
- readonly _type: "guard";
1330
- readonly name: string;
1331
- readonly operations?: OperationFilter;
1332
- handler(ctx: PipelineContext): boolean | Promise<boolean>;
1333
- }
1334
- /**
1335
- * Transform — modifies request data before the handler.
1336
- * Returns modified context (or mutates in place).
1337
- */
1338
- interface Transform {
1339
- readonly _type: "transform";
1340
- readonly name: string;
1341
- readonly operations?: OperationFilter;
1342
- handler(ctx: PipelineContext): PipelineContext | undefined | Promise<PipelineContext | undefined>;
1343
- }
1344
- /**
1345
- * Next function passed to interceptors — calls the handler (or next interceptor).
1346
- */
1347
- type NextFunction = () => Promise<IControllerResponse<unknown>>;
1309
+ //#region src/types/handlers.d.ts
1348
1310
  /**
1349
- * Intercept — wraps handler execution (before + after pattern).
1311
+ * Minimal server accessor — exposes safe, read-only server decorators.
1312
+ * Allows controller handlers to publish events, log, and audit
1313
+ * without switching to `raw: true`.
1350
1314
  */
1351
- interface Interceptor {
1352
- readonly _type: "interceptor";
1353
- readonly name: string;
1354
- readonly operations?: OperationFilter;
1355
- handler(ctx: PipelineContext, next: NextFunction): Promise<IControllerResponse<unknown>>;
1315
+ interface ServerAccessor {
1316
+ /** Event bus — publish domain events from any handler */
1317
+ events?: {
1318
+ publish: <T>(type: string, payload: T, meta?: Partial<Record<string, unknown>>) => Promise<void>;
1319
+ };
1320
+ /** Audit logger — log custom audit entries */
1321
+ audit?: {
1322
+ create: (resource: string, documentId: string, data: Record<string, unknown>, context?: Record<string, unknown>) => Promise<void>;
1323
+ update: (resource: string, documentId: string, before: Record<string, unknown>, after: Record<string, unknown>, context?: Record<string, unknown>) => Promise<void>;
1324
+ delete: (resource: string, documentId: string, data: Record<string, unknown>, context?: Record<string, unknown>) => Promise<void>;
1325
+ custom: (resource: string, documentId: string, action: string, data?: Record<string, unknown>, context?: Record<string, unknown>) => Promise<void>;
1326
+ };
1327
+ /** Logger — structured logging */
1328
+ log?: {
1329
+ info: (...args: unknown[]) => void;
1330
+ warn: (...args: unknown[]) => void;
1331
+ error: (...args: unknown[]) => void;
1332
+ debug: (...args: unknown[]) => void;
1333
+ };
1334
+ /** QueryCache — stale-while-revalidate data cache */
1335
+ queryCache?: {
1336
+ get: <T>(key: string) => Promise<{
1337
+ data: T;
1338
+ status: "fresh" | "stale" | "miss";
1339
+ }>;
1340
+ set: <T>(key: string, data: T, config: {
1341
+ staleTime?: number;
1342
+ gcTime?: number;
1343
+ tags?: string[];
1344
+ }) => Promise<void>;
1345
+ getResourceVersion: (resource: string) => Promise<number>;
1346
+ bumpResourceVersion: (resource: string) => Promise<void>;
1347
+ };
1356
1348
  }
1357
- type PipelineStep = Guard | Transform | Interceptor;
1358
- /**
1359
- * Pipeline configuration — can be a flat array or per-operation map.
1360
- */
1361
- type PipelineConfig = PipelineStep[] | {
1362
- list?: PipelineStep[];
1363
- get?: PipelineStep[];
1364
- create?: PipelineStep[];
1365
- update?: PipelineStep[];
1366
- delete?: PipelineStep[];
1367
- [operation: string]: PipelineStep[] | undefined;
1368
- };
1369
- //#endregion
1370
- //#region src/core/aggregation/types.d.ts
1371
1349
  /**
1372
- * Sugar for measures: `'count'` / `'count:field'` / `'sum:price'` /
1373
- * `'avg:rating'` / `'min:created'` / `'max:updated'` /
1374
- * `'countDistinct:userId'` / `'percentile:latency:0.95'`.
1350
+ * Request context passed to controller handlers.
1375
1351
  *
1376
- * Compiles to the canonical `AggMeasure` IR at boot. Hosts who want
1377
- * the full IR can pass an `AggMeasure` object directly.
1352
+ * **Generic parameters** (all default to safe permissive types so existing code keeps working):
1353
+ * - `TBody` — request body shape (default: `unknown`)
1354
+ * - `TParams` — route param shape (default: `Record<string, string>`)
1355
+ * - `TQuery` — query string shape (default: `Record<string, unknown>`)
1356
+ * - `TUser` — authenticated user shape (default: `UserBase`)
1357
+ * - `TMetadata` — internal metadata shape (default: `Record<string, unknown>`;
1358
+ * override with `ArcInternalMetadata` or your own augmentation when you
1359
+ * need typed access to `_scope`, `_policyFilters`, custom hook context, etc.)
1378
1360
  *
1379
- * **Percentile.** `'percentile:<field>:<p>'` where `p` is a numeric
1380
- * literal in `[0, 1]` (e.g. `'percentile:latency:0.95'` for P95).
1381
- * Mongokit (≥3.13) compiles to `$percentile`; sqlitekit throws
1382
- * `UnsupportedOperationError` (no native percentile in SQLite).
1361
+ * @example
1362
+ * ```typescript
1363
+ * // Untyped (default) — req.body is `unknown`, must be narrowed
1364
+ * async create(req: IRequestContext) {
1365
+ * const data = req.body as Partial<Product>;
1366
+ * return { success: true, data: await productRepo.create(data) };
1367
+ * }
1368
+ *
1369
+ * // Typed body — req.body is `CreateProductInput`, narrowing not needed
1370
+ * async create(req: IRequestContext<CreateProductInput>) {
1371
+ * return { success: true, data: await productRepo.create(req.body) };
1372
+ * }
1373
+ *
1374
+ * // Fully typed — body, route params, query, and metadata
1375
+ * async update(
1376
+ * req: IRequestContext<
1377
+ * Partial<Product>,
1378
+ * { id: string },
1379
+ * { fields?: string },
1380
+ * ArcInternalMetadata
1381
+ * >,
1382
+ * ) {
1383
+ * const fields = req.query.fields?.split(',');
1384
+ * const orgId = req.metadata?._scope ? getOrgId(req.metadata._scope) : undefined;
1385
+ * return { success: true, data: await productRepo.update(req.params.id, req.body) };
1386
+ * }
1387
+ * ```
1383
1388
  */
1384
- type AggMeasureShorthand = "count" | `count:${string}` | `countDistinct:${string}` | `sum:${string}` | `avg:${string}` | `min:${string}` | `max:${string}` | `percentile:${string}:${number}`;
1385
- /** Either canonical IR or shorthand string — both compile to `AggMeasure`. */
1386
- type AggMeasureInput = AggMeasure | AggMeasureShorthand;
1387
1389
  /**
1388
- * Cache config for an aggregation. Translates directly to the kit-side
1389
- * `CacheOptions` (TanStack-shaped) which the unified
1390
- * `@classytic/repo-core/cache` plugin reads from `req.cache`.
1390
+ * First-class projection of `request._scope` for controller handlers.
1391
1391
  *
1392
- * Caching only fires when the kit's repo has the `cachePlugin` wired —
1393
- * arc declares the policy; the kit handles SWR + tag invalidation +
1394
- * version-bump on writes. Hosts without the plugin installed silently
1395
- * fall through to a non-cached call.
1392
+ * **v2.10.6:** previously, pulling tenant/user/role info from inside a
1393
+ * controller override meant digging through `req.metadata._scope` and
1394
+ * calling `getOrgId(scope)` / `getUserId(user)` manually. This projection
1395
+ * lifts the two fields most hosts need directly onto `req` so cross-kit
1396
+ * controller code reads:
1397
+ *
1398
+ * ```ts
1399
+ * async create(req: IRequestContext) {
1400
+ * const flowCtx = { organizationId: req.scope?.organizationId, actorId: req.scope?.userId };
1401
+ * }
1402
+ * ```
1403
+ *
1404
+ * Full scope shape (discriminated union of `member` / `service` / `elevated` / `public`)
1405
+ * still lives on `req.metadata._scope` for code that needs to branch on
1406
+ * `scope.kind` — this projection just surfaces the two keys every
1407
+ * tenant-scoped resource reaches for.
1396
1408
  */
1397
- interface AggregationCacheConfig {
1398
- /** Seconds the entry is fresh — no revalidation while inside this window. */
1399
- staleTime?: number;
1400
- /** Seconds the entry stays in cache past stale before eviction. Default: 60. */
1401
- gcTime?: number;
1409
+ interface RequestScopeProjection {
1410
+ /** Tenant the caller is scoped to (org member, service key bound to an org, or elevated admin's target org). */
1411
+ organizationId?: string;
1412
+ /** Caller's user id when authenticated — undefined for public / service-only scopes. */
1413
+ userId?: string;
1414
+ /** Org-level roles (e.g. `['admin', 'warehouse-manager']`) — separate from global `user.roles`. */
1415
+ orgRoles?: string[];
1416
+ }
1417
+ interface IRequestContext<TBody = unknown, TParams extends Record<string, string> = Record<string, string>, TQuery extends Record<string, unknown> = Record<string, unknown>, TUser extends UserBase = UserBase, TMetadata extends Record<string, unknown> = Record<string, unknown>> {
1418
+ /** Route parameters (e.g., { id: '123' }) */
1419
+ params: TParams;
1420
+ /** Query string parameters */
1421
+ query: TQuery;
1422
+ /** Request body */
1423
+ body: TBody;
1424
+ /** Authenticated user or null */
1425
+ user: TUser | null;
1426
+ /** Request headers */
1427
+ headers: Record<string, string | undefined>;
1428
+ /** Organization ID (for multi-tenant apps) */
1429
+ organizationId?: string;
1430
+ /** Team ID (for team-scoped resources) */
1431
+ teamId?: string;
1402
1432
  /**
1403
- * Stale-while-revalidate. When stale entries serve immediately and a
1404
- * background refresh updates the cache. Default: `true` for
1405
- * aggregations (dashboards almost always benefit from stale-serve).
1433
+ * First-class tenant/user scope projection — lifted from `metadata._scope`
1434
+ * so controller overrides don't have to dig through Arc internals.
1435
+ * See {@link RequestScopeProjection}. `undefined` for routes that run
1436
+ * without auth / scope resolution.
1406
1437
  */
1407
- swr?: boolean;
1438
+ scope?: RequestScopeProjection;
1408
1439
  /**
1409
- * Group invalidation tags. Pass to `repo.cache?.invalidateByTags(tags)`
1410
- * after a write to clear matching entries. The model name is
1411
- * auto-tagged by the plugin — you only declare cross-cutting tags
1412
- * (e.g. `'pricing'` to invalidate every aggregation that depends on
1413
- * pricing across multiple resources).
1440
+ * Organization/auth context from middleware.
1441
+ * Contains orgRoles, orgScope, organizationId, and any custom fields
1442
+ * set by the auth adapter or org-scope plugin.
1443
+ *
1444
+ * @example
1445
+ * ```typescript
1446
+ * async create(req: IRequestContext) {
1447
+ * const roles = req.context?.orgRoles ?? [];
1448
+ * if (roles.includes('manager')) { ... }
1449
+ * }
1450
+ * ```
1414
1451
  */
1415
- tags?: readonly string[];
1452
+ context?: RequestContext;
1453
+ /**
1454
+ * Internal metadata (includes context + Arc internals like `_policyFilters`,
1455
+ * `_scope`, `log`). Type as `ArcInternalMetadata` for typed access to Arc's
1456
+ * built-in fields, or supply your own interface to layer custom fields.
1457
+ */
1458
+ metadata?: TMetadata;
1459
+ /**
1460
+ * Fastify server accessor — publish events, log, and audit
1461
+ * from any handler without switching to `raw: true`.
1462
+ *
1463
+ * @example
1464
+ * ```typescript
1465
+ * async reschedule(req: IRequestContext) {
1466
+ * const result = await repo.reschedule(req.params.id, req.body);
1467
+ * await req.server?.events?.publish('interview.rescheduled', { data: result });
1468
+ * return { data: result };
1469
+ * }
1470
+ * ```
1471
+ */
1472
+ server?: ServerAccessor;
1416
1473
  }
1417
1474
  /**
1418
- * Per-aggregation rate limit. Layers on top of any global rate limit
1419
- * via `@fastify/rate-limit` route-level config.
1475
+ * Controller response shape — the success-path return from any handler.
1476
+ *
1477
+ * Errors throw `ArcError` (or any `HttpError`-shaped class); the global
1478
+ * error handler catches them and emits an `ErrorContract`. There is no
1479
+ * `success` discriminator on the response — HTTP status is the wire
1480
+ * discriminator (2xx = data, 4xx/5xx = ErrorContract).
1420
1481
  */
1421
- interface AggregationRateLimit {
1422
- /** Max requests per window. */
1423
- max: number;
1424
- /** Window in milliseconds. */
1425
- windowMs: number;
1482
+ interface IControllerResponse<T = unknown> {
1483
+ /** Response payload — emitted directly to the wire (no envelope wrap). */
1484
+ data: T;
1485
+ /** HTTP status code. Defaults to 200. */
1486
+ status?: number;
1487
+ /** Custom response headers (e.g. X-Total-Count, Link, ETag). */
1488
+ headers?: Record<string, string>;
1489
+ /** Top-level metadata merged into list-shaped responses (e.g. `{ took }`). */
1490
+ meta?: Record<string, unknown>;
1426
1491
  }
1427
1492
  /**
1428
- * Required date-range narrowing. Caller MUST send a bounded range on
1429
- * this field, and the range MUST NOT exceed `maxRangeDays`.
1493
+ * Controller handler — Arc's standard pattern.
1430
1494
  *
1431
- * Prevents "all-time" scans on billion-row collections — the single
1432
- * biggest performance footgun for live aggregation endpoints.
1495
+ * Receives a request context object, returns IControllerResponse.
1496
+ * Use with `raw: false` in routes.
1497
+ *
1498
+ * **Generic parameters:**
1499
+ * - `TResponse` — shape of `IControllerResponse.data` (default: `unknown`)
1500
+ * - `TBody` — shape of `req.body` (default: `unknown`)
1501
+ * - `TParams` — shape of `req.params` (default: `Record<string, string>`)
1502
+ * - `TQuery` — shape of `req.query` (default: `Record<string, unknown>`)
1503
+ *
1504
+ * Backward-compatible: `ControllerHandler<Product>` still works (only the
1505
+ * response data is typed); add more generics as needed when you want
1506
+ * type-safe access to the request body, params, or query string.
1507
+ *
1508
+ * @example
1509
+ * ```typescript
1510
+ * // Untyped req — body is unknown, must be narrowed
1511
+ * const createProduct: ControllerHandler<Product> = async (req) => {
1512
+ * const product = await productRepo.create(req.body as Partial<Product>);
1513
+ * return { data: product, status: 201 };
1514
+ * };
1515
+ *
1516
+ * // Fully typed — body, params, query, and response all inferred
1517
+ * const updateProduct: ControllerHandler<
1518
+ * Product,
1519
+ * Partial<Product>,
1520
+ * { id: string },
1521
+ * { upsert?: string }
1522
+ * > = async (req) => {
1523
+ * const upsert = req.query.upsert === "true";
1524
+ * const product = await productRepo.update(req.params.id, req.body, { upsert });
1525
+ * return { data: product };
1526
+ * };
1527
+ *
1528
+ * routes: [{
1529
+ * method: 'POST',
1530
+ * path: '/products',
1531
+ * handler: createProduct,
1532
+ * permissions: requireAuth(),
1533
+ * raw: false, // Arc wraps this into Fastify handler
1534
+ * }]
1535
+ * ```
1433
1536
  */
1434
- interface AggregationDateRangeRequirement {
1435
- /** Field whose range the caller must narrow (e.g. `'createdAt'`). */
1436
- field: string;
1437
- /**
1438
- * Cap on the queryable range. A request asking for >N days is
1439
- * rejected 400. Omit for "any range, but bounded" (lower + upper
1440
- * required, no cap).
1441
- */
1442
- maxRangeDays?: number;
1443
- }
1537
+ type ControllerHandler<TResponse = unknown, TBody = unknown, TParams extends Record<string, string> = Record<string, string>, TQuery extends Record<string, unknown> = Record<string, unknown>> = (req: IRequestContext<TBody, TParams, TQuery>) => Promise<IControllerResponse<TResponse>>;
1444
1538
  /**
1445
- * Boot-time index hint. Arc warns when the kit's schema doesn't have
1446
- * an index whose leading keys match — flags the misconfig before
1447
- * traffic hits the DB.
1539
+ * Fastify native handler
1448
1540
  *
1449
- * Documented intent, NOT runtime-enforced. Kits with their own index
1450
- * introspection (mongokit reads Mongoose schema, sqlitekit reads
1451
- * Drizzle indexes) can act on the hint; kits without introspection
1452
- * silently accept it.
1541
+ * Standard Fastify request/reply pattern.
1542
+ * Use with `raw: true` in routes.
1543
+ *
1544
+ * @example
1545
+ * ```typescript
1546
+ * const downloadFile: FastifyHandler = async (request, reply) => {
1547
+ * const file = await getFile(request.params.id);
1548
+ * reply.header('Content-Type', file.mimeType);
1549
+ * return reply.send(file.buffer);
1550
+ * };
1551
+ *
1552
+ * routes: [{
1553
+ * method: 'GET',
1554
+ * path: '/files/:id/download',
1555
+ * handler: downloadFile,
1556
+ * permissions: requireAuth(),
1557
+ * raw: true, // Use as-is, no wrapping
1558
+ * }]
1559
+ * ```
1453
1560
  */
1454
- interface AggregationIndexHint {
1455
- /** Leading-key columns the host expects the planner to use. */
1456
- leadingKeys: readonly string[];
1561
+ type FastifyHandler<RouteGeneric extends Record<string, unknown> = Record<string, unknown>> = (request: FastifyRequest<RouteGeneric>, reply: FastifyReply) => Promise<unknown> | unknown;
1562
+ /**
1563
+ * Union type for route handlers
1564
+ */
1565
+ type RouteHandler = ControllerHandler | FastifyHandler;
1566
+ /**
1567
+ * Controller interface for CRUD operations (strict).
1568
+ *
1569
+ * `list`'s return type aligns with repo-core's `MinimalRepo.getAll()`
1570
+ * contract — the kit MAY return an offset envelope, a keyset envelope,
1571
+ * or a raw array. Arc's `BaseController` forwards the kit's response
1572
+ * verbatim; consumers narrow on shape
1573
+ * (`Array.isArray(data)` → bare array, presence of `total` → offset,
1574
+ * presence of `nextCursor` → keyset).
1575
+ */
1576
+ interface IController<TDoc = unknown> {
1577
+ list(req: IRequestContext): Promise<IControllerResponse<unknown>>;
1578
+ get(req: IRequestContext): Promise<IControllerResponse<TDoc>>;
1579
+ create(req: IRequestContext): Promise<IControllerResponse<TDoc>>;
1580
+ update(req: IRequestContext): Promise<IControllerResponse<TDoc>>;
1581
+ delete(req: IRequestContext): Promise<IControllerResponse<{
1582
+ message: string;
1583
+ }>>;
1457
1584
  }
1458
1585
  /**
1459
- * Runtime context passed to the `materialized` hook.
1586
+ * Flexible controller interface — accepts controllers with any handler style,
1587
+ * including class instances with extra methods / private fields.
1460
1588
  *
1461
- * The hook returns pre-computed data instead of running the live
1462
- * aggregation. Hosts use this for ultra-frequent dashboards backed by
1463
- * rollup tables maintained out-of-band (cron / CDC).
1589
+ * **v2.10.6:** the previous `[key: string]: unknown` index signature made
1590
+ * real class instances fail structural assignment (`new ScrapController()`
1591
+ * needed a `as unknown as ControllerLike` cast, because class instances
1592
+ * don't have an index signature). Dropped — arc only invokes the CRUD
1593
+ * methods at runtime, so the rest of the shape is the caller's concern.
1594
+ *
1595
+ * The five CRUD slots stay optional so partial controllers (e.g. read-only)
1596
+ * assign too. Additional domain methods on the controller are allowed by
1597
+ * construction (they're just not part of this contract).
1464
1598
  */
1465
- interface AggregationMaterializedContext {
1466
- /** Compiled filter (host base + tenant + caller). */
1467
- filter: AnyRecord;
1468
- /** Tenant id when the resource is tenant-scoped. */
1469
- orgId?: string;
1470
- /** Authenticated user id, when present. */
1471
- userId?: string;
1472
- /** Fastify request id for tracing. */
1473
- requestId?: string;
1474
- /** Raw URL query params (post-validation). */
1475
- query: Record<string, unknown>;
1599
+ interface ControllerLike {
1600
+ list?: unknown;
1601
+ get?: unknown;
1602
+ create?: unknown;
1603
+ update?: unknown;
1604
+ delete?: unknown;
1476
1605
  }
1477
- /** Materialized hook return shape — same envelope as `AggResult`. */
1478
- interface AggregationMaterializedResult<TRow = AnyRecord> {
1479
- rows: readonly TRow[];
1606
+ //#endregion
1607
+ //#region src/types/resource/rate-limit.d.ts
1608
+ /**
1609
+ * Resource-level rate-limit shape — shared by `ResourceConfig.rateLimit`
1610
+ * and per-route `RouteDefinition.rateLimit` overrides.
1611
+ */
1612
+ interface RateLimitConfig {
1613
+ /** Maximum number of requests allowed within the time window */
1614
+ max: number;
1615
+ /** Time window for rate limiting (e.g., '1 minute', '15 seconds') */
1616
+ timeWindow: string;
1617
+ }
1618
+ //#endregion
1619
+ //#region src/types/resource/routes.d.ts
1620
+ /** HTTP methods for custom routes. */
1621
+ type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
1622
+ /** MCP tool configuration for a route or action. */
1623
+ interface RouteMcpConfig {
1624
+ /** Override auto-generated tool description */
1625
+ readonly description?: string;
1626
+ /** MCP tool annotations */
1627
+ readonly annotations?: {
1628
+ readonly readOnlyHint?: boolean;
1629
+ readonly destructiveHint?: boolean;
1630
+ readonly idempotentHint?: boolean;
1631
+ readonly openWorldHint?: boolean;
1632
+ };
1480
1633
  }
1481
1634
  /**
1482
- * Single named aggregation declaration. Composes into `AggRequest` at
1483
- * request time, with safety knobs layered on at the arc-handler level.
1635
+ * Route definition — single custom-route shape (user-facing + internal).
1636
+ *
1637
+ * - `handler: 'string'` → controller method → full Arc pipeline + MCP tool
1638
+ * - `handler: function` → inline handler → full Arc pipeline + MCP tool
1639
+ * - `raw: true` → raw Fastify handler → no pipeline, no MCP by default
1484
1640
  */
1485
- interface AggregationConfig {
1486
- /**
1487
- * Pre-aggregate filter on the BASE rows (before lookups). Always
1488
- * ANDed with auto-injected tenant scope + caller URL-narrowing
1489
- * filters. Use for host-defined invariants (e.g. `archived: false`).
1490
- */
1491
- filter?: AnyRecord;
1641
+ interface RouteDefinition {
1642
+ readonly method: RouteMethod;
1643
+ /** Path relative to resource prefix */
1644
+ readonly path: string;
1492
1645
  /**
1493
- * Cross-table joins. Each `LookupSpec` reuses the IR
1494
- * `@classytic/repo-core/lookup` defines for `lookupPopulate()`.
1495
- * Same compile path the kit already ships.
1646
+ * Route handler.
1647
+ * - String: controller method name (Arc pipeline) — runtime lookup, no TS coverage on typos.
1648
+ * - Function without `raw: true`: receives IRequestContext, returns IControllerResponse (Arc pipeline)
1649
+ * - Function with `raw: true`: raw Fastify handler `(request, reply)`
1496
1650
  *
1497
- * **Kit support is incremental.** A kit's `aggregate()` may not yet
1498
- * compile lookups — boot validation against the adapter version
1499
- * surfaces this loud, so hosts pin the kit major they need.
1500
- */
1501
- lookups?: readonly LookupSpec[];
1502
- /**
1503
- * Group key(s). Dotted paths into joined aliases supported when
1504
- * `lookups` is set: `'category.parent'` groups by the joined
1505
- * `category` row's `parent` field.
1651
+ * Prefer `controllerMethod` (2.16) over the string form when you want the
1652
+ * compiler to catch typos. `handler` stays optional when `controllerMethod`
1653
+ * is set — exactly one of the two must be declared.
1506
1654
  */
1507
- groupBy?: string | readonly string[];
1655
+ readonly handler?: string | ControllerHandler | RouteHandlerMethod | ((request: FastifyRequest<Record<string, unknown>>, reply: FastifyReply) => unknown);
1508
1656
  /**
1509
- * Time-bucket group keys for time-series aggregations. Each entry
1510
- * promotes a date column into a synthetic group key bucketed at
1511
- * the chosen interval. The map key becomes a column on the output
1512
- * row holding the canonical ISO-shaped bucket label
1513
- * (`'2026-04'` for month, `'2026-W15'` for ISO week, etc.).
1657
+ * Typed function-reference handler (2.16). Receives the live controller
1658
+ * instance and returns the method to invoke — TypeScript catches typos
1659
+ * and surfaces autocomplete on the controller's method names. Prefer
1660
+ * this over the string `handler` form for any host that uses a typed
1661
+ * controller subclass.
1514
1662
  *
1515
- * Bucketed keys participate in grouping the same way `groupBy`
1516
- * columns do — `sort: { month: 1 }`, `having`, pagination, and
1517
- * `topN.partitionBy` all treat them as first-class.
1663
+ * Resolved ONCE at route-registration time (the same path string
1664
+ * handlers go through), so there's no per-request lookup overhead.
1665
+ * The returned method is bound to the controller before dispatch.
1518
1666
  *
1519
- * Aliases must NOT collide with a `groupBy` field name or measure
1520
- * alias — boot validation throws on collision.
1667
+ * Mutually exclusive with `handler` — passing both throws at boot
1668
+ * with a clear "pick one" message. The runtime contract on what the
1669
+ * returned function accepts mirrors the `handler` rules: a plain
1670
+ * `ControllerHandler` for pipeline routes, a raw Fastify handler when
1671
+ * the route is `raw: true`.
1521
1672
  *
1522
- * @example "Daily revenue for the last quarter"
1523
- * ```ts
1524
- * dailyRevenue: defineAggregation({
1525
- * dateBuckets: { day: { field: 'createdAt', interval: 'day' } },
1526
- * measures: { revenue: 'sum:totalPrice' },
1527
- * sort: { day: 1 },
1528
- * permissions: requireRoles(['admin']),
1529
- * }),
1530
- * ```
1673
+ * Typed loosely (`(controller: unknown) => …`) at the type-system
1674
+ * boundary because `RouteDefinition` is not generic over the
1675
+ * controller shape — host code annotates the parameter to opt in:
1531
1676
  *
1532
- * @example "15-minute traffic buckets (custom-bin form)"
1677
+ * @example
1533
1678
  * ```ts
1534
- * traffic: defineAggregation({
1535
- * dateBuckets: {
1536
- * slot: { field: 'ts', interval: { every: 15, unit: 'minute' } },
1537
- * },
1538
- * measures: { hits: 'count' },
1539
- * permissions: allowPublic(),
1540
- * }),
1679
+ * class PostController extends BaseController<Post> {
1680
+ * async getStats(ctx: IRequestContext) { … }
1681
+ * }
1682
+ *
1683
+ * defineResource({
1684
+ * controller: new PostController(repo),
1685
+ * routes: [{
1686
+ * method: 'GET',
1687
+ * path: '/stats',
1688
+ * controllerMethod: (c: PostController) => c.getStats,
1689
+ * // ^^^^^^^^^^^^^^ TS catches typos here
1690
+ * permissions: requireAuth(),
1691
+ * }],
1692
+ * });
1541
1693
  * ```
1542
1694
  */
1543
- dateBuckets?: Record<string, AggDateBucket>;
1544
- /** Named aggregations. At least one entry required. */
1545
- measures: Record<string, AggMeasureInput>;
1546
- /**
1547
- * Post-aggregate filter referencing measure aliases.
1548
- * Example: `{ revenue: { gt: 1000 } }` → `HAVING revenue > 1000`.
1549
- */
1550
- having?: AnyRecord;
1551
- /** Order grouped rows by groupBy field, measure alias, or joined-alias path. */
1552
- sort?: Record<string, 1 | -1>;
1695
+ readonly controllerMethod?: (controller: unknown) => ControllerHandler | RouteHandlerMethod;
1696
+ /** Permission check — REQUIRED */
1697
+ readonly permissions: PermissionCheck;
1553
1698
  /**
1554
- * Static hard cap on result rows. Always applied at the IR level
1555
- * (LIMIT / `$limit`), regardless of URL params. Use when the
1556
- * aggregation has a fixed-size shape ("top 10 categories"). Mutually
1557
- * exclusive with `defaultLimit` / `maxLimit` — pick the static form
1558
- * OR the URL-driven form, not both.
1699
+ * Raw mode — bypasses Arc pipeline. Handler receives raw Fastify
1700
+ * request/reply. Default: false.
1559
1701
  */
1560
- limit?: number;
1702
+ readonly raw?: boolean;
1703
+ /** Logical operation name (pipeline keys, MCP tool naming). */
1704
+ readonly operation?: string;
1705
+ /** OpenAPI summary */
1706
+ readonly summary?: string;
1707
+ /** OpenAPI description */
1708
+ readonly description?: string;
1709
+ /** OpenAPI tags */
1710
+ readonly tags?: string[];
1711
+ /** Route-level middleware */
1712
+ readonly preHandler?: RouteHandlerMethod[] | ((fastify: FastifyInstance) => RouteHandlerMethod[]);
1713
+ /** Pre-auth handlers (run before authentication) */
1714
+ readonly preAuth?: RouteHandlerMethod[];
1561
1715
  /**
1562
- * URL-driven row limit — applied when the caller passes `?limit=N`.
1563
- * When set, the auto-route reads `query.limit`, parses it as a
1564
- * positive integer, caps it at `maxLimit` (or the framework default
1565
- * if `maxLimit` is unset), and writes the result into `AggRequest.limit`.
1566
- * When the caller omits `?limit`, this default applies.
1716
+ * Opt this custom route into the multiTenant preset's tenant scoping.
1567
1717
  *
1568
- * **DoS defense.** Auto-generated `/aggregations/:name` routes today
1569
- * have no upper bound on response size. A `groupBy: 'userId'` on a
1570
- * 10M-user table without `defaultLimit` returns a 10M-row JSON. Setting
1571
- * `defaultLimit: 100, maxLimit: 1000` bounds the response shape while
1572
- * letting power users request up to 1000 rows when they need them.
1718
+ * When `true` AND the resource declares `multiTenantPreset` (or
1719
+ * `flexibleMultiTenantPreset`), arc prepends the preset's tenant
1720
+ * filter + injection middleware to this route's chain — the same
1721
+ * pair `update` gets. The handler can then read the resolved tenant
1722
+ * via `getOrgId(req.scope)` / `req._tenantFields` (or, for write
1723
+ * routes, off `req.body` after injection) without re-implementing
1724
+ * the scope read + header fallback + 400 boilerplate.
1573
1725
  *
1574
- * Mutually exclusive with the static `limit` — boot error if both set.
1575
- * Setting `defaultLimit` without `maxLimit` uses the framework
1576
- * default cap (`AGG_FRAMEWORK_MAX_LIMIT = 1000`) — explicit is better.
1726
+ * Throws at boot if set when no multiTenant preset is wired — the
1727
+ * misconfiguration would otherwise be silently insecure (read routes
1728
+ * returning every tenant's rows).
1729
+ *
1730
+ * @default false
1577
1731
  */
1578
- defaultLimit?: number;
1732
+ readonly tenantScope?: boolean;
1579
1733
  /**
1580
- * Hard ceiling for URL-driven `?limit=N`. Only meaningful when
1581
- * `defaultLimit` is set; ignored otherwise. Defaults to
1582
- * `AGG_FRAMEWORK_MAX_LIMIT` (1000) when omitted but `defaultLimit` is
1583
- * present. Boot validation: must be ≥ `defaultLimit`.
1734
+ * SSE streaming mode. Two handler shapes work:
1735
+ *
1736
+ * - Write to `reply.raw` directly (NDJSON, custom SSE — historical contract).
1737
+ * - Return a Web `ReadableStream` (Vercel AI SDK's `result.toUIMessageStream()`,
1738
+ * `fetch().body`, etc.). 2.17.1+ auto-pipes these through
1739
+ * `pipeUIMessageStreamToReply()` so each chunk is JSON-encoded into
1740
+ * an SSE `data:` frame and client-disconnect cancels the source.
1741
+ * Pre-2.17.1 this crashed with `chunk must be a string or Buffer`.
1584
1742
  */
1585
- maxLimit?: number;
1743
+ readonly streamResponse?: boolean;
1586
1744
  /**
1587
- * Top-N-per-group filter. Keeps only the top `limit` rows per
1588
- * partition, ranked by `sortBy`. The classic "top 3 products per
1589
- * category" / "top 5 customers per region" dashboard primitive.
1590
- *
1591
- * Composes with `having` / `sort` — applies AFTER group + measures +
1592
- * having, so `partitionBy` and `sortBy` may reference groupBy fields,
1593
- * dateBucket aliases, or measure aliases. The top-level `sort` orders
1594
- * the final row set across partitions.
1745
+ * INTERNAL — marker stamped by built-in presets (softDelete, tree, …)
1746
+ * onto routes they emit. Read by the MCP collision detector
1747
+ * (`createMcpServer.resolveToolCollisions`) to attribute the route
1748
+ * source ("preset:softDelete vs user `actions.restore`") and to
1749
+ * auto-namespace the preset side when a user-authored tool legitimately
1750
+ * shadows it. Not part of the public surface — hosts must not set this.
1595
1751
  *
1596
- * **Per-kit support.** Mongokit compiles to `$setWindowFields` (Mongo 5+,
1597
- * runs in-engine — scales). Sqlitekit post-processes in JS (fine for
1598
- * typical dashboards; prefer mongokit for >100k groups). See
1599
- * `AggTopN` for full semantics.
1752
+ * @internal
1600
1753
  */
1601
- topN?: AggTopN;
1754
+ readonly _presetSource?: string;
1602
1755
  /**
1603
- * Permission check. **REQUIRED.** Aggregations are read-shape but
1604
- * different from list (different threat model — measures may expose
1605
- * cardinality info even when individual rows are hidden). Boot error
1606
- * if missing.
1756
+ * Apply the resource's `fields` (field-level write permissions) to this
1757
+ * custom route's request body.
1758
+ *
1759
+ * Default: `true` for body-bearing methods (POST/PUT/PATCH), `false`
1760
+ * otherwise. Set to `false` to opt out — handler accepts the body as
1761
+ * supplied with no field-write filtering. The resource-level
1762
+ * `onFieldWriteDenied: 'reject' | 'strip'` setting governs how denials
1763
+ * are surfaced.
1764
+ *
1765
+ * `raw: true` routes ALWAYS bypass this — they've opted out of the
1766
+ * pipeline entirely.
1607
1767
  */
1608
- permissions: PermissionCheck;
1768
+ readonly fieldWrite?: boolean;
1609
1769
  /**
1610
- * DB-level execution cap (ms). Mongokit threads to `maxTimeMS`;
1611
- * sqlitekit threads to per-statement timeout where supported.
1612
- * Default: kit's default (typically none).
1770
+ * Per-route rate limit. A custom route is its own Fastify route, so this
1771
+ * overrides the resource-level `rateLimit` for THIS endpoint only:
1772
+ *
1773
+ * - omitted → inherit the resource-level limit (or app default)
1774
+ * - `false` → disable rate limiting on this route
1775
+ * - `{ max, timeWindow }` → apply this specific limit
1776
+ *
1777
+ * Requires `@fastify/rate-limit` registered (arc's factory wires it by
1778
+ * default). Use for an expensive `/export` or an auth-sensitive `/reset`
1779
+ * that needs a tighter cap than the resource's read-heavy CRUD, or `false`
1780
+ * on an internal health/webhook route that must not be throttled.
1781
+ *
1782
+ * Note: this is per-route because each custom route is a distinct endpoint.
1783
+ * `actions` share ONE `POST /:id/action` mount by design, so a per-ACTION
1784
+ * limit can't be expressed here — throttle a specific action by promoting
1785
+ * it to a dedicated `routes:` entry, or rely on the resource-level limit.
1613
1786
  */
1614
- timeout?: number;
1787
+ readonly rateLimit?: RateLimitConfig | false;
1615
1788
  /**
1616
- * Reject 422 if the result row count exceeds this cap. Better than
1617
- * silent truncation — caller knows the dashboard is incomplete.
1618
- * Default: no cap (use `limit` for truncation semantics).
1789
+ * Fastify route schema. Each slot (`body`, `querystring`, `params`,
1790
+ * `headers`, `response[status]`) accepts a plain JSON Schema object
1791
+ * **or** a Zod v4 schema — Arc auto-converts via `convertRouteSchema`.
1619
1792
  */
1620
- maxGroups?: number;
1793
+ readonly schema?: {
1794
+ body?: unknown;
1795
+ querystring?: unknown;
1796
+ params?: unknown;
1797
+ headers?: unknown;
1798
+ response?: Record<number | string, unknown>;
1799
+ [key: string]: unknown;
1800
+ };
1621
1801
  /**
1622
- * Caller MUST provide filters on these fields (else 400 at request).
1623
- * Use to require a tenant-side narrowing the host can't infer
1624
- * (segment id, customer id, etc.).
1802
+ * MCP tool generation:
1803
+ * - omitted/true: auto-generate (non-raw routes only)
1804
+ * - false: skip MCP
1805
+ * - object: explicit config
1625
1806
  */
1626
- requireFilters?: readonly string[];
1807
+ readonly mcp?: boolean | RouteMcpConfig;
1627
1808
  /**
1628
- * Caller MUST send a bounded date range on this field. Prevents
1629
- * all-time scans on billion-row collections.
1809
+ * MCP handler for raw routes — parallel entry point for MCP without
1810
+ * changing the HTTP handler.
1630
1811
  */
1631
- requireDateRange?: AggregationDateRangeRequirement;
1812
+ readonly mcpHandler?: (input: Record<string, unknown>) => Promise<{
1813
+ content: Array<{
1814
+ type: string;
1815
+ text: string;
1816
+ }>;
1817
+ isError?: boolean;
1818
+ }>;
1819
+ }
1820
+ //#endregion
1821
+ //#region src/types/resource/actions.d.ts
1822
+ /**
1823
+ * Action handler function for state transitions. Receives the resource
1824
+ * ID, action-specific data, and the request.
1825
+ */
1826
+ type ActionHandlerFn = (id: string, data: Record<string, unknown>, req: RequestWithExtras) => Promise<unknown>;
1827
+ /**
1828
+ * Full action configuration with handler, permissions, and schema.
1829
+ *
1830
+ * Rate limiting is intentionally NOT per-action: every action shares one
1831
+ * `POST /:id/action` (or `POST /action`) mount, so Fastify's per-route limit
1832
+ * can't distinguish them. Actions inherit the resource-level `rateLimit`; to
1833
+ * throttle a specific operation, promote it to a `routes:` entry (which
1834
+ * supports `RouteDefinition.rateLimit`).
1835
+ */
1836
+ interface ActionDefinition {
1837
+ readonly handler: ActionHandlerFn;
1838
+ /** Per-action permission (overrides resource-level `actionPermissions`) */
1839
+ readonly permissions?: PermissionCheck;
1632
1840
  /**
1633
- * Documented index expectation. Arc warns at boot when the kit
1634
- * exposes index introspection and no matching index exists. NOT
1635
- * runtime-enforced — purely a misconfig signal.
1841
+ * JSON Schema or Zod v4 schema for action-specific body fields.
1842
+ *
1843
+ * Typed `unknown` (not `Record<string, unknown>`) so Zod class instances
1844
+ * — `ZodObject<...>` carries no string index signature — assign without
1845
+ * a cast. Same convention as `RouteDefinition.schema.body` / `customSchemas`.
1846
+ * Runtime feature-detects via `convertRouteSchema` / `toJsonSchema`.
1636
1847
  */
1637
- indexHint?: AggregationIndexHint;
1848
+ readonly schema?: unknown;
1849
+ /** Description for OpenAPI docs and MCP tool */
1850
+ readonly description?: string;
1638
1851
  /**
1639
- * Per-aggregation cache. Tenant-scoped keys; invalidates with the
1640
- * resource's cache namespace + any explicit `tags`.
1852
+ * Whether this action needs an entity id from the URL.
1853
+ *
1854
+ * - `true` (default) — mounts under `POST /<prefix>/:id/action`. The `id`
1855
+ * path param is required; handler receives it as the first argument.
1856
+ * Use for actions that operate on an existing entity: `approve`,
1857
+ * `dispatch`, `cancel`, `archive`.
1858
+ * - `false` — mounts under `POST /<prefix>/action` (no `:id` segment).
1859
+ * Handler receives an empty-string first argument. Use for
1860
+ * collection-level actions that create / search / bulk-mutate:
1861
+ * `propose` (creates a new entity), `search` (returns rows), `bulk`.
1862
+ *
1863
+ * 2.15.5: previously every action had to live under `:id/action`, forcing
1864
+ * `propose`-style actions to swallow a meaningless URL parameter and
1865
+ * making the auto-generated MCP tool advertise an `id` field agents
1866
+ * had no value for. Setting `id: false` mounts the action at the
1867
+ * resource root and drops `id` from the MCP tool's input shape.
1641
1868
  */
1642
- cache?: AggregationCacheConfig;
1869
+ readonly id?: boolean;
1643
1870
  /**
1644
- * Per-route rate limit. Wired to `@fastify/rate-limit` when the
1645
- * plugin is registered.
1871
+ * MCP tool generation:
1872
+ * - omitted/true: auto-generate
1873
+ * - false: skip
1874
+ * - object: explicit config
1646
1875
  */
1647
- rateLimit?: AggregationRateLimit;
1648
- /**
1649
- * Pre-computed read replacement. When set, arc skips
1650
- * `repo.aggregate()` and calls this function instead. Same wire
1651
- * shape, same permissions, different data source.
1652
- *
1653
- * Use for homepage-counter dashboards backed by host-managed rollup
1654
- * tables (cron / CDC). The hook receives the compiled context
1655
- * (filter + scope) so the host can route the lookup to the right
1656
- * pre-aggregated bucket.
1657
- */
1658
- materialized?: (ctx: AggregationMaterializedContext) => Promise<AggregationMaterializedResult>;
1659
- /** Optional summary rendered in OpenAPI + MCP tool description. */
1660
- summary?: string;
1661
- /** Optional longer description for OpenAPI / MCP. */
1662
- description?: string;
1663
- /**
1664
- * MCP tool generation control. Mirrors `actions[name].mcp` semantics.
1665
- *
1666
- * - `undefined` (default) — generate an MCP tool for this aggregation
1667
- * - `false` — skip MCP tool generation (REST route still works)
1668
- * - `{ description?, annotations? }` — generate with overrides
1669
- */
1670
- mcp?: boolean | {
1671
- readonly description?: string;
1672
- readonly annotations?: Record<string, unknown>;
1673
- };
1876
+ readonly mcp?: boolean | RouteMcpConfig;
1674
1877
  }
1675
- /** Map of name → declaration. Keys become URL segments under `/aggregations/<name>`. */
1676
- type AggregationsMap = Record<string, AggregationConfig>;
1878
+ /** Action config: bare handler function OR full ActionDefinition. */
1879
+ type ActionEntry = ActionHandlerFn | ActionDefinition;
1880
+ /** Actions configuration map. */
1881
+ type ActionsMap = Record<string, ActionEntry>;
1677
1882
  //#endregion
1678
- //#region src/types/handlers.d.ts
1883
+ //#region src/types/resource/cache.d.ts
1679
1884
  /**
1680
- * Minimal server accessor — exposes safe, read-only server decorators.
1681
- * Allows controller handlers to publish events, log, and audit
1682
- * without switching to `raw: true`.
1885
+ * Per-resource QueryCache configuration — stale-while-revalidate
1886
+ * windows, per-operation overrides, and tag-based cross-resource
1887
+ * invalidation.
1683
1888
  */
1684
- interface ServerAccessor {
1685
- /** Event bus — publish domain events from any handler */
1686
- events?: {
1687
- publish: <T>(type: string, payload: T, meta?: Partial<Record<string, unknown>>) => Promise<void>;
1688
- };
1689
- /** Audit logger — log custom audit entries */
1690
- audit?: {
1691
- create: (resource: string, documentId: string, data: Record<string, unknown>, context?: Record<string, unknown>) => Promise<void>;
1692
- update: (resource: string, documentId: string, before: Record<string, unknown>, after: Record<string, unknown>, context?: Record<string, unknown>) => Promise<void>;
1693
- delete: (resource: string, documentId: string, data: Record<string, unknown>, context?: Record<string, unknown>) => Promise<void>;
1694
- custom: (resource: string, documentId: string, action: string, data?: Record<string, unknown>, context?: Record<string, unknown>) => Promise<void>;
1695
- };
1696
- /** Logger — structured logging */
1697
- log?: {
1698
- info: (...args: unknown[]) => void;
1699
- warn: (...args: unknown[]) => void;
1700
- error: (...args: unknown[]) => void;
1701
- debug: (...args: unknown[]) => void;
1889
+ /**
1890
+ * Per-resource cache configuration for QueryCache. Enables
1891
+ * stale-while-revalidate, auto-invalidation on mutations, and
1892
+ * cross-resource tag-based invalidation.
1893
+ */
1894
+ interface ResourceCacheConfig {
1895
+ /** Seconds data is "fresh" (no revalidation). Default: 0 */
1896
+ staleTime?: number;
1897
+ /** Seconds stale data stays cached (SWR window). Default: 60 */
1898
+ gcTime?: number;
1899
+ /** Per-operation overrides */
1900
+ list?: {
1901
+ staleTime?: number;
1902
+ gcTime?: number;
1702
1903
  };
1703
- /** QueryCache — stale-while-revalidate data cache */
1704
- queryCache?: {
1705
- get: <T>(key: string) => Promise<{
1706
- data: T;
1707
- status: "fresh" | "stale" | "miss";
1708
- }>;
1709
- set: <T>(key: string, data: T, config: {
1710
- staleTime?: number;
1711
- gcTime?: number;
1712
- tags?: string[];
1713
- }) => Promise<void>;
1714
- getResourceVersion: (resource: string) => Promise<number>;
1715
- bumpResourceVersion: (resource: string) => Promise<void>;
1904
+ byId?: {
1905
+ staleTime?: number;
1906
+ gcTime?: number;
1716
1907
  };
1908
+ /** Tags for cross-resource invalidation grouping */
1909
+ tags?: string[];
1910
+ /**
1911
+ * Cross-resource invalidation: event pattern → tag targets.
1912
+ * @example { 'category.*': ['catalog'] }
1913
+ */
1914
+ invalidateOn?: Record<string, string[]>;
1915
+ /** Disable caching for this resource */
1916
+ disabled?: boolean;
1717
1917
  }
1918
+ //#endregion
1919
+ //#region src/pipeline/types.d.ts
1718
1920
  /**
1719
- * Request context passed to controller handlers.
1720
- *
1721
- * **Generic parameters** (all default to safe permissive types so existing code keeps working):
1722
- * - `TBody` — request body shape (default: `unknown`)
1723
- * - `TParams` — route param shape (default: `Record<string, string>`)
1724
- * - `TQuery` — query string shape (default: `Record<string, unknown>`)
1725
- * - `TUser` — authenticated user shape (default: `UserBase`)
1726
- * - `TMetadata` — internal metadata shape (default: `Record<string, unknown>`;
1727
- * override with `ArcInternalMetadata` or your own augmentation when you
1728
- * need typed access to `_scope`, `_policyFilters`, custom hook context, etc.)
1729
- *
1730
- * @example
1731
- * ```typescript
1732
- * // Untyped (default) — req.body is `unknown`, must be narrowed
1733
- * async create(req: IRequestContext) {
1734
- * const data = req.body as Partial<Product>;
1735
- * return { success: true, data: await productRepo.create(data) };
1736
- * }
1737
- *
1738
- * // Typed body — req.body is `CreateProductInput`, narrowing not needed
1739
- * async create(req: IRequestContext<CreateProductInput>) {
1740
- * return { success: true, data: await productRepo.create(req.body) };
1741
- * }
1742
- *
1743
- * // Fully typed — body, route params, query, and metadata
1744
- * async update(
1745
- * req: IRequestContext<
1746
- * Partial<Product>,
1747
- * { id: string },
1748
- * { fields?: string },
1749
- * ArcInternalMetadata
1750
- * >,
1751
- * ) {
1752
- * const fields = req.query.fields?.split(',');
1753
- * const orgId = req.metadata?._scope ? getOrgId(req.metadata._scope) : undefined;
1754
- * return { success: true, data: await productRepo.update(req.params.id, req.body) };
1755
- * }
1756
- * ```
1921
+ * Pipeline context passed to guards, transforms, and interceptors.
1922
+ * Extends IRequestContext with pipeline-specific metadata.
1757
1923
  */
1924
+ interface PipelineContext extends IRequestContext {
1925
+ /** Resource name being accessed */
1926
+ resource: string;
1927
+ /** CRUD operation being performed */
1928
+ operation: "list" | "get" | "create" | "update" | "delete" | string;
1929
+ }
1758
1930
  /**
1759
- * First-class projection of `request._scope` for controller handlers.
1760
- *
1761
- * **v2.10.6:** previously, pulling tenant/user/role info from inside a
1762
- * controller override meant digging through `req.metadata._scope` and
1763
- * calling `getOrgId(scope)` / `getUserId(user)` manually. This projection
1764
- * lifts the two fields most hosts need directly onto `req` so cross-kit
1765
- * controller code reads:
1766
- *
1767
- * ```ts
1768
- * async create(req: IRequestContext) {
1769
- * const flowCtx = { organizationId: req.scope?.organizationId, actorId: req.scope?.userId };
1770
- * }
1771
- * ```
1772
- *
1773
- * Full scope shape (discriminated union of `member` / `service` / `elevated` / `public`)
1774
- * still lives on `req.metadata._scope` for code that needs to branch on
1775
- * `scope.kind` — this projection just surfaces the two keys every
1776
- * tenant-scoped resource reaches for.
1931
+ * Which operations a pipeline step applies to.
1932
+ * If omitted, applies to ALL operations.
1777
1933
  */
1778
- interface RequestScopeProjection {
1779
- /** Tenant the caller is scoped to (org member, service key bound to an org, or elevated admin's target org). */
1780
- organizationId?: string;
1781
- /** Caller's user id when authenticated — undefined for public / service-only scopes. */
1782
- userId?: string;
1783
- /** Org-level roles (e.g. `['admin', 'warehouse-manager']`) — separate from global `user.roles`. */
1784
- orgRoles?: string[];
1785
- }
1786
- interface IRequestContext<TBody = unknown, TParams extends Record<string, string> = Record<string, string>, TQuery extends Record<string, unknown> = Record<string, unknown>, TUser extends UserBase = UserBase, TMetadata extends Record<string, unknown> = Record<string, unknown>> {
1787
- /** Route parameters (e.g., { id: '123' }) */
1788
- params: TParams;
1789
- /** Query string parameters */
1790
- query: TQuery;
1791
- /** Request body */
1792
- body: TBody;
1793
- /** Authenticated user or null */
1794
- user: TUser | null;
1795
- /** Request headers */
1796
- headers: Record<string, string | undefined>;
1797
- /** Organization ID (for multi-tenant apps) */
1798
- organizationId?: string;
1799
- /** Team ID (for team-scoped resources) */
1800
- teamId?: string;
1801
- /**
1802
- * First-class tenant/user scope projection — lifted from `metadata._scope`
1803
- * so controller overrides don't have to dig through Arc internals.
1804
- * See {@link RequestScopeProjection}. `undefined` for routes that run
1805
- * without auth / scope resolution.
1806
- */
1807
- scope?: RequestScopeProjection;
1808
- /**
1809
- * Organization/auth context from middleware.
1810
- * Contains orgRoles, orgScope, organizationId, and any custom fields
1811
- * set by the auth adapter or org-scope plugin.
1812
- *
1813
- * @example
1814
- * ```typescript
1815
- * async create(req: IRequestContext) {
1816
- * const roles = req.context?.orgRoles ?? [];
1817
- * if (roles.includes('manager')) { ... }
1818
- * }
1819
- * ```
1820
- */
1821
- context?: RequestContext;
1822
- /**
1823
- * Internal metadata (includes context + Arc internals like `_policyFilters`,
1824
- * `_scope`, `log`). Type as `ArcInternalMetadata` for typed access to Arc's
1825
- * built-in fields, or supply your own interface to layer custom fields.
1826
- */
1827
- metadata?: TMetadata;
1828
- /**
1829
- * Fastify server accessor — publish events, log, and audit
1830
- * from any handler without switching to `raw: true`.
1831
- *
1832
- * @example
1833
- * ```typescript
1834
- * async reschedule(req: IRequestContext) {
1835
- * const result = await repo.reschedule(req.params.id, req.body);
1836
- * await req.server?.events?.publish('interview.rescheduled', { data: result });
1837
- * return { data: result };
1838
- * }
1839
- * ```
1840
- */
1841
- server?: ServerAccessor;
1934
+ type OperationFilter = Array<"list" | "get" | "create" | "update" | "delete" | string>;
1935
+ /**
1936
+ * Guard — boolean check that short-circuits on failure.
1937
+ * Return true to proceed, throw to deny.
1938
+ */
1939
+ interface Guard {
1940
+ readonly _type: "guard";
1941
+ readonly name: string;
1942
+ readonly operations?: OperationFilter;
1943
+ handler(ctx: PipelineContext): boolean | Promise<boolean>;
1842
1944
  }
1843
1945
  /**
1844
- * Controller response shape — the success-path return from any handler.
1845
- *
1846
- * Errors throw `ArcError` (or any `HttpError`-shaped class); the global
1847
- * error handler catches them and emits an `ErrorContract`. There is no
1848
- * `success` discriminator on the response — HTTP status is the wire
1849
- * discriminator (2xx = data, 4xx/5xx = ErrorContract).
1946
+ * Transform — modifies request data before the handler.
1947
+ * Returns modified context (or mutates in place).
1850
1948
  */
1851
- interface IControllerResponse<T = unknown> {
1852
- /** Response payload — emitted directly to the wire (no envelope wrap). */
1853
- data: T;
1854
- /** HTTP status code. Defaults to 200. */
1855
- status?: number;
1856
- /** Custom response headers (e.g. X-Total-Count, Link, ETag). */
1857
- headers?: Record<string, string>;
1858
- /** Top-level metadata merged into list-shaped responses (e.g. `{ took }`). */
1859
- meta?: Record<string, unknown>;
1949
+ interface Transform {
1950
+ readonly _type: "transform";
1951
+ readonly name: string;
1952
+ readonly operations?: OperationFilter;
1953
+ handler(ctx: PipelineContext): PipelineContext | undefined | Promise<PipelineContext | undefined>;
1860
1954
  }
1861
1955
  /**
1862
- * Controller handler — Arc's standard pattern.
1863
- *
1864
- * Receives a request context object, returns IControllerResponse.
1865
- * Use with `raw: false` in routes.
1866
- *
1867
- * **Generic parameters:**
1868
- * - `TResponse` — shape of `IControllerResponse.data` (default: `unknown`)
1869
- * - `TBody` — shape of `req.body` (default: `unknown`)
1870
- * - `TParams` — shape of `req.params` (default: `Record<string, string>`)
1871
- * - `TQuery` — shape of `req.query` (default: `Record<string, unknown>`)
1872
- *
1873
- * Backward-compatible: `ControllerHandler<Product>` still works (only the
1874
- * response data is typed); add more generics as needed when you want
1875
- * type-safe access to the request body, params, or query string.
1876
- *
1877
- * @example
1878
- * ```typescript
1879
- * // Untyped req — body is unknown, must be narrowed
1880
- * const createProduct: ControllerHandler<Product> = async (req) => {
1881
- * const product = await productRepo.create(req.body as Partial<Product>);
1882
- * return { data: product, status: 201 };
1883
- * };
1884
- *
1885
- * // Fully typed — body, params, query, and response all inferred
1886
- * const updateProduct: ControllerHandler<
1887
- * Product,
1888
- * Partial<Product>,
1889
- * { id: string },
1890
- * { upsert?: string }
1891
- * > = async (req) => {
1892
- * const upsert = req.query.upsert === "true";
1893
- * const product = await productRepo.update(req.params.id, req.body, { upsert });
1894
- * return { data: product };
1895
- * };
1896
- *
1897
- * routes: [{
1898
- * method: 'POST',
1899
- * path: '/products',
1900
- * handler: createProduct,
1901
- * permissions: requireAuth(),
1902
- * raw: false, // Arc wraps this into Fastify handler
1903
- * }]
1904
- * ```
1905
- */
1906
- type ControllerHandler<TResponse = unknown, TBody = unknown, TParams extends Record<string, string> = Record<string, string>, TQuery extends Record<string, unknown> = Record<string, unknown>> = (req: IRequestContext<TBody, TParams, TQuery>) => Promise<IControllerResponse<TResponse>>;
1907
- /**
1908
- * Fastify native handler
1909
- *
1910
- * Standard Fastify request/reply pattern.
1911
- * Use with `raw: true` in routes.
1912
- *
1913
- * @example
1914
- * ```typescript
1915
- * const downloadFile: FastifyHandler = async (request, reply) => {
1916
- * const file = await getFile(request.params.id);
1917
- * reply.header('Content-Type', file.mimeType);
1918
- * return reply.send(file.buffer);
1919
- * };
1920
- *
1921
- * routes: [{
1922
- * method: 'GET',
1923
- * path: '/files/:id/download',
1924
- * handler: downloadFile,
1925
- * permissions: requireAuth(),
1926
- * raw: true, // Use as-is, no wrapping
1927
- * }]
1928
- * ```
1929
- */
1930
- type FastifyHandler<RouteGeneric extends Record<string, unknown> = Record<string, unknown>> = (request: FastifyRequest<RouteGeneric>, reply: FastifyReply) => Promise<unknown> | unknown;
1931
- /**
1932
- * Union type for route handlers
1956
+ * Next function passed to interceptors — calls the handler (or next interceptor).
1933
1957
  */
1934
- type RouteHandler = ControllerHandler | FastifyHandler;
1958
+ type NextFunction = () => Promise<IControllerResponse<unknown>>;
1935
1959
  /**
1936
- * Controller interface for CRUD operations (strict).
1937
- *
1938
- * `list`'s return type aligns with repo-core's `MinimalRepo.getAll()`
1939
- * contract — the kit MAY return an offset envelope, a keyset envelope,
1940
- * or a raw array. Arc's `BaseController` forwards the kit's response
1941
- * verbatim; consumers narrow on shape
1942
- * (`Array.isArray(data)` → bare array, presence of `total` → offset,
1943
- * presence of `nextCursor` → keyset).
1960
+ * Intercept — wraps handler execution (before + after pattern).
1944
1961
  */
1945
- interface IController<TDoc = unknown> {
1946
- list(req: IRequestContext): Promise<IControllerResponse<unknown>>;
1947
- get(req: IRequestContext): Promise<IControllerResponse<TDoc>>;
1948
- create(req: IRequestContext): Promise<IControllerResponse<TDoc>>;
1949
- update(req: IRequestContext): Promise<IControllerResponse<TDoc>>;
1950
- delete(req: IRequestContext): Promise<IControllerResponse<{
1951
- message: string;
1952
- }>>;
1962
+ interface Interceptor {
1963
+ readonly _type: "interceptor";
1964
+ readonly name: string;
1965
+ readonly operations?: OperationFilter;
1966
+ handler(ctx: PipelineContext, next: NextFunction): Promise<IControllerResponse<unknown>>;
1953
1967
  }
1968
+ type PipelineStep = Guard | Transform | Interceptor;
1954
1969
  /**
1955
- * Flexible controller interface — accepts controllers with any handler style,
1956
- * including class instances with extra methods / private fields.
1957
- *
1958
- * **v2.10.6:** the previous `[key: string]: unknown` index signature made
1959
- * real class instances fail structural assignment (`new ScrapController()`
1960
- * needed a `as unknown as ControllerLike` cast, because class instances
1961
- * don't have an index signature). Dropped — arc only invokes the CRUD
1962
- * methods at runtime, so the rest of the shape is the caller's concern.
1963
- *
1964
- * The five CRUD slots stay optional so partial controllers (e.g. read-only)
1965
- * assign too. Additional domain methods on the controller are allowed by
1966
- * construction (they're just not part of this contract).
1970
+ * Pipeline configuration — can be a flat array or per-operation map.
1967
1971
  */
1968
- interface ControllerLike {
1969
- list?: unknown;
1970
- get?: unknown;
1971
- create?: unknown;
1972
- update?: unknown;
1973
- delete?: unknown;
1974
- }
1972
+ type PipelineConfig = PipelineStep[] | {
1973
+ list?: PipelineStep[];
1974
+ get?: PipelineStep[];
1975
+ create?: PipelineStep[];
1976
+ update?: PipelineStep[];
1977
+ delete?: PipelineStep[];
1978
+ [operation: string]: PipelineStep[] | undefined;
1979
+ };
1975
1980
  //#endregion
1976
- //#region src/types/resource.d.ts
1977
- /** Standard controller type alias for CRUD operations. */
1978
- type CrudController<TDoc> = IController<TDoc>;
1981
+ //#region src/core/aggregation/types.d.ts
1979
1982
  /**
1980
- * Tenant-cleanup declaration on a resource — compliance-grade strategy
1981
- * for what happens to this resource's rows when the owning organization
1982
- * is deleted. Surfaces in arc's org-delete cascade runner and in
1983
- * registry introspection (audit scripts ask "what happens to this
1984
- * resource on org delete?").
1983
+ * Sugar for measures: `'count'` / `'count:field'` / `'sum:price'` /
1984
+ * `'avg:rating'` / `'min:created'` / `'max:updated'` /
1985
+ * `'countDistinct:userId'` / `'percentile:latency:0.95'`.
1985
1986
  *
1986
- * Strategy variants:
1987
- * - `hard` — permanent removal (GDPR right-to-be-forgotten).
1988
- * - `soft` — recoverable; pair with TTL for eventual hard-purge.
1989
- * - `anonymize` — keep the row (legal retention) but clear PII
1990
- * (HIPAA / PCI / SOX-compatible).
1991
- * - `skip` — explicit opt-out with mandatory `reason`.
1987
+ * Compiles to the canonical `AggMeasure` IR at boot. Hosts who want
1988
+ * the full IR can pass an `AggMeasure` object directly.
1992
1989
  *
1993
- * See {@link ResourceConfig.onTenantDelete} for the full decision tree.
1990
+ * **Percentile.** `'percentile:<field>:<p>'` where `p` is a numeric
1991
+ * literal in `[0, 1]` (e.g. `'percentile:latency:0.95'` for P95).
1992
+ * Mongokit (≥3.13) compiles to `$percentile`; sqlitekit throws
1993
+ * `UnsupportedOperationError` (no native percentile in SQLite).
1994
1994
  */
1995
- interface OnTenantDeleteConfig {
1996
- /**
1997
- * What to do with rows whose `tenantField` matches the deleted org.
1998
- * Discriminated union from `@classytic/repo-core/repository` — every
1999
- * kit's `purgeByField` consumes the same shape.
2000
- */
2001
- strategy: TenantPurgeStrategy;
2002
- /**
2003
- * Resources are processed in ascending `priority` order. Use to land
2004
- * leaf data (logs, events) before aggregate references. Default `100`.
2005
- */
2006
- priority?: number;
2007
- /**
2008
- * Rows per chunk for the underlying `purgeByField` call — bounds
2009
- * lock contention + replication-log pressure on very large tenants.
2010
- * Default kit-specific (~1000).
2011
- */
2012
- batchSize?: number;
2013
- }
1995
+ type AggMeasureShorthand = "count" | `count:${string}` | `countDistinct:${string}` | `sum:${string}` | `avg:${string}` | `min:${string}` | `max:${string}` | `percentile:${string}:${number}`;
1996
+ /** Either canonical IR or shorthand string — both compile to `AggMeasure`. */
1997
+ type AggMeasureInput = AggMeasure | AggMeasureShorthand;
2014
1998
  /**
2015
- * Resolved tenant-purge declaration — what arc actually runs when
2016
- * `cascadeDeleteForOrganization` fires. Computed once at boot from the
2017
- * resource's `onTenantDelete` declaration.
1999
+ * Cache config for an aggregation. Translates directly to the kit-side
2000
+ * `CacheOptions` (TanStack-shaped) which the unified
2001
+ * `@classytic/repo-core/cache` plugin reads from `req.cache`.
2018
2002
  *
2019
- * Exposed via `ResourceDefinition.resolvedTenantPurge` and
2020
- * `getCascadingResourcesWithMetadata(registry)` so audit tooling can
2021
- * answer "is this resource really going to hard-delete?" without
2022
- * reading the source.
2023
- */
2024
- interface ResolvedTenantPurge {
2025
- readonly strategy: TenantPurgeStrategy;
2026
- readonly priority: number;
2027
- readonly batchSize?: number;
2028
- /**
2029
- * Where the strategy came from — `'declared'` (host wrote
2030
- * `onTenantDelete` explicitly) or `'disabled'` (no declaration —
2031
- * runner skips this resource).
2032
- */
2033
- readonly source: "declared" | "disabled";
2034
- }
2035
- /**
2036
- * Per-resource cache configuration for QueryCache. Enables
2037
- * stale-while-revalidate, auto-invalidation on mutations, and
2038
- * cross-resource tag-based invalidation.
2003
+ * Caching only fires when the kit's repo has the `cachePlugin` wired —
2004
+ * arc declares the policy; the kit handles SWR + tag invalidation +
2005
+ * version-bump on writes. Hosts without the plugin installed silently
2006
+ * fall through to a non-cached call.
2039
2007
  */
2040
- interface ResourceCacheConfig {
2041
- /** Seconds data is "fresh" (no revalidation). Default: 0 */
2008
+ interface AggregationCacheConfig {
2009
+ /** Seconds the entry is fresh — no revalidation while inside this window. */
2042
2010
  staleTime?: number;
2043
- /** Seconds stale data stays cached (SWR window). Default: 60 */
2011
+ /** Seconds the entry stays in cache past stale before eviction. Default: 60. */
2044
2012
  gcTime?: number;
2045
- /** Per-operation overrides */
2046
- list?: {
2047
- staleTime?: number;
2048
- gcTime?: number;
2049
- };
2050
- byId?: {
2051
- staleTime?: number;
2052
- gcTime?: number;
2053
- };
2054
- /** Tags for cross-resource invalidation grouping */
2055
- tags?: string[];
2056
- /**
2057
- * Cross-resource invalidation: event pattern → tag targets.
2058
- * @example { 'category.*': ['catalog'] }
2059
- */
2060
- invalidateOn?: Record<string, string[]>;
2061
- /** Disable caching for this resource */
2062
- disabled?: boolean;
2063
- }
2064
- interface RateLimitConfig {
2065
- /** Maximum number of requests allowed within the time window */
2066
- max: number;
2067
- /** Time window for rate limiting (e.g., '1 minute', '15 seconds') */
2068
- timeWindow: string;
2069
- }
2070
- /**
2071
- * Per-field rule — arc's extension of repo-core's 4-field `FieldRule` floor
2072
- * (`immutable`, `immutableAfterCreate`, `systemManaged`, `optional`) with
2073
- * the constraint / UI / security bits arc layers on top.
2074
- *
2075
- * Kept structurally compatible with `@classytic/repo-core/schema`'s
2076
- * `FieldRule` so arc's `fieldRules: Record<string, ArcFieldRule>` flows
2077
- * into mongokit's / sqlitekit's `buildCrudSchemasFromModel(..., options)`
2078
- * without a cast. See `RouteSchemaOptions` JSDoc for the full rationale.
2079
- */
2080
- interface ArcFieldRule extends FieldRule {
2081
- /**
2082
- * When `true`, bypass the `systemManaged` / `readonly` / `immutable`
2083
- * strip in `BodySanitizer` for callers whose request scope is
2084
- * `elevated`. Lets platform admins stamp the value from the request
2085
- * body — needed for cross-tenant admin writes where the tenant field
2086
- * is the only way to pick a target org.
2087
- *
2088
- * Auto-set by `defineResource` on the configured `tenantField`. Hosts
2089
- * can set it manually on other fields (e.g. `createdBy`) if they want
2090
- * elevation-only override semantics for those too.
2091
- *
2092
- * Has no effect when `isElevated(scope)` is false — member and
2093
- * service callers continue to have the field stripped.
2094
- */
2095
- preserveForElevated?: boolean;
2096
- hidden?: boolean;
2097
- /**
2098
- * Aggregation visibility override. By default, only `hidden: true`
2099
- * blocks a field from `groupBy` / `measures.field` / `sort` / `dateBuckets`
2100
- * — that's the genuine cardinality-leak guard (the value is omitted from
2101
- * list/get responses, so exposing it via aggregation would reveal data
2102
- * the client can't otherwise see).
2103
- *
2104
- * `systemManaged: true` does **not** block aggregation — it's a write
2105
- * rule, not a visibility rule. Server-stamped fields like `createdAt`,
2106
- * `status`, or plugin-generated handles are visible in every list
2107
- * response and should aggregate freely.
2108
- *
2109
- * Use this flag to override the default:
2110
- *
2111
- * - `aggregable: false` — explicit deny, even on visible fields. Useful
2112
- * when a value is exposed per-row but the cardinality across rows is
2113
- * itself sensitive (e.g. `email` is visible in `get/:id` to admins
2114
- * but you don't want a public-readable agg of email distributions).
2115
- * - `aggregable: true` — escape hatch on `hidden` fields. Lets you
2116
- * aggregate a hidden column when you're sure cardinality leakage
2117
- * isn't a concern (e.g. `internalScore` hidden from list, but a
2118
- * committee-only `byScore` agg is fine).
2119
- *
2120
- * Defaults to `undefined` (use the `hidden`-only rule).
2121
- */
2122
- aggregable?: boolean;
2123
- /** String minimum length — auto-maps to OpenAPI `minLength` and MCP tool schema */
2124
- minLength?: number;
2125
- /** String maximum length — auto-maps to OpenAPI `maxLength` and MCP tool schema */
2126
- maxLength?: number;
2127
- /** Number minimum — auto-maps to OpenAPI `minimum` and MCP tool schema */
2128
- min?: number;
2129
- /** Number maximum — auto-maps to OpenAPI `maximum` and MCP tool schema */
2130
- max?: number;
2131
- /** Regex pattern — auto-maps to OpenAPI `pattern` and MCP tool schema */
2132
- pattern?: string;
2133
- /** Allowed values — auto-maps to OpenAPI `enum` and MCP tool schema */
2134
- enum?: ReadonlyArray<string | number>;
2135
- /**
2136
- * When `true`, widen the JSON Schema `type` of this field to also
2137
- * accept `null`. Mirrors Zod's `.nullable()` at the arc config layer
2138
- * for kit-generated schemas that don't carry the flag end-to-end
2139
- * (e.g. Zod → Mongoose → mongokit drops `.nullable()` because
2140
- * Mongoose has no first-class nullable marker unless `default: null`
2141
- * is also set).
2142
- *
2143
- * Applied post-kit by `mergeFieldRuleConstraints`: if the adapter
2144
- * emitted `{ type: 'string', enum: [...] }` for a field arc should
2145
- * accept null for, the merge widens it to
2146
- * `{ type: ['string', 'null'], enum: [...] }` — draft-7 tuple form
2147
- * AJV 8 validates natively.
2148
- *
2149
- * No-op when the property already declares `type: [...,'null']` or
2150
- * an `anyOf: [..., { type: 'null' }]` branch — arc never fights the
2151
- * kit's own output.
2152
- */
2153
- nullable?: boolean;
2154
- /** Human-readable description — auto-maps to OpenAPI `description` */
2155
- description?: string;
2156
- [key: string]: unknown;
2157
- }
2158
- /**
2159
- * Schema-shaping options for a resource.
2160
- *
2161
- * Extends `@classytic/repo-core/schema`'s `SchemaBuilderOptions` so every
2162
- * kit-generator callback typed against the repo-core contract
2163
- * (mongokit's `buildCrudSchemasFromModel`, sqlitekit's
2164
- * `buildCrudSchemasFromTable`, prismakit's equivalent) accepts arc's
2165
- * options bag directly — no `as SchemaBuilderOptions` / `Parameters<...>[1]`
2166
- * cast at the host wiring site.
2167
- *
2168
- * Inherited from `SchemaBuilderOptions`:
2169
- * - `strictAdditionalProperties` — emit `additionalProperties: false`
2170
- * - `dateAs` — `'date'` vs `'datetime'` ISO rendering
2171
- * - `softRequiredFields` — stay in `properties`, drop from `required[]`
2172
- * - `create: { omitFields, requiredOverrides, optionalOverrides, schemaOverrides }`
2173
- * - `update: { omitFields, requireAtLeastOne }`
2174
- * - `query: { filterableFields }` (kit-native filter declaration)
2175
- * - `openApiExtensions` — emit `x-*` vendor keywords for docgen
2176
- *
2177
- * Arc adds:
2178
- * - `fieldRules` with the richer `ArcFieldRule` per-entry shape
2179
- * (preserveForElevated, minLength/maxLength/min/max/pattern, enum,
2180
- * nullable, description) — arc's extensions are applied post-kit by
2181
- * `mergeFieldRuleConstraints`; the kit only sees the repo-core floor.
2182
- * - `hiddenFields` / `readonlyFields` / `requiredFields` / `optionalFields`
2183
- * / `excludeFields` — arc-only convenience lists that predate fieldRules.
2184
- * Keep using them if they're already in place; new code should prefer
2185
- * `fieldRules` for per-field control.
2186
- * - `filterableFields: string[]` — top-level list arc's MCP layer auto-
2187
- * derives from `QueryParser.allowedFilterFields`. Distinct from the
2188
- * inherited `query.filterableFields: Record<...>` which feeds the kit's
2189
- * list-query schema; nothing stops a resource from using both.
2190
- *
2191
- * **Why extend rather than duplicate**: mongokit's
2192
- * `buildCrudSchemasFromModel(model, options: SchemaBuilderOptions)` is the
2193
- * canonical callback shape. Before the extension, hosts wrote
2194
- * `Parameters<typeof buildCrudSchemasFromModel>[1]` or
2195
- * `as SchemaBuilderOptions` at every wiring site — a defensive cast with
2196
- * no runtime effect. Extension locks the structural relationship at the
2197
- * type layer so the cast is compile-verified gone.
2198
- */
2199
- interface RouteSchemaOptions extends SchemaBuilderOptions {
2200
- hiddenFields?: string[];
2201
- readonlyFields?: string[];
2202
- requiredFields?: string[];
2203
- optionalFields?: string[];
2204
- excludeFields?: string[];
2205
- /**
2206
- * Fields allowed for filtering in list operations. MCP auto-derives
2207
- * from `QueryParser.allowedFilterFields` when not set explicitly.
2208
- *
2209
- * Distinct from the inherited `query.filterableFields: Record<...>`
2210
- * from `SchemaBuilderOptions` — that entry feeds the kit's list-query
2211
- * JSON Schema; this one is arc's MCP-auto-derivation list.
2212
- */
2213
- filterableFields?: string[];
2214
- /**
2215
- * Per-field rules. Richer than repo-core's `FieldRules` — arc adds
2216
- * `preserveForElevated`, constraint hints (`minLength`, `enum`,
2217
- * `nullable`, etc.), and `description` on top of the four-flag floor
2218
- * (`immutable`, `immutableAfterCreate`, `systemManaged`, `optional`).
2219
- *
2220
- * Structurally compatible: `Record<string, ArcFieldRule>` is assignable
2221
- * to repo-core's `Record<string, FieldRule>` since `ArcFieldRule extends
2222
- * FieldRule`. Kits see only the floor; arc's extensions are applied
2223
- * post-kit by `mergeFieldRuleConstraints`.
2224
- */
2225
- fieldRules?: Record<string, ArcFieldRule>;
2226
2013
  /**
2227
- * Query-time security whitelists + the kit's `filterableFields`.
2228
- *
2229
- * Extends repo-core's `SchemaBuilderOptions['query']` with arc-specific
2230
- * runtime features that `QueryResolver` reads at request time:
2231
- *
2232
- * - **`allowedPopulate`** — populate-path whitelist consumed by
2233
- * `QueryResolver.sanitizePopulate` / `sanitizeAdvancedPopulate`.
2234
- * When set, only paths in the list pass through; everything else is
2235
- * stripped silently. Shrinks the auto-wired `?populate=` attack surface.
2236
- *
2237
- * - **`allowedLookups`** — lookup-collection whitelist consumed by
2238
- * `QueryResolver.sanitizeLookups`. When set, only the listed
2239
- * collections may be `$lookup`'d into the pipeline.
2240
- *
2241
- * Both are pre-2.11.2 runtime features — the type was missing them, so
2242
- * hosts wrote `as Record<string, unknown>` at every call site. Arc's own
2243
- * `QueryResolver` had to cast its own input via `as AnyRecord` for the
2244
- * same reason. Adding the type dropped both casts.
2245
- */
2246
- query?: SchemaBuilderOptions["query"] & {
2247
- /**
2248
- * Populate-path whitelist. When set, `QueryResolver.sanitizePopulate`
2249
- * strips any `?populate=<path>` not in this list. Omit to allow all
2250
- * paths the kit recognizes.
2251
- */
2252
- allowedPopulate?: string[];
2253
- /**
2254
- * Lookup-collection whitelist for `QueryResolver.sanitizeLookups`.
2255
- * When set, only the listed collections may be `$lookup`'d. Omit to
2256
- * disable the whitelist (kit-level rules still apply).
2257
- */
2258
- allowedLookups?: string[];
2259
- };
2260
- }
2261
- interface FieldRule$1 {
2262
- field: string;
2263
- required?: boolean;
2264
- readonly?: boolean;
2265
- hidden?: boolean;
2014
+ * Stale-while-revalidate. When stale entries serve immediately and a
2015
+ * background refresh updates the cache. Default: `true` for
2016
+ * aggregations (dashboards almost always benefit from stale-serve).
2017
+ */
2018
+ swr?: boolean;
2019
+ /**
2020
+ * Group invalidation tags. Pass to `repo.cache?.invalidateByTags(tags)`
2021
+ * after a write to clear matching entries. The model name is
2022
+ * auto-tagged by the plugin — you only declare cross-cutting tags
2023
+ * (e.g. `'pricing'` to invalidate every aggregation that depends on
2024
+ * pricing across multiple resources).
2025
+ */
2026
+ tags?: readonly string[];
2266
2027
  }
2267
2028
  /**
2268
- * CRUD route schemas (Fastify native format). Each slot accepts a plain
2269
- * JSON Schema object **or** a Zod v4 schema — Arc's `convertRouteSchema`
2270
- * feature-detects at runtime. Slot values are typed `unknown` so
2271
- * class-based Zod schemas assign without casts.
2029
+ * Per-aggregation rate limit. Layers on top of any global rate limit
2030
+ * via `@fastify/rate-limit` route-level config.
2272
2031
  */
2273
- interface CrudSchemas {
2274
- /** GET / — list */
2275
- list?: {
2276
- querystring?: unknown;
2277
- response?: Record<number, unknown>;
2278
- [key: string]: unknown;
2279
- };
2280
- /** GET /:id — get one */
2281
- get?: {
2282
- params?: unknown;
2283
- response?: Record<number, unknown>;
2284
- [key: string]: unknown;
2285
- };
2286
- /** POST / — create */
2287
- create?: {
2288
- body?: unknown;
2289
- response?: Record<number, unknown>;
2290
- [key: string]: unknown;
2291
- };
2292
- /** PATCH /:id — update */
2293
- update?: {
2294
- params?: unknown;
2295
- body?: unknown;
2296
- response?: Record<number, unknown>;
2297
- [key: string]: unknown;
2298
- };
2299
- /** DELETE /:id — delete */
2300
- delete?: {
2301
- params?: unknown;
2302
- response?: Record<number, unknown>;
2303
- [key: string]: unknown;
2304
- };
2305
- [key: string]: unknown;
2032
+ interface AggregationRateLimit {
2033
+ /** Max requests per window. */
2034
+ max: number;
2035
+ /** Window in milliseconds. */
2036
+ windowMs: number;
2306
2037
  }
2307
- interface OpenApiSchemas {
2308
- entity?: unknown;
2309
- createBody?: unknown;
2310
- updateBody?: unknown;
2311
- params?: unknown;
2312
- listQuery?: unknown;
2038
+ /**
2039
+ * Required date-range narrowing. Caller MUST send a bounded range on
2040
+ * this field, and the range MUST NOT exceed `maxRangeDays`.
2041
+ *
2042
+ * Prevents "all-time" scans on billion-row collections — the single
2043
+ * biggest performance footgun for live aggregation endpoints.
2044
+ */
2045
+ interface AggregationDateRangeRequirement {
2046
+ /** Field whose range the caller must narrow (e.g. `'createdAt'`). */
2047
+ field: string;
2313
2048
  /**
2314
- * Explicit response schema for OpenAPI documentation. Auto-generated
2315
- * from `createBody` if omitted. Does NOT affect Fastify serialization.
2049
+ * Cap on the queryable range. A request asking for >N days is
2050
+ * rejected 400. Omit for "any range, but bounded" (lower + upper
2051
+ * required, no cap).
2316
2052
  */
2317
- response?: unknown;
2318
- [key: string]: unknown;
2319
- }
2320
- type CrudRouteKey = "list" | "get" | "create" | "update" | "delete";
2321
- interface MiddlewareConfig {
2322
- list?: MiddlewareHandler[];
2323
- get?: MiddlewareHandler[];
2324
- create?: MiddlewareHandler[];
2325
- update?: MiddlewareHandler[];
2326
- delete?: MiddlewareHandler[];
2327
- [key: string]: MiddlewareHandler[] | undefined;
2053
+ maxRangeDays?: number;
2328
2054
  }
2329
- /** HTTP methods for custom routes. */
2330
- type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
2331
- /** MCP tool configuration for a route or action. */
2332
- interface RouteMcpConfig {
2333
- /** Override auto-generated tool description */
2334
- readonly description?: string;
2335
- /** MCP tool annotations */
2336
- readonly annotations?: {
2337
- readonly readOnlyHint?: boolean;
2338
- readonly destructiveHint?: boolean;
2339
- readonly idempotentHint?: boolean;
2340
- readonly openWorldHint?: boolean;
2341
- };
2055
+ /**
2056
+ * Boot-time index hint. Arc warns when the kit's schema doesn't have
2057
+ * an index whose leading keys match — flags the misconfig before
2058
+ * traffic hits the DB.
2059
+ *
2060
+ * Documented intent, NOT runtime-enforced. Kits with their own index
2061
+ * introspection (mongokit reads Mongoose schema, sqlitekit reads
2062
+ * Drizzle indexes) can act on the hint; kits without introspection
2063
+ * silently accept it.
2064
+ */
2065
+ interface AggregationIndexHint {
2066
+ /** Leading-key columns the host expects the planner to use. */
2067
+ leadingKeys: readonly string[];
2342
2068
  }
2343
2069
  /**
2344
- * Route definition — single custom-route shape (user-facing + internal).
2070
+ * Runtime context passed to the `materialized` hook.
2345
2071
  *
2346
- * - `handler: 'string'` → controller method → full Arc pipeline + MCP tool
2347
- * - `handler: function` → inline handler → full Arc pipeline + MCP tool
2348
- * - `raw: true` → raw Fastify handler → no pipeline, no MCP by default
2072
+ * The hook returns pre-computed data instead of running the live
2073
+ * aggregation. Hosts use this for ultra-frequent dashboards backed by
2074
+ * rollup tables maintained out-of-band (cron / CDC).
2349
2075
  */
2350
- interface RouteDefinition {
2351
- readonly method: RouteMethod;
2352
- /** Path relative to resource prefix */
2353
- readonly path: string;
2076
+ interface AggregationMaterializedContext {
2077
+ /** Compiled filter (host base + tenant + caller). */
2078
+ filter: AnyRecord;
2079
+ /** Tenant id when the resource is tenant-scoped. */
2080
+ orgId?: string;
2081
+ /** Authenticated user id, when present. */
2082
+ userId?: string;
2083
+ /** Fastify request id for tracing. */
2084
+ requestId?: string;
2085
+ /** Raw URL query params (post-validation). */
2086
+ query: Record<string, unknown>;
2087
+ }
2088
+ /** Materialized hook return shape — same envelope as `AggResult`. */
2089
+ interface AggregationMaterializedResult<TRow = AnyRecord> {
2090
+ rows: readonly TRow[];
2091
+ }
2092
+ /**
2093
+ * Single named aggregation declaration. Composes into `AggRequest` at
2094
+ * request time, with safety knobs layered on at the arc-handler level.
2095
+ */
2096
+ interface AggregationConfig {
2354
2097
  /**
2355
- * Route handler.
2356
- * - String: controller method name (Arc pipeline) — runtime lookup, no TS coverage on typos.
2357
- * - Function without `raw: true`: receives IRequestContext, returns IControllerResponse (Arc pipeline)
2358
- * - Function with `raw: true`: raw Fastify handler `(request, reply)`
2359
- *
2360
- * Prefer `controllerMethod` (2.16) over the string form when you want the
2361
- * compiler to catch typos. `handler` stays optional when `controllerMethod`
2362
- * is set — exactly one of the two must be declared.
2098
+ * Pre-aggregate filter on the BASE rows (before lookups). Always
2099
+ * ANDed with auto-injected tenant scope + caller URL-narrowing
2100
+ * filters. Use for host-defined invariants (e.g. `archived: false`).
2363
2101
  */
2364
- readonly handler?: string | ControllerHandler | RouteHandlerMethod | ((request: FastifyRequest<Record<string, unknown>>, reply: FastifyReply) => unknown);
2102
+ filter?: AnyRecord;
2365
2103
  /**
2366
- * Typed function-reference handler (2.16). Receives the live controller
2367
- * instance and returns the method to invoke — TypeScript catches typos
2368
- * and surfaces autocomplete on the controller's method names. Prefer
2369
- * this over the string `handler` form for any host that uses a typed
2370
- * controller subclass.
2104
+ * Cross-table joins. Each `LookupSpec` reuses the IR
2105
+ * `@classytic/repo-core/lookup` defines for `lookupPopulate()`.
2106
+ * Same compile path the kit already ships.
2371
2107
  *
2372
- * Resolved ONCE at route-registration time (the same path string
2373
- * handlers go through), so there's no per-request lookup overhead.
2374
- * The returned method is bound to the controller before dispatch.
2108
+ * **Kit support is incremental.** A kit's `aggregate()` may not yet
2109
+ * compile lookups — boot validation against the adapter version
2110
+ * surfaces this loud, so hosts pin the kit major they need.
2111
+ */
2112
+ lookups?: readonly LookupSpec[];
2113
+ /**
2114
+ * Group key(s). Dotted paths into joined aliases supported when
2115
+ * `lookups` is set: `'category.parent'` groups by the joined
2116
+ * `category` row's `parent` field.
2117
+ */
2118
+ groupBy?: string | readonly string[];
2119
+ /**
2120
+ * Time-bucket group keys for time-series aggregations. Each entry
2121
+ * promotes a date column into a synthetic group key bucketed at
2122
+ * the chosen interval. The map key becomes a column on the output
2123
+ * row holding the canonical ISO-shaped bucket label
2124
+ * (`'2026-04'` for month, `'2026-W15'` for ISO week, etc.).
2375
2125
  *
2376
- * Mutually exclusive with `handler` — passing both throws at boot
2377
- * with a clear "pick one" message. The runtime contract on what the
2378
- * returned function accepts mirrors the `handler` rules: a plain
2379
- * `ControllerHandler` for pipeline routes, a raw Fastify handler when
2380
- * the route is `raw: true`.
2126
+ * Bucketed keys participate in grouping the same way `groupBy`
2127
+ * columns do — `sort: { month: 1 }`, `having`, pagination, and
2128
+ * `topN.partitionBy` all treat them as first-class.
2381
2129
  *
2382
- * Typed loosely (`(controller: unknown) => …`) at the type-system
2383
- * boundary because `RouteDefinition` is not generic over the
2384
- * controller shape — host code annotates the parameter to opt in:
2130
+ * Aliases must NOT collide with a `groupBy` field name or measure
2131
+ * alias — boot validation throws on collision.
2385
2132
  *
2386
- * @example
2133
+ * @example "Daily revenue for the last quarter"
2387
2134
  * ```ts
2388
- * class PostController extends BaseController<Post> {
2389
- * async getStats(ctx: IRequestContext) { … }
2390
- * }
2135
+ * dailyRevenue: defineAggregation({
2136
+ * dateBuckets: { day: { field: 'createdAt', interval: 'day' } },
2137
+ * measures: { revenue: 'sum:totalPrice' },
2138
+ * sort: { day: 1 },
2139
+ * permissions: requireRoles(['admin']),
2140
+ * }),
2141
+ * ```
2391
2142
  *
2392
- * defineResource({
2393
- * controller: new PostController(repo),
2394
- * routes: [{
2395
- * method: 'GET',
2396
- * path: '/stats',
2397
- * controllerMethod: (c: PostController) => c.getStats,
2398
- * // ^^^^^^^^^^^^^^ TS catches typos here
2399
- * permissions: requireAuth(),
2400
- * }],
2401
- * });
2143
+ * @example "15-minute traffic buckets (custom-bin form)"
2144
+ * ```ts
2145
+ * traffic: defineAggregation({
2146
+ * dateBuckets: {
2147
+ * slot: { field: 'ts', interval: { every: 15, unit: 'minute' } },
2148
+ * },
2149
+ * measures: { hits: 'count' },
2150
+ * permissions: allowPublic(),
2151
+ * }),
2402
2152
  * ```
2403
2153
  */
2404
- readonly controllerMethod?: (controller: unknown) => ControllerHandler | RouteHandlerMethod;
2405
- /** Permission check — REQUIRED */
2406
- readonly permissions: PermissionCheck;
2154
+ dateBuckets?: Record<string, AggDateBucket>;
2155
+ /** Named aggregations. At least one entry required. */
2156
+ measures: Record<string, AggMeasureInput>;
2157
+ /**
2158
+ * Post-aggregate filter referencing measure aliases.
2159
+ * Example: `{ revenue: { gt: 1000 } }` → `HAVING revenue > 1000`.
2160
+ */
2161
+ having?: AnyRecord;
2162
+ /** Order grouped rows by groupBy field, measure alias, or joined-alias path. */
2163
+ sort?: Record<string, 1 | -1>;
2164
+ /**
2165
+ * Static hard cap on result rows. Always applied at the IR level
2166
+ * (LIMIT / `$limit`), regardless of URL params. Use when the
2167
+ * aggregation has a fixed-size shape ("top 10 categories"). Mutually
2168
+ * exclusive with `defaultLimit` / `maxLimit` — pick the static form
2169
+ * OR the URL-driven form, not both.
2170
+ */
2171
+ limit?: number;
2172
+ /**
2173
+ * URL-driven row limit — applied when the caller passes `?limit=N`.
2174
+ * When set, the auto-route reads `query.limit`, parses it as a
2175
+ * positive integer, caps it at `maxLimit` (or the framework default
2176
+ * if `maxLimit` is unset), and writes the result into `AggRequest.limit`.
2177
+ * When the caller omits `?limit`, this default applies.
2178
+ *
2179
+ * **DoS defense.** Auto-generated `/aggregations/:name` routes today
2180
+ * have no upper bound on response size. A `groupBy: 'userId'` on a
2181
+ * 10M-user table without `defaultLimit` returns a 10M-row JSON. Setting
2182
+ * `defaultLimit: 100, maxLimit: 1000` bounds the response shape while
2183
+ * letting power users request up to 1000 rows when they need them.
2184
+ *
2185
+ * Mutually exclusive with the static `limit` — boot error if both set.
2186
+ * Setting `defaultLimit` without `maxLimit` uses the framework
2187
+ * default cap (`AGG_FRAMEWORK_MAX_LIMIT = 1000`) — explicit is better.
2188
+ */
2189
+ defaultLimit?: number;
2407
2190
  /**
2408
- * Raw mode — bypasses Arc pipeline. Handler receives raw Fastify
2409
- * request/reply. Default: false.
2191
+ * Hard ceiling for URL-driven `?limit=N`. Only meaningful when
2192
+ * `defaultLimit` is set; ignored otherwise. Defaults to
2193
+ * `AGG_FRAMEWORK_MAX_LIMIT` (1000) when omitted but `defaultLimit` is
2194
+ * present. Boot validation: must be ≥ `defaultLimit`.
2410
2195
  */
2411
- readonly raw?: boolean;
2412
- /** Logical operation name (pipeline keys, MCP tool naming). */
2413
- readonly operation?: string;
2414
- /** OpenAPI summary */
2415
- readonly summary?: string;
2416
- /** OpenAPI description */
2417
- readonly description?: string;
2418
- /** OpenAPI tags */
2419
- readonly tags?: string[];
2420
- /** Route-level middleware */
2421
- readonly preHandler?: RouteHandlerMethod[] | ((fastify: FastifyInstance) => RouteHandlerMethod[]);
2422
- /** Pre-auth handlers (run before authentication) */
2423
- readonly preAuth?: RouteHandlerMethod[];
2196
+ maxLimit?: number;
2424
2197
  /**
2425
- * Opt this custom route into the multiTenant preset's tenant scoping.
2426
- *
2427
- * When `true` AND the resource declares `multiTenantPreset` (or
2428
- * `flexibleMultiTenantPreset`), arc prepends the preset's tenant
2429
- * filter + injection middleware to this route's chain — the same
2430
- * pair `update` gets. The handler can then read the resolved tenant
2431
- * via `getOrgId(req.scope)` / `req._tenantFields` (or, for write
2432
- * routes, off `req.body` after injection) without re-implementing
2433
- * the scope read + header fallback + 400 boilerplate.
2198
+ * Top-N-per-group filter. Keeps only the top `limit` rows per
2199
+ * partition, ranked by `sortBy`. The classic "top 3 products per
2200
+ * category" / "top 5 customers per region" dashboard primitive.
2434
2201
  *
2435
- * Throws at boot if set when no multiTenant preset is wired — the
2436
- * misconfiguration would otherwise be silently insecure (read routes
2437
- * returning every tenant's rows).
2202
+ * Composes with `having` / `sort` — applies AFTER group + measures +
2203
+ * having, so `partitionBy` and `sortBy` may reference groupBy fields,
2204
+ * dateBucket aliases, or measure aliases. The top-level `sort` orders
2205
+ * the final row set across partitions.
2438
2206
  *
2439
- * @default false
2207
+ * **Per-kit support.** Mongokit compiles to `$setWindowFields` (Mongo 5+,
2208
+ * runs in-engine — scales). Sqlitekit post-processes in JS (fine for
2209
+ * typical dashboards; prefer mongokit for >100k groups). See
2210
+ * `AggTopN` for full semantics.
2440
2211
  */
2441
- readonly tenantScope?: boolean;
2212
+ topN?: AggTopN;
2442
2213
  /**
2443
- * SSE streaming mode. Two handler shapes work:
2444
- *
2445
- * - Write to `reply.raw` directly (NDJSON, custom SSE — historical contract).
2446
- * - Return a Web `ReadableStream` (Vercel AI SDK's `result.toUIMessageStream()`,
2447
- * `fetch().body`, etc.). 2.17.1+ auto-pipes these through
2448
- * `pipeUIMessageStreamToReply()` so each chunk is JSON-encoded into
2449
- * an SSE `data:` frame and client-disconnect cancels the source.
2450
- * Pre-2.17.1 this crashed with `chunk must be a string or Buffer`.
2214
+ * Permission check. **REQUIRED.** Aggregations are read-shape but
2215
+ * different from list (different threat model — measures may expose
2216
+ * cardinality info even when individual rows are hidden). Boot error
2217
+ * if missing.
2451
2218
  */
2452
- readonly streamResponse?: boolean;
2219
+ permissions: PermissionCheck;
2453
2220
  /**
2454
- * INTERNAL — marker stamped by built-in presets (softDelete, tree, …)
2455
- * onto routes they emit. Read by the MCP collision detector
2456
- * (`createMcpServer.resolveToolCollisions`) to attribute the route
2457
- * source ("preset:softDelete vs user `actions.restore`") and to
2458
- * auto-namespace the preset side when a user-authored tool legitimately
2459
- * shadows it. Not part of the public surface — hosts must not set this.
2460
- *
2461
- * @internal
2221
+ * DB-level execution cap (ms). Mongokit threads to `maxTimeMS`;
2222
+ * sqlitekit threads to per-statement timeout where supported.
2223
+ * Default: kit's default (typically none).
2462
2224
  */
2463
- readonly _presetSource?: string;
2225
+ timeout?: number;
2464
2226
  /**
2465
- * Apply the resource's `fields` (field-level write permissions) to this
2466
- * custom route's request body.
2467
- *
2468
- * Default: `true` for body-bearing methods (POST/PUT/PATCH), `false`
2469
- * otherwise. Set to `false` to opt out — handler accepts the body as
2470
- * supplied with no field-write filtering. The resource-level
2471
- * `onFieldWriteDenied: 'reject' | 'strip'` setting governs how denials
2472
- * are surfaced.
2473
- *
2474
- * `raw: true` routes ALWAYS bypass this — they've opted out of the
2475
- * pipeline entirely.
2227
+ * Reject 422 if the result row count exceeds this cap. Better than
2228
+ * silent truncation — caller knows the dashboard is incomplete.
2229
+ * Default: no cap (use `limit` for truncation semantics).
2476
2230
  */
2477
- readonly fieldWrite?: boolean;
2231
+ maxGroups?: number;
2478
2232
  /**
2479
- * Per-route rate limit. A custom route is its own Fastify route, so this
2480
- * overrides the resource-level `rateLimit` for THIS endpoint only:
2481
- *
2482
- * - omitted → inherit the resource-level limit (or app default)
2483
- * - `false` → disable rate limiting on this route
2484
- * - `{ max, timeWindow }` → apply this specific limit
2485
- *
2486
- * Requires `@fastify/rate-limit` registered (arc's factory wires it by
2487
- * default). Use for an expensive `/export` or an auth-sensitive `/reset`
2488
- * that needs a tighter cap than the resource's read-heavy CRUD, or `false`
2489
- * on an internal health/webhook route that must not be throttled.
2490
- *
2491
- * Note: this is per-route because each custom route is a distinct endpoint.
2492
- * `actions` share ONE `POST /:id/action` mount by design, so a per-ACTION
2493
- * limit can't be expressed here — throttle a specific action by promoting
2494
- * it to a dedicated `routes:` entry, or rely on the resource-level limit.
2233
+ * Caller MUST provide filters on these fields (else 400 at request).
2234
+ * Use to require a tenant-side narrowing the host can't infer
2235
+ * (segment id, customer id, etc.).
2495
2236
  */
2496
- readonly rateLimit?: RateLimitConfig | false;
2237
+ requireFilters?: readonly string[];
2497
2238
  /**
2498
- * Fastify route schema. Each slot (`body`, `querystring`, `params`,
2499
- * `headers`, `response[status]`) accepts a plain JSON Schema object
2500
- * **or** a Zod v4 schema — Arc auto-converts via `convertRouteSchema`.
2239
+ * Caller MUST send a bounded date range on this field. Prevents
2240
+ * all-time scans on billion-row collections.
2501
2241
  */
2502
- readonly schema?: {
2503
- body?: unknown;
2504
- querystring?: unknown;
2505
- params?: unknown;
2506
- headers?: unknown;
2507
- response?: Record<number | string, unknown>;
2508
- [key: string]: unknown;
2509
- };
2242
+ requireDateRange?: AggregationDateRangeRequirement;
2510
2243
  /**
2511
- * MCP tool generation:
2512
- * - omitted/true: auto-generate (non-raw routes only)
2513
- * - false: skip MCP
2514
- * - object: explicit config
2244
+ * Documented index expectation. Arc warns at boot when the kit
2245
+ * exposes index introspection and no matching index exists. NOT
2246
+ * runtime-enforced — purely a misconfig signal.
2515
2247
  */
2516
- readonly mcp?: boolean | RouteMcpConfig;
2248
+ indexHint?: AggregationIndexHint;
2517
2249
  /**
2518
- * MCP handler for raw routes — parallel entry point for MCP without
2519
- * changing the HTTP handler.
2250
+ * Per-aggregation cache. Tenant-scoped keys; invalidates with the
2251
+ * resource's cache namespace + any explicit `tags`.
2520
2252
  */
2521
- readonly mcpHandler?: (input: Record<string, unknown>) => Promise<{
2522
- content: Array<{
2523
- type: string;
2524
- text: string;
2525
- }>;
2526
- isError?: boolean;
2527
- }>;
2253
+ cache?: AggregationCacheConfig;
2254
+ /**
2255
+ * Per-route rate limit. Wired to `@fastify/rate-limit` when the
2256
+ * plugin is registered.
2257
+ */
2258
+ rateLimit?: AggregationRateLimit;
2259
+ /**
2260
+ * Pre-computed read replacement. When set, arc skips
2261
+ * `repo.aggregate()` and calls this function instead. Same wire
2262
+ * shape, same permissions, different data source.
2263
+ *
2264
+ * Use for homepage-counter dashboards backed by host-managed rollup
2265
+ * tables (cron / CDC). The hook receives the compiled context
2266
+ * (filter + scope) so the host can route the lookup to the right
2267
+ * pre-aggregated bucket.
2268
+ */
2269
+ materialized?: (ctx: AggregationMaterializedContext) => Promise<AggregationMaterializedResult>;
2270
+ /** Optional summary rendered in OpenAPI + MCP tool description. */
2271
+ summary?: string;
2272
+ /** Optional longer description for OpenAPI / MCP. */
2273
+ description?: string;
2274
+ /**
2275
+ * MCP tool generation control. Mirrors `actions[name].mcp` semantics.
2276
+ *
2277
+ * - `undefined` (default) — generate an MCP tool for this aggregation
2278
+ * - `false` — skip MCP tool generation (REST route still works)
2279
+ * - `{ description?, annotations? }` — generate with overrides
2280
+ */
2281
+ mcp?: boolean | {
2282
+ readonly description?: string;
2283
+ readonly annotations?: Record<string, unknown>;
2284
+ };
2528
2285
  }
2286
+ /** Map of name → declaration. Keys become URL segments under `/aggregations/<name>`. */
2287
+ type AggregationsMap = Record<string, AggregationConfig>;
2288
+ //#endregion
2289
+ //#region src/types/resource/events.d.ts
2529
2290
  /**
2530
- * Action handler function for state transitions. Receives the resource
2531
- * ID, action-specific data, and the request.
2291
+ * Domain-event declaration on a resource — name, optional handler, and
2292
+ * payload schema for the `events:` block of a resource definition.
2532
2293
  */
2533
- type ActionHandlerFn = (id: string, data: Record<string, unknown>, req: RequestWithExtras) => Promise<unknown>;
2294
+ interface EventDefinition {
2295
+ name: string;
2296
+ /** Optional handler — events are published via `fastify.events.publish()`. */
2297
+ handler?: (data: unknown) => Promise<void> | void;
2298
+ /**
2299
+ * JSON Schema or Zod v4 schema for event payload. Typed `unknown` so Zod
2300
+ * class instances assign without a cast (same convention as
2301
+ * `ActionDefinition.schema` and `RouteDefinition.schema`).
2302
+ */
2303
+ schema?: unknown;
2304
+ description?: string;
2305
+ }
2306
+ //#endregion
2307
+ //#region src/types/resource/extensions.d.ts
2534
2308
  /**
2535
- * Full action configuration with handler, permissions, and schema.
2309
+ * `ResourceExtensions` — the typed plugin-extension namespace plugins
2310
+ * augment via declaration merging (`declare module "@classytic/arc/types"`).
2311
+ */
2312
+ /**
2313
+ * Plugin extension namespace — arc's typed escape hatch for attaching
2314
+ * declarative, per-resource config that **plugins** read at request time.
2536
2315
  *
2537
- * Rate limiting is intentionally NOT per-action: every action shares one
2538
- * `POST /:id/action` (or `POST /action`) mount, so Fastify's per-route limit
2539
- * can't distinguish them. Actions inherit the resource-level `rateLimit`; to
2540
- * throttle a specific operation, promote it to a `routes:` entry (which
2541
- * supports `RouteDefinition.rateLimit`).
2316
+ * **External** plugins augment it via TypeScript declaration merging
2317
+ * (`declare module "@classytic/arc/types"`) to register their own typed
2318
+ * slice — exactly the model Fastify uses for `FastifyInstance` decorators.
2319
+ * The host gets full autocomplete + compile-time checking on the matching
2320
+ * `extensions` block, and a typo (`extensions: { encyrption: … }`) is a
2321
+ * type error rather than a silent no-op.
2322
+ *
2323
+ * **First-party** slices (arc's own subpath plugins) are declared inline
2324
+ * below with type-only imports instead of `declare module`. Not a style
2325
+ * choice: arc bundles its declarations, and a relative module augmentation
2326
+ * (`declare module "../types/resource.js"`) survives bundling as an
2327
+ * unresolvable specifier — the merge silently never happens for consumers,
2328
+ * so the key would be a compile ERROR downstream while working inside this
2329
+ * repo. Inline declaration is bundler-proof; the type-only import is erased
2330
+ * at runtime, so the plugin stays fully opt-in.
2331
+ *
2332
+ * **The "React for backend" composition model.** `defineResource()` is the
2333
+ * declarative component, `extensions` is its typed props bag, and plugins
2334
+ * are the providers that consume those props at the framework boundary.
2335
+ * Adding a cross-cutting capability becomes *additive* — a plugin ships a
2336
+ * subpath + a one-line `declare module` augmentation, with no new
2337
+ * first-class `ResourceConfig` field and no core release per feature.
2338
+ *
2339
+ * Arc threads the declared `extensions` onto every generated route's
2340
+ * Fastify `config` (see `createCrudRouter`), so a plugin reads its slice
2341
+ * at request time via `request.routeOptions.config.arcExtensions` without
2342
+ * re-deriving which resource a route belongs to.
2343
+ *
2344
+ * @example An external plugin package registers its slice
2345
+ * ```ts
2346
+ * declare module "@classytic/arc/types" {
2347
+ * interface ResourceExtensions {
2348
+ * myPlugin?: import("my-arc-plugin").MyPluginDirective;
2349
+ * }
2350
+ * }
2351
+ * ```
2352
+ *
2353
+ * @example A host declares it on a resource
2354
+ * ```ts
2355
+ * defineResource({
2356
+ * name: "payment",
2357
+ * extensions: { encryption: { mode: "fields", fields: ["cardNumber", "cvv"] } },
2358
+ * });
2359
+ * ```
2542
2360
  */
2543
- interface ActionDefinition {
2544
- readonly handler: ActionHandlerFn;
2545
- /** Per-action permission (overrides resource-level `actionPermissions`) */
2546
- readonly permissions?: PermissionCheck;
2547
- /**
2548
- * JSON Schema or Zod v4 schema for action-specific body fields.
2549
- *
2550
- * Typed `unknown` (not `Record<string, unknown>`) so Zod class instances
2551
- * — `ZodObject<...>` carries no string index signature — assign without
2552
- * a cast. Same convention as `RouteDefinition.schema.body` / `customSchemas`.
2553
- * Runtime feature-detects via `convertRouteSchema` / `toJsonSchema`.
2554
- */
2555
- readonly schema?: unknown;
2556
- /** Description for OpenAPI docs and MCP tool */
2557
- readonly description?: string;
2558
- /**
2559
- * Whether this action needs an entity id from the URL.
2560
- *
2561
- * - `true` (default) — mounts under `POST /<prefix>/:id/action`. The `id`
2562
- * path param is required; handler receives it as the first argument.
2563
- * Use for actions that operate on an existing entity: `approve`,
2564
- * `dispatch`, `cancel`, `archive`.
2565
- * - `false` — mounts under `POST /<prefix>/action` (no `:id` segment).
2566
- * Handler receives an empty-string first argument. Use for
2567
- * collection-level actions that create / search / bulk-mutate:
2568
- * `propose` (creates a new entity), `search` (returns rows), `bulk`.
2569
- *
2570
- * 2.15.5: previously every action had to live under `:id/action`, forcing
2571
- * `propose`-style actions to swallow a meaningless URL parameter and
2572
- * making the auto-generated MCP tool advertise an `id` field agents
2573
- * had no value for. Setting `id: false` mounts the action at the
2574
- * resource root and drops `id` from the MCP tool's input shape.
2575
- */
2576
- readonly id?: boolean;
2361
+ interface ResourceExtensions {
2577
2362
  /**
2578
- * MCP tool generation:
2579
- * - omitted/true: auto-generate
2580
- * - false: skip
2581
- * - object: explicit config
2363
+ * Encrypt this resource's responses — full-body JWE or specific fields.
2364
+ * Read at request time by `@classytic/arc/encryption`'s `encryptionPlugin`
2365
+ * from `request.routeOptions.config.arcExtensions.encryption`; inert (and
2366
+ * dependency-free — the import is type-only) unless that plugin is
2367
+ * registered.
2582
2368
  */
2583
- readonly mcp?: boolean | RouteMcpConfig;
2369
+ encryption?: EncryptionDirective;
2584
2370
  }
2585
- /** Action config: bare handler function OR full ActionDefinition. */
2586
- type ActionEntry = ActionHandlerFn | ActionDefinition;
2587
- /** Actions configuration map. */
2588
- type ActionsMap = Record<string, ActionEntry>;
2371
+ //#endregion
2372
+ //#region src/types/resource/hooks.d.ts
2589
2373
  /**
2590
2374
  * Hook context passed to resource-level hook handlers. Mirrors
2591
2375
  * HookSystem's HookContext but with a simpler API for inline use.
@@ -2633,39 +2417,304 @@ interface ResourceHookContext {
2633
2417
  * identically-named field on `IRequestContext` (v2.10.6) so the same
2634
2418
  * read pattern works in controllers and hooks.
2635
2419
  */
2636
- scope?: {
2637
- organizationId?: string;
2638
- userId?: string;
2639
- orgRoles?: string[];
2420
+ scope?: {
2421
+ organizationId?: string;
2422
+ userId?: string;
2423
+ orgRoles?: string[];
2424
+ };
2425
+ /** Additional metadata (e.g. `{ id, existing }` for update/delete) */
2426
+ meta?: AnyRecord;
2427
+ }
2428
+ /**
2429
+ * Inline lifecycle hooks on a resource definition. Wired into the
2430
+ * HookSystem automatically — same pipeline as presets and app-level hooks.
2431
+ *
2432
+ * @example
2433
+ * ```typescript
2434
+ * defineResource({
2435
+ * name: 'chat',
2436
+ * hooks: {
2437
+ * afterCreate: async (ctx) => { analytics.track('chat.created', { id: ctx.data._id }); },
2438
+ * beforeDelete: async (ctx) => {
2439
+ * if (ctx.data.isProtected) throw new Error('Cannot delete protected chat');
2440
+ * },
2441
+ * },
2442
+ * });
2443
+ * ```
2444
+ */
2445
+ interface ResourceHooks {
2446
+ beforeCreate?: (ctx: ResourceHookContext) => Promise<AnyRecord | undefined> | AnyRecord | undefined;
2447
+ afterCreate?: (ctx: ResourceHookContext) => Promise<void> | void;
2448
+ beforeUpdate?: (ctx: ResourceHookContext) => Promise<AnyRecord | undefined> | AnyRecord | undefined;
2449
+ afterUpdate?: (ctx: ResourceHookContext) => Promise<void> | void;
2450
+ beforeDelete?: (ctx: ResourceHookContext) => Promise<void> | void;
2451
+ afterDelete?: (ctx: ResourceHookContext) => Promise<void> | void;
2452
+ }
2453
+ //#endregion
2454
+ //#region src/types/resource/fields.d.ts
2455
+ /**
2456
+ * Per-field rule — arc's extension of repo-core's 4-field `FieldRule` floor
2457
+ * (`immutable`, `immutableAfterCreate`, `systemManaged`, `optional`) with
2458
+ * the constraint / UI / security bits arc layers on top.
2459
+ *
2460
+ * Kept structurally compatible with `@classytic/repo-core/schema`'s
2461
+ * `FieldRule` so arc's `fieldRules: Record<string, ArcFieldRule>` flows
2462
+ * into mongokit's / sqlitekit's `buildCrudSchemasFromModel(..., options)`
2463
+ * without a cast. See `RouteSchemaOptions` JSDoc for the full rationale.
2464
+ */
2465
+ interface ArcFieldRule extends FieldRule {
2466
+ /**
2467
+ * When `true`, bypass the `systemManaged` / `readonly` / `immutable`
2468
+ * strip in `BodySanitizer` for callers whose request scope is
2469
+ * `elevated`. Lets platform admins stamp the value from the request
2470
+ * body — needed for cross-tenant admin writes where the tenant field
2471
+ * is the only way to pick a target org.
2472
+ *
2473
+ * Auto-set by `defineResource` on the configured `tenantField`. Hosts
2474
+ * can set it manually on other fields (e.g. `createdBy`) if they want
2475
+ * elevation-only override semantics for those too.
2476
+ *
2477
+ * Has no effect when `isElevated(scope)` is false — member and
2478
+ * service callers continue to have the field stripped.
2479
+ */
2480
+ preserveForElevated?: boolean;
2481
+ hidden?: boolean;
2482
+ /**
2483
+ * Aggregation visibility override. By default, only `hidden: true`
2484
+ * blocks a field from `groupBy` / `measures.field` / `sort` / `dateBuckets`
2485
+ * — that's the genuine cardinality-leak guard (the value is omitted from
2486
+ * list/get responses, so exposing it via aggregation would reveal data
2487
+ * the client can't otherwise see).
2488
+ *
2489
+ * `systemManaged: true` does **not** block aggregation — it's a write
2490
+ * rule, not a visibility rule. Server-stamped fields like `createdAt`,
2491
+ * `status`, or plugin-generated handles are visible in every list
2492
+ * response and should aggregate freely.
2493
+ *
2494
+ * Use this flag to override the default:
2495
+ *
2496
+ * - `aggregable: false` — explicit deny, even on visible fields. Useful
2497
+ * when a value is exposed per-row but the cardinality across rows is
2498
+ * itself sensitive (e.g. `email` is visible in `get/:id` to admins
2499
+ * but you don't want a public-readable agg of email distributions).
2500
+ * - `aggregable: true` — escape hatch on `hidden` fields. Lets you
2501
+ * aggregate a hidden column when you're sure cardinality leakage
2502
+ * isn't a concern (e.g. `internalScore` hidden from list, but a
2503
+ * committee-only `byScore` agg is fine).
2504
+ *
2505
+ * Defaults to `undefined` (use the `hidden`-only rule).
2506
+ */
2507
+ aggregable?: boolean;
2508
+ /** String minimum length — auto-maps to OpenAPI `minLength` and MCP tool schema */
2509
+ minLength?: number;
2510
+ /** String maximum length — auto-maps to OpenAPI `maxLength` and MCP tool schema */
2511
+ maxLength?: number;
2512
+ /** Number minimum — auto-maps to OpenAPI `minimum` and MCP tool schema */
2513
+ min?: number;
2514
+ /** Number maximum — auto-maps to OpenAPI `maximum` and MCP tool schema */
2515
+ max?: number;
2516
+ /** Regex pattern — auto-maps to OpenAPI `pattern` and MCP tool schema */
2517
+ pattern?: string;
2518
+ /** Allowed values — auto-maps to OpenAPI `enum` and MCP tool schema */
2519
+ enum?: ReadonlyArray<string | number>;
2520
+ /**
2521
+ * When `true`, widen the JSON Schema `type` of this field to also
2522
+ * accept `null`. Mirrors Zod's `.nullable()` at the arc config layer
2523
+ * for kit-generated schemas that don't carry the flag end-to-end
2524
+ * (e.g. Zod → Mongoose → mongokit drops `.nullable()` because
2525
+ * Mongoose has no first-class nullable marker unless `default: null`
2526
+ * is also set).
2527
+ *
2528
+ * Applied post-kit by `mergeFieldRuleConstraints`: if the adapter
2529
+ * emitted `{ type: 'string', enum: [...] }` for a field arc should
2530
+ * accept null for, the merge widens it to
2531
+ * `{ type: ['string', 'null'], enum: [...] }` — draft-7 tuple form
2532
+ * AJV 8 validates natively.
2533
+ *
2534
+ * No-op when the property already declares `type: [...,'null']` or
2535
+ * an `anyOf: [..., { type: 'null' }]` branch — arc never fights the
2536
+ * kit's own output.
2537
+ */
2538
+ nullable?: boolean;
2539
+ /** Human-readable description — auto-maps to OpenAPI `description` */
2540
+ description?: string;
2541
+ [key: string]: unknown;
2542
+ }
2543
+ interface FieldRule$1 {
2544
+ field: string;
2545
+ required?: boolean;
2546
+ readonly?: boolean;
2547
+ hidden?: boolean;
2548
+ }
2549
+ //#endregion
2550
+ //#region src/types/resource/schemas.d.ts
2551
+ /**
2552
+ * Schema-shaping options for a resource.
2553
+ *
2554
+ * Extends `@classytic/repo-core/schema`'s `SchemaBuilderOptions` so every
2555
+ * kit-generator callback typed against the repo-core contract
2556
+ * (mongokit's `buildCrudSchemasFromModel`, sqlitekit's
2557
+ * `buildCrudSchemasFromTable`, prismakit's equivalent) accepts arc's
2558
+ * options bag directly — no `as SchemaBuilderOptions` / `Parameters<...>[1]`
2559
+ * cast at the host wiring site.
2560
+ *
2561
+ * Inherited from `SchemaBuilderOptions`:
2562
+ * - `strictAdditionalProperties` — emit `additionalProperties: false`
2563
+ * - `dateAs` — `'date'` vs `'datetime'` ISO rendering
2564
+ * - `softRequiredFields` — stay in `properties`, drop from `required[]`
2565
+ * - `create: { omitFields, requiredOverrides, optionalOverrides, schemaOverrides }`
2566
+ * - `update: { omitFields, requireAtLeastOne }`
2567
+ * - `query: { filterableFields }` (kit-native filter declaration)
2568
+ * - `openApiExtensions` — emit `x-*` vendor keywords for docgen
2569
+ *
2570
+ * Arc adds:
2571
+ * - `fieldRules` with the richer `ArcFieldRule` per-entry shape
2572
+ * (preserveForElevated, minLength/maxLength/min/max/pattern, enum,
2573
+ * nullable, description) — arc's extensions are applied post-kit by
2574
+ * `mergeFieldRuleConstraints`; the kit only sees the repo-core floor.
2575
+ * - `hiddenFields` / `readonlyFields` / `requiredFields` / `optionalFields`
2576
+ * / `excludeFields` — arc-only convenience lists that predate fieldRules.
2577
+ * Keep using them if they're already in place; new code should prefer
2578
+ * `fieldRules` for per-field control.
2579
+ * - `filterableFields: string[]` — top-level list arc's MCP layer auto-
2580
+ * derives from `QueryParser.allowedFilterFields`. Distinct from the
2581
+ * inherited `query.filterableFields: Record<...>` which feeds the kit's
2582
+ * list-query schema; nothing stops a resource from using both.
2583
+ *
2584
+ * **Why extend rather than duplicate**: mongokit's
2585
+ * `buildCrudSchemasFromModel(model, options: SchemaBuilderOptions)` is the
2586
+ * canonical callback shape. Before the extension, hosts wrote
2587
+ * `Parameters<typeof buildCrudSchemasFromModel>[1]` or
2588
+ * `as SchemaBuilderOptions` at every wiring site — a defensive cast with
2589
+ * no runtime effect. Extension locks the structural relationship at the
2590
+ * type layer so the cast is compile-verified gone.
2591
+ */
2592
+ interface RouteSchemaOptions extends SchemaBuilderOptions {
2593
+ hiddenFields?: string[];
2594
+ readonlyFields?: string[];
2595
+ requiredFields?: string[];
2596
+ optionalFields?: string[];
2597
+ excludeFields?: string[];
2598
+ /**
2599
+ * Fields allowed for filtering in list operations. MCP auto-derives
2600
+ * from `QueryParser.allowedFilterFields` when not set explicitly.
2601
+ *
2602
+ * Distinct from the inherited `query.filterableFields: Record<...>`
2603
+ * from `SchemaBuilderOptions` — that entry feeds the kit's list-query
2604
+ * JSON Schema; this one is arc's MCP-auto-derivation list.
2605
+ */
2606
+ filterableFields?: string[];
2607
+ /**
2608
+ * Per-field rules. Richer than repo-core's `FieldRules` — arc adds
2609
+ * `preserveForElevated`, constraint hints (`minLength`, `enum`,
2610
+ * `nullable`, etc.), and `description` on top of the four-flag floor
2611
+ * (`immutable`, `immutableAfterCreate`, `systemManaged`, `optional`).
2612
+ *
2613
+ * Structurally compatible: `Record<string, ArcFieldRule>` is assignable
2614
+ * to repo-core's `Record<string, FieldRule>` since `ArcFieldRule extends
2615
+ * FieldRule`. Kits see only the floor; arc's extensions are applied
2616
+ * post-kit by `mergeFieldRuleConstraints`.
2617
+ */
2618
+ fieldRules?: Record<string, ArcFieldRule>;
2619
+ /**
2620
+ * Query-time security whitelists + the kit's `filterableFields`.
2621
+ *
2622
+ * Extends repo-core's `SchemaBuilderOptions['query']` with arc-specific
2623
+ * runtime features that `QueryResolver` reads at request time:
2624
+ *
2625
+ * - **`allowedPopulate`** — populate-path whitelist consumed by
2626
+ * `QueryResolver.sanitizePopulate` / `sanitizeAdvancedPopulate`.
2627
+ * When set, only paths in the list pass through; everything else is
2628
+ * stripped silently. Shrinks the auto-wired `?populate=` attack surface.
2629
+ *
2630
+ * - **`allowedLookups`** — lookup-collection whitelist consumed by
2631
+ * `QueryResolver.sanitizeLookups`. When set, only the listed
2632
+ * collections may be `$lookup`'d into the pipeline.
2633
+ *
2634
+ * Both are pre-2.11.2 runtime features — the type was missing them, so
2635
+ * hosts wrote `as Record<string, unknown>` at every call site. Arc's own
2636
+ * `QueryResolver` had to cast its own input via `as AnyRecord` for the
2637
+ * same reason. Adding the type dropped both casts.
2638
+ */
2639
+ query?: SchemaBuilderOptions["query"] & {
2640
+ /**
2641
+ * Populate-path whitelist. When set, `QueryResolver.sanitizePopulate`
2642
+ * strips any `?populate=<path>` not in this list. Omit to allow all
2643
+ * paths the kit recognizes.
2644
+ */
2645
+ allowedPopulate?: string[];
2646
+ /**
2647
+ * Lookup-collection whitelist for `QueryResolver.sanitizeLookups`.
2648
+ * When set, only the listed collections may be `$lookup`'d. Omit to
2649
+ * disable the whitelist (kit-level rules still apply).
2650
+ */
2651
+ allowedLookups?: string[];
2640
2652
  };
2641
- /** Additional metadata (e.g. `{ id, existing }` for update/delete) */
2642
- meta?: AnyRecord;
2643
2653
  }
2644
2654
  /**
2645
- * Inline lifecycle hooks on a resource definition. Wired into the
2646
- * HookSystem automatically — same pipeline as presets and app-level hooks.
2647
- *
2648
- * @example
2649
- * ```typescript
2650
- * defineResource({
2651
- * name: 'chat',
2652
- * hooks: {
2653
- * afterCreate: async (ctx) => { analytics.track('chat.created', { id: ctx.data._id }); },
2654
- * beforeDelete: async (ctx) => {
2655
- * if (ctx.data.isProtected) throw new Error('Cannot delete protected chat');
2656
- * },
2657
- * },
2658
- * });
2659
- * ```
2655
+ * CRUD route schemas (Fastify native format). Each slot accepts a plain
2656
+ * JSON Schema object **or** a Zod v4 schema — Arc's `convertRouteSchema`
2657
+ * feature-detects at runtime. Slot values are typed `unknown` so
2658
+ * class-based Zod schemas assign without casts.
2660
2659
  */
2661
- interface ResourceHooks {
2662
- beforeCreate?: (ctx: ResourceHookContext) => Promise<AnyRecord | undefined> | AnyRecord | undefined;
2663
- afterCreate?: (ctx: ResourceHookContext) => Promise<void> | void;
2664
- beforeUpdate?: (ctx: ResourceHookContext) => Promise<AnyRecord | undefined> | AnyRecord | undefined;
2665
- afterUpdate?: (ctx: ResourceHookContext) => Promise<void> | void;
2666
- beforeDelete?: (ctx: ResourceHookContext) => Promise<void> | void;
2667
- afterDelete?: (ctx: ResourceHookContext) => Promise<void> | void;
2660
+ interface CrudSchemas {
2661
+ /** GET / — list */
2662
+ list?: {
2663
+ querystring?: unknown;
2664
+ response?: Record<number, unknown>;
2665
+ [key: string]: unknown;
2666
+ };
2667
+ /** GET /:id — get one */
2668
+ get?: {
2669
+ params?: unknown;
2670
+ response?: Record<number, unknown>;
2671
+ [key: string]: unknown;
2672
+ };
2673
+ /** POST / — create */
2674
+ create?: {
2675
+ body?: unknown;
2676
+ response?: Record<number, unknown>;
2677
+ [key: string]: unknown;
2678
+ };
2679
+ /** PATCH /:id — update */
2680
+ update?: {
2681
+ params?: unknown;
2682
+ body?: unknown;
2683
+ response?: Record<number, unknown>;
2684
+ [key: string]: unknown;
2685
+ };
2686
+ /** DELETE /:id — delete */
2687
+ delete?: {
2688
+ params?: unknown;
2689
+ response?: Record<number, unknown>;
2690
+ [key: string]: unknown;
2691
+ };
2692
+ [key: string]: unknown;
2693
+ }
2694
+ interface OpenApiSchemas {
2695
+ entity?: unknown;
2696
+ createBody?: unknown;
2697
+ updateBody?: unknown;
2698
+ params?: unknown;
2699
+ listQuery?: unknown;
2700
+ /**
2701
+ * Explicit response schema for OpenAPI documentation. Auto-generated
2702
+ * from `createBody` if omitted. Does NOT affect Fastify serialization.
2703
+ */
2704
+ response?: unknown;
2705
+ [key: string]: unknown;
2668
2706
  }
2707
+ type CrudRouteKey = "list" | "get" | "create" | "update" | "delete";
2708
+ interface MiddlewareConfig {
2709
+ list?: MiddlewareHandler[];
2710
+ get?: MiddlewareHandler[];
2711
+ create?: MiddlewareHandler[];
2712
+ update?: MiddlewareHandler[];
2713
+ delete?: MiddlewareHandler[];
2714
+ [key: string]: MiddlewareHandler[] | undefined;
2715
+ }
2716
+ //#endregion
2717
+ //#region src/types/resource/presets.d.ts
2669
2718
  interface PresetHook {
2670
2719
  operation: "create" | "update" | "delete" | "read" | "list";
2671
2720
  phase: "before" | "after";
@@ -2682,18 +2731,68 @@ interface PresetResult {
2682
2731
  hooks?: PresetHook[];
2683
2732
  }
2684
2733
  type PresetFunction = (config: ResourceConfig) => PresetResult;
2685
- interface EventDefinition {
2686
- name: string;
2687
- /** Optional handler — events are published via `fastify.events.publish()`. */
2688
- handler?: (data: unknown) => Promise<void> | void;
2734
+ //#endregion
2735
+ //#region src/types/resource/tenant.d.ts
2736
+ /**
2737
+ * Tenant-cleanup declaration on a resource — compliance-grade strategy
2738
+ * for what happens to this resource's rows when the owning organization
2739
+ * is deleted. Surfaces in arc's org-delete cascade runner and in
2740
+ * registry introspection (audit scripts ask "what happens to this
2741
+ * resource on org delete?").
2742
+ *
2743
+ * Strategy variants:
2744
+ * - `hard` — permanent removal (GDPR right-to-be-forgotten).
2745
+ * - `soft` — recoverable; pair with TTL for eventual hard-purge.
2746
+ * - `anonymize` — keep the row (legal retention) but clear PII
2747
+ * (HIPAA / PCI / SOX-compatible).
2748
+ * - `skip` — explicit opt-out with mandatory `reason`.
2749
+ *
2750
+ * See {@link ResourceConfig.onTenantDelete} for the full decision tree.
2751
+ */
2752
+ interface OnTenantDeleteConfig {
2689
2753
  /**
2690
- * JSON Schema or Zod v4 schema for event payload. Typed `unknown` so Zod
2691
- * class instances assign without a cast (same convention as
2692
- * `ActionDefinition.schema` and `RouteDefinition.schema`).
2754
+ * What to do with rows whose `tenantField` matches the deleted org.
2755
+ * Discriminated union from `@classytic/repo-core/repository` — every
2756
+ * kit's `purgeByField` consumes the same shape.
2693
2757
  */
2694
- schema?: unknown;
2695
- description?: string;
2758
+ strategy: TenantPurgeStrategy;
2759
+ /**
2760
+ * Resources are processed in ascending `priority` order. Use to land
2761
+ * leaf data (logs, events) before aggregate references. Default `100`.
2762
+ */
2763
+ priority?: number;
2764
+ /**
2765
+ * Rows per chunk for the underlying `purgeByField` call — bounds
2766
+ * lock contention + replication-log pressure on very large tenants.
2767
+ * Default kit-specific (~1000).
2768
+ */
2769
+ batchSize?: number;
2770
+ }
2771
+ /**
2772
+ * Resolved tenant-purge declaration — what arc actually runs when
2773
+ * `cascadeDeleteForOrganization` fires. Computed once at boot from the
2774
+ * resource's `onTenantDelete` declaration.
2775
+ *
2776
+ * Exposed via `ResourceDefinition.resolvedTenantPurge` and
2777
+ * `getCascadingResourcesWithMetadata(registry)` so audit tooling can
2778
+ * answer "is this resource really going to hard-delete?" without
2779
+ * reading the source.
2780
+ */
2781
+ interface ResolvedTenantPurge {
2782
+ readonly strategy: TenantPurgeStrategy;
2783
+ readonly priority: number;
2784
+ readonly batchSize?: number;
2785
+ /**
2786
+ * Where the strategy came from — `'declared'` (host wrote
2787
+ * `onTenantDelete` explicitly) or `'disabled'` (no declaration —
2788
+ * runner skips this resource).
2789
+ */
2790
+ readonly source: "declared" | "disabled";
2696
2791
  }
2792
+ //#endregion
2793
+ //#region src/types/resource/config.d.ts
2794
+ /** Standard controller type alias for CRUD operations. */
2795
+ type CrudController<TDoc> = IController<TDoc>;
2697
2796
  /** Resource-level permissions — only `PermissionCheck` functions allowed. */
2698
2797
  interface ResourcePermissions {
2699
2798
  list?: PermissionCheck;
@@ -2702,65 +2801,6 @@ interface ResourcePermissions {
2702
2801
  update?: PermissionCheck;
2703
2802
  delete?: PermissionCheck;
2704
2803
  }
2705
- /**
2706
- * Plugin extension namespace — arc's typed escape hatch for attaching
2707
- * declarative, per-resource config that **plugins** read at request time.
2708
- *
2709
- * **External** plugins augment it via TypeScript declaration merging
2710
- * (`declare module "@classytic/arc/types"`) to register their own typed
2711
- * slice — exactly the model Fastify uses for `FastifyInstance` decorators.
2712
- * The host gets full autocomplete + compile-time checking on the matching
2713
- * `extensions` block, and a typo (`extensions: { encyrption: … }`) is a
2714
- * type error rather than a silent no-op.
2715
- *
2716
- * **First-party** slices (arc's own subpath plugins) are declared inline
2717
- * below with type-only imports instead of `declare module`. Not a style
2718
- * choice: arc bundles its declarations, and a relative module augmentation
2719
- * (`declare module "../types/resource.js"`) survives bundling as an
2720
- * unresolvable specifier — the merge silently never happens for consumers,
2721
- * so the key would be a compile ERROR downstream while working inside this
2722
- * repo. Inline declaration is bundler-proof; the type-only import is erased
2723
- * at runtime, so the plugin stays fully opt-in.
2724
- *
2725
- * **The "React for backend" composition model.** `defineResource()` is the
2726
- * declarative component, `extensions` is its typed props bag, and plugins
2727
- * are the providers that consume those props at the framework boundary.
2728
- * Adding a cross-cutting capability becomes *additive* — a plugin ships a
2729
- * subpath + a one-line `declare module` augmentation, with no new
2730
- * first-class `ResourceConfig` field and no core release per feature.
2731
- *
2732
- * Arc threads the declared `extensions` onto every generated route's
2733
- * Fastify `config` (see `createCrudRouter`), so a plugin reads its slice
2734
- * at request time via `request.routeOptions.config.arcExtensions` without
2735
- * re-deriving which resource a route belongs to.
2736
- *
2737
- * @example An external plugin package registers its slice
2738
- * ```ts
2739
- * declare module "@classytic/arc/types" {
2740
- * interface ResourceExtensions {
2741
- * myPlugin?: import("my-arc-plugin").MyPluginDirective;
2742
- * }
2743
- * }
2744
- * ```
2745
- *
2746
- * @example A host declares it on a resource
2747
- * ```ts
2748
- * defineResource({
2749
- * name: "payment",
2750
- * extensions: { encryption: { mode: "fields", fields: ["cardNumber", "cvv"] } },
2751
- * });
2752
- * ```
2753
- */
2754
- interface ResourceExtensions {
2755
- /**
2756
- * Encrypt this resource's responses — full-body JWE or specific fields.
2757
- * Read at request time by `@classytic/arc/encryption`'s `encryptionPlugin`
2758
- * from `request.routeOptions.config.arcExtensions.encryption`; inert (and
2759
- * dependency-free — the import is type-only) unless that plugin is
2760
- * registered.
2761
- */
2762
- encryption?: EncryptionDirective;
2763
- }
2764
2804
  interface ResourceConfig<TDoc = AnyRecord> {
2765
2805
  name: string;
2766
2806
  displayName?: string;
@@ -3191,6 +3231,28 @@ interface ResourceConfig<TDoc = AnyRecord> {
3191
3231
  audit?: boolean | {
3192
3232
  operations?: ("create" | "update" | "delete")[];
3193
3233
  };
3234
+ /**
3235
+ * Per-record change timeline (2.22) — `history: true` adds
3236
+ * `GET /:prefix/:id/history`, serving this record's audit entries
3237
+ * (who/when/what-changed, newest first, `?limit=&offset=`). Implies
3238
+ * `audit: true` (the flag auto-enables it when unset) and requires
3239
+ * `auditPlugin` to be registered — the route answers 503 with
3240
+ * `history.audit_unavailable` otherwise.
3241
+ *
3242
+ * Change history exposes before/after snapshots, so the gate defaults
3243
+ * STRICTER than reads: the resource's `update` permission, falling back
3244
+ * to `get`, falling back to authenticated-only via the route's normal
3245
+ * auth. Override with the object form:
3246
+ *
3247
+ * ```ts
3248
+ * defineResource({ name: 'order', history: true });
3249
+ * defineResource({ name: 'payment', history: { permissions: requireRoles(['auditor']), limit: 100 } });
3250
+ * ```
3251
+ */
3252
+ history?: boolean | {
3253
+ permissions?: PermissionCheck;
3254
+ limit?: number;
3255
+ };
3194
3256
  /**
3195
3257
  * Typed plugin-extension namespace — declarative per-resource config that
3196
3258
  * arc plugins read at request time. Empty by default; each installed
@@ -4175,4 +4237,4 @@ interface ValidateOptions {
4175
4237
  strict?: boolean;
4176
4238
  }
4177
4239
  //#endregion
4178
- export { OnTenantDeleteConfig as $, UserOrganization as $t, RequestIdOptions as A, ArcCreateResult as An, AggregationMaterializedResult as At, defineResource as B, BodySanitizerConfig as Bn, Transform as Bt, RequestContext as C, afterDelete as Cn, AggMeasureInput as Ct, HealthCheck as D, beforeUpdate as Dn, AggregationDateRangeRequirement as Dt, GracefulShutdownOptions as E, beforeDelete as En, AggregationConfig as Et, FastifyWithDecorators as F, BaseControllerOptions as Fn, NextFunction as Ft, ActionsMap as G, JwtContext as Gt, ActionDefinition as H, AuthPluginOptions as Ht, MiddlewareHandler as I, ControllerConfigurableOptions as In, OperationFilter as It, CrudRouteKey as J, ApiResponse as Jt, ArcFieldRule as K, TokenPair as Kt, RequestWithExtras as L, ControllerConstructionOptions as Ln, PipelineConfig as Lt, EventsDecorator as M, ArcGetResult as Mn, AggregationsMap as Mt, FastifyRequestExtras as N, ArcListResult as Nn, Guard as Nt, HealthOptions as O, createHookSystem as On, AggregationIndexHint as Ot, FastifyWithAuth as P, ArcUpdateResult as Pn, Interceptor as Pt, MiddlewareConfig as Q, UserLike as Qt, RegisterOptions as R, ListResult as Rn, PipelineContext as Rt, QueryParserInterface as S, afterCreate as Sn, RouteHandler as St, CrudRouterOptions as T, beforeCreate as Tn, AggregationCacheConfig as Tt, ActionEntry as U, Authenticator as Ut, ResourceDefinition as V, AuthHelpers as Vt, ActionHandlerFn as W, AuthenticatorContext as Wt, EventDefinition as X, JWTPayload as Xt, CrudSchemas as Y, ArcRequest as Yt, FieldRule$1 as Z, ObjectId as Zt, ControllerQueryOptions as _, HookOperation as _n, ControllerLike as _t, InferAdapterDoc as a, SlugExt as an, ResolvedTenantPurge as at, ParsedQuery as b, HookSystem as bn, IControllerResponse as bt, TypedController as c, BulkMixin as cn, ResourceExtensions as ct, PaginationResult as d, QueryResolverConfig as dn, ResourcePermissions as dt, BaseController as en, OpenApiSchemas as et, IntrospectionData as f, AccessControl as fn, RouteDefinition as ft, ArcInternalMetadata as g, HookHandler as gn, ControllerHandler as gt, ResourceMetadata as h, HookContext as hn, RouteSchemaOptions as ht, ValidationResult as i, TreeMixin as in, RateLimitConfig as it, ArcDecorator as j, ArcDeleteResult as jn, AggregationRateLimit as jt, IntrospectionPluginOptions as k, defineHook as kn, AggregationMaterializedContext as kt, TypedRepository as l, BaseCrudController as ln, ResourceHookContext as lt, RegistryStats as m, DefineHookOptions as mn, RouteMethod as mt, ConfigError as n, SoftDeleteMixin as nn, PresetHook as nt, InferDocType as o, SlugMixin as on, ResourceCacheConfig as ot, RegistryEntry as p, AccessControlConfig as pn, RouteMcpConfig as pt, CrudController as q, AnyRecord as qt, ValidateOptions as r, TreeExt as rn, PresetResult as rt, InferResourceDoc as s, BulkExt as sn, ResourceConfig as st, RouteHandlerMethod$1 as t, SoftDeleteExt as tn, PresetFunction as tt, TypedResourceConfig as u, QueryResolver as un, ResourceHooks as ut, LookupOption as v, HookPhase as vn, FastifyHandler as vt, ServiceContext as w, afterUpdate as wn, AggMeasureShorthand as wt, PopulateOption as x, HookSystemOptions as xn, IRequestContext as xt, OwnershipCheck as y, HookRegistration as yn, IController as yt, ResourceRegistry as z, BodySanitizer as zn, PipelineStep as zt };
4240
+ export { OpenApiSchemas as $, UserOrganization as $t, RequestIdOptions as A, ArcCreateResult as An, RouteDefinition as At, defineResource as B, BodySanitizerConfig as Bn, RouteHandler as Bt, RequestContext as C, afterDelete as Cn, PipelineStep as Ct, HealthCheck as D, beforeUpdate as Dn, ActionEntry as Dt, GracefulShutdownOptions as E, beforeDelete as En, ActionDefinition as Et, FastifyWithDecorators as F, BaseControllerOptions as Fn, ControllerLike as Ft, OnTenantDeleteConfig as G, JwtContext as Gt, CrudController as H, AuthPluginOptions as Ht, MiddlewareHandler as I, ControllerConfigurableOptions as In, FastifyHandler as It, PresetHook as J, ApiResponse as Jt, ResolvedTenantPurge as K, TokenPair as Kt, RequestWithExtras as L, ControllerConstructionOptions as Ln, IController as Lt, EventsDecorator as M, ArcGetResult as Mn, RouteMethod as Mt, FastifyRequestExtras as N, ArcListResult as Nn, RateLimitConfig as Nt, HealthOptions as O, createHookSystem as On, ActionHandlerFn as Ot, FastifyWithAuth as P, ArcUpdateResult as Pn, ControllerHandler as Pt, MiddlewareConfig as Q, UserLike as Qt, RegisterOptions as R, ListResult as Rn, IControllerResponse as Rt, QueryParserInterface as S, afterCreate as Sn, PipelineContext as St, CrudRouterOptions as T, beforeCreate as Tn, ResourceCacheConfig as Tt, ResourceConfig as U, Authenticator as Ut, ResourceDefinition as V, AuthHelpers as Vt, ResourcePermissions as W, AuthenticatorContext as Wt, CrudRouteKey as X, JWTPayload as Xt, PresetResult as Y, ArcRequest as Yt, CrudSchemas as Z, ObjectId as Zt, ControllerQueryOptions as _, HookOperation as _n, Guard as _t, InferAdapterDoc as a, SlugExt as an, ResourceExtensions as at, ParsedQuery as b, HookSystem as bn, OperationFilter as bt, TypedController as c, BulkMixin as cn, AggMeasureShorthand as ct, PaginationResult as d, QueryResolverConfig as dn, AggregationDateRangeRequirement as dt, BaseController as en, RouteSchemaOptions as et, IntrospectionData as f, AccessControl as fn, AggregationIndexHint as ft, ArcInternalMetadata as g, HookHandler as gn, AggregationsMap as gt, ResourceMetadata as h, HookContext as hn, AggregationRateLimit as ht, ValidationResult as i, TreeMixin as in, ResourceHooks as it, ArcDecorator as j, ArcDeleteResult as jn, RouteMcpConfig as jt, IntrospectionPluginOptions as k, defineHook as kn, ActionsMap as kt, TypedRepository as l, BaseCrudController as ln, AggregationCacheConfig as lt, RegistryStats as m, DefineHookOptions as mn, AggregationMaterializedResult as mt, ConfigError as n, SoftDeleteMixin as nn, FieldRule$1 as nt, InferDocType as o, SlugMixin as on, EventDefinition as ot, RegistryEntry as p, AccessControlConfig as pn, AggregationMaterializedContext as pt, PresetFunction as q, AnyRecord as qt, ValidateOptions as r, TreeExt as rn, ResourceHookContext as rt, InferResourceDoc as s, BulkExt as sn, AggMeasureInput as st, RouteHandlerMethod$1 as t, SoftDeleteExt as tn, ArcFieldRule as tt, TypedResourceConfig as u, QueryResolver as un, AggregationConfig as ut, LookupOption as v, HookPhase as vn, Interceptor as vt, ServiceContext as w, afterUpdate as wn, Transform as wt, PopulateOption as x, HookSystemOptions as xn, PipelineConfig as xt, OwnershipCheck as y, HookRegistration as yn, NextFunction as yt, ResourceRegistry as z, BodySanitizer as zn, IRequestContext as zt };