@terreno/api 0.25.0 → 0.27.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 (114) hide show
  1. package/.ai/guidelines/core.md +1 -0
  2. package/README.md +4 -3
  3. package/dist/__tests__/openApiCompat.test.js +8 -2
  4. package/dist/__tests__/versionCheckPlugin.test.js +15 -0
  5. package/dist/actions.openApi.test.js +1 -0
  6. package/dist/actions.test.js +1 -0
  7. package/dist/api.arrayOperations.test.js +1 -0
  8. package/dist/api.coverage.test.d.ts +1 -0
  9. package/dist/api.coverage.test.js +191 -0
  10. package/dist/api.errorPaths.test.d.ts +1 -0
  11. package/dist/api.errorPaths.test.js +278 -0
  12. package/dist/api.errors.test.js +1 -0
  13. package/dist/api.hooks.test.js +1 -0
  14. package/dist/api.js +160 -167
  15. package/dist/api.query.test.js +1 -0
  16. package/dist/api.test.js +1 -0
  17. package/dist/auth.js +1 -0
  18. package/dist/auth.test.js +122 -0
  19. package/dist/betterAuthApp.test.js +1 -2
  20. package/dist/betterAuthSetup.js +1 -0
  21. package/dist/betterAuthSetup.test.js +1 -0
  22. package/dist/configuration.test.js +1 -0
  23. package/dist/configurationApp.js +1 -0
  24. package/dist/configurationPlugin.test.js +80 -0
  25. package/dist/consentApp.test.js +1 -0
  26. package/dist/docLoader.js +1 -3
  27. package/dist/envConfigurationPlugin.js +1 -0
  28. package/dist/example.js +3 -2
  29. package/dist/expressServer.js +6 -6
  30. package/dist/expressServer.test.js +23 -0
  31. package/dist/githubAuth.js +2 -0
  32. package/dist/githubAuth.test.js +1 -0
  33. package/dist/index.d.ts +9 -2
  34. package/dist/index.js +28 -3
  35. package/dist/logger.test.js +107 -0
  36. package/dist/openApi.test.js +52 -0
  37. package/dist/openApiBuilder.js +2 -1
  38. package/dist/openApiBuilder.test.js +3 -2
  39. package/dist/openApiValidator.js +1 -0
  40. package/dist/openApiValidator.test.js +41 -0
  41. package/dist/permissions.middleware.test.js +1 -0
  42. package/dist/permissions.test.js +1 -0
  43. package/dist/plugins.js +8 -0
  44. package/dist/plugins.test.js +1 -0
  45. package/dist/populate.js +4 -2
  46. package/dist/populate.test.js +1 -0
  47. package/dist/realtime/realtime.test.js +13 -3
  48. package/dist/realtime/types.d.ts +1 -1
  49. package/dist/requestContext.test.js +28 -0
  50. package/dist/terrenoApp.js +1 -0
  51. package/dist/tests/createTestData.js +11 -6
  52. package/dist/tests/fixtures/compileAuthEntry.js +1 -1
  53. package/dist/tests/models.js +1 -0
  54. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +3 -1
  55. package/package.json +7 -7
  56. package/src/__tests__/openApiCompat.test.ts +8 -2
  57. package/src/__tests__/versionCheckPlugin.test.ts +9 -0
  58. package/src/actions.openApi.test.ts +1 -0
  59. package/src/actions.test.ts +1 -0
  60. package/src/api.arrayOperations.test.ts +1 -0
  61. package/src/api.coverage.test.ts +121 -0
  62. package/src/api.errorPaths.test.ts +171 -0
  63. package/src/api.errors.test.ts +1 -0
  64. package/src/api.hooks.test.ts +1 -0
  65. package/src/api.query.test.ts +1 -0
  66. package/src/api.test.ts +1 -0
  67. package/src/api.ts +13 -9
  68. package/src/auth.test.ts +91 -2
  69. package/src/auth.ts +6 -0
  70. package/src/betterAuthApp.test.ts +3 -3
  71. package/src/betterAuthSetup.test.ts +1 -0
  72. package/src/betterAuthSetup.ts +3 -0
  73. package/src/configuration.test.ts +1 -0
  74. package/src/configurationApp.ts +2 -0
  75. package/src/configurationPlugin.test.ts +46 -1
  76. package/src/consentApp.test.ts +1 -0
  77. package/src/docLoader.ts +1 -2
  78. package/src/envConfigurationPlugin.ts +2 -0
  79. package/src/example.ts +3 -2
  80. package/src/expressServer.test.ts +13 -0
  81. package/src/expressServer.ts +5 -3
  82. package/src/githubAuth.test.ts +1 -0
  83. package/src/githubAuth.ts +2 -0
  84. package/src/index.ts +40 -2
  85. package/src/logger.test.ts +78 -0
  86. package/src/openApi.test.ts +54 -0
  87. package/src/openApiBuilder.test.ts +7 -6
  88. package/src/openApiBuilder.ts +2 -1
  89. package/src/openApiValidator.test.ts +64 -0
  90. package/src/openApiValidator.ts +1 -0
  91. package/src/permissions.middleware.test.ts +1 -0
  92. package/src/permissions.test.ts +1 -0
  93. package/src/plugins.test.ts +1 -0
  94. package/src/plugins.ts +9 -0
  95. package/src/populate.test.ts +1 -0
  96. package/src/populate.ts +4 -2
  97. package/src/realtime/realtime.test.ts +13 -3
  98. package/src/realtime/realtimeApp.ts +1 -0
  99. package/src/realtime/registry.ts +1 -0
  100. package/src/realtime/types.ts +1 -2
  101. package/src/requestContext.test.ts +32 -0
  102. package/src/terrenoApp.ts +1 -0
  103. package/src/tests/createTestData.ts +11 -6
  104. package/src/tests/fixtures/compileAuthEntry.ts +1 -1
  105. package/src/tests/models.ts +1 -0
  106. package/src/vendor/wesleytodd-openapi/lib/generate-doc.js +4 -1
  107. package/tsconfig.json +3 -3
  108. package/dist/notifiers/index.d.ts +0 -3
  109. package/dist/notifiers/index.js +0 -19
  110. package/dist/realtime/index.d.ts +0 -6
  111. package/dist/realtime/index.js +0 -27
  112. package/src/notifiers/index.ts +0 -3
  113. package/src/realtime/index.ts +0 -34
  114. /package/{types.d.ts → src/types.d.ts} +0 -0
