@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
@@ -1,4 +1,19 @@
1
1
  "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
2
17
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
18
  if (k2 === undefined) k2 = k;
4
19
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -58,7 +73,6 @@ var buildResponse = function () {
58
73
  title: "Validation failed",
59
74
  });
60
75
  (0, bun_test_1.expect)(error).toBeInstanceOf(Error);
61
- (0, bun_test_1.expect)(error.name).toBe("APIError");
62
76
  (0, bun_test_1.expect)(error.title).toBe("Validation failed");
63
77
  (0, bun_test_1.expect)(error.detail).toBe("Email is invalid");
64
78
  (0, bun_test_1.expect)(error.code).toBe("validation-failed");
@@ -75,16 +89,42 @@ var buildResponse = function () {
75
89
  });
76
90
  (0, bun_test_1.expect)(error.meta).toEqual({ requestId: "req-1" });
77
91
  });
78
- (0, bun_test_1.it)("includes the title and detail in the error message", function () {
92
+ (0, bun_test_1.it)("uses the title as the message, without detail or stacks", function () {
79
93
  var error = new errors_1.APIError({ detail: "Something exploded", title: "Boom" });
80
- (0, bun_test_1.expect)(error.message).toBe("Boom: Something exploded");
94
+ (0, bun_test_1.expect)(error.message).toBe("Boom");
95
+ (0, bun_test_1.expect)(error.title).toBe("Boom");
81
96
  });
82
- (0, bun_test_1.it)("includes the wrapped error stack in the message", function () {
83
- var _a;
97
+ (0, bun_test_1.it)("exposes the wrapped error as the standard cause", function () {
98
+ var wrapped = new Error("inner");
99
+ var error = new errors_1.APIError({ cause: wrapped, title: "Outer" });
100
+ (0, bun_test_1.expect)(error.message).toBe("Outer");
101
+ (0, bun_test_1.expect)(error.cause).toBe(wrapped);
102
+ });
103
+ (0, bun_test_1.it)("supports the deprecated error option as a cause alias", function () {
84
104
  var wrapped = new Error("inner");
85
105
  var error = new errors_1.APIError({ error: wrapped, title: "Outer" });
86
- (0, bun_test_1.expect)(error.message).toContain("Outer");
87
- (0, bun_test_1.expect)(error.message).toContain((_a = wrapped.stack) !== null && _a !== void 0 ? _a : "");
106
+ (0, bun_test_1.expect)(error.cause).toBe(wrapped);
107
+ (0, bun_test_1.expect)(error.error).toBe(wrapped);
108
+ });
109
+ (0, bun_test_1.it)("derives the name from the status code", function () {
110
+ (0, bun_test_1.expect)(new errors_1.APIError({ status: 400, title: "T" }).name).toBe("BadRequestError");
111
+ (0, bun_test_1.expect)(new errors_1.APIError({ status: 401, title: "T" }).name).toBe("UnauthorizedError");
112
+ (0, bun_test_1.expect)(new errors_1.APIError({ status: 403, title: "T" }).name).toBe("ForbiddenError");
113
+ (0, bun_test_1.expect)(new errors_1.APIError({ status: 404, title: "T" }).name).toBe("NotFoundError");
114
+ (0, bun_test_1.expect)(new errors_1.APIError({ status: 409, title: "T" }).name).toBe("ConflictError");
115
+ (0, bun_test_1.expect)(new errors_1.APIError({ status: 500, title: "T" }).name).toBe("InternalServerError");
116
+ });
117
+ (0, bun_test_1.it)("falls back to APIError for unmapped statuses", function () {
118
+ (0, bun_test_1.expect)(new errors_1.APIError({ status: 418, title: "T" }).name).toBe("APIError");
119
+ });
120
+ (0, bun_test_1.it)("derives the name from the code when provided", function () {
121
+ var error = new errors_1.APIError({ code: "update-admin-error", status: 403, title: "T" });
122
+ (0, bun_test_1.expect)(error.name).toBe("UpdateAdminError");
123
+ });
124
+ (0, bun_test_1.it)("keeps title in sync with message via the getter", function () {
125
+ var error = new errors_1.APIError({ title: "Original" });
126
+ error.message = "Changed";
127
+ (0, bun_test_1.expect)(error.title).toBe("Changed");
88
128
  });
89
129
  (0, bun_test_1.it)("defaults status to 500 when status is omitted", function () {
90
130
  var error = new errors_1.APIError({ title: "No status" });
@@ -120,6 +160,54 @@ var buildResponse = function () {
120
160
  (0, bun_test_1.expect)(untrackedError.disableExternalErrorTracking).toBe(true);
121
161
  });
122
162
  });
163
+ (0, bun_test_1.describe)("APIError subclasses", function () {
164
+ (0, bun_test_1.it)("sets the status and name from the subclass", function () {
165
+ var error = new errors_1.NotFoundError("Todo not found");
166
+ (0, bun_test_1.expect)(error.status).toBe(404);
167
+ (0, bun_test_1.expect)(error.name).toBe("NotFoundError");
168
+ (0, bun_test_1.expect)(error.message).toBe("Todo not found");
169
+ (0, bun_test_1.expect)(error).toBeInstanceOf(errors_1.APIError);
170
+ (0, bun_test_1.expect)((0, errors_1.isAPIError)(error)).toBe(true);
171
+ });
172
+ (0, bun_test_1.it)("accepts full options", function () {
173
+ var cause = new Error("inner");
174
+ var error = new errors_1.ForbiddenError({ cause: cause, detail: "Admins only", title: "Not allowed" });
175
+ (0, bun_test_1.expect)(error.status).toBe(403);
176
+ (0, bun_test_1.expect)(error.name).toBe("ForbiddenError");
177
+ (0, bun_test_1.expect)(error.detail).toBe("Admins only");
178
+ (0, bun_test_1.expect)(error.cause).toBe(cause);
179
+ });
180
+ (0, bun_test_1.it)("keeps the subclass name even when a code is provided", function () {
181
+ var error = new errors_1.BadRequestError({ code: "invalid-cursor", title: "Bad cursor" });
182
+ (0, bun_test_1.expect)(error.name).toBe("BadRequestError");
183
+ (0, bun_test_1.expect)(error.status).toBe(400);
184
+ });
185
+ (0, bun_test_1.it)("uses ValidationError with a 400 status", function () {
186
+ var _a;
187
+ var error = new errors_1.ValidationError({ fields: { email: "Required" }, title: "Validation failed" });
188
+ (0, bun_test_1.expect)(error.status).toBe(400);
189
+ (0, bun_test_1.expect)(error.name).toBe("ValidationError");
190
+ (0, bun_test_1.expect)((_a = error.meta) === null || _a === void 0 ? void 0 : _a.fields).toEqual({ email: "Required" });
191
+ });
192
+ (0, bun_test_1.it)("derives name from custom subclasses via new.target", function () {
193
+ var PaymentError = /** @class */ (function (_super) {
194
+ __extends(PaymentError, _super);
195
+ function PaymentError(title) {
196
+ return _super.call(this, { status: 402, title: title }) || this;
197
+ }
198
+ return PaymentError;
199
+ }(errors_1.APIError));
200
+ (0, bun_test_1.expect)(new PaymentError("declined").name).toBe("PaymentError");
201
+ });
202
+ (0, bun_test_1.it)("covers the remaining status subclasses", function () {
203
+ (0, bun_test_1.expect)(new errors_1.UnauthorizedError("U").status).toBe(401);
204
+ (0, bun_test_1.expect)(new errors_1.UnauthorizedError("U").name).toBe("UnauthorizedError");
205
+ (0, bun_test_1.expect)(new errors_1.ConflictError("C").status).toBe(409);
206
+ (0, bun_test_1.expect)(new errors_1.ConflictError("C").name).toBe("ConflictError");
207
+ (0, bun_test_1.expect)(new errors_1.InternalServerError("I").status).toBe(500);
208
+ (0, bun_test_1.expect)(new errors_1.InternalServerError("I").name).toBe("InternalServerError");
209
+ });
210
+ });
123
211
  (0, bun_test_1.describe)("isAPIError", function () {
124
212
  (0, bun_test_1.it)("returns true for an APIError instance", function () {
125
213
  (0, bun_test_1.expect)((0, errors_1.isAPIError)(new errors_1.APIError({ title: "Boom" }))).toBe(true);
@@ -127,11 +215,19 @@ var buildResponse = function () {
127
215
  (0, bun_test_1.it)("returns false for a regular Error", function () {
128
216
  (0, bun_test_1.expect)((0, errors_1.isAPIError)(new Error("nope"))).toBe(false);
129
217
  });
130
- (0, bun_test_1.it)("returns true for any error whose name is APIError", function () {
218
+ (0, bun_test_1.it)("returns true for any error whose name is APIError (transition fallback)", function () {
131
219
  var err = new Error("custom");
132
220
  err.name = "APIError";
133
221
  (0, bun_test_1.expect)((0, errors_1.isAPIError)(err)).toBe(true);
134
222
  });
223
+ (0, bun_test_1.it)("returns true for a branded error from a duplicate package copy", function () {
224
+ var err = new Error("branded");
225
+ err.isTerrenoAPIError = true;
226
+ (0, bun_test_1.expect)((0, errors_1.isAPIError)(err)).toBe(true);
227
+ });
228
+ (0, bun_test_1.it)("returns true for subclasses", function () {
229
+ (0, bun_test_1.expect)((0, errors_1.isAPIError)(new errors_1.NotFoundError("missing"))).toBe(true);
230
+ });
135
231
  });
136
232
  (0, bun_test_1.describe)("getDisableExternalErrorTracking", function () {
137
233
  (0, bun_test_1.it)("returns the flag from an APIError", function () {
@@ -184,9 +280,9 @@ var buildResponse = function () {
184
280
  (0, bun_test_1.it)("returns title and status by default", function () {
185
281
  var error = new errors_1.APIError({ status: 404, title: "Not Found" });
186
282
  var body = (0, errors_1.getAPIErrorBody)(error);
187
- (0, bun_test_1.expect)(body).toEqual({ meta: {}, status: 404, title: "Not Found" });
283
+ (0, bun_test_1.expect)(body).toEqual({ status: 404, title: "Not Found" });
188
284
  });
189
- (0, bun_test_1.it)("includes optional fields when set", function () {
285
+ (0, bun_test_1.it)("includes optional fields when set, including disableExternalErrorTracking when true", function () {
190
286
  var error = new errors_1.APIError({
191
287
  code: "not-found",
192
288
  detail: "Could not find resource",
@@ -204,17 +300,48 @@ var buildResponse = function () {
204
300
  disableExternalErrorTracking: true,
205
301
  id: "err-1",
206
302
  links: { about: "https://example.com/help" },
207
- meta: {},
208
303
  source: { pointer: "/data/id" },
209
304
  status: 404,
210
305
  title: "Not Found",
211
306
  });
212
307
  });
308
+ (0, bun_test_1.it)("matches toJSON and excludes name, stack, and cause", function () {
309
+ var error = new errors_1.APIError({
310
+ cause: new Error("inner"),
311
+ detail: "d",
312
+ status: 404,
313
+ title: "Not Found",
314
+ });
315
+ var body = error.toJSON();
316
+ (0, bun_test_1.expect)(body).toEqual((0, errors_1.getAPIErrorBody)(error));
317
+ (0, bun_test_1.expect)(body.name).toBeUndefined();
318
+ (0, bun_test_1.expect)(body.stack).toBeUndefined();
319
+ (0, bun_test_1.expect)(body.cause).toBeUndefined();
320
+ (0, bun_test_1.expect)(body.disableExternalErrorTracking).toBeUndefined();
321
+ (0, bun_test_1.expect)(JSON.parse(JSON.stringify(error))).toEqual(JSON.parse(JSON.stringify(body)));
322
+ });
323
+ (0, bun_test_1.it)("exposes deprecated error getter as alias for cause", function () {
324
+ var cause = new Error("inner");
325
+ var error = new errors_1.APIError({ cause: cause, title: "Wrapped" });
326
+ (0, bun_test_1.expect)(error.error).toBe(cause);
327
+ (0, bun_test_1.expect)(error.cause).toBe(cause);
328
+ });
329
+ (0, bun_test_1.it)("prefers explicit title over message when serializing legacy instances", function () {
330
+ var legacy = new Error("polluted message with stack");
331
+ legacy.status = 404;
332
+ legacy.title = "Clean title";
333
+ var body = (0, errors_1.getAPIErrorBody)(legacy);
334
+ (0, bun_test_1.expect)(body.title).toBe("Clean title");
335
+ });
336
+ (0, bun_test_1.it)("truncates fractional and invalid status codes to 500", function () {
337
+ (0, bun_test_1.expect)(new errors_1.APIError({ status: 404.7, title: "x" }).status).toBe(404);
338
+ (0, bun_test_1.expect)(new errors_1.APIError({ status: Number.NaN, title: "x" }).status).toBe(500);
339
+ (0, bun_test_1.expect)(new errors_1.APIError({ status: 200, title: "x" }).status).toBe(500);
340
+ });
213
341
  (0, bun_test_1.it)("omits empty meta and unset optional fields", function () {
214
342
  var error = new errors_1.APIError({ status: 400, title: "Bad" });
215
- // meta defaults to {} which is truthy, so it is included.
216
343
  var body = (0, errors_1.getAPIErrorBody)(error);
217
- (0, bun_test_1.expect)(body.meta).toEqual({});
344
+ (0, bun_test_1.expect)(body.meta).toBeUndefined();
218
345
  (0, bun_test_1.expect)(body.code).toBeUndefined();
219
346
  (0, bun_test_1.expect)(body.detail).toBeUndefined();
220
347
  (0, bun_test_1.expect)(body.id).toBeUndefined();
@@ -286,6 +413,29 @@ var buildResponse = function () {
286
413
  (0, errors_1.apiErrorMiddleware)(err, req, res, next);
287
414
  (0, bun_test_1.expect)(captureExceptionSpy).toHaveBeenCalledWith(err);
288
415
  });
416
+ (0, bun_test_1.it)("fingerprints Sentry captures on the logical error type", function () {
417
+ var scope = {
418
+ setContext: (0, bun_test_1.mock)(function () { }),
419
+ setFingerprint: (0, bun_test_1.mock)(function () { }),
420
+ setTag: (0, bun_test_1.mock)(function () { }),
421
+ };
422
+ var withScopeSpy = (0, bun_test_1.spyOn)(Sentry, "withScope").mockImplementation((function (callback) { return callback(scope); }));
423
+ try {
424
+ var err = new errors_1.APIError({ code: "todo-sync-failed", status: 502, title: "Sync failed" });
425
+ (0, errors_1.apiErrorMiddleware)(err, req, res, next);
426
+ (0, bun_test_1.expect)(scope.setFingerprint).toHaveBeenCalledWith([
427
+ "TodoSyncFailed",
428
+ "todo-sync-failed",
429
+ "502",
430
+ ]);
431
+ (0, bun_test_1.expect)(scope.setTag).toHaveBeenCalledWith("http.status_code", "502");
432
+ (0, bun_test_1.expect)(scope.setTag).toHaveBeenCalledWith("api_error.code", "todo-sync-failed");
433
+ (0, bun_test_1.expect)(scope.setContext).toHaveBeenCalledWith("apiError", bun_test_1.expect.objectContaining({ status: 502, title: "Sync failed" }));
434
+ }
435
+ finally {
436
+ withScopeSpy.mockRestore();
437
+ }
438
+ });
289
439
  (0, bun_test_1.it)("does not capture the exception when disableExternalErrorTracking is true", function () {
290
440
  var err = new errors_1.APIError({
291
441
  disableExternalErrorTracking: true,
package/dist/example.js CHANGED
@@ -68,8 +68,9 @@ var userSchema = new mongoose_1.Schema({
68
68
  admin: { default: false, description: "Whether the user has admin privileges", type: Boolean },
69
69
  username: { description: "The user's username", type: String },
70
70
  }, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
71
- // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose's plugin type is incompatible with mongoose Schema generics
72
- userSchema.plugin(passport_local_mongoose_1.default, { usernameField: "email" });
71
+ userSchema.plugin(passport_local_mongoose_1.default, {
72
+ usernameField: "email",
73
+ });
73
74
  userSchema.plugin(plugins_1.createdUpdatedPlugin);
74
75
  userSchema.plugin(plugins_1.isDeletedPlugin);
75
76
  userSchema.plugin(plugins_1.findOneOrNone);
@@ -119,6 +119,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
119
119
  return (mod && mod.__esModule) ? mod : { "default": mod };
120
120
  };
121
121
  Object.defineProperty(exports, "__esModule", { value: true });
122
+ // noExplicitAny: test mock typing
122
123
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
123
124
  var bun_test_1 = require("bun:test");
124
125
  var node_stream_1 = require("node:stream");
@@ -58,6 +58,7 @@ var plugins_1 = require("./plugins");
58
58
  * userSchema.plugin(githubUserPlugin);
59
59
  * ```
60
60
  */
61
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
61
62
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
62
63
  var githubUserPlugin = function (schema) {
63
64
  schema.add({
@@ -82,6 +83,7 @@ var setupGitHubAuth = function (_app, userModel, githubOptions) {
82
83
  var _a;
83
84
  var scope = (_a = githubOptions.scope) !== null && _a !== void 0 ? _a : ["user:email"];
84
85
  passport_1.default.use("github",
86
+ // noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
85
87
  // biome-ignore lint/suspicious/noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
86
88
  new passport_github2_1.Strategy({
87
89
  callbackURL: githubOptions.callbackURL,
@@ -72,6 +72,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
72
72
  return (mod && mod.__esModule) ? mod : { "default": mod };
73
73
  };
74
74
  Object.defineProperty(exports, "__esModule", { value: true });
75
+ // noExplicitAny: test mock typing
75
76
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
76
77
  var bun_test_1 = require("bun:test");
77
78
  var mongoose_1 = __importStar(require("mongoose"));
@@ -59,9 +59,8 @@ export interface WithApiErrorHandlingOptions {
59
59
  *
60
60
  * In "raw" mode (default) the wrapper logs the normalized shape via the injected logger
61
61
  * and rethrows the original error. In "apiError" mode the wrapper throws a terreno
62
- * APIError — whose constructor already logs — so the wrapper itself stays silent to
63
- * preserve the log-once contract. The APIError title is stable per JSONAPI convention;
64
- * per-occurrence text goes in `detail`, built from the (redacted) normalized messages.
62
+ * APIError with a stable title (per-occurrence text goes in `detail`) and stays silent
63
+ * itself — apiErrorMiddleware logs APIErrors, so logging here too would double-log.
65
64
  */
66
65
  export declare const withApiErrorHandling: <T>(fn: () => Promise<T>, options: WithApiErrorHandlingOptions) => Promise<T>;
67
66
  export type AuthStrategy = {
@@ -182,9 +182,8 @@ exports.normalizeApiError = normalizeApiError;
182
182
  *
183
183
  * In "raw" mode (default) the wrapper logs the normalized shape via the injected logger
184
184
  * and rethrows the original error. In "apiError" mode the wrapper throws a terreno
185
- * APIError — whose constructor already logs — so the wrapper itself stays silent to
186
- * preserve the log-once contract. The APIError title is stable per JSONAPI convention;
187
- * per-occurrence text goes in `detail`, built from the (redacted) normalized messages.
185
+ * APIError with a stable title (per-occurrence text goes in `detail`) and stays silent
186
+ * itself — apiErrorMiddleware logs APIErrors, so logging here too would double-log.
188
187
  */
189
188
  var withApiErrorHandling = function (fn, options) { return __awaiter(void 0, void 0, void 0, function () {
190
189
  var log, error_1, normalized, statusCode;
@@ -210,8 +209,9 @@ var withApiErrorHandling = function (fn, options) { return __awaiter(void 0, voi
210
209
  if (options.rethrowAs === "apiError") {
211
210
  statusCode = normalized.statusCode;
212
211
  throw new errors_1.APIError({
212
+ cause: error_1,
213
+ code: "http-client-error",
213
214
  detail: (_b = normalized.messages[0]) !== null && _b !== void 0 ? _b : "unknown error",
214
- error: error_1,
215
215
  meta: { classification: normalized.classification },
216
216
  status: statusCode !== undefined && statusCode >= 400 ? statusCode : 500,
217
217
  title: "".concat(options.apiName, " ").concat(options.operation, " request failed"),
@@ -313,7 +313,7 @@ var buildAxiosError = function (_a) {
313
313
  }
314
314
  });
315
315
  }); });
316
- (0, bun_test_1.it)("converts to an APIError when rethrowAs is apiError, logging via APIError only", function () { return __awaiter(void 0, void 0, void 0, function () {
316
+ (0, bun_test_1.it)("converts to an APIError when rethrowAs is apiError without logging itself", function () { return __awaiter(void 0, void 0, void 0, function () {
317
317
  var _a, logger, entries, original, caught, error_2, apiError;
318
318
  var _b;
319
319
  return __generator(this, function (_c) {
@@ -344,7 +344,8 @@ var buildAxiosError = function (_a) {
344
344
  (0, bun_test_1.expect)(apiError.detail).toBe("Rate limit exceeded");
345
345
  (0, bun_test_1.expect)(apiError.error).toBe(original);
346
346
  (0, bun_test_1.expect)((_b = apiError.meta) === null || _b === void 0 ? void 0 : _b.classification).toBe("rateLimited");
347
- // Logged exactly once: the APIError constructor logs, so the wrapper must not.
347
+ // The wrapper stays silent — apiErrorMiddleware logs the APIError, so logging here
348
+ // too would produce two log entries for the same failure.
348
349
  (0, bun_test_1.expect)(entries).toHaveLength(0);
349
350
  return [2 /*return*/];
350
351
  }
@@ -10,6 +10,39 @@ var __assign = (this && this.__assign) || function () {
10
10
  };
11
11
  return __assign.apply(this, arguments);
12
12
  };
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || (function () {
30
+ var ownKeys = function(o) {
31
+ ownKeys = Object.getOwnPropertyNames || function (o) {
32
+ var ar = [];
33
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
34
+ return ar;
35
+ };
36
+ return ownKeys(o);
37
+ };
38
+ return function (mod) {
39
+ if (mod && mod.__esModule) return mod;
40
+ var result = {};
41
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
42
+ __setModuleDefault(result, mod);
43
+ return result;
44
+ };
45
+ })();
13
46
  var __importDefault = (this && this.__importDefault) || function (mod) {
14
47
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
48
  };
@@ -19,6 +52,7 @@ var node_fs_1 = __importDefault(require("node:fs"));
19
52
  var node_os_1 = __importDefault(require("node:os"));
20
53
  var node_path_1 = __importDefault(require("node:path"));
21
54
  var node_stream_1 = require("node:stream");
55
+ var Sentry = __importStar(require("@sentry/bun"));
22
56
  var winston_1 = __importDefault(require("winston"));
23
57
  var logger_1 = require("./logger");
24
58
  var requestContext_1 = require("./requestContext");
@@ -53,6 +87,55 @@ var requestContext_1 = require("./requestContext");
53
87
  (0, bun_test_1.expect)(function () { return logger_1.logger.catch(new Error("captured")); }).not.toThrow();
54
88
  });
55
89
  });
90
+ (0, bun_test_1.describe)("logger Sentry structured logging", function () {
91
+ (0, bun_test_1.afterEach)(function () {
92
+ Reflect.deleteProperty(process.env, "USE_SENTRY_LOGGING");
93
+ });
94
+ (0, bun_test_1.it)("forwards every level to Sentry.logger when USE_SENTRY_LOGGING is true", function () {
95
+ var _a, _b, _c, _d;
96
+ process.env.USE_SENTRY_LOGGING = "true";
97
+ logger_1.logger.debug("sentry-debug-message");
98
+ logger_1.logger.info("sentry-info-message");
99
+ logger_1.logger.warn("sentry-warn-message");
100
+ logger_1.logger.error("sentry-error-message");
101
+ (0, bun_test_1.expect)((_a = Sentry.logger) === null || _a === void 0 ? void 0 : _a.debug).toHaveBeenCalledWith("sentry-debug-message", bun_test_1.expect.anything());
102
+ (0, bun_test_1.expect)((_b = Sentry.logger) === null || _b === void 0 ? void 0 : _b.info).toHaveBeenCalledWith("sentry-info-message", bun_test_1.expect.anything());
103
+ (0, bun_test_1.expect)((_c = Sentry.logger) === null || _c === void 0 ? void 0 : _c.warn).toHaveBeenCalledWith("sentry-warn-message", bun_test_1.expect.anything());
104
+ (0, bun_test_1.expect)((_d = Sentry.logger) === null || _d === void 0 ? void 0 : _d.error).toHaveBeenCalledWith("sentry-error-message", bun_test_1.expect.anything());
105
+ });
106
+ (0, bun_test_1.it)("does not forward to Sentry.logger when USE_SENTRY_LOGGING is unset", function () {
107
+ var _a;
108
+ Reflect.deleteProperty(process.env, "USE_SENTRY_LOGGING");
109
+ (0, bun_test_1.expect)(function () { return logger_1.logger.info("no-sentry-message"); }).not.toThrow();
110
+ (0, bun_test_1.expect)((_a = Sentry.logger) === null || _a === void 0 ? void 0 : _a.info).not.toHaveBeenCalledWith("no-sentry-message", bun_test_1.expect.anything());
111
+ });
112
+ (0, bun_test_1.it)("attaches terrenoRequestLog to Sentry attributes inside a request scope", function () {
113
+ var _a;
114
+ process.env.USE_SENTRY_LOGGING = "true";
115
+ (0, requestContext_1.runWithRequestContext)({ requestId: "sentry-req-1", userId: "sentry-user-1" }, function () {
116
+ logger_1.logger.info("sentry-request-scoped-message");
117
+ });
118
+ (0, bun_test_1.expect)((_a = Sentry.logger) === null || _a === void 0 ? void 0 : _a.info).toHaveBeenCalledWith("sentry-request-scoped-message", bun_test_1.expect.objectContaining({
119
+ terrenoRequestLog: bun_test_1.expect.objectContaining({
120
+ requestId: "sentry-req-1",
121
+ userId: "sentry-user-1",
122
+ }),
123
+ }));
124
+ });
125
+ (0, bun_test_1.it)("logs a caught non-Error value via Sentry.logger.error when enabled", function () {
126
+ var _a;
127
+ process.env.USE_SENTRY_LOGGING = "true";
128
+ (0, bun_test_1.expect)(function () { return logger_1.logger.catch("plain-string-failure"); }).not.toThrow();
129
+ (0, bun_test_1.expect)((_a = Sentry.logger) === null || _a === void 0 ? void 0 : _a.error).toHaveBeenCalled();
130
+ });
131
+ (0, bun_test_1.it)("scoped logger catch logs a non-Error value via Sentry.logger.error when enabled", function () {
132
+ var _a;
133
+ process.env.USE_SENTRY_LOGGING = "true";
134
+ var scoped = (0, logger_1.createScopedLogger)({ labels: { jobId: "j1" }, prefix: "[SentryScoped]" });
135
+ (0, bun_test_1.expect)(function () { return scoped.catch("scoped-plain-failure"); }).not.toThrow();
136
+ (0, bun_test_1.expect)((_a = Sentry.logger) === null || _a === void 0 ? void 0 : _a.error).toHaveBeenCalled();
137
+ });
138
+ });
56
139
  (0, bun_test_1.describe)("formatLogContextSuffix", function () {
57
140
  (0, bun_test_1.it)("includes request ids and sorts terrenoLabels for stable output", function () {
58
141
  var suffix = (0, logger_1.formatLogContextSuffix)({
@@ -575,4 +658,28 @@ var requestContext_1 = require("./requestContext");
575
658
  });
576
659
  }).not.toThrow();
577
660
  });
661
+ (0, bun_test_1.it)("attaches the dev JSONL transport when TERRENO_LOG_FILE forces it on", function () {
662
+ var originalCwd = process.cwd();
663
+ process.env.TERRENO_LOG_FILE = "true";
664
+ try {
665
+ process.chdir(tempDir);
666
+ (0, logger_1.setupLogging)({ disableConsoleLogging: true, disableFileLogging: true });
667
+ (0, bun_test_1.expect)(node_fs_1.default.existsSync(node_path_1.default.join(tempDir, ".terreno", "logs"))).toBe(true);
668
+ }
669
+ finally {
670
+ process.chdir(originalCwd);
671
+ Reflect.deleteProperty(process.env, "TERRENO_LOG_FILE");
672
+ }
673
+ });
674
+ (0, bun_test_1.it)("skips the dev JSONL transport when TERRENO_LOG_FILE forces it off", function () {
675
+ process.env.TERRENO_LOG_FILE = "false";
676
+ try {
677
+ (0, bun_test_1.expect)(function () {
678
+ return (0, logger_1.setupLogging)({ disableConsoleLogging: true, disableFileLogging: true });
679
+ }).not.toThrow();
680
+ }
681
+ finally {
682
+ Reflect.deleteProperty(process.env, "TERRENO_LOG_FILE");
683
+ }
684
+ });
578
685
  });
@@ -102,6 +102,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
102
102
  var bun_test_1 = require("bun:test");
103
103
  var Sentry = __importStar(require("@sentry/bun"));
104
104
  var axios_1 = __importDefault(require("axios"));
105
+ var errors_1 = require("../errors");
105
106
  var googleChatNotifier_1 = require("./googleChatNotifier");
106
107
  (0, bun_test_1.describe)("sendToGoogleChat", function () {
107
108
  var mockAxiosPost;
@@ -232,7 +233,7 @@ var googleChatNotifier_1 = require("./googleChatNotifier");
232
233
  throw new Error("Expected sendToGoogleChat to throw APIError");
233
234
  case 3:
234
235
  error_1 = _a.sent();
235
- (0, bun_test_1.expect)(error_1.name).toBe("APIError");
236
+ (0, bun_test_1.expect)((0, errors_1.isAPIError)(error_1)).toBe(true);
236
237
  (0, bun_test_1.expect)(error_1.title).toMatch(/Error posting to Google Chat/i);
237
238
  return [3 /*break*/, 4];
238
239
  case 4:
@@ -269,7 +269,7 @@ var slackNotifier_1 = require("./slackNotifier");
269
269
  case 3:
270
270
  error_1 = _a.sent();
271
271
  apiError = error_1;
272
- (0, bun_test_1.expect)(apiError.name).toBe("APIError");
272
+ (0, bun_test_1.expect)((0, errors_1.isAPIError)(apiError)).toBe(true);
273
273
  (0, bun_test_1.expect)(apiError.title).toMatch(/Error posting to slack/i);
274
274
  return [3 /*break*/, 4];
275
275
  case 4:
@@ -102,6 +102,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
102
102
  var bun_test_1 = require("bun:test");
103
103
  var Sentry = __importStar(require("@sentry/bun"));
104
104
  var axios_1 = __importDefault(require("axios"));
105
+ var errors_1 = require("../errors");
105
106
  var zoomNotifier_1 = require("./zoomNotifier");
106
107
  (0, bun_test_1.describe)("sendToZoom", function () {
107
108
  var mockAxiosPost;
@@ -341,7 +342,7 @@ var zoomNotifier_1 = require("./zoomNotifier");
341
342
  throw new Error("Expected sendToZoom to throw APIError");
342
343
  case 3:
343
344
  error_1 = _a.sent();
344
- (0, bun_test_1.expect)(error_1.name).toBe("APIError");
345
+ (0, bun_test_1.expect)((0, errors_1.isAPIError)(error_1)).toBe(true);
345
346
  (0, bun_test_1.expect)(error_1.title).toMatch(/Error posting to Zoom/i);
346
347
  return [3 /*break*/, 4];
347
348
  case 4:
@@ -66,6 +66,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
66
66
  return (mod && mod.__esModule) ? mod : { "default": mod };
67
67
  };
68
68
  Object.defineProperty(exports, "__esModule", { value: true });
69
+ // noExplicitAny: test mock typing
69
70
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
70
71
  var bun_test_1 = require("bun:test");
71
72
  var supertest_1 = __importDefault(require("supertest"));
@@ -459,7 +459,8 @@ var OpenApiMiddlewareBuilder = /** @class */ (function () {
459
459
  * router.get("/users/:id", middleware, getUserHandler);
460
460
  * ```
461
461
  */
462
- // biome-ignore lint/suspicious/noExplicitAny: returns either a single RequestHandler or an array depending on validation config — callers spread or invoke
462
+ // noExplicitAny: returns either a single RequestHandler or an array depending on validation config — callers spread or invoke
463
+ // biome-ignore lint/suspicious/noExplicitAny: returns either a single RequestHandler or an array depending on validation config
463
464
  OpenApiMiddlewareBuilder.prototype.build = function () {
464
465
  var _c, _d, _e, _f, _g;
465
466
  var noop = function (_a, _b, next) { return next(); };
@@ -50,6 +50,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
50
50
  return (mod && mod.__esModule) ? mod : { "default": mod };
51
51
  };
52
52
  Object.defineProperty(exports, "__esModule", { value: true });
53
+ // noExplicitAny: test mock typing
53
54
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
54
55
  var bun_test_1 = require("bun:test");
55
56
  var supertest_1 = __importDefault(require("supertest"));
@@ -569,14 +570,14 @@ function addRoutesWithBuilder(router, options) {
569
570
  .buildWithSchemas();
570
571
  (0, bun_test_1.expect)(result.validationEnabled).toBe(false);
571
572
  });
572
- (0, bun_test_1.it)("build() returns an array with validators when validation is enabled", function () {
573
+ (0, bun_test_1.it)("build() returns an array when validation is enabled with body and query", function () {
573
574
  var result = (0, openApiBuilder_1.createOpenApiBuilder)({})
574
575
  .withRequestBody({ name: { required: true, type: "string" } })
575
576
  .withQueryParameter("page", { type: "number" })
576
577
  .withValidation()
577
578
  .build();
578
579
  (0, bun_test_1.expect)(Array.isArray(result)).toBe(true);
579
- (0, bun_test_1.expect)(result.length).toBeGreaterThan(1);
580
+ (0, bun_test_1.expect)(result).toHaveLength(3);
580
581
  });
581
582
  (0, bun_test_1.it)("build() returns a single middleware when validation is disabled", function () {
582
583
  var result = (0, openApiBuilder_1.createOpenApiBuilder)({})
@@ -191,6 +191,7 @@ var getAjvInstance = function () {
191
191
  useDefaults: true,
192
192
  validateSchema: false,
193
193
  });
194
+ // noExplicitAny: ajv-formats has a known type compat issue with AJV instances
194
195
  // biome-ignore lint/suspicious/noExplicitAny: ajv-formats has a known type compat issue with AJV instances
195
196
  (0, ajv_formats_1.default)(instance);
196
197
  ajvCache.set(key, instance);
@@ -72,6 +72,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
72
72
  return to.concat(ar || Array.prototype.slice.call(from));
73
73
  };
74
74
  Object.defineProperty(exports, "__esModule", { value: true });
75
+ // noExplicitAny: test mock typing
75
76
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
76
77
  var bun_test_1 = require("bun:test");
77
78
  var api_1 = require("./api");
@@ -717,4 +718,44 @@ var setupFreshApp = function () { return __awaiter(void 0, void 0, void 0, funct
717
718
  (0, bun_test_1.expect)((0, openApiValidator_1.getOpenApiValidatorConfig)().removeAdditional).toBe(false);
718
719
  });
719
720
  });
721
+ (0, bun_test_1.describe)("schema sanitization and validator caching", function () {
722
+ var runMiddleware = function (middleware, req) {
723
+ var nextCalled = false;
724
+ middleware(req, {}, function () {
725
+ nextCalled = true;
726
+ });
727
+ return nextCalled;
728
+ };
729
+ // An unresolvable $ref makes ajv.compile throw, so getValidator catches the error
730
+ // and returns null. Built via `unknown` to keep the non-standard keyword out of the
731
+ // typed surface (and out of the explicit-any baseline).
732
+ var uncompilableSchema = {
733
+ broken: { $ref: "#/components/schemas/DoesNotExist" },
734
+ };
735
+ (0, bun_test_1.it)("maps an unrecognized mongoose type to string so the schema still compiles", function () {
736
+ (0, openApiValidator_1.configureOpenApiValidator)();
737
+ // "buffer" is neither a valid JSON Schema type nor present in MONGOOSE_TYPE_MAP,
738
+ // so sanitizeSchemaForAjv falls through to the `type = "string"` branch.
739
+ var middleware = (0, openApiValidator_1.validateRequestBody)({ raw: { type: "buffer" } });
740
+ (0, bun_test_1.expect)(runMiddleware(middleware, { body: { raw: "some-string" }, method: "POST", path: "/t" })).toBe(true);
741
+ });
742
+ (0, bun_test_1.it)("reuses the cached validator on subsequent requests with the same schema", function () {
743
+ (0, openApiValidator_1.configureOpenApiValidator)();
744
+ var middleware = (0, openApiValidator_1.validateRequestBody)({ name: { type: "string" } });
745
+ var req = { body: { name: "ok" }, method: "POST", path: "/t" };
746
+ // First request compiles and caches the validator; the second must hit the cache.
747
+ (0, bun_test_1.expect)(runMiddleware(middleware, req)).toBe(true);
748
+ (0, bun_test_1.expect)(runMiddleware(middleware, req)).toBe(true);
749
+ });
750
+ (0, bun_test_1.it)("skips query validation when the schema cannot be compiled", function () {
751
+ (0, openApiValidator_1.configureOpenApiValidator)();
752
+ var middleware = (0, openApiValidator_1.validateQueryParams)(uncompilableSchema);
753
+ (0, bun_test_1.expect)(runMiddleware(middleware, { method: "GET", path: "/t", query: { broken: "x" } })).toBe(true);
754
+ });
755
+ (0, bun_test_1.it)("skips response validation when the schema cannot be compiled", function () {
756
+ (0, openApiValidator_1.configureOpenApiValidator)({ validateResponses: true });
757
+ var result = (0, openApiValidator_1.validateResponseData)({ broken: "x" }, uncompilableSchema);
758
+ (0, bun_test_1.expect)(result.valid).toBe(true);
759
+ });
760
+ });
720
761
  });