@terreno/api 57.4.0 → 57.6.1

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 (210) 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 +617 -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/api.arrayOperations.test.ts +44 -0
  173. package/src/api.ts +64 -39
  174. package/src/audit/auditApp.test.ts +5 -5
  175. package/src/audit/auditEventModel.ts +7 -3
  176. package/src/audit/auditRouter.test.ts +5 -5
  177. package/src/audit/rbacSink.test.ts +2 -2
  178. package/src/audit/record.test.ts +2 -2
  179. package/src/audit/record.ts +3 -2
  180. package/src/auth.ts +1 -1
  181. package/src/authRecovery.test.ts +43 -0
  182. package/src/authRecovery.ts +16 -10
  183. package/src/authTokens.ts +6 -2
  184. package/src/authVerification.test.ts +22 -0
  185. package/src/browserLogsRoute.ts +110 -0
  186. package/src/configurationPlugin.test.ts +1 -11
  187. package/src/expressServer.ts +10 -0
  188. package/src/frameworkModelNames.test.ts +62 -0
  189. package/src/frameworkModelNames.ts +33 -0
  190. package/src/index.ts +7 -0
  191. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  192. package/src/mcp/auth.test.ts +34 -1
  193. package/src/migrations/cli.test.ts +0 -23
  194. package/src/models/mcpServiceToken.ts +4 -3
  195. package/src/models/notification.ts +3 -2
  196. package/src/models/notificationPreference.ts +1 -1
  197. package/src/notifications/notificationsApp.test.ts +24 -1
  198. package/src/notifiers/slackNotifier.test.ts +186 -1
  199. package/src/notifiers/slackNotifier.ts +167 -8
  200. package/src/orgs/orgPlugin.ts +1 -1
  201. package/src/orgs/organizationModel.ts +11 -6
  202. package/src/plugins.test.ts +5 -0
  203. package/src/plugins.ts +3 -0
  204. package/src/realtime/realtimeApp.ts +1 -1
  205. package/src/sync/integration.test.ts +2 -2
  206. package/src/terrenoApp.ts +3 -0
  207. package/src/types.d.ts +1 -0
  208. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  209. package/tsconfig.json +13 -54
  210. package/tsconfig.typedoc.json +2 -0
package/dist/api.js CHANGED
@@ -1,15 +1,4 @@
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
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
3
  if (k2 === undefined) k2 = k;
15
4
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -43,78 +32,6 @@ var __importStar = (this && this.__importStar) || (function () {
43
32
  return result;
44
33
  };
45
34
  })();
46
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
47
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
48
- return new (P || (P = Promise))(function (resolve, reject) {
49
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
50
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
51
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
52
- step((generator = generator.apply(thisArg, _arguments || [])).next());
53
- });
54
- };
55
- var __generator = (this && this.__generator) || function (thisArg, body) {
56
- 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);
57
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
58
- function verb(n) { return function (v) { return step([n, v]); }; }
59
- function step(op) {
60
- if (f) throw new TypeError("Generator is already executing.");
61
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
62
- 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;
63
- if (y = 0, t) op = [op[0] & 2, t.value];
64
- switch (op[0]) {
65
- case 0: case 1: t = op; break;
66
- case 4: _.label++; return { value: op[1], done: false };
67
- case 5: _.label++; y = op[1]; op = [0]; continue;
68
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
69
- default:
70
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
71
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
72
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
73
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
74
- if (t[2]) _.ops.pop();
75
- _.trys.pop(); continue;
76
- }
77
- op = body.call(thisArg, _);
78
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
79
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
80
- }
81
- };
82
- var __values = (this && this.__values) || function(o) {
83
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
84
- if (m) return m.call(o);
85
- if (o && typeof o.length === "number") return {
86
- next: function () {
87
- if (o && i >= o.length) o = void 0;
88
- return { value: o && o[i++], done: !o };
89
- }
90
- };
91
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
92
- };
93
- var __read = (this && this.__read) || function (o, n) {
94
- var m = typeof Symbol === "function" && o[Symbol.iterator];
95
- if (!m) return o;
96
- var i = m.call(o), r, ar = [], e;
97
- try {
98
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
99
- }
100
- catch (error) { e = { error: error }; }
101
- finally {
102
- try {
103
- if (r && !r.done && (m = i["return"])) m.call(i);
104
- }
105
- finally { if (e) throw e.error; }
106
- }
107
- return ar;
108
- };
109
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
110
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
111
- if (ar || !(i in from)) {
112
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
113
- ar[i] = from[i];
114
- }
115
- }
116
- return to.concat(ar || Array.prototype.slice.call(from));
117
- };
118
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
119
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
120
37
  };
@@ -126,48 +43,37 @@ exports.modelRouter = modelRouter;
126
43
  *
127
44
  * @packageDocumentation
128
45
  */
