@terreno/api 0.31.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 (232) hide show
  1. package/dist/api.d.ts +10 -0
  2. package/dist/api.js +110 -361
  3. package/dist/auth.d.ts +26 -0
  4. package/dist/auth.js +121 -26
  5. package/dist/betterAuth.d.ts +5 -0
  6. package/dist/betterAuthSetup.js +23 -4
  7. package/dist/docLoader.js +12 -9
  8. package/dist/errors.d.ts +13 -0
  9. package/dist/errors.js +29 -1
  10. package/dist/index.d.ts +17 -1
  11. package/dist/index.js +29 -1
  12. package/dist/middleware.d.ts +7 -0
  13. package/dist/middleware.js +16 -1
  14. package/dist/openApiCompat.d.ts +10 -1
  15. package/dist/openApiCompat.js +115 -47
  16. package/dist/permissions.d.ts +27 -0
  17. package/dist/permissions.js +42 -1
  18. package/dist/plugins.d.ts +13 -0
  19. package/dist/plugins.js +47 -1
  20. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  21. package/dist/realtime/changeStreamWatcher.js +542 -137
  22. package/dist/realtime/realtimeApp.d.ts +2 -0
  23. package/dist/realtime/realtimeApp.js +83 -27
  24. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  25. package/dist/realtime/sessionRevalidation.js +438 -0
  26. package/dist/realtime/socketAuth.d.ts +97 -0
  27. package/dist/realtime/socketAuth.js +272 -0
  28. package/dist/realtime/socketUser.d.ts +54 -0
  29. package/dist/realtime/socketUser.js +75 -5
  30. package/dist/realtime/types.d.ts +54 -0
  31. package/dist/secretProviders.d.ts +23 -0
  32. package/dist/secretProviders.js +9 -3
  33. package/dist/sync/executors.d.ts +198 -0
  34. package/dist/sync/executors.js +670 -0
  35. package/dist/sync/loadHarness.js +807 -0
  36. package/dist/sync/models.d.ts +216 -0
  37. package/dist/sync/models.js +644 -0
  38. package/dist/sync/mutationHandler.d.ts +97 -0
  39. package/dist/sync/mutationHandler.js +886 -0
  40. package/dist/sync/registry.d.ts +73 -0
  41. package/dist/sync/registry.js +223 -0
  42. package/dist/sync/routes.d.ts +62 -0
  43. package/dist/sync/routes.js +936 -0
  44. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  45. package/dist/sync/scripts/compactTombstones.js +270 -0
  46. package/dist/sync/serialize.d.ts +20 -0
  47. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  48. package/dist/sync/socketHandlers.d.ts +54 -0
  49. package/dist/sync/socketHandlers.js +470 -0
  50. package/dist/sync/streams.d.ts +85 -0
  51. package/dist/sync/streams.js +221 -0
  52. package/dist/sync/syncApp.d.ts +29 -0
  53. package/dist/sync/syncApp.js +44 -0
  54. package/dist/sync/syncBatch.d.ts +71 -0
  55. package/dist/sync/syncBatch.js +252 -0
  56. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  57. package/dist/sync/syncSeqPlugin.js +899 -0
  58. package/dist/sync/types.d.ts +254 -0
  59. package/dist/sync/types.js +9 -0
  60. package/dist/terrenoApp.js +90 -27
  61. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  62. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  63. package/package.json +7 -6
  64. package/src/__tests__/openApiCompat.test.ts +20 -0
  65. package/src/api.errors.test.ts +32 -23
  66. package/src/api.test.ts +12 -0
  67. package/src/api.ts +87 -296
  68. package/src/auth.test.ts +202 -0
  69. package/src/auth.ts +134 -23
  70. package/src/betterAuth.ts +6 -0
  71. package/src/betterAuthSetup.test.ts +34 -0
  72. package/src/betterAuthSetup.ts +20 -1
  73. package/src/configuration.test.ts +59 -38
  74. package/src/configurationPlugin.test.ts +72 -42
  75. package/src/docLoader.ts +3 -1
  76. package/src/errors.ts +33 -0
  77. package/src/expressServer.test.ts +7 -1
  78. package/src/index.ts +42 -0
  79. package/src/middleware.test.ts +56 -1
  80. package/src/middleware.ts +15 -0
  81. package/src/openApiCompat.ts +99 -45
  82. package/src/permissions.test.ts +101 -17
  83. package/src/permissions.ts +49 -0
  84. package/src/plugins.test.ts +64 -0
  85. package/src/plugins.ts +56 -0
  86. package/src/realtime/changeStreamWatcher.ts +552 -114
  87. package/src/realtime/realtime.test.ts +157 -0
  88. package/src/realtime/realtimeApp.ts +82 -14
  89. package/src/realtime/realtimeAppSetup.test.ts +25 -27
  90. package/src/realtime/sessionRevalidation.test.ts +423 -0
  91. package/src/realtime/sessionRevalidation.ts +273 -0
  92. package/src/realtime/socketAuth.test.ts +355 -0
  93. package/src/realtime/socketAuth.ts +228 -0
  94. package/src/realtime/socketUser.ts +69 -0
  95. package/src/realtime/types.ts +54 -0
  96. package/src/secretProviders.test.ts +7 -1
  97. package/src/secretProviders.ts +15 -3
  98. package/src/secretProvidersGcpClient.test.ts +66 -0
  99. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  100. package/src/sync/executors.test.ts +882 -0
  101. package/src/sync/executors.ts +705 -0
  102. package/src/sync/integration.test.ts +1160 -0
  103. package/src/sync/loadHarness.ts +618 -0
  104. package/src/sync/models.ts +641 -0
  105. package/src/sync/mutationHandler.test.ts +1252 -0
  106. package/src/sync/mutationHandler.ts +850 -0
  107. package/src/sync/registry.ts +232 -0
  108. package/src/sync/routes.ts +812 -0
  109. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  110. package/src/sync/scripts/compactTombstones.ts +145 -0
  111. package/src/sync/serialize.ts +48 -0
  112. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  113. package/src/sync/socketHandlers.ts +320 -0
  114. package/src/sync/streams.ts +188 -0
  115. package/src/sync/sync.test.ts +582 -0
  116. package/src/sync/syncApp.ts +44 -0
  117. package/src/sync/syncBatch.ts +219 -0
  118. package/src/sync/syncFrontier.test.ts +494 -0
  119. package/src/sync/syncPhaseC.test.ts +718 -0
  120. package/src/sync/syncRoutes.test.ts +865 -0
  121. package/src/sync/syncSeqPlugin.ts +730 -0
  122. package/src/sync/syncSocket.test.ts +1440 -0
  123. package/src/sync/types.ts +270 -0
  124. package/src/terrenoApp.ts +37 -17
  125. package/src/tests/bunSetup.ts +8 -0
  126. package/tsconfig.json +4 -4
  127. package/tsconfig.typedoc.json +7 -1
  128. package/dist/__tests__/openApiCompat.test.js +0 -317
  129. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  130. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  131. package/dist/actions.openApi.test.d.ts +0 -1
  132. package/dist/actions.openApi.test.js +0 -253
  133. package/dist/actions.test.d.ts +0 -1
  134. package/dist/actions.test.js +0 -1087
  135. package/dist/api.arrayOperations.test.d.ts +0 -1
  136. package/dist/api.arrayOperations.test.js +0 -878
  137. package/dist/api.asyncHandler.test.d.ts +0 -1
  138. package/dist/api.asyncHandler.test.js +0 -236
  139. package/dist/api.coverage.test.d.ts +0 -1
  140. package/dist/api.coverage.test.js +0 -192
  141. package/dist/api.errorPaths.test.d.ts +0 -1
  142. package/dist/api.errorPaths.test.js +0 -887
  143. package/dist/api.errors.test.d.ts +0 -1
  144. package/dist/api.errors.test.js +0 -185
  145. package/dist/api.hooks.test.d.ts +0 -1
  146. package/dist/api.hooks.test.js +0 -950
  147. package/dist/api.query.test.d.ts +0 -1
  148. package/dist/api.query.test.js +0 -948
  149. package/dist/api.test.d.ts +0 -1
  150. package/dist/api.test.js +0 -2820
  151. package/dist/auth.compile.test.d.ts +0 -1
  152. package/dist/auth.compile.test.js +0 -201
  153. package/dist/auth.coverage.test.d.ts +0 -1
  154. package/dist/auth.coverage.test.js +0 -202
  155. package/dist/auth.test.d.ts +0 -1
  156. package/dist/auth.test.js +0 -2286
  157. package/dist/betterAuth.test.d.ts +0 -1
  158. package/dist/betterAuth.test.js +0 -181
  159. package/dist/betterAuthApp.test.d.ts +0 -1
  160. package/dist/betterAuthApp.test.js +0 -242
  161. package/dist/betterAuthSetup.test.d.ts +0 -1
  162. package/dist/betterAuthSetup.test.js +0 -762
  163. package/dist/config.test.d.ts +0 -1
  164. package/dist/config.test.js +0 -353
  165. package/dist/configuration.test.d.ts +0 -1
  166. package/dist/configuration.test.js +0 -980
  167. package/dist/configurationPlugin.test.d.ts +0 -1
  168. package/dist/configurationPlugin.test.js +0 -827
  169. package/dist/consentApp.test.d.ts +0 -1
  170. package/dist/consentApp.test.js +0 -1411
  171. package/dist/docLoader.test.d.ts +0 -1
  172. package/dist/docLoader.test.js +0 -137
  173. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  174. package/dist/envConfigurationPlugin.test.js +0 -369
  175. package/dist/errors.test.d.ts +0 -1
  176. package/dist/errors.test.js +0 -607
  177. package/dist/expressServer.test.d.ts +0 -1
  178. package/dist/expressServer.test.js +0 -1249
  179. package/dist/githubAuth.test.d.ts +0 -1
  180. package/dist/githubAuth.test.js +0 -1142
  181. package/dist/httpClient.test.d.ts +0 -1
  182. package/dist/httpClient.test.js +0 -1471
  183. package/dist/logger.test.d.ts +0 -1
  184. package/dist/logger.test.js +0 -685
  185. package/dist/middleware.test.d.ts +0 -1
  186. package/dist/middleware.test.js +0 -241
  187. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  188. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  189. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  190. package/dist/notifiers/slackNotifier.test.js +0 -297
  191. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  192. package/dist/notifiers/zoomNotifier.test.js +0 -373
  193. package/dist/openApi.test.d.ts +0 -1
  194. package/dist/openApi.test.js +0 -620
  195. package/dist/openApiBuilder.test.d.ts +0 -1
  196. package/dist/openApiBuilder.test.js +0 -599
  197. package/dist/openApiEtag.test.d.ts +0 -1
  198. package/dist/openApiEtag.test.js +0 -86
  199. package/dist/openApiValidator.test.d.ts +0 -1
  200. package/dist/openApiValidator.test.js +0 -795
  201. package/dist/permissions.middleware.test.d.ts +0 -1
  202. package/dist/permissions.middleware.test.js +0 -308
  203. package/dist/permissions.test.d.ts +0 -1
  204. package/dist/permissions.test.js +0 -439
  205. package/dist/plugins.test.d.ts +0 -1
  206. package/dist/plugins.test.js +0 -902
  207. package/dist/populate.test.d.ts +0 -1
  208. package/dist/populate.test.js +0 -370
  209. package/dist/realtime/realtime.test.d.ts +0 -10
  210. package/dist/realtime/realtime.test.js +0 -4213
  211. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  212. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  213. package/dist/requestContext.test.d.ts +0 -1
  214. package/dist/requestContext.test.js +0 -412
  215. package/dist/scriptRunner.test.d.ts +0 -1
  216. package/dist/scriptRunner.test.js +0 -386
  217. package/dist/secretProviders.test.d.ts +0 -1
  218. package/dist/secretProviders.test.js +0 -726
  219. package/dist/syncConsents.test.d.ts +0 -1
  220. package/dist/syncConsents.test.js +0 -522
  221. package/dist/terrenoApp.test.d.ts +0 -1
  222. package/dist/terrenoApp.test.js +0 -489
  223. package/dist/tests/bunSetup.d.ts +0 -1
  224. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  225. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  226. package/dist/tests/testEnv.d.ts +0 -0
  227. package/dist/tests/testEnv.js +0 -6
  228. package/dist/transformers.test.d.ts +0 -1
  229. package/dist/transformers.test.js +0 -423
  230. package/dist/utils.test.d.ts +0 -1
  231. package/dist/utils.test.js +0 -242
  232. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
