@terreno/api 57.4.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 (208) hide show
  1. package/README.md +5 -5
  2. package/bunfig.toml +1 -1
  3. package/dist/actions.js +197 -368
  4. package/dist/adminModelRouter.js +88 -173
  5. package/dist/api.js +598 -852
  6. package/dist/audit/auditApp.js +48 -89
  7. package/dist/audit/auditEventModel.js +15 -16
  8. package/dist/audit/cloudTasksEnqueue.js +56 -149
  9. package/dist/audit/diff.js +70 -160
  10. package/dist/audit/processQueue.js +25 -70
  11. package/dist/audit/rbacSink.js +25 -66
  12. package/dist/audit/record.js +129 -251
  13. package/dist/auth.js +432 -681
  14. package/dist/authRecovery.js +155 -269
  15. package/dist/authTokens.js +43 -118
  16. package/dist/betterAuthApp.js +25 -26
  17. package/dist/betterAuthSetup.js +258 -413
  18. package/dist/browserLogsRoute.d.ts +6 -0
  19. package/dist/browserLogsRoute.js +97 -0
  20. package/dist/collectionRegistry.js +32 -47
  21. package/dist/config.js +53 -122
  22. package/dist/configurationApp.js +180 -361
  23. package/dist/configurationPlugin.js +130 -302
  24. package/dist/consentApp.js +276 -421
  25. package/dist/docLoader.js +78 -126
  26. package/dist/envConfigurationPlugin.js +25 -147
  27. package/dist/errors.js +151 -247
  28. package/dist/example.js +28 -34
  29. package/dist/expressServer.d.ts +10 -0
  30. package/dist/expressServer.js +109 -255
  31. package/dist/frameworkModelNames.d.ts +24 -0
  32. package/dist/frameworkModelNames.js +31 -0
  33. package/dist/githubAuth.js +152 -216
  34. package/dist/httpClient.js +176 -264
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.js +7 -2
  37. package/dist/logger.js +145 -278
  38. package/dist/mcp/auth.js +76 -128
  39. package/dist/mcp/createMCPRequest.js +4 -5
  40. package/dist/mcp/handlers.js +268 -480
  41. package/dist/mcp/query.js +56 -150
  42. package/dist/mcp/registry.js +17 -30
  43. package/dist/mcp/schemaGenerator.js +95 -181
  44. package/dist/mcp/server.js +28 -100
  45. package/dist/mcp/serviceTokens.js +102 -191
  46. package/dist/mcp/toolGenerator.js +78 -191
  47. package/dist/middleware.js +15 -27
  48. package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
  49. package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
  50. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
  51. package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
  52. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
  53. package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
  54. package/dist/migrations/generate.js +107 -229
  55. package/dist/migrations/load.js +75 -201
  56. package/dist/migrations/lock.js +54 -126
  57. package/dist/migrations/runner.js +192 -446
  58. package/dist/migrations/schemaCatalog.js +122 -263
  59. package/dist/models/consentForm.js +6 -6
  60. package/dist/models/consentResponse.js +5 -5
  61. package/dist/models/mcpServiceToken.js +66 -156
  62. package/dist/models/notification.js +6 -6
  63. package/dist/models/notificationPreference.js +6 -6
  64. package/dist/models/versionConfig.js +5 -5
  65. package/dist/notifications/notificationService.js +133 -273
  66. package/dist/notifications/notificationsApp.js +85 -179
  67. package/dist/notifications/notificationsBeforeSend.js +19 -64
  68. package/dist/notifiers/googleChatNotifier.js +36 -117
  69. package/dist/notifiers/slackNotifier.d.ts +31 -2
  70. package/dist/notifiers/slackNotifier.js +170 -119
  71. package/dist/notifiers/zoomNotifier.js +60 -111
  72. package/dist/openApi.js +107 -122
  73. package/dist/openApiBuilder.js +117 -159
  74. package/dist/openApiCompat.js +81 -148
  75. package/dist/openApiEtag.js +7 -7
  76. package/dist/openApiValidator.js +177 -286
  77. package/dist/orgs/orgContext.js +87 -157
  78. package/dist/orgs/orgPermissions.js +29 -68
  79. package/dist/orgs/orgPlugin.js +9 -27
  80. package/dist/orgs/organizationModel.js +65 -166
  81. package/dist/orgs/organizationSettings.js +29 -36
  82. package/dist/orgs/orgsApp.js +346 -608
  83. package/dist/permissions.js +88 -181
  84. package/dist/plugins.js +125 -218
  85. package/dist/populate.js +130 -240
  86. package/dist/rateLimit/applyTrustProxy.js +1 -1
  87. package/dist/rateLimit/createStore.js +7 -8
  88. package/dist/rateLimit/memoryStore.js +22 -100
  89. package/dist/rateLimit/middleware.js +48 -99
  90. package/dist/rateLimit/mongoStore.js +54 -112
  91. package/dist/rateLimit/policies.js +41 -75
  92. package/dist/rateLimit/redisStore.js +39 -133
  93. package/dist/rbac/access.js +119 -267
  94. package/dist/rbac/assertAllowed.js +95 -171
  95. package/dist/rbac/auditModel.js +14 -58
  96. package/dist/rbac/backfillAdmins.js +24 -130
  97. package/dist/rbac/fieldViews.js +46 -141
  98. package/dist/rbac/membershipOrgAdminSource.js +28 -99
  99. package/dist/rbac/middleware.js +30 -96
  100. package/dist/rbac/modelRouterAccess.js +130 -307
  101. package/dist/rbac/permissionUtils.js +40 -179
  102. package/dist/rbac/realtimeAccess.js +81 -147
  103. package/dist/rbac/resolve.d.ts +1 -1
  104. package/dist/rbac/resolve.js +148 -342
  105. package/dist/rbac/roleManager.js +318 -700
  106. package/dist/rbac/roleModel.js +44 -171
  107. package/dist/rbac/routes.js +93 -196
  108. package/dist/rbac/scopes.js +39 -133
  109. package/dist/rbac/statements.js +23 -91
  110. package/dist/rbac/userPlugin.js +3 -29
  111. package/dist/realtime/changeStreamWatcher.js +489 -800
  112. package/dist/realtime/deprecation.js +8 -10
  113. package/dist/realtime/queryMatcher.js +110 -191
  114. package/dist/realtime/queryStore.js +35 -118
  115. package/dist/realtime/realtimeApp.js +247 -401
  116. package/dist/realtime/registry.js +19 -30
  117. package/dist/realtime/sessionRevalidation.js +132 -358
  118. package/dist/realtime/socketAuth.js +89 -208
  119. package/dist/realtime/socketUser.js +10 -56
  120. package/dist/requestContext.js +93 -139
  121. package/dist/schemaMetadata.js +179 -274
  122. package/dist/scriptRunner.js +96 -266
  123. package/dist/scrubAdminFields.js +36 -108
  124. package/dist/secretProviders.js +130 -299
  125. package/dist/seedRunner.js +221 -514
  126. package/dist/sync/adminBroadcastScope.js +58 -170
  127. package/dist/sync/adminWindowAccess.js +15 -86
  128. package/dist/sync/adminWindowMutation.js +110 -181
  129. package/dist/sync/executors.js +425 -629
  130. package/dist/sync/loadHarness.js +392 -689
  131. package/dist/sync/models.js +181 -341
  132. package/dist/sync/mutationHandler.js +533 -801
  133. package/dist/sync/registrationSideEffects.js +41 -95
  134. package/dist/sync/registry.js +29 -49
  135. package/dist/sync/routes.js +484 -817
  136. package/dist/sync/scripts/compactTombstones.js +83 -228
  137. package/dist/sync/serialize.js +18 -58
  138. package/dist/sync/socketHandlers.js +253 -478
  139. package/dist/sync/streams.js +49 -117
  140. package/dist/sync/syncApp.js +12 -15
  141. package/dist/sync/syncBatch.js +63 -168
  142. package/dist/sync/syncSeqPlugin.js +430 -702
  143. package/dist/syncConsents.js +113 -253
  144. package/dist/terrenoApp.js +166 -276
  145. package/dist/tests/createTestData.js +146 -256
  146. package/dist/tests/models.js +14 -54
  147. package/dist/tests/mongoTestSetup.js +42 -103
  148. package/dist/tests/testHelper.js +31 -93
  149. package/dist/tests.js +12 -51
  150. package/dist/transformers.js +61 -164
  151. package/dist/utils.js +31 -93
  152. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  153. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  154. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  155. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  156. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  157. package/dist/versionCheckPlugin.js +52 -100
  158. package/dist/webhooks/headerValue.js +2 -2
  159. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  160. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  161. package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
  162. package/dist/webhooks/rawBody.js +1 -1
  163. package/dist/webhooks/timingSafeEqual.js +4 -5
  164. package/dist/webhooks/verifiers/hmac.js +17 -18
  165. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  166. package/dist/webhooks/verifiers/stripe.js +31 -65
  167. package/dist/webhooks/verifiers/twilio.js +23 -73
  168. package/dist/webhooks/webhooksApp.js +78 -177
  169. package/dist/zodOpenApi.js +2 -2
  170. package/package.json +6 -6
  171. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  172. package/src/audit/auditApp.test.ts +5 -5
  173. package/src/audit/auditEventModel.ts +7 -3
  174. package/src/audit/auditRouter.test.ts +5 -5
  175. package/src/audit/rbacSink.test.ts +2 -2
  176. package/src/audit/record.test.ts +2 -2
  177. package/src/audit/record.ts +3 -2
  178. package/src/auth.ts +1 -1
  179. package/src/authRecovery.test.ts +43 -0
  180. package/src/authRecovery.ts +16 -10
  181. package/src/authTokens.ts +6 -2
  182. package/src/authVerification.test.ts +22 -0
  183. package/src/browserLogsRoute.ts +110 -0
  184. package/src/configurationPlugin.test.ts +1 -11
  185. package/src/expressServer.ts +10 -0
  186. package/src/frameworkModelNames.test.ts +62 -0
  187. package/src/frameworkModelNames.ts +33 -0
  188. package/src/index.ts +7 -0
  189. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  190. package/src/mcp/auth.test.ts +34 -1
  191. package/src/migrations/cli.test.ts +0 -23
  192. package/src/models/mcpServiceToken.ts +4 -3
  193. package/src/models/notification.ts +3 -2
  194. package/src/models/notificationPreference.ts +1 -1
  195. package/src/notifications/notificationsApp.test.ts +24 -1
  196. package/src/notifiers/slackNotifier.test.ts +186 -1
  197. package/src/notifiers/slackNotifier.ts +167 -8
  198. package/src/orgs/orgPlugin.ts +1 -1
  199. package/src/orgs/organizationModel.ts +11 -6
  200. package/src/plugins.test.ts +5 -0
  201. package/src/plugins.ts +3 -0
  202. package/src/realtime/realtimeApp.ts +1 -1
  203. package/src/sync/integration.test.ts +2 -2
  204. package/src/terrenoApp.ts +3 -0
  205. package/src/types.d.ts +1 -0
  206. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  207. package/tsconfig.json +13 -54
  208. package/tsconfig.typedoc.json +2 -0
