@terreno/api 56.0.0-beta.0 → 56.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +2 -122
  2. package/LICENSE +21 -202
  3. package/dist/api.d.ts +3 -2
  4. package/dist/auth.js +21 -25
  5. package/dist/betterAuthSetup.d.ts +15 -1
  6. package/dist/betterAuthSetup.js +4 -6
  7. package/dist/configurationPlugin.js +2 -2
  8. package/dist/expressServer.js +11 -5
  9. package/dist/githubAuth.js +1 -4
  10. package/dist/plugins.d.ts +7 -6
  11. package/dist/plugins.js +24 -8
  12. package/dist/realtime/realtimeApp.d.ts +1 -1
  13. package/dist/realtime/realtimeApp.js +16 -8
  14. package/dist/realtime/types.d.ts +14 -0
  15. package/dist/sync/executors.js +14 -14
  16. package/dist/sync/models.js +1 -1
  17. package/dist/sync/registry.js +1 -1
  18. package/dist/sync/syncSeqPlugin.js +25 -29
  19. package/dist/tests/models.d.ts +27 -11
  20. package/dist/tests/models.js +5 -3
  21. package/dist/tests/testHelper.d.ts +9 -3
  22. package/package.json +5 -6
  23. package/src/actions.test.ts +19 -12
  24. package/src/actions.ts +2 -2
  25. package/src/api.coverage.test.ts +7 -9
  26. package/src/api.errorPaths.test.ts +47 -1
  27. package/src/api.errors.test.ts +32 -23
  28. package/src/api.ts +22 -12
  29. package/src/auth.test.ts +251 -1
  30. package/src/auth.ts +25 -23
  31. package/src/betterAuthSetup.ts +7 -7
  32. package/src/configuration.test.ts +59 -38
  33. package/src/configurationPlugin.test.ts +72 -42
  34. package/src/configurationPlugin.ts +2 -2
  35. package/src/consentApp.test.ts +12 -12
  36. package/src/expressServer.ts +11 -5
  37. package/src/githubAuth.ts +1 -3
  38. package/src/middleware.test.ts +16 -0
  39. package/src/models/versionConfig.ts +1 -1
  40. package/src/openApiBuilder.test.ts +24 -9
  41. package/src/openApiValidator.test.ts +41 -0
  42. package/src/permissions.test.ts +35 -25
  43. package/src/plugins.test.ts +24 -0
  44. package/src/plugins.ts +29 -11
  45. package/src/populate.test.ts +25 -16
  46. package/src/realtime/realtime.test.ts +239 -0
  47. package/src/realtime/realtimeApp.ts +15 -8
  48. package/src/realtime/realtimeAppSetup.test.ts +159 -0
  49. package/src/realtime/types.ts +14 -0
  50. package/src/secretProvidersGcpClient.test.ts +66 -0
  51. package/src/sync/executors.ts +16 -14
  52. package/src/sync/models.ts +2 -1
  53. package/src/sync/registry.ts +1 -1
  54. package/src/sync/syncFrontier.test.ts +2 -2
  55. package/src/sync/syncSeqPlugin.ts +43 -51
  56. package/src/tests/models.ts +8 -6
@@ -1,5 +1,6 @@
1
1
  import {beforeEach, describe, expect, it, type Mock, mock} from "bun:test";
2
2
  import * as Sentry from "@sentry/bun";
3
+ import {assert} from "chai";
3
4
  import express, {type NextFunction, type Request, type Response} from "express";
4
5
  import supertest from "supertest";
5
6
 
@@ -170,6 +171,21 @@ describe("jsonResponseRequestIdMiddleware", () => {
170
171
  expect(res.body.requestId).toBeUndefined();
171
172
  });
172
173
 
