@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
@@ -1,100 +1,28 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __read = (this && this.__read) || function (o, n) {
50
- var m = typeof Symbol === "function" && o[Symbol.iterator];
51
- if (!m) return o;
52
- var i = m.call(o), r, ar = [], e;
53
- try {
54
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
- }
56
- catch (error) { e = { error: error }; }
57
- finally {
58
- try {
59
- if (r && !r.done && (m = i["return"])) m.call(i);
60
- }
61
- finally { if (e) throw e.error; }
62
- }
63
- return ar;
64
- };
65
- var __values = (this && this.__values) || function(o) {
66
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
67
- if (m) return m.call(o);
68
- if (o && typeof o.length === "number") return {
69
- next: function () {
70
- if (o && i >= o.length) o = void 0;
71
- return { value: o && o[i++], done: !o };
72
- }
73
- };
74
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
75
- };
76
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
77
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
78
4
  };
79
5
  Object.defineProperty(exports, "__esModule", { value: true });
80
6
  exports.applySyncMutationBatch = exports.validateSyncMutationBatch = exports.applySyncMutation = exports.docMatchesMutationData = exports.MAX_SYNC_MUTATIONS_PER_BATCH = void 0;
81
- var luxon_1 = require("luxon");
82
- var mongoose_1 = __importDefault(require("mongoose"));
83
- var errors_1 = require("../errors");
84
- var logger_1 = require("../logger");
85
- var plugins_1 = require("../plugins");
86
- var executors_1 = require("./executors");
87
- var models_1 = require("./models");
88
- var registry_1 = require("./registry");
89
- var routes_1 = require("./routes");
90
- var streams_1 = require("./streams");
7
+ const luxon_1 = require("luxon");
8
+ const mongoose_1 = __importDefault(require("mongoose"));
9
+ const errors_1 = require("../errors");
10
+ const logger_1 = require("../logger");
11
+ const orgContext_1 = require("../orgs/orgContext");
12
+ const plugins_1 = require("../plugins");
13
+ const adminWindowMutation_1 = require("./adminWindowMutation");
14
+ const executors_1 = require("./executors");
15
+ const models_1 = require("./models");
16
+ const registry_1 = require("./registry");
17
+ const routes_1 = require("./routes");
18
+ const streams_1 = require("./streams");
91
19
  /**
92
20
  * Per-mutation success traces (`Mutation applied`) are high-volume. Gate them behind
93
21
  * `SYNC_DEBUG=true` so they stay silent by default even when Winston's console level is
94
22
  * `debug`.
95
23
  */
96
- var syncDebugLog = (0, logger_1.createFeatureFlaggedLogger)({
97
- isEnabled: function () { return process.env.SYNC_DEBUG === "true"; },
24
+ const syncDebugLog = (0, logger_1.createFeatureFlaggedLogger)({
25
+ isEnabled: () => process.env.SYNC_DEBUG === "true",
98
26
  });
99
27
  /**
100
28
  * C6 (M6): enforce write scope at the sync boundary regardless of consumer `preCreate`
@@ -103,74 +31,64 @@ var syncDebugLog = (0, logger_1.createFeatureFlaggedLogger)({
103
31
  * memberships. Throws a 403 APIError (mapped to `unauthorized`) otherwise. A no-op for
104
32
  * broadcast/custom scopes and for update data that does not touch the scope field.
105
33
  */
106
- var enforceWriteScope = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
107
- var scope, field, incoming, memberships;
108
- var entry = _b.entry, user = _b.user, operation = _b.operation, data = _b.data, scopeResolver = _b.scopeResolver;
109
- return __generator(this, function (_c) {
110
- switch (_c.label) {
111
- case 0:
112
- if (operation === "delete") {
113
- return [2 /*return*/];
114
- }
115
- scope = entry.config.scope;
116
- if (typeof scope === "function" || scope.type === "broadcast") {
117
- return [2 /*return*/];
118
- }
119
- field = (0, streams_1.getScopeField)(scope);
120
- incoming = data === null || data === void 0 ? void 0 : data[field];
121
- if (scope.type === "owner") {
122
- // Create must belong to the caller; an update may not move ownership to someone else.
123
- if (operation === "create" && (incoming === undefined || incoming === null)) {
124
- // preCreate typically injects ownerId; nothing to verify if absent here.
125
- return [2 /*return*/];
126
- }
127
- if (incoming !== undefined && incoming !== null && String(incoming) !== String(user.id)) {
128
- throw new errors_1.APIError({
129
- status: 403,
130
- title: "Write scope violation on ".concat(entry.collectionTag, ": ").concat(field, " must be the caller"),
131
- });
132
- }
133
- return [2 /*return*/];
134
- }
135
- // Tenant: the incoming value (create) or the changed value (update) must be a membership.
136
- if (incoming === undefined || incoming === null) {
137
- // Nothing to check against memberships yet. A create may legitimately omit the tenant
138
- // field for `preCreate` to inject from the authenticated user (see the example
139
- // projects router), and an update that does not touch the scope field leaves it
140
- // alone. Task 9.21's "never file a document under `tenant:undefined`" guarantee is
141
- // enforced by resolveStreamForDoc on the write path instead, which sees the value
142
- // AFTER preCreate has run — inferring intent from the mere presence of a preCreate
143
- // hook would let an unrelated one (logging, timestamps) silently reopen that hole.
144
- return [2 /*return*/];
145
- }
146
- if (!scopeResolver) {
147
- throw new errors_1.APIError({
148
- status: 500,
149
- title: "Sync collection ".concat(entry.collectionTag, " is tenant-scoped but SyncApp has no getUserScopes resolver"),
150
- });
151
- }
152
- return [4 /*yield*/, scopeResolver(user, entry)];
153
- case 1:
154
- memberships = _c.sent();
155
- if (!memberships.map(String).includes(String(incoming))) {
156
- throw new errors_1.APIError({
157
- status: 403,
158
- title: "Write scope violation on ".concat(entry.collectionTag, ": ").concat(field, " ").concat(String(incoming), " is not a membership"),
159
- });
160
- }
161
- return [2 /*return*/];
34
+ const enforceWriteScope = async ({ entry, user, operation, data, scopeResolver, }) => {
35
+ if (operation === "delete") {
36
+ return;
37
+ }
38
+ const { scope } = entry.config;
39
+ if (typeof scope === "function" || scope.type === "broadcast") {
40
+ return;
41
+ }
42
+ const field = (0, streams_1.getScopeField)(scope);
43
+ const incoming = data?.[field];
44
+ if (scope.type === "owner") {
45
+ // Create must belong to the caller; an update may not move ownership to someone else.
46
+ if (operation === "create" && (incoming === undefined || incoming === null)) {
47
+ // preCreate typically injects ownerId; nothing to verify if absent here.
48
+ return;
162
49
  }
163
- });
164
- }); };
165
- var PENDING_POLL_ATTEMPTS = 10;
166
- var PENDING_POLL_INTERVAL_MS = 100;
167
- var VALID_OPERATIONS = new Set(["create", "update", "delete"]);
50
+ if (incoming !== undefined && incoming !== null && String(incoming) !== String(user.id)) {
51
+ throw new errors_1.APIError({
52
+ status: 403,
53
+ title: `Write scope violation on ${entry.collectionTag}: ${field} must be the caller`,
54
+ });
55
+ }
56
+ return;
57
+ }
58
+ // Tenant: the incoming value (create) or the changed value (update) must be a membership.
59
+ if (incoming === undefined || incoming === null) {
60
+ // Nothing to check against memberships yet. A create may legitimately omit the tenant
61
+ // field for `preCreate` to inject from the authenticated user (see the example
62
+ // projects router), and an update that does not touch the scope field leaves it
63
+ // alone. Task 9.21's "never file a document under `tenant:undefined`" guarantee is
64
+ // enforced by resolveStreamForDoc on the write path instead, which sees the value
65
+ // AFTER preCreate has run — inferring intent from the mere presence of a preCreate
66
+ // hook would let an unrelated one (logging, timestamps) silently reopen that hole.
67
+ return;
68
+ }
69
+ if (!scopeResolver) {
70
+ throw new errors_1.APIError({
71
+ status: 500,
72
+ title: `Sync collection ${entry.collectionTag} is tenant-scoped but SyncApp has no getUserScopes resolver`,
73
+ });
74
+ }
75
+ const memberships = await scopeResolver(user, entry);
76
+ if (!memberships.map(String).includes(String(incoming))) {
77
+ throw new errors_1.APIError({
78
+ status: 403,
79
+ title: `Write scope violation on ${entry.collectionTag}: ${field} ${String(incoming)} is not a membership`,
80
+ });
81
+ }
82
+ };
83
+ const PENDING_POLL_ATTEMPTS = 10;
84
+ const PENDING_POLL_INTERVAL_MS = 100;
85
+ const VALID_OPERATIONS = new Set(["create", "update", "delete"]);
168
86
  /** Maximum mutations accepted in a single `sync:mutateBatch` / `POST /sync/mutate/batch` request. */