@@ -1,102 +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 orgContext_1 = require("../orgs/orgContext");
86
- var plugins_1 = require("../plugins");
87
- var adminWindowMutation_1 = require("./adminWindowMutation");
88
- var executors_1 = require("./executors");
89
- var models_1 = require("./models");
90
- var registry_1 = require("./registry");
91
- var routes_1 = require("./routes");
92
- 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");
93
19
  /**
94
20
  * Per-mutation success traces (`Mutation applied`) are high-volume. Gate them behind
95
21
  * `SYNC_DEBUG=true` so they stay silent by default even when Winston's console level is
96
22
  * `debug`.
97
23
  */
98
- var syncDebugLog = (0, logger_1.createFeatureFlaggedLogger)({
99
- isEnabled: function () { return process.env.SYNC_DEBUG === "true"; },
24
+ const syncDebugLog = (0, logger_1.createFeatureFlaggedLogger)({
25
+ isEnabled: () => process.env.SYNC_DEBUG === "true",
100
26
  });
101
27
  /**
102
28
  * C6 (M6): enforce write scope at the sync boundary regardless of consumer `preCreate`
@@ -105,74 +31,64 @@ var syncDebugLog = (0, logger_1.createFeatureFlaggedLogger)({
105
31
  * memberships. Throws a 403 APIError (mapped to `unauthorized`) otherwise. A no-op for
106
32
  * broadcast/custom scopes and for update data that does not touch the scope field.
107
33
  */
108
- var enforceWriteScope = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
109
- var scope, field, incoming, memberships;
110
- var entry = _b.entry, user = _b.user, operation = _b.operation, data = _b.data, scopeResolver = _b.scopeResolver;
111
- return __generator(this, function (_c) {
112
- switch (_c.label) {
113
- case 0:
114
- if (operation === "delete") {
115
- return [2 /*return*/];
116
- }
117
- scope = entry.config.scope;
118
- if (typeof scope === "function" || scope.type === "broadcast") {
119
- return [2 /*return*/];
120
- }
121
- field = (0, streams_1.getScopeField)(scope);
122
- incoming = data === null || data === void 0 ? void 0 : data[field];
123
- if (scope.type === "owner") {
124
- // Create must belong to the caller; an update may not move ownership to someone else.
125
- if (operation === "create" && (incoming === undefined || incoming === null)) {
126
- // preCreate typically injects ownerId; nothing to verify if absent here.
127
- return [2 /*return*/];
128
- }
129
- if (incoming !== undefined && incoming !== null && String(incoming) !== String(user.id)) {
130
- throw new errors_1.APIError({
131
- status: 403,
132
- title: "Write scope violation on ".concat(entry.collectionTag, ": ").concat(field, " must be the caller"),
133
- });
134
- }
135
- return [2 /*return*/];
136
- }
137
- // Tenant: the incoming value (create) or the changed value (update) must be a membership.
138
- if (incoming === undefined || incoming === null) {
139
- // Nothing to check against memberships yet. A create may legitimately omit the tenant
140
- // field for `preCreate` to inject from the authenticated user (see the example
141
- // projects router), and an update that does not touch the scope field leaves it
142
- // alone. Task 9.21's "never file a document under `tenant:undefined`" guarantee is
143
- // enforced by resolveStreamForDoc on the write path instead, which sees the value
144
- // AFTER preCreate has run — inferring intent from the mere presence of a preCreate
145
- // hook would let an unrelated one (logging, timestamps) silently reopen that hole.
146
- return [2 /*return*/];
147
- }
148
- if (!scopeResolver) {
149
- throw new errors_1.APIError({
150
- status: 500,
151
- title: "Sync collection ".concat(entry.collectionTag, " is tenant-scoped but SyncApp has no getUserScopes resolver"),
152
- });
153
- }
154
- return [4 /*yield*/, scopeResolver(user, entry)];
155
- case 1:
156
- memberships = _c.sent();
157
- if (!memberships.map(String).includes(String(incoming))) {
158
- throw new errors_1.APIError({
159
- status: 403,
160
- title: "Write scope violation on ".concat(entry.collectionTag, ": ").concat(field, " ").concat(String(incoming), " is not a membership"),
161
- });
162
- }
163
- 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;
164
49
  }
165
- });
166
- }); };
167
- var PENDING_POLL_ATTEMPTS = 10;
168
- var PENDING_POLL_INTERVAL_MS = 100;
169
- 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"]);
170
86
  /** Maximum mutations accepted in a single `sync:mutateBatch` / `POST /sync/mutate/batch` request. */
