@classytic/arc 1.0.8 → 2.1.2

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 (322) hide show
  1. package/README.md +247 -794
  2. package/bin/arc.js +91 -52
  3. package/dist/EventTransport-BD2U0BTc.d.mts +100 -0
  4. package/dist/EventTransport-BD2U0BTc.d.mts.map +1 -0
  5. package/dist/HookSystem-BsGV-j2l.mjs +405 -0
  6. package/dist/HookSystem-BsGV-j2l.mjs.map +1 -0
  7. package/dist/ResourceRegistry-DsN4KJjV.mjs +250 -0
  8. package/dist/ResourceRegistry-DsN4KJjV.mjs.map +1 -0
  9. package/dist/adapters/index.d.mts +5 -0
  10. package/dist/adapters/index.mjs +3 -0
  11. package/dist/audit/index.d.mts +82 -0
  12. package/dist/audit/index.d.mts.map +1 -0
  13. package/dist/audit/index.mjs +276 -0
  14. package/dist/audit/index.mjs.map +1 -0
  15. package/dist/audit/mongodb.d.mts +5 -0
  16. package/dist/audit/mongodb.mjs +3 -0
  17. package/dist/audited-C3T5DTUx.mjs +141 -0
  18. package/dist/audited-C3T5DTUx.mjs.map +1 -0
  19. package/dist/auth/index.d.mts +189 -0
  20. package/dist/auth/index.d.mts.map +1 -0
  21. package/dist/auth/index.mjs +1102 -0
  22. package/dist/auth/index.mjs.map +1 -0
  23. package/dist/auth/redis-session.d.mts +44 -0
  24. package/dist/auth/redis-session.d.mts.map +1 -0
  25. package/dist/auth/redis-session.mjs +76 -0
  26. package/dist/auth/redis-session.mjs.map +1 -0
  27. package/dist/betterAuthOpenApi-BrHKeSAx.mjs +250 -0
  28. package/dist/betterAuthOpenApi-BrHKeSAx.mjs.map +1 -0
  29. package/dist/cache/index.d.mts +146 -0
  30. package/dist/cache/index.d.mts.map +1 -0
  31. package/dist/cache/index.mjs +92 -0
  32. package/dist/cache/index.mjs.map +1 -0
  33. package/dist/caching-Bl28lYsR.mjs +94 -0
  34. package/dist/caching-Bl28lYsR.mjs.map +1 -0
  35. package/dist/chunk-C7Uep-_p.mjs +20 -0
  36. package/dist/circuitBreaker-DeY4FCjs.mjs +1097 -0
  37. package/dist/circuitBreaker-DeY4FCjs.mjs.map +1 -0
  38. package/dist/cli/commands/describe.d.mts +19 -0
  39. package/dist/cli/commands/describe.d.mts.map +1 -0
  40. package/dist/cli/commands/describe.mjs +239 -0
  41. package/dist/cli/commands/describe.mjs.map +1 -0
  42. package/dist/cli/commands/docs.d.mts +14 -0
  43. package/dist/cli/commands/docs.d.mts.map +1 -0
  44. package/dist/cli/commands/docs.mjs +53 -0
  45. package/dist/cli/commands/docs.mjs.map +1 -0
  46. package/dist/cli/commands/{generate.d.ts → generate.d.mts} +3 -1
  47. package/dist/cli/commands/generate.d.mts.map +1 -0
  48. package/dist/cli/commands/generate.mjs +358 -0
  49. package/dist/cli/commands/generate.mjs.map +1 -0
  50. package/dist/cli/commands/{init.d.ts → init.d.mts} +12 -8
  51. package/dist/cli/commands/init.d.mts.map +1 -0
  52. package/dist/cli/commands/{init.js → init.mjs} +807 -616
  53. package/dist/cli/commands/init.mjs.map +1 -0
  54. package/dist/cli/commands/introspect.d.mts +11 -0
  55. package/dist/cli/commands/introspect.d.mts.map +1 -0
  56. package/dist/cli/commands/introspect.mjs +76 -0
  57. package/dist/cli/commands/introspect.mjs.map +1 -0
  58. package/dist/cli/index.d.mts +17 -0
  59. package/dist/cli/index.d.mts.map +1 -0
  60. package/dist/cli/index.mjs +157 -0
  61. package/dist/cli/index.mjs.map +1 -0
  62. package/dist/constants-DdXFXQtN.mjs +85 -0
  63. package/dist/constants-DdXFXQtN.mjs.map +1 -0
  64. package/dist/core/index.d.mts +5 -0
  65. package/dist/core/index.mjs +4 -0
  66. package/dist/createApp-CUgNqegw.mjs +560 -0
  67. package/dist/createApp-CUgNqegw.mjs.map +1 -0
  68. package/dist/defineResource-k0_BDn8v.mjs +2197 -0
  69. package/dist/defineResource-k0_BDn8v.mjs.map +1 -0
  70. package/dist/discovery/index.d.mts +47 -0
  71. package/dist/discovery/index.d.mts.map +1 -0
  72. package/dist/discovery/index.mjs +110 -0
  73. package/dist/discovery/index.mjs.map +1 -0
  74. package/dist/docs/index.d.mts +163 -0
  75. package/dist/docs/index.d.mts.map +1 -0
  76. package/dist/docs/index.mjs +73 -0
  77. package/dist/docs/index.mjs.map +1 -0
  78. package/dist/elevation-BRy3yFWT.mjs +113 -0
  79. package/dist/elevation-BRy3yFWT.mjs.map +1 -0
  80. package/dist/elevation-B_2dRLVP.d.mts +88 -0
  81. package/dist/elevation-B_2dRLVP.d.mts.map +1 -0
  82. package/dist/errorHandler-BbcgBmIH.d.mts +73 -0
  83. package/dist/errorHandler-BbcgBmIH.d.mts.map +1 -0
  84. package/dist/errorHandler-C1okiriz.mjs +109 -0
  85. package/dist/errorHandler-C1okiriz.mjs.map +1 -0
  86. package/dist/errors-B9bZok84.mjs +212 -0
  87. package/dist/errors-B9bZok84.mjs.map +1 -0
  88. package/dist/errors-ChKiFz62.d.mts +125 -0
  89. package/dist/errors-ChKiFz62.d.mts.map +1 -0
  90. package/dist/eventPlugin-CTrLH3mt.d.mts +125 -0
  91. package/dist/eventPlugin-CTrLH3mt.d.mts.map +1 -0
  92. package/dist/eventPlugin-DGR_B2on.mjs +230 -0
  93. package/dist/eventPlugin-DGR_B2on.mjs.map +1 -0
  94. package/dist/events/index.d.mts +54 -0
  95. package/dist/events/index.d.mts.map +1 -0
  96. package/dist/events/index.mjs +52 -0
  97. package/dist/events/index.mjs.map +1 -0
  98. package/dist/events/transports/redis-stream-entry.d.mts +2 -0
  99. package/dist/events/transports/redis-stream-entry.mjs +178 -0
  100. package/dist/events/transports/redis-stream-entry.mjs.map +1 -0
  101. package/dist/events/transports/redis.d.mts +77 -0
  102. package/dist/events/transports/redis.d.mts.map +1 -0
  103. package/dist/events/transports/redis.mjs +125 -0
  104. package/dist/events/transports/redis.mjs.map +1 -0
  105. package/dist/externalPaths-DlINfKbP.d.mts +51 -0
  106. package/dist/externalPaths-DlINfKbP.d.mts.map +1 -0
  107. package/dist/factory/index.d.mts +64 -0
  108. package/dist/factory/index.d.mts.map +1 -0
  109. package/dist/factory/index.mjs +3 -0
  110. package/dist/fastifyAdapter-BkrGrlFi.d.mts +217 -0
  111. package/dist/fastifyAdapter-BkrGrlFi.d.mts.map +1 -0
  112. package/dist/fields-DyaDVX4J.d.mts +110 -0
  113. package/dist/fields-DyaDVX4J.d.mts.map +1 -0
  114. package/dist/fields-iagOozy0.mjs +115 -0
  115. package/dist/fields-iagOozy0.mjs.map +1 -0
  116. package/dist/hooks/index.d.mts +4 -0
  117. package/dist/hooks/index.mjs +3 -0
  118. package/dist/idempotency/index.d.mts +97 -0
  119. package/dist/idempotency/index.d.mts.map +1 -0
  120. package/dist/idempotency/index.mjs +320 -0
  121. package/dist/idempotency/index.mjs.map +1 -0
  122. package/dist/idempotency/mongodb.d.mts +2 -0
  123. package/dist/idempotency/mongodb.mjs +115 -0
  124. package/dist/idempotency/mongodb.mjs.map +1 -0
  125. package/dist/idempotency/redis.d.mts +2 -0
  126. package/dist/idempotency/redis.mjs +104 -0
  127. package/dist/idempotency/redis.mjs.map +1 -0
  128. package/dist/index.d.mts +261 -0
  129. package/dist/index.d.mts.map +1 -0
  130. package/dist/index.mjs +105 -0
  131. package/dist/index.mjs.map +1 -0
  132. package/dist/integrations/event-gateway.d.mts +47 -0
  133. package/dist/integrations/event-gateway.d.mts.map +1 -0
  134. package/dist/integrations/event-gateway.mjs +44 -0
  135. package/dist/integrations/event-gateway.mjs.map +1 -0
  136. package/dist/integrations/index.d.mts +5 -0
  137. package/dist/integrations/index.mjs +1 -0
  138. package/dist/integrations/jobs.d.mts +104 -0
  139. package/dist/integrations/jobs.d.mts.map +1 -0
  140. package/dist/integrations/jobs.mjs +124 -0
  141. package/dist/integrations/jobs.mjs.map +1 -0
  142. package/dist/integrations/streamline.d.mts +61 -0
  143. package/dist/integrations/streamline.d.mts.map +1 -0
  144. package/dist/integrations/streamline.mjs +126 -0
  145. package/dist/integrations/streamline.mjs.map +1 -0
  146. package/dist/integrations/websocket.d.mts +83 -0
  147. package/dist/integrations/websocket.d.mts.map +1 -0
  148. package/dist/integrations/websocket.mjs +289 -0
  149. package/dist/integrations/websocket.mjs.map +1 -0
  150. package/dist/interface-B01JvPVc.d.mts +78 -0
  151. package/dist/interface-B01JvPVc.d.mts.map +1 -0
  152. package/dist/interface-CZe8IkMf.d.mts +55 -0
  153. package/dist/interface-CZe8IkMf.d.mts.map +1 -0
  154. package/dist/interface-Ch8HU9uM.d.mts +1098 -0
  155. package/dist/interface-Ch8HU9uM.d.mts.map +1 -0
  156. package/dist/introspectionPlugin-rFdO8ZUa.mjs +54 -0
  157. package/dist/introspectionPlugin-rFdO8ZUa.mjs.map +1 -0
  158. package/dist/keys-BqNejWup.mjs +43 -0
  159. package/dist/keys-BqNejWup.mjs.map +1 -0
  160. package/dist/logger-Df2O2WsW.mjs +79 -0
  161. package/dist/logger-Df2O2WsW.mjs.map +1 -0
  162. package/dist/memory-cQgelFOj.mjs +144 -0
  163. package/dist/memory-cQgelFOj.mjs.map +1 -0
  164. package/dist/migrations/index.d.mts +157 -0
  165. package/dist/migrations/index.d.mts.map +1 -0
  166. package/dist/migrations/index.mjs +261 -0
  167. package/dist/migrations/index.mjs.map +1 -0
  168. package/dist/mongodb-BfJVlUJH.mjs +94 -0
  169. package/dist/mongodb-BfJVlUJH.mjs.map +1 -0
  170. package/dist/mongodb-CGzRbfAK.d.mts +119 -0
  171. package/dist/mongodb-CGzRbfAK.d.mts.map +1 -0
  172. package/dist/mongodb-JN-9JA7K.d.mts +72 -0
  173. package/dist/mongodb-JN-9JA7K.d.mts.map +1 -0
  174. package/dist/openapi-G3Cw7XuM.mjs +524 -0
  175. package/dist/openapi-G3Cw7XuM.mjs.map +1 -0
  176. package/dist/org/index.d.mts +69 -0
  177. package/dist/org/index.d.mts.map +1 -0
  178. package/dist/org/index.mjs +514 -0
  179. package/dist/org/index.mjs.map +1 -0
  180. package/dist/org/types.d.mts +83 -0
  181. package/dist/org/types.d.mts.map +1 -0
  182. package/dist/org/types.mjs +1 -0
  183. package/dist/permissions/index.d.mts +279 -0
  184. package/dist/permissions/index.d.mts.map +1 -0
  185. package/dist/permissions/index.mjs +579 -0
  186. package/dist/permissions/index.mjs.map +1 -0
  187. package/dist/plugins/index.d.mts +173 -0
  188. package/dist/plugins/index.d.mts.map +1 -0
  189. package/dist/plugins/index.mjs +523 -0
  190. package/dist/plugins/index.mjs.map +1 -0
  191. package/dist/plugins/response-cache.d.mts +88 -0
  192. package/dist/plugins/response-cache.d.mts.map +1 -0
  193. package/dist/plugins/response-cache.mjs +284 -0
  194. package/dist/plugins/response-cache.mjs.map +1 -0
  195. package/dist/plugins/tracing-entry.d.mts +2 -0
  196. package/dist/plugins/tracing-entry.mjs +186 -0
  197. package/dist/plugins/tracing-entry.mjs.map +1 -0
  198. package/dist/pluralize-CEweyOEm.mjs +87 -0
  199. package/dist/pluralize-CEweyOEm.mjs.map +1 -0
  200. package/dist/policies/{index.d.ts → index.d.mts} +204 -169
  201. package/dist/policies/index.d.mts.map +1 -0
  202. package/dist/policies/index.mjs +322 -0
  203. package/dist/policies/index.mjs.map +1 -0
  204. package/dist/presets/{index.d.ts → index.d.mts} +63 -131
  205. package/dist/presets/index.d.mts.map +1 -0
  206. package/dist/presets/index.mjs +144 -0
  207. package/dist/presets/index.mjs.map +1 -0
  208. package/dist/presets/multiTenant.d.mts +25 -0
  209. package/dist/presets/multiTenant.d.mts.map +1 -0
  210. package/dist/presets/multiTenant.mjs +114 -0
  211. package/dist/presets/multiTenant.mjs.map +1 -0
  212. package/dist/presets-BITljm96.mjs +120 -0
  213. package/dist/presets-BITljm96.mjs.map +1 -0
  214. package/dist/presets-DzSMwlKj.d.mts +58 -0
  215. package/dist/presets-DzSMwlKj.d.mts.map +1 -0
  216. package/dist/prisma-DJbMt3yf.mjs +628 -0
  217. package/dist/prisma-DJbMt3yf.mjs.map +1 -0
  218. package/dist/prisma-Dg9GoVdj.d.mts +275 -0
  219. package/dist/prisma-Dg9GoVdj.d.mts.map +1 -0
  220. package/dist/queryCachePlugin-7THaI5mt.d.mts +72 -0
  221. package/dist/queryCachePlugin-7THaI5mt.d.mts.map +1 -0
  222. package/dist/queryCachePlugin-DMBnp2Q0.mjs +139 -0
  223. package/dist/queryCachePlugin-DMBnp2Q0.mjs.map +1 -0
  224. package/dist/redis-D-JAeLtm.d.mts +50 -0
  225. package/dist/redis-D-JAeLtm.d.mts.map +1 -0
  226. package/dist/redis-stream-Bdh_vUU8.d.mts +104 -0
  227. package/dist/redis-stream-Bdh_vUU8.d.mts.map +1 -0
  228. package/dist/registry/index.d.mts +12 -0
  229. package/dist/registry/index.d.mts.map +1 -0
  230. package/dist/registry/index.mjs +4 -0
  231. package/dist/requestContext-QQD6ROJc.mjs +56 -0
  232. package/dist/requestContext-QQD6ROJc.mjs.map +1 -0
  233. package/dist/schemaConverter-BwrmWroW.mjs +99 -0
  234. package/dist/schemaConverter-BwrmWroW.mjs.map +1 -0
  235. package/dist/schemas/index.d.mts +64 -0
  236. package/dist/schemas/index.d.mts.map +1 -0
  237. package/dist/schemas/index.mjs +83 -0
  238. package/dist/schemas/index.mjs.map +1 -0
  239. package/dist/scope/index.d.mts +22 -0
  240. package/dist/scope/index.d.mts.map +1 -0
  241. package/dist/scope/index.mjs +66 -0
  242. package/dist/scope/index.mjs.map +1 -0
  243. package/dist/sessionManager-jPKLbHE0.d.mts +187 -0
  244. package/dist/sessionManager-jPKLbHE0.d.mts.map +1 -0
  245. package/dist/sse-B3c3_yZp.mjs +124 -0
  246. package/dist/sse-B3c3_yZp.mjs.map +1 -0
  247. package/dist/testing/index.d.mts +908 -0
  248. package/dist/testing/index.d.mts.map +1 -0
  249. package/dist/testing/index.mjs +1977 -0
  250. package/dist/testing/index.mjs.map +1 -0
  251. package/dist/tracing-Cc7vVQPp.d.mts +71 -0
  252. package/dist/tracing-Cc7vVQPp.d.mts.map +1 -0
  253. package/dist/typeGuards-DhMNLuvU.mjs +10 -0
  254. package/dist/typeGuards-DhMNLuvU.mjs.map +1 -0
  255. package/dist/types/index.d.mts +947 -0
  256. package/dist/types/index.d.mts.map +1 -0
  257. package/dist/types/index.mjs +15 -0
  258. package/dist/types/index.mjs.map +1 -0
  259. package/dist/types-Beqn1Un7.mjs +39 -0
  260. package/dist/types-Beqn1Un7.mjs.map +1 -0
  261. package/dist/types-CIgB7UUl.d.mts +446 -0
  262. package/dist/types-CIgB7UUl.d.mts.map +1 -0
  263. package/dist/types-aYB4V7uN.d.mts +87 -0
  264. package/dist/types-aYB4V7uN.d.mts.map +1 -0
  265. package/dist/utils/index.d.mts +748 -0
  266. package/dist/utils/index.d.mts.map +1 -0
  267. package/dist/utils/index.mjs +6 -0
  268. package/package.json +198 -70
  269. package/dist/BaseController-nNRS3vpA.d.ts +0 -233
  270. package/dist/adapters/index.d.ts +0 -237
  271. package/dist/adapters/index.js +0 -668
  272. package/dist/arcCorePlugin-CAjBQtZB.d.ts +0 -273
  273. package/dist/audit/index.d.ts +0 -195
  274. package/dist/audit/index.js +0 -319
  275. package/dist/auth/index.d.ts +0 -47
  276. package/dist/auth/index.js +0 -174
  277. package/dist/cli/commands/docs.d.ts +0 -11
  278. package/dist/cli/commands/docs.js +0 -474
  279. package/dist/cli/commands/generate.js +0 -334
  280. package/dist/cli/commands/introspect.d.ts +0 -8
  281. package/dist/cli/commands/introspect.js +0 -338
  282. package/dist/cli/index.d.ts +0 -4
  283. package/dist/cli/index.js +0 -3269
  284. package/dist/core/index.d.ts +0 -220
  285. package/dist/core/index.js +0 -2764
  286. package/dist/createApp-CjN9zZSL.d.ts +0 -77
  287. package/dist/docs/index.d.ts +0 -166
  288. package/dist/docs/index.js +0 -658
  289. package/dist/errors-8WIxGS_6.d.ts +0 -122
  290. package/dist/events/index.d.ts +0 -117
  291. package/dist/events/index.js +0 -89
  292. package/dist/factory/index.d.ts +0 -38
  293. package/dist/factory/index.js +0 -1647
  294. package/dist/hooks/index.d.ts +0 -4
  295. package/dist/hooks/index.js +0 -199
  296. package/dist/idempotency/index.d.ts +0 -323
  297. package/dist/idempotency/index.js +0 -500
  298. package/dist/index-D5QTob1X.d.ts +0 -1322
  299. package/dist/index.d.ts +0 -135
  300. package/dist/index.js +0 -4729
  301. package/dist/migrations/index.d.ts +0 -185
  302. package/dist/migrations/index.js +0 -274
  303. package/dist/org/index.d.ts +0 -129
  304. package/dist/org/index.js +0 -220
  305. package/dist/permissions/index.d.ts +0 -144
  306. package/dist/permissions/index.js +0 -103
  307. package/dist/plugins/index.d.ts +0 -46
  308. package/dist/plugins/index.js +0 -1069
  309. package/dist/policies/index.js +0 -196
  310. package/dist/presets/index.js +0 -384
  311. package/dist/presets/multiTenant.d.ts +0 -39
  312. package/dist/presets/multiTenant.js +0 -112
  313. package/dist/registry/index.d.ts +0 -16
  314. package/dist/registry/index.js +0 -253
  315. package/dist/testing/index.d.ts +0 -618
  316. package/dist/testing/index.js +0 -48015
  317. package/dist/types/index.d.ts +0 -4
  318. package/dist/types/index.js +0 -8
  319. package/dist/types-B99TBmFV.d.ts +0 -76
  320. package/dist/types-zpN48n6B.d.ts +0 -143
  321. package/dist/utils/index.d.ts +0 -679
  322. package/dist/utils/index.js +0 -914
