@terreno/api 0.29.0 → 0.31.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 (79) hide show
  1. package/CHANGELOG.md +2 -43
  2. package/LICENSE +21 -202
  3. package/dist/actions.js +17 -8
  4. package/dist/actions.openApi.test.js +1 -3
  5. package/dist/actions.test.js +8 -5
  6. package/dist/api.arrayOperations.test.js +16 -8
  7. package/dist/api.coverage.test.js +2 -3
  8. package/dist/api.d.ts +3 -2
  9. package/dist/api.errorPaths.test.js +608 -1
  10. package/dist/api.errors.test.js +9 -0
  11. package/dist/api.js +137 -170
  12. package/dist/api.query.test.js +20 -8
  13. package/dist/api.test.js +12 -6
  14. package/dist/auth.coverage.test.d.ts +1 -0
  15. package/dist/auth.coverage.test.js +202 -0
  16. package/dist/auth.test.js +159 -0
  17. package/dist/betterAuthSetup.d.ts +15 -1
  18. package/dist/betterAuthSetup.js +4 -6
  19. package/dist/configurationPlugin.js +2 -2
  20. package/dist/consentApp.test.js +1 -5
  21. package/dist/docLoader.js +5 -1
  22. package/dist/envConfigurationPlugin.d.ts +1 -1
  23. package/dist/envConfigurationPlugin.js +0 -2
  24. package/dist/errors.d.ts +14 -0
  25. package/dist/errors.js +24 -2
  26. package/dist/errors.test.js +137 -0
  27. package/dist/expressServer.js +11 -5
  28. package/dist/githubAuth.js +1 -4
  29. package/dist/httpClient.js +5 -1
  30. package/dist/openApiBuilder.test.js +0 -2
  31. package/dist/openApiValidator.test.js +34 -0
  32. package/dist/plugins.d.ts +6 -5
  33. package/dist/plugins.js +56 -10
  34. package/dist/plugins.test.js +73 -17
  35. package/dist/populate.test.js +9 -12
  36. package/dist/realtime/realtime.test.js +231 -0
  37. package/dist/realtime/realtimeApp.d.ts +1 -1
  38. package/dist/realtime/realtimeApp.js +6 -2
  39. package/dist/realtime/realtimeAppSetup.test.d.ts +1 -0
  40. package/dist/realtime/realtimeAppSetup.test.js +213 -0
  41. package/dist/realtime/registry.d.ts +3 -2
  42. package/dist/tests/models.d.ts +27 -11
  43. package/dist/tests/models.js +5 -3
  44. package/dist/tests/testHelper.d.ts +9 -3
  45. package/package.json +4 -5
  46. package/src/actions.openApi.test.ts +7 -10
  47. package/src/actions.test.ts +27 -15
  48. package/src/actions.ts +21 -12
  49. package/src/api.arrayOperations.test.ts +16 -8
  50. package/src/api.coverage.test.ts +9 -10
  51. package/src/api.errorPaths.test.ts +360 -4
  52. package/src/api.errors.test.ts +12 -0
  53. package/src/api.query.test.ts +20 -8
  54. package/src/api.test.ts +12 -6
  55. package/src/api.ts +162 -171
  56. package/src/auth.coverage.test.ts +101 -0
  57. package/src/auth.test.ts +125 -2
  58. package/src/betterAuthSetup.ts +7 -7
  59. package/src/configurationPlugin.ts +2 -2
  60. package/src/consentApp.test.ts +12 -12
  61. package/src/docLoader.ts +6 -2
  62. package/src/envConfigurationPlugin.ts +2 -6
  63. package/src/errors.test.ts +106 -1
  64. package/src/errors.ts +25 -1
  65. package/src/expressServer.ts +11 -5
  66. package/src/githubAuth.ts +1 -3
  67. package/src/httpClient.ts +6 -2
  68. package/src/models/versionConfig.ts +1 -1
  69. package/src/openApiBuilder.test.ts +24 -9
  70. package/src/openApiValidator.test.ts +41 -0
  71. package/src/plugins.test.ts +59 -9
  72. package/src/plugins.ts +81 -39
  73. package/src/populate.test.ts +25 -16
  74. package/src/realtime/changeStreamWatcher.ts +8 -1
  75. package/src/realtime/realtime.test.ts +239 -0
  76. package/src/realtime/realtimeApp.ts +8 -5
  77. package/src/realtime/realtimeAppSetup.test.ts +161 -0
  78. package/src/realtime/registry.ts +3 -4
  79. package/src/tests/models.ts +8 -6