129
- var Sentry = __importStar(require("@sentry/bun"));
130
- var express_1 = __importDefault(require("express"));
131
- var cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
132
- var luxon_1 = require("luxon");
133
- var mongoose_1 = __importDefault(require("mongoose"));
134
- var actions_1 = require("./actions");
135
- var adminModelRouter_1 = require("./adminModelRouter");
136
- var record_1 = require("./audit/record");
137
- var auth_1 = require("./auth");
138
- var collectionRegistry_1 = require("./collectionRegistry");
139
- var errors_1 = require("./errors");
140
- var logger_1 = require("./logger");
141
- var registry_1 = require("./mcp/registry");
142
- var openApi_1 = require("./openApi");
143
- var openApiValidator_1 = require("./openApiValidator");
144
- var permissions_1 = require("./permissions");
145
- var modelRouterAccess_1 = require("./rbac/modelRouterAccess");
146
- var deprecation_1 = require("./realtime/deprecation");
147
- var executors_1 = require("./sync/executors");
148
- var transformers_1 = require("./transformers");
149
- var utils_1 = require("./utils");
150
- var addPopulateToQuery = function (
46
+ const Sentry = __importStar(require("@sentry/bun"));
47
+ const express_1 = __importDefault(require("express"));
48
+ const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
49
+ const luxon_1 = require("luxon");
50
+ const mongoose_1 = __importDefault(require("mongoose"));
51
+ const actions_1 = require("./actions");
52
+ const adminModelRouter_1 = require("./adminModelRouter");
53
+ const record_1 = require("./audit/record");
54
+ const auth_1 = require("./auth");
55
+ const collectionRegistry_1 = require("./collectionRegistry");
56
+ const errors_1 = require("./errors");
57
+ const logger_1 = require("./logger");
58
+ const registry_1 = require("./mcp/registry");
59
+ const openApi_1 = require("./openApi");
60
+ const openApiValidator_1 = require("./openApiValidator");
61
+ const permissions_1 = require("./permissions");
62
+ const modelRouterAccess_1 = require("./rbac/modelRouterAccess");
63
+ const deprecation_1 = require("./realtime/deprecation");
64
+ const executors_1 = require("./sync/executors");
65
+ const transformers_1 = require("./transformers");
66
+ const utils_1 = require("./utils");
67
+ const addPopulateToQuery = (
151
68
  // noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
152
69
  // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
153
- builtQuery, populatePaths) {
154
- var e_1, _a;
155
- var paths = populatePaths !== null && populatePaths !== void 0 ? populatePaths : [];
156
- var query = builtQuery;
157
- try {
158
- for (var paths_1 = __values(paths), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {
159
- var populatePath = paths_1_1.value;
160
- var path = populatePath.path;
161
- var select = populatePath.fields;
162
- query = builtQuery.populate({ path: path, select: select });
163
- }
164
- }
165
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
166
- finally {
167
- try {
168
- if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);
169
- }
170
- finally { if (e_1) throw e_1.error; }
70
+ builtQuery, populatePaths) => {
71
+ const paths = populatePaths ?? [];
72
+ let query = builtQuery;
73
+ for (const populatePath of paths) {
74
+ const path = populatePath.path;
75
+ const select = populatePath.fields;
76
+ query = builtQuery.populate({ path, select });
171
77
  }
172
78
  return query;
173
79
  };
@@ -177,20 +83,20 @@ exports.addPopulateToQuery = addPopulateToQuery;
177
83
  // Support more complex query fields
178
84
  // Rate limiting
179
85
  // These are the query params that are reserved for pagination.
180
- var PAGINATION_QUERY_PARAMS = ["limit", "page", "sort"];
86
+ const PAGINATION_QUERY_PARAMS = ["limit", "page", "sort"];
181
87
  // Add support for more complex queries.
182
- var COMPLEX_QUERY_PARAMS = ["$and", "$or"];
88
+ const COMPLEX_QUERY_PARAMS = ["$and", "$or"];
183
89
  /**
184
90
  * Parses a date-range query bound from an ISO-8601 string using Luxon, throwing a 400
185
91
  * APIError when the value cannot be parsed. Centralizes date-string parsing so the repo's
186
92
  * Luxon convention is honored for admin changelist date-range filters.
187
93
  */
188
- var parseDateRangeBound = function (rawValue, queryKey) {
189
- var parsed = luxon_1.DateTime.fromISO(String(rawValue), { zone: "utc" });
94
+ const parseDateRangeBound = (rawValue, queryKey) => {
95
+ const parsed = luxon_1.DateTime.fromISO(String(rawValue), { zone: "utc" });
190
96
  if (!parsed.isValid) {
191
97
  throw new errors_1.BadRequestError({
192
98
  code: "invalid-date-query-parameter",
193
- detail: "Invalid date for query parameter ".concat(queryKey),
99
+ detail: `Invalid date for query parameter ${queryKey}`,
194
100
  source: { parameter: queryKey },
195
101
  title: "Invalid date query parameter",
196
102
  });
@@ -201,114 +107,71 @@ var parseDateRangeBound = function (rawValue, queryKey) {
201
107
  * Collapses `field_gte` / `field_lte` query pairs into `{ field: { $gte, $lte } }` for Date paths,
202
108
  * so admin changelist date-range filters map to valid Mongoose range queries.
203
109
  */
204
- var mergeDateRangeQueryParams = function (model, query) {
205
- var e_2, _a, e_3, _b;
206
- var schema = model.schema;
207
- var result = __assign({}, query);
208
- var dateRangeBases = new Set();
209
- try {
210
- for (var _c = __values(Object.keys(result)), _d = _c.next(); !_d.done; _d = _c.next()) {
211
- var key = _d.value;
212
- var match = /^(.+)_(gte|lte)$/.exec(key);
213
- if (!match) {
214
- continue;
215
- }
216
- var baseField = match[1];
217
- var path = schema.path(baseField);
218
- if ((path === null || path === void 0 ? void 0 : path.instance) !== "Date") {
219
- continue;
220
- }
221
- dateRangeBases.add(baseField);
110
+ const mergeDateRangeQueryParams = (model, query) => {
111
+ const schema = model.schema;
112
+ const result = { ...query };
113
+ const dateRangeBases = new Set();
114
+ for (const key of Object.keys(result)) {
115
+ const match = /^(.+)_(gte|lte)$/.exec(key);
116
+ if (!match) {
117
+ continue;
222
118
  }
223
- }
224
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
225
- finally {
226
- try {
227
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
119
+ const baseField = match[1];
120
+ const path = schema.path(baseField);
121
+ if (path?.instance !== "Date") {
122
+ continue;
228
123
  }
229
- finally { if (e_2) throw e_2.error; }
230
- }
231
- try {
232
- for (var dateRangeBases_1 = __values(dateRangeBases), dateRangeBases_1_1 = dateRangeBases_1.next(); !dateRangeBases_1_1.done; dateRangeBases_1_1 = dateRangeBases_1.next()) {
233
- var baseField = dateRangeBases_1_1.value;
234
- var gteKey = "".concat(baseField, "_gte");
235
- var lteKey = "".concat(baseField, "_lte");
236
- var gteRaw = result[gteKey];
237
- var lteRaw = result[lteKey];
238
- var bounds = {};
239
- if (gteRaw !== undefined && gteRaw !== null && String(gteRaw).trim() !== "") {
240
- bounds.$gte = parseDateRangeBound(gteRaw, gteKey);
241
- }
242
- if (lteRaw !== undefined && lteRaw !== null && String(lteRaw).trim() !== "") {
243
- bounds.$lte = parseDateRangeBound(lteRaw, lteKey);
244
- }
245
- if (Object.keys(bounds).length === 0) {
246
- continue;
247
- }
248
- delete result[gteKey];
249
- delete result[lteKey];
250
- var direct = result[baseField];
251
- if (direct !== undefined && direct !== null && typeof direct !== "object") {
252
- delete result[baseField];
253
- }
254
- if (typeof direct === "object" && direct !== null && !Array.isArray(direct)) {
255
- result[baseField] = __assign(__assign({}, direct), bounds);
256
- }
257
- else {
258
- result[baseField] = bounds;
259
- }
124
+ dateRangeBases.add(baseField);
125
+ }
126
+ for (const baseField of dateRangeBases) {
127
+ const gteKey = `${baseField}_gte`;
128
+ const lteKey = `${baseField}_lte`;
129
+ const gteRaw = result[gteKey];
130
+ const lteRaw = result[lteKey];
131
+ const bounds = {};
132
+ if (gteRaw !== undefined && gteRaw !== null && String(gteRaw).trim() !== "") {
133
+ bounds.$gte = parseDateRangeBound(gteRaw, gteKey);
260
134
  }
261
- }
262
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
263
- finally {
264
- try {
265
- if (dateRangeBases_1_1 && !dateRangeBases_1_1.done && (_b = dateRangeBases_1.return)) _b.call(dateRangeBases_1);
135
+ if (lteRaw !== undefined && lteRaw !== null && String(lteRaw).trim() !== "") {
136
+ bounds.$lte = parseDateRangeBound(lteRaw, lteKey);
137
+ }
138
+ if (Object.keys(bounds).length === 0) {
139
+ continue;
140
+ }
141
+ delete result[gteKey];
142
+ delete result[lteKey];
143
+ const direct = result[baseField];
144
+ if (direct !== undefined && direct !== null && typeof direct !== "object") {
145
+ delete result[baseField];
146
+ }
147
+ if (typeof direct === "object" && direct !== null && !Array.isArray(direct)) {
148
+ result[baseField] = { ...direct, ...bounds };
149
+ }
150
+ else {
151
+ result[baseField] = bounds;
266
152
  }
267
- finally { if (e_3) throw e_3.error; }
268
153
  }
269
154
  return result;
270
155
  };
271
156
  // Ensures query params are allowed. Also checks nested query params when using $and/$or.
272
- var checkQueryParamAllowed = function (queryParam, queryParamValue, queryFields) {
273
- var e_4, _a, e_5, _b;
274
- if (queryFields === void 0) { queryFields = []; }
157
+ const checkQueryParamAllowed = (queryParam, queryParamValue, queryFields = []) => {
275
158
  // Cast for iteration through complex query values
276
- var complexValue = queryParamValue;
159
+ const complexValue = queryParamValue;
277
160
  // Check the values of each of the complex query params. We don't support recursive queries here,
278
161
  // just one level of and/or
279
162
  if (COMPLEX_QUERY_PARAMS.includes(queryParam)) {
280
- try {
281
- // Complex query of the form `$and: [{key1: value1}, {key2: value2}]`
282
- for (var complexValue_1 = __values(complexValue), complexValue_1_1 = complexValue_1.next(); !complexValue_1_1.done; complexValue_1_1 = complexValue_1.next()) {
283
- var subQuery = complexValue_1_1.value;
284
- try {
285
- for (var _c = (e_5 = void 0, __values(Object.keys(subQuery))), _d = _c.next(); !_d.done; _d = _c.next()) {
286
- var subKey = _d.value;
287
- checkQueryParamAllowed(subKey, subQuery[subKey], queryFields);
288
- }
289
- }
290
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
291
- finally {
292
- try {
293
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
294
- }
295
- finally { if (e_5) throw e_5.error; }
296
- }
163
+ // Complex query of the form `$and: [{key1: value1}, {key2: value2}]`
164
+ for (const subQuery of complexValue) {
165
+ for (const subKey of Object.keys(subQuery)) {
166
+ checkQueryParamAllowed(subKey, subQuery[subKey], queryFields);
297
167
  }
298
168
  }
299
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
300
- finally {
301
- try {
302
- if (complexValue_1_1 && !complexValue_1_1.done && (_a = complexValue_1.return)) _a.call(complexValue_1);
303
- }
304
- finally { if (e_4) throw e_4.error; }
305
- }
306
169
  return;
307
170
  }
308
171
  if (!queryFields.includes(queryParam)) {
309
172
  throw new errors_1.BadRequestError({
310
173
  code: "query-param-not-allowed",
311
- detail: "".concat(queryParam, " is not allowed as a query param."),
174
+ detail: `${queryParam} is not allowed as a query param.`,
312
175
  source: { parameter: queryParam },
313
176
  title: "Query parameter not allowed",
314
177
  });
@@ -335,27 +198,26 @@ var checkQueryParamAllowed = function (queryParam, queryParamValue, queryFields)
335
198
  // Helper to determine if validation should be enabled for a specific operation.
336
199
  // When options.validation is not set, returns true — the middleware's own
337
200
  // isConfigured check will decide whether to actually validate.
338
- var shouldValidate = function (options, operation) {
339
- var _a, _b, _c;
201
+ const shouldValidate = (options, operation) => {
340
202
  // Check route-specific validation option first
341
203
  if (options.validation !== undefined) {
342
204
  if (typeof options.validation === "boolean") {
343
205
  return options.validation;
344
206
  }
345
207
  if (operation === "create") {
346
- return (_a = options.validation.validateCreate) !== null && _a !== void 0 ? _a : true;
208
+ return options.validation.validateCreate ?? true;
347
209
  }
348
210
  if (operation === "update") {
349
- return (_b = options.validation.validateUpdate) !== null && _b !== void 0 ? _b : true;
211
+ return options.validation.validateUpdate ?? true;
350
212
  }
351
- return (_c = options.validation.validateQuery) !== null && _c !== void 0 ? _c : true;
213
+ return options.validation.validateQuery ?? true;
352
214
  }
353
215
  // Default: let middleware's isConfigured check decide
354
216
  return true;
355
217
  };
356
218
  // Get body validation middleware if validation is enabled
357
- var getBodyValidationMiddleware = function (model, options, operation) {
358
- var validationOptions = {};
219
+ const getBodyValidationMiddleware = (model, options, operation) => {
220
+ const validationOptions = {};
359
221
  if (!shouldValidate(options, operation)) {
360
222
  validationOptions.enabled = false;
361
223
  }
@@ -367,10 +229,10 @@ var getBodyValidationMiddleware = function (model, options, operation) {
367
229
  validationOptions.onAdditionalPropertiesRemoved =
368
230
  options.validation.onAdditionalPropertiesRemoved;
369
231
  }
370
- var excludeFields = operation === "create"
232
+ const excludeFields = operation === "create"
371
233
  ? options.validation.excludeFromCreate
372
234
  : options.validation.excludeFromUpdate;
373
- if (excludeFields === null || excludeFields === void 0 ? void 0 : excludeFields.length) {
235
+ if (excludeFields?.length) {
374
236
  validationOptions.excludeFields = excludeFields;
375
237
  }
376
238
  }
@@ -380,9 +242,9 @@ var getBodyValidationMiddleware = function (model, options, operation) {
380
242
  return (0, openApiValidator_1.validateModelRequestBody)(model, validationOptions);
381
243
  };
382
244
  // Get query validation middleware if validation is enabled
383
- var getQueryValidationMiddleware = function (model, options) {
384
- var querySchema = (0, openApiValidator_1.buildQuerySchemaFromFields)(model, options.queryFields);
385
- var validationOptions = {};
245
+ const getQueryValidationMiddleware = (model, options) => {
246
+ const querySchema = (0, openApiValidator_1.buildQuerySchemaFromFields)(model, options.queryFields);
247
+ const validationOptions = {};
386
248
  if (!shouldValidate(options, "query")) {
387
249
  validationOptions.enabled = false;
388
250
  }
@@ -392,9 +254,9 @@ var getQueryValidationMiddleware = function (model, options) {
392
254
  return (0, openApiValidator_1.validateQueryParams)(querySchema, validationOptions);
393
255
  };
394
256
  function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
395
- var model;
396
- var options;
397
- var path;
257
+ let model;
258
+ let options;
259
+ let path;
398
260
  if (typeof pathOrModel === "string") {
399
261
  path = pathOrModel;
400
262
  model = modelOrOptions;
@@ -409,53 +271,62 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
409
271
  if (options.mcp && path === undefined) {
410
272
  (0, registry_1.registerMCPModel)(model, options.mcp, options);
411
273
  }
412
- var shouldDeferBuild = path !== undefined && Boolean(options.access) && !options.accessControl;
274
+ const shouldDeferBuild = path !== undefined && Boolean(options.access) && !options.accessControl;
413
275
  if (path !== undefined) {
414
276
  if (options.realtime) {
415
277
  (0, deprecation_1.warnRealtimeDeprecated)(model.modelName, path);
416
278
  }
417
- (0, collectionRegistry_1.registerCollection)({ model: model, options: options, routePath: path });
279
+ (0, collectionRegistry_1.registerCollection)({ model, options, routePath: path });
418
280
  }
419
- var router = shouldDeferBuild ? express_1.default.Router() : _buildModelRouter(model, options, path);
281
+ const router = shouldDeferBuild ? express_1.default.Router() : _buildModelRouter(model, options, path);
420
282
  if (path !== undefined) {
421
283
  return {
422
284
  __type: "modelRouter",
423
- _buildWithContext: function (context) {
424
- var _a;
425
- var enrichedOptions = (0, adminModelRouter_1.enrichModelRouterOptions)(model, __assign(__assign({}, options), { openApi: context.openApi }), context);
426
- var runtimeOptions = __assign(__assign({}, enrichedOptions), { accessControl: (_a = enrichedOptions.accessControl) !== null && _a !== void 0 ? _a : context.accessControl });
285
+ _buildWithContext: (context) => {
286
+ const enrichedOptions = (0, adminModelRouter_1.enrichModelRouterOptions)(model, { ...options, openApi: context.openApi }, context);
287
+ const runtimeOptions = {
288
+ ...enrichedOptions,
289
+ accessControl: enrichedOptions.accessControl ?? context.accessControl,
290
+ };
427
291
  (0, collectionRegistry_1.replaceCollectionOptions)(path, runtimeOptions);
428
292
  return _buildModelRouter(model, runtimeOptions, path);
429
293
  },
430
- model: model,
431
- options: options,
432
- path: path,
433
- router: router,
294
+ model,
295
+ options,
296
+ path,
297
+ router,
434
298
  };
435
299
  }
436
300
  if (options.realtime) {
437
301
  (0, deprecation_1.warnRealtimeDeprecated)(model.modelName);
438
- logger_1.logger.warn("modelRouter for ".concat(model.modelName, " has realtime config but was called without a path. ") +
302
+ logger_1.logger.warn(`modelRouter for ${model.modelName} has realtime config but was called without a path. ` +
439
303
  "Realtime sync only works with the three-argument form: modelRouter('/path', Model, options)");
440
304
  }
441
305
  if (options.sync) {
442
- logger_1.logger.warn("modelRouter for ".concat(model.modelName, " has sync config but was called without a path. ") +
306
+ logger_1.logger.warn(`modelRouter for ${model.modelName} has sync config but was called without a path. ` +
443
307
  "Local-first sync only works with the three-argument form: modelRouter('/path', Model, options)");
444
308
  }
445
309
  return router;
446
310
  }
447
- var _buildModelRouter = function (model, options, routePath) {
448
- var _a, _b, _c, _d, _e;
449
- var router = express_1.default.Router();
450
- var resolvedAccess = (0, modelRouterAccess_1.resolveModelRouterAccess)({
311
+ const _buildModelRouter = (model, options, routePath) => {
312
+ const router = express_1.default.Router();
313
+ const resolvedAccess = (0, modelRouterAccess_1.resolveModelRouterAccess)({
451
314
  access: options.access,
452
315
  accessControl: options.accessControl,
453
316
  permissions: options.permissions,
454
317
  queryFilter: options.queryFilter,
455
318
  responseHandler: options.responseHandler,
456
- scope: (_a = options.access) === null || _a === void 0 ? void 0 : _a.scope,
319
+ scope: options.access?.scope,
457
320
  });
458
- options = __assign(__assign({}, options), { permissions: resolvedAccess.permissions, queryFilter: ((_b = resolvedAccess.queryFilter) !== null && _b !== void 0 ? _b : options.queryFilter), responseHandler: ((_d = (_c = resolvedAccess.responseHandler) !== null && _c !== void 0 ? _c : options.responseHandler) !== null && _d !== void 0 ? _d : transformers_1.defaultResponseHandler) });
321
+ options = {
322
+ ...options,
323
+ permissions: resolvedAccess.permissions,
324
+ queryFilter: (resolvedAccess.queryFilter ??
325
+ options.queryFilter),
326
+ responseHandler: (resolvedAccess.responseHandler ??
327
+ options.responseHandler ??
328
+ transformers_1.defaultResponseHandler),
329
+ };
459
330
  if (routePath) {
460
331
  (0, collectionRegistry_1.replaceCollectionOptions)(routePath, options);
461
332
  }
@@ -468,636 +339,531 @@ var _buildModelRouter = function (model, options, routePath) {
468
339
  if (options.endpoints) {
469
340
  options.endpoints(router, options);
470
341
  }
471
- var responseHandler = (_e = options.responseHandler) !== null && _e !== void 0 ? _e : transformers_1.defaultResponseHandler;
342
+ const responseHandler = options.responseHandler ?? transformers_1.defaultResponseHandler;
472
343
  // Always install validation middleware — they are no-ops until configureOpenApiValidator() is called
473
- var createValidation = getBodyValidationMiddleware(model, options, "create");
474
- var updateValidation = getBodyValidationMiddleware(model, options, "update");
475
- var queryValidation = getQueryValidationMiddleware(model, options);
344
+ const createValidation = getBodyValidationMiddleware(model, options, "create");
345
+ const updateValidation = getBodyValidationMiddleware(model, options, "update");
346
+ const queryValidation = getQueryValidationMiddleware(model, options);
476
347
  router.post("/", [
477
348
  (0, auth_1.authenticateMiddleware)(options.allowAnonymous),
478
349
  (0, openApi_1.createOpenApiMiddleware)(model, options),
479
350
  (0, permissions_1.permissionMiddleware)(model, options),
480
351
  createValidation,
481
- ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
482
- var doc, serialized, error_1;
483
- return __generator(this, function (_a) {
484
- switch (_a.label) {
485
- case 0: return [4 /*yield*/, (0, executors_1.executeCreate)({
486
- body: req.body,
487
- model: model,
488
- options: options,
489
- req: req,
490
- user: req.user,
491
- })];
492
- case 1:
493
- doc = (_a.sent()).doc;
494
- void (0, record_1.maybeRecordModelRouterAudit)({
495
- after: doc,
496
- audit: options.audit,
497
- modelName: model.modelName,
498
- operation: "create",
499
- recordId: String(doc._id),
500
- req: req,
501
- verb: "created",
502
- });
503
- _a.label = 2;
504
- case 2:
505
- _a.trys.push([2, 4, , 5]);
506
- return [4 /*yield*/, responseHandler(doc, "create", req, options)];
507
- case 3:
508
- serialized = _a.sent();
509
- return [2 /*return*/, res.status(201).json({ data: serialized })];
510
- case 4:
511
- error_1 = _a.sent();
512
- throw (0, errors_1.passthroughOrWrap)(error_1, {
513
- code: "response-handler-error",
514
- title: "responseHandler error",
515
- });
516
- case 5: return [2 /*return*/];
517
- }
352
+ ], (0, exports.asyncHandler)(async (req, res) => {
353
+ const { doc } = await (0, executors_1.executeCreate)({
354
+ body: req.body,
355
+ model,
356
+ options,
357
+ req,
358
+ user: req.user,
359
+ });
360
+ void (0, record_1.maybeRecordModelRouterAudit)({
361
+ after: doc,
362
+ audit: options.audit,
363
+ modelName: model.modelName,
364
+ operation: "create",
365
+ recordId: String(doc._id),
366
+ req,
367
+ verb: "created",
518
368
  });
519
- }); }));
369
+ try {
370
+ const serialized = await responseHandler(doc, "create", req, options);
371
+ return res.status(201).json({ data: serialized });
372
+ }
373
+ catch (error) {
374
+ throw (0, errors_1.passthroughOrWrap)(error, {
375
+ code: "response-handler-error",
376
+ title: "responseHandler error",
377
+ });
378
+ }
379
+ }));
520
380
  router.get("/", [
521
381
  (0, auth_1.authenticateMiddleware)(options.allowAnonymous),
522
382
  (0, permissions_1.permissionMiddleware)(model, options),
523
383
  (0, openApi_1.listOpenApiMiddleware)(model, options, routePath),
524
384
  queryValidation,
525
- ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
526
- var query, _a, _b, queryParam, _c, _d, queryParam, queryFilter, error_2, _e, _f, _g, key, value, limit, builtQuery, total, populatedQuery, data, error_3, serialized, error_4, more, msg;
527
- var e_6, _h, e_7, _j, e_8, _k;
528
- var _l, _m, _o, _p, _q, _r;
529
- return __generator(this, function (_s) {
530
- switch (_s.label) {
531
- case 0:
532
- query = {};
533
- try {
534
- for (_a = __values(Object.keys((_l = options.defaultQueryParams) !== null && _l !== void 0 ? _l : [])), _b = _a.next(); !_b.done; _b = _a.next()) {
535
- queryParam = _b.value;
536
- query[queryParam] = (_m = options.defaultQueryParams) === null || _m === void 0 ? void 0 : _m[queryParam];
537
- }
538
- }
539
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
540
- finally {
541
- try {
542
- if (_b && !_b.done && (_h = _a.return)) _h.call(_a);
543
- }
544
- finally { if (e_6) throw e_6.error; }
545
- }
546
- try {
547
- for (_c = __values(Object.keys(req.query)), _d = _c.next(); !_d.done; _d = _c.next()) {
548
- queryParam = _d.value;
549
- if (PAGINATION_QUERY_PARAMS.includes(queryParam)) {
550
- continue;
551
- }
552
- checkQueryParamAllowed(queryParam, req.query[queryParam], options.queryFields);
553
- // Not sure if this is necessary or if mongoose does the right thing.
554
- if (req.query[queryParam] === "true") {
555
- query[queryParam] = true;
556
- }
557
- else if (req.query[queryParam] === "false") {
558
- query[queryParam] = false;
559
- }
560
- else {
561
- query[queryParam] = req.query[queryParam];
562
- }
563
- }
564
- }
565
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
566
- finally {
567
- try {
568
- if (_d && !_d.done && (_j = _c.return)) _j.call(_c);
569
- }
570
- finally { if (e_7) throw e_7.error; }
571
- }
572
- query = mergeDateRangeQueryParams(model, query);
573
- // Special operators. NOTE: these request Mongo Atlas.
574
- if (req.query.$search) {
575
- (_o = mongoose_1.default.connection.db) === null || _o === void 0 ? void 0 : _o.collection(model.collection.collectionName);
576
- }
577
- if (req.query.$autocomplete) {
578
- (_p = mongoose_1.default.connection.db) === null || _p === void 0 ? void 0 : _p.collection(model.collection.collectionName);
579
- }
580
- if (!options.queryFilter) return [3 /*break*/, 5];
581
- queryFilter = void 0;
582
- _s.label = 1;
583
- case 1:
584
- _s.trys.push([1, 3, , 4]);
585
- return [4 /*yield*/, options.queryFilter(req.user, query)];
586
- case 2:
587
- queryFilter = _s.sent();
588
- return [3 /*break*/, 4];
589
- case 3:
590
- error_2 = _s.sent();
591
- throw (0, errors_1.passthroughOrWrap)(error_2, {
592
- code: "query-filter-error",
593
- status: 400,
594
- title: "Query filter error",
595
- });
596
- case 4:
597
- // If the query filter returns null specifically, we know this is a query that shouldn't
598
- // return any results.
599
- if (queryFilter === null) {
600
- return [2 /*return*/, res.json({ data: [] })];
601
- }
602
- query = __assign(__assign({}, query), queryFilter);
603
- try {
604
- for (_e = __values(Object.entries(queryFilter)), _f = _e.next(); !_f.done; _f = _e.next()) {
605
- _g = __read(_f.value, 2), key = _g[0], value = _g[1];
606
- if (value === undefined) {
607
- delete query[key];
608
- }
609
- }
610
- }
611
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
612
- finally {
385
+ ], (0, exports.asyncHandler)(async (req, res) => {
386
+ let query = {};
387
+ for (const queryParam of Object.keys(options.defaultQueryParams ?? [])) {
388
+ query[queryParam] = options.defaultQueryParams?.[queryParam];
389
+ }
390
+ for (const queryParam of Object.keys(req.query)) {
391
+ if (PAGINATION_QUERY_PARAMS.includes(queryParam)) {
392
+ continue;
393
+ }
394
+ checkQueryParamAllowed(queryParam, req.query[queryParam], options.queryFields);
395
+ // Not sure if this is necessary or if mongoose does the right thing.
396
+ if (req.query[queryParam] === "true") {
397
+ query[queryParam] = true;
398
+ }
399
+ else if (req.query[queryParam] === "false") {
400
+ query[queryParam] = false;
401
+ }
402
+ else {
403
+ query[queryParam] = req.query[queryParam];
404
+ }
405
+ }
406
+ query = mergeDateRangeQueryParams(model, query);
407
+ // Special operators. NOTE: these request Mongo Atlas.
408
+ if (req.query.$search) {
409
+ mongoose_1.default.connection.db?.collection(model.collection.collectionName);
410
+ }
411
+ if (req.query.$autocomplete) {
412
+ mongoose_1.default.connection.db?.collection(model.collection.collectionName);
413
+ }
414
+ // Check if any of the keys in the query are not allowed by options.queryFilter
415
+ if (options.queryFilter) {
416
+ let queryFilter;
417
+ try {
418
+ queryFilter = await options.queryFilter(req.user, query);
419
+ }
420
+ catch (error) {
421
+ throw (0, errors_1.passthroughOrWrap)(error, {
422
+ code: "query-filter-error",
423
+ status: 400,
424
+ title: "Query filter error",
425
+ });
426
+ }
427
+ // If the query filter returns null specifically, we know this is a query that shouldn't
428
+ // return any results.
429
+ if (queryFilter === null) {
430
+ return res.json({ data: [] });
431
+ }
432
+ query = { ...query, ...queryFilter };
433
+ for (const [key, value] of Object.entries(queryFilter)) {
434
+ if (value === undefined) {
435
+ delete query[key];
436
+ }
437
+ }
438
+ }
439
+ let limit = options.defaultLimit ?? 100;
440
+ if (Number(req.query.limit)) {
441
+ limit = Math.min(Number(req.query.limit), options.maxLimit ?? 500);
442
+ }
443
+ if (query.period) {
444
+ // need to remove 'period' since it isn't part of any schemas but parsed and applied in
445
+ // queryFilter instead
446
+ query.period = undefined;
447
+ }
448
+ let builtQuery = model.find(query).limit(limit + 1);
449
+ const total = await model.countDocuments(query);
450
+ if (req.query.page) {
451
+ if (Number(req.query.page) === 0 || Number.isNaN(Number(req.query.page))) {
452
+ throw new errors_1.BadRequestError({
453
+ code: "invalid-page",
454
+ detail: `Invalid page: ${req.query.page}`,
455
+ source: { parameter: "page" },
456
+ title: "Invalid page",
457
+ });
458
+ }
459
+ builtQuery = builtQuery.skip((Number(req.query.page) - 1) * limit);
460
+ }
461
+ // Query param sort takes precedence over options.sort.
462
+ if (req.query.sort) {
463
+ builtQuery = builtQuery.sort(req.query.sort);
464
+ }
465
+ else if (options.sort) {
466
+ builtQuery = builtQuery.sort(options.sort);
467
+ }
468
+ const populatedQuery = (0, exports.addPopulateToQuery)(builtQuery, options.populatePaths);
469
+ let data;
470
+ try {
471
+ data = (await populatedQuery.exec());
472
+ }
473
+ catch (error) {
474
+ throw (0, errors_1.passthroughOrWrap)(error, {
475
+ code: "list-error",
476
+ title: "List error",
477
+ });
478
+ }
479
+ let serialized;
480
+ try {
481
+ serialized = await responseHandler(data, "list", req, options);
482
+ }
483
+ catch (error) {
484
+ throw (0, errors_1.passthroughOrWrap)(error, {
485
+ code: "response-handler-error",
486
+ title: "responseHandler error",
487
+ });
488
+ }
489
+ let more;
490
+ try {
491
+ if (serialized && Array.isArray(serialized)) {
492
+ more = serialized.length === limit + 1 && serialized.length > 0;
493
+ if (more) {
494
+ // Slice off the extra document we fetched to determine if more is true or not.
495
+ serialized = serialized.slice(0, limit);
496
+ if (!req.query.page) {
497
+ const msg = `More than ${limit} results returned for ${model.collection.name} without pagination, data may be silently truncated. req.query: ${JSON.stringify(req.query)}`;
498
+ logger_1.logger.warn(msg);
613
499
  try {
614
- if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
500
+ Sentry.captureMessage(msg);
615
501
  }
616
- finally { if (e_8) throw e_8.error; }
617
- }
618
- _s.label = 5;
619
- case 5:
620
- limit = (_q = options.defaultLimit) !== null && _q !== void 0 ? _q : 100;
621
- if (Number(req.query.limit)) {
622
- limit = Math.min(Number(req.query.limit), (_r = options.maxLimit) !== null && _r !== void 0 ? _r : 500);
623
- }
624
- if (query.period) {
625
- // need to remove 'period' since it isn't part of any schemas but parsed and applied in
626
- // queryFilter instead
627
- query.period = undefined;
628
- }
629
- builtQuery = model.find(query).limit(limit + 1);
630
- return [4 /*yield*/, model.countDocuments(query)];
631
- case 6:
632
- total = _s.sent();
633
- if (req.query.page) {
634
- if (Number(req.query.page) === 0 || Number.isNaN(Number(req.query.page))) {
635
- throw new errors_1.BadRequestError({
636
- code: "invalid-page",
637
- detail: "Invalid page: ".concat(req.query.page),
638
- source: { parameter: "page" },
639
- title: "Invalid page",
640
- });
641
- }
642
- builtQuery = builtQuery.skip((Number(req.query.page) - 1) * limit);
643
- }
644
- // Query param sort takes precedence over options.sort.
645
- if (req.query.sort) {
646
- builtQuery = builtQuery.sort(req.query.sort);
647
- }
648
- else if (options.sort) {
649
- builtQuery = builtQuery.sort(options.sort);
650
- }
651
- populatedQuery = (0, exports.addPopulateToQuery)(builtQuery, options.populatePaths);
652
- _s.label = 7;
653
- case 7:
654
- _s.trys.push([7, 9, , 10]);
655
- return [4 /*yield*/, populatedQuery.exec()];
656
- case 8:
657
- data = (_s.sent());
658
- return [3 /*break*/, 10];
659
- case 9:
660
- error_3 = _s.sent();
661
- throw (0, errors_1.passthroughOrWrap)(error_3, {
662
- code: "list-error",
663
- title: "List error",
664
- });
665
- case 10:
666
- _s.trys.push([10, 12, , 13]);
667
- return [4 /*yield*/, responseHandler(data, "list", req, options)];
668
- case 11:
669
- serialized = _s.sent();
670
- return [3 /*break*/, 13];
671
- case 12:
672
- error_4 = _s.sent();
673
- throw (0, errors_1.passthroughOrWrap)(error_4, {
674
- code: "response-handler-error",
675
- title: "responseHandler error",
676
- });
677
- case 13:
678
- try {
679
- if (serialized && Array.isArray(serialized)) {
680
- more = serialized.length === limit + 1 && serialized.length > 0;
681
- if (more) {
682
- // Slice off the extra document we fetched to determine if more is true or not.
683
- serialized = serialized.slice(0, limit);
684
- if (!req.query.page) {
685
- msg = "More than ".concat(limit, " results returned for ").concat(model.collection.name, " without pagination, data may be silently truncated. req.query: ").concat(JSON.stringify(req.query));
686
- logger_1.logger.warn(msg);
687
- try {
688
- Sentry.captureMessage(msg);
689
- }
690
- catch (error) {
691
- logger_1.logger.error("Error capturing message: ".concat(error));
692
- }
693
- }
694
- }
695
- return [2 /*return*/, res.json({
696
- data: serialized,
697
- limit: limit,
698
- more: more,
699
- page: req.query.page,
700
- total: total,
701
- })];
502
+ catch (error) {
503
+ logger_1.logger.error(`Error capturing message: ${error}`);
702
504
  }
703
- return [2 /*return*/, res.json({ data: serialized })];
704
- }
705
- catch (error) {
706
- throw (0, errors_1.passthroughOrWrap)(error, {
707
- code: "serialization-error",
708
- title: "Serialization error",
709
- });
710
505
  }
711
- return [2 /*return*/];
506
+ }
507
+ return res.json({
508
+ data: serialized,
509
+ limit,
510
+ more,
511
+ page: req.query.page,
512
+ total,
513
+ });
712
514
  }
713
- });
714
- }); }));
515
+ return res.json({ data: serialized });
516
+ }
517
+ catch (error) {
518
+ throw (0, errors_1.passthroughOrWrap)(error, {
519
+ code: "serialization-error",
520
+ title: "Serialization error",
521
+ });
522
+ }
523
+ }));
715
524
  router.get("/:id", [
716
525
  (0, auth_1.authenticateMiddleware)(options.allowAnonymous),
717
526
  (0, openApi_1.getOpenApiMiddleware)(model, options),
718
527
  (0, permissions_1.permissionMiddleware)(model, options),
719
- ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
720
- var data, serialized, error_5;
721
- return __generator(this, function (_a) {
722
- switch (_a.label) {
723
- case 0:
724
- data = req.obj;
725
- _a.label = 1;
726
- case 1:
727
- _a.trys.push([1, 3, , 4]);
728
- return [4 /*yield*/, responseHandler(data, "read", req, options)];
729
- case 2:
730
- serialized = _a.sent();
731
- return [2 /*return*/, res.json({ data: serialized })];
732
- case 3:
733
- error_5 = _a.sent();
734
- throw (0, errors_1.passthroughOrWrap)(error_5, {
735
- code: "response-handler-error",
736
- title: "responseHandler error",
737
- });
738
- case 4: return [2 /*return*/];
739
- }
740
- });
741
- }); }));
742
- router.put("/:id", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(function (_req, _res) { return __awaiter(void 0, void 0, void 0, function () {
743
- return __generator(this, function (_a) {
744
- // Patch is what we want 90% of the time
745
- throw new errors_1.APIError({
746
- code: "put-not-supported",
747
- detail: "Use PATCH to update a document.",
748
- title: "PUT is not supported.",
528
+ ], (0, exports.asyncHandler)(async (req, res) => {
529
+ const data = req.obj;
530
+ try {
531
+ const serialized = await responseHandler(data, "read", req, options);
532
+ return res.json({ data: serialized });
533
+ }
534
+ catch (error) {
535
+ throw (0, errors_1.passthroughOrWrap)(error, {
536
+ code: "response-handler-error",
537
+ title: "responseHandler error",
749
538
  });
539
+ }
540
+ }));
541
+ router.put("/:id", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(async (_req, _res) => {
542
+ // Patch is what we want 90% of the time
543
+ throw new errors_1.APIError({
544
+ code: "put-not-supported",
545
+ detail: "Use PATCH to update a document.",
546
+ title: "PUT is not supported.",
750
547
  });
751
- }); }));
548
+ }));
752
549
  router.patch("/:id", [
753
550
  (0, auth_1.authenticateMiddleware)(options.allowAnonymous),
754
551
  (0, openApi_1.patchOpenApiMiddleware)(model, options),
755
552
  (0, permissions_1.permissionMiddleware)(model, options),
756
553
  updateValidation,
757
- ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
758
- var existingDoc, bodyUpdatedAt, preciseUnmodifiedSince, httpUnmodifiedSince, timestampValue, httpTimestampValue, concurrencyCheck, usingPreciseHeader, usingHttpHeader, clientTimestamp, doc, previous, error_6, serialized, serialized, error_7;
759
- return __generator(this, function (_a) {
760
- switch (_a.label) {
761
- case 0:
762
- existingDoc = req
763
- .obj;
764
- bodyUpdatedAt = req.body._updatedAt;
765
- preciseUnmodifiedSince = req.headers["x-unmodified-since-iso"];
766
- httpUnmodifiedSince = req.headers["if-unmodified-since"];
767
- timestampValue = Array.isArray(preciseUnmodifiedSince)
768
- ? preciseUnmodifiedSince[0]
769
- : preciseUnmodifiedSince;
770
- httpTimestampValue = Array.isArray(httpUnmodifiedSince)
771
- ? httpUnmodifiedSince[0]
772
- : httpUnmodifiedSince;
773
- if (timestampValue || httpTimestampValue || bodyUpdatedAt) {
774
- usingPreciseHeader = Boolean(timestampValue);
775
- usingHttpHeader = !usingPreciseHeader && Boolean(httpTimestampValue);
776
- clientTimestamp = timestampValue
777
- ? luxon_1.DateTime.fromISO(timestampValue)
778
- : httpTimestampValue
779
- ? luxon_1.DateTime.fromHTTP(httpTimestampValue)
780
- : luxon_1.DateTime.fromISO(bodyUpdatedAt);
781
- concurrencyCheck = {
782
- // An unparseable value round-trips as an invalid Date; the executor turns it into
783
- // the 400 "Invalid conflict-detection timestamp" error after preUpdate has run.
784
- ifUnmodifiedSince: clientTimestamp.toJSDate(),
785
- invalidTimestampDetail: usingPreciseHeader
786
- ? "X-Unmodified-Since-ISO header could not be parsed as an ISO date"
787
- : usingHttpHeader
788
- ? "If-Unmodified-Since header could not be parsed as an HTTP date"
789
- : "_updatedAt body field could not be parsed as an ISO date",
790
- type: "timestamp",
791
- };
792
- }
793
- previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
794
- _a.label = 1;
795
- case 1:
796
- _a.trys.push([1, 3, , 6]);
797
- return [4 /*yield*/, (0, executors_1.executeUpdate)({
798
- body: req.body,
799
- concurrencyCheck: concurrencyCheck,
800
- existingDoc: existingDoc,
801
- id: req.params.id,
802
- model: model,
803
- options: options,
804
- req: req,
805
- user: req.user,
806
- })];
807
- case 2:
808
- (doc = (_a.sent()).doc);
809
- return [3 /*break*/, 6];
810
- case 3:
811
- error_6 = _a.sent();
812
- if (!(0, executors_1.isExecutorConflictError)(error_6)) return [3 /*break*/, 5];
813
- return [4 /*yield*/, responseHandler(error_6.doc, "update", req, options)];
814
- case 4:
815
- serialized = _a.sent();
816
- return [2 /*return*/, res.status(409).json({
817
- data: serialized,
818
- error: "Conflict",
819
- message: "Document was modified since your last read",
820
- })];
821
- case 5: throw error_6;
822
- case 6:
823
- void (0, record_1.maybeRecordModelRouterAudit)({
824
- after: doc,
825
- audit: options.audit,
826
- before: previous,
827
- modelName: model.modelName,
828
- operation: "update",
829
- recordId: String(doc._id),
830
- req: req,
831
- verb: "updated",
832
- });
833
- _a.label = 7;
834
- case 7:
835
- _a.trys.push([7, 9, , 10]);
836
- return [4 /*yield*/, responseHandler(doc, "update", req, options)];
837
- case 8:
838
- serialized = _a.sent();
839
- return [2 /*return*/, res.json({ data: serialized })];
840
- case 9:
841
- error_7 = _a.sent();
842
- throw (0, errors_1.passthroughOrWrap)(error_7, {
843
- code: "response-handler-error",
844
- title: "responseHandler error",
845
- });
846
- case 10: return [2 /*return*/];
554
+ ], (0, exports.asyncHandler)(async (req, res) => {
555
+ const existingDoc = req
556
+ .obj;
557
+ // Read `_updatedAt` before the executor strips it from the body; the executor's
558
+ // conflict detection still runs after preUpdate, matching the previous inline order.
559
+ const bodyUpdatedAt = req.body._updatedAt;
560
+ const preciseUnmodifiedSince = req.headers["x-unmodified-since-iso"];
561
+ const httpUnmodifiedSince = req.headers["if-unmodified-since"];
562
+ const timestampValue = Array.isArray(preciseUnmodifiedSince)
563
+ ? preciseUnmodifiedSince[0]
564
+ : preciseUnmodifiedSince;
565
+ const httpTimestampValue = Array.isArray(httpUnmodifiedSince)
566
+ ? httpUnmodifiedSince[0]
567
+ : httpUnmodifiedSince;
568
+ let concurrencyCheck;
569
+ if (timestampValue || httpTimestampValue || bodyUpdatedAt) {
570
+ const usingPreciseHeader = Boolean(timestampValue);
571
+ const usingHttpHeader = !usingPreciseHeader && Boolean(httpTimestampValue);
572
+ const clientTimestamp = timestampValue
573
+ ? luxon_1.DateTime.fromISO(timestampValue)
574
+ : httpTimestampValue
575
+ ? luxon_1.DateTime.fromHTTP(httpTimestampValue)
576
+ : luxon_1.DateTime.fromISO(bodyUpdatedAt);
577
+ concurrencyCheck = {
578
+ // An unparseable value round-trips as an invalid Date; the executor turns it into
579
+ // the 400 "Invalid conflict-detection timestamp" error after preUpdate has run.
580
+ ifUnmodifiedSince: clientTimestamp.toJSDate(),
581
+ invalidTimestampDetail: usingPreciseHeader
582
+ ? "X-Unmodified-Since-ISO header could not be parsed as an ISO date"
583
+ : usingHttpHeader
584
+ ? "If-Unmodified-Since header could not be parsed as an HTTP date"
585
+ : "_updatedAt body field could not be parsed as an ISO date",
586
+ type: "timestamp",
587
+ };
588
+ }
589
+ let doc;
590
+ const previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
591
+ try {
592
+ ({ doc } = await (0, executors_1.executeUpdate)({
593
+ body: req.body,
594
+ concurrencyCheck,
595
+ existingDoc,
596
+ id: req.params.id,
597
+ model,
598
+ options,
599
+ req,
600
+ user: req.user,
601
+ }));
602
+ }
603
+ catch (error) {
604
+ // Duck-typed: `instanceof` breaks for Error subclasses in the compiled ES5 dist.
605
+ if ((0, executors_1.isExecutorConflictError)(error)) {
606
+ const serialized = await responseHandler(error.doc, "update", req, options);
607
+ return res.status(409).json({
608
+ data: serialized,
609
+ error: "Conflict",
610
+ message: "Document was modified since your last read",
611
+ });
847
612
  }
613
+ throw error;
614
+ }
615
+ void (0, record_1.maybeRecordModelRouterAudit)({
616
+ after: doc,
617
+ audit: options.audit,
618
+ before: previous,
619
+ modelName: model.modelName,
620
+ operation: "update",
621
+ recordId: String(doc._id),
622
+ req,
623
+ verb: "updated",
848
624
  });
849
- }); }));
625
+ try {
626
+ const serialized = await responseHandler(doc, "update", req, options);
627
+ return res.json({ data: serialized });
628
+ }
629
+ catch (error) {
630
+ throw (0, errors_1.passthroughOrWrap)(error, {
631
+ code: "response-handler-error",
632
+ title: "responseHandler error",
633
+ });
634
+ }
635
+ }));
850
636
  router.delete("/:id", [
851
637
  (0, auth_1.authenticateMiddleware)(options.allowAnonymous),
852
638
  (0, openApi_1.deleteOpenApiMiddleware)(model, options),
853
639
  (0, permissions_1.permissionMiddleware)(model, options),
854
- ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
855
- var existingDoc, previous;
856
- return __generator(this, function (_a) {
857
- switch (_a.label) {
858
- case 0:
859
- existingDoc = req.obj;
860
- previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
861
- return [4 /*yield*/, (0, executors_1.executeDelete)({
862
- existingDoc: existingDoc,
863
- id: req.params.id,
864
- model: model,
865
- options: options,
866
- req: req,
867
- user: req.user,
868
- })];
869
- case 1:
870
- _a.sent();
871
- void (0, record_1.maybeRecordModelRouterAudit)({
872
- audit: options.audit,
873
- before: previous,
874
- modelName: model.modelName,
875
- operation: "delete",
876
- recordId: String(existingDoc._id),
877
- req: req,
878
- verb: "deleted",
879
- });
880
- return [2 /*return*/, res.status(204).json({})];
881
- }
640
+ ], (0, exports.asyncHandler)(async (req, res) => {
641
+ const existingDoc = req.obj;
642
+ const previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
643
+ await (0, executors_1.executeDelete)({
644
+ existingDoc,
645
+ id: req.params.id,
646
+ model,
647
+ options,
648
+ req,
649
+ user: req.user,
882
650
  });
883
- }); }));
884
- var arrayOperation = function (req, res, operation) { return __awaiter(void 0, void 0, void 0, function () {
885
- var doc, prevDoc, field, itemId, array, index, body, error_8, error_9, error_10, arrayAuditOperation;
886
- var _a;
887
- var _b, _c;
888
- return __generator(this, function (_d) {
889
- switch (_d.label) {
890
- case 0: return [4 /*yield*/, (0, permissions_1.checkPermissions)("update", options.permissions.update, req.user)];
891
- case 1:
892
- // TODO Combine array operations and .patch(), as they are very similar.
893
- if (!(_d.sent())) {
894
- throw new errors_1.APIError({
895
- code: "array-update-not-allowed",
896
- detail: "Access to PATCH on ".concat(model.modelName, " denied for ").concat((_b = req.user) === null || _b === void 0 ? void 0 : _b.id),
897
- meta: { method: "PATCH", model: model.modelName },
898
- status: 405,
899
- title: "Access denied",
900
- });
901
- }
902
- return [4 /*yield*/, model.findById(req.params.id)];
903
- case 2:
904
- doc = _d.sent();
905
- prevDoc = (0, cloneDeep_1.default)(doc);
906
- if (!doc) {
907
- throw new errors_1.NotFoundError({
908
- code: "document-not-found",
909
- detail: "Could not find document to PATCH: ".concat(req.params.id),
910
- meta: { model: model.modelName },
911
- title: "Document not found",
912
- });
913
- }
914
- return [4 /*yield*/, (0, permissions_1.checkPermissions)("update", options.permissions.update, req.user, doc)];
915
- case 3:
916
- if (!(_d.sent())) {
917
- throw new errors_1.ForbiddenError({
918
- code: "update-not-allowed",
919
- detail: "Patch not allowed for user ".concat((_c = req.user) === null || _c === void 0 ? void 0 : _c.id, " on doc ").concat(doc._id),
920
- meta: { model: model.modelName },
921
- title: "Update not allowed",
922
- });
923
- }
924
- field = req.params.field;
925
- itemId = req.params.itemId;
926
- // We apply the operation *before* the hooks. As far as the callers are concerned, this should
927
- // be like PATCHing the field and replacing the whole thing.
928
- if (operation !== "DELETE" && req.body[field] === undefined) {
929
- throw new errors_1.BadRequestError({
930
- code: "malformed-array-operation-body",
931
- detail: "Malformed body, array operations should have a single, top level key, got: ".concat(Object.keys(req.body).join(",")),
932
- meta: { field: field },
933
- title: "Malformed array operation body",
934
- });
935
- }
936
- array = __spreadArray([], __read(doc[field]), false);
937
- if (operation === "POST") {
938
- array.push(req.body[field]);
939
- }
940
- else if (operation === "PATCH" || operation === "DELETE") {
941
- index = void 0;
942
- if ((0, utils_1.isValidObjectId)(itemId)) {
943
- index = array.findIndex(function (x) { return (x === null || x === void 0 ? void 0 : x.id) === itemId; });
944
- }
945
- else {
946
- index = array.indexOf(itemId);
947
- }
948
- if (index === -1) {
949
- throw new errors_1.NotFoundError({
950
- code: "array-item-not-found",
951
- detail: "Could not find ".concat(field, "/").concat(itemId),
952
- meta: { field: field, itemId: itemId },
953
- title: "Array item not found",
954
- });
955
- }
956
- // For PATCHing an item by ID, we need to merge the objects so we don't override the _id or
957
- // other parts of the subdocument.
958
- if (operation === "PATCH" && (0, utils_1.isValidObjectId)(itemId)) {
959
- Object.assign(array[index], req.body[field]);
960
- }
961
- else if (operation === "PATCH") {
962
- // For PATCHing a string array, we can replace the whole object.
963
- array[index] = req.body[field];
964
- }
965
- else {
966
- array.splice(index, 1);
967
- }
968
- }
969
- else {
970
- throw new errors_1.BadRequestError({
971
- code: "invalid-array-operation",
972
- detail: "Invalid array operation: ".concat(operation),
973
- meta: { operation: operation },
974
- title: "Invalid array operation",
975
- });
976
- }
977
- body = (_a = {}, _a[field] = array, _a);
978
- try {
979
- body = (0, transformers_1.transform)(options, body, "update", req.user);
980
- }
981
- catch (error) {
982
- throw (0, errors_1.passthroughOrWrap)(error, {
983
- code: "transform-error",
984
- status: 403,
985
- title: "Transform error",
986
- });
987
- }
988
- if (!options.preUpdate) return [3 /*break*/, 8];
989
- _d.label = 4;
990
- case 4:
991
- _d.trys.push([4, 6, , 7]);
992
- return [4 /*yield*/, options.preUpdate(body, req)];
993
- case 5:
994
- body = _d.sent();
995
- return [3 /*break*/, 7];
996
- case 6:
997
- error_8 = _d.sent();
998
- throw (0, errors_1.passthroughOrWrap)(error_8, {
999
- code: "pre-update-hook-error",
1000
- detail: "preUpdate hook error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_8)),
1001
- status: 400,
1002
- title: "preUpdate hook error",
1003
- });
1004
- case 7:
1005
- if (body === undefined) {
1006
- throw new errors_1.ForbiddenError({
1007
- code: "update-not-allowed",
1008
- detail: "A body must be returned from preUpdate",
1009
- title: "Update not allowed",
1010
- });
1011
- }
1012
- if (body === null) {
1013
- throw new errors_1.ForbiddenError({
1014
- code: "update-not-allowed",
1015
- detail: "preUpdate hook on ".concat(req.params.id, " returned null"),
1016
- title: "Update not allowed",
1017
- });
1018
- }
1019
- _d.label = 8;
1020
- case 8:
1021
- body = (0, auth_1.omitUserRolesFromWriteBody)(model.modelName, options.accessControl, body, req.terrenoAllowUserAdminWrite === true);
1022
- if (!(options.access && options.accessControl && body && typeof body === "object")) return [3 /*break*/, 10];
1023
- return [4 /*yield*/, (0, modelRouterAccess_1.validateAccessWriteBody)({
1024
- access: options.access,
1025
- accessControl: options.accessControl,
1026
- body: body,
1027
- doc: doc,
1028
- phase: "write",
1029
- user: req.user,
1030
- })];
1031
- case 9:
1032
- _d.sent();
1033
- _d.label = 10;
1034
- case 10:
1035
- _d.trys.push([10, 12, , 13]);
1036
- Object.assign(doc, body);
1037
- return [4 /*yield*/, doc.save()];
1038
- case 11:
1039
- _d.sent();
1040
- return [3 /*break*/, 13];
1041
- case 12:
1042
- error_9 = _d.sent();
1043
- throw (0, errors_1.passthroughOrWrapWrite)(error_9, {
1044
- code: "update-save-error",
1045
- detail: "PATCH Pre Update error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_9)),
1046
- status: 400,
1047
- title: "PATCH Pre Update error",
1048
- });
1049
- case 13:
1050
- if (!options.postUpdate) return [3 /*break*/, 17];
1051
- _d.label = 14;
1052
- case 14:
1053
- _d.trys.push([14, 16, , 17]);
1054
- return [4 /*yield*/, options.postUpdate(doc, body, req, prevDoc)];
1055
- case 15:
1056
- _d.sent();
1057
- return [3 /*break*/, 17];
1058
- case 16:
1059
- error_10 = _d.sent();
1060
- throw (0, errors_1.passthroughOrWrap)(error_10, {
1061
- code: "post-update-hook-error",
1062
- detail: "PATCH Post Update error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_10)),
1063
- status: 400,
1064
- title: "PATCH Post Update error",
1065
- });
1066
- case 17:
1067
- arrayAuditOperation = operation === "POST" ? "arrayPush" : operation === "PATCH" ? "arrayUpdate" : "arrayRemove";
1068
- void (0, record_1.maybeRecordModelRouterAudit)({
1069
- after: doc,
1070
- audit: options.audit,
1071
- before: prevDoc,
1072
- modelName: model.modelName,
1073
- operation: arrayAuditOperation,
1074
- recordId: String(doc._id),
1075
- req: req,
1076
- verb: "updated",
1077
- });
1078
- return [2 /*return*/, res.json({
1079
- data: (0, transformers_1.serialize)(req, options, doc),
1080
- })];
1081
- }
1082
- });
1083
- }); };
1084
- var arrayPost = function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
1085
- return __generator(this, function (_a) {
1086
- return [2 /*return*/, arrayOperation(req, res, "POST")];
651
+ void (0, record_1.maybeRecordModelRouterAudit)({
652
+ audit: options.audit,
653
+ before: previous,
654
+ modelName: model.modelName,
655
+ operation: "delete",
656
+ recordId: String(existingDoc._id),
657
+ req,
658
+ verb: "deleted",
1087
659
  });
1088
- }); };
1089
- var arrayPatch = function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
1090
- return __generator(this, function (_a) {
1091
- return [2 /*return*/, arrayOperation(req, res, "PATCH")];
660
+ return res.status(204).json({});
661
+ }));
662
+ /**
663
+ * Applies consumer update transforms and authorization hooks for array subroutes.
664
+ * Keeping this pipeline shared ensures invalid field requests cannot bypass consumer
665
+ * authorization before modelRouter returns its own validation error.
666
+ */
667
+ const applyArrayOperationUpdateHooks = async (inputBody, req) => {
668
+ let body = inputBody;
669
+ try {
670
+ body = (0, transformers_1.transform)(options, body, "update", req.user);
671
+ }
672
+ catch (error) {
673
+ throw (0, errors_1.passthroughOrWrap)(error, {
674
+ code: "transform-error",
675
+ status: 403,
676
+ title: "Transform error",
677
+ });
678
+ }
679
+ if (options.preUpdate) {
680
+ try {
681
+ body = await options.preUpdate(body, req);
682
+ }
683
+ catch (error) {
684
+ throw (0, errors_1.passthroughOrWrap)(error, {
685
+ code: "pre-update-hook-error",
686
+ detail: `preUpdate hook error on ${req.params.id}: ${(0, errors_1.errorDetail)(error)}`,
687
+ status: 400,
688
+ title: "preUpdate hook error",
689
+ });
690
+ }
691
+ if (body === undefined) {
692
+ throw new errors_1.ForbiddenError({
693
+ code: "update-not-allowed",
694
+ detail: "A body must be returned from preUpdate",
695
+ title: "Update not allowed",
696
+ });
697
+ }
698
+ if (body === null) {
699
+ throw new errors_1.ForbiddenError({
700
+ code: "update-not-allowed",
701
+ detail: `preUpdate hook on ${req.params.id} returned null`,
702
+ title: "Update not allowed",
703
+ });
704
+ }
705
+ }
706
+ return body;
707
+ };
708
+ const arrayOperation = async (req, res, operation) => {
709
+ // TODO Combine array operations and .patch(), as they are very similar.
710
+ if (!(await (0, permissions_1.checkPermissions)("update", options.permissions.update, req.user))) {
711
+ throw new errors_1.APIError({
712
+ code: "array-update-not-allowed",
713
+ detail: `Access to PATCH on ${model.modelName} denied for ${req.user?.id}`,
714
+ meta: { method: "PATCH", model: model.modelName },
715
+ status: 405,
716
+ title: "Access denied",
717
+ });
718
+ }
719
+ const doc = await model.findById(req.params.id);
720
+ // Make a copy for passing pre-saved values to hooks.
721
+ const prevDoc = (0, cloneDeep_1.default)(doc);
722
+ if (!doc) {
723
+ throw new errors_1.NotFoundError({
724
+ code: "document-not-found",
725
+ detail: `Could not find document to PATCH: ${req.params.id}`,
726
+ meta: { model: model.modelName },
727
+ title: "Document not found",
728
+ });
729
+ }
730
+ if (!(await (0, permissions_1.checkPermissions)("update", options.permissions.update, req.user, doc))) {
731
+ throw new errors_1.ForbiddenError({
732
+ code: "update-not-allowed",
733
+ detail: `Patch not allowed for user ${req.user?.id} on doc ${doc._id}`,
734
+ meta: { model: model.modelName },
735
+ title: "Update not allowed",
736
+ });
737
+ }
738
+ const field = req.params.field;
739
+ const itemId = req.params.itemId;
740
+ // We apply the operation *before* the hooks. As far as the callers are concerned, this should
741
+ // be like PATCHing the field and replacing the whole thing.
742
+ if (operation !== "DELETE" && req.body[field] === undefined) {
743
+ throw new errors_1.BadRequestError({
744
+ code: "malformed-array-operation-body",
745
+ detail: `Malformed body, array operations should have a single, top level key, got: ${Object.keys(req.body).join(",")}`,
746
+ meta: { field },
747
+ title: "Malformed array operation body",
748
+ });
749
+ }
750
+ const currentFieldValue = doc[field];
751
+ if (!Array.isArray(currentFieldValue)) {
752
+ await applyArrayOperationUpdateHooks(req.body, req);
753
+ throw new errors_1.BadRequestError({
754
+ code: "array-operation-field-not-array",
755
+ detail: `Cannot apply an array operation to non-array field ${field}`,
756
+ meta: { field },
757
+ title: "Array operation field is not an array",
758
+ });
759
+ }
760
+ const array = [...currentFieldValue];
761
+ if (operation === "POST") {
762
+ array.push(req.body[field]);
763
+ }
764
+ else if (operation === "PATCH" || operation === "DELETE") {
765
+ // Check for subschema vs String array:
766
+ let index;
767
+ if ((0, utils_1.isValidObjectId)(itemId)) {
768
+ index = array.findIndex((x) => x?.id === itemId);
769
+ }
770
+ else {
771
+ index = array.indexOf(itemId);
772
+ }
773
+ if (index === -1) {
774
+ throw new errors_1.NotFoundError({
775
+ code: "array-item-not-found",
776
+ detail: `Could not find ${field}/${itemId}`,
777
+ meta: { field, itemId },
778
+ title: "Array item not found",
779
+ });
780
+ }
781
+ // For PATCHing an item by ID, we need to merge the objects so we don't override the _id or
782
+ // other parts of the subdocument.
783
+ if (operation === "PATCH" && (0, utils_1.isValidObjectId)(itemId)) {
784
+ Object.assign(array[index], req.body[field]);
785
+ }
786
+ else if (operation === "PATCH") {
787
+ // For PATCHing a string array, we can replace the whole object.
788
+ array[index] = req.body[field];
789
+ }
790
+ else {
791
+ array.splice(index, 1);
792
+ }
793
+ }
794
+ else {
795
+ throw new errors_1.BadRequestError({
796
+ code: "invalid-array-operation",
797
+ detail: `Invalid array operation: ${operation}`,
798
+ meta: { operation },
799
+ title: "Invalid array operation",
800
+ });
801
+ }
802
+ let body = await applyArrayOperationUpdateHooks({ [field]: array }, req);
803
+ body = (0, auth_1.omitUserRolesFromWriteBody)(model.modelName, options.accessControl, body, req.terrenoAllowUserAdminWrite === true);
804
+ if (options.access && options.accessControl && body && typeof body === "object") {
805
+ await (0, modelRouterAccess_1.validateAccessWriteBody)({
806
+ access: options.access,
807
+ accessControl: options.accessControl,
808
+ body: body,
809
+ doc,
810
+ phase: "write",
811
+ user: req.user,
812
+ });
813
+ }
814
+ // Using .save here runs the risk of a versioning error if you try to make two simultaneous
815
+ // updates. We won't wind up with corrupted data, just an API error.
816
+ try {
817
+ Object.assign(doc, body);
818
+ await doc.save();
819
+ }
820
+ catch (error) {
821
+ throw (0, errors_1.passthroughOrWrapWrite)(error, {
822
+ code: "update-save-error",
823
+ detail: `PATCH Pre Update error on ${req.params.id}: ${(0, errors_1.errorDetail)(error)}`,
824
+ status: 400,
825
+ title: "PATCH Pre Update error",
826
+ });
827
+ }
828
+ if (options.postUpdate) {
829
+ try {
830
+ await options.postUpdate(doc, body, req, prevDoc);
831
+ }
832
+ catch (error) {
833
+ throw (0, errors_1.passthroughOrWrap)(error, {
834
+ code: "post-update-hook-error",
835
+ detail: `PATCH Post Update error on ${req.params.id}: ${(0, errors_1.errorDetail)(error)}`,
836
+ status: 400,
837
+ title: "PATCH Post Update error",
838
+ });
839
+ }
840
+ }
841
+ const arrayAuditOperation = operation === "POST" ? "arrayPush" : operation === "PATCH" ? "arrayUpdate" : "arrayRemove";
842
+ void (0, record_1.maybeRecordModelRouterAudit)({
843
+ after: doc,
844
+ audit: options.audit,
845
+ before: prevDoc,
846
+ modelName: model.modelName,
847
+ operation: arrayAuditOperation,
848
+ recordId: String(doc._id),
849
+ req,
850
+ verb: "updated",
1092
851
  });
1093
- }); };
1094
- var arrayDelete = function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
1095
- return __generator(this, function (_a) {
1096
- return [2 /*return*/, arrayOperation(req, res, "DELETE")];
852
+ return res.json({
853
+ data: (0, transformers_1.serialize)(req, options, doc),
1097
854
  });
1098
- }); };
855
+ };
856
+ const arrayPost = async (req, res) => {
857
+ return arrayOperation(req, res, "POST");
858
+ };
859
+ const arrayPatch = async (req, res) => {
860
+ return arrayOperation(req, res, "PATCH");
861
+ };
862
+ const arrayDelete = async (req, res) => {
863
+ return arrayOperation(req, res, "DELETE");
864
+ };
1099
865
  // Set up routes for managing array fields. Check if there any array fields to add this for.
1100
- if (Object.values(model.schema.paths).find(function (config) { return config.instance === "Array"; })) {
866
+ if (Object.values(model.schema.paths).find((config) => config.instance === "Array")) {
1101
867
  router.post("/:id/:field", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(arrayPost));
1102
868
  router.patch("/:id/:field/:itemId", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(arrayPatch));
1103
869
  router.delete("/:id/:field/:itemId", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(arrayDelete));
@@ -1105,20 +871,19 @@ var _buildModelRouter = function (model, options, routePath) {
1105
871
  router.use(errors_1.apiErrorMiddleware);
1106
872
  return router;
1107
873
  };
1108
- var asyncHandler = function (fn, options) {
1109
- var _a, _b;
874
+ const asyncHandler = (fn, options) => {
1110
875
  // If no validation options, return simple handler
1111
- if (!(options === null || options === void 0 ? void 0 : options.bodySchema) && !(options === null || options === void 0 ? void 0 : options.querySchema)) {
1112
- return function (req, res, next) {
876
+ if (!options?.bodySchema && !options?.querySchema) {
877
+ return (req, res, next) => {
1113
878
  return Promise.resolve(fn(req, res, next)).catch(next);
1114
879
  };
1115
880
  }
1116
881
  // Import validation functions dynamically to avoid circular deps at module load
1117
- var _c = require("./openApiValidator"), validateRequestBody = _c.validateRequestBody, validateQueryParams = _c.validateQueryParams, getOpenApiValidatorConfig = _c.getOpenApiValidatorConfig;
882
+ const { validateRequestBody, validateQueryParams, getOpenApiValidatorConfig, } = require("./openApiValidator");
1118
883
  // Build validation middleware
1119
- var validators = [];
884
+ const validators = [];
1120
885
  // Determine if validation should be enabled
1121
- var shouldValidate = (_b = (_a = options.validate) !== null && _a !== void 0 ? _a : getOpenApiValidatorConfig().validateRequests) !== null && _b !== void 0 ? _b : false;
886
+ const shouldValidate = options.validate ?? getOpenApiValidatorConfig().validateRequests ?? false;
1122
887
  if (shouldValidate) {
1123
888
  if (options.bodySchema) {
1124
889
  validators.push(validateRequestBody(options.bodySchema, { enabled: true }));
@@ -1127,16 +892,16 @@ var asyncHandler = function (fn, options) {
1127
892
  validators.push(validateQueryParams(options.querySchema, { enabled: true }));
1128
893
  }
1129
894
  }
1130
- return function (req, res, next) {
895
+ return (req, res, next) => {
1131
896
  // Run validators sequentially, then the handler
1132
- var runValidators = function (index) {
897
+ const runValidators = (index) => {
1133
898
  if (index >= validators.length) {
1134
899
  // All validators passed, run the actual handler
1135
900
  Promise.resolve(fn(req, res, next)).catch(next);
1136
901
  return;
1137
902
  }
1138
903
  try {
1139
- validators[index](req, res, (function (err) {
904
+ validators[index](req, res, ((err) => {
1140
905
  if (err) {
1141
906
  next(err);
1142
907
  return;