@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
@@ -1,2764 +0,0 @@
1
- // src/types/index.ts
2
- function getUserId(user) {
3
- if (!user) return void 0;
4
- const id = user.id ?? user._id;
5
- return id ? String(id) : void 0;
6
- }
7
-
8
- // src/hooks/HookSystem.ts
9
- var HookSystem = class {
10
- hooks;
11
- logger;
12
- constructor(options) {
13
- this.hooks = /* @__PURE__ */ new Map();
14
- this.logger = options?.logger ?? { error: (...args) => console.error(...args) };
15
- }
16
- /**
17
- * Generate hook key
18
- */
19
- getKey(resource, operation, phase) {
20
- return `${resource}:${operation}:${phase}`;
21
- }
22
- /**
23
- * Register a hook
24
- * Supports both object parameter and positional arguments
25
- */
26
- register(resourceOrOptions, operation, phase, handler, priority = 10) {
27
- let resource;
28
- let finalOperation;
29
- let finalPhase;
30
- let finalHandler;
31
- let finalPriority;
32
- if (typeof resourceOrOptions === "object") {
33
- resource = resourceOrOptions.resource;
34
- finalOperation = resourceOrOptions.operation;
35
- finalPhase = resourceOrOptions.phase;
36
- finalHandler = resourceOrOptions.handler;
37
- finalPriority = resourceOrOptions.priority ?? 10;
38
- } else {
39
- resource = resourceOrOptions;
40
- finalOperation = operation;
41
- finalPhase = phase;
42
- finalHandler = handler;
43
- finalPriority = priority;
44
- }
45
- const key = this.getKey(resource, finalOperation, finalPhase);
46
- if (!this.hooks.has(key)) {
47
- this.hooks.set(key, []);
48
- }
49
- const registration = {
50
- resource,
51
- operation: finalOperation,
52
- phase: finalPhase,
53
- handler: finalHandler,
54
- priority: finalPriority
55
- };
56
- const hooks = this.hooks.get(key);
57
- hooks.push(registration);
58
- hooks.sort((a, b) => a.priority - b.priority);
59
- return () => {
60
- const idx = hooks.indexOf(registration);
61
- if (idx !== -1) {
62
- hooks.splice(idx, 1);
63
- }
64
- };
65
- }
66
- /**
67
- * Register before hook
68
- */
69
- before(resource, operation, handler, priority = 10) {
70
- return this.register(resource, operation, "before", handler, priority);
71
- }
72
- /**
73
- * Register after hook
74
- */
75
- after(resource, operation, handler, priority = 10) {
76
- return this.register(resource, operation, "after", handler, priority);
77
- }
78
- /**
79
- * Execute hooks for a given context
80
- */
81
- async execute(ctx) {
82
- const key = this.getKey(ctx.resource, ctx.operation, ctx.phase);
83
- const hooks = this.hooks.get(key) ?? [];
84
- const wildcardKey = this.getKey("*", ctx.operation, ctx.phase);
85
- const wildcardHooks = this.hooks.get(wildcardKey) ?? [];
86
- const allHooks = [...wildcardHooks, ...hooks];
87
- allHooks.sort((a, b) => a.priority - b.priority);
88
- let result = ctx.data;
89
- for (const hook of allHooks) {
90
- const handlerContext = {
91
- resource: ctx.resource,
92
- operation: ctx.operation,
93
- phase: ctx.phase,
94
- data: result,
95
- result: ctx.result,
96
- user: ctx.user,
97
- context: ctx.context,
98
- meta: ctx.meta
99
- };
100
- const hookResult = await hook.handler(handlerContext);
101
- if (hookResult !== void 0 && hookResult !== null) {
102
- result = hookResult;
103
- }
104
- }
105
- return result;
106
- }
107
- /**
108
- * Execute before hooks
109
- */
110
- async executeBefore(resource, operation, data, options) {
111
- const result = await this.execute({
112
- resource,
113
- operation,
114
- phase: "before",
115
- data,
116
- user: options?.user,
117
- context: options?.context,
118
- meta: options?.meta
119
- });
120
- return result ?? data;
121
- }
122
- /**
123
- * Execute after hooks
124
- * Errors in after hooks are logged but don't fail the request
125
- */
126
- async executeAfter(resource, operation, result, options) {
127
- try {
128
- await this.execute({
129
- resource,
130
- operation,
131
- phase: "after",
132
- result,
133
- user: options?.user,
134
- context: options?.context,
135
- meta: options?.meta
136
- });
137
- } catch (error) {
138
- this.logger.error(
139
- `[HookSystem] Error in after hook for ${resource}:${operation}:`,
140
- error
141
- );
142
- }
143
- }
144
- /**
145
- * Get all registered hooks
146
- */
147
- getAll() {
148
- const all = [];
149
- for (const hooks of this.hooks.values()) {
150
- all.push(...hooks);
151
- }
152
- return all;
153
- }
154
- /**
155
- * Get hooks for a specific resource
156
- */
157
- getForResource(resource) {
158
- const all = [];
159
- for (const [key, hooks] of this.hooks.entries()) {
160
- if (key.startsWith(`${resource}:`)) {
161
- all.push(...hooks);
162
- }
163
- }
164
- return all;
165
- }
166
- /**
167
- * Clear all hooks
168
- */
169
- clear() {
170
- this.hooks.clear();
171
- }
172
- /**
173
- * Clear hooks for a specific resource
174
- */
175
- clearResource(resource) {
176
- for (const key of this.hooks.keys()) {
177
- if (key.startsWith(`${resource}:`)) {
178
- this.hooks.delete(key);
179
- }
180
- }
181
- }
182
- };
183
- var hookSystem = new HookSystem();
184
-
185
- // src/utils/queryParser.ts
186
- var DANGEROUS_REGEX_PATTERNS = /(\{[0-9,]+\}|\*\+|\+\+|\?\+|(\(.+\))\+|\(\?\:|\\[0-9]|(\[.+\]).+(\[.+\]))/;
187
- var MAX_REGEX_LENGTH = 500;
188
- var MAX_SEARCH_LENGTH = 200;
189
- var MAX_FILTER_DEPTH = 10;
190
- var MAX_LIMIT = 1e3;
191
- var DEFAULT_LIMIT = 20;
192
- var ArcQueryParser = class {
193
- maxLimit;
194
- defaultLimit;
195
- maxRegexLength;
196
- maxSearchLength;
197
- maxFilterDepth;
198
- /** Supported filter operators */
199
- operators = {
200
- eq: "$eq",
201
- ne: "$ne",
202
- gt: "$gt",
203
- gte: "$gte",
204
- lt: "$lt",
205
- lte: "$lte",
206
- in: "$in",
207
- nin: "$nin",
208
- like: "$regex",
209
- contains: "$regex",
210
- regex: "$regex",
211
- exists: "$exists"
212
- };
213
- constructor(options = {}) {
214
- this.maxLimit = options.maxLimit ?? MAX_LIMIT;
215
- this.defaultLimit = options.defaultLimit ?? DEFAULT_LIMIT;
216
- this.maxRegexLength = options.maxRegexLength ?? MAX_REGEX_LENGTH;
217
- this.maxSearchLength = options.maxSearchLength ?? MAX_SEARCH_LENGTH;
218
- this.maxFilterDepth = options.maxFilterDepth ?? MAX_FILTER_DEPTH;
219
- }
220
- /**
221
- * Parse URL query parameters into structured query options
222
- */
223
- parse(query) {
224
- const q = query ?? {};
225
- const page = this.parseNumber(q.page, 1);
226
- const limit = Math.min(this.parseNumber(q.limit, this.defaultLimit), this.maxLimit);
227
- const after = this.parseString(q.after ?? q.cursor);
228
- const sort = this.parseSort(q.sort);
229
- const populate = this.parseString(q.populate);
230
- const search = this.parseSearch(q.search);
231
- const select = this.parseSelect(q.select);
232
- const filters = this.parseFilters(q);
233
- return {
234
- filters,
235
- limit,
236
- sort,
237
- populate,
238
- search,
239
- page: after ? void 0 : page,
240
- after,
241
- select
242
- };
243
- }
244
- // ============================================================================
245
- // Parse Helpers
246
- // ============================================================================
247
- parseNumber(value, defaultValue) {
248
- if (value === void 0 || value === null) return defaultValue;
249
- const num = parseInt(String(value), 10);
250
- return Number.isNaN(num) ? defaultValue : Math.max(1, num);
251
- }
252
- parseString(value) {
253
- if (value === void 0 || value === null) return void 0;
254
- const str = String(value).trim();
255
- return str.length > 0 ? str : void 0;
256
- }
257
- parseSort(value) {
258
- if (!value) return void 0;
259
- const sortStr = String(value);
260
- const result = {};
261
- for (const field of sortStr.split(",")) {
262
- const trimmed = field.trim();
263
- if (!trimmed) continue;
264
- if (!/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test(trimmed)) continue;
265
- if (trimmed.startsWith("-")) {
266
- result[trimmed.slice(1)] = -1;
267
- } else {
268
- result[trimmed] = 1;
269
- }
270
- }
271
- return Object.keys(result).length > 0 ? result : void 0;
272
- }
273
- parseSearch(value) {
274
- if (!value) return void 0;
275
- const search = String(value).trim();
276
- if (search.length === 0) return void 0;
277
- if (search.length > this.maxSearchLength) {
278
- return search.slice(0, this.maxSearchLength);
279
- }
280
- return search;
281
- }
282
- parseSelect(value) {
283
- if (!value) return void 0;
284
- const selectStr = String(value);
285
- const result = {};
286
- for (const field of selectStr.split(",")) {
287
- const trimmed = field.trim();
288
- if (!trimmed) continue;
289
- if (!/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test(trimmed)) continue;
290
- if (trimmed.startsWith("-")) {
291
- result[trimmed.slice(1)] = 0;
292
- } else {
293
- result[trimmed] = 1;
294
- }
295
- }
296
- return Object.keys(result).length > 0 ? result : void 0;
297
- }
298
- parseFilters(query) {
299
- const reservedKeys = /* @__PURE__ */ new Set([
300
- "page",
301
- "limit",
302
- "sort",
303
- "populate",
304
- "search",
305
- "select",
306
- "after",
307
- "cursor",
308
- "lean",
309
- "_policyFilters"
310
- ]);
311
- const filters = {};
312
- for (const [key, value] of Object.entries(query)) {
313
- if (reservedKeys.has(key)) continue;
314
- if (value === void 0 || value === null) continue;
315
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_.]*)(?:\[([a-z]+)\])?$/);
316
- if (!match) continue;
317
- const [, fieldName, operator] = match;
318
- if (!fieldName) continue;
319
- if (operator && this.operators[operator]) {
320
- const mongoOp = this.operators[operator];
321
- const parsedValue = this.parseFilterValue(value, operator);
322
- if (!filters[fieldName]) {
323
- filters[fieldName] = {};
324
- }
325
- filters[fieldName][mongoOp] = parsedValue;
326
- } else if (!operator) {
327
- filters[fieldName] = this.parseFilterValue(value);
328
- }
329
- }
330
- return filters;
331
- }
332
- parseFilterValue(value, operator) {
333
- if (operator === "in" || operator === "nin") {
334
- if (Array.isArray(value)) {
335
- return value.map((v) => this.coerceValue(v));
336
- }
337
- if (typeof value === "string" && value.includes(",")) {
338
- return value.split(",").map((v) => this.coerceValue(v.trim()));
339
- }
340
- return [this.coerceValue(value)];
341
- }
342
- if (operator === "like" || operator === "contains" || operator === "regex") {
343
- return this.sanitizeRegex(String(value));
344
- }
345
- if (operator === "exists") {
346
- const str = String(value).toLowerCase();
347
- return str === "true" || str === "1";
348
- }
349
- return this.coerceValue(value);
350
- }
351
- coerceValue(value) {
352
- if (value === "true") return true;
353
- if (value === "false") return false;
354
- if (value === "null") return null;
355
- if (typeof value === "string") {
356
- const num = Number(value);
357
- if (!Number.isNaN(num) && value.trim() !== "") {
358
- return num;
359
- }
360
- }
361
- return value;
362
- }
363
- sanitizeRegex(pattern) {
364
- let sanitized = pattern.slice(0, this.maxRegexLength);
365
- if (DANGEROUS_REGEX_PATTERNS.test(sanitized)) {
366
- sanitized = sanitized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
367
- }
368
- return sanitized;
369
- }
370
- };
371
-
372
- // src/core/BaseController.ts
373
- var defaultParser = new ArcQueryParser();
374
- function getDefaultQueryParser() {
375
- return defaultParser;
376
- }
377
- var BaseController = class _BaseController {
378
- repository;
379
- schemaOptions;
380
- queryParser;
381
- maxLimit;
382
- defaultLimit;
383
- defaultSort;
384
- resourceName;
385
- disableEvents;
386
- /** Preset field names for dynamic param reading */
387
- _presetFields = {};
388
- constructor(repository, options = {}) {
389
- this.repository = repository;
390
- this.schemaOptions = options.schemaOptions ?? {};
391
- this.queryParser = options.queryParser ?? getDefaultQueryParser();
392
- this.maxLimit = options.maxLimit ?? 100;
393
- this.defaultLimit = options.defaultLimit ?? 20;
394
- this.defaultSort = options.defaultSort ?? "-createdAt";
395
- this.resourceName = options.resourceName;
396
- this.disableEvents = options.disableEvents ?? false;
397
- this.list = this.list.bind(this);
398
- this.get = this.get.bind(this);
399
- this.create = this.create.bind(this);
400
- this.update = this.update.bind(this);
401
- this.delete = this.delete.bind(this);
402
- }
403
- /**
404
- * Inject resource options from defineResource
405
- */
406
- _setResourceOptions(options) {
407
- if (options.schemaOptions) {
408
- this.schemaOptions = { ...this.schemaOptions, ...options.schemaOptions };
409
- }
410
- if (options.presetFields) {
411
- this._presetFields = { ...this._presetFields, ...options.presetFields };
412
- }
413
- if (options.resourceName) {
414
- this.resourceName = options.resourceName;
415
- }
416
- if (options.queryParser) {
417
- this.queryParser = options.queryParser;
418
- }
419
- }
420
- // ============================================================================
421
- // Context & Query Parsing
422
- // ============================================================================
423
- /**
424
- * Build service context from IRequestContext
425
- */
426
- _buildContext(req) {
427
- const parsed = this.queryParser.parse(req.query);
428
- const arcContext = req.metadata;
429
- const selectString = this._selectToString(parsed.select) ?? req.query?.select;
430
- const sanitizedSelect = this._sanitizeSelect(selectString, this.schemaOptions);
431
- return {
432
- user: req.user,
433
- organizationId: arcContext?.organizationId ?? req.organizationId ?? void 0,
434
- select: sanitizedSelect ? sanitizedSelect.split(/\s+/) : void 0,
435
- populate: this._sanitizePopulate(parsed.populate, this.schemaOptions),
436
- lean: this._parseLean(req.query?.lean)
437
- };
438
- }
439
- /**
440
- * Parse query into QueryOptions using queryParser
441
- */
442
- _parseQueryOptions(req) {
443
- const parsed = this.queryParser.parse(req.query);
444
- const arcContext = req.metadata;
445
- delete parsed.filters._policyFilters;
446
- const limit = Math.min(Math.max(1, parsed.limit || this.defaultLimit), this.maxLimit);
447
- const page = parsed.after ? void 0 : parsed.page ? Math.max(1, parsed.page) : 1;
448
- const sortString = parsed.sort ? Object.entries(parsed.sort).map(([k, v]) => v === -1 ? `-${k}` : k).join(",") : this.defaultSort;
449
- const selectString = this._selectToString(parsed.select) ?? req.query?.select;
450
- return {
451
- page,
452
- limit,
453
- sort: sortString,
454
- select: this._sanitizeSelect(selectString, this.schemaOptions),
455
- populate: this._sanitizePopulate(parsed.populate, this.schemaOptions),
456
- filters: parsed.filters,
457
- // MongoKit features
458
- search: parsed.search,
459
- after: parsed.after,
460
- user: req.user,
461
- organizationId: arcContext?.organizationId ?? req.organizationId,
462
- context: arcContext
463
- };
464
- }
465
- /**
466
- * Apply org and policy filters
467
- */
468
- _applyFilters(options, req) {
469
- const filters = { ...options.filters };
470
- const arcContext = req.metadata;
471
- const policyFilters = arcContext?._policyFilters;
472
- if (policyFilters) {
473
- Object.assign(filters, policyFilters);
474
- }
475
- const orgId = arcContext?.organizationId ?? req.organizationId;
476
- if (orgId) {
477
- filters.organizationId = orgId;
478
- }
479
- return { ...options, filters };
480
- }
481
- /**
482
- * Build filter for single-item operations (get/update/delete)
483
- * Combines ID filter with policy/org filters for proper security enforcement
484
- */
485
- _buildIdFilter(id, req) {
486
- const filter = { _id: id };
487
- const arcContext = req.metadata;
488
- const policyFilters = arcContext?._policyFilters;
489
- if (policyFilters) {
490
- Object.assign(filter, policyFilters);
491
- }
492
- const orgId = arcContext?.organizationId ?? req.organizationId;
493
- if (orgId) {
494
- filter.organizationId = orgId;
495
- }
496
- return filter;
497
- }
498
- /**
499
- * Check if a value matches a MongoDB query operator
500
- */
501
- _matchesOperator(itemValue, operator, filterValue) {
502
- switch (operator) {
503
- case "$eq":
504
- return itemValue === filterValue;
505
- case "$ne":
506
- return itemValue !== filterValue;
507
- case "$gt":
508
- return typeof itemValue === "number" && typeof filterValue === "number" && itemValue > filterValue;
509
- case "$gte":
510
- return typeof itemValue === "number" && typeof filterValue === "number" && itemValue >= filterValue;
511
- case "$lt":
512
- return typeof itemValue === "number" && typeof filterValue === "number" && itemValue < filterValue;
513
- case "$lte":
514
- return typeof itemValue === "number" && typeof filterValue === "number" && itemValue <= filterValue;
515
- case "$in":
516
- return Array.isArray(filterValue) && filterValue.includes(itemValue);
517
- case "$nin":
518
- return Array.isArray(filterValue) && !filterValue.includes(itemValue);
519
- case "$exists":
520
- return filterValue ? itemValue !== void 0 : itemValue === void 0;
521
- case "$regex":
522
- if (typeof itemValue === "string" && (typeof filterValue === "string" || filterValue instanceof RegExp)) {
523
- const regex = typeof filterValue === "string" ? new RegExp(filterValue) : filterValue;
524
- return regex.test(itemValue);
525
- }
526
- return false;
527
- default:
528
- return false;
529
- }
530
- }
531
- /**
532
- * Forbidden paths that could lead to prototype pollution
533
- */
534
- static FORBIDDEN_PATHS = ["__proto__", "constructor", "prototype"];
535
- /**
536
- * Get nested value from object using dot notation (e.g., "owner.id")
537
- * Security: Validates path against forbidden patterns to prevent prototype pollution
538
- */
539
- _getNestedValue(obj, path) {
540
- if (_BaseController.FORBIDDEN_PATHS.some((p) => path.toLowerCase().includes(p))) {
541
- return void 0;
542
- }
543
- const keys = path.split(".");
544
- let value = obj;
545
- for (const key of keys) {
546
- if (value == null) return void 0;
547
- if (_BaseController.FORBIDDEN_PATHS.includes(key.toLowerCase())) {
548
- return void 0;
549
- }
550
- value = value[key];
551
- }
552
- return value;
553
- }
554
- /**
555
- * Check if item matches a single filter condition
556
- * Supports nested paths (e.g., "owner.id", "metadata.status")
557
- */
558
- _matchesFilter(item, key, filterValue) {
559
- const itemValue = key.includes(".") ? this._getNestedValue(item, key) : item[key];
560
- if (filterValue && typeof filterValue === "object" && !Array.isArray(filterValue)) {
561
- const operators = Object.keys(filterValue);
562
- if (operators.some((op) => op.startsWith("$"))) {
563
- for (const [operator, opValue] of Object.entries(filterValue)) {
564
- if (!this._matchesOperator(itemValue, operator, opValue)) {
565
- return false;
566
- }
567
- }
568
- return true;
569
- }
570
- }
571
- return itemValue === filterValue;
572
- }
573
- /**
574
- * Check if item matches policy filters (for get/update/delete operations)
575
- * Validates that fetched item satisfies all policy constraints
576
- * Supports MongoDB query operators: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $exists, $regex, $and, $or
577
- */
578
- _checkPolicyFilters(item, req) {
579
- const arcContext = req.metadata;
580
- const policyFilters = arcContext?._policyFilters;
581
- if (!policyFilters) return true;
582
- if (policyFilters.$and && Array.isArray(policyFilters.$and)) {
583
- return policyFilters.$and.every((condition) => {
584
- return Object.entries(condition).every(([key, value]) => {
585
- return this._matchesFilter(item, key, value);
586
- });
587
- });
588
- }
589
- if (policyFilters.$or && Array.isArray(policyFilters.$or)) {
590
- return policyFilters.$or.some((condition) => {
591
- return Object.entries(condition).every(([key, value]) => {
592
- return this._matchesFilter(item, key, value);
593
- });
594
- });
595
- }
596
- for (const [key, value] of Object.entries(policyFilters)) {
597
- if (key.startsWith("$")) continue;
598
- if (!this._matchesFilter(item, key, value)) {
599
- return false;
600
- }
601
- }
602
- return true;
603
- }
604
- // ============================================================================
605
- // Sanitization Helpers
606
- // ============================================================================
607
- /** Parse lean option (default: true for performance) */
608
- _parseLean(leanValue) {
609
- if (typeof leanValue === "boolean") return leanValue;
610
- if (typeof leanValue === "string") return leanValue.toLowerCase() !== "false";
611
- return true;
612
- }
613
- /** Get blocked fields from schema options */
614
- _getBlockedFields(schemaOptions) {
615
- const fieldRules = schemaOptions.fieldRules ?? {};
616
- return Object.entries(fieldRules).filter(([, rules]) => rules.systemManaged || rules.hidden).map(([field]) => field);
617
- }
618
- /**
619
- * Convert parsed select object to string format
620
- * Converts { name: 1, email: 1, password: 0 } → 'name email -password'
621
- */
622
- _selectToString(select) {
623
- if (!select) return void 0;
624
- if (typeof select === "string") return select;
625
- if (Array.isArray(select)) return select.join(" ");
626
- if (Object.keys(select).length === 0) return void 0;
627
- return Object.entries(select).map(([field, include]) => include === 0 ? `-${field}` : field).join(" ");
628
- }
629
- /** Sanitize select fields */
630
- _sanitizeSelect(select, schemaOptions) {
631
- if (!select) return void 0;
632
- const blockedFields = this._getBlockedFields(schemaOptions);
633
- if (blockedFields.length === 0) return select;
634
- const fields = select.split(/[\s,]+/).filter(Boolean);
635
- const sanitized = fields.filter((f) => {
636
- const fieldName = f.replace(/^-/, "");
637
- return !blockedFields.includes(fieldName);
638
- });
639
- return sanitized.length > 0 ? sanitized.join(" ") : void 0;
640
- }
641
- /** Sanitize populate fields */
642
- _sanitizePopulate(populate, schemaOptions) {
643
- if (!populate) return void 0;
644
- const allowedPopulate = schemaOptions.query?.allowedPopulate;
645
- const requested = typeof populate === "string" ? populate.split(",").map((p) => p.trim()) : Array.isArray(populate) ? populate.map(String) : [];
646
- if (requested.length === 0) return void 0;
647
- if (!allowedPopulate) return requested;
648
- const sanitized = requested.filter((p) => allowedPopulate.includes(p));
649
- return sanitized.length > 0 ? sanitized : void 0;
650
- }
651
- // ============================================================================
652
- // Access Control Helpers
653
- // ============================================================================
654
- /** Check org scope for a document */
655
- _checkOrgScope(item, arcContext) {
656
- if (!item || !arcContext?.organizationId) return true;
657
- const itemOrgId = item.organizationId;
658
- if (!itemOrgId) return true;
659
- return String(itemOrgId) === String(arcContext.organizationId);
660
- }
661
- /** Check ownership for update/delete (ownedByUser preset) */
662
- _checkOwnership(item, req) {
663
- const ownershipCheck = req.metadata?._ownershipCheck;
664
- if (!item || !ownershipCheck) return true;
665
- const { field, userId } = ownershipCheck;
666
- const itemOwnerId = item[field];
667
- if (!itemOwnerId) return true;
668
- return String(itemOwnerId) === String(userId);
669
- }
670
- /**
671
- * Get hook system from context (instance-scoped) or fall back to global singleton
672
- * This allows proper isolation when running multiple app instances (e.g., in tests)
673
- */
674
- _getHooks(req) {
675
- const arcMeta = req.metadata?.arc;
676
- return arcMeta?.hooks ?? hookSystem;
677
- }
678
- // ============================================================================
679
- // IController Implementation - CRUD Operations
680
- // ============================================================================
681
- /**
682
- * List resources with filtering, pagination, sorting
683
- * Implements IController.list()
684
- */
685
- async list(req) {
686
- const options = this._parseQueryOptions(req);
687
- const filteredOptions = this._applyFilters(options, req);
688
- const result = await this.repository.getAll(filteredOptions);
689
- if (Array.isArray(result)) {
690
- return {
691
- success: true,
692
- data: {
693
- docs: result,
694
- page: 1,
695
- limit: result.length,
696
- total: result.length,
697
- pages: 1,
698
- hasNext: false,
699
- hasPrev: false
700
- },
701
- status: 200
702
- };
703
- }
704
- return {
705
- success: true,
706
- data: result,
707
- status: 200
708
- };
709
- }
710
- /**
711
- * Get single resource by ID
712
- * Implements IController.get()
713
- */
714
- async get(req) {
715
- const id = req.params.id;
716
- if (!id) {
717
- return {
718
- success: false,
719
- error: "ID parameter is required",
720
- status: 400
721
- };
722
- }
723
- const options = this._parseQueryOptions(req);
724
- const arcContext = req.metadata;
725
- try {
726
- const item = await this.repository.getById(id, options);
727
- if (!item || !this._checkOrgScope(item, arcContext) || !this._checkPolicyFilters(item, req)) {
728
- return {
729
- success: false,
730
- error: "Resource not found",
731
- status: 404
732
- };
733
- }
734
- return {
735
- success: true,
736
- data: item,
737
- status: 200
738
- };
739
- } catch (error) {
740
- if (error instanceof Error && error.message?.includes("not found")) {
741
- return {
742
- success: false,
743
- error: "Resource not found",
744
- status: 404
745
- };
746
- }
747
- throw error;
748
- }
749
- }
750
- /**
751
- * Create new resource
752
- * Implements IController.create()
753
- */
754
- async create(req) {
755
- const data = { ...req.body };
756
- const arcContext = req.metadata;
757
- if (arcContext?.organizationId) {
758
- data.organizationId = arcContext.organizationId;
759
- }
760
- const userId = getUserId(req.user);
761
- if (userId) {
762
- data.createdBy = userId;
763
- }
764
- const hooks = this._getHooks(req);
765
- const user = req.user;
766
- let processedData = data;
767
- if (this.resourceName) {
768
- processedData = await hooks.executeBefore(this.resourceName, "create", data, {
769
- user,
770
- context: arcContext
771
- });
772
- }
773
- const item = await this.repository.create(processedData, {
774
- user,
775
- context: arcContext
776
- });
777
- if (this.resourceName) {
778
- await hooks.executeAfter(this.resourceName, "create", item, {
779
- user,
780
- context: arcContext
781
- });
782
- }
783
- return {
784
- success: true,
785
- data: item,
786
- status: 201,
787
- meta: { message: "Created successfully" }
788
- };
789
- }
790
- /**
791
- * Update existing resource
792
- * Implements IController.update()
793
- */
794
- async update(req) {
795
- const id = req.params.id;
796
- if (!id) {
797
- return {
798
- success: false,
799
- error: "ID parameter is required",
800
- status: 400
801
- };
802
- }
803
- const data = { ...req.body };
804
- const arcContext = req.metadata;
805
- const user = req.user;
806
- const userId = getUserId(user);
807
- if (userId) {
808
- data.updatedBy = userId;
809
- }
810
- const existing = await this.repository.getById(id);
811
- if (!existing) {
812
- return {
813
- success: false,
814
- error: "Resource not found",
815
- status: 404
816
- };
817
- }
818
- if (!this._checkOrgScope(existing, arcContext) || !this._checkPolicyFilters(existing, req)) {
819
- return {
820
- success: false,
821
- error: "Resource not found",
822
- status: 404
823
- };
824
- }
825
- if (!this._checkOwnership(existing, req)) {
826
- return {
827
- success: false,
828
- error: "You do not have permission to modify this resource",
829
- details: { code: "OWNERSHIP_DENIED" },
830
- status: 403
831
- };
832
- }
833
- const hooks = this._getHooks(req);
834
- let processedData = data;
835
- if (this.resourceName) {
836
- processedData = await hooks.executeBefore(this.resourceName, "update", data, {
837
- user,
838
- context: arcContext,
839
- meta: { id, existing }
840
- });
841
- }
842
- const item = await this.repository.update(id, processedData, {
843
- user,
844
- context: arcContext
845
- });
846
- if (!item) {
847
- return {
848
- success: false,
849
- error: "Resource not found",
850
- status: 404
851
- };
852
- }
853
- if (this.resourceName) {
854
- await hooks.executeAfter(this.resourceName, "update", item, {
855
- user,
856
- context: arcContext,
857
- meta: { id, existing }
858
- });
859
- }
860
- return {
861
- success: true,
862
- data: item,
863
- status: 200,
864
- meta: { message: "Updated successfully" }
865
- };
866
- }
867
- /**
868
- * Delete resource
869
- * Implements IController.delete()
870
- */
871
- async delete(req) {
872
- const id = req.params.id;
873
- if (!id) {
874
- return {
875
- success: false,
876
- error: "ID parameter is required",
877
- status: 400
878
- };
879
- }
880
- const arcContext = req.metadata;
881
- const user = req.user;
882
- const existing = await this.repository.getById(id);
883
- if (!existing) {
884
- return {
885
- success: false,
886
- error: "Resource not found",
887
- status: 404
888
- };
889
- }
890
- if (!this._checkOrgScope(existing, arcContext) || !this._checkPolicyFilters(existing, req)) {
891
- return {
892
- success: false,
893
- error: "Resource not found",
894
- status: 404
895
- };
896
- }
897
- if (!this._checkOwnership(existing, req)) {
898
- return {
899
- success: false,
900
- error: "You do not have permission to delete this resource",
901
- details: { code: "OWNERSHIP_DENIED" },
902
- status: 403
903
- };
904
- }
905
- const hooks = this._getHooks(req);
906
- if (this.resourceName) {
907
- await hooks.executeBefore(this.resourceName, "delete", existing, {
908
- user,
909
- context: arcContext,
910
- meta: { id }
911
- });
912
- }
913
- const result = await this.repository.delete(id, {
914
- user,
915
- context: arcContext
916
- });
917
- const deleteSuccess = typeof result === "object" ? result?.success : result;
918
- if (!deleteSuccess) {
919
- return {
920
- success: false,
921
- error: "Resource not found",
922
- status: 404
923
- };
924
- }
925
- if (this.resourceName) {
926
- await hooks.executeAfter(this.resourceName, "delete", existing, {
927
- user,
928
- context: arcContext,
929
- meta: { id }
930
- });
931
- }
932
- return {
933
- success: true,
934
- data: { message: "Deleted successfully" },
935
- status: 200
936
- };
937
- }
938
- // ============================================================================
939
- // Preset Methods (framework-agnostic versions)
940
- // ============================================================================
941
- /** Get resource by slug (slugLookup preset) */
942
- async getBySlug(req) {
943
- const repo = this.repository;
944
- if (!repo.getBySlug) {
945
- return {
946
- success: false,
947
- error: "Slug lookup not implemented",
948
- status: 501
949
- };
950
- }
951
- const slugField = this._presetFields.slugField ?? "slug";
952
- const slug = req.params[slugField] ?? req.params.slug;
953
- const options = this._parseQueryOptions(req);
954
- const arcContext = req.metadata;
955
- const item = await repo.getBySlug(slug, options);
956
- if (!item || !this._checkOrgScope(item, arcContext)) {
957
- return {
958
- success: false,
959
- error: "Resource not found",
960
- status: 404
961
- };
962
- }
963
- return {
964
- success: true,
965
- data: item,
966
- status: 200
967
- };
968
- }
969
- /** Get soft-deleted resources (softDelete preset) */
970
- async getDeleted(req) {
971
- const repo = this.repository;
972
- if (!repo.getDeleted) {
973
- return {
974
- success: false,
975
- error: "Soft delete not implemented",
976
- status: 501
977
- };
978
- }
979
- const options = this._parseQueryOptions(req);
980
- const filteredOptions = this._applyFilters(options, req);
981
- const result = await repo.getDeleted(filteredOptions);
982
- if (Array.isArray(result)) {
983
- return {
984
- success: true,
985
- data: {
986
- docs: result,
987
- page: 1,
988
- limit: result.length,
989
- total: result.length,
990
- pages: 1,
991
- hasNext: false,
992
- hasPrev: false
993
- },
994
- status: 200
995
- };
996
- }
997
- return {
998
- success: true,
999
- data: result,
1000
- status: 200
1001
- };
1002
- }
1003
- /** Restore soft-deleted resource (softDelete preset) */
1004
- async restore(req) {
1005
- const repo = this.repository;
1006
- if (!repo.restore) {
1007
- return {
1008
- success: false,
1009
- error: "Restore not implemented",
1010
- status: 501
1011
- };
1012
- }
1013
- const id = req.params.id;
1014
- if (!id) {
1015
- return {
1016
- success: false,
1017
- error: "ID parameter is required",
1018
- status: 400
1019
- };
1020
- }
1021
- const item = await repo.restore(id);
1022
- if (!item) {
1023
- return {
1024
- success: false,
1025
- error: "Resource not found",
1026
- status: 404
1027
- };
1028
- }
1029
- return {
1030
- success: true,
1031
- data: item,
1032
- status: 200,
1033
- meta: { message: "Restored successfully" }
1034
- };
1035
- }
1036
- /** Get hierarchical tree (tree preset) */
1037
- async getTree(req) {
1038
- const repo = this.repository;
1039
- if (!repo.getTree) {
1040
- return {
1041
- success: false,
1042
- error: "Tree structure not implemented",
1043
- status: 501
1044
- };
1045
- }
1046
- const options = this._parseQueryOptions(req);
1047
- const filteredOptions = this._applyFilters(options, req);
1048
- const tree = await repo.getTree(filteredOptions);
1049
- return {
1050
- success: true,
1051
- data: tree,
1052
- status: 200
1053
- };
1054
- }
1055
- /** Get children of parent (tree preset) */
1056
- async getChildren(req) {
1057
- const repo = this.repository;
1058
- if (!repo.getChildren) {
1059
- return {
1060
- success: false,
1061
- error: "Tree structure not implemented",
1062
- status: 501
1063
- };
1064
- }
1065
- const parentField = this._presetFields.parentField ?? "parent";
1066
- const parentId = req.params[parentField] ?? req.params.parent ?? req.params.id;
1067
- const options = this._parseQueryOptions(req);
1068
- const filteredOptions = this._applyFilters(options, req);
1069
- const children = await repo.getChildren(parentId, filteredOptions);
1070
- return {
1071
- success: true,
1072
- data: children,
1073
- status: 200
1074
- };
1075
- }
1076
- };
1077
-
1078
- // src/core/fastifyAdapter.ts
1079
- function applyFieldMaskToObject(obj, fieldMask) {
1080
- if (!obj || typeof obj !== "object") return obj;
1081
- const { include, exclude } = fieldMask;
1082
- if (include && include.length > 0) {
1083
- const filtered = {};
1084
- for (const field of include) {
1085
- if (field in obj) {
1086
- filtered[field] = obj[field];
1087
- }
1088
- }
1089
- return filtered;
1090
- }
1091
- if (exclude && exclude.length > 0) {
1092
- const filtered = { ...obj };
1093
- for (const field of exclude) {
1094
- delete filtered[field];
1095
- }
1096
- return filtered;
1097
- }
1098
- return obj;
1099
- }
1100
- function applyFieldMask(data, fieldMask) {
1101
- if (!fieldMask) return data;
1102
- if (Array.isArray(data)) {
1103
- return data.map((item) => applyFieldMaskToObject(item, fieldMask));
1104
- }
1105
- if (data && typeof data === "object") {
1106
- return applyFieldMaskToObject(data, fieldMask);
1107
- }
1108
- return data;
1109
- }
1110
- function createRequestContext(req) {
1111
- const reqWithExtras = req;
1112
- return {
1113
- query: reqWithExtras.query ?? {},
1114
- body: reqWithExtras.body ?? {},
1115
- params: reqWithExtras.params ?? {},
1116
- headers: reqWithExtras.headers,
1117
- user: reqWithExtras.user ? (() => {
1118
- const user = reqWithExtras.user;
1119
- return {
1120
- ...user,
1121
- // Normalize ID for MongoDB compatibility
1122
- id: String(user._id ?? user.id),
1123
- _id: user._id ?? user.id
1124
- // Preserve original role/roles/permissions as-is
1125
- // Devs can define their own authorization structure
1126
- };
1127
- })() : void 0,
1128
- organizationId: reqWithExtras.organizationId,
1129
- metadata: {
1130
- ...reqWithExtras.context,
1131
- // Include Arc metadata for hook execution
1132
- arc: reqWithExtras.arc,
1133
- // Include ownership check for access control
1134
- _ownershipCheck: reqWithExtras._ownershipCheck,
1135
- // Merge policy filters - TRUSTED sources override user input
1136
- // Order matters: query (can be user-injected) FIRST, then trusted middleware LAST
1137
- _policyFilters: {
1138
- ...reqWithExtras.query?._policyFilters ?? {},
1139
- ...reqWithExtras._policyFilters ?? {}
1140
- },
1141
- // Include logger for logging
1142
- log: reqWithExtras.log
1143
- }
1144
- };
1145
- }
1146
- function sendControllerResponse(reply, response, request) {
1147
- const reqWithExtras = request;
1148
- const fieldMask = reqWithExtras?.fieldMask;
1149
- const fieldMaskConfig = fieldMask ? { include: fieldMask } : void 0;
1150
- if (response.success && response.data && typeof response.data === "object" && "docs" in response.data) {
1151
- const paginatedData = response.data;
1152
- const filteredDocs = fieldMaskConfig ? applyFieldMask(paginatedData.docs, fieldMaskConfig) : paginatedData.docs;
1153
- reply.code(response.status ?? 200).send({
1154
- success: true,
1155
- docs: filteredDocs,
1156
- page: paginatedData.page,
1157
- limit: paginatedData.limit,
1158
- total: paginatedData.total,
1159
- pages: paginatedData.pages,
1160
- hasNext: paginatedData.hasNext,
1161
- hasPrev: paginatedData.hasPrev,
1162
- ...response.meta ?? {}
1163
- });
1164
- return;
1165
- }
1166
- const filteredData = fieldMaskConfig ? applyFieldMask(response.data, fieldMaskConfig) : response.data;
1167
- reply.code(response.status ?? (response.success ? 200 : 400)).send({
1168
- success: response.success,
1169
- data: filteredData,
1170
- error: response.error,
1171
- details: response.details,
1172
- ...response.meta ?? {}
1173
- });
1174
- }
1175
- function createFastifyHandler(controllerMethod) {
1176
- return async (req, reply) => {
1177
- const requestContext = createRequestContext(req);
1178
- const response = await controllerMethod(requestContext);
1179
- sendControllerResponse(reply, response, req);
1180
- };
1181
- }
1182
- function createCrudHandlers(controller) {
1183
- return {
1184
- list: createFastifyHandler(controller.list.bind(controller)),
1185
- get: createFastifyHandler(controller.get.bind(controller)),
1186
- create: createFastifyHandler(controller.create.bind(controller)),
1187
- update: createFastifyHandler(controller.update.bind(controller)),
1188
- delete: createFastifyHandler(controller.delete.bind(controller))
1189
- };
1190
- }
1191
-
1192
- // src/core/createCrudRouter.ts
1193
- function requiresAuthentication(permission) {
1194
- if (!permission) return false;
1195
- return !permission._isPublic;
1196
- }
1197
- function buildAuthMiddleware(fastify, permission) {
1198
- if (!requiresAuthentication(permission)) return null;
1199
- if (!fastify.authenticate) return null;
1200
- return fastify.authenticate;
1201
- }
1202
- function buildPermissionMiddleware(permissionCheck, resourceName, action) {
1203
- if (!permissionCheck) return null;
1204
- return async (request, reply) => {
1205
- const reqWithExtras = request;
1206
- const context = {
1207
- user: reqWithExtras.user ?? null,
1208
- request,
1209
- resource: resourceName,
1210
- action,
1211
- resourceId: request.params?.id,
1212
- organizationId: reqWithExtras.organizationId,
1213
- data: request.body
1214
- };
1215
- const result = await permissionCheck(context);
1216
- if (typeof result === "boolean") {
1217
- if (!result) {
1218
- reply.code(context.user ? 403 : 401).send({
1219
- success: false,
1220
- error: context.user ? "Permission denied" : "Authentication required"
1221
- });
1222
- return;
1223
- }
1224
- return;
1225
- }
1226
- const permResult = result;
1227
- if (!permResult.granted) {
1228
- reply.code(context.user ? 403 : 401).send({
1229
- success: false,
1230
- error: permResult.reason ?? (context.user ? "Permission denied" : "Authentication required")
1231
- });
1232
- return;
1233
- }
1234
- if (permResult.filters) {
1235
- reqWithExtras._policyFilters = {
1236
- ...reqWithExtras._policyFilters ?? {},
1237
- ...permResult.filters
1238
- };
1239
- }
1240
- };
1241
- }
1242
- function buildOrgScopedMiddleware(fastify, orgScoped, globalOrgScoped) {
1243
- const shouldApplyOrgScoped = orgScoped ?? globalOrgScoped;
1244
- if (!shouldApplyOrgScoped) return [];
1245
- if (!fastify.organizationScoped) {
1246
- throw new Error(
1247
- "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"
1248
- );
1249
- }
1250
- return [fastify.organizationScoped()];
1251
- }
1252
- function createAdditionalRoutes(fastify, routes, controller, options) {
1253
- const { tag, resourceName, orgMw, arcDecorator } = options;
1254
- for (const route of routes) {
1255
- let handler;
1256
- if (typeof route.handler === "string") {
1257
- if (!controller) {
1258
- throw new Error(
1259
- `Route ${route.method} ${route.path}: string handler '${route.handler}' requires a controller. Either provide a controller or use a function handler instead.`
1260
- );
1261
- }
1262
- const ctrl = controller;
1263
- const method = ctrl[route.handler];
1264
- if (typeof method !== "function") {
1265
- throw new Error(`Handler '${route.handler}' not found on controller`);
1266
- }
1267
- const boundMethod = method.bind(controller);
1268
- handler = route.wrapHandler ? createFastifyHandler(boundMethod) : boundMethod;
1269
- } else {
1270
- handler = route.wrapHandler ? createFastifyHandler(route.handler) : route.handler;
1271
- }
1272
- const routeTags = route.tags ?? (tag ? [tag] : void 0);
1273
- const schema = {
1274
- ...routeTags ? { tags: routeTags } : {},
1275
- ...route.summary ? { summary: route.summary } : {},
1276
- ...route.description ? { description: route.description } : {},
1277
- ...route.schema ?? {}
1278
- };
1279
- const authMw = buildAuthMiddleware(fastify, route.permissions);
1280
- const permissionMw = buildPermissionMiddleware(route.permissions, resourceName, route.method.toLowerCase());
1281
- const customPreHandlers = typeof route.preHandler === "function" ? route.preHandler(fastify) : route.preHandler ?? [];
1282
- const preHandler = [
1283
- arcDecorator,
1284
- authMw,
1285
- // Authenticate first (populates request.user)
1286
- permissionMw,
1287
- // Then check permissions
1288
- ...orgMw(),
1289
- ...customPreHandlers
1290
- ].filter(Boolean);
1291
- fastify.route({
1292
- method: route.method,
1293
- url: route.path,
1294
- schema,
1295
- // Fastify schema is flexible - allow any valid JSON schema
1296
- preHandler: preHandler.length > 0 ? preHandler : void 0,
1297
- handler
1298
- });
1299
- }
1300
- }
1301
- function createCrudRouter(fastify, controller, options = {}) {
1302
- const {
1303
- tag = "Resource",
1304
- schemas = {},
1305
- permissions = {},
1306
- middlewares = {},
1307
- additionalRoutes = [],
1308
- disableDefaultRoutes = false,
1309
- disabledRoutes = [],
1310
- organizationScoped = false,
1311
- resourceName = "unknown",
1312
- schemaOptions
1313
- } = options;
1314
- const orgMw = (orgScoped) => {
1315
- return buildOrgScopedMiddleware(fastify, orgScoped, organizationScoped);
1316
- };
1317
- const arcDecorator = async (req, _reply) => {
1318
- req.arc = {
1319
- resourceName,
1320
- schemaOptions,
1321
- permissions,
1322
- // Include instance-scoped hooks if available (for proper isolation)
1323
- hooks: fastify.arc?.hooks,
1324
- // Include events emitter if available
1325
- events: fastify.events
1326
- };
1327
- };
1328
- const mw = {
1329
- list: middlewares.list ?? [],
1330
- get: middlewares.get ?? [],
1331
- create: middlewares.create ?? [],
1332
- update: middlewares.update ?? [],
1333
- delete: middlewares.delete ?? []
1334
- };
1335
- const idParamsSchema = {
1336
- type: "object",
1337
- properties: { id: { type: "string" } },
1338
- required: ["id"]
1339
- };
1340
- let handlers;
1341
- if (!disableDefaultRoutes) {
1342
- if (!controller) {
1343
- throw new Error(
1344
- "Controller is required when disableDefaultRoutes is not true. Provide a controller or use defineResource which auto-creates BaseController."
1345
- );
1346
- }
1347
- handlers = createCrudHandlers(controller);
1348
- }
1349
- if (!disableDefaultRoutes && handlers) {
1350
- if (!disabledRoutes.includes("list")) {
1351
- const authMw = buildAuthMiddleware(fastify, permissions.list);
1352
- const permMw = buildPermissionMiddleware(permissions.list, resourceName, "list");
1353
- const listPreHandler = [arcDecorator, authMw, permMw, ...orgMw(), ...mw.list].filter(Boolean);
1354
- fastify.route({
1355
- method: "GET",
1356
- url: "/",
1357
- schema: {
1358
- tags: [tag],
1359
- summary: `List ${tag}`,
1360
- ...schemas.list ?? {}
1361
- },
1362
- preHandler: listPreHandler.length > 0 ? listPreHandler : void 0,
1363
- handler: handlers.list
1364
- });
1365
- }
1366
- if (!disabledRoutes.includes("get")) {
1367
- const authMw = buildAuthMiddleware(fastify, permissions.get);
1368
- const permMw = buildPermissionMiddleware(permissions.get, resourceName, "get");
1369
- const getPreHandler = [arcDecorator, authMw, permMw, ...orgMw(), ...mw.get].filter(Boolean);
1370
- fastify.route({
1371
- method: "GET",
1372
- url: "/:id",
1373
- schema: {
1374
- tags: [tag],
1375
- summary: `Get ${tag} by ID`,
1376
- params: idParamsSchema,
1377
- ...schemas.get ?? {}
1378
- },
1379
- preHandler: getPreHandler.length > 0 ? getPreHandler : void 0,
1380
- handler: handlers.get
1381
- });
1382
- }
1383
- if (!disabledRoutes.includes("create")) {
1384
- const authMw = buildAuthMiddleware(fastify, permissions.create);
1385
- const permMw = buildPermissionMiddleware(permissions.create, resourceName, "create");
1386
- const createPreHandler = [arcDecorator, authMw, permMw, ...orgMw(), ...mw.create].filter(Boolean);
1387
- fastify.route({
1388
- method: "POST",
1389
- url: "/",
1390
- schema: {
1391
- tags: [tag],
1392
- summary: `Create ${tag}`,
1393
- ...schemas.create ?? {}
1394
- },
1395
- preHandler: createPreHandler.length > 0 ? createPreHandler : void 0,
1396
- handler: handlers.create
1397
- });
1398
- }
1399
- if (!disabledRoutes.includes("update")) {
1400
- const authMw = buildAuthMiddleware(fastify, permissions.update);
1401
- const permMw = buildPermissionMiddleware(permissions.update, resourceName, "update");
1402
- const updatePreHandler = [arcDecorator, authMw, permMw, ...orgMw(), ...mw.update].filter(Boolean);
1403
- fastify.route({
1404
- method: "PATCH",
1405
- url: "/:id",
1406
- schema: {
1407
- tags: [tag],
1408
- summary: `Update ${tag}`,
1409
- params: idParamsSchema,
1410
- ...schemas.update ?? {}
1411
- },
1412
- preHandler: updatePreHandler.length > 0 ? updatePreHandler : void 0,
1413
- handler: handlers.update
1414
- });
1415
- }
1416
- if (!disabledRoutes.includes("delete")) {
1417
- const authMw = buildAuthMiddleware(fastify, permissions.delete);
1418
- const permMw = buildPermissionMiddleware(permissions.delete, resourceName, "delete");
1419
- const deletePreHandler = [arcDecorator, authMw, permMw, ...orgMw(), ...mw.delete].filter(Boolean);
1420
- fastify.route({
1421
- method: "DELETE",
1422
- url: "/:id",
1423
- schema: {
1424
- tags: [tag],
1425
- summary: `Delete ${tag}`,
1426
- params: idParamsSchema,
1427
- ...schemas.delete ?? {}
1428
- },
1429
- preHandler: deletePreHandler.length > 0 ? deletePreHandler : void 0,
1430
- handler: handlers.delete
1431
- });
1432
- }
1433
- }
1434
- if (additionalRoutes.length > 0) {
1435
- createAdditionalRoutes(fastify, additionalRoutes, controller, { tag, resourceName, orgMw, arcDecorator });
1436
- }
1437
- }
1438
- function createOrgScopedMiddleware(instance) {
1439
- return instance.organizationScoped ? [instance.organizationScoped()] : [];
1440
- }
1441
- function createPermissionMiddleware(permission, resourceName, action) {
1442
- return buildPermissionMiddleware(permission, resourceName, action);
1443
- }
1444
-
1445
- // src/core/createActionRouter.ts
1446
- function createActionRouter(fastify, config) {
1447
- const {
1448
- tag,
1449
- actions,
1450
- actionPermissions = {},
1451
- actionSchemas = {},
1452
- globalAuth,
1453
- idempotencyService,
1454
- onError
1455
- } = config;
1456
- const actionEnum = Object.keys(actions);
1457
- if (actionEnum.length === 0) {
1458
- fastify.log.warn("[createActionRouter] No actions defined, skipping route creation");
1459
- return;
1460
- }
1461
- const bodyProperties = {
1462
- action: {
1463
- type: "string",
1464
- enum: actionEnum,
1465
- description: `Action to perform: ${actionEnum.join(" | ")}`
1466
- }
1467
- };
1468
- Object.entries(actionSchemas).forEach(([actionName, schema]) => {
1469
- if (schema && typeof schema === "object") {
1470
- Object.entries(schema).forEach(([propName, propSchema]) => {
1471
- bodyProperties[propName] = {
1472
- ...propSchema,
1473
- description: `${propSchema.description || ""} (for ${actionName} action)`.trim()
1474
- };
1475
- });
1476
- }
1477
- });
1478
- const routeSchema = {
1479
- tags: tag ? [tag] : void 0,
1480
- summary: `Perform action (${actionEnum.join("/")})`,
1481
- description: buildActionDescription(actions, actionPermissions),
1482
- params: {
1483
- type: "object",
1484
- properties: {
1485
- id: { type: "string", description: "Resource ID" }
1486
- },
1487
- required: ["id"]
1488
- },
1489
- body: {
1490
- type: "object",
1491
- properties: bodyProperties,
1492
- required: ["action"]
1493
- },
1494
- response: {
1495
- 200: {
1496
- type: "object",
1497
- properties: {
1498
- success: { type: "boolean" },
1499
- data: { type: "object" }
1500
- }
1501
- },
1502
- 400: {
1503
- type: "object",
1504
- properties: {
1505
- success: { type: "boolean" },
1506
- error: { type: "string" }
1507
- }
1508
- },
1509
- 403: {
1510
- type: "object",
1511
- properties: {
1512
- success: { type: "boolean" },
1513
- error: { type: "string" }
1514
- }
1515
- }
1516
- }
1517
- };
1518
- const preHandler = [];
1519
- const allPermissions = Object.values(actionPermissions);
1520
- const needsAuth = allPermissions.some(
1521
- (p) => !p?._isPublic
1522
- ) || globalAuth && !globalAuth?._isPublic;
1523
- if (needsAuth && fastify.authenticate) {
1524
- preHandler.push(fastify.authenticate);
1525
- }
1526
- fastify.post(
1527
- "/:id/action",
1528
- {
1529
- schema: routeSchema,
1530
- preHandler: preHandler.length ? preHandler : void 0
1531
- },
1532
- async (req, reply) => {
1533
- const { action, ...data } = req.body;
1534
- const { id } = req.params;
1535
- const rawIdempotencyKey = req.headers["idempotency-key"];
1536
- const idempotencyKey = Array.isArray(rawIdempotencyKey) ? rawIdempotencyKey[0] : rawIdempotencyKey;
1537
- const handler = actions[action];
1538
- if (!handler) {
1539
- return reply.code(400).send({
1540
- success: false,
1541
- error: `Invalid action '${action}'. Valid actions: ${actionEnum.join(", ")}`,
1542
- validActions: actionEnum
1543
- });
1544
- }
1545
- const permissionCheck = actionPermissions[action] ?? globalAuth;
1546
- if (permissionCheck) {
1547
- const reqWithExtras = req;
1548
- const context = {
1549
- user: reqWithExtras.user ?? null,
1550
- request: req,
1551
- resource: tag ?? "action",
1552
- action,
1553
- resourceId: id,
1554
- data
1555
- };
1556
- const result = await permissionCheck(context);
1557
- if (typeof result === "boolean") {
1558
- if (!result) {
1559
- return reply.code(context.user ? 403 : 401).send({
1560
- success: false,
1561
- error: context.user ? `Permission denied for '${action}'` : "Authentication required"
1562
- });
1563
- }
1564
- } else {
1565
- const permResult = result;
1566
- if (!permResult.granted) {
1567
- return reply.code(context.user ? 403 : 401).send({
1568
- success: false,
1569
- error: permResult.reason ?? (context.user ? `Permission denied for '${action}'` : "Authentication required")
1570
- });
1571
- }
1572
- }
1573
- }
1574
- try {
1575
- if (idempotencyKey && idempotencyService) {
1576
- const user = req.user;
1577
- const payloadForHash = {
1578
- action,
1579
- id,
1580
- data,
1581
- userId: user?._id?.toString?.() || user?.id || null
1582
- };
1583
- const { isNew, existingResult } = await idempotencyService.check(
1584
- idempotencyKey,
1585
- payloadForHash
1586
- );
1587
- if (!isNew && existingResult) {
1588
- return reply.send({
1589
- success: true,
1590
- data: existingResult,
1591
- cached: true
1592
- });
1593
- }
1594
- }
1595
- const result = await handler(id, data, req);
1596
- if (idempotencyService) {
1597
- await idempotencyService.complete(idempotencyKey, result);
1598
- }
1599
- return reply.send({
1600
- success: true,
1601
- data: result
1602
- });
1603
- } catch (error) {
1604
- if (idempotencyService) {
1605
- await idempotencyService.fail(idempotencyKey, error);
1606
- }
1607
- if (onError) {
1608
- const { statusCode: statusCode2, error: errorMsg, code } = onError(error, action, id);
1609
- return reply.code(statusCode2).send({
1610
- success: false,
1611
- error: errorMsg,
1612
- code
1613
- });
1614
- }
1615
- const err = error;
1616
- const statusCode = err.statusCode || err.status || 500;
1617
- const errorCode = err.code || "ACTION_FAILED";
1618
- if (statusCode >= 500) {
1619
- req.log.error({ err: error, action, id }, "Action handler error");
1620
- }
1621
- return reply.code(statusCode).send({
1622
- success: false,
1623
- error: err.message || `Failed to execute '${action}' action`,
1624
- code: errorCode
1625
- });
1626
- }
1627
- }
1628
- );
1629
- fastify.log.info(
1630
- { actions: actionEnum, tag },
1631
- "[createActionRouter] Registered action endpoint: POST /:id/action"
1632
- );
1633
- }
1634
- function buildActionDescription(actions, actionPermissions) {
1635
- const lines = ["Unified action endpoint for state transitions.\n\n**Available actions:**"];
1636
- Object.keys(actions).forEach((action) => {
1637
- const perm = actionPermissions[action];
1638
- const roles = perm?._roles;
1639
- const roleStr = roles?.length ? ` (requires: ${roles.join(" or ")})` : "";
1640
- lines.push(`- \`${action}\`${roleStr}`);
1641
- });
1642
- return lines.join("\n");
1643
- }
1644
-
1645
- // src/permissions/index.ts
1646
- function allowPublic() {
1647
- const check = () => true;
1648
- check._isPublic = true;
1649
- return check;
1650
- }
1651
- function requireRoles(roles, options) {
1652
- const check = (ctx) => {
1653
- if (!ctx.user) {
1654
- return { granted: false, reason: "Authentication required" };
1655
- }
1656
- const userRoles = ctx.user.roles ?? [];
1657
- if (roles.some((r) => userRoles.includes(r))) {
1658
- return true;
1659
- }
1660
- return {
1661
- granted: false,
1662
- reason: `Required roles: ${roles.join(", ")}`
1663
- };
1664
- };
1665
- check._roles = roles;
1666
- return check;
1667
- }
1668
-
1669
- // src/presets/softDelete.ts
1670
- function softDeletePreset(options = {}) {
1671
- const { deletedField: _deletedField = "deletedAt" } = options;
1672
- return {
1673
- name: "softDelete",
1674
- additionalRoutes: (permissions) => [
1675
- {
1676
- method: "GET",
1677
- path: "/deleted",
1678
- handler: "getDeleted",
1679
- summary: "Get soft-deleted items",
1680
- permissions: permissions.list ?? requireRoles(["admin"]),
1681
- wrapHandler: true
1682
- },
1683
- {
1684
- method: "POST",
1685
- path: "/:id/restore",
1686
- handler: "restore",
1687
- summary: "Restore soft-deleted item",
1688
- permissions: permissions.update ?? requireRoles(["admin"]),
1689
- wrapHandler: true
1690
- }
1691
- ]
1692
- };
1693
- }
1694
-
1695
- // src/presets/slugLookup.ts
1696
- function slugLookupPreset(options = {}) {
1697
- const { slugField = "slug" } = options;
1698
- return {
1699
- name: "slugLookup",
1700
- additionalRoutes: (permissions) => [
1701
- {
1702
- method: "GET",
1703
- path: `/slug/:${slugField}`,
1704
- handler: "getBySlug",
1705
- summary: "Get by slug",
1706
- permissions: permissions.get ?? allowPublic(),
1707
- wrapHandler: true
1708
- // Handler is a ControllerHandler
1709
- }
1710
- ],
1711
- // Pass to controller so it knows which param to read
1712
- controllerOptions: {
1713
- slugField
1714
- }
1715
- };
1716
- }
1717
-
1718
- // src/presets/ownedByUser.ts
1719
- function createOwnershipCheck(ownerField, bypassRoles) {
1720
- return async (request, _reply) => {
1721
- const user = request.user;
1722
- if (!user) return;
1723
- const userWithRoles = user;
1724
- if (userWithRoles.roles && bypassRoles.some((r) => userWithRoles.roles.includes(r))) return;
1725
- const userWithId = user;
1726
- const userId = userWithId._id ?? userWithId.id;
1727
- if (userId) {
1728
- request._ownershipCheck = {
1729
- field: ownerField,
1730
- userId
1731
- };
1732
- }
1733
- };
1734
- }
1735
- function ownedByUserPreset(options = {}) {
1736
- const {
1737
- ownerField = "userId",
1738
- bypassRoles = ["admin", "superadmin"]
1739
- } = options;
1740
- const ownershipMiddleware = createOwnershipCheck(ownerField, bypassRoles);
1741
- return {
1742
- name: "ownedByUser",
1743
- middlewares: {
1744
- update: [ownershipMiddleware],
1745
- delete: [ownershipMiddleware]
1746
- }
1747
- };
1748
- }
1749
-
1750
- // src/presets/multiTenant.ts
1751
- function defaultExtractOrganizationId(request) {
1752
- const context = request.context;
1753
- if (context?.organizationId) {
1754
- return context.organizationId;
1755
- }
1756
- const user = request.user;
1757
- if (user?.organizationId) {
1758
- return user.organizationId;
1759
- }
1760
- if (user?.organization) {
1761
- const org = user.organization;
1762
- return org._id || org.id || org;
1763
- }
1764
- return null;
1765
- }
1766
- function createTenantFilter(tenantField, bypassRoles, extractOrganizationId) {
1767
- return async (request, reply) => {
1768
- const user = request.user;
1769
- if (!user) {
1770
- reply.code(401).send({
1771
- success: false,
1772
- error: "Unauthorized",
1773
- message: "Authentication required for multi-tenant resources"
1774
- });
1775
- return;
1776
- }
1777
- const userWithRoles = user;
1778
- if (userWithRoles.roles && bypassRoles.some((r) => userWithRoles.roles.includes(r))) return;
1779
- const orgId = extractOrganizationId(request);
1780
- if (!orgId) {
1781
- reply.code(403).send({
1782
- success: false,
1783
- error: "Forbidden",
1784
- message: "Organization context required for this operation"
1785
- });
1786
- return;
1787
- }
1788
- request.query = request.query ?? {};
1789
- request.query._policyFilters = {
1790
- ...request.query._policyFilters ?? {},
1791
- [tenantField]: orgId
1792
- };
1793
- };
1794
- }
1795
- function createFlexibleTenantFilter(tenantField, bypassRoles, extractOrganizationId) {
1796
- return async (request, reply) => {
1797
- const user = request.user;
1798
- const orgId = extractOrganizationId(request);
1799
- if (!orgId) {
1800
- return;
1801
- }
1802
- if (!user) {
1803
- reply.code(401).send({
1804
- success: false,
1805
- error: "Unauthorized",
1806
- message: "Authentication required for organization-scoped data"
1807
- });
1808
- return;
1809
- }
1810
- const userWithRoles = user;
1811
- if (userWithRoles.roles && bypassRoles.some((r) => userWithRoles.roles.includes(r))) {
1812
- return;
1813
- }
1814
- request.query = request.query ?? {};
1815
- request.query._policyFilters = {
1816
- ...request.query._policyFilters ?? {},
1817
- [tenantField]: orgId
1818
- };
1819
- };
1820
- }
1821
- function createTenantInjection(tenantField, extractOrganizationId) {
1822
- return async (request, reply) => {
1823
- const orgId = extractOrganizationId(request);
1824
- if (!orgId) {
1825
- reply.code(403).send({
1826
- success: false,
1827
- error: "Forbidden",
1828
- message: "Organization context required to create resources"
1829
- });
1830
- return;
1831
- }
1832
- if (request.body) {
1833
- request.body[tenantField] = orgId;
1834
- }
1835
- };
1836
- }
1837
- function multiTenantPreset(options = {}) {
1838
- const {
1839
- tenantField = "organizationId",
1840
- bypassRoles = ["superadmin"],
1841
- extractOrganizationId = defaultExtractOrganizationId,
1842
- allowPublic: allowPublic2 = []
1843
- } = options;
1844
- const strictTenantFilter = createTenantFilter(tenantField, bypassRoles, extractOrganizationId);
1845
- const flexibleTenantFilter = createFlexibleTenantFilter(tenantField, bypassRoles, extractOrganizationId);
1846
- const tenantInjection = createTenantInjection(tenantField, extractOrganizationId);
1847
- const getFilter = (route) => allowPublic2.includes(route) ? flexibleTenantFilter : strictTenantFilter;
1848
- return {
1849
- name: "multiTenant",
1850
- middlewares: {
1851
- list: [getFilter("list")],
1852
- get: [getFilter("get")],
1853
- create: [tenantInjection],
1854
- update: [getFilter("update")],
1855
- delete: [getFilter("delete")]
1856
- }
1857
- };
1858
- }
1859
-
1860
- // src/presets/tree.ts
1861
- function treePreset(options = {}) {
1862
- const { parentField = "parent" } = options;
1863
- return {
1864
- name: "tree",
1865
- additionalRoutes: (permissions) => [
1866
- {
1867
- method: "GET",
1868
- path: "/tree",
1869
- handler: "getTree",
1870
- summary: "Get hierarchical tree",
1871
- permissions: permissions.list ?? allowPublic(),
1872
- wrapHandler: true
1873
- },
1874
- {
1875
- method: "GET",
1876
- path: `/:${parentField}/children`,
1877
- handler: "getChildren",
1878
- summary: "Get children of parent",
1879
- permissions: permissions.list ?? allowPublic(),
1880
- wrapHandler: true
1881
- }
1882
- ],
1883
- // Pass to controller so it knows which param to read
1884
- controllerOptions: {
1885
- parentField
1886
- }
1887
- };
1888
- }
1889
-
1890
- // src/presets/audited.ts
1891
- function auditedPreset(options = {}) {
1892
- const { createdByField = "createdBy", updatedByField = "updatedBy" } = options;
1893
- const injectCreatedBy = async (request, _reply) => {
1894
- const userWithId = request.user;
1895
- if (userWithId?._id || userWithId?.id) {
1896
- const userId = userWithId._id ?? userWithId.id;
1897
- request.body[createdByField] = userId;
1898
- request.body[updatedByField] = userId;
1899
- }
1900
- return void 0;
1901
- };
1902
- const injectUpdatedBy = async (request, _reply) => {
1903
- const userWithId = request.user;
1904
- if (userWithId?._id || userWithId?.id) {
1905
- request.body[updatedByField] = userWithId._id ?? userWithId.id;
1906
- }
1907
- return void 0;
1908
- };
1909
- return {
1910
- name: "audited",
1911
- schemaOptions: {
1912
- fieldRules: {
1913
- [createdByField]: { systemManaged: true },
1914
- [updatedByField]: { systemManaged: true },
1915
- createdAt: { systemManaged: true },
1916
- updatedAt: { systemManaged: true }
1917
- }
1918
- },
1919
- middlewares: {
1920
- create: [injectCreatedBy],
1921
- update: [injectUpdatedBy]
1922
- }
1923
- };
1924
- }
1925
-
1926
- // src/presets/index.ts
1927
- var presetRegistry = {
1928
- softDelete: softDeletePreset,
1929
- slugLookup: slugLookupPreset,
1930
- ownedByUser: ownedByUserPreset,
1931
- multiTenant: multiTenantPreset,
1932
- tree: treePreset,
1933
- audited: auditedPreset
1934
- };
1935
- function resolvePreset(name, options = {}) {
1936
- const factory = presetRegistry[name];
1937
- if (!factory) {
1938
- const available = Object.keys(presetRegistry).join(", ");
1939
- throw new Error(
1940
- `Unknown preset: '${name}'
1941
- Available presets: ${available}
1942
- Docs: https://github.com/classytic/arc#presets`
1943
- );
1944
- }
1945
- return factory(options);
1946
- }
1947
- function getAvailablePresets() {
1948
- return Object.keys(presetRegistry);
1949
- }
1950
- function applyPresets(config, presets = []) {
1951
- let result = { ...config };
1952
- for (const preset of presets) {
1953
- const resolved = resolvePresetInput(preset);
1954
- result = mergePreset(result, resolved);
1955
- }
1956
- return result;
1957
- }
1958
- function resolvePresetInput(preset) {
1959
- if (typeof preset === "object" && ("middlewares" in preset || "additionalRoutes" in preset)) {
1960
- return preset;
1961
- }
1962
- if (typeof preset === "object" && "name" in preset) {
1963
- const { name, ...options } = preset;
1964
- return resolvePreset(name, options);
1965
- }
1966
- return resolvePreset(preset);
1967
- }
1968
- function mergePreset(config, preset) {
1969
- const result = { ...config };
1970
- if (preset.additionalRoutes) {
1971
- const routes = typeof preset.additionalRoutes === "function" ? preset.additionalRoutes(config.permissions ?? {}) : preset.additionalRoutes;
1972
- result.additionalRoutes = [
1973
- ...result.additionalRoutes ?? [],
1974
- ...routes
1975
- ];
1976
- }
1977
- if (preset.middlewares) {
1978
- result.middlewares = result.middlewares ?? {};
1979
- for (const [op, mws] of Object.entries(preset.middlewares)) {
1980
- const key = op;
1981
- result.middlewares[key] = [
1982
- ...result.middlewares[key] ?? [],
1983
- ...mws ?? []
1984
- ];
1985
- }
1986
- }
1987
- if (preset.schemaOptions) {
1988
- result.schemaOptions = {
1989
- ...result.schemaOptions,
1990
- ...preset.schemaOptions
1991
- };
1992
- }
1993
- if (preset.controllerOptions) {
1994
- result._controllerOptions = {
1995
- ...result._controllerOptions,
1996
- ...preset.controllerOptions
1997
- };
1998
- }
1999
- if (preset.hooks && preset.hooks.length > 0) {
2000
- result._hooks = result._hooks ?? [];
2001
- for (const hook of preset.hooks) {
2002
- result._hooks.push({
2003
- presetName: preset.name,
2004
- operation: hook.operation,
2005
- phase: hook.phase,
2006
- handler: hook.handler,
2007
- priority: hook.priority
2008
- });
2009
- }
2010
- }
2011
- return result;
2012
- }
2013
-
2014
- // src/registry/ResourceRegistry.ts
2015
- var ResourceRegistry = class {
2016
- _resources;
2017
- _frozen;
2018
- constructor() {
2019
- this._resources = /* @__PURE__ */ new Map();
2020
- this._frozen = false;
2021
- }
2022
- /**
2023
- * Register a resource
2024
- */
2025
- register(resource, options = {}) {
2026
- if (this._frozen) {
2027
- throw new Error(
2028
- `Registry frozen. Cannot register '${resource.name}' after startup.`
2029
- );
2030
- }
2031
- if (this._resources.has(resource.name)) {
2032
- throw new Error(`Resource '${resource.name}' already registered.`);
2033
- }
2034
- const entry = {
2035
- name: resource.name,
2036
- displayName: resource.displayName,
2037
- tag: resource.tag,
2038
- prefix: resource.prefix,
2039
- module: options.module ?? void 0,
2040
- adapter: resource.adapter ? {
2041
- type: resource.adapter.type,
2042
- name: resource.adapter.name
2043
- } : null,
2044
- permissions: resource.permissions,
2045
- presets: resource._appliedPresets ?? [],
2046
- routes: [],
2047
- // Populated later by getIntrospection()
2048
- additionalRoutes: resource.additionalRoutes.map((r) => ({
2049
- method: r.method,
2050
- path: r.path,
2051
- handler: typeof r.handler === "string" ? r.handler : r.handler.name || "anonymous",
2052
- summary: r.summary,
2053
- description: r.description,
2054
- permissions: r.permissions,
2055
- wrapHandler: r.wrapHandler,
2056
- schema: r.schema
2057
- // Include schema for OpenAPI docs
2058
- })),
2059
- events: Object.keys(resource.events ?? {}),
2060
- registeredAt: (/* @__PURE__ */ new Date()).toISOString(),
2061
- disableDefaultRoutes: resource.disableDefaultRoutes,
2062
- openApiSchemas: options.openApiSchemas,
2063
- plugin: resource.toPlugin()
2064
- // Store plugin factory
2065
- };
2066
- this._resources.set(resource.name, entry);
2067
- return this;
2068
- }
2069
- /**
2070
- * Get resource by name
2071
- */
2072
- get(name) {
2073
- return this._resources.get(name);
2074
- }
2075
- /**
2076
- * Get all resources
2077
- */
2078
- getAll() {
2079
- return Array.from(this._resources.values());
2080
- }
2081
- /**
2082
- * Get resources by module
2083
- */
2084
- getByModule(moduleName) {
2085
- return this.getAll().filter((r) => r.module === moduleName);
2086
- }
2087
- /**
2088
- * Get resources by preset
2089
- */
2090
- getByPreset(presetName) {
2091
- return this.getAll().filter((r) => r.presets.includes(presetName));
2092
- }
2093
- /**
2094
- * Check if resource exists
2095
- */
2096
- has(name) {
2097
- return this._resources.has(name);
2098
- }
2099
- /**
2100
- * Get registry statistics
2101
- */
2102
- getStats() {
2103
- const resources = this.getAll();
2104
- const presetCounts = {};
2105
- for (const r of resources) {
2106
- for (const preset of r.presets) {
2107
- presetCounts[preset] = (presetCounts[preset] ?? 0) + 1;
2108
- }
2109
- }
2110
- return {
2111
- totalResources: resources.length,
2112
- byModule: this._groupBy(resources, "module"),
2113
- presetUsage: presetCounts,
2114
- totalRoutes: resources.reduce((sum, r) => {
2115
- const defaultRouteCount = r.disableDefaultRoutes ? 0 : 5;
2116
- return sum + (r.additionalRoutes?.length ?? 0) + defaultRouteCount;
2117
- }, 0),
2118
- totalEvents: resources.reduce((sum, r) => sum + (r.events?.length ?? 0), 0)
2119
- };
2120
- }
2121
- /**
2122
- * Get full introspection data
2123
- */
2124
- getIntrospection() {
2125
- return {
2126
- resources: this.getAll().map((r) => {
2127
- const defaultRoutes = r.disableDefaultRoutes ? [] : [
2128
- { method: "GET", path: r.prefix, operation: "list" },
2129
- { method: "GET", path: `${r.prefix}/:id`, operation: "get" },
2130
- { method: "POST", path: r.prefix, operation: "create" },
2131
- { method: "PATCH", path: `${r.prefix}/:id`, operation: "update" },
2132
- { method: "DELETE", path: `${r.prefix}/:id`, operation: "delete" }
2133
- ];
2134
- return {
2135
- name: r.name,
2136
- displayName: r.displayName,
2137
- prefix: r.prefix,
2138
- module: r.module,
2139
- presets: r.presets,
2140
- permissions: r.permissions,
2141
- routes: [
2142
- ...defaultRoutes,
2143
- ...r.additionalRoutes?.map((ar) => ({
2144
- method: ar.method,
2145
- path: `${r.prefix}${ar.path}`,
2146
- operation: typeof ar.handler === "string" ? ar.handler : "custom",
2147
- handler: typeof ar.handler === "string" ? ar.handler : void 0,
2148
- summary: ar.summary
2149
- })) ?? []
2150
- ],
2151
- events: r.events
2152
- };
2153
- }),
2154
- stats: this.getStats(),
2155
- generatedAt: (/* @__PURE__ */ new Date()).toISOString()
2156
- };
2157
- }
2158
- /**
2159
- * Freeze registry (prevent further registrations)
2160
- */
2161
- freeze() {
2162
- this._frozen = true;
2163
- }
2164
- /**
2165
- * Check if frozen
2166
- */
2167
- isFrozen() {
2168
- return this._frozen;
2169
- }
2170
- /**
2171
- * Unfreeze registry (for testing)
2172
- */
2173
- _unfreeze() {
2174
- this._frozen = false;
2175
- }
2176
- /**
2177
- * Clear all resources (for testing)
2178
- */
2179
- _clear() {
2180
- this._resources.clear();
2181
- this._frozen = false;
2182
- }
2183
- /**
2184
- * Group by key
2185
- */
2186
- _groupBy(arr, key) {
2187
- const result = {};
2188
- for (const item of arr) {
2189
- const k = String(item[key] ?? "uncategorized");
2190
- result[k] = (result[k] ?? 0) + 1;
2191
- }
2192
- return result;
2193
- }
2194
- };
2195
- var registryKey = /* @__PURE__ */ Symbol.for("arc.resourceRegistry");
2196
- var globalScope = globalThis;
2197
- var resourceRegistry = globalScope[registryKey] ?? new ResourceRegistry();
2198
- if (!globalScope[registryKey]) {
2199
- globalScope[registryKey] = resourceRegistry;
2200
- }
2201
-
2202
- // src/core/validateResourceConfig.ts
2203
- function validateResourceConfig(config, options = {}) {
2204
- const errors = [];
2205
- const warnings = [];
2206
- if (!config.name) {
2207
- errors.push({
2208
- field: "name",
2209
- message: "Resource name is required",
2210
- suggestion: 'Add a unique resource name (e.g., "product", "user")'
2211
- });
2212
- } else if (!/^[a-z][a-z0-9-]*$/i.test(config.name)) {
2213
- errors.push({
2214
- field: "name",
2215
- message: `Invalid resource name "${config.name}"`,
2216
- suggestion: "Use alphanumeric characters and hyphens, starting with a letter"
2217
- });
2218
- }
2219
- const crudRoutes = ["list", "get", "create", "update", "delete"];
2220
- const disabledRoutes = new Set(config.disabledRoutes ?? []);
2221
- const enabledCrudRoutes = crudRoutes.filter((route) => !disabledRoutes.has(route));
2222
- const hasCrudRoutes = !config.disableDefaultRoutes && enabledCrudRoutes.length > 0;
2223
- if (hasCrudRoutes) {
2224
- if (!config.adapter) {
2225
- errors.push({
2226
- field: "adapter",
2227
- message: "Data adapter is required when CRUD routes are enabled",
2228
- suggestion: "Provide an adapter: createMongooseAdapter({ model, repository })"
2229
- });
2230
- } else if (!config.adapter.repository) {
2231
- errors.push({
2232
- field: "adapter.repository",
2233
- message: "Adapter must provide a repository",
2234
- suggestion: "Ensure your adapter returns a valid CrudRepository"
2235
- });
2236
- }
2237
- if (!config.controller) {
2238
- warnings.push({
2239
- field: "controller",
2240
- message: "No controller provided, will auto-create BaseController"
2241
- });
2242
- }
2243
- } else {
2244
- if (!config.adapter && !config.additionalRoutes?.length) {
2245
- warnings.push({
2246
- field: "config",
2247
- message: "Resource has no adapter and no additionalRoutes",
2248
- suggestion: "Provide either adapter for CRUD or additionalRoutes for custom logic"
2249
- });
2250
- }
2251
- }
2252
- if (config.controller && !options.skipControllerCheck && !config.disableDefaultRoutes) {
2253
- const ctrl = config.controller;
2254
- const requiredMethods = ["list", "get", "create", "update", "delete"];
2255
- for (const method of requiredMethods) {
2256
- if (typeof ctrl[method] !== "function") {
2257
- errors.push({
2258
- field: `controller.${method}`,
2259
- message: `Missing required CRUD method "${method}"`,
2260
- suggestion: "Extend BaseController which implements IController interface"
2261
- });
2262
- }
2263
- }
2264
- }
2265
- if (config.controller && config.additionalRoutes) {
2266
- validateAdditionalRouteHandlers(config.controller, config.additionalRoutes, errors);
2267
- }
2268
- if (config.permissions) {
2269
- validatePermissionKeys(config, options, errors, warnings);
2270
- }
2271
- if (config.presets && !options.allowUnknownPresets) {
2272
- validatePresets(config.presets, errors, warnings);
2273
- }
2274
- if (config.prefix) {
2275
- if (!config.prefix.startsWith("/")) {
2276
- errors.push({
2277
- field: "prefix",
2278
- message: `Prefix must start with "/" (got "${config.prefix}")`,
2279
- suggestion: `Change to "/${config.prefix}"`
2280
- });
2281
- }
2282
- if (config.prefix.endsWith("/") && config.prefix !== "/") {
2283
- warnings.push({
2284
- field: "prefix",
2285
- message: `Prefix should not end with "/" (got "${config.prefix}")`,
2286
- suggestion: `Change to "${config.prefix.slice(0, -1)}"`
2287
- });
2288
- }
2289
- }
2290
- if (config.additionalRoutes) {
2291
- validateAdditionalRoutes(config.additionalRoutes, errors);
2292
- }
2293
- return {
2294
- valid: errors.length === 0,
2295
- errors,
2296
- warnings
2297
- };
2298
- }
2299
- function validateAdditionalRouteHandlers(controller, routes, errors) {
2300
- const ctrl = controller;
2301
- for (const route of routes) {
2302
- if (typeof route.handler === "string") {
2303
- if (typeof ctrl[route.handler] !== "function") {
2304
- errors.push({
2305
- field: `additionalRoutes[${route.method} ${route.path}]`,
2306
- message: `Handler "${route.handler}" not found on controller`,
2307
- suggestion: `Add method "${route.handler}" to controller or use a function handler`
2308
- });
2309
- }
2310
- }
2311
- }
2312
- }
2313
- function validatePermissionKeys(config, options, errors, warnings) {
2314
- const validKeys = /* @__PURE__ */ new Set([
2315
- "list",
2316
- "get",
2317
- "create",
2318
- "update",
2319
- "delete",
2320
- ...options.additionalPermissionKeys ?? []
2321
- ]);
2322
- for (const route of config.additionalRoutes ?? []) {
2323
- if (typeof route.handler === "string") {
2324
- validKeys.add(route.handler);
2325
- }
2326
- }
2327
- for (const preset of config.presets ?? []) {
2328
- const presetName = typeof preset === "string" ? preset : preset.name;
2329
- if (presetName === "softDelete") {
2330
- validKeys.add("deleted");
2331
- validKeys.add("restore");
2332
- }
2333
- if (presetName === "slugLookup") {
2334
- validKeys.add("getBySlug");
2335
- }
2336
- if (presetName === "tree") {
2337
- validKeys.add("tree");
2338
- validKeys.add("children");
2339
- validKeys.add("getTree");
2340
- validKeys.add("getChildren");
2341
- }
2342
- }
2343
- for (const key of Object.keys(config.permissions ?? {})) {
2344
- if (!validKeys.has(key)) {
2345
- warnings.push({
2346
- field: `permissions.${key}`,
2347
- message: `Unknown permission key "${key}"`,
2348
- suggestion: `Valid keys: ${Array.from(validKeys).join(", ")}`
2349
- });
2350
- }
2351
- }
2352
- }
2353
- function validatePresets(presets, errors, warnings) {
2354
- const availablePresets = getAvailablePresets();
2355
- for (const preset of presets) {
2356
- if (typeof preset === "object" && ("middlewares" in preset || "additionalRoutes" in preset)) {
2357
- continue;
2358
- }
2359
- const presetName = typeof preset === "string" ? preset : preset.name;
2360
- if (!availablePresets.includes(presetName)) {
2361
- errors.push({
2362
- field: "presets",
2363
- message: `Unknown preset "${presetName}"`,
2364
- suggestion: `Available presets: ${availablePresets.join(", ")}`
2365
- });
2366
- }
2367
- if (typeof preset === "object") {
2368
- validatePresetOptions(preset, warnings);
2369
- }
2370
- }
2371
- }
2372
- function validatePresetOptions(preset, warnings) {
2373
- const knownOptions = {
2374
- slugLookup: ["slugField"],
2375
- tree: ["parentField"],
2376
- softDelete: ["deletedField"],
2377
- ownedByUser: ["ownerField", "bypassRoles"],
2378
- multiTenant: ["tenantField", "bypassRoles"]
2379
- };
2380
- const validOptions = knownOptions[preset.name] ?? [];
2381
- const providedOptions = Object.keys(preset).filter((k) => k !== "name");
2382
- for (const opt of providedOptions) {
2383
- if (!validOptions.includes(opt)) {
2384
- warnings.push({
2385
- field: `presets[${preset.name}].${opt}`,
2386
- message: `Unknown option "${opt}" for preset "${preset.name}"`,
2387
- suggestion: validOptions.length > 0 ? `Valid options: ${validOptions.join(", ")}` : `Preset "${preset.name}" has no configurable options`
2388
- });
2389
- }
2390
- }
2391
- }
2392
- function validateAdditionalRoutes(routes, errors) {
2393
- const validMethods = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"];
2394
- const seenRoutes = /* @__PURE__ */ new Set();
2395
- for (const [i, route] of routes.entries()) {
2396
- if (!validMethods.includes(route.method)) {
2397
- errors.push({
2398
- field: `additionalRoutes[${i}].method`,
2399
- message: `Invalid HTTP method "${route.method}"`,
2400
- suggestion: `Valid methods: ${validMethods.join(", ")}`
2401
- });
2402
- }
2403
- if (!route.path) {
2404
- errors.push({
2405
- field: `additionalRoutes[${i}].path`,
2406
- message: "Route path is required"
2407
- });
2408
- } else if (!route.path.startsWith("/")) {
2409
- errors.push({
2410
- field: `additionalRoutes[${i}].path`,
2411
- message: `Route path must start with "/" (got "${route.path}")`,
2412
- suggestion: `Change to "/${route.path}"`
2413
- });
2414
- }
2415
- if (!route.handler) {
2416
- errors.push({
2417
- field: `additionalRoutes[${i}].handler`,
2418
- message: "Route handler is required"
2419
- });
2420
- }
2421
- const routeKey = `${route.method} ${route.path}`;
2422
- if (seenRoutes.has(routeKey)) {
2423
- errors.push({
2424
- field: `additionalRoutes[${i}]`,
2425
- message: `Duplicate route "${routeKey}"`
2426
- });
2427
- }
2428
- seenRoutes.add(routeKey);
2429
- }
2430
- }
2431
- function formatValidationErrors(resourceName, result) {
2432
- const lines = [];
2433
- if (result.errors.length > 0) {
2434
- lines.push(`Resource "${resourceName}" validation failed:`);
2435
- lines.push("");
2436
- lines.push("ERRORS:");
2437
- for (const err of result.errors) {
2438
- lines.push(` ✗ ${err.field}: ${err.message}`);
2439
- if (err.suggestion) {
2440
- lines.push(` → ${err.suggestion}`);
2441
- }
2442
- }
2443
- }
2444
- if (result.warnings.length > 0) {
2445
- if (lines.length > 0) lines.push("");
2446
- lines.push("WARNINGS:");
2447
- for (const warn of result.warnings) {
2448
- lines.push(` ⚠ ${warn.field}: ${warn.message}`);
2449
- if (warn.suggestion) {
2450
- lines.push(` → ${warn.suggestion}`);
2451
- }
2452
- }
2453
- }
2454
- return lines.join("\n");
2455
- }
2456
- function assertValidConfig(config, options) {
2457
- const result = validateResourceConfig(config, options);
2458
- if (!result.valid) {
2459
- const errorMsg = formatValidationErrors(config.name ?? "unknown", result);
2460
- throw new Error(errorMsg);
2461
- }
2462
- if (result.warnings.length > 0 && process.env.NODE_ENV !== "production") {
2463
- console.warn(formatValidationErrors(config.name ?? "unknown", {
2464
- errors: [],
2465
- warnings: result.warnings
2466
- }));
2467
- }
2468
- }
2469
-
2470
- // src/core/defineResource.ts
2471
- function defineResource(config) {
2472
- if (!config.skipValidation) {
2473
- assertValidConfig(config, { skipControllerCheck: true });
2474
- if (config.permissions) {
2475
- for (const [key, value] of Object.entries(config.permissions)) {
2476
- if (value !== void 0 && typeof value !== "function") {
2477
- throw new Error(
2478
- `[Arc] Resource '${config.name}': permissions.${key} must be a PermissionCheck function.
2479
- Use allowPublic(), requireAuth(), or requireRoles(['role']) from @classytic/arc/permissions.`
2480
- );
2481
- }
2482
- }
2483
- }
2484
- for (const route of config.additionalRoutes ?? []) {
2485
- if (typeof route.permissions !== "function") {
2486
- throw new Error(
2487
- `[Arc] Resource '${config.name}' route ${route.method} ${route.path}: permissions is required and must be a PermissionCheck function.
2488
- Use allowPublic() or requireAuth() from @classytic/arc/permissions.`
2489
- );
2490
- }
2491
- if (typeof route.wrapHandler !== "boolean") {
2492
- throw new Error(
2493
- `[Arc] Resource '${config.name}' route ${route.method} ${route.path}: wrapHandler is required.
2494
- Set true for ControllerHandler (context object) or false for FastifyHandler (req, reply).`
2495
- );
2496
- }
2497
- }
2498
- }
2499
- const repository = config.adapter?.repository;
2500
- const crudRoutes = ["list", "get", "create", "update", "delete"];
2501
- const disabledRoutes = new Set(config.disabledRoutes ?? []);
2502
- const hasCrudRoutes = !config.disableDefaultRoutes && crudRoutes.some((route) => !disabledRoutes.has(route));
2503
- let controller = config.controller;
2504
- if (!controller && hasCrudRoutes && repository) {
2505
- controller = new BaseController(repository, {
2506
- resourceName: config.name,
2507
- schemaOptions: config.schemaOptions,
2508
- queryParser: config.queryParser
2509
- });
2510
- }
2511
- const originalPresets = (config.presets ?? []).map(
2512
- (p) => typeof p === "string" ? p : p.name
2513
- );
2514
- const resolvedConfig = config.presets?.length ? applyPresets(config, config.presets) : config;
2515
- resolvedConfig._appliedPresets = originalPresets;
2516
- if (controller) {
2517
- const ctrl = controller;
2518
- if (typeof ctrl._setResourceOptions === "function") {
2519
- ctrl._setResourceOptions({
2520
- schemaOptions: resolvedConfig.schemaOptions,
2521
- presetFields: resolvedConfig._controllerOptions ? {
2522
- slugField: resolvedConfig._controllerOptions.slugField,
2523
- parentField: resolvedConfig._controllerOptions.parentField
2524
- } : void 0,
2525
- resourceName: resolvedConfig.name,
2526
- queryParser: resolvedConfig.queryParser
2527
- });
2528
- }
2529
- }
2530
- const resource = new ResourceDefinition({
2531
- ...resolvedConfig,
2532
- adapter: config.adapter,
2533
- controller
2534
- });
2535
- if (!config.skipValidation && controller) {
2536
- resource._validateControllerMethods();
2537
- }
2538
- if (resolvedConfig._hooks?.length) {
2539
- for (const hook of resolvedConfig._hooks) {
2540
- hookSystem.register({
2541
- resource: resolvedConfig.name,
2542
- operation: hook.operation,
2543
- phase: hook.phase,
2544
- handler: hook.handler,
2545
- priority: hook.priority ?? 10
2546
- });
2547
- }
2548
- }
2549
- if (!config.skipRegistry) {
2550
- try {
2551
- let openApiSchemas = config.openApiSchemas;
2552
- if (!openApiSchemas && config.adapter?.generateSchemas) {
2553
- const generated = config.adapter.generateSchemas(config.schemaOptions);
2554
- if (generated) {
2555
- openApiSchemas = generated;
2556
- }
2557
- }
2558
- const queryParser = config.queryParser;
2559
- if (!openApiSchemas?.listQuery && queryParser?.getQuerySchema) {
2560
- const querySchema = queryParser.getQuerySchema();
2561
- if (querySchema) {
2562
- openApiSchemas = {
2563
- ...openApiSchemas,
2564
- listQuery: querySchema
2565
- };
2566
- }
2567
- }
2568
- resourceRegistry.register(resource, {
2569
- module: config.module,
2570
- openApiSchemas
2571
- });
2572
- } catch {
2573
- }
2574
- }
2575
- return resource;
2576
- }
2577
- var ResourceDefinition = class {
2578
- // Identity
2579
- name;
2580
- displayName;
2581
- tag;
2582
- prefix;
2583
- // Adapter (database abstraction) - optional for service resources
2584
- adapter;
2585
- // Controller
2586
- controller;
2587
- // Schema & Validation
2588
- schemaOptions;
2589
- customSchemas;
2590
- // Security
2591
- permissions;
2592
- // Customization
2593
- additionalRoutes;
2594
- middlewares;
2595
- disableDefaultRoutes;
2596
- disabledRoutes;
2597
- organizationScoped;
2598
- // Events
2599
- events;
2600
- // Presets tracking
2601
- _appliedPresets;
2602
- constructor(config) {
2603
- this.name = config.name;
2604
- this.displayName = config.displayName ?? capitalize(config.name) + "s";
2605
- this.tag = config.tag ?? this.displayName;
2606
- this.prefix = config.prefix ?? `/${config.name}s`;
2607
- this.adapter = config.adapter;
2608
- this.controller = config.controller;
2609
- this.schemaOptions = config.schemaOptions ?? {};
2610
- this.customSchemas = config.customSchemas ?? {};
2611
- this.permissions = config.permissions ?? {};
2612
- this.additionalRoutes = config.additionalRoutes ?? [];
2613
- this.middlewares = config.middlewares ?? {};
2614
- this.disableDefaultRoutes = config.disableDefaultRoutes ?? false;
2615
- this.disabledRoutes = config.disabledRoutes ?? [];
2616
- this.organizationScoped = config.organizationScoped ?? false;
2617
- this.events = config.events ?? {};
2618
- this._appliedPresets = config._appliedPresets ?? [];
2619
- }
2620
- /** Get repository from adapter (if available) */
2621
- get repository() {
2622
- return this.adapter?.repository;
2623
- }
2624
- /** Get model from adapter (if available) */
2625
- get model() {
2626
- if (!this.adapter) return void 0;
2627
- return this.adapter.getSchemaMetadata?.() ? this.adapter.model : void 0;
2628
- }
2629
- _validateControllerMethods() {
2630
- const errors = [];
2631
- const crudRoutes = ["list", "get", "create", "update", "delete"];
2632
- const disabledRoutes = new Set(this.disabledRoutes ?? []);
2633
- const enabledCrudRoutes = crudRoutes.filter((route) => !disabledRoutes.has(route));
2634
- const hasCrudRoutes = !this.disableDefaultRoutes && enabledCrudRoutes.length > 0;
2635
- if (hasCrudRoutes) {
2636
- if (!this.controller) {
2637
- errors.push("Controller is required when CRUD routes are enabled");
2638
- } else {
2639
- const ctrl = this.controller;
2640
- for (const method of enabledCrudRoutes) {
2641
- if (typeof ctrl[method] !== "function") {
2642
- errors.push(`CRUD method '${method}' not found on controller`);
2643
- }
2644
- }
2645
- }
2646
- }
2647
- for (const route of this.additionalRoutes) {
2648
- if (typeof route.handler === "string") {
2649
- if (!this.controller) {
2650
- errors.push(
2651
- `Route ${route.method} ${route.path}: string handler '${route.handler}' requires a controller`
2652
- );
2653
- } else {
2654
- const ctrl = this.controller;
2655
- if (typeof ctrl[route.handler] !== "function") {
2656
- errors.push(
2657
- `Route ${route.method} ${route.path}: handler '${route.handler}' not found`
2658
- );
2659
- }
2660
- }
2661
- }
2662
- }
2663
- if (errors.length > 0) {
2664
- const errorMsg = [
2665
- `Resource '${this.name}' validation failed:`,
2666
- ...errors.map((e) => ` - ${e}`),
2667
- "",
2668
- "Ensure controller implements IController<TDoc> interface.",
2669
- "For preset routes (softDelete, tree), add corresponding methods to controller."
2670
- ].join("\n");
2671
- throw new Error(errorMsg);
2672
- }
2673
- }
2674
- toPlugin() {
2675
- const self = this;
2676
- return async function resourcePlugin(fastify, _opts) {
2677
- await fastify.register(async (instance) => {
2678
- const typedInstance = instance;
2679
- let schemas = null;
2680
- if (self.adapter) {
2681
- const metadata = self.adapter.getSchemaMetadata?.();
2682
- if (metadata && typedInstance.generateSchemas) {
2683
- const model = self.adapter.model;
2684
- if (model && typeof typedInstance.generateSchemas === "function") {
2685
- schemas = typedInstance.generateSchemas(model, self.schemaOptions);
2686
- }
2687
- }
2688
- }
2689
- if (self.customSchemas && Object.keys(self.customSchemas).length > 0) {
2690
- schemas = schemas ?? {};
2691
- for (const [op, customSchema] of Object.entries(self.customSchemas)) {
2692
- const key = op;
2693
- schemas[key] = schemas[key] ? deepMergeSchemas(schemas[key], customSchema) : customSchema;
2694
- }
2695
- }
2696
- const resolvedRoutes = self.additionalRoutes;
2697
- createCrudRouter(typedInstance, self.controller, {
2698
- tag: self.tag,
2699
- schemas: schemas ?? void 0,
2700
- permissions: self.permissions,
2701
- middlewares: self.middlewares,
2702
- additionalRoutes: resolvedRoutes,
2703
- disableDefaultRoutes: self.disableDefaultRoutes,
2704
- disabledRoutes: self.disabledRoutes,
2705
- organizationScoped: self.organizationScoped,
2706
- resourceName: self.name,
2707
- schemaOptions: self.schemaOptions
2708
- });
2709
- if (self.events && Object.keys(self.events).length > 0) {
2710
- typedInstance.log?.info?.(
2711
- `Resource '${self.name}' defined ${Object.keys(self.events).length} events`
2712
- );
2713
- }
2714
- }, { prefix: self.prefix });
2715
- };
2716
- }
2717
- /**
2718
- * Get event definitions for registry
2719
- */
2720
- getEvents() {
2721
- return Object.entries(this.events).map(([action, meta]) => ({
2722
- name: `${this.name}:${action}`,
2723
- module: this.name,
2724
- schema: meta.schema,
2725
- description: meta.description
2726
- }));
2727
- }
2728
- /**
2729
- * Get resource metadata
2730
- */
2731
- getMetadata() {
2732
- return {
2733
- name: this.name,
2734
- displayName: this.displayName,
2735
- tag: this.tag,
2736
- prefix: this.prefix,
2737
- presets: this._appliedPresets,
2738
- permissions: this.permissions,
2739
- additionalRoutes: this.additionalRoutes,
2740
- routes: [],
2741
- // Populated at runtime during registration
2742
- events: Object.keys(this.events)
2743
- };
2744
- }
2745
- };
2746
- function deepMergeSchemas(base, override) {
2747
- if (!override) return base;
2748
- if (!base) return override;
2749
- const result = { ...base };
2750
- for (const [key, value] of Object.entries(override)) {
2751
- if (value && typeof value === "object" && !Array.isArray(value)) {
2752
- result[key] = deepMergeSchemas(result[key], value);
2753
- } else {
2754
- result[key] = value;
2755
- }
2756
- }
2757
- return result;
2758
- }
2759
- function capitalize(str) {
2760
- if (!str) return "";
2761
- return str.charAt(0).toUpperCase() + str.slice(1);
2762
- }
2763
-
2764
- export { BaseController, ResourceDefinition, createActionRouter, createCrudHandlers, createCrudRouter, createFastifyHandler, createOrgScopedMiddleware, createPermissionMiddleware, createRequestContext, defineResource, sendControllerResponse };