@classytic/arc 2.8.1 → 2.8.4

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 (107) hide show
  1. package/README.md +22 -1
  2. package/dist/{ResourceRegistry-Dtcojmu8.mjs → ResourceRegistry-Dq3_zBQP.mjs} +5 -5
  3. package/dist/adapters/index.d.mts +2 -2
  4. package/dist/audit/index.d.mts +1 -1
  5. package/dist/audit/index.mjs +1 -1
  6. package/dist/audit/mongodb.d.mts +1 -1
  7. package/dist/audit/mongodb.mjs +1 -1
  8. package/dist/auth/index.d.mts +4 -4
  9. package/dist/auth/redis-session.d.mts +1 -1
  10. package/dist/cache/index.d.mts +2 -2
  11. package/dist/cli/commands/describe.mjs +1 -1
  12. package/dist/cli/commands/docs.mjs +2 -2
  13. package/dist/cli/commands/generate.mjs +1 -1
  14. package/dist/cli/commands/init.mjs +10 -10
  15. package/dist/cli/commands/introspect.mjs +3 -3
  16. package/dist/core/index.d.mts +3 -3
  17. package/dist/core/index.mjs +4 -4
  18. package/dist/{core-CrLDuqoT.mjs → core-DKSwNSXf.mjs} +1 -1
  19. package/dist/{createApp-p2OThysU.mjs → createApp-BOYjBgdI.mjs} +16 -7
  20. package/dist/{defineResource-CqeUltrW.mjs → defineResource-Bb_Bdhtw.mjs} +42 -27
  21. package/dist/docs/index.d.mts +2 -2
  22. package/dist/docs/index.mjs +1 -1
  23. package/dist/dynamic/index.d.mts +2 -2
  24. package/dist/dynamic/index.mjs +1 -1
  25. package/dist/{errorHandler-DJ7OAB2V.d.mts → errorHandler-CdZDavNH.d.mts} +2 -2
  26. package/dist/{eventPlugin-Cdjwo0Gv.d.mts → eventPlugin-CVxlE6De.d.mts} +1 -1
  27. package/dist/events/index.d.mts +3 -3
  28. package/dist/events/index.mjs +1 -1
  29. package/dist/events/transports/redis-stream-entry.d.mts +1 -1
  30. package/dist/events/transports/redis-stream-entry.mjs +3 -1
  31. package/dist/events/transports/redis.d.mts +1 -1
  32. package/dist/factory/index.d.mts +1 -1
  33. package/dist/factory/index.mjs +2 -152
  34. package/dist/hooks/index.d.mts +1 -1
  35. package/dist/idempotency/index.d.mts +3 -3
  36. package/dist/idempotency/mongodb.d.mts +1 -1
  37. package/dist/idempotency/mongodb.mjs +18 -6
  38. package/dist/idempotency/redis.d.mts +1 -1
  39. package/dist/idempotency/redis.mjs +10 -1
  40. package/dist/{index-0zj73o2U.d.mts → index-BgmMdpm8.d.mts} +1 -1
  41. package/dist/{index-CBru2y5Y.d.mts → index-CSkeivBx.d.mts} +3 -3
  42. package/dist/{index-DadoLP51.d.mts → index-CpTSDqmD.d.mts} +26 -4
  43. package/dist/index.d.mts +7 -7
  44. package/dist/index.mjs +3 -3
  45. package/dist/integrations/event-gateway.d.mts +1 -1
  46. package/dist/integrations/event-gateway.mjs +1 -1
  47. package/dist/integrations/index.d.mts +1 -1
  48. package/dist/integrations/mcp/index.d.mts +51 -3
  49. package/dist/integrations/mcp/index.mjs +78 -19
  50. package/dist/integrations/mcp/testing.d.mts +1 -1
  51. package/dist/integrations/mcp/testing.mjs +1 -1
  52. package/dist/{interface-CS6d7HiB.d.mts → interface-BVuMfeVv.d.mts} +47 -18
  53. package/dist/loadResources-Bksk8ydA.mjs +154 -0
  54. package/dist/{mongodb-B1eVtFhw.d.mts → mongodb-B8U2xaLj.d.mts} +1 -1
  55. package/dist/{mongodb-NShVZDMr.d.mts → mongodb-X7LbEjTN.d.mts} +10 -1
  56. package/dist/{openapi-q6rNKfZy.mjs → openapi-CYCuekCn.mjs} +2 -2
  57. package/dist/org/index.d.mts +2 -2
  58. package/dist/permissions/index.d.mts +3 -3
  59. package/dist/plugins/index.d.mts +5 -5
  60. package/dist/plugins/index.mjs +7 -7
  61. package/dist/plugins/tracing-entry.d.mts +1 -1
  62. package/dist/plugins/tracing-entry.mjs +1 -1
  63. package/dist/policies/index.d.mts +1 -1
  64. package/dist/presets/index.d.mts +1 -1
  65. package/dist/presets/index.mjs +1 -1
  66. package/dist/presets/multiTenant.d.mts +1 -1
  67. package/dist/{presets-BFrGvvjL.mjs → presets-C2xgzW6x.mjs} +10 -18
  68. package/dist/{queryCachePlugin-BCFVXnxK.d.mts → queryCachePlugin-CnTZZTC5.d.mts} +1 -1
  69. package/dist/{redis-stream-BgrYzpeq.d.mts → redis-stream-D54N5oXs.d.mts} +1 -1
  70. package/dist/{redis-Bunu3qWg.d.mts → redis-z3sFr1UP.d.mts} +1 -1
  71. package/dist/registry/index.d.mts +1 -1
  72. package/dist/registry/index.mjs +1 -1
  73. package/dist/{resourceToTools-DNNWnZtx.mjs → resourceToTools-O_HwWXFa.mjs} +1 -1
  74. package/dist/rpc/index.d.mts +1 -1
  75. package/dist/scope/index.d.mts +2 -2
  76. package/dist/testing/index.d.mts +2 -2
  77. package/dist/testing/index.mjs +1 -1
  78. package/dist/types/index.d.mts +4 -4
  79. package/dist/{types-BlOuKTPw.d.mts → types-Bg2X42_m.d.mts} +30 -9
  80. package/dist/{types-BoaZHr-2.d.mts → types-CVC4HOKi.d.mts} +1 -1
  81. package/dist/{types-D3b7hA00.d.mts → types-CcG4avic.d.mts} +1 -1
  82. package/dist/utils/index.d.mts +43 -5
  83. package/dist/utils/index.mjs +3 -3
  84. package/dist/{utils-7sJ8X83I.mjs → utils-yYT3HDXt.mjs} +65 -1
  85. package/package.json +8 -8
  86. package/skills/arc/SKILL.md +101 -6
  87. package/skills/arc/references/mcp.md +37 -0
  88. /package/dist/{EventTransport-CLXJUzyT.d.mts → EventTransport-CinyO7zQ.d.mts} +0 -0
  89. /package/dist/{caching-CHH-iHs3.mjs → caching-CjybdRwx.mjs} +0 -0
  90. /package/dist/{circuitBreaker-BGVoB1hD.d.mts → circuitBreaker-CvXkjfrW.d.mts} +0 -0
  91. /package/dist/{elevation-UJO3-NvX.d.mts → elevation-s5ykdNHr.d.mts} +0 -0
  92. /package/dist/{errorHandler-Cw34h_om.mjs → errorHandler-mzqk4cGl.mjs} +0 -0
  93. /package/dist/{errors-BI8kEKsO.d.mts → errors-Bmn3eZT6.d.mts} +0 -0
  94. /package/dist/{eventPlugin-XijlQmlL.mjs → eventPlugin-D91S2YF4.mjs} +0 -0
  95. /package/dist/{externalPaths-BQ8QijNH.d.mts → externalPaths-Bapitwvd.d.mts} +0 -0
  96. /package/dist/{fields-DoeDgh2b.d.mts → fields-DC4So2M2.d.mts} +0 -0
  97. /package/dist/{interface-CkkWm5uR.d.mts → interface-B-pe8fhj.d.mts} +0 -0
  98. /package/dist/{interface-bpoLKKqx.d.mts → interface-DplgQO2e.d.mts} +0 -0
  99. /package/dist/{metrics-DuhiSEZI.mjs → metrics-TuOmguhi.mjs} +0 -0
  100. /package/dist/{mongodb-5Ff3w8jy.mjs → mongodb-B5O6xaW1.mjs} +0 -0
  101. /package/dist/{pluralize-BneOJkpi.mjs → pluralize-A0tWEl1K.mjs} +0 -0
  102. /package/dist/{replyHelpers-CXtJDAZ0.mjs → replyHelpers-BLojtuvR.mjs} +0 -0
  103. /package/dist/{sessionManager-BkzVU8h2.d.mts → sessionManager-D-oNWHz3.d.mts} +0 -0
  104. /package/dist/{sse-CD5Hghpu.mjs → sse-CJpt7LGI.mjs} +0 -0
  105. /package/dist/{tracing-xqXzWeaf.d.mts → tracing-DxjKk7eW.d.mts} +0 -0
  106. /package/dist/{types-CN6JvmYz.d.mts → types-C72d3NDn.d.mts} +0 -0
  107. /package/dist/{versioning-CPU_5Xfs.mjs → versioning-Cm8qoFDg.mjs} +0 -0
