@terreno/api 57.3.0 → 57.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (412) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +23 -10
  2. package/README.md +11 -5
  3. package/bunfig.toml +1 -1
  4. package/dist/actions.js +197 -368
  5. package/dist/adminModelRouter.js +88 -173
  6. package/dist/adminTypes.d.ts +7 -0
  7. package/dist/adminTypes.js +6 -1
  8. package/dist/api.d.ts +10 -0
  9. package/dist/api.js +601 -792
  10. package/dist/audit/auditApp.d.ts +30 -0
  11. package/dist/audit/auditApp.js +114 -0
  12. package/dist/audit/auditEventModel.d.ts +29 -0
  13. package/dist/audit/auditEventModel.js +101 -0
  14. package/dist/audit/cloudTasksEnqueue.d.ts +32 -0
  15. package/dist/audit/cloudTasksEnqueue.js +69 -0
  16. package/dist/audit/diff.d.ts +10 -0
  17. package/dist/audit/diff.js +140 -0
  18. package/dist/audit/processQueue.d.ts +6 -0
  19. package/dist/audit/processQueue.js +56 -0
  20. package/dist/audit/rbacSink.d.ts +2 -0
  21. package/dist/audit/rbacSink.js +41 -0
  22. package/dist/audit/record.d.ts +56 -0
  23. package/dist/audit/record.js +251 -0
  24. package/dist/auth.js +432 -681
  25. package/dist/authRecovery.js +155 -269
  26. package/dist/authTokens.js +43 -118
  27. package/dist/betterAuth.d.ts +6 -0
  28. package/dist/betterAuthApp.js +25 -26
  29. package/dist/betterAuthSetup.js +258 -413
  30. package/dist/browserLogsRoute.d.ts +6 -0
  31. package/dist/browserLogsRoute.js +97 -0
  32. package/dist/collectionRegistry.d.ts +3 -1
  33. package/dist/collectionRegistry.js +43 -33
  34. package/dist/config.js +53 -122
  35. package/dist/configurationApp.js +180 -361
  36. package/dist/configurationPlugin.js +130 -302
  37. package/dist/consentApp.js +276 -421
  38. package/dist/docLoader.js +78 -126
  39. package/dist/envConfigurationPlugin.js +25 -147
  40. package/dist/errors.js +151 -247
  41. package/dist/example.js +28 -34
  42. package/dist/expressServer.d.ts +10 -0
  43. package/dist/expressServer.js +109 -255
  44. package/dist/frameworkModelNames.d.ts +24 -0
  45. package/dist/frameworkModelNames.js +31 -0
  46. package/dist/githubAuth.js +152 -216
  47. package/dist/httpClient.js +176 -264
  48. package/dist/index.d.ts +28 -1
  49. package/dist/index.js +53 -2
  50. package/dist/logger.js +145 -278
  51. package/dist/mcp/auth.js +76 -128
  52. package/dist/mcp/createMCPRequest.js +4 -5
  53. package/dist/mcp/handlers.js +268 -480
  54. package/dist/mcp/query.d.ts +0 -13
  55. package/dist/mcp/query.js +57 -151
  56. package/dist/mcp/registry.js +17 -30
  57. package/dist/mcp/schemaGenerator.js +95 -181
  58. package/dist/mcp/server.js +28 -100
  59. package/dist/mcp/serviceTokens.js +102 -191
  60. package/dist/mcp/toolGenerator.js +78 -191
  61. package/dist/middleware.js +15 -27
  62. package/dist/migrations/fixtures/all-down/20260910120000-one.d.ts +4 -0
  63. package/dist/migrations/fixtures/all-down/20260910120000-one.js +9 -0
  64. package/dist/migrations/fixtures/all-down/20260910120001-two.d.ts +4 -0
  65. package/dist/migrations/fixtures/all-down/20260910120001-two.js +9 -0
  66. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.d.ts +3 -0
  67. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +7 -0
  68. package/dist/migrations/fixtures/bad-name/not-a-migration.d.ts +3 -0
  69. package/dist/migrations/fixtures/bad-name/not-a-migration.js +7 -0
  70. package/dist/migrations/fixtures/missing-up/20260910120000-noup.d.ts +2 -0
  71. package/dist/migrations/fixtures/missing-up/20260910120000-noup.js +5 -0
  72. package/dist/migrations/fixtures/valid/20260910120000-alpha.d.ts +3 -0
  73. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +7 -0
  74. package/dist/migrations/fixtures/valid/20260910120001-beta.d.ts +4 -0
  75. package/dist/migrations/fixtures/valid/20260910120001-beta.js +9 -0
  76. package/dist/migrations/generate.d.ts +17 -0
  77. package/dist/migrations/generate.js +155 -0
  78. package/dist/migrations/load.d.ts +20 -0
  79. package/dist/migrations/load.js +110 -0
  80. package/dist/migrations/lock.d.ts +13 -0
  81. package/dist/migrations/lock.js +73 -0
  82. package/dist/migrations/runner.d.ts +42 -0
  83. package/dist/migrations/runner.js +249 -0
  84. package/dist/migrations/schemaCatalog.d.ts +44 -0
  85. package/dist/migrations/schemaCatalog.js +185 -0
  86. package/dist/migrations/types.d.ts +87 -0
  87. package/dist/migrations/types.js +7 -0
  88. package/dist/models/consentForm.js +6 -6
  89. package/dist/models/consentResponse.js +5 -5
  90. package/dist/models/mcpServiceToken.js +66 -156
  91. package/dist/models/notification.d.ts +2 -0
  92. package/dist/models/notification.js +62 -0
  93. package/dist/models/notificationPreference.d.ts +2 -0
  94. package/dist/models/notificationPreference.js +49 -0
  95. package/dist/models/versionConfig.js +5 -5
  96. package/dist/notifications/notificationService.d.ts +40 -0
  97. package/dist/notifications/notificationService.js +183 -0
  98. package/dist/notifications/notificationsApp.d.ts +18 -0
  99. package/dist/notifications/notificationsApp.js +156 -0
  100. package/dist/notifications/notificationsBeforeSend.d.ts +14 -0
  101. package/dist/notifications/notificationsBeforeSend.js +32 -0
  102. package/dist/notifiers/googleChatNotifier.js +36 -117
  103. package/dist/notifiers/slackNotifier.d.ts +31 -2
  104. package/dist/notifiers/slackNotifier.js +170 -119
  105. package/dist/notifiers/zoomNotifier.js +60 -111
  106. package/dist/openApi.d.ts +1 -7
  107. package/dist/openApi.js +113 -127
  108. package/dist/openApiBuilder.d.ts +14 -3
  109. package/dist/openApiBuilder.js +117 -159
  110. package/dist/openApiCompat.js +81 -148
  111. package/dist/openApiEtag.js +7 -7
  112. package/dist/openApiValidator.d.ts +13 -1
  113. package/dist/openApiValidator.js +301 -246
  114. package/dist/orgs/orgContext.d.ts +23 -0
  115. package/dist/orgs/orgContext.js +128 -0
  116. package/dist/orgs/orgPermissions.d.ts +4 -0
  117. package/dist/orgs/orgPermissions.js +38 -0
  118. package/dist/orgs/orgPlugin.d.ts +13 -0
  119. package/dist/orgs/orgPlugin.js +66 -0
  120. package/dist/orgs/organizationModel.d.ts +13 -0
  121. package/dist/orgs/organizationModel.js +200 -0
  122. package/dist/orgs/organizationSettings.d.ts +19 -0
  123. package/dist/orgs/organizationSettings.js +113 -0
  124. package/dist/orgs/orgsApp.d.ts +28 -0
  125. package/dist/orgs/orgsApp.js +416 -0
  126. package/dist/permissions.d.ts +7 -13
  127. package/dist/permissions.js +95 -211
  128. package/dist/plugins.js +125 -218
  129. package/dist/populate.js +130 -240
  130. package/dist/rateLimit/applyTrustProxy.js +1 -1
  131. package/dist/rateLimit/createStore.js +7 -8
  132. package/dist/rateLimit/memoryStore.js +22 -100
  133. package/dist/rateLimit/middleware.d.ts +0 -8
  134. package/dist/rateLimit/middleware.js +49 -101
  135. package/dist/rateLimit/mongoStore.d.ts +1 -0
  136. package/dist/rateLimit/mongoStore.js +55 -112
  137. package/dist/rateLimit/policies.d.ts +0 -4
  138. package/dist/rateLimit/policies.js +44 -80
  139. package/dist/rateLimit/redisStore.d.ts +1 -0
  140. package/dist/rateLimit/redisStore.js +40 -133
  141. package/dist/rbac/access.js +122 -253
  142. package/dist/rbac/assertAllowed.js +95 -171
  143. package/dist/rbac/auditModel.js +14 -58
  144. package/dist/rbac/backfillAdmins.js +24 -130
  145. package/dist/rbac/fieldViews.js +46 -141
  146. package/dist/rbac/membershipOrgAdminSource.d.ts +6 -0
  147. package/dist/rbac/membershipOrgAdminSource.js +51 -0
  148. package/dist/rbac/middleware.js +30 -96
  149. package/dist/rbac/modelRouterAccess.d.ts +3 -0
  150. package/dist/rbac/modelRouterAccess.js +133 -307
  151. package/dist/rbac/permissionUtils.js +40 -179
  152. package/dist/rbac/realtimeAccess.js +81 -147
  153. package/dist/rbac/resolve.d.ts +1 -1
  154. package/dist/rbac/resolve.js +154 -319
  155. package/dist/rbac/roleManager.js +318 -700
  156. package/dist/rbac/roleModel.d.ts +2 -5
  157. package/dist/rbac/roleModel.js +60 -173
  158. package/dist/rbac/routes.js +93 -196
  159. package/dist/rbac/scopes.js +39 -133
  160. package/dist/rbac/statements.d.ts +10 -1
  161. package/dist/rbac/statements.js +42 -93
  162. package/dist/rbac/types.d.ts +5 -0
  163. package/dist/rbac/userPlugin.js +3 -29
  164. package/dist/realtime/changeStreamWatcher.d.ts +10 -4
  165. package/dist/realtime/changeStreamWatcher.js +499 -764
  166. package/dist/realtime/deprecation.d.ts +1 -0
  167. package/dist/realtime/deprecation.js +9 -10
  168. package/dist/realtime/queryMatcher.js +110 -191
  169. package/dist/realtime/queryStore.js +35 -118
  170. package/dist/realtime/realtimeApp.d.ts +1 -0
  171. package/dist/realtime/realtimeApp.js +248 -401
  172. package/dist/realtime/registry.js +19 -30
  173. package/dist/realtime/sessionRevalidation.js +132 -358
  174. package/dist/realtime/socketAuth.js +89 -208
  175. package/dist/realtime/socketUser.js +10 -56
  176. package/dist/requestContext.js +93 -139
  177. package/dist/schemaMetadata.js +181 -265
  178. package/dist/scriptRunner.js +96 -266
  179. package/dist/scrubAdminFields.js +36 -108
  180. package/dist/secretProviders.js +130 -299
  181. package/dist/seedRunner.js +221 -514
  182. package/dist/sync/adminBroadcastScope.d.ts +40 -0
  183. package/dist/sync/adminBroadcastScope.js +82 -0
  184. package/dist/sync/adminWindowAccess.d.ts +13 -0
  185. package/dist/sync/adminWindowAccess.js +25 -0
  186. package/dist/sync/adminWindowMutation.d.ts +88 -0
  187. package/dist/sync/adminWindowMutation.js +176 -0
  188. package/dist/sync/executors.d.ts +9 -3
  189. package/dist/sync/executors.js +425 -598
  190. package/dist/sync/loadHarness.js +392 -689
  191. package/dist/sync/models.js +181 -341
  192. package/dist/sync/mutationHandler.d.ts +5 -2
  193. package/dist/sync/mutationHandler.js +549 -697
  194. package/dist/sync/registrationSideEffects.js +41 -95
  195. package/dist/sync/registry.js +31 -47
  196. package/dist/sync/routes.d.ts +13 -0
  197. package/dist/sync/routes.js +484 -760
  198. package/dist/sync/scripts/compactTombstones.js +83 -228
  199. package/dist/sync/serialize.js +18 -58
  200. package/dist/sync/socketHandlers.d.ts +8 -2
  201. package/dist/sync/socketHandlers.js +271 -402
  202. package/dist/sync/streams.d.ts +2 -0
  203. package/dist/sync/streams.js +54 -116
  204. package/dist/sync/syncApp.d.ts +2 -1
  205. package/dist/sync/syncApp.js +14 -16
  206. package/dist/sync/syncBatch.d.ts +5 -2
  207. package/dist/sync/syncBatch.js +63 -168
  208. package/dist/sync/syncSeqPlugin.js +430 -702
  209. package/dist/sync/types.d.ts +18 -0
  210. package/dist/syncConsents.js +113 -253
  211. package/dist/terrenoApp.d.ts +29 -0
  212. package/dist/terrenoApp.js +184 -257
  213. package/dist/tests/createTestData.d.ts +1 -3
  214. package/dist/tests/createTestData.js +147 -259
  215. package/dist/tests/models.d.ts +1 -0
  216. package/dist/tests/models.js +23 -56
  217. package/dist/tests/mongoTestSetup.js +42 -103
  218. package/dist/tests/testHelper.d.ts +0 -5
  219. package/dist/tests/testHelper.js +32 -101
  220. package/dist/tests.js +12 -51
  221. package/dist/transformers.js +61 -164
  222. package/dist/types/authToken.d.ts +3 -3
  223. package/dist/types/mcpServiceToken.d.ts +2 -2
  224. package/dist/types/membership.d.ts +23 -0
  225. package/dist/types/membership.js +2 -0
  226. package/dist/types/notification.d.ts +28 -0
  227. package/dist/types/notification.js +2 -0
  228. package/dist/types/notificationPreference.d.ts +20 -0
  229. package/dist/types/notificationPreference.js +2 -0
  230. package/dist/types/organization.d.ts +36 -0
  231. package/dist/types/organization.js +2 -0
  232. package/dist/utils.js +31 -93
  233. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  234. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  235. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  236. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  237. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  238. package/dist/versionCheckPlugin.js +52 -100
  239. package/dist/webhooks/headerValue.js +2 -2
  240. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  241. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  242. package/dist/webhooks/idempotency/webhookReceipt.d.ts +4 -49
  243. package/dist/webhooks/idempotency/webhookReceipt.js +14 -14
  244. package/dist/webhooks/rawBody.d.ts +1 -0
  245. package/dist/webhooks/rawBody.js +2 -1
  246. package/dist/webhooks/timingSafeEqual.js +4 -5
  247. package/dist/webhooks/verifiers/hmac.js +17 -18
  248. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  249. package/dist/webhooks/verifiers/stripe.js +31 -65
  250. package/dist/webhooks/verifiers/twilio.js +23 -73
  251. package/dist/webhooks/webhooksApp.js +78 -177
  252. package/dist/zodOpenApi.js +2 -2
  253. package/package.json +34 -28
  254. package/src/__snapshots__/openApi.test.ts.snap +192 -54
  255. package/src/__snapshots__/openApiBuilder.test.ts.snap +0 -18
  256. package/src/__snapshots__/schemaMetadata.test.ts.snap +0 -1
  257. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  258. package/src/adminTypes.ts +8 -0
  259. package/src/api.test.ts +39 -2
  260. package/src/api.ts +68 -0
  261. package/src/audit/auditApp.test.ts +243 -0
  262. package/src/audit/auditApp.ts +139 -0
  263. package/src/audit/auditEventModel.ts +160 -0
  264. package/src/audit/auditRouter.test.ts +456 -0
  265. package/src/audit/cloudTasksEnqueue.test.ts +124 -0
  266. package/src/audit/cloudTasksEnqueue.ts +104 -0
  267. package/src/audit/diff.ts +163 -0
  268. package/src/audit/processQueue.ts +69 -0
  269. package/src/audit/rbacSink.test.ts +86 -0
  270. package/src/audit/rbacSink.ts +42 -0
  271. package/src/audit/record.test.ts +402 -0
  272. package/src/audit/record.ts +329 -0
  273. package/src/auth.test.ts +1 -1
  274. package/src/auth.ts +1 -1
  275. package/src/authRecovery.test.ts +43 -0
  276. package/src/authRecovery.ts +16 -10
  277. package/src/authTokens.ts +6 -2
  278. package/src/authVerification.test.ts +22 -0
  279. package/src/betterAuth.ts +7 -0
  280. package/src/betterAuthSetup.test.ts +27 -0
  281. package/src/betterAuthSetup.ts +1 -0
  282. package/src/browserLogsRoute.ts +110 -0
  283. package/src/collectionRegistry.test.ts +8 -9
  284. package/src/collectionRegistry.ts +21 -1
  285. package/src/configurationPlugin.test.ts +1 -11
  286. package/src/express.d.ts +2 -0
  287. package/src/expressServer.test.ts +50 -2
  288. package/src/expressServer.ts +10 -0
  289. package/src/frameworkModelNames.test.ts +62 -0
  290. package/src/frameworkModelNames.ts +33 -0
  291. package/src/index.ts +76 -0
  292. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  293. package/src/mcp/auth.test.ts +34 -1
  294. package/src/mcp/handlers.test.ts +275 -0
  295. package/src/mcp/query.ts +3 -3
  296. package/src/mcp/toolGenerator.test.ts +81 -0
  297. package/src/migrations/cli.test.ts +353 -0
  298. package/src/migrations/cli.ts +283 -0
  299. package/src/migrations/fixtures/all-down/20260910120000-one.ts +6 -0
  300. package/src/migrations/fixtures/all-down/20260910120001-two.ts +6 -0
  301. package/src/migrations/fixtures/bad-id/20260910120000-mismatch.ts +4 -0
  302. package/src/migrations/fixtures/bad-name/not-a-migration.ts +4 -0
  303. package/src/migrations/fixtures/missing-up/20260910120000-noup.ts +2 -0
  304. package/src/migrations/fixtures/valid/20260910120000-alpha.ts +4 -0
  305. package/src/migrations/fixtures/valid/20260910120001-beta.ts +6 -0
  306. package/src/migrations/generate.test.ts +333 -0
  307. package/src/migrations/generate.ts +216 -0
  308. package/src/migrations/load.test.ts +103 -0
  309. package/src/migrations/load.ts +124 -0
  310. package/src/migrations/lock.test.ts +133 -0
  311. package/src/migrations/lock.ts +118 -0
  312. package/src/migrations/runner.test.ts +504 -0
  313. package/src/migrations/runner.ts +358 -0
  314. package/src/migrations/schemaCatalog.test.ts +159 -0
  315. package/src/migrations/schemaCatalog.ts +262 -0
  316. package/src/migrations/types.ts +94 -0
  317. package/src/models/mcpServiceToken.ts +4 -3
  318. package/src/models/notification.ts +69 -0
  319. package/src/models/notificationPreference.ts +62 -0
  320. package/src/notifications/notificationService.ts +254 -0
  321. package/src/notifications/notificationsApp.test.ts +528 -0
  322. package/src/notifications/notificationsApp.ts +200 -0
  323. package/src/notifications/notificationsBeforeSend.ts +51 -0
  324. package/src/notifiers/slackNotifier.test.ts +186 -1
  325. package/src/notifiers/slackNotifier.ts +167 -8
  326. package/src/openApi.test.ts +0 -1
  327. package/src/openApi.ts +2 -1
  328. package/src/openApiBuilder.ts +14 -3
  329. package/src/openApiValidator.test.ts +221 -2
  330. package/src/openApiValidator.ts +218 -33
  331. package/src/orgs/orgAccessOptIn.test.ts +87 -0
  332. package/src/orgs/orgContext.test.ts +259 -0
  333. package/src/orgs/orgContext.ts +151 -0
  334. package/src/orgs/orgPermissions.test.ts +105 -0
  335. package/src/orgs/orgPermissions.ts +40 -0
  336. package/src/orgs/orgPlugin.test.ts +130 -0
  337. package/src/orgs/orgPlugin.ts +70 -0
  338. package/src/orgs/orgRbac.test.ts +267 -0
  339. package/src/orgs/orgSecurityDefects.test.ts +415 -0
  340. package/src/orgs/organizationModel.test.ts +205 -0
  341. package/src/orgs/organizationModel.ts +262 -0
  342. package/src/orgs/organizationSettings.test.ts +113 -0
  343. package/src/orgs/organizationSettings.ts +126 -0
  344. package/src/orgs/orgsApp.test.ts +382 -0
  345. package/src/orgs/orgsApp.ts +563 -0
  346. package/src/permissions.test.ts +62 -36
  347. package/src/permissions.ts +8 -30
  348. package/src/plugins.test.ts +5 -0
  349. package/src/plugins.ts +3 -0
  350. package/src/rateLimit/middleware.ts +1 -1
  351. package/src/rateLimit/mongoStore.ts +1 -0
  352. package/src/rateLimit/policies.ts +2 -2
  353. package/src/rateLimit/redisStore.ts +1 -0
  354. package/src/rbac/access.ts +11 -3
  355. package/src/rbac/membershipOrgAdminSource.ts +59 -0
  356. package/src/rbac/modelRouterAccess.ts +3 -0
  357. package/src/rbac/permissionUtils.test.ts +26 -5
  358. package/src/rbac/resolve.test.ts +34 -2
  359. package/src/rbac/resolve.ts +26 -7
  360. package/src/rbac/roleModel.test.ts +34 -1
  361. package/src/rbac/roleModel.ts +17 -1
  362. package/src/rbac/statements.test.ts +19 -0
  363. package/src/rbac/statements.ts +19 -1
  364. package/src/rbac/types.ts +5 -0
  365. package/src/realtime/changeStreamWatcher.ts +73 -33
  366. package/src/realtime/deprecation.ts +1 -0
  367. package/src/realtime/realtime.test.ts +357 -185
  368. package/src/realtime/realtimeApp.ts +2 -1
  369. package/src/schemaMetadata.test.ts +14 -0
  370. package/src/schemaMetadata.ts +5 -5
  371. package/src/sync/adminBroadcastConfig.test.ts +96 -0
  372. package/src/sync/adminBroadcastScope.test.ts +155 -0
  373. package/src/sync/adminBroadcastScope.ts +123 -0
  374. package/src/sync/adminWindowAccess.test.ts +57 -0
  375. package/src/sync/adminWindowAccess.ts +32 -0
  376. package/src/sync/adminWindowMutation.test.ts +450 -0
  377. package/src/sync/adminWindowMutation.ts +283 -0
  378. package/src/sync/executors.ts +33 -6
  379. package/src/sync/integration.test.ts +2 -2
  380. package/src/sync/mutationHandler.test.ts +277 -1
  381. package/src/sync/mutationHandler.ts +171 -29
  382. package/src/sync/registry.ts +4 -0
  383. package/src/sync/routes.ts +52 -8
  384. package/src/sync/socketHandlers.ts +154 -58
  385. package/src/sync/streams.ts +6 -0
  386. package/src/sync/sync.test.ts +3 -2
  387. package/src/sync/syncApp.ts +2 -1
  388. package/src/sync/syncBatch.ts +7 -2
  389. package/src/sync/syncRoutes.test.ts +297 -3
  390. package/src/sync/syncSocket.test.ts +229 -0
  391. package/src/sync/types.ts +20 -0
  392. package/src/terrenoApp.migrations.test.ts +114 -0
  393. package/src/terrenoApp.test.ts +41 -0
  394. package/src/terrenoApp.ts +97 -31
  395. package/src/tests/createTestData.ts +2 -2
  396. package/src/tests/models.ts +10 -2
  397. package/src/tests/testHelper.ts +1 -7
  398. package/src/types/authToken.ts +2 -4
  399. package/src/types/mcpServiceToken.ts +1 -7
  400. package/src/types/membership.ts +48 -0
  401. package/src/types/notification.ts +34 -0
  402. package/src/types/notificationPreference.ts +28 -0
  403. package/src/types/organization.ts +49 -0
  404. package/src/types.d.ts +1 -0
  405. package/src/webhooks/idempotency/webhookReceipt.ts +8 -10
  406. package/src/webhooks/rawBody.test.ts +33 -0
  407. package/src/webhooks/rawBody.ts +1 -0
  408. package/tsconfig.json +13 -54
  409. package/tsconfig.typedoc.json +4 -1
  410. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.d.ts +0 -2
  411. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
  412. package/src/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