171
87
  exports.MAX_SYNC_MUTATIONS_PER_BATCH = 100;
172
- var sleep = function (ms) { return new Promise(function (resolve) { return setTimeout(resolve, ms); }); };
173
- var makeNack = function (nack) {
88
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
89
+ const makeNack = (nack) => {
174
90
  logger_1.logger.info("[sync] Mutation nacked", { code: nack.code, mutationId: nack.mutationId });
175
- return { nack: nack, type: "nack" };
91
+ return { nack, type: "nack" };
176
92
  };
177
93
  /**
178
94
  * Load a document by id INCLUDING tombstones (`isDeletedPlugin` would otherwise filter a
@@ -180,40 +96,28 @@ var makeNack = function (nack) {
180
96
  * document is gone, the id does not cast, or the consumer's serializer throws — callers
181
97
  * treat a missing `serverDoc` as "seq only", which is what the client needs to re-base.
182
98
  */
183
- var serializeLiveDoc = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
184
- var model, found, doc, error_1;
185
- var entry = _b.entry, id = _b.id, request = _b.request;
186
- return __generator(this, function (_c) {
187
- switch (_c.label) {
188
- case 0:
189
- if (!id) {
190
- return [2 /*return*/, undefined];
191
- }
192
- _c.label = 1;
193
- case 1:
194
- _c.trys.push([1, 4, , 5]);
195
- model = mongoose_1.default.model(entry.modelName);
196
- return [4 /*yield*/, model.find({ _id: id, deleted: { $in: [true, false] } }).limit(1)];
197
- case 2:
198
- found = _c.sent();
199
- doc = found[0];
200
- if (!doc) {
201
- return [2 /*return*/, undefined];
202
- }
203
- return [4 /*yield*/, (0, routes_1.serializeSyncDoc)({ doc: doc, entry: entry, req: request })];
204
- case 3: return [2 /*return*/, _c.sent()];
205
- case 4:
206
- error_1 = _c.sent();
207
- logger_1.logger.warn("[sync] Failed to serialize the server doc for a recorded conflict", {
208
- collection: entry.collectionTag,
209
- error: String(error_1),
210
- id: id,
211
- });
212
- return [2 /*return*/, undefined];
213
- 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;
214
109
  }
215
- });
216
- }); };
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
+ };
217
121
  /**
218
122
  * Reconstruct the outcome recorded on a finalized ledger row; undefined while pending.
219
123
  *
@@ -222,43 +126,31 @@ var serializeLiveDoc = function (_a) { return __awaiter(void 0, [_a], void 0, fu
222
126
  * `syncmutations` for the ledger's 30-day TTL, this hands the client current server
223
127
  * state rather than a snapshot frozen at first-conflict time.
224
128
  */
225
- var outcomeFromLedgerRow = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
226
- var _c;
227
- var _d;
228
- var _e, _f, _g;
229
- var entry = _b.entry, request = _b.request, row = _b.row;
230
- return __generator(this, function (_h) {
231
- switch (_h.label) {
232
- case 0:
233
- if (row.status === "applied") {
234
- return [2 /*return*/, {
235
- ack: { id: (_e = row.resultId) !== null && _e !== void 0 ? _e : "", mutationId: row.mutationId, seq: (_f = row.resultSeq) !== null && _f !== void 0 ? _f : 0 },
236
- type: "ack",
237
- }];
238
- }
239
- if (!(row.status === "conflicted")) return [3 /*break*/, 2];
240
- _c = makeNack;
241
- _d = {
242
- code: "conflict",
243
- message: row.error,
244
- mutationId: row.mutationId
245
- };
246
- return [4 /*yield*/, serializeLiveDoc({ entry: entry, id: row.resultId, request: request })];
247
- case 1: return [2 /*return*/, _c.apply(void 0, [(_d.serverDoc = _h.sent(),
248
- _d.serverSeq = row.resultSeq,
249
- _d)])];
250
- case 2:
251
- if (row.status === "failed") {
252
- return [2 /*return*/, makeNack({
253
- code: (_g = row.nackCode) !== null && _g !== void 0 ? _g : "error",
254
- message: row.error,
255
- mutationId: row.mutationId,
256
- })];
257
- }
258
- return [2 /*return*/, undefined];
259
- }
260
- });
261
- }); };
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
+ };
262
154
  /**
263
155
  * C5 (FIX 6) lease takeover: a `pending` row older than {@link SYNC_MUTATION_LEASE_MS}
264
156
  * is assumed abandoned (the original claimant crashed between claiming the row and
@@ -267,19 +159,11 @@ var outcomeFromLedgerRow = function (_a) { return __awaiter(void 0, [_a], void 0
267
159
  * `claimedAt`) on success, or `undefined` if the row is not stale/pending (someone else
268
160
  * is actively working it, or it already finalized).
269
161
  */