@@ -1,23 +1,6 @@
1
- import { n as fieldRulesToZod, r as createMcpServer, t as resourceToTools } from "../../resourceToTools-DNNWnZtx.mjs";
1
+ import { n as fieldRulesToZod, r as createMcpServer, t as resourceToTools } from "../../resourceToTools-O_HwWXFa.mjs";
2
2
  import { createHash } from "node:crypto";
3
3
  import fp from "fastify-plugin";
4
- //#region src/integrations/mcp/definePrompt.ts
5
- /**
6
- * Define a type-safe MCP prompt.
7
- *
8
- * @param name - Prompt name (snake_case recommended)
9
- * @param config - Description, args schema, handler
10
- */
11
- function definePrompt(name, config) {
12
- return {
13
- name,
14
- description: config.description,
15
- title: config.title,
16
- argsSchema: config.args,
17
- handler: config.handler
18
- };
19
- }
20
- //#endregion
21
4
  //#region src/integrations/mcp/defineTool.ts
22
5
  /**
23
6
  * Define a type-safe MCP tool.
@@ -127,6 +110,82 @@ function customGuard(check, errorMessage) {
127
110
  };
128
111
  }
129
112
  //#endregion
113
+ //#region src/integrations/mcp/aiSdkBridge.ts
114
+ /** Serialize an AI SDK tool result into MCP's text-content envelope. */
115
+ function toMcpEnvelope(result) {
116
+ if (result && typeof result === "object" && "error" in result) {
117
+ const msg = result.error;
118
+ return {
119
+ content: [{
120
+ type: "text",
121
+ text: typeof msg === "string" ? msg : JSON.stringify(msg)
122
+ }],
123
+ isError: true
124
+ };
125
+ }
126
+ return { content: [{
127
+ type: "text",
128
+ text: typeof result === "string" ? result : JSON.stringify(result, null, 2)
129
+ }] };
130
+ }
131
+ /** Convert a McpBridge into a registered MCP tool. */
132
+ function bridgeToMcp(bridge) {
133
+ return defineTool(bridge.name, {
134
+ description: bridge.description,
135
+ input: bridge.inputSchema,
136
+ annotations: bridge.annotations,
137
+ handler: async (input, ctx) => {
138
+ if (!isAuthenticated(ctx)) return denied("Authentication required");
139
+ if (bridge.guard) {
140
+ const reason = bridge.guard(ctx);
141
+ if (reason) return denied(reason);
142
+ }
143
+ try {
144
+ return toMcpEnvelope(await bridge.buildTool(ctx).execute(input));
145
+ } catch (err) {
146
+ return denied(err instanceof Error ? err.message : String(err));
147
+ }
148
+ }
149
+ });
150
+ }
151
+ /**
152
+ * Take a list of McpBridge objects and produce a ready-to-register MCP tool
153
+ * array, with optional include/exclude filtering for per-environment config.
154
+ *
155
+ * @example
156
+ * ```typescript
157
+ * // All bridges
158
+ * extraTools: [...buildMcpToolsFromBridges(allBridges)]
159
+ *
160
+ * // Read-only deployment — hide destructive tools
161
+ * extraTools: [...buildMcpToolsFromBridges(allBridges, { exclude: ['trigger_job'] })]
162
+ * ```
163
+ */
164
+ function buildMcpToolsFromBridges(bridges, options = {}) {
165
+ return bridges.filter((bridge) => {
166
+ if (options.include) return options.include.includes(bridge.name);
167
+ if (options.exclude) return !options.exclude.includes(bridge.name);
168
+ return true;
169
+ }).map(bridgeToMcp);
170
+ }
171
+ //#endregion
172
+ //#region src/integrations/mcp/definePrompt.ts
173
+ /**
174
+ * Define a type-safe MCP prompt.
175
+ *
176
+ * @param name - Prompt name (snake_case recommended)
177
+ * @param config - Description, args schema, handler
178
+ */
179
+ function definePrompt(name, config) {
180
+ return {
181
+ name,
182
+ description: config.description,
183
+ title: config.title,
184
+ argsSchema: config.args,
185
+ handler: config.handler
186
+ };
187
+ }
188
+ //#endregion
130
189
  //#region src/integrations/mcp/authBridge.ts