@@ -1,15 +1,18 @@
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 mongoose, {Schema} from "mongoose";
6
4
  import supertest from "supertest";
7
5
  import type TestAgent from "supertest/lib/agent";
8
6
 
9
- import {addAuthRoutes, setupAuth} from "./auth";
10
- import {ConfigurationApp} from "./configurationApp";
7
+ import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
8
+ import {
9
+ ConfigurationApp,
10
+ type ConfigurationAppOptions,
11
+ type ConfigurationMetaResponse,
12
+ } from "./configurationApp";
11
13
  import {type ConfigurationModel, configurationPlugin} from "./configurationPlugin";
12
14
  import {apiErrorMiddleware, apiUnauthorizedMiddleware} from "./errors";
15
+ import type {PermissionMethod} from "./permissions";
13
16
  import {createdUpdatedPlugin} from "./plugins";
14
17
  import {authAsUser, getBaseServer, setupDb, UserModel} from "./tests";
15
18
 
@@ -92,13 +95,31 @@ const ScalarConfig = (mongoose.models.ScalarConfig ||
92
95
 
93
96
  // -- Helpers --
94
97
 
98
+ /** APIError exposes `title`; plain errors only `message`. */
99
+ const errorText = (error: unknown): string => {
100
+ if (error && typeof error === "object" && "title" in error && typeof error.title === "string") {
101
+ return error.title;
102
+ }
103
+ return error instanceof Error ? error.message : String(error);
104
+ };
105
+
106
+ const findSection = (
107
+ body: ConfigurationMetaResponse,
108
+ name: string
109
+ ): ConfigurationMetaResponse["sections"][number] | undefined =>
110
+ body.sections.find((s) => s.name === name);
111
+
112
+ /** Hook payloads are untyped bags of section values. */
113
+ const section = (payload: Record<string, unknown>, name: string): Record<string, unknown> =>
114
+ payload[name] as Record<string, unknown>;
115
+
95
116
  const buildApp = (
96
- configModel: mongoose.Model<any>,
97
- options?: Partial<Omit<ConstructorParameters<typeof ConfigurationApp>[0], "model">>
117
+ configModel: ConfigurationAppOptions["model"],
118
+ options?: Partial<Omit<ConfigurationAppOptions, "model">>
98
119
  ): express.Application => {
99
120
  const app = getBaseServer();
100
- setupAuth(app, UserModel as any);
101
- addAuthRoutes(app, UserModel as any);
121
+ setupAuth(app, UserModel as unknown as AuthUserModel);
122
+ addAuthRoutes(app, UserModel as unknown as AuthUserModel);
102
123
 
103
124
  const configApp = new ConfigurationApp({
104
125
  model: configModel,
@@ -201,8 +222,8 @@ describe("configurationPlugin", () => {
201
222
  try {
202
223
  await TestConfig.create({});
203
224
  throw new Error("Should have thrown");
204
- } catch (error: any) {
205
- expect(error.title || error.message).toInclude("Only one configuration document");
225
+ } catch (error) {
226
+ expect(errorText(error)).toInclude("Only one configuration document");
206
227
  }
207
228
  });
208
229
  });
@@ -213,8 +234,8 @@ describe("configurationPlugin", () => {
213
234
  try {
214
235
  await TestConfig.deleteOne({});
215
236
  throw new Error("Should have thrown");
216
- } catch (error: any) {
217
- expect(error.title || error.message).toInclude("Cannot hard-delete");
237
+ } catch (error) {
238
+ expect(errorText(error)).toInclude("Cannot hard-delete");
218
239
  }
219
240
  });
220
241
 
@@ -223,8 +244,8 @@ describe("configurationPlugin", () => {
223
244
  try {
224
245
  await TestConfig.deleteMany({});
225
246
  throw new Error("Should have thrown");
226
- } catch (error: any) {
227
- expect(error.title || error.message).toInclude("Cannot hard-delete");
247
+ } catch (error) {
248
+ expect(errorText(error)).toInclude("Cannot hard-delete");
228
249
  }
229
250
  });
230
251
 
@@ -233,8 +254,8 @@ describe("configurationPlugin", () => {
233
254
  try {
234
255
  await TestConfig.findOneAndDelete({});
235
256
  throw new Error("Should have thrown");
236
- } catch (error: any) {
237
- expect(error.title || error.message).toInclude("Cannot hard-delete");
257
+ } catch (error) {
258
+ expect(errorText(error)).toInclude("Cannot hard-delete");
238
259
  }
239
260
  });
240
261
  });