174
+ it("leaves bodies untouched when no request context or requestId exists", async () => {
175
+ // Without requestContextMiddleware there is no requestId to correlate on, so
176
+ // the middleware must pass payloads through unchanged.
177
+ const app = express();
178
+ app.use(jsonResponseRequestIdMiddleware);
179
+ app.get("/object", (_req, res) => {
180
+ return res.json({hello: "world"});
181
+ });
182
+
183
+ const res = await supertest(app).get("/object").expect(200);
184
+
185
+ assert.deepEqual(res.body, {hello: "world"});
186
+ assert.isUndefined(res.headers["x-request-id"]);
187
+ });
188
+
173
189
  it("uses incoming X-Request-ID on wrapped object responses", async () => {
174
190
  const app = buildStackedApp();
175
191
  const res = await supertest(app)
@@ -79,7 +79,7 @@ const versionConfigSchema = new mongoose.Schema<VersionConfigDocument, VersionCo
79
79
  // Enforce singleton: only one VersionConfig document can exist.
80
80
  // The _singleton field is always "config" (required, immutable, enum-constrained)
81
81
  // and a unique index guarantees at most one document.
82
- (versionConfigSchema as mongoose.Schema).add({
82
+ (versionConfigSchema as unknown as mongoose.Schema).add({
83
83
  _singleton: {
84
84
  default: "config",
85
85
  description: "Sentinel field to enforce singleton via unique index",
@@ -1,5 +1,3 @@
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 type {Router} from "express";
@@ -7,12 +5,25 @@ import supertest from "supertest";
7
5
  import type TestAgent from "supertest/lib/agent";
8
6
 
9
7
  import {type ModelRouterOptions, modelRouter} from "./api";
8
+ import type {UserModel as AuthUserModel} from "./auth";
10
9
  import {createOpenApiBuilder, OpenApiMiddlewareBuilder} from "./openApiBuilder";
11
10
  import {Permissions} from "./permissions";
12
11
  import {TerrenoApp} from "./terrenoApp";
13
- import {FoodModel, UserModel} from "./tests";
12
+ import {type Food, FoodModel, UserModel} from "./tests";
13
+
14
+ /** The subset of an OpenAPI parameter object the assertions below inspect. */
15
+ interface OpenApiParameter {
16
+ name: string;
17
+ in: string;
18
+ required?: boolean;
19
+ description?: string;
20
+ schema: {type: string};
21
+ }
14
22
 
15
- function addRoutesWithBuilder(router: Router, options?: Partial<ModelRouterOptions<any>>): void {
23
+ function addRoutesWithBuilder(
24
+ router: Router,
25
+ options?: Partial<ModelRouterOptions<unknown>>
26
+ ): void {
16
27
  // Add a custom endpoint using the OpenApiMiddlewareBuilder
17
28
  const statsMiddleware = createOpenApiBuilder(options ?? {})
18
29
  .withTags(["Stats"])
@@ -124,8 +135,8 @@ function addRoutesWithBuilder(router: Router, options?: Partial<ModelRouterOptio
124
135
  // Standard modelRouter for food
125
136
  router.use(
126
137
  "/food",
127
- modelRouter(FoodModel as any, {
128
- ...options,
138
+ modelRouter(FoodModel, {
139
+ ...(options as Partial<ModelRouterOptions<Food>>),
129
140
  allowAnonymous: true,
130
141
  permissions: {
131
142
  create: [Permissions.IsAny],
@@ -149,7 +160,7 @@ describe("OpenApiMiddlewareBuilder", () => {
149
160
  app = new TerrenoApp({
150
161
  configureApp: addRoutesWithBuilder,
151
162
  skipListen: true,
152
- userModel: UserModel as any,
163
+ userModel: UserModel as unknown as AuthUserModel,
153
164
  }).build();
154
165
  });
155
166
 
@@ -189,7 +200,9 @@ describe("OpenApiMiddlewareBuilder", () => {
189
200
  expect(statsPath.get.description).toBe("Returns aggregated statistics about food items");
190
201
 
191
202
  // Check query parameter
192
- const categoryParam = statsPath.get.parameters.find((p: any) => p.name === "category");
203
+ const categoryParam = statsPath.get.parameters.find(
204
+ (p: OpenApiParameter) => p.name === "category"
205
+ );
193
206
  expect(categoryParam).toBeDefined();
194
207
  expect(categoryParam.in).toBe("query");
195
208
  expect(categoryParam.schema.type).toBe("string");
@@ -269,7 +282,9 @@ describe("OpenApiMiddlewareBuilder", () => {
269
282
  const categoryPath = res.body.paths["/food/categories/{categoryId}"];
270
283
  expect(categoryPath).toBeDefined();
271
284
 
272
- const pathParam = categoryPath.get.parameters.find((p: any) => p.name === "categoryId");
285
+ const pathParam = categoryPath.get.parameters.find(
286
+ (p: OpenApiParameter) => p.name === "categoryId"
287
+ );
273
288
  expect(pathParam).toBeDefined();
274
289
  expect(pathParam.in).toBe("path");
275
290
  expect(pathParam.required).toBe(true);
@@ -563,6 +563,47 @@ describe("openApiValidator", () => {
563
563
  expect(req.query.page).toBe(5);
564
564
  });
565
565
 
566
+ it("runs only body validation when no query schema is provided", () => {
567
+ configureOpenApiValidator({coerceTypes: true});
568
+
569
+ const middleware = createValidator({
570
+ body: {count: {type: "number"}, name: {required: true, type: "string"}},
571
+ });
572
+
573
+ const req = {
574
+ body: {count: "3", name: "ok"},
575
+ method: "POST",
576
+ path: "/test",
577
+ query: {unchecked: "kept"},
578
+ } as unknown as Request;
579
+ const res = {} as Response;
580
+
581
+ const nextCalls: unknown[][] = [];
582
+ middleware(req, res, ((...args: unknown[]) => {
583
+ nextCalls.push(args);
584
+ }) as NextFunction);
585
+
586
+ expect(nextCalls).toEqual([[]]);
587
+ expect(req.body.count).toBe(3);
588
+ // Query params are untouched when no query schema is configured.
589
+ expect(req.query.unchecked).toBe("kept");
590
+ });
591
+
592
+ it("throws body validation errors when only a body schema is provided", () => {
593
+ configureOpenApiValidator({});
594
+
595
+ const middleware = createValidator({
596
+ body: {name: {required: true, type: "string"}},
597
+ });
598
+
599
+ const req = {body: {}, method: "POST", path: "/test", query: {}} as unknown as Request;
600
+ const res = {} as Response;
601
+
602
+ expect(() => middleware(req, res, (() => {}) as NextFunction)).toThrow(
603
+ "Request validation failed"
604
+ );
605
+ });
606
+
566
607
  it("propagates body validation error via next", () => {
567
608
  let capturedErrors: ErrorObject[] = [];
568
609
  configureOpenApiValidator({
@@ -1,12 +1,15 @@
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
4
  import type TestAgent from "supertest/lib/agent";
7
5
 
8
6
  import {modelRouter} from "./api";
9
- import {addAuthRoutes, setupAuth} from "./auth";
7
+ import {
8
+ type User as AuthUser,
9
+ type UserModel as AuthUserModel,
10
+ addAuthRoutes,
11
+ setupAuth,
12
+ } from "./auth";
10
13
  import {
11
14
  getUserOrganizationIds,
12
15
  OrganizationQueryFilter,
@@ -32,8 +35,8 @@ describe("permissions", () => {
32
35
 
33
36
  await setupTestData();
34
37
  app = getBaseServer();
35
- setupAuth(app, UserModel as any);
36
- addAuthRoutes(app, UserModel as any);
38
+ setupAuth(app, UserModel as unknown as AuthUserModel);
39
+ addAuthRoutes(app, UserModel as unknown as AuthUserModel);
37
40
  app.use(
38
41
  "/food",
39
42
  modelRouter(FoodModel, {
@@ -210,10 +213,19 @@ describe("permissions", () => {
210
213
  });
211
214
  });
212
215
 
216
+ const testUser = (
217
+ overrides: Partial<AuthUser & {organizationIds?: string[]; isAnonymous?: boolean}> = {}
218
+ ): AuthUser & {organizationIds?: string[]; isAnonymous?: boolean} => ({
219
+ _id: "user-123",
220
+ admin: false,
221
+ id: "user-123",
222
+ ...overrides,
223
+ });
224
+
213
225
  describe("permissions module", () => {
214
226
  describe("OwnerQueryFilter", () => {
215
227
  it("returns ownerId filter when user is provided", () => {
216
- const user = {id: "user-123"} as any;
228
+ const user = testUser();
217
229
  const filter = OwnerQueryFilter(user);
218
230
  expect(filter).toEqual({ownerId: "user-123"});
219
231
  });
@@ -226,26 +238,26 @@ describe("permissions module", () => {
226
238
 
227
239
  describe("getUserOrganizationIds", () => {
228
240
  it("returns the user's organizationIds", () => {
229
- const user = {id: "u1", organizationIds: ["org-1", "org-2"]} as any;
241
+ const user = testUser({id: "u1", organizationIds: ["org-1", "org-2"]});
230
242
  expect(getUserOrganizationIds(user)).toEqual(["org-1", "org-2"]);
231
243
  });
232
244
 
233
245
  it("returns an empty array when missing or undefined", () => {
234
- expect(getUserOrganizationIds({id: "u1"} as any)).toEqual([]);
246
+ expect(getUserOrganizationIds(testUser({id: "u1"}))).toEqual([]);
235
247
  expect(getUserOrganizationIds(undefined)).toEqual([]);
236
248
  });
237
249
  });
238
250
 
239
251
  describe("OrganizationQueryFilter", () => {
240
252
  it("returns an $in filter over the user's organizationIds", () => {
241
- const user = {id: "u1", organizationIds: ["org-1", "org-2"]} as any;
253
+ const user = testUser({id: "u1", organizationIds: ["org-1", "org-2"]});
242
254
  expect(OrganizationQueryFilter(user)).toEqual({
243
255
  organizationId: {$in: ["org-1", "org-2"]},
244
256
  });
245
257
  });
246
258
 
247
259
  it("returns an empty $in filter when the user has no organizations", () => {
248
- const user = {id: "u1"} as any;
260
+ const user = testUser({id: "u1"});
249
261
  expect(OrganizationQueryFilter(user)).toEqual({organizationId: {$in: []}});
250
262
  });
251
263
 
@@ -256,7 +268,7 @@ describe("permissions module", () => {
256
268
 
257
269
  describe("Permissions.IsOrganizationMember", () => {
258
270
  it("returns true when no object is provided", () => {
259
- const user = {id: "u1", organizationIds: ["org-1"]} as any;
271
+ const user = testUser({id: "u1", organizationIds: ["org-1"]});
260
272
  expect(Permissions.IsOrganizationMember("list", user, undefined)).toBe(true);
261
273
  });
262
274
 
@@ -267,46 +279,46 @@ describe("permissions module", () => {
267
279
  });
268
280
 
269
281
  it("returns true for admins regardless of membership", () => {
270
- const user = {admin: true, id: "admin-1", organizationIds: []} as any;
282
+ const user = testUser({admin: true, id: "admin-1", organizationIds: []});
271
283
  expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-9"})).toBe(
272
284
  true
273
285
  );
274
286
  });
275
287
 
276
288
  it("returns true when the user belongs to the document's organization", () => {
277
- const user = {id: "u1", organizationIds: ["org-1", "org-2"]} as any;
289
+ const user = testUser({id: "u1", organizationIds: ["org-1", "org-2"]});
278
290
  expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-2"})).toBe(
279
291
  true
280
292
  );
281
293
  });
282
294
 
283
295
  it("returns false when the user does not belong to the document's organization", () => {
284
- const user = {id: "u1", organizationIds: ["org-1"]} as any;
296
+ const user = testUser({id: "u1", organizationIds: ["org-1"]});
285
297
  expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-9"})).toBe(
286
298
  false
287
299
  );
288
300
  });
289
301
 
290
302
  it("returns false when the document has no organizationId", () => {
291
- const user = {id: "u1", organizationIds: ["org-1"]} as any;
303
+ const user = testUser({id: "u1", organizationIds: ["org-1"]});
292
304
  expect(Permissions.IsOrganizationMember("read", user, {})).toBe(false);
293
305
  });
294
306
  });
295
307
 
296
308
  describe("Permissions.IsAuthenticatedOrReadOnly", () => {
297
309
  it("returns true for authenticated non-anonymous users", () => {
298
- const user = {id: "user-123", isAnonymous: false} as any;
310
+ const user = testUser({isAnonymous: false});
299
311
  expect(Permissions.IsAuthenticatedOrReadOnly("create", user)).toBe(true);
300
312
  });
301
313
 
302
314
  it("returns true for read methods when user is anonymous", () => {
303
- const user = {id: "user-123", isAnonymous: true} as any;
315
+ const user = testUser({isAnonymous: true});
304
316
  expect(Permissions.IsAuthenticatedOrReadOnly("list", user)).toBe(true);
305
317
  expect(Permissions.IsAuthenticatedOrReadOnly("read", user)).toBe(true);
306
318
  });
307
319
 
308
320
  it("returns false for write methods when user is anonymous", () => {
309
- const user = {id: "user-123", isAnonymous: true} as any;
321
+ const user = testUser({isAnonymous: true});
310
322
  expect(Permissions.IsAuthenticatedOrReadOnly("create", user)).toBe(false);
311
323
  expect(Permissions.IsAuthenticatedOrReadOnly("update", user)).toBe(false);
312
324
  expect(Permissions.IsAuthenticatedOrReadOnly("delete", user)).toBe(false);
@@ -315,32 +327,30 @@ describe("permissions module", () => {
315
327
 
316
328
  describe("Permissions.IsOwnerOrReadOnly", () => {
317
329
  it("returns true when no object is provided", () => {
318
- expect(Permissions.IsOwnerOrReadOnly("update", {id: "user-123"} as any, undefined)).toBe(
319
- true
320
- );
330
+ expect(Permissions.IsOwnerOrReadOnly("update", testUser(), undefined)).toBe(true);
321
331
  });
322
332
 
323
333
  it("returns true for admin users", () => {
324
- const user = {admin: true, id: "admin-123"} as any;
334
+ const user = testUser({admin: true, id: "admin-123"});
325
335
  const obj = {ownerId: "other-user"};
326
336
  expect(Permissions.IsOwnerOrReadOnly("update", user, obj)).toBe(true);
327
337
  });
328
338
 
329
339
  it("returns true when user is owner", () => {
330
- const user = {id: "user-123"} as any;
340
+ const user = testUser();
331
341
  const obj = {ownerId: "user-123"};
332
342
  expect(Permissions.IsOwnerOrReadOnly("update", user, obj)).toBe(true);
333
343
  });
334
344
 
335
345
  it("returns true for read methods when not owner", () => {
336
- const user = {id: "user-123"} as any;
346
+ const user = testUser();
337
347
  const obj = {ownerId: "other-user"};
338
348
  expect(Permissions.IsOwnerOrReadOnly("list", user, obj)).toBe(true);
339
349
  expect(Permissions.IsOwnerOrReadOnly("read", user, obj)).toBe(true);
340
350
  });
341
351
 
342
352
  it("returns false for write methods when not owner", () => {
343
- const user = {id: "user-123"} as any;
353
+ const user = testUser();
344
354
  const obj = {ownerId: "other-user"};
345
355
  expect(Permissions.IsOwnerOrReadOnly("update", user, obj)).toBe(false);
346
356
  expect(Permissions.IsOwnerOrReadOnly("delete", user, obj)).toBe(false);
@@ -1,6 +1,7 @@
1
1
  // noExplicitAny: test mock typing
2
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
3
  import {beforeEach, describe, expect, it, setSystemTime} from "bun:test";
4
+ import {assert} from "chai";
4
5
  import type express from "express";
5
6
  import {type Document, type Model, model, Schema} from "mongoose";
6
7
  import supertest from "supertest";
@@ -460,6 +461,16 @@ describe("excludeArchivedPlugin", () => {
460
461
  expect(results[0].name).toBe("Active");
461
462
  });
462
463
 
464
+ it("excludes archived documents from findOne() by default", async () => {
465
+ await ArchivableModel.create({archived: false, name: "Active"});
466
+ await ArchivableModel.create({archived: true, name: "Archived"});
467
+
468
+ const active = await ArchivableModel.findOne({name: "Active"});
469
+ expect(active?.name).toBe("Active");
470
+ const archived = await ArchivableModel.findOne({name: "Archived"});
471
+ expect(archived).toBeNull();
472
+ });
473
+
463
474
  it("includes archived documents when explicitly requested", async () => {
464
475
  await ArchivableModel.create({archived: false, name: "Active"});
465
476
  await ArchivableModel.create({archived: true, name: "Archived"});
@@ -523,6 +534,19 @@ describe("TypeScript return types", () => {
523
534
  });
524
535
  });
525
536
  describe("DateOnly", () => {
537
+ it("strips the time portion when getting a Date value", () => {
538
+ const dateOnly = new DateOnly("date", {});
539
+ const value = dateOnly.get(new Date("2005-10-10T17:17:17.017Z")) as unknown as Date;
540
+ assert.instanceOf(value, Date);
541
+ assert.equal(value.toISOString(), "2005-10-10T00:00:00.000Z");
542
+ });
543
+
544
+ it("returns non-Date values unchanged when getting a value", () => {
545
+ const dateOnly = new DateOnly("date", {});
546
+ assert.isNull(dateOnly.get(null));
547
+ assert.equal(dateOnly.get("2005-10-10") as unknown as string, "2005-10-10");
548
+ });
549
+
526
550
  it("throws error with invalid date", async () => {
527
551
  try {
528
552
  await StuffModel.create({
package/src/plugins.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import {DateTime} from "luxon";
2
2
  import mongoose, {
3
3
  type Document,
4
- type FilterQuery,
5
4
  Error as MongooseError,
6
5
  type Query,
7
6
  type Schema,
@@ -11,6 +10,8 @@ import mongoose, {
11
10
 
12
11
  import {APIError, type APIErrorOptions, InternalServerError, NotFoundError} from "./errors";
13
12
 
13
+ export type ModelQuery<T> = Partial<Record<keyof T, unknown>> & Record<string, unknown>;
14
+
14
15
  export interface BaseUser {
15
16
  admin: boolean;
16
17
  email: string;
@@ -172,14 +173,14 @@ export const findOneOrNone = <T>(schema: Schema<T>): void => {
172
173
  */
173
174
  export const findOneOrNoneFor = async <T>(
174
175
  model: mongoose.Model<T>,
175
- query: FilterQuery<T>,
176
+ query: ModelQuery<T>,
176
177
  errorArgs?: Partial<APIErrorOptions>
177
178
  ): Promise<(Document & T) | null> => {
178
179
  const withStatic = model as mongoose.Model<T> & Partial<FindOneOrNonePlugin<T>>;
179
180
  if (typeof withStatic.findOneOrNone === "function") {
180
181
  return withStatic.findOneOrNone(query, errorArgs);
181
182
  }
182
- const results = await model.find(query);
183
+ const results = await model.find(query as never);
183
184
  if (results.length === 0) {
184
185
  return null;
185
186
  }
@@ -291,10 +292,10 @@ export interface IsArchived {
291
292
  }
292
293
 
293
294
  /**
294
- * Adds an `archived` boolean field and excludes archived documents from `find()` queries by
295
- * default. Pass `{archived: true}` explicitly to include them. This is a soft-archive analog to
296
- * {@link isDeletedPlugin}: use it when documents should be hidden from normal listings but kept
297
- * (and still directly queryable) rather than treated as deleted.
295
+ * Adds an `archived` boolean field and excludes archived documents from `find()` / `findOne()`
296
+ * queries by default. Pass `{archived: true}` explicitly to include them. This is a soft-archive
297
+ * analog to {@link isDeletedPlugin}: use it when documents should be hidden from normal listings
298
+ * but kept (and still directly queryable) rather than treated as deleted.
298
299
  * @param schema Mongoose Schema
299
300
  * @param defaultValue Default value for the `archived` field (defaults to `false`)
300
301
  */
@@ -315,15 +316,28 @@ export const excludeArchivedPlugin = (
315
316
  },
316
317
  });
317
318
 
319
+ // Mirror isDeletedPlugin: filter both find and findOne so findExactlyOne / findOneOrNone
320
+ // also exclude archived documents unless the query sets `archived` explicitly.
318
321
  // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
319
322
  // biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
320
- schema.pre<Query<any, any>>("find", function () {
321
- const conditions = this.getFilter();
323
+ const applyArchiveFilter = (query: Query<any, any>): void => {
324
+ const conditions = query.getFilter();
322
325
  // Only apply the default filter when the query does not mention `archived` at all, so an
323
326
  // explicit `{archived: true}` (or `false`) is always respected.
324
327
  if (conditions.archived === undefined) {
325
- this.setQuery({...conditions, archived: {$ne: true}});
328
+ query.setQuery({...conditions, archived: {$ne: true}});
326
329
  }
330
+ };
331
+
332
+ // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
333
+ // biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
334
+ schema.pre<Query<any, any>>("find", function () {
335
+ applyArchiveFilter(this);
336
+ });
337
+ // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
338
+ // biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
339
+ schema.pre<Query<any, any>>("findOne", function () {
340
+ applyArchiveFilter(this);
327
341
  });
328
342
  };
329
343
 
@@ -372,7 +386,11 @@ export class DateOnly extends SchemaType {
372
386
  const handler = this.$conditionalHandlers[$conditional];
373
387
 
374
388
  if (!handler) {
375
- throw new Error(`Can't use ${$conditional} with DateOnly.`);
389
+ throw new APIError({
390
+ detail: `Can't use ${$conditional} with DateOnly.`,
391
+ status: 400,
392
+ title: "Unsupported query conditional for DateOnly",
393
+ });
376
394
  }
377
395
 
378
396
  return handler.call(this, val);
@@ -1,17 +1,24 @@
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 mongoose, {type Document, type HydratedDocument, Schema} from "mongoose";
5
3
 
6
4
  import {fixMixedFields, getOpenApiSpecForModel, unpopulate} from "./populate";
7
- import {FoodModel, setupTestData, type User, UserModel} from "./tests";
5
+ import {type Food, FoodModel, setupTestData, type User, UserModel} from "./tests";
6
+
7
+ /**
8
+ * A Food document whose ObjectId references have been replaced by populated user
9
+ * documents. `unpopulate` swaps them back to ObjectIds in place, so both shapes
10
+ * are optional on the reference fields.
11
+ */
12
+ type PopulatedFood = Omit<HydratedDocument<Food>, "eatenBy" | "likesIds" | "ownerId"> & {
13
+ ownerId: Partial<User> & {toString(): string};
14
+ eatenBy: (Partial<User> & {id?: string})[] & {toString(): string};
15
+ likesIds: {likes: boolean; userId: Partial<User> & {id?: string; toString(): string}}[];
16
+ };
8
17
 
9
18
  describe("populate functions", () => {
10
19
  let admin: HydratedDocument<User>;
11
20
  let notAdmin: HydratedDocument<User>;
12
-
13
- // noExplicitAny: typing as HydratedDocument<Food> causes cascading errors on populated field access patterns (e.g. populated.ownerId.name)
14
- let spinach: any;
21
+ let spinach: HydratedDocument<Food>;
15
22
 
16
23
  beforeEach(async () => {
17
24
  const testData = await setupTestData();
@@ -21,9 +28,10 @@ describe("populate functions", () => {
21
28
  });
22
29
 
23
30
  it("unpopulate", async () => {
24
- let populated = await spinach.populate("ownerId");
25
- populated = await populated.populate("eatenBy");
26
- populated = await populated.populate("likesIds.userId");
31
+ await spinach.populate("ownerId");
32
+ await spinach.populate("eatenBy");
33
+ await spinach.populate("likesIds.userId");
34
+ const populated = spinach as unknown as PopulatedFood;
27
35
  expect(populated.ownerId.name).toBe("Not Admin");
28
36
  expect(populated.eatenBy[0].id).toBe(admin.id);
29
37
  expect(populated.eatenBy[0].name).toBe("Admin");
@@ -32,9 +40,11 @@ describe("populate functions", () => {
32
40
  expect(populated.likesIds[1].userId.id).toBe(notAdmin.id);
33
41
  expect(populated.likesIds[1].userId.name).toBe("Not Admin");
34
42
 
35
- // noExplicitAny: unpopulate returns Document<T> which doesn't expose model properties; would require refactoring the return type
36
- let unpopulated: any = unpopulate(populated, "ownerId");
37
- expect(spinach.ownerId.name).toBeUndefined();
43
+ const unpopulated = unpopulate(
44
+ populated as unknown as Document<unknown>,
45
+ "ownerId"
46
+ ) as unknown as PopulatedFood;
47
+ expect(populated.ownerId.name).toBeUndefined();
38
48
  expect(unpopulated.ownerId.toString()).toBe(notAdmin.id);
39
49
  // Ensure nothing else was touched.
40
50
  expect(populated.likesIds[0].userId.id).toBe(admin.id);
@@ -42,11 +52,11 @@ describe("populate functions", () => {
42
52
  expect(populated.likesIds[1].userId.id).toBe(notAdmin.id);
43
53
  expect(populated.likesIds[1].userId.name).toBe("Not Admin");
44
54
 
45
- unpopulated = unpopulate(populated, "eatenBy");
55
+ unpopulate(populated as unknown as Document<unknown>, "eatenBy");
46
56
  expect(populated.eatenBy.toString()).toBe(admin.id);
47
57
  expect(populated.eatenBy[0]?.name).toBeUndefined();
48
58
 
49
- unpopulated = unpopulate(populated, "likesIds.userId");
59
+ unpopulate(populated as unknown as Document<unknown>, "likesIds.userId");
50
60
  expect(populated.likesIds[0].userId.toString()).toBe(admin.id);
51
61
  expect(populated.likesIds[0].userId?.name).toBeUndefined();
52
62
  expect(populated.likesIds[1].userId.toString()).toBe(notAdmin.id);
@@ -326,8 +336,7 @@ describe("filterKeys (via getOpenApiSpecForModel populatePaths)", () => {
326
336
  populatePaths: [{fields: ["__proto__.polluted"], path: "ownerId"}],
327
337
  });
328
338
  expect(result.properties).toBeDefined();
329
- // noExplicitAny: testing that prototype pollution did not add a 'polluted' property to Object.prototype
330
- expect((Object.prototype as any).polluted).toBeUndefined();
339
+ expect((Object.prototype as Record<string, unknown>).polluted).toBeUndefined();
331
340
  const ownerProps = (result.properties.ownerId as Record<string, unknown>).properties as Record<
332
341
  string,
333
342
  unknown