@terreno/api 0.23.0 → 0.24.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/dist/api.test.js +6 -2
- package/dist/auth.test.js +183 -0
- package/dist/consentApp.d.ts +1 -1
- package/dist/docLoader.test.js +0 -1
- package/dist/envConfigurationPlugin.test.js +4 -6
- package/dist/expressServer.d.ts +25 -1
- package/dist/expressServer.js +1 -3
- package/dist/githubAuth.d.ts +1 -1
- package/dist/notifiers/googleChatNotifier.test.js +0 -1
- package/dist/notifiers/zoomNotifier.test.js +3 -2
- package/dist/populate.test.js +30 -0
- package/dist/scriptRunner.test.js +235 -0
- package/dist/transformers.test.js +0 -1
- package/package.json +11 -11
- package/src/api.test.ts +5 -1
- package/src/auth.test.ts +135 -0
- package/src/consentApp.ts +1 -1
- package/src/docLoader.test.ts +4 -4
- package/src/envConfigurationPlugin.test.ts +4 -6
- package/src/expressServer.ts +30 -6
- package/src/githubAuth.ts +2 -4
- package/src/notifiers/googleChatNotifier.test.ts +5 -4
- package/src/notifiers/zoomNotifier.test.ts +7 -4
- package/src/populate.test.ts +32 -0
- package/src/scriptRunner.test.ts +111 -2
- package/src/transformers.test.ts +15 -8
|
@@ -50,7 +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
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
54
53
|
var bun_test_1 = require("bun:test");
|
|
55
54
|
var supertest_1 = __importDefault(require("supertest"));
|
|
56
55
|
var api_1 = require("./api");
|
package/package.json
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
},
|
|
6
6
|
"dependencies": {
|
|
7
7
|
"@asteasolutions/zod-to-openapi": "^8.5.0",
|
|
8
|
-
"@sentry/bun": "^10.
|
|
8
|
+
"@sentry/bun": "^10.39.0",
|
|
9
9
|
"@sentry/profiling-node": "^10.25.0",
|
|
10
|
-
"@terreno/test": "0.
|
|
10
|
+
"@terreno/test": "0.24.0",
|
|
11
11
|
"@types/qs": "^6.14.0",
|
|
12
12
|
"ajv": "8.18.0",
|
|
13
13
|
"ajv-formats": "^3.0.1",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"passport-jwt": "^4.0.0",
|
|
39
39
|
"passport-local": "^1.0.0",
|
|
40
40
|
"passport-local-mongoose": "^9.0.1",
|
|
41
|
-
"qs": "^6.
|
|
41
|
+
"qs": "^6.15.0",
|
|
42
42
|
"@thream/socketio-jwt": "^3.1.4",
|
|
43
43
|
"scmp": "^2.1.0",
|
|
44
44
|
"socket.io": "^4.8.1",
|
|
@@ -48,12 +48,12 @@
|
|
|
48
48
|
"devDependencies": {
|
|
49
49
|
"@biomejs/biome": "^2.3.6",
|
|
50
50
|
"@types/bcrypt": "^6.0.0",
|
|
51
|
-
"@types/bun": "^1.
|
|
51
|
+
"@types/bun": "^1.3.8",
|
|
52
52
|
"@types/cors": "^2.8.17",
|
|
53
53
|
"@types/cron": "^2.4.3",
|
|
54
54
|
"@types/express": "^5.0.6",
|
|
55
55
|
"@types/jsonwebtoken": "^9.0.9",
|
|
56
|
-
"@types/lodash": "^4.17.
|
|
56
|
+
"@types/lodash": "^4.17.17",
|
|
57
57
|
"@types/mongodb": "^4.0.7",
|
|
58
58
|
"@types/node": "^25.3.0",
|
|
59
59
|
"@types/on-finished": "^2.3.4",
|
|
@@ -63,14 +63,14 @@
|
|
|
63
63
|
"@types/passport-jwt": "^4.0.1",
|
|
64
64
|
"@types/passport-local": "^1.0.38",
|
|
65
65
|
"@types/sinon": "^21.0.0",
|
|
66
|
-
"@types/supertest": "^
|
|
66
|
+
"@types/supertest": "^7.2.0",
|
|
67
67
|
"mongodb-memory-server": "^11.0.1",
|
|
68
68
|
"mongoose": "8.23.0",
|
|
69
69
|
"sinon": "^21.0.1",
|
|
70
|
-
"supertest": "^7.
|
|
71
|
-
"typedoc": "
|
|
72
|
-
"typescript": "5.9.
|
|
73
|
-
"zod": "^4.3
|
|
70
|
+
"supertest": "^7.2.2",
|
|
71
|
+
"typedoc": "^0.28.17",
|
|
72
|
+
"typescript": "~5.9.2",
|
|
73
|
+
"zod": "^4.4.3"
|
|
74
74
|
},
|
|
75
75
|
"homepage": "https://github.com/FlourishHealth/terreno#readme",
|
|
76
76
|
"keywords": [
|
|
@@ -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.24.0"
|
|
127
127
|
}
|
package/src/api.test.ts
CHANGED
|
@@ -2078,10 +2078,14 @@ describe("@terreno/api", () => {
|
|
|
2078
2078
|
{_id: spinach._id as unknown as mongoose.Types.ObjectId},
|
|
2079
2079
|
{$set: {updated: "2025-06-15T12:00:00.000Z"}}
|
|
2080
2080
|
);
|
|
2081
|
+
const ifUnmodifiedSince = DateTime.fromISO("2025-06-15T11:00:00.000Z").toHTTP();
|
|
2082
|
+
if (!ifUnmodifiedSince) {
|
|
2083
|
+
throw new Error("Expected valid HTTP date");
|
|
2084
|
+
}
|
|
2081
2085
|
|
|
2082
2086
|
const res = await agent
|
|
2083
2087
|
.patch(`/food/${spinach._id}`)
|
|
2084
|
-
.set("If-Unmodified-Since",
|
|
2088
|
+
.set("If-Unmodified-Since", ifUnmodifiedSince)
|
|
2085
2089
|
.send({name: "String Timestamp"})
|
|
2086
2090
|
.expect(409);
|
|
2087
2091
|
|
package/src/auth.test.ts
CHANGED
|
@@ -1175,3 +1175,138 @@ describe("login error and disabled user paths", () => {
|
|
|
1175
1175
|
expect(res.body.title).toContain("disabled");
|
|
1176
1176
|
});
|
|
1177
1177
|
});
|
|
1178
|
+
|
|
1179
|
+
describe("PATCH /me route edge cases", () => {
|
|
1180
|
+
let app: express.Application;
|
|
1181
|
+
let agent: TestAgent;
|
|
1182
|
+
|
|
1183
|
+
beforeEach(async () => {
|
|
1184
|
+
setSystemTime();
|
|
1185
|
+
await setupTestData();
|
|
1186
|
+
app = new TerrenoApp({
|
|
1187
|
+
configureApp: () => {},
|
|
1188
|
+
skipListen: true,
|
|
1189
|
+
userModel: UserModel as any,
|
|
1190
|
+
}).build();
|
|
1191
|
+
agent = supertest.agent(app);
|
|
1192
|
+
});
|
|
1193
|
+
|
|
1194
|
+
afterEach(() => {
|
|
1195
|
+
setSystemTime();
|
|
1196
|
+
});
|
|
1197
|
+
|
|
1198
|
+
it("returns 404 for PATCH /me when authenticated user is deleted from DB", async () => {
|
|
1199
|
+
const loginRes = await agent
|
|
1200
|
+
.post("/auth/login")
|
|
1201
|
+
.send({email: "notAdmin@example.com", password: "password"})
|
|
1202
|
+
.expect(200);
|
|
1203
|
+
const {token, userId} = loginRes.body.data;
|
|
1204
|
+
|
|
1205
|
+
await UserModel.deleteOne({_id: userId});
|
|
1206
|
+
|
|
1207
|
+
const freshAgent = supertest.agent(app);
|
|
1208
|
+
const res = await freshAgent
|
|
1209
|
+
.patch("/auth/me")
|
|
1210
|
+
.set("authorization", `Bearer ${token}`)
|
|
1211
|
+
.send({name: "Updated"});
|
|
1212
|
+
// Without user in DB, should get 401 or 404
|
|
1213
|
+
expect([401, 404]).toContain(res.status);
|
|
1214
|
+
});
|
|
1215
|
+
});
|
|
1216
|
+
|
|
1217
|
+
describe("generateTokens with SIGNUP_DISABLED and user.postCreate", () => {
|
|
1218
|
+
const OLD_ENV = process.env;
|
|
1219
|
+
|
|
1220
|
+
beforeEach(() => {
|
|
1221
|
+
process.env = {...OLD_ENV};
|
|
1222
|
+
process.env.TOKEN_SECRET = "secret";
|
|
1223
|
+
process.env.REFRESH_TOKEN_SECRET = "refresh_secret";
|
|
1224
|
+
});
|
|
1225
|
+
|
|
1226
|
+
afterEach(() => {
|
|
1227
|
+
process.env = OLD_ENV;
|
|
1228
|
+
});
|
|
1229
|
+
|
|
1230
|
+
it("generates token with sessionId in both token and refresh token", async () => {
|
|
1231
|
+
const jwtLib = await import("jsonwebtoken");
|
|
1232
|
+
const result = await generateTokens({_id: "user-123"});
|
|
1233
|
+
expect(result.sessionId).toBeDefined();
|
|
1234
|
+
const tokenDecoded = jwtLib.decode(result.token as string) as {sid?: string};
|
|
1235
|
+
const refreshDecoded = jwtLib.decode(result.refreshToken as string) as {sid?: string};
|
|
1236
|
+
expect(tokenDecoded.sid).toBe(result.sessionId);
|
|
1237
|
+
expect(refreshDecoded.sid).toBe(result.sessionId);
|
|
1238
|
+
});
|
|
1239
|
+
});
|
|
1240
|
+
|
|
1241
|
+
describe("JWT cookie extraction", () => {
|
|
1242
|
+
let app: express.Application;
|
|
1243
|
+
let agent: TestAgent;
|
|
1244
|
+
|
|
1245
|
+
beforeEach(async () => {
|
|
1246
|
+
setSystemTime();
|
|
1247
|
+
await setupTestData();
|
|
1248
|
+
app = new TerrenoApp({
|
|
1249
|
+
configureApp: (router: express.Router) => {
|
|
1250
|
+
router.use(
|
|
1251
|
+
"/food",
|
|
1252
|
+
modelRouter(FoodModel, {
|
|
1253
|
+
allowAnonymous: true,
|
|
1254
|
+
permissions: {
|
|
1255
|
+
create: [],
|
|
1256
|
+
delete: [],
|
|
1257
|
+
list: [Permissions.IsAny],
|
|
1258
|
+
read: [Permissions.IsAny],
|
|
1259
|
+
update: [],
|
|
1260
|
+
},
|
|
1261
|
+
})
|
|
1262
|
+
);
|
|
1263
|
+
},
|
|
1264
|
+
skipListen: true,
|
|
1265
|
+
userModel: UserModel as any,
|
|
1266
|
+
}).build();
|
|
1267
|
+
agent = supertest.agent(app);
|
|
1268
|
+
});
|
|
1269
|
+
|
|
1270
|
+
afterEach(() => {
|
|
1271
|
+
setSystemTime();
|
|
1272
|
+
});
|
|
1273
|
+
|
|
1274
|
+
it("skips decode when token is the string null", async () => {
|
|
1275
|
+
const res = await agent.get("/food").set("authorization", "Bearer null").expect(200);
|
|
1276
|
+
expect(res.body.data).toBeDefined();
|
|
1277
|
+
});
|
|
1278
|
+
|
|
1279
|
+
it("skips decode when token is the string undefined", async () => {
|
|
1280
|
+
const res = await agent.get("/food").set("authorization", "Bearer undefined").expect(200);
|
|
1281
|
+
expect(res.body.data).toBeDefined();
|
|
1282
|
+
});
|
|
1283
|
+
});
|
|
1284
|
+
|
|
1285
|
+
describe("signup disabled", () => {
|
|
1286
|
+
let app: express.Application;
|
|
1287
|
+
let agent: TestAgent;
|
|
1288
|
+
const OLD_ENV = process.env;
|
|
1289
|
+
|
|
1290
|
+
beforeEach(async () => {
|
|
1291
|
+
setSystemTime();
|
|
1292
|
+
process.env = {...OLD_ENV};
|
|
1293
|
+
process.env.SIGNUP_DISABLED = "true";
|
|
1294
|
+
await setupTestData();
|
|
1295
|
+
app = new TerrenoApp({
|
|
1296
|
+
configureApp: () => {},
|
|
1297
|
+
skipListen: true,
|
|
1298
|
+
userModel: UserModel as any,
|
|
1299
|
+
}).build();
|
|
1300
|
+
agent = supertest.agent(app);
|
|
1301
|
+
});
|
|
1302
|
+
|
|
1303
|
+
afterEach(() => {
|
|
1304
|
+
setSystemTime();
|
|
1305
|
+
process.env = OLD_ENV;
|
|
1306
|
+
});
|
|
1307
|
+
|
|
1308
|
+
it("returns 404 when SIGNUP_DISABLED is true", async () => {
|
|
1309
|
+
const res = await agent.post("/auth/signup").send({email: "new@example.com", password: "123"});
|
|
1310
|
+
expect(res.status).toBe(404);
|
|
1311
|
+
});
|
|
1312
|
+
});
|
package/src/consentApp.ts
CHANGED
|
@@ -17,8 +17,8 @@ import {logger} from "./logger";
|
|
|
17
17
|
import {ConsentForm} from "./models/consentForm";
|
|
18
18
|
import {ConsentResponse} from "./models/consentResponse";
|
|
19
19
|
import {Permissions} from "./permissions";
|
|
20
|
-
import type {TerrenoPlugin} from "./terrenoPlugin";
|
|
21
20
|
import type {PopulatePath} from "./populate";
|
|
21
|
+
import type {TerrenoPlugin} from "./terrenoPlugin";
|
|
22
22
|
import type {ConsentFormDocument} from "./types/consentForm";
|
|
23
23
|
|
|
24
24
|
/** Shared populate config for consent response list/read endpoints. */
|
package/src/docLoader.test.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
1
|
import {describe, expect, it, mock} from "bun:test";
|
|
2
|
+
import type {Model} from "mongoose";
|
|
3
3
|
import {loadDocOr404} from "./docLoader";
|
|
4
4
|
import {APIError} from "./errors";
|
|
5
5
|
|
|
@@ -9,7 +9,7 @@ describe("loadDocOr404", () => {
|
|
|
9
9
|
collection: {findOne: mock(async () => ({deleted: true}))},
|
|
10
10
|
findById: mock(() => ({exec: mock(async () => null)})),
|
|
11
11
|
modelName: "MockModel",
|
|
12
|
-
} as
|
|
12
|
+
} as unknown as Model<unknown>;
|
|
13
13
|
|
|
14
14
|
try {
|
|
15
15
|
await loadDocOr404(model, "507f1f77bcf86cd799439011");
|
|
@@ -33,7 +33,7 @@ describe("loadDocOr404", () => {
|
|
|
33
33
|
}),
|
|
34
34
|
})),
|
|
35
35
|
modelName: "MockModel",
|
|
36
|
-
} as
|
|
36
|
+
} as unknown as Model<unknown>;
|
|
37
37
|
|
|
38
38
|
await expect(loadDocOr404(model, "507f1f77bcf86cd799439011")).rejects.toBe(original);
|
|
39
39
|
});
|
|
@@ -43,7 +43,7 @@ describe("loadDocOr404", () => {
|
|
|
43
43
|
collection: {findOne: mock(async () => null)},
|
|
44
44
|
findById: mock(() => ({exec: mock(async () => null)})),
|
|
45
45
|
modelName: "MockModel",
|
|
46
|
-
} as
|
|
46
|
+
} as unknown as Model<unknown>;
|
|
47
47
|
|
|
48
48
|
try {
|
|
49
49
|
await loadDocOr404(model, "507f1f77bcf86cd799439011");
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import {afterEach, beforeEach, describe, expect, it} from "bun:test";
|
|
1
|
+
import {afterEach, beforeEach, describe, expect, it, spyOn} from "bun:test";
|
|
3
2
|
import mongoose, {Schema} from "mongoose";
|
|
4
3
|
|
|
5
4
|
import {Config} from "./config";
|
|
@@ -163,16 +162,15 @@ describe("envConfigurationPlugin", () => {
|
|
|
163
162
|
|
|
164
163
|
// Override Model.find to simulate a DB error inside refreshFromDoc
|
|
165
164
|
// (findOneOrNoneFor falls back to model.find when the findOneOrNone static is absent)
|
|
166
|
-
const
|
|
167
|
-
(TestEnvConfig as any).find = () => {
|
|
165
|
+
const findSpy = spyOn(TestEnvConfig, "find").mockImplementation(() => {
|
|
168
166
|
throw new Error("Simulated DB error");
|
|
169
|
-
};
|
|
167
|
+
});
|
|
170
168
|
|
|
171
169
|
// Trigger the post-findOneAndUpdate hook → refreshFromDoc → findOneOrNoneFor → throws
|
|
172
170
|
await TestEnvConfig.findOneAndUpdate({_id: doc._id}, {$set: {__v: 2}});
|
|
173
171
|
|
|
174
172
|
// Restore immediately
|
|
175
|
-
(
|
|
173
|
+
findSpy.mockRestore();
|
|
176
174
|
|
|
177
175
|
// The catch block should have swallowed the error; cache keeps old value
|
|
178
176
|
expect(Config.get("TERRENO_PLUGIN_KEY")).toBe("cached");
|
package/src/expressServer.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type {OutgoingMessage} from "node:http";
|
|
1
2
|
import * as Sentry from "@sentry/bun";
|
|
2
3
|
import cron from "cron";
|
|
3
4
|
import express, {type Router} from "express";
|
|
@@ -36,8 +37,27 @@ export const setupEnvironment = (): void => {
|
|
|
36
37
|
|
|
37
38
|
export type AddRoutes = (router: Router, options?: Partial<ModelRouterOptions<unknown>>) => void;
|
|
38
39
|
|
|
39
|
-
|
|
40
|
-
|
|
40
|
+
interface LoggableRequest {
|
|
41
|
+
body?: Record<string, unknown>;
|
|
42
|
+
method: string;
|
|
43
|
+
originalUrl?: string;
|
|
44
|
+
route?: {path: string};
|
|
45
|
+
routeMount?: string | string[];
|
|
46
|
+
url?: string;
|
|
47
|
+
user?: {
|
|
48
|
+
admin?: boolean;
|
|
49
|
+
id?: string;
|
|
50
|
+
testUser?: boolean;
|
|
51
|
+
type?: string;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface LoggableResponse {
|
|
56
|
+
locals?: {loggingOptions?: LoggingOptions};
|
|
57
|
+
statusCode?: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const logRequestsFinished = (req: LoggableRequest, res: LoggableResponse, startTime: bigint) => {
|
|
41
61
|
const options = (res.locals?.loggingOptions ?? {}) as LoggingOptions;
|
|
42
62
|
|
|
43
63
|
const slowReadMs = options.logSlowRequestsReadMs ?? SLOW_READ_MAX;
|
|
@@ -50,7 +70,7 @@ const logRequestsFinished = (req: any, res: any, startTime: bigint) => {
|
|
|
50
70
|
pathName = `${req.routeMount}${req.route.path}`;
|
|
51
71
|
} else if (req.route) {
|
|
52
72
|
pathName = req.route.path;
|
|
53
|
-
} else if (res.statusCode < 400) {
|
|
73
|
+
} else if (res.statusCode != null && res.statusCode < 400) {
|
|
54
74
|
logger.warn(`Request without route: ${req.originalUrl}`);
|
|
55
75
|
}
|
|
56
76
|
if (process.env.DISABLE_LOG_ALL_REQUESTS !== "true") {
|
|
@@ -77,8 +97,11 @@ const logRequestsFinished = (req: any, res: any, startTime: bigint) => {
|
|
|
77
97
|
}
|
|
78
98
|
};
|
|
79
99
|
|
|
80
|
-
|
|
81
|
-
|
|
100
|
+
export const logRequests = (
|
|
101
|
+
req: LoggableRequest,
|
|
102
|
+
res: LoggableResponse,
|
|
103
|
+
next: express.NextFunction
|
|
104
|
+
): void => {
|
|
82
105
|
const startTime = process.hrtime.bigint();
|
|
83
106
|
|
|
84
107
|
let userString = "";
|
|
@@ -106,7 +129,7 @@ export const logRequests = (req: any, res: any, next: express.NextFunction): voi
|
|
|
106
129
|
if (process.env.DISABLE_LOG_ALL_REQUESTS !== "true") {
|
|
107
130
|
logger.debug(`${req.method} <- ${req.url}${userString}${body}`);
|
|
108
131
|
}
|
|
109
|
-
onFinished(res, () => logRequestsFinished(req, res, startTime));
|
|
132
|
+
onFinished(res as unknown as OutgoingMessage, () => logRequestsFinished(req, res, startTime));
|
|
110
133
|
next();
|
|
111
134
|
};
|
|
112
135
|
|
|
@@ -145,6 +168,7 @@ export const createRouterWithAuth = (
|
|
|
145
168
|
};
|
|
146
169
|
|
|
147
170
|
export interface AuthOptions {
|
|
171
|
+
// noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
|
|
148
172
|
// biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
|
|
149
173
|
generateJWTPayload?: (user: any) => Record<string, unknown>;
|
|
150
174
|
// biome-ignore lint/suspicious/noExplicitAny: see above
|
package/src/githubAuth.ts
CHANGED
|
@@ -33,10 +33,8 @@ export interface GitHubAuthOptions {
|
|
|
33
33
|
profile: Profile,
|
|
34
34
|
accessToken: string,
|
|
35
35
|
refreshToken: string,
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
// biome-ignore lint/suspicious/noExplicitAny: passport user value remains untyped
|
|
39
|
-
) => Promise<any>;
|
|
36
|
+
existingUser?: Record<string, unknown>
|
|
37
|
+
) => Promise<unknown>;
|
|
40
38
|
}
|
|
41
39
|
|
|
42
40
|
/** Fields added to user documents for GitHub authentication */
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
1
|
import {afterAll, afterEach, beforeEach, describe, expect, it, type Mock, spyOn} from "bun:test";
|
|
3
2
|
import * as Sentry from "@sentry/bun";
|
|
3
|
+
import type {AxiosResponse} from "axios";
|
|
4
4
|
import axios from "axios";
|
|
5
5
|
|
|
6
|
+
import type {APIError} from "../errors";
|
|
6
7
|
import {sendToGoogleChat} from "./googleChatNotifier";
|
|
7
8
|
|
|
8
9
|
describe("sendToGoogleChat", () => {
|
|
@@ -11,7 +12,7 @@ describe("sendToGoogleChat", () => {
|
|
|
11
12
|
const ORIGINAL_ENV = process.env;
|
|
12
13
|
|
|
13
14
|
beforeEach(() => {
|
|
14
|
-
mockAxiosPost = spyOn(axios, "post").mockResolvedValue({status: 200} as
|
|
15
|
+
mockAxiosPost = spyOn(axios, "post").mockResolvedValue({status: 200} as AxiosResponse);
|
|
15
16
|
process.env = {...ORIGINAL_ENV};
|
|
16
17
|
process.env.GOOGLE_CHAT_WEBHOOKS = undefined;
|
|
17
18
|
(Sentry.captureException as Mock<typeof Sentry.captureException>).mockClear();
|
|
@@ -97,8 +98,8 @@ describe("sendToGoogleChat", () => {
|
|
|
97
98
|
await sendToGoogleChat("err", {shouldThrow: true});
|
|
98
99
|
throw new Error("Expected sendToGoogleChat to throw APIError");
|
|
99
100
|
} catch (error) {
|
|
100
|
-
expect((error as
|
|
101
|
-
expect((error as
|
|
101
|
+
expect((error as APIError).name).toBe("APIError");
|
|
102
|
+
expect((error as APIError).title).toMatch(/Error posting to Google Chat/i);
|
|
102
103
|
}
|
|
103
104
|
expect(mockAxiosPost.mock.calls.length).toBe(1);
|
|
104
105
|
});
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
1
|
import {afterAll, afterEach, beforeEach, describe, expect, it, type Mock, spyOn} from "bun:test";
|
|
3
2
|
import * as Sentry from "@sentry/bun";
|
|
3
|
+
import type {AxiosResponse} from "axios";
|
|
4
4
|
import axios from "axios";
|
|
5
5
|
|
|
6
|
+
import type {APIError} from "../errors";
|
|
6
7
|
import {sendToZoom} from "./zoomNotifier";
|
|
7
8
|
|
|
8
9
|
describe("sendToZoom", () => {
|
|
@@ -11,7 +12,9 @@ describe("sendToZoom", () => {
|
|
|
11
12
|
const ORIGINAL_ENV = process.env;
|
|
12
13
|
|
|
13
14
|
beforeEach(() => {
|
|
14
|
-
mockAxiosPost = spyOn(axios, "post").mockResolvedValue({
|
|
15
|
+
mockAxiosPost = spyOn(axios, "post").mockResolvedValue({
|
|
16
|
+
status: 200,
|
|
17
|
+
} as unknown as AxiosResponse);
|
|
15
18
|
process.env = {...ORIGINAL_ENV};
|
|
16
19
|
process.env.ZOOM_CHAT_WEBHOOKS = undefined;
|
|
17
20
|
(Sentry.captureException as Mock<typeof Sentry.captureException>).mockClear();
|
|
@@ -187,8 +190,8 @@ describe("sendToZoom", () => {
|
|
|
187
190
|
await sendToZoom({body: "err", header: "err"}, {channel: "default", shouldThrow: true});
|
|
188
191
|
throw new Error("Expected sendToZoom to throw APIError");
|
|
189
192
|
} catch (error) {
|
|
190
|
-
expect((error as
|
|
191
|
-
expect((error as
|
|
193
|
+
expect((error as APIError).name).toBe("APIError");
|
|
194
|
+
expect((error as APIError).title).toMatch(/Error posting to Zoom/i);
|
|
192
195
|
}
|
|
193
196
|
expect(mockAxiosPost.mock.calls.length).toBe(1);
|
|
194
197
|
});
|
package/src/populate.test.ts
CHANGED
|
@@ -275,6 +275,38 @@ describe("getOpenApiSpecForModel populate with existing properties", () => {
|
|
|
275
275
|
});
|
|
276
276
|
});
|
|
277
277
|
|
|
278
|
+
describe("getOpenApiSpecForModel populate property merge", () => {
|
|
279
|
+
it("merges properties when the same path is populated twice", () => {
|
|
280
|
+
// First populate sets the field properties, second triggers the merge branch.
|
|
281
|
+
const result = getOpenApiSpecForModel(FoodModel, {
|
|
282
|
+
populatePaths: [{fields: ["name"], path: "likesIds.userId"}, {path: "likesIds.userId"}],
|
|
283
|
+
});
|
|
284
|
+
const likesIds = result.properties.likesIds as Record<string, unknown>;
|
|
285
|
+
const items = likesIds.items as Record<string, Record<string, unknown>>;
|
|
286
|
+
const userIdProps = items.properties.userId as Record<string, Record<string, unknown>>;
|
|
287
|
+
// After the merge the wider populate should have contributed all user fields.
|
|
288
|
+
expect(userIdProps.properties).toBeDefined();
|
|
289
|
+
expect(userIdProps.properties.name).toBeDefined();
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it("merges openApiComponent ref into an already-populated path", () => {
|
|
293
|
+
const result = getOpenApiSpecForModel(FoodModel, {
|
|
294
|
+
populatePaths: [
|
|
295
|
+
{path: "likesIds.userId"},
|
|
296
|
+
{openApiComponent: "UserComponent", path: "likesIds.userId"},
|
|
297
|
+
],
|
|
298
|
+
});
|
|
299
|
+
const likesIds = result.properties.likesIds as Record<string, unknown>;
|
|
300
|
+
const items = likesIds.items as Record<string, Record<string, unknown>>;
|
|
301
|
+
const userIdProps = items.properties.userId as Record<string, Record<string, unknown>>;
|
|
302
|
+
// Merge path adds the $ref key inside the existing properties.
|
|
303
|
+
expect(userIdProps.properties).toBeDefined();
|
|
304
|
+
expect(userIdProps.properties.userId).toEqual({
|
|
305
|
+
$ref: "#/components/schemas/UserComponent",
|
|
306
|
+
});
|
|
307
|
+
});
|
|
308
|
+
});
|
|
309
|
+
|
|
278
310
|
describe("filterKeys (via getOpenApiSpecForModel populatePaths)", () => {
|
|
279
311
|
it("filters populated fields using dot-notation keys", () => {
|
|
280
312
|
const result = getOpenApiSpecForModel(FoodModel, {
|
package/src/scriptRunner.test.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
|
-
import {describe, expect, it} from "bun:test";
|
|
1
|
+
import {afterAll, beforeAll, describe, expect, it} from "bun:test";
|
|
2
|
+
import mongoose from "mongoose";
|
|
2
3
|
|
|
3
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
BackgroundTask,
|
|
6
|
+
createScriptArgs,
|
|
7
|
+
parseScriptArgs,
|
|
8
|
+
type ScriptArgDef,
|
|
9
|
+
TaskCancelledError,
|
|
10
|
+
} from "./scriptRunner";
|
|
4
11
|
|
|
5
12
|
describe("parseScriptArgs", () => {
|
|
6
13
|
it("parses --name=value form", () => {
|
|
@@ -173,3 +180,105 @@ describe("createScriptArgs", () => {
|
|
|
173
180
|
});
|
|
174
181
|
});
|
|
175
182
|
});
|
|
183
|
+
|
|
184
|
+
describe("TaskCancelledError", () => {
|
|
185
|
+
it("sets the message and name", () => {
|
|
186
|
+
const err = new TaskCancelledError("task-123");
|
|
187
|
+
expect(err.message).toBe("Task task-123 was cancelled");
|
|
188
|
+
expect(err.name).toBe("TaskCancelledError");
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it("is an instance of Error", () => {
|
|
192
|
+
const err = new TaskCancelledError("abc");
|
|
193
|
+
expect(err).toBeInstanceOf(Error);
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
describe("BackgroundTask model", () => {
|
|
198
|
+
beforeAll(async () => {
|
|
199
|
+
if (mongoose.connection.readyState !== 1) {
|
|
200
|
+
await mongoose.connect(process.env.MONGO_URL ?? "mongodb://127.0.0.1/terreno-test");
|
|
201
|
+
}
|
|
202
|
+
await BackgroundTask.deleteMany({});
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
afterAll(async () => {
|
|
206
|
+
await BackgroundTask.deleteMany({});
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
it("creates a task with required fields", async () => {
|
|
210
|
+
const task = await BackgroundTask.create({taskType: "test-task"});
|
|
211
|
+
expect(task.taskType).toBe("test-task");
|
|
212
|
+
expect(task.status).toBe("pending");
|
|
213
|
+
expect(task.isDryRun).toBe(false);
|
|
214
|
+
expect(task.logs).toEqual([]);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
describe("addLog", () => {
|
|
218
|
+
it("appends a log entry and saves", async () => {
|
|
219
|
+
const task = await BackgroundTask.create({taskType: "log-test"});
|
|
220
|
+
await task.addLog("info", "step completed");
|
|
221
|
+
|
|
222
|
+
const reloaded = await BackgroundTask.findById(task._id);
|
|
223
|
+
expect(reloaded?.logs).toHaveLength(1);
|
|
224
|
+
expect(reloaded?.logs[0].level).toBe("info");
|
|
225
|
+
expect(reloaded?.logs[0].message).toBe("step completed");
|
|
226
|
+
expect(reloaded?.logs[0].timestamp).toBeDefined();
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it("appends multiple log entries", async () => {
|
|
230
|
+
const task = await BackgroundTask.create({taskType: "multi-log"});
|
|
231
|
+
await task.addLog("info", "first");
|
|
232
|
+
await task.addLog("warn", "second");
|
|
233
|
+
await task.addLog("error", "third");
|
|
234
|
+
|
|
235
|
+
const reloaded = await BackgroundTask.findById(task._id);
|
|
236
|
+
expect(reloaded?.logs).toHaveLength(3);
|
|
237
|
+
expect(reloaded?.logs[0].level).toBe("info");
|
|
238
|
+
expect(reloaded?.logs[1].level).toBe("warn");
|
|
239
|
+
expect(reloaded?.logs[2].level).toBe("error");
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
describe("updateProgress", () => {
|
|
244
|
+
it("sets progress percentage and stage", async () => {
|
|
245
|
+
const task = await BackgroundTask.create({taskType: "progress-test"});
|
|
246
|
+
await task.updateProgress(50, "processing", "halfway done");
|
|
247
|
+
|
|
248
|
+
const reloaded = await BackgroundTask.findById(task._id);
|
|
249
|
+
expect(reloaded?.progress?.percentage).toBe(50);
|
|
250
|
+
expect(reloaded?.progress?.stage).toBe("processing");
|
|
251
|
+
expect(reloaded?.progress?.message).toBe("halfway done");
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("preserves previous stage and message when not provided", async () => {
|
|
255
|
+
const task = await BackgroundTask.create({taskType: "progress-retain"});
|
|
256
|
+
await task.updateProgress(25, "init", "starting");
|
|
257
|
+
await task.updateProgress(75);
|
|
258
|
+
|
|
259
|
+
const reloaded = await BackgroundTask.findById(task._id);
|
|
260
|
+
expect(reloaded?.progress?.percentage).toBe(75);
|
|
261
|
+
expect(reloaded?.progress?.stage).toBe("init");
|
|
262
|
+
expect(reloaded?.progress?.message).toBe("starting");
|
|
263
|
+
});
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
describe("checkCancellation", () => {
|
|
267
|
+
it("does nothing when task is not cancelled", async () => {
|
|
268
|
+
const task = await BackgroundTask.create({status: "running", taskType: "check-cancel"});
|
|
269
|
+
await expect(BackgroundTask.checkCancellation(task._id.toString())).resolves.toBeUndefined();
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
it("throws TaskCancelledError when task is cancelled", async () => {
|
|
273
|
+
const task = await BackgroundTask.create({status: "cancelled", taskType: "check-cancel"});
|
|
274
|
+
await expect(BackgroundTask.checkCancellation(task._id.toString())).rejects.toThrow(
|
|
275
|
+
TaskCancelledError
|
|
276
|
+
);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it("does nothing when task does not exist", async () => {
|
|
280
|
+
const fakeId = new mongoose.Types.ObjectId().toString();
|
|
281
|
+
await expect(BackgroundTask.checkCancellation(fakeId)).resolves.toBeUndefined();
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
});
|
package/src/transformers.test.ts
CHANGED
|
@@ -1,21 +1,28 @@
|
|
|
1
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
1
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
3
2
|
import type express from "express";
|
|
4
|
-
import type {Document, ObjectId} from "mongoose";
|
|
3
|
+
import type {Document, HydratedDocument, ObjectId} from "mongoose";
|
|
5
4
|
import supertest from "supertest";
|
|
6
5
|
import type TestAgent from "supertest/lib/agent";
|
|
7
6
|
|
|
8
7
|
import type {ModelRouterOptions} from "./api";
|
|
9
8
|
import {modelRouter} from "./api";
|
|
10
|
-
import {addAuthRoutes, setupAuth} from "./auth";
|
|
9
|
+
import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
|
|
11
10
|
import {APIError} from "./errors";
|
|
12
11
|
import {Permissions} from "./permissions";
|
|
13
|
-
import {
|
|
12
|
+
import {
|
|
13
|
+
authAsUser,
|
|
14
|
+
type Food,
|
|
15
|
+
FoodModel,
|
|
16
|
+
getBaseServer,
|
|
17
|
+
setupTestData,
|
|
18
|
+
type User,
|
|
19
|
+
UserModel,
|
|
20
|
+
} from "./tests";
|
|
14
21
|
import {AdminOwnerTransformer, defaultResponseHandler, transform} from "./transformers";
|
|
15
22
|
|
|
16
23
|
describe("query and transform", () => {
|
|
17
|
-
let notAdmin:
|
|
18
|
-
let admin:
|
|
24
|
+
let notAdmin: HydratedDocument<User>;
|
|
25
|
+
let admin: HydratedDocument<User>;
|
|
19
26
|
let server: TestAgent;
|
|
20
27
|
let app: express.Application;
|
|
21
28
|
|
|
@@ -26,8 +33,8 @@ describe("query and transform", () => {
|
|
|
26
33
|
admin = testData.users.admin;
|
|
27
34
|
notAdmin = testData.users.notAdmin;
|
|
28
35
|
app = getBaseServer();
|
|
29
|
-
setupAuth(app, UserModel as
|
|
30
|
-
addAuthRoutes(app, UserModel as
|
|
36
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
37
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
31
38
|
app.use(
|
|
32
39
|
"/food",
|
|
33
40
|
modelRouter(FoodModel, {
|