270
- var takeoverStaleLease = function (mutationId) { return __awaiter(void 0, void 0, void 0, function () {
271
- var cutoff, claimed;
272
- return __generator(this, function (_a) {
273
- switch (_a.label) {
274
- case 0:
275
- cutoff = luxon_1.DateTime.now().minus({ milliseconds: models_1.SYNC_MUTATION_LEASE_MS }).toJSDate();
276
- return [4 /*yield*/, models_1.SyncMutation.findOneAndUpdate({ claimedAt: { $lt: cutoff }, mutationId: mutationId, status: "pending" }, { $set: { claimedAt: luxon_1.DateTime.now().toJSDate() } }, { new: true })];
277
- case 1:
278
- claimed = _a.sent();
279
- return [2 /*return*/, claimed !== null && claimed !== void 0 ? claimed : undefined];
280
- }
281
- });
282
- }); };
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
+ };
283
167
  /**
284
168
  * Another delivery claimed this mutationId: poll the ledger row until its status leaves
285
169
  * `pending` and return the recorded outcome. Before each poll, attempt a lease takeover
@@ -289,73 +173,53 @@ var takeoverStaleLease = function (mutationId) { return __awaiter(void 0, void 0
289
173
  * pending and un-stale past the timeout, nack `error` without modifying the row — the
290
174
  * owning delivery will still finalize it.
291
175
  */
292
- var waitForRecordedOutcome = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
293
- var attempt, row, outcome, takenOver;
294
- var entry = _b.entry, mutationId = _b.mutationId, request = _b.request, user = _b.user, onTakeover = _b.onTakeover;
295
- return __generator(this, function (_c) {
296
- switch (_c.label) {
297
- case 0:
298
- attempt = 0;
299
- _c.label = 1;
300
- case 1:
301
- if (!(attempt < PENDING_POLL_ATTEMPTS)) return [3 /*break*/, 8];
302
- return [4 /*yield*/, (0, plugins_1.findOneOrNoneFor)(models_1.SyncMutation, { mutationId: mutationId })];
303
- case 2:
304
- row = _c.sent();
305
- if (!row) return [3 /*break*/, 5];
306
- if (String(row.userId) !== String(user.id)) {
307
- return [2 /*return*/, makeNack({
308
- code: "unauthorized",
309
- message: "Mutation ".concat(mutationId, " was submitted by another user"),
310
- mutationId: mutationId,
311
- })];
312
- }
313
- return [4 /*yield*/, outcomeFromLedgerRow({ entry: entry, request: request, row: row })];
314
- case 3:
315
- outcome = _c.sent();
316
- if (outcome) {
317
- return [2 /*return*/, outcome];
318
- }
319
- if (!(row.status === "pending")) return [3 /*break*/, 5];
320
- return [4 /*yield*/, takeoverStaleLease(mutationId)];
321
- case 4:
322
- 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);
323
193
  if (takenOver) {
324
194
  logger_1.logger.warn("[sync] Took over a stale mutation lease", {
325
- mutationId: mutationId,
195
+ mutationId,
326
196
  staleForMs: luxon_1.DateTime.now().diff(luxon_1.DateTime.fromJSDate(row.claimedAt)).toMillis(),
327
197
  });
328
- return [2 /*return*/, onTakeover(takenOver)];
198
+ return onTakeover(takenOver);
329
199
  }
330
- _c.label = 5;
331
- case 5: return [4 /*yield*/, sleep(PENDING_POLL_INTERVAL_MS)];
332
- case 6:
333
- _c.sent();
334
- _c.label = 7;
335
- case 7:
336
- attempt++;
337
- return [3 /*break*/, 1];
338
- case 8: return [2 /*return*/, makeNack({
339
- code: "error",
340
- message: "Mutation ".concat(mutationId, " is still in flight"),
341
- mutationId: mutationId,
342
- })];
200
+ }
343
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,
344
208
  });
345
- }); };
209
+ };
346
210
  /**
347
211
  * C5 (FIX 6): true when `error` is (or wraps, via `APIError.error` — see
348
212
  * `executeCreate`'s `model.create()` catch, which wraps the raw Mongo driver
349
213
  * error in an APIError before it ever reaches the caller) a MongoDB E11000
350
214
  * duplicate-key error.
351
215
  */