131
190
  /**
132
191
  * @classytic/arc — MCP Auth Bridge
@@ -572,4 +631,4 @@ const mcpPlugin = fp(mcpPluginImpl, {
572
631
  fastify: "5.x"
573
632
  });
574
633
  //#endregion
575
- export { createMcpServer, customGuard, definePrompt, defineTool, denied, fieldRulesToZod, getOrgId, getUserId, guard, hasOrg, isAuthenticated, isOrg, mcpPlugin, requireAuth, requireOrg, requireOrgId, requireRole, resourceToTools };
634
+ export { bridgeToMcp, buildMcpToolsFromBridges, createMcpServer, customGuard, definePrompt, defineTool, denied, fieldRulesToZod, getOrgId, getUserId, guard, hasOrg, isAuthenticated, isOrg, mcpPlugin, requireAuth, requireOrg, requireOrgId, requireRole, resourceToTools };
@@ -1,4 +1,4 @@
1
- import { o as McpAuthResult, s as McpPluginOptions } from "../../types-D3b7hA00.mjs";
1
+ import { o as McpAuthResult, s as McpPluginOptions } from "../../types-CcG4avic.mjs";
2
2
 
3
3
  //#region src/integrations/mcp/testing.d.ts
4
4
  interface TestMcpClientOptions {
@@ -1,4 +1,4 @@
1
- import { r as createMcpServer, t as resourceToTools } from "../../resourceToTools-DNNWnZtx.mjs";
1
+ import { r as createMcpServer, t as resourceToTools } from "../../resourceToTools-O_HwWXFa.mjs";
2
2
  //#region src/integrations/mcp/testing.ts
3
3
  /**
4
4
  * @classytic/arc/mcp/testing — MCP Test Utilities
@@ -1,6 +1,6 @@
1
- import { r as RequestScope } from "./types-CN6JvmYz.mjs";
2
- import { n as FieldPermissionMap } from "./fields-DoeDgh2b.mjs";
3
- import { i as UserBase, t as PermissionCheck } from "./types-BoaZHr-2.mjs";
1
+ import { r as RequestScope } from "./types-C72d3NDn.mjs";
2
+ import { n as FieldPermissionMap } from "./fields-DC4So2M2.mjs";
3
+ import { i as UserBase, t as PermissionCheck } from "./types-CVC4HOKi.mjs";
4
4
  import { FastifyInstance, FastifyPluginAsync, FastifyReply, FastifyRequest, RouteHandlerMethod, RouteHandlerMethod as RouteHandlerMethod$1 } from "fastify";
5
5
 
6
6
  //#region src/hooks/HookSystem.d.ts
@@ -839,6 +839,7 @@ declare class ResourceDefinition<TDoc = AnyRecord> {
839
839
  */
840
840
  readonly routes?: readonly RouteDefinition[];
841
841
  readonly middlewares: MiddlewareConfig;
842
+ readonly routeGuards?: RouteHandlerMethod$1[];
842
843
  readonly disableDefaultRoutes: boolean;
843
844
  readonly disabledRoutes: CrudRouteKey[];
844
845
  readonly actions?: ActionsMap;
