@nice-code/common-errors 0.2.8 → 0.2.10

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.
@@ -1,2881 +1,3 @@
1
- // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/legacy.js
2
- var ACCEPTED = 202;
3
- var BAD_GATEWAY = 502;
4
- var BAD_REQUEST = 400;
5
- var CONFLICT = 409;
6
- var CONTINUE = 100;
7
- var CREATED = 201;
8
- var EXPECTATION_FAILED = 417;
9
- var FORBIDDEN = 403;
10
- var GATEWAY_TIMEOUT = 504;
11
- var GONE = 410;
12
- var HTTP_VERSION_NOT_SUPPORTED = 505;
13
- var IM_A_TEAPOT = 418;
14
- var INSUFFICIENT_SPACE_ON_RESOURCE = 419;
15
- var INSUFFICIENT_STORAGE = 507;
16
- var INTERNAL_SERVER_ERROR = 500;
17
- var LENGTH_REQUIRED = 411;
18
- var LOCKED = 423;
19
- var METHOD_FAILURE = 420;
20
- var METHOD_NOT_ALLOWED = 405;
21
- var MOVED_PERMANENTLY = 301;
22
- var MOVED_TEMPORARILY = 302;
23
- var MULTI_STATUS = 207;
24
- var MULTIPLE_CHOICES = 300;
25
- var NETWORK_AUTHENTICATION_REQUIRED = 511;
26
- var NO_CONTENT = 204;
27
- var NON_AUTHORITATIVE_INFORMATION = 203;
28
- var NOT_ACCEPTABLE = 406;
29
- var NOT_FOUND = 404;
30
- var NOT_IMPLEMENTED = 501;
31
- var NOT_MODIFIED = 304;
32
- var OK = 200;
33
- var PARTIAL_CONTENT = 206;
34
- var PAYMENT_REQUIRED = 402;
35
- var PERMANENT_REDIRECT = 308;
36
- var PRECONDITION_FAILED = 412;
37
- var PRECONDITION_REQUIRED = 428;
38
- var PROCESSING = 102;
39
- var PROXY_AUTHENTICATION_REQUIRED = 407;
40
- var REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
41
- var REQUEST_TIMEOUT = 408;
42
- var REQUEST_TOO_LONG = 413;
43
- var REQUEST_URI_TOO_LONG = 414;
44
- var REQUESTED_RANGE_NOT_SATISFIABLE = 416;
45
- var RESET_CONTENT = 205;
46
- var SEE_OTHER = 303;
47
- var SERVICE_UNAVAILABLE = 503;
48
- var SWITCHING_PROTOCOLS = 101;
49
- var TEMPORARY_REDIRECT = 307;
50
- var TOO_MANY_REQUESTS = 429;
51
- var UNAUTHORIZED = 401;
52
- var UNPROCESSABLE_ENTITY = 422;
53
- var UNSUPPORTED_MEDIA_TYPE = 415;
54
- var USE_PROXY = 305;
55
- var legacy_default = {
56
- ACCEPTED,
57
- BAD_GATEWAY,
58
- BAD_REQUEST,
59
- CONFLICT,
60
- CONTINUE,
61
- CREATED,
62
- EXPECTATION_FAILED,
63
- FORBIDDEN,
64
- GATEWAY_TIMEOUT,
65
- GONE,
66
- HTTP_VERSION_NOT_SUPPORTED,
67
- IM_A_TEAPOT,
68
- INSUFFICIENT_SPACE_ON_RESOURCE,
69
- INSUFFICIENT_STORAGE,
70
- INTERNAL_SERVER_ERROR,
71
- LENGTH_REQUIRED,
72
- LOCKED,
73
- METHOD_FAILURE,
74
- METHOD_NOT_ALLOWED,
75
- MOVED_PERMANENTLY,
76
- MOVED_TEMPORARILY,
77
- MULTI_STATUS,
78
- MULTIPLE_CHOICES,
79
- NETWORK_AUTHENTICATION_REQUIRED,
80
- NO_CONTENT,
81
- NON_AUTHORITATIVE_INFORMATION,
82
- NOT_ACCEPTABLE,
83
- NOT_FOUND,
84
- NOT_IMPLEMENTED,
85
- NOT_MODIFIED,
86
- OK,
87
- PARTIAL_CONTENT,
88
- PAYMENT_REQUIRED,
89
- PERMANENT_REDIRECT,
90
- PRECONDITION_FAILED,
91
- PRECONDITION_REQUIRED,
92
- PROCESSING,
93
- PROXY_AUTHENTICATION_REQUIRED,
94
- REQUEST_HEADER_FIELDS_TOO_LARGE,
95
- REQUEST_TIMEOUT,
96
- REQUEST_TOO_LONG,
97
- REQUEST_URI_TOO_LONG,
98
- REQUESTED_RANGE_NOT_SATISFIABLE,
99
- RESET_CONTENT,
100
- SEE_OTHER,
101
- SERVICE_UNAVAILABLE,
102
- SWITCHING_PROTOCOLS,
103
- TEMPORARY_REDIRECT,
104
- TOO_MANY_REQUESTS,
105
- UNAUTHORIZED,
106
- UNPROCESSABLE_ENTITY,
107
- UNSUPPORTED_MEDIA_TYPE,
108
- USE_PROXY
109
- };
110
-
111
- // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/utils.js
112
- var statusCodeToReasonPhrase = {
113
- "202": "Accepted",
114
- "502": "Bad Gateway",
115
- "400": "Bad Request",
116
- "409": "Conflict",
117
- "100": "Continue",
118
- "201": "Created",
119
- "417": "Expectation Failed",
120
- "424": "Failed Dependency",
121
- "403": "Forbidden",
122
- "504": "Gateway Timeout",
123
- "410": "Gone",
124
- "505": "HTTP Version Not Supported",
125
- "418": "I'm a teapot",
126
- "419": "Insufficient Space on Resource",
127
- "507": "Insufficient Storage",
128
- "500": "Internal Server Error",
129
- "411": "Length Required",
130
- "423": "Locked",
131
- "420": "Method Failure",
132
- "405": "Method Not Allowed",
133
- "301": "Moved Permanently",
134
- "302": "Moved Temporarily",
135
- "207": "Multi-Status",
136
- "300": "Multiple Choices",
137
- "511": "Network Authentication Required",
138
- "204": "No Content",
139
- "203": "Non Authoritative Information",
140
- "406": "Not Acceptable",
141
- "404": "Not Found",
142
- "501": "Not Implemented",
143
- "304": "Not Modified",
144
- "200": "OK",
145
- "206": "Partial Content",
146
- "402": "Payment Required",
147
- "308": "Permanent Redirect",
148
- "412": "Precondition Failed",
149
- "428": "Precondition Required",
150
- "102": "Processing",
151
- "103": "Early Hints",
152
- "426": "Upgrade Required",
153
- "407": "Proxy Authentication Required",
154
- "431": "Request Header Fields Too Large",
155
- "408": "Request Timeout",
156
- "413": "Request Entity Too Large",
157
- "414": "Request-URI Too Long",
158
- "416": "Requested Range Not Satisfiable",
159
- "205": "Reset Content",
160
- "303": "See Other",
161
- "503": "Service Unavailable",
162
- "101": "Switching Protocols",
163
- "307": "Temporary Redirect",
164
- "429": "Too Many Requests",
165
- "401": "Unauthorized",
166
- "451": "Unavailable For Legal Reasons",
167
- "422": "Unprocessable Entity",
168
- "415": "Unsupported Media Type",
169
- "305": "Use Proxy",
170
- "421": "Misdirected Request"
171
- };
172
- var reasonPhraseToStatusCode = {
173
- Accepted: 202,
174
- "Bad Gateway": 502,
175
- "Bad Request": 400,
176
- Conflict: 409,
177
- Continue: 100,
178
- Created: 201,
179
- "Expectation Failed": 417,
180
- "Failed Dependency": 424,
181
- Forbidden: 403,
182
- "Gateway Timeout": 504,
183
- Gone: 410,
184
- "HTTP Version Not Supported": 505,
185
- "I'm a teapot": 418,
186
- "Insufficient Space on Resource": 419,
187
- "Insufficient Storage": 507,
188
- "Internal Server Error": 500,
189
- "Length Required": 411,
190
- Locked: 423,
191
- "Method Failure": 420,
192
- "Method Not Allowed": 405,
193
- "Moved Permanently": 301,
194
- "Moved Temporarily": 302,
195
- "Multi-Status": 207,
196
- "Multiple Choices": 300,
197
- "Network Authentication Required": 511,
198
- "No Content": 204,
199
- "Non Authoritative Information": 203,
200
- "Not Acceptable": 406,
201
- "Not Found": 404,
202
- "Not Implemented": 501,
203
- "Not Modified": 304,
204
- OK: 200,
205
- "Partial Content": 206,
206
- "Payment Required": 402,
207
- "Permanent Redirect": 308,
208
- "Precondition Failed": 412,
209
- "Precondition Required": 428,
210
- Processing: 102,
211
- "Early Hints": 103,
212
- "Upgrade Required": 426,
213
- "Proxy Authentication Required": 407,
214
- "Request Header Fields Too Large": 431,
215
- "Request Timeout": 408,
216
- "Request Entity Too Large": 413,
217
- "Request-URI Too Long": 414,
218
- "Requested Range Not Satisfiable": 416,
219
- "Reset Content": 205,
220
- "See Other": 303,
221
- "Service Unavailable": 503,
222
- "Switching Protocols": 101,
223
- "Temporary Redirect": 307,
224
- "Too Many Requests": 429,
225
- Unauthorized: 401,
226
- "Unavailable For Legal Reasons": 451,
227
- "Unprocessable Entity": 422,
228
- "Unsupported Media Type": 415,
229
- "Use Proxy": 305,
230
- "Misdirected Request": 421
231
- };
232
-
233
- // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/utils-functions.js
234
- function getReasonPhrase(statusCode) {
235
- var result = statusCodeToReasonPhrase[statusCode.toString()];
236
- if (!result) {
237
- throw new Error("Status code does not exist: " + statusCode);
238
- }
239
- return result;
240
- }
241
- function getStatusCode(reasonPhrase) {
242
- var result = reasonPhraseToStatusCode[reasonPhrase];
243
- if (!result) {
244
- throw new Error("Reason phrase does not exist: " + reasonPhrase);
245
- }
246
- return result;
247
- }
248
- var getStatusText = getReasonPhrase;
249
-
250
- // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/status-codes.js
251
- var StatusCodes;
252
- (function(StatusCodes2) {
253
- StatusCodes2[StatusCodes2["CONTINUE"] = 100] = "CONTINUE";
254
- StatusCodes2[StatusCodes2["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
255
- StatusCodes2[StatusCodes2["PROCESSING"] = 102] = "PROCESSING";
256
- StatusCodes2[StatusCodes2["EARLY_HINTS"] = 103] = "EARLY_HINTS";
257
- StatusCodes2[StatusCodes2["OK"] = 200] = "OK";
258
- StatusCodes2[StatusCodes2["CREATED"] = 201] = "CREATED";
259
- StatusCodes2[StatusCodes2["ACCEPTED"] = 202] = "ACCEPTED";
260
- StatusCodes2[StatusCodes2["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
261
- StatusCodes2[StatusCodes2["NO_CONTENT"] = 204] = "NO_CONTENT";
262
- StatusCodes2[StatusCodes2["RESET_CONTENT"] = 205] = "RESET_CONTENT";
263
- StatusCodes2[StatusCodes2["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
264
- StatusCodes2[StatusCodes2["MULTI_STATUS"] = 207] = "MULTI_STATUS";
265
- StatusCodes2[StatusCodes2["MULTIPLE_CHOICES"] = 300] = "MULTIPLE_CHOICES";
266
- StatusCodes2[StatusCodes2["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
267
- StatusCodes2[StatusCodes2["MOVED_TEMPORARILY"] = 302] = "MOVED_TEMPORARILY";
268
- StatusCodes2[StatusCodes2["SEE_OTHER"] = 303] = "SEE_OTHER";
269
- StatusCodes2[StatusCodes2["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
270
- StatusCodes2[StatusCodes2["USE_PROXY"] = 305] = "USE_PROXY";
271
- StatusCodes2[StatusCodes2["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
272
- StatusCodes2[StatusCodes2["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT";
273
- StatusCodes2[StatusCodes2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
274
- StatusCodes2[StatusCodes2["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
275
- StatusCodes2[StatusCodes2["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
276
- StatusCodes2[StatusCodes2["FORBIDDEN"] = 403] = "FORBIDDEN";
277
- StatusCodes2[StatusCodes2["NOT_FOUND"] = 404] = "NOT_FOUND";
278
- StatusCodes2[StatusCodes2["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
279
- StatusCodes2[StatusCodes2["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
280
- StatusCodes2[StatusCodes2["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
281
- StatusCodes2[StatusCodes2["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
282
- StatusCodes2[StatusCodes2["CONFLICT"] = 409] = "CONFLICT";
283
- StatusCodes2[StatusCodes2["GONE"] = 410] = "GONE";
284
- StatusCodes2[StatusCodes2["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
285
- StatusCodes2[StatusCodes2["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
286
- StatusCodes2[StatusCodes2["REQUEST_TOO_LONG"] = 413] = "REQUEST_TOO_LONG";
287
- StatusCodes2[StatusCodes2["REQUEST_URI_TOO_LONG"] = 414] = "REQUEST_URI_TOO_LONG";
288
- StatusCodes2[StatusCodes2["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
289
- StatusCodes2[StatusCodes2["REQUESTED_RANGE_NOT_SATISFIABLE"] = 416] = "REQUESTED_RANGE_NOT_SATISFIABLE";
290
- StatusCodes2[StatusCodes2["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
291
- StatusCodes2[StatusCodes2["IM_A_TEAPOT"] = 418] = "IM_A_TEAPOT";
292
- StatusCodes2[StatusCodes2["INSUFFICIENT_SPACE_ON_RESOURCE"] = 419] = "INSUFFICIENT_SPACE_ON_RESOURCE";
293
- StatusCodes2[StatusCodes2["METHOD_FAILURE"] = 420] = "METHOD_FAILURE";
294
- StatusCodes2[StatusCodes2["MISDIRECTED_REQUEST"] = 421] = "MISDIRECTED_REQUEST";
295
- StatusCodes2[StatusCodes2["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
296
- StatusCodes2[StatusCodes2["LOCKED"] = 423] = "LOCKED";
297
- StatusCodes2[StatusCodes2["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
298
- StatusCodes2[StatusCodes2["UPGRADE_REQUIRED"] = 426] = "UPGRADE_REQUIRED";
299
- StatusCodes2[StatusCodes2["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
300
- StatusCodes2[StatusCodes2["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
301
- StatusCodes2[StatusCodes2["REQUEST_HEADER_FIELDS_TOO_LARGE"] = 431] = "REQUEST_HEADER_FIELDS_TOO_LARGE";
302
- StatusCodes2[StatusCodes2["UNAVAILABLE_FOR_LEGAL_REASONS"] = 451] = "UNAVAILABLE_FOR_LEGAL_REASONS";
303
- StatusCodes2[StatusCodes2["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
304
- StatusCodes2[StatusCodes2["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
305
- StatusCodes2[StatusCodes2["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
306
- StatusCodes2[StatusCodes2["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
307
- StatusCodes2[StatusCodes2["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
308
- StatusCodes2[StatusCodes2["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
309
- StatusCodes2[StatusCodes2["INSUFFICIENT_STORAGE"] = 507] = "INSUFFICIENT_STORAGE";
310
- StatusCodes2[StatusCodes2["NETWORK_AUTHENTICATION_REQUIRED"] = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
311
- })(StatusCodes || (StatusCodes = {}));
312
- // ../../node_modules/.bun/http-status-codes@2.3.0/node_modules/http-status-codes/build/es/index.js
313
- var __assign = function() {
314
- __assign = Object.assign || function(t) {
315
- for (var s, i = 1, n = arguments.length;i < n; i++) {
316
- s = arguments[i];
317
- for (var p in s)
318
- if (Object.prototype.hasOwnProperty.call(s, p))
319
- t[p] = s[p];
320
- }
321
- return t;
322
- };
323
- return __assign.apply(this, arguments);
324
- };
325
- var es_default = __assign(__assign({}, legacy_default), {
326
- getStatusCode,
327
- getStatusText
328
- });
329
-
330
- // ../nice-error/src/utils/jsErrorOrCastJsError.ts
331
- function jsErrorOrCastJsError(error, logMessage = true) {
332
- if (error instanceof Error) {
333
- return Object.assign(error, {
334
- message: error.message
335
- });
336
- }
337
- const message = error?.message ?? (typeof error === "string" ? error : "No error message found");
338
- if (logMessage) {
339
- console.error(`An unknown and unstructured error was thrown: ${message}`, error);
340
- }
341
- return {
342
- ...new Error(message),
343
- ...error
344
- };
345
- }
346
-
347
- // ../nice-error/src/NiceError/nice_error.static.ts
348
- var DUR_OBJ_PACK_PREFIX = "NE_DUROBJ[[";
349
- var DUR_OBJ_PACK_SUFFIX = "]]NE_DUROBJ";
350
-
351
- // ../nice-error/src/utils/packError/causePack.ts
352
- var causePack = (error) => {
353
- error._packedState = { cause: error.cause, packedAs: "cause_pack" /* cause_pack */ };
354
- error.cause = `${DUR_OBJ_PACK_PREFIX}${JSON.stringify(error.toJsonObject())}${DUR_OBJ_PACK_SUFFIX}`;
355
- return error;
356
- };
357
-
358
- // ../nice-error/src/utils/packError/msgPack.ts
359
- var msgPack = (error) => {
360
- error._packedState = { message: error.cleanMessage, packedAs: "msg_pack" /* msg_pack */ };
361
- error.message = `${DUR_OBJ_PACK_PREFIX}${JSON.stringify(error.toJsonObject())}${DUR_OBJ_PACK_SUFFIX}`;
362
- return error;
363
- };
364
-
365
- // ../nice-error/src/utils/packError/packError.ts
366
- var packError = (error, packType = "msg_pack") => {
367
- if (packType === "no_pack") {
368
- return error;
369
- }
370
- if (packType === "msg_pack") {
371
- return msgPack(error);
372
- }
373
- return causePack(error);
374
- };
375
-
376
- // ../nice-error/src/NiceError/NiceError.ts
377
- class NiceError extends Error {
378
- name = "NiceError";
379
- def;
380
- ids;
381
- wasntNice;
382
- httpStatusCode;
383
- timeCreated;
384
- cleanMessage;
385
- originError;
386
- _packedState;
387
- _errorDataMap;
388
- constructor(options) {
389
- const messagePure = options.message;
390
- const prefixedMessage = `[${options.def.domain}](${options.ids.join(",")}) ${messagePure}`;
391
- super(prefixedMessage);
392
- this.cleanMessage = messagePure;
393
- this.def = options.def;
394
- this.ids = options.ids;
395
- this._errorDataMap = options.errorData;
396
- this.wasntNice = options.wasntNice ?? false;
397
- this.httpStatusCode = options.httpStatusCode ?? 500;
398
- if (options.originError != null) {
399
- this.originError = options.originError;
400
- }
401
- this.timeCreated = options.timeCreated ?? Date.now();
402
- }
403
- hasId(id) {
404
- return id in this._errorDataMap;
405
- }
406
- hasOneOfIds(ids) {
407
- return ids.some((id) => (id in this._errorDataMap));
408
- }
409
- get hasMultiple() {
410
- return Object.keys(this._errorDataMap).length > 1;
411
- }
412
- getIds() {
413
- return Object.keys(this._errorDataMap);
414
- }
415
- getContext(id) {
416
- const errorData = this._errorDataMap[id];
417
- const state = errorData?.contextState;
418
- if (state == null) {
419
- return;
420
- }
421
- if (state.kind === "unhydrated") {
422
- throw new Error(`[NiceError.getContext] Context for id "${String(id)}" is in the "unhydrated" state. ` + `The error was reconstructed from a serialized payload but has not been deserialized yet. ` + `Call \`niceErrorDefined.hydrate(error)\` to reconstruct the typed context.`);
423
- }
424
- return state.value;
425
- }
426
- getErrorDataForId(id) {
427
- return this._errorDataMap[id];
428
- }
429
- withOriginError(error) {
430
- this.originError = jsErrorOrCastJsError(error);
431
- if (this._packedState?.packedAs !== "cause_pack" /* cause_pack */) {
432
- this.cause = this.originError;
433
- }
434
- return this;
435
- }
436
- matches(other) {
437
- const myDef = this.def;
438
- const otherDef = other.def;
439
- if (myDef.domain !== otherDef.domain)
440
- return false;
441
- const myIds = this.getIds().map(String).sort();
442
- const otherIds = other.getIds().map(String).sort();
443
- if (myIds.length !== otherIds.length)
444
- return false;
445
- return myIds.every((id, i) => id === otherIds[i]);
446
- }
447
- toJsonObject() {
448
- const originError = this.originError ? {
449
- name: this.originError.name,
450
- message: this.originError.cleanMessage ?? this.originError.message,
451
- stack: this.originError.stack,
452
- cause: this.originError.cause
453
- } : undefined;
454
- const def = {
455
- domain: this.def.domain,
456
- allDomains: this.def.allDomains
457
- };
458
- if (this.def.defaultHttpStatusCode != null) {
459
- def["defaultHttpStatusCode"] = this.def.defaultHttpStatusCode;
460
- }
461
- if (this.def.defaultMessage != null) {
462
- def["defaultMessage"] = this.def.defaultMessage;
463
- }
464
- const errorData = {};
465
- for (const rawId of Object.keys(this._errorDataMap)) {
466
- const id = rawId;
467
- const data = this._errorDataMap[id];
468
- if (data == null)
469
- continue;
470
- let contextState;
471
- if (data.contextState.kind === "hydrated" /* hydrated */) {
472
- contextState = {
473
- kind: "unhydrated" /* unhydrated */,
474
- serialized: data.contextState.serialized
475
- };
476
- } else {
477
- contextState = data.contextState;
478
- }
479
- errorData[id] = {
480
- contextState,
481
- message: data.cleanMessage ?? data.message,
482
- httpStatusCode: data.httpStatusCode,
483
- timeAdded: data.timeAdded
484
- };
485
- }
486
- return {
487
- name: "NiceError",
488
- def,
489
- ids: this.ids,
490
- errorData,
491
- wasntNice: this.wasntNice,
492
- message: this.cleanMessage,
493
- httpStatusCode: this.httpStatusCode,
494
- timeCreated: this.timeCreated,
495
- ...this.stack != null ? { stack: this.stack } : {},
496
- originError
497
- };
498
- }
499
- toJsonString() {
500
- return JSON.stringify(this.toJsonObject());
501
- }
502
- toHttpResponse() {
503
- return new Response(this.toJsonString(), {
504
- status: this.httpStatusCode,
505
- headers: { "Content-Type": "application/json" }
506
- });
507
- }
508
- hydrate(definedNiceError) {
509
- return definedNiceError.hydrate(this);
510
- }
511
- handleWithSync(handlerInput, handlerOptions = {}) {
512
- const handlersArray = Array.isArray(handlerInput) ? handlerInput : [handlerInput];
513
- for (const handler of handlersArray) {
514
- const result = handler.handleErrorWithPromiseInspection(this, handlerOptions);
515
- if (result.matched) {
516
- if (result.isPromise) {
517
- console.warn(`[NiceError.handleWith] Handler ${result.target.identifier} returned a Promise but was called via \`handleWith\` (synchronous). ` + `The Promise will not be awaited. Use \`handleWithAsync\` for async handlers.`);
518
- }
519
- return result.isPromise ? undefined : result.handlerResponse;
520
- }
521
- }
522
- if (handlerOptions.throwOnUnhandled === true)
523
- throw this;
524
- return;
525
- }
526
- async handleWithAsync(handlerInput, handlerOptions = {}) {
527
- const handlersArray = Array.isArray(handlerInput) ? handlerInput : [handlerInput];
528
- for (const handler of handlersArray) {
529
- const result = handler.handleErrorWithPromiseInspection(this, handlerOptions);
530
- if (result.matched) {
531
- return result.isPromise ? await result.handlerPromise : result.handlerResponse;
532
- }
533
- }
534
- if (handlerOptions.throwOnUnhandled === true)
535
- throw this;
536
- return;
537
- }
538
- get isPacked() {
539
- return this._packedState != null;
540
- }
541
- pack(packType = "msg_pack") {
542
- if (this.isPacked)
543
- return this;
544
- return packError(this, packType);
545
- }
546
- unpack() {
547
- if (this._packedState == null)
548
- return this;
549
- if (this._packedState.packedAs === "msg_pack" /* msg_pack */) {
550
- this.message = this._packedState.message;
551
- }
552
- if (this._packedState.packedAs === "cause_pack" /* cause_pack */) {
553
- this.cause = this._packedState.cause;
554
- }
555
- this._packedState = undefined;
556
- delete this._packedState;
557
- return this;
558
- }
559
- }
560
-
561
- // ../nice-error/src/NiceError/NiceErrorHydrated.ts
562
- class NiceErrorHydrated extends NiceError {
563
- def;
564
- niceErrorDefined;
565
- constructor(options) {
566
- super(options);
567
- this.def = options.def;
568
- this.niceErrorDefined = options.niceErrorDefined;
569
- }
570
- addContext(context) {
571
- const newIds = Object.keys(context);
572
- const newErrorData = {};
573
- for (const id of newIds) {
574
- newErrorData[id] = this.niceErrorDefined.reconcileErrorDataForId(id, context[id]);
575
- }
576
- const mergedErrorData = {
577
- ...this._errorDataMap,
578
- ...newErrorData
579
- };
580
- const mergedIds = Array.from(new Set([...this.getIds(), ...Object.keys(context)]));
581
- return new NiceErrorHydrated({
582
- def: this.def,
583
- niceErrorDefined: this.niceErrorDefined,
584
- ids: mergedIds,
585
- errorData: mergedErrorData,
586
- message: this.cleanMessage,
587
- wasntNice: this.wasntNice,
588
- httpStatusCode: this.httpStatusCode,
589
- originError: this.originError
590
- });
591
- }
592
- addId(...args) {
593
- const [id, context] = args;
594
- const reconciledData = this.niceErrorDefined.reconcileErrorDataForId(id, context);
595
- const errorDataMap = {};
596
- errorDataMap[id] = reconciledData;
597
- const mergedContexts = {
598
- ...this._errorDataMap,
599
- ...errorDataMap
600
- };
601
- const mergedIds = Array.from(new Set([...this.getIds(), id]));
602
- return new NiceErrorHydrated({
603
- def: this.def,
604
- niceErrorDefined: this.niceErrorDefined,
605
- ids: mergedIds,
606
- errorData: mergedContexts,
607
- message: this.cleanMessage,
608
- wasntNice: this.wasntNice,
609
- httpStatusCode: this.httpStatusCode,
610
- originError: this.originError
611
- });
612
- }
613
- }
614
-
615
- // ../nice-error/src/NiceErrorDefined/NiceErrorDefined.ts
616
- class NiceErrorDomain {
617
- domain;
618
- allDomains;
619
- defaultHttpStatusCode;
620
- defaultMessage;
621
- _schema;
622
- _definedChildNiceErrors = [];
623
- _definedParentNiceError;
624
- _setPack;
625
- _packAsFn;
626
- constructor(definition) {
627
- this.domain = definition.domain;
628
- this.allDomains = definition.allDomains;
629
- this._schema = definition.schema;
630
- if (definition.packAs != null) {
631
- this._packAsFn = definition.packAs;
632
- }
633
- if (definition.defaultHttpStatusCode != null) {
634
- this.defaultHttpStatusCode = definition.defaultHttpStatusCode;
635
- }
636
- if (definition.defaultMessage != null) {
637
- this.defaultMessage = definition.defaultMessage;
638
- }
639
- }
640
- createChildDomain(subErrorDef) {
641
- const child = new NiceErrorDomain({
642
- domain: subErrorDef.domain,
643
- allDomains: [subErrorDef.domain, ...this.allDomains],
644
- schema: subErrorDef.schema,
645
- defaultHttpStatusCode: subErrorDef.defaultHttpStatusCode,
646
- defaultMessage: subErrorDef.defaultMessage
647
- });
648
- this.addChildNiceErrorDefined(child);
649
- child.addParentNiceErrorDefined(this);
650
- if (subErrorDef.packAs != null) {
651
- child._packAsFn = subErrorDef.packAs;
652
- } else if (this._setPack) {
653
- child.packAs(this._setPack);
654
- } else if (this._packAsFn) {
655
- child._packAsFn = this._packAsFn;
656
- }
657
- return child;
658
- }
659
- addParentNiceErrorDefined(parentError) {
660
- if (this._definedParentNiceError?.domain === parentError.domain) {
661
- return;
662
- }
663
- this._definedParentNiceError = {
664
- domain: parentError.domain,
665
- definedError: parentError
666
- };
667
- }
668
- addChildNiceErrorDefined(child) {
669
- if (this._definedChildNiceErrors.some((linked) => linked.domain === child.domain)) {
670
- return;
671
- }
672
- this._definedChildNiceErrors.push({
673
- domain: child.domain,
674
- definedError: child
675
- });
676
- if (this._definedParentNiceError) {
677
- this._definedParentNiceError.definedError.addChildNiceErrorDefined(child);
678
- }
679
- }
680
- packAs(pack) {
681
- this._setPack = pack;
682
- return this;
683
- }
684
- createError(input) {
685
- const err = new NiceErrorHydrated(input);
686
- const packType = this._setPack ?? this._packAsFn?.();
687
- if (packType != null && packType !== "no_pack") {
688
- return err.pack(packType);
689
- }
690
- return err;
691
- }
692
- hydrate(error) {
693
- const errDef = error.def;
694
- if (errDef.domain !== this.domain) {
695
- throw new Error(`[NiceErrorDefined.hydrate] Domain mismatch: this definition is "${this.domain}" ` + `but the error belongs to "${errDef.domain}". ` + `Call \`niceErrorDefined.is(error)\` before hydrating to ensure compatibility.`);
696
- }
697
- const finalError = error instanceof NiceError ? error : new NiceError(error);
698
- const reconciledErrorData = {};
699
- for (const id of finalError.getIds()) {
700
- const existingData = finalError.getErrorDataForId(id);
701
- if (existingData == null)
702
- continue;
703
- let contextState = existingData.contextState;
704
- if (contextState.kind === "unhydrated") {
705
- const entry = this._schema[id];
706
- const deserialize = entry?.context?.serialization?.fromJsonSerializable;
707
- if (deserialize != null) {
708
- contextState = {
709
- kind: "hydrated" /* hydrated */,
710
- value: deserialize(contextState.serialized),
711
- serialized: contextState.serialized
712
- };
713
- }
714
- }
715
- reconciledErrorData[id] = {
716
- contextState,
717
- message: existingData.cleanMessage ?? existingData.message,
718
- httpStatusCode: existingData.httpStatusCode,
719
- timeAdded: existingData.timeAdded
720
- };
721
- }
722
- return new NiceErrorHydrated({
723
- def: this._buildDef(),
724
- niceErrorDefined: this,
725
- ids: finalError.ids,
726
- errorData: reconciledErrorData,
727
- message: finalError.cleanMessage ?? finalError.message,
728
- httpStatusCode: finalError.httpStatusCode,
729
- wasntNice: finalError.wasntNice,
730
- originError: finalError.originError,
731
- timeCreated: finalError.timeCreated
732
- });
733
- }
734
- fromId(...args) {
735
- const [id, context] = args;
736
- const reconciledData = this.reconcileErrorDataForId(id, context);
737
- const errorData = {};
738
- errorData[id] = reconciledData;
739
- return this.createError({
740
- def: this._buildDef(),
741
- niceErrorDefined: this,
742
- ids: [id],
743
- errorData,
744
- message: reconciledData.cleanMessage ?? reconciledData.message,
745
- httpStatusCode: reconciledData.httpStatusCode
746
- });
747
- }
748
- fromContext(context) {
749
- const ids = Object.keys(context);
750
- if (ids.length === 0) {
751
- throw new Error("[NiceErrorDefined.fromContext] context object must contain at least one error id.");
752
- }
753
- const errorData = {};
754
- for (const id of ids) {
755
- errorData[id] = this.reconcileErrorDataForId(id, context[id]);
756
- }
757
- const primaryId = ids[0];
758
- return this.createError({
759
- def: this._buildDef(),
760
- niceErrorDefined: this,
761
- ids,
762
- errorData,
763
- message: errorData[primaryId].cleanMessage ?? errorData[primaryId].message,
764
- httpStatusCode: errorData[primaryId].httpStatusCode
765
- });
766
- }
767
- isExact(error) {
768
- if (!(error instanceof NiceError))
769
- return false;
770
- const errDef = error.def;
771
- return errDef.domain === this.domain;
772
- }
773
- isThisOrChild(error) {
774
- if (!(error instanceof NiceError))
775
- return false;
776
- const errDef = error.def;
777
- return errDef.domain === this.domain || this.allDomains.includes(errDef.domain);
778
- }
779
- isParentOf(target) {
780
- const allDomains = target instanceof NiceError ? target.def.allDomains : target.allDomains;
781
- return Array.isArray(allDomains) && allDomains.includes(this.domain);
782
- }
783
- _buildDef() {
784
- return {
785
- domain: this.domain,
786
- allDomains: this.allDomains,
787
- schema: this._schema
788
- };
789
- }
790
- _resolveMessage(id, context) {
791
- const entry = this._schema[id];
792
- if (typeof entry?.message === "function") {
793
- return entry.message(context);
794
- }
795
- if (typeof entry?.message === "string") {
796
- return entry.message;
797
- }
798
- return this.defaultMessage ?? `[${this.domain}::${id}] An error occurred.`;
799
- }
800
- _resolveHttpStatusCode(id, context) {
801
- const entry = this._schema[id];
802
- let httpStatusCode;
803
- if (typeof entry?.httpStatusCode === "function") {
804
- httpStatusCode = entry.httpStatusCode(context);
805
- }
806
- if (typeof entry?.httpStatusCode === "number") {
807
- httpStatusCode = entry.httpStatusCode;
808
- }
809
- return typeof httpStatusCode === "number" ? httpStatusCode : this.defaultHttpStatusCode ?? 500;
810
- }
811
- reconcileErrorDataForId(id, context) {
812
- const message = this._resolveMessage(id, context);
813
- const httpStatusCode = this._resolveHttpStatusCode(id, context);
814
- const entry = this._schema[id];
815
- let contextState;
816
- if (context != null && entry?.context?.serialization != null) {
817
- const serialized = entry.context.serialization.toJsonSerializable(context);
818
- contextState = { kind: "hydrated" /* hydrated */, value: context, serialized };
819
- } else {
820
- contextState = { kind: "serde_unset" /* serde_unset */, value: context };
821
- }
822
- return { contextState, message, httpStatusCode, timeAdded: Date.now() };
823
- }
824
- }
825
-
826
- // ../nice-error/src/NiceErrorDefined/defineNiceError.ts
827
- var defineNiceError = (definition) => {
828
- return new NiceErrorDomain({
829
- domain: definition.domain,
830
- allDomains: [definition.domain],
831
- schema: definition.schema,
832
- ...definition.packAs != null ? { packAs: definition.packAs } : {}
833
- });
834
- };
835
-
836
- // ../nice-error/src/NiceErrorDefined/err.ts
837
- function err(meta) {
838
- return meta ?? {};
839
- }
840
-
841
- // ../nice-error/src/internal/nice_core_errors.ts
842
- var err_nice = defineNiceError({
843
- domain: "err_nice",
844
- schema: {}
845
- });
846
- var err_cast_not_nice = err_nice.createChildDomain({
847
- domain: "err_cast_not_nice",
848
- defaultHttpStatusCode: StatusCodes.UNPROCESSABLE_ENTITY,
849
- schema: {
850
- ["native_error" /* js_error */]: err({
851
- context: {
852
- required: true
853
- },
854
- message: ({ jsError }) => `A native JavaScript Error was encountered during casting: ${jsError.message}`,
855
- httpStatusCode: StatusCodes.INTERNAL_SERVER_ERROR
856
- }),
857
- ["js_error_like_object" /* js_error_like_object */]: err({
858
- context: {
859
- required: true
860
- },
861
- message: ({ jsErrorObject }) => `An object resembling a JavaScript Error was encountered during casting: [${jsErrorObject.name}] ${jsErrorObject.message}`,
862
- httpStatusCode: StatusCodes.INTERNAL_SERVER_ERROR
863
- }),
864
- ["nullish_value" /* nullish_value */]: err({
865
- context: {
866
- required: true
867
- },
868
- message: ({ value }) => `A nullish value [${value === null ? "null" : "undefined"}] was encountered during casting`
869
- }),
870
- ["js_data_type" /* js_data_type */]: err({
871
- context: {
872
- required: true
873
- },
874
- message: ({ jsDataType, jsDataValue }) => {
875
- let inspectedValue;
876
- try {
877
- inspectedValue = JSON.stringify(jsDataValue);
878
- } catch {}
879
- return `A value of type [${jsDataType}] with value [${inspectedValue ?? "UNSERIALIZABLE"}] was encountered during casting, which is not a valid error type`;
880
- }
881
- }),
882
- ["js_other" /* js_other */]: err({
883
- context: {
884
- required: true
885
- },
886
- message: ({ jsDataValue }) => {
887
- let inspectedValue;
888
- try {
889
- inspectedValue = JSON.stringify(jsDataValue);
890
- } catch {}
891
- return `An unhandled type [${typeof jsDataValue}] with value [${inspectedValue ?? "UNSERIALIZABLE"}] was encountered during casting, which is not a valid error type`;
892
- }
893
- })
894
- }
895
- });
896
- var err_nice_handler = err_nice.createChildDomain({
897
- domain: "err_nice_handler",
898
- schema: {}
899
- });
900
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/urlToObj.js
901
- function urlToObject(url) {
902
- return {
903
- href: url.href,
904
- protocol: url.protocol,
905
- username: url.username,
906
- password: url.password,
907
- host: url.host,
908
- hostname: url.hostname,
909
- port: url.port,
910
- pathname: url.pathname,
911
- search: url.search,
912
- searchParams: [...url.searchParams].map(([key, value]) => ({ key, value })),
913
- hash: url.hash,
914
- origin: url.origin
915
- };
916
- }
917
-
918
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/prettyLogStyles.js
919
- var prettyLogStyles = {
920
- reset: [0, 0],
921
- bold: [1, 22],
922
- dim: [2, 22],
923
- italic: [3, 23],
924
- underline: [4, 24],
925
- overline: [53, 55],
926
- inverse: [7, 27],
927
- hidden: [8, 28],
928
- strikethrough: [9, 29],
929
- black: [30, 39],
930
- red: [31, 39],
931
- green: [32, 39],
932
- yellow: [33, 39],
933
- blue: [34, 39],
934
- magenta: [35, 39],
935
- cyan: [36, 39],
936
- white: [37, 39],
937
- blackBright: [90, 39],
938
- redBright: [91, 39],
939
- greenBright: [92, 39],
940
- yellowBright: [93, 39],
941
- blueBright: [94, 39],
942
- magentaBright: [95, 39],
943
- cyanBright: [96, 39],
944
- whiteBright: [97, 39],
945
- bgBlack: [40, 49],
946
- bgRed: [41, 49],
947
- bgGreen: [42, 49],
948
- bgYellow: [43, 49],
949
- bgBlue: [44, 49],
950
- bgMagenta: [45, 49],
951
- bgCyan: [46, 49],
952
- bgWhite: [47, 49],
953
- bgBlackBright: [100, 49],
954
- bgRedBright: [101, 49],
955
- bgGreenBright: [102, 49],
956
- bgYellowBright: [103, 49],
957
- bgBlueBright: [104, 49],
958
- bgMagentaBright: [105, 49],
959
- bgCyanBright: [106, 49],
960
- bgWhiteBright: [107, 49]
961
- };
962
-
963
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/formatTemplate.js
964
- function formatTemplate(settings, template, values, hideUnsetPlaceholder = false) {
965
- const templateString = String(template);
966
- const ansiColorWrap = (placeholderValue, code) => `\x1B[${code[0]}m${placeholderValue}\x1B[${code[1]}m`;
967
- const styleWrap = (value, style) => {
968
- if (style != null && typeof style === "string") {
969
- return ansiColorWrap(value, prettyLogStyles[style]);
970
- } else if (style != null && Array.isArray(style)) {
971
- return style.reduce((prevValue, thisStyle) => styleWrap(prevValue, thisStyle), value);
972
- } else {
973
- if (style != null && style[value.trim()] != null) {
974
- return styleWrap(value, style[value.trim()]);
975
- } else if (style != null && style["*"] != null) {
976
- return styleWrap(value, style["*"]);
977
- } else {
978
- return value;
979
- }
980
- }
981
- };
982
- const defaultStyle = null;
983
- return templateString.replace(/{{(.+?)}}/g, (_, placeholder) => {
984
- const value = values[placeholder] != null ? String(values[placeholder]) : hideUnsetPlaceholder ? "" : _;
985
- return settings.stylePrettyLogs ? styleWrap(value, settings?.prettyLogStyles?.[placeholder] ?? defaultStyle) + ansiColorWrap("", prettyLogStyles.reset) : value;
986
- });
987
- }
988
-
989
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/formatNumberAddZeros.js
990
- function formatNumberAddZeros(value, digits = 2, addNumber = 0) {
991
- if (value != null && isNaN(value)) {
992
- return "";
993
- }
994
- value = value != null ? value + addNumber : value;
995
- return digits === 2 ? value == null ? "--" : value < 10 ? "0" + value : value.toString() : value == null ? "---" : value < 10 ? "00" + value : value < 100 ? "0" + value : value.toString();
996
- }
997
-
998
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/metaFormatting.js
999
- function buildPrettyMeta(settings, meta) {
1000
- if (meta == null) {
1001
- return {
1002
- text: "",
1003
- template: settings.prettyLogTemplate,
1004
- placeholders: {}
1005
- };
1006
- }
1007
- let template = settings.prettyLogTemplate;
1008
- const placeholderValues = {};
1009
- if (template.includes("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}")) {
1010
- template = template.replace("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}", "{{dateIsoStr}}");
1011
- } else {
1012
- if (settings.prettyLogTimeZone === "UTC") {
1013
- placeholderValues["yyyy"] = meta.date?.getUTCFullYear() ?? "----";
1014
- placeholderValues["mm"] = formatNumberAddZeros(meta.date?.getUTCMonth(), 2, 1);
1015
- placeholderValues["dd"] = formatNumberAddZeros(meta.date?.getUTCDate(), 2);
1016
- placeholderValues["hh"] = formatNumberAddZeros(meta.date?.getUTCHours(), 2);
1017
- placeholderValues["MM"] = formatNumberAddZeros(meta.date?.getUTCMinutes(), 2);
1018
- placeholderValues["ss"] = formatNumberAddZeros(meta.date?.getUTCSeconds(), 2);
1019
- placeholderValues["ms"] = formatNumberAddZeros(meta.date?.getUTCMilliseconds(), 3);
1020
- } else {
1021
- placeholderValues["yyyy"] = meta.date?.getFullYear() ?? "----";
1022
- placeholderValues["mm"] = formatNumberAddZeros(meta.date?.getMonth(), 2, 1);
1023
- placeholderValues["dd"] = formatNumberAddZeros(meta.date?.getDate(), 2);
1024
- placeholderValues["hh"] = formatNumberAddZeros(meta.date?.getHours(), 2);
1025
- placeholderValues["MM"] = formatNumberAddZeros(meta.date?.getMinutes(), 2);
1026
- placeholderValues["ss"] = formatNumberAddZeros(meta.date?.getSeconds(), 2);
1027
- placeholderValues["ms"] = formatNumberAddZeros(meta.date?.getMilliseconds(), 3);
1028
- }
1029
- }
1030
- const dateInSettingsTimeZone = settings.prettyLogTimeZone === "UTC" ? meta.date : meta.date != null ? new Date(meta.date.getTime() - meta.date.getTimezoneOffset() * 60000) : undefined;
1031
- placeholderValues["rawIsoStr"] = dateInSettingsTimeZone?.toISOString() ?? "";
1032
- placeholderValues["dateIsoStr"] = dateInSettingsTimeZone?.toISOString().replace("T", " ").replace("Z", "") ?? "";
1033
- placeholderValues["logLevelName"] = meta.logLevelName;
1034
- placeholderValues["fileNameWithLine"] = meta.path?.fileNameWithLine ?? "";
1035
- placeholderValues["filePathWithLine"] = meta.path?.filePathWithLine ?? "";
1036
- placeholderValues["fullFilePath"] = meta.path?.fullFilePath ?? "";
1037
- let parentNamesString = settings.parentNames?.join(settings.prettyErrorParentNamesSeparator);
1038
- parentNamesString = parentNamesString != null && meta.name != null ? parentNamesString + settings.prettyErrorParentNamesSeparator : undefined;
1039
- const combinedName = meta.name != null || parentNamesString != null ? `${parentNamesString ?? ""}${meta.name ?? ""}` : "";
1040
- placeholderValues["name"] = combinedName;
1041
- placeholderValues["nameWithDelimiterPrefix"] = combinedName.length > 0 ? settings.prettyErrorLoggerNameDelimiter + combinedName : "";
1042
- placeholderValues["nameWithDelimiterSuffix"] = combinedName.length > 0 ? combinedName + settings.prettyErrorLoggerNameDelimiter : "";
1043
- if (settings.overwrite?.addPlaceholders != null) {
1044
- settings.overwrite.addPlaceholders(meta, placeholderValues);
1045
- }
1046
- return {
1047
- text: formatTemplate(settings, template, placeholderValues),
1048
- template,
1049
- placeholders: placeholderValues
1050
- };
1051
- }
1052
-
1053
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/stackTrace.js
1054
- var DEFAULT_IGNORE_PATTERNS = [
1055
- /(?:^|[\\/])node_modules[\\/].*tslog/i,
1056
- /(?:^|[\\/])deps[\\/].*tslog/i,
1057
- /tslog[\\/]+src[\\/]+internal[\\/]/i,
1058
- /tslog[\\/]+src[\\/]BaseLogger/i,
1059
- /tslog[\\/]+src[\\/]index/i
1060
- ];
1061
- function splitStackLines(error) {
1062
- const stack = typeof error?.stack === "string" ? error.stack : undefined;
1063
- if (stack == null || stack.length === 0) {
1064
- return [];
1065
- }
1066
- return stack.split(`
1067
- `).map((line) => line.trimEnd());
1068
- }
1069
- function sanitizeStackLines(lines) {
1070
- return lines.filter((line) => line.length > 0 && !/^\s*Error\b/.test(line));
1071
- }
1072
- function toStackFrames(lines, parseLine) {
1073
- const frames = [];
1074
- for (const line of lines) {
1075
- const frame = parseLine(line);
1076
- if (frame != null) {
1077
- frames.push(frame);
1078
- }
1079
- }
1080
- return frames;
1081
- }
1082
- function findFirstExternalFrameIndex(frames, ignorePatterns = DEFAULT_IGNORE_PATTERNS) {
1083
- for (let index = 0;index < frames.length; index += 1) {
1084
- const frame = frames[index];
1085
- const filePathCandidate = frame.filePath ?? "";
1086
- const fullPathCandidate = frame.fullFilePath ?? "";
1087
- if (!ignorePatterns.some((pattern) => pattern.test(filePathCandidate) || pattern.test(fullPathCandidate))) {
1088
- return index;
1089
- }
1090
- }
1091
- return 0;
1092
- }
1093
- function getCleanStackLines(error) {
1094
- return sanitizeStackLines(splitStackLines(error));
1095
- }
1096
- function buildStackTrace(error, parseLine) {
1097
- return toStackFrames(getCleanStackLines(error), parseLine);
1098
- }
1099
- function clampIndex(index, maxExclusive) {
1100
- if (index < 0) {
1101
- return 0;
1102
- }
1103
- if (index >= maxExclusive) {
1104
- return Math.max(0, maxExclusive - 1);
1105
- }
1106
- return index;
1107
- }
1108
- function getDefaultIgnorePatterns() {
1109
- return [...DEFAULT_IGNORE_PATTERNS];
1110
- }
1111
-
1112
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/errorUtils.js
1113
- var DEFAULT_CAUSE_DEPTH = 5;
1114
- function collectErrorCauses(error, options = {}) {
1115
- const maxDepth = options.maxDepth ?? DEFAULT_CAUSE_DEPTH;
1116
- const causes = [];
1117
- const visited = new Set;
1118
- let current = error;
1119
- let depth = 0;
1120
- while (current != null && depth < maxDepth) {
1121
- const cause = current?.cause;
1122
- if (cause == null || visited.has(cause)) {
1123
- break;
1124
- }
1125
- visited.add(cause);
1126
- causes.push(toError(cause));
1127
- current = cause;
1128
- depth += 1;
1129
- }
1130
- return causes;
1131
- }
1132
- function toError(value) {
1133
- if (value instanceof Error) {
1134
- return value;
1135
- }
1136
- const error = new Error(typeof value === "string" ? value : JSON.stringify(value));
1137
- if (typeof value === "object" && value != null) {
1138
- Object.assign(error, value);
1139
- }
1140
- return error;
1141
- }
1142
-
1143
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/jsonStringifyRecursive.js
1144
- function jsonStringifyRecursive(obj) {
1145
- const cache = new Set;
1146
- return JSON.stringify(obj, (key, value) => {
1147
- if (typeof value === "object" && value !== null) {
1148
- if (cache.has(value)) {
1149
- return "[Circular]";
1150
- }
1151
- cache.add(value);
1152
- }
1153
- if (typeof value === "bigint") {
1154
- return `${value}`;
1155
- }
1156
- if (typeof value === "undefined") {
1157
- return "[undefined]";
1158
- }
1159
- return value;
1160
- });
1161
- }
1162
-
1163
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/util.inspect.polyfill.js
1164
- function inspect(obj, opts) {
1165
- const ctx = {
1166
- seen: [],
1167
- stylize: stylizeNoColor
1168
- };
1169
- if (opts != null) {
1170
- _extend(ctx, opts);
1171
- }
1172
- if (isUndefined(ctx.showHidden))
1173
- ctx.showHidden = false;
1174
- if (isUndefined(ctx.depth))
1175
- ctx.depth = 2;
1176
- if (isUndefined(ctx.colors))
1177
- ctx.colors = true;
1178
- if (isUndefined(ctx.customInspect))
1179
- ctx.customInspect = true;
1180
- if (ctx.colors)
1181
- ctx.stylize = stylizeWithColor;
1182
- return formatValue(ctx, obj, ctx.depth);
1183
- }
1184
- inspect.colors = prettyLogStyles;
1185
- inspect.styles = {
1186
- special: "cyan",
1187
- number: "yellow",
1188
- boolean: "yellow",
1189
- undefined: "grey",
1190
- null: "bold",
1191
- string: "green",
1192
- date: "magenta",
1193
- regexp: "red"
1194
- };
1195
- function isBoolean(arg) {
1196
- return typeof arg === "boolean";
1197
- }
1198
- function isUndefined(arg) {
1199
- return arg === undefined;
1200
- }
1201
- function stylizeNoColor(str) {
1202
- return str;
1203
- }
1204
- function stylizeWithColor(str, styleType) {
1205
- const style = inspect.styles[styleType];
1206
- if (style != null && inspect?.colors?.[style]?.[0] != null && inspect?.colors?.[style]?.[1] != null) {
1207
- return "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + inspect.colors[style][1] + "m";
1208
- } else {
1209
- return str;
1210
- }
1211
- }
1212
- function isFunction(arg) {
1213
- return typeof arg === "function";
1214
- }
1215
- function isString(arg) {
1216
- return typeof arg === "string";
1217
- }
1218
- function isNumber(arg) {
1219
- return typeof arg === "number";
1220
- }
1221
- function isNull(arg) {
1222
- return arg === null;
1223
- }
1224
- function hasOwn(obj, prop) {
1225
- return Object.prototype.hasOwnProperty.call(obj, prop);
1226
- }
1227
- function isRegExp(re) {
1228
- return isObject(re) && objectToString(re) === "[object RegExp]";
1229
- }
1230
- function isObject(arg) {
1231
- return typeof arg === "object" && arg !== null;
1232
- }
1233
- function isError(e) {
1234
- return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error);
1235
- }
1236
- function isDate(d) {
1237
- return isObject(d) && objectToString(d) === "[object Date]";
1238
- }
1239
- function objectToString(o) {
1240
- return Object.prototype.toString.call(o);
1241
- }
1242
- function arrayToHash(array) {
1243
- const hash = {};
1244
- array.forEach((val) => {
1245
- hash[val] = true;
1246
- });
1247
- return hash;
1248
- }
1249
- function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
1250
- const output = [];
1251
- for (let i = 0, l = value.length;i < l; ++i) {
1252
- if (hasOwn(value, String(i))) {
1253
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
1254
- } else {
1255
- output.push("");
1256
- }
1257
- }
1258
- keys.forEach((key) => {
1259
- if (!key.match(/^\d+$/)) {
1260
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
1261
- }
1262
- });
1263
- return output;
1264
- }
1265
- function formatError(value) {
1266
- return "[" + Error.prototype.toString.call(value) + "]";
1267
- }
1268
- function formatValue(ctx, value, recurseTimes = 0) {
1269
- if (ctx.customInspect && value != null && isFunction(value) && value?.inspect !== inspect && !(value?.constructor && value?.constructor.prototype === value)) {
1270
- if (typeof value.inspect !== "function" && value.toString != null) {
1271
- return value.toString();
1272
- }
1273
- let ret = value?.inspect(recurseTimes, ctx);
1274
- if (!isString(ret)) {
1275
- ret = formatValue(ctx, ret, recurseTimes);
1276
- }
1277
- return ret;
1278
- }
1279
- const primitive = formatPrimitive(ctx, value);
1280
- if (primitive) {
1281
- return primitive;
1282
- }
1283
- let keys = Object.keys(value);
1284
- const visibleKeys = arrayToHash(keys);
1285
- try {
1286
- if (ctx.showHidden && Object.getOwnPropertyNames) {
1287
- keys = Object.getOwnPropertyNames(value);
1288
- }
1289
- } catch {}
1290
- if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) {
1291
- return formatError(value);
1292
- }
1293
- if (keys.length === 0) {
1294
- if (isFunction(ctx.stylize)) {
1295
- if (isFunction(value)) {
1296
- const name = value.name ? ": " + value.name : "";
1297
- return ctx.stylize("[Function" + name + "]", "special");
1298
- }
1299
- if (isRegExp(value)) {
1300
- return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
1301
- }
1302
- if (isDate(value)) {
1303
- return ctx.stylize(Date.prototype.toISOString.call(value), "date");
1304
- }
1305
- if (isError(value)) {
1306
- return formatError(value);
1307
- }
1308
- } else {
1309
- return value;
1310
- }
1311
- }
1312
- let base = "";
1313
- let array = false;
1314
- let braces = [`{
1315
- `, `
1316
- }`];
1317
- if (Array.isArray(value)) {
1318
- array = true;
1319
- braces = [`[
1320
- `, `
1321
- ]`];
1322
- }
1323
- if (isFunction(value)) {
1324
- const n = value.name ? ": " + value.name : "";
1325
- base = " [Function" + n + "]";
1326
- }
1327
- if (isRegExp(value)) {
1328
- base = " " + RegExp.prototype.toString.call(value);
1329
- }
1330
- if (isDate(value)) {
1331
- base = " " + Date.prototype.toUTCString.call(value);
1332
- }
1333
- if (isError(value)) {
1334
- base = " " + formatError(value);
1335
- }
1336
- if (keys.length === 0 && (!array || value.length == 0)) {
1337
- return braces[0] + base + braces[1];
1338
- }
1339
- if (recurseTimes < 0) {
1340
- if (isRegExp(value)) {
1341
- return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
1342
- } else {
1343
- return ctx.stylize("[Object]", "special");
1344
- }
1345
- }
1346
- ctx.seen.push(value);
1347
- let output;
1348
- if (array) {
1349
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
1350
- } else {
1351
- output = keys.map((key) => {
1352
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
1353
- });
1354
- }
1355
- ctx.seen.pop();
1356
- return reduceToSingleString(output, base, braces);
1357
- }
1358
- function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
1359
- let name, str;
1360
- let desc = { value: undefined };
1361
- try {
1362
- desc.value = value[key];
1363
- } catch {}
1364
- try {
1365
- if (Object.getOwnPropertyDescriptor) {
1366
- desc = Object.getOwnPropertyDescriptor(value, key) || desc;
1367
- }
1368
- } catch {}
1369
- if (desc.get) {
1370
- if (desc.set) {
1371
- str = ctx.stylize("[Getter/Setter]", "special");
1372
- } else {
1373
- str = ctx.stylize("[Getter]", "special");
1374
- }
1375
- } else {
1376
- if (desc.set) {
1377
- str = ctx.stylize("[Setter]", "special");
1378
- }
1379
- }
1380
- if (!hasOwn(visibleKeys, key)) {
1381
- name = "[" + key + "]";
1382
- }
1383
- if (!str) {
1384
- if (ctx.seen.indexOf(desc.value) < 0) {
1385
- if (isNull(recurseTimes)) {
1386
- str = formatValue(ctx, desc.value, undefined);
1387
- } else {
1388
- str = formatValue(ctx, desc.value, recurseTimes - 1);
1389
- }
1390
- if (str.indexOf(`
1391
- `) > -1) {
1392
- if (array) {
1393
- str = str.split(`
1394
- `).map((line) => {
1395
- return " " + line;
1396
- }).join(`
1397
- `).substr(2);
1398
- } else {
1399
- str = `
1400
- ` + str.split(`
1401
- `).map((line) => {
1402
- return " " + line;
1403
- }).join(`
1404
- `);
1405
- }
1406
- }
1407
- } else {
1408
- str = ctx.stylize("[Circular]", "special");
1409
- }
1410
- }
1411
- if (isUndefined(name)) {
1412
- if (array && key.match(/^\d+$/)) {
1413
- return str;
1414
- }
1415
- name = JSON.stringify("" + key);
1416
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
1417
- name = name.substr(1, name.length - 2);
1418
- name = ctx.stylize(name, "name");
1419
- } else {
1420
- name = name.replace(/'/g, "\\'").replace(/\\"/g, "\\'").replace(/(^"|"$)/g, "'");
1421
- name = ctx.stylize(name, "string");
1422
- }
1423
- }
1424
- return name + ": " + str;
1425
- }
1426
- function formatPrimitive(ctx, value) {
1427
- if (isUndefined(value))
1428
- return ctx.stylize("undefined", "undefined");
1429
- if (isString(value)) {
1430
- const simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, "\\'") + "'";
1431
- return ctx.stylize(simple, "string");
1432
- }
1433
- if (isNumber(value))
1434
- return ctx.stylize("" + value, "number");
1435
- if (isBoolean(value))
1436
- return ctx.stylize("" + value, "boolean");
1437
- if (isNull(value))
1438
- return ctx.stylize("null", "null");
1439
- }
1440
- function reduceToSingleString(output, base, braces) {
1441
- return braces[0] + (base === "" ? "" : base + `
1442
- `) + " " + output.join(`,
1443
- `) + " " + braces[1];
1444
- }
1445
- function _extend(origin, add) {
1446
- const typedOrigin = { ...origin };
1447
- if (!add || !isObject(add))
1448
- return origin;
1449
- const clonedAdd = { ...add };
1450
- const keys = Object.keys(add);
1451
- let i = keys.length;
1452
- while (i--) {
1453
- typedOrigin[keys[i]] = clonedAdd[keys[i]];
1454
- }
1455
- return typedOrigin;
1456
- }
1457
- function formatWithOptions(inspectOptions, ...args) {
1458
- const ctx = {
1459
- seen: [],
1460
- stylize: stylizeNoColor
1461
- };
1462
- if (inspectOptions != null) {
1463
- _extend(ctx, inspectOptions);
1464
- }
1465
- const first = args[0];
1466
- let a = 0;
1467
- let str = "";
1468
- let join = "";
1469
- if (typeof first === "string") {
1470
- if (args.length === 1) {
1471
- return first;
1472
- }
1473
- let tempStr;
1474
- let lastPos = 0;
1475
- for (let i = 0;i < first.length - 1; i++) {
1476
- if (first.charCodeAt(i) === 37) {
1477
- const nextChar = first.charCodeAt(++i);
1478
- if (a + 1 !== args.length) {
1479
- switch (nextChar) {
1480
- case 115: {
1481
- const tempArg = args[++a];
1482
- if (typeof tempArg === "number") {
1483
- tempStr = formatPrimitive(ctx, tempArg);
1484
- } else if (typeof tempArg === "bigint") {
1485
- tempStr = formatPrimitive(ctx, tempArg);
1486
- } else if (typeof tempArg !== "object" || tempArg === null) {
1487
- tempStr = String(tempArg);
1488
- } else {
1489
- tempStr = inspect(tempArg, {
1490
- ...inspectOptions,
1491
- compact: 3,
1492
- colors: false,
1493
- depth: 0
1494
- });
1495
- }
1496
- break;
1497
- }
1498
- case 106:
1499
- tempStr = jsonStringifyRecursive(args[++a]);
1500
- break;
1501
- case 100: {
1502
- const tempNum = args[++a];
1503
- if (typeof tempNum === "bigint") {
1504
- tempStr = formatPrimitive(ctx, tempNum);
1505
- } else if (typeof tempNum === "symbol") {
1506
- tempStr = "NaN";
1507
- } else {
1508
- tempStr = formatPrimitive(ctx, tempNum);
1509
- }
1510
- break;
1511
- }
1512
- case 79:
1513
- tempStr = inspect(args[++a], inspectOptions);
1514
- break;
1515
- case 111:
1516
- tempStr = inspect(args[++a], {
1517
- ...inspectOptions,
1518
- showHidden: true,
1519
- showProxy: true,
1520
- depth: 4
1521
- });
1522
- break;
1523
- case 105: {
1524
- const tempInteger = args[++a];
1525
- if (typeof tempInteger === "bigint") {
1526
- tempStr = formatPrimitive(ctx, tempInteger);
1527
- } else if (typeof tempInteger === "symbol") {
1528
- tempStr = "NaN";
1529
- } else {
1530
- tempStr = formatPrimitive(ctx, parseInt(tempStr));
1531
- }
1532
- break;
1533
- }
1534
- case 102: {
1535
- const tempFloat = args[++a];
1536
- if (typeof tempFloat === "symbol") {
1537
- tempStr = "NaN";
1538
- } else {
1539
- tempStr = formatPrimitive(ctx, parseInt(tempFloat));
1540
- }
1541
- break;
1542
- }
1543
- case 99:
1544
- a += 1;
1545
- tempStr = "";
1546
- break;
1547
- case 37:
1548
- str += first.slice(lastPos, i);
1549
- lastPos = i + 1;
1550
- continue;
1551
- default:
1552
- continue;
1553
- }
1554
- if (lastPos !== i - 1) {
1555
- str += first.slice(lastPos, i - 1);
1556
- }
1557
- str += tempStr;
1558
- lastPos = i + 1;
1559
- } else if (nextChar === 37) {
1560
- str += first.slice(lastPos, i);
1561
- lastPos = i + 1;
1562
- }
1563
- }
1564
- }
1565
- if (lastPos !== 0) {
1566
- a++;
1567
- join = " ";
1568
- if (lastPos < first.length) {
1569
- str += first.slice(lastPos);
1570
- }
1571
- }
1572
- }
1573
- while (a < args.length) {
1574
- const value = args[a];
1575
- str += join;
1576
- str += typeof value !== "string" ? inspect(value, inspectOptions) : value;
1577
- join = " ";
1578
- a++;
1579
- }
1580
- return str;
1581
- }
1582
-
1583
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/internal/environment.js
1584
- function safeGetCwd() {
1585
- try {
1586
- const nodeProcess = globalThis?.process;
1587
- if (typeof nodeProcess?.cwd === "function") {
1588
- return nodeProcess.cwd();
1589
- }
1590
- } catch {}
1591
- try {
1592
- const deno = globalThis?.["Deno"];
1593
- if (typeof deno?.cwd === "function") {
1594
- return deno.cwd();
1595
- }
1596
- } catch {}
1597
- return;
1598
- }
1599
- function isBrowserEnvironment() {
1600
- return typeof window !== "undefined" && typeof document !== "undefined";
1601
- }
1602
- function consoleSupportsCssStyling() {
1603
- if (!isBrowserEnvironment()) {
1604
- return false;
1605
- }
1606
- const navigatorObj = globalThis?.navigator;
1607
- const userAgent = navigatorObj?.userAgent ?? "";
1608
- if (/firefox/i.test(userAgent)) {
1609
- return true;
1610
- }
1611
- const windowObj = globalThis;
1612
- if (windowObj?.CSS?.supports?.("color", "#000")) {
1613
- return true;
1614
- }
1615
- return /safari/i.test(userAgent) && !/chrome/i.test(userAgent);
1616
- }
1617
-
1618
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/BaseLogger.js
1619
- function createLoggerEnvironment() {
1620
- const runtimeInfo = detectRuntimeInfo();
1621
- const meta = createRuntimeMeta(runtimeInfo);
1622
- const usesBrowserStack = runtimeInfo.name === "browser" || runtimeInfo.name === "worker";
1623
- const callerIgnorePatterns = usesBrowserStack ? [...getDefaultIgnorePatterns(), /node_modules[\\/].*tslog/i] : [...getDefaultIgnorePatterns(), /node:(?:internal|vm)/i, /\binternal[\\/]/i];
1624
- let cachedCwd;
1625
- const environment = {
1626
- getMeta(logLevelId, logLevelName, stackDepthLevel, hideLogPositionForPerformance, name, parentNames) {
1627
- return Object.assign({}, meta, {
1628
- name,
1629
- parentNames,
1630
- date: new Date,
1631
- logLevelId,
1632
- logLevelName,
1633
- path: !hideLogPositionForPerformance ? environment.getCallerStackFrame(stackDepthLevel) : undefined
1634
- });
1635
- },
1636
- getCallerStackFrame(stackDepthLevel, error = new Error) {
1637
- const frames = buildStackTrace(error, (line) => parseStackLine(line));
1638
- if (frames.length === 0) {
1639
- return {};
1640
- }
1641
- const autoIndex = findFirstExternalFrameIndex(frames, callerIgnorePatterns);
1642
- const useManualIndex = Number.isFinite(stackDepthLevel) && stackDepthLevel >= 0;
1643
- const resolvedIndex = useManualIndex ? clampIndex(stackDepthLevel, frames.length) : clampIndex(autoIndex, frames.length);
1644
- return frames[resolvedIndex] ?? {};
1645
- },
1646
- getErrorTrace(error) {
1647
- return buildStackTrace(error, (line) => parseStackLine(line));
1648
- },
1649
- isError(value) {
1650
- return isNativeError(value);
1651
- },
1652
- isBuffer(value) {
1653
- return typeof Buffer !== "undefined" && typeof Buffer.isBuffer === "function" ? Buffer.isBuffer(value) : false;
1654
- },
1655
- prettyFormatLogObj(maskedArgs, settings) {
1656
- return maskedArgs.reduce((result, arg) => {
1657
- if (environment.isError(arg)) {
1658
- result.errors.push(environment.prettyFormatErrorObj(arg, settings));
1659
- } else {
1660
- result.args.push(arg);
1661
- }
1662
- return result;
1663
- }, { args: [], errors: [] });
1664
- },
1665
- prettyFormatErrorObj(error, settings) {
1666
- const stackLines = formatStackFrames(environment.getErrorTrace(error), settings);
1667
- const causeSections = collectErrorCauses(error).map((cause, index) => {
1668
- const header = `Caused by (${index + 1}): ${cause.name ?? "Error"}${cause.message ? `: ${cause.message}` : ""}`;
1669
- const frames = formatStackFrames(buildStackTrace(cause, (line) => parseStackLine(line)), settings);
1670
- return [header, ...frames].join(`
1671
- `);
1672
- });
1673
- const placeholderValuesError = {
1674
- errorName: ` ${error.name} `,
1675
- errorMessage: formatErrorMessage(error),
1676
- errorStack: [...stackLines, ...causeSections].join(`
1677
- `)
1678
- };
1679
- return formatTemplate(settings, settings.prettyErrorTemplate, placeholderValuesError);
1680
- },
1681
- transportFormatted(logMetaMarkup, logArgs, logErrors, logMeta, settings) {
1682
- const prettyLogs = settings.stylePrettyLogs !== false;
1683
- const logErrorsStr = (logErrors.length > 0 && logArgs.length > 0 ? `
1684
- ` : "") + logErrors.join(`
1685
- `);
1686
- const sanitizedMetaMarkup = stripAnsi(logMetaMarkup);
1687
- const metaMarkupForText = prettyLogs ? logMetaMarkup : sanitizedMetaMarkup;
1688
- if (shouldUseCss(prettyLogs)) {
1689
- settings.prettyInspectOptions.colors = false;
1690
- const formattedArgs2 = formatWithOptionsSafe(settings.prettyInspectOptions, logArgs);
1691
- const cssMeta = logMeta != null ? buildCssMetaOutput(settings, logMeta) : { text: sanitizedMetaMarkup, styles: [] };
1692
- const hasCssMeta = cssMeta.text.length > 0 && cssMeta.styles.length > 0;
1693
- const metaOutput = hasCssMeta ? cssMeta.text : sanitizedMetaMarkup;
1694
- const output = metaOutput + formattedArgs2 + logErrorsStr;
1695
- if (hasCssMeta) {
1696
- console.log(output, ...cssMeta.styles);
1697
- } else {
1698
- console.log(output);
1699
- }
1700
- return;
1701
- }
1702
- settings.prettyInspectOptions.colors = prettyLogs;
1703
- const formattedArgs = formatWithOptionsSafe(settings.prettyInspectOptions, logArgs);
1704
- console.log(metaMarkupForText + formattedArgs + logErrorsStr);
1705
- },
1706
- transportJSON(json) {
1707
- console.log(jsonStringifyRecursive(json));
1708
- }
1709
- };
1710
- if (getNodeEnv() === "test") {
1711
- environment.__resetWorkingDirectoryCacheForTests = () => {
1712
- cachedCwd = undefined;
1713
- };
1714
- }
1715
- return environment;
1716
- function parseStackLine(line) {
1717
- return usesBrowserStack ? parseBrowserStackLine(line) : parseServerStackLine(line);
1718
- }
1719
- function parseServerStackLine(rawLine) {
1720
- if (typeof rawLine !== "string" || rawLine.length === 0) {
1721
- return;
1722
- }
1723
- const trimmedLine = rawLine.trim();
1724
- if (!trimmedLine.includes(" at ") && !trimmedLine.startsWith("at ")) {
1725
- return;
1726
- }
1727
- const line = trimmedLine.replace(/^at\s+/, "");
1728
- let method;
1729
- let location = line;
1730
- const methodMatch = line.match(/^(.*?)\s+\((.*)\)$/);
1731
- if (methodMatch) {
1732
- method = methodMatch[1];
1733
- location = methodMatch[2];
1734
- }
1735
- const sanitizedLocation = location.replace(/^\(/, "").replace(/\)$/, "");
1736
- const withoutQuery = sanitizedLocation.replace(/\?.*$/, "");
1737
- let fileLine;
1738
- let fileColumn;
1739
- let filePathCandidate = withoutQuery;
1740
- const segments = withoutQuery.split(":");
1741
- if (segments.length >= 3 && /^\d+$/.test(segments[segments.length - 1] ?? "")) {
1742
- fileColumn = segments.pop();
1743
- fileLine = segments.pop();
1744
- filePathCandidate = segments.join(":");
1745
- } else if (segments.length >= 2 && /^\d+$/.test(segments[segments.length - 1] ?? "")) {
1746
- fileLine = segments.pop();
1747
- filePathCandidate = segments.join(":");
1748
- }
1749
- let normalizedPath = filePathCandidate.replace(/^file:\/\//, "");
1750
- const cwd = getWorkingDirectory();
1751
- if (cwd != null && normalizedPath.startsWith(cwd)) {
1752
- normalizedPath = normalizedPath.slice(cwd.length);
1753
- normalizedPath = normalizedPath.replace(/^[\\/]/, "");
1754
- }
1755
- if (normalizedPath.length === 0) {
1756
- normalizedPath = filePathCandidate;
1757
- }
1758
- const normalizedPathWithoutLine = normalizeFilePath(normalizedPath);
1759
- const effectivePath = normalizedPathWithoutLine.length > 0 ? normalizedPathWithoutLine : normalizedPath;
1760
- const pathSegments = effectivePath.split(/\\|\//);
1761
- const fileName = pathSegments[pathSegments.length - 1];
1762
- const fileNameWithLine = fileName && fileLine ? `${fileName}:${fileLine}` : undefined;
1763
- const filePathWithLine = effectivePath && fileLine ? `${effectivePath}:${fileLine}` : undefined;
1764
- return {
1765
- fullFilePath: sanitizedLocation,
1766
- fileName,
1767
- fileNameWithLine,
1768
- fileColumn,
1769
- fileLine,
1770
- filePath: effectivePath,
1771
- filePathWithLine,
1772
- method
1773
- };
1774
- }
1775
- function parseBrowserStackLine(line) {
1776
- const href = globalThis.location?.origin;
1777
- if (line == null) {
1778
- return;
1779
- }
1780
- const match = line.match(BROWSER_PATH_REGEX);
1781
- if (!match) {
1782
- return;
1783
- }
1784
- const filePath = match[1]?.replace(/\?.*$/, "");
1785
- if (filePath == null) {
1786
- return;
1787
- }
1788
- const pathParts = filePath.split("/");
1789
- const fileLine = match[2];
1790
- const fileColumn = match[3];
1791
- const fileName = pathParts[pathParts.length - 1];
1792
- return {
1793
- fullFilePath: href ? `${href}${filePath}` : filePath,
1794
- fileName,
1795
- fileNameWithLine: fileName && fileLine ? `${fileName}:${fileLine}` : undefined,
1796
- fileColumn,
1797
- fileLine,
1798
- filePath,
1799
- filePathWithLine: fileLine ? `${filePath}:${fileLine}` : undefined,
1800
- method: undefined
1801
- };
1802
- }
1803
- function formatStackFrames(frames, settings) {
1804
- return frames.map((stackFrame) => formatTemplate(settings, settings.prettyErrorStackTemplate, { ...stackFrame }, true));
1805
- }
1806
- function formatErrorMessage(error) {
1807
- return Object.getOwnPropertyNames(error).filter((key) => key !== "stack" && key !== "cause").reduce((result, key) => {
1808
- const value = error[key];
1809
- if (typeof value === "function") {
1810
- return result;
1811
- }
1812
- result.push(String(value));
1813
- return result;
1814
- }, []).join(", ");
1815
- }
1816
- function shouldUseCss(prettyLogs) {
1817
- return prettyLogs && (runtimeInfo.name === "browser" || runtimeInfo.name === "worker") && consoleSupportsCssStyling();
1818
- }
1819
- function stripAnsi(value) {
1820
- return value.replace(ANSI_REGEX, "");
1821
- }
1822
- function buildCssMetaOutput(settings, metaValue) {
1823
- if (metaValue == null) {
1824
- return { text: "", styles: [] };
1825
- }
1826
- const { template, placeholders } = buildPrettyMeta(settings, metaValue);
1827
- const parts = [];
1828
- const styles = [];
1829
- let lastIndex = 0;
1830
- const placeholderRegex = /{{(.+?)}}/g;
1831
- let match;
1832
- while ((match = placeholderRegex.exec(template)) != null) {
1833
- if (match.index > lastIndex) {
1834
- parts.push(template.slice(lastIndex, match.index));
1835
- }
1836
- const key = match[1];
1837
- const rawValue = placeholders[key] != null ? String(placeholders[key]) : "";
1838
- const tokens = collectStyleTokens(settings.prettyLogStyles?.[key], rawValue);
1839
- const css = tokensToCss(tokens);
1840
- if (css.length > 0) {
1841
- parts.push(`%c${rawValue}%c`);
1842
- styles.push(css, "");
1843
- } else {
1844
- parts.push(rawValue);
1845
- }
1846
- lastIndex = placeholderRegex.lastIndex;
1847
- }
1848
- if (lastIndex < template.length) {
1849
- parts.push(template.slice(lastIndex));
1850
- }
1851
- return {
1852
- text: parts.join(""),
1853
- styles
1854
- };
1855
- }
1856
- function collectStyleTokens(style, value) {
1857
- if (style == null) {
1858
- return [];
1859
- }
1860
- if (typeof style === "string") {
1861
- return [style];
1862
- }
1863
- if (Array.isArray(style)) {
1864
- return style.flatMap((token) => collectStyleTokens(token, value));
1865
- }
1866
- if (typeof style === "object") {
1867
- const normalizedValue = value.trim();
1868
- const nextStyle = style[normalizedValue] ?? style["*"];
1869
- if (nextStyle == null) {
1870
- return [];
1871
- }
1872
- return collectStyleTokens(nextStyle, value);
1873
- }
1874
- return [];
1875
- }
1876
- function tokensToCss(tokens) {
1877
- const seen = new Set;
1878
- const cssParts = [];
1879
- for (const token of tokens) {
1880
- const css = styleTokenToCss(token);
1881
- if (css != null && css.length > 0 && !seen.has(css)) {
1882
- seen.add(css);
1883
- cssParts.push(css);
1884
- }
1885
- }
1886
- return cssParts.join("; ");
1887
- }
1888
- function styleTokenToCss(token) {
1889
- const color = COLOR_TOKENS[token];
1890
- if (color != null) {
1891
- return `color: ${color}`;
1892
- }
1893
- const background = BACKGROUND_TOKENS[token];
1894
- if (background != null) {
1895
- return `background-color: ${background}`;
1896
- }
1897
- switch (token) {
1898
- case "bold":
1899
- return "font-weight: bold";
1900
- case "dim":
1901
- return "opacity: 0.75";
1902
- case "italic":
1903
- return "font-style: italic";
1904
- case "underline":
1905
- return "text-decoration: underline";
1906
- case "overline":
1907
- return "text-decoration: overline";
1908
- case "inverse":
1909
- return "filter: invert(1)";
1910
- case "hidden":
1911
- return "visibility: hidden";
1912
- case "strikethrough":
1913
- return "text-decoration: line-through";
1914
- default:
1915
- return;
1916
- }
1917
- }
1918
- function getWorkingDirectory() {
1919
- if (cachedCwd === undefined) {
1920
- cachedCwd = safeGetCwd() ?? null;
1921
- }
1922
- return cachedCwd ?? undefined;
1923
- }
1924
- function shouldCaptureHostname() {
1925
- return runtimeInfo.name === "node" || runtimeInfo.name === "deno" || runtimeInfo.name === "bun";
1926
- }
1927
- function shouldCaptureRuntimeVersion() {
1928
- return runtimeInfo.name === "node" || runtimeInfo.name === "deno" || runtimeInfo.name === "bun";
1929
- }
1930
- function createRuntimeMeta(info) {
1931
- if (info.name === "browser" || info.name === "worker") {
1932
- return {
1933
- runtime: info.name,
1934
- browser: info.userAgent
1935
- };
1936
- }
1937
- const metaStatic = {
1938
- runtime: info.name
1939
- };
1940
- if (shouldCaptureRuntimeVersion()) {
1941
- metaStatic.runtimeVersion = info.version ?? "unknown";
1942
- }
1943
- if (shouldCaptureHostname()) {
1944
- metaStatic.hostname = info.hostname ?? "unknown";
1945
- }
1946
- return metaStatic;
1947
- }
1948
- function formatWithOptionsSafe(options, args) {
1949
- try {
1950
- return formatWithOptions(options, ...args);
1951
- } catch {
1952
- return args.map(stringifyFallback).join(" ");
1953
- }
1954
- }
1955
- function stringifyFallback(value) {
1956
- if (typeof value === "string") {
1957
- return value;
1958
- }
1959
- try {
1960
- return JSON.stringify(value);
1961
- } catch {
1962
- return String(value);
1963
- }
1964
- }
1965
- function normalizeFilePath(value) {
1966
- if (typeof value !== "string" || value.length === 0) {
1967
- return value;
1968
- }
1969
- const replaced = value.replace(/\\+/g, "\\").replace(/\\/g, "/");
1970
- const hasRootDoubleSlash = replaced.startsWith("//");
1971
- const hasLeadingSlash = replaced.startsWith("/") && !hasRootDoubleSlash;
1972
- const driveMatch = replaced.match(/^[A-Za-z]:/);
1973
- const drivePrefix = driveMatch ? driveMatch[0] : "";
1974
- const withoutDrive = drivePrefix ? replaced.slice(drivePrefix.length) : replaced;
1975
- const segments = withoutDrive.split("/");
1976
- const normalizedSegments = [];
1977
- for (const segment of segments) {
1978
- if (segment === "" || segment === ".") {
1979
- continue;
1980
- }
1981
- if (segment === "..") {
1982
- if (normalizedSegments.length > 0) {
1983
- normalizedSegments.pop();
1984
- }
1985
- continue;
1986
- }
1987
- normalizedSegments.push(segment);
1988
- }
1989
- let normalized = normalizedSegments.join("/");
1990
- if (hasRootDoubleSlash) {
1991
- normalized = `//${normalized}`;
1992
- } else if (hasLeadingSlash) {
1993
- normalized = `/${normalized}`;
1994
- } else if (drivePrefix !== "") {
1995
- normalized = `${drivePrefix}${normalized.length > 0 ? `/${normalized}` : ""}`;
1996
- }
1997
- if (normalized.length === 0) {
1998
- return value;
1999
- }
2000
- return normalized;
2001
- }
2002
- function detectRuntimeInfo() {
2003
- if (isBrowserEnvironment()) {
2004
- const navigatorObj = globalThis.navigator;
2005
- return {
2006
- name: "browser",
2007
- userAgent: navigatorObj?.userAgent
2008
- };
2009
- }
2010
- const globalScope = globalThis;
2011
- if (typeof globalScope.importScripts === "function") {
2012
- return {
2013
- name: "worker",
2014
- userAgent: globalScope.navigator?.userAgent
2015
- };
2016
- }
2017
- const globalAny = globalThis;
2018
- if (globalAny.Bun != null) {
2019
- const bunVersion = globalAny.Bun.version;
2020
- return {
2021
- name: "bun",
2022
- version: bunVersion != null ? `bun/${bunVersion}` : undefined,
2023
- hostname: getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
2024
- };
2025
- }
2026
- if (globalAny.Deno != null) {
2027
- const denoHostname = resolveDenoHostname(globalAny.Deno);
2028
- const denoVersion = globalAny.Deno?.version?.deno;
2029
- return {
2030
- name: "deno",
2031
- version: denoVersion != null ? `deno/${denoVersion}` : undefined,
2032
- hostname: denoHostname ?? getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
2033
- };
2034
- }
2035
- if (globalAny.process?.versions?.node != null || globalAny.process?.version != null) {
2036
- return {
2037
- name: "node",
2038
- version: globalAny.process?.versions?.node ?? globalAny.process?.version,
2039
- hostname: getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
2040
- };
2041
- }
2042
- if (globalAny.process != null) {
2043
- return {
2044
- name: "node",
2045
- version: "unknown",
2046
- hostname: getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
2047
- };
2048
- }
2049
- return {
2050
- name: "unknown"
2051
- };
2052
- }
2053
- function getEnvironmentHostname(nodeProcess, deno, bun, location) {
2054
- const processHostname = nodeProcess?.env?.HOSTNAME ?? nodeProcess?.env?.HOST ?? nodeProcess?.env?.COMPUTERNAME;
2055
- if (processHostname != null && processHostname.length > 0) {
2056
- return processHostname;
2057
- }
2058
- const bunHostname = bun?.env?.HOSTNAME ?? bun?.env?.HOST ?? bun?.env?.COMPUTERNAME;
2059
- if (bunHostname != null && bunHostname.length > 0) {
2060
- return bunHostname;
2061
- }
2062
- try {
2063
- const denoEnvGet = deno?.env?.get;
2064
- if (typeof denoEnvGet === "function") {
2065
- const value = denoEnvGet("HOSTNAME");
2066
- if (value != null && value.length > 0) {
2067
- return value;
2068
- }
2069
- }
2070
- } catch {}
2071
- if (location?.hostname != null && location.hostname.length > 0) {
2072
- return location.hostname;
2073
- }
2074
- return;
2075
- }
2076
- function resolveDenoHostname(deno) {
2077
- try {
2078
- if (typeof deno?.hostname === "function") {
2079
- const value = deno.hostname();
2080
- if (value != null && value.length > 0) {
2081
- return value;
2082
- }
2083
- }
2084
- } catch {}
2085
- const locationHostname = globalThis.location?.hostname;
2086
- if (locationHostname != null && locationHostname.length > 0) {
2087
- return locationHostname;
2088
- }
2089
- return;
2090
- }
2091
- function getNodeEnv() {
2092
- const globalProcess = globalThis?.process;
2093
- return globalProcess?.env?.NODE_ENV;
2094
- }
2095
- function isNativeError(value) {
2096
- if (value instanceof Error) {
2097
- return true;
2098
- }
2099
- if (value != null && typeof value === "object") {
2100
- const objectTag = Object.prototype.toString.call(value);
2101
- if (/\[object .*Error\]/.test(objectTag)) {
2102
- return true;
2103
- }
2104
- const name = value.name;
2105
- if (typeof name === "string" && name.endsWith("Error")) {
2106
- return true;
2107
- }
2108
- }
2109
- return false;
2110
- }
2111
- }
2112
- var ANSI_REGEX = /\u001b\[[0-9;]*m/g;
2113
- var COLOR_TOKENS = {
2114
- black: "#000000",
2115
- red: "#ef5350",
2116
- green: "#66bb6a",
2117
- yellow: "#fdd835",
2118
- blue: "#42a5f5",
2119
- magenta: "#ab47bc",
2120
- cyan: "#26c6da",
2121
- white: "#fafafa",
2122
- blackBright: "#424242",
2123
- redBright: "#ff7043",
2124
- greenBright: "#81c784",
2125
- yellowBright: "#ffe082",
2126
- blueBright: "#64b5f6",
2127
- magentaBright: "#ce93d8",
2128
- cyanBright: "#4dd0e1",
2129
- whiteBright: "#ffffff"
2130
- };
2131
- var BACKGROUND_TOKENS = {
2132
- bgBlack: "#000000",
2133
- bgRed: "#ef5350",
2134
- bgGreen: "#66bb6a",
2135
- bgYellow: "#fdd835",
2136
- bgBlue: "#42a5f5",
2137
- bgMagenta: "#ab47bc",
2138
- bgCyan: "#26c6da",
2139
- bgWhite: "#fafafa",
2140
- bgBlackBright: "#424242",
2141
- bgRedBright: "#ff7043",
2142
- bgGreenBright: "#81c784",
2143
- bgYellowBright: "#ffe082",
2144
- bgBlueBright: "#64b5f6",
2145
- bgMagentaBright: "#ce93d8",
2146
- bgCyanBright: "#4dd0e1",
2147
- bgWhiteBright: "#ffffff"
2148
- };
2149
- var BROWSER_PATH_REGEX = /(?:(?:file|https?|global code|[^@]+)@)?(?:file:)?((?:\/[^:/]+){2,})(?::(\d+))?(?::(\d+))?/;
2150
- var runtime = createLoggerEnvironment();
2151
- class BaseLogger {
2152
- constructor(settings, logObj, stackDepthLevel = Number.NaN) {
2153
- this.logObj = logObj;
2154
- this.stackDepthLevel = stackDepthLevel;
2155
- this.runtime = runtime;
2156
- this.maxErrorCauseDepth = 5;
2157
- this.settings = {
2158
- type: settings?.type ?? "pretty",
2159
- name: settings?.name,
2160
- parentNames: settings?.parentNames,
2161
- minLevel: settings?.minLevel ?? 0,
2162
- argumentsArrayName: settings?.argumentsArrayName,
2163
- hideLogPositionForProduction: settings?.hideLogPositionForProduction ?? false,
2164
- prettyLogTemplate: settings?.prettyLogTemplate ?? "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t{{filePathWithLine}}{{nameWithDelimiterPrefix}}\t",
2165
- prettyErrorTemplate: settings?.prettyErrorTemplate ?? `
2166
- {{errorName}} {{errorMessage}}
2167
- error stack:
2168
- {{errorStack}}`,
2169
- prettyErrorStackTemplate: settings?.prettyErrorStackTemplate ?? ` • {{fileName}} {{method}}
2170
- {{filePathWithLine}}`,
2171
- prettyErrorParentNamesSeparator: settings?.prettyErrorParentNamesSeparator ?? ":",
2172
- prettyErrorLoggerNameDelimiter: settings?.prettyErrorLoggerNameDelimiter ?? "\t",
2173
- stylePrettyLogs: settings?.stylePrettyLogs ?? true,
2174
- prettyLogTimeZone: settings?.prettyLogTimeZone ?? "UTC",
2175
- prettyLogStyles: settings?.prettyLogStyles ?? {
2176
- logLevelName: {
2177
- "*": ["bold", "black", "bgWhiteBright", "dim"],
2178
- SILLY: ["bold", "white"],
2179
- TRACE: ["bold", "whiteBright"],
2180
- DEBUG: ["bold", "green"],
2181
- INFO: ["bold", "blue"],
2182
- WARN: ["bold", "yellow"],
2183
- ERROR: ["bold", "red"],
2184
- FATAL: ["bold", "redBright"]
2185
- },
2186
- dateIsoStr: "white",
2187
- filePathWithLine: "white",
2188
- name: ["white", "bold"],
2189
- nameWithDelimiterPrefix: ["white", "bold"],
2190
- nameWithDelimiterSuffix: ["white", "bold"],
2191
- errorName: ["bold", "bgRedBright", "whiteBright"],
2192
- fileName: ["yellow"],
2193
- fileNameWithLine: "white"
2194
- },
2195
- prettyInspectOptions: settings?.prettyInspectOptions ?? {
2196
- colors: true,
2197
- compact: false,
2198
- depth: Infinity
2199
- },
2200
- metaProperty: settings?.metaProperty ?? "_meta",
2201
- maskPlaceholder: settings?.maskPlaceholder ?? "[***]",
2202
- maskValuesOfKeys: settings?.maskValuesOfKeys ?? ["password"],
2203
- maskValuesOfKeysCaseInsensitive: settings?.maskValuesOfKeysCaseInsensitive ?? false,
2204
- maskValuesRegEx: settings?.maskValuesRegEx,
2205
- prefix: [...settings?.prefix ?? []],
2206
- attachedTransports: [...settings?.attachedTransports ?? []],
2207
- overwrite: {
2208
- mask: settings?.overwrite?.mask,
2209
- toLogObj: settings?.overwrite?.toLogObj,
2210
- addMeta: settings?.overwrite?.addMeta,
2211
- addPlaceholders: settings?.overwrite?.addPlaceholders,
2212
- formatMeta: settings?.overwrite?.formatMeta,
2213
- formatLogObj: settings?.overwrite?.formatLogObj,
2214
- transportFormatted: settings?.overwrite?.transportFormatted,
2215
- transportJSON: settings?.overwrite?.transportJSON
2216
- }
2217
- };
2218
- this.captureStackForMeta = this._shouldCaptureStack();
2219
- }
2220
- log(logLevelId, logLevelName, ...args) {
2221
- if (logLevelId < this.settings.minLevel) {
2222
- return;
2223
- }
2224
- const resolvedArgs = this._resolveLogArguments(args);
2225
- const logArgs = [...this.settings.prefix, ...resolvedArgs];
2226
- const maskedArgs = this.settings.overwrite?.mask != null ? this.settings.overwrite?.mask(logArgs) : this.settings.maskValuesOfKeys != null && this.settings.maskValuesOfKeys.length > 0 ? this._mask(logArgs) : logArgs;
2227
- const thisLogObj = this.logObj != null ? this._recursiveCloneAndExecuteFunctions(this.logObj) : undefined;
2228
- const logObj = this.settings.overwrite?.toLogObj != null ? this.settings.overwrite?.toLogObj(maskedArgs, thisLogObj) : this._toLogObj(maskedArgs, thisLogObj);
2229
- const logObjWithMeta = this.settings.overwrite?.addMeta != null ? this.settings.overwrite?.addMeta(logObj, logLevelId, logLevelName) : this._addMetaToLogObj(logObj, logLevelId, logLevelName);
2230
- const logMeta = logObjWithMeta?.[this.settings.metaProperty];
2231
- let logMetaMarkup;
2232
- let logArgsAndErrorsMarkup = undefined;
2233
- if (this.settings.overwrite?.formatMeta != null) {
2234
- logMetaMarkup = this.settings.overwrite?.formatMeta(logObjWithMeta?.[this.settings.metaProperty]);
2235
- }
2236
- if (this.settings.overwrite?.formatLogObj != null) {
2237
- logArgsAndErrorsMarkup = this.settings.overwrite?.formatLogObj(maskedArgs, this.settings);
2238
- }
2239
- if (this.settings.type === "pretty") {
2240
- logMetaMarkup = logMetaMarkup ?? this._prettyFormatLogObjMeta(logObjWithMeta?.[this.settings.metaProperty]);
2241
- logArgsAndErrorsMarkup = logArgsAndErrorsMarkup ?? runtime.prettyFormatLogObj(maskedArgs, this.settings);
2242
- }
2243
- if (logMetaMarkup != null && logArgsAndErrorsMarkup != null) {
2244
- if (this.settings.overwrite?.transportFormatted != null) {
2245
- const transport = this.settings.overwrite.transportFormatted;
2246
- const declaredParams = transport.length;
2247
- if (declaredParams < 4) {
2248
- transport(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors);
2249
- } else if (declaredParams === 4) {
2250
- transport(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, logMeta);
2251
- } else {
2252
- transport(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, logMeta, this.settings);
2253
- }
2254
- } else {
2255
- runtime.transportFormatted(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, logMeta, this.settings);
2256
- }
2257
- } else {
2258
- if (this.settings.overwrite?.transportJSON != null) {
2259
- this.settings.overwrite.transportJSON(logObjWithMeta);
2260
- } else if (this.settings.type !== "hidden") {
2261
- runtime.transportJSON(logObjWithMeta);
2262
- }
2263
- }
2264
- if (this.settings.attachedTransports != null && this.settings.attachedTransports.length > 0) {
2265
- this.settings.attachedTransports.forEach((transportLogger) => {
2266
- transportLogger(logObjWithMeta);
2267
- });
2268
- }
2269
- return logObjWithMeta;
2270
- }
2271
- attachTransport(transportLogger) {
2272
- this.settings.attachedTransports.push(transportLogger);
2273
- }
2274
- getSubLogger(settings, logObj) {
2275
- const subLoggerSettings = {
2276
- ...this.settings,
2277
- ...settings,
2278
- parentNames: this.settings?.parentNames != null && this.settings?.name != null ? [...this.settings.parentNames, this.settings.name] : this.settings?.name != null ? [this.settings.name] : undefined,
2279
- prefix: [...this.settings.prefix, ...settings?.prefix ?? []]
2280
- };
2281
- const subLogger = new this.constructor(subLoggerSettings, logObj ?? this.logObj, this.stackDepthLevel);
2282
- return subLogger;
2283
- }
2284
- _mask(args) {
2285
- const maskKeys = this._getMaskKeys();
2286
- return args?.map((arg) => {
2287
- return this._recursiveCloneAndMaskValuesOfKeys(arg, maskKeys);
2288
- });
2289
- }
2290
- _getMaskKeys() {
2291
- const maskKeys = this.settings.maskValuesOfKeys ?? [];
2292
- const signature = maskKeys.map(String).join("|");
2293
- if (this.settings.maskValuesOfKeysCaseInsensitive === true) {
2294
- if (this.maskKeysCache?.source === maskKeys && this.maskKeysCache.caseInsensitive === true && this.maskKeysCache.signature === signature) {
2295
- return this.maskKeysCache.normalized;
2296
- }
2297
- const normalized = maskKeys.map((key) => typeof key === "string" ? key.toLowerCase() : String(key).toLowerCase());
2298
- this.maskKeysCache = {
2299
- source: maskKeys,
2300
- caseInsensitive: true,
2301
- normalized,
2302
- signature
2303
- };
2304
- return normalized;
2305
- }
2306
- this.maskKeysCache = {
2307
- source: maskKeys,
2308
- caseInsensitive: false,
2309
- normalized: maskKeys,
2310
- signature
2311
- };
2312
- return maskKeys;
2313
- }
2314
- _resolveLogArguments(args) {
2315
- if (args.length === 1 && typeof args[0] === "function") {
2316
- const candidate = args[0];
2317
- if (candidate.length === 0) {
2318
- const result = candidate();
2319
- return Array.isArray(result) ? result : [result];
2320
- }
2321
- }
2322
- return args;
2323
- }
2324
- _recursiveCloneAndMaskValuesOfKeys(source, keys, seen = []) {
2325
- if (seen.includes(source)) {
2326
- return { ...source };
2327
- }
2328
- if (typeof source === "object" && source !== null) {
2329
- seen.push(source);
2330
- }
2331
- if (runtime.isError(source) || runtime.isBuffer(source)) {
2332
- return source;
2333
- } else if (source instanceof Map) {
2334
- return new Map(source);
2335
- } else if (source instanceof Set) {
2336
- return new Set(source);
2337
- } else if (Array.isArray(source)) {
2338
- return source.map((item) => this._recursiveCloneAndMaskValuesOfKeys(item, keys, seen));
2339
- } else if (source instanceof Date) {
2340
- return new Date(source.getTime());
2341
- } else if (source instanceof URL) {
2342
- return urlToObject(source);
2343
- } else if (source !== null && typeof source === "object") {
2344
- const baseObject = runtime.isError(source) ? this._cloneError(source) : Object.create(Object.getPrototypeOf(source));
2345
- return Object.getOwnPropertyNames(source).reduce((o, prop) => {
2346
- const lookupKey = this.settings?.maskValuesOfKeysCaseInsensitive !== true ? prop : typeof prop === "string" ? prop.toLowerCase() : String(prop).toLowerCase();
2347
- o[prop] = keys.includes(lookupKey) ? this.settings.maskPlaceholder : (() => {
2348
- try {
2349
- return this._recursiveCloneAndMaskValuesOfKeys(source[prop], keys, seen);
2350
- } catch {
2351
- return null;
2352
- }
2353
- })();
2354
- return o;
2355
- }, baseObject);
2356
- } else {
2357
- if (typeof source === "string") {
2358
- let modifiedSource = source;
2359
- for (const regEx of this.settings?.maskValuesRegEx || []) {
2360
- modifiedSource = modifiedSource.replace(regEx, this.settings?.maskPlaceholder || "");
2361
- }
2362
- return modifiedSource;
2363
- }
2364
- return source;
2365
- }
2366
- }
2367
- _recursiveCloneAndExecuteFunctions(source, seen = []) {
2368
- if (this.isObjectOrArray(source) && seen.includes(source)) {
2369
- return this.shallowCopy(source);
2370
- }
2371
- if (this.isObjectOrArray(source)) {
2372
- seen.push(source);
2373
- }
2374
- if (Array.isArray(source)) {
2375
- return source.map((item) => this._recursiveCloneAndExecuteFunctions(item, seen));
2376
- } else if (source instanceof Date) {
2377
- return new Date(source.getTime());
2378
- } else if (this.isObject(source)) {
2379
- return Object.getOwnPropertyNames(source).reduce((o, prop) => {
2380
- const descriptor = Object.getOwnPropertyDescriptor(source, prop);
2381
- if (descriptor) {
2382
- Object.defineProperty(o, prop, descriptor);
2383
- const value = source[prop];
2384
- o[prop] = typeof value === "function" ? value() : this._recursiveCloneAndExecuteFunctions(value, seen);
2385
- }
2386
- return o;
2387
- }, Object.create(Object.getPrototypeOf(source)));
2388
- } else {
2389
- return source;
2390
- }
2391
- }
2392
- isObjectOrArray(value) {
2393
- return typeof value === "object" && value !== null;
2394
- }
2395
- isObject(value) {
2396
- return typeof value === "object" && !Array.isArray(value) && value !== null;
2397
- }
2398
- shallowCopy(source) {
2399
- if (Array.isArray(source)) {
2400
- return [...source];
2401
- } else {
2402
- return { ...source };
2403
- }
2404
- }
2405
- _toLogObj(args, clonedLogObj = {}) {
2406
- args = args?.map((arg) => runtime.isError(arg) ? this._toErrorObject(arg) : arg);
2407
- if (this.settings.argumentsArrayName == null) {
2408
- if (args.length === 1 && !Array.isArray(args[0]) && runtime.isBuffer(args[0]) !== true && !(args[0] instanceof Date)) {
2409
- clonedLogObj = typeof args[0] === "object" && args[0] != null ? { ...args[0], ...clonedLogObj } : { 0: args[0], ...clonedLogObj };
2410
- } else {
2411
- clonedLogObj = { ...clonedLogObj, ...args };
2412
- }
2413
- } else {
2414
- clonedLogObj = {
2415
- ...clonedLogObj,
2416
- [this.settings.argumentsArrayName]: args
2417
- };
2418
- }
2419
- return clonedLogObj;
2420
- }
2421
- _cloneError(error) {
2422
- const cloned = new error.constructor;
2423
- Object.getOwnPropertyNames(error).forEach((key) => {
2424
- cloned[key] = error[key];
2425
- });
2426
- return cloned;
2427
- }
2428
- _toErrorObject(error, depth = 0, seen = new Set) {
2429
- if (!seen.has(error)) {
2430
- seen.add(error);
2431
- }
2432
- const errorObject = {
2433
- nativeError: error,
2434
- name: error.name ?? "Error",
2435
- message: error.message,
2436
- stack: runtime.getErrorTrace(error)
2437
- };
2438
- if (depth >= this.maxErrorCauseDepth) {
2439
- return errorObject;
2440
- }
2441
- const causeValue = error.cause;
2442
- if (causeValue != null) {
2443
- const normalizedCause = toError(causeValue);
2444
- if (!seen.has(normalizedCause)) {
2445
- errorObject.cause = this._toErrorObject(normalizedCause, depth + 1, seen);
2446
- }
2447
- }
2448
- return errorObject;
2449
- }
2450
- _addMetaToLogObj(logObj, logLevelId, logLevelName) {
2451
- return {
2452
- ...logObj,
2453
- [this.settings.metaProperty]: runtime.getMeta(logLevelId, logLevelName, this.stackDepthLevel, !this.captureStackForMeta, this.settings.name, this.settings.parentNames)
2454
- };
2455
- }
2456
- _shouldCaptureStack() {
2457
- if (this.settings.hideLogPositionForProduction) {
2458
- return false;
2459
- }
2460
- if (this.settings.type === "json") {
2461
- return true;
2462
- }
2463
- const template = this.settings.prettyLogTemplate ?? "";
2464
- const stackPlaceholders = /{{\s*(file(Name|Path|Line|PathWithLine|NameWithLine)|fullFilePath)\s*}}/;
2465
- if (stackPlaceholders.test(template)) {
2466
- return true;
2467
- }
2468
- return false;
2469
- }
2470
- _prettyFormatLogObjMeta(logObjMeta) {
2471
- return buildPrettyMeta(this.settings, logObjMeta).text;
2472
- }
2473
- }
2474
-
2475
- // ../../node_modules/.bun/tslog@4.10.2/node_modules/tslog/esm/index.js
2476
- class Logger extends BaseLogger {
2477
- constructor(settings, logObj) {
2478
- const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
2479
- const normalizedSettings = { ...settings ?? {} };
2480
- if (isBrowser) {
2481
- normalizedSettings.stylePrettyLogs = settings?.stylePrettyLogs ?? true;
2482
- }
2483
- super(normalizedSettings, logObj, Number.NaN);
2484
- }
2485
- log(logLevelId, logLevelName, ...args) {
2486
- return super.log(logLevelId, logLevelName, ...args);
2487
- }
2488
- silly(...args) {
2489
- return super.log(0, "SILLY", ...args);
2490
- }
2491
- trace(...args) {
2492
- return super.log(1, "TRACE", ...args);
2493
- }
2494
- debug(...args) {
2495
- return super.log(2, "DEBUG", ...args);
2496
- }
2497
- info(...args) {
2498
- return super.log(3, "INFO", ...args);
2499
- }
2500
- warn(...args) {
2501
- return super.log(4, "WARN", ...args);
2502
- }
2503
- error(...args) {
2504
- return super.log(5, "ERROR", ...args);
2505
- }
2506
- fatal(...args) {
2507
- return super.log(6, "FATAL", ...args);
2508
- }
2509
- getSubLogger(settings, logObj) {
2510
- return super.getSubLogger(settings, logObj);
2511
- }
2512
- }
2513
-
2514
- // ../nice-error/src/utils/logger.ts
2515
- var logger_NiceError = new Logger({
2516
- name: "NiceErrorLogger"
2517
- });
2518
- var logger_NiceError_testing = logger_NiceError.getSubLogger({
2519
- name: "NiceErrorTestingLogger"
2520
- });
2521
- // src/validation/standard_schema/extractMessageFromStandardSchema.ts
2522
- function extractPathFromIssue(issue) {
2523
- let pathString = "";
2524
- for (const segment of issue) {
2525
- if (typeof segment === "object") {
2526
- if (segment.key != null) {
2527
- if (typeof segment.key === "number") {
2528
- pathString += `[${String(segment.key)}]`;
2529
- } else if (typeof segment.key === "symbol") {
2530
- pathString += `[SYMBOL:${String(segment.key)}]`;
2531
- } else {
2532
- pathString += `.${String(segment.key)}`;
2533
- }
2534
- }
2535
- } else {
2536
- pathString += `.${String(segment)}`;
2537
- }
2538
- }
2539
- return pathString.slice(1);
2540
- }
2541
- var extractMessageFromStandardSchema = (failureResult) => {
2542
- let message = `Data validation failed:
2543
- `;
2544
- let issueCount = 0;
2545
- for (const issue of failureResult.issues) {
2546
- issueCount++;
2547
- if (issue.path == null || issue.path.length === 0) {
2548
- message += ` (issue ${issueCount}) ${issue.message}
2549
- `;
2550
- } else {
2551
- message += ` (issue ${issueCount}) [${extractPathFromIssue(issue.path)}]: ${issue.message}
2552
- `;
2553
- }
2554
- }
2555
- return message;
2556
- };
2557
-
2558
- // src/validation/err_validation.ts
2559
- var EValidator;
2560
- ((EValidator2) => {
2561
- EValidator2["standard_schema"] = "standard_schema";
2562
- })(EValidator ||= {});
2563
- var err_validation = err_nice.createChildDomain({
2564
- domain: "err_validation",
2565
- defaultHttpStatusCode: StatusCodes.BAD_REQUEST,
2566
- schema: {
2567
- ["standard_schema" /* standard_schema */]: err({
2568
- message: ({ issues }) => extractMessageFromStandardSchema({ issues })
2569
- })
2570
- }
2571
- });
2572
- // src/hono/niceCatchSValidation.ts
2573
- var niceCatchSValidation = () => async (ctx, next) => {
2574
- await next();
2575
- if (!ctx.res.ok) {
2576
- const clonedResponse = ctx.res.clone();
2577
- const contentType = clonedResponse.headers.get("content-type");
2578
- if (contentType?.includes("application/json")) {
2579
- try {
2580
- const responseJson = await clonedResponse.json();
2581
- if (responseJson["success"] != null && responseJson["error"] != null) {
2582
- console.log("Intercepted JSON:", responseJson);
2583
- const result = responseJson;
2584
- const newError = err_validation.fromId("standard_schema" /* standard_schema */, {
2585
- issues: result.error
2586
- });
2587
- ctx.res = undefined;
2588
- ctx.res = new Response(JSON.stringify(newError.toJsonObject()), {
2589
- status: newError.httpStatusCode,
2590
- headers: {
2591
- "Content-Type": "application/json"
2592
- }
2593
- });
2594
- }
2595
- } catch (error) {
2596
- console.error("Failed to parse response JSON:", error);
2597
- }
2598
- }
2599
- }
2600
- };
2601
- // ../../node_modules/.bun/hono@4.12.15/node_modules/hono/dist/utils/url.js
2602
- var tryDecode = (str, decoder) => {
2603
- try {
2604
- return decoder(str);
2605
- } catch {
2606
- return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
2607
- try {
2608
- return decoder(match);
2609
- } catch {
2610
- return match;
2611
- }
2612
- });
2613
- }
2614
- };
2615
- var decodeURIComponent_ = decodeURIComponent;
2616
-
2617
- // ../../node_modules/.bun/hono@4.12.15/node_modules/hono/dist/utils/cookie.js
2618
- var validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
2619
- var validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
2620
- var trimCookieWhitespace = (value) => {
2621
- let start = 0;
2622
- let end = value.length;
2623
- while (start < end) {
2624
- const charCode = value.charCodeAt(start);
2625
- if (charCode !== 32 && charCode !== 9) {
2626
- break;
2627
- }
2628
- start++;
2629
- }
2630
- while (end > start) {
2631
- const charCode = value.charCodeAt(end - 1);
2632
- if (charCode !== 32 && charCode !== 9) {
2633
- break;
2634
- }
2635
- end--;
2636
- }
2637
- return start === 0 && end === value.length ? value : value.slice(start, end);
2638
- };
2639
- var parse = (cookie, name) => {
2640
- if (name && cookie.indexOf(name) === -1) {
2641
- return {};
2642
- }
2643
- const pairs = cookie.split(";");
2644
- const parsedCookie = {};
2645
- for (const pairStr of pairs) {
2646
- const valueStartPos = pairStr.indexOf("=");
2647
- if (valueStartPos === -1) {
2648
- continue;
2649
- }
2650
- const cookieName = trimCookieWhitespace(pairStr.substring(0, valueStartPos));
2651
- if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) {
2652
- continue;
2653
- }
2654
- let cookieValue = trimCookieWhitespace(pairStr.substring(valueStartPos + 1));
2655
- if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {
2656
- cookieValue = cookieValue.slice(1, -1);
2657
- }
2658
- if (validCookieValueRegEx.test(cookieValue)) {
2659
- parsedCookie[cookieName] = cookieValue.indexOf("%") !== -1 ? tryDecode(cookieValue, decodeURIComponent_) : cookieValue;
2660
- if (name) {
2661
- break;
2662
- }
2663
- }
2664
- }
2665
- return parsedCookie;
2666
- };
2667
-
2668
- // ../../node_modules/.bun/hono@4.12.15/node_modules/hono/dist/helper/cookie/index.js
2669
- var getCookie = (c, key, prefix) => {
2670
- const cookie = c.req.raw.headers.get("Cookie");
2671
- if (typeof key === "string") {
2672
- if (!cookie) {
2673
- return;
2674
- }
2675
- let finalKey = key;
2676
- if (prefix === "secure") {
2677
- finalKey = "__Secure-" + key;
2678
- } else if (prefix === "host") {
2679
- finalKey = "__Host-" + key;
2680
- }
2681
- const obj2 = parse(cookie, finalKey);
2682
- return obj2[finalKey];
2683
- }
2684
- if (!cookie) {
2685
- return {};
2686
- }
2687
- const obj = parse(cookie);
2688
- return obj;
2689
- };
2690
-
2691
- // ../../node_modules/.bun/hono@4.12.15/node_modules/hono/dist/http-exception.js
2692
- var HTTPException = class extends Error {
2693
- res;
2694
- status;
2695
- constructor(status = 500, options) {
2696
- super(options?.message, { cause: options?.cause });
2697
- this.res = options?.res;
2698
- this.status = status;
2699
- }
2700
- getResponse() {
2701
- if (this.res) {
2702
- const newResponse = new Response(this.res.body, {
2703
- status: this.status,
2704
- headers: this.res.headers
2705
- });
2706
- return newResponse;
2707
- }
2708
- return new Response(this.message, {
2709
- status: this.status
2710
- });
2711
- }
2712
- };
2713
-
2714
- // ../../node_modules/.bun/hono@4.12.15/node_modules/hono/dist/utils/buffer.js
2715
- var bufferToFormData = (arrayBuffer, contentType) => {
2716
- const response = new Response(arrayBuffer, {
2717
- headers: {
2718
- "Content-Type": contentType
2719
- }
2720
- });
2721
- return response.formData();
2722
- };
2723
-
2724
- // ../../node_modules/.bun/hono@4.12.15/node_modules/hono/dist/validator/validator.js
2725
- var jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
2726
- var multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/;
2727
- var urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
2728
- var validator = (target, validationFunc) => {
2729
- return async (c, next) => {
2730
- let value = {};
2731
- const contentType = c.req.header("Content-Type");
2732
- switch (target) {
2733
- case "json":
2734
- if (!contentType || !jsonRegex.test(contentType)) {
2735
- break;
2736
- }
2737
- try {
2738
- value = await c.req.json();
2739
- } catch {
2740
- const message = "Malformed JSON in request body";
2741
- throw new HTTPException(400, { message });
2742
- }
2743
- break;
2744
- case "form": {
2745
- if (!contentType || !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))) {
2746
- break;
2747
- }
2748
- let formData;
2749
- if (c.req.bodyCache.formData) {
2750
- formData = await c.req.bodyCache.formData;
2751
- } else {
2752
- try {
2753
- const arrayBuffer = await c.req.arrayBuffer();
2754
- formData = await bufferToFormData(arrayBuffer, contentType);
2755
- c.req.bodyCache.formData = formData;
2756
- } catch (e) {
2757
- let message = "Malformed FormData request.";
2758
- message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`;
2759
- throw new HTTPException(400, { message });
2760
- }
2761
- }
2762
- const form = /* @__PURE__ */ Object.create(null);
2763
- formData.forEach((value2, key) => {
2764
- if (key.endsWith("[]")) {
2765
- (form[key] ??= []).push(value2);
2766
- } else if (Array.isArray(form[key])) {
2767
- form[key].push(value2);
2768
- } else if (Object.hasOwn(form, key)) {
2769
- form[key] = [form[key], value2];
2770
- } else {
2771
- form[key] = value2;
2772
- }
2773
- });
2774
- value = form;
2775
- break;
2776
- }
2777
- case "query":
2778
- value = Object.fromEntries(Object.entries(c.req.queries()).map(([k, v]) => {
2779
- return v.length === 1 ? [k, v[0]] : [k, v];
2780
- }));
2781
- break;
2782
- case "param":
2783
- value = c.req.param();
2784
- break;
2785
- case "header":
2786
- value = c.req.header();
2787
- break;
2788
- case "cookie":
2789
- value = getCookie(c);
2790
- break;
2791
- }
2792
- const res = await validationFunc(value, c);
2793
- if (res instanceof Response) {
2794
- return res;
2795
- }
2796
- c.req.addValidatedData(target, res);
2797
- return await next();
2798
- };
2799
- };
2800
-
2801
- // ../../node_modules/.bun/@hono+standard-validator@0.2.2+ba5f02f09be4faa7/node_modules/@hono/standard-validator/dist/index.js
2802
- var RESTRICTED_DATA_FIELDS = { header: ["cookie"] };
2803
- function sanitizeIssues(issues, vendor, target) {
2804
- if (!(target in RESTRICTED_DATA_FIELDS))
2805
- return issues;
2806
- const restrictedFields = RESTRICTED_DATA_FIELDS[target] || [];
2807
- if (vendor === "arktype")
2808
- return sanitizeArktypeIssues(issues, restrictedFields);
2809
- if (vendor === "valibot")
2810
- return sanitizeValibotIssues(issues, restrictedFields);
2811
- return issues;
2812
- }
2813
- function sanitizeArktypeIssues(issues, restrictedFields) {
2814
- return issues.map((issue) => {
2815
- if (issue && typeof issue === "object" && "data" in issue && typeof issue.data === "object" && issue.data !== null && !Array.isArray(issue.data)) {
2816
- const dataCopy = { ...issue.data };
2817
- for (const field of restrictedFields)
2818
- delete dataCopy[field];
2819
- const sanitizedIssue = Object.create(Object.getPrototypeOf(issue));
2820
- Object.assign(sanitizedIssue, issue, { data: dataCopy });
2821
- return sanitizedIssue;
2822
- }
2823
- return issue;
2824
- });
2825
- }
2826
- function sanitizeValibotIssues(issues, restrictedFields) {
2827
- return issues.map((issue) => {
2828
- if (issue && typeof issue === "object" && "path" in issue && Array.isArray(issue.path)) {
2829
- for (const path of issue.path)
2830
- if (typeof path === "object" && "input" in path && typeof path.input === "object" && path.input !== null && !Array.isArray(path.input))
2831
- for (const field of restrictedFields)
2832
- delete path.input[field];
2833
- }
2834
- return issue;
2835
- });
2836
- }
2837
- var sValidator = (target, schema, hook) => validator(target, async (value, c) => {
2838
- const result = await schema["~standard"].validate(value);
2839
- if (hook) {
2840
- const hookResult = await hook(result.issues ? {
2841
- data: value,
2842
- error: result.issues,
2843
- success: false,
2844
- target
2845
- } : {
2846
- data: value,
2847
- success: true,
2848
- target
2849
- }, c);
2850
- if (hookResult) {
2851
- if (hookResult instanceof Response)
2852
- return hookResult;
2853
- if ("response" in hookResult)
2854
- return hookResult.response;
2855
- }
2856
- }
2857
- if (result.issues) {
2858
- const processedIssues = sanitizeIssues(result.issues, schema["~standard"].vendor, target);
2859
- return c.json({
2860
- data: value,
2861
- error: processedIssues,
2862
- success: false
2863
- }, 400);
2864
- }
2865
- return result.value;
2866
- });
2867
-
2868
- // src/hono/niceSValidator.ts
2869
- function niceSValidator(target, schema) {
2870
- return sValidator(target, schema, (result) => {
2871
- if (!result.success) {
2872
- throw err_validation.fromId("standard_schema" /* standard_schema */, {
2873
- issues: result.error
2874
- });
2875
- }
2876
- });
2877
- }
2878
- export {
2879
- niceSValidator,
2880
- niceCatchSValidation
2881
- };
1
+ // src/hono/index.ts
2
+ export * from "./niceCatchSValidation";
3
+ export * from "./niceSValidator";