352
- var isE11000Error = function (error) {
353
- var candidate = error;
354
- if ((candidate === null || candidate === void 0 ? void 0 : candidate.code) === 11000) {
216
+ const isE11000Error = (error) => {
217
+ const candidate = error;
218
+ if (candidate?.code === 11000) {
355
219
  return true;
356
220
  }
357
- var wrapped = candidate === null || candidate === void 0 ? void 0 : candidate.error;
358
- return (wrapped === null || wrapped === void 0 ? void 0 : wrapped.code) === 11000;
221
+ const wrapped = candidate?.error;
222
+ return wrapped?.code === 11000;
359
223
  };
360
224
  /**
361
225
  * C5 (FIX 6): true when every key/value in `data` (the mutation's own
@@ -365,19 +229,18 @@ var isE11000Error = function (error) {
365
229
  * different write landed and happens to have advanced the seq by exactly
366
230
  * one" (a real conflict; a seq match alone cannot tell these apart).
367
231
  */
368
- var docMatchesMutationData = function (doc, data) {
232
+ const docMatchesMutationData = (doc, data) => {
369
233
  if (!data) {
370
234
  return true;
371
235
  }
372
- var asDocument = doc;
373
- var plain = typeof (asDocument === null || asDocument === void 0 ? void 0 : asDocument.toObject) === "function"
236
+ const asDocument = doc;
237
+ const plain = typeof asDocument?.toObject === "function"
374
238
  ? asDocument.toObject()
375
239
  : doc;
376
- return Object.entries(data).every(function (_a) {
377
- var _b = __read(_a, 2), key = _b[0], value = _b[1];
378
- var current = plain === null || plain === void 0 ? void 0 : plain[key];
240
+ return Object.entries(data).every(([key, value]) => {
241
+ const current = plain?.[key];
379
242
  if (current instanceof Date && typeof value === "string") {
380
- var parsed = luxon_1.DateTime.fromISO(value, { zone: "utc" });
243
+ const parsed = luxon_1.DateTime.fromISO(value, { zone: "utc" });
381
244
  if (!parsed.isValid) {
382
245
  return false;
383
246
  }
@@ -387,7 +250,7 @@ var docMatchesMutationData = function (doc, data) {
387
250
  });
388
251
  };
389
252
  exports.docMatchesMutationData = docMatchesMutationData;
390
- var nackCodeForError = function (error) {
253
+ const nackCodeForError = (error) => {
391
254
  if (!(0, errors_1.isAPIError)(error)) {
392
255
  return "error";
393
256
  }
@@ -400,89 +263,66 @@ var nackCodeForError = function (error) {
400
263
  return "error";
401
264
  };
402
265
  /** Record a failed/conflicted outcome on the claimed ledger row and build the nack. */
403
- var finalizeNack = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
404
- var serverDoc, serializeError_1, resultId, code, message;
405
- var _c;
406
- var claimedId = _b.claimedId, entry = _b.entry, error = _b.error, mutation = _b.mutation, request = _b.request;
407
- return __generator(this, function (_d) {
408
- switch (_d.label) {
409
- case 0:
410
- if (!(0, executors_1.isExecutorConflictError)(error)) return [3 /*break*/, 6];
411
- serverDoc = void 0;
412
- _d.label = 1;
413
- case 1:
414
- _d.trys.push([1, 3, , 4]);
415
- return [4 /*yield*/, (0, routes_1.serializeSyncDoc)({
416
- doc: error.doc,
417
- entry: entry,
418
- req: request,
419
- })];
420
- case 2:
421
- serverDoc = _d.sent();
422
- return [3 /*break*/, 4];
423
- case 3:
424
- serializeError_1 = _d.sent();
425
- logger_1.logger.warn("[sync] Failed to serialize conflict server doc", {
426
- error: String(serializeError_1),
427
- mutationId: mutation.mutationId,
428
- });
429
- return [3 /*break*/, 4];
430
- case 4:
431
- resultId = ((_c = error.doc) === null || _c === void 0 ? void 0 : _c._id) !== undefined
432
- ? String(error.doc._id)
433
- : mutation.id;
434
- return [4 /*yield*/, models_1.SyncMutation.updateOne({ _id: claimedId }, {
435
- $set: {
436
- error: error.title,
437
- nackCode: "conflict",
438
- resultId: resultId,
439
- resultSeq: error.serverSeq,
440
- status: "conflicted",
441
- },
442
- })];
443
- case 5:
444
- _d.sent();
445
- return [2 /*return*/, makeNack({
446
- code: "conflict",
447
- message: error.title,
448
- mutationId: mutation.mutationId,
449
- serverDoc: serverDoc,
450
- serverSeq: error.serverSeq,
451
- })];
452
- case 6:
453
- code = nackCodeForError(error);
454
- message = (0, errors_1.isAPIError)(error) ? error.title : String(error);
455
- if (!(code === "error")) return [3 /*break*/, 8];
456
- logger_1.logger.warn("[sync] Mutation failed unexpectedly", {
457
- collection: mutation.collection,
458
- error: message,
459
- mutationId: mutation.mutationId,
460
- });
461
- // Task 9.18: an `error`-class failure is non-deterministic (DB hiccup, replica
462
- // step-down) — it is not a verdict on the mutation. Recording it `failed` would make
463
- // it sticky for the ledger's 30-day TTL, so every replay of the same mutationId reads
464
- // the nack back and the client's durable outbox retries forever without the mutation
465
- // ever re-executing. Release the claim instead: the next delivery re-claims the
466
- // mutationId and genuinely re-runs the write. Deterministic outcomes
467
- // (validation/unauthorized/conflict) stay recorded — replaying those must not re-run.
468
- return [4 /*yield*/, models_1.SyncMutation.deleteOne({ _id: claimedId })];
469
- case 7:
470
- // Task 9.18: an `error`-class failure is non-deterministic (DB hiccup, replica
471
- // step-down) — it is not a verdict on the mutation. Recording it `failed` would make
472
- // it sticky for the ledger's 30-day TTL, so every replay of the same mutationId reads
473
- // the nack back and the client's durable outbox retries forever without the mutation
474
- // ever re-executing. Release the claim instead: the next delivery re-claims the
475
- // mutationId and genuinely re-runs the write. Deterministic outcomes
476
- // (validation/unauthorized/conflict) stay recorded — replaying those must not re-run.
477
- _d.sent();
478
- return [2 /*return*/, makeNack({ code: code, message: message, mutationId: mutation.mutationId })];
479
- case 8: return [4 /*yield*/, models_1.SyncMutation.updateOne({ _id: claimedId }, { $set: { error: message, nackCode: code, status: "failed" } })];
480
- case 9:
481
- _d.sent();
482
- 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
+ });
483
276
  }
484
- });
485
- }); };
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
+ };
486
326
  /**
487
327
  * C5 (FIX 6): read the doc back and report it as the ack for an ALREADY-APPLIED write —
488
328
  * used both by the create-E11000 tolerance and the update/delete already-applied check.
@@ -490,27 +330,17 @@ var finalizeNack = function (_a) { return __awaiter(void 0, [_a], void 0, functi
490
330
  * returning, exactly like the normal apply path, so a subsequent duplicate delivery
491
331
  * reads back the same outcome.
492
332
  */
493
- var finalizeAlreadyApplied = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
494
- var resultId, resultSeq;
495
- var _c;
496
- var claimedId = _b.claimedId, doc = _b.doc, mutation = _b.mutation;
497
- return __generator(this, function (_d) {
498
- switch (_d.label) {
499
- case 0:
500
- resultId = String(doc._id);
501
- resultSeq = (_c = doc._syncSeq) !== null && _c !== void 0 ? _c : 0;
502
- return [4 /*yield*/, models_1.SyncMutation.updateOne({ _id: claimedId }, { $set: { resultId: resultId, resultSeq: resultSeq, status: "applied" } })];
503
- case 1:
504
- _d.sent();
505
- logger_1.logger.info("[sync] Mutation already applied (lease-takeover tolerance)", {
506
- collection: mutation.collection,
507
- mutationId: mutation.mutationId,
508
- seq: resultSeq,
509
- });
510
- return [2 /*return*/, { resultId: resultId, resultSeq: resultSeq }];
511
- }
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,
512
341
  });
513
- }); };
342
+ return { resultId, resultSeq };
343
+ };
514
344
  /**
515
345
  * Apply a client mutation through the transport-agnostic executors (permissions,
516
346
  * pre/post hooks, validation) against an ALREADY-CLAIMED ledger row (either a fresh claim
@@ -535,367 +365,311 @@ var finalizeAlreadyApplied = function (_a) { return __awaiter(void 0, [_a], void
535
365
  * - delete: idempotent already (executeDelete on an already-deleted tombstone is a no-op
536
366
  * success in this codebase's soft-delete model), so no special tolerance is needed.
537
367
  */