@@ -121,8 +121,6 @@ var refreshFromDoc = function (Model) { return __awaiter(void 0, void 0, void 0,
121
121
  }
122
122
  });
123
123
  }); };
124
- // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
125
- // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
126
124
  var envConfigurationPlugin = function (schema) {
127
125
  schema.add({
128
126
  env: {
package/dist/errors.d.ts CHANGED
@@ -127,6 +127,12 @@ export declare const errorsPlugin: (schema: Schema) => void;
127
127
  export declare const isAPIError: (error: unknown) => error is APIError;
128
128
  /** Extract a human-readable message from an unknown error. */
129
129
  export declare const errorMessage: (error: unknown) => string;
130
+ /**
131
+ * Extract the fullest human-readable text from an unknown error, for use as the `detail` of a
132
+ * wrapper error. An `APIError`'s `message` is exactly its `title`, so `errorMessage` alone would
133
+ * drop the per-occurrence text the caller put in `detail`.
134
+ */
135
+ export declare const errorDetail: (error: unknown) => string;
130
136
  /** Extract a stack trace string from an unknown error. */
131
137
  export declare const errorStack: (error: unknown) => string;
132
138
  /**
@@ -140,6 +146,14 @@ export declare const getDisableExternalErrorTracking: (error: unknown) => boolea
140
146
  * @deprecated Use `error.toJSON()` instead.
141
147
  */
142
148
  export declare const getAPIErrorBody: (error: APIError) => Record<string, unknown>;
149
+ /**
150
+ * Converts the bare `Error("Unauthorized")` that Passport throws into a quiet 401.
151
+ *
152
+ * Only the plain `Error` prototype is matched. An `APIError` carries its own status, code,
153
+ * detail, and meta, so one whose title happens to be "Unauthorized" falls through to
154
+ * `apiErrorMiddleware`. A domain-specific `Error` subclass with the same message also falls
155
+ * through so its own handler can respond.
156
+ */
143
157
  export declare const apiUnauthorizedMiddleware: (err: Error, _req: Request, res: Response, next: NextFunction) => void;
144
158
  /**
145
159
  * Converts Mongoose validation/cast errors into client-friendly APIErrors.
package/dist/errors.js CHANGED
@@ -86,7 +86,7 @@ var __read = (this && this.__read) || function (o, n) {
86
86
  return ar;
87
87
  };
88
88
  Object.defineProperty(exports, "__esModule", { value: true });
89
- exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.InternalServerError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.APIError = void 0;
89
+ exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorDetail = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.InternalServerError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.APIError = void 0;
90
90
  // https://jsonapi.org/format/#errors
91
91
  var Sentry = __importStar(require("@sentry/bun"));
92
92
  var mongoose_1 = __importStar(require("mongoose"));
@@ -344,6 +344,18 @@ var errorMessage = function (error) {
344
344
  return String(error);
345
345
  };
346
346
  exports.errorMessage = errorMessage;
347
+ /**
348
+ * Extract the fullest human-readable text from an unknown error, for use as the `detail` of a
349
+ * wrapper error. An `APIError`'s `message` is exactly its `title`, so `errorMessage` alone would
350
+ * drop the per-occurrence text the caller put in `detail`.
351
+ */
352
+ var errorDetail = function (error) {
353
+ if ((0, exports.isAPIError)(error) && error.detail) {
354
+ return "".concat(error.title, ": ").concat(error.detail);
355
+ }
356
+ return (0, exports.errorMessage)(error);
357
+ };
358
+ exports.errorDetail = errorDetail;
347
359
  /** Extract a stack trace string from an unknown error. */
348
360
  var errorStack = function (error) {
349
361
  if (error instanceof Error && error.stack) {
@@ -418,8 +430,18 @@ var getAPIErrorBody = function (error) {
418
430
  return serializeAPIError(error);
419
431
  };
420
432
  exports.getAPIErrorBody = getAPIErrorBody;
433
+ /**
434
+ * Converts the bare `Error("Unauthorized")` that Passport throws into a quiet 401.
435
+ *
436
+ * Only the plain `Error` prototype is matched. An `APIError` carries its own status, code,
437
+ * detail, and meta, so one whose title happens to be "Unauthorized" falls through to
438
+ * `apiErrorMiddleware`. A domain-specific `Error` subclass with the same message also falls
439
+ * through so its own handler can respond.
440
+ */
421
441
  var apiUnauthorizedMiddleware = function (err, _req, res, next) {
422
- if (err.message === "Unauthorized") {
442
+ if (!(0, exports.isAPIError)(err) &&
443
+ err.message === "Unauthorized" &&
444
+ Object.getPrototypeOf(err) === Error.prototype) {
423
445
  // not using the actual APIError class here because we don't want to log it as an error.
424
446
  res.status(401).json({ status: 401, title: "Unauthorized" }).send();
425
447
  }
@@ -47,10 +47,51 @@ var __importStar = (this && this.__importStar) || (function () {
47
47
  return result;
48
48
  };
49
49
  })();
50
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
51
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
52
+ return new (P || (P = Promise))(function (resolve, reject) {
53
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
54
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
55
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
56
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
57
+ });
58
+ };
59
+ var __generator = (this && this.__generator) || function (thisArg, body) {
60
+ 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);
61
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
62
+ function verb(n) { return function (v) { return step([n, v]); }; }
63
+ function step(op) {
64
+ if (f) throw new TypeError("Generator is already executing.");
65
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
66
+ 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;
67
+ if (y = 0, t) op = [op[0] & 2, t.value];
68
+ switch (op[0]) {
69
+ case 0: case 1: t = op; break;
70
+ case 4: _.label++; return { value: op[1], done: false };
71
+ case 5: _.label++; y = op[1]; op = [0]; continue;
72
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
73
+ default:
74
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
75
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
76
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
77
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
78
+ if (t[2]) _.ops.pop();
79
+ _.trys.pop(); continue;
80
+ }
81
+ op = body.call(thisArg, _);
82
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
83
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
84
+ }
85
+ };
86
+ var __importDefault = (this && this.__importDefault) || function (mod) {
87
+ return (mod && mod.__esModule) ? mod : { "default": mod };
88
+ };
50
89
  Object.defineProperty(exports, "__esModule", { value: true });
51
90
  var bun_test_1 = require("bun:test");
52
91
  var Sentry = __importStar(require("@sentry/bun"));
92
+ var express_1 = __importDefault(require("express"));
53
93
  var mongoose_1 = __importStar(require("mongoose"));
94
+ var supertest_1 = __importDefault(require("supertest"));
54
95
  var errors_1 = require("./errors");
55
96
  var buildResponse = function () {
56
97
  var res = {
@@ -388,6 +429,102 @@ var buildResponse = function () {
388
429
  (0, bun_test_1.expect)(next).toHaveBeenCalledWith(err);
389
430
  (0, bun_test_1.expect)(res.status).not.toHaveBeenCalled();
390
431
  });
432
+ (0, bun_test_1.it)("forwards an APIError titled Unauthorized so it keeps its own status", function () {
433
+ var err = new errors_1.ForbiddenError({
434
+ code: "org-membership-required",
435
+ detail: "You are not a member of this organization",
436
+ title: "Unauthorized",
437
+ });
438
+ (0, errors_1.apiUnauthorizedMiddleware)(err, req, res, next);
439
+ (0, bun_test_1.expect)(next).toHaveBeenCalledWith(err);
440
+ (0, bun_test_1.expect)(res.status).not.toHaveBeenCalled();
441
+ });
442
+ (0, bun_test_1.it)("forwards a plain APIError titled Unauthorized rather than rewriting it to a 401", function () {
443
+ var err = new errors_1.APIError({ status: 403, title: "Unauthorized" });
444
+ (0, errors_1.apiUnauthorizedMiddleware)(err, req, res, next);
445
+ (0, bun_test_1.expect)(next).toHaveBeenCalledWith(err);
446
+ (0, bun_test_1.expect)(res.status).not.toHaveBeenCalled();
447
+ });
448
+ (0, bun_test_1.it)("forwards an Error subclass whose message is Unauthorized", function () {
449
+ var DomainUnauthorizedError = /** @class */ (function (_super) {
450
+ __extends(DomainUnauthorizedError, _super);
451
+ function DomainUnauthorizedError() {
452
+ return _super !== null && _super.apply(this, arguments) || this;
453
+ }
454
+ return DomainUnauthorizedError;
455
+ }(Error));
456
+ var err = new DomainUnauthorizedError("Unauthorized");
457
+ (0, errors_1.apiUnauthorizedMiddleware)(err, req, res, next);
458
+ (0, bun_test_1.expect)(next).toHaveBeenCalledWith(err);
459
+ (0, bun_test_1.expect)(res.status).not.toHaveBeenCalled();
460
+ });
461
+ });
462
+ (0, bun_test_1.describe)("apiUnauthorizedMiddleware in the terrenoApp middleware order", function () {
463
+ var buildApp = function () {
464
+ var app = (0, express_1.default)();
465
+ app.get("/forbidden", function (_req, _res, next) {
466
+ next(new errors_1.ForbiddenError({
467
+ code: "org-membership-required",
468
+ detail: "You are not a member of this organization",
469
+ title: "Unauthorized",
470
+ }));
471
+ });
472
+ app.get("/passport", function (_req, _res, next) {
473
+ next(new Error("Unauthorized"));
474
+ });
475
+ app.use(errors_1.apiUnauthorizedMiddleware);
476
+ app.use(errors_1.apiErrorMiddleware);
477
+ return app;
478
+ };
479
+ (0, bun_test_1.it)("keeps a 403 titled Unauthorized a 403", function () { return __awaiter(void 0, void 0, void 0, function () {
480
+ var res;
481
+ return __generator(this, function (_a) {
482
+ switch (_a.label) {
483
+ case 0: return [4 /*yield*/, (0, supertest_1.default)(buildApp()).get("/forbidden").expect(403)];
484
+ case 1:
485
+ res = _a.sent();
486
+ (0, bun_test_1.expect)(res.body).toEqual({
487
+ code: "org-membership-required",
488
+ detail: "You are not a member of this organization",
489
+ status: 403,
490
+ title: "Unauthorized",
491
+ });
492
+ return [2 /*return*/];
493
+ }
494
+ });
495
+ }); });
496
+ (0, bun_test_1.it)("still converts a plain Passport Unauthorized error to a 401", function () { return __awaiter(void 0, void 0, void 0, function () {
497
+ var res;
498
+ return __generator(this, function (_a) {
499
+ switch (_a.label) {
500
+ case 0: return [4 /*yield*/, (0, supertest_1.default)(buildApp()).get("/passport").expect(401)];
501
+ case 1:
502
+ res = _a.sent();
503
+ (0, bun_test_1.expect)(res.body).toEqual({ status: 401, title: "Unauthorized" });
504
+ return [2 /*return*/];
505
+ }
506
+ });
507
+ }); });
508
+ });
509
+ (0, bun_test_1.describe)("errorDetail", function () {
510
+ (0, bun_test_1.it)("combines an APIError's title and detail", function () {
511
+ var error = new errors_1.ConflictError({
512
+ code: "schedule-item-staff-conflict",
513
+ detail: "Conflict detected for Dr. Ada on 2026-07-31",
514
+ title: "Conflict detected",
515
+ });
516
+ (0, bun_test_1.expect)((0, errors_1.errorDetail)(error)).toBe("Conflict detected: Conflict detected for Dr. Ada on 2026-07-31");
517
+ });
518
+ (0, bun_test_1.it)("falls back to the title when an APIError has no detail", function () {
519
+ (0, bun_test_1.expect)((0, errors_1.errorDetail)(new errors_1.APIError({ title: "Conflict detected" }))).toBe("Conflict detected");
520
+ });
521
+ (0, bun_test_1.it)("returns the message for a plain Error", function () {
522
+ (0, bun_test_1.expect)((0, errors_1.errorDetail)(new Error("boom"))).toBe("boom");
523
+ });
524
+ (0, bun_test_1.it)("stringifies non-Error values", function () {
525
+ (0, bun_test_1.expect)((0, errors_1.errorDetail)("boom")).toBe("boom");
526
+ (0, bun_test_1.expect)((0, errors_1.errorDetail)(42)).toBe("42");
527
+ });
391
528
  });
392
529
  (0, bun_test_1.describe)("apiErrorMiddleware", function () {
393
530
  var res;
@@ -104,6 +104,7 @@ var express_1 = __importDefault(require("express"));
104
104
  var cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
105
105
  var on_finished_1 = __importDefault(require("on-finished"));
106
106
  var passport_1 = __importDefault(require("passport"));
107
+ var errors_1 = require("./errors");
107
108
  var logger_1 = require("./logger");
108
109
  var slackNotifier_1 = require("./notifiers/slackNotifier");
109
110
  var SLOW_READ_MAX = 200;
@@ -111,16 +112,16 @@ var SLOW_WRITE_MAX = 500;
111
112
  var IS_JEST = process.env.JEST_WORKER_ID !== undefined;
112
113
  var setupEnvironment = function () {
113
114
  if (!process.env.TOKEN_ISSUER) {
114
- throw new Error("TOKEN_ISSUER must be set in env.");
115
+ throw new errors_1.APIError({ status: 500, title: "TOKEN_ISSUER must be set in env." });
115
116
  }
116
117
  if (!process.env.TOKEN_SECRET) {
117
- throw new Error("TOKEN_SECRET must be set.");
118
+ throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set." });
118
119
  }
119
120
  if (!process.env.REFRESH_TOKEN_SECRET) {
120
- throw new Error("REFRESH_TOKEN_SECRET must be set.");
121
+ throw new errors_1.APIError({ status: 500, title: "REFRESH_TOKEN_SECRET must be set." });
121
122
  }
122
123
  if (!process.env.SESSION_SECRET) {
123
- throw new Error("SESSION_SECRET must be set.");
124
+ throw new errors_1.APIError({ status: 500, title: "SESSION_SECRET must be set." });
124
125
  }
125
126
  if (!process.env.TOKEN_EXPIRES_IN && !IS_JEST) {
126
127
  logger_1.logger.warn("TOKEN_EXPIRES_IN is not set so using default.");
@@ -228,7 +229,12 @@ var cronjob = function (name, schedule, callback) {
228
229
  new cron_1.default.CronJob(cronSchedule, callback, null, true, "America/Chicago");
229
230
  }
230
231
  catch (error) {
231
- throw new Error("Failed to create cronjob: ".concat(error));
232
+ throw new errors_1.APIError({
233
+ cause: error,
234
+ detail: "Failed to create cronjob ".concat(name, " with schedule ").concat(cronSchedule, ": ").concat(error),
235
+ status: 500,
236
+ title: "Failed to create cronjob",
237
+ });
232
238
  }
233
239
  };
234
240
  exports.cronjob = cronjob;
@@ -82,10 +82,7 @@ exports.githubUserPlugin = githubUserPlugin;
82
82
  var setupGitHubAuth = function (_app, userModel, githubOptions) {
83
83
  var _a;
84
84
  var scope = (_a = githubOptions.scope) !== null && _a !== void 0 ? _a : ["user:email"];
85
- passport_1.default.use("github",
86
- // noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
87
- // biome-ignore lint/suspicious/noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
88
- new passport_github2_1.Strategy({
85
+ passport_1.default.use("github", new passport_github2_1.Strategy({
89
86
  callbackURL: githubOptions.callbackURL,
90
87
  clientID: githubOptions.clientId,
91
88
  clientSecret: githubOptions.clientSecret,
@@ -294,7 +294,11 @@ var createAuthenticatedClient = function (options) {
294
294
  response = _b.sent();
295
295
  accessToken = (_a = response.data) === null || _a === void 0 ? void 0 : _a.access_token;
296
296
  if (typeof accessToken !== "string" || accessToken.length === 0) {
297
- throw new Error("[httpClient] ".concat(apiName, " token response has no access_token"));
297
+ throw new errors_1.InternalServerError({
298
+ code: "http-client-error",
299
+ detail: "".concat(apiName, " token response has no access_token"),
300
+ title: "[httpClient] token response has no access_token",
301
+ });
298
302
  }
299
303
  return [2 /*return*/, accessToken];
300
304
  }
@@ -50,8 +50,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
50
50
  return (mod && mod.__esModule) ? mod : { "default": mod };
51
51
  };
52
52
  Object.defineProperty(exports, "__esModule", { value: true });
53
- // noExplicitAny: test mock typing
54
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
55
53
  var bun_test_1 = require("bun:test");
56
54
  var supertest_1 = __importDefault(require("supertest"));
57
55
  var api_1 = require("./api");
@@ -595,6 +595,40 @@ var setupFreshApp = function () { return __awaiter(void 0, void 0, void 0, funct
595
595
  (0, bun_test_1.expect)(nextCalled).toBe(true);
596
596
  (0, bun_test_1.expect)(req.query.page).toBe(5);
597
597
  });
598
+ (0, bun_test_1.it)("runs only body validation when no query schema is provided", function () {
599
+ (0, openApiValidator_1.configureOpenApiValidator)({ coerceTypes: true });
600
+ var middleware = (0, openApiValidator_1.createValidator)({
601
+ body: { count: { type: "number" }, name: { required: true, type: "string" } },
602
+ });
603
+ var req = {
604
+ body: { count: "3", name: "ok" },
605
+ method: "POST",
606
+ path: "/test",
607
+ query: { unchecked: "kept" },
608
+ };
609
+ var res = {};
610
+ var nextCalls = [];
611
+ middleware(req, res, (function () {
612
+ var args = [];
613
+ for (var _i = 0; _i < arguments.length; _i++) {
614
+ args[_i] = arguments[_i];
615
+ }
616
+ nextCalls.push(args);
617
+ }));
618
+ (0, bun_test_1.expect)(nextCalls).toEqual([[]]);
619
+ (0, bun_test_1.expect)(req.body.count).toBe(3);
620
+ // Query params are untouched when no query schema is configured.
621
+ (0, bun_test_1.expect)(req.query.unchecked).toBe("kept");
622
+ });
623
+ (0, bun_test_1.it)("throws body validation errors when only a body schema is provided", function () {
624
+ (0, openApiValidator_1.configureOpenApiValidator)({});
625
+ var middleware = (0, openApiValidator_1.createValidator)({
626
+ body: { name: { required: true, type: "string" } },
627
+ });
628
+ var req = { body: {}, method: "POST", path: "/test", query: {} };
629
+ var res = {};
630
+ (0, bun_test_1.expect)(function () { return middleware(req, res, (function () { })); }).toThrow("Request validation failed");
631
+ });
598
632
  (0, bun_test_1.it)("propagates body validation error via next", function () {
599
633
  var capturedErrors = [];
600
634
  (0, openApiValidator_1.configureOpenApiValidator)({
package/dist/plugins.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import mongoose, { type Document, type FilterQuery, type Schema, SchemaType, type SchemaTypeOptions } from "mongoose";
2
- import { type APIErrorConstructor } from "./errors";
1
+ import mongoose, { type Document, type Schema, SchemaType, type SchemaTypeOptions } from "mongoose";
2
+ import { type APIErrorOptions } from "./errors";
3
+ export type ModelQuery<T> = Partial<Record<keyof T, unknown>> & Record<string, unknown>;
3
4
  export interface BaseUser {
4
5
  admin: boolean;
5
6
  email: string;
@@ -41,7 +42,7 @@ export declare const findOneOrNone: <T>(schema: Schema<T>) => void;
41
42
  * @param query Mongoose query object
42
43
  * @param errorArgs Optional overrides for the thrown {@link APIError} when multiple match
43
44
  */
44
- export declare const findOneOrNoneFor: <T>(model: mongoose.Model<T>, query: FilterQuery<T>, errorArgs?: Partial<APIErrorConstructor>) => Promise<(Document & T) | null>;
45
+ export declare const findOneOrNoneFor: <T>(model: mongoose.Model<T>, query: ModelQuery<T>, errorArgs?: Partial<APIErrorOptions>) => Promise<(Document & T) | null>;
45
46
  /**
46
47
  * This adds a static method `Model.findExactlyOne` to the schema. This or findOneOrNone should replace `Model.findOne`
47
48
  * in most instances.
@@ -63,10 +64,10 @@ export interface HasUpsert<T> {
63
64
  upsert(conditions: Record<string, unknown>, update: Record<string, unknown>): Promise<T>;
64
65
  }
65
66
  export interface FindOneOrNonePlugin<T> {
66
- findOneOrNone(query: Record<string, unknown>, errorArgs?: Partial<APIErrorConstructor>): Promise<(Document & T) | null>;
67
+ findOneOrNone(query: Record<string, unknown>, errorArgs?: Partial<APIErrorOptions>): Promise<(Document & T) | null>;
67
68
  }
68
69
  export interface FindExactlyOnePlugin<T> {
69
- findExactlyOne(query: Record<string, unknown>, errorArgs?: Partial<APIErrorConstructor>): Promise<Document & T>;
70
+ findExactlyOne(query: Record<string, unknown>, errorArgs?: Partial<APIErrorOptions>): Promise<Document & T>;
70
71
  }
71
72
  export declare class DateOnly extends SchemaType {
72
73
  constructor(key: string, options: SchemaTypeOptions<Date>);
package/dist/plugins.js CHANGED
@@ -99,6 +99,21 @@ exports.DateOnly = exports.upsertPlugin = exports.findExactlyOne = exports.findO
99
99
  var luxon_1 = require("luxon");
100
100
  var mongoose_1 = __importStar(require("mongoose"));
101
101
  var errors_1 = require("./errors");
102
+ /**
103
+ * Builds the error thrown by the query plugins. `errorArgs` is applied last so consumers can
104
+ * override every field, including `status`; the status-specific subclass is used when the resulting
105
+ * status still matches one of them, so Sentry sees a meaningful error type.
106
+ */
107
+ var pluginError = function (defaults, errorArgs) {
108
+ var options = __assign(__assign({}, defaults), errorArgs);
109
+ if (options.status === 404) {
110
+ return new errors_1.NotFoundError(options);
111
+ }
112
+ if (options.status === 500) {
113
+ return new errors_1.InternalServerError(options);
114
+ }
115
+ return new errors_1.APIError(options);
116
+ };
102
117
  // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
103
118
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
104
119
  var baseUserPlugin = function (schema) {
@@ -201,7 +216,13 @@ var findOneOrNone = function (schema) {
201
216
  return [2 /*return*/, null];
202
217
  }
203
218
  if (results.length > 1) {
204
- throw new errors_1.APIError(__assign({ detail: "query: ".concat(JSON.stringify(query)), status: 500, title: "".concat(this.modelName, ".findOne query returned multiple documents") }, errorArgs));
219
+ throw pluginError({
220
+ code: "find-one-multiple-documents",
221
+ detail: "".concat(this.modelName, ".findOne query returned multiple documents. query: ").concat(JSON.stringify(query)),
222
+ meta: { model: this.modelName },
223
+ status: 500,
224
+ title: "findOne query returned multiple documents",
225
+ }, errorArgs);
205
226
  }
206
227
  return [2 /*return*/, results[0]];
207
228
  }
@@ -236,7 +257,13 @@ var findOneOrNoneFor = function (model, query, errorArgs) { return __awaiter(voi
236
257
  return [2 /*return*/, null];
237
258
  }
238
259
  if (results.length > 1) {
239
- throw new errors_1.APIError(__assign({ detail: "query: ".concat(JSON.stringify(query)), status: 500, title: "".concat(model.modelName, ".findOne query returned multiple documents") }, errorArgs));
260
+ throw pluginError({
261
+ code: "find-one-multiple-documents",
262
+ detail: "".concat(model.modelName, ".findOne query returned multiple documents. query: ").concat(JSON.stringify(query)),
263
+ meta: { model: model.modelName },
264
+ status: 500,
265
+ title: "findOne query returned multiple documents",
266
+ }, errorArgs);
240
267
  }
241
268
  return [2 /*return*/, results[0]];
242
269
  }
@@ -261,10 +288,22 @@ var findExactlyOne = function (schema) {
261
288
  case 1:
262
289
  results = _a.sent();
263
290
  if (results.length === 0) {
264
- throw new errors_1.APIError(__assign({ detail: "query: ".concat(JSON.stringify(query)), status: 404, title: "".concat(this.modelName, ".findExactlyOne query returned no documents") }, errorArgs));
291
+ throw pluginError({
292
+ code: "find-exactly-one-no-documents",
293
+ detail: "".concat(this.modelName, ".findExactlyOne query returned no documents. query: ").concat(JSON.stringify(query)),
294
+ meta: { model: this.modelName },
295
+ status: 404,
296
+ title: "findExactlyOne query returned no documents",
297
+ }, errorArgs);
265
298
  }
266
299
  if (results.length > 1) {
267
- throw new errors_1.APIError(__assign({ detail: "query: ".concat(JSON.stringify(query)), status: 500, title: "".concat(this.modelName, ".findExactlyOne query returned multiple documents") }, errorArgs));
300
+ throw pluginError({
301
+ code: "find-exactly-one-multiple-documents",
302
+ detail: "".concat(this.modelName, ".findExactlyOne query returned multiple documents. query: ").concat(JSON.stringify(query)),
303
+ meta: { model: this.modelName },
304
+ status: 500,
305
+ title: "findExactlyOne query returned multiple documents",
306
+ }, errorArgs);
268
307
  }
269
308
  return [2 /*return*/, results[0]];
270
309
  }
@@ -291,10 +330,11 @@ var upsertPlugin = function (schema) {
291
330
  case 1:
292
331
  docs = _a.sent();
293
332
  if (docs.length > 1) {
294
- throw new errors_1.APIError({
295
- detail: "query: ".concat(JSON.stringify(conditions)),
296
- status: 500,
297
- title: "".concat(this.modelName, ".upsert find query returned multiple documents"),
333
+ throw new errors_1.InternalServerError({
334
+ code: "upsert-multiple-documents",
335
+ detail: "".concat(this.modelName, ".upsert find query returned multiple documents. query: ").concat(JSON.stringify(conditions)),
336
+ meta: { model: this.modelName },
337
+ title: "upsert find query returned multiple documents",
298
338
  });
299
339
  }
300
340
  doc = docs[0];
@@ -334,7 +374,11 @@ var DateOnly = /** @class */ (function (_super) {
334
374
  }
335
375
  var handler = this.$conditionalHandlers[$conditional];
336
376
  if (!handler) {
337
- throw new Error("Can't use ".concat($conditional, " with DateOnly."));
377
+ throw new errors_1.APIError({
378
+ detail: "Can't use ".concat($conditional, " with DateOnly."),
379
+ status: 400,
380
+ title: "Unsupported query conditional for DateOnly",
381
+ });
338
382
  }
339
383
  return handler.call(this, val);
340
384
  };
@@ -349,7 +393,9 @@ var DateOnly = /** @class */ (function (_super) {
349
393
  return date.toJSDate();
350
394
  }
351
395
  if (typeof val === "string" || typeof val === "number") {
352
- var date = luxon_1.DateTime.fromJSDate(new Date(val)).toUTC().startOf("day");
396
+ var date = (typeof val === "number" ? luxon_1.DateTime.fromMillis(val) : luxon_1.DateTime.fromISO(val, { zone: "utc" }))
397
+ .toUTC()
398
+ .startOf("day");
353
399
  if (!date.isValid) {
354
400
  throw new mongoose_1.Error.CastError("DateOnly", val, this.path, new Error("Value is not a valid date"));
355
401
  }