@terreno/api 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/dist/__tests__/openApiCompat.test.js +8 -2
  2. package/dist/actions.openApi.test.js +1 -0
  3. package/dist/actions.test.js +3 -1
  4. package/dist/api.arrayOperations.test.js +1 -0
  5. package/dist/api.coverage.test.d.ts +1 -0
  6. package/dist/api.coverage.test.js +193 -0
  7. package/dist/api.errorPaths.test.d.ts +1 -0
  8. package/dist/api.errorPaths.test.js +280 -0
  9. package/dist/api.errors.test.js +7 -7
  10. package/dist/api.hooks.test.js +66 -8
  11. package/dist/api.js +245 -206
  12. package/dist/api.query.test.js +1 -0
  13. package/dist/api.test.js +11 -4
  14. package/dist/auth.js +1 -0
  15. package/dist/auth.test.js +123 -1
  16. package/dist/betterAuthSetup.js +1 -0
  17. package/dist/betterAuthSetup.test.js +1 -0
  18. package/dist/config.js +7 -4
  19. package/dist/config.test.js +28 -3
  20. package/dist/configuration.test.js +1 -0
  21. package/dist/configurationApp.js +1 -0
  22. package/dist/configurationPlugin.test.js +80 -0
  23. package/dist/consentApp.test.js +1 -0
  24. package/dist/docLoader.js +16 -54
  25. package/dist/docLoader.test.js +2 -1
  26. package/dist/envConfigurationPlugin.js +1 -0
  27. package/dist/errors.d.ts +72 -5
  28. package/dist/errors.js +265 -67
  29. package/dist/errors.test.js +163 -13
  30. package/dist/example.js +3 -2
  31. package/dist/expressServer.test.js +1 -0
  32. package/dist/githubAuth.js +2 -0
  33. package/dist/githubAuth.test.js +1 -0
  34. package/dist/httpClient.d.ts +2 -3
  35. package/dist/httpClient.js +4 -4
  36. package/dist/httpClient.test.js +3 -2
  37. package/dist/logger.test.js +107 -0
  38. package/dist/notifiers/googleChatNotifier.test.js +2 -1
  39. package/dist/notifiers/slackNotifier.test.js +1 -1
  40. package/dist/notifiers/zoomNotifier.test.js +2 -1
  41. package/dist/openApi.test.js +1 -0
  42. package/dist/openApiBuilder.js +2 -1
  43. package/dist/openApiBuilder.test.js +3 -2
  44. package/dist/openApiValidator.js +1 -0
  45. package/dist/openApiValidator.test.js +41 -0
  46. package/dist/permissions.js +0 -2
  47. package/dist/permissions.middleware.test.js +8 -42
  48. package/dist/permissions.test.js +1 -0
  49. package/dist/plugins.js +8 -0
  50. package/dist/plugins.test.js +5 -2
  51. package/dist/populate.js +4 -2
  52. package/dist/populate.test.js +1 -0
  53. package/dist/realtime/realtime.test.js +13 -3
  54. package/dist/realtime/types.d.ts +1 -1
  55. package/dist/requestContext.test.js +28 -0
  56. package/dist/terrenoApp.js +1 -0
  57. package/dist/tests/createTestData.js +11 -6
  58. package/dist/tests/models.js +1 -0
  59. package/dist/transformers.js +4 -2
  60. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +3 -1
  61. package/package.json +7 -7
  62. package/src/__tests__/openApiCompat.test.ts +8 -2
  63. package/src/actions.openApi.test.ts +1 -0
  64. package/src/actions.test.ts +3 -1
  65. package/src/api.arrayOperations.test.ts +1 -0
  66. package/src/api.coverage.test.ts +123 -0
  67. package/src/api.errorPaths.test.ts +173 -0
  68. package/src/api.errors.test.ts +7 -7
  69. package/src/api.hooks.test.ts +25 -1
  70. package/src/api.query.test.ts +1 -0
  71. package/src/api.test.ts +11 -4
  72. package/src/api.ts +106 -57
  73. package/src/auth.test.ts +92 -3
  74. package/src/auth.ts +6 -0
  75. package/src/betterAuthSetup.test.ts +1 -0
  76. package/src/betterAuthSetup.ts +3 -0
  77. package/src/config.test.ts +25 -3
  78. package/src/config.ts +7 -4
  79. package/src/configuration.test.ts +1 -0
  80. package/src/configurationApp.ts +2 -0
  81. package/src/configurationPlugin.test.ts +46 -1
  82. package/src/consentApp.test.ts +1 -0
  83. package/src/docLoader.test.ts +2 -1
  84. package/src/docLoader.ts +17 -20
  85. package/src/envConfigurationPlugin.ts +2 -0
  86. package/src/errors.test.ts +178 -13
  87. package/src/errors.ts +278 -79
  88. package/src/example.ts +3 -2
  89. package/src/expressServer.test.ts +1 -0
  90. package/src/expressServer.ts +4 -2
  91. package/src/githubAuth.test.ts +1 -0
  92. package/src/githubAuth.ts +2 -0
  93. package/src/httpClient.test.ts +3 -2
  94. package/src/httpClient.ts +4 -4
  95. package/src/logger.test.ts +78 -0
  96. package/src/notifiers/googleChatNotifier.test.ts +2 -2
  97. package/src/notifiers/slackNotifier.test.ts +2 -2
  98. package/src/notifiers/zoomNotifier.test.ts +2 -2
  99. package/src/openApi.test.ts +1 -0
  100. package/src/openApiBuilder.test.ts +7 -6
  101. package/src/openApiBuilder.ts +2 -1
  102. package/src/openApiValidator.test.ts +64 -0
  103. package/src/openApiValidator.ts +1 -0
  104. package/src/permissions.middleware.test.ts +8 -11
  105. package/src/permissions.test.ts +1 -0
  106. package/src/permissions.ts +0 -2
  107. package/src/plugins.test.ts +5 -2
  108. package/src/plugins.ts +9 -0
  109. package/src/populate.test.ts +1 -0
  110. package/src/populate.ts +4 -2
  111. package/src/realtime/realtime.test.ts +13 -3
  112. package/src/realtime/realtimeApp.ts +1 -0
  113. package/src/realtime/registry.ts +1 -0
  114. package/src/realtime/types.ts +1 -2
  115. package/src/requestContext.test.ts +32 -0
  116. package/src/terrenoApp.ts +1 -0
  117. package/src/tests/createTestData.ts +11 -6
  118. package/src/tests/models.ts +1 -0
  119. package/src/transformers.ts +4 -2
  120. package/src/vendor/wesleytodd-openapi/lib/generate-doc.js +4 -1
  121. package/tsconfig.json +4 -4
  122. /package/{types.d.ts → src/types.d.ts} +0 -0
