@terreno/api 0.30.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.
- package/CHANGELOG.md +2 -122
- package/LICENSE +21 -202
- package/dist/actions.openApi.test.js +1 -3
- package/dist/actions.test.js +0 -2
- package/dist/api.coverage.test.js +0 -2
- package/dist/api.d.ts +3 -2
- package/dist/api.errorPaths.test.js +86 -0
- package/dist/betterAuthSetup.d.ts +15 -1
- package/dist/betterAuthSetup.js +4 -6
- package/dist/configurationPlugin.js +2 -2
- package/dist/consentApp.test.js +1 -5
- package/dist/expressServer.js +11 -5
- package/dist/githubAuth.js +1 -4
- package/dist/openApiBuilder.test.js +0 -2
- package/dist/openApiValidator.test.js +34 -0
- package/dist/plugins.d.ts +3 -2
- package/dist/plugins.js +5 -1
- package/dist/plugins.test.js +12 -0
- package/dist/populate.test.js +9 -12
- package/dist/realtime/realtime.test.js +231 -0
- package/dist/realtime/realtimeApp.d.ts +1 -1
- package/dist/realtime/realtimeApp.js +6 -2
- package/dist/realtime/realtimeAppSetup.test.d.ts +1 -0
- package/dist/realtime/realtimeAppSetup.test.js +213 -0
- package/dist/tests/models.d.ts +27 -11
- package/dist/tests/models.js +5 -3
- package/dist/tests/testHelper.d.ts +9 -3
- package/package.json +4 -5
- package/src/actions.openApi.test.ts +7 -10
- package/src/actions.test.ts +19 -12
- package/src/actions.ts +2 -2
- package/src/api.coverage.test.ts +7 -9
- package/src/api.errorPaths.test.ts +47 -1
- package/src/api.ts +22 -11
- package/src/betterAuthSetup.ts +7 -7
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/expressServer.ts +11 -5
- package/src/githubAuth.ts +1 -3
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +24 -9
- package/src/openApiValidator.test.ts +41 -0
- package/src/plugins.test.ts +14 -0
- package/src/plugins.ts +9 -4
- package/src/populate.test.ts +25 -16
- package/src/realtime/realtime.test.ts +239 -0
- package/src/realtime/realtimeApp.ts +8 -5
- package/src/realtime/realtimeAppSetup.test.ts +161 -0
- package/src/tests/models.ts +8 -6
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
36
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
37
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
38
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
39
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
40
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
41
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
45
|
+
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);
|
|
46
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
47
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
48
|
+
function step(op) {
|
|
49
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
50
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
51
|
+
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;
|
|
52
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
53
|
+
switch (op[0]) {
|
|
54
|
+
case 0: case 1: t = op; break;
|
|
55
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
56
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
57
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
58
|
+
default:
|
|
59
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
60
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
61
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
62
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
63
|
+
if (t[2]) _.ops.pop();
|
|
64
|
+
_.trys.pop(); continue;
|
|
65
|
+
}
|
|
66
|
+
op = body.call(thisArg, _);
|
|
67
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
68
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
72
|
+
/**
|
|
73
|
+
* Tests for RealtimeApp.onServerCreated — the Socket.io server wiring that a
|
|
74
|
+
* live server would exercise. socket.io, the JWT authorize middleware, and the
|
|
75
|
+
* change-stream watcher are mocked so the connection / connect_error handlers
|
|
76
|
+
* can be captured and invoked without standing up a real server.
|
|
77
|
+
*/
|
|
78
|
+
var bun_test_1 = require("bun:test");
|
|
79
|
+
var ios = [];
|
|
80
|
+
var watcherStarts = 0;
|
|
81
|
+
var FakeServer = /** @class */ (function () {
|
|
82
|
+
function FakeServer() {
|
|
83
|
+
var _args = [];
|
|
84
|
+
for (var _i = 0; _i < arguments.length; _i++) {
|
|
85
|
+
_args[_i] = arguments[_i];
|
|
86
|
+
}
|
|
87
|
+
this.handlers = new Map();
|
|
88
|
+
this.middleware = [];
|
|
89
|
+
this.closed = false;
|
|
90
|
+
this.engine = { clientsCount: 0 };
|
|
91
|
+
ios.push(this);
|
|
92
|
+
}
|
|
93
|
+
FakeServer.prototype.use = function (mw) {
|
|
94
|
+
this.middleware.push(mw);
|
|
95
|
+
};
|
|
96
|
+
FakeServer.prototype.on = function (event, handler) {
|
|
97
|
+
this.handlers.set(event, handler);
|
|
98
|
+
};
|
|
99
|
+
FakeServer.prototype.close = function (cb) {
|
|
100
|
+
this.closed = true;
|
|
101
|
+
cb === null || cb === void 0 ? void 0 : cb();
|
|
102
|
+
};
|
|
103
|
+
return FakeServer;
|
|
104
|
+
}());
|
|
105
|
+
bun_test_1.mock.module("socket.io", function () { return ({ Server: FakeServer }); });
|
|
106
|
+
bun_test_1.mock.module("@thream/socketio-jwt", function () { return ({
|
|
107
|
+
authorize: function (_opts) { return function (_socket, next) { return next(); }; },
|
|
108
|
+
}); });
|
|
109
|
+
bun_test_1.mock.module("./changeStreamWatcher", function () { return ({
|
|
110
|
+
startChangeStreamWatcher: function () {
|
|
111
|
+
watcherStarts += 1;
|
|
112
|
+
},
|
|
113
|
+
stopChangeStreamWatcher: function () { },
|
|
114
|
+
}); });
|
|
115
|
+
var RealtimeApp;
|
|
116
|
+
(0, bun_test_1.beforeAll)(function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
117
|
+
return __generator(this, function (_a) {
|
|
118
|
+
switch (_a.label) {
|
|
119
|
+
case 0: return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require("./realtimeApp")); })];
|
|
120
|
+
case 1:
|
|
121
|
+
(RealtimeApp = (_a.sent()).RealtimeApp);
|
|
122
|
+
return [2 /*return*/];
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}); });
|
|
126
|
+
var lastIo = function () {
|
|
127
|
+
var io = ios[ios.length - 1];
|
|
128
|
+
if (!io) {
|
|
129
|
+
throw new Error("No Socket.io server was created");
|
|
130
|
+
}
|
|
131
|
+
return io;
|
|
132
|
+
};
|
|
133
|
+
var getHandler = function (event) {
|
|
134
|
+
var handler = lastIo().handlers.get(event);
|
|
135
|
+
if (!handler) {
|
|
136
|
+
throw new Error("No handler registered for ".concat(event));
|
|
137
|
+
}
|
|
138
|
+
return handler;
|
|
139
|
+
};
|
|
140
|
+
var fakeServer = {};
|
|
141
|
+
var createConnectionSocket = function (throwOnOn) {
|
|
142
|
+
if (throwOnOn === void 0) { throwOnOn = false; }
|
|
143
|
+
var listeners = new Map();
|
|
144
|
+
return {
|
|
145
|
+
decodedToken: { admin: false, id: "user-42" },
|
|
146
|
+
emit: function () { },
|
|
147
|
+
id: "socket-1",
|
|
148
|
+
join: function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
|
|
149
|
+
return [2 /*return*/];
|
|
150
|
+
}); }); },
|
|
151
|
+
leave: function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
|
|
152
|
+
return [2 /*return*/];
|
|
153
|
+
}); }); },
|
|
154
|
+
on: function (event, handler) {
|
|
155
|
+
if (throwOnOn) {
|
|
156
|
+
throw new Error("boom");
|
|
157
|
+
}
|
|
158
|
+
listeners.set(event, handler);
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
(0, bun_test_1.describe)("RealtimeApp.onServerCreated", function () {
|
|
163
|
+
(0, bun_test_1.beforeEach)(function () {
|
|
164
|
+
ios = [];
|
|
165
|
+
watcherStarts = 0;
|
|
166
|
+
});
|
|
167
|
+
(0, bun_test_1.afterEach)(function () {
|
|
168
|
+
delete process.env.TOKEN_SECRET;
|
|
169
|
+
});
|
|
170
|
+
(0, bun_test_1.it)("wires up auth middleware, connection handlers, and the change-stream watcher", function () {
|
|
171
|
+
var app = new RealtimeApp({ debug: true, tokenSecret: "test-secret" });
|
|
172
|
+
app.onServerCreated(fakeServer);
|
|
173
|
+
var io = lastIo();
|
|
174
|
+
(0, bun_test_1.expect)(io.middleware.length).toBe(1);
|
|
175
|
+
(0, bun_test_1.expect)(io.handlers.has("connection")).toBe(true);
|
|
176
|
+
(0, bun_test_1.expect)(io.handlers.has("connect_error")).toBe(true);
|
|
177
|
+
(0, bun_test_1.expect)(watcherStarts).toBe(1);
|
|
178
|
+
(0, bun_test_1.expect)(app.getIo()).not.toBeNull();
|
|
179
|
+
});
|
|
180
|
+
(0, bun_test_1.it)("installs socket handlers for each new connection", function () {
|
|
181
|
+
var app = new RealtimeApp({ tokenSecret: "test-secret" });
|
|
182
|
+
app.onServerCreated(fakeServer);
|
|
183
|
+
var connectionHandler = getHandler("connection");
|
|
184
|
+
var socket = createConnectionSocket();
|
|
185
|
+
// Should run installRealtimeSocketHandlers without throwing.
|
|
186
|
+
(0, bun_test_1.expect)(function () { return connectionHandler(socket); }).not.toThrow();
|
|
187
|
+
});
|
|
188
|
+
(0, bun_test_1.it)("captures errors thrown while handling a connection", function () {
|
|
189
|
+
var app = new RealtimeApp({ tokenSecret: "test-secret" });
|
|
190
|
+
app.onServerCreated(fakeServer);
|
|
191
|
+
var connectionHandler = getHandler("connection");
|
|
192
|
+
var brokenSocket = createConnectionSocket(true);
|
|
193
|
+
// The handler swallows the error rather than crashing the server.
|
|
194
|
+
(0, bun_test_1.expect)(function () { return connectionHandler(brokenSocket); }).not.toThrow();
|
|
195
|
+
});
|
|
196
|
+
(0, bun_test_1.it)("logs connect_error events without throwing", function () {
|
|
197
|
+
var app = new RealtimeApp({ tokenSecret: "test-secret" });
|
|
198
|
+
app.onServerCreated(fakeServer);
|
|
199
|
+
var errorHandler = getHandler("connect_error");
|
|
200
|
+
(0, bun_test_1.expect)(function () { return errorHandler(new Error("handshake failed")); }).not.toThrow();
|
|
201
|
+
});
|
|
202
|
+
(0, bun_test_1.it)("reads the token secret from the environment when not provided in config", function () {
|
|
203
|
+
process.env.TOKEN_SECRET = "env-secret";
|
|
204
|
+
var app = new RealtimeApp();
|
|
205
|
+
app.onServerCreated(fakeServer);
|
|
206
|
+
(0, bun_test_1.expect)(lastIo().handlers.has("connection")).toBe(true);
|
|
207
|
+
});
|
|
208
|
+
(0, bun_test_1.it)("throws when no token secret is available", function () {
|
|
209
|
+
delete process.env.TOKEN_SECRET;
|
|
210
|
+
var app = new RealtimeApp();
|
|
211
|
+
(0, bun_test_1.expect)(function () { return app.onServerCreated(fakeServer); }).toThrow(/TOKEN_SECRET is required/);
|
|
212
|
+
});
|
|
213
|
+
});
|
package/dist/tests/models.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import mongoose, { type Model
|
|
1
|
+
import mongoose, { type Model } from "mongoose";
|
|
2
2
|
export interface User {
|
|
3
3
|
admin: boolean;
|
|
4
4
|
name?: string;
|
|
@@ -33,14 +33,14 @@ export interface Food {
|
|
|
33
33
|
dateAdded?: string;
|
|
34
34
|
};
|
|
35
35
|
tags: string[];
|
|
36
|
-
eatenBy:
|
|
36
|
+
eatenBy: Array<mongoose.Types.ObjectId | User>;
|
|
37
37
|
lastEatenWith: {
|
|
38
38
|
[name: string]: Date;
|
|
39
39
|
};
|
|
40
40
|
categories: FoodCategory[];
|
|
41
41
|
expiration: string;
|
|
42
42
|
likesIds: {
|
|
43
|
-
userId: string;
|
|
43
|
+
userId: mongoose.Types.ObjectId | string;
|
|
44
44
|
likes: boolean;
|
|
45
45
|
}[];
|
|
46
46
|
}
|
|
@@ -48,24 +48,40 @@ export interface RequiredField {
|
|
|
48
48
|
name: string;
|
|
49
49
|
about?: string;
|
|
50
50
|
}
|
|
51
|
-
export declare const UserModel: mongoose.Model<User, {}, {}, {}, mongoose.Document<unknown, {}, User, {},
|
|
51
|
+
export declare const UserModel: mongoose.Model<User, {}, {}, {}, mongoose.Document<unknown, {}, User, {}, mongoose.DefaultSchemaOptions> & User & {
|
|
52
52
|
_id: mongoose.Types.ObjectId;
|
|
53
53
|
} & {
|
|
54
54
|
__v: number;
|
|
55
|
-
}
|
|
56
|
-
|
|
55
|
+
} & {
|
|
56
|
+
id: string;
|
|
57
|
+
}, any, User>;
|
|
58
|
+
export declare const SuperUserModel: mongoose.Model<User & SuperUser, {}, {}, {
|
|
59
|
+
id: string;
|
|
60
|
+
}, mongoose.Document<unknown, {}, User & SuperUser, {
|
|
61
|
+
id: string;
|
|
62
|
+
}, mongoose.DefaultSchemaOptions> & Omit<User & SuperUser & {
|
|
57
63
|
_id: mongoose.Types.ObjectId;
|
|
58
64
|
} & {
|
|
59
65
|
__v: number;
|
|
60
|
-
},
|
|
61
|
-
|
|
66
|
+
}, "id"> & mongoose.HydratedDocumentOverrides<{
|
|
67
|
+
id: string;
|
|
68
|
+
}>, any, User & SuperUser>;
|
|
69
|
+
export declare const StaffUserModel: mongoose.Model<User & StaffUser, {}, {}, {
|
|
70
|
+
id: string;
|
|
71
|
+
}, mongoose.Document<unknown, {}, User & StaffUser, {
|
|
72
|
+
id: string;
|
|
73
|
+
}, mongoose.DefaultSchemaOptions> & Omit<User & StaffUser & {
|
|
62
74
|
_id: mongoose.Types.ObjectId;
|
|
63
75
|
} & {
|
|
64
76
|
__v: number;
|
|
65
|
-
},
|
|
77
|
+
}, "id"> & mongoose.HydratedDocumentOverrides<{
|
|
78
|
+
id: string;
|
|
79
|
+
}>, any, User & StaffUser>;
|
|
66
80
|
export declare const FoodModel: Model<Food>;
|
|
67
|
-
export declare const RequiredModel: mongoose.Model<RequiredField, {}, {}, {}, mongoose.Document<unknown, {}, RequiredField, {},
|
|
81
|
+
export declare const RequiredModel: mongoose.Model<RequiredField, {}, {}, {}, mongoose.Document<unknown, {}, RequiredField, {}, mongoose.DefaultSchemaOptions> & RequiredField & {
|
|
68
82
|
_id: mongoose.Types.ObjectId;
|
|
69
83
|
} & {
|
|
70
84
|
__v: number;
|
|
71
|
-
}
|
|
85
|
+
} & {
|
|
86
|
+
id: string;
|
|
87
|
+
}, any, RequiredField>;
|
package/dist/tests/models.js
CHANGED
|
@@ -101,9 +101,11 @@ var foodSchema = new mongoose_1.Schema({
|
|
|
101
101
|
type: mongoose_1.Schema.Types.ObjectId,
|
|
102
102
|
},
|
|
103
103
|
],
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
104
|
+
expiration: {
|
|
105
|
+
description: "Expiration date of the food",
|
|
106
|
+
// DateOnly is a custom SchemaType registered on Schema.Types; it stores an ISO date string.
|
|
107
|
+
type: plugins_1.DateOnly,
|
|
108
|
+
},
|
|
107
109
|
hidden: {
|
|
108
110
|
default: false,
|
|
109
111
|
description: "Whether this food is hidden from listings",
|
|
@@ -1,18 +1,24 @@
|
|
|
1
1
|
import type { TestData } from "./types";
|
|
2
2
|
export declare const applyTestAuthEnv: () => void;
|
|
3
3
|
/** Seeds only the standard users (legacy helper). */
|
|
4
|
-
export declare const setupDb: () => Promise<readonly [import("mongoose").Document<unknown, {}, import("./models").User, {},
|
|
4
|
+
export declare const setupDb: () => Promise<readonly [import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
|
|
5
5
|
_id: import("mongoose").Types.ObjectId;
|
|
6
6
|
} & {
|
|
7
7
|
__v: number;
|
|
8
|
-
}
|
|
8
|
+
} & {
|
|
9
|
+
id: string;
|
|
10
|
+
}, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
|
|
9
11
|
_id: import("mongoose").Types.ObjectId;
|
|
10
12
|
} & {
|
|
11
13
|
__v: number;
|
|
12
|
-
}
|
|
14
|
+
} & {
|
|
15
|
+
id: string;
|
|
16
|
+
}, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
|
|
13
17
|
_id: import("mongoose").Types.ObjectId;
|
|
14
18
|
} & {
|
|
15
19
|
__v: number;
|
|
20
|
+
} & {
|
|
21
|
+
id: string;
|
|
16
22
|
}]>;
|
|
17
23
|
/** Seeds users, foods, and required docs — the recommended API test baseline. */
|
|
18
24
|
export declare const setupTestData: () => Promise<TestData>;
|
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.31.0",
|
|
11
11
|
"@types/qs": "^6.14.0",
|
|
12
12
|
"ajv": "8.20.0",
|
|
13
13
|
"ajv-formats": "^3.0.1",
|
|
@@ -54,7 +54,6 @@
|
|
|
54
54
|
"@types/express": "^5.0.6",
|
|
55
55
|
"@types/jsonwebtoken": "^9.0.9",
|
|
56
56
|
"@types/lodash": "^4.17.17",
|
|
57
|
-
"@types/mongodb": "^4.0.7",
|
|
58
57
|
"@types/node": "^25.3.0",
|
|
59
58
|
"@types/on-finished": "^2.3.4",
|
|
60
59
|
"@types/passport": "^1.0.17",
|
|
@@ -65,7 +64,7 @@
|
|
|
65
64
|
"@types/sinon": "^21.0.0",
|
|
66
65
|
"@types/supertest": "^7.2.0",
|
|
67
66
|
"mongodb-memory-server": "^11.0.1",
|
|
68
|
-
"mongoose": "
|
|
67
|
+
"mongoose": "9.7.4",
|
|
69
68
|
"sinon": "^22.0.0",
|
|
70
69
|
"supertest": "^7.2.2",
|
|
71
70
|
"typedoc": "^0.28.17",
|
|
@@ -79,7 +78,7 @@
|
|
|
79
78
|
"mongoose",
|
|
80
79
|
"express"
|
|
81
80
|
],
|
|
82
|
-
"license": "
|
|
81
|
+
"license": "MIT",
|
|
83
82
|
"main": "dist/index.js",
|
|
84
83
|
"exports": {
|
|
85
84
|
".": {
|
|
@@ -123,5 +122,5 @@
|
|
|
123
122
|
"updateSnapshot": "bun test --update-snapshots"
|
|
124
123
|
},
|
|
125
124
|
"types": "dist/index.d.ts",
|
|
126
|
-
"version": "0.
|
|
125
|
+
"version": "0.31.0"
|
|
127
126
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
4
2
|
import type express from "express";
|
|
5
3
|
import supertest from "supertest";
|
|
6
|
-
import {
|
|
4
|
+
import {modelRouter} from "./api";
|
|
5
|
+
import type {UserModel as UserMongooseModel} from "./auth";
|
|
6
|
+
import type {AddRoutes} from "./expressServer";
|
|
7
7
|
import {Permissions} from "./permissions";
|
|
8
8
|
import {TerrenoApp} from "./terrenoApp";
|
|
9
9
|
import {FoodModel, setupDb, UserModel} from "./tests";
|
|
@@ -130,7 +130,7 @@ describe("action OpenAPI emission", () => {
|
|
|
130
130
|
const foodRegistration = modelRouter("/food", FoodModel, foodActionRouterOptions);
|
|
131
131
|
const app = new TerrenoApp({
|
|
132
132
|
skipListen: true,
|
|
133
|
-
userModel: UserModel as
|
|
133
|
+
userModel: UserModel as unknown as UserMongooseModel,
|
|
134
134
|
})
|
|
135
135
|
.register(foodRegistration)
|
|
136
136
|
.build();
|
|
@@ -151,20 +151,17 @@ describe("action OpenAPI emission", () => {
|
|
|
151
151
|
let app: express.Application;
|
|
152
152
|
|
|
153
153
|
beforeEach(() => {
|
|
154
|
-
const configureApp = (
|
|
155
|
-
router: express.Router,
|
|
156
|
-
routerOptions?: Partial<ModelRouterOptions<unknown>>
|
|
157
|
-
): void => {
|
|
154
|
+
const configureApp: AddRoutes = (router, routerOptions) => {
|
|
158
155
|
router.use(
|
|
159
156
|
"/food",
|
|
160
|
-
modelRouter(FoodModel
|
|
157
|
+
modelRouter(FoodModel, {...foodActionRouterOptions, openApi: routerOptions?.openApi})
|
|
161
158
|
);
|
|
162
159
|
};
|
|
163
160
|
|
|
164
161
|
app = new TerrenoApp({
|
|
165
162
|
configureApp,
|
|
166
163
|
skipListen: true,
|
|
167
|
-
userModel: UserModel as
|
|
164
|
+
userModel: UserModel as unknown as UserMongooseModel,
|
|
168
165
|
}).build();
|
|
169
166
|
});
|
|
170
167
|
|
package/src/actions.test.ts
CHANGED
|
@@ -1,22 +1,29 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
4
2
|
import type express from "express";
|
|
5
|
-
import {type Model, model, Schema} from "mongoose";
|
|
3
|
+
import {type HydratedDocument, type Model, model, Schema} from "mongoose";
|
|
6
4
|
import supertest from "supertest";
|
|
7
5
|
import type TestAgent from "supertest/lib/agent";
|
|
8
6
|
import {
|
|
9
7
|
ACTION_NAME_PATTERN,
|
|
8
|
+
type CollectionActionConfig,
|
|
10
9
|
createActionOpenApiMiddleware,
|
|
11
10
|
defineCollectionAction,
|
|
12
11
|
defineInstanceAction,
|
|
13
12
|
} from "./actions";
|
|
14
13
|
import {modelRouter, type OpenApiMiddleware} from "./api";
|
|
15
|
-
import {addAuthRoutes, setupAuth} from "./auth";
|
|
14
|
+
import {addAuthRoutes, setupAuth, type UserModel as UserMongooseModel} from "./auth";
|
|
16
15
|
import {apiUnauthorizedMiddleware} from "./errors";
|
|
17
16
|
import {Permissions} from "./permissions";
|
|
18
17
|
import {type IsDeleted, isDeletedPlugin} from "./plugins";
|
|
19
|
-
import {
|
|
18
|
+
import {
|
|
19
|
+
authAsUser,
|
|
20
|
+
type Food,
|
|
21
|
+
FoodModel,
|
|
22
|
+
getBaseServer,
|
|
23
|
+
setupDb,
|
|
24
|
+
type User,
|
|
25
|
+
UserModel,
|
|
26
|
+
} from "./tests";
|
|
20
27
|
import {z} from "./zodOpenApi";
|
|
21
28
|
|
|
22
29
|
interface Stuff extends IsDeleted {
|
|
@@ -49,7 +56,7 @@ describe("modelRouter actions", () => {
|
|
|
49
56
|
broken: {
|
|
50
57
|
handler: async () => ({ok: true}),
|
|
51
58
|
method: "POST",
|
|
52
|
-
} as
|
|
59
|
+
} as unknown as CollectionActionConfig<unknown, unknown, unknown>,
|
|
53
60
|
},
|
|
54
61
|
permissions: allPermissions,
|
|
55
62
|
})
|
|
@@ -142,8 +149,8 @@ describe("modelRouter actions", () => {
|
|
|
142
149
|
describe("integration", () => {
|
|
143
150
|
let app: express.Application;
|
|
144
151
|
let server: TestAgent;
|
|
145
|
-
let admin:
|
|
146
|
-
let notAdmin:
|
|
152
|
+
let admin: HydratedDocument<User>;
|
|
153
|
+
let notAdmin: HydratedDocument<User>;
|
|
147
154
|
let spinach: Food;
|
|
148
155
|
|
|
149
156
|
const mountFoodRouter = (options: Parameters<typeof modelRouter<Food>>[1]): void => {
|
|
@@ -174,8 +181,8 @@ describe("modelRouter actions", () => {
|
|
|
174
181
|
}),
|
|
175
182
|
]);
|
|
176
183
|
app = getBaseServer();
|
|
177
|
-
setupAuth(app, UserModel as
|
|
178
|
-
addAuthRoutes(app, UserModel as
|
|
184
|
+
setupAuth(app, UserModel as unknown as UserMongooseModel);
|
|
185
|
+
addAuthRoutes(app, UserModel as unknown as UserMongooseModel);
|
|
179
186
|
server = supertest(app);
|
|
180
187
|
});
|
|
181
188
|
|
|
@@ -284,8 +291,8 @@ describe("modelRouter actions", () => {
|
|
|
284
291
|
await StuffModel.deleteMany({});
|
|
285
292
|
const doc = await StuffModel.create({deleted: true, name: "hidden", ownerId: "1"});
|
|
286
293
|
app = getBaseServer();
|
|
287
|
-
setupAuth(app, UserModel as
|
|
288
|
-
addAuthRoutes(app, UserModel as
|
|
294
|
+
setupAuth(app, UserModel as unknown as UserMongooseModel);
|
|
295
|
+
addAuthRoutes(app, UserModel as unknown as UserMongooseModel);
|
|
289
296
|
app.use(
|
|
290
297
|
"/stuff",
|
|
291
298
|
modelRouter(StuffModel as Model<Stuff>, {
|
package/src/actions.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {OpenAPIRegistry, OpenApiGeneratorV3} from "@asteasolutions/zod-to-openapi";
|
|
2
2
|
import type express from "express";
|
|
3
3
|
import type {NextFunction, Request, Response} from "express";
|
|
4
|
-
import type {Model} from "mongoose";
|
|
4
|
+
import type {Model, SchemaType} from "mongoose";
|
|
5
5
|
import type {ZodSchema, ZodType} from "zod";
|
|
6
6
|
import {asyncHandler, type ModelRouterOptions, type RESTMethod} from "./api";
|
|
7
7
|
import {authenticateMiddleware, type User} from "./auth";
|
|
@@ -282,7 +282,7 @@ export const createActionOpenApiMiddleware = <T>({
|
|
|
282
282
|
};
|
|
283
283
|
|
|
284
284
|
const getArrayFieldNames = <T>(model: Model<T>): string[] => {
|
|
285
|
-
return Object.values(model.schema.paths)
|
|
285
|
+
return (Object.values(model.schema.paths) as SchemaType[])
|
|
286
286
|
.filter((config) => config.instance === "Array")
|
|
287
287
|
.map((config) => config.path);
|
|
288
288
|
};
|
package/src/api.coverage.test.ts
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
4
2
|
import type express from "express";
|
|
5
|
-
import mongoose from "mongoose";
|
|
3
|
+
import mongoose, {type HydratedDocument} from "mongoose";
|
|
6
4
|
import supertest from "supertest";
|
|
7
5
|
import type TestAgent from "supertest/lib/agent";
|
|
8
6
|
|
|
9
7
|
import {modelRouter} from "./api";
|
|
10
|
-
import {addAuthRoutes, setupAuth} from "./auth";
|
|
8
|
+
import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
|
|
11
9
|
import {Permissions} from "./permissions";
|
|
12
|
-
import {type Food, FoodModel, getBaseServer, setupDb, UserModel} from "./tests";
|
|
10
|
+
import {type Food, FoodModel, getBaseServer, setupDb, type User, UserModel} from "./tests";
|
|
13
11
|
|
|
14
12
|
// A model without the isDeleted plugin so deletes call doc.deleteOne(). The
|
|
15
13
|
// document delete hook throws to exercise the hard-delete error branch.
|
|
@@ -24,7 +22,7 @@ const ExplosiveModel = mongoose.model<{name: string}>("ExplosiveCoverage", explo
|
|
|
24
22
|
describe("modelRouter error path coverage", () => {
|
|
25
23
|
let server: TestAgent;
|
|
26
24
|
let app: express.Application;
|
|
27
|
-
let admin:
|
|
25
|
+
let admin: HydratedDocument<User>;
|
|
28
26
|
let apple: Food;
|
|
29
27
|
|
|
30
28
|
beforeEach(async () => {
|
|
@@ -44,8 +42,8 @@ describe("modelRouter error path coverage", () => {
|
|
|
44
42
|
});
|
|
45
43
|
|
|
46
44
|
app = getBaseServer();
|
|
47
|
-
setupAuth(app, UserModel as
|
|
48
|
-
addAuthRoutes(app, UserModel as
|
|
45
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
46
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
49
47
|
});
|
|
50
48
|
|
|
51
49
|
it("returns 400 when an array operation transformer throws a non-APIError", async () => {
|
|
@@ -104,7 +102,7 @@ describe("modelRouter error path coverage", () => {
|
|
|
104
102
|
const doc = await ExplosiveModel.create({name: "boom"});
|
|
105
103
|
app.use(
|
|
106
104
|
"/explosive",
|
|
107
|
-
modelRouter(ExplosiveModel
|
|
105
|
+
modelRouter(ExplosiveModel, {
|
|
108
106
|
allowAnonymous: true,
|
|
109
107
|
permissions: {
|
|
110
108
|
create: [Permissions.IsAny],
|
|
@@ -2,11 +2,12 @@ import {afterEach, beforeEach, describe, it, spyOn} from "bun:test";
|
|
|
2
2
|
import * as Sentry from "@sentry/bun";
|
|
3
3
|
import {assert} from "chai";
|
|
4
4
|
import type express from "express";
|
|
5
|
+
import {DateTime} from "luxon";
|
|
5
6
|
import mongoose from "mongoose";
|
|
6
7
|
import supertest from "supertest";
|
|
7
8
|
import type TestAgent from "supertest/lib/agent";
|
|
8
9
|
|
|
9
|
-
import {type ModelRouterOptions, modelRouter} from "./api";
|
|
10
|
+
import {type JSONValue, type ModelRouterOptions, modelRouter} from "./api";
|
|
10
11
|
import {addAuthRoutes, setupAuth} from "./auth";
|
|
11
12
|
import {ConflictError} from "./errors";
|
|
12
13
|
import {Permissions} from "./permissions";
|
|
@@ -192,6 +193,51 @@ describe("modelRouter error paths", () => {
|
|
|
192
193
|
saveSpy.mockRestore();
|
|
193
194
|
}
|
|
194
195
|
});
|
|
196
|
+
|
|
197
|
+
it("wraps failures while assembling the list response", async () => {
|
|
198
|
+
mountFood({
|
|
199
|
+
responseHandler: async (data) => {
|
|
200
|
+
const serialized = [...(data as Food[])] as Food[] & {slice: () => never};
|
|
201
|
+
serialized.slice = () => {
|
|
202
|
+
throw new Error("slice exploded");
|
|
203
|
+
};
|
|
204
|
+
return serialized as unknown as JSONValue;
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
const ownerId = new mongoose.Types.ObjectId();
|
|
208
|
+
await FoodModel.create([
|
|
209
|
+
{calories: 1, name: "First", ownerId},
|
|
210
|
+
{calories: 2, name: "Second", ownerId},
|
|
211
|
+
] as Partial<Food>[]);
|
|
212
|
+
|
|
213
|
+
// limit=1 fetches an extra doc, so the handler slices off the overflow.
|
|
214
|
+
const res = await server.get("/food?limit=1");
|
|
215
|
+
assert.equal(res.body.title, "Serialization error");
|
|
216
|
+
assert.include(res.body.detail, "slice exploded");
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("rejects a patch when the stored timestamp cannot be parsed", async () => {
|
|
220
|
+
// `updated` is a string here so the router has to parse it as an ISO date.
|
|
221
|
+
const timestampSchema = new mongoose.Schema({
|
|
222
|
+
name: {description: "The name", type: String},
|
|
223
|
+
updated: {description: "Last update, as an ISO string", type: String},
|
|
224
|
+
});
|
|
225
|
+
const TimestampModel = mongoose.model(`StringTimestamp_${Date.now()}`, timestampSchema);
|
|
226
|
+
app.use(
|
|
227
|
+
"/timestamped",
|
|
228
|
+
modelRouter(TimestampModel, {allowAnonymous: true, permissions: anyPermissions})
|
|
229
|
+
);
|
|
230
|
+
server = supertest(app);
|
|
231
|
+
|
|
232
|
+
const doc = await TimestampModel.create({name: "Timeless", updated: "not-a-date"});
|
|
233
|
+
|
|
234
|
+
const res = await server
|
|
235
|
+
.patch(`/timestamped/${doc._id}`)
|
|
236
|
+
.set("If-Unmodified-Since", DateTime.now().toHTTP() as string)
|
|
237
|
+
.send({name: "Renamed"})
|
|
238
|
+
.expect(400);
|
|
239
|
+
assert.equal(res.body.title, "Invalid server timestamp");
|
|
240
|
+
});
|
|
195
241
|
});
|
|
196
242
|
|
|
197
243
|
interface Guarded {
|