@@ -7,7 +7,8 @@
7
7
  *
8
8
  * Validation is always installed as middleware but only activates after
9
9
  * `configureOpenApiValidator()` is called. This makes it safe to include
10
- * in modelRouter by default.
10
+ * in modelRouter by default. Create bodies enforce Mongoose required fields;
11
+ * PATCH/update bodies are partial (present fields only).
11
12
  *
12
13
  * @module openApiValidator
13
14
  *
@@ -34,79 +35,21 @@
34
35
  * });
35
36
  * ```
36
37
  */
37
- var __assign = (this && this.__assign) || function () {
38
- __assign = Object.assign || function(t) {
39
- for (var s, i = 1, n = arguments.length; i < n; i++) {
40
- s = arguments[i];
41
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
42
- t[p] = s[p];
43
- }
44
- return t;
45
- };
46
- return __assign.apply(this, arguments);
47
- };
48
- var __rest = (this && this.__rest) || function (s, e) {
49
- var t = {};
50
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
51
- t[p] = s[p];
52
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
53
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
54
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
55
- t[p[i]] = s[p[i]];
56
- }
57
- return t;
58
- };
59
- var __values = (this && this.__values) || function(o) {
60
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
61
- if (m) return m.call(o);
62
- if (o && typeof o.length === "number") return {
63
- next: function () {
64
- if (o && i >= o.length) o = void 0;
65
- return { value: o && o[i++], done: !o };
66
- }
67
- };
68
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
69
- };
70
- var __read = (this && this.__read) || function (o, n) {
71
- var m = typeof Symbol === "function" && o[Symbol.iterator];
72
- if (!m) return o;
73
- var i = m.call(o), r, ar = [], e;
74
- try {
75
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
76
- }
77
- catch (error) { e = { error: error }; }
78
- finally {
79
- try {
80
- if (r && !r.done && (m = i["return"])) m.call(i);
81
- }
82
- finally { if (e) throw e.error; }
83
- }
84
- return ar;
85
- };
86
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
87
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
88
- if (ar || !(i in from)) {
89
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
90
- ar[i] = from[i];
91
- }
92
- }
93
- return to.concat(ar || Array.prototype.slice.call(from));
94
- };
95
38
  var __importDefault = (this && this.__importDefault) || function (mod) {
96
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
97
40
  };
98
41
  Object.defineProperty(exports, "__esModule", { value: true });
99
- exports.buildQuerySchemaFromFields = exports.createModelValidators = exports.validateModelRequestBody = exports.getSchemaFromModel = exports.validateResponseData = exports.createValidator = exports.validateQueryParams = exports.validateRequestBody = exports.resetOpenApiValidatorConfig = exports.getOpenApiValidatorConfig = exports.configureOpenApiValidator = exports.isOpenApiValidatorConfigured = void 0;
100
- var ajv_1 = __importDefault(require("ajv"));
101
- var ajv_formats_1 = __importDefault(require("ajv-formats"));
102
- var mongoose_to_swagger_1 = __importDefault(require("mongoose-to-swagger"));
103
- var errors_1 = require("./errors");
104
- var logger_1 = require("./logger");
105
- var populate_1 = require("./populate");
42
+ exports.buildQuerySchemaFromFields = exports.buildNumericListQueryFieldSchema = exports.buildStringListQueryFieldSchema = exports.createModelValidators = exports.validateModelRequestBody = exports.getSchemaFromModel = exports.validateResponseData = exports.createValidator = exports.validateQueryParams = exports.validateRequestBody = exports.isEscapedRegexLiteral = exports.resetOpenApiValidatorConfig = exports.getOpenApiValidatorConfig = exports.configureOpenApiValidator = exports.isOpenApiValidatorConfigured = void 0;
43
+ const ajv_1 = __importDefault(require("ajv"));
44
+ const ajv_formats_1 = __importDefault(require("ajv-formats"));
45
+ const adminTypes_1 = require("./adminTypes");
46
+ const errors_1 = require("./errors");
47
+ const logger_1 = require("./logger");
48
+ const populate_1 = require("./populate");
106
49
  // Whether configureOpenApiValidator() has been called
107
- var isConfigured = false;
50
+ let isConfigured = false;
108
51
  // Global validator configuration - can be modified at runtime
109
- var globalConfig = {
52
+ let globalConfig = {
110
53
  coerceTypes: true,
111
54
  logValidationErrors: true,
112
55
  removeAdditional: true,
@@ -117,7 +60,7 @@ var globalConfig = {
117
60
  * Check whether `configureOpenApiValidator()` has been called.
118
61
  * Validation middleware is a no-op when this returns false.
119
62
  */
120
- var isOpenApiValidatorConfigured = function () {
63
+ const isOpenApiValidatorConfigured = () => {
121
64
  return isConfigured;
122
65
  };
123
66
  exports.isOpenApiValidatorConfigured = isOpenApiValidatorConfigured;
@@ -138,21 +81,20 @@ exports.isOpenApiValidatorConfigured = isOpenApiValidatorConfigured;
138
81
  * });
139
82
  * ```