package/src/githubAuth.ts CHANGED
@@ -60,6 +60,7 @@ export interface GitHubUserFields {
60
60
  * userSchema.plugin(githubUserPlugin);
61
61
  * ```
62
62
  */
63
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
63
64
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
64
65
  export const githubUserPlugin = (schema: Schema<any, any, any, any>): void => {
65
66
  schema.add({
@@ -89,6 +90,7 @@ export const setupGitHubAuth = (
89
90
 
90
91
  passport.use(
91
92
  "github",
93
+ // noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
92
94
  // biome-ignore lint/suspicious/noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
93
95
  new (GitHubStrategy as any)(
94
96
  {
package/src/index.ts CHANGED
@@ -18,7 +18,9 @@ export * from "./middleware";
18
18
  export * from "./models/consentForm";
19
19
  export * from "./models/consentResponse";
20
20
  export * from "./models/versionConfig";
21
- export * from "./notifiers";
21
+ export * from "./notifiers/googleChatNotifier";
22
+ export * from "./notifiers/slackNotifier";
23
+ export * from "./notifiers/zoomNotifier";
22
24
  export * from "./openApiBuilder";
23
25
  export * from "./openApiCompat";
24
26
  export * from "./openApiEtag";
@@ -26,7 +28,43 @@ export * from "./openApiValidator";
26
28
  export * from "./permissions";
27
29
  export * from "./plugins";
28
30
  export * from "./populate";
29
- export * from "./realtime";
31
+ export {
32
+ startChangeStreamWatcher,
33
+ stopChangeStreamWatcher,
34
+ } from "./realtime/changeStreamWatcher";
35
+ export {matchesQuery} from "./realtime/queryMatcher";
36
+ export {
37
+ addQuerySubscription,
38
+ clearQueryStore,
39
+ computeQueryId,
40
+ getQuerySubscriptionsForCollection,
41
+ removeAllSocketQueries,
42
+ removeQuerySubscription,
43
+ } from "./realtime/queryStore";
44
+ export {
45
+ installRealtimeSocketHandlers,
46
+ MAX_DOCUMENT_SUBSCRIPTIONS,
47
+ MAX_MODEL_SUBSCRIPTIONS,
48
+ MAX_QUERY_SUBSCRIPTIONS,
49
+ RealtimeApp,
50
+ type RealtimeSocketLike,
51
+ } from "./realtime/realtimeApp";
52
+ export {
53
+ clearRealtimeRegistry,
54
+ findRegistryEntryByCollection,
55
+ findRegistryEntryByRoutePath,
56
+ getRealtimeRegistry,
57
+ type RealtimeRegistryEntry,
58
+ registerRealtime,
59
+ } from "./realtime/registry";
60
+ export type {
61
+ ChangeStreamConfig,
62
+ DocumentSubscription,
63
+ QuerySubscription,
64
+ RealtimeAppOptions,
65
+ RealtimeConfig,
66
+ RealtimeEvent,
67
+ } from "./realtime/types";
30
68
  export * from "./requestContext";
31
69
  export * from "./scriptRunner";
32
70
  export * from "./secretProviders";
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import {Writable} from "node:stream";
6
+ import * as Sentry from "@sentry/bun";
6
7
  import winston from "winston";
7
8
 
8
9
  import {
@@ -57,6 +58,59 @@ describe("logger", () => {
57
58
  });
58
59
  });
59
60
 
61
+ describe("logger Sentry structured logging", () => {
62
+ afterEach(() => {
63
+ Reflect.deleteProperty(process.env, "USE_SENTRY_LOGGING");
64
+ });
65
+
66
+ it("forwards every level to Sentry.logger when USE_SENTRY_LOGGING is true", () => {
67
+ process.env.USE_SENTRY_LOGGING = "true";
68
+ logger.debug("sentry-debug-message");
69
+ logger.info("sentry-info-message");
70
+ logger.warn("sentry-warn-message");
71
+ logger.error("sentry-error-message");
72
+ expect(Sentry.logger?.debug).toHaveBeenCalledWith("sentry-debug-message", expect.anything());
73
+ expect(Sentry.logger?.info).toHaveBeenCalledWith("sentry-info-message", expect.anything());
74
+ expect(Sentry.logger?.warn).toHaveBeenCalledWith("sentry-warn-message", expect.anything());
75
+ expect(Sentry.logger?.error).toHaveBeenCalledWith("sentry-error-message", expect.anything());
76
+ });
77
+
78
+ it("does not forward to Sentry.logger when USE_SENTRY_LOGGING is unset", () => {
79
+ Reflect.deleteProperty(process.env, "USE_SENTRY_LOGGING");
80
+ expect(() => logger.info("no-sentry-message")).not.toThrow();
81
+ expect(Sentry.logger?.info).not.toHaveBeenCalledWith("no-sentry-message", expect.anything());
82
+ });
83
+
84
+ it("attaches terrenoRequestLog to Sentry attributes inside a request scope", () => {
85
+ process.env.USE_SENTRY_LOGGING = "true";
86
+ runWithRequestContext({requestId: "sentry-req-1", userId: "sentry-user-1"}, () => {
87
+ logger.info("sentry-request-scoped-message");
88
+ });
89
+ expect(Sentry.logger?.info).toHaveBeenCalledWith(
90
+ "sentry-request-scoped-message",
91
+ expect.objectContaining({
92
+ terrenoRequestLog: expect.objectContaining({
93
+ requestId: "sentry-req-1",
94
+ userId: "sentry-user-1",
95
+ }),
96
+ })
97
+ );
98
+ });
99
+
100
+ it("logs a caught non-Error value via Sentry.logger.error when enabled", () => {
101
+ process.env.USE_SENTRY_LOGGING = "true";
102
+ expect(() => logger.catch("plain-string-failure")).not.toThrow();
103
+ expect(Sentry.logger?.error).toHaveBeenCalled();
104
+ });
105
+
106
+ it("scoped logger catch logs a non-Error value via Sentry.logger.error when enabled", () => {
107
+ process.env.USE_SENTRY_LOGGING = "true";
108
+ const scoped = createScopedLogger({labels: {jobId: "j1"}, prefix: "[SentryScoped]"});
109
+ expect(() => scoped.catch("scoped-plain-failure")).not.toThrow();
110
+ expect(Sentry.logger?.error).toHaveBeenCalled();
111
+ });
112
+ });
113
+
60
114
  describe("formatLogContextSuffix", () => {
61
115
  it("includes request ids and sorts terrenoLabels for stable output", () => {
62
116
  const suffix = formatLogContextSuffix({
@@ -611,4 +665,28 @@ describe("setupLogging", () => {
611
665
  })
612
666
  ).not.toThrow();
613
667
  });
668
+
669
+ it("attaches the dev JSONL transport when TERRENO_LOG_FILE forces it on", () => {
670
+ const originalCwd = process.cwd();
671
+ process.env.TERRENO_LOG_FILE = "true";
672
+ try {
673
+ process.chdir(tempDir);
674
+ setupLogging({disableConsoleLogging: true, disableFileLogging: true});
675
+ expect(fs.existsSync(path.join(tempDir, ".terreno", "logs"))).toBe(true);
676
+ } finally {
677
+ process.chdir(originalCwd);
678
+ Reflect.deleteProperty(process.env, "TERRENO_LOG_FILE");
679
+ }
680
+ });
681
+
682
+ it("skips the dev JSONL transport when TERRENO_LOG_FILE forces it off", () => {
683
+ process.env.TERRENO_LOG_FILE = "false";
684
+ try {
685
+ expect(() =>
686
+ setupLogging({disableConsoleLogging: true, disableFileLogging: true})
687
+ ).not.toThrow();
688
+ } finally {
689
+ Reflect.deleteProperty(process.env, "TERRENO_LOG_FILE");
690
+ }
691
+ });
614
692
  });
@@ -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";
@@ -186,6 +187,59 @@ describe("openApi", () => {
186
187
  });
187
188
  });
188
189
 
190
+ function addRoutesStringQuery(router: Router, options?: Partial<ModelRouterOptions<any>>): void {
191
+ router.use(
192
+ "/food",
193
+ modelRouter(FoodModel as any, {
194
+ ...options,
195
+ allowAnonymous: true,
196
+ permissions: {
197
+ create: [Permissions.IsAny],
198
+ delete: [Permissions.IsAny],
199
+ list: [Permissions.IsAny],
200
+ read: [Permissions.IsAny],
201
+ update: [Permissions.IsAny],
202
+ },
203
+ queryFields: ["name"],
204
+ })
205
+ );
206
+ }
207
+
208
+ describe("openApi string query fields", () => {
209
+ let server: TestAgent;
210
+ let app: express.Application;
211
+
212
+ beforeEach(async () => {
213
+ process.env.REFRESH_TOKEN_SECRET = "testsecret1234";
214
+ process.env.ENABLE_SWAGGER = "true";
215
+
216
+ app = new TerrenoApp({
217
+ configureApp: addRoutesStringQuery,
218
+ skipListen: true,
219
+ userModel: UserModel as any,
220
+ }).build();
221
+ });
222
+
223
+ it("builds an $in array query param for non-numeric query fields", async () => {
224
+ server = supertest(app);
225
+ const res = await server.get("/openapi.json").expect(200);
226
+ const nameQuery = res.body.paths["/food/"].get.parameters.find((p) => p.name === "name");
227
+
228
+ // Non-number/non-datetime fields support equality and $in array matching.
229
+ expect(nameQuery.schema).toEqual({
230
+ oneOf: [
231
+ {description: "The name of the food", type: "string"},
232
+ {
233
+ properties: {
234
+ $in: {items: {type: "string"}, type: "array"},
235
+ },
236
+ type: "object",
237
+ },
238
+ ],
239
+ });
240
+ });
241
+ });
242
+
189
243
  function addRoutesPopulate(router: Router, options?: Partial<ModelRouterOptions<any>>): void {
190
244
  options?.openApi?.component("schemas", "LimitedUser", {
191
245
  properties: {
@@ -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,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {describe, expect, it, mock, spyOn} from "bun:test";
3
4
  import * as Sentry from "@sentry/bun";
@@ -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, setSystemTime} from "bun:test";
3
4
  import type express from "express";
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">