169
87
  exports.MAX_SYNC_MUTATIONS_PER_BATCH = 100;
170
- var sleep = function (ms) { return new Promise(function (resolve) { return setTimeout(resolve, ms); }); };
171
- var makeNack = function (nack) {
88
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
89
+ const makeNack = (nack) => {
172
90
  logger_1.logger.info("[sync] Mutation nacked", { code: nack.code, mutationId: nack.mutationId });
173
- return { nack: nack, type: "nack" };
91
+ return { nack, type: "nack" };
174
92
  };
175
93
  /**
176
94
  * Load a document by id INCLUDING tombstones (`isDeletedPlugin` would otherwise filter a
@@ -178,40 +96,28 @@ var makeNack = function (nack) {
178
96
  * document is gone, the id does not cast, or the consumer's serializer throws — callers
179
97
  * treat a missing `serverDoc` as "seq only", which is what the client needs to re-base.
180
98
  */
181
- var serializeLiveDoc = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
182
- var model, found, doc, error_1;
183
- var entry = _b.entry, id = _b.id, request = _b.request;
184
- return __generator(this, function (_c) {
185
- switch (_c.label) {
186
- case 0:
187
- if (!id) {
188
- return [2 /*return*/, undefined];
189
- }
190
- _c.label = 1;
191
- case 1:
192
- _c.trys.push([1, 4, , 5]);
193
- model = mongoose_1.default.model(entry.modelName);
194
- return [4 /*yield*/, model.find({ _id: id, deleted: { $in: [true, false] } }).limit(1)];
195
- case 2:
196
- found = _c.sent();
197
- doc = found[0];
198
- if (!doc) {
199
- return [2 /*return*/, undefined];
200
- }
201
- return [4 /*yield*/, (0, routes_1.serializeSyncDoc)({ doc: doc, entry: entry, req: request })];
202
- case 3: return [2 /*return*/, _c.sent()];
203
- case 4:
204
- error_1 = _c.sent();
205
- logger_1.logger.warn("[sync] Failed to serialize the server doc for a recorded conflict", {
206
- collection: entry.collectionTag,
207
- error: String(error_1),
208
- id: id,
209
- });
210
- return [2 /*return*/, undefined];
211
- case 5: return [2 /*return*/];
99
+ const serializeLiveDoc = async ({ entry, id, request, }) => {
100
+ if (!id) {
101
+ return undefined;
102
+ }
103
+ try {
104
+ const model = mongoose_1.default.model(entry.modelName);
105
+ const found = await model.find({ _id: id, deleted: { $in: [true, false] } }).limit(1);
106
+ const doc = found[0];
107
+ if (!doc) {
108
+ return undefined;
212
109
  }
213
- });
214
- }); };
110
+ return await (0, routes_1.serializeSyncDoc)({ doc, entry, req: request });
111
+ }
112
+ catch (error) {
113
+ logger_1.logger.warn("[sync] Failed to serialize the server doc for a recorded conflict", {
114
+ collection: entry.collectionTag,
115
+ error: String(error),
116
+ id,
117
+ });
118
+ return undefined;
119
+ }
120
+ };
215
121
  /**
216
122
  * Reconstruct the outcome recorded on a finalized ledger row; undefined while pending.
217
123
  *
@@ -220,43 +126,31 @@ var serializeLiveDoc = function (_a) { return __awaiter(void 0, [_a], void 0, fu
220
126
  * `syncmutations` for the ledger's 30-day TTL, this hands the client current server
221
127
  * state rather than a snapshot frozen at first-conflict time.
222
128
  */
223
- var outcomeFromLedgerRow = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
224
- var _c;
225
- var _d;
226
- var _e, _f, _g;
227
- var entry = _b.entry, request = _b.request, row = _b.row;
228
- return __generator(this, function (_h) {
229
- switch (_h.label) {
230
- case 0:
231
- if (row.status === "applied") {
232
- return [2 /*return*/, {
233
- ack: { id: (_e = row.resultId) !== null && _e !== void 0 ? _e : "", mutationId: row.mutationId, seq: (_f = row.resultSeq) !== null && _f !== void 0 ? _f : 0 },
234
- type: "ack",
235
- }];
236
- }
237
- if (!(row.status === "conflicted")) return [3 /*break*/, 2];
238
- _c = makeNack;
239
- _d = {
240
- code: "conflict",
241
- message: row.error,
242
- mutationId: row.mutationId
243
- };
244
- return [4 /*yield*/, serializeLiveDoc({ entry: entry, id: row.resultId, request: request })];
245
- case 1: return [2 /*return*/, _c.apply(void 0, [(_d.serverDoc = _h.sent(),
246
- _d.serverSeq = row.resultSeq,
247
- _d)])];
248
- case 2:
249
- if (row.status === "failed") {
250
- return [2 /*return*/, makeNack({
251
- code: (_g = row.nackCode) !== null && _g !== void 0 ? _g : "error",
252
- message: row.error,
253
- mutationId: row.mutationId,
254
- })];
255
- }
256
- return [2 /*return*/, undefined];
257
- }
258
- });
259
- }); };
129
+ const outcomeFromLedgerRow = async ({ entry, request, row, }) => {
130
+ if (row.status === "applied") {
131
+ return {
132
+ ack: { id: row.resultId ?? "", mutationId: row.mutationId, seq: row.resultSeq ?? 0 },
133
+ type: "ack",
134
+ };
135
+ }
136
+ if (row.status === "conflicted") {
137
+ return makeNack({
138
+ code: "conflict",
139
+ message: row.error,
140
+ mutationId: row.mutationId,
141
+ serverDoc: await serializeLiveDoc({ entry, id: row.resultId, request }),
142
+ serverSeq: row.resultSeq,
143
+ });
144
+ }
145
+ if (row.status === "failed") {
146
+ return makeNack({
147
+ code: row.nackCode ?? "error",
148
+ message: row.error,
149
+ mutationId: row.mutationId,
150
+ });
151
+ }
152
+ return undefined;
153
+ };
260
154
  /**
261
155
  * C5 (FIX 6) lease takeover: a `pending` row older than {@link SYNC_MUTATION_LEASE_MS}
262
156
  * is assumed abandoned (the original claimant crashed between claiming the row and
@@ -265,19 +159,11 @@ var outcomeFromLedgerRow = function (_a) { return __awaiter(void 0, [_a], void 0
265
159
  * `claimedAt`) on success, or `undefined` if the row is not stale/pending (someone else
266
160
  * is actively working it, or it already finalized).
267
161
  */
