@terreno/api 0.31.0 → 56.0.0-beta.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 (250) hide show
  1. package/CHANGELOG.md +122 -2
  2. package/LICENSE +202 -21
  3. package/dist/api.d.ts +12 -3
  4. package/dist/api.js +110 -361
  5. package/dist/auth.d.ts +26 -0
  6. package/dist/auth.js +100 -1
  7. package/dist/betterAuth.d.ts +5 -0
  8. package/dist/betterAuthSetup.d.ts +1 -15
  9. package/dist/betterAuthSetup.js +29 -8
  10. package/dist/configurationPlugin.js +2 -2
  11. package/dist/docLoader.js +12 -9
  12. package/dist/errors.d.ts +13 -0
  13. package/dist/errors.js +29 -1
  14. package/dist/expressServer.js +5 -11
  15. package/dist/githubAuth.js +4 -1
  16. package/dist/index.d.ts +17 -1
  17. package/dist/index.js +29 -1
  18. package/dist/middleware.d.ts +7 -0
  19. package/dist/middleware.js +16 -1
  20. package/dist/openApiCompat.d.ts +10 -1
  21. package/dist/openApiCompat.js +115 -47
  22. package/dist/permissions.d.ts +27 -0
  23. package/dist/permissions.js +42 -1
  24. package/dist/plugins.d.ts +15 -3
  25. package/dist/plugins.js +36 -6
  26. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  27. package/dist/realtime/changeStreamWatcher.js +542 -137
  28. package/dist/realtime/realtimeApp.d.ts +3 -1
  29. package/dist/realtime/realtimeApp.js +75 -27
  30. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  31. package/dist/realtime/sessionRevalidation.js +438 -0
  32. package/dist/realtime/socketAuth.d.ts +97 -0
  33. package/dist/realtime/socketAuth.js +272 -0
  34. package/dist/realtime/socketUser.d.ts +54 -0
  35. package/dist/realtime/socketUser.js +75 -5
  36. package/dist/realtime/types.d.ts +40 -0
  37. package/dist/secretProviders.d.ts +23 -0
  38. package/dist/secretProviders.js +9 -3
  39. package/dist/sync/executors.d.ts +198 -0
  40. package/dist/sync/executors.js +670 -0
  41. package/dist/sync/loadHarness.js +807 -0
  42. package/dist/sync/models.d.ts +216 -0
  43. package/dist/sync/models.js +644 -0
  44. package/dist/sync/mutationHandler.d.ts +97 -0
  45. package/dist/sync/mutationHandler.js +886 -0
  46. package/dist/sync/registry.d.ts +73 -0
  47. package/dist/sync/registry.js +223 -0
  48. package/dist/sync/routes.d.ts +62 -0
  49. package/dist/sync/routes.js +936 -0
  50. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  51. package/dist/sync/scripts/compactTombstones.js +270 -0
  52. package/dist/sync/serialize.d.ts +20 -0
  53. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  54. package/dist/sync/socketHandlers.d.ts +54 -0
  55. package/dist/sync/socketHandlers.js +470 -0
  56. package/dist/sync/streams.d.ts +85 -0
  57. package/dist/sync/streams.js +221 -0
  58. package/dist/sync/syncApp.d.ts +29 -0
  59. package/dist/sync/syncApp.js +44 -0
  60. package/dist/sync/syncBatch.d.ts +71 -0
  61. package/dist/sync/syncBatch.js +252 -0
  62. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  63. package/dist/sync/syncSeqPlugin.js +903 -0
  64. package/dist/sync/types.d.ts +254 -0
  65. package/dist/sync/types.js +9 -0
  66. package/dist/terrenoApp.js +90 -27
  67. package/dist/tests/models.d.ts +11 -27
  68. package/dist/tests/models.js +3 -5
  69. package/dist/tests/testHelper.d.ts +3 -9
  70. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  71. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  72. package/package.json +10 -8
  73. package/src/__tests__/openApiCompat.test.ts +20 -0
  74. package/src/actions.test.ts +12 -19
  75. package/src/actions.ts +2 -2
  76. package/src/api.coverage.test.ts +9 -7
  77. package/src/api.errorPaths.test.ts +1 -47
  78. package/src/api.test.ts +12 -0
  79. package/src/api.ts +98 -317
  80. package/src/auth.test.ts +128 -176
  81. package/src/auth.ts +109 -0
  82. package/src/betterAuth.ts +6 -0
  83. package/src/betterAuthSetup.test.ts +34 -0
  84. package/src/betterAuthSetup.ts +27 -8
  85. package/src/configurationPlugin.ts +2 -2
  86. package/src/consentApp.test.ts +12 -12
  87. package/src/docLoader.ts +3 -1
  88. package/src/errors.ts +33 -0
  89. package/src/expressServer.test.ts +7 -1
  90. package/src/expressServer.ts +5 -11
  91. package/src/githubAuth.ts +3 -1
  92. package/src/index.ts +42 -0
  93. package/src/middleware.test.ts +40 -1
  94. package/src/middleware.ts +15 -0
  95. package/src/models/versionConfig.ts +1 -1
  96. package/src/openApiBuilder.test.ts +9 -24
  97. package/src/openApiCompat.ts +99 -45
  98. package/src/openApiValidator.test.ts +0 -41
  99. package/src/permissions.test.ts +75 -1
  100. package/src/permissions.ts +49 -0
  101. package/src/plugins.test.ts +54 -14
  102. package/src/plugins.ts +47 -9
  103. package/src/populate.test.ts +16 -25
  104. package/src/realtime/changeStreamWatcher.ts +552 -114
  105. package/src/realtime/realtime.test.ts +157 -239
  106. package/src/realtime/realtimeApp.ts +80 -19
  107. package/src/realtime/sessionRevalidation.test.ts +423 -0
  108. package/src/realtime/sessionRevalidation.ts +273 -0
  109. package/src/realtime/socketAuth.test.ts +355 -0
  110. package/src/realtime/socketAuth.ts +228 -0
  111. package/src/realtime/socketUser.ts +69 -0
  112. package/src/realtime/types.ts +40 -0
  113. package/src/secretProviders.test.ts +7 -1
  114. package/src/secretProviders.ts +15 -3
  115. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  116. package/src/sync/executors.test.ts +882 -0
  117. package/src/sync/executors.ts +703 -0
  118. package/src/sync/integration.test.ts +1160 -0
  119. package/src/sync/loadHarness.ts +618 -0
  120. package/src/sync/models.ts +640 -0
  121. package/src/sync/mutationHandler.test.ts +1252 -0
  122. package/src/sync/mutationHandler.ts +850 -0
  123. package/src/sync/registry.ts +232 -0
  124. package/src/sync/routes.ts +812 -0
  125. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  126. package/src/sync/scripts/compactTombstones.ts +145 -0
  127. package/src/sync/serialize.ts +48 -0
  128. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  129. package/src/sync/socketHandlers.ts +320 -0
  130. package/src/sync/streams.ts +188 -0
  131. package/src/sync/sync.test.ts +582 -0
  132. package/src/sync/syncApp.ts +44 -0
  133. package/src/sync/syncBatch.ts +219 -0
  134. package/src/sync/syncFrontier.test.ts +494 -0
  135. package/src/sync/syncPhaseC.test.ts +718 -0
  136. package/src/sync/syncRoutes.test.ts +865 -0
  137. package/src/sync/syncSeqPlugin.ts +738 -0
  138. package/src/sync/syncSocket.test.ts +1440 -0
  139. package/src/sync/types.ts +270 -0
  140. package/src/terrenoApp.ts +37 -17
  141. package/src/tests/bunSetup.ts +8 -0
  142. package/src/tests/models.ts +6 -8
  143. package/tsconfig.json +4 -4
  144. package/tsconfig.typedoc.json +7 -1
  145. package/dist/__tests__/openApiCompat.test.js +0 -317
  146. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  147. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  148. package/dist/actions.openApi.test.d.ts +0 -1
  149. package/dist/actions.openApi.test.js +0 -253
  150. package/dist/actions.test.d.ts +0 -1
  151. package/dist/actions.test.js +0 -1087
  152. package/dist/api.arrayOperations.test.d.ts +0 -1
  153. package/dist/api.arrayOperations.test.js +0 -878
  154. package/dist/api.asyncHandler.test.d.ts +0 -1
  155. package/dist/api.asyncHandler.test.js +0 -236
  156. package/dist/api.coverage.test.d.ts +0 -1
  157. package/dist/api.coverage.test.js +0 -192
  158. package/dist/api.errorPaths.test.d.ts +0 -1
  159. package/dist/api.errorPaths.test.js +0 -887
  160. package/dist/api.errors.test.d.ts +0 -1
  161. package/dist/api.errors.test.js +0 -185
  162. package/dist/api.hooks.test.d.ts +0 -1
  163. package/dist/api.hooks.test.js +0 -950
  164. package/dist/api.query.test.d.ts +0 -1
  165. package/dist/api.query.test.js +0 -948
  166. package/dist/api.test.d.ts +0 -1
  167. package/dist/api.test.js +0 -2820
  168. package/dist/auth.compile.test.d.ts +0 -1
  169. package/dist/auth.compile.test.js +0 -201
  170. package/dist/auth.coverage.test.d.ts +0 -1
  171. package/dist/auth.coverage.test.js +0 -202
  172. package/dist/auth.test.d.ts +0 -1
  173. package/dist/auth.test.js +0 -2286
  174. package/dist/betterAuth.test.d.ts +0 -1
  175. package/dist/betterAuth.test.js +0 -181
  176. package/dist/betterAuthApp.test.d.ts +0 -1
  177. package/dist/betterAuthApp.test.js +0 -242
  178. package/dist/betterAuthSetup.test.d.ts +0 -1
  179. package/dist/betterAuthSetup.test.js +0 -762
  180. package/dist/config.test.d.ts +0 -1
  181. package/dist/config.test.js +0 -353
  182. package/dist/configuration.test.d.ts +0 -1
  183. package/dist/configuration.test.js +0 -980
  184. package/dist/configurationPlugin.test.d.ts +0 -1
  185. package/dist/configurationPlugin.test.js +0 -827
  186. package/dist/consentApp.test.d.ts +0 -1
  187. package/dist/consentApp.test.js +0 -1411
  188. package/dist/docLoader.test.d.ts +0 -1
  189. package/dist/docLoader.test.js +0 -137
  190. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  191. package/dist/envConfigurationPlugin.test.js +0 -369
  192. package/dist/errors.test.d.ts +0 -1
  193. package/dist/errors.test.js +0 -607
  194. package/dist/expressServer.test.d.ts +0 -1
  195. package/dist/expressServer.test.js +0 -1249
  196. package/dist/githubAuth.test.d.ts +0 -1
  197. package/dist/githubAuth.test.js +0 -1142
  198. package/dist/httpClient.test.d.ts +0 -1
  199. package/dist/httpClient.test.js +0 -1471
  200. package/dist/logger.test.d.ts +0 -1
  201. package/dist/logger.test.js +0 -685
  202. package/dist/middleware.test.d.ts +0 -1
  203. package/dist/middleware.test.js +0 -241
  204. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  205. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  206. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  207. package/dist/notifiers/slackNotifier.test.js +0 -297
  208. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  209. package/dist/notifiers/zoomNotifier.test.js +0 -373
  210. package/dist/openApi.test.d.ts +0 -1
  211. package/dist/openApi.test.js +0 -620
  212. package/dist/openApiBuilder.test.d.ts +0 -1
  213. package/dist/openApiBuilder.test.js +0 -599
  214. package/dist/openApiEtag.test.d.ts +0 -1
  215. package/dist/openApiEtag.test.js +0 -86
  216. package/dist/openApiValidator.test.d.ts +0 -1
  217. package/dist/openApiValidator.test.js +0 -795
  218. package/dist/permissions.middleware.test.d.ts +0 -1
  219. package/dist/permissions.middleware.test.js +0 -308
  220. package/dist/permissions.test.d.ts +0 -1
  221. package/dist/permissions.test.js +0 -439
  222. package/dist/plugins.test.d.ts +0 -1
  223. package/dist/plugins.test.js +0 -902
  224. package/dist/populate.test.d.ts +0 -1
  225. package/dist/populate.test.js +0 -370
  226. package/dist/realtime/realtime.test.d.ts +0 -10
  227. package/dist/realtime/realtime.test.js +0 -4213
  228. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  229. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  230. package/dist/requestContext.test.d.ts +0 -1
  231. package/dist/requestContext.test.js +0 -412
  232. package/dist/scriptRunner.test.d.ts +0 -1
  233. package/dist/scriptRunner.test.js +0 -386
  234. package/dist/secretProviders.test.d.ts +0 -1
  235. package/dist/secretProviders.test.js +0 -726
  236. package/dist/syncConsents.test.d.ts +0 -1
  237. package/dist/syncConsents.test.js +0 -522
  238. package/dist/terrenoApp.test.d.ts +0 -1
  239. package/dist/terrenoApp.test.js +0 -489
  240. package/dist/tests/bunSetup.d.ts +0 -1
  241. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  242. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  243. package/dist/tests/testEnv.d.ts +0 -0
  244. package/dist/tests/testEnv.js +0 -6
  245. package/dist/transformers.test.d.ts +0 -1
  246. package/dist/transformers.test.js +0 -423
  247. package/dist/utils.test.d.ts +0 -1
  248. package/dist/utils.test.js +0 -242
  249. package/src/realtime/realtimeAppSetup.test.ts +0 -161
  250. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
