@terreno/api 0.29.0 → 0.30.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.
- package/CHANGELOG.md +79 -0
- package/dist/actions.js +17 -8
- package/dist/actions.test.js +8 -3
- package/dist/api.arrayOperations.test.js +16 -8
- package/dist/api.coverage.test.js +2 -1
- package/dist/api.errorPaths.test.js +522 -1
- package/dist/api.errors.test.js +9 -0
- package/dist/api.js +137 -170
- package/dist/api.query.test.js +20 -8
- package/dist/api.test.js +12 -6
- package/dist/auth.coverage.test.d.ts +1 -0
- package/dist/auth.coverage.test.js +202 -0
- package/dist/auth.test.js +159 -0
- package/dist/docLoader.js +5 -1
- package/dist/envConfigurationPlugin.d.ts +1 -1
- package/dist/envConfigurationPlugin.js +0 -2
- package/dist/errors.d.ts +14 -0
- package/dist/errors.js +24 -2
- package/dist/errors.test.js +137 -0
- package/dist/httpClient.js +5 -1
- package/dist/plugins.d.ts +4 -4
- package/dist/plugins.js +51 -9
- package/dist/plugins.test.js +61 -17
- package/dist/realtime/registry.d.ts +3 -2
- package/package.json +2 -2
- package/src/actions.test.ts +8 -3
- package/src/actions.ts +19 -10
- package/src/api.arrayOperations.test.ts +16 -8
- package/src/api.coverage.test.ts +2 -1
- package/src/api.errorPaths.test.ts +313 -3
- package/src/api.errors.test.ts +12 -0
- package/src/api.query.test.ts +20 -8
- package/src/api.test.ts +12 -6
- package/src/api.ts +141 -161
- package/src/auth.coverage.test.ts +101 -0
- package/src/auth.test.ts +125 -2
- package/src/docLoader.ts +6 -2
- package/src/envConfigurationPlugin.ts +2 -6
- package/src/errors.test.ts +106 -1
- package/src/errors.ts +25 -1
- package/src/httpClient.ts +6 -2
- package/src/plugins.test.ts +45 -9
- package/src/plugins.ts +72 -35
- package/src/realtime/changeStreamWatcher.ts +8 -1
- package/src/realtime/registry.ts +3 -4
package/dist/errors.test.js
CHANGED
|
@@ -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;
|
package/dist/httpClient.js
CHANGED
|
@@ -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
|
|
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
|
}
|
package/dist/plugins.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import mongoose, { type Document, type FilterQuery, type Schema, SchemaType, type SchemaTypeOptions } from "mongoose";
|
|
2
|
-
import { type
|
|
2
|
+
import { type APIErrorOptions } from "./errors";
|
|
3
3
|
export interface BaseUser {
|
|
4
4
|
admin: boolean;
|
|
5
5
|
email: string;
|
|
@@ -41,7 +41,7 @@ export declare const findOneOrNone: <T>(schema: Schema<T>) => void;
|
|
|
41
41
|
* @param query Mongoose query object
|
|
42
42
|
* @param errorArgs Optional overrides for the thrown {@link APIError} when multiple match
|
|
43
43
|
*/
|
|
44
|
-
export declare const findOneOrNoneFor: <T>(model: mongoose.Model<T>, query: FilterQuery<T>, errorArgs?: Partial<
|
|
44
|
+
export declare const findOneOrNoneFor: <T>(model: mongoose.Model<T>, query: FilterQuery<T>, errorArgs?: Partial<APIErrorOptions>) => Promise<(Document & T) | null>;
|
|
45
45
|
/**
|
|
46
46
|
* This adds a static method `Model.findExactlyOne` to the schema. This or findOneOrNone should replace `Model.findOne`
|
|
47
47
|
* in most instances.
|
|
@@ -63,10 +63,10 @@ export interface HasUpsert<T> {
|
|
|
63
63
|
upsert(conditions: Record<string, unknown>, update: Record<string, unknown>): Promise<T>;
|
|
64
64
|
}
|
|
65
65
|
export interface FindOneOrNonePlugin<T> {
|
|
66
|
-
findOneOrNone(query: Record<string, unknown>, errorArgs?: Partial<
|
|
66
|
+
findOneOrNone(query: Record<string, unknown>, errorArgs?: Partial<APIErrorOptions>): Promise<(Document & T) | null>;
|
|
67
67
|
}
|
|
68
68
|
export interface FindExactlyOnePlugin<T> {
|
|
69
|
-
findExactlyOne(query: Record<string, unknown>, errorArgs?: Partial<
|
|
69
|
+
findExactlyOne(query: Record<string, unknown>, errorArgs?: Partial<APIErrorOptions>): Promise<Document & T>;
|
|
70
70
|
}
|
|
71
71
|
export declare class DateOnly extends SchemaType {
|
|
72
72
|
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
|
|
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
|
|
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
|
|
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
|
|
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.
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
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];
|
|
@@ -349,7 +389,9 @@ var DateOnly = /** @class */ (function (_super) {
|
|
|
349
389
|
return date.toJSDate();
|
|
350
390
|
}
|
|
351
391
|
if (typeof val === "string" || typeof val === "number") {
|
|
352
|
-
var date = luxon_1.DateTime.
|
|
392
|
+
var date = (typeof val === "number" ? luxon_1.DateTime.fromMillis(val) : luxon_1.DateTime.fromISO(val, { zone: "utc" }))
|
|
393
|
+
.toUTC()
|
|
394
|
+
.startOf("day");
|
|
353
395
|
if (!date.isValid) {
|
|
354
396
|
throw new mongoose_1.Error.CastError("DateOnly", val, this.path, new Error("Value is not a valid date"));
|
|
355
397
|
}
|
package/dist/plugins.test.js
CHANGED
|
@@ -62,6 +62,7 @@ var mongoose_1 = require("mongoose");
|
|
|
62
62
|
var supertest_1 = __importDefault(require("supertest"));
|
|
63
63
|
var api_1 = require("./api");
|
|
64
64
|
var auth_1 = require("./auth");
|
|
65
|
+
var errors_1 = require("./errors");
|
|
65
66
|
var permissions_1 = require("./permissions");
|
|
66
67
|
var plugins_1 = require("./plugins");
|
|
67
68
|
var tests_1 = require("./tests");
|
|
@@ -246,7 +247,7 @@ var StuffModel = (0, mongoose_1.model)("Stuff", stuffSchema);
|
|
|
246
247
|
switch (_a.label) {
|
|
247
248
|
case 0:
|
|
248
249
|
fn = function () { return StuffModel.findOneOrNone({ ownerId: "123" }); };
|
|
249
|
-
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(
|
|
250
|
+
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^findOne query returned multiple documents$/)];
|
|
250
251
|
case 1:
|
|
251
252
|
_a.sent();
|
|
252
253
|
return [2 /*return*/];
|
|
@@ -272,7 +273,8 @@ var StuffModel = (0, mongoose_1.model)("Stuff", stuffSchema);
|
|
|
272
273
|
// Check if the error has title and status properties
|
|
273
274
|
(0, bun_test_1.expect)(error_1.title).toBe("Oh no!");
|
|
274
275
|
(0, bun_test_1.expect)(error_1.status).toBe(400);
|
|
275
|
-
(0, bun_test_1.expect)(error_1.detail).toBe('query: {"ownerId":"123"}');
|
|
276
|
+
(0, bun_test_1.expect)(error_1.detail).toBe('Stuff.findOne query returned multiple documents. query: {"ownerId":"123"}');
|
|
277
|
+
(0, bun_test_1.expect)(error_1.code).toBe("find-one-multiple-documents");
|
|
276
278
|
return [3 /*break*/, 4];
|
|
277
279
|
case 4: return [2 /*return*/];
|
|
278
280
|
}
|
|
@@ -348,7 +350,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
|
|
|
348
350
|
switch (_a.label) {
|
|
349
351
|
case 0:
|
|
350
352
|
fn = function () { return (0, plugins_1.findOneOrNoneFor)(StuffModel, { ownerId: "123" }); };
|
|
351
|
-
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(
|
|
353
|
+
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^findOne query returned multiple documents$/)];
|
|
352
354
|
case 1:
|
|
353
355
|
_a.sent();
|
|
354
356
|
return [2 /*return*/];
|
|
@@ -428,7 +430,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
|
|
|
428
430
|
switch (_a.label) {
|
|
429
431
|
case 0:
|
|
430
432
|
fn = function () { return (0, plugins_1.findOneOrNoneFor)(BareThingModel, { ownerId: "123" }); };
|
|
431
|
-
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(
|
|
433
|
+
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^findOne query returned multiple documents$/)];
|
|
432
434
|
case 1:
|
|
433
435
|
_a.sent();
|
|
434
436
|
return [2 /*return*/];
|
|
@@ -495,13 +497,38 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
|
|
|
495
497
|
switch (_a.label) {
|
|
496
498
|
case 0:
|
|
497
499
|
fn = function () { return StuffModel.findExactlyOne({ name: "OtherStuff" }); };
|
|
498
|
-
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(
|
|
500
|
+
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^findExactlyOne query returned no documents$/)];
|
|
499
501
|
case 1:
|
|
500
502
|
_a.sent();
|
|
501
503
|
return [2 /*return*/];
|
|
502
504
|
}
|
|
503
505
|
});
|
|
504
506
|
}); });
|
|
507
|
+
(0, bun_test_1.it)("throws a NotFoundError carrying the model name in detail and meta", function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
508
|
+
var error_4;
|
|
509
|
+
return __generator(this, function (_a) {
|
|
510
|
+
switch (_a.label) {
|
|
511
|
+
case 0:
|
|
512
|
+
_a.trys.push([0, 2, , 3]);
|
|
513
|
+
return [4 /*yield*/, StuffModel.findExactlyOne({ name: "OtherStuff" })];
|
|
514
|
+
case 1:
|
|
515
|
+
_a.sent();
|
|
516
|
+
throw new Error("Expected promise to reject");
|
|
517
|
+
case 2:
|
|
518
|
+
error_4 = _a.sent();
|
|
519
|
+
(0, bun_test_1.expect)(error_4).toBeInstanceOf(errors_1.NotFoundError);
|
|
520
|
+
if (!(0, errors_1.isAPIError)(error_4)) {
|
|
521
|
+
throw error_4;
|
|
522
|
+
}
|
|
523
|
+
(0, bun_test_1.expect)(error_4.status).toBe(404);
|
|
524
|
+
(0, bun_test_1.expect)(error_4.code).toBe("find-exactly-one-no-documents");
|
|
525
|
+
(0, bun_test_1.expect)(error_4.detail).toBe('Stuff.findExactlyOne query returned no documents. query: {"name":"OtherStuff"}');
|
|
526
|
+
(0, bun_test_1.expect)(error_4.meta).toEqual({ model: "Stuff" });
|
|
527
|
+
return [3 /*break*/, 3];
|
|
528
|
+
case 3: return [2 /*return*/];
|
|
529
|
+
}
|
|
530
|
+
});
|
|
531
|
+
}); });
|
|
505
532
|
(0, bun_test_1.it)("returns a single match", function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
506
533
|
var result;
|
|
507
534
|
return __generator(this, function (_a) {
|
|
@@ -520,7 +547,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
|
|
|
520
547
|
switch (_a.label) {
|
|
521
548
|
case 0:
|
|
522
549
|
fn = function () { return StuffModel.findExactlyOne({ ownerId: "123" }); };
|
|
523
|
-
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(
|
|
550
|
+
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^findExactlyOne query returned multiple documents$/)];
|
|
524
551
|
case 1:
|
|
525
552
|
_a.sent();
|
|
526
553
|
return [2 /*return*/];
|
|
@@ -528,7 +555,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
|
|
|
528
555
|
});
|
|
529
556
|
}); });
|
|
530
557
|
(0, bun_test_1.it)("throws custom error with two matches.", function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
531
|
-
var fn,
|
|
558
|
+
var fn, error_5;
|
|
532
559
|
return __generator(this, function (_a) {
|
|
533
560
|
switch (_a.label) {
|
|
534
561
|
case 0:
|
|
@@ -542,11 +569,12 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
|
|
|
542
569
|
// If the promise doesn't reject, the test should fail
|
|
543
570
|
throw new Error("Expected promise to reject");
|
|
544
571
|
case 3:
|
|
545
|
-
|
|
572
|
+
error_5 = _a.sent();
|
|
546
573
|
// Check if the error has title and status properties
|
|
547
|
-
(0, bun_test_1.expect)(
|
|
548
|
-
(0, bun_test_1.expect)(
|
|
549
|
-
(0, bun_test_1.expect)(
|
|
574
|
+
(0, bun_test_1.expect)(error_5.title).toBe("Oh no!");
|
|
575
|
+
(0, bun_test_1.expect)(error_5.status).toBe(400);
|
|
576
|
+
(0, bun_test_1.expect)(error_5.detail).toBe('Stuff.findExactlyOne query returned multiple documents. query: {"ownerId":"123"}');
|
|
577
|
+
(0, bun_test_1.expect)(error_5.code).toBe("find-exactly-one-multiple-documents");
|
|
550
578
|
return [3 /*break*/, 4];
|
|
551
579
|
case 4: return [2 /*return*/];
|
|
552
580
|
}
|
|
@@ -610,7 +638,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
|
|
|
610
638
|
});
|
|
611
639
|
}); });
|
|
612
640
|
(0, bun_test_1.it)("throws error when multiple documents match conditions", function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
613
|
-
var fn;
|
|
641
|
+
var fn, error_6;
|
|
614
642
|
return __generator(this, function (_a) {
|
|
615
643
|
switch (_a.label) {
|
|
616
644
|
case 0: return [4 /*yield*/, Promise.all([
|
|
@@ -620,10 +648,26 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
|
|
|
620
648
|
case 1:
|
|
621
649
|
_a.sent();
|
|
622
650
|
fn = function () { return StuffModel.upsert({ ownerId: "123" }, { name: "Updated" }); };
|
|
623
|
-
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(
|
|
651
|
+
return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^upsert find query returned multiple documents$/)];
|
|
624
652
|
case 2:
|
|
625
653
|
_a.sent();
|
|
626
|
-
|
|
654
|
+
_a.label = 3;
|
|
655
|
+
case 3:
|
|
656
|
+
_a.trys.push([3, 5, , 6]);
|
|
657
|
+
return [4 /*yield*/, fn()];
|
|
658
|
+
case 4:
|
|
659
|
+
_a.sent();
|
|
660
|
+
return [3 /*break*/, 6];
|
|
661
|
+
case 5:
|
|
662
|
+
error_6 = _a.sent();
|
|
663
|
+
(0, bun_test_1.expect)(error_6).toBeInstanceOf(errors_1.InternalServerError);
|
|
664
|
+
if (!(0, errors_1.isAPIError)(error_6)) {
|
|
665
|
+
throw error_6;
|
|
666
|
+
}
|
|
667
|
+
(0, bun_test_1.expect)(error_6.code).toBe("upsert-multiple-documents");
|
|
668
|
+
(0, bun_test_1.expect)(error_6.detail).toBe('Stuff.upsert find query returned multiple documents. query: {"ownerId":"123"}');
|
|
669
|
+
return [3 /*break*/, 6];
|
|
670
|
+
case 6: return [2 /*return*/];
|
|
627
671
|
}
|
|
628
672
|
});
|
|
629
673
|
}); });
|
|
@@ -709,7 +753,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
|
|
|
709
753
|
});
|
|
710
754
|
(0, bun_test_1.describe)("DateOnly", function () {
|
|
711
755
|
(0, bun_test_1.it)("throws error with invalid date", function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
712
|
-
var
|
|
756
|
+
var error_7;
|
|
713
757
|
return __generator(this, function (_a) {
|
|
714
758
|
switch (_a.label) {
|
|
715
759
|
case 0:
|
|
@@ -723,8 +767,8 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
|
|
|
723
767
|
_a.sent();
|
|
724
768
|
return [3 /*break*/, 3];
|
|
725
769
|
case 2:
|
|
726
|
-
|
|
727
|
-
(0, bun_test_1.expect)(
|
|
770
|
+
error_7 = _a.sent();
|
|
771
|
+
(0, bun_test_1.expect)(error_7.message).toMatch(/Cast to DateOnly failed/);
|
|
728
772
|
return [2 /*return*/];
|
|
729
773
|
case 3: throw new Error("Expected error was not thrown");
|
|
730
774
|
}
|
|
@@ -13,9 +13,10 @@ export interface RealtimeRegistryEntry {
|
|
|
13
13
|
/** Real-time configuration from modelRouter options */
|
|
14
14
|
config: RealtimeConfig;
|
|
15
15
|
/**
|
|
16
|
-
* Full modelRouter options (for responseHandler, permissions, etc.)
|
|
16
|
+
* Full modelRouter options (for responseHandler, permissions, etc.), erased to
|
|
17
|
+
* `unknown` since the registry holds entries for every model.
|
|
17
18
|
*/
|
|
18
|
-
options: ModelRouterOptions<
|
|
19
|
+
options: ModelRouterOptions<unknown>;
|
|
19
20
|
}
|
|
20
21
|
/**
|
|
21
22
|
* Register a model for real-time sync. Called automatically by modelRouter
|
package/package.json
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
"@asteasolutions/zod-to-openapi": "^8.5.0",
|
|
8
8
|
"@sentry/bun": "^10.39.0",
|
|
9
9
|
"@sentry/profiling-node": "^10.25.0",
|
|
10
|
-
"@terreno/test": "0.
|
|
10
|
+
"@terreno/test": "0.30.0",
|
|
11
11
|
"@types/qs": "^6.14.0",
|
|
12
12
|
"ajv": "8.20.0",
|
|
13
13
|
"ajv-formats": "^3.0.1",
|
|
@@ -123,5 +123,5 @@
|
|
|
123
123
|
"updateSnapshot": "bun test --update-snapshots"
|
|
124
124
|
},
|
|
125
125
|
"types": "dist/index.d.ts",
|
|
126
|
-
"version": "0.
|
|
126
|
+
"version": "0.30.0"
|
|
127
127
|
}
|
package/src/actions.test.ts
CHANGED
|
@@ -193,7 +193,8 @@ describe("modelRouter actions", () => {
|
|
|
193
193
|
});
|
|
194
194
|
const agent = await authAsUser(app, "admin");
|
|
195
195
|
const res = await agent.post("/food/disabled").send({}).expect(405);
|
|
196
|
-
expect(res.body.title).
|
|
196
|
+
expect(res.body.title).toBe("Access denied");
|
|
197
|
+
expect(res.body.detail).toContain("Access to CREATE on Food denied");
|
|
197
198
|
});
|
|
198
199
|
|
|
199
200
|
it("runs instance POST action with ctx.doc and req.obj", async () => {
|
|
@@ -333,7 +334,8 @@ describe("modelRouter actions", () => {
|
|
|
333
334
|
});
|
|
334
335
|
const agent = await authAsUser(app, "notAdmin");
|
|
335
336
|
const res = await agent.post("/food/adminOnly").send({}).expect(405);
|
|
336
|
-
expect(res.body.title).
|
|
337
|
+
expect(res.body.title).toBe("Access denied");
|
|
338
|
+
expect(res.body.detail).toContain("Access to CREATE on Food denied");
|
|
337
339
|
});
|
|
338
340
|
|
|
339
341
|
it("returns 403 for instance action when post-doc permission denied", async () => {
|
|
@@ -357,7 +359,8 @@ describe("modelRouter actions", () => {
|
|
|
357
359
|
});
|
|
358
360
|
const agent = await authAsUser(app, "notAdmin");
|
|
359
361
|
const res = await agent.post(`/food/${adminFood._id}/ownerOnly`).send({}).expect(403);
|
|
360
|
-
expect(res.body.title).
|
|
362
|
+
expect(res.body.title).toBe("Access denied");
|
|
363
|
+
expect(res.body.detail).toContain(`Access to UPDATE on Food:${adminFood._id} denied`);
|
|
361
364
|
});
|
|
362
365
|
|
|
363
366
|
it("allows IsAuthenticatedOrReadOnly on GET with allowAnonymous", async () => {
|
|
@@ -412,6 +415,7 @@ describe("modelRouter actions", () => {
|
|
|
412
415
|
});
|
|
413
416
|
const res = await server.post("/food/notify").send({email: "not-an-email"}).expect(400);
|
|
414
417
|
expect(res.body.title).toBe("Validation failed");
|
|
418
|
+
expect(res.body.code).toBe("action-body-validation-failed");
|
|
415
419
|
expect(res.body.meta.fields.email).toBeDefined();
|
|
416
420
|
});
|
|
417
421
|
|
|
@@ -451,6 +455,7 @@ describe("modelRouter actions", () => {
|
|
|
451
455
|
});
|
|
452
456
|
const res = await server.get("/food/lookup?email=bad").expect(400);
|
|
453
457
|
expect(res.body.title).toBe("Validation failed");
|
|
458
|
+
expect(res.body.code).toBe("action-query-validation-failed");
|
|
454
459
|
expect(res.body.meta.fields.email).toBeDefined();
|
|
455
460
|
});
|
|
456
461
|
|
package/src/actions.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type {ZodSchema, ZodType} from "zod";
|
|
|
6
6
|
import {asyncHandler, type ModelRouterOptions, type RESTMethod} from "./api";
|
|
7
7
|
import {authenticateMiddleware, type User} from "./auth";
|
|
8
8
|
import {loadDocOr404} from "./docLoader";
|
|
9
|
-
import {APIError} from "./errors";
|
|
9
|
+
import {APIError, ForbiddenError, ValidationError} from "./errors";
|
|
10
10
|
import {defaultOpenApiErrorResponses} from "./openApi";
|
|
11
11
|
import {checkPermissions, type PermissionMethod} from "./permissions";
|
|
12
12
|
|
|
@@ -85,18 +85,25 @@ export const runActionPermissions = async <T>(
|
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
if (!doc) {
|
|
88
|
+
// Status kept at 405 for backwards compatibility with the same pre-document permission denial
|
|
89
|
+
// in modelRouter's array operations; changing it would break consumers matching on it.
|
|
88
90
|
throw new APIError({
|
|
89
|
-
|
|
90
|
-
|
|
91
|
+
code: "action-access-denied",
|
|
92
|
+
detail:
|
|
91
93
|
`Access to ${method.toUpperCase()} on ${model.modelName} ` + `denied for ${req.user?.id}`,
|
|
94
|
+
meta: {action: method.toUpperCase(), model: model.modelName},
|
|
95
|
+
status: 405,
|
|
96
|
+
title: "Access denied",
|
|
92
97
|
});
|
|
93
98
|
}
|
|
94
99
|
|
|
95
|
-
throw new
|
|
96
|
-
|
|
97
|
-
|
|
100
|
+
throw new ForbiddenError({
|
|
101
|
+
code: "action-access-denied",
|
|
102
|
+
detail:
|
|
98
103
|
`Access to ${method.toUpperCase()} on ${model.modelName}:${req.params.id} ` +
|
|
99
104
|
`denied for ${req.user?.id}`,
|
|
105
|
+
meta: {action: method.toUpperCase(), model: model.modelName},
|
|
106
|
+
title: "Access denied",
|
|
100
107
|
});
|
|
101
108
|
};
|
|
102
109
|
|
|
@@ -123,9 +130,10 @@ export const validateActionRequest = <TBody, TQuery>({
|
|
|
123
130
|
if (action.body) {
|
|
124
131
|
const parsedBody = action.body.safeParse(req.body);
|
|
125
132
|
if (!parsedBody.success) {
|
|
126
|
-
throw new
|
|
133
|
+
throw new ValidationError({
|
|
134
|
+
code: "action-body-validation-failed",
|
|
135
|
+
detail: "The request body did not match the action's schema",
|
|
127
136
|
fields: flattenZodFieldErrors(parsedBody.error.flatten().fieldErrors),
|
|
128
|
-
status: 400,
|
|
129
137
|
title: "Validation failed",
|
|
130
138
|
});
|
|
131
139
|
}
|
|
@@ -138,9 +146,10 @@ export const validateActionRequest = <TBody, TQuery>({
|
|
|
138
146
|
if (action.query) {
|
|
139
147
|
const parsedQuery = action.query.safeParse(req.query);
|
|
140
148
|
if (!parsedQuery.success) {
|
|
141
|
-
throw new
|
|
149
|
+
throw new ValidationError({
|
|
150
|
+
code: "action-query-validation-failed",
|
|
151
|
+
detail: "The query parameters did not match the action's schema",
|
|
142
152
|
fields: flattenZodFieldErrors(parsedQuery.error.flatten().fieldErrors),
|
|
143
|
-
status: 400,
|
|
144
153
|
title: "Validation failed",
|
|
145
154
|
});
|
|
146
155
|
}
|