@terreno/api 57.4.0 → 57.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +5 -5
  2. package/bunfig.toml +1 -1
  3. package/dist/actions.js +197 -368
  4. package/dist/adminModelRouter.js +88 -173
  5. package/dist/api.js +598 -852
  6. package/dist/audit/auditApp.js +48 -89
  7. package/dist/audit/auditEventModel.js +15 -16
  8. package/dist/audit/cloudTasksEnqueue.js +56 -149
  9. package/dist/audit/diff.js +70 -160
  10. package/dist/audit/processQueue.js +25 -70
  11. package/dist/audit/rbacSink.js +25 -66
  12. package/dist/audit/record.js +129 -251
  13. package/dist/auth.js +432 -681
  14. package/dist/authRecovery.js +155 -269
  15. package/dist/authTokens.js +43 -118
  16. package/dist/betterAuthApp.js +25 -26
  17. package/dist/betterAuthSetup.js +258 -413
  18. package/dist/browserLogsRoute.d.ts +6 -0
  19. package/dist/browserLogsRoute.js +97 -0
  20. package/dist/collectionRegistry.js +32 -47
  21. package/dist/config.js +53 -122
  22. package/dist/configurationApp.js +180 -361
  23. package/dist/configurationPlugin.js +130 -302
  24. package/dist/consentApp.js +276 -421
  25. package/dist/docLoader.js +78 -126
  26. package/dist/envConfigurationPlugin.js +25 -147
  27. package/dist/errors.js +151 -247
  28. package/dist/example.js +28 -34
  29. package/dist/expressServer.d.ts +10 -0
  30. package/dist/expressServer.js +109 -255
  31. package/dist/frameworkModelNames.d.ts +24 -0
  32. package/dist/frameworkModelNames.js +31 -0
  33. package/dist/githubAuth.js +152 -216
  34. package/dist/httpClient.js +176 -264
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.js +7 -2
  37. package/dist/logger.js +145 -278
  38. package/dist/mcp/auth.js +76 -128
  39. package/dist/mcp/createMCPRequest.js +4 -5
  40. package/dist/mcp/handlers.js +268 -480
  41. package/dist/mcp/query.js +56 -150
  42. package/dist/mcp/registry.js +17 -30
  43. package/dist/mcp/schemaGenerator.js +95 -181
  44. package/dist/mcp/server.js +28 -100
  45. package/dist/mcp/serviceTokens.js +102 -191
  46. package/dist/mcp/toolGenerator.js +78 -191
  47. package/dist/middleware.js +15 -27
  48. package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
  49. package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
  50. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
  51. package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
  52. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
  53. package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
  54. package/dist/migrations/generate.js +107 -229
  55. package/dist/migrations/load.js +75 -201
  56. package/dist/migrations/lock.js +54 -126
  57. package/dist/migrations/runner.js +192 -446
  58. package/dist/migrations/schemaCatalog.js +122 -263
  59. package/dist/models/consentForm.js +6 -6
  60. package/dist/models/consentResponse.js +5 -5
  61. package/dist/models/mcpServiceToken.js +66 -156
  62. package/dist/models/notification.js +6 -6
  63. package/dist/models/notificationPreference.js +6 -6
  64. package/dist/models/versionConfig.js +5 -5
  65. package/dist/notifications/notificationService.js +133 -273
  66. package/dist/notifications/notificationsApp.js +85 -179
  67. package/dist/notifications/notificationsBeforeSend.js +19 -64
  68. package/dist/notifiers/googleChatNotifier.js +36 -117
  69. package/dist/notifiers/slackNotifier.d.ts +31 -2
  70. package/dist/notifiers/slackNotifier.js +170 -119
  71. package/dist/notifiers/zoomNotifier.js +60 -111
  72. package/dist/openApi.js +107 -122
  73. package/dist/openApiBuilder.js +117 -159
  74. package/dist/openApiCompat.js +81 -148
  75. package/dist/openApiEtag.js +7 -7
  76. package/dist/openApiValidator.js +177 -286
  77. package/dist/orgs/orgContext.js +87 -157
  78. package/dist/orgs/orgPermissions.js +29 -68
  79. package/dist/orgs/orgPlugin.js +9 -27
  80. package/dist/orgs/organizationModel.js +65 -166
  81. package/dist/orgs/organizationSettings.js +29 -36
  82. package/dist/orgs/orgsApp.js +346 -608
  83. package/dist/permissions.js +88 -181
  84. package/dist/plugins.js +125 -218
  85. package/dist/populate.js +130 -240
  86. package/dist/rateLimit/applyTrustProxy.js +1 -1
  87. package/dist/rateLimit/createStore.js +7 -8
  88. package/dist/rateLimit/memoryStore.js +22 -100
  89. package/dist/rateLimit/middleware.js +48 -99
  90. package/dist/rateLimit/mongoStore.js +54 -112
  91. package/dist/rateLimit/policies.js +41 -75
  92. package/dist/rateLimit/redisStore.js +39 -133
  93. package/dist/rbac/access.js +119 -267
  94. package/dist/rbac/assertAllowed.js +95 -171
  95. package/dist/rbac/auditModel.js +14 -58
  96. package/dist/rbac/backfillAdmins.js +24 -130
  97. package/dist/rbac/fieldViews.js +46 -141
  98. package/dist/rbac/membershipOrgAdminSource.js +28 -99
  99. package/dist/rbac/middleware.js +30 -96
  100. package/dist/rbac/modelRouterAccess.js +130 -307
  101. package/dist/rbac/permissionUtils.js +40 -179
  102. package/dist/rbac/realtimeAccess.js +81 -147
  103. package/dist/rbac/resolve.d.ts +1 -1
  104. package/dist/rbac/resolve.js +148 -342
  105. package/dist/rbac/roleManager.js +318 -700
  106. package/dist/rbac/roleModel.js +44 -171
  107. package/dist/rbac/routes.js +93 -196
  108. package/dist/rbac/scopes.js +39 -133
  109. package/dist/rbac/statements.js +23 -91
  110. package/dist/rbac/userPlugin.js +3 -29
  111. package/dist/realtime/changeStreamWatcher.js +489 -800
  112. package/dist/realtime/deprecation.js +8 -10
  113. package/dist/realtime/queryMatcher.js +110 -191
  114. package/dist/realtime/queryStore.js +35 -118
  115. package/dist/realtime/realtimeApp.js +247 -401
  116. package/dist/realtime/registry.js +19 -30
  117. package/dist/realtime/sessionRevalidation.js +132 -358
  118. package/dist/realtime/socketAuth.js +89 -208
  119. package/dist/realtime/socketUser.js +10 -56
  120. package/dist/requestContext.js +93 -139
  121. package/dist/schemaMetadata.js +179 -274
  122. package/dist/scriptRunner.js +96 -266
  123. package/dist/scrubAdminFields.js +36 -108
  124. package/dist/secretProviders.js +130 -299
  125. package/dist/seedRunner.js +221 -514
  126. package/dist/sync/adminBroadcastScope.js +58 -170
  127. package/dist/sync/adminWindowAccess.js +15 -86
  128. package/dist/sync/adminWindowMutation.js +110 -181
  129. package/dist/sync/executors.js +425 -629
  130. package/dist/sync/loadHarness.js +392 -689
  131. package/dist/sync/models.js +181 -341
  132. package/dist/sync/mutationHandler.js +533 -801
  133. package/dist/sync/registrationSideEffects.js +41 -95
  134. package/dist/sync/registry.js +29 -49
  135. package/dist/sync/routes.js +484 -817
  136. package/dist/sync/scripts/compactTombstones.js +83 -228
  137. package/dist/sync/serialize.js +18 -58
  138. package/dist/sync/socketHandlers.js +253 -478
  139. package/dist/sync/streams.js +49 -117
  140. package/dist/sync/syncApp.js +12 -15
  141. package/dist/sync/syncBatch.js +63 -168
  142. package/dist/sync/syncSeqPlugin.js +430 -702
  143. package/dist/syncConsents.js +113 -253
  144. package/dist/terrenoApp.js +166 -276
  145. package/dist/tests/createTestData.js +146 -256
  146. package/dist/tests/models.js +14 -54
  147. package/dist/tests/mongoTestSetup.js +42 -103
  148. package/dist/tests/testHelper.js +31 -93
  149. package/dist/tests.js +12 -51
  150. package/dist/transformers.js +61 -164
  151. package/dist/utils.js +31 -93
  152. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  153. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  154. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  155. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  156. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  157. package/dist/versionCheckPlugin.js +52 -100
  158. package/dist/webhooks/headerValue.js +2 -2
  159. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  160. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  161. package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
  162. package/dist/webhooks/rawBody.js +1 -1
  163. package/dist/webhooks/timingSafeEqual.js +4 -5
  164. package/dist/webhooks/verifiers/hmac.js +17 -18
  165. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  166. package/dist/webhooks/verifiers/stripe.js +31 -65
  167. package/dist/webhooks/verifiers/twilio.js +23 -73
  168. package/dist/webhooks/webhooksApp.js +78 -177
  169. package/dist/zodOpenApi.js +2 -2
  170. package/package.json +6 -6
  171. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  172. package/src/audit/auditApp.test.ts +5 -5
  173. package/src/audit/auditEventModel.ts +7 -3
  174. package/src/audit/auditRouter.test.ts +5 -5
  175. package/src/audit/rbacSink.test.ts +2 -2
  176. package/src/audit/record.test.ts +2 -2
  177. package/src/audit/record.ts +3 -2
  178. package/src/auth.ts +1 -1
  179. package/src/authRecovery.test.ts +43 -0
  180. package/src/authRecovery.ts +16 -10
  181. package/src/authTokens.ts +6 -2
  182. package/src/authVerification.test.ts +22 -0
  183. package/src/browserLogsRoute.ts +110 -0
  184. package/src/configurationPlugin.test.ts +1 -11
  185. package/src/expressServer.ts +10 -0
  186. package/src/frameworkModelNames.test.ts +62 -0
  187. package/src/frameworkModelNames.ts +33 -0
  188. package/src/index.ts +7 -0
  189. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  190. package/src/mcp/auth.test.ts +34 -1
  191. package/src/migrations/cli.test.ts +0 -23
  192. package/src/models/mcpServiceToken.ts +4 -3
  193. package/src/models/notification.ts +3 -2
  194. package/src/models/notificationPreference.ts +1 -1
  195. package/src/notifications/notificationsApp.test.ts +24 -1
  196. package/src/notifiers/slackNotifier.test.ts +186 -1
  197. package/src/notifiers/slackNotifier.ts +167 -8
  198. package/src/orgs/orgPlugin.ts +1 -1
  199. package/src/orgs/organizationModel.ts +11 -6
  200. package/src/plugins.test.ts +5 -0
  201. package/src/plugins.ts +3 -0
  202. package/src/realtime/realtimeApp.ts +1 -1
  203. package/src/sync/integration.test.ts +2 -2
  204. package/src/terrenoApp.ts +3 -0
  205. package/src/types.d.ts +1 -0
  206. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  207. package/tsconfig.json +13 -54
  208. package/tsconfig.typedoc.json +2 -0