538
- var organizationIdFromRequest = function (request) {
368
+ const organizationIdFromRequest = (request) => {
539
369
  if (typeof request.header !== "function") {
540
370
  return undefined;
541
371
  }
542
- var raw = request.header("X-Organization-Id");
372
+ const raw = request.header("X-Organization-Id");
543
373
  if (typeof raw !== "string") {
544
374
  return undefined;
545
375
  }
546
- var trimmed = raw.trim();
376
+ const trimmed = raw.trim();
547
377
  if (!trimmed) {
548
378
  return undefined;
549
379
  }
550
380
  return trimmed;
551
381
  };
552
- var withRequestOrgContext = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
553
- var organizationId, context;
554
- var request = _b.request, run = _b.run, user = _b.user;
555
- return __generator(this, function (_c) {
556
- switch (_c.label) {
557
- case 0:
558
- organizationId = organizationIdFromRequest(request);
559
- if (!organizationId) {
560
- return [2 /*return*/, run()];
561
- }
562
- return [4 /*yield*/, (0, orgContext_1.resolveOrgContext)({ organizationId: organizationId, required: false, user: user })];
563
- case 1:
564
- context = _c.sent();
565
- return [2 /*return*/, (0, orgContext_1.runWithOrgContext)(context, run)];
566
- }
567
- });
568
- }); };
569
- var applyClaimedMutation = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
570
- var claimed = _b.claimed, entry = _b.entry, mutation = _b.mutation, request = _b.request, user = _b.user, scopeResolver = _b.scopeResolver, syncOptions = _b.syncOptions, _c = _b.isLeaseTakeover, isLeaseTakeover = _c === void 0 ? false : _c;
571
- return __generator(this, function (_d) {
572
- return [2 /*return*/, withRequestOrgContext({
573
- request: request,
574
- run: function () {
575
- return applyClaimedMutationInContext({
576
- claimed: claimed,
577
- entry: entry,
578
- isLeaseTakeover: isLeaseTakeover,
579
- mutation: mutation,
580
- request: request,
581
- scopeResolver: scopeResolver,
582
- syncOptions: syncOptions,
583
- user: user,
584
- });
585
- },
586
- user: user,
587
- })];
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,
588
404
  });
589
- }); };
590
- var applyClaimedMutationInContext = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
591
- var mutationId, adminWindowScope, model, adminWindow, effectiveMutation, skipPermissionChecks, executorOptions_1, executorRequest_1, 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, auditError_1, error_2;
592
- var _e, _f, _g, _h, _j;
593
- var claimed = _b.claimed, entry = _b.entry, mutation = _b.mutation, request = _b.request, user = _b.user, scopeResolver = _b.scopeResolver, syncOptions = _b.syncOptions, _k = _b.isLeaseTakeover, isLeaseTakeover = _k === void 0 ? false : _k;
594
- return __generator(this, function (_l) {
595
- switch (_l.label) {
596
- case 0:
597
- mutationId = mutation.mutationId;
598
- _l.label = 1;
599
- case 1:
600
- _l.trys.push([1, 32, , 33]);
601
- model = mongoose_1.default.model(entry.modelName);
602
- return [4 /*yield*/, (0, adminWindowMutation_1.prepareAdminWindowMutation)({
603
- entry: entry,
604
- mutation: mutation,
605
- req: request,
606
- syncOptions: syncOptions,
607
- user: user,
608
- })];
609
- case 2:
610
- adminWindow = _l.sent();
611
- effectiveMutation = mutation;
612
- if (!adminWindow) return [3 /*break*/, 3];
613
- effectiveMutation = adminWindow.mutation;
614
- adminWindowScope = adminWindow.scope;
615
- return [3 /*break*/, 5];
616
- case 3:
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 {
617
427
  // C6 (M6): product-path write-scope backstop before any write pipeline runs.
618
- return [4 /*yield*/, enforceWriteScope({
619
- data: effectiveMutation.data,
620
- entry: entry,
621
- operation: effectiveMutation.operation,
622
- scopeResolver: scopeResolver,
623
- user: user,
624
- })];
625
- case 4:
626
- // C6 (M6): product-path write-scope backstop before any write pipeline runs.
627
- _l.sent();
628
- _l.label = 5;
629
- case 5:
630
- skipPermissionChecks = Boolean(adminWindowScope);
631
- executorOptions_1 = adminWindowScope
632
- ? (0, adminWindowMutation_1.buildAdminWindowExecutorOptions)({ productOptions: entry.options, scope: adminWindowScope })
633
- : entry.options;
634
- executorRequest_1 = adminWindowScope
635
- ? (0, adminWindowMutation_1.withAdminWindowMutationRequestContext)({ mutation: effectiveMutation, req: request })
636
- : request;
637
- doc = void 0;
638
- postHook = void 0;
639
- if (!(effectiveMutation.operation === "create")) return [3 /*break*/, 13];
640
- body = __assign({}, ((_e = effectiveMutation.data) !== null && _e !== void 0 ? _e : {}));
641
- if (effectiveMutation.id) {
642
- body._id = effectiveMutation.id;
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
+ }
643
483
  }
644
- _l.label = 6;
645
- case 6:
646
- _l.trys.push([6, 8, , 12]);
647
- return [4 /*yield*/, (0, executors_1.executeCreate)({
648
- body: body,
649
- model: model,
650
- options: executorOptions_1,
651
- req: executorRequest_1,
652
- skipPermissionChecks: skipPermissionChecks,
653
- skipPostHooks: true,
654
- user: user,
655
- })];
656
- case 7:
657
- result_1 = _l.sent();
658
- doc = result_1.doc;
659
- postHook = function () {
660
- return (0, executors_1.runPostCreate)({ doc: result_1.doc, options: executorOptions_1, request: executorRequest_1 });
661
- };
662
- return [3 /*break*/, 12];
663
- case 8:
664
- createError_1 = _l.sent();
665
- if (!(isLeaseTakeover &&
666
- isE11000Error(createError_1) &&
667
- typeof effectiveMutation.id === "string")) return [3 /*break*/, 11];
668
- return [4 /*yield*/, (0, plugins_1.findOneOrNoneFor)(model, { _id: effectiveMutation.id })];
669
- case 9:
670
- existing = _l.sent();
671
- if (!existing) return [3 /*break*/, 11];
672
- return [4 /*yield*/, finalizeAlreadyApplied({
673
- claimedId: claimed._id,
674
- doc: existing,
675
- mutation: mutation,
676
- })];
677
- case 10:
678
- _c = _l.sent(), resultId_1 = _c.resultId, resultSeq_1 = _c.resultSeq;
679
- return [2 /*return*/, { ack: { id: resultId_1, mutationId: mutationId, seq: resultSeq_1 }, type: "ack" }];
680
- case 11: throw createError_1;
681
- case 12: return [3 /*break*/, 22];
682
- case 13:
683
- if (!(effectiveMutation.operation === "update")) return [3 /*break*/, 20];
684
- _l.label = 14;
685
- case 14:
686
- _l.trys.push([14, 16, , 19]);
687
- return [4 /*yield*/, (0, executors_1.executeUpdate)({
688
- body: (_f = effectiveMutation.data) !== null && _f !== void 0 ? _f : {},
689
- concurrencyCheck: { baseSeq: (_g = effectiveMutation.baseVersion) !== null && _g !== void 0 ? _g : 0, type: "seq" },
690
- id: effectiveMutation.id,
691
- model: model,
692
- options: executorOptions_1,
693
- req: executorRequest_1,
694
- skipPermissionChecks: skipPermissionChecks,
695
- skipPostHooks: true,
696
- user: user,
697
- })];
698
- case 15:
699
- result_2 = _l.sent();
700
- doc = result_2.doc;
701
- cleanedBody_1 = result_2.cleanedBody;
702
- prevDoc_1 = result_2.prevDoc;
703
- postHook = function () {
704
- return (0, executors_1.runPostUpdate)({
705
- cleanedBody: cleanedBody_1,
706
- doc: result_2.doc,
707
- options: executorOptions_1,
708
- prevDoc: prevDoc_1,
709
- request: executorRequest_1,
710
- });
711
- };
712
- return [3 /*break*/, 19];
713
- case 16:
714
- updateError_1 = _l.sent();
715
- if (!(isLeaseTakeover &&
716
- (0, executors_1.isExecutorConflictError)(updateError_1) &&
717
- updateError_1.conflictType === "seq" &&
718
- updateError_1.serverSeq === ((_h = effectiveMutation.baseVersion) !== null && _h !== void 0 ? _h : 0) + 1 &&
719
- (0, exports.docMatchesMutationData)(updateError_1.doc, effectiveMutation.data))) return [3 /*break*/, 18];
720
- return [4 /*yield*/, finalizeAlreadyApplied({
721
- claimedId: claimed._id,
722
- doc: updateError_1.doc,
723
- mutation: mutation,
724
- })];
725
- case 17:
726
- _d = _l.sent(), resultId_2 = _d.resultId, resultSeq_2 = _d.resultSeq;
727
- return [2 /*return*/, { ack: { id: resultId_2, mutationId: mutationId, seq: resultSeq_2 }, type: "ack" }];
728
- case 18: throw updateError_1;
729
- case 19: return [3 /*break*/, 22];
730
- case 20: return [4 /*yield*/, (0, executors_1.executeDelete)({
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" },
731
492
  id: effectiveMutation.id,
732
- model: model,
733
- options: executorOptions_1,
734
- req: executorRequest_1,
735
- skipPermissionChecks: skipPermissionChecks,
493
+ model,
494
+ options: executorOptions,
495
+ req: executorRequest,
496
+ skipPermissionChecks,
736
497
  skipPostHooks: true,
737
- user: user,
738
- })];
739
- case 21:
740
- result_3 = _l.sent();
741
- doc = result_3.doc;
742
- postHook = function () {
743
- return (0, executors_1.runPostDelete)({ doc: result_3.doc, options: executorOptions_1, request: executorRequest_1 });
744
- };
745
- _l.label = 22;
746
- case 22:
747
- resultId = String(doc._id);
748
- resultSeq = (_j = doc._syncSeq) !== null && _j !== void 0 ? _j : 0;
749
- // M5: finalize the ledger BEFORE the post-hook runs — a post-hook throw
750
- // must never make a committed write look like a failure.
751
- return [4 /*yield*/, models_1.SyncMutation.updateOne({ _id: claimed._id }, { $set: { resultId: resultId, resultSeq: resultSeq, status: "applied" } })];
752
- case 23:
753
- // M5: finalize the ledger BEFORE the post-hook runs — a post-hook throw
754
- // must never make a committed write look like a failure.
755
- _l.sent();
756
- syncDebugLog.debug("[sync] Mutation applied", {
757
- collection: mutation.collection,
758
- mutationId: mutationId,
759
- seq: resultSeq,
498
+ user,
760
499
  });
761
- warning = void 0;
762
- _l.label = 24;
763
- case 24:
764
- _l.trys.push([24, 26, , 27]);
765
- return [4 /*yield*/, postHook()];
766
- case 25:
767
- _l.sent();
768
- return [3 /*break*/, 27];
769
- case 26:
770
- postHookError_1 = _l.sent();
771
- warning = errorMessageOf(postHookError_1);
772
- logger_1.logger.error("[sync] Post-hook failed after a committed mutation", {
773
- collection: mutation.collection,
774
- error: warning,
775
- mutationId: mutationId,
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,
776
511
  });
777
- return [3 /*break*/, 27];
778
- case 27:
779
- if (!(adminWindowScope === null || adminWindowScope === void 0 ? void 0 : adminWindowScope.emitAudit)) return [3 /*break*/, 31];
780
- _l.label = 28;
781
- case 28:
782
- _l.trys.push([28, 30, , 31]);
783
- return [4 /*yield*/, (0, adminWindowMutation_1.emitAdminWindowMutationAudit)({
784
- doc: doc,
785
- mutation: effectiveMutation,
786
- req: executorRequest_1,
787
- scope: adminWindowScope,
788
- })];
789
- case 29:
790
- _l.sent();
791
- return [3 /*break*/, 31];
792
- case 30:
793
- auditError_1 = _l.sent();
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) {
794
584
  logger_1.logger.error("[sync] Admin window audit hook failed after a committed mutation", {
795
585
  collection: mutation.collection,
796
- error: errorMessageOf(auditError_1),
797
- mutationId: mutationId,
586
+ error: errorMessageOf(auditError),
587
+ mutationId,
798
588
  });
799
- return [3 /*break*/, 31];
800
- case 31: return [2 /*return*/, {
801
- ack: __assign({ id: resultId, mutationId: mutationId, seq: resultSeq }, (warning ? { warning: warning } : {})),
802
- type: "ack",
803
- }];
804
- case 32:
805
- error_2 = _l.sent();
806
- return [2 /*return*/, finalizeNack({ claimedId: claimed._id, entry: entry, error: error_2, mutation: mutation, request: request })];
807
- case 33: return [2 /*return*/];
589
+ }
808
590
  }
809
- });
810
- }); };
811
- var errorMessageOf = function (error) {
812
- 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
+ }
813
599
  };