268
- var takeoverStaleLease = function (mutationId) { return __awaiter(void 0, void 0, void 0, function () {
269
- var cutoff, claimed;
270
- return __generator(this, function (_a) {
271
- switch (_a.label) {
272
- case 0:
273
- cutoff = luxon_1.DateTime.now().minus({ milliseconds: models_1.SYNC_MUTATION_LEASE_MS }).toJSDate();
274
- return [4 /*yield*/, models_1.SyncMutation.findOneAndUpdate({ claimedAt: { $lt: cutoff }, mutationId: mutationId, status: "pending" }, { $set: { claimedAt: luxon_1.DateTime.now().toJSDate() } }, { new: true })];
275
- case 1:
276
- claimed = _a.sent();
277
- return [2 /*return*/, claimed !== null && claimed !== void 0 ? claimed : undefined];
278
- }
279
- });
280
- }); };
162
+ const takeoverStaleLease = async (mutationId) => {
163
+ const cutoff = luxon_1.DateTime.now().minus({ milliseconds: models_1.SYNC_MUTATION_LEASE_MS }).toJSDate();
164
+ const claimed = await models_1.SyncMutation.findOneAndUpdate({ claimedAt: { $lt: cutoff }, mutationId, status: "pending" }, { $set: { claimedAt: luxon_1.DateTime.now().toJSDate() } }, { new: true });
165
+ return claimed ?? undefined;
166
+ };
281
167
  /**
282
168
  * Another delivery claimed this mutationId: poll the ledger row until its status leaves
283
169
  * `pending` and return the recorded outcome. Before each poll, attempt a lease takeover
@@ -287,73 +173,53 @@ var takeoverStaleLease = function (mutationId) { return __awaiter(void 0, void 0
287
173
  * pending and un-stale past the timeout, nack `error` without modifying the row — the
288
174
  * owning delivery will still finalize it.
289
175
  */
290
- var waitForRecordedOutcome = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
291
- var attempt, row, outcome, takenOver;
292
- var entry = _b.entry, mutationId = _b.mutationId, request = _b.request, user = _b.user, onTakeover = _b.onTakeover;
293
- return __generator(this, function (_c) {
294
- switch (_c.label) {
295
- case 0:
296
- attempt = 0;
297
- _c.label = 1;
298
- case 1:
299
- if (!(attempt < PENDING_POLL_ATTEMPTS)) return [3 /*break*/, 8];
300
- return [4 /*yield*/, (0, plugins_1.findOneOrNoneFor)(models_1.SyncMutation, { mutationId: mutationId })];
301
- case 2:
302
- row = _c.sent();
303
- if (!row) return [3 /*break*/, 5];
304
- if (String(row.userId) !== String(user.id)) {
305
- return [2 /*return*/, makeNack({
306
- code: "unauthorized",
307
- message: "Mutation ".concat(mutationId, " was submitted by another user"),
308
- mutationId: mutationId,
309
- })];
310
- }
311
- return [4 /*yield*/, outcomeFromLedgerRow({ entry: entry, request: request, row: row })];
312
- case 3:
313
- outcome = _c.sent();
314
- if (outcome) {
315
- return [2 /*return*/, outcome];
316
- }
317
- if (!(row.status === "pending")) return [3 /*break*/, 5];
318
- return [4 /*yield*/, takeoverStaleLease(mutationId)];
319
- case 4:
320
- takenOver = _c.sent();
176
+ const waitForRecordedOutcome = async ({ entry, mutationId, request, user, onTakeover, }) => {
177
+ for (let attempt = 0; attempt < PENDING_POLL_ATTEMPTS; attempt++) {
178
+ const row = await (0, plugins_1.findOneOrNoneFor)(models_1.SyncMutation, { mutationId });
179
+ if (row) {
180
+ if (String(row.userId) !== String(user.id)) {
181
+ return makeNack({
182
+ code: "unauthorized",
183
+ message: `Mutation ${mutationId} was submitted by another user`,
184
+ mutationId,
185
+ });
186
+ }
187
+ const outcome = await outcomeFromLedgerRow({ entry, request, row });
188
+ if (outcome) {
189
+ return outcome;
190
+ }
191
+ if (row.status === "pending") {
192
+ const takenOver = await takeoverStaleLease(mutationId);
321
193
  if (takenOver) {
322
194
  logger_1.logger.warn("[sync] Took over a stale mutation lease", {
323
- mutationId: mutationId,
195
+ mutationId,
324
196
  staleForMs: luxon_1.DateTime.now().diff(luxon_1.DateTime.fromJSDate(row.claimedAt)).toMillis(),
325
197
  });
326
- return [2 /*return*/, onTakeover(takenOver)];
198
+ return onTakeover(takenOver);
327
199
  }
328
- _c.label = 5;
329
- case 5: return [4 /*yield*/, sleep(PENDING_POLL_INTERVAL_MS)];
330
- case 6:
331
- _c.sent();
332
- _c.label = 7;
333
- case 7:
334
- attempt++;
335
- return [3 /*break*/, 1];
336
- case 8: return [2 /*return*/, makeNack({
337
- code: "error",
338
- message: "Mutation ".concat(mutationId, " is still in flight"),
339
- mutationId: mutationId,
340
- })];
200
+ }
341
201
  }
202
+ await sleep(PENDING_POLL_INTERVAL_MS);
203
+ }
204
+ return makeNack({
205
+ code: "error",
206
+ message: `Mutation ${mutationId} is still in flight`,
207
+ mutationId,
342
208
  });
343
- }); };
209
+ };
344
210
  /**
345
211
  * C5 (FIX 6): true when `error` is (or wraps, via `APIError.error` — see
346
212
  * `executeCreate`'s `model.create()` catch, which wraps the raw Mongo driver
347
213
  * error in an APIError before it ever reaches the caller) a MongoDB E11000
348
214
  * duplicate-key error.
349
215
  */