package/dist/plugins.js CHANGED
@@ -1,30 +1,4 @@
1
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 __assign = (this && this.__assign) || function () {
18
- __assign = Object.assign || function(t) {
19
- for (var s, i = 1, n = arguments.length; i < n; i++) {
20
- s = arguments[i];
21
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
- t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
29
3
  if (k2 === undefined) k2 = k;
30
4
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -58,54 +32,18 @@ var __importStar = (this && this.__importStar) || (function () {
58
32
  return result;
59
33
  };
60
34
  })();
61
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
62
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
63
- return new (P || (P = Promise))(function (resolve, reject) {
64
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
65
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
66
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
67
- step((generator = generator.apply(thisArg, _arguments || [])).next());
68
- });
69
- };
70
- var __generator = (this && this.__generator) || function (thisArg, body) {
71
- 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);
72
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
73
- function verb(n) { return function (v) { return step([n, v]); }; }
74
- function step(op) {
75
- if (f) throw new TypeError("Generator is already executing.");
76
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
77
- 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;
78
- if (y = 0, t) op = [op[0] & 2, t.value];
79
- switch (op[0]) {
80
- case 0: case 1: t = op; break;
81
- case 4: _.label++; return { value: op[1], done: false };
82
- case 5: _.label++; y = op[1]; op = [0]; continue;
83
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
84
- default:
85
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
86
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
87
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
88
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
89
- if (t[2]) _.ops.pop();
90
- _.trys.pop(); continue;
91
- }
92
- op = body.call(thisArg, _);
93
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
94
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
95
- }
96
- };
97
35
  Object.defineProperty(exports, "__esModule", { value: true });