600
+ const errorMessageOf = (error) => (0, errors_1.isAPIError)(error) ? error.title : error instanceof Error ? error.message : String(error);
814
601
  /**
815
602
  * Apply a client mutation through the transport-agnostic executors (permissions,
816
603
  * pre/post hooks, validation) with an atomic idempotency claim. Always finalizes the
817
604
  * claimed ledger row before returning so duplicate deliveries can read the outcome back.
818
605
  */
819
- var applySyncMutation = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
820
- var mutationId, validationNack, entry, request, claimed, error_3;
821
- var user = _b.user, mutation = _b.mutation, req = _b.req, scopeResolver = _b.scopeResolver, syncOptions = _b.syncOptions;
822
- return __generator(this, function (_c) {
823
- switch (_c.label) {
824
- case 0:
825
- mutationId = typeof (mutation === null || mutation === void 0 ? void 0 : mutation.mutationId) === "string" ? mutation.mutationId : "";
826
- validationNack = function (message) {
827
- return makeNack({ code: "validation", message: message, mutationId: mutationId });
828
- };
829
- if (!mutationId) {
830
- return [2 /*return*/, validationNack("mutationId is required")];
831
- }
832
- if (!mutation.collection || typeof mutation.collection !== "string") {
833
- return [2 /*return*/, validationNack("collection is required")];
834
- }
835
- if (!VALID_OPERATIONS.has(mutation.operation)) {
836
- return [2 /*return*/, validationNack("Unknown operation: ".concat(String(mutation.operation)))];
837
- }
838
- if ((mutation.operation === "update" || mutation.operation === "delete") && !mutation.id) {
839
- return [2 /*return*/, validationNack("id is required for ".concat(mutation.operation, " mutations"))];
840
- }
841
- // C8: an update MUST carry an explicit baseVersion — omitting it would silently become
842
- // a `baseSeq: 0` check (an accidental conflict against every non-fresh doc, or an
843
- // accidental success against a seq-0 doc). Reject it as a client bug up front.
844
- if (mutation.operation === "update" && typeof mutation.baseVersion !== "number") {
845
- return [2 /*return*/, validationNack("baseVersion is required for update mutations")];
846
- }
847
- entry = (0, registry_1.findSyncEntryByCollectionTag)(mutation.collection);
848
- if (!entry) {
849
- return [2 /*return*/, validationNack("Unknown sync collection: ".concat(mutation.collection))];
850
- }
851
- request = req !== null && req !== void 0 ? req : { user: user };
852
- _c.label = 1;
853
- case 1:
854
- _c.trys.push([1, 3, , 4]);
855
- return [4 /*yield*/, models_1.SyncMutation.create({
856
- claimedAt: luxon_1.DateTime.now().toJSDate(),
857
- mutationId: mutationId,
858
- status: "pending",
859
- userId: String(user.id),
860
- })];
861
- case 2:
862
- claimed = _c.sent();
863
- return [3 /*break*/, 4];
864
- case 3:
865
- error_3 = _c.sent();
866
- if (error_3.code !== 11000) {
867
- throw error_3;
868
- }
869
- return [2 /*return*/, waitForRecordedOutcome({
870
- entry: entry,
871
- mutationId: mutationId,
872
- onTakeover: function (takenOver) {
873
- return applyClaimedMutation({
874
- claimed: takenOver,
875
- entry: entry,
876
- isLeaseTakeover: true,
877
- mutation: mutation,
878
- request: request,
879
- scopeResolver: scopeResolver,
880
- syncOptions: syncOptions,
881
- user: user,
882
- });
883
- },
884
- request: request,
885
- user: user,
886
- })];
887
- case 4: return [2 /*return*/, applyClaimedMutation({
888
- claimed: claimed,
889
- entry: entry,
890
- mutation: mutation,
891
- request: request,
892
- scopeResolver: scopeResolver,
893
- syncOptions: syncOptions,
894
- user: user,
895
- })];
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;
896
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,
897
671
  });
898
- }); };
672
+ };
899
673
  exports.applySyncMutation = applySyncMutation;