140
83
  */
141
- var configureOpenApiValidator = function (config) {
142
- if (config === void 0) { config = {}; }
84
+ const configureOpenApiValidator = (config = {}) => {
143
85
  isConfigured = true;
144
- globalConfig = __assign(__assign({}, globalConfig), config);
86
+ globalConfig = { ...globalConfig, ...config };
145
87
  // Clear cached AJV instances so new config takes effect
146
88
  ajvCache.clear();
147
89
  validatorCache.clear();
148
- logger_1.logger.debug("OpenAPI validator configured: ".concat(JSON.stringify(globalConfig)));
90
+ logger_1.logger.debug(`OpenAPI validator configured: ${JSON.stringify(globalConfig)}`);
149
91
  };
150
92
  exports.configureOpenApiValidator = configureOpenApiValidator;
151
93
  /**
152
94
  * Get the current global validator configuration.
153
95
  */
154
- var getOpenApiValidatorConfig = function () {
155
- return __assign({}, globalConfig);
96
+ const getOpenApiValidatorConfig = () => {
97
+ return { ...globalConfig };
156
98
  };
157
99
  exports.getOpenApiValidatorConfig = getOpenApiValidatorConfig;
158
100
  /**
@@ -160,7 +102,7 @@ exports.getOpenApiValidatorConfig = getOpenApiValidatorConfig;
160
102
  * Also resets `isConfigured` to false.
161
103
  * Useful for testing.
162
104
  */
163
- var resetOpenApiValidatorConfig = function () {
105
+ const resetOpenApiValidatorConfig = () => {
164
106
  isConfigured = false;
165
107
  globalConfig = {
166
108
  coerceTypes: true,
@@ -174,37 +116,41 @@ var resetOpenApiValidatorConfig = function () {
174
116
  };
175
117
  exports.resetOpenApiValidatorConfig = resetOpenApiValidatorConfig;
176
118
  // Lazy AJV instance cache keyed by coerceTypes + removeAdditional
177
- var ajvCache = new Map();
119
+ const ajvCache = new Map();
178
120
  /**
179
121
  * Get or create an AJV instance with the current config settings.
180
122
  */
181
- var getAjvInstance = function () {
182
- var _a, _b, _c, _d;
183
- var key = "coerce:".concat((_a = globalConfig.coerceTypes) !== null && _a !== void 0 ? _a : true, ",remove:").concat((_b = globalConfig.removeAdditional) !== null && _b !== void 0 ? _b : true);
184
- var instance = ajvCache.get(key);
123
+ const getAjvInstance = () => {
124
+ const key = `coerce:${globalConfig.coerceTypes ?? true},remove:${globalConfig.removeAdditional ?? true}`;
125
+ let instance = ajvCache.get(key);
185
126
  if (!instance) {
186
127
  instance = new ajv_1.default({
187
128
  allErrors: true,
188
- coerceTypes: (_c = globalConfig.coerceTypes) !== null && _c !== void 0 ? _c : true,
189
- removeAdditional: (_d = globalConfig.removeAdditional) !== null && _d !== void 0 ? _d : true,
129
+ coerceTypes: globalConfig.coerceTypes ?? true,
130
+ removeAdditional: globalConfig.removeAdditional ?? true,
190
131
  strict: false,
191
132
  useDefaults: true,
192
133
  validateSchema: false,
193
134
  });
194
135
  (0, ajv_formats_1.default)(instance);
136
+ instance.addKeyword({
137
+ keyword: ESCAPED_REGEX_LITERAL_KEYWORD,
138
+ type: "string",
139
+ validate: (_enabled, data) => (0, exports.isEscapedRegexLiteral)(data),
140
+ });
195
141
  ajvCache.set(key, instance);
196
142
  }
197
143
  return instance;
198
144
  };
199
145
  // Cache compiled validators by schema hash + config key
200
- var validatorCache = new Map();
146
+ const validatorCache = new Map();
201
147
  /**
202
148
  * Generate a simple hash for a schema to use as a cache key.
203
149
  */
204
- var hashSchema = function (schema) {
150
+ const hashSchema = (schema) => {
205
151
  return JSON.stringify(schema);
206
152
  };
207
- var VALID_JSON_SCHEMA_TYPES = new Set([
153
+ const VALID_JSON_SCHEMA_TYPES = new Set([
208
154
  "string",
209
155
  "number",
210
156
  "integer",
@@ -213,8 +159,44 @@ var VALID_JSON_SCHEMA_TYPES = new Set([
213
159
  "object",
214
160
  "null",
215
161
  ]);
162
+ const REGEX_META_CHARACTERS = new Set([
163
+ "\\",
164
+ ".",
165
+ "*",
166
+ "+",
167
+ "?",
168
+ "^",
169
+ "$",
170
+ "{",
171
+ "}",
172
+ "(",
173
+ ")",
174
+ "|",
175
+ "[",
176
+ "]",
177
+ ]);
178
+ /** Accepts literal text and escaped metacharacters (e.g. `\\.`), rejects executable patterns. */
179
+ const isEscapedRegexLiteral = (value) => {
180
+ for (let index = 0; index < value.length; index += 1) {
181
+ const character = value[index];
182
+ if (character === "\\") {
183
+ const escapedCharacter = value[index + 1];
184
+ if (!escapedCharacter || !REGEX_META_CHARACTERS.has(escapedCharacter)) {
185
+ return false;
186
+ }
187
+ index += 1;
188
+ continue;
189
+ }
190
+ if (REGEX_META_CHARACTERS.has(character)) {
191
+ return false;
192
+ }
193
+ }
194
+ return true;
195
+ };
196
+ exports.isEscapedRegexLiteral = isEscapedRegexLiteral;
197
+ const ESCAPED_REGEX_LITERAL_KEYWORD = "escapedRegexLiteral";
216
198
  // mongoose-to-swagger emits non-standard type strings for some Mongoose types
217
- var MONGOOSE_TYPE_MAP = {
199
+ const MONGOOSE_TYPE_MAP = {
218
200
  dateonly: { format: "date", type: "string" },
219
201
  schemaobjectid: { type: "string" },
220
202
  };
@@ -222,14 +204,13 @@ var MONGOOSE_TYPE_MAP = {
222
204
  * Recursively replace non-standard mongoose-to-swagger types with valid JSON Schema types
223
205
  * so AJV can compile the schema.
224
206
  */
225
- var sanitizeSchemaForAjv = function (schema) {
226
- var e_1, _a;
207
+ const sanitizeSchemaForAjv = (schema) => {
227
208
  if (!schema || typeof schema !== "object") {
228
209
  return schema;
229
210
  }
230
- var result = __assign({}, schema);
211
+ const result = { ...schema };
231
212
  if (typeof result.type === "string" && !VALID_JSON_SCHEMA_TYPES.has(result.type)) {
232
- var mapped = MONGOOSE_TYPE_MAP[result.type];
213
+ const mapped = MONGOOSE_TYPE_MAP[result.type];
233
214
  if (mapped) {
234
215
  result.type = mapped.type;
235
216
  if (mapped.format && !result.format) {
@@ -244,53 +225,85 @@ var sanitizeSchemaForAjv = function (schema) {
244
225
  result.items = sanitizeSchemaForAjv(result.items);
245
226
  }
246
227
  if (result.properties && typeof result.properties === "object") {
247
- var sanitizedProps = {};
248
- try {
249
- for (var _b = __values(Object.entries(result.properties)), _c = _b.next(); !_c.done; _c = _b.next()) {
250
- var _d = __read(_c.value, 2), key = _d[0], value = _d[1];
251
- sanitizedProps[key] =
252
- typeof value === "object" && value !== null
253
- ? sanitizeSchemaForAjv(value)
254
- : value;
255
- }
256
- }
257
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
258
- finally {
259
- try {
260
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
261
- }
262
- finally { if (e_1) throw e_1.error; }
228
+ const sanitizedProps = {};
229
+ for (const [key, value] of Object.entries(result.properties)) {
230
+ sanitizedProps[key] =
231
+ typeof value === "object" && value !== null
232
+ ? sanitizeSchemaForAjv(value)
233
+ : value;
263
234
  }
264
235
  result.properties = sanitizedProps;
265
236
  }
266
237
  if (result.additionalProperties && typeof result.additionalProperties === "object") {
267
238
  result.additionalProperties = sanitizeSchemaForAjv(result.additionalProperties);
268
239
  }
240
+ if (Array.isArray(result.oneOf)) {
241
+ result.oneOf = result.oneOf.map((entry) => typeof entry === "object" && entry !== null
242
+ ? sanitizeSchemaForAjv(entry)
243
+ : entry);
244
+ }
245
+ if (typeof result.required === "boolean") {
246
+ delete result.required;
247
+ }
269
248
  return result;
270
249
  };
250
+ const stripBooleanRequiredFlag = (schema) => {
251
+ if (schema.required === true || schema.required === false) {
252
+ const { required: _, ...rest } = schema;
253
+ const cleaned = { ...rest };
254
+ if (cleaned.properties) {
255
+ cleaned.properties = Object.fromEntries(Object.entries(cleaned.properties).map(([key, value]) => [
256
+ key,
257
+ stripBooleanRequiredFlag(value),
258
+ ]));
259
+ }
260
+ if (cleaned.items) {
261
+ cleaned.items = stripBooleanRequiredFlag(cleaned.items);
262
+ }
263
+ if (cleaned.oneOf) {
264
+ cleaned.oneOf = cleaned.oneOf.map((entry) => stripBooleanRequiredFlag(entry));
265
+ }
266
+ return cleaned;
267
+ }
268
+ if (schema.properties) {
269
+ return {
270
+ ...schema,
271
+ properties: Object.fromEntries(Object.entries(schema.properties).map(([key, value]) => [
272
+ key,
273
+ stripBooleanRequiredFlag(value),
274
+ ])),
275
+ };
276
+ }
277
+ if (schema.items) {
278
+ return { ...schema, items: stripBooleanRequiredFlag(schema.items) };
279
+ }
280
+ if (schema.oneOf) {
281
+ return { ...schema, oneOf: schema.oneOf.map((entry) => stripBooleanRequiredFlag(entry)) };
282
+ }
283
+ return schema;
284
+ };
271
285
  /**
272
286
  * Get or create a compiled validator for a schema.
273
287
  * Uses the current config so changes take effect on next call.
274
288
  * Sanitizes non-standard mongoose-to-swagger types before compilation.
275
289
  * Returns null if the schema still cannot be compiled after sanitization.
276
290
  */
277
- var getValidator = function (schema) {
278
- var _a, _b;
279
- var ajv = getAjvInstance();
280
- var configKey = "coerce:".concat((_a = globalConfig.coerceTypes) !== null && _a !== void 0 ? _a : true, ",remove:").concat((_b = globalConfig.removeAdditional) !== null && _b !== void 0 ? _b : true);
281
- var hash = "".concat(configKey, ":").concat(hashSchema(schema));
282
- var cached = validatorCache.get(hash);
291
+ const getValidator = (schema) => {
292
+ const ajv = getAjvInstance();
293
+ const configKey = `coerce:${globalConfig.coerceTypes ?? true},remove:${globalConfig.removeAdditional ?? true}`;
294
+ const hash = `${configKey}:${hashSchema(schema)}`;
295
+ const cached = validatorCache.get(hash);
283
296
  if (cached !== undefined) {
284
297
  return cached;
285
298
  }
286
- var sanitized = sanitizeSchemaForAjv(schema);
299
+ const sanitized = sanitizeSchemaForAjv(schema);
287
300
  try {
288
- var validator = ajv.compile(sanitized);
301
+ const validator = ajv.compile(sanitized);
289
302
  validatorCache.set(hash, validator);
290
303
  return validator;
291
304
  }
292
305
  catch (err) {
293
- logger_1.logger.debug("Could not compile validation schema after sanitization: ".concat(err.message));
306
+ logger_1.logger.debug(`Could not compile validation schema after sanitization: ${err.message}`);
294
307
  validatorCache.set(hash, null);
295
308
  return null;
296
309
  }
@@ -298,12 +311,12 @@ var getValidator = function (schema) {
298
311
  /**
299
312
  * Format AJV errors into a human-readable string.
300
313
  */
301
- var formatValidationErrors = function (errors) {
314
+ const formatValidationErrors = (errors) => {
302
315
  return errors
303
- .map(function (err) {
304
- var path = err.instancePath || "/";
305
- var message = err.message || "validation failed";
306
- return "".concat(path, ": ").concat(message);
316
+ .map((err) => {
317
+ const path = err.instancePath || "/";
318
+ const message = err.message || "validation failed";
319
+ return `${path}: ${message}`;
307
320
  })
308
321
  .join("; ");
309
322
  };
@@ -312,36 +325,23 @@ var formatValidationErrors = function (errors) {
312
325
  * Strips `required` from individual properties (OpenAPI-style) and moves it
313
326
  * to the schema-level `required` array (JSON Schema-style) for AJV compatibility.
314
327
  */
315
- var propertiesToSchema = function (properties, requiredFields) {
316
- var e_2, _a;
317
- // Extract required fields from properties that have required: true
318
- var autoRequired = Object.entries(properties)
319
- .filter(function (_a) {
320
- var _b = __read(_a, 2), _ = _b[0], prop = _b[1];
321
- return prop.required;
322
- })
323
- .map(function (_a) {
324
- var _b = __read(_a, 1), key = _b[0];
325
- return key;
326
- });
327
- var allRequired = __spreadArray([], __read(new Set(__spreadArray(__spreadArray([], __read((requiredFields !== null && requiredFields !== void 0 ? requiredFields : [])), false), __read(autoRequired), false))), false);
328
- // Strip `required` from individual properties — AJV only accepts `required` at schema level
329
- var cleanedProperties = {};
330
- try {
331
- for (var _b = __values(Object.entries(properties)), _c = _b.next(); !_c.done; _c = _b.next()) {
332
- var _d = __read(_c.value, 2), key = _d[0], prop = _d[1];
333
- var _1 = prop.required, rest = __rest(prop, ["required"]);
334
- cleanedProperties[key] = rest;
335
- }
336
- }
337
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
338
- finally {
339
- try {
340
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
341
- }
342
- finally { if (e_2) throw e_2.error; }
328
+ const propertiesToSchema = (properties, requiredFields, options) => {
329
+ // Extract required fields from properties marked required: true (OpenAPI builder style).
330
+ // PATCH bodies are partial: omit mongoose/OpenAPI required so one field can be sent.
331
+ const autoRequired = options?.partial
332
+ ? []
333
+ : Object.entries(properties)
334
+ .filter(([_, prop]) => prop.required === true)
335
+ .map(([key]) => key);
336
+ const allRequired = options?.partial
337
+ ? []
338
+ : [...new Set([...(requiredFields ?? []), ...autoRequired])];
339
+ // Strip boolean `required` from individual properties — AJV only accepts `required` arrays on objects
340
+ const cleanedProperties = {};
341
+ for (const [key, prop] of Object.entries(properties)) {
342
+ cleanedProperties[key] = stripBooleanRequiredFlag(prop);
343
343
  }
344
- var schema = {
344
+ const schema = {
345
345
  properties: cleanedProperties,
346
346
  required: allRequired.length > 0 ? allRequired : undefined,
347
347
  type: "object",
@@ -363,40 +363,41 @@ var propertiesToSchema = function (properties, requiredFields) {
363
363
  * @param options - Optional configuration for this validator
364
364
  * @returns Express middleware function
365
365
  */
366
- var validateRequestBody = function (schema, options) {
367
- var fullSchema = propertiesToSchema(schema, options === null || options === void 0 ? void 0 : options.required);
368
- return function (req, _res, next) {
369
- var _a, _b, _c;
366
+ const validateRequestBody = (schema, options) => {
367
+ const fullSchema = propertiesToSchema(schema, options?.required, {
368
+ partial: options?.partial,
369
+ });
370
+ return (req, _res, next) => {
370
371
  // No-op if not configured
371
372
  if (!isConfigured) {
372
373
  next();
373
374
  return;
374
375
  }
375
376
  // Check if validation is enabled (route override takes precedence)
376
- var isEnabled = (_a = options === null || options === void 0 ? void 0 : options.enabled) !== null && _a !== void 0 ? _a : globalConfig.validateRequests;
377
+ const isEnabled = options?.enabled ?? globalConfig.validateRequests;
377
378
  if (!isEnabled) {
378
379
  next();
379
380
  return;
380
381
  }
381
382
  // Capture keys before validation for removeAdditional detection
382
- var keysBefore = req.body && typeof req.body === "object" ? Object.keys(req.body) : [];
383
+ const keysBefore = req.body && typeof req.body === "object" ? Object.keys(req.body) : [];
383
384
  // Get validator at request time so config changes take effect
384
- var validator = getValidator(fullSchema);
385
+ const validator = getValidator(fullSchema);
385
386
  // If schema couldn't be compiled (e.g., non-standard types), skip validation
386
387
  if (!validator) {
387
388
  next();
388
389
  return;
389
390
  }
390
391
  // Clone body if we might modify it (coercion or removeAdditional)
391
- var bodyToValidate = __assign({}, req.body);
392
- var valid = validator(bodyToValidate);
392
+ const bodyToValidate = { ...req.body };
393
+ const valid = validator(bodyToValidate);
393
394
  if (!valid && validator.errors) {
394
- var errors = validator.errors;
395
+ const errors = validator.errors;
395
396
  if (globalConfig.logValidationErrors) {
396
- logger_1.logger.warn("Request body validation failed for ".concat(req.method, " ").concat(req.path, ": ").concat(formatValidationErrors(errors)));
397
+ logger_1.logger.warn(`Request body validation failed for ${req.method} ${req.path}: ${formatValidationErrors(errors)}`);
397
398
  }
398
399
  // Use custom error handler if provided
399
- var errorHandler = (_b = options === null || options === void 0 ? void 0 : options.onError) !== null && _b !== void 0 ? _b : globalConfig.onValidationError;
400
+ const errorHandler = options?.onError ?? globalConfig.onValidationError;
400
401
  if (errorHandler) {
401
402
  errorHandler(errors, req);
402
403
  next();
@@ -407,11 +408,11 @@ var validateRequestBody = function (schema, options) {
407
408
  detail: formatValidationErrors(errors),
408
409
  disableExternalErrorTracking: true,
409
410
  meta: {
410
- validationErrors: JSON.stringify(errors.map(function (e) { return ({
411
+ validationErrors: JSON.stringify(errors.map((e) => ({
411
412
  message: e.message,
412
413
  params: e.params,
413
414
  path: e.instancePath,
414
- }); })),
415
+ }))),
415
416
  },
416
417
  source: {
417
418
  pointer: "/body",
@@ -424,15 +425,15 @@ var validateRequestBody = function (schema, options) {
424
425
  if (valid) {
425
426
  // Detect removed properties (top-level only)
426
427
  if (globalConfig.removeAdditional) {
427
- var keysAfter_1 = Object.keys(bodyToValidate);
428
- var removedProperties = keysBefore.filter(function (k) { return !keysAfter_1.includes(k); });
428
+ const keysAfter = Object.keys(bodyToValidate);
429
+ const removedProperties = keysBefore.filter((k) => !keysAfter.includes(k));
429
430
  if (removedProperties.length > 0) {
430
- var hook = (_c = options === null || options === void 0 ? void 0 : options.onAdditionalPropertiesRemoved) !== null && _c !== void 0 ? _c : globalConfig.onAdditionalPropertiesRemoved;
431
+ const hook = options?.onAdditionalPropertiesRemoved ?? globalConfig.onAdditionalPropertiesRemoved;
431
432
  if (hook) {
432
433
  hook(removedProperties, req);
433
434
  }
434
435
  if (globalConfig.logValidationErrors) {
435
- logger_1.logger.debug("Stripped additional properties from ".concat(req.method, " ").concat(req.path, ": ").concat(removedProperties.join(", ")));
436
+ logger_1.logger.debug(`Stripped additional properties from ${req.method} ${req.path}: ${removedProperties.join(", ")}`);
436
437
  }
437
438
  }
438
439
  }
@@ -449,35 +450,34 @@ exports.validateRequestBody = validateRequestBody;
449
450
  * @param options - Optional configuration for this validator
450
451
  * @returns Express middleware function
451
452
  */
452
- var validateQueryParams = function (schema, options) {
453
- var fullSchema = propertiesToSchema(schema);
454
- return function (req, _res, next) {
455
- var _a, _b, _c, _d;
453
+ const validateQueryParams = (schema, options) => {
454
+ const fullSchema = propertiesToSchema(schema);
455
+ return (req, _res, next) => {
456
456
  // No-op if not configured
457
457
  if (!isConfigured) {
458
458
  next();
459
459
  return;
460
460
  }
461
- var isEnabled = (_a = options === null || options === void 0 ? void 0 : options.enabled) !== null && _a !== void 0 ? _a : globalConfig.validateRequests;
461
+ const isEnabled = options?.enabled ?? globalConfig.validateRequests;
462
462
  if (!isEnabled) {
463
463
  next();
464
464
  return;
465
465
  }
466
466
  // Get validator at request time
467
- var validator = getValidator(fullSchema);
467
+ const validator = getValidator(fullSchema);
468
468
  // If schema couldn't be compiled, skip validation
469
469
  if (!validator) {
470
470
  next();
471
471
  return;
472
472
  }
473
- var queryToValidate = globalConfig.coerceTypes ? __assign({}, req.query) : req.query;
474
- var valid = validator(queryToValidate);
473
+ const queryToValidate = globalConfig.coerceTypes ? { ...req.query } : req.query;
474
+ const valid = validator(queryToValidate);
475
475
  if (!valid && validator.errors) {
476
- var errors = validator.errors;
476
+ const errors = validator.errors;
477
477
  if (globalConfig.logValidationErrors) {
478
- logger_1.logger.warn("Query parameter validation failed for ".concat(req.method, " ").concat(req.path, ": ").concat(formatValidationErrors(errors)));
478
+ logger_1.logger.warn(`Query parameter validation failed for ${req.method} ${req.path}: ${formatValidationErrors(errors)}`);
479
479
  }
480
- var errorHandler = (_b = options === null || options === void 0 ? void 0 : options.onError) !== null && _b !== void 0 ? _b : globalConfig.onValidationError;
480
+ const errorHandler = options?.onError ?? globalConfig.onValidationError;
481
481
  if (errorHandler) {
482
482
  errorHandler(errors, req);
483
483
  next();
@@ -487,14 +487,14 @@ var validateQueryParams = function (schema, options) {
487
487
  detail: formatValidationErrors(errors),
488
488
  disableExternalErrorTracking: true,
489
489
  meta: {
490
- validationErrors: JSON.stringify(errors.map(function (e) { return ({
490
+ validationErrors: JSON.stringify(errors.map((e) => ({
491
491
  message: e.message,
492
492
  params: e.params,
493
493
  path: e.instancePath,
494
- }); })),
494
+ }))),
495
495
  },
496
496
  source: {
497
- parameter: ((_d = (_c = errors[0]) === null || _c === void 0 ? void 0 : _c.instancePath) === null || _d === void 0 ? void 0 : _d.replace("/", "")) || "unknown",
497
+ parameter: errors[0]?.instancePath?.replace("/", "") || "unknown",
498
498
  },
499
499
  status: 400,
500
500
  title: "Query parameter validation failed",
@@ -526,17 +526,17 @@ exports.validateQueryParams = validateQueryParams;
526
526
  * ], handler);
527
527
  * ```
528
528
  */
529
- var createValidator = function (options) {
530
- var bodyValidator = options.body
529
+ const createValidator = (options) => {
530
+ const bodyValidator = options.body
531
531
  ? (0, exports.validateRequestBody)(options.body, { enabled: options.enabled })
532
532
  : null;
533
- var queryValidator = options.query
533
+ const queryValidator = options.query
534
534
  ? (0, exports.validateQueryParams)(options.query, { enabled: options.enabled })
535
535
  : null;
536
- return function (req, res, next) {
536
+ return (req, res, next) => {
537
537
  // Run body validation first
538
538
  if (bodyValidator) {
539
- bodyValidator(req, res, (function (err) {
539
+ bodyValidator(req, res, ((err) => {
540
540
  if (err) {
541
541
  next(err);
542
542
  return;
@@ -567,28 +567,25 @@ exports.createValidator = createValidator;
567
567
  * @param schema - The expected schema
568
568
  * @returns Object with valid flag and any errors
569
569
  */
570
- var validateResponseData = function (data, schema) {
570
+ const validateResponseData = (data, schema) => {
571
571
  if (!globalConfig.validateResponses) {
572
572
  return { valid: true };
573
573
  }
574
- var fullSchema = propertiesToSchema(schema);
575
- var validator = getValidator(fullSchema);
574
+ const fullSchema = propertiesToSchema(schema);
575
+ const validator = getValidator(fullSchema);
576
576
  if (!validator) {
577
577
  return { valid: true };
578
578
  }
579
- var valid = validator(data);
579
+ const valid = validator(data);
580
580
  if (!valid && validator.errors) {
581
581
  if (globalConfig.logValidationErrors) {
582
- logger_1.logger.warn("Response validation failed: ".concat(formatValidationErrors(validator.errors)));
582
+ logger_1.logger.warn(`Response validation failed: ${formatValidationErrors(validator.errors)}`);
583
583
  }
584
584
  return { errors: validator.errors, valid: false };
585
585
  }
586
586
  return { valid: true };
587
587
  };
588
588
  exports.validateResponseData = validateResponseData;
589
- var m2sOptions = {
590
- props: ["readOnly", "required", "enum", "default"],
591
- };
592
589
  /**
593
590
  * Extract an OpenAPI-compatible schema from a Mongoose model.
594
591
  * This allows you to use the same schema definitions for both documentation
@@ -597,19 +594,17 @@ var m2sOptions = {
597
594
  * @param model - A Mongoose model
598
595
  * @returns Schema properties suitable for validation
599
596
  */
600
- var getSchemaFromModel = function (model) {
601
- var modelSwagger = (0, mongoose_to_swagger_1.default)(model, m2sOptions);
602
- (0, populate_1.fixMixedFields)(model.schema, modelSwagger.properties);
603
- return modelSwagger.properties;
597
+ const getSchemaFromModel = (model) => {
598
+ const { properties } = (0, populate_1.getOpenApiSpecForModel)(model);
599
+ return properties;
604
600
  };
605
601
  exports.getSchemaFromModel = getSchemaFromModel;
606
602
  /**
607
603
  * Extract required field names from a Mongoose model's swagger schema.
608
604
  */
609
- var getRequiredFieldsFromModel = function (model) {
610
- var _a;
611
- var modelSwagger = (0, mongoose_to_swagger_1.default)(model, m2sOptions);
612
- return (_a = modelSwagger.required) !== null && _a !== void 0 ? _a : [];
605
+ const getRequiredFieldsFromModel = (model) => {
606
+ const { required } = (0, populate_1.getOpenApiSpecForModel)(model);
607
+ return required;
613
608
  };
614
609
  /**
615
610
  * Creates a request body validator middleware from a Mongoose model.
@@ -619,19 +614,18 @@ var getRequiredFieldsFromModel = function (model) {
619
614
  * @param options - Optional configuration for the validator
620
615
  * @returns Express middleware function
621
616
  */
622
- var validateModelRequestBody = function (model, options) {
623
- var _a, _b;
624
- var schema = (0, exports.getSchemaFromModel)(model);
625
- var requiredFields = getRequiredFieldsFromModel(model);
626
- if ((_a = options === null || options === void 0 ? void 0 : options.excludeFields) === null || _a === void 0 ? void 0 : _a.length) {
627
- var excluded_1 = new Set(options.excludeFields);
628
- schema = Object.fromEntries(Object.entries(schema).filter(function (_a) {
629
- var _b = __read(_a, 1), key = _b[0];
630
- return !excluded_1.has(key);
631
- }));
632
- requiredFields = requiredFields.filter(function (f) { return !excluded_1.has(f); });
617
+ const validateModelRequestBody = (model, options) => {
618
+ let schema = (0, exports.getSchemaFromModel)(model);
619
+ let requiredFields = options?.partial ? [] : getRequiredFieldsFromModel(model);
620
+ if (options?.excludeFields?.length) {
621
+ const excluded = new Set(options.excludeFields);
622
+ schema = Object.fromEntries(Object.entries(schema).filter(([key]) => !excluded.has(key)));
623
+ requiredFields = requiredFields.filter((f) => !excluded.has(f));
633
624
  }
634
- return (0, exports.validateRequestBody)(schema, __assign(__assign({}, options), { required: __spreadArray(__spreadArray([], __read(((_b = options === null || options === void 0 ? void 0 : options.required) !== null && _b !== void 0 ? _b : [])), false), __read(requiredFields), false) }));
625
+ return (0, exports.validateRequestBody)(schema, {
626
+ ...options,
627
+ required: options?.partial ? [] : [...(options?.required ?? []), ...requiredFields],
628
+ });
635
629
  };
636
630
  exports.validateModelRequestBody = validateModelRequestBody;
637
631
  /**
@@ -642,22 +636,90 @@ exports.validateModelRequestBody = validateModelRequestBody;
642
636
  * @param options - Configuration options
643
637
  * @returns Object with create and update validation middleware
644
638
  */
645
- var createModelValidators = function (model, options) {
646
- var schema = (0, exports.getSchemaFromModel)(model);
639
+ const createModelValidators = (model, options) => {
640
+ const schema = (0, exports.getSchemaFromModel)(model);
647
641
  return {
648
642
  create: (0, exports.validateRequestBody)(schema, {
649
- enabled: options === null || options === void 0 ? void 0 : options.validateCreate,
650
- onAdditionalPropertiesRemoved: options === null || options === void 0 ? void 0 : options.onAdditionalPropertiesRemoved,
651
- onError: options === null || options === void 0 ? void 0 : options.onError,
643
+ enabled: options?.validateCreate,
644
+ onAdditionalPropertiesRemoved: options?.onAdditionalPropertiesRemoved,
645
+ onError: options?.onError,
652
646
  }),
653
647
  update: (0, exports.validateRequestBody)(schema, {
654
- enabled: options === null || options === void 0 ? void 0 : options.validateUpdate,
655
- onAdditionalPropertiesRemoved: options === null || options === void 0 ? void 0 : options.onAdditionalPropertiesRemoved,
656
- onError: options === null || options === void 0 ? void 0 : options.onError,
648
+ enabled: options?.validateUpdate,
649
+ onAdditionalPropertiesRemoved: options?.onAdditionalPropertiesRemoved,
650
+ onError: options?.onError,
651
+ partial: true,
657
652
  }),
658
653
  };
659
654
  };
660
655
  exports.createModelValidators = createModelValidators;
656
+ const choiceEmptyInItemSchema = (baseItem) => {
657
+ if (baseItem.enum) {
658
+ return {
659
+ oneOf: [
660
+ { enum: baseItem.enum, type: "string" },
661
+ { enum: [adminTypes_1.ADMIN_LIST_CHOICE_EMPTY_VALUE], type: "string" },
662
+ ],
663
+ };
664
+ }
665
+ return {
666
+ oneOf: [
667
+ stripBooleanRequiredFlag(baseItem),
668
+ { enum: [adminTypes_1.ADMIN_LIST_CHOICE_EMPTY_VALUE], type: "string" },
669
+ ],
670
+ };
671
+ };
672
+ const buildInOperatorSchema = (itemSchema) => ({
673
+ additionalProperties: false,
674
+ properties: {
675
+ $in: {
676
+ items: itemSchema,
677
+ minItems: 1,
678
+ type: "array",
679
+ },
680
+ },
681
+ required: ["$in"],
682
+ type: "object",
683
+ });
684
+ const buildRegexOperatorSchema = () => ({
685
+ additionalProperties: false,
686
+ properties: {
687
+ $options: { enum: ["i"], type: "string" },
688
+ $regex: { escapedRegexLiteral: true, type: "string" },
689
+ },
690
+ required: ["$regex", "$options"],
691
+ type: "object",
692
+ });
693
+ const buildRangeOperatorSchema = (valueSchema) => ({
694
+ additionalProperties: false,
695
+ properties: {
696
+ $gt: valueSchema,
697
+ $gte: valueSchema,
698
+ $lt: valueSchema,
699
+ $lte: valueSchema,
700
+ },
701
+ type: "object",
702
+ });
703
+ /** Query schema for string/enum fields: scalar, `$in`, or escaped `$regex`. */
704
+ const buildStringListQueryFieldSchema = (fieldSchema) => {
705
+ const scalar = stripBooleanRequiredFlag(fieldSchema);
706
+ const inItems = fieldSchema.enum
707
+ ? choiceEmptyInItemSchema(fieldSchema)
708
+ : stripBooleanRequiredFlag(fieldSchema);
709
+ return {
710
+ oneOf: [scalar, buildInOperatorSchema(inItems), buildRegexOperatorSchema()],
711
+ };
712
+ };
713
+ exports.buildStringListQueryFieldSchema = buildStringListQueryFieldSchema;
714
+ /** Query schema for number/date fields: scalar or comparison operators. */
715
+ const buildNumericListQueryFieldSchema = (fieldSchema) => {
716
+ const scalar = stripBooleanRequiredFlag(fieldSchema);
717
+ const valueSchema = stripBooleanRequiredFlag(fieldSchema);
718
+ return {
719
+ oneOf: [scalar, buildRangeOperatorSchema(valueSchema)],
720
+ };
721
+ };
722
+ exports.buildNumericListQueryFieldSchema = buildNumericListQueryFieldSchema;
661
723
  /**
662
724
  * Build a query parameter schema from a model's Mongoose schema and queryFields array.
663
725
  * Always includes pagination parameters (limit, page, sort).
@@ -666,35 +728,28 @@ exports.createModelValidators = createModelValidators;
666
728
  * @param queryFields - Array of field names allowed for querying
667
729
  * @returns Schema properties suitable for query validation
668
730
  */
669
- var buildQuerySchemaFromFields = function (model, queryFields) {
670
- var e_3, _a;
671
- if (queryFields === void 0) { queryFields = []; }
672
- var modelSchema = (0, exports.getSchemaFromModel)(model);
673
- var querySchema = {
731
+ const buildQuerySchemaFromFields = (model, queryFields = []) => {
732
+ const modelSchema = (0, exports.getSchemaFromModel)(model);
733
+ const querySchema = {
674
734
  limit: { type: "number" },
675
735
  page: { type: "number" },
676
736
  sort: { type: "string" },
677
737
  };
678
- try {
679
- for (var queryFields_1 = __values(queryFields), queryFields_1_1 = queryFields_1.next(); !queryFields_1_1.done; queryFields_1_1 = queryFields_1.next()) {
680
- var field = queryFields_1_1.value;
681
- var modelField = modelSchema[field];
682
- if (modelField) {
683
- // Use the model's type info, but mark as not required for queries
684
- querySchema[field] = __assign(__assign({}, modelField), { required: false });
685
- }
686
- else {
687
- // Field not in model schema — allow as string
688
- querySchema[field] = { type: "string" };
689
- }
738
+ for (const field of queryFields) {
739
+ const modelField = modelSchema[field];
740
+ if (!modelField) {
741
+ querySchema[field] = (0, exports.buildStringListQueryFieldSchema)({ type: "string" });
742
+ continue;
690
743
  }
691
- }
692
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
693
- finally {
694
- try {
695
- if (queryFields_1_1 && !queryFields_1_1.done && (_a = queryFields_1.return)) _a.call(queryFields_1);
744
+ if (modelField.type === "boolean") {
745
+ querySchema[field] = stripBooleanRequiredFlag(modelField);
746
+ continue;
747
+ }
748
+ if (modelField.type === "number" || modelField.format === "date-time") {
749
+ querySchema[field] = (0, exports.buildNumericListQueryFieldSchema)(modelField);
750
+ continue;
696
751
  }
697
- finally { if (e_3) throw e_3.error; }
752
+ querySchema[field] = (0, exports.buildStringListQueryFieldSchema)(modelField);
698
753
  }
699
754
  return querySchema;
700
755
  };