98
36
  exports.DateOnly = exports.excludeArchivedPlugin = exports.upsertPlugin = exports.findExactlyOne = exports.findOneOrNoneFor = exports.findOneOrNone = exports.firebaseJWTPlugin = exports.createdUpdatedPlugin = exports.isDisabledPlugin = exports.isDeletedPlugin = exports.emailVerificationPlugin = exports.baseUserPlugin = void 0;
99
- var luxon_1 = require("luxon");
100
- var mongoose_1 = __importStar(require("mongoose"));
101
- var errors_1 = require("./errors");
37
+ const luxon_1 = require("luxon");
38
+ const mongoose_1 = __importStar(require("mongoose"));
39
+ const errors_1 = require("./errors");
102
40
  /**
103
41
  * Builds the error thrown by the query plugins. `errorArgs` is applied last so consumers can
104
42
  * override every field, including `status`; the status-specific subclass is used when the resulting
105
43
  * status still matches one of them, so Sentry sees a meaningful error type.
106
44
  */
107
- var pluginError = function (defaults, errorArgs) {
108
- var options = __assign(__assign({}, defaults), errorArgs);
45
+ const pluginError = (defaults, errorArgs) => {
46
+ const options = { ...defaults, ...errorArgs };
109
47
  if (options.status === 404) {
110
48
  return new errors_1.NotFoundError(options);
111
49
  }
@@ -116,7 +54,7 @@ var pluginError = function (defaults, errorArgs) {
116
54
  };
117
55
  // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
118
56
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
119
- var baseUserPlugin = function (schema) {
57
+ const baseUserPlugin = (schema) => {
120
58
  schema.add({
121
59
  admin: { default: false, description: "Whether the user has admin privileges", type: Boolean },
122
60
  });
@@ -127,7 +65,7 @@ exports.baseUserPlugin = baseUserPlugin;
127
65
  * Opt-in `emailVerified` field for user schemas. Defaults to false so existing
128
66
  * documents stay unverified until they complete the email-verification flow.
129
67
  */
130
- var emailVerificationPlugin = function (schema) {
68
+ const emailVerificationPlugin = (schema) => {
131
69
  schema.add({
132
70
  emailVerified: {
133
71
  default: false,
@@ -139,8 +77,7 @@ var emailVerificationPlugin = function (schema) {
139
77
  exports.emailVerificationPlugin = emailVerificationPlugin;
140
78
  // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
141
79
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
142
- var isDeletedPlugin = function (schema, defaultValue) {
143
- if (defaultValue === void 0) { defaultValue = false; }
80
+ const isDeletedPlugin = (schema, defaultValue = false) => {
144
81
  schema.add({
145
82
  deleted: {
146
83
  default: defaultValue,
@@ -152,8 +89,8 @@ var isDeletedPlugin = function (schema, defaultValue) {
152
89
  });
153
90
  // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
154
91
  // biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
155
- var applyDeleteFilter = function (q) {
156
- var query = q.getQuery();
92
+ const applyDeleteFilter = (q) => {
93
+ const query = q.getQuery();
157
94
  if (query && query.deleted === undefined) {
158
95
  void q.where({ deleted: { $ne: true } });
159
96
  }
@@ -164,13 +101,15 @@ var isDeletedPlugin = function (schema, defaultValue) {
164
101
  schema.pre("findOne", function () {
165
102
  applyDeleteFilter(this);
166
103
  });
104
+ schema.pre("countDocuments", function () {
105
+ applyDeleteFilter(this);
106
+ });
167
107
  };
168
108
  exports.isDeletedPlugin = isDeletedPlugin;
169
- var isDisabledPlugin = function (
109
+ const isDisabledPlugin = (
170
110
  // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
171
111
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
172
- schema, defaultValue) {
173
- if (defaultValue === void 0) { defaultValue = false; }
112
+ schema, defaultValue = false) => {
174
113
  schema.add({
175
114
  disabled: {
176
115
  default: defaultValue,
@@ -183,7 +122,7 @@ schema, defaultValue) {
183
122
  exports.isDisabledPlugin = isDisabledPlugin;
184
123
  // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
185
124
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
186
- var createdUpdatedPlugin = function (schema) {
125
+ const createdUpdatedPlugin = (schema) => {
187
126
  schema.add({
188
127
  updated: { description: "When this document was last updated", index: true, type: Date },
189
128
  });
@@ -204,7 +143,7 @@ var createdUpdatedPlugin = function (schema) {
204
143
  });
205
144
  };
206
145
  exports.createdUpdatedPlugin = createdUpdatedPlugin;
207
- var firebaseJWTPlugin = function (schema) {
146
+ const firebaseJWTPlugin = (schema) => {
208
147
  schema.add({
209
148
  firebaseId: { description: "The user's Firebase authentication ID", index: true, type: String },
210
149
  });
@@ -217,31 +156,22 @@ exports.firebaseJWTPlugin = firebaseJWTPlugin;
217
156
  * document, or throws an exception if multiple are found.
218
157
  * @param schema Mongoose Schema
219
158
  */
220
- var findOneOrNone = function (schema) {
221
- schema.statics.findOneOrNone = function (query, errorArgs) {
222
- return __awaiter(this, void 0, void 0, function () {
223
- var results;
224
- return __generator(this, function (_a) {
225
- switch (_a.label) {
226
- case 0: return [4 /*yield*/, this.find(query)];
227
- case 1:
228
- results = _a.sent();
229
- if (results.length === 0) {
230
- return [2 /*return*/, null];
231
- }
232
- if (results.length > 1) {
233
- throw pluginError({
234
- code: "find-one-multiple-documents",
235
- detail: "".concat(this.modelName, ".findOne query returned multiple documents. query: ").concat(JSON.stringify(query)),
236
- meta: { model: this.modelName },
237
- status: 500,
238
- title: "findOne query returned multiple documents",
239
- }, errorArgs);
240
- }
241
- return [2 /*return*/, results[0]];
242
- }
243
- });
244
- });
159
+ const findOneOrNone = (schema) => {
160
+ schema.statics.findOneOrNone = async function (query, errorArgs) {
161
+ const results = await this.find(query);
162
+ if (results.length === 0) {
163
+ return null;
164
+ }
165
+ if (results.length > 1) {
166
+ throw pluginError({
167
+ code: "find-one-multiple-documents",
168
+ detail: `${this.modelName}.findOne query returned multiple documents. query: ${JSON.stringify(query)}`,
169
+ meta: { model: this.modelName },
170
+ status: 500,
171
+ title: "findOne query returned multiple documents",
172
+ }, errorArgs);
173
+ }
174
+ return results[0];
245
175
  };
246
176
  };
247
177
  exports.findOneOrNone = findOneOrNone;
@@ -255,34 +185,26 @@ exports.findOneOrNone = findOneOrNone;
255
185
  * @param query Mongoose query object
256
186
  * @param errorArgs Optional overrides for the thrown {@link APIError} when multiple match
257
187
  */
258
- var findOneOrNoneFor = function (model, query, errorArgs) { return __awaiter(void 0, void 0, void 0, function () {
259
- var withStatic, results;
260
- return __generator(this, function (_a) {
261
- switch (_a.label) {
262
- case 0:
263
- withStatic = model;
264
- if (typeof withStatic.findOneOrNone === "function") {
265
- return [2 /*return*/, withStatic.findOneOrNone(query, errorArgs)];
266
- }
267
- return [4 /*yield*/, model.find(query)];
268
- case 1:
269
- results = _a.sent();
270
- if (results.length === 0) {
271
- return [2 /*return*/, null];
272
- }
273
- if (results.length > 1) {
274
- throw pluginError({
275
- code: "find-one-multiple-documents",
276
- detail: "".concat(model.modelName, ".findOne query returned multiple documents. query: ").concat(JSON.stringify(query)),
277
- meta: { model: model.modelName },
278
- status: 500,
279
- title: "findOne query returned multiple documents",
280
- }, errorArgs);
281
- }
282
- return [2 /*return*/, results[0]];
283
- }
284
- });
285
- }); };
188
+ const findOneOrNoneFor = async (model, query, errorArgs) => {
189
+ const withStatic = model;
190
+ if (typeof withStatic.findOneOrNone === "function") {
191
+ return withStatic.findOneOrNone(query, errorArgs);
192
+ }
193
+ const results = await model.find(query);
194
+ if (results.length === 0) {
195
+ return null;
196
+ }
197
+ if (results.length > 1) {
198
+ throw pluginError({
199
+ code: "find-one-multiple-documents",
200
+ detail: `${model.modelName}.findOne query returned multiple documents. query: ${JSON.stringify(query)}`,
201
+ meta: { model: model.modelName },
202
+ status: 500,
203
+ title: "findOne query returned multiple documents",
204
+ }, errorArgs);
205
+ }
206
+ return results[0];
207
+ };
286
208
  exports.findOneOrNoneFor = findOneOrNoneFor;
287
209
  /**
288
210
  * This adds a static method `Model.findExactlyOne` to the schema. This or findOneOrNone should replace `Model.findOne`
@@ -292,37 +214,28 @@ exports.findOneOrNoneFor = findOneOrNoneFor;
292
214
  * multiple or none are found.
293
215
  * @param schema Mongoose Schema
294
216
  */
295
- var findExactlyOne = function (schema) {
296
- schema.statics.findExactlyOne = function (query, errorArgs) {
297
- return __awaiter(this, void 0, void 0, function () {
298
- var results;
299
- return __generator(this, function (_a) {
300
- switch (_a.label) {
301
- case 0: return [4 /*yield*/, this.find(query)];
302
- case 1:
303
- results = _a.sent();
304
- if (results.length === 0) {
305
- throw pluginError({
306
- code: "find-exactly-one-no-documents",
307
- detail: "".concat(this.modelName, ".findExactlyOne query returned no documents. query: ").concat(JSON.stringify(query)),
308
- meta: { model: this.modelName },
309
- status: 404,
310
- title: "findExactlyOne query returned no documents",
311
- }, errorArgs);
312
- }
313
- if (results.length > 1) {
314
- throw pluginError({
315
- code: "find-exactly-one-multiple-documents",
316
- detail: "".concat(this.modelName, ".findExactlyOne query returned multiple documents. query: ").concat(JSON.stringify(query)),
317
- meta: { model: this.modelName },
318
- status: 500,
319
- title: "findExactlyOne query returned multiple documents",
320
- }, errorArgs);
321
- }
322
- return [2 /*return*/, results[0]];
323
- }
324
- });
325
- });
217
+ const findExactlyOne = (schema) => {
218
+ schema.statics.findExactlyOne = async function (query, errorArgs) {
219
+ const results = await this.find(query);
220
+ if (results.length === 0) {
221
+ throw pluginError({
222
+ code: "find-exactly-one-no-documents",
223
+ detail: `${this.modelName}.findExactlyOne query returned no documents. query: ${JSON.stringify(query)}`,
224
+ meta: { model: this.modelName },
225
+ status: 404,
226
+ title: "findExactlyOne query returned no documents",
227
+ }, errorArgs);
228
+ }
229
+ if (results.length > 1) {
230
+ throw pluginError({
231
+ code: "find-exactly-one-multiple-documents",
232
+ detail: `${this.modelName}.findExactlyOne query returned multiple documents. query: ${JSON.stringify(query)}`,
233
+ meta: { model: this.modelName },
234
+ status: 500,
235
+ title: "findExactlyOne query returned multiple documents",
236
+ }, errorArgs);
237
+ }
238
+ return results[0];
326
239
  };
327
240
  };
328
241
  exports.findExactlyOne = findExactlyOne;
@@ -334,37 +247,29 @@ exports.findExactlyOne = findExactlyOne;
334
247
  */
335
248
  // noExplicitAny: Schema generics with unknown collide with mongoose's loose this-binding on schema.statics
336
249
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics with unknown collide with mongoose's loose this-binding on schema.statics
337
- var upsertPlugin = function (schema) {
338
- schema.statics.upsert = function (conditions, update) {
339
- return __awaiter(this, void 0, void 0, function () {
340
- var docs, doc, combinedData, newDoc;
341
- return __generator(this, function (_a) {
342
- switch (_a.label) {
343
- case 0: return [4 /*yield*/, this.find(conditions)];
344
- case 1:
345
- docs = _a.sent();
346
- if (docs.length > 1) {
347
- throw new errors_1.InternalServerError({
348
- code: "upsert-multiple-documents",
349
- detail: "".concat(this.modelName, ".upsert find query returned multiple documents. query: ").concat(JSON.stringify(conditions)),
350
- meta: { model: this.modelName },
351
- title: "upsert find query returned multiple documents",
352
- });
353
- }
354
- doc = docs[0];
355
- if (!doc) return [3 /*break*/, 3];
356
- // If the document exists, update it with the provided update values.
357
- Object.assign(doc, update);
358
- return [4 /*yield*/, doc.save()];
359
- case 2: return [2 /*return*/, (_a.sent())];
360
- case 3:
361
- combinedData = __assign(__assign({}, conditions), update);
362
- newDoc = new this(combinedData);
363
- return [4 /*yield*/, newDoc.save()];
364
- case 4: return [2 /*return*/, (_a.sent())];
365
- }
250
+ const upsertPlugin = (schema) => {
251
+ schema.statics.upsert = async function (conditions, update) {
252
+ // Try to find the document with the given conditions.
253
+ const docs = await this.find(conditions);
254
+ if (docs.length > 1) {
255
+ throw new errors_1.InternalServerError({
256
+ code: "upsert-multiple-documents",
257
+ detail: `${this.modelName}.upsert find query returned multiple documents. query: ${JSON.stringify(conditions)}`,
258
+ meta: { model: this.modelName },
259
+ title: "upsert find query returned multiple documents",
366
260
  });
367
- });
261
+ }
262
+ const doc = docs[0];
263
+ if (doc) {
264
+ // If the document exists, update it with the provided update values.
265
+ Object.assign(doc, update);
266
+ return (await doc.save());
267
+ }
268
+ // If the document doesn't exist, create a new one with the combined conditions and update
269
+ // values.
270
+ const combinedData = { ...conditions, ...update };
271
+ const newDoc = new this(combinedData);
272
+ return (await newDoc.save());
368
273
  };
369
274
  };
370
275
  exports.upsertPlugin = upsertPlugin;
@@ -376,11 +281,10 @@ exports.upsertPlugin = upsertPlugin;
376
281
  * @param schema Mongoose Schema
377
282
  * @param defaultValue Default value for the `archived` field (defaults to `false`)
378
283
  */
379
- var excludeArchivedPlugin = function (
284
+ const excludeArchivedPlugin = (
380
285
  // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
381
286
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
382
- schema, defaultValue) {
383
- if (defaultValue === void 0) { defaultValue = false; }
287
+ schema, defaultValue = false) => {
384
288
  schema.add({
385
289
  archived: {
386
290
  default: defaultValue,
@@ -394,12 +298,12 @@ schema, defaultValue) {
394
298
  // also exclude archived documents unless the query sets `archived` explicitly.
395
299
  // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
396
300
  // biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
397
- var applyArchiveFilter = function (query) {
398
- var conditions = query.getFilter();
301
+ const applyArchiveFilter = (query) => {
302
+ const conditions = query.getFilter();
399
303
  // Only apply the default filter when the query does not mention `archived` at all, so an
400
304
  // explicit `{archived: true}` (or `false`) is always respected.
401
305
  if (conditions.archived === undefined) {
402
- query.setQuery(__assign(__assign({}, conditions), { archived: { $ne: true } }));
306
+ query.setQuery({ ...conditions, archived: { $ne: true } });
403
307
  }
404
308
  };
405
309
  // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
@@ -414,45 +318,49 @@ schema, defaultValue) {
414
318
  });
415
319
  };
416
320
  exports.excludeArchivedPlugin = excludeArchivedPlugin;
417
- var DateOnly = /** @class */ (function (_super) {
418
- __extends(DateOnly, _super);
419
- function DateOnly(key, options) {
420
- var _this = _super.call(this, key, options, "DateOnly") || this;
421
- _this.$conditionalHandlers = __assign(__assign({}, mongoose_1.SchemaType.prototype
422
- .$conditionalHandlers), { $gt: _this.handleSingle, $gte: _this.handleSingle, $lt: _this.handleSingle, $lte: _this.handleSingle });
423
- return _this;
321
+ class DateOnly extends mongoose_1.SchemaType {
322
+ constructor(key, options) {
323
+ super(key, options, "DateOnly");
424
324
  }
425
- DateOnly.prototype.handleSingle = function (val) {
325
+ handleSingle(val) {
426
326
  return this.cast(val);
327
+ }
328
+ $conditionalHandlers = {
329
+ ...mongoose_1.SchemaType.prototype
330
+ .$conditionalHandlers,
331
+ $gt: this.handleSingle,
332
+ $gte: this.handleSingle,
333
+ $lt: this.handleSingle,
334
+ $lte: this.handleSingle,
427
335
  };
428
336
  // Based on castForQuery in mongoose/lib/schema/date.js
429
337
  // When using $gt, $gte, $lt, $lte, etc, we need to cast the value to a Date
430
- DateOnly.prototype.castForQuery = function ($conditional, val, context) {
338
+ castForQuery($conditional, val, context) {
431
339
  if ($conditional == null) {
432
340
  return this.applySetters(val, context);
433
341
  }
434
- var handler = this.$conditionalHandlers[$conditional];
342
+ const handler = this.$conditionalHandlers[$conditional];
435
343
  if (!handler) {
436
344
  throw new errors_1.APIError({
437
- detail: "Can't use ".concat($conditional, " with DateOnly."),
345
+ detail: `Can't use ${$conditional} with DateOnly.`,
438
346
  status: 400,
439
347
  title: "Unsupported query conditional for DateOnly",
440
348
  });
441
349
  }
442
350
  return handler.call(this, val);
443
- };
351
+ }
444
352
  // When either setting a value to a DateOnly or fetching from the DB,
445
353
  // we want to strip off the time portion.
446
- DateOnly.prototype.cast = function (val) {
354
+ cast(val) {
447
355
  if (val instanceof Date) {
448
- var date = luxon_1.DateTime.fromJSDate(val).toUTC().startOf("day");
356
+ const date = luxon_1.DateTime.fromJSDate(val).toUTC().startOf("day");
449
357
  if (!date.isValid) {
450
358
  throw new mongoose_1.Error.CastError("DateOnly", val, this.path, new Error("Value is not a valid date"));
451
359
  }
452
360
  return date.toJSDate();
453
361
  }
454
362
  if (typeof val === "string" || typeof val === "number") {
455
- var date = (typeof val === "number" ? luxon_1.DateTime.fromMillis(val) : luxon_1.DateTime.fromISO(val, { zone: "utc" }))
363
+ const date = (typeof val === "number" ? luxon_1.DateTime.fromMillis(val) : luxon_1.DateTime.fromISO(val, { zone: "utc" }))
456
364
  .toUTC()
457
365
  .startOf("day");
458
366
  if (!date.isValid) {
@@ -465,14 +373,13 @@ var DateOnly = /** @class */ (function (_super) {
465
373
  return val;
466
374
  }
467
375
  throw new mongoose_1.Error.CastError("DateOnly", val, this.path, new Error("Value is not a valid date"));
468
- };
469
- DateOnly.prototype.get = function (val) {
376
+ }
377
+ get(val) {
470
378
  return (val instanceof Date
471
379
  ? luxon_1.DateTime.fromJSDate(val).startOf("day").toJSDate()
472
380
  : val);
473
- };
474
- return DateOnly;
475
- }(mongoose_1.SchemaType));
381
+ }
382
+ }
476
383
  exports.DateOnly = DateOnly;
477
384
  // Register DateOnly with Mongoose's Schema.Types
478
385
  mongoose_1.default.Schema.Types.DateOnly = DateOnly;