@@ -295,17 +316,17 @@ describe("ConfigurationApp routes", () => {
295
316
  expect(res.body.sections).toBeDefined();
296
317
  expect(res.body.sections.length).toBeGreaterThan(0);
297
318
 
298
- const generalSection = res.body.sections.find((s: any) => s.name === "general");
319
+ const generalSection = findSection(res.body, "general");
299
320
  expect(generalSection).toBeDefined();
300
- expect(generalSection.fields.appName).toBeDefined();
301
- expect(generalSection.fields.appName.type).toBe("string");
321
+ expect(generalSection?.fields.appName).toBeDefined();
322
+ expect(generalSection?.fields.appName.type).toBe("string");
302
323
  });
303
324
 
304
325
  it("marks secret fields in metadata", async () => {
305
326
  const res = await adminAgent.get("/configuration/meta").expect(200);
306
- const intSection = res.body.sections.find((s: any) => s.name === "integrations");
307
- expect(intSection.fields.apiKey.secret).toBe(true);
308
- expect(intSection.fields.webhookUrl.secret).toBeFalsy();
327
+ const intSection = findSection(res.body, "integrations");
328
+ expect(intSection?.fields.apiKey.secret).toBe(true);
329
+ expect(intSection?.fields.webhookUrl.secret).toBeFalsy();
309
330
  });
