@nice-code/common-errors 0.0.15

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