@@ -956,7 +957,7 @@ declare class ResourceRegistry {
956
957
  /**
957
958
  * Minimal server accessor — exposes safe, read-only server decorators.
958
959
  * Allows controller handlers to publish events, log, and audit
959
- * without switching to `wrapHandler: false`.
960
+ * without switching to `raw: true`.
960
961
  */
961
962
  interface ServerAccessor {
962
963
  /** Event bus — publish domain events from any handler */
@@ -1069,7 +1070,7 @@ interface IRequestContext<TBody = unknown, TParams extends Record<string, string
1069
1070
  metadata?: TMetadata;
1070
1071
  /**
1071
1072
  * Fastify server accessor — publish events, log, and audit
1072
- * from any handler without switching to `wrapHandler: false`.
1073
+ * from any handler without switching to `raw: true`.
1073
1074
  *
1074
1075
  * @example
1075
1076
  * ```typescript
@@ -1105,7 +1106,7 @@ interface IControllerResponse<T = unknown> {
1105
1106
  * Controller handler — Arc's standard pattern.
1106
1107
  *
1107
1108
  * Receives a request context object, returns IControllerResponse.
1108
- * Use with `wrapHandler: true` in additionalRoutes.
1109
+ * Use with `raw: false` in routes.
1109
1110
  *
1110
1111
  * **Generic parameters:**
1111
1112
  * - `TResponse` — shape of `IControllerResponse.data` (default: `unknown`)
@@ -1137,12 +1138,12 @@ interface IControllerResponse<T = unknown> {
1137
1138
  * return { success: true, data: product };
1138
1139
  * };
1139
1140
  *
1140
- * additionalRoutes: [{
1141
+ * routes: [{
1141
1142
  * method: 'POST',
1142
1143
  * path: '/products',
1143
1144
  * handler: createProduct,
1144
1145
  * permissions: requireAuth(),
1145
- * wrapHandler: true, // Arc wraps this into Fastify handler
1146
+ * raw: false, // Arc wraps this into Fastify handler
1146
1147
  * }]
1147
1148
  * ```
1148
1149
  */
@@ -1151,7 +1152,7 @@ type ControllerHandler<TResponse = unknown, TBody = unknown, TParams extends Rec
1151
1152
  * Fastify native handler
1152
1153
  *
1153
1154
  * Standard Fastify request/reply pattern.
1154
- * Use with `wrapHandler: false` in additionalRoutes.
1155
+ * Use with `raw: true` in routes.
1155
1156
  *
1156
1157
  * @example
1157
1158
  * ```typescript
@@ -1161,12 +1162,12 @@ type ControllerHandler<TResponse = unknown, TBody = unknown, TParams extends Rec
1161
1162
  * return reply.send(file.buffer);
1162
1163
  * };
1163
1164
  *
1164
- * additionalRoutes: [{
1165
+ * routes: [{
1165
1166
  * method: 'GET',
1166
1167
  * path: '/files/:id/download',
1167
1168
  * handler: downloadFile,
1168
1169
  * permissions: requireAuth(),
1169
- * wrapHandler: false, // Use as-is, no wrapping
1170
+ * raw: true, // Use as-is, no wrapping
1170
1171
  * }]
1171
1172
  * ```
1172
1173
  */
@@ -1596,7 +1597,7 @@ declare module 'fastify' {
1596
1597
  /**
1597
1598
  * Typed Fastify request with Arc decorations.
1598
1599
  *
1599
- * Use this in `wrapHandler: false` handlers instead of `(req as any).user`.
1600
+ * Use this in `raw: true` handlers instead of `(req as any).user`.
1600
1601
  *
1601
1602
  * @example
1602
1603
  * ```typescript
@@ -2027,11 +2028,26 @@ interface ResourceConfig<TDoc = AnyRecord> {
2027
2028
  */
2028
2029
  fields?: FieldPermissionMap;
2029
2030
  middlewares?: MiddlewareConfig;
2030
- /** @deprecated Use `routes` instead. Will error in v3. */
2031
- additionalRoutes?: AdditionalRoute[];
2032
2031
  /**
2033
- * Custom routes the v2.8 way to add endpoints beyond CRUD.
2034
- * Replaces `additionalRoutes` with cleaner naming and no `wrapHandler` boolean.
2032
+ * PreHandler guards auto-applied to **every** route on this resource
2033
+ * (CRUD + custom `routes` + preset routes). Runs after auth/permissions,
2034
+ * before per-route `preHandler`. Use for mode gates, tenant checks,
2035
+ * feature flags — anything that applies to every endpoint.
2036
+ *
2037
+ * @example
2038
+ * ```typescript
2039
+ * defineResource({
2040
+ * routeGuards: [requireFlowMode('standard')],
2041
+ * routes: [
2042
+ * { method: 'GET', path: '/', raw: true, handler: listHandler },
2043
+ * // guard runs automatically — no per-route boilerplate
2044
+ * ],
2045
+ * });
2046
+ * ```
2047
+ */
2048
+ routeGuards?: RouteHandlerMethod[];
2049
+ /**
2050
+ * Custom routes beyond CRUD. Presets also merge their routes here.
2035
2051
  *
2036
2052
  * @example
2037
2053
  * ```typescript
@@ -2697,7 +2713,8 @@ interface PresetHook {
2697
2713
  }
2698
2714
  interface PresetResult {
2699
2715
  name: string;
2700
- additionalRoutes?: AdditionalRoute[] | ((permissions: ResourcePermissions) => AdditionalRoute[]);
2716
+ /** Preset routes merged into the resource's `routes` array. */
2717
+ routes?: RouteDefinition[] | ((permissions: ResourcePermissions) => RouteDefinition[]);
2701
2718
  middlewares?: MiddlewareConfig;
2702
2719
  schemaOptions?: RouteSchemaOptions;
2703
2720
  controllerOptions?: Record<string, unknown>;
@@ -2892,6 +2909,8 @@ interface CrudRouterOptions {
2892
2909
  * Set to `false` to disable rate limiting for this resource.
2893
2910
  */
2894
2911
  rateLimit?: RateLimitConfig | false;
2912
+ /** PreHandler guards applied to every route (CRUD + custom + preset). */
2913
+ routeGuards?: RouteHandlerMethod[];
2895
2914
  }
2896
2915
  interface ResourceMetadata {
2897
2916
  name: string;
@@ -2901,7 +2920,17 @@ interface ResourceMetadata {
2901
2920
  module?: string;
2902
2921
  permissions?: ResourcePermissions;
2903
2922
  presets: string[];
2904
- additionalRoutes?: AdditionalRoute[];
2923
+ customRoutes?: Array<{
2924
+ method: string;
2925
+ path: string;
2926
+ handler: string;
2927
+ operation?: string;
2928
+ summary?: string;
2929
+ description?: string;
2930
+ permissions?: PermissionCheck;
2931
+ raw?: boolean;
2932
+ schema?: Record<string, unknown>;
2933
+ }>;
2905
2934
  routes: Array<{
2906
2935
  method: string;
2907
2936
  path: string;
@@ -0,0 +1,154 @@
1
+ import { t as __exportAll } from "./chunk-BpYLSNr0.mjs";
2
+ import { readdir } from "node:fs/promises";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ //#region src/factory/loadResources.ts
6
+ /**
7
+ * loadResources — Auto-discover resource files from a directory.
8
+ *
9
+ * Scans for `*.resource.{ts,js,mts,mjs}` files, imports each,
10
+ * and collects their default exports. No barrel file needed.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { createApp, loadResources } from '@classytic/arc/factory';
15
+ *
16
+ * // Recommended: import.meta.url — works in both src/ (dev) and dist/ (prod)
17
+ * const app = await createApp({
18
+ * resources: await loadResources(import.meta.url),
19
+ * auth: { type: 'jwt', jwt: { secret: process.env.JWT_SECRET } },
20
+ * });
21
+ *
22
+ * // Or explicit path (must match runtime layout)
23
+ * const app2 = await createApp({
24
+ * resources: await loadResources('./src/resources'),
25
+ * });
26
+ * ```
27
+ *
28
+ * File convention:
29
+ * ```
30
+ * src/resources/
31
+ * product/product.resource.ts → export default defineResource({ name: 'product', ... })
32
+ * order/order.resource.ts → export default defineResource({ name: 'order', ... })
33
+ * ```
34
+ */
35
+ var loadResources_exports = /* @__PURE__ */ __exportAll({ loadResources: () => loadResources });
36
+ /**
37
+ * Scan a directory for resource files and import their default exports.
38
+ *
39
+ * Accepts a directory path OR `import.meta.url` (file:// URL).
40
+ * When given a URL, resolves to the directory containing that file —
41
+ * so `loadResources(import.meta.url)` works in both dev (`src/`) and
42
+ * production (`dist/`) without path gymnastics.
43
+ *
44
+ * @param dir - Directory path, or `import.meta.url` (file:// URL resolved to its dirname)
45
+ * @param options - Pattern and recursion options
46
+ * @returns Array of resource definitions (anything with `.toPlugin()`)
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * // Works from both src/ and dist/ — resolves relative to the calling file
51
+ * await loadResources(import.meta.url);
52
+ *
53
+ * // Subdirectory relative to the calling file
54
+ * await loadResources(import.meta.url, { suffix: '.resource' });
55
+ *
56
+ * // Explicit path (must match runtime layout)
57
+ * await loadResources('./src/resources');
58
+ * ```
59
+ */
60
+ async function loadResources(dir, options = {}) {
61
+ const { suffix = ".resource", recursive = true, exclude, include, silent = false } = options;
62
+ const files = await collectFiles(resolve(dir.startsWith("file://") ? dirname(fileURLToPath(dir)) : dir), new RegExp(`${escapeRegex(suffix)}\\.(ts|js|mts|mjs)$`), recursive);
63
+ files.sort();
64
+ const includeSet = include ? new Set(include) : null;
65
+ const excludeSet = exclude ? new Set(exclude) : null;
66
+ const skipped = [];
67
+ const failed = [];
68
+ const isWindowsPath = (p) => /^[a-z]:[\\/]/i.test(p);
69
+ const results = await Promise.all(files.map(async (file) => {
70
+ let mod;
71
+ let primaryError;
72
+ try {
73
+ mod = await import(pathToFileURL(file).href);
74
+ return {
75
+ file,
76
+ mod
77
+ };
78
+ } catch (err) {
79
+ primaryError = err;
80
+ }
81
+ if (!isWindowsPath(file)) try {
82
+ mod = await import(file);
83
+ return {
84
+ file,
85
+ mod
86
+ };
87
+ } catch {}
88
+ const err = primaryError;
89
+ const code = err.code;
90
+ const msg = err instanceof Error ? err.message : String(err);
91
+ if (code === "ERR_MODULE_NOT_FOUND" && msg.includes(".js")) failed.push(`${file}: ${msg}\n Hint: This file uses .js extension imports (TypeScript ESM convention).
92
+ • Production: ensure your build compiles .ts→.js before loadResources() runs.
93
+ • Node.js: use tsx, ts-node/esm, or a build step.
94
+ • Vitest: nested .js→.ts resolution may fail through dynamic imports.
95
+ Workaround: use import.meta.glob to preload resources statically.
96
+ See: https://github.com/classytic/arc/blob/main/docs/production-ops/factory.mdx#vitest-limitation`);
97
+ else failed.push(`${file}: ${msg}`);
98
+ return null;
99
+ }));
100
+ const resources = [];
101
+ for (const result of results) {
102
+ if (!result) continue;
103
+ let resource = result.mod.default ?? result.mod.resource;
104
+ if (!resource || typeof resource.toPlugin !== "function") {
105
+ for (const value of Object.values(result.mod)) if (value && typeof value === "object" && typeof value.toPlugin === "function") {
106
+ resource = value;
107
+ break;
108
+ }
109
+ }
110
+ if (!resource || typeof resource.toPlugin !== "function") {
111
+ skipped.push(result.file);
112
+ continue;
113
+ }
114
+ const name = resource.name;
115
+ if (name) {
116
+ if (includeSet && !includeSet.has(name)) continue;
117
+ if (!includeSet && excludeSet?.has(name)) continue;
118
+ }
119
+ resources.push(resource);
120
+ }
121
+ const log = silent ? void 0 : options?.logger;
122
+ if (log) {
123
+ if (failed.length) {
124
+ log.warn(`[arc] loadResources: ${failed.length} file(s) failed to import:`);
125
+ for (const f of failed) log.warn(` - ${f}`);
126
+ }
127
+ if (skipped.length) {
128
+ log.warn(`[arc] loadResources: ${skipped.length} file(s) skipped (no default export with toPlugin):`);
129
+ for (const f of skipped) log.warn(` - ${f}`);
130
+ }
131
+ }
132
+ return resources;
133
+ }
134
+ async function collectFiles(dir, pattern, recursive) {
135
+ const results = [];
136
+ let entries;
137
+ try {
138
+ entries = await readdir(dir, { withFileTypes: true });
139
+ } catch {
140
+ return results;
141
+ }
142
+ for (const entry of entries) {
143
+ const name = String(entry.name);
144
+ const fullPath = join(dir, name);
145
+ if (entry.isDirectory() && recursive) results.push(...await collectFiles(fullPath, pattern, recursive));
146
+ else if (entry.isFile() && pattern.test(name)) results.push(fullPath);
147
+ }
148
+ return results;
149
+ }
150
+ function escapeRegex(str) {
151
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
152
+ }
153
+ //#endregion
154
+ export { loadResources_exports as n, loadResources as t };
@@ -1,4 +1,4 @@
1
- import { i as UserBase } from "./types-BoaZHr-2.mjs";
1
+ import { i as UserBase } from "./types-CVC4HOKi.mjs";
2
2
 
3
3
  //#region src/audit/stores/interface.d.ts
4
4
  type AuditAction = "create" | "update" | "delete" | "restore" | "custom";
@@ -1,4 +1,4 @@
1
- import { n as IdempotencyResult, r as IdempotencyStore } from "./interface-CkkWm5uR.mjs";
1
+ import { n as IdempotencyResult, r as IdempotencyStore } from "./interface-B-pe8fhj.mjs";
2
2
 
3
3
  //#region src/idempotency/stores/mongodb.d.ts
4
4
  interface MongoConnection {
@@ -15,6 +15,7 @@ interface MongoCollection {
15
15
  acknowledged: boolean;
16
16
  matchedCount: number;
17
17
  modifiedCount: number;
18
+ upsertedCount?: number;
18
19
  }>;
19
20
  deleteOne(filter: object): Promise<{
20
21
  deletedCount: number;
@@ -38,6 +39,10 @@ interface IdempotencyDocument {
38
39
  createdAt: Date;
39
40
  expiresAt: Date;
40
41
  }
42
+ /** Minimal logger interface — compatible with console, pino, fastify.log */
43
+ interface IdempotencyLogger {
44
+ warn(message: string, ...args: unknown[]): void;
45
+ }
41
46
  interface MongoIdempotencyStoreOptions {
42
47
  /** Mongoose connection or MongoDB connection object */
43
48
  connection: MongoConnection;
@@ -47,6 +52,8 @@ interface MongoIdempotencyStoreOptions {
47
52
  createIndex?: boolean;
48
53
  /** Default TTL in ms (default: 86400000 = 24 hours) */
49
54
  ttlMs?: number;
55
+ /** Logger for operational warnings (default: console) */
56
+ logger?: IdempotencyLogger;
50
57
  }
51
58
  declare class MongoIdempotencyStore implements IdempotencyStore {
52
59
  readonly name = "mongodb";
@@ -54,6 +61,8 @@ declare class MongoIdempotencyStore implements IdempotencyStore {
54
61
  private collectionName;
55
62
  private ttlMs;
56
63
  private indexCreated;
64
+ private shouldEnsureIndex;
65
+ private logger;
57
66
  constructor(options: MongoIdempotencyStoreOptions);
58
67
  private get collection();
59
68
  private ensureIndex;
@@ -159,7 +159,7 @@ const DEFAULT_LIST_PARAMS = [
159
159
  function generateResourcePaths(resource, apiPrefix = "", additionalSecurity = []) {
160
160
  const paths = {};
161
161
  const basePath = `${apiPrefix}${resource.prefix}`;
162
- if (resource.disableDefaultRoutes && (!resource.additionalRoutes || resource.additionalRoutes.length === 0) && (!resource.actions || resource.actions.length === 0)) return paths;
162
+ if (resource.disableDefaultRoutes && (!resource.customRoutes || resource.customRoutes.length === 0) && (!resource.actions || resource.actions.length === 0)) return paths;
163
163
  if (!resource.disableDefaultRoutes) {
164
164
  const disabledSet = new Set(resource.disabledRoutes ?? []);
165
165
  const updateMethod = resource.updateMethod ?? "PATCH";
@@ -276,7 +276,7 @@ function generateResourcePaths(resource, apiPrefix = "", additionalSecurity = []
276
276
  }, void 0, additionalSecurity);
277
277
  if (Object.keys(itemPath).length > 0) paths[toOpenApiPath(`${basePath}/:id`)] = itemPath;
278
278
  }
279
- for (const route of resource.additionalRoutes || []) {
279
+ for (const route of resource.customRoutes || []) {
280
280
  const fullPath = toOpenApiPath(`${basePath}${route.path}`);
281
281
  const method = route.method.toLowerCase();
282
282
  if (!paths[fullPath]) paths[fullPath] = {};
@@ -1,5 +1,5 @@
1
- import { Wt as RouteHandler } from "../interface-CS6d7HiB.mjs";
2
- import { i as UserBase } from "../types-BoaZHr-2.mjs";
1
+ import { Wt as RouteHandler } from "../interface-BVuMfeVv.mjs";
2
+ import { i as UserBase } from "../types-CVC4HOKi.mjs";
3
3
  import { InvitationAdapter, InvitationDoc, MemberDoc, OrgAdapter, OrgDoc, OrgPermissionStatement, OrgRole, OrganizationPluginOptions } from "./types.mjs";
4
4
  import { FastifyPluginAsync, RouteHandlerMethod } from "fastify";
5
5
 
@@ -1,4 +1,4 @@
1
- import { a as applyFieldWritePermissions, i as applyFieldReadPermissions, n as FieldPermissionMap, o as fields, r as FieldPermissionType, s as resolveEffectiveRoles, t as FieldPermission } from "../fields-DoeDgh2b.mjs";
2
- import { a as getUserRoles, i as UserBase, n as PermissionContext, o as normalizeRoles, r as PermissionResult, t as PermissionCheck } from "../types-BoaZHr-2.mjs";
3
- import { A as RoleHierarchy, C as authenticated, D as publicRead, E as presets_d_exports, M as applyPermissionResult, N as normalizePermissionResult, O as publicReadAdminWrite, S as adminOnly, T as ownerWithAdminBypass, _ as requireScopeContext, a as allOf, b as roles, c as createDynamicPermissionMatrix, d as requireAuth, f as requireOrgInScope, g as requireRoles, h as requireOwnership, i as PermissionEventBus, j as createRoleHierarchy, k as readOnly, l as createOrgPermissions, m as requireOrgRole, n as DynamicPermissionMatrix, o as allowPublic, p as requireOrgMembership, r as DynamicPermissionMatrixConfig, s as anyOf, t as ConnectEventsOptions, u as denyAll, v as requireServiceScope, w as fullPublic, x as when, y as requireTeamMembership } from "../index-CBru2y5Y.mjs";
1
+ import { a as applyFieldWritePermissions, i as applyFieldReadPermissions, n as FieldPermissionMap, o as fields, r as FieldPermissionType, s as resolveEffectiveRoles, t as FieldPermission } from "../fields-DC4So2M2.mjs";
2
+ import { a as getUserRoles, i as UserBase, n as PermissionContext, o as normalizeRoles, r as PermissionResult, t as PermissionCheck } from "../types-CVC4HOKi.mjs";
3
+ import { A as RoleHierarchy, C as authenticated, D as publicRead, E as presets_d_exports, M as applyPermissionResult, N as normalizePermissionResult, O as publicReadAdminWrite, S as adminOnly, T as ownerWithAdminBypass, _ as requireScopeContext, a as allOf, b as roles, c as createDynamicPermissionMatrix, d as requireAuth, f as requireOrgInScope, g as requireRoles, h as requireOwnership, i as PermissionEventBus, j as createRoleHierarchy, k as readOnly, l as createOrgPermissions, m as requireOrgRole, n as DynamicPermissionMatrix, o as allowPublic, p as requireOrgMembership, r as DynamicPermissionMatrixConfig, s as anyOf, t as ConnectEventsOptions, u as denyAll, v as requireServiceScope, w as fullPublic, x as when, y as requireTeamMembership } from "../index-CSkeivBx.mjs";
4
4
  export { ConnectEventsOptions, DynamicPermissionMatrix, DynamicPermissionMatrixConfig, FieldPermission, FieldPermissionMap, FieldPermissionType, PermissionCheck, PermissionContext, PermissionEventBus, PermissionResult, RoleHierarchy, UserBase, adminOnly, allOf, allowPublic, anyOf, applyFieldReadPermissions, applyFieldWritePermissions, applyPermissionResult, authenticated, createDynamicPermissionMatrix, createOrgPermissions, createRoleHierarchy, denyAll, fields, fullPublic, getUserRoles, normalizePermissionResult, normalizeRoles, ownerWithAdminBypass, presets_d_exports as permissions, publicRead, publicReadAdminWrite, readOnly, requireAuth, requireOrgInScope, requireOrgMembership, requireOrgRole, requireOwnership, requireRoles, requireScopeContext, requireServiceScope, requireTeamMembership, resolveEffectiveRoles, roles, when };
@@ -1,7 +1,7 @@
1
- import { K as MiddlewareConfig, Kt as ResourceRegistry, Tn as HookSystem, et as PresetHook, m as AnyRecord, p as AdditionalRoute, vt as RouteSchemaOptions } from "../interface-CS6d7HiB.mjs";
2
- import { t as ExternalOpenApiPaths } from "../externalPaths-BQ8QijNH.mjs";
3
- import { _ as cachingPlugin, a as versioningPlugin, c as MetricsOptions, d as SSEOptions, f as _default$6, g as _default$1, h as CachingRule, i as _default$7, l as _default$4, m as CachingOptions, n as errorHandlerPlugin, o as MetricEntry, p as ssePlugin, r as VersioningOptions, s as MetricsCollector, t as ErrorHandlerOptions, u as metricsPlugin } from "../errorHandler-DJ7OAB2V.mjs";
4
- import { t as TracingOptions } from "../tracing-xqXzWeaf.mjs";
1
+ import { K as MiddlewareConfig, Kt as ResourceRegistry, Tn as HookSystem, et as PresetHook, m as AnyRecord, p as AdditionalRoute, vt as RouteSchemaOptions } from "../interface-BVuMfeVv.mjs";
2
+ import { t as ExternalOpenApiPaths } from "../externalPaths-Bapitwvd.mjs";
3
+ import { _ as _default$1, a as _default$7, c as MetricsCollector, d as metricsPlugin, f as SSEOptions, g as CachingRule, h as CachingOptions, i as VersioningOptions, l as MetricsOptions, m as ssePlugin, n as ErrorMapper, o as versioningPlugin, p as _default$6, r as errorHandlerPlugin, s as MetricEntry, t as ErrorHandlerOptions, u as _default$4, v as cachingPlugin } from "../errorHandler-CdZDavNH.mjs";
4
+ import { t as TracingOptions } from "../tracing-DxjKk7eW.mjs";
5
5
  import { FastifyInstance, FastifyPluginAsync } from "fastify";
6
6
  import * as _$node_stream0 from "node:stream";
7
7
 
@@ -213,4 +213,4 @@ declare module "fastify" {
213
213
  declare const requestIdPlugin: FastifyPluginAsync<RequestIdOptions>;
214
214
  declare const _default$5: FastifyPluginAsync<RequestIdOptions>;
215
215
  //#endregion
216
- export { type ArcCore, type ArcCorePluginOptions, type ArcPlugin, type CachingOptions, type CachingRule, type CreatePluginDefinition, type ErrorHandlerOptions, type GracefulShutdownOptions, type HealthCheck, type HealthOptions, type MetricEntry, type MetricsCollector, type MetricsOptions, type PluginMeta, type PluginResourceResult, type RequestIdOptions, type SSEOptions, type TracingOptions, type VersioningOptions, _default as arcCorePlugin, arcCorePlugin as arcCorePluginFn, _default$1 as cachingPlugin, cachingPlugin as cachingPluginFn, createPlugin, errorHandlerPlugin, errorHandlerPlugin as errorHandlerPluginFn, _default$2 as gracefulShutdownPlugin, gracefulShutdownPlugin as gracefulShutdownPluginFn, _default$3 as healthPlugin, healthPlugin as healthPluginFn, _default$4 as metricsPlugin, metricsPlugin as metricsPluginFn, replyHelpersPlugin, _default$5 as requestIdPlugin, requestIdPlugin as requestIdPluginFn, _default$6 as ssePlugin, ssePlugin as ssePluginFn, _default$7 as versioningPlugin, versioningPlugin as versioningPluginFn };
216
+ export { type ArcCore, type ArcCorePluginOptions, type ArcPlugin, type CachingOptions, type CachingRule, type CreatePluginDefinition, type ErrorHandlerOptions, type ErrorMapper, type GracefulShutdownOptions, type HealthCheck, type HealthOptions, type MetricEntry, type MetricsCollector, type MetricsOptions, type PluginMeta, type PluginResourceResult, type RequestIdOptions, type SSEOptions, type TracingOptions, type VersioningOptions, _default as arcCorePlugin, arcCorePlugin as arcCorePluginFn, _default$1 as cachingPlugin, cachingPlugin as cachingPluginFn, createPlugin, errorHandlerPlugin, errorHandlerPlugin as errorHandlerPluginFn, _default$2 as gracefulShutdownPlugin, gracefulShutdownPlugin as gracefulShutdownPluginFn, _default$3 as healthPlugin, healthPlugin as healthPluginFn, _default$4 as metricsPlugin, metricsPlugin as metricsPluginFn, replyHelpersPlugin, _default$5 as requestIdPlugin, requestIdPlugin as requestIdPluginFn, _default$6 as ssePlugin, ssePlugin as ssePluginFn, _default$7 as versioningPlugin, versioningPlugin as versioningPluginFn };
@@ -3,13 +3,13 @@ import { o as getOrgId } from "../types-AOD8fxIw.mjs";
3
3
  import { t as requestContext } from "../requestContext-DYvHl113.mjs";
4
4
  import { t as hasEvents } from "../typeGuards-CcFZXgU7.mjs";
5
5
  import { t as HookSystem } from "../HookSystem-BjFu7zf1.mjs";
6
- import { t as ResourceRegistry } from "../ResourceRegistry-Dtcojmu8.mjs";
7
- import { n as caching_default, t as cachingPlugin } from "../caching-CHH-iHs3.mjs";
8
- import { t as errorHandlerPlugin } from "../errorHandler-Cw34h_om.mjs";
9
- import { n as metrics_default, t as metricsPlugin } from "../metrics-DuhiSEZI.mjs";
10
- import { t as replyHelpersPlugin } from "../replyHelpers-CXtJDAZ0.mjs";
11
- import { n as sse_default, t as ssePlugin } from "../sse-CD5Hghpu.mjs";
12
- import { n as versioning_default, t as versioningPlugin } from "../versioning-CPU_5Xfs.mjs";
6
+ import { t as ResourceRegistry } from "../ResourceRegistry-Dq3_zBQP.mjs";
7
+ import { n as caching_default, t as cachingPlugin } from "../caching-CjybdRwx.mjs";
8
+ import { t as errorHandlerPlugin } from "../errorHandler-mzqk4cGl.mjs";
9
+ import { n as metrics_default, t as metricsPlugin } from "../metrics-TuOmguhi.mjs";
10
+ import { t as replyHelpersPlugin } from "../replyHelpers-BLojtuvR.mjs";
11
+ import { n as sse_default, t as ssePlugin } from "../sse-CJpt7LGI.mjs";
12
+ import { n as versioning_default, t as versioningPlugin } from "../versioning-Cm8qoFDg.mjs";
13
13
  import { randomUUID } from "node:crypto";
14
14
  import fp from "fastify-plugin";
15
15
  //#region src/core/arcCorePlugin.ts
@@ -1,2 +1,2 @@
1
- import { a as traced, i as isTracingAvailable, n as _default, r as createSpan, t as TracingOptions } from "../tracing-xqXzWeaf.mjs";
1
+ import { a as traced, i as isTracingAvailable, n as _default, r as createSpan, t as TracingOptions } from "../tracing-DxjKk7eW.mjs";
2
2
  export { type TracingOptions, createSpan, isTracingAvailable, traced, _default as tracingPlugin };
@@ -44,7 +44,7 @@ try {
44
44
  function createTracerProvider(options) {
45
45
  if (!isAvailable) return null;
46
46
  const { serviceName = "@classytic/arc", serviceVersion, exporterUrl = "http://localhost:4318/v1/traces" } = options;
47
- const resolvedVersion = serviceVersion ?? "2.8.1";
47
+ const resolvedVersion = serviceVersion ?? "2.8.4";
48
48
  const exporter = new OTLPTraceExporter({ url: exporterUrl });
49
49
  const provider = new NodeTracerProvider({ resource: { attributes: {
50
50
  "service.name": serviceName,
@@ -1,4 +1,4 @@
1
- import { t as PermissionCheck } from "../types-BoaZHr-2.mjs";
1
+ import { t as PermissionCheck } from "../types-CVC4HOKi.mjs";
2
2
  import { FastifyReply, FastifyRequest } from "fastify";
3
3
 
4
4
  //#region src/policies/PolicyInterface.d.ts
@@ -1,4 +1,4 @@
1
- import { Ht as IControllerResponse, Ut as IRequestContext, m as AnyRecord, on as PaginationResult, tt as PresetResult, ut as ResourceConfig } from "../interface-CS6d7HiB.mjs";
1
+ import { Ht as IControllerResponse, Ut as IRequestContext, m as AnyRecord, on as PaginationResult, tt as PresetResult, ut as ResourceConfig } from "../interface-BVuMfeVv.mjs";
2
2
  import { MultiTenantOptions, TenantFieldSpec, multiTenantPreset } from "./multiTenant.mjs";
3
3
 
4
4
  //#region src/presets/ownedByUser.d.ts
@@ -1,3 +1,3 @@
1
1
  import { multiTenantPreset } from "./multiTenant.mjs";
2
- import { a as registerPreset, c as auditedPreset, d as ownedByUserPreset, i as getPreset, l as softDeletePreset, n as flexibleMultiTenantPreset, o as treePreset, r as getAvailablePresets, s as bulkPreset, t as applyPresets, u as slugLookupPreset } from "../presets-BFrGvvjL.mjs";
2
+ import { a as registerPreset, c as auditedPreset, d as ownedByUserPreset, i as getPreset, l as softDeletePreset, n as flexibleMultiTenantPreset, o as treePreset, r as getAvailablePresets, s as bulkPreset, t as applyPresets, u as slugLookupPreset } from "../presets-C2xgzW6x.mjs";
3
3
  export { applyPresets, auditedPreset, bulkPreset, flexibleMultiTenantPreset, getAvailablePresets, getPreset, multiTenantPreset, ownedByUserPreset, registerPreset, slugLookupPreset, softDeletePreset, treePreset };
@@ -1,4 +1,4 @@
1
- import { E as CrudRouteKey, tt as PresetResult } from "../interface-CS6d7HiB.mjs";
1
+ import { E as CrudRouteKey, tt as PresetResult } from "../interface-BVuMfeVv.mjs";
2
2
 
3
3
  //#region src/presets/multiTenant.d.ts
4
4
  /**