310
331
 
311
332
  it("returns 403 for non-admin", async () => {
@@ -326,7 +347,7 @@ describe("ConfigurationApp routes", () => {
326
347
 
327
348
  it("redacts secret fields", async () => {
328
349
  // Set a secret value first
329
- await (TestConfig as any).updateConfig({integrations: {apiKey: "super-secret-key"}});
350
+ await TestConfig.updateConfig({integrations: {apiKey: "super-secret-key"}});
330
351
  const res = await adminAgent.get("/configuration").expect(200);
331
352
  expect(res.body.data.integrations.apiKey).toBe("********");
332
353
  expect(res.body.data.integrations.webhookUrl).toBe("https://example.com/hook");
@@ -362,7 +383,7 @@ describe("ConfigurationApp routes", () => {
362
383
  expect(res.body.data.integrations.webhookUrl).toBe("https://changed.example.com");
363
384
 
364
385
  // Confirm the raw stored document holds no secret value.
365
- const stored = await (TestConfig as any).getConfig();
386
+ const stored = await TestConfig.getConfig();
366
387
  expect(stored.integrations.apiKey).toBe("");
367
388
  });
368
389
 
@@ -387,9 +408,9 @@ describe("ConfigurationApp routes", () => {
387
408
  });
388
409
 
389
410
  it("does not mutate the stored config document's secret fields", async () => {
390
- await (TestConfig as any).getConfig();
411
+ await TestConfig.getConfig();
391
412
  await adminAgent.post("/configuration/list-secrets").expect(200);
392
- const stored = await (TestConfig as any).getConfig();
413
+ const stored = await TestConfig.getConfig();
393
414
  // list-secrets must never write resolved values into the document.
394
415
  expect(stored.integrations.apiKey).toBe("");
395
416
  });
@@ -419,11 +440,11 @@ describe("ConfigurationApp with scalar fields", () => {
419
440
 
420
441
  it("puts scalar fields into __root__ section", async () => {
421
442
  const res = await adminAgent.get("/configuration/meta").expect(200);
422
- const rootSection = res.body.sections.find((s: any) => s.name === "__root__");
443
+ const rootSection = findSection(res.body, "__root__");
423
444
  expect(rootSection).toBeDefined();
424
- expect(rootSection.displayName).toBe("General");
425
- expect(rootSection.fields.siteName).toBeDefined();
426
- expect(rootSection.fields.debugMode).toBeDefined();
445
+ expect(rootSection?.displayName).toBe("General");
446
+ expect(rootSection?.fields.siteName).toBeDefined();
447
+ expect(rootSection?.fields.debugMode).toBeDefined();
427
448
  });
428
449
  });
429
450
 
@@ -442,8 +463,8 @@ describe("ConfigurationApp with field overrides", () => {
442
463
 
443
464
  it("applies widget overrides to metadata", async () => {
444
465
  const res = await adminAgent.get("/configuration/meta").expect(200);
445
- const intSection = res.body.sections.find((s: any) => s.name === "integrations");
446
- expect(intSection.fields.webhookUrl.widget).toBe("url");
466
+ const intSection = findSection(res.body, "integrations");
467
+ expect(intSection?.fields.webhookUrl.widget).toBe("url");
447
468
  });
448
469
  });
449
470
 
@@ -453,7 +474,7 @@ describe("ConfigurationApp with custom permissions", () => {
453
474
  let notAdminAgent: TestAgent;
454
475
 
455
476
  // Terreno-style permission: any authenticated user (not just admins).
456
- const isAuthenticated = (_method: any, user?: any): boolean => Boolean(user?.id);
477
+ const isAuthenticated: PermissionMethod<unknown> = (_method, user) => Boolean(user?.id);
457
478
 
458
479
  beforeEach(async () => {
459
480
  await setupDb();
@@ -541,13 +562,13 @@ describe("ConfigurationApp with update hooks", () => {
541
562
  expect(res.body.data.general.appName).toBe("Safe");
542
563
  expect(res.body.data.integrations.apiKey).toBe("");
543
564
 
544
- const stored = await (TestConfig as any).getConfig();
565
+ const stored = await TestConfig.getConfig();
545
566
  expect(stored.integrations.apiKey).toBe("");
546
567
  });
547
568
 
548
569
  it("runs postUpdate with redacted config and previous value", async () => {
549
570
  // Seed a secret so we can confirm it is redacted in hook payloads.
550
- await (TestConfig as any).updateConfig({integrations: {apiKey: "should-not-leak"}});
571
+ await TestConfig.updateConfig({integrations: {apiKey: "should-not-leak"}});
551
572
  await adminAgent
552
573
  .patch("/configuration")
553
574
  .send({general: {appName: "Audited"}})
@@ -555,10 +576,10 @@ describe("ConfigurationApp with update hooks", () => {
555
576
 
556
577
  expect(postUpdateCalls).toHaveLength(1);
557
578
  const {config, prev} = postUpdateCalls[0];
558
- expect((config.general as any).appName).toBe("Audited");
579
+ expect(section(config, "general").appName).toBe("Audited");
559
580
  // Secret values must be redacted in both payloads.
560
- expect((config.integrations as any).apiKey).toBe("********");
561
- expect((prev.integrations as any).apiKey).toBe("********");
581
+ expect(section(config, "integrations").apiKey).toBe("********");
582
+ expect(section(prev, "integrations").apiKey).toBe("********");
562
583
  expect(JSON.stringify(postUpdateCalls)).not.toContain("should-not-leak");
563
584
  });
564
585
  });
@@ -1,10 +1,12 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {afterAll, beforeAll, beforeEach, describe, expect, it, spyOn} from "bun:test";
4
2
  import mongoose, {model, Schema} from "mongoose";
5
- import type {SecretProvider} from "./configurationPlugin";
3
+ import type {ConfigurationModel, Paths, SecretProvider} from "./configurationPlugin";
6
4
  import {configurationPlugin, flattenToDotPaths} from "./configurationPlugin";
7
- import {isDeletedPlugin} from "./plugins";
5
+ import type {APIError} from "./errors";
6
+ import {type FindOneOrNonePlugin, type IsDeleted, isDeletedPlugin} from "./plugins";
7
+
8
+ /** A configuration model as created by the plugin, including the findOneOrNone static it adds. */
9
+ type ConfigModel<T extends object> = ConfigurationModel<T> & FindOneOrNonePlugin<T>;
8
10
 
9
11
  // --- Test schema with secret fields ---
10
12
 
@@ -57,36 +59,58 @@ const testConfigSchema = new Schema<TestConfig>({
57
59
 
58
60
  testConfigSchema.plugin(configurationPlugin);
59
61
 
60
- const TestConfigModel = model("TestConfiguration", testConfigSchema) as any;
62
+ const TestConfigModel = model<TestConfig, ConfigModel<TestConfig>>(
63
+ "TestConfiguration",
64
+ testConfigSchema
65
+ );
61
66
 
62
67
  // --- Simple schema for singleton tests ---
63
68
 
64
- const simpleSchema = new Schema({
69
+ interface SimpleConfig {
70
+ value: string;
71
+ }
72
+
73
+ const simpleSchema = new Schema<SimpleConfig>({
65
74
  value: {default: "default", description: "A value", type: String},
66
75
  });
67
76
  simpleSchema.plugin(configurationPlugin);
68
- const SimpleConfigModel = model("SimpleConfiguration", simpleSchema) as any;
77
+ const SimpleConfigModel = model<SimpleConfig, ConfigModel<SimpleConfig>>(
78
+ "SimpleConfiguration",
79
+ simpleSchema
80
+ );
69
81
 
70
82
  // --- Schema opting into the _singleton unique index ---
71
83
 
72
- const indexedSchema = new Schema({
84
+ const indexedSchema = new Schema<SimpleConfig>({
73
85
  value: {default: "default", description: "A value", type: String},
74
86
  });
75
87
  indexedSchema.plugin(configurationPlugin, {enforceSingletonIndex: true});
76
- const IndexedConfigModel = model("IndexedConfiguration", indexedSchema) as any;
88
+ const IndexedConfigModel = model<SimpleConfig, ConfigModel<SimpleConfig>>(
89
+ "IndexedConfiguration",
90
+ indexedSchema
91
+ );
77
92
 
78
93
  // --- Soft-delete-aware schema ---
79
94
 
80
- const softDeleteSchema = new Schema({
95
+ interface SoftDeleteConfig extends SimpleConfig, IsDeleted {}
96
+
97
+ const softDeleteSchema = new Schema<SoftDeleteConfig>({
81
98
  value: {default: "default", description: "A value", type: String},
82
99
  });
83
100
  softDeleteSchema.plugin(configurationPlugin);
84
101
  softDeleteSchema.plugin(isDeletedPlugin);
85
- const SoftDeleteConfigModel = model("SoftDeleteConfiguration", softDeleteSchema) as any;
102
+ const SoftDeleteConfigModel = model<SoftDeleteConfig, ConfigModel<SoftDeleteConfig>>(
103
+ "SoftDeleteConfiguration",
104
+ softDeleteSchema
105
+ );
86
106
 
87
107
  // --- Schema with a validated field (enum) for runValidators coverage ---
88
108
 
89
- const validatedSchema = new Schema({
109
+ interface ValidatedConfig {
110
+ level: string;
111
+ }
112
+
113
+ const validatedSchema = new Schema<ValidatedConfig>({
90
114
  level: {
91
115
  default: "low",
92
116
  description: "Severity level",
@@ -95,26 +119,25 @@ const validatedSchema = new Schema({
95
119
  },
96
120
  });
97
121
  validatedSchema.plugin(configurationPlugin);
98
- const ValidatedConfigModel = model("ValidatedConfiguration", validatedSchema) as any;
122
+ const ValidatedConfigModel = model<ValidatedConfig, ConfigModel<ValidatedConfig>>(
123
+ "ValidatedConfiguration",
124
+ validatedSchema
125
+ );
99
126
 
100
127
  describe("configurationPlugin", () => {
101
128
  describe("schema setup", () => {
102
129
  it("does not add a _singleton index by default", () => {
103
130
  const indexes = SimpleConfigModel.schema.indexes();
104
- const singletonIndex = indexes.find(
105
- ([fields]: [Record<string, any>]) => fields._singleton !== undefined
106
- );
131
+ const singletonIndex = indexes.find(([fields]) => fields._singleton !== undefined);
107
132
  expect(singletonIndex).toBeUndefined();
108
133
  expect(SimpleConfigModel.schema.path("_singleton")).toBeUndefined();
109
134
  });
110
135
 
111
136
  it("adds a _singleton field with unique index when enforceSingletonIndex is true", () => {
112
137
  const indexes = IndexedConfigModel.schema.indexes();
113
- const singletonIndex = indexes.find(
114
- ([fields]: [Record<string, any>]) => fields._singleton !== undefined
115
- );
138
+ const singletonIndex = indexes.find(([fields]) => fields._singleton !== undefined);
116
139
  expect(singletonIndex).toBeDefined();
117
- expect(singletonIndex[1].unique).toBe(true);
140
+ expect(singletonIndex?.[1]?.unique).toBe(true);
118
141
  });
119
142
 
120
143
  it("adds getConfig static", () => {
@@ -137,22 +160,22 @@ describe("configurationPlugin", () => {
137
160
  describe("getSecretFields", () => {
138
161
  it("discovers top-level secret fields", () => {
139
162
  const secrets = TestConfigModel.getSecretFields();
140
- const apiKeySecret = secrets.find((s: {path: string}) => s.path === "apiKey");
163
+ const apiKeySecret = secrets.find((s) => s.path === "apiKey");
141
164
  expect(apiKeySecret).toBeDefined();
142
- expect(apiKeySecret.secretName).toBe("ext-api-key");
165
+ expect(apiKeySecret?.secretName).toBe("ext-api-key");
143
166
  });
144
167
 
145
168
  it("discovers nested secret fields", () => {
146
169
  const secrets = TestConfigModel.getSecretFields();
147
- const nestedSecret = secrets.find((s: {path: string}) => s.path === "nested.secretToken");
170
+ const nestedSecret = secrets.find((s) => s.path === "nested.secretToken");
148
171
  expect(nestedSecret).toBeDefined();
149
- expect(nestedSecret.secretName).toBe("nested-token");
150
- expect(nestedSecret.secretProvider).toBe("vault");
172
+ expect(nestedSecret?.secretName).toBe("nested-token");
173
+ expect(nestedSecret?.secretProvider).toBe("vault");
151
174
  });
152
175
 
153
176
  it("does not include non-secret fields", () => {
154
177
  const secrets = TestConfigModel.getSecretFields();
155
- const nonSecret = secrets.find((s: {path: string}) => s.path === "appName");
178
+ const nonSecret = secrets.find((s) => s.path === "appName");
156
179
  expect(nonSecret).toBeUndefined();
157
180
  });
158
181
 
@@ -211,7 +234,7 @@ describe("configurationPlugin", () => {
211
234
  });
212
235
 
213
236
  it("passes the discovered secret version to the provider", async () => {
214
- const versionedSchema = new Schema({
237
+ const versionedSchema = new Schema<{token: string}>({
215
238
  token: {
216
239
  default: "",
217
240
  description: "Pinned secret",
@@ -222,7 +245,10 @@ describe("configurationPlugin", () => {
222
245
  },
223
246
  });
224
247
  versionedSchema.plugin(configurationPlugin);
225
- const VersionedModel = model("VersionedConfiguration", versionedSchema) as any;
248
+ const VersionedModel = model<{token: string}, ConfigModel<{token: string}>>(
249
+ "VersionedConfiguration",
250
+ versionedSchema
251
+ );
226
252
 
227
253
  const received: Array<{name: string; version?: string}> = [];
228
254
  const provider: SecretProvider = {
@@ -311,7 +337,7 @@ describe("configurationPlugin", () => {
311
337
  }
312
338
  const first = await SimpleConfigModel.getConfig();
313
339
  const second = await SimpleConfigModel.getConfig();
314
- expect(first._id.toString()).toBe(second._id.toString());
340
+ expect(String(first._id)).toBe(String(second._id));
315
341
  });
316
342
 
317
343
  it("prevents creating a second document via save", async () => {
@@ -327,14 +353,14 @@ describe("configurationPlugin", () => {
327
353
  if (!dbConnected) {
328
354
  return;
329
355
  }
330
- const existing = (await SimpleConfigModel.getConfig()) as {_id: {toString(): string}};
356
+ const existing = await SimpleConfigModel.getConfig();
331
357
  // Simulate a race: the initial lookup misses, so getConfig attempts a create
332
358
  // that the pre-save singleton guard rejects with a 409. getConfig should then
333
359
  // re-fetch and return the document created by the "other process".
334
360
  const spy = spyOn(SimpleConfigModel, "findOneOrNone").mockResolvedValueOnce(null);
335
361
  try {
336
- const config = (await SimpleConfigModel.getConfig()) as {_id: {toString(): string}};
337
- expect(config._id.toString()).toBe(existing._id.toString());
362
+ const config = await SimpleConfigModel.getConfig();
363
+ expect(String(config._id)).toBe(String(existing._id));
338
364
  } finally {
339
365
  spy.mockRestore();
340
366
  }
@@ -362,9 +388,13 @@ describe("configurationPlugin", () => {
362
388
  }
363
389
  await SimpleConfigModel.getConfig();
364
390
  // `value` is a string, so descending into `value.missing` bails out.
365
- expect(await SimpleConfigModel.getConfig("value.missing")).toBeUndefined();
391
+ expect(
392
+ await SimpleConfigModel.getConfig("value.missing" as Paths<SimpleConfig>)
393
+ ).toBeUndefined();
366
394
  // A missing top-level segment also resolves to undefined.
367
- expect(await SimpleConfigModel.getConfig("nope.deeper")).toBeUndefined();
395
+ expect(
396
+ await SimpleConfigModel.getConfig("nope.deeper" as Paths<SimpleConfig>)
397
+ ).toBeUndefined();
368
398
  });
369
399
 
370
400
  it("updates an existing document via updateConfig", async () => {
@@ -411,8 +441,8 @@ describe("configurationPlugin", () => {
411
441
  try {
412
442
  await SimpleConfigModel.deleteOne({}).exec();
413
443
  expect.unreachable("Should have thrown");
414
- } catch (err: any) {
415
- expect(err.title).toMatch(/Cannot hard-delete the configuration document/);
444
+ } catch (err) {
445
+ expect((err as APIError).title).toMatch(/Cannot hard-delete the configuration document/);
416
446
  }
417
447
  });
418
448
 
@@ -424,8 +454,8 @@ describe("configurationPlugin", () => {
424
454
  try {
425
455
  await SimpleConfigModel.findOneAndDelete({}).exec();
426
456
  expect.unreachable("Should have thrown");
427
- } catch (err: any) {
428
- expect(err.title).toMatch(/Cannot hard-delete the configuration document/);
457
+ } catch (err) {
458
+ expect((err as APIError).title).toMatch(/Cannot hard-delete the configuration document/);
429
459
  }
430
460
  });
431
461
 
@@ -437,8 +467,8 @@ describe("configurationPlugin", () => {
437
467
  try {
438
468
  await SimpleConfigModel.deleteMany({}).exec();
439
469
  expect.unreachable("Should have thrown");
440
- } catch (err: any) {
441
- expect(err.title).toMatch(/Cannot hard-delete the configuration document/);
470
+ } catch (err) {
471
+ expect((err as APIError).title).toMatch(/Cannot hard-delete the configuration document/);
442
472
  }
443
473
  });
444
474
  });
@@ -496,7 +526,7 @@ describe("configurationPlugin", () => {
496
526
  // A new non-deleted singleton can now be created
497
527
  const second = await SoftDeleteConfigModel.getConfig();
498
528
  expect(second.deleted).toBe(false);
499
- expect(second._id.toString()).not.toBe(first._id.toString());
529
+ expect(String(second._id)).not.toBe(String(first._id));
500
530
  });
501
531
 
502
532
  it("does not let updateConfig touch a soft-deleted document", async () => {
@@ -511,7 +541,7 @@ describe("configurationPlugin", () => {
511
541
  const updated = await SoftDeleteConfigModel.updateConfig({value: "fresh"});
512
542
  expect(updated.deleted).toBe(false);
513
543
  expect(updated.value).toBe("fresh");
514
- expect(updated._id.toString()).not.toBe(first._id.toString());
544
+ expect(String(updated._id)).not.toBe(String(first._id));
515
545
  });
516
546
  });
517
547
  });
package/src/docLoader.ts CHANGED
@@ -35,8 +35,10 @@ export const loadDocOr404 = async <T>(
35
35
  });
36
36
  }
37
37
  if (!data) {
38
+ const idSchemaType = model.schema?.path("_id");
39
+ const hiddenId = idSchemaType?.instance === "String" ? id : new mongoose.Types.ObjectId(id);
38
40
  const hiddenDoc = await model.collection.findOne({
39
- _id: new mongoose.Types.ObjectId(id),
41
+ _id: hiddenId as never,
40
42
  });
41
43
 
42
44
  const notFoundDetail = `Document ${id} not found for model ${model.modelName}`;
package/src/errors.ts CHANGED
@@ -478,6 +478,39 @@ export const mongooseErrorToAPIError = (err: Error): APIError | null => {
478
478
  return null;
479
479
  };
480
480
 
481
+ /**
482
+ * Picks the error to throw for something caught in a hook, transformer, or Mongoose middleware.
483
+ * An `APIError` is passed through untouched so its status, code, detail, and meta reach the client;
484
+ * anything else is wrapped in the given framework error. `wrapper` may override any field,
485
+ * including `detail`, which defaults to the caught error's text.
486
+ */
487
+ export const passthroughOrWrap = (error: unknown, wrapper: APIErrorOptions): APIError => {
488
+ if (isAPIError(error)) {
489
+ return error;
490
+ }
491
+ return new APIError({
492
+ cause: error,
493
+ detail: errorDetail(error),
494
+ disableExternalErrorTracking: getDisableExternalErrorTracking(error),
495
+ ...wrapper,
496
+ });
497
+ };
498
+
499
+ /**
500
+ * `passthroughOrWrap` for write paths (`model.create`, `doc.save`). Mongoose validation and cast
501
+ * errors are converted first so their per-field messages survive as `meta.fields` instead of being
502
+ * flattened into the wrapper's `detail`.
503
+ */
504
+ export const passthroughOrWrapWrite = (error: unknown, wrapper: APIErrorOptions): APIError => {
505
+ if (!isAPIError(error) && error instanceof Error) {
506
+ const converted = mongooseErrorToAPIError(error);
507
+ if (converted) {
508
+ return converted;
509
+ }
510
+ }
511
+ return passthroughOrWrap(error, wrapper);
512
+ };
513
+
481
514
  // Logs the error (warn for 4xx client errors, error for 5xx server errors) and captures it with
482
515
  // Sentry unless external tracking is disabled. Fingerprints on the logical error type
483
516
  // (name + code/title + status) so unrelated errors constructed at the same framework lines don't
@@ -833,7 +833,7 @@ describe("expressServer", () => {
833
833
  }
834
834
  });
835
835
 
836
- it("handles listen errors", () => {
836
+ it("handles listen errors", async () => {
837
837
  const configureApp = (): void => {};
838
838
  const http = require("node:http") as typeof import("node:http");
839
839
  const originalListen = http.Server.prototype.listen;
@@ -849,6 +849,12 @@ describe("expressServer", () => {
849
849
  skipListen: false,
850
850
  userModel: typedUserModel,
851
851
  }).start();
852
+ // start() defers listen behind an awaited ensureSyncIndexes(), so the
853
+ // exit-on-listen-error path settles asynchronously.
854
+ const deadline = Date.now() + 2_000;
855
+ while (exit.mock.calls.length === 0 && Date.now() < deadline) {
856
+ await new Promise((resolve) => setTimeout(resolve, 5));
857
+ }
852
858
  expect(exit).toHaveBeenCalledWith(1);
853
859
  } finally {
854
860
  http.Server.prototype.listen = originalListen;
package/src/index.ts CHANGED
@@ -29,6 +29,9 @@ export * from "./permissions";
29
29
  export * from "./plugins";
30
30
  export * from "./populate";
31
31
  export {
32
+ type AuthorizedEmitEntry,
33
+ emitPayloadToAuthorizedRoom,
34
+ emitSyncDeltaForChange,
32
35
  startChangeStreamWatcher,
33
36
  stopChangeStreamWatcher,
34
37
  } from "./realtime/changeStreamWatcher";
@@ -57,6 +60,32 @@ export {
57
60
  type RealtimeRegistryEntry,
58
61
  registerRealtime,
59
62
  } from "./realtime/registry";
63
+ export {
64
+ DEFAULT_SESSION_REVALIDATION_INTERVAL_MS,
65
+ loadFullUserForSocket,
66
+ type RevalidatableSocket,
67
+ type RevalidationOutcome,
68
+ reresolveSyncRoomsForSocket,
69
+ revalidateSocketSession,
70
+ runSessionRevalidationSweep,
71
+ type SessionRevalidationHandle,
72
+ type SessionRevalidationOptions,
73
+ startSessionRevalidationSweep,
74
+ } from "./realtime/sessionRevalidation";
75
+ export {
76
+ type AuthenticatableSocket,
77
+ type BetterAuthSocketOptions,
78
+ createBetterAuthValidator,
79
+ createLegacyJwtValidator,
80
+ createSocketAuthMiddleware,
81
+ type SocketAuthValidator,
82
+ } from "./realtime/socketAuth";
83
+ export {
84
+ type DecodedRealtimeToken,
85
+ getSocketUser,
86
+ type SocketDataBag,
87
+ type SocketWithDecodedToken,
88
+ } from "./realtime/socketUser";
60
89
  export type {
61
90
  ChangeStreamConfig,
62
91
  DocumentSubscription,
@@ -68,6 +97,19 @@ export type {
68
97
  export * from "./requestContext";
69
98
  export * from "./scriptRunner";
70
99
  export * from "./secretProviders";
100
+ export * from "./sync/executors";
101
+ export * from "./sync/models";
102
+ export * from "./sync/mutationHandler";
103
+ export * from "./sync/registry";
104
+ export * from "./sync/routes";
105
+ export * from "./sync/scripts/compactTombstones";
106
+ export * from "./sync/serialize";
107
+ export * from "./sync/socketHandlers";
108
+ export * from "./sync/streams";
109
+ export * from "./sync/syncApp";
110
+ export * from "./sync/syncBatch";
111
+ export * from "./sync/syncSeqPlugin";
112
+ export * from "./sync/types";
71
113
  export * from "./syncConsents";
72
114
  export * from "./terrenoApp";
73
115
  export * from "./terrenoPlugin";