@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
@@ -132,6 +132,7 @@ export type ConfigurationPostUpdateHook = (
132
132
  */
133
133
  export interface ConfigurationAppOptions {
134
134
  /** The Mongoose model with configurationPlugin applied. */
135
+ // noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
135
136
  // biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
136
137
  model: Model<any>;
137
138
  /** Base path for configuration routes. Defaults to "/configuration". */
@@ -478,6 +479,7 @@ export class ConfigurationApp implements TerrenoPlugin {
478
479
  * Top-level fields with subschemas become sections.
479
480
  * Top-level scalar fields go into a "General" section.
480
481
  */
482
+ // noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
481
483
  // biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
482
484
  private buildMetadata(_model: Model<any>, schema: Schema): ConfigurationMetaResponse {
483
485
  const sections: ConfigSectionMeta[] = [];
@@ -1,5 +1,6 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
- import {afterAll, beforeAll, beforeEach, describe, expect, it} from "bun:test";
3
+ import {afterAll, beforeAll, beforeEach, describe, expect, it, spyOn} from "bun:test";
3
4
  import mongoose, {model, Schema} from "mongoose";
4
5
  import type {SecretProvider} from "./configurationPlugin";
5
6
  import {configurationPlugin, flattenToDotPaths} from "./configurationPlugin";
@@ -322,6 +323,50 @@ describe("configurationPlugin", () => {
322
323
  await expect(duplicate.save()).rejects.toThrow();
323
324
  });
324
325
 
326
+ it("re-fetches the existing singleton when a concurrent create hits a 409", async () => {
327
+ if (!dbConnected) {
328
+ return;
329
+ }
330
+ const existing = (await SimpleConfigModel.getConfig()) as {_id: {toString(): string}};
331
+ // Simulate a race: the initial lookup misses, so getConfig attempts a create
332
+ // that the pre-save singleton guard rejects with a 409. getConfig should then
333
+ // re-fetch and return the document created by the "other process".
334
+ const spy = spyOn(SimpleConfigModel, "findOneOrNone").mockResolvedValueOnce(null);
335
+ try {
336
+ const config = (await SimpleConfigModel.getConfig()) as {_id: {toString(): string}};
337
+ expect(config._id.toString()).toBe(existing._id.toString());
338
+ } finally {
339
+ spy.mockRestore();
340
+ }
341
+ });
342
+
343
+ it("rethrows non-409 errors raised while creating the singleton", async () => {
344
+ if (!dbConnected) {
345
+ return;
346
+ }
347
+ const findSpy = spyOn(SimpleConfigModel, "findOneOrNone").mockResolvedValueOnce(null);
348
+ const saveSpy = spyOn(SimpleConfigModel.prototype, "save").mockRejectedValueOnce(
349
+ new Error("unexpected save failure")
350
+ );
351
+ try {
352
+ await expect(SimpleConfigModel.getConfig()).rejects.toThrow("unexpected save failure");
353
+ } finally {
354
+ findSpy.mockRestore();
355
+ saveSpy.mockRestore();
356
+ }
357
+ });
358
+
359
+ it("returns undefined for a dotted key that traverses a non-object value", async () => {
360
+ if (!dbConnected) {
361
+ return;
362
+ }
363
+ await SimpleConfigModel.getConfig();
364
+ // `value` is a string, so descending into `value.missing` bails out.
365
+ expect(await SimpleConfigModel.getConfig("value.missing")).toBeUndefined();
366
+ // A missing top-level segment also resolves to undefined.
367
+ expect(await SimpleConfigModel.getConfig("nope.deeper")).toBeUndefined();
368
+ });
369
+
325
370
  it("updates an existing document via updateConfig", async () => {
326
371
  if (!dbConnected) {
327
372
  return;
@@ -1,3 +1,4 @@
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 express from "express";
@@ -52,7 +52,8 @@ describe("loadDocOr404", () => {
52
52
  expect(error).toBeInstanceOf(APIError);
53
53
  const apiError = error as APIError;
54
54
  expect(apiError.status).toBe(404);
55
- expect(apiError.meta).toBeUndefined();
55
+ expect(apiError.title).toBe("Document not found");
56
+ expect(apiError.meta).toEqual({});
56
57
  }
57
58
  });
58
59
  });
package/src/docLoader.ts CHANGED
@@ -1,8 +1,7 @@
1
- import * as Sentry from "@sentry/bun";
2
1
  import mongoose, {type Model} from "mongoose";
3
2
 
4
3
  import {addPopulateToQuery} from "./api";
5
- import {APIError, isAPIError} from "./errors";
4
+ import {APIError, isAPIError, NotFoundError} from "./errors";
6
5
  import type {PopulatePath} from "./populate";
7
6
 
8
7
  /**
@@ -16,8 +15,7 @@ export const loadDocOr404 = async <T>(
16
15
  ): Promise<T> => {
17
16
  const builtQuery = model.findById(id);
18
17
  const populatedQuery = addPopulateToQuery(
19
- // biome-ignore lint/suspicious/noExplicitAny: Query types vary based on populate paths
20
- builtQuery as any,
18
+ builtQuery as unknown as Parameters<typeof addPopulateToQuery>[0],
21
19
  populatePaths
22
20
  );
23
21
  let data: T | null;
@@ -28,9 +26,11 @@ export const loadDocOr404 = async <T>(
28
26
  throw error;
29
27
  }
30
28
  throw new APIError({
31
- error: error as Error,
29
+ cause: error,
30
+ code: "get-error",
31
+ detail: `GET failed on ${id}`,
32
32
  status: 500,
33
- title: `GET failed on ${id}`,
33
+ title: "GET error",
34
34
  });
35
35
  }
36
36
  if (!data) {
@@ -38,14 +38,13 @@ export const loadDocOr404 = async <T>(
38
38
  _id: new mongoose.Types.ObjectId(id),
39
39
  });
40
40
 
41
+ const notFoundDetail = `Document ${id} not found for model ${model.modelName}`;
42
+
41
43
  if (!hiddenDoc) {
42
- Sentry.captureMessage(`Document ${id} not found for model ${model.modelName}`);
43
- const error = new APIError({
44
- status: 404,
45
- title: `Document ${id} not found for model ${model.modelName}`,
44
+ throw new NotFoundError({
45
+ detail: notFoundDetail,
46
+ title: "Document not found",
46
47
  });
47
- error.meta = undefined;
48
- throw error;
49
48
  }
50
49
 
51
50
  let reason: {[key: string]: string} | null = null;
@@ -58,18 +57,16 @@ export const loadDocOr404 = async <T>(
58
57
  }
59
58
 
60
59
  if (!reason) {
61
- const error = new APIError({
62
- status: 404,
63
- title: `Document ${id} not found for model ${model.modelName}`,
60
+ throw new NotFoundError({
61
+ detail: notFoundDetail,
62
+ title: "Document not found",
64
63
  });
65
- error.meta = undefined;
66
- throw error;
67
64
  }
68
- throw new APIError({
65
+ throw new NotFoundError({
66
+ detail: notFoundDetail,
69
67
  disableExternalErrorTracking: true,
70
68
  meta: reason,
71
- status: 404,
72
- title: `Document ${id} not found for model ${model.modelName}`,
69
+ title: "Document not found",
73
70
  });
74
71
  }
75
72
 
@@ -60,6 +60,7 @@ const mapToObject = (
60
60
 
61
61
  const refreshFromDoc = async (Model: Model<unknown>): Promise<void> => {
62
62
  try {
63
+ // noExplicitAny: doc shape determined by consumer schema
63
64
  // biome-ignore lint/suspicious/noExplicitAny: doc shape determined by consumer schema
64
65
  const doc = (await findOneOrNoneFor(Model as Model<any>, {})) as
65
66
  | (Document & {env?: Map<string, string> | Record<string, string>})
@@ -72,6 +73,7 @@ const refreshFromDoc = async (Model: Model<unknown>): Promise<void> => {
72
73
  }
73
74
  };
74
75
 
76
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
75
77
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
76
78
  export const envConfigurationPlugin = (schema: Schema<any, any, any, any>): void => {
77
79
  schema.add({
@@ -1,4 +1,4 @@
1
- import {beforeEach, describe, expect, it, mock} from "bun:test";
1
+ import {beforeEach, describe, expect, it, mock, spyOn} from "bun:test";
2
2
  import * as Sentry from "@sentry/bun";
3
3
  import type {NextFunction, Request, Response} from "express";
4
4
  import mongoose, {Schema} from "mongoose";
@@ -7,12 +7,19 @@ import {
7
7
  APIError,
8
8
  apiErrorMiddleware,
9
9
  apiUnauthorizedMiddleware,
10
+ BadRequestError,
11
+ ConflictError,
10
12
  errorMessage,
11
13
  errorStack,
12
14
  errorsPlugin,
15
+ ForbiddenError,
13
16
  getAPIErrorBody,
14
17
  getDisableExternalErrorTracking,
18
+ InternalServerError,
15
19
  isAPIError,
20
+ NotFoundError,
21
+ UnauthorizedError,
22
+ ValidationError,
16
23
  } from "./errors";
17
24
 
18
25
  interface MockResponse {
@@ -44,7 +51,6 @@ describe("APIError", () => {
44
51
  });
45
52
 
46
53
  expect(error).toBeInstanceOf(Error);
47
- expect(error.name).toBe("APIError");
48
54
  expect(error.title).toBe("Validation failed");
49
55
  expect(error.detail).toBe("Email is invalid");
50
56
  expect(error.code).toBe("validation-failed");
@@ -62,16 +68,48 @@ describe("APIError", () => {
62
68
  expect(error.meta).toEqual({requestId: "req-1"});
63
69
  });
64
70
 
65
- it("includes the title and detail in the error message", () => {
71
+ it("uses the title as the message, without detail or stacks", () => {
66
72
  const error = new APIError({detail: "Something exploded", title: "Boom"});
67
- expect(error.message).toBe("Boom: Something exploded");
73
+ expect(error.message).toBe("Boom");
74
+ expect(error.title).toBe("Boom");
68
75
  });
69
76
 
70
- it("includes the wrapped error stack in the message", () => {
77
+ it("exposes the wrapped error as the standard cause", () => {
78
+ const wrapped = new Error("inner");
79
+ const error = new APIError({cause: wrapped, title: "Outer"});
80
+ expect(error.message).toBe("Outer");
81
+ expect(error.cause).toBe(wrapped);
82
+ });
83
+
84
+ it("supports the deprecated error option as a cause alias", () => {
71
85
  const wrapped = new Error("inner");
72
86
  const error = new APIError({error: wrapped, title: "Outer"});
73
- expect(error.message).toContain("Outer");
74
- expect(error.message).toContain(wrapped.stack ?? "");
87
+ expect(error.cause).toBe(wrapped);
88
+ expect(error.error).toBe(wrapped);
89
+ });
90
+
91
+ it("derives the name from the status code", () => {
92
+ expect(new APIError({status: 400, title: "T"}).name).toBe("BadRequestError");
93
+ expect(new APIError({status: 401, title: "T"}).name).toBe("UnauthorizedError");
94
+ expect(new APIError({status: 403, title: "T"}).name).toBe("ForbiddenError");
95
+ expect(new APIError({status: 404, title: "T"}).name).toBe("NotFoundError");
96
+ expect(new APIError({status: 409, title: "T"}).name).toBe("ConflictError");
97
+ expect(new APIError({status: 500, title: "T"}).name).toBe("InternalServerError");
98
+ });
99
+
100
+ it("falls back to APIError for unmapped statuses", () => {
101
+ expect(new APIError({status: 418, title: "T"}).name).toBe("APIError");
102
+ });
103
+
104
+ it("derives the name from the code when provided", () => {
105
+ const error = new APIError({code: "update-admin-error", status: 403, title: "T"});
106
+ expect(error.name).toBe("UpdateAdminError");
107
+ });
108
+
109
+ it("keeps title in sync with message via the getter", () => {
110
+ const error = new APIError({title: "Original"});
111
+ error.message = "Changed";
112
+ expect(error.title).toBe("Changed");
75
113
  });
76
114
 
77
115
  it("defaults status to 500 when status is omitted", () => {
@@ -113,6 +151,57 @@ describe("APIError", () => {
113
151
  });
114
152
  });
115
153
 
154
+ describe("APIError subclasses", () => {
155
+ it("sets the status and name from the subclass", () => {
156
+ const error = new NotFoundError("Todo not found");
157
+ expect(error.status).toBe(404);
158
+ expect(error.name).toBe("NotFoundError");
159
+ expect(error.message).toBe("Todo not found");
160
+ expect(error).toBeInstanceOf(APIError);
161
+ expect(isAPIError(error)).toBe(true);
162
+ });
163
+
164
+ it("accepts full options", () => {
165
+ const cause = new Error("inner");
166
+ const error = new ForbiddenError({cause, detail: "Admins only", title: "Not allowed"});
167
+ expect(error.status).toBe(403);
168
+ expect(error.name).toBe("ForbiddenError");
169
+ expect(error.detail).toBe("Admins only");
170
+ expect(error.cause).toBe(cause);
171
+ });
172
+
173
+ it("keeps the subclass name even when a code is provided", () => {
174
+ const error = new BadRequestError({code: "invalid-cursor", title: "Bad cursor"});
175
+ expect(error.name).toBe("BadRequestError");
176
+ expect(error.status).toBe(400);
177
+ });
178
+
179
+ it("uses ValidationError with a 400 status", () => {
180
+ const error = new ValidationError({fields: {email: "Required"}, title: "Validation failed"});
181
+ expect(error.status).toBe(400);
182
+ expect(error.name).toBe("ValidationError");
183
+ expect(error.meta?.fields).toEqual({email: "Required"});
184
+ });
185
+
186
+ it("derives name from custom subclasses via new.target", () => {
187
+ class PaymentError extends APIError {
188
+ constructor(title: string) {
189
+ super({status: 402, title});
190
+ }
191
+ }
192
+ expect(new PaymentError("declined").name).toBe("PaymentError");
193
+ });
194
+
195
+ it("covers the remaining status subclasses", () => {
196
+ expect(new UnauthorizedError("U").status).toBe(401);
197
+ expect(new UnauthorizedError("U").name).toBe("UnauthorizedError");
198
+ expect(new ConflictError("C").status).toBe(409);
199
+ expect(new ConflictError("C").name).toBe("ConflictError");
200
+ expect(new InternalServerError("I").status).toBe(500);
201
+ expect(new InternalServerError("I").name).toBe("InternalServerError");
202
+ });
203
+ });
204
+
116
205
  describe("isAPIError", () => {
117
206
  it("returns true for an APIError instance", () => {
118
207
  expect(isAPIError(new APIError({title: "Boom"}))).toBe(true);
@@ -122,11 +211,21 @@ describe("isAPIError", () => {
122
211
  expect(isAPIError(new Error("nope"))).toBe(false);
123
212
  });
124
213
 
125
- it("returns true for any error whose name is APIError", () => {
214
+ it("returns true for any error whose name is APIError (transition fallback)", () => {
126
215
  const err = new Error("custom");
127
216
  err.name = "APIError";
128
217
  expect(isAPIError(err)).toBe(true);
129
218
  });
219
+
220
+ it("returns true for a branded error from a duplicate package copy", () => {
221
+ const err = new Error("branded") as Error & {isTerrenoAPIError?: boolean};
222
+ err.isTerrenoAPIError = true;
223
+ expect(isAPIError(err)).toBe(true);
224
+ });
225
+
226
+ it("returns true for subclasses", () => {
227
+ expect(isAPIError(new NotFoundError("missing"))).toBe(true);
228
+ });
130
229
  });
131
230
 
132
231
  describe("getDisableExternalErrorTracking", () => {
@@ -190,10 +289,10 @@ describe("getAPIErrorBody", () => {
190
289
  it("returns title and status by default", () => {
191
290
  const error = new APIError({status: 404, title: "Not Found"});
192
291
  const body = getAPIErrorBody(error);
193
- expect(body).toEqual({meta: {}, status: 404, title: "Not Found"});
292
+ expect(body).toEqual({status: 404, title: "Not Found"});
194
293
  });
195
294
 
196
- it("includes optional fields when set", () => {
295
+ it("includes optional fields when set, including disableExternalErrorTracking when true", () => {
197
296
  const error = new APIError({
198
297
  code: "not-found",
199
298
  detail: "Could not find resource",
@@ -211,18 +310,56 @@ describe("getAPIErrorBody", () => {
211
310
  disableExternalErrorTracking: true,
212
311
  id: "err-1",
213
312
  links: {about: "https://example.com/help"},
214
- meta: {},
215
313
  source: {pointer: "/data/id"},
216
314
  status: 404,
217
315
  title: "Not Found",
218
316
  });
219
317
  });
220
318
 
319
+ it("matches toJSON and excludes name, stack, and cause", () => {
320
+ const error = new APIError({
321
+ cause: new Error("inner"),
322
+ detail: "d",
323
+ status: 404,
324
+ title: "Not Found",
325
+ });
326
+ const body = error.toJSON() as unknown as Record<string, unknown>;
327
+ expect(body).toEqual(getAPIErrorBody(error) as unknown as typeof body);
328
+ expect(body.name).toBeUndefined();
329
+ expect(body.stack).toBeUndefined();
330
+ expect(body.cause).toBeUndefined();
331
+ expect(body.disableExternalErrorTracking).toBeUndefined();
332
+ expect(JSON.parse(JSON.stringify(error))).toEqual(JSON.parse(JSON.stringify(body)));
333
+ });
334
+
335
+ it("exposes deprecated error getter as alias for cause", () => {
336
+ const cause = new Error("inner");
337
+ const error = new APIError({cause, title: "Wrapped"});
338
+ expect(error.error).toBe(cause);
339
+ expect(error.cause).toBe(cause);
340
+ });
341
+
342
+ it("prefers explicit title over message when serializing legacy instances", () => {
343
+ const legacy = new Error("polluted message with stack") as Error & {
344
+ status: number;
345
+ title: string;
346
+ };
347
+ legacy.status = 404;
348
+ legacy.title = "Clean title";
349
+ const body = getAPIErrorBody(legacy as unknown as APIError);
350
+ expect(body.title).toBe("Clean title");
351
+ });
352
+
353
+ it("truncates fractional and invalid status codes to 500", () => {
354
+ expect(new APIError({status: 404.7, title: "x"}).status).toBe(404);
355
+ expect(new APIError({status: Number.NaN, title: "x"}).status).toBe(500);
356
+ expect(new APIError({status: 200, title: "x"}).status).toBe(500);
357
+ });
358
+
221
359
  it("omits empty meta and unset optional fields", () => {
222
360
  const error = new APIError({status: 400, title: "Bad"});
223
- // meta defaults to {} which is truthy, so it is included.
224
361
  const body = getAPIErrorBody(error);
225
- expect(body.meta).toEqual({});
362
+ expect(body.meta).toBeUndefined();
226
363
  expect(body.code).toBeUndefined();
227
364
  expect(body.detail).toBeUndefined();
228
365
  expect(body.id).toBeUndefined();
@@ -314,6 +451,34 @@ describe("apiErrorMiddleware", () => {
314
451
  expect(captureExceptionSpy).toHaveBeenCalledWith(err);
315
452
  });
316
453
 
454
+ it("fingerprints Sentry captures on the logical error type", () => {
455
+ const scope = {
456
+ setContext: mock(() => {}),
457
+ setFingerprint: mock(() => {}),
458
+ setTag: mock(() => {}),
459
+ };
460
+ const withScopeSpy = spyOn(Sentry, "withScope").mockImplementation(((
461
+ callback: (s: unknown) => void
462
+ ) => callback(scope)) as unknown as typeof Sentry.withScope);
463
+ try {
464
+ const err = new APIError({code: "todo-sync-failed", status: 502, title: "Sync failed"});
465
+ apiErrorMiddleware(err, req, res as unknown as Response, next as unknown as NextFunction);
466
+ expect(scope.setFingerprint).toHaveBeenCalledWith([
467
+ "TodoSyncFailed",
468
+ "todo-sync-failed",
469
+ "502",
470
+ ]);
471
+ expect(scope.setTag).toHaveBeenCalledWith("http.status_code", "502");
472
+ expect(scope.setTag).toHaveBeenCalledWith("api_error.code", "todo-sync-failed");
473
+ expect(scope.setContext).toHaveBeenCalledWith(
474
+ "apiError",
475
+ expect.objectContaining({status: 502, title: "Sync failed"})
476
+ );
477
+ } finally {
478
+ withScopeSpy.mockRestore();
479
+ }
480
+ });
481
+
317
482
  it("does not capture the exception when disableExternalErrorTracking is true", () => {
318
483
  const err = new APIError({
319
484
  disableExternalErrorTracking: true,