@@ -3,7 +3,7 @@ import * as Sentry from "@sentry/bun";
3
3
  import type {AxiosResponse} from "axios";
4
4
  import axios from "axios";
5
5
 
6
- import type {APIError} from "../errors";
6
+ import {type APIError, isAPIError} from "../errors";
7
7
  import {sendToGoogleChat} from "./googleChatNotifier";
8
8
 
9
9
  describe("sendToGoogleChat", () => {
@@ -98,7 +98,7 @@ describe("sendToGoogleChat", () => {
98
98
  await sendToGoogleChat("err", {shouldThrow: true});
99
99
  throw new Error("Expected sendToGoogleChat to throw APIError");
100
100
  } catch (error) {
101
- expect((error as APIError).name).toBe("APIError");
101
+ expect(isAPIError(error)).toBe(true);
102
102
  expect((error as APIError).title).toMatch(/Error posting to Google Chat/i);
103
103
  }
104
104
  expect(mockAxiosPost.mock.calls.length).toBe(1);
@@ -2,7 +2,7 @@ import {afterAll, afterEach, beforeEach, describe, expect, it, type Mock, spyOn}
2
2
  import * as Sentry from "@sentry/bun";
3
3
  import axios from "axios";
4
4
 
5
- import {APIError} from "../errors";
5
+ import {APIError, isAPIError} from "../errors";
6
6
  import {sendToSlack} from "./slackNotifier";
7
7
 
8
8
  describe("sendToSlack", () => {
@@ -121,7 +121,7 @@ describe("sendToSlack", () => {
121
121
  throw new Error("Expected sendToSlack to throw APIError");
122
122
  } catch (error) {
123
123
  const apiError = error as APIError;
124
- expect(apiError.name).toBe("APIError");
124
+ expect(isAPIError(apiError)).toBe(true);
125
125
  expect(apiError.title).toMatch(/Error posting to slack/i);
126
126
  }
127
127
  expect(mockAxiosPost.mock.calls.length).toBe(1);
@@ -3,7 +3,7 @@ import * as Sentry from "@sentry/bun";
3
3
  import type {AxiosResponse} from "axios";
4
4
  import axios from "axios";
5
5
 
6
- import type {APIError} from "../errors";
6
+ import {type APIError, isAPIError} from "../errors";
7
7
  import {sendToZoom} from "./zoomNotifier";
8
8
 
9
9
  describe("sendToZoom", () => {
@@ -190,7 +190,7 @@ describe("sendToZoom", () => {
190
190
  await sendToZoom({body: "err", header: "err"}, {channel: "default", shouldThrow: true});
191
191
  throw new Error("Expected sendToZoom to throw APIError");
192
192
  } catch (error) {
193
- expect((error as APIError).name).toBe("APIError");
193
+ expect(isAPIError(error)).toBe(true);
194
194
  expect((error as APIError).title).toMatch(/Error posting to Zoom/i);
195
195
  }
196
196
  expect(mockAxiosPost.mock.calls.length).toBe(1);
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {beforeEach, describe, expect, it} from "bun:test";
3
4
  import type express from "express";
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {beforeEach, describe, expect, it} from "bun:test";
3
4
  import type express from "express";
@@ -362,24 +363,24 @@ describe("OpenApiMiddlewareBuilder without OpenAPI", () => {
362
363
  .withTags(["test"])
363
364
  .withSummary("Test")
364
365
  .withResponse(200, {id: {type: "string"}})
365
- .build();
366
+ .build() as express.RequestHandler;
366
367
 
367
368
  // Middleware should be a function
368
369
  expect(typeof middleware).toBe("function");
369
370
 
370
371
  // Should call next() without error
371
372
  let nextCalled = false;
372
- middleware({}, {}, () => {
373
+ middleware({} as express.Request, {} as express.Response, () => {
373
374
  nextCalled = true;
374
375
  });
375
376
  expect(nextCalled).toBe(true);
376
377
  });
377
378
 
378
379
  it("build returns noop middleware when options is empty", () => {
379
- const middleware = createOpenApiBuilder({}).build();
380
+ const middleware = createOpenApiBuilder({}).build() as express.RequestHandler;
380
381
 
381
382
  let nextCalled = false;
382
- middleware({}, {}, () => {
383
+ middleware({} as express.Request, {} as express.Response, () => {
383
384
  nextCalled = true;
384
385
  });
385
386
  expect(nextCalled).toBe(true);
@@ -503,7 +504,7 @@ describe("OpenApiMiddlewareBuilder withValidation / buildWithSchemas", () => {
503
504
  expect(result.validationEnabled).toBe(false);
504
505
  });
505
506
 
506
- it("build() returns an array with validators when validation is enabled", () => {
507
+ it("build() returns an array when validation is enabled with body and query", () => {
507
508
  const result = createOpenApiBuilder({})
508
509
  .withRequestBody({name: {required: true, type: "string"}})
509
510
  .withQueryParameter("page", {type: "number"})
@@ -511,7 +512,7 @@ describe("OpenApiMiddlewareBuilder withValidation / buildWithSchemas", () => {
511
512
  .build();
512
513
 
513
514
  expect(Array.isArray(result)).toBe(true);
514
- expect(result.length).toBeGreaterThan(1);
515
+ expect(result).toHaveLength(3);
515
516
  });
516
517
 
517
518
  it("build() returns a single middleware when validation is disabled", () => {
@@ -759,7 +759,8 @@ export class OpenApiMiddlewareBuilder {
759
759
  * router.get("/users/:id", middleware, getUserHandler);
760
760
  * ```
761
761
  */
762
- // biome-ignore lint/suspicious/noExplicitAny: returns either a single RequestHandler or an array depending on validation config — callers spread or invoke
762
+ // noExplicitAny: returns either a single RequestHandler or an array depending on validation config — callers spread or invoke
763
+ // biome-ignore lint/suspicious/noExplicitAny: returns either a single RequestHandler or an array depending on validation config
763
764
  build(): any {
764
765
  const noop: express.RequestHandler = (_a, _b, next) => next();
765
766
 
@@ -1,9 +1,12 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {afterEach, beforeEach, describe, expect, it} from "bun:test";
3
4
  import type {ErrorObject} from "ajv";
5
+ import type {NextFunction, Request, Response} from "express";
4
6
 
5
7
  import {modelRouter} from "./api";
6
8
  import {addAuthRoutes, setupAuth} from "./auth";
9
+ import type {OpenApiSchemaProperty} from "./openApiBuilder";
7
10
  import {
8
11
  buildQuerySchemaFromFields,
9
12
  configureOpenApiValidator,
@@ -707,4 +710,65 @@ describe("openApiValidator", () => {
707
710
  expect(getOpenApiValidatorConfig().removeAdditional).toBe(false);
708
711
  });
709
712
  });
713
+
714
+ describe("schema sanitization and validator caching", () => {
715
+ const runMiddleware = (
716
+ middleware: (req: Request, res: Response, next: NextFunction) => void,
717
+ req: Partial<Request>
718
+ ): boolean => {
719
+ let nextCalled = false;
720
+ middleware(req as unknown as Request, {} as unknown as Response, () => {
721
+ nextCalled = true;
722
+ });
723
+ return nextCalled;
724
+ };
725
+
726
+ // An unresolvable $ref makes ajv.compile throw, so getValidator catches the error
727
+ // and returns null. Built via `unknown` to keep the non-standard keyword out of the
728
+ // typed surface (and out of the explicit-any baseline).
729
+ const uncompilableSchema = {
730
+ broken: {$ref: "#/components/schemas/DoesNotExist"},
731
+ } as unknown as Record<string, OpenApiSchemaProperty>;
732
+
733
+ it("maps an unrecognized mongoose type to string so the schema still compiles", () => {
734
+ configureOpenApiValidator();
735
+
736
+ // "buffer" is neither a valid JSON Schema type nor present in MONGOOSE_TYPE_MAP,
737
+ // so sanitizeSchemaForAjv falls through to the `type = "string"` branch.
738
+ const middleware = validateRequestBody({raw: {type: "buffer"}});
739
+
740
+ expect(
741
+ runMiddleware(middleware, {body: {raw: "some-string"}, method: "POST", path: "/t"})
742
+ ).toBe(true);
743
+ });
744
+
745
+ it("reuses the cached validator on subsequent requests with the same schema", () => {
746
+ configureOpenApiValidator();
747
+
748
+ const middleware = validateRequestBody({name: {type: "string"}});
749
+ const req: Partial<Request> = {body: {name: "ok"}, method: "POST", path: "/t"};
750
+
751
+ // First request compiles and caches the validator; the second must hit the cache.
752
+ expect(runMiddleware(middleware, req)).toBe(true);
753
+ expect(runMiddleware(middleware, req)).toBe(true);
754
+ });
755
+
756
+ it("skips query validation when the schema cannot be compiled", () => {
757
+ configureOpenApiValidator();
758
+
759
+ const middleware = validateQueryParams(uncompilableSchema);
760
+
761
+ expect(runMiddleware(middleware, {method: "GET", path: "/t", query: {broken: "x"}})).toBe(
762
+ true
763
+ );
764
+ });
765
+
766
+ it("skips response validation when the schema cannot be compiled", () => {
767
+ configureOpenApiValidator({validateResponses: true});
768
+
769
+ const result = validateResponseData({broken: "x"}, uncompilableSchema);
770
+
771
+ expect(result.valid).toBe(true);
772
+ });
773
+ });
710
774
  });
@@ -184,6 +184,7 @@ const getAjvInstance = (): Ajv => {
184
184
  useDefaults: true,
185
185
  validateSchema: false,
186
186
  });
187
+ // noExplicitAny: ajv-formats has a known type compat issue with AJV instances
187
188
  // biome-ignore lint/suspicious/noExplicitAny: ajv-formats has a known type compat issue with AJV instances
188
189
  addFormats(instance as any);
189
190
  ajvCache.set(key, instance);
@@ -1,6 +1,6 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
- import {describe, expect, it, mock, spyOn} from "bun:test";
3
- import * as Sentry from "@sentry/bun";
3
+ import {describe, expect, it, mock} from "bun:test";
4
4
  import type express from "express";
5
5
 
6
6
  import {APIError} from "./errors";
@@ -80,11 +80,11 @@ describe("permissionMiddleware", () => {
80
80
  const [error] = (next as any).mock.calls[0];
81
81
  expect(error).toBeInstanceOf(APIError);
82
82
  expect(error.status).toBe(500);
83
- expect(error.title).toContain("GET failed on 507f1f77bcf86cd799439011");
83
+ expect(error.title).toBe("GET error");
84
+ expect(error.detail).toContain("GET failed on 507f1f77bcf86cd799439011");
84
85
  });
85
86
 
86
- it("captures sentry message when document does not exist", async () => {
87
- const captureMessageSpy = spyOn(Sentry, "captureMessage");
87
+ it("returns plain not found when document does not exist", async () => {
88
88
  const model = {
89
89
  collection: {findOne: mock(async () => null)},
90
90
  findById: mock(() => ({exec: mock(async () => null)})),
@@ -99,14 +99,11 @@ describe("permissionMiddleware", () => {
99
99
  next as any
100
100
  );
101
101
 
102
- expect(captureMessageSpy).toHaveBeenCalledWith(
103
- "Document 507f1f77bcf86cd799439011 not found for model MockModel"
104
- );
105
102
  const [error] = (next as any).mock.calls[0];
106
103
  expect(error).toBeInstanceOf(APIError);
107
104
  expect(error.status).toBe(404);
108
- expect(error.meta).toBeUndefined();
109
- captureMessageSpy.mockRestore();
105
+ expect(error.title).toBe("Document not found");
106
+ expect(error.detail).toContain("507f1f77bcf86cd799439011");
110
107
  });
111
108
 
112
109
  it("returns hidden reason metadata when document is deleted", async () => {
@@ -193,6 +190,6 @@ describe("permissionMiddleware", () => {
193
190
  const [error] = (next as any).mock.calls[0];
194
191
  expect(error).toBeInstanceOf(APIError);
195
192
  expect(error.status).toBe(404);
196
- expect(error.meta).toBeUndefined();
193
+ expect(error.title).toBe("Document not found");
197
194
  });
198
195
  });
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {beforeEach, describe, expect, it} from "bun:test";
3
4
  import type express from "express";
@@ -6,7 +6,6 @@ import type {ModelRouterOptions, RESTMethod} from "./api";
6
6
  import type {User} from "./auth";
7
7
  import {loadDocOr404} from "./docLoader";
8
8
  import {APIError} from "./errors";
9
- import {logger} from "./logger";
10
9
 
11
10
  export type PermissionMethod<T> = (
12
11
  method: RESTMethod,
@@ -158,7 +157,6 @@ export const permissionMiddleware = <T>(
158
157
 
159
158
  return next();
160
159
  } catch (error) {
161
- logger.error(`Permissions error: ${error instanceof Error ? error.message : error}`);
162
160
  return next(error);
163
161
  }
164
162
  };
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {beforeEach, describe, expect, it, setSystemTime} from "bun:test";
3
4
  import type express from "express";
@@ -506,14 +507,16 @@ describe("DateOnly", () => {
506
507
  it("returns 404 with context for hidden document", async () => {
507
508
  const doc = await StuffModel.create({deleted: true, name: "test"});
508
509
  const res = await agent.get(`/stuff/${doc._id}`).expect(404);
509
- expect(res.body.title).toBe(`Document ${doc._id} not found for model Stuff`);
510
+ expect(res.body.title).toBe("Document not found");
511
+ expect(res.body.detail).toContain(String(doc._id));
510
512
  expect(res.body.meta).toEqual({deleted: "true"});
511
513
  });
512
514
 
513
515
  it("returns 404 without meta for missing document", async () => {
514
516
  const nonExistentId = "507f1f77bcf86cd799439011";
515
517
  const res = await agent.get(`/stuff/${nonExistentId}`).expect(404);
516
- expect(res.body.title).toBe(`Document ${nonExistentId} not found for model Stuff`);
518
+ expect(res.body.title).toBe("Document not found");
519
+ expect(res.body.detail).toContain(nonExistentId);
517
520
  expect(res.body.meta).toBeUndefined();
518
521
  });
519
522
  });
package/src/plugins.ts CHANGED
@@ -16,6 +16,7 @@ export interface BaseUser {
16
16
  email: string;
17
17
  }
18
18
 
19
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
19
20
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
20
21
  export const baseUserPlugin = (schema: Schema<any, any, any, any>): void => {
21
22
  schema.add({
@@ -30,6 +31,7 @@ export interface IsDeleted {
30
31
  deleted: boolean;
31
32
  }
32
33
 
34
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
33
35
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
34
36
  export const isDeletedPlugin = (schema: Schema<any, any, any, any>, defaultValue = false): void => {
35
37
  schema.add({
@@ -42,6 +44,7 @@ export const isDeletedPlugin = (schema: Schema<any, any, any, any>, defaultValue
42
44
  type: Boolean,
43
45
  },
44
46
  });
47
+ // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
45
48
  // biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
46
49
  const applyDeleteFilter = (q: Query<any, any>): void => {
47
50
  const query = q.getQuery();
@@ -58,6 +61,7 @@ export const isDeletedPlugin = (schema: Schema<any, any, any, any>, defaultValue
58
61
  };
59
62
 
60
63
  export const isDisabledPlugin = (
64
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
61
65
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
62
66
  schema: Schema<any, any, any, any>,
63
67
  defaultValue = false
@@ -77,6 +81,7 @@ export interface CreatedDeleted {
77
81
  created: {type: Date; required: true};
78
82
  }
79
83
 
84
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
80
85
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
81
86
  export const createdUpdatedPlugin = (schema: Schema<any, any, any, any>): void => {
82
87
  schema.add({
@@ -209,6 +214,7 @@ export const findExactlyOne = <T>(schema: Schema<T>): void => {
209
214
  * match the conditions to prevent ambiguous updates.
210
215
  * @param schema Mongoose Schema
211
216
  */
217
+ // noExplicitAny: Schema generics with unknown collide with mongoose's loose this-binding on schema.statics
212
218
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics with unknown collide with mongoose's loose this-binding on schema.statics
213
219
  export const upsertPlugin = <T>(schema: Schema<any, any, any, any>): void => {
214
220
  schema.statics.upsert = async function (
@@ -269,6 +275,7 @@ export class DateOnly extends SchemaType {
269
275
  }
270
276
 
271
277
  $conditionalHandlers = {
278
+ // noExplicitAny: $conditionalHandlers is not exposed on SchemaType's prototype in Mongoose's public type definitions
272
279
  // biome-ignore lint/suspicious/noExplicitAny: $conditionalHandlers is not exposed on SchemaType's prototype in Mongoose's public type definitions
273
280
  ...(SchemaType as any).prototype.$conditionalHandlers,
274
281
  $gt: this.handleSingle,
@@ -281,6 +288,7 @@ export class DateOnly extends SchemaType {
281
288
  // When using $gt, $gte, $lt, $lte, etc, we need to cast the value to a Date
282
289
  castForQuery($conditional: string | undefined, val: unknown, context: unknown): Date | undefined {
283
290
  if ($conditional == null) {
291
+ // noExplicitAny: applySetters is an internal Mongoose SchemaType method not in public type definitions
284
292
  // biome-ignore lint/suspicious/noExplicitAny: applySetters is an internal Mongoose SchemaType method not in public type definitions
285
293
  return (this as any).applySetters(val, context);
286
294
  }
@@ -341,5 +349,6 @@ export class DateOnly extends SchemaType {
341
349
  }
342
350
 
343
351
  // Register DateOnly with Mongoose's Schema.Types
352
+ // noExplicitAny: DateOnly is a custom SchemaType not declared in Mongoose's Schema.Types interface
344
353
  // biome-ignore lint/suspicious/noExplicitAny: DateOnly is a custom SchemaType not declared in Mongoose's Schema.Types interface
345
354
  (mongoose.Schema.Types as any).DateOnly = DateOnly;
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {beforeEach, describe, expect, it} from "bun:test";
3
4
  import mongoose, {type Document, type HydratedDocument, Schema} from "mongoose";
package/src/populate.ts CHANGED
@@ -140,7 +140,8 @@ export const fixMixedFields = (schema: Schema | null, properties: Record<string,
140
140
  };
141
141
 
142
142
  export const getOpenApiSpecForModel = (
143
- // biome-ignore lint/suspicious/noExplicitAny: noExplicitAny: Mongoose Model param uses deep internal APIs (schema.path().options.ref, schema.virtuals, schema.childSchemas, db.model) that are not exposed in public type definitions
143
+ // noExplicitAny: Mongoose Model param uses deep internal APIs (schema.path().options.ref, schema.virtuals, schema.childSchemas, db.model) that are not exposed in public type definitions
144
+ // biome-ignore lint/suspicious/noExplicitAny: Mongoose Model param uses deep internal APIs (schema.path().options.ref, schema.virtuals, schema.childSchemas, db.model) that are not exposed in public type definitions
144
145
  model: any,
145
146
  {
146
147
  populatePaths,
@@ -261,7 +262,8 @@ export const unpopulate = <T>(doc: Document<T>, path: string): Document<T> => {
261
262
  const pathParts = path.split(".");
262
263
 
263
264
  // Recursive because we need to support nested paths.
264
- // biome-ignore lint/suspicious/noExplicitAny: noExplicitAny: recursive document traversal uses bracket-notation indexing on arbitrary nested document shapes that Mongoose Document types do not expose
265
+ // noExplicitAny: recursive document traversal uses bracket-notation indexing on arbitrary nested document shapes that Mongoose Document types do not expose
266
+ // biome-ignore lint/suspicious/noExplicitAny: recursive document traversal uses bracket-notation indexing on arbitrary nested document shapes that Mongoose Document types do not expose
265
267
  const recursiveUnpopulate = (current: any, parts: string[]): any => {
266
268
  const part = parts[0];
267
269
 
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mocks use dynamic shapes for registry entries and documents
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mocks use dynamic shapes for registry entries and documents
2
3
  /**
3
4
  * Tests for the realtime module's pure functions and classes:
@@ -934,7 +935,10 @@ describe("installRealtimeSocketHandlers", () => {
934
935
  // queryId emitted back must encode the injected ownerId
935
936
  const subscribed = socket.emitted.find((e) => e.event === "query:subscribed");
936
937
  expect(subscribed).toBeDefined();
937
- expect((subscribed?.payload as any).queryId).toContain("user1");
938
+ if (!subscribed) {
939
+ throw new Error("Expected a query subscription event");
940
+ }
941
+ expect((subscribed.payload as any).queryId).toContain("user1");
938
942
  });
939
943
 
940
944
  it("does NOT inject ownerId for admins (admins see all)", async () => {
@@ -947,7 +951,10 @@ describe("installRealtimeSocketHandlers", () => {
947
951
  });
948
952
  const subscribed = socket.emitted.find((e) => e.event === "query:subscribed");
949
953
  expect(subscribed).toBeDefined();
950
- expect((subscribed?.payload as any).queryId).not.toContain("admin1");
954
+ if (!subscribed) {
955
+ throw new Error("Expected a query subscription event");
956
+ }
957
+ expect((subscribed.payload as any).queryId).not.toContain("admin1");
951
958
  });
952
959
 
953
960
  it("ignores subscriptions when user has no id (anonymous) for owner strategy", async () => {
@@ -1135,7 +1142,10 @@ describe("installRealtimeSocketHandlers", () => {
1135
1142
  await socket.trigger("subscribe:query", {collection: "broadcasts", query: {priority: 1}});
1136
1143
  const subscribed = socket.emitted.find((e) => e.event === "query:subscribed");
1137
1144
  expect(subscribed).toBeDefined();
1138
- const queryId = (subscribed?.payload as {queryId: string}).queryId;
1145
+ if (!subscribed) {
1146
+ throw new Error("Expected a query subscription event");
1147
+ }
1148
+ const queryId = (subscribed.payload as {queryId: string}).queryId;
1139
1149
  expect(socket.rooms.has(`query:${queryId}`)).toBe(true);
1140
1150
  expect(getQuerySubscriptionsForCollection("broadcasts").length).toBe(1);
1141
1151
  await socket.trigger("unsubscribe:query", {queryId});
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: Socket.io handler signatures require dynamic args
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: Socket.io handler signatures require dynamic args
2
3
  import type http from "node:http";
3
4
  import * as Sentry from "@sentry/bun";
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: model router options are generic across all models
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: model router options are generic across all models
2
3
  import type {ModelRouterOptions} from "../api";
3
4
  import type {RealtimeConfig} from "./types";
@@ -36,8 +36,7 @@ export interface RealtimeEvent {
36
36
  /** Document ID */
37
37
  id: string;
38
38
  /** Serialized document data (omitted for hard deletes) */
39
- // biome-ignore lint/suspicious/noExplicitAny: noExplicitAny: event data is a serialized document whose shape varies by model; consumers must narrow to their specific type
40
- data?: any;
39
+ data?: unknown;
41
40
  /** Fields that were updated (for update events from change streams) */
42
41
  updatedFields?: string[];
43
42
  /** Epoch milliseconds when the event was generated */
@@ -289,6 +289,38 @@ describe("request context job propagation", () => {
289
289
  expect(ctx.traceId).toBeUndefined();
290
290
  });
291
291
 
292
+ it("returns undefined trace when google cloud trace context has empty trace id", () => {
293
+ const ctx = getRequestContextFromAttributes({
294
+ "x-cloud-trace-context": "/1;o=1",
295
+ "x-request-id": "r7",
296
+ });
297
+ expect(ctx.traceId).toBeUndefined();
298
+ expect(ctx.spanId).toBeUndefined();
299
+ expect(ctx.requestId).toBe("r7");
300
+ });
301
+
302
+ it("reads the first value when a request header arrives as an array", () => {
303
+ const headers: Record<string, string[] | string | undefined> = {
304
+ "x-cloud-trace-context": ["arrtrace/7;o=1", "ignored/9;o=0"],
305
+ };
306
+ const req = {
307
+ header: (name: string): string[] | string | undefined => headers[name.toLowerCase()],
308
+ user: undefined,
309
+ } as unknown as express.Request;
310
+ const res = {
311
+ setHeader: (): void => {},
312
+ } as unknown as express.Response;
313
+
314
+ let captured: {spanId?: string; traceId?: string} | undefined;
315
+ requestContextMiddleware(req, res, () => {
316
+ const ctx = getCurrentRequestContext();
317
+ captured = {spanId: ctx?.spanId, traceId: ctx?.traceId};
318
+ });
319
+
320
+ expect(captured?.traceId).toBe("arrtrace");
321
+ expect(captured?.spanId).toBe("7");
322
+ });
323
+
292
324
  it("adds job id to logger context", () => {
293
325
  let output = "";
294
326
  const stream = new Writable({
package/src/terrenoApp.ts CHANGED
@@ -228,6 +228,7 @@ export class TerrenoApp {
228
228
  * ```
229
229
  */
230
230
  configure(
231
+ // noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
231
232
  // biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
232
233
  model: import("mongoose").Model<any>,
233
234
  options?: Omit<ConfigurationAppOptions, "model">
@@ -1,6 +1,8 @@
1
+ import {DateTime} from "luxon";
1
2
  import type {HydratedDocument} from "mongoose";
2
3
  import type {PassportLocalMongooseDocument} from "passport-local-mongoose";
3
4
 
5
+ import {APIError} from "../errors";
4
6
  import {logger} from "../logger";
5
7
  import {FoodModel, RequiredModel, type User, UserModel} from "./models";
6
8
  import type {CachedTestData, TestData, TestFoods, TestRequired, TestUsers} from "./types";
@@ -41,12 +43,12 @@ export const createStandardFoods = async (users: TestUsers): Promise<TestFoods>
41
43
  FoodModel.create({
42
44
  calories: 1,
43
45
  categories: [{name: "Vegetables", show: true}],
44
- created: new Date("2021-12-03T00:00:20.000Z"),
46
+ created: DateTime.fromISO("2021-12-03T00:00:20.000Z").toJSDate(),
45
47
  eatenBy: [admin._id],
46
48
  expiration: "2026-12-31",
47
49
  hidden: false,
48
50
  lastEatenWith: {
49
- dressing: new Date("2021-12-03T19:00:30.000Z"),
51
+ dressing: DateTime.fromISO("2021-12-03T19:00:30.000Z").toJSDate(),
50
52
  },
51
53
  likesIds: [
52
54
  {likes: true, userId: admin._id},
@@ -63,7 +65,7 @@ export const createStandardFoods = async (users: TestUsers): Promise<TestFoods>
63
65
  }),
64
66
  FoodModel.create({
65
67
  calories: 100,
66
- created: new Date("2021-12-03T00:00:30.000Z"),
68
+ created: DateTime.fromISO("2021-12-03T00:00:30.000Z").toJSDate(),
67
69
  expiration: "2026-12-31",
68
70
  hidden: true,
69
71
  likesIds: [{likes: true, userId: admin._id}],
@@ -74,7 +76,7 @@ export const createStandardFoods = async (users: TestUsers): Promise<TestFoods>
74
76
  }),
75
77
  FoodModel.create({
76
78
  calories: 100,
77
- created: new Date("2021-12-03T00:00:00.000Z"),
79
+ created: DateTime.fromISO("2021-12-03T00:00:00.000Z").toJSDate(),
78
80
  eatenBy: [admin._id, notAdmin._id],
79
81
  expiration: "2026-12-31",
80
82
  hidden: false,
@@ -86,7 +88,7 @@ export const createStandardFoods = async (users: TestUsers): Promise<TestFoods>
86
88
  }),
87
89
  FoodModel.create({
88
90
  calories: 800,
89
- created: new Date("2022-01-01T00:00:00.000Z"),
91
+ created: DateTime.fromISO("2022-01-01T00:00:00.000Z").toJSDate(),
90
92
  expiration: "2026-12-31",
91
93
  hidden: false,
92
94
  likesIds: [{likes: true, userId: adminOther._id}],
@@ -165,7 +167,10 @@ export const loadTestDataFromDocuments = async (cached: CachedTestData): Promise
165
167
  !sample ||
166
168
  !withAbout
167
169
  ) {
168
- throw new Error("[createTestData] Cached test data references missing documents");
170
+ throw new APIError({
171
+ status: 500,
172
+ title: "[createTestData] Cached test data references missing documents",
173
+ });
169
174
  }
170
175
 
171
176
  return {
@@ -126,6 +126,7 @@ const foodSchema = new Schema<Food>(
126
126
  type: Schema.Types.ObjectId,
127
127
  },
128
128
  ],
129
+ // noExplicitAny: DateOnly is a custom SchemaType not recognized by Mongoose's built-in type definitions
129
130
  // biome-ignore lint/suspicious/noExplicitAny: DateOnly is a custom SchemaType not recognized by Mongoose's built-in type definitions
130
131
  expiration: {description: "Expiration date of the food", type: DateOnly as any},
131
132
  hidden: {
@@ -173,9 +173,11 @@ export const defaultResponseHandler = async <T>(
173
173
  } catch (error: unknown) {
174
174
  const errorObj = error as Error;
175
175
  throw new APIError({
176
- error: errorObj,
176
+ cause: errorObj,
177
+ code: "serialization-error",
178
+ detail: errorObj.message,
177
179
  status: 400,
178
- title: `Error serializing ${method} response: ${errorObj.message}`,
180
+ title: `Error serializing ${method} response`,
179
181
  });
180
182
  }
181
183
  };
@@ -68,7 +68,7 @@ module.exports = function generateDocument (baseDocument, router, basePath) {
68
68
 
69
69
  operation.parameters = params.filter((p) => typeof p.name === 'string' && p.name)
70
70
  try {
71
- path = pathToRegexp.compile(path.replace(/\*|\(\*\)/g, '(.*)'))(keys, { encode: (value) => value })
71
+ path = pathToRegexp.compile(path.replace(/\*|\(\*\)/g, '(.*)'), { encode: (value) => value })(keys)
72
72
  } catch (_e) {
73
73
  // Express 5 stores path params in matchers instead of layer.keys, so keys
74
74
  // may be incomplete. Fall back to simple regex replacement of :param → {param}.
@@ -76,6 +76,9 @@ module.exports = function generateDocument (baseDocument, router, basePath) {
76
76
  }
77
77
  }
78
78
 
79
+ // Normalize any percent-encoded path parameters to OpenAPI syntax.
80
+ path = path.replace(/%7B/gi, '{').replace(/%7D/gi, '}')
81
+
79
82
  doc.paths[path] = doc.paths[path] || {}
80
83
  doc.paths[path][layer.method] = operation
81
84
  setSchema(layer.handle, operation)