package/dist/index.js DELETED
@@ -1,4729 +0,0 @@
1
- import fp from 'fastify-plugin';
2
- import { randomUUID } from 'crypto';
3
- import { createRequire } from 'module';
4
- import Fastify from 'fastify';
5
-
6
- var __defProp = Object.defineProperty;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
-
16
- // src/hooks/HookSystem.ts
17
- var HookSystem, hookSystem;
18
- var init_HookSystem = __esm({
19
- "src/hooks/HookSystem.ts"() {
20
- HookSystem = class {
21
- hooks;
22
- logger;
23
- constructor(options) {
24
- this.hooks = /* @__PURE__ */ new Map();
25
- this.logger = options?.logger ?? { error: (...args) => console.error(...args) };
26
- }
27
- /**
28
- * Generate hook key
29
- */
30
- getKey(resource, operation, phase) {
31
- return `${resource}:${operation}:${phase}`;
32
- }
33
- /**
34
- * Register a hook
35
- * Supports both object parameter and positional arguments
36
- */
37
- register(resourceOrOptions, operation, phase, handler, priority = 10) {
38
- let resource;
39
- let finalOperation;
40
- let finalPhase;
41
- let finalHandler;
42
- let finalPriority;
43
- if (typeof resourceOrOptions === "object") {
44
- resource = resourceOrOptions.resource;
45
- finalOperation = resourceOrOptions.operation;
46
- finalPhase = resourceOrOptions.phase;
47
- finalHandler = resourceOrOptions.handler;
48
- finalPriority = resourceOrOptions.priority ?? 10;
49
- } else {
50
- resource = resourceOrOptions;
51
- finalOperation = operation;
52
- finalPhase = phase;
53
- finalHandler = handler;
54
- finalPriority = priority;
55
- }
56
- const key = this.getKey(resource, finalOperation, finalPhase);
57
- if (!this.hooks.has(key)) {
58
- this.hooks.set(key, []);
59
- }
60
- const registration = {
61
- resource,
62
- operation: finalOperation,
63
- phase: finalPhase,
64
- handler: finalHandler,
65
- priority: finalPriority
66
- };
67
- const hooks = this.hooks.get(key);
68
- hooks.push(registration);
69
- hooks.sort((a, b) => a.priority - b.priority);
70
- return () => {
71
- const idx = hooks.indexOf(registration);
72
- if (idx !== -1) {
73
- hooks.splice(idx, 1);
74
- }
75
- };
76
- }
77
- /**
78
- * Register before hook
79
- */
80
- before(resource, operation, handler, priority = 10) {
81
- return this.register(resource, operation, "before", handler, priority);
82
- }
83
- /**
84
- * Register after hook
85
- */
86
- after(resource, operation, handler, priority = 10) {
87
- return this.register(resource, operation, "after", handler, priority);
88
- }
89
- /**
90
- * Execute hooks for a given context
91
- */
92
- async execute(ctx) {
93
- const key = this.getKey(ctx.resource, ctx.operation, ctx.phase);
94
- const hooks = this.hooks.get(key) ?? [];
95
- const wildcardKey = this.getKey("*", ctx.operation, ctx.phase);
96
- const wildcardHooks = this.hooks.get(wildcardKey) ?? [];
97
- const allHooks = [...wildcardHooks, ...hooks];
98
- allHooks.sort((a, b) => a.priority - b.priority);
99
- let result = ctx.data;
100
- for (const hook of allHooks) {
101
- const handlerContext = {
102
- resource: ctx.resource,
103
- operation: ctx.operation,
104
- phase: ctx.phase,
105
- data: result,
106
- result: ctx.result,
107
- user: ctx.user,
108
- context: ctx.context,
109
- meta: ctx.meta
110
- };
111
- const hookResult = await hook.handler(handlerContext);
112
- if (hookResult !== void 0 && hookResult !== null) {
113
- result = hookResult;
114
- }
115
- }
116
- return result;
117
- }
118
- /**
119
- * Execute before hooks
120
- */
121
- async executeBefore(resource, operation, data, options) {
122
- const result = await this.execute({
123
- resource,
124
- operation,
125
- phase: "before",
126
- data,
127
- user: options?.user,
128
- context: options?.context,
129
- meta: options?.meta
130
- });
131
- return result ?? data;
132
- }
133
- /**
134
- * Execute after hooks
135
- * Errors in after hooks are logged but don't fail the request
136
- */
137
- async executeAfter(resource, operation, result, options) {
138
- try {
139
- await this.execute({
140
- resource,
141
- operation,
142
- phase: "after",
143
- result,
144
- user: options?.user,
145
- context: options?.context,
146
- meta: options?.meta
147
- });
148
- } catch (error) {
149
- this.logger.error(
150
- `[HookSystem] Error in after hook for ${resource}:${operation}:`,
151
- error
152
- );
153
- }
154
- }
155
- /**
156
- * Get all registered hooks
157
- */
158
- getAll() {
159
- const all = [];
160
- for (const hooks of this.hooks.values()) {
161
- all.push(...hooks);
162
- }
163
- return all;
164
- }
165
- /**
166
- * Get hooks for a specific resource
167
- */
168
- getForResource(resource) {
169
- const all = [];
170
- for (const [key, hooks] of this.hooks.entries()) {
171
- if (key.startsWith(`${resource}:`)) {
172
- all.push(...hooks);
173
- }
174
- }
175
- return all;
176
- }
177
- /**
178
- * Clear all hooks
179
- */
180
- clear() {
181
- this.hooks.clear();
182
- }
183
- /**
184
- * Clear hooks for a specific resource
185
- */
186
- clearResource(resource) {
187
- for (const key of this.hooks.keys()) {
188
- if (key.startsWith(`${resource}:`)) {
189
- this.hooks.delete(key);
190
- }
191
- }
192
- }
193
- };
194
- hookSystem = new HookSystem();
195
- }
196
- });
197
-
198
- // src/registry/ResourceRegistry.ts
199
- var ResourceRegistry, registryKey, globalScope, resourceRegistry;
200
- var init_ResourceRegistry = __esm({
201
- "src/registry/ResourceRegistry.ts"() {
202
- ResourceRegistry = class {
203
- _resources;
204
- _frozen;
205
- constructor() {
206
- this._resources = /* @__PURE__ */ new Map();
207
- this._frozen = false;
208
- }
209
- /**
210
- * Register a resource
211
- */
212
- register(resource, options = {}) {
213
- if (this._frozen) {
214
- throw new Error(
215
- `Registry frozen. Cannot register '${resource.name}' after startup.`
216
- );
217
- }
218
- if (this._resources.has(resource.name)) {
219
- throw new Error(`Resource '${resource.name}' already registered.`);
220
- }
221
- const entry = {
222
- name: resource.name,
223
- displayName: resource.displayName,
224
- tag: resource.tag,
225
- prefix: resource.prefix,
226
- module: options.module ?? void 0,
227
- adapter: resource.adapter ? {
228
- type: resource.adapter.type,
229
- name: resource.adapter.name
230
- } : null,
231
- permissions: resource.permissions,
232
- presets: resource._appliedPresets ?? [],
233
- routes: [],
234
- // Populated later by getIntrospection()
235
- additionalRoutes: resource.additionalRoutes.map((r) => ({
236
- method: r.method,
237
- path: r.path,
238
- handler: typeof r.handler === "string" ? r.handler : r.handler.name || "anonymous",
239
- summary: r.summary,
240
- description: r.description,
241
- permissions: r.permissions,
242
- wrapHandler: r.wrapHandler,
243
- schema: r.schema
244
- // Include schema for OpenAPI docs
245
- })),
246
- events: Object.keys(resource.events ?? {}),
247
- registeredAt: (/* @__PURE__ */ new Date()).toISOString(),
248
- disableDefaultRoutes: resource.disableDefaultRoutes,
249
- openApiSchemas: options.openApiSchemas,
250
- plugin: resource.toPlugin()
251
- // Store plugin factory
252
- };
253
- this._resources.set(resource.name, entry);
254
- return this;
255
- }
256
- /**
257
- * Get resource by name
258
- */
259
- get(name) {
260
- return this._resources.get(name);
261
- }
262
- /**
263
- * Get all resources
264
- */
265
- getAll() {
266
- return Array.from(this._resources.values());
267
- }
268
- /**
269
- * Get resources by module
270
- */
271
- getByModule(moduleName) {
272
- return this.getAll().filter((r) => r.module === moduleName);
273
- }
274
- /**
275
- * Get resources by preset
276
- */
277
- getByPreset(presetName) {
278
- return this.getAll().filter((r) => r.presets.includes(presetName));
279
- }
280
- /**
281
- * Check if resource exists
282
- */
283
- has(name) {
284
- return this._resources.has(name);
285
- }
286
- /**
287
- * Get registry statistics
288
- */
289
- getStats() {
290
- const resources = this.getAll();
291
- const presetCounts = {};
292
- for (const r of resources) {
293
- for (const preset of r.presets) {
294
- presetCounts[preset] = (presetCounts[preset] ?? 0) + 1;
295
- }
296
- }
297
- return {
298
- totalResources: resources.length,
299
- byModule: this._groupBy(resources, "module"),
300
- presetUsage: presetCounts,
301
- totalRoutes: resources.reduce((sum, r) => {
302
- const defaultRouteCount = r.disableDefaultRoutes ? 0 : 5;
303
- return sum + (r.additionalRoutes?.length ?? 0) + defaultRouteCount;
304
- }, 0),
305
- totalEvents: resources.reduce((sum, r) => sum + (r.events?.length ?? 0), 0)
306
- };
307
- }
308
- /**
309
- * Get full introspection data
310
- */
311
- getIntrospection() {
312
- return {
313
- resources: this.getAll().map((r) => {
314
- const defaultRoutes = r.disableDefaultRoutes ? [] : [
315
- { method: "GET", path: r.prefix, operation: "list" },
316
- { method: "GET", path: `${r.prefix}/:id`, operation: "get" },
317
- { method: "POST", path: r.prefix, operation: "create" },
318
- { method: "PATCH", path: `${r.prefix}/:id`, operation: "update" },
319
- { method: "DELETE", path: `${r.prefix}/:id`, operation: "delete" }
320
- ];
321
- return {
322
- name: r.name,
323
- displayName: r.displayName,
324
- prefix: r.prefix,
325
- module: r.module,
326
- presets: r.presets,
327
- permissions: r.permissions,
328
- routes: [
329
- ...defaultRoutes,
330
- ...r.additionalRoutes?.map((ar) => ({
331
- method: ar.method,
332
- path: `${r.prefix}${ar.path}`,
333
- operation: typeof ar.handler === "string" ? ar.handler : "custom",
334
- handler: typeof ar.handler === "string" ? ar.handler : void 0,
335
- summary: ar.summary
336
- })) ?? []
337
- ],
338
- events: r.events
339
- };
340
- }),
341
- stats: this.getStats(),
342
- generatedAt: (/* @__PURE__ */ new Date()).toISOString()
343
- };
344
- }
345
- /**
346
- * Freeze registry (prevent further registrations)
347
- */
348
- freeze() {
349
- this._frozen = true;
350
- }
351
- /**
352
- * Check if frozen
353
- */
354
- isFrozen() {
355
- return this._frozen;
356
- }
357
- /**
358
- * Unfreeze registry (for testing)
359
- */
360
- _unfreeze() {
361
- this._frozen = false;
362
- }
363
- /**
364
- * Clear all resources (for testing)
365
- */
366
- _clear() {
367
- this._resources.clear();
368
- this._frozen = false;
369
- }
370
- /**
371
- * Group by key
372
- */
373
- _groupBy(arr, key) {
374
- const result = {};
375
- for (const item of arr) {
376
- const k = String(item[key] ?? "uncategorized");
377
- result[k] = (result[k] ?? 0) + 1;
378
- }
379
- return result;
380
- }
381
- };
382
- registryKey = /* @__PURE__ */ Symbol.for("arc.resourceRegistry");
383
- globalScope = globalThis;
384
- resourceRegistry = globalScope[registryKey] ?? new ResourceRegistry();
385
- if (!globalScope[registryKey]) {
386
- globalScope[registryKey] = resourceRegistry;
387
- }
388
- }
389
- });
390
-
391
- // src/utils/errors.ts
392
- function isArcError(error) {
393
- return error instanceof ArcError;
394
- }
395
- var ArcError, NotFoundError, ValidationError, UnauthorizedError, ForbiddenError;
396
- var init_errors = __esm({
397
- "src/utils/errors.ts"() {
398
- ArcError = class extends Error {
399
- name;
400
- code;
401
- statusCode;
402
- details;
403
- cause;
404
- timestamp;
405
- requestId;
406
- constructor(message, options = {}) {
407
- super(message);
408
- this.name = "ArcError";
409
- this.code = options.code ?? "ARC_ERROR";
410
- this.statusCode = options.statusCode ?? 500;
411
- this.details = options.details;
412
- this.cause = options.cause;
413
- this.timestamp = (/* @__PURE__ */ new Date()).toISOString();
414
- this.requestId = options.requestId;
415
- if (Error.captureStackTrace) {
416
- Error.captureStackTrace(this, this.constructor);
417
- }
418
- }
419
- /**
420
- * Set request ID (typically from request context)
421
- */
422
- withRequestId(requestId) {
423
- this.requestId = requestId;
424
- return this;
425
- }
426
- /**
427
- * Convert to JSON response
428
- */
429
- toJSON() {
430
- return {
431
- success: false,
432
- error: this.message,
433
- code: this.code,
434
- timestamp: this.timestamp,
435
- ...this.requestId && { requestId: this.requestId },
436
- ...this.details && { details: this.details }
437
- };
438
- }
439
- };
440
- NotFoundError = class extends ArcError {
441
- constructor(resource, identifier) {
442
- const message = identifier ? `${resource} with identifier '${identifier}' not found` : `${resource} not found`;
443
- super(message, {
444
- code: "NOT_FOUND",
445
- statusCode: 404,
446
- details: { resource, identifier }
447
- });
448
- this.name = "NotFoundError";
449
- }
450
- };
451
- ValidationError = class extends ArcError {
452
- errors;
453
- constructor(message, errors = []) {
454
- super(message, {
455
- code: "VALIDATION_ERROR",
456
- statusCode: 400,
457
- details: { errors }
458
- });
459
- this.name = "ValidationError";
460
- this.errors = errors;
461
- }
462
- };
463
- UnauthorizedError = class extends ArcError {
464
- constructor(message = "Authentication required") {
465
- super(message, {
466
- code: "UNAUTHORIZED",
467
- statusCode: 401
468
- });
469
- this.name = "UnauthorizedError";
470
- }
471
- };
472
- ForbiddenError = class extends ArcError {
473
- constructor(message = "Access denied") {
474
- super(message, {
475
- code: "FORBIDDEN",
476
- statusCode: 403
477
- });
478
- this.name = "ForbiddenError";
479
- }
480
- };
481
- }
482
- });
483
- var requestIdPlugin, requestId_default;
484
- var init_requestId = __esm({
485
- "src/plugins/requestId.ts"() {
486
- requestIdPlugin = async (fastify, opts = {}) => {
487
- const {
488
- header = "x-request-id",
489
- generator = randomUUID,
490
- setResponseHeader = true
491
- } = opts;
492
- if (!fastify.hasRequestDecorator("requestId")) {
493
- fastify.decorateRequest("requestId", "");
494
- }
495
- fastify.addHook("onRequest", async (request) => {
496
- const incomingId = request.headers[header];
497
- const requestId = typeof incomingId === "string" && incomingId.trim() ? incomingId.trim() : generator();
498
- request.id = requestId;
499
- request.requestId = requestId;
500
- });
501
- if (setResponseHeader) {
502
- fastify.addHook("onSend", async (request, reply) => {
503
- reply.header(header, request.requestId);
504
- });
505
- }
506
- fastify.log?.debug?.("Request ID plugin registered");
507
- };
508
- requestId_default = fp(requestIdPlugin, {
509
- name: "arc-request-id",
510
- fastify: "5.x"
511
- });
512
- }
513
- });
514
- async function runChecks(checks) {
515
- const results = [];
516
- for (const check of checks) {
517
- const start = Date.now();
518
- const timeout = check.timeout ?? 5e3;
519
- try {
520
- const checkPromise = Promise.resolve(check.check());
521
- const timeoutPromise = new Promise((_, reject) => {
522
- setTimeout(() => reject(new Error("Health check timeout")), timeout);
523
- });
524
- const healthy = await Promise.race([checkPromise, timeoutPromise]);
525
- results.push({
526
- name: check.name,
527
- healthy: Boolean(healthy),
528
- duration: Date.now() - start
529
- });
530
- } catch (err) {
531
- results.push({
532
- name: check.name,
533
- healthy: false,
534
- duration: Date.now() - start,
535
- error: err.message
536
- });
537
- }
538
- }
539
- return results;
540
- }
541
- var httpMetrics, healthPlugin, health_default;
542
- var init_health = __esm({
543
- "src/plugins/health.ts"() {
544
- httpMetrics = {
545
- requestsTotal: {},
546
- requestDurations: [],
547
- startTime: Date.now()
548
- };
549
- healthPlugin = async (fastify, opts = {}) => {
550
- const {
551
- prefix = "/_health",
552
- checks = [],
553
- metrics = false,
554
- metricsCollector,
555
- version: version2,
556
- collectHttpMetrics = metrics
557
- } = opts;
558
- fastify.get(`${prefix}/live`, {
559
- schema: {
560
- tags: ["Health"],
561
- summary: "Liveness probe",
562
- description: "Returns 200 if the process is alive",
563
- response: {
564
- 200: {
565
- type: "object",
566
- properties: {
567
- status: { type: "string", enum: ["ok"] },
568
- timestamp: { type: "string" },
569
- version: { type: "string" }
570
- }
571
- }
572
- }
573
- }
574
- }, async () => {
575
- return {
576
- status: "ok",
577
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
578
- ...version2 ? { version: version2 } : {}
579
- };
580
- });
581
- fastify.get(`${prefix}/ready`, {
582
- schema: {
583
- tags: ["Health"],
584
- summary: "Readiness probe",
585
- description: "Returns 200 if all dependencies are healthy",
586
- response: {
587
- 200: {
588
- type: "object",
589
- properties: {
590
- status: { type: "string", enum: ["ready", "not_ready"] },
591
- timestamp: { type: "string" },
592
- checks: {
593
- type: "array",
594
- items: {
595
- type: "object",
596
- properties: {
597
- name: { type: "string" },
598
- healthy: { type: "boolean" },
599
- duration: { type: "number" },
600
- error: { type: "string" }
601
- }
602
- }
603
- }
604
- }
605
- },
606
- 503: {
607
- type: "object",
608
- properties: {
609
- status: { type: "string", enum: ["not_ready"] },
610
- timestamp: { type: "string" },
611
- checks: { type: "array" }
612
- }
613
- }
614
- }
615
- }
616
- }, async (_, reply) => {
617
- const results = await runChecks(checks);
618
- const criticalFailed = results.some(
619
- (r) => !r.healthy && (checks.find((c) => c.name === r.name)?.critical ?? true)
620
- );
621
- const response = {
622
- status: criticalFailed ? "not_ready" : "ready",
623
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
624
- checks: results
625
- };
626
- if (criticalFailed) {
627
- reply.code(503);
628
- }
629
- return response;
630
- });
631
- if (metrics) {
632
- fastify.get(`${prefix}/metrics`, async (_, reply) => {
633
- reply.type("text/plain; charset=utf-8");
634
- if (metricsCollector) {
635
- return await metricsCollector();
636
- }
637
- const uptime = process.uptime();
638
- const memory = process.memoryUsage();
639
- const cpu = process.cpuUsage();
640
- const lines = [
641
- "# HELP process_uptime_seconds Process uptime in seconds",
642
- "# TYPE process_uptime_seconds gauge",
643
- `process_uptime_seconds ${uptime.toFixed(2)}`,
644
- "",
645
- "# HELP process_memory_heap_bytes Heap memory usage in bytes",
646
- "# TYPE process_memory_heap_bytes gauge",
647
- `process_memory_heap_bytes{type="used"} ${memory.heapUsed}`,
648
- `process_memory_heap_bytes{type="total"} ${memory.heapTotal}`,
649
- "",
650
- "# HELP process_memory_rss_bytes RSS memory in bytes",
651
- "# TYPE process_memory_rss_bytes gauge",
652
- `process_memory_rss_bytes ${memory.rss}`,
653
- "",
654
- "# HELP process_memory_external_bytes External memory in bytes",
655
- "# TYPE process_memory_external_bytes gauge",
656
- `process_memory_external_bytes ${memory.external}`,
657
- "",
658
- "# HELP process_cpu_user_microseconds User CPU time in microseconds",
659
- "# TYPE process_cpu_user_microseconds counter",
660
- `process_cpu_user_microseconds ${cpu.user}`,
661
- "",
662
- "# HELP process_cpu_system_microseconds System CPU time in microseconds",
663
- "# TYPE process_cpu_system_microseconds counter",
664
- `process_cpu_system_microseconds ${cpu.system}`,
665
- ""
666
- ];
667
- if (collectHttpMetrics && Object.keys(httpMetrics.requestsTotal).length > 0) {
668
- lines.push(
669
- "# HELP http_requests_total Total HTTP requests by status code",
670
- "# TYPE http_requests_total counter"
671
- );
672
- for (const [status, count] of Object.entries(httpMetrics.requestsTotal)) {
673
- lines.push(`http_requests_total{status="${status}"} ${count}`);
674
- }
675
- lines.push("");
676
- if (httpMetrics.requestDurations.length > 0) {
677
- const sorted = [...httpMetrics.requestDurations].sort((a, b) => a - b);
678
- const p50 = sorted[Math.floor(sorted.length * 0.5)] || 0;
679
- const p95 = sorted[Math.floor(sorted.length * 0.95)] || 0;
680
- const p99 = sorted[Math.floor(sorted.length * 0.99)] || 0;
681
- const sum = sorted.reduce((a, b) => a + b, 0);
682
- lines.push(
683
- "# HELP http_request_duration_milliseconds HTTP request duration",
684
- "# TYPE http_request_duration_milliseconds summary",
685
- `http_request_duration_milliseconds{quantile="0.5"} ${p50.toFixed(2)}`,
686
- `http_request_duration_milliseconds{quantile="0.95"} ${p95.toFixed(2)}`,
687
- `http_request_duration_milliseconds{quantile="0.99"} ${p99.toFixed(2)}`,
688
- `http_request_duration_milliseconds_sum ${sum.toFixed(2)}`,
689
- `http_request_duration_milliseconds_count ${sorted.length}`,
690
- ""
691
- );
692
- }
693
- }
694
- return lines.join("\n");
695
- });
696
- }
697
- if (collectHttpMetrics) {
698
- fastify.addHook("onRequest", async (request) => {
699
- request._startTime = Date.now();
700
- });
701
- fastify.addHook("onResponse", async (request, reply) => {
702
- const duration = Date.now() - (request._startTime || Date.now());
703
- const statusBucket = `${Math.floor(reply.statusCode / 100)}xx`;
704
- httpMetrics.requestsTotal[statusBucket] = (httpMetrics.requestsTotal[statusBucket] || 0) + 1;
705
- httpMetrics.requestDurations.push(duration);
706
- if (httpMetrics.requestDurations.length > 1e4) {
707
- httpMetrics.requestDurations.shift();
708
- }
709
- });
710
- }
711
- fastify.log?.info?.(`Health plugin registered at ${prefix}`);
712
- };
713
- health_default = fp(healthPlugin, {
714
- name: "arc-health",
715
- fastify: "5.x"
716
- });
717
- }
718
- });
719
- function createTracerProvider(options) {
720
- if (!isAvailable) {
721
- return null;
722
- }
723
- const { serviceName = "@classytic/arc", exporterUrl = "http://localhost:4318/v1/traces" } = options;
724
- const exporter = new OTLPTraceExporter({
725
- url: exporterUrl
726
- });
727
- const provider = new NodeTracerProvider({
728
- resource: {
729
- attributes: {
730
- "service.name": serviceName,
731
- "service.version": "1.0.0"
732
- }
733
- }
734
- });
735
- provider.addSpanProcessor(new BatchSpanProcessor(exporter));
736
- provider.register();
737
- return provider;
738
- }
739
- async function tracingPlugin(fastify, options = {}) {
740
- const {
741
- serviceName = "@classytic/arc",
742
- autoInstrumentation = true,
743
- traceRepository = true,
744
- traceController = true,
745
- sampleRate = 1
746
- } = options;
747
- if (!isAvailable) {
748
- fastify.log.warn("OpenTelemetry not installed. Tracing disabled.");
749
- fastify.log.warn("Install: npm install @opentelemetry/api @opentelemetry/sdk-node");
750
- return;
751
- }
752
- const provider = createTracerProvider(options);
753
- if (!provider) {
754
- return;
755
- }
756
- if (autoInstrumentation && getNodeAutoInstrumentations) {
757
- getNodeAutoInstrumentations({
758
- "@opentelemetry/instrumentation-http": {
759
- enabled: true
760
- },
761
- "@opentelemetry/instrumentation-mongodb": {
762
- enabled: true
763
- }
764
- });
765
- }
766
- const tracer = trace.getTracer(serviceName);
767
- fastify.decorateRequest("tracer", void 0);
768
- fastify.addHook("onRequest", async (request, reply) => {
769
- if (Math.random() > sampleRate) {
770
- return;
771
- }
772
- const span = tracer.startSpan(`HTTP ${request.method} ${request.url}`, {
773
- kind: 1,
774
- // SpanKind.SERVER
775
- attributes: {
776
- "http.method": request.method,
777
- "http.url": request.url,
778
- "http.target": request.routeOptions?.url ?? request.url,
779
- "http.host": request.hostname,
780
- "http.scheme": request.protocol,
781
- "http.user_agent": request.headers["user-agent"]
782
- }
783
- });
784
- request.tracer = {
785
- tracer,
786
- currentSpan: span
787
- };
788
- context.with(trace.setSpan(context.active(), span), () => {
789
- });
790
- });
791
- fastify.addHook("onResponse", async (request, reply) => {
792
- if (!request.tracer?.currentSpan) {
793
- return;
794
- }
795
- const span = request.tracer.currentSpan;
796
- span.setAttributes({
797
- "http.status_code": reply.statusCode,
798
- "http.response_content_length": reply.getHeader("content-length")
799
- });
800
- if (reply.statusCode >= 500) {
801
- span.setStatus({
802
- code: SpanStatusCode.ERROR,
803
- message: `HTTP ${reply.statusCode}`
804
- });
805
- } else {
806
- span.setStatus({ code: SpanStatusCode.OK });
807
- }
808
- span.end();
809
- });
810
- fastify.addHook("onError", async (request, reply, error) => {
811
- if (!request.tracer?.currentSpan) {
812
- return;
813
- }
814
- const span = request.tracer.currentSpan;
815
- span.recordException(error);
816
- span.setStatus({
817
- code: SpanStatusCode.ERROR,
818
- message: error.message
819
- });
820
- });
821
- fastify.log.info({ serviceName }, "OpenTelemetry tracing enabled");
822
- }
823
- function createSpan(request, name, fn, attributes) {
824
- if (!isAvailable || !request.tracer) {
825
- return fn(null);
826
- }
827
- const { tracer, currentSpan } = request.tracer;
828
- const span = tracer.startSpan(
829
- name,
830
- {
831
- parent: currentSpan,
832
- attributes: attributes || {}
833
- },
834
- trace.setSpan(context.active(), currentSpan)
835
- );
836
- return context.with(trace.setSpan(context.active(), span), async () => {
837
- try {
838
- const result = await fn(span);
839
- span.setStatus({ code: SpanStatusCode.OK });
840
- return result;
841
- } catch (error) {
842
- span.recordException(error);
843
- span.setStatus({
844
- code: SpanStatusCode.ERROR,
845
- message: error.message
846
- });
847
- throw error;
848
- } finally {
849
- span.end();
850
- }
851
- });
852
- }
853
- function traced(spanName) {
854
- return function(target, propertyKey, descriptor) {
855
- const originalMethod = descriptor.value;
856
- descriptor.value = async function(...args) {
857
- const request = args.find((arg) => arg && arg.tracer);
858
- if (!request?.tracer) {
859
- return originalMethod.apply(this, args);
860
- }
861
- const name = spanName || `${target.constructor.name}.${propertyKey}`;
862
- return createSpan(request, name, async (span) => {
863
- if (span) {
864
- span.setAttribute("db.operation", propertyKey);
865
- span.setAttribute("db.system", "mongodb");
866
- }
867
- return originalMethod.apply(this, args);
868
- });
869
- };
870
- return descriptor;
871
- };
872
- }
873
- function isTracingAvailable() {
874
- return isAvailable;
875
- }
876
- var require2, trace, context, SpanStatusCode, NodeTracerProvider, BatchSpanProcessor, OTLPTraceExporter, HttpInstrumentation, MongoDBInstrumentation, getNodeAutoInstrumentations, isAvailable, tracing_default;
877
- var init_tracing = __esm({
878
- "src/plugins/tracing.ts"() {
879
- require2 = createRequire(import.meta.url);
880
- isAvailable = false;
881
- try {
882
- const api = require2("@opentelemetry/api");
883
- trace = api.trace;
884
- context = api.context;
885
- SpanStatusCode = api.SpanStatusCode;
886
- const sdkNode = require2("@opentelemetry/sdk-node");
887
- NodeTracerProvider = sdkNode.NodeTracerProvider;
888
- BatchSpanProcessor = sdkNode.BatchSpanProcessor;
889
- const exporterTraceOtlp = require2("@opentelemetry/exporter-trace-otlp-http");
890
- OTLPTraceExporter = exporterTraceOtlp.OTLPTraceExporter;
891
- const instrHttp = require2("@opentelemetry/instrumentation-http");
892
- HttpInstrumentation = instrHttp.HttpInstrumentation;
893
- const instrMongo = require2("@opentelemetry/instrumentation-mongodb");
894
- MongoDBInstrumentation = instrMongo.MongoDBInstrumentation;
895
- const autoInstr = require2("@opentelemetry/auto-instrumentations-node");
896
- getNodeAutoInstrumentations = autoInstr.getNodeAutoInstrumentations;
897
- isAvailable = true;
898
- } catch (e) {
899
- }
900
- tracing_default = fp(tracingPlugin, {
901
- name: "arc-tracing",
902
- fastify: "5.x"
903
- });
904
- }
905
- });
906
- var gracefulShutdownPlugin, gracefulShutdown_default;
907
- var init_gracefulShutdown = __esm({
908
- "src/plugins/gracefulShutdown.ts"() {
909
- gracefulShutdownPlugin = async (fastify, opts = {}) => {
910
- const {
911
- timeout = 3e4,
912
- onShutdown,
913
- signals = ["SIGTERM", "SIGINT"],
914
- logEvents = true
915
- } = opts;
916
- let isShuttingDown = false;
917
- const shutdown = async (signal) => {
918
- if (isShuttingDown) {
919
- if (logEvents) {
920
- fastify.log?.warn?.({ signal }, "Shutdown already in progress, ignoring signal");
921
- }
922
- return;
923
- }
924
- isShuttingDown = true;
925
- if (logEvents) {
926
- fastify.log?.info?.({ signal, timeout }, "Shutdown signal received, starting graceful shutdown");
927
- }
928
- const forceExitTimer = setTimeout(() => {
929
- if (logEvents) {
930
- fastify.log?.error?.("Graceful shutdown timeout exceeded, forcing exit");
931
- }
932
- process.exit(1);
933
- }, timeout);
934
- forceExitTimer.unref();
935
- try {
936
- if (logEvents) {
937
- fastify.log?.info?.("Closing server to new connections");
938
- }
939
- await fastify.close();
940
- if (onShutdown) {
941
- if (logEvents) {
942
- fastify.log?.info?.("Running custom shutdown handler");
943
- }
944
- await onShutdown();
945
- }
946
- if (logEvents) {
947
- fastify.log?.info?.("Graceful shutdown complete");
948
- }
949
- clearTimeout(forceExitTimer);
950
- process.exit(0);
951
- } catch (err) {
952
- if (logEvents) {
953
- fastify.log?.error?.({ error: err.message }, "Error during shutdown");
954
- }
955
- clearTimeout(forceExitTimer);
956
- process.exit(1);
957
- }
958
- };
959
- for (const signal of signals) {
960
- process.on(signal, () => {
961
- void shutdown(signal);
962
- });
963
- }
964
- fastify.decorate("shutdown", async () => {
965
- await shutdown("MANUAL");
966
- });
967
- if (logEvents) {
968
- fastify.log?.debug?.({ signals }, "Graceful shutdown plugin registered");
969
- }
970
- };
971
- gracefulShutdown_default = fp(gracefulShutdownPlugin, {
972
- name: "arc-graceful-shutdown",
973
- fastify: "5.x"
974
- });
975
- }
976
- });
977
- async function errorHandlerPluginFn(fastify, options = {}) {
978
- const {
979
- includeStack = process.env.NODE_ENV !== "production",
980
- onError,
981
- errorMap = {}
982
- } = options;
983
- fastify.setErrorHandler(async (error, request, reply) => {
984
- if (onError) {
985
- try {
986
- await onError(error, request);
987
- } catch (callbackError) {
988
- request.log.error({ err: callbackError }, "Error in onError callback");
989
- }
990
- }
991
- const requestId = request.id;
992
- const response = {
993
- success: false,
994
- error: error.message || "Internal Server Error",
995
- code: "INTERNAL_ERROR",
996
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
997
- ...requestId && { requestId }
998
- };
999
- let statusCode = 500;
1000
- if (isArcError(error)) {
1001
- statusCode = error.statusCode;
1002
- response.code = error.code;
1003
- if (error.details) {
1004
- response.details = error.details;
1005
- }
1006
- if (error.requestId) {
1007
- response.requestId = error.requestId;
1008
- }
1009
- } else if ("validation" in error && Array.isArray(error.validation)) {
1010
- statusCode = 400;
1011
- response.code = "VALIDATION_ERROR";
1012
- response.error = "Validation failed";
1013
- response.details = {
1014
- errors: error.validation?.map((v) => ({
1015
- field: v.instancePath?.replace(/^\//, "") || v.params?.missingProperty || "unknown",
1016
- message: v.message || "Invalid value",
1017
- keyword: v.keyword
1018
- }))
1019
- };
1020
- } else if ("statusCode" in error && typeof error.statusCode === "number") {
1021
- statusCode = error.statusCode;
1022
- response.code = statusCodeToCode(statusCode);
1023
- } else if (error.name && errorMap[error.name]) {
1024
- const mapping = errorMap[error.name];
1025
- statusCode = mapping.statusCode;
1026
- response.code = mapping.code;
1027
- if (mapping.message) {
1028
- response.error = mapping.message;
1029
- }
1030
- } else if (error.name === "ValidationError" && "errors" in error) {
1031
- statusCode = 400;
1032
- response.code = "VALIDATION_ERROR";
1033
- const mongooseErrors = error.errors;
1034
- if (process.env.NODE_ENV === "production") {
1035
- response.details = { errorCount: Object.keys(mongooseErrors).length };
1036
- } else {
1037
- response.details = {
1038
- errors: Object.entries(mongooseErrors).map(([field, err]) => ({
1039
- field: err.path || field,
1040
- message: err.message
1041
- }))
1042
- };
1043
- }
1044
- } else if (error.name === "CastError") {
1045
- statusCode = 400;
1046
- response.code = "INVALID_ID";
1047
- response.error = "Invalid identifier format";
1048
- } else if (error.name === "MongoServerError" && error.code === 11e3) {
1049
- statusCode = 409;
1050
- response.code = "DUPLICATE_KEY";
1051
- response.error = "Resource already exists";
1052
- const keyValue = error.keyValue;
1053
- if (keyValue && process.env.NODE_ENV !== "production") {
1054
- response.details = { duplicateFields: Object.keys(keyValue) };
1055
- }
1056
- }
1057
- if (includeStack && error.stack) {
1058
- response.stack = error.stack;
1059
- }
1060
- if (statusCode >= 500) {
1061
- request.log.error({ err: error, statusCode }, "Server error");
1062
- } else if (statusCode >= 400) {
1063
- request.log.warn({ err: error, statusCode }, "Client error");
1064
- }
1065
- return reply.status(statusCode).send(response);
1066
- });
1067
- }
1068
- function statusCodeToCode(statusCode) {
1069
- const codes = {
1070
- 400: "BAD_REQUEST",
1071
- 401: "UNAUTHORIZED",
1072
- 403: "FORBIDDEN",
1073
- 404: "NOT_FOUND",
1074
- 405: "METHOD_NOT_ALLOWED",
1075
- 409: "CONFLICT",
1076
- 422: "UNPROCESSABLE_ENTITY",
1077
- 429: "RATE_LIMITED",
1078
- 500: "INTERNAL_ERROR",
1079
- 502: "BAD_GATEWAY",
1080
- 503: "SERVICE_UNAVAILABLE",
1081
- 504: "GATEWAY_TIMEOUT"
1082
- };
1083
- return codes[statusCode] ?? "ERROR";
1084
- }
1085
- var errorHandlerPlugin, errorHandler_default;
1086
- var init_errorHandler = __esm({
1087
- "src/plugins/errorHandler.ts"() {
1088
- init_errors();
1089
- errorHandlerPlugin = fp(errorHandlerPluginFn, {
1090
- name: "arc-error-handler",
1091
- fastify: "5.x"
1092
- });
1093
- errorHandler_default = errorHandlerPlugin;
1094
- }
1095
- });
1096
- function hasEvents(instance) {
1097
- return "events" in instance && instance.events != null && typeof instance.events.publish === "function";
1098
- }
1099
- var arcCorePlugin, arcCorePlugin_default;
1100
- var init_arcCorePlugin = __esm({
1101
- "src/core/arcCorePlugin.ts"() {
1102
- init_HookSystem();
1103
- init_ResourceRegistry();
1104
- arcCorePlugin = async (fastify, opts = {}) => {
1105
- const {
1106
- emitEvents = true,
1107
- hookSystem: hookSystem2,
1108
- registry,
1109
- useGlobalSingletons = false
1110
- } = opts;
1111
- const actualHookSystem = useGlobalSingletons ? hookSystem : hookSystem2 ?? new HookSystem();
1112
- const actualRegistry = useGlobalSingletons ? resourceRegistry : registry ?? new ResourceRegistry();
1113
- fastify.decorate("arc", {
1114
- hooks: actualHookSystem,
1115
- registry: actualRegistry,
1116
- emitEvents
1117
- });
1118
- if (emitEvents) {
1119
- const eventOperations = ["create", "update", "delete"];
1120
- for (const operation of eventOperations) {
1121
- actualHookSystem.after("*", operation, async (ctx) => {
1122
- if (!hasEvents(fastify)) return;
1123
- const eventType = `${ctx.resource}.${operation}d`;
1124
- const payload = {
1125
- resource: ctx.resource,
1126
- operation: ctx.operation,
1127
- data: ctx.result,
1128
- userId: ctx.user?.id ?? ctx.user?._id,
1129
- organizationId: ctx.context?.organizationId,
1130
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1131
- };
1132
- try {
1133
- await fastify.events.publish(eventType, payload);
1134
- } catch (error) {
1135
- fastify.log?.warn?.(
1136
- { eventType, error },
1137
- "Failed to emit event"
1138
- );
1139
- }
1140
- });
1141
- }
1142
- }
1143
- fastify.addHook("onClose", async () => {
1144
- actualHookSystem.clear();
1145
- actualRegistry._clear();
1146
- });
1147
- fastify.log?.info?.("✅ Arc core plugin enabled (instance-scoped hooks & registry)");
1148
- };
1149
- arcCorePlugin_default = fp(arcCorePlugin, {
1150
- name: "arc-core",
1151
- fastify: "5.x"
1152
- });
1153
- }
1154
- });
1155
-
1156
- // src/plugins/index.ts
1157
- var plugins_exports = {};
1158
- __export(plugins_exports, {
1159
- arcCorePlugin: () => arcCorePlugin_default,
1160
- arcCorePluginFn: () => arcCorePlugin,
1161
- createSpan: () => createSpan,
1162
- errorHandlerPlugin: () => errorHandler_default,
1163
- errorHandlerPluginFn: () => errorHandlerPlugin,
1164
- gracefulShutdownPlugin: () => gracefulShutdown_default,
1165
- gracefulShutdownPluginFn: () => gracefulShutdownPlugin,
1166
- healthPlugin: () => health_default,
1167
- healthPluginFn: () => healthPlugin,
1168
- isTracingAvailable: () => isTracingAvailable,
1169
- requestIdPlugin: () => requestId_default,
1170
- requestIdPluginFn: () => requestIdPlugin,
1171
- traced: () => traced,
1172
- tracingPlugin: () => tracing_default
1173
- });
1174
- var init_plugins = __esm({
1175
- "src/plugins/index.ts"() {
1176
- init_requestId();
1177
- init_health();
1178
- init_tracing();
1179
- init_gracefulShutdown();
1180
- init_errorHandler();
1181
- init_arcCorePlugin();
1182
- }
1183
- });
1184
- function parseExpiresIn(input, defaultValue) {
1185
- if (!input) return defaultValue;
1186
- if (/^\d+$/.test(input)) return parseInt(input, 10);
1187
- const match = /^(\d+)\s*([smhd])$/i.exec(input);
1188
- if (!match) return defaultValue;
1189
- const value = parseInt(match[1], 10);
1190
- const unit = match[2].toLowerCase();
1191
- const multipliers = { s: 1, m: 60, h: 3600, d: 86400 };
1192
- return value * (multipliers[unit] ?? 1);
1193
- }
1194
- function extractBearerToken(request) {
1195
- const auth = request.headers.authorization;
1196
- if (!auth?.startsWith("Bearer ")) return null;
1197
- return auth.slice(7);
1198
- }
1199
- var authPlugin, authPlugin_default;
1200
- var init_authPlugin = __esm({
1201
- "src/auth/authPlugin.ts"() {
1202
- authPlugin = async (fastify, opts = {}) => {
1203
- const { jwt: jwtConfig, authenticate: appAuthenticator, onFailure, userProperty = "user" } = opts;
1204
- let jwtContext = null;
1205
- if (jwtConfig?.secret) {
1206
- if (jwtConfig.secret.length < 32) {
1207
- throw new Error(
1208
- `JWT secret must be at least 32 characters (current: ${jwtConfig.secret.length}).
1209
- Use a strong random secret for production.`
1210
- );
1211
- }
1212
- const jwtPlugin = await import('@fastify/jwt');
1213
- await fastify.register(jwtPlugin.default ?? jwtPlugin, {
1214
- secret: jwtConfig.secret,
1215
- sign: {
1216
- expiresIn: jwtConfig.expiresIn ?? "15m",
1217
- ...jwtConfig.sign ?? {}
1218
- },
1219
- verify: { ...jwtConfig.verify ?? {} }
1220
- });
1221
- const fastifyWithJwt = fastify;
1222
- jwtContext = {
1223
- verify: (token) => {
1224
- return fastifyWithJwt.jwt.verify(token);
1225
- },
1226
- sign: (payload, options) => {
1227
- return fastifyWithJwt.jwt.sign(payload, options);
1228
- },
1229
- decode: (token) => {
1230
- try {
1231
- return fastifyWithJwt.jwt.decode(token);
1232
- } catch {
1233
- return null;
1234
- }
1235
- }
1236
- };
1237
- fastify.log.info("Auth: JWT infrastructure enabled");
1238
- }
1239
- const authContext = {
1240
- jwt: jwtContext,
1241
- fastify
1242
- };
1243
- const authenticate = async (request, reply) => {
1244
- try {
1245
- let user = null;
1246
- if (appAuthenticator) {
1247
- user = await appAuthenticator(request, authContext);
1248
- } else if (jwtContext) {
1249
- const token = extractBearerToken(request);
1250
- if (token) {
1251
- const decoded = jwtContext.verify(token);
1252
- user = decoded;
1253
- }
1254
- } else {
1255
- throw new Error(
1256
- "No authenticator configured. Provide auth.authenticate function or auth.jwt.secret."
1257
- );
1258
- }
1259
- if (!user) {
1260
- throw new Error("Authentication required");
1261
- }
1262
- request[userProperty] = user;
1263
- } catch (err) {
1264
- const error = err instanceof Error ? err : new Error(String(err));
1265
- if (onFailure) {
1266
- await onFailure(request, reply, error);
1267
- return;
1268
- }
1269
- const message = process.env.NODE_ENV === "production" ? "Authentication required" : error.message;
1270
- reply.code(401).send({
1271
- success: false,
1272
- error: "Unauthorized",
1273
- message
1274
- });
1275
- }
1276
- };
1277
- const refreshSecret = jwtConfig?.refreshSecret ?? jwtConfig?.secret;
1278
- const accessExpiresIn = jwtConfig?.expiresIn ?? "15m";
1279
- const refreshExpiresIn = jwtConfig?.refreshExpiresIn ?? "7d";
1280
- const issueTokens = (payload, options) => {
1281
- if (!jwtContext) {
1282
- throw new Error("JWT not configured. Provide auth.jwt.secret to use issueTokens.");
1283
- }
1284
- const accessTtl = options?.expiresIn ?? accessExpiresIn;
1285
- const refreshTtl = options?.refreshExpiresIn ?? refreshExpiresIn;
1286
- const accessToken = jwtContext.sign(payload, { expiresIn: accessTtl });
1287
- const refreshPayload = payload.id ? { id: payload.id, type: "refresh" } : payload._id ? { id: payload._id, type: "refresh" } : { ...payload, type: "refresh" };
1288
- let refreshToken;
1289
- if (refreshSecret) {
1290
- const fastifyWithJwt = fastify;
1291
- refreshToken = fastifyWithJwt.jwt.sign(refreshPayload, {
1292
- expiresIn: refreshTtl,
1293
- // Use refresh secret if different from main secret
1294
- ...refreshSecret !== jwtConfig?.secret ? { secret: refreshSecret } : {}
1295
- });
1296
- }
1297
- return {
1298
- accessToken,
1299
- refreshToken,
1300
- expiresIn: parseExpiresIn(accessTtl, 900),
1301
- refreshExpiresIn: refreshToken ? parseExpiresIn(refreshTtl, 604800) : void 0,
1302
- tokenType: "Bearer"
1303
- };
1304
- };
1305
- const verifyRefreshToken = (token) => {
1306
- if (!jwtContext) {
1307
- throw new Error("JWT not configured. Provide auth.jwt.secret to use verifyRefreshToken.");
1308
- }
1309
- const fastifyWithJwt = fastify;
1310
- return fastifyWithJwt.jwt.verify(token, {
1311
- ...refreshSecret !== jwtConfig?.secret ? { secret: refreshSecret } : {}
1312
- });
1313
- };
1314
- const authorize = (...allowedRoles) => {
1315
- return async (request, reply) => {
1316
- const user = request[userProperty];
1317
- if (!user) {
1318
- reply.code(401).send({
1319
- success: false,
1320
- error: "Unauthorized",
1321
- message: "No user context"
1322
- });
1323
- return;
1324
- }
1325
- const userRoles = user.roles ?? [];
1326
- if (allowedRoles.length === 1 && allowedRoles[0] === "*") {
1327
- return;
1328
- }
1329
- const hasRole = allowedRoles.some((role) => userRoles.includes(role));
1330
- if (!hasRole) {
1331
- reply.code(403).send({
1332
- success: false,
1333
- error: "Forbidden",
1334
- message: `Requires one of: ${allowedRoles.join(", ")}`
1335
- });
1336
- return;
1337
- }
1338
- };
1339
- };
1340
- const authHelpers = {
1341
- jwt: jwtContext,
1342
- issueTokens,
1343
- verifyRefreshToken
1344
- };
1345
- fastify.decorate("authenticate", authenticate);
1346
- fastify.decorate("authorize", authorize);
1347
- fastify.decorate("auth", authHelpers);
1348
- fastify.log.info(
1349
- `Auth: Plugin registered (jwt=${!!jwtContext}, customAuth=${!!appAuthenticator})`
1350
- );
1351
- };
1352
- authPlugin_default = fp(authPlugin, {
1353
- name: "arc-auth",
1354
- fastify: "5.x"
1355
- });
1356
- }
1357
- });
1358
-
1359
- // src/auth/index.ts
1360
- var auth_exports = {};
1361
- __export(auth_exports, {
1362
- authPlugin: () => authPlugin_default,
1363
- authPluginFn: () => authPlugin
1364
- });
1365
- var init_auth = __esm({
1366
- "src/auth/index.ts"() {
1367
- init_authPlugin();
1368
- }
1369
- });
1370
-
1371
- // src/adapters/types.ts
1372
- function isMongooseModel(value) {
1373
- return typeof value === "function" && value.prototype && "modelName" in value && "schema" in value;
1374
- }
1375
- function isRepository(value) {
1376
- return typeof value === "object" && value !== null && "getAll" in value && "getById" in value && "create" in value && "update" in value && "delete" in value;
1377
- }
1378
-
1379
- // src/adapters/mongoose.ts
1380
- var MongooseAdapter = class {
1381
- type = "mongoose";
1382
- name;
1383
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1384
- model;
1385
- repository;
1386
- constructor(options) {
1387
- if (!isMongooseModel(options.model)) {
1388
- throw new TypeError(
1389
- "MongooseAdapter: Invalid model. Expected Mongoose Model instance.\nUsage: createMongooseAdapter({ model: YourModel, repository: yourRepo })"
1390
- );
1391
- }
1392
- if (!isRepository(options.repository)) {
1393
- throw new TypeError(
1394
- "MongooseAdapter: Invalid repository. Expected CrudRepository instance.\nUsage: createMongooseAdapter({ model: YourModel, repository: yourRepo })"
1395
- );
1396
- }
1397
- this.model = options.model;
1398
- this.repository = options.repository;
1399
- this.name = `MongooseAdapter<${options.model.modelName}>`;
1400
- }
1401
- /**
1402
- * Get schema metadata from Mongoose model
1403
- */
1404
- getSchemaMetadata() {
1405
- const schema = this.model.schema;
1406
- const paths = schema.paths;
1407
- const fields = {};
1408
- for (const [fieldName, schemaType] of Object.entries(paths)) {
1409
- if (fieldName.startsWith("_") && fieldName !== "_id") continue;
1410
- const typeInfo = schemaType;
1411
- const mongooseType = typeInfo.instance || "Mixed";
1412
- const typeMap = {
1413
- String: "string",
1414
- Number: "number",
1415
- Boolean: "boolean",
1416
- Date: "date",
1417
- ObjectID: "objectId",
1418
- Array: "array",
1419
- Mixed: "object",
1420
- Buffer: "object",
1421
- Embedded: "object"
1422
- };
1423
- fields[fieldName] = {
1424
- type: typeMap[mongooseType] ?? "object",
1425
- required: !!typeInfo.isRequired,
1426
- ref: typeInfo.options?.ref
1427
- };
1428
- }
1429
- return {
1430
- name: this.model.modelName,
1431
- fields,
1432
- relations: this.extractRelations(paths)
1433
- };
1434
- }
1435
- /**
1436
- * Generate OpenAPI schemas from Mongoose model
1437
- */
1438
- generateSchemas(schemaOptions) {
1439
- try {
1440
- const schema = this.model.schema;
1441
- const paths = schema.paths;
1442
- const properties = {};
1443
- const required = [];
1444
- const fieldRules = schemaOptions?.fieldRules || {};
1445
- const blockedFields = new Set(
1446
- Object.entries(fieldRules).filter(([, rules]) => rules.systemManaged || rules.hidden).map(([field]) => field)
1447
- );
1448
- for (const [fieldName, schemaType] of Object.entries(paths)) {
1449
- if (fieldName.startsWith("__")) continue;
1450
- if (blockedFields.has(fieldName)) continue;
1451
- const typeInfo = schemaType;
1452
- properties[fieldName] = this.mongooseTypeToOpenApi(typeInfo);
1453
- if (typeInfo.isRequired) {
1454
- required.push(fieldName);
1455
- }
1456
- }
1457
- const baseSchema = {
1458
- type: "object",
1459
- properties,
1460
- required: required.length > 0 ? required : void 0
1461
- };
1462
- return {
1463
- create: {
1464
- body: {
1465
- ...baseSchema,
1466
- // Remove system-managed fields from create
1467
- properties: Object.fromEntries(
1468
- Object.entries(properties).filter(
1469
- ([field]) => !["_id", "createdAt", "updatedAt", "deletedAt"].includes(field)
1470
- )
1471
- )
1472
- }
1473
- },
1474
- update: {
1475
- body: {
1476
- ...baseSchema,
1477
- // All fields optional for PATCH
1478
- required: void 0,
1479
- properties: Object.fromEntries(
1480
- Object.entries(properties).filter(
1481
- ([field]) => !["_id", "createdAt", "updatedAt", "deletedAt"].includes(field)
1482
- )
1483
- )
1484
- }
1485
- },
1486
- response: {
1487
- type: "object",
1488
- properties
1489
- }
1490
- };
1491
- } catch {
1492
- return null;
1493
- }
1494
- }
1495
- /**
1496
- * Extract relation metadata
1497
- */
1498
- extractRelations(paths) {
1499
- const relations = {};
1500
- for (const [fieldName, schemaType] of Object.entries(paths)) {
1501
- const ref = schemaType.options?.ref;
1502
- if (ref) {
1503
- relations[fieldName] = {
1504
- type: "one-to-one",
1505
- // Mongoose refs are typically one-to-one
1506
- target: ref,
1507
- foreignKey: fieldName
1508
- };
1509
- }
1510
- }
1511
- return Object.keys(relations).length > 0 ? relations : void 0;
1512
- }
1513
- /**
1514
- * Convert Mongoose type to OpenAPI type
1515
- */
1516
- mongooseTypeToOpenApi(typeInfo) {
1517
- const instance = typeInfo.instance;
1518
- const options = typeInfo.options || {};
1519
- const baseType = {};
1520
- switch (instance) {
1521
- case "String":
1522
- baseType.type = "string";
1523
- if (options.enum) baseType.enum = options.enum;
1524
- if (options.minlength) baseType.minLength = options.minlength;
1525
- if (options.maxlength) baseType.maxLength = options.maxlength;
1526
- break;
1527
- case "Number":
1528
- baseType.type = "number";
1529
- if (options.min !== void 0) baseType.minimum = options.min;
1530
- if (options.max !== void 0) baseType.maximum = options.max;
1531
- break;
1532
- case "Boolean":
1533
- baseType.type = "boolean";
1534
- break;
1535
- case "Date":
1536
- baseType.type = "string";
1537
- baseType.format = "date-time";
1538
- break;
1539
- case "ObjectID":
1540
- baseType.type = "string";
1541
- baseType.pattern = "^[a-f\\d]{24}$";
1542
- break;
1543
- case "Array":
1544
- baseType.type = "array";
1545
- baseType.items = { type: "string" };
1546
- break;
1547
- default:
1548
- baseType.type = "object";
1549
- }
1550
- return baseType;
1551
- }
1552
- };
1553
- function createMongooseAdapter(options) {
1554
- return new MongooseAdapter(options);
1555
- }
1556
-
1557
- // src/adapters/prisma.ts
1558
- var PrismaQueryParser = class {
1559
- maxLimit;
1560
- defaultLimit;
1561
- softDeleteEnabled;
1562
- softDeleteField;
1563
- /** Map Arc operators to Prisma operators */
1564
- operatorMap = {
1565
- $eq: "equals",
1566
- $ne: "not",
1567
- $gt: "gt",
1568
- $gte: "gte",
1569
- $lt: "lt",
1570
- $lte: "lte",
1571
- $in: "in",
1572
- $nin: "notIn",
1573
- $regex: "contains",
1574
- $exists: void 0
1575
- // Handled specially
1576
- };
1577
- constructor(options = {}) {
1578
- this.maxLimit = options.maxLimit ?? 1e3;
1579
- this.defaultLimit = options.defaultLimit ?? 20;
1580
- this.softDeleteEnabled = options.softDeleteEnabled ?? true;
1581
- this.softDeleteField = options.softDeleteField ?? "deletedAt";
1582
- }
1583
- /**
1584
- * Parse URL query parameters (delegates to ArcQueryParser format)
1585
- */
1586
- parse(query) {
1587
- const q = query ?? {};
1588
- const page = this.parseNumber(q.page, 1);
1589
- const limit = Math.min(this.parseNumber(q.limit, this.defaultLimit), this.maxLimit);
1590
- return {
1591
- filters: this.parseFilters(q),
1592
- limit,
1593
- page,
1594
- sort: this.parseSort(q.sort),
1595
- search: q.search,
1596
- select: this.parseSelect(q.select)
1597
- };
1598
- }
1599
- /**
1600
- * Convert ParsedQuery to Prisma query options
1601
- */
1602
- toPrismaQuery(parsed, policyFilters) {
1603
- const where = {};
1604
- if (parsed.filters) {
1605
- Object.assign(where, this.translateFilters(parsed.filters));
1606
- }
1607
- if (policyFilters) {
1608
- Object.assign(where, this.translateFilters(policyFilters));
1609
- }
1610
- if (this.softDeleteEnabled) {
1611
- where[this.softDeleteField] = null;
1612
- }
1613
- const orderBy = parsed.sort ? Object.entries(parsed.sort).map(([field, dir]) => ({
1614
- [field]: dir === 1 ? "asc" : "desc"
1615
- })) : void 0;
1616
- const take = parsed.limit ?? this.defaultLimit;
1617
- const skip = parsed.page ? (parsed.page - 1) * take : 0;
1618
- const select = parsed.select ? Object.fromEntries(
1619
- Object.entries(parsed.select).filter(([, v]) => v === 1).map(([k]) => [k, true])
1620
- ) : void 0;
1621
- return {
1622
- where: Object.keys(where).length > 0 ? where : void 0,
1623
- orderBy: orderBy && orderBy.length > 0 ? orderBy : void 0,
1624
- take,
1625
- skip,
1626
- select: select && Object.keys(select).length > 0 ? select : void 0
1627
- };
1628
- }
1629
- /**
1630
- * Translate Arc/MongoDB-style filters to Prisma where clause
1631
- */
1632
- translateFilters(filters) {
1633
- const result = {};
1634
- for (const [field, value] of Object.entries(filters)) {
1635
- if (value === null || value === void 0) continue;
1636
- if (typeof value === "object" && !Array.isArray(value)) {
1637
- const prismaCondition = {};
1638
- for (const [op, opValue] of Object.entries(value)) {
1639
- if (op === "$exists") {
1640
- result[field] = opValue ? { not: null } : null;
1641
- continue;
1642
- }
1643
- const prismaOp = this.operatorMap[op];
1644
- if (prismaOp) {
1645
- prismaCondition[prismaOp] = opValue;
1646
- }
1647
- }
1648
- if (Object.keys(prismaCondition).length > 0) {
1649
- result[field] = prismaCondition;
1650
- }
1651
- } else {
1652
- result[field] = value;
1653
- }
1654
- }
1655
- return result;
1656
- }
1657
- parseNumber(value, defaultValue) {
1658
- if (value === void 0 || value === null) return defaultValue;
1659
- const num = parseInt(String(value), 10);
1660
- return Number.isNaN(num) ? defaultValue : Math.max(1, num);
1661
- }
1662
- parseSort(value) {
1663
- if (!value) return void 0;
1664
- const sortStr = String(value);
1665
- const result = {};
1666
- for (const field of sortStr.split(",")) {
1667
- const trimmed = field.trim();
1668
- if (!trimmed || !/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test(trimmed)) continue;
1669
- if (trimmed.startsWith("-")) {
1670
- result[trimmed.slice(1)] = -1;
1671
- } else {
1672
- result[trimmed] = 1;
1673
- }
1674
- }
1675
- return Object.keys(result).length > 0 ? result : void 0;
1676
- }
1677
- parseSelect(value) {
1678
- if (!value) return void 0;
1679
- const result = {};
1680
- for (const field of String(value).split(",")) {
1681
- const trimmed = field.trim();
1682
- if (!trimmed || !/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test(trimmed)) continue;
1683
- result[trimmed.startsWith("-") ? trimmed.slice(1) : trimmed] = trimmed.startsWith("-") ? 0 : 1;
1684
- }
1685
- return Object.keys(result).length > 0 ? result : void 0;
1686
- }
1687
- parseFilters(query) {
1688
- const reserved = /* @__PURE__ */ new Set(["page", "limit", "sort", "search", "select", "populate", "after", "cursor"]);
1689
- const filters = {};
1690
- const operators = {
1691
- eq: "$eq",
1692
- ne: "$ne",
1693
- gt: "$gt",
1694
- gte: "$gte",
1695
- lt: "$lt",
1696
- lte: "$lte",
1697
- in: "$in",
1698
- nin: "$nin",
1699
- like: "$regex",
1700
- contains: "$regex",
1701
- exists: "$exists"
1702
- };
1703
- for (const [key, value] of Object.entries(query)) {
1704
- if (reserved.has(key) || value === void 0 || value === null) continue;
1705
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_.]*)(?:\[([a-z]+)\])?$/);
1706
- if (!match) continue;
1707
- const [, fieldName, operator] = match;
1708
- if (!fieldName) continue;
1709
- if (operator && operators[operator]) {
1710
- if (!filters[fieldName]) filters[fieldName] = {};
1711
- filters[fieldName][operators[operator]] = this.coerceValue(value, operator);
1712
- } else if (!operator) {
1713
- filters[fieldName] = this.coerceValue(value);
1714
- }
1715
- }
1716
- return filters;
1717
- }
1718
- coerceValue(value, operator) {
1719
- if (operator === "in" || operator === "nin") {
1720
- if (Array.isArray(value)) return value.map((v) => this.coerceValue(v));
1721
- if (typeof value === "string" && value.includes(",")) {
1722
- return value.split(",").map((v) => this.coerceValue(v.trim()));
1723
- }
1724
- return [this.coerceValue(value)];
1725
- }
1726
- if (operator === "exists") {
1727
- return String(value).toLowerCase() === "true" || value === "1";
1728
- }
1729
- if (value === "true") return true;
1730
- if (value === "false") return false;
1731
- if (value === "null") return null;
1732
- if (typeof value === "string") {
1733
- const num = Number(value);
1734
- if (!Number.isNaN(num) && value.trim() !== "") return num;
1735
- }
1736
- return value;
1737
- }
1738
- };
1739
- var PrismaAdapter = class {
1740
- type = "prisma";
1741
- name;
1742
- repository;
1743
- queryParser;
1744
- client;
1745
- modelName;
1746
- dmmf;
1747
- softDeleteEnabled;
1748
- softDeleteField;
1749
- constructor(options) {
1750
- this.client = options.client;
1751
- this.modelName = options.modelName;
1752
- this.repository = options.repository;
1753
- this.dmmf = options.dmmf;
1754
- this.name = `prisma:${options.modelName}`;
1755
- this.softDeleteEnabled = options.softDeleteEnabled ?? true;
1756
- this.softDeleteField = options.softDeleteField ?? "deletedAt";
1757
- this.queryParser = options.queryParser ?? new PrismaQueryParser({
1758
- softDeleteEnabled: this.softDeleteEnabled,
1759
- softDeleteField: this.softDeleteField
1760
- });
1761
- }
1762
- /**
1763
- * Parse URL query parameters and convert to Prisma query options
1764
- */
1765
- parseQuery(query, policyFilters) {
1766
- const parsed = this.queryParser.parse(query);
1767
- return this.queryParser.toPrismaQuery(parsed, policyFilters);
1768
- }
1769
- /**
1770
- * Apply policy filters to existing Prisma where clause
1771
- * Used for multi-tenant, ownership, and other security filters
1772
- */
1773
- applyPolicyFilters(where, policyFilters) {
1774
- return { ...where, ...policyFilters };
1775
- }
1776
- generateSchemas(options) {
1777
- if (!this.dmmf) return null;
1778
- try {
1779
- const model = this.dmmf.datamodel?.models?.find(
1780
- (m) => m.name.toLowerCase() === this.modelName.toLowerCase()
1781
- );
1782
- if (!model) return null;
1783
- const entitySchema = this.buildEntitySchema(model, options);
1784
- const createBodySchema = this.buildCreateSchema(model, options);
1785
- const updateBodySchema = this.buildUpdateSchema(model, options);
1786
- return {
1787
- entity: entitySchema,
1788
- createBody: createBodySchema,
1789
- updateBody: updateBodySchema,
1790
- params: {
1791
- type: "object",
1792
- properties: {
1793
- id: { type: "string" }
1794
- },
1795
- required: ["id"]
1796
- },
1797
- listQuery: {
1798
- type: "object",
1799
- properties: {
1800
- page: { type: "number", minimum: 1, description: "Page number for pagination" },
1801
- limit: { type: "number", minimum: 1, maximum: 100, description: "Items per page" },
1802
- sort: { type: "string", description: 'Sort field (e.g., "name", "-createdAt")' }
1803
- // Note: Actual filtering requires custom query parser implementation
1804
- // This is placeholder documentation only
1805
- }
1806
- }
1807
- };
1808
- } catch {
1809
- return null;
1810
- }
1811
- }
1812
- getSchemaMetadata() {
1813
- if (!this.dmmf) return null;
1814
- try {
1815
- const model = this.dmmf.datamodel?.models?.find(
1816
- (m) => m.name.toLowerCase() === this.modelName.toLowerCase()
1817
- );
1818
- if (!model) return null;
1819
- const fields = {};
1820
- for (const field of model.fields) {
1821
- fields[field.name] = this.convertPrismaFieldToMetadata(field);
1822
- }
1823
- return {
1824
- name: model.name,
1825
- fields,
1826
- indexes: model.uniqueIndexes?.map((idx) => ({
1827
- fields: idx.fields,
1828
- unique: true
1829
- }))
1830
- };
1831
- } catch (err) {
1832
- return null;
1833
- }
1834
- }
1835
- async validate(data) {
1836
- if (!data || typeof data !== "object") {
1837
- return {
1838
- valid: false,
1839
- errors: [{ field: "root", message: "Data must be an object" }]
1840
- };
1841
- }
1842
- if (this.dmmf) {
1843
- try {
1844
- const model = this.dmmf.datamodel?.models?.find(
1845
- (m) => m.name.toLowerCase() === this.modelName.toLowerCase()
1846
- );
1847
- if (model) {
1848
- const requiredFields = model.fields.filter(
1849
- (f) => f.isRequired && !f.hasDefaultValue && !f.isGenerated
1850
- );
1851
- const errors = [];
1852
- for (const field of requiredFields) {
1853
- if (!(field.name in data)) {
1854
- errors.push({
1855
- field: field.name,
1856
- message: `${field.name} is required`
1857
- });
1858
- }
1859
- }
1860
- if (errors.length > 0) {
1861
- return { valid: false, errors };
1862
- }
1863
- }
1864
- } catch (err) {
1865
- }
1866
- }
1867
- return { valid: true };
1868
- }
1869
- async healthCheck() {
1870
- try {
1871
- const delegateName = this.modelName.charAt(0).toLowerCase() + this.modelName.slice(1);
1872
- const delegate = this.client[delegateName];
1873
- if (!delegate) {
1874
- return false;
1875
- }
1876
- await delegate.findMany({ take: 1 });
1877
- return true;
1878
- } catch (err) {
1879
- return false;
1880
- }
1881
- }
1882
- async close() {
1883
- try {
1884
- await this.client.$disconnect();
1885
- } catch (err) {
1886
- }
1887
- }
1888
- // ============================================================================
1889
- // Private Helper Methods
1890
- // ============================================================================
1891
- buildEntitySchema(model, options) {
1892
- const properties = {};
1893
- const required = [];
1894
- for (const field of model.fields) {
1895
- if (this.shouldSkipField(field, options)) continue;
1896
- properties[field.name] = this.convertPrismaFieldToJsonSchema(field);
1897
- if (field.isRequired && !field.hasDefaultValue) {
1898
- required.push(field.name);
1899
- }
1900
- }
1901
- return {
1902
- type: "object",
1903
- properties,
1904
- ...required.length > 0 && { required }
1905
- };
1906
- }
1907
- buildCreateSchema(model, options) {
1908
- const properties = {};
1909
- const required = [];
1910
- for (const field of model.fields) {
1911
- if (field.isGenerated || field.relationName) continue;
1912
- if (this.shouldSkipField(field, options)) continue;
1913
- properties[field.name] = this.convertPrismaFieldToJsonSchema(field);
1914
- if (field.isRequired && !field.hasDefaultValue) {
1915
- required.push(field.name);
1916
- }
1917
- }
1918
- return {
1919
- type: "object",
1920
- properties,
1921
- ...required.length > 0 && { required }
1922
- };
1923
- }
1924
- buildUpdateSchema(model, options) {
1925
- const properties = {};
1926
- for (const field of model.fields) {
1927
- if (field.isGenerated || field.isId || field.relationName) continue;
1928
- if (this.shouldSkipField(field, options)) continue;
1929
- properties[field.name] = this.convertPrismaFieldToJsonSchema(field);
1930
- }
1931
- return {
1932
- type: "object",
1933
- properties
1934
- };
1935
- }
1936
- shouldSkipField(field, options) {
1937
- if (options?.excludeFields?.includes(field.name)) {
1938
- return true;
1939
- }
1940
- if (field.name.startsWith("_")) {
1941
- return true;
1942
- }
1943
- return false;
1944
- }
1945
- convertPrismaFieldToJsonSchema(field) {
1946
- const schema = {};
1947
- switch (field.type) {
1948
- case "String":
1949
- schema.type = "string";
1950
- break;
1951
- case "Int":
1952
- case "BigInt":
1953
- schema.type = "integer";
1954
- break;
1955
- case "Float":
1956
- case "Decimal":
1957
- schema.type = "number";
1958
- break;
1959
- case "Boolean":
1960
- schema.type = "boolean";
1961
- break;
1962
- case "DateTime":
1963
- schema.type = "string";
1964
- schema.format = "date-time";
1965
- break;
1966
- case "Json":
1967
- schema.type = "object";
1968
- break;
1969
- default:
1970
- if (field.kind === "enum") {
1971
- schema.type = "string";
1972
- if (this.dmmf?.datamodel?.enums) {
1973
- const enumDef = this.dmmf.datamodel.enums.find((e) => e.name === field.type);
1974
- if (enumDef) {
1975
- schema.enum = enumDef.values.map((v) => v.name);
1976
- }
1977
- }
1978
- } else {
1979
- schema.type = "string";
1980
- }
1981
- }
1982
- if (field.isList) {
1983
- return {
1984
- type: "array",
1985
- items: schema
1986
- };
1987
- }
1988
- if (field.documentation) {
1989
- schema.description = field.documentation;
1990
- }
1991
- return schema;
1992
- }
1993
- convertPrismaFieldToMetadata(field) {
1994
- const metadata = {
1995
- type: this.mapPrismaTypeToMetadataType(field.type, field.kind),
1996
- required: field.isRequired,
1997
- array: field.isList
1998
- };
1999
- if (field.isUnique) {
2000
- metadata.unique = true;
2001
- }
2002
- if (field.hasDefaultValue) {
2003
- metadata.default = field.default;
2004
- }
2005
- if (field.documentation) {
2006
- metadata.description = field.documentation;
2007
- }
2008
- if (field.relationName) {
2009
- metadata.ref = field.type;
2010
- }
2011
- return metadata;
2012
- }
2013
- mapPrismaTypeToMetadataType(type, kind) {
2014
- if (kind === "enum") return "enum";
2015
- switch (type) {
2016
- case "String":
2017
- return "string";
2018
- case "Int":
2019
- case "BigInt":
2020
- case "Float":
2021
- case "Decimal":
2022
- return "number";
2023
- case "Boolean":
2024
- return "boolean";
2025
- case "DateTime":
2026
- return "date";
2027
- case "Json":
2028
- return "object";
2029
- default:
2030
- return "string";
2031
- }
2032
- }
2033
- };
2034
- function createPrismaAdapter(options) {
2035
- return new PrismaAdapter(options);
2036
- }
2037
-
2038
- // src/types/index.ts
2039
- function getUserId(user) {
2040
- if (!user) return void 0;
2041
- const id = user.id ?? user._id;
2042
- return id ? String(id) : void 0;
2043
- }
2044
-
2045
- // src/core/BaseController.ts
2046
- init_HookSystem();
2047
-
2048
- // src/utils/queryParser.ts
2049
- var DANGEROUS_REGEX_PATTERNS = /(\{[0-9,]+\}|\*\+|\+\+|\?\+|(\(.+\))\+|\(\?\:|\\[0-9]|(\[.+\]).+(\[.+\]))/;
2050
- var MAX_REGEX_LENGTH = 500;
2051
- var MAX_SEARCH_LENGTH = 200;
2052
- var MAX_FILTER_DEPTH = 10;
2053
- var MAX_LIMIT = 1e3;
2054
- var DEFAULT_LIMIT = 20;
2055
- var ArcQueryParser = class {
2056
- maxLimit;
2057
- defaultLimit;
2058
- maxRegexLength;
2059
- maxSearchLength;
2060
- maxFilterDepth;
2061
- /** Supported filter operators */
2062
- operators = {
2063
- eq: "$eq",
2064
- ne: "$ne",
2065
- gt: "$gt",
2066
- gte: "$gte",
2067
- lt: "$lt",
2068
- lte: "$lte",
2069
- in: "$in",
2070
- nin: "$nin",
2071
- like: "$regex",
2072
- contains: "$regex",
2073
- regex: "$regex",
2074
- exists: "$exists"
2075
- };
2076
- constructor(options = {}) {
2077
- this.maxLimit = options.maxLimit ?? MAX_LIMIT;
2078
- this.defaultLimit = options.defaultLimit ?? DEFAULT_LIMIT;
2079
- this.maxRegexLength = options.maxRegexLength ?? MAX_REGEX_LENGTH;
2080
- this.maxSearchLength = options.maxSearchLength ?? MAX_SEARCH_LENGTH;
2081
- this.maxFilterDepth = options.maxFilterDepth ?? MAX_FILTER_DEPTH;
2082
- }
2083
- /**
2084
- * Parse URL query parameters into structured query options
2085
- */
2086
- parse(query) {
2087
- const q = query ?? {};
2088
- const page = this.parseNumber(q.page, 1);
2089
- const limit = Math.min(this.parseNumber(q.limit, this.defaultLimit), this.maxLimit);
2090
- const after = this.parseString(q.after ?? q.cursor);
2091
- const sort = this.parseSort(q.sort);
2092
- const populate = this.parseString(q.populate);
2093
- const search = this.parseSearch(q.search);
2094
- const select = this.parseSelect(q.select);
2095
- const filters = this.parseFilters(q);
2096
- return {
2097
- filters,
2098
- limit,
2099
- sort,
2100
- populate,
2101
- search,
2102
- page: after ? void 0 : page,
2103
- after,
2104
- select
2105
- };
2106
- }
2107
- // ============================================================================
2108
- // Parse Helpers
2109
- // ============================================================================
2110
- parseNumber(value, defaultValue) {
2111
- if (value === void 0 || value === null) return defaultValue;
2112
- const num = parseInt(String(value), 10);
2113
- return Number.isNaN(num) ? defaultValue : Math.max(1, num);
2114
- }
2115
- parseString(value) {
2116
- if (value === void 0 || value === null) return void 0;
2117
- const str = String(value).trim();
2118
- return str.length > 0 ? str : void 0;
2119
- }
2120
- parseSort(value) {
2121
- if (!value) return void 0;
2122
- const sortStr = String(value);
2123
- const result = {};
2124
- for (const field of sortStr.split(",")) {
2125
- const trimmed = field.trim();
2126
- if (!trimmed) continue;
2127
- if (!/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test(trimmed)) continue;
2128
- if (trimmed.startsWith("-")) {
2129
- result[trimmed.slice(1)] = -1;
2130
- } else {
2131
- result[trimmed] = 1;
2132
- }
2133
- }
2134
- return Object.keys(result).length > 0 ? result : void 0;
2135
- }
2136
- parseSearch(value) {
2137
- if (!value) return void 0;
2138
- const search = String(value).trim();
2139
- if (search.length === 0) return void 0;
2140
- if (search.length > this.maxSearchLength) {
2141
- return search.slice(0, this.maxSearchLength);
2142
- }
2143
- return search;
2144
- }
2145
- parseSelect(value) {
2146
- if (!value) return void 0;
2147
- const selectStr = String(value);
2148
- const result = {};
2149
- for (const field of selectStr.split(",")) {
2150
- const trimmed = field.trim();
2151
- if (!trimmed) continue;
2152
- if (!/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test(trimmed)) continue;
2153
- if (trimmed.startsWith("-")) {
2154
- result[trimmed.slice(1)] = 0;
2155
- } else {
2156
- result[trimmed] = 1;
2157
- }
2158
- }
2159
- return Object.keys(result).length > 0 ? result : void 0;
2160
- }
2161
- parseFilters(query) {
2162
- const reservedKeys = /* @__PURE__ */ new Set([
2163
- "page",
2164
- "limit",
2165
- "sort",
2166
- "populate",
2167
- "search",
2168
- "select",
2169
- "after",
2170
- "cursor",
2171
- "lean",
2172
- "_policyFilters"
2173
- ]);
2174
- const filters = {};
2175
- for (const [key, value] of Object.entries(query)) {
2176
- if (reservedKeys.has(key)) continue;
2177
- if (value === void 0 || value === null) continue;
2178
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_.]*)(?:\[([a-z]+)\])?$/);
2179
- if (!match) continue;
2180
- const [, fieldName, operator] = match;
2181
- if (!fieldName) continue;
2182
- if (operator && this.operators[operator]) {
2183
- const mongoOp = this.operators[operator];
2184
- const parsedValue = this.parseFilterValue(value, operator);
2185
- if (!filters[fieldName]) {
2186
- filters[fieldName] = {};
2187
- }
2188
- filters[fieldName][mongoOp] = parsedValue;
2189
- } else if (!operator) {
2190
- filters[fieldName] = this.parseFilterValue(value);
2191
- }
2192
- }
2193
- return filters;
2194
- }
2195
- parseFilterValue(value, operator) {
2196
- if (operator === "in" || operator === "nin") {
2197
- if (Array.isArray(value)) {
2198
- return value.map((v) => this.coerceValue(v));
2199
- }
2200
- if (typeof value === "string" && value.includes(",")) {
2201
- return value.split(",").map((v) => this.coerceValue(v.trim()));
2202
- }
2203
- return [this.coerceValue(value)];
2204
- }
2205
- if (operator === "like" || operator === "contains" || operator === "regex") {
2206
- return this.sanitizeRegex(String(value));
2207
- }
2208
- if (operator === "exists") {
2209
- const str = String(value).toLowerCase();
2210
- return str === "true" || str === "1";
2211
- }
2212
- return this.coerceValue(value);
2213
- }
2214
- coerceValue(value) {
2215
- if (value === "true") return true;
2216
- if (value === "false") return false;
2217
- if (value === "null") return null;
2218
- if (typeof value === "string") {
2219
- const num = Number(value);
2220
- if (!Number.isNaN(num) && value.trim() !== "") {
2221
- return num;
2222
- }
2223
- }
2224
- return value;
2225
- }
2226
- sanitizeRegex(pattern) {
2227
- let sanitized = pattern.slice(0, this.maxRegexLength);
2228
- if (DANGEROUS_REGEX_PATTERNS.test(sanitized)) {
2229
- sanitized = sanitized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2230
- }
2231
- return sanitized;
2232
- }
2233
- };
2234
-
2235
- // src/core/BaseController.ts
2236
- var defaultParser = new ArcQueryParser();
2237
- function getDefaultQueryParser() {
2238
- return defaultParser;
2239
- }
2240
- var BaseController = class _BaseController {
2241
- repository;
2242
- schemaOptions;
2243
- queryParser;
2244
- maxLimit;
2245
- defaultLimit;
2246
- defaultSort;
2247
- resourceName;
2248
- disableEvents;
2249
- /** Preset field names for dynamic param reading */
2250
- _presetFields = {};
2251
- constructor(repository, options = {}) {
2252
- this.repository = repository;
2253
- this.schemaOptions = options.schemaOptions ?? {};
2254
- this.queryParser = options.queryParser ?? getDefaultQueryParser();
2255
- this.maxLimit = options.maxLimit ?? 100;
2256
- this.defaultLimit = options.defaultLimit ?? 20;
2257
- this.defaultSort = options.defaultSort ?? "-createdAt";
2258
- this.resourceName = options.resourceName;
2259
- this.disableEvents = options.disableEvents ?? false;
2260
- this.list = this.list.bind(this);
2261
- this.get = this.get.bind(this);
2262
- this.create = this.create.bind(this);
2263
- this.update = this.update.bind(this);
2264
- this.delete = this.delete.bind(this);
2265
- }
2266
- /**
2267
- * Inject resource options from defineResource
2268
- */
2269
- _setResourceOptions(options) {
2270
- if (options.schemaOptions) {
2271
- this.schemaOptions = { ...this.schemaOptions, ...options.schemaOptions };
2272
- }
2273
- if (options.presetFields) {
2274
- this._presetFields = { ...this._presetFields, ...options.presetFields };
2275
- }
2276
- if (options.resourceName) {
2277
- this.resourceName = options.resourceName;
2278
- }
2279
- if (options.queryParser) {
2280
- this.queryParser = options.queryParser;
2281
- }
2282
- }
2283
- // ============================================================================
2284
- // Context & Query Parsing
2285
- // ============================================================================
2286
- /**
2287
- * Build service context from IRequestContext
2288
- */
2289
- _buildContext(req) {
2290
- const parsed = this.queryParser.parse(req.query);
2291
- const arcContext = req.metadata;
2292
- const selectString = this._selectToString(parsed.select) ?? req.query?.select;
2293
- const sanitizedSelect = this._sanitizeSelect(selectString, this.schemaOptions);
2294
- return {
2295
- user: req.user,
2296
- organizationId: arcContext?.organizationId ?? req.organizationId ?? void 0,
2297
- select: sanitizedSelect ? sanitizedSelect.split(/\s+/) : void 0,
2298
- populate: this._sanitizePopulate(parsed.populate, this.schemaOptions),
2299
- lean: this._parseLean(req.query?.lean)
2300
- };
2301
- }
2302
- /**
2303
- * Parse query into QueryOptions using queryParser
2304
- */
2305
- _parseQueryOptions(req) {
2306
- const parsed = this.queryParser.parse(req.query);
2307
- const arcContext = req.metadata;
2308
- delete parsed.filters._policyFilters;
2309
- const limit = Math.min(Math.max(1, parsed.limit || this.defaultLimit), this.maxLimit);
2310
- const page = parsed.after ? void 0 : parsed.page ? Math.max(1, parsed.page) : 1;
2311
- const sortString = parsed.sort ? Object.entries(parsed.sort).map(([k, v]) => v === -1 ? `-${k}` : k).join(",") : this.defaultSort;
2312
- const selectString = this._selectToString(parsed.select) ?? req.query?.select;
2313
- return {
2314
- page,
2315
- limit,
2316
- sort: sortString,
2317
- select: this._sanitizeSelect(selectString, this.schemaOptions),
2318
- populate: this._sanitizePopulate(parsed.populate, this.schemaOptions),
2319
- filters: parsed.filters,
2320
- // MongoKit features
2321
- search: parsed.search,
2322
- after: parsed.after,
2323
- user: req.user,
2324
- organizationId: arcContext?.organizationId ?? req.organizationId,
2325
- context: arcContext
2326
- };
2327
- }
2328
- /**
2329
- * Apply org and policy filters
2330
- */
2331
- _applyFilters(options, req) {
2332
- const filters = { ...options.filters };
2333
- const arcContext = req.metadata;
2334
- const policyFilters = arcContext?._policyFilters;
2335
- if (policyFilters) {
2336
- Object.assign(filters, policyFilters);
2337
- }
2338
- const orgId = arcContext?.organizationId ?? req.organizationId;
2339
- if (orgId) {
2340
- filters.organizationId = orgId;
2341
- }
2342
- return { ...options, filters };
2343
- }
2344
- /**
2345
- * Build filter for single-item operations (get/update/delete)
2346
- * Combines ID filter with policy/org filters for proper security enforcement
2347
- */
2348
- _buildIdFilter(id, req) {
2349
- const filter = { _id: id };
2350
- const arcContext = req.metadata;
2351
- const policyFilters = arcContext?._policyFilters;
2352
- if (policyFilters) {
2353
- Object.assign(filter, policyFilters);
2354
- }
2355
- const orgId = arcContext?.organizationId ?? req.organizationId;
2356
- if (orgId) {
2357
- filter.organizationId = orgId;
2358
- }
2359
- return filter;
2360
- }
2361
- /**
2362
- * Check if a value matches a MongoDB query operator
2363
- */
2364
- _matchesOperator(itemValue, operator, filterValue) {
2365
- switch (operator) {
2366
- case "$eq":
2367
- return itemValue === filterValue;
2368
- case "$ne":
2369
- return itemValue !== filterValue;
2370
- case "$gt":
2371
- return typeof itemValue === "number" && typeof filterValue === "number" && itemValue > filterValue;
2372
- case "$gte":
2373
- return typeof itemValue === "number" && typeof filterValue === "number" && itemValue >= filterValue;
2374
- case "$lt":
2375
- return typeof itemValue === "number" && typeof filterValue === "number" && itemValue < filterValue;
2376
- case "$lte":
2377
- return typeof itemValue === "number" && typeof filterValue === "number" && itemValue <= filterValue;
2378
- case "$in":
2379
- return Array.isArray(filterValue) && filterValue.includes(itemValue);
2380
- case "$nin":
2381
- return Array.isArray(filterValue) && !filterValue.includes(itemValue);
2382
- case "$exists":
2383
- return filterValue ? itemValue !== void 0 : itemValue === void 0;
2384
- case "$regex":
2385
- if (typeof itemValue === "string" && (typeof filterValue === "string" || filterValue instanceof RegExp)) {
2386
- const regex = typeof filterValue === "string" ? new RegExp(filterValue) : filterValue;
2387
- return regex.test(itemValue);
2388
- }
2389
- return false;
2390
- default:
2391
- return false;
2392
- }
2393
- }
2394
- /**
2395
- * Forbidden paths that could lead to prototype pollution
2396
- */
2397
- static FORBIDDEN_PATHS = ["__proto__", "constructor", "prototype"];
2398
- /**
2399
- * Get nested value from object using dot notation (e.g., "owner.id")
2400
- * Security: Validates path against forbidden patterns to prevent prototype pollution
2401
- */
2402
- _getNestedValue(obj, path) {
2403
- if (_BaseController.FORBIDDEN_PATHS.some((p) => path.toLowerCase().includes(p))) {
2404
- return void 0;
2405
- }
2406
- const keys = path.split(".");
2407
- let value = obj;
2408
- for (const key of keys) {
2409
- if (value == null) return void 0;
2410
- if (_BaseController.FORBIDDEN_PATHS.includes(key.toLowerCase())) {
2411
- return void 0;
2412
- }
2413
- value = value[key];
2414
- }
2415
- return value;
2416
- }
2417
- /**
2418
- * Check if item matches a single filter condition
2419
- * Supports nested paths (e.g., "owner.id", "metadata.status")
2420
- */
2421
- _matchesFilter(item, key, filterValue) {
2422
- const itemValue = key.includes(".") ? this._getNestedValue(item, key) : item[key];
2423
- if (filterValue && typeof filterValue === "object" && !Array.isArray(filterValue)) {
2424
- const operators = Object.keys(filterValue);
2425
- if (operators.some((op) => op.startsWith("$"))) {
2426
- for (const [operator, opValue] of Object.entries(filterValue)) {
2427
- if (!this._matchesOperator(itemValue, operator, opValue)) {
2428
- return false;
2429
- }
2430
- }
2431
- return true;
2432
- }
2433
- }
2434
- return itemValue === filterValue;
2435
- }
2436
- /**
2437
- * Check if item matches policy filters (for get/update/delete operations)
2438
- * Validates that fetched item satisfies all policy constraints
2439
- * Supports MongoDB query operators: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $exists, $regex, $and, $or
2440
- */
2441
- _checkPolicyFilters(item, req) {
2442
- const arcContext = req.metadata;
2443
- const policyFilters = arcContext?._policyFilters;
2444
- if (!policyFilters) return true;
2445
- if (policyFilters.$and && Array.isArray(policyFilters.$and)) {
2446
- return policyFilters.$and.every((condition) => {
2447
- return Object.entries(condition).every(([key, value]) => {
2448
- return this._matchesFilter(item, key, value);
2449
- });
2450
- });
2451
- }
2452
- if (policyFilters.$or && Array.isArray(policyFilters.$or)) {
2453
- return policyFilters.$or.some((condition) => {
2454
- return Object.entries(condition).every(([key, value]) => {
2455
- return this._matchesFilter(item, key, value);
2456
- });
2457
- });
2458
- }
2459
- for (const [key, value] of Object.entries(policyFilters)) {
2460
- if (key.startsWith("$")) continue;
2461
- if (!this._matchesFilter(item, key, value)) {
2462
- return false;
2463
- }
2464
- }
2465
- return true;
2466
- }
2467
- // ============================================================================
2468
- // Sanitization Helpers
2469
- // ============================================================================
2470
- /** Parse lean option (default: true for performance) */
2471
- _parseLean(leanValue) {
2472
- if (typeof leanValue === "boolean") return leanValue;
2473
- if (typeof leanValue === "string") return leanValue.toLowerCase() !== "false";
2474
- return true;
2475
- }
2476
- /** Get blocked fields from schema options */
2477
- _getBlockedFields(schemaOptions) {
2478
- const fieldRules = schemaOptions.fieldRules ?? {};
2479
- return Object.entries(fieldRules).filter(([, rules]) => rules.systemManaged || rules.hidden).map(([field]) => field);
2480
- }
2481
- /**
2482
- * Convert parsed select object to string format
2483
- * Converts { name: 1, email: 1, password: 0 } → 'name email -password'
2484
- */
2485
- _selectToString(select) {
2486
- if (!select) return void 0;
2487
- if (typeof select === "string") return select;
2488
- if (Array.isArray(select)) return select.join(" ");
2489
- if (Object.keys(select).length === 0) return void 0;
2490
- return Object.entries(select).map(([field, include]) => include === 0 ? `-${field}` : field).join(" ");
2491
- }
2492
- /** Sanitize select fields */
2493
- _sanitizeSelect(select, schemaOptions) {
2494
- if (!select) return void 0;
2495
- const blockedFields = this._getBlockedFields(schemaOptions);
2496
- if (blockedFields.length === 0) return select;
2497
- const fields = select.split(/[\s,]+/).filter(Boolean);
2498
- const sanitized = fields.filter((f) => {
2499
- const fieldName = f.replace(/^-/, "");
2500
- return !blockedFields.includes(fieldName);
2501
- });
2502
- return sanitized.length > 0 ? sanitized.join(" ") : void 0;
2503
- }
2504
- /** Sanitize populate fields */
2505
- _sanitizePopulate(populate, schemaOptions) {
2506
- if (!populate) return void 0;
2507
- const allowedPopulate = schemaOptions.query?.allowedPopulate;
2508
- const requested = typeof populate === "string" ? populate.split(",").map((p) => p.trim()) : Array.isArray(populate) ? populate.map(String) : [];
2509
- if (requested.length === 0) return void 0;
2510
- if (!allowedPopulate) return requested;
2511
- const sanitized = requested.filter((p) => allowedPopulate.includes(p));
2512
- return sanitized.length > 0 ? sanitized : void 0;
2513
- }
2514
- // ============================================================================
2515
- // Access Control Helpers
2516
- // ============================================================================
2517
- /** Check org scope for a document */
2518
- _checkOrgScope(item, arcContext) {
2519
- if (!item || !arcContext?.organizationId) return true;
2520
- const itemOrgId = item.organizationId;
2521
- if (!itemOrgId) return true;
2522
- return String(itemOrgId) === String(arcContext.organizationId);
2523
- }
2524
- /** Check ownership for update/delete (ownedByUser preset) */
2525
- _checkOwnership(item, req) {
2526
- const ownershipCheck = req.metadata?._ownershipCheck;
2527
- if (!item || !ownershipCheck) return true;
2528
- const { field, userId } = ownershipCheck;
2529
- const itemOwnerId = item[field];
2530
- if (!itemOwnerId) return true;
2531
- return String(itemOwnerId) === String(userId);
2532
- }
2533
- /**
2534
- * Get hook system from context (instance-scoped) or fall back to global singleton
2535
- * This allows proper isolation when running multiple app instances (e.g., in tests)
2536
- */
2537
- _getHooks(req) {
2538
- const arcMeta = req.metadata?.arc;
2539
- return arcMeta?.hooks ?? hookSystem;
2540
- }
2541
- // ============================================================================
2542
- // IController Implementation - CRUD Operations
2543
- // ============================================================================
2544
- /**
2545
- * List resources with filtering, pagination, sorting
2546
- * Implements IController.list()
2547
- */
2548
- async list(req) {
2549
- const options = this._parseQueryOptions(req);
2550
- const filteredOptions = this._applyFilters(options, req);
2551
- const result = await this.repository.getAll(filteredOptions);
2552
- if (Array.isArray(result)) {
2553
- return {
2554
- success: true,
2555
- data: {
2556
- docs: result,
2557
- page: 1,
2558
- limit: result.length,
2559
- total: result.length,
2560
- pages: 1,
2561
- hasNext: false,
2562
- hasPrev: false
2563
- },
2564
- status: 200
2565
- };
2566
- }
2567
- return {
2568
- success: true,
2569
- data: result,
2570
- status: 200
2571
- };
2572
- }
2573
- /**
2574
- * Get single resource by ID
2575
- * Implements IController.get()
2576
- */
2577
- async get(req) {
2578
- const id = req.params.id;
2579
- if (!id) {
2580
- return {
2581
- success: false,
2582
- error: "ID parameter is required",
2583
- status: 400
2584
- };
2585
- }
2586
- const options = this._parseQueryOptions(req);
2587
- const arcContext = req.metadata;
2588
- try {
2589
- const item = await this.repository.getById(id, options);
2590
- if (!item || !this._checkOrgScope(item, arcContext) || !this._checkPolicyFilters(item, req)) {
2591
- return {
2592
- success: false,
2593
- error: "Resource not found",
2594
- status: 404
2595
- };
2596
- }
2597
- return {
2598
- success: true,
2599
- data: item,
2600
- status: 200
2601
- };
2602
- } catch (error) {
2603
- if (error instanceof Error && error.message?.includes("not found")) {
2604
- return {
2605
- success: false,
2606
- error: "Resource not found",
2607
- status: 404
2608
- };
2609
- }
2610
- throw error;
2611
- }
2612
- }
2613
- /**
2614
- * Create new resource
2615
- * Implements IController.create()
2616
- */
2617
- async create(req) {
2618
- const data = { ...req.body };
2619
- const arcContext = req.metadata;
2620
- if (arcContext?.organizationId) {
2621
- data.organizationId = arcContext.organizationId;
2622
- }
2623
- const userId = getUserId(req.user);
2624
- if (userId) {
2625
- data.createdBy = userId;
2626
- }
2627
- const hooks = this._getHooks(req);
2628
- const user = req.user;
2629
- let processedData = data;
2630
- if (this.resourceName) {
2631
- processedData = await hooks.executeBefore(this.resourceName, "create", data, {
2632
- user,
2633
- context: arcContext
2634
- });
2635
- }
2636
- const item = await this.repository.create(processedData, {
2637
- user,
2638
- context: arcContext
2639
- });
2640
- if (this.resourceName) {
2641
- await hooks.executeAfter(this.resourceName, "create", item, {
2642
- user,
2643
- context: arcContext
2644
- });
2645
- }
2646
- return {
2647
- success: true,
2648
- data: item,
2649
- status: 201,
2650
- meta: { message: "Created successfully" }
2651
- };
2652
- }
2653
- /**
2654
- * Update existing resource
2655
- * Implements IController.update()
2656
- */
2657
- async update(req) {
2658
- const id = req.params.id;
2659
- if (!id) {
2660
- return {
2661
- success: false,
2662
- error: "ID parameter is required",
2663
- status: 400
2664
- };
2665
- }
2666
- const data = { ...req.body };
2667
- const arcContext = req.metadata;
2668
- const user = req.user;
2669
- const userId = getUserId(user);
2670
- if (userId) {
2671
- data.updatedBy = userId;
2672
- }
2673
- const existing = await this.repository.getById(id);
2674
- if (!existing) {
2675
- return {
2676
- success: false,
2677
- error: "Resource not found",
2678
- status: 404
2679
- };
2680
- }
2681
- if (!this._checkOrgScope(existing, arcContext) || !this._checkPolicyFilters(existing, req)) {
2682
- return {
2683
- success: false,
2684
- error: "Resource not found",
2685
- status: 404
2686
- };
2687
- }
2688
- if (!this._checkOwnership(existing, req)) {
2689
- return {
2690
- success: false,
2691
- error: "You do not have permission to modify this resource",
2692
- details: { code: "OWNERSHIP_DENIED" },
2693
- status: 403
2694
- };
2695
- }
2696
- const hooks = this._getHooks(req);
2697
- let processedData = data;
2698
- if (this.resourceName) {
2699
- processedData = await hooks.executeBefore(this.resourceName, "update", data, {
2700
- user,
2701
- context: arcContext,
2702
- meta: { id, existing }
2703
- });
2704
- }
2705
- const item = await this.repository.update(id, processedData, {
2706
- user,
2707
- context: arcContext
2708
- });
2709
- if (!item) {
2710
- return {
2711
- success: false,
2712
- error: "Resource not found",
2713
- status: 404
2714
- };
2715
- }
2716
- if (this.resourceName) {
2717
- await hooks.executeAfter(this.resourceName, "update", item, {
2718
- user,
2719
- context: arcContext,
2720
- meta: { id, existing }
2721
- });
2722
- }
2723
- return {
2724
- success: true,
2725
- data: item,
2726
- status: 200,
2727
- meta: { message: "Updated successfully" }
2728
- };
2729
- }
2730
- /**
2731
- * Delete resource
2732
- * Implements IController.delete()
2733
- */
2734
- async delete(req) {
2735
- const id = req.params.id;
2736
- if (!id) {
2737
- return {
2738
- success: false,
2739
- error: "ID parameter is required",
2740
- status: 400
2741
- };
2742
- }
2743
- const arcContext = req.metadata;
2744
- const user = req.user;
2745
- const existing = await this.repository.getById(id);
2746
- if (!existing) {
2747
- return {
2748
- success: false,
2749
- error: "Resource not found",
2750
- status: 404
2751
- };
2752
- }
2753
- if (!this._checkOrgScope(existing, arcContext) || !this._checkPolicyFilters(existing, req)) {
2754
- return {
2755
- success: false,
2756
- error: "Resource not found",
2757
- status: 404
2758
- };
2759
- }
2760
- if (!this._checkOwnership(existing, req)) {
2761
- return {
2762
- success: false,
2763
- error: "You do not have permission to delete this resource",
2764
- details: { code: "OWNERSHIP_DENIED" },
2765
- status: 403
2766
- };
2767
- }
2768
- const hooks = this._getHooks(req);
2769
- if (this.resourceName) {
2770
- await hooks.executeBefore(this.resourceName, "delete", existing, {
2771
- user,
2772
- context: arcContext,
2773
- meta: { id }
2774
- });
2775
- }
2776
- const result = await this.repository.delete(id, {
2777
- user,
2778
- context: arcContext
2779
- });
2780
- const deleteSuccess = typeof result === "object" ? result?.success : result;
2781
- if (!deleteSuccess) {
2782
- return {
2783
- success: false,
2784
- error: "Resource not found",
2785
- status: 404
2786
- };
2787
- }
2788
- if (this.resourceName) {
2789
- await hooks.executeAfter(this.resourceName, "delete", existing, {
2790
- user,
2791
- context: arcContext,
2792
- meta: { id }
2793
- });
2794
- }
2795
- return {
2796
- success: true,
2797
- data: { message: "Deleted successfully" },
2798
- status: 200
2799
- };
2800
- }
2801
- // ============================================================================
2802
- // Preset Methods (framework-agnostic versions)
2803
- // ============================================================================
2804
- /** Get resource by slug (slugLookup preset) */
2805
- async getBySlug(req) {
2806
- const repo = this.repository;
2807
- if (!repo.getBySlug) {
2808
- return {
2809
- success: false,
2810
- error: "Slug lookup not implemented",
2811
- status: 501
2812
- };
2813
- }
2814
- const slugField = this._presetFields.slugField ?? "slug";
2815
- const slug = req.params[slugField] ?? req.params.slug;
2816
- const options = this._parseQueryOptions(req);
2817
- const arcContext = req.metadata;
2818
- const item = await repo.getBySlug(slug, options);
2819
- if (!item || !this._checkOrgScope(item, arcContext)) {
2820
- return {
2821
- success: false,
2822
- error: "Resource not found",
2823
- status: 404
2824
- };
2825
- }
2826
- return {
2827
- success: true,
2828
- data: item,
2829
- status: 200
2830
- };
2831
- }
2832
- /** Get soft-deleted resources (softDelete preset) */
2833
- async getDeleted(req) {
2834
- const repo = this.repository;
2835
- if (!repo.getDeleted) {
2836
- return {
2837
- success: false,
2838
- error: "Soft delete not implemented",
2839
- status: 501
2840
- };
2841
- }
2842
- const options = this._parseQueryOptions(req);
2843
- const filteredOptions = this._applyFilters(options, req);
2844
- const result = await repo.getDeleted(filteredOptions);
2845
- if (Array.isArray(result)) {
2846
- return {
2847
- success: true,
2848
- data: {
2849
- docs: result,
2850
- page: 1,
2851
- limit: result.length,
2852
- total: result.length,
2853
- pages: 1,
2854
- hasNext: false,
2855
- hasPrev: false
2856
- },
2857
- status: 200
2858
- };
2859
- }
2860
- return {
2861
- success: true,
2862
- data: result,
2863
- status: 200
2864
- };
2865
- }
2866
- /** Restore soft-deleted resource (softDelete preset) */
2867
- async restore(req) {
2868
- const repo = this.repository;
2869
- if (!repo.restore) {
2870
- return {
2871
- success: false,
2872
- error: "Restore not implemented",
2873
- status: 501
2874
- };
2875
- }
2876
- const id = req.params.id;
2877
- if (!id) {
2878
- return {
2879
- success: false,
2880
- error: "ID parameter is required",
2881
- status: 400
2882
- };
2883
- }
2884
- const item = await repo.restore(id);
2885
- if (!item) {
2886
- return {
2887
- success: false,
2888
- error: "Resource not found",
2889
- status: 404
2890
- };
2891
- }
2892
- return {
2893
- success: true,
2894
- data: item,
2895
- status: 200,
2896
- meta: { message: "Restored successfully" }
2897
- };
2898
- }
2899
- /** Get hierarchical tree (tree preset) */
2900
- async getTree(req) {
2901
- const repo = this.repository;
2902
- if (!repo.getTree) {
2903
- return {
2904
- success: false,
2905
- error: "Tree structure not implemented",
2906
- status: 501
2907
- };
2908
- }
2909
- const options = this._parseQueryOptions(req);
2910
- const filteredOptions = this._applyFilters(options, req);
2911
- const tree = await repo.getTree(filteredOptions);
2912
- return {
2913
- success: true,
2914
- data: tree,
2915
- status: 200
2916
- };
2917
- }
2918
- /** Get children of parent (tree preset) */
2919
- async getChildren(req) {
2920
- const repo = this.repository;
2921
- if (!repo.getChildren) {
2922
- return {
2923
- success: false,
2924
- error: "Tree structure not implemented",
2925
- status: 501
2926
- };
2927
- }
2928
- const parentField = this._presetFields.parentField ?? "parent";
2929
- const parentId = req.params[parentField] ?? req.params.parent ?? req.params.id;
2930
- const options = this._parseQueryOptions(req);
2931
- const filteredOptions = this._applyFilters(options, req);
2932
- const children = await repo.getChildren(parentId, filteredOptions);
2933
- return {
2934
- success: true,
2935
- data: children,
2936
- status: 200
2937
- };
2938
- }
2939
- };
2940
-
2941
- // src/core/fastifyAdapter.ts
2942
- function applyFieldMaskToObject(obj, fieldMask) {
2943
- if (!obj || typeof obj !== "object") return obj;
2944
- const { include, exclude } = fieldMask;
2945
- if (include && include.length > 0) {
2946
- const filtered = {};
2947
- for (const field of include) {
2948
- if (field in obj) {
2949
- filtered[field] = obj[field];
2950
- }
2951
- }
2952
- return filtered;
2953
- }
2954
- if (exclude && exclude.length > 0) {
2955
- const filtered = { ...obj };
2956
- for (const field of exclude) {
2957
- delete filtered[field];
2958
- }
2959
- return filtered;
2960
- }
2961
- return obj;
2962
- }
2963
- function applyFieldMask(data, fieldMask) {
2964
- if (!fieldMask) return data;
2965
- if (Array.isArray(data)) {
2966
- return data.map((item) => applyFieldMaskToObject(item, fieldMask));
2967
- }
2968
- if (data && typeof data === "object") {
2969
- return applyFieldMaskToObject(data, fieldMask);
2970
- }
2971
- return data;
2972
- }
2973
- function createRequestContext(req) {
2974
- const reqWithExtras = req;
2975
- return {
2976
- query: reqWithExtras.query ?? {},
2977
- body: reqWithExtras.body ?? {},
2978
- params: reqWithExtras.params ?? {},
2979
- headers: reqWithExtras.headers,
2980
- user: reqWithExtras.user ? (() => {
2981
- const user = reqWithExtras.user;
2982
- return {
2983
- ...user,
2984
- // Normalize ID for MongoDB compatibility
2985
- id: String(user._id ?? user.id),
2986
- _id: user._id ?? user.id
2987
- // Preserve original role/roles/permissions as-is
2988
- // Devs can define their own authorization structure
2989
- };
2990
- })() : void 0,
2991
- organizationId: reqWithExtras.organizationId,
2992
- metadata: {
2993
- ...reqWithExtras.context,
2994
- // Include Arc metadata for hook execution
2995
- arc: reqWithExtras.arc,
2996
- // Include ownership check for access control
2997
- _ownershipCheck: reqWithExtras._ownershipCheck,
2998
- // Merge policy filters - TRUSTED sources override user input
2999
- // Order matters: query (can be user-injected) FIRST, then trusted middleware LAST
3000
- _policyFilters: {
3001
- ...reqWithExtras.query?._policyFilters ?? {},
3002
- ...reqWithExtras._policyFilters ?? {}
3003
- },
3004
- // Include logger for logging
3005
- log: reqWithExtras.log
3006
- }
3007
- };
3008
- }
3009
- function sendControllerResponse(reply, response, request) {
3010
- const reqWithExtras = request;
3011
- const fieldMask = reqWithExtras?.fieldMask;
3012
- const fieldMaskConfig = fieldMask ? { include: fieldMask } : void 0;
3013
- if (response.success && response.data && typeof response.data === "object" && "docs" in response.data) {
3014
- const paginatedData = response.data;
3015
- const filteredDocs = fieldMaskConfig ? applyFieldMask(paginatedData.docs, fieldMaskConfig) : paginatedData.docs;
3016
- reply.code(response.status ?? 200).send({
3017
- success: true,
3018
- docs: filteredDocs,
3019
- page: paginatedData.page,
3020
- limit: paginatedData.limit,
3021
- total: paginatedData.total,
3022
- pages: paginatedData.pages,
3023
- hasNext: paginatedData.hasNext,
3024
- hasPrev: paginatedData.hasPrev,
3025
- ...response.meta ?? {}
3026
- });
3027
- return;
3028
- }
3029
- const filteredData = fieldMaskConfig ? applyFieldMask(response.data, fieldMaskConfig) : response.data;
3030
- reply.code(response.status ?? (response.success ? 200 : 400)).send({
3031
- success: response.success,
3032
- data: filteredData,
3033
- error: response.error,
3034
- details: response.details,
3035
- ...response.meta ?? {}
3036
- });
3037
- }
3038
- function createFastifyHandler(controllerMethod) {
3039
- return async (req, reply) => {
3040
- const requestContext = createRequestContext(req);
3041
- const response = await controllerMethod(requestContext);
3042
- sendControllerResponse(reply, response, req);
3043
- };
3044
- }
3045
- function createCrudHandlers(controller) {
3046
- return {
3047
- list: createFastifyHandler(controller.list.bind(controller)),
3048
- get: createFastifyHandler(controller.get.bind(controller)),
3049
- create: createFastifyHandler(controller.create.bind(controller)),
3050
- update: createFastifyHandler(controller.update.bind(controller)),
3051
- delete: createFastifyHandler(controller.delete.bind(controller))
3052
- };
3053
- }
3054
-
3055
- // src/core/createCrudRouter.ts
3056
- function requiresAuthentication(permission) {
3057
- if (!permission) return false;
3058
- return !permission._isPublic;
3059
- }
3060
- function buildAuthMiddleware(fastify, permission) {
3061
- if (!requiresAuthentication(permission)) return null;
3062
- if (!fastify.authenticate) return null;
3063
- return fastify.authenticate;
3064
- }
3065
- function buildPermissionMiddleware(permissionCheck, resourceName, action) {
3066
- if (!permissionCheck) return null;
3067
- return async (request, reply) => {
3068
- const reqWithExtras = request;
3069
- const context2 = {
3070
- user: reqWithExtras.user ?? null,
3071
- request,
3072
- resource: resourceName,
3073
- action,
3074
- resourceId: request.params?.id,
3075
- organizationId: reqWithExtras.organizationId,
3076
- data: request.body
3077
- };
3078
- const result = await permissionCheck(context2);
3079
- if (typeof result === "boolean") {
3080
- if (!result) {
3081
- reply.code(context2.user ? 403 : 401).send({
3082
- success: false,
3083
- error: context2.user ? "Permission denied" : "Authentication required"
3084
- });
3085
- return;
3086
- }
3087
- return;
3088
- }
3089
- const permResult = result;
3090
- if (!permResult.granted) {
3091
- reply.code(context2.user ? 403 : 401).send({
3092
- success: false,
3093
- error: permResult.reason ?? (context2.user ? "Permission denied" : "Authentication required")
3094
- });
3095
- return;
3096
- }
3097
- if (permResult.filters) {
3098
- reqWithExtras._policyFilters = {
3099
- ...reqWithExtras._policyFilters ?? {},
3100
- ...permResult.filters
3101
- };
3102
- }
3103
- };
3104
- }
3105
- function buildOrgScopedMiddleware(fastify, orgScoped, globalOrgScoped) {
3106
- const shouldApplyOrgScoped = orgScoped ?? globalOrgScoped;
3107
- if (!shouldApplyOrgScoped) return [];
3108
- if (!fastify.organizationScoped) {
3109
- throw new Error(
3110
- "Organization scoping is enabled but fastify.organizationScoped decorator is not registered.\nRegister the org scope plugin before mounting resources:\nawait app.register(orgScopePlugin);\nDocs: https://github.com/classytic/arc#multi-tenant"
3111
- );
3112
- }
3113
- return [fastify.organizationScoped()];
3114
- }
3115
- function createAdditionalRoutes(fastify, routes, controller, options) {
3116
- const { tag, resourceName, orgMw, arcDecorator } = options;
3117
- for (const route of routes) {
3118
- let handler;
3119
- if (typeof route.handler === "string") {
3120
- if (!controller) {
3121
- throw new Error(
3122
- `Route ${route.method} ${route.path}: string handler '${route.handler}' requires a controller. Either provide a controller or use a function handler instead.`
3123
- );
3124
- }
3125
- const ctrl = controller;
3126
- const method = ctrl[route.handler];
3127
- if (typeof method !== "function") {
3128
- throw new Error(`Handler '${route.handler}' not found on controller`);
3129
- }
3130
- const boundMethod = method.bind(controller);
3131
- handler = route.wrapHandler ? createFastifyHandler(boundMethod) : boundMethod;
3132
- } else {
3133
- handler = route.wrapHandler ? createFastifyHandler(route.handler) : route.handler;
3134
- }
3135
- const routeTags = route.tags ?? (tag ? [tag] : void 0);
3136
- const schema = {
3137
- ...routeTags ? { tags: routeTags } : {},
3138
- ...route.summary ? { summary: route.summary } : {},
3139
- ...route.description ? { description: route.description } : {},
3140
- ...route.schema ?? {}
3141
- };
3142
- const authMw = buildAuthMiddleware(fastify, route.permissions);
3143
- const permissionMw = buildPermissionMiddleware(route.permissions, resourceName, route.method.toLowerCase());
3144
- const customPreHandlers = typeof route.preHandler === "function" ? route.preHandler(fastify) : route.preHandler ?? [];
3145
- const preHandler = [
3146
- arcDecorator,
3147
- authMw,
3148
- // Authenticate first (populates request.user)
3149
- permissionMw,
3150
- // Then check permissions
3151
- ...orgMw(),
3152
- ...customPreHandlers
3153
- ].filter(Boolean);
3154
- fastify.route({
3155
- method: route.method,
3156
- url: route.path,
3157
- schema,
3158
- // Fastify schema is flexible - allow any valid JSON schema
3159
- preHandler: preHandler.length > 0 ? preHandler : void 0,
3160
- handler
3161
- });
3162
- }
3163
- }
3164
- function createCrudRouter(fastify, controller, options = {}) {
3165
- const {
3166
- tag = "Resource",
3167
- schemas = {},
3168
- permissions = {},
3169
- middlewares = {},
3170
- additionalRoutes = [],
3171
- disableDefaultRoutes = false,
3172
- disabledRoutes = [],
3173
- organizationScoped = false,
3174
- resourceName = "unknown",
3175
- schemaOptions
3176
- } = options;
3177
- const orgMw = (orgScoped) => {
3178
- return buildOrgScopedMiddleware(fastify, orgScoped, organizationScoped);
3179
- };
3180
- const arcDecorator = async (req, _reply) => {
3181
- req.arc = {
3182
- resourceName,
3183
- schemaOptions,
3184
- permissions,
3185
- // Include instance-scoped hooks if available (for proper isolation)
3186
- hooks: fastify.arc?.hooks,
3187
- // Include events emitter if available
3188
- events: fastify.events
3189
- };
3190
- };
3191
- const mw = {
3192
- list: middlewares.list ?? [],
3193
- get: middlewares.get ?? [],
3194
- create: middlewares.create ?? [],
3195
- update: middlewares.update ?? [],
3196
- delete: middlewares.delete ?? []
3197
- };
3198
- const idParamsSchema = {
3199
- type: "object",
3200
- properties: { id: { type: "string" } },
3201
- required: ["id"]
3202
- };
3203
- let handlers;
3204
- if (!disableDefaultRoutes) {
3205
- if (!controller) {
3206
- throw new Error(
3207
- "Controller is required when disableDefaultRoutes is not true. Provide a controller or use defineResource which auto-creates BaseController."
3208
- );
3209
- }
3210
- handlers = createCrudHandlers(controller);
3211
- }
3212
- if (!disableDefaultRoutes && handlers) {
3213
- if (!disabledRoutes.includes("list")) {
3214
- const authMw = buildAuthMiddleware(fastify, permissions.list);
3215
- const permMw = buildPermissionMiddleware(permissions.list, resourceName, "list");
3216
- const listPreHandler = [arcDecorator, authMw, permMw, ...orgMw(), ...mw.list].filter(Boolean);
3217
- fastify.route({
3218
- method: "GET",
3219
- url: "/",
3220
- schema: {
3221
- tags: [tag],
3222
- summary: `List ${tag}`,
3223
- ...schemas.list ?? {}
3224
- },
3225
- preHandler: listPreHandler.length > 0 ? listPreHandler : void 0,
3226
- handler: handlers.list
3227
- });
3228
- }
3229
- if (!disabledRoutes.includes("get")) {
3230
- const authMw = buildAuthMiddleware(fastify, permissions.get);
3231
- const permMw = buildPermissionMiddleware(permissions.get, resourceName, "get");
3232
- const getPreHandler = [arcDecorator, authMw, permMw, ...orgMw(), ...mw.get].filter(Boolean);
3233
- fastify.route({
3234
- method: "GET",
3235
- url: "/:id",
3236
- schema: {
3237
- tags: [tag],
3238
- summary: `Get ${tag} by ID`,
3239
- params: idParamsSchema,
3240
- ...schemas.get ?? {}
3241
- },
3242
- preHandler: getPreHandler.length > 0 ? getPreHandler : void 0,
3243
- handler: handlers.get
3244
- });
3245
- }
3246
- if (!disabledRoutes.includes("create")) {
3247
- const authMw = buildAuthMiddleware(fastify, permissions.create);
3248
- const permMw = buildPermissionMiddleware(permissions.create, resourceName, "create");
3249
- const createPreHandler = [arcDecorator, authMw, permMw, ...orgMw(), ...mw.create].filter(Boolean);
3250
- fastify.route({
3251
- method: "POST",
3252
- url: "/",
3253
- schema: {
3254
- tags: [tag],
3255
- summary: `Create ${tag}`,
3256
- ...schemas.create ?? {}
3257
- },
3258
- preHandler: createPreHandler.length > 0 ? createPreHandler : void 0,
3259
- handler: handlers.create
3260
- });
3261
- }
3262
- if (!disabledRoutes.includes("update")) {
3263
- const authMw = buildAuthMiddleware(fastify, permissions.update);
3264
- const permMw = buildPermissionMiddleware(permissions.update, resourceName, "update");
3265
- const updatePreHandler = [arcDecorator, authMw, permMw, ...orgMw(), ...mw.update].filter(Boolean);
3266
- fastify.route({
3267
- method: "PATCH",
3268
- url: "/:id",
3269
- schema: {
3270
- tags: [tag],
3271
- summary: `Update ${tag}`,
3272
- params: idParamsSchema,
3273
- ...schemas.update ?? {}
3274
- },
3275
- preHandler: updatePreHandler.length > 0 ? updatePreHandler : void 0,
3276
- handler: handlers.update
3277
- });
3278
- }
3279
- if (!disabledRoutes.includes("delete")) {
3280
- const authMw = buildAuthMiddleware(fastify, permissions.delete);
3281
- const permMw = buildPermissionMiddleware(permissions.delete, resourceName, "delete");
3282
- const deletePreHandler = [arcDecorator, authMw, permMw, ...orgMw(), ...mw.delete].filter(Boolean);
3283
- fastify.route({
3284
- method: "DELETE",
3285
- url: "/:id",
3286
- schema: {
3287
- tags: [tag],
3288
- summary: `Delete ${tag}`,
3289
- params: idParamsSchema,
3290
- ...schemas.delete ?? {}
3291
- },
3292
- preHandler: deletePreHandler.length > 0 ? deletePreHandler : void 0,
3293
- handler: handlers.delete
3294
- });
3295
- }
3296
- }
3297
- if (additionalRoutes.length > 0) {
3298
- createAdditionalRoutes(fastify, additionalRoutes, controller, { tag, resourceName, orgMw, arcDecorator });
3299
- }
3300
- }
3301
-
3302
- // src/permissions/index.ts
3303
- function allowPublic() {
3304
- const check = () => true;
3305
- check._isPublic = true;
3306
- return check;
3307
- }
3308
- function requireAuth() {
3309
- const check = (ctx) => {
3310
- if (!ctx.user) {
3311
- return { granted: false, reason: "Authentication required" };
3312
- }
3313
- return true;
3314
- };
3315
- return check;
3316
- }
3317
- function requireRoles(roles, options) {
3318
- const check = (ctx) => {
3319
- if (!ctx.user) {
3320
- return { granted: false, reason: "Authentication required" };
3321
- }
3322
- const userRoles = ctx.user.roles ?? [];
3323
- if (options?.bypassRoles?.some((r) => userRoles.includes(r))) {
3324
- return true;
3325
- }
3326
- if (roles.some((r) => userRoles.includes(r))) {
3327
- return true;
3328
- }
3329
- return {
3330
- granted: false,
3331
- reason: `Required roles: ${roles.join(", ")}`
3332
- };
3333
- };
3334
- check._roles = roles;
3335
- return check;
3336
- }
3337
- function requireOwnership(ownerField = "userId", options) {
3338
- return (ctx) => {
3339
- if (!ctx.user) {
3340
- return { granted: false, reason: "Authentication required" };
3341
- }
3342
- const userRoles = ctx.user.roles ?? [];
3343
- if (options?.bypassRoles?.some((r) => userRoles.includes(r))) {
3344
- return true;
3345
- }
3346
- const userId = ctx.user.id ?? ctx.user._id;
3347
- return {
3348
- granted: true,
3349
- filters: { [ownerField]: userId }
3350
- };
3351
- };
3352
- }
3353
- function allOf(...checks) {
3354
- return async (ctx) => {
3355
- let mergedFilters = {};
3356
- for (const check of checks) {
3357
- const result = await check(ctx);
3358
- const normalized = typeof result === "boolean" ? { granted: result } : result;
3359
- if (!normalized.granted) {
3360
- return normalized;
3361
- }
3362
- if (normalized.filters) {
3363
- mergedFilters = { ...mergedFilters, ...normalized.filters };
3364
- }
3365
- }
3366
- return {
3367
- granted: true,
3368
- filters: Object.keys(mergedFilters).length > 0 ? mergedFilters : void 0
3369
- };
3370
- };
3371
- }
3372
- function anyOf(...checks) {
3373
- return async (ctx) => {
3374
- const reasons = [];
3375
- for (const check of checks) {
3376
- const result = await check(ctx);
3377
- const normalized = typeof result === "boolean" ? { granted: result } : result;
3378
- if (normalized.granted) {
3379
- return normalized;
3380
- }
3381
- if (normalized.reason) {
3382
- reasons.push(normalized.reason);
3383
- }
3384
- }
3385
- return {
3386
- granted: false,
3387
- reason: reasons.join("; ")
3388
- };
3389
- };
3390
- }
3391
- function denyAll(reason = "Access denied") {
3392
- return () => ({ granted: false, reason });
3393
- }
3394
- function when(condition) {
3395
- return async (ctx) => {
3396
- const result = await condition(ctx);
3397
- return {
3398
- granted: result,
3399
- reason: result ? void 0 : "Condition not met"
3400
- };
3401
- };
3402
- }
3403
-
3404
- // src/presets/softDelete.ts
3405
- function softDeletePreset(options = {}) {
3406
- const { deletedField: _deletedField = "deletedAt" } = options;
3407
- return {
3408
- name: "softDelete",
3409
- additionalRoutes: (permissions) => [
3410
- {
3411
- method: "GET",
3412
- path: "/deleted",
3413
- handler: "getDeleted",
3414
- summary: "Get soft-deleted items",
3415
- permissions: permissions.list ?? requireRoles(["admin"]),
3416
- wrapHandler: true
3417
- },
3418
- {
3419
- method: "POST",
3420
- path: "/:id/restore",
3421
- handler: "restore",
3422
- summary: "Restore soft-deleted item",
3423
- permissions: permissions.update ?? requireRoles(["admin"]),
3424
- wrapHandler: true
3425
- }
3426
- ]
3427
- };
3428
- }
3429
-
3430
- // src/presets/slugLookup.ts
3431
- function slugLookupPreset(options = {}) {
3432
- const { slugField = "slug" } = options;
3433
- return {
3434
- name: "slugLookup",
3435
- additionalRoutes: (permissions) => [
3436
- {
3437
- method: "GET",
3438
- path: `/slug/:${slugField}`,
3439
- handler: "getBySlug",
3440
- summary: "Get by slug",
3441
- permissions: permissions.get ?? allowPublic(),
3442
- wrapHandler: true
3443
- // Handler is a ControllerHandler
3444
- }
3445
- ],
3446
- // Pass to controller so it knows which param to read
3447
- controllerOptions: {
3448
- slugField
3449
- }
3450
- };
3451
- }
3452
-
3453
- // src/presets/ownedByUser.ts
3454
- function createOwnershipCheck(ownerField, bypassRoles) {
3455
- return async (request, _reply) => {
3456
- const user = request.user;
3457
- if (!user) return;
3458
- const userWithRoles = user;
3459
- if (userWithRoles.roles && bypassRoles.some((r) => userWithRoles.roles.includes(r))) return;
3460
- const userWithId = user;
3461
- const userId = userWithId._id ?? userWithId.id;
3462
- if (userId) {
3463
- request._ownershipCheck = {
3464
- field: ownerField,
3465
- userId
3466
- };
3467
- }
3468
- };
3469
- }
3470
- function ownedByUserPreset(options = {}) {
3471
- const {
3472
- ownerField = "userId",
3473
- bypassRoles = ["admin", "superadmin"]
3474
- } = options;
3475
- const ownershipMiddleware = createOwnershipCheck(ownerField, bypassRoles);
3476
- return {
3477
- name: "ownedByUser",
3478
- middlewares: {
3479
- update: [ownershipMiddleware],
3480
- delete: [ownershipMiddleware]
3481
- }
3482
- };
3483
- }
3484
-
3485
- // src/presets/multiTenant.ts
3486
- function defaultExtractOrganizationId(request) {
3487
- const context2 = request.context;
3488
- if (context2?.organizationId) {
3489
- return context2.organizationId;
3490
- }
3491
- const user = request.user;
3492
- if (user?.organizationId) {
3493
- return user.organizationId;
3494
- }
3495
- if (user?.organization) {
3496
- const org = user.organization;
3497
- return org._id || org.id || org;
3498
- }
3499
- return null;
3500
- }
3501
- function createTenantFilter(tenantField, bypassRoles, extractOrganizationId) {
3502
- return async (request, reply) => {
3503
- const user = request.user;
3504
- if (!user) {
3505
- reply.code(401).send({
3506
- success: false,
3507
- error: "Unauthorized",
3508
- message: "Authentication required for multi-tenant resources"
3509
- });
3510
- return;
3511
- }
3512
- const userWithRoles = user;
3513
- if (userWithRoles.roles && bypassRoles.some((r) => userWithRoles.roles.includes(r))) return;
3514
- const orgId = extractOrganizationId(request);
3515
- if (!orgId) {
3516
- reply.code(403).send({
3517
- success: false,
3518
- error: "Forbidden",
3519
- message: "Organization context required for this operation"
3520
- });
3521
- return;
3522
- }
3523
- request.query = request.query ?? {};
3524
- request.query._policyFilters = {
3525
- ...request.query._policyFilters ?? {},
3526
- [tenantField]: orgId
3527
- };
3528
- };
3529
- }
3530
- function createFlexibleTenantFilter(tenantField, bypassRoles, extractOrganizationId) {
3531
- return async (request, reply) => {
3532
- const user = request.user;
3533
- const orgId = extractOrganizationId(request);
3534
- if (!orgId) {
3535
- return;
3536
- }
3537
- if (!user) {
3538
- reply.code(401).send({
3539
- success: false,
3540
- error: "Unauthorized",
3541
- message: "Authentication required for organization-scoped data"
3542
- });
3543
- return;
3544
- }
3545
- const userWithRoles = user;
3546
- if (userWithRoles.roles && bypassRoles.some((r) => userWithRoles.roles.includes(r))) {
3547
- return;
3548
- }
3549
- request.query = request.query ?? {};
3550
- request.query._policyFilters = {
3551
- ...request.query._policyFilters ?? {},
3552
- [tenantField]: orgId
3553
- };
3554
- };
3555
- }
3556
- function createTenantInjection(tenantField, extractOrganizationId) {
3557
- return async (request, reply) => {
3558
- const orgId = extractOrganizationId(request);
3559
- if (!orgId) {
3560
- reply.code(403).send({
3561
- success: false,
3562
- error: "Forbidden",
3563
- message: "Organization context required to create resources"
3564
- });
3565
- return;
3566
- }
3567
- if (request.body) {
3568
- request.body[tenantField] = orgId;
3569
- }
3570
- };
3571
- }
3572
- function multiTenantPreset(options = {}) {
3573
- const {
3574
- tenantField = "organizationId",
3575
- bypassRoles = ["superadmin"],
3576
- extractOrganizationId = defaultExtractOrganizationId,
3577
- allowPublic: allowPublic2 = []
3578
- } = options;
3579
- const strictTenantFilter = createTenantFilter(tenantField, bypassRoles, extractOrganizationId);
3580
- const flexibleTenantFilter = createFlexibleTenantFilter(tenantField, bypassRoles, extractOrganizationId);
3581
- const tenantInjection = createTenantInjection(tenantField, extractOrganizationId);
3582
- const getFilter = (route) => allowPublic2.includes(route) ? flexibleTenantFilter : strictTenantFilter;
3583
- return {
3584
- name: "multiTenant",
3585
- middlewares: {
3586
- list: [getFilter("list")],
3587
- get: [getFilter("get")],
3588
- create: [tenantInjection],
3589
- update: [getFilter("update")],
3590
- delete: [getFilter("delete")]
3591
- }
3592
- };
3593
- }
3594
-
3595
- // src/presets/tree.ts
3596
- function treePreset(options = {}) {
3597
- const { parentField = "parent" } = options;
3598
- return {
3599
- name: "tree",
3600
- additionalRoutes: (permissions) => [
3601
- {
3602
- method: "GET",
3603
- path: "/tree",
3604
- handler: "getTree",
3605
- summary: "Get hierarchical tree",
3606
- permissions: permissions.list ?? allowPublic(),
3607
- wrapHandler: true
3608
- },
3609
- {
3610
- method: "GET",
3611
- path: `/:${parentField}/children`,
3612
- handler: "getChildren",
3613
- summary: "Get children of parent",
3614
- permissions: permissions.list ?? allowPublic(),
3615
- wrapHandler: true
3616
- }
3617
- ],
3618
- // Pass to controller so it knows which param to read
3619
- controllerOptions: {
3620
- parentField
3621
- }
3622
- };
3623
- }
3624
-
3625
- // src/presets/audited.ts
3626
- function auditedPreset(options = {}) {
3627
- const { createdByField = "createdBy", updatedByField = "updatedBy" } = options;
3628
- const injectCreatedBy = async (request, _reply) => {
3629
- const userWithId = request.user;
3630
- if (userWithId?._id || userWithId?.id) {
3631
- const userId = userWithId._id ?? userWithId.id;
3632
- request.body[createdByField] = userId;
3633
- request.body[updatedByField] = userId;
3634
- }
3635
- return void 0;
3636
- };
3637
- const injectUpdatedBy = async (request, _reply) => {
3638
- const userWithId = request.user;
3639
- if (userWithId?._id || userWithId?.id) {
3640
- request.body[updatedByField] = userWithId._id ?? userWithId.id;
3641
- }
3642
- return void 0;
3643
- };
3644
- return {
3645
- name: "audited",
3646
- schemaOptions: {
3647
- fieldRules: {
3648
- [createdByField]: { systemManaged: true },
3649
- [updatedByField]: { systemManaged: true },
3650
- createdAt: { systemManaged: true },
3651
- updatedAt: { systemManaged: true }
3652
- }
3653
- },
3654
- middlewares: {
3655
- create: [injectCreatedBy],
3656
- update: [injectUpdatedBy]
3657
- }
3658
- };
3659
- }
3660
-
3661
- // src/presets/index.ts
3662
- var presetRegistry = {
3663
- softDelete: softDeletePreset,
3664
- slugLookup: slugLookupPreset,
3665
- ownedByUser: ownedByUserPreset,
3666
- multiTenant: multiTenantPreset,
3667
- tree: treePreset,
3668
- audited: auditedPreset
3669
- };
3670
- function resolvePreset(name, options = {}) {
3671
- const factory = presetRegistry[name];
3672
- if (!factory) {
3673
- const available = Object.keys(presetRegistry).join(", ");
3674
- throw new Error(
3675
- `Unknown preset: '${name}'
3676
- Available presets: ${available}
3677
- Docs: https://github.com/classytic/arc#presets`
3678
- );
3679
- }
3680
- return factory(options);
3681
- }
3682
- function getAvailablePresets() {
3683
- return Object.keys(presetRegistry);
3684
- }
3685
- function applyPresets(config, presets = []) {
3686
- let result = { ...config };
3687
- for (const preset of presets) {
3688
- const resolved = resolvePresetInput(preset);
3689
- result = mergePreset(result, resolved);
3690
- }
3691
- return result;
3692
- }
3693
- function resolvePresetInput(preset) {
3694
- if (typeof preset === "object" && ("middlewares" in preset || "additionalRoutes" in preset)) {
3695
- return preset;
3696
- }
3697
- if (typeof preset === "object" && "name" in preset) {
3698
- const { name, ...options } = preset;
3699
- return resolvePreset(name, options);
3700
- }
3701
- return resolvePreset(preset);
3702
- }
3703
- function mergePreset(config, preset) {
3704
- const result = { ...config };
3705
- if (preset.additionalRoutes) {
3706
- const routes = typeof preset.additionalRoutes === "function" ? preset.additionalRoutes(config.permissions ?? {}) : preset.additionalRoutes;
3707
- result.additionalRoutes = [
3708
- ...result.additionalRoutes ?? [],
3709
- ...routes
3710
- ];
3711
- }
3712
- if (preset.middlewares) {
3713
- result.middlewares = result.middlewares ?? {};
3714
- for (const [op, mws] of Object.entries(preset.middlewares)) {
3715
- const key = op;
3716
- result.middlewares[key] = [
3717
- ...result.middlewares[key] ?? [],
3718
- ...mws ?? []
3719
- ];
3720
- }
3721
- }
3722
- if (preset.schemaOptions) {
3723
- result.schemaOptions = {
3724
- ...result.schemaOptions,
3725
- ...preset.schemaOptions
3726
- };
3727
- }
3728
- if (preset.controllerOptions) {
3729
- result._controllerOptions = {
3730
- ...result._controllerOptions,
3731
- ...preset.controllerOptions
3732
- };
3733
- }
3734
- if (preset.hooks && preset.hooks.length > 0) {
3735
- result._hooks = result._hooks ?? [];
3736
- for (const hook of preset.hooks) {
3737
- result._hooks.push({
3738
- presetName: preset.name,
3739
- operation: hook.operation,
3740
- phase: hook.phase,
3741
- handler: hook.handler,
3742
- priority: hook.priority
3743
- });
3744
- }
3745
- }
3746
- return result;
3747
- }
3748
-
3749
- // src/registry/index.ts
3750
- init_ResourceRegistry();
3751
-
3752
- // src/core/validateResourceConfig.ts
3753
- function validateResourceConfig(config, options = {}) {
3754
- const errors = [];
3755
- const warnings = [];
3756
- if (!config.name) {
3757
- errors.push({
3758
- field: "name",
3759
- message: "Resource name is required",
3760
- suggestion: 'Add a unique resource name (e.g., "product", "user")'
3761
- });
3762
- } else if (!/^[a-z][a-z0-9-]*$/i.test(config.name)) {
3763
- errors.push({
3764
- field: "name",
3765
- message: `Invalid resource name "${config.name}"`,
3766
- suggestion: "Use alphanumeric characters and hyphens, starting with a letter"
3767
- });
3768
- }
3769
- const crudRoutes = ["list", "get", "create", "update", "delete"];
3770
- const disabledRoutes = new Set(config.disabledRoutes ?? []);
3771
- const enabledCrudRoutes = crudRoutes.filter((route) => !disabledRoutes.has(route));
3772
- const hasCrudRoutes = !config.disableDefaultRoutes && enabledCrudRoutes.length > 0;
3773
- if (hasCrudRoutes) {
3774
- if (!config.adapter) {
3775
- errors.push({
3776
- field: "adapter",
3777
- message: "Data adapter is required when CRUD routes are enabled",
3778
- suggestion: "Provide an adapter: createMongooseAdapter({ model, repository })"
3779
- });
3780
- } else if (!config.adapter.repository) {
3781
- errors.push({
3782
- field: "adapter.repository",
3783
- message: "Adapter must provide a repository",
3784
- suggestion: "Ensure your adapter returns a valid CrudRepository"
3785
- });
3786
- }
3787
- if (!config.controller) {
3788
- warnings.push({
3789
- field: "controller",
3790
- message: "No controller provided, will auto-create BaseController"
3791
- });
3792
- }
3793
- } else {
3794
- if (!config.adapter && !config.additionalRoutes?.length) {
3795
- warnings.push({
3796
- field: "config",
3797
- message: "Resource has no adapter and no additionalRoutes",
3798
- suggestion: "Provide either adapter for CRUD or additionalRoutes for custom logic"
3799
- });
3800
- }
3801
- }
3802
- if (config.controller && !options.skipControllerCheck && !config.disableDefaultRoutes) {
3803
- const ctrl = config.controller;
3804
- const requiredMethods = ["list", "get", "create", "update", "delete"];
3805
- for (const method of requiredMethods) {
3806
- if (typeof ctrl[method] !== "function") {
3807
- errors.push({
3808
- field: `controller.${method}`,
3809
- message: `Missing required CRUD method "${method}"`,
3810
- suggestion: "Extend BaseController which implements IController interface"
3811
- });
3812
- }
3813
- }
3814
- }
3815
- if (config.controller && config.additionalRoutes) {
3816
- validateAdditionalRouteHandlers(config.controller, config.additionalRoutes, errors);
3817
- }
3818
- if (config.permissions) {
3819
- validatePermissionKeys(config, options, errors, warnings);
3820
- }
3821
- if (config.presets && !options.allowUnknownPresets) {
3822
- validatePresets(config.presets, errors, warnings);
3823
- }
3824
- if (config.prefix) {
3825
- if (!config.prefix.startsWith("/")) {
3826
- errors.push({
3827
- field: "prefix",
3828
- message: `Prefix must start with "/" (got "${config.prefix}")`,
3829
- suggestion: `Change to "/${config.prefix}"`
3830
- });
3831
- }
3832
- if (config.prefix.endsWith("/") && config.prefix !== "/") {
3833
- warnings.push({
3834
- field: "prefix",
3835
- message: `Prefix should not end with "/" (got "${config.prefix}")`,
3836
- suggestion: `Change to "${config.prefix.slice(0, -1)}"`
3837
- });
3838
- }
3839
- }
3840
- if (config.additionalRoutes) {
3841
- validateAdditionalRoutes(config.additionalRoutes, errors);
3842
- }
3843
- return {
3844
- valid: errors.length === 0,
3845
- errors,
3846
- warnings
3847
- };
3848
- }
3849
- function validateAdditionalRouteHandlers(controller, routes, errors) {
3850
- const ctrl = controller;
3851
- for (const route of routes) {
3852
- if (typeof route.handler === "string") {
3853
- if (typeof ctrl[route.handler] !== "function") {
3854
- errors.push({
3855
- field: `additionalRoutes[${route.method} ${route.path}]`,
3856
- message: `Handler "${route.handler}" not found on controller`,
3857
- suggestion: `Add method "${route.handler}" to controller or use a function handler`
3858
- });
3859
- }
3860
- }
3861
- }
3862
- }
3863
- function validatePermissionKeys(config, options, errors, warnings) {
3864
- const validKeys = /* @__PURE__ */ new Set([
3865
- "list",
3866
- "get",
3867
- "create",
3868
- "update",
3869
- "delete",
3870
- ...options.additionalPermissionKeys ?? []
3871
- ]);
3872
- for (const route of config.additionalRoutes ?? []) {
3873
- if (typeof route.handler === "string") {
3874
- validKeys.add(route.handler);
3875
- }
3876
- }
3877
- for (const preset of config.presets ?? []) {
3878
- const presetName = typeof preset === "string" ? preset : preset.name;
3879
- if (presetName === "softDelete") {
3880
- validKeys.add("deleted");
3881
- validKeys.add("restore");
3882
- }
3883
- if (presetName === "slugLookup") {
3884
- validKeys.add("getBySlug");
3885
- }
3886
- if (presetName === "tree") {
3887
- validKeys.add("tree");
3888
- validKeys.add("children");
3889
- validKeys.add("getTree");
3890
- validKeys.add("getChildren");
3891
- }
3892
- }
3893
- for (const key of Object.keys(config.permissions ?? {})) {
3894
- if (!validKeys.has(key)) {
3895
- warnings.push({
3896
- field: `permissions.${key}`,
3897
- message: `Unknown permission key "${key}"`,
3898
- suggestion: `Valid keys: ${Array.from(validKeys).join(", ")}`
3899
- });
3900
- }
3901
- }
3902
- }
3903
- function validatePresets(presets, errors, warnings) {
3904
- const availablePresets = getAvailablePresets();
3905
- for (const preset of presets) {
3906
- if (typeof preset === "object" && ("middlewares" in preset || "additionalRoutes" in preset)) {
3907
- continue;
3908
- }
3909
- const presetName = typeof preset === "string" ? preset : preset.name;
3910
- if (!availablePresets.includes(presetName)) {
3911
- errors.push({
3912
- field: "presets",
3913
- message: `Unknown preset "${presetName}"`,
3914
- suggestion: `Available presets: ${availablePresets.join(", ")}`
3915
- });
3916
- }
3917
- if (typeof preset === "object") {
3918
- validatePresetOptions(preset, warnings);
3919
- }
3920
- }
3921
- }
3922
- function validatePresetOptions(preset, warnings) {
3923
- const knownOptions = {
3924
- slugLookup: ["slugField"],
3925
- tree: ["parentField"],
3926
- softDelete: ["deletedField"],
3927
- ownedByUser: ["ownerField", "bypassRoles"],
3928
- multiTenant: ["tenantField", "bypassRoles"]
3929
- };
3930
- const validOptions = knownOptions[preset.name] ?? [];
3931
- const providedOptions = Object.keys(preset).filter((k) => k !== "name");
3932
- for (const opt of providedOptions) {
3933
- if (!validOptions.includes(opt)) {
3934
- warnings.push({
3935
- field: `presets[${preset.name}].${opt}`,
3936
- message: `Unknown option "${opt}" for preset "${preset.name}"`,
3937
- suggestion: validOptions.length > 0 ? `Valid options: ${validOptions.join(", ")}` : `Preset "${preset.name}" has no configurable options`
3938
- });
3939
- }
3940
- }
3941
- }
3942
- function validateAdditionalRoutes(routes, errors) {
3943
- const validMethods = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"];
3944
- const seenRoutes = /* @__PURE__ */ new Set();
3945
- for (const [i, route] of routes.entries()) {
3946
- if (!validMethods.includes(route.method)) {
3947
- errors.push({
3948
- field: `additionalRoutes[${i}].method`,
3949
- message: `Invalid HTTP method "${route.method}"`,
3950
- suggestion: `Valid methods: ${validMethods.join(", ")}`
3951
- });
3952
- }
3953
- if (!route.path) {
3954
- errors.push({
3955
- field: `additionalRoutes[${i}].path`,
3956
- message: "Route path is required"
3957
- });
3958
- } else if (!route.path.startsWith("/")) {
3959
- errors.push({
3960
- field: `additionalRoutes[${i}].path`,
3961
- message: `Route path must start with "/" (got "${route.path}")`,
3962
- suggestion: `Change to "/${route.path}"`
3963
- });
3964
- }
3965
- if (!route.handler) {
3966
- errors.push({
3967
- field: `additionalRoutes[${i}].handler`,
3968
- message: "Route handler is required"
3969
- });
3970
- }
3971
- const routeKey = `${route.method} ${route.path}`;
3972
- if (seenRoutes.has(routeKey)) {
3973
- errors.push({
3974
- field: `additionalRoutes[${i}]`,
3975
- message: `Duplicate route "${routeKey}"`
3976
- });
3977
- }
3978
- seenRoutes.add(routeKey);
3979
- }
3980
- }
3981
- function formatValidationErrors(resourceName, result) {
3982
- const lines = [];
3983
- if (result.errors.length > 0) {
3984
- lines.push(`Resource "${resourceName}" validation failed:`);
3985
- lines.push("");
3986
- lines.push("ERRORS:");
3987
- for (const err of result.errors) {
3988
- lines.push(` ✗ ${err.field}: ${err.message}`);
3989
- if (err.suggestion) {
3990
- lines.push(` → ${err.suggestion}`);
3991
- }
3992
- }
3993
- }
3994
- if (result.warnings.length > 0) {
3995
- if (lines.length > 0) lines.push("");
3996
- lines.push("WARNINGS:");
3997
- for (const warn of result.warnings) {
3998
- lines.push(` ⚠ ${warn.field}: ${warn.message}`);
3999
- if (warn.suggestion) {
4000
- lines.push(` → ${warn.suggestion}`);
4001
- }
4002
- }
4003
- }
4004
- return lines.join("\n");
4005
- }
4006
- function assertValidConfig(config, options) {
4007
- const result = validateResourceConfig(config, options);
4008
- if (!result.valid) {
4009
- const errorMsg = formatValidationErrors(config.name ?? "unknown", result);
4010
- throw new Error(errorMsg);
4011
- }
4012
- if (result.warnings.length > 0 && process.env.NODE_ENV !== "production") {
4013
- console.warn(formatValidationErrors(config.name ?? "unknown", {
4014
- errors: [],
4015
- warnings: result.warnings
4016
- }));
4017
- }
4018
- }
4019
-
4020
- // src/hooks/index.ts
4021
- init_HookSystem();
4022
-
4023
- // src/core/defineResource.ts
4024
- function defineResource(config) {
4025
- if (!config.skipValidation) {
4026
- assertValidConfig(config, { skipControllerCheck: true });
4027
- if (config.permissions) {
4028
- for (const [key, value] of Object.entries(config.permissions)) {
4029
- if (value !== void 0 && typeof value !== "function") {
4030
- throw new Error(
4031
- `[Arc] Resource '${config.name}': permissions.${key} must be a PermissionCheck function.
4032
- Use allowPublic(), requireAuth(), or requireRoles(['role']) from @classytic/arc/permissions.`
4033
- );
4034
- }
4035
- }
4036
- }
4037
- for (const route of config.additionalRoutes ?? []) {
4038
- if (typeof route.permissions !== "function") {
4039
- throw new Error(
4040
- `[Arc] Resource '${config.name}' route ${route.method} ${route.path}: permissions is required and must be a PermissionCheck function.
4041
- Use allowPublic() or requireAuth() from @classytic/arc/permissions.`
4042
- );
4043
- }
4044
- if (typeof route.wrapHandler !== "boolean") {
4045
- throw new Error(
4046
- `[Arc] Resource '${config.name}' route ${route.method} ${route.path}: wrapHandler is required.
4047
- Set true for ControllerHandler (context object) or false for FastifyHandler (req, reply).`
4048
- );
4049
- }
4050
- }
4051
- }
4052
- const repository = config.adapter?.repository;
4053
- const crudRoutes = ["list", "get", "create", "update", "delete"];
4054
- const disabledRoutes = new Set(config.disabledRoutes ?? []);
4055
- const hasCrudRoutes = !config.disableDefaultRoutes && crudRoutes.some((route) => !disabledRoutes.has(route));
4056
- let controller = config.controller;
4057
- if (!controller && hasCrudRoutes && repository) {
4058
- controller = new BaseController(repository, {
4059
- resourceName: config.name,
4060
- schemaOptions: config.schemaOptions,
4061
- queryParser: config.queryParser
4062
- });
4063
- }
4064
- const originalPresets = (config.presets ?? []).map(
4065
- (p) => typeof p === "string" ? p : p.name
4066
- );
4067
- const resolvedConfig = config.presets?.length ? applyPresets(config, config.presets) : config;
4068
- resolvedConfig._appliedPresets = originalPresets;
4069
- if (controller) {
4070
- const ctrl = controller;
4071
- if (typeof ctrl._setResourceOptions === "function") {
4072
- ctrl._setResourceOptions({
4073
- schemaOptions: resolvedConfig.schemaOptions,
4074
- presetFields: resolvedConfig._controllerOptions ? {
4075
- slugField: resolvedConfig._controllerOptions.slugField,
4076
- parentField: resolvedConfig._controllerOptions.parentField
4077
- } : void 0,
4078
- resourceName: resolvedConfig.name,
4079
- queryParser: resolvedConfig.queryParser
4080
- });
4081
- }
4082
- }
4083
- const resource = new ResourceDefinition({
4084
- ...resolvedConfig,
4085
- adapter: config.adapter,
4086
- controller
4087
- });
4088
- if (!config.skipValidation && controller) {
4089
- resource._validateControllerMethods();
4090
- }
4091
- if (resolvedConfig._hooks?.length) {
4092
- for (const hook of resolvedConfig._hooks) {
4093
- hookSystem.register({
4094
- resource: resolvedConfig.name,
4095
- operation: hook.operation,
4096
- phase: hook.phase,
4097
- handler: hook.handler,
4098
- priority: hook.priority ?? 10
4099
- });
4100
- }
4101
- }
4102
- if (!config.skipRegistry) {
4103
- try {
4104
- let openApiSchemas = config.openApiSchemas;
4105
- if (!openApiSchemas && config.adapter?.generateSchemas) {
4106
- const generated = config.adapter.generateSchemas(config.schemaOptions);
4107
- if (generated) {
4108
- openApiSchemas = generated;
4109
- }
4110
- }
4111
- const queryParser = config.queryParser;
4112
- if (!openApiSchemas?.listQuery && queryParser?.getQuerySchema) {
4113
- const querySchema = queryParser.getQuerySchema();
4114
- if (querySchema) {
4115
- openApiSchemas = {
4116
- ...openApiSchemas,
4117
- listQuery: querySchema
4118
- };
4119
- }
4120
- }
4121
- resourceRegistry.register(resource, {
4122
- module: config.module,
4123
- openApiSchemas
4124
- });
4125
- } catch {
4126
- }
4127
- }
4128
- return resource;
4129
- }
4130
- var ResourceDefinition = class {
4131
- // Identity
4132
- name;
4133
- displayName;
4134
- tag;
4135
- prefix;
4136
- // Adapter (database abstraction) - optional for service resources
4137
- adapter;
4138
- // Controller
4139
- controller;
4140
- // Schema & Validation
4141
- schemaOptions;
4142
- customSchemas;
4143
- // Security
4144
- permissions;
4145
- // Customization
4146
- additionalRoutes;
4147
- middlewares;
4148
- disableDefaultRoutes;
4149
- disabledRoutes;
4150
- organizationScoped;
4151
- // Events
4152
- events;
4153
- // Presets tracking
4154
- _appliedPresets;
4155
- constructor(config) {
4156
- this.name = config.name;
4157
- this.displayName = config.displayName ?? capitalize(config.name) + "s";
4158
- this.tag = config.tag ?? this.displayName;
4159
- this.prefix = config.prefix ?? `/${config.name}s`;
4160
- this.adapter = config.adapter;
4161
- this.controller = config.controller;
4162
- this.schemaOptions = config.schemaOptions ?? {};
4163
- this.customSchemas = config.customSchemas ?? {};
4164
- this.permissions = config.permissions ?? {};
4165
- this.additionalRoutes = config.additionalRoutes ?? [];
4166
- this.middlewares = config.middlewares ?? {};
4167
- this.disableDefaultRoutes = config.disableDefaultRoutes ?? false;
4168
- this.disabledRoutes = config.disabledRoutes ?? [];
4169
- this.organizationScoped = config.organizationScoped ?? false;
4170
- this.events = config.events ?? {};
4171
- this._appliedPresets = config._appliedPresets ?? [];
4172
- }
4173
- /** Get repository from adapter (if available) */
4174
- get repository() {
4175
- return this.adapter?.repository;
4176
- }
4177
- /** Get model from adapter (if available) */
4178
- get model() {
4179
- if (!this.adapter) return void 0;
4180
- return this.adapter.getSchemaMetadata?.() ? this.adapter.model : void 0;
4181
- }
4182
- _validateControllerMethods() {
4183
- const errors = [];
4184
- const crudRoutes = ["list", "get", "create", "update", "delete"];
4185
- const disabledRoutes = new Set(this.disabledRoutes ?? []);
4186
- const enabledCrudRoutes = crudRoutes.filter((route) => !disabledRoutes.has(route));
4187
- const hasCrudRoutes = !this.disableDefaultRoutes && enabledCrudRoutes.length > 0;
4188
- if (hasCrudRoutes) {
4189
- if (!this.controller) {
4190
- errors.push("Controller is required when CRUD routes are enabled");
4191
- } else {
4192
- const ctrl = this.controller;
4193
- for (const method of enabledCrudRoutes) {
4194
- if (typeof ctrl[method] !== "function") {
4195
- errors.push(`CRUD method '${method}' not found on controller`);
4196
- }
4197
- }
4198
- }
4199
- }
4200
- for (const route of this.additionalRoutes) {
4201
- if (typeof route.handler === "string") {
4202
- if (!this.controller) {
4203
- errors.push(
4204
- `Route ${route.method} ${route.path}: string handler '${route.handler}' requires a controller`
4205
- );
4206
- } else {
4207
- const ctrl = this.controller;
4208
- if (typeof ctrl[route.handler] !== "function") {
4209
- errors.push(
4210
- `Route ${route.method} ${route.path}: handler '${route.handler}' not found`
4211
- );
4212
- }
4213
- }
4214
- }
4215
- }
4216
- if (errors.length > 0) {
4217
- const errorMsg = [
4218
- `Resource '${this.name}' validation failed:`,
4219
- ...errors.map((e) => ` - ${e}`),
4220
- "",
4221
- "Ensure controller implements IController<TDoc> interface.",
4222
- "For preset routes (softDelete, tree), add corresponding methods to controller."
4223
- ].join("\n");
4224
- throw new Error(errorMsg);
4225
- }
4226
- }
4227
- toPlugin() {
4228
- const self = this;
4229
- return async function resourcePlugin(fastify, _opts) {
4230
- await fastify.register(async (instance) => {
4231
- const typedInstance = instance;
4232
- let schemas = null;
4233
- if (self.adapter) {
4234
- const metadata = self.adapter.getSchemaMetadata?.();
4235
- if (metadata && typedInstance.generateSchemas) {
4236
- const model = self.adapter.model;
4237
- if (model && typeof typedInstance.generateSchemas === "function") {
4238
- schemas = typedInstance.generateSchemas(model, self.schemaOptions);
4239
- }
4240
- }
4241
- }
4242
- if (self.customSchemas && Object.keys(self.customSchemas).length > 0) {
4243
- schemas = schemas ?? {};
4244
- for (const [op, customSchema] of Object.entries(self.customSchemas)) {
4245
- const key = op;
4246
- schemas[key] = schemas[key] ? deepMergeSchemas(schemas[key], customSchema) : customSchema;
4247
- }
4248
- }
4249
- const resolvedRoutes = self.additionalRoutes;
4250
- createCrudRouter(typedInstance, self.controller, {
4251
- tag: self.tag,
4252
- schemas: schemas ?? void 0,
4253
- permissions: self.permissions,
4254
- middlewares: self.middlewares,
4255
- additionalRoutes: resolvedRoutes,
4256
- disableDefaultRoutes: self.disableDefaultRoutes,
4257
- disabledRoutes: self.disabledRoutes,
4258
- organizationScoped: self.organizationScoped,
4259
- resourceName: self.name,
4260
- schemaOptions: self.schemaOptions
4261
- });
4262
- if (self.events && Object.keys(self.events).length > 0) {
4263
- typedInstance.log?.info?.(
4264
- `Resource '${self.name}' defined ${Object.keys(self.events).length} events`
4265
- );
4266
- }
4267
- }, { prefix: self.prefix });
4268
- };
4269
- }
4270
- /**
4271
- * Get event definitions for registry
4272
- */
4273
- getEvents() {
4274
- return Object.entries(this.events).map(([action, meta]) => ({
4275
- name: `${this.name}:${action}`,
4276
- module: this.name,
4277
- schema: meta.schema,
4278
- description: meta.description
4279
- }));
4280
- }
4281
- /**
4282
- * Get resource metadata
4283
- */
4284
- getMetadata() {
4285
- return {
4286
- name: this.name,
4287
- displayName: this.displayName,
4288
- tag: this.tag,
4289
- prefix: this.prefix,
4290
- presets: this._appliedPresets,
4291
- permissions: this.permissions,
4292
- additionalRoutes: this.additionalRoutes,
4293
- routes: [],
4294
- // Populated at runtime during registration
4295
- events: Object.keys(this.events)
4296
- };
4297
- }
4298
- };
4299
- function deepMergeSchemas(base, override) {
4300
- if (!override) return base;
4301
- if (!base) return override;
4302
- const result = { ...base };
4303
- for (const [key, value] of Object.entries(override)) {
4304
- if (value && typeof value === "object" && !Array.isArray(value)) {
4305
- result[key] = deepMergeSchemas(result[key], value);
4306
- } else {
4307
- result[key] = value;
4308
- }
4309
- }
4310
- return result;
4311
- }
4312
- function capitalize(str) {
4313
- if (!str) return "";
4314
- return str.charAt(0).toUpperCase() + str.slice(1);
4315
- }
4316
-
4317
- // src/utils/index.ts
4318
- init_errors();
4319
-
4320
- // src/index.ts
4321
- init_plugins();
4322
-
4323
- // src/events/EventTransport.ts
4324
- var MemoryEventTransport = class {
4325
- name = "memory";
4326
- handlers = /* @__PURE__ */ new Map();
4327
- async publish(event) {
4328
- const exactHandlers = this.handlers.get(event.type) ?? /* @__PURE__ */ new Set();
4329
- const wildcardHandlers = this.handlers.get("*") ?? /* @__PURE__ */ new Set();
4330
- const patternHandlers = /* @__PURE__ */ new Set();
4331
- for (const [pattern, handlers] of this.handlers.entries()) {
4332
- if (pattern.endsWith(".*")) {
4333
- const prefix = pattern.slice(0, -2);
4334
- if (event.type.startsWith(prefix + ".")) {
4335
- handlers.forEach((h) => patternHandlers.add(h));
4336
- }
4337
- }
4338
- }
4339
- const allHandlers = /* @__PURE__ */ new Set([...exactHandlers, ...wildcardHandlers, ...patternHandlers]);
4340
- for (const handler of allHandlers) {
4341
- try {
4342
- await handler(event);
4343
- } catch (err) {
4344
- console.error(`[EventTransport] Handler error for ${event.type}:`, err);
4345
- }
4346
- }
4347
- }
4348
- async subscribe(pattern, handler) {
4349
- if (!this.handlers.has(pattern)) {
4350
- this.handlers.set(pattern, /* @__PURE__ */ new Set());
4351
- }
4352
- this.handlers.get(pattern).add(handler);
4353
- return () => {
4354
- this.handlers.get(pattern)?.delete(handler);
4355
- };
4356
- }
4357
- async close() {
4358
- this.handlers.clear();
4359
- }
4360
- };
4361
- function createEvent(type, payload, meta) {
4362
- return {
4363
- type,
4364
- payload,
4365
- meta: {
4366
- id: crypto.randomUUID(),
4367
- timestamp: /* @__PURE__ */ new Date(),
4368
- ...meta
4369
- }
4370
- };
4371
- }
4372
- var eventPlugin = async (fastify, opts = {}) => {
4373
- const {
4374
- transport = new MemoryEventTransport(),
4375
- logEvents = false
4376
- } = opts;
4377
- fastify.decorate("events", {
4378
- publish: async (type, payload, meta) => {
4379
- const event = createEvent(type, payload, meta);
4380
- if (logEvents) {
4381
- fastify.log?.info?.({ eventType: type, eventId: event.meta.id }, "Publishing event");
4382
- }
4383
- await transport.publish(event);
4384
- },
4385
- subscribe: async (pattern, handler) => {
4386
- if (logEvents) {
4387
- fastify.log?.info?.({ pattern }, "Subscribing to events");
4388
- }
4389
- return transport.subscribe(pattern, handler);
4390
- },
4391
- transportName: transport.name
4392
- });
4393
- fastify.addHook("onClose", async () => {
4394
- await transport.close?.();
4395
- });
4396
- if (transport.name === "memory") {
4397
- fastify.log?.warn?.(
4398
- "[Arc Events] Using in-memory transport. Events will not persist or scale across instances. For production, configure a durable transport (Redis, RabbitMQ, etc.)"
4399
- );
4400
- } else {
4401
- fastify.log?.info?.(`[Arc Events] Using ${transport.name} transport`);
4402
- }
4403
- };
4404
- fp(eventPlugin, {
4405
- name: "arc-events",
4406
- fastify: "5.x"
4407
- });
4408
-
4409
- // src/factory/presets.ts
4410
- var productionPreset = {
4411
- // Raw JSON logs for production (log aggregators like Datadog, CloudWatch, etc.)
4412
- logger: {
4413
- level: "info"
4414
- },
4415
- trustProxy: true,
4416
- // Security
4417
- helmet: {
4418
- contentSecurityPolicy: {
4419
- directives: {
4420
- defaultSrc: ["'self'"],
4421
- styleSrc: ["'self'", "'unsafe-inline'"],
4422
- scriptSrc: ["'self'"],
4423
- imgSrc: ["'self'", "data:", "https:"]
4424
- }
4425
- }
4426
- },
4427
- // CORS - must be explicitly configured
4428
- cors: {
4429
- origin: false,
4430
- // Disabled by default in production
4431
- credentials: true,
4432
- methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
4433
- allowedHeaders: ["Content-Type", "Authorization", "Accept"]
4434
- },
4435
- // Rate limiting - strict
4436
- rateLimit: {
4437
- max: 100,
4438
- timeWindow: "1 minute"
4439
- },
4440
- // Note: Compression not included (use proxy/CDN instead)
4441
- // Under pressure - health monitoring
4442
- underPressure: {
4443
- exposeStatusRoute: true,
4444
- maxEventLoopDelay: 1e3,
4445
- maxHeapUsedBytes: 1024 * 1024 * 1024,
4446
- // 1GB
4447
- maxRssBytes: 1024 * 1024 * 1024
4448
- // 1GB
4449
- }
4450
- };
4451
- var developmentPreset = {
4452
- logger: {
4453
- level: "debug",
4454
- transport: {
4455
- target: "pino-pretty",
4456
- options: {
4457
- colorize: true,
4458
- translateTime: "SYS:HH:MM:ss",
4459
- ignore: "pid,hostname"
4460
- }
4461
- }
4462
- },
4463
- trustProxy: true,
4464
- // Security - relaxed for development
4465
- helmet: {
4466
- contentSecurityPolicy: false
4467
- // Disable CSP in dev
4468
- },
4469
- // CORS - allow all origins in development
4470
- cors: {
4471
- origin: true,
4472
- // Allow all origins
4473
- credentials: true,
4474
- methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
4475
- allowedHeaders: ["Content-Type", "Authorization", "Accept"]
4476
- },
4477
- // Rate limiting - very relaxed
4478
- rateLimit: {
4479
- max: 1e3,
4480
- timeWindow: "1 minute"
4481
- },
4482
- // Note: Compression not included (use proxy/CDN instead)
4483
- // Under pressure - relaxed
4484
- underPressure: {
4485
- exposeStatusRoute: true,
4486
- maxEventLoopDelay: 5e3
4487
- }
4488
- };
4489
- var testingPreset = {
4490
- logger: false,
4491
- // Disable logging in tests
4492
- trustProxy: false,
4493
- // Security - disabled for tests
4494
- helmet: false,
4495
- cors: false,
4496
- rateLimit: false,
4497
- underPressure: false,
4498
- // Sensible plugins still enabled
4499
- sensible: true,
4500
- multipart: {
4501
- limits: {
4502
- fileSize: 1024 * 1024,
4503
- // 1MB
4504
- files: 5
4505
- }
4506
- }
4507
- };
4508
- function getPreset(name) {
4509
- switch (name) {
4510
- case "production":
4511
- return productionPreset;
4512
- case "development":
4513
- return developmentPreset;
4514
- case "testing":
4515
- return testingPreset;
4516
- default:
4517
- throw new Error(`Unknown preset: ${name}`);
4518
- }
4519
- }
4520
-
4521
- // src/factory/createApp.ts
4522
- var PLUGIN_PACKAGES = {
4523
- cors: "@fastify/cors",
4524
- helmet: "@fastify/helmet",
4525
- rateLimit: "@fastify/rate-limit",
4526
- underPressure: "@fastify/under-pressure",
4527
- sensible: "@fastify/sensible",
4528
- multipart: "@fastify/multipart",
4529
- rawBody: "fastify-raw-body"
4530
- };
4531
- var OPTIONAL_PLUGINS = /* @__PURE__ */ new Set(["multipart", "rawBody"]);
4532
- async function loadPlugin(name, logger) {
4533
- const packageName = PLUGIN_PACKAGES[name];
4534
- if (!packageName) {
4535
- throw new Error(`Unknown plugin: ${name}`);
4536
- }
4537
- try {
4538
- switch (name) {
4539
- case "cors":
4540
- return (await import('@fastify/cors')).default;
4541
- case "helmet":
4542
- return (await import('@fastify/helmet')).default;
4543
- case "rateLimit":
4544
- return (await import('@fastify/rate-limit')).default;
4545
- case "underPressure":
4546
- return (await import('@fastify/under-pressure')).default;
4547
- case "sensible":
4548
- return (await import('@fastify/sensible')).default;
4549
- case "multipart":
4550
- return (await import('@fastify/multipart')).default;
4551
- case "rawBody":
4552
- return (await import('fastify-raw-body')).default;
4553
- default:
4554
- throw new Error(`Unknown plugin: ${name}`);
4555
- }
4556
- } catch (error) {
4557
- const err = error;
4558
- const isModuleNotFound = err.message.includes("Cannot find module") || err.message.includes("Cannot find package") || err.message.includes("MODULE_NOT_FOUND") || err.message.includes("Could not resolve");
4559
- if (isModuleNotFound && OPTIONAL_PLUGINS.has(name)) {
4560
- logger?.warn(`ℹ️ Optional plugin '${name}' skipped (${packageName} not installed)`);
4561
- return null;
4562
- }
4563
- if (isModuleNotFound) {
4564
- throw new Error(
4565
- `Plugin '${name}' requires package '${packageName}' which is not installed.
4566
- Install it with: npm install ${packageName}
4567
- Or disable this plugin by setting ${name}: false in createApp options.`
4568
- );
4569
- }
4570
- throw new Error(`Failed to load plugin '${name}': ${err.message}`);
4571
- }
4572
- }
4573
- async function createApp(options) {
4574
- const authConfig = options.auth;
4575
- const isAuthDisabled = authConfig === false;
4576
- const hasCustomPlugin = typeof authConfig === "object" && "plugin" in authConfig && authConfig.plugin;
4577
- const hasCustomAuthenticator = typeof authConfig === "object" && "authenticate" in authConfig;
4578
- const jwtSecret = typeof authConfig === "object" && "jwt" in authConfig ? authConfig.jwt?.secret : void 0;
4579
- if (!isAuthDisabled && !hasCustomPlugin && !jwtSecret && !hasCustomAuthenticator) {
4580
- throw new Error(
4581
- "createApp: JWT secret required when Arc auth is enabled.\nProvide auth.jwt.secret, auth.authenticate, or set auth: false to disable.\nExample: auth: { jwt: { secret: process.env.JWT_SECRET } }"
4582
- );
4583
- }
4584
- const presetConfig = options.preset ? getPreset(options.preset) : {};
4585
- const config = { ...presetConfig, ...options };
4586
- const fastify = Fastify({
4587
- logger: config.logger ?? true,
4588
- trustProxy: config.trustProxy ?? false,
4589
- ajv: {
4590
- customOptions: {
4591
- coerceTypes: true,
4592
- useDefaults: true,
4593
- removeAdditional: false
4594
- }
4595
- }
4596
- });
4597
- if (config.helmet !== false) {
4598
- const helmet = await loadPlugin("helmet");
4599
- await fastify.register(helmet, config.helmet ?? {});
4600
- fastify.log.info("✅ Helmet (security headers) enabled");
4601
- } else {
4602
- fastify.log.warn("⚠️ Helmet disabled - security headers not applied");
4603
- }
4604
- if (config.cors !== false) {
4605
- const cors = await loadPlugin("cors");
4606
- const corsOptions = config.cors ?? {};
4607
- if (config.preset === "production" && (!corsOptions || !("origin" in corsOptions))) {
4608
- throw new Error(
4609
- "CORS origin must be explicitly configured in production.\nSet cors.origin to allowed domains or set cors: false to disable.\nExample: cors: { origin: ['https://yourdomain.com'] }\nDocs: https://github.com/classytic/arc#security"
4610
- );
4611
- }
4612
- await fastify.register(cors, corsOptions);
4613
- fastify.log.info("✅ CORS enabled");
4614
- } else {
4615
- fastify.log.warn("⚠️ CORS disabled");
4616
- }
4617
- if (config.rateLimit !== false) {
4618
- const rateLimit = await loadPlugin("rateLimit");
4619
- await fastify.register(rateLimit, config.rateLimit ?? { max: 100, timeWindow: "1 minute" });
4620
- fastify.log.info("✅ Rate limiting enabled");
4621
- } else {
4622
- fastify.log.warn("⚠️ Rate limiting disabled");
4623
- }
4624
- if (config.underPressure !== false) {
4625
- const underPressure = await loadPlugin("underPressure");
4626
- await fastify.register(underPressure, config.underPressure ?? { exposeStatusRoute: true });
4627
- fastify.log.info("✅ Health monitoring (under-pressure) enabled");
4628
- } else {
4629
- fastify.log.info("ℹ️ Health monitoring disabled");
4630
- }
4631
- if (config.sensible !== false) {
4632
- const sensible = await loadPlugin("sensible");
4633
- await fastify.register(sensible);
4634
- fastify.log.info("✅ Sensible (HTTP helpers) enabled");
4635
- }
4636
- if (config.multipart !== false) {
4637
- const multipart = await loadPlugin("multipart", fastify.log);
4638
- if (multipart) {
4639
- const multipartDefaults = {
4640
- limits: {
4641
- fileSize: 10 * 1024 * 1024,
4642
- // 10MB
4643
- files: 10
4644
- }
4645
- };
4646
- await fastify.register(multipart, { ...multipartDefaults, ...config.multipart });
4647
- fastify.log.info("✅ Multipart (file uploads) enabled");
4648
- }
4649
- }
4650
- if (config.rawBody !== false) {
4651
- const rawBody = await loadPlugin("rawBody", fastify.log);
4652
- if (rawBody) {
4653
- const rawBodyDefaults = {
4654
- field: "rawBody",
4655
- global: false,
4656
- encoding: "utf8",
4657
- runFirst: true
4658
- };
4659
- await fastify.register(rawBody, { ...rawBodyDefaults, ...config.rawBody });
4660
- fastify.log.info("✅ Raw body parsing enabled");
4661
- }
4662
- }
4663
- const { arcCorePlugin: arcCorePlugin2 } = await Promise.resolve().then(() => (init_plugins(), plugins_exports));
4664
- await fastify.register(arcCorePlugin2, {
4665
- emitEvents: config.arcPlugins?.emitEvents !== false
4666
- });
4667
- if (config.arcPlugins?.requestId !== false) {
4668
- const { requestIdPlugin: requestIdPlugin2 } = await Promise.resolve().then(() => (init_plugins(), plugins_exports));
4669
- await fastify.register(requestIdPlugin2);
4670
- fastify.log.info("✅ Arc requestId plugin enabled");
4671
- }
4672
- if (config.arcPlugins?.health !== false) {
4673
- const { healthPlugin: healthPlugin2 } = await Promise.resolve().then(() => (init_plugins(), plugins_exports));
4674
- await fastify.register(healthPlugin2);
4675
- fastify.log.info("✅ Arc health plugin enabled");
4676
- }
4677
- if (config.arcPlugins?.gracefulShutdown !== false) {
4678
- const { gracefulShutdownPlugin: gracefulShutdownPlugin2 } = await Promise.resolve().then(() => (init_plugins(), plugins_exports));
4679
- await fastify.register(gracefulShutdownPlugin2);
4680
- fastify.log.info("✅ Arc gracefulShutdown plugin enabled");
4681
- }
4682
- if (!isAuthDisabled) {
4683
- if (hasCustomPlugin) {
4684
- const pluginFn = authConfig.plugin;
4685
- await pluginFn(fastify);
4686
- fastify.log.info("✅ Custom authentication plugin enabled");
4687
- } else {
4688
- const { authPlugin: authPlugin2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
4689
- const { plugin: _, ...authOpts } = typeof authConfig === "object" ? authConfig : {};
4690
- await fastify.register(authPlugin2, authOpts);
4691
- fastify.log.info("✅ Arc authentication plugin enabled");
4692
- }
4693
- } else {
4694
- fastify.log.info("ℹ️ Authentication disabled");
4695
- }
4696
- if (config.plugins) {
4697
- await config.plugins(fastify);
4698
- fastify.log.info("✅ Custom plugins registered");
4699
- }
4700
- fastify.log.info(
4701
- `🚀 Arc application created successfully (preset: ${config.preset ?? "custom"}, security: helmet=${config.helmet !== false}, cors=${config.cors !== false}, rateLimit=${config.rateLimit !== false})`
4702
- );
4703
- return fastify;
4704
- }
4705
- var ArcFactory = {
4706
- /**
4707
- * Create production app with strict security
4708
- */
4709
- async production(options) {
4710
- return createApp({ ...options, preset: "production" });
4711
- },
4712
- /**
4713
- * Create development app with relaxed security
4714
- */
4715
- async development(options) {
4716
- return createApp({ ...options, preset: "development" });
4717
- },
4718
- /**
4719
- * Create testing app with minimal setup
4720
- */
4721
- async testing(options) {
4722
- return createApp({ ...options, preset: "testing" });
4723
- }
4724
- };
4725
-
4726
- // src/index.ts
4727
- var version = "1.0.0";
4728
-
4729
- export { ArcError, ArcFactory, BaseController, ForbiddenError, MongooseAdapter, NotFoundError, PrismaAdapter, ResourceDefinition, UnauthorizedError, ValidationError, allOf, allowPublic, anyOf, assertValidConfig, createApp, createMongooseAdapter, createPrismaAdapter, defineResource, denyAll, eventPlugin, formatValidationErrors, gracefulShutdown_default as gracefulShutdownPlugin, health_default as healthPlugin, hookSystem, requestId_default as requestIdPlugin, requireAuth, requireOwnership, requireRoles, resourceRegistry, validateResourceConfig, version, when };