@@ -0,0 +1,670 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
18
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19
+ return new (P || (P = Promise))(function (resolve, reject) {
20
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
23
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
24
+ });
25
+ };
26
+ var __generator = (this && this.__generator) || function (thisArg, body) {
27
+ 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);
28
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
+ function verb(n) { return function (v) { return step([n, v]); }; }
30
+ function step(op) {
31
+ if (f) throw new TypeError("Generator is already executing.");
32
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
33
+ 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;
34
+ if (y = 0, t) op = [op[0] & 2, t.value];
35
+ switch (op[0]) {
36
+ case 0: case 1: t = op; break;
37
+ case 4: _.label++; return { value: op[1], done: false };
38
+ case 5: _.label++; y = op[1]; op = [0]; continue;
39
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
40
+ default:
41
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45
+ if (t[2]) _.ops.pop();
46
+ _.trys.pop(); continue;
47
+ }
48
+ op = body.call(thisArg, _);
49
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51
+ }
52
+ };
53
+ var __rest = (this && this.__rest) || function (s, e) {
54
+ var t = {};
55
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
56
+ t[p] = s[p];
57
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
58
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
59
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
60
+ t[p[i]] = s[p[i]];
61
+ }
62
+ return t;
63
+ };
64
+ var __importDefault = (this && this.__importDefault) || function (mod) {
65
+ return (mod && mod.__esModule) ? mod : { "default": mod };
66
+ };
67
+ Object.defineProperty(exports, "__esModule", { value: true });
68
+ exports.runPostDelete = exports.executeDelete = exports.runPostUpdate = exports.executeUpdate = exports.runPostCreate = exports.executeCreate = exports.isVersionError = exports.isExecutorConflictError = exports.ExecutorConflictError = void 0;
69
+ var cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
70
+ var luxon_1 = require("luxon");
71
+ var api_1 = require("../api");
72
+ var docLoader_1 = require("../docLoader");
73
+ var errors_1 = require("../errors");
74
+ var permissions_1 = require("../permissions");
75
+ var transformers_1 = require("../transformers");
76
+ /**
77
+ * Thrown by executeUpdate when a concurrency check fails. Carries the current server document
78
+ * (canonical copy) so callers can serialize it into a conflict response: the REST handler
79
+ * turns timestamp conflicts into the legacy 409 `{data, error, message}` body, and the sync
80
+ * mutation channel returns the doc + seq in its conflict nack.
81
+ */
82
+ var ExecutorConflictError = /** @class */ (function (_super) {
83
+ __extends(ExecutorConflictError, _super);
84
+ function ExecutorConflictError(_a) {
85
+ var _this = this;
86
+ var conflictType = _a.conflictType, doc = _a.doc, serverSeq = _a.serverSeq, apiErrorData = __rest(_a, ["conflictType", "doc", "serverSeq"]);
87
+ _this = _super.call(this, apiErrorData) || this;
88
+ _this.conflictType = conflictType;
89
+ _this.doc = doc;
90
+ _this.serverSeq = serverSeq;
91
+ return _this;
92
+ }
93
+ return ExecutorConflictError;
94
+ }(errors_1.APIError));
95
+ exports.ExecutorConflictError = ExecutorConflictError;
96
+ /**
97
+ * Duck-typed guard for {@link ExecutorConflictError}. The package compiles to ES5, where
98
+ * TypeScript's emit for classes extending built-ins (Error) breaks the prototype chain, so
99
+ * `instanceof` returns false for consumers running the compiled dist (bun running the TS
100
+ * source directly is unaffected — which is why unit/integration tests never caught it).
101
+ * Always use this guard instead of `instanceof ExecutorConflictError`.
102
+ */
103
+ var isExecutorConflictError = function (error) {
104
+ if (error instanceof ExecutorConflictError) {
105
+ return true;
106
+ }
107
+ var candidate = error;
108
+ return (!!candidate &&
109
+ typeof candidate === "object" &&
110
+ (candidate.conflictType === "timestamp" || candidate.conflictType === "seq") &&
111
+ candidate.status === 409);
112
+ };
113
+ exports.isExecutorConflictError = isExecutorConflictError;
114
+ /**
115
+ * Minimal stand-in for an Express request when executors run outside HTTP. Only `user` is
116
+ * populated — see the module doc comment for the hook compatibility contract.
117
+ */
118
+ var stubRequest = function (user) { return ({ user: user }); };
119
+ /**
120
+ * True for the Mongoose error thrown when an `optimisticConcurrency` save matched no
121
+ * document (its `__v` filter failed) — i.e. another write landed since the load.
122
+ * Name-checked rather than `instanceof` for the same ES5-dist reason as
123
+ * {@link isExecutorConflictError}.
124
+ */
125
+ var isVersionError = function (error) {
126
+ return (error === null || error === void 0 ? void 0 : error.name) === "VersionError";
127
+ };
128
+ exports.isVersionError = isVersionError;
129
+ /**
130
+ * Re-read the document a version-conflicted save lost to, so the conflict response carries
131
+ * the CURRENT server state (the in-memory instance still holds the caller's rejected
132
+ * edits). Includes tombstones: the winning write may have been a soft delete, and the
133
+ * client needs to learn that too. Returns undefined if the read fails — the caller falls
134
+ * back to its own instance rather than failing the request.
135
+ */
136
+ var reloadDocForConflict = function (model, id) { return __awaiter(void 0, void 0, void 0, function () {
137
+ var found, _a;
138
+ return __generator(this, function (_b) {
139
+ switch (_b.label) {
140
+ case 0:
141
+ _b.trys.push([0, 2, , 3]);
142
+ return [4 /*yield*/, model.find({ _id: id, deleted: { $in: [true, false] } }).limit(1)];
143
+ case 1:
144
+ found = _b.sent();
145
+ return [2 /*return*/, found[0]];
146
+ case 2:
147
+ _a = _b.sent();
148
+ return [2 /*return*/, undefined];
149
+ case 3: return [2 /*return*/];
150
+ }
151
+ });
152
+ }); };
153
+ /**
154
+ * Create a document through the same pipeline as `POST /`: method-level permissions,
155
+ * `transformer.transform`, `preCreate`, `Model.create` (Mongoose validation), population,
156
+ * and `postCreate`. Throws APIErrors with the same statuses/titles as the REST handler.
157
+ */
158
+ var executeCreate = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
159
+ var request, cleanedBody, error_1, data, error_2, populateQuery, error_3, error_4;
160
+ var model = _b.model, options = _b.options, user = _b.user, body = _b.body, req = _b.req, skipPostHooks = _b.skipPostHooks;
161
+ return __generator(this, function (_c) {
162
+ switch (_c.label) {
163
+ case 0:
164
+ request = req !== null && req !== void 0 ? req : stubRequest(user);
165
+ return [4 /*yield*/, (0, permissions_1.checkPermissions)("create", options.permissions.create, user)];
166
+ case 1:
167
+ if (!(_c.sent())) {
168
+ throw new errors_1.APIError({
169
+ status: 405,
170
+ title: "Access to CREATE on ".concat(model.modelName, " denied for ").concat(user === null || user === void 0 ? void 0 : user.id),
171
+ });
172
+ }
173
+ try {
174
+ cleanedBody = (0, transformers_1.transform)(options, body, "create", user);
175
+ }
176
+ catch (error) {
177
+ throw (0, errors_1.passthroughOrWrap)(error, {
178
+ code: "transform-error",
179
+ status: 400,
180
+ title: "Transform error",
181
+ });
182
+ }
183
+ if (!options.preCreate) return [3 /*break*/, 6];
184
+ _c.label = 2;
185
+ case 2:
186
+ _c.trys.push([2, 4, , 5]);
187
+ return [4 /*yield*/, options.preCreate(cleanedBody, request)];
188
+ case 3:
189
+ cleanedBody = _c.sent();
190
+ return [3 /*break*/, 5];
191
+ case 4:
192
+ error_1 = _c.sent();
193
+ throw (0, errors_1.passthroughOrWrap)(error_1, {
194
+ code: "pre-create-hook-error",
195
+ status: 400,
196
+ title: "preCreate hook error",
197
+ });
198
+ case 5:
199
+ if (cleanedBody === undefined) {
200
+ throw new errors_1.APIError({
201
+ detail: "A body must be returned from preCreate",
202
+ status: 403,
203
+ title: "Create not allowed",
204
+ });
205
+ }
206
+ if (cleanedBody === null) {
207
+ throw new errors_1.APIError({
208
+ detail: "preCreate hook returned null",
209
+ status: 403,
210
+ title: "Create not allowed",
211
+ });
212
+ }
213
+ _c.label = 6;
214
+ case 6:
215
+ if (cleanedBody === undefined) {
216
+ throw new errors_1.APIError({
217
+ detail: "Body is undefined",
218
+ status: 400,
219
+ title: "Invalid request body",
220
+ });
221
+ }
222
+ _c.label = 7;
223
+ case 7:
224
+ _c.trys.push([7, 9, , 10]);
225
+ return [4 /*yield*/, model.create(cleanedBody)];
226
+ case 8:
227
+ data = (_c.sent());
228
+ return [3 /*break*/, 10];
229
+ case 9:
230
+ error_2 = _c.sent();
231
+ throw (0, errors_1.passthroughOrWrapWrite)(error_2, {
232
+ code: "create-error",
233
+ status: 400,
234
+ title: "Create error",
235
+ });
236
+ case 10:
237
+ if (!options.populatePaths) return [3 /*break*/, 14];
238
+ _c.label = 11;
239
+ case 11:
240
+ _c.trys.push([11, 13, , 14]);
241
+ populateQuery = model.findById(data._id);
242
+ populateQuery = (0, api_1.addPopulateToQuery)(populateQuery, options.populatePaths);
243
+ return [4 /*yield*/, populateQuery.exec()];
244
+ case 12:
245
+ data = _c.sent();
246
+ return [3 /*break*/, 14];
247
+ case 13:
248
+ error_3 = _c.sent();
249
+ throw (0, errors_1.passthroughOrWrap)(error_3, {
250
+ code: "populate-error",
251
+ status: 400,
252
+ title: "Populate error",
253
+ });
254
+ case 14:
255
+ if (!(options.postCreate && !skipPostHooks)) return [3 /*break*/, 18];
256
+ _c.label = 15;
257
+ case 15:
258
+ _c.trys.push([15, 17, , 18]);
259
+ return [4 /*yield*/, options.postCreate(data, request)];
260
+ case 16:
261
+ _c.sent();
262
+ return [3 /*break*/, 18];
263
+ case 17:
264
+ error_4 = _c.sent();
265
+ throw (0, errors_1.passthroughOrWrap)(error_4, {
266
+ code: "post-create-hook-error",
267
+ status: 400,
268
+ title: "postCreate hook error",
269
+ });
270
+ case 18: return [2 /*return*/, { doc: data }];
271
+ }
272
+ });
273
+ }); };
274
+ exports.executeCreate = executeCreate;
275
+ /**
276
+ * C5 (FIX 6): run `postCreate` outside the write transaction/ledger-finalize
277
+ * window. Errors are the caller's responsibility to catch — the sync mutation
278
+ * handler logs them and reports a warning, never converting them into a nack
279
+ * (the document write already committed and the ledger already finalized
280
+ * `applied`).
281
+ */
282
+ var runPostCreate = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
283
+ var doc = _b.doc, options = _b.options, request = _b.request;
284
+ return __generator(this, function (_c) {
285
+ switch (_c.label) {
286
+ case 0:
287
+ if (!options.postCreate) return [3 /*break*/, 2];
288
+ return [4 /*yield*/, options.postCreate(doc, request)];
289
+ case 1:
290
+ _c.sent();
291
+ _c.label = 2;
292
+ case 2: return [2 /*return*/];
293
+ }
294
+ });
295
+ }); };
296
+ exports.runPostCreate = runPostCreate;
297
+ /**
298
+ * Update a document through the same pipeline as `PATCH /:id`: method-level and object-level
299
+ * permissions, doc loading (404), `transformer.transform`, `_updatedAt` stripping,
300
+ * `preUpdate`, the optional concurrency check, `doc.set` + `doc.save` (Mongoose validation),
301
+ * population, and `postUpdate`. Throws APIErrors with the same statuses/titles as the REST
302
+ * handler; concurrency conflicts throw `ExecutorConflictError` (409) carrying the server doc.
303
+ */
304
+ var executeUpdate = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
305
+ var request, doc, _c, cleanedBody, error_5, clientTimestamp, docRecord, serverTimestamp, serverTimestampValue, serverSeq, prevDoc, error_6, current, serverSeq, populateQuery, error_7;
306
+ var _d, _e, _f, _g;
307
+ var model = _b.model, options = _b.options, user = _b.user, id = _b.id, body = _b.body, concurrencyCheck = _b.concurrencyCheck, existingDoc = _b.existingDoc, req = _b.req, skipPostHooks = _b.skipPostHooks;
308
+ return __generator(this, function (_h) {
309
+ switch (_h.label) {
310
+ case 0:
311
+ request = req !== null && req !== void 0 ? req : stubRequest(user);
312
+ return [4 /*yield*/, (0, permissions_1.checkPermissions)("update", options.permissions.update, user)];
313
+ case 1:
314
+ if (!(_h.sent())) {
315
+ throw new errors_1.APIError({
316
+ status: 405,
317
+ title: "Access to UPDATE on ".concat(model.modelName, " denied for ").concat(user === null || user === void 0 ? void 0 : user.id),
318
+ });
319
+ }
320
+ if (!(existingDoc !== null && existingDoc !== void 0)) return [3 /*break*/, 2];
321
+ _c = existingDoc;
322
+ return [3 /*break*/, 4];
323
+ case 2: return [4 /*yield*/, (0, docLoader_1.loadDocOr404)(model, id, options.populatePaths)];
324
+ case 3:
325
+ _c = (_h.sent());
326
+ _h.label = 4;
327
+ case 4:
328
+ doc = _c;
329
+ return [4 /*yield*/, (0, permissions_1.checkPermissions)("update", options.permissions.update, user, doc)];
330
+ case 5:
331
+ if (!(_h.sent())) {
332
+ throw new errors_1.APIError({
333
+ status: 403,
334
+ title: "Access to GET on ".concat(model.modelName, ":").concat(id, " denied for ").concat(user === null || user === void 0 ? void 0 : user.id),
335
+ });
336
+ }
337
+ try {
338
+ cleanedBody = (0, transformers_1.transform)(options, body, "update", user);
339
+ }
340
+ catch (error) {
341
+ throw (0, errors_1.passthroughOrWrap)(error, {
342
+ code: "transform-error",
343
+ detail: "PATCH failed on ".concat(id, " for user ").concat(user === null || user === void 0 ? void 0 : user.id, ": ").concat((0, errors_1.errorMessage)(error)),
344
+ status: 403,
345
+ title: "PATCH failed",
346
+ });
347
+ }
348
+ // `_updatedAt` is conflict-detection metadata, not a model field: strip it from both the
349
+ // raw and transformed bodies before preUpdate processes them (mirrors the REST handler).
350
+ if (body && typeof body === "object") {
351
+ delete body._updatedAt;
352
+ }
353
+ if (cleanedBody && typeof cleanedBody === "object") {
354
+ delete cleanedBody._updatedAt;
355
+ }
356
+ if (!options.preUpdate) return [3 /*break*/, 10];
357
+ _h.label = 6;
358
+ case 6:
359
+ _h.trys.push([6, 8, , 9]);
360
+ return [4 /*yield*/, options.preUpdate(cleanedBody, request)];
361
+ case 7:
362
+ cleanedBody = _h.sent();
363
+ return [3 /*break*/, 9];
364
+ case 8:
365
+ error_5 = _h.sent();
366
+ throw (0, errors_1.passthroughOrWrap)(error_5, {
367
+ code: "pre-update-hook-error",
368
+ detail: "preUpdate hook error on ".concat(id, ": ").concat((0, errors_1.errorMessage)(error_5)),
369
+ status: 400,
370
+ title: "preUpdate hook error",
371
+ });
372
+ case 9:
373
+ if (cleanedBody === undefined) {
374
+ throw new errors_1.APIError({
375
+ detail: "A body must be returned from preUpdate",
376
+ status: 403,
377
+ title: "Update not allowed",
378
+ });
379
+ }
380
+ if (cleanedBody === null) {
381
+ throw new errors_1.APIError({
382
+ detail: "preUpdate hook on ".concat(id, " returned null"),
383
+ status: 403,
384
+ title: "Update not allowed",
385
+ });
386
+ }
387
+ _h.label = 10;
388
+ case 10:
389
+ // Conflict detection runs after preUpdate so that unauthorized mutations
390
+ // are rejected before we leak document data in a conflict response.
391
+ if ((concurrencyCheck === null || concurrencyCheck === void 0 ? void 0 : concurrencyCheck.type) === "timestamp") {
392
+ clientTimestamp = luxon_1.DateTime.fromJSDate(concurrencyCheck.ifUnmodifiedSince);
393
+ if (!clientTimestamp.isValid) {
394
+ throw new errors_1.APIError({
395
+ detail: (_d = concurrencyCheck.invalidTimestampDetail) !== null && _d !== void 0 ? _d : "Conflict-detection timestamp could not be parsed as a date",
396
+ status: 400,
397
+ title: "Invalid conflict-detection timestamp",
398
+ });
399
+ }
400
+ docRecord = doc;
401
+ serverTimestamp = null;
402
+ serverTimestampValue = (_e = docRecord.updated) !== null && _e !== void 0 ? _e : docRecord.created;
403
+ if (serverTimestampValue instanceof Date) {
404
+ serverTimestamp = luxon_1.DateTime.fromJSDate(serverTimestampValue);
405
+ }
406
+ else if (typeof serverTimestampValue === "string") {
407
+ serverTimestamp = luxon_1.DateTime.fromISO(serverTimestampValue);
408
+ }
409
+ if (serverTimestamp && !serverTimestamp.isValid) {
410
+ throw new errors_1.APIError({
411
+ detail: "Document timestamp could not be parsed as a date",
412
+ status: 400,
413
+ title: "Invalid server timestamp",
414
+ });
415
+ }
416
+ if (serverTimestamp && clientTimestamp < serverTimestamp) {
417
+ throw new ExecutorConflictError({
418
+ conflictType: "timestamp",
419
+ detail: "Document was modified since your last read",
420
+ disableExternalErrorTracking: true,
421
+ doc: doc,
422
+ status: 409,
423
+ title: "Conflict",
424
+ });
425
+ }
426
+ }
427
+ else if ((concurrencyCheck === null || concurrencyCheck === void 0 ? void 0 : concurrencyCheck.type) === "seq") {
428
+ serverSeq = (_f = doc._syncSeq) !== null && _f !== void 0 ? _f : 0;
429
+ if (concurrencyCheck.baseSeq !== serverSeq) {
430
+ throw new ExecutorConflictError({
431
+ conflictType: "seq",
432
+ detail: "Document was modified since your last read",
433
+ disableExternalErrorTracking: true,
434
+ doc: doc,
435
+ serverSeq: serverSeq,
436
+ status: 409,
437
+ title: "Sync conflict on ".concat(model.modelName, ":").concat(id, ": baseSeq ").concat(concurrencyCheck.baseSeq, " does not match server seq ").concat(serverSeq),
438
+ });
439
+ }
440
+ }
441
+ prevDoc = (0, cloneDeep_1.default)(doc);
442
+ _h.label = 11;
443
+ case 11:
444
+ _h.trys.push([11, 13, , 16]);
445
+ doc.set(cleanedBody);
446
+ return [4 /*yield*/, doc.save()];
447
+ case 12:
448
+ _h.sent();
449
+ return [3 /*break*/, 16];
450
+ case 13:
451
+ error_6 = _h.sent();
452
+ if (!((concurrencyCheck === null || concurrencyCheck === void 0 ? void 0 : concurrencyCheck.type) === "seq" && (0, exports.isVersionError)(error_6))) return [3 /*break*/, 15];
453
+ return [4 /*yield*/, reloadDocForConflict(model, id)];
454
+ case 14:
455
+ current = _h.sent();
456
+ serverSeq = (_g = current === null || current === void 0 ? void 0 : current._syncSeq) !== null && _g !== void 0 ? _g : 0;
457
+ throw new ExecutorConflictError({
458
+ conflictType: "seq",
459
+ detail: "Document was modified since your last read",
460
+ disableExternalErrorTracking: true,
461
+ doc: current !== null && current !== void 0 ? current : doc,
462
+ serverSeq: serverSeq,
463
+ status: 409,
464
+ title: "Sync conflict on ".concat(model.modelName, ":").concat(id, ": a concurrent write landed while this update was in flight (baseSeq ").concat(concurrencyCheck.baseSeq, ")"),
465
+ });
466
+ case 15: throw (0, errors_1.passthroughOrWrapWrite)(error_6, {
467
+ code: "update-save-error",
468
+ detail: "preUpdate hook save error on ".concat(id, ": ").concat((0, errors_1.errorMessage)(error_6)),
469
+ status: 400,
470
+ title: "preUpdate hook save error",
471
+ });
472
+ case 16:
473
+ if (!options.populatePaths) return [3 /*break*/, 18];
474
+ populateQuery = model.findById(doc._id);
475
+ populateQuery = (0, api_1.addPopulateToQuery)(populateQuery, options.populatePaths);
476
+ return [4 /*yield*/, populateQuery.exec()];
477
+ case 17:
478
+ doc = _h.sent();
479
+ _h.label = 18;
480
+ case 18:
481
+ if (!(options.postUpdate && !skipPostHooks)) return [3 /*break*/, 22];
482
+ _h.label = 19;
483
+ case 19:
484
+ _h.trys.push([19, 21, , 22]);
485
+ return [4 /*yield*/, options.postUpdate(doc, cleanedBody, request, prevDoc)];
486
+ case 20:
487
+ _h.sent();
488
+ return [3 /*break*/, 22];
489
+ case 21:
490
+ error_7 = _h.sent();
491
+ throw (0, errors_1.passthroughOrWrap)(error_7, {
492
+ code: "post-update-hook-error",
493
+ detail: "postUpdate hook error on ".concat(id, ": ").concat((0, errors_1.errorMessage)(error_7)),
494
+ status: 400,
495
+ title: "postUpdate hook error",
496
+ });
497
+ case 22: return [2 /*return*/, { cleanedBody: cleanedBody, doc: doc, prevDoc: prevDoc }];
498
+ }
499
+ });
500
+ }); };
501
+ exports.executeUpdate = executeUpdate;
502
+ /** C5 (FIX 6): run `postUpdate` outside the write/ledger-finalize window — see `runPostCreate`. */
503
+ var runPostUpdate = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
504
+ var doc = _b.doc, cleanedBody = _b.cleanedBody, prevDoc = _b.prevDoc, options = _b.options, request = _b.request;
505
+ return __generator(this, function (_c) {
506
+ switch (_c.label) {
507
+ case 0:
508
+ if (!options.postUpdate) return [3 /*break*/, 2];
509
+ return [4 /*yield*/, options.postUpdate(doc, cleanedBody, request, prevDoc)];
510
+ case 1:
511
+ _c.sent();
512
+ _c.label = 2;
513
+ case 2: return [2 /*return*/];
514
+ }
515
+ });
516
+ }); };
517
+ exports.runPostUpdate = runPostUpdate;
518
+ /**
519
+ * Delete a document through the same pipeline as `DELETE /:id`: method-level and object-level
520
+ * permissions, doc loading (404), `preDelete`, soft delete (`deleted = true` + save when the
521
+ * schema has a Boolean `deleted` path, else `doc.deleteOne()`), and `postDelete`. Throws
522
+ * APIErrors with the same statuses/titles as the REST handler.
523
+ */
524
+ var executeDelete = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
525
+ var request, doc, error_8, alreadyDeleted, tombstone, resolved, body, error_9, error_10, error_11;
526
+ var _c;
527
+ var model = _b.model, options = _b.options, user = _b.user, id = _b.id, existingDoc = _b.existingDoc, req = _b.req, skipPostHooks = _b.skipPostHooks;
528
+ return __generator(this, function (_d) {
529
+ switch (_d.label) {
530
+ case 0:
531
+ request = req !== null && req !== void 0 ? req : stubRequest(user);
532
+ return [4 /*yield*/, (0, permissions_1.checkPermissions)("delete", options.permissions.delete, user)];
533
+ case 1:
534
+ if (!(_d.sent())) {
535
+ throw new errors_1.APIError({
536
+ status: 405,
537
+ title: "Access to DELETE on ".concat(model.modelName, " denied for ").concat(user === null || user === void 0 ? void 0 : user.id),
538
+ });
539
+ }
540
+ doc = existingDoc;
541
+ if (!!doc) return [3 /*break*/, 8];
542
+ _d.label = 2;
543
+ case 2:
544
+ _d.trys.push([2, 4, , 8]);
545
+ return [4 /*yield*/, (0, docLoader_1.loadDocOr404)(model, id, options.populatePaths)];
546
+ case 3:
547
+ doc = (_d.sent());
548
+ return [3 /*break*/, 8];
549
+ case 4:
550
+ error_8 = _d.sent();
551
+ alreadyDeleted = (0, errors_1.isAPIError)(error_8) &&
552
+ error_8.status === 404 &&
553
+ ((_c = error_8.meta) === null || _c === void 0 ? void 0 : _c.deleted) === "true";
554
+ if (!alreadyDeleted) return [3 /*break*/, 7];
555
+ return [4 /*yield*/, model.find({ _id: id, deleted: { $in: [true, false] } }).limit(1)];
556
+ case 5:
557
+ tombstone = _d.sent();
558
+ resolved = tombstone[0];
559
+ if (!resolved) {
560
+ throw error_8;
561
+ }
562
+ return [4 /*yield*/, (0, permissions_1.checkPermissions)("delete", options.permissions.delete, user, resolved)];
563
+ case 6:
564
+ if (!(_d.sent())) {
565
+ throw new errors_1.APIError({
566
+ status: 403,
567
+ title: "Access to GET on ".concat(model.modelName, ":").concat(id, " denied for ").concat(user === null || user === void 0 ? void 0 : user.id),
568
+ });
569
+ }
570
+ return [2 /*return*/, { doc: resolved }];
571
+ case 7: throw error_8;
572
+ case 8: return [4 /*yield*/, (0, permissions_1.checkPermissions)("delete", options.permissions.delete, user, doc)];
573
+ case 9:
574
+ if (!(_d.sent())) {
575
+ throw new errors_1.APIError({
576
+ status: 403,
577
+ title: "Access to GET on ".concat(model.modelName, ":").concat(id, " denied for ").concat(user === null || user === void 0 ? void 0 : user.id),
578
+ });
579
+ }
580
+ if (!options.preDelete) return [3 /*break*/, 14];
581
+ body = void 0;
582
+ _d.label = 10;
583
+ case 10:
584
+ _d.trys.push([10, 12, , 13]);
585
+ return [4 /*yield*/, options.preDelete(doc, request)];
586
+ case 11:
587
+ body = _d.sent();
588
+ return [3 /*break*/, 13];
589
+ case 12:
590
+ error_9 = _d.sent();
591
+ throw (0, errors_1.passthroughOrWrap)(error_9, {
592
+ code: "pre-delete-hook-error",
593
+ detail: "preDelete hook error on ".concat(id, ": ").concat((0, errors_1.errorMessage)(error_9)),
594
+ status: 403,
595
+ title: "preDelete hook error",
596
+ });
597
+ case 13:
598
+ if (body === undefined) {
599
+ throw new errors_1.APIError({
600
+ detail: "A body must be returned from preDelete",
601
+ status: 403,
602
+ title: "Delete not allowed",
603
+ });
604
+ }
605
+ if (body === null) {
606
+ throw new errors_1.APIError({
607
+ detail: "preDelete hook for ".concat(id, " returned null"),
608
+ status: 403,
609
+ title: "Delete not allowed",
610
+ });
611
+ }
612
+ _d.label = 14;
613
+ case 14:
614
+ if (!(Object.keys(model.schema.paths).includes("deleted") &&
615
+ model.schema.paths.deleted.instance === "Boolean")) return [3 /*break*/, 16];
616
+ doc.deleted = true;
617
+ return [4 /*yield*/, doc.save()];
618
+ case 15:
619
+ _d.sent();
620
+ return [3 /*break*/, 19];
621
+ case 16:
622
+ _d.trys.push([16, 18, , 19]);
623
+ return [4 /*yield*/, doc.deleteOne()];
624
+ case 17:
625
+ _d.sent();
626
+ return [3 /*break*/, 19];
627
+ case 18:
628
+ error_10 = _d.sent();
629
+ throw (0, errors_1.passthroughOrWrap)(error_10, {
630
+ code: "delete-error",
631
+ status: 400,
632
+ title: "Delete error",
633
+ });
634
+ case 19:
635
+ if (!(options.postDelete && !skipPostHooks)) return [3 /*break*/, 23];
636
+ _d.label = 20;
637
+ case 20:
638
+ _d.trys.push([20, 22, , 23]);
639
+ return [4 /*yield*/, options.postDelete(request, doc)];
640
+ case 21:
641
+ _d.sent();
642
+ return [3 /*break*/, 23];
643
+ case 22:
644
+ error_11 = _d.sent();
645
+ throw (0, errors_1.passthroughOrWrap)(error_11, {
646
+ code: "post-delete-hook-error",
647
+ status: 400,
648
+ title: "postDelete hook error",
649
+ });
650
+ case 23: return [2 /*return*/, { doc: doc }];
651
+ }
652
+ });
653
+ }); };
654
+ exports.executeDelete = executeDelete;
655
+ /** C5 (FIX 6): run `postDelete` outside the write/ledger-finalize window — see `runPostCreate`. */
656
+ var runPostDelete = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
657
+ var doc = _b.doc, options = _b.options, request = _b.request;
658
+ return __generator(this, function (_c) {
659
+ switch (_c.label) {
660
+ case 0:
661
+ if (!options.postDelete) return [3 /*break*/, 2];
662
+ return [4 /*yield*/, options.postDelete(request, doc)];
663
+ case 1:
664
+ _c.sent();
665
+ _c.label = 2;
666
+ case 2: return [2 /*return*/];
667
+ }
668
+ });
669
+ }); };
670
+ exports.runPostDelete = runPostDelete;