350
- var isE11000Error = function (error) {
351
- var candidate = error;
352
- if ((candidate === null || candidate === void 0 ? void 0 : candidate.code) === 11000) {
216
+ const isE11000Error = (error) => {
217
+ const candidate = error;
218
+ if (candidate?.code === 11000) {
353
219
  return true;
354
220
  }
355
- var wrapped = candidate === null || candidate === void 0 ? void 0 : candidate.error;
356
- return (wrapped === null || wrapped === void 0 ? void 0 : wrapped.code) === 11000;
221
+ const wrapped = candidate?.error;
222
+ return wrapped?.code === 11000;
357
223
  };
358
224
  /**
359
225
  * C5 (FIX 6): true when every key/value in `data` (the mutation's own
@@ -363,19 +229,18 @@ var isE11000Error = function (error) {
363
229
  * different write landed and happens to have advanced the seq by exactly
364
230
  * one" (a real conflict; a seq match alone cannot tell these apart).
365
231
  */
366
- var docMatchesMutationData = function (doc, data) {
232
+ const docMatchesMutationData = (doc, data) => {
367
233
  if (!data) {
368
234
  return true;
369
235
  }
370
- var asDocument = doc;
371
- var plain = typeof (asDocument === null || asDocument === void 0 ? void 0 : asDocument.toObject) === "function"
236
+ const asDocument = doc;
237
+ const plain = typeof asDocument?.toObject === "function"
372
238
  ? asDocument.toObject()
373
239
  : doc;
374
- return Object.entries(data).every(function (_a) {
375
- var _b = __read(_a, 2), key = _b[0], value = _b[1];
376
- var current = plain === null || plain === void 0 ? void 0 : plain[key];
240
+ return Object.entries(data).every(([key, value]) => {
241
+ const current = plain?.[key];
377
242
  if (current instanceof Date && typeof value === "string") {
378
- var parsed = luxon_1.DateTime.fromISO(value, { zone: "utc" });
243
+ const parsed = luxon_1.DateTime.fromISO(value, { zone: "utc" });
379
244
  if (!parsed.isValid) {
380
245
  return false;
381
246
  }
@@ -385,7 +250,7 @@ var docMatchesMutationData = function (doc, data) {
385
250
  });
386
251
  };
387
252
  exports.docMatchesMutationData = docMatchesMutationData;
388
- var nackCodeForError = function (error) {
253
+ const nackCodeForError = (error) => {
389
254
  if (!(0, errors_1.isAPIError)(error)) {
390
255
  return "error";
391
256
  }
@@ -398,89 +263,66 @@ var nackCodeForError = function (error) {
398
263
  return "error";
399
264
  };
400
265
  /** Record a failed/conflicted outcome on the claimed ledger row and build the nack. */
401
- var finalizeNack = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
402
- var serverDoc, serializeError_1, resultId, code, message;
403
- var _c;
404
- var claimedId = _b.claimedId, entry = _b.entry, error = _b.error, mutation = _b.mutation, request = _b.request;
405
- return __generator(this, function (_d) {
406
- switch (_d.label) {
407
- case 0:
408
- if (!(0, executors_1.isExecutorConflictError)(error)) return [3 /*break*/, 6];
409
- serverDoc = void 0;
410
- _d.label = 1;
411
- case 1:
412
- _d.trys.push([1, 3, , 4]);
413
- return [4 /*yield*/, (0, routes_1.serializeSyncDoc)({
414
- doc: error.doc,
415
- entry: entry,
416
- req: request,
417
- })];
418
- case 2:
419
- serverDoc = _d.sent();
420
- return [3 /*break*/, 4];
421
- case 3:
422
- serializeError_1 = _d.sent();
423
- logger_1.logger.warn("[sync] Failed to serialize conflict server doc", {
424
- error: String(serializeError_1),
425
- mutationId: mutation.mutationId,
426
- });
427
- return [3 /*break*/, 4];
428
- case 4:
429
- resultId = ((_c = error.doc) === null || _c === void 0 ? void 0 : _c._id) !== undefined
430
- ? String(error.doc._id)
431
- : mutation.id;
432
- return [4 /*yield*/, models_1.SyncMutation.updateOne({ _id: claimedId }, {
433
- $set: {
434
- error: error.title,
435
- nackCode: "conflict",
436
- resultId: resultId,
437
- resultSeq: error.serverSeq,
438
- status: "conflicted",
439
- },
440
- })];
441
- case 5:
442
- _d.sent();
443
- return [2 /*return*/, makeNack({
444
- code: "conflict",
445
- message: error.title,
446
- mutationId: mutation.mutationId,
447
- serverDoc: serverDoc,
448
- serverSeq: error.serverSeq,
449
- })];
450
- case 6:
451
- code = nackCodeForError(error);
452
- message = (0, errors_1.isAPIError)(error) ? error.title : String(error);
453
- if (!(code === "error")) return [3 /*break*/, 8];
454
- logger_1.logger.warn("[sync] Mutation failed unexpectedly", {
455
- collection: mutation.collection,
456
- error: message,
457
- mutationId: mutation.mutationId,
458
- });
459
- // Task 9.18: an `error`-class failure is non-deterministic (DB hiccup, replica
460
- // step-down) — it is not a verdict on the mutation. Recording it `failed` would make
461
- // it sticky for the ledger's 30-day TTL, so every replay of the same mutationId reads
462
- // the nack back and the client's durable outbox retries forever without the mutation
463
- // ever re-executing. Release the claim instead: the next delivery re-claims the
464
- // mutationId and genuinely re-runs the write. Deterministic outcomes
465
- // (validation/unauthorized/conflict) stay recorded — replaying those must not re-run.
466
- return [4 /*yield*/, models_1.SyncMutation.deleteOne({ _id: claimedId })];
467
- case 7:
468
- // Task 9.18: an `error`-class failure is non-deterministic (DB hiccup, replica
469
- // step-down) — it is not a verdict on the mutation. Recording it `failed` would make
470
- // it sticky for the ledger's 30-day TTL, so every replay of the same mutationId reads
471
- // the nack back and the client's durable outbox retries forever without the mutation
472
- // ever re-executing. Release the claim instead: the next delivery re-claims the
473
- // mutationId and genuinely re-runs the write. Deterministic outcomes
474
- // (validation/unauthorized/conflict) stay recorded — replaying those must not re-run.
475
- _d.sent();
476
- return [2 /*return*/, makeNack({ code: code, message: message, mutationId: mutation.mutationId })];
477
- case 8: return [4 /*yield*/, models_1.SyncMutation.updateOne({ _id: claimedId }, { $set: { error: message, nackCode: code, status: "failed" } })];
478
- case 9:
479
- _d.sent();
480
- return [2 /*return*/, makeNack({ code: code, message: message, mutationId: mutation.mutationId })];
266
+ const finalizeNack = async ({ claimedId, entry, error, mutation, request, }) => {
267
+ // Duck-typed: `instanceof` breaks for Error subclasses in the compiled ES5 dist.
268
+ if ((0, executors_1.isExecutorConflictError)(error)) {
269
+ let serverDoc;
270
+ try {
271
+ serverDoc = await (0, routes_1.serializeSyncDoc)({
272
+ doc: error.doc,
273
+ entry,
274
+ req: request,
275
+ });
481
276
  }
482
- });
483
- }); };
277
+ catch (serializeError) {
278
+ logger_1.logger.warn("[sync] Failed to serialize conflict server doc", {
279
+ error: String(serializeError),
280
+ mutationId: mutation.mutationId,
281
+ });
282
+ }
283
+ // Task 9.21: record only the pointer ({resultId, resultSeq}), never `serverDoc` —
284
+ // a duplicate delivery re-serializes the live document from `resultId`.
285
+ const resultId = error.doc?._id !== undefined
286
+ ? String(error.doc._id)
287
+ : mutation.id;
288
+ await models_1.SyncMutation.updateOne({ _id: claimedId }, {
289
+ $set: {
290
+ error: error.title,
291
+ nackCode: "conflict",
292
+ resultId,
293
+ resultSeq: error.serverSeq,
294
+ status: "conflicted",
295
+ },
296
+ });
297
+ return makeNack({
298
+ code: "conflict",
299
+ message: error.title,
300
+ mutationId: mutation.mutationId,
301
+ serverDoc,
302
+ serverSeq: error.serverSeq,
303
+ });
304
+ }
305
+ const code = nackCodeForError(error);
306
+ const message = (0, errors_1.isAPIError)(error) ? error.title : String(error);
307
+ if (code === "error") {
308
+ logger_1.logger.warn("[sync] Mutation failed unexpectedly", {
309
+ collection: mutation.collection,
310
+ error: message,
311
+ mutationId: mutation.mutationId,
312
+ });
313
+ // Task 9.18: an `error`-class failure is non-deterministic (DB hiccup, replica
314
+ // step-down) — it is not a verdict on the mutation. Recording it `failed` would make
315
+ // it sticky for the ledger's 30-day TTL, so every replay of the same mutationId reads
316
+ // the nack back and the client's durable outbox retries forever without the mutation
317
+ // ever re-executing. Release the claim instead: the next delivery re-claims the
318
+ // mutationId and genuinely re-runs the write. Deterministic outcomes
319
+ // (validation/unauthorized/conflict) stay recorded — replaying those must not re-run.
320
+ await models_1.SyncMutation.deleteOne({ _id: claimedId });
321
+ return makeNack({ code, message, mutationId: mutation.mutationId });
322
+ }
323
+ await models_1.SyncMutation.updateOne({ _id: claimedId }, { $set: { error: message, nackCode: code, status: "failed" } });
324
+ return makeNack({ code, message, mutationId: mutation.mutationId });
325
+ };
484
326
  /**
485
327
  * C5 (FIX 6): read the doc back and report it as the ack for an ALREADY-APPLIED write —
486
328
  * used both by the create-E11000 tolerance and the update/delete already-applied check.
@@ -488,27 +330,17 @@ var finalizeNack = function (_a) { return __awaiter(void 0, [_a], void 0, functi
488
330
  * returning, exactly like the normal apply path, so a subsequent duplicate delivery
489
331
  * reads back the same outcome.
490
332
  */
491
- var finalizeAlreadyApplied = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
492
- var resultId, resultSeq;
493
- var _c;
494
- var claimedId = _b.claimedId, doc = _b.doc, mutation = _b.mutation;
495
- return __generator(this, function (_d) {
496
- switch (_d.label) {
497
- case 0:
498
- resultId = String(doc._id);
499
- resultSeq = (_c = doc._syncSeq) !== null && _c !== void 0 ? _c : 0;
500
- return [4 /*yield*/, models_1.SyncMutation.updateOne({ _id: claimedId }, { $set: { resultId: resultId, resultSeq: resultSeq, status: "applied" } })];
501
- case 1:
502
- _d.sent();
503
- logger_1.logger.info("[sync] Mutation already applied (lease-takeover tolerance)", {
504
- collection: mutation.collection,
505
- mutationId: mutation.mutationId,
506
- seq: resultSeq,
507
- });
508
- return [2 /*return*/, { resultId: resultId, resultSeq: resultSeq }];
509
- }
333
+ const finalizeAlreadyApplied = async ({ claimedId, doc, mutation, }) => {
334
+ const resultId = String(doc._id);
335
+ const resultSeq = doc._syncSeq ?? 0;
336
+ await models_1.SyncMutation.updateOne({ _id: claimedId }, { $set: { resultId, resultSeq, status: "applied" } });
337
+ logger_1.logger.info("[sync] Mutation already applied (lease-takeover tolerance)", {
338
+ collection: mutation.collection,
339
+ mutationId: mutation.mutationId,
340
+ seq: resultSeq,
510
341
  });
511
- }); };
342
+ return { resultId, resultSeq };
343
+ };
512
344
  /**
513
345
  * Apply a client mutation through the transport-agnostic executors (permissions,
514
346
  * pre/post hooks, validation) against an ALREADY-CLAIMED ledger row (either a fresh claim
@@ -533,249 +365,311 @@ var finalizeAlreadyApplied = function (_a) { return __awaiter(void 0, [_a], void
533
365
  * - delete: idempotent already (executeDelete on an already-deleted tombstone is a no-op
534
366
  * success in this codebase's soft-delete model), so no special tolerance is needed.
535
367
  */
536
- var applyClaimedMutation = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
537
- var mutationId, model, doc, postHook, body, result_1, createError_1, existing, _c, resultId_1, resultSeq_1, result_2, cleanedBody_1, prevDoc_1, updateError_1, _d, resultId_2, resultSeq_2, result_3, resultId, resultSeq, warning, postHookError_1, error_2;
538
- var _e, _f, _g, _h, _j;
539
- var claimed = _b.claimed, entry = _b.entry, mutation = _b.mutation, request = _b.request, user = _b.user, scopeResolver = _b.scopeResolver, _k = _b.isLeaseTakeover, isLeaseTakeover = _k === void 0 ? false : _k;
540
- return __generator(this, function (_l) {
541
- switch (_l.label) {
542
- case 0:
543
- mutationId = mutation.mutationId;
544
- _l.label = 1;
545
- case 1:
546
- _l.trys.push([1, 25, , 26]);
547
- model = mongoose_1.default.model(entry.modelName);
548
- // C6 (M6): sync-boundary write-scope backstop before any write pipeline runs.
549
- return [4 /*yield*/, enforceWriteScope({
550
- data: mutation.data,
551
- entry: entry,
552
- operation: mutation.operation,
553
- scopeResolver: scopeResolver,
554
- user: user,
555
- })];
556
- case 2:
557
- // C6 (M6): sync-boundary write-scope backstop before any write pipeline runs.
558
- _l.sent();
559
- doc = void 0;
560
- postHook = void 0;
561
- if (!(mutation.operation === "create")) return [3 /*break*/, 10];
562
- body = __assign({}, ((_e = mutation.data) !== null && _e !== void 0 ? _e : {}));
563
- if (mutation.id) {
564
- body._id = mutation.id;
368
+ const organizationIdFromRequest = (request) => {
369
+ if (typeof request.header !== "function") {
370
+ return undefined;
371
+ }
372
+ const raw = request.header("X-Organization-Id");
373
+ if (typeof raw !== "string") {
374
+ return undefined;
375
+ }
376
+ const trimmed = raw.trim();
377
+ if (!trimmed) {
378
+ return undefined;
379
+ }
380
+ return trimmed;
381
+ };
382
+ const withRequestOrgContext = async ({ request, run, user, }) => {
383
+ const organizationId = organizationIdFromRequest(request);
384
+ if (!organizationId) {
385
+ return run();
386
+ }
387
+ const context = await (0, orgContext_1.resolveOrgContext)({ organizationId, required: false, user });
388
+ return (0, orgContext_1.runWithOrgContext)(context, run);
389
+ };
390
+ const applyClaimedMutation = async ({ claimed, entry, mutation, request, user, scopeResolver, syncOptions, isLeaseTakeover = false, }) => {
391
+ return withRequestOrgContext({
392
+ request,
393
+ run: () => applyClaimedMutationInContext({
394
+ claimed,
395
+ entry,
396
+ isLeaseTakeover,
397
+ mutation,
398
+ request,
399
+ scopeResolver,
400
+ syncOptions,
401
+ user,
402
+ }),
403
+ user,
404
+ });
405
+ };
406
+ const applyClaimedMutationInContext = async ({ claimed, entry, mutation, request, user, scopeResolver, syncOptions, isLeaseTakeover = false, }) => {
407
+ const mutationId = mutation.mutationId;
408
+ let adminWindowScope;
409
+ try {
410
+ // Task 9.18: resolving the model must be INSIDE the try — a MissingSchemaError thrown
411
+ // here would escape without finalizing the claimed row, wedging the mutationId
412
+ // `pending` for the whole lease window instead of nacking it.
413
+ const model = mongoose_1.default.model(entry.modelName);
414
+ const adminWindow = await (0, adminWindowMutation_1.prepareAdminWindowMutation)({
415
+ entry,
416
+ mutation,
417
+ req: request,
418
+ syncOptions,
419
+ user,
420
+ });
421
+ let effectiveMutation = mutation;
422
+ if (adminWindow) {
423
+ effectiveMutation = adminWindow.mutation;
424
+ adminWindowScope = adminWindow.scope;
425
+ }
426
+ else {
427
+ // C6 (M6): product-path write-scope backstop before any write pipeline runs.
428
+ await enforceWriteScope({
429
+ data: effectiveMutation.data,
430
+ entry,
431
+ operation: effectiveMutation.operation,
432
+ scopeResolver,
433
+ user,
434
+ });
435
+ }
436
+ const skipPermissionChecks = Boolean(adminWindowScope);
437
+ const executorOptions = adminWindowScope
438
+ ? (0, adminWindowMutation_1.buildAdminWindowExecutorOptions)({ productOptions: entry.options, scope: adminWindowScope })
439
+ : entry.options;
440
+ const executorRequest = adminWindowScope
441
+ ? (0, adminWindowMutation_1.withAdminWindowMutationRequestContext)({ mutation: effectiveMutation, req: request })
442
+ : request;
443
+ let doc;
444
+ let postHook;
445
+ if (effectiveMutation.operation === "create") {
446
+ const body = { ...(effectiveMutation.data ?? {}) };
447
+ if (effectiveMutation.id) {
448
+ body._id = effectiveMutation.id;
449
+ }
450
+ try {
451
+ const result = await (0, executors_1.executeCreate)({
452
+ body,
453
+ model,
454
+ options: executorOptions,
455
+ req: executorRequest,
456
+ skipPermissionChecks,
457
+ skipPostHooks: true,
458
+ user,
459
+ });
460
+ doc = result.doc;
461
+ postHook = () => (0, executors_1.runPostCreate)({ doc: result.doc, options: executorOptions, request: executorRequest });
462
+ }
463
+ catch (createError) {
464
+ // M4 (lease takeover only): an E11000 on the exact target _id is
465
+ // tolerated as "already applied" — a prior (crashed) attempt at
466
+ // THIS mutation landed the write before finalizing the ledger. A
467
+ // normal (non-takeover) first attempt reports the error as usual —
468
+ // client-minted UUIDs make a genuine unrelated _id collision
469
+ // vanishingly unlikely, so gating this on isLeaseTakeover keeps the
470
+ // tolerance scoped to its actual crash-recovery purpose.
471
+ if (isLeaseTakeover &&
472
+ isE11000Error(createError) &&
473
+ typeof effectiveMutation.id === "string") {
474
+ const existing = await (0, plugins_1.findOneOrNoneFor)(model, { _id: effectiveMutation.id });
475
+ if (existing) {
476
+ const { resultId, resultSeq } = await finalizeAlreadyApplied({
477
+ claimedId: claimed._id,
478
+ doc: existing,
479
+ mutation,
480
+ });
481
+ return { ack: { id: resultId, mutationId, seq: resultSeq }, type: "ack" };
482
+ }
565
483
  }
566
- _l.label = 3;
567
- case 3:
568
- _l.trys.push([3, 5, , 9]);
569
- return [4 /*yield*/, (0, executors_1.executeCreate)({
570
- body: body,
571
- model: model,
572
- options: entry.options,
573
- req: request,
574
- skipPostHooks: true,
575
- user: user,
576
- })];
577
- case 4:
578
- result_1 = _l.sent();
579
- doc = result_1.doc;
580
- postHook = function () {
581
- return (0, executors_1.runPostCreate)({ doc: result_1.doc, options: entry.options, request: request });
582
- };
583
- return [3 /*break*/, 9];
584
- case 5:
585
- createError_1 = _l.sent();
586
- if (!(isLeaseTakeover && isE11000Error(createError_1) && typeof mutation.id === "string")) return [3 /*break*/, 8];
587
- return [4 /*yield*/, (0, plugins_1.findOneOrNoneFor)(model, { _id: mutation.id })];
588
- case 6:
589
- existing = _l.sent();
590
- if (!existing) return [3 /*break*/, 8];
591
- return [4 /*yield*/, finalizeAlreadyApplied({
592
- claimedId: claimed._id,
593
- doc: existing,
594
- mutation: mutation,
595
- })];
596
- case 7:
597
- _c = _l.sent(), resultId_1 = _c.resultId, resultSeq_1 = _c.resultSeq;
598
- return [2 /*return*/, { ack: { id: resultId_1, mutationId: mutationId, seq: resultSeq_1 }, type: "ack" }];
599
- case 8: throw createError_1;
600
- case 9: return [3 /*break*/, 19];
601
- case 10:
602
- if (!(mutation.operation === "update")) return [3 /*break*/, 17];
603
- _l.label = 11;
604
- case 11:
605
- _l.trys.push([11, 13, , 16]);
606
- return [4 /*yield*/, (0, executors_1.executeUpdate)({
607
- body: (_f = mutation.data) !== null && _f !== void 0 ? _f : {},
608
- concurrencyCheck: { baseSeq: (_g = mutation.baseVersion) !== null && _g !== void 0 ? _g : 0, type: "seq" },
609
- id: mutation.id,
610
- model: model,
611
- options: entry.options,
612
- req: request,
613
- skipPostHooks: true,
614
- user: user,
615
- })];
616
- case 12:
617
- result_2 = _l.sent();
618
- doc = result_2.doc;
619
- cleanedBody_1 = result_2.cleanedBody;
620
- prevDoc_1 = result_2.prevDoc;
621
- postHook = function () {
622
- return (0, executors_1.runPostUpdate)({ cleanedBody: cleanedBody_1, doc: result_2.doc, options: entry.options, prevDoc: prevDoc_1, request: request });
623
- };
624
- return [3 /*break*/, 16];
625
- case 13:
626
- updateError_1 = _l.sent();
627
- if (!(isLeaseTakeover &&
628
- (0, executors_1.isExecutorConflictError)(updateError_1) &&
629
- updateError_1.conflictType === "seq" &&
630
- updateError_1.serverSeq === ((_h = mutation.baseVersion) !== null && _h !== void 0 ? _h : 0) + 1 &&
631
- (0, exports.docMatchesMutationData)(updateError_1.doc, mutation.data))) return [3 /*break*/, 15];
632
- return [4 /*yield*/, finalizeAlreadyApplied({
633
- claimedId: claimed._id,
634
- doc: updateError_1.doc,
635
- mutation: mutation,
636
- })];
637
- case 14:
638
- _d = _l.sent(), resultId_2 = _d.resultId, resultSeq_2 = _d.resultSeq;
639
- return [2 /*return*/, { ack: { id: resultId_2, mutationId: mutationId, seq: resultSeq_2 }, type: "ack" }];
640
- case 15: throw updateError_1;
641
- case 16: return [3 /*break*/, 19];
642
- case 17: return [4 /*yield*/, (0, executors_1.executeDelete)({
643
- id: mutation.id,
644
- model: model,
645
- options: entry.options,
646
- req: request,
484
+ throw createError;
485
+ }
486
+ }
487
+ else if (effectiveMutation.operation === "update") {
488
+ try {
489
+ const result = await (0, executors_1.executeUpdate)({
490
+ body: effectiveMutation.data ?? {},
491
+ concurrencyCheck: { baseSeq: effectiveMutation.baseVersion ?? 0, type: "seq" },
492
+ id: effectiveMutation.id,
493
+ model,
494
+ options: executorOptions,
495
+ req: executorRequest,
496
+ skipPermissionChecks,
647
497
  skipPostHooks: true,
648
- user: user,
649
- })];
650
- case 18:
651
- result_3 = _l.sent();
652
- doc = result_3.doc;
653
- postHook = function () {
654
- return (0, executors_1.runPostDelete)({ doc: result_3.doc, options: entry.options, request: request });
655
- };
656
- _l.label = 19;
657
- case 19:
658
- resultId = String(doc._id);
659
- resultSeq = (_j = doc._syncSeq) !== null && _j !== void 0 ? _j : 0;
660
- // M5: finalize the ledger BEFORE the post-hook runs — a post-hook throw
661
- // must never make a committed write look like a failure.
662
- return [4 /*yield*/, models_1.SyncMutation.updateOne({ _id: claimed._id }, { $set: { resultId: resultId, resultSeq: resultSeq, status: "applied" } })];
663
- case 20:
664
- // M5: finalize the ledger BEFORE the post-hook runs — a post-hook throw
665
- // must never make a committed write look like a failure.
666
- _l.sent();
667
- syncDebugLog.debug("[sync] Mutation applied", {
668
- collection: mutation.collection,
669
- mutationId: mutationId,
670
- seq: resultSeq,
498
+ user,
499
+ });
500
+ doc = result.doc;
501
+ // biome-ignore lint/style/noNonNullAssertion: executeUpdate with skipPostHooks always returns cleanedBody/prevDoc.
502
+ const cleanedBody = result.cleanedBody;
503
+ // biome-ignore lint/style/noNonNullAssertion: executeUpdate with skipPostHooks always returns cleanedBody/prevDoc.
504
+ const prevDoc = result.prevDoc;
505
+ postHook = () => (0, executors_1.runPostUpdate)({
506
+ cleanedBody,
507
+ doc: result.doc,
508
+ options: executorOptions,
509
+ prevDoc,
510
+ request: executorRequest,
671
511
  });
672
- warning = void 0;
673
- _l.label = 21;
674
- case 21:
675
- _l.trys.push([21, 23, , 24]);
676
- return [4 /*yield*/, postHook()];
677
- case 22:
678
- _l.sent();
679
- return [3 /*break*/, 24];
680
- case 23:
681
- postHookError_1 = _l.sent();
682
- warning = errorMessageOf(postHookError_1);
683
- logger_1.logger.error("[sync] Post-hook failed after a committed mutation", {
512
+ }
513
+ catch (updateError) {
514
+ // M4 (lease takeover only): a conflict whose serverSeq is EXACTLY
515
+ // this mutation's own expected post-write seq COULD mean the write
516
+ // this very mutation intended already landed on a prior (crashed)
517
+ // attempt — but a seq match alone is ambiguous (any other write
518
+ // landing between the claim and the retry would also bump the seq
519
+ // by exactly one). Additionally require the current doc's fields to
520
+ // already contain every value this mutation's own `data` would have
521
+ // written — only THEN is it safe to treat as already-applied and
522
+ // report success; otherwise it is a genuine external conflict and
523
+ // must nack as usual, exactly like a normal (non-takeover) apply.
524
+ if (isLeaseTakeover &&
525
+ (0, executors_1.isExecutorConflictError)(updateError) &&
526
+ updateError.conflictType === "seq" &&
527
+ updateError.serverSeq === (effectiveMutation.baseVersion ?? 0) + 1 &&
528
+ (0, exports.docMatchesMutationData)(updateError.doc, effectiveMutation.data)) {
529
+ const { resultId, resultSeq } = await finalizeAlreadyApplied({
530
+ claimedId: claimed._id,
531
+ doc: updateError.doc,
532
+ mutation,
533
+ });
534
+ return { ack: { id: resultId, mutationId, seq: resultSeq }, type: "ack" };
535
+ }
536
+ throw updateError;
537
+ }
538
+ }
539
+ else {
540
+ const result = await (0, executors_1.executeDelete)({
541
+ id: effectiveMutation.id,
542
+ model,
543
+ options: executorOptions,
544
+ req: executorRequest,
545
+ skipPermissionChecks,
546
+ skipPostHooks: true,
547
+ user,
548
+ });
549
+ doc = result.doc;
550
+ postHook = () => (0, executors_1.runPostDelete)({ doc: result.doc, options: executorOptions, request: executorRequest });
551
+ }
552
+ const resultId = String(doc._id);
553
+ const resultSeq = doc._syncSeq ?? 0;
554
+ // M5: finalize the ledger BEFORE the post-hook runs — a post-hook throw
555
+ // must never make a committed write look like a failure.
556
+ await models_1.SyncMutation.updateOne({ _id: claimed._id }, { $set: { resultId, resultSeq, status: "applied" } });
557
+ syncDebugLog.debug("[sync] Mutation applied", {
558
+ collection: mutation.collection,
559
+ mutationId,
560
+ seq: resultSeq,
561
+ });
562
+ let warning;
563
+ try {
564
+ await postHook();
565
+ }
566
+ catch (postHookError) {
567
+ warning = errorMessageOf(postHookError);
568
+ logger_1.logger.error("[sync] Post-hook failed after a committed mutation", {
569
+ collection: mutation.collection,
570
+ error: warning,
571
+ mutationId,
572
+ });
573
+ }
574
+ if (adminWindowScope?.emitAudit) {
575
+ try {
576
+ await (0, adminWindowMutation_1.emitAdminWindowMutationAudit)({
577
+ doc,
578
+ mutation: effectiveMutation,
579
+ req: executorRequest,
580
+ scope: adminWindowScope,
581
+ });
582
+ }
583
+ catch (auditError) {
584
+ logger_1.logger.error("[sync] Admin window audit hook failed after a committed mutation", {
684
585
  collection: mutation.collection,
685
- error: warning,
686
- mutationId: mutationId,
586
+ error: errorMessageOf(auditError),
587
+ mutationId,
687
588
  });
688
- return [3 /*break*/, 24];
689
- case 24: return [2 /*return*/, {
690
- ack: __assign({ id: resultId, mutationId: mutationId, seq: resultSeq }, (warning ? { warning: warning } : {})),
691
- type: "ack",
692
- }];
693
- case 25:
694
- error_2 = _l.sent();
695
- return [2 /*return*/, finalizeNack({ claimedId: claimed._id, entry: entry, error: error_2, mutation: mutation, request: request })];
696
- case 26: return [2 /*return*/];
589
+ }
697
590
  }
698
- });
699
- }); };
700
- var errorMessageOf = function (error) {
701
- return (0, errors_1.isAPIError)(error) ? error.title : error instanceof Error ? error.message : String(error);
591
+ return {
592
+ ack: { id: resultId, mutationId, seq: resultSeq, ...(warning ? { warning } : {}) },
593
+ type: "ack",
594
+ };
595
+ }
596
+ catch (error) {
597
+ return finalizeNack({ claimedId: claimed._id, entry, error, mutation, request });
598
+ }
702
599
  };
600
+ const errorMessageOf = (error) => (0, errors_1.isAPIError)(error) ? error.title : error instanceof Error ? error.message : String(error);
703
601
  /**
704
602
  * Apply a client mutation through the transport-agnostic executors (permissions,
705
603
  * pre/post hooks, validation) with an atomic idempotency claim. Always finalizes the
706
604
  * claimed ledger row before returning so duplicate deliveries can read the outcome back.
707
605
  */
708
- var applySyncMutation = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
709
- var mutationId, validationNack, entry, request, claimed, error_3;
710
- var user = _b.user, mutation = _b.mutation, req = _b.req, scopeResolver = _b.scopeResolver;
711
- return __generator(this, function (_c) {
712
- switch (_c.label) {
713
- case 0:
714
- mutationId = typeof (mutation === null || mutation === void 0 ? void 0 : mutation.mutationId) === "string" ? mutation.mutationId : "";
715
- validationNack = function (message) {
716
- return makeNack({ code: "validation", message: message, mutationId: mutationId });
717
- };
718
- if (!mutationId) {
719
- return [2 /*return*/, validationNack("mutationId is required")];
720
- }
721
- if (!mutation.collection || typeof mutation.collection !== "string") {
722
- return [2 /*return*/, validationNack("collection is required")];
723
- }
724
- if (!VALID_OPERATIONS.has(mutation.operation)) {
725
- return [2 /*return*/, validationNack("Unknown operation: ".concat(String(mutation.operation)))];
726
- }
727
- if ((mutation.operation === "update" || mutation.operation === "delete") && !mutation.id) {
728
- return [2 /*return*/, validationNack("id is required for ".concat(mutation.operation, " mutations"))];
729
- }
730
- // C8: an update MUST carry an explicit baseVersion — omitting it would silently become
731
- // a `baseSeq: 0` check (an accidental conflict against every non-fresh doc, or an
732
- // accidental success against a seq-0 doc). Reject it as a client bug up front.
733
- if (mutation.operation === "update" && typeof mutation.baseVersion !== "number") {
734
- return [2 /*return*/, validationNack("baseVersion is required for update mutations")];
735
- }
736
- entry = (0, registry_1.findSyncEntryByCollectionTag)(mutation.collection);
737
- if (!entry) {
738
- return [2 /*return*/, validationNack("Unknown sync collection: ".concat(mutation.collection))];
739
- }
740
- request = req !== null && req !== void 0 ? req : { user: user };
741
- _c.label = 1;
742
- case 1:
743
- _c.trys.push([1, 3, , 4]);
744
- return [4 /*yield*/, models_1.SyncMutation.create({
745
- claimedAt: luxon_1.DateTime.now().toJSDate(),
746
- mutationId: mutationId,
747
- status: "pending",
748
- userId: String(user.id),
749
- })];
750
- case 2:
751
- claimed = _c.sent();
752
- return [3 /*break*/, 4];
753
- case 3:
754
- error_3 = _c.sent();
755
- if (error_3.code !== 11000) {
756
- throw error_3;
757
- }
758
- return [2 /*return*/, waitForRecordedOutcome({
759
- entry: entry,
760
- mutationId: mutationId,
761
- onTakeover: function (takenOver) {
762
- return applyClaimedMutation({
763
- claimed: takenOver,
764
- entry: entry,
765
- isLeaseTakeover: true,
766
- mutation: mutation,
767
- request: request,
768
- scopeResolver: scopeResolver,
769
- user: user,
770
- });
771
- },
772
- request: request,
773
- user: user,
774
- })];
775
- case 4: return [2 /*return*/, applyClaimedMutation({ claimed: claimed, entry: entry, mutation: mutation, request: request, scopeResolver: scopeResolver, user: user })];
606
+ const applySyncMutation = async ({ user, mutation, req, scopeResolver, syncOptions, }) => {
607
+ const mutationId = typeof mutation?.mutationId === "string" ? mutation.mutationId : "";
608
+ const validationNack = (message) => makeNack({ code: "validation", message, mutationId });
609
+ if (!mutationId) {
610
+ return validationNack("mutationId is required");
611
+ }
612
+ if (!mutation.collection || typeof mutation.collection !== "string") {
613
+ return validationNack("collection is required");
614
+ }
615
+ if (!VALID_OPERATIONS.has(mutation.operation)) {
616
+ return validationNack(`Unknown operation: ${String(mutation.operation)}`);
617
+ }
618
+ if ((mutation.operation === "update" || mutation.operation === "delete") && !mutation.id) {
619
+ return validationNack(`id is required for ${mutation.operation} mutations`);
620
+ }
621
+ // C8: an update MUST carry an explicit baseVersion — omitting it would silently become
622
+ // a `baseSeq: 0` check (an accidental conflict against every non-fresh doc, or an
623
+ // accidental success against a seq-0 doc). Reject it as a client bug up front.
624
+ if (mutation.operation === "update" && typeof mutation.baseVersion !== "number") {
625
+ return validationNack("baseVersion is required for update mutations");
626
+ }
627
+ const entry = (0, registry_1.findSyncEntryByCollectionTag)(mutation.collection);
628
+ if (!entry) {
629
+ return validationNack(`Unknown sync collection: ${mutation.collection}`);
630
+ }
631
+ const request = req ?? { user };
632
+ // Atomic claim: inserting the pending row first means exactly one delivery applies.
633
+ let claimed;
634
+ try {
635
+ claimed = await models_1.SyncMutation.create({
636
+ claimedAt: luxon_1.DateTime.now().toJSDate(),
637
+ mutationId,
638
+ status: "pending",
639
+ userId: String(user.id),
640
+ });
641
+ }
642
+ catch (error) {
643
+ if (error.code !== 11000) {
644
+ throw error;
776
645
  }
646
+ return waitForRecordedOutcome({
647
+ entry,
648
+ mutationId,
649
+ onTakeover: (takenOver) => applyClaimedMutation({
650
+ claimed: takenOver,
651
+ entry,
652
+ isLeaseTakeover: true,
653
+ mutation,
654
+ request,
655
+ scopeResolver,
656
+ syncOptions,
657
+ user,
658
+ }),
659
+ request,
660
+ user,
661
+ });
662
+ }
663
+ return applyClaimedMutation({
664
+ claimed,
665
+ entry,
666
+ mutation,
667
+ request,
668
+ scopeResolver,
669
+ syncOptions,
670
+ user,
777
671
  });
778
- }); };
672
+ };
779
673
  exports.applySyncMutation = applySyncMutation;
780
674
  /**
781
675
  * Up-front validation shared by both batch transports (HTTP and socket): reject an
@@ -785,8 +679,7 @@ exports.applySyncMutation = applySyncMutation;
785
679
  * the shape callers expect from `applySyncMutationBatch`, but produced without
786
680
  * touching the idempotency ledger since nothing was attempted.
787
681
  */
788
- var validateSyncMutationBatch = function (mutations) {
789
- var e_1, _a;
682
+ const validateSyncMutationBatch = (mutations) => {
790
683
  if (mutations.length > exports.MAX_SYNC_MUTATIONS_PER_BATCH) {
791
684
  return {
792
685
  ok: false,
@@ -794,41 +687,31 @@ var validateSyncMutationBatch = function (mutations) {
794
687
  results: [
795
688
  makeNack({
796
689
  code: "validation",
797
- message: "Batch of ".concat(mutations.length, " exceeds the maximum of ").concat(exports.MAX_SYNC_MUTATIONS_PER_BATCH, " mutations"),
690
+ message: `Batch of ${mutations.length} exceeds the maximum of ${exports.MAX_SYNC_MUTATIONS_PER_BATCH} mutations`,
798
691
  mutationId: "",
799
692
  }),
800
693
  ],
801
694
  },
802
695
  };
803
696
  }
804
- var seen = new Set();
805
- try {
806
- for (var mutations_1 = __values(mutations), mutations_1_1 = mutations_1.next(); !mutations_1_1.done; mutations_1_1 = mutations_1.next()) {
807
- var mutation = mutations_1_1.value;
808
- var mutationId = typeof (mutation === null || mutation === void 0 ? void 0 : mutation.mutationId) === "string" ? mutation.mutationId : "";
809
- if (mutationId && seen.has(mutationId)) {
810
- return {
811
- ok: false,
812
- response: {
813
- results: [
814
- makeNack({
815
- code: "validation",
816
- message: "Duplicate mutationId within batch: ".concat(mutationId),
817
- mutationId: mutationId,
818
- }),
819
- ],
820
- },
821
- };
822
- }
823
- seen.add(mutationId);
824
- }
825
- }
826
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
827
- finally {
828
- try {
829
- if (mutations_1_1 && !mutations_1_1.done && (_a = mutations_1.return)) _a.call(mutations_1);
697
+ const seen = new Set();
698
+ for (const mutation of mutations) {
699
+ const mutationId = typeof mutation?.mutationId === "string" ? mutation.mutationId : "";
700
+ if (mutationId && seen.has(mutationId)) {
701
+ return {
702
+ ok: false,
703
+ response: {
704
+ results: [
705
+ makeNack({
706
+ code: "validation",
707
+ message: `Duplicate mutationId within batch: ${mutationId}`,
708
+ mutationId,
709
+ }),
710
+ ],
711
+ },
712
+ };
830
713
  }
831
- finally { if (e_1) throw e_1.error; }
714
+ seen.add(mutationId);
832
715
  }
833
716
  return { ok: true };
834
717
  };
@@ -844,48 +727,17 @@ exports.validateSyncMutationBatch = validateSyncMutationBatch;
844
727
  * rejection happens before any mutation is attempted); this function assumes the
845
728
  * batch already passed that check.
846
729
  */
847
- var applySyncMutationBatch = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
848
- var results, mutations_2, mutations_2_1, mutation, outcome, e_2_1;
849
- var e_2, _c;
850
- var user = _b.user, mutations = _b.mutations, req = _b.req, scopeResolver = _b.scopeResolver;
851
- return __generator(this, function (_d) {
852
- switch (_d.label) {
853
- case 0:
854
- results = [];
855
- _d.label = 1;
856
- case 1:
857
- _d.trys.push([1, 6, 7, 8]);
858
- mutations_2 = __values(mutations), mutations_2_1 = mutations_2.next();
859
- _d.label = 2;
860
- case 2:
861
- if (!!mutations_2_1.done) return [3 /*break*/, 5];
862
- mutation = mutations_2_1.value;
863
- return [4 /*yield*/, (0, exports.applySyncMutation)({ mutation: mutation, req: req, scopeResolver: scopeResolver, user: user })];
864
- case 3:
865
- outcome = _d.sent();
866
- results.push(outcome);
867
- if (outcome.type === "nack") {
868
- // Stop-on-error: the client re-sends everything after this point, and
869
- // INV-3's idempotency ledger makes that overlap safe.
870
- return [3 /*break*/, 5];
871
- }
872
- _d.label = 4;
873
- case 4:
874
- mutations_2_1 = mutations_2.next();
875
- return [3 /*break*/, 2];
876
- case 5: return [3 /*break*/, 8];
877
- case 6:
878
- e_2_1 = _d.sent();
879
- e_2 = { error: e_2_1 };
880
- return [3 /*break*/, 8];
881
- case 7:
882
- try {
883
- if (mutations_2_1 && !mutations_2_1.done && (_c = mutations_2.return)) _c.call(mutations_2);
884
- }
885
- finally { if (e_2) throw e_2.error; }
886
- return [7 /*endfinally*/];
887
- case 8: return [2 /*return*/, { results: results }];
730
+ const applySyncMutationBatch = async ({ user, mutations, req, scopeResolver, syncOptions, }) => {
731
+ const results = [];
732
+ for (const mutation of mutations) {
733
+ const outcome = await (0, exports.applySyncMutation)({ mutation, req, scopeResolver, syncOptions, user });
734
+ results.push(outcome);
735
+ if (outcome.type === "nack") {
736
+ // Stop-on-error: the client re-sends everything after this point, and
737
+ // INV-3's idempotency ledger makes that overlap safe.
738
+ break;
888
739
  }
889
- });
890
- }); };
740
+ }
741
+ return { results };
742
+ };
891
743
  exports.applySyncMutationBatch = applySyncMutationBatch;