900
674
  /**
901
675
  * Up-front validation shared by both batch transports (HTTP and socket): reject an
@@ -905,8 +679,7 @@ exports.applySyncMutation = applySyncMutation;
905
679
  * the shape callers expect from `applySyncMutationBatch`, but produced without
906
680
  * touching the idempotency ledger since nothing was attempted.
907
681
  */
908
- var validateSyncMutationBatch = function (mutations) {
909
- var e_1, _a;
682
+ const validateSyncMutationBatch = (mutations) => {
910
683
  if (mutations.length > exports.MAX_SYNC_MUTATIONS_PER_BATCH) {
911
684
  return {
912
685
  ok: false,
@@ -914,41 +687,31 @@ var validateSyncMutationBatch = function (mutations) {
914
687
  results: [
915
688
  makeNack({
916
689
  code: "validation",
917
- 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`,
918
691
  mutationId: "",
919
692
  }),
920
693
  ],
921
694
  },
922
695
  };
923
696
  }
924
- var seen = new Set();
925
- try {
926
- for (var mutations_1 = __values(mutations), mutations_1_1 = mutations_1.next(); !mutations_1_1.done; mutations_1_1 = mutations_1.next()) {
927
- var mutation = mutations_1_1.value;
928
- var mutationId = typeof (mutation === null || mutation === void 0 ? void 0 : mutation.mutationId) === "string" ? mutation.mutationId : "";
929
- if (mutationId && seen.has(mutationId)) {
930
- return {
931
- ok: false,
932
- response: {
933
- results: [
934
- makeNack({
935
- code: "validation",
936
- message: "Duplicate mutationId within batch: ".concat(mutationId),
937
- mutationId: mutationId,
938
- }),
939
- ],
940
- },
941
- };
942
- }
943
- seen.add(mutationId);
944
- }
945
- }
946
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
947
- finally {
948
- try {
949
- 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
+ };
950
713
  }
951
- finally { if (e_1) throw e_1.error; }
714
+ seen.add(mutationId);
952
715
  }
953
716
  return { ok: true };
954
717
  };
@@ -964,48 +727,17 @@ exports.validateSyncMutationBatch = validateSyncMutationBatch;
964
727
  * rejection happens before any mutation is attempted); this function assumes the
965
728
  * batch already passed that check.
966
729
  */
967
- var applySyncMutationBatch = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
968
- var results, mutations_2, mutations_2_1, mutation, outcome, e_2_1;
969
- var e_2, _c;
970
- var user = _b.user, mutations = _b.mutations, req = _b.req, scopeResolver = _b.scopeResolver, syncOptions = _b.syncOptions;
971
- return __generator(this, function (_d) {
972
- switch (_d.label) {
973
- case 0:
974
- results = [];
975
- _d.label = 1;
976
- case 1:
977
- _d.trys.push([1, 6, 7, 8]);
978
- mutations_2 = __values(mutations), mutations_2_1 = mutations_2.next();
979
- _d.label = 2;
980
- case 2:
981
- if (!!mutations_2_1.done) return [3 /*break*/, 5];
982
- mutation = mutations_2_1.value;
983
- return [4 /*yield*/, (0, exports.applySyncMutation)({ mutation: mutation, req: req, scopeResolver: scopeResolver, syncOptions: syncOptions, user: user })];
984
- case 3:
985
- outcome = _d.sent();
986
- results.push(outcome);
987
- if (outcome.type === "nack") {
988
- // Stop-on-error: the client re-sends everything after this point, and
989
- // INV-3's idempotency ledger makes that overlap safe.
990
- return [3 /*break*/, 5];
991
- }
992
- _d.label = 4;
993
- case 4:
994
- mutations_2_1 = mutations_2.next();
995
- return [3 /*break*/, 2];
996
- case 5: return [3 /*break*/, 8];
997
- case 6:
998
- e_2_1 = _d.sent();
999
- e_2 = { error: e_2_1 };
1000
- return [3 /*break*/, 8];
1001
- case 7:
1002
- try {
1003
- if (mutations_2_1 && !mutations_2_1.done && (_c = mutations_2.return)) _c.call(mutations_2);
1004
- }
1005
- finally { if (e_2) throw e_2.error; }
1006
- return [7 /*endfinally*/];
1007
- 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;
1008
739
  }
1009
- });
1010
- }); };
740
+ }
741
+ return { results };
742
+ };
1011
743
  exports.applySyncMutationBatch = applySyncMutationBatch;