@teyik0/furin 0.4.0-alpha.2 → 0.5.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/dist/build/compile-entry.d.ts +2 -1
  2. package/dist/build/compile-entry.ts +17 -13
  3. package/dist/build/elysia-aot.d.ts +9 -0
  4. package/dist/build/entry-template.d.ts +5 -1
  5. package/dist/build/entry-template.ts +27 -6
  6. package/dist/build/index.js +969 -528
  7. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  8. package/dist/build/server-app-entry.d.ts +12 -0
  9. package/dist/build/types.d.ts +2 -0
  10. package/dist/cache.d.ts +1 -0
  11. package/dist/cache.js +185 -0
  12. package/dist/cli/index.js +983 -541
  13. package/dist/client/document.d.ts +2 -0
  14. package/dist/client/internal/runtime-types.d.ts +8 -1
  15. package/dist/client/link.js +232 -11
  16. package/dist/client/sync.d.ts +1 -0
  17. package/dist/client.js +11 -0
  18. package/dist/config.d.ts +28 -22
  19. package/dist/config.js +25 -2
  20. package/dist/define-route.d.ts +273 -1009
  21. package/dist/furin.d.ts +20 -5
  22. package/dist/furin.js +6431 -5457
  23. package/dist/plugin/routes.d.ts +6 -0
  24. package/dist/rsc-client.js +9 -1
  25. package/dist/rsc.js +19 -7
  26. package/dist/server/assets/production.d.ts +3 -0
  27. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  28. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  29. package/dist/server/browser-events/shutdown.d.ts +3 -0
  30. package/dist/server/cache/invalidation.d.ts +1 -1
  31. package/dist/server/cache/page-cache-state.d.ts +5 -0
  32. package/dist/server/cache/page-cache.d.ts +53 -0
  33. package/dist/server/cache/redis/index.d.ts +41 -0
  34. package/dist/server/cache/redis/index.js +451 -0
  35. package/dist/server/cache/redis/scripts.d.ts +6 -0
  36. package/dist/server/context-logger.d.ts +2 -2
  37. package/dist/server/dev/plugin.d.ts +1 -0
  38. package/dist/server/dev/runtime.production.d.ts +1 -0
  39. package/dist/server/dev-page-plugin.d.ts +7 -0
  40. package/dist/server/evlog.d.ts +14 -0
  41. package/dist/server/internal.d.ts +6 -0
  42. package/dist/server/internal.js +2539 -0
  43. package/dist/server/production-server.d.ts +13 -0
  44. package/dist/server/production-server.js +2906 -0
  45. package/dist/server/render/not-found.d.ts +1 -1
  46. package/dist/server/render/ssg.d.ts +5 -0
  47. package/dist/server/render/static-params.d.ts +4 -0
  48. package/dist/server/router/defined-route.d.ts +1 -1
  49. package/dist/server/router/hmr.d.ts +6 -0
  50. package/dist/server/router/hmr.production.d.ts +5 -0
  51. package/dist/server/router/plugin.d.ts +5 -1
  52. package/dist/server/router/schemas.d.ts +1 -0
  53. package/dist/server/sync/index.js +798 -117
  54. package/dist/server/sync/plugin.d.ts +31 -158
  55. package/dist/server/sync/stream.d.ts +38 -49
  56. package/dist/shared/elysia-contract.d.ts +8 -14
  57. package/dist/shared/production-build.d.ts +2 -0
  58. package/package.json +19 -8
  59. package/src/adapter/README.md +9 -2
  60. package/src/adapter/bun.ts +146 -41
  61. package/src/adapter/package.ts +6 -2
  62. package/src/adapter/runtime-build.ts +11 -4
  63. package/src/adapter/static.ts +8 -6
  64. package/src/adapter/vercel.ts +64 -31
  65. package/src/build/client.ts +18 -1
  66. package/src/build/compile-entry.ts +17 -13
  67. package/src/build/elysia-aot.ts +102 -0
  68. package/src/build/entry-template.ts +27 -6
  69. package/src/build/hydrate.ts +5 -1
  70. package/src/build/index.ts +5 -5
  71. package/src/build/private-server-sourcemaps.ts +20 -0
  72. package/src/build/production-instrumentation.ts +2 -2
  73. package/src/build/server-app-entry.ts +61 -0
  74. package/src/build/shared.ts +3 -1
  75. package/src/build/ssg-cache.ts +5 -10
  76. package/src/build/types.ts +2 -0
  77. package/src/build/virtual-entry.ts +5 -4
  78. package/src/cache.ts +12 -0
  79. package/src/cli/config.ts +3 -3
  80. package/src/cli/index.ts +6 -2
  81. package/src/client/document.tsx +19 -0
  82. package/src/client/internal/runtime-types.ts +10 -1
  83. package/src/client/sync.ts +1 -0
  84. package/src/config.ts +33 -4
  85. package/src/define-route.ts +266 -128
  86. package/src/furin.ts +168 -154
  87. package/src/plugin/route-config-autofix.ts +11 -2
  88. package/src/plugin/routes.ts +85 -29
  89. package/src/rsc/codec.ts +11 -6
  90. package/src/rsc/render-error.ts +3 -1
  91. package/src/server/assets/production.ts +99 -0
  92. package/src/server/auto-invalidate/plugin.ts +4 -4
  93. package/src/server/auto-invalidate/runtime.ts +74 -42
  94. package/src/server/browser-events/plugin.ts +13 -1
  95. package/src/server/browser-events/shutdown.ts +32 -0
  96. package/src/server/cache/invalidation.ts +61 -20
  97. package/src/server/cache/page-cache-state.ts +22 -0
  98. package/src/server/cache/page-cache.ts +300 -0
  99. package/src/server/cache/redis/index.ts +367 -0
  100. package/src/server/cache/redis/scripts.ts +200 -0
  101. package/src/server/context-logger.ts +5 -5
  102. package/src/server/dev/plugin.ts +10 -1
  103. package/src/server/dev/runtime.production.ts +4 -0
  104. package/src/server/dev-page-plugin.ts +54 -10
  105. package/src/server/evlog.ts +106 -0
  106. package/src/server/internal.ts +7 -0
  107. package/src/server/production-server.ts +135 -0
  108. package/src/server/render/document.tsx +7 -1
  109. package/src/server/render/isr.ts +480 -132
  110. package/src/server/render/loaders.ts +18 -12
  111. package/src/server/render/not-found.ts +4 -4
  112. package/src/server/render/ppr-document.ts +2 -2
  113. package/src/server/render/ppr-route.ts +193 -7
  114. package/src/server/render/ssg.ts +148 -4
  115. package/src/server/render/ssr.ts +6 -7
  116. package/src/server/render/static-params.ts +174 -0
  117. package/src/server/render/template.ts +5 -1
  118. package/src/server/router/defined-route.ts +2 -1
  119. package/src/server/router/discovery.ts +3 -1
  120. package/src/server/router/hmr.production.ts +11 -0
  121. package/src/server/router/hmr.ts +85 -76
  122. package/src/server/router/plugin.ts +118 -50
  123. package/src/server/router/schema-merge.ts +10 -3
  124. package/src/server/router/schemas.ts +174 -61
  125. package/src/server/sync/plugin.ts +14 -10
  126. package/src/server/sync/response.ts +3 -3
  127. package/src/server/sync/stream.ts +43 -2
  128. package/src/shared/elysia-contract.ts +23 -25
  129. package/src/shared/production-build.ts +20 -0
@@ -1,4 +1,2538 @@
1
1
  // @bun
2
+ var __esm = (fn, res, err) => () => {
3
+ if (fn)
4
+ try {
5
+ res = fn(fn = 0);
6
+ } catch (e) {
7
+ err = [e];
8
+ }
9
+ if (err)
10
+ throw err[0];
11
+ return res;
12
+ };
13
+
14
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
15
+ function shouldDeferEmitForResponse(response) {
16
+ if (!response.body)
17
+ return false;
18
+ const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
19
+ if (contentType.includes("text/event-stream"))
20
+ return true;
21
+ if (contentType.includes("application/x-ndjson"))
22
+ return true;
23
+ if (response.headers.has("x-vercel-ai-ui-message-stream"))
24
+ return true;
25
+ if (response.headers.get("transfer-encoding")?.toLowerCase().includes("chunked"))
26
+ return true;
27
+ return false;
28
+ }
29
+ function toError(value) {
30
+ return value instanceof Error ? value : new Error(String(value));
31
+ }
32
+ function createObservedBody(body, onDone, onError) {
33
+ if (body.locked) {
34
+ Promise.resolve(onError(/* @__PURE__ */ new TypeError("stream is already locked"))).catch((err) => {
35
+ console.error("[evlog] stream error handling failed:", err);
36
+ });
37
+ return null;
38
+ }
39
+ const reader = body.getReader();
40
+ let settled = false;
41
+ const settle = (fn) => {
42
+ if (settled)
43
+ return;
44
+ settled = true;
45
+ Promise.resolve(fn()).catch((err) => {
46
+ console.error("[evlog] stream completion handling failed:", err);
47
+ });
48
+ };
49
+ return new ReadableStream({
50
+ async pull(controller) {
51
+ try {
52
+ const { done, value } = await reader.read();
53
+ if (done) {
54
+ settle(onDone);
55
+ controller.close();
56
+ return;
57
+ }
58
+ controller.enqueue(value);
59
+ } catch (err) {
60
+ settle(() => onError(err));
61
+ controller.error(err);
62
+ }
63
+ },
64
+ async cancel(reason) {
65
+ try {
66
+ await reader.cancel(reason);
67
+ } finally {
68
+ settle(onDone);
69
+ }
70
+ }
71
+ });
72
+ }
73
+ function bindStreamingResponseLifecycle(response, onComplete) {
74
+ if (!response.body) {
75
+ Promise.resolve(onComplete({ status: response.status })).catch((err) => {
76
+ console.error("[evlog] stream completion handling failed:", err);
77
+ });
78
+ return response;
79
+ }
80
+ const body = createObservedBody(response.body, () => onComplete({ status: response.status }), (err) => onComplete({
81
+ status: response.status,
82
+ error: toError(err)
83
+ }));
84
+ if (!body)
85
+ return response;
86
+ return new Response(body, {
87
+ status: response.status,
88
+ statusText: response.statusText,
89
+ headers: response.headers
90
+ });
91
+ }
92
+ var init_streamResponse_OlirMA5P = () => {};
93
+
94
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/utils.mjs
95
+ function elapsedMs(startTime) {
96
+ return Math.max(0, Date.now() - startTime);
97
+ }
98
+ function formatDuration(ms) {
99
+ if (ms < 1000)
100
+ return `${Math.round(ms)}ms`;
101
+ return `${(ms / 1000).toFixed(2)}s`;
102
+ }
103
+ function isServer() {
104
+ return typeof window === "undefined";
105
+ }
106
+ function isBrowser() {
107
+ if (typeof window === "undefined")
108
+ return false;
109
+ if (typeof document === "undefined")
110
+ return false;
111
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative")
112
+ return false;
113
+ return true;
114
+ }
115
+ function isDev() {
116
+ if (typeof process !== "undefined")
117
+ return true;
118
+ if (typeof window !== "undefined")
119
+ return true;
120
+ return false;
121
+ }
122
+ function detectEnvironment() {
123
+ const env = typeof process !== "undefined" ? process.env : {};
124
+ const defaultEnvironment = isDev() ? "development" : "production";
125
+ return {
126
+ environment: env.NODE_ENV || defaultEnvironment,
127
+ service: env.SERVICE_NAME || "app",
128
+ version: env.APP_VERSION,
129
+ commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
130
+ region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
131
+ };
132
+ }
133
+ function isLevelEnabled(level, minLevel) {
134
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
135
+ }
136
+ function getConsoleMethod(level) {
137
+ return level;
138
+ }
139
+ function getLevelColor(level) {
140
+ return levelColorMap[level] ?? colors.white;
141
+ }
142
+ function getCssLevelColor(level) {
143
+ return cssLevelColorMap[level] ?? cssColors.reset;
144
+ }
145
+ function escapeFormatString(str) {
146
+ return str.replace(/%/g, "%%");
147
+ }
148
+ function filterSafeHeaders(headers) {
149
+ const safeHeaders = {};
150
+ for (const [key, value] of Object.entries(headers))
151
+ if (value !== undefined && !SENSITIVE_HEADER_SET.has(key.toLowerCase()))
152
+ safeHeaders[key] = value;
153
+ return safeHeaders;
154
+ }
155
+ function globToRegExp(pattern, separator = "/") {
156
+ const cacheKey = `${separator}:${pattern}`;
157
+ let regex = patternCache.get(cacheKey);
158
+ if (!regex) {
159
+ const segment = separator === "/" ? "[^/]*" : "[^.]*";
160
+ const char = separator === "/" ? "[^/]" : "[^.]";
161
+ const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, segment).replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, char);
162
+ regex = new RegExp(`^${regexPattern}$`);
163
+ patternCache.set(cacheKey, regex);
164
+ }
165
+ return regex;
166
+ }
167
+ function matchesPattern(path, pattern) {
168
+ return globToRegExp(pattern, "/").test(path);
169
+ }
170
+ function isoNow() {
171
+ const now = Date.now();
172
+ const sec = Math.floor(now / 1000);
173
+ if (sec !== _isoCachedSecond) {
174
+ _isoCachedSecond = sec;
175
+ _isoDate.setTime(now);
176
+ _isoCachedPrefix = _isoDate.toISOString().slice(0, 19);
177
+ }
178
+ return `${_isoCachedPrefix}.${String(now % 1000).padStart(3, "0")}Z`;
179
+ }
180
+ var LEVEL_ORDER, colors, levelColorMap, cssColors, cssLevelColorMap, SENSITIVE_HEADERS, SENSITIVE_HEADER_SET, patternCache, _isoDate, _isoCachedSecond = -1, _isoCachedPrefix = "";
181
+ var init_utils = __esm(() => {
182
+ LEVEL_ORDER = {
183
+ debug: 0,
184
+ info: 1,
185
+ warn: 2,
186
+ error: 3
187
+ };
188
+ colors = {
189
+ reset: "\x1B[0m",
190
+ bold: "\x1B[1m",
191
+ dim: "\x1B[2m",
192
+ red: "\x1B[31m",
193
+ green: "\x1B[32m",
194
+ yellow: "\x1B[33m",
195
+ blue: "\x1B[34m",
196
+ magenta: "\x1B[35m",
197
+ cyan: "\x1B[36m",
198
+ white: "\x1B[37m",
199
+ gray: "\x1B[90m"
200
+ };
201
+ levelColorMap = {
202
+ error: colors.red,
203
+ warn: colors.yellow,
204
+ info: colors.cyan,
205
+ debug: colors.gray
206
+ };
207
+ cssColors = {
208
+ dim: "color: #6b7280",
209
+ red: "color: #ef4444; font-weight: bold",
210
+ green: "color: #22c55e",
211
+ yellow: "color: #f59e0b; font-weight: bold",
212
+ cyan: "color: #06b6d4; font-weight: bold",
213
+ gray: "color: #6b7280; font-weight: bold",
214
+ reset: "color: inherit; font-weight: normal"
215
+ };
216
+ cssLevelColorMap = {
217
+ error: cssColors.red,
218
+ warn: cssColors.yellow,
219
+ info: cssColors.cyan,
220
+ debug: cssColors.gray
221
+ };
222
+ SENSITIVE_HEADERS = [
223
+ "authorization",
224
+ "cookie",
225
+ "set-cookie",
226
+ "x-api-key",
227
+ "x-auth-token",
228
+ "proxy-authorization"
229
+ ];
230
+ SENSITIVE_HEADER_SET = new Set(SENSITIVE_HEADERS);
231
+ patternCache = /* @__PURE__ */ new Map;
232
+ _isoDate = /* @__PURE__ */ new Date;
233
+ });
234
+
235
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/redact-C7FmdhwI.mjs
236
+ function normalizeRedactPathPattern(pattern) {
237
+ if (!pattern.includes("*") && !pattern.includes("."))
238
+ return `**.${pattern}`;
239
+ return pattern;
240
+ }
241
+ function compileRedactPathMatchers(patterns) {
242
+ if (!patterns?.length)
243
+ return;
244
+ const exactPaths = /* @__PURE__ */ new Set;
245
+ const pathGlobs = [];
246
+ const keyGlobs = [];
247
+ const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
248
+ for (const raw of patterns) {
249
+ if (!raw.includes("*")) {
250
+ if (raw.includes("."))
251
+ exactPaths.add(raw);
252
+ else
253
+ addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
254
+ continue;
255
+ }
256
+ if (!raw.includes("."))
257
+ keyGlobs.push(globToRegExp(raw, "."));
258
+ else
259
+ addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
260
+ }
261
+ if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
262
+ return;
263
+ return {
264
+ exactPaths,
265
+ pathGlobs,
266
+ keyGlobs,
267
+ caseInsensitiveLeaves
268
+ };
269
+ }
270
+ function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
271
+ pathGlobs.push(globToRegExp(pattern, "."));
272
+ const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
273
+ if (leaf) {
274
+ exactPaths.add(leaf[1]);
275
+ caseInsensitiveLeaves.add(leaf[1].toLowerCase());
276
+ }
277
+ }
278
+ function matchesRedactPath(fullPath, leafKey, matchers) {
279
+ if (matchers.exactPaths.has(fullPath))
280
+ return true;
281
+ if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
282
+ return true;
283
+ for (const glob of matchers.pathGlobs) {
284
+ glob.lastIndex = 0;
285
+ if (glob.test(fullPath))
286
+ return true;
287
+ }
288
+ for (const glob of matchers.keyGlobs) {
289
+ glob.lastIndex = 0;
290
+ if (glob.test(leafKey))
291
+ return true;
292
+ }
293
+ return false;
294
+ }
295
+ function resolveReplacement(replacement, matched, ctx) {
296
+ if (typeof replacement === "string")
297
+ return replacement;
298
+ try {
299
+ const result = replacement(matched, ctx);
300
+ if (typeof result !== "string") {
301
+ console.error(`[evlog] redact replacement returned ${typeof result} for "${ctx.path}", expected string \u2014 using ${DEFAULT_REPLACEMENT}`);
302
+ return DEFAULT_REPLACEMENT;
303
+ }
304
+ return result;
305
+ } catch (err) {
306
+ console.error(`[evlog] redact replacement failed for "${ctx.path}":`, err);
307
+ return DEFAULT_REPLACEMENT;
308
+ }
309
+ }
310
+ function redactPathsInTree(obj, matchers, replacement, prefix = "") {
311
+ if (obj === null || obj === undefined)
312
+ return;
313
+ if (Array.isArray(obj)) {
314
+ for (let i = 0;i < obj.length; i++) {
315
+ const segment = String(i);
316
+ const fullPath = prefix ? `${prefix}.${segment}` : segment;
317
+ redactPathsInTree(obj[i], matchers, replacement, fullPath);
318
+ }
319
+ return;
320
+ }
321
+ if (typeof obj === "object") {
322
+ const record = obj;
323
+ for (const key of redactableKeys(record)) {
324
+ const fullPath = prefix ? `${prefix}.${key}` : key;
325
+ if (matchesRedactPath(fullPath, key, matchers))
326
+ setRedacted(record, key, resolveReplacement(replacement, record[key], {
327
+ path: fullPath,
328
+ key
329
+ }), fullPath);
330
+ else
331
+ redactPathsInTree(record[key], matchers, replacement, fullPath);
332
+ }
333
+ }
334
+ }
335
+ function redactableKeys(record) {
336
+ return Object.keys(record);
337
+ }
338
+ function setRedacted(record, key, value, path) {
339
+ if (Reflect.set(record, key, value))
340
+ return;
341
+ const desc = Object.getOwnPropertyDescriptor(record, key);
342
+ if (desc && "value" in desc && desc.configurable) {
343
+ Object.defineProperty(record, key, {
344
+ ...desc,
345
+ value
346
+ });
347
+ return;
348
+ }
349
+ console.warn(`[evlog] redact could not rewrite read-only field "${path}" \u2014 value left as-is`);
350
+ }
351
+ function resolveRedactConfig(input) {
352
+ if (input === undefined || input === false)
353
+ return;
354
+ if (input === true)
355
+ return { _maskers: allBuiltinMaskers() };
356
+ if (input.builtins === false)
357
+ return {
358
+ ...input,
359
+ _pathMatchers: compileRedactPathMatchers(input.paths)
360
+ };
361
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
362
+ return {
363
+ ...input,
364
+ _maskers: maskers,
365
+ _pathMatchers: compileRedactPathMatchers(input.paths)
366
+ };
367
+ }
368
+ function allBuiltinMaskers() {
369
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
370
+ }
371
+ function cloneRegex(re) {
372
+ return new RegExp(re.source, re.flags);
373
+ }
374
+ function markGloballyRedacted(event) {
375
+ Object.defineProperty(event, globallyRedacted, {
376
+ value: true,
377
+ enumerable: false,
378
+ configurable: true
379
+ });
380
+ }
381
+ function isGloballyRedacted(event) {
382
+ return Reflect.has(event, globallyRedacted);
383
+ }
384
+ function cloneForRedaction(event) {
385
+ try {
386
+ return structuredClone(event);
387
+ } catch {
388
+ try {
389
+ return JSON.parse(JSON.stringify(event));
390
+ } catch {
391
+ console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
392
+ return { ...event };
393
+ }
394
+ }
395
+ }
396
+ function redactEvent(event, config) {
397
+ const clone = cloneForRedaction(event);
398
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
399
+ if (config.transform)
400
+ try {
401
+ config.transform(clone);
402
+ } catch (err) {
403
+ console.error("[evlog] redact transform failed:", err);
404
+ }
405
+ const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
406
+ if (pathMatchers)
407
+ redactPathsInTree(clone, pathMatchers, replacement);
408
+ if (config._maskers?.length)
409
+ applyMaskersToTree(clone, config._maskers);
410
+ if (config.patterns?.length)
411
+ redactPatterns(clone, config.patterns, replacement);
412
+ return clone;
413
+ }
414
+ function redactPatterns(obj, patterns, replacement, prefix = "") {
415
+ if (obj === null || obj === undefined)
416
+ return;
417
+ if (Array.isArray(obj)) {
418
+ for (let i = 0;i < obj.length; i++) {
419
+ const key = String(i);
420
+ const fullPath = prefix ? `${prefix}.${key}` : key;
421
+ if (typeof obj[i] === "string")
422
+ obj[i] = applyPatterns(obj[i], patterns, replacement, fullPath, key);
423
+ else if (typeof obj[i] === "object")
424
+ redactPatterns(obj[i], patterns, replacement, fullPath);
425
+ }
426
+ return;
427
+ }
428
+ if (typeof obj === "object") {
429
+ const record = obj;
430
+ for (const key of redactableKeys(record)) {
431
+ const val = record[key];
432
+ const fullPath = prefix ? `${prefix}.${key}` : key;
433
+ if (typeof val === "string")
434
+ setRedacted(record, key, applyPatterns(val, patterns, replacement, fullPath, key), fullPath);
435
+ else if (typeof val === "object")
436
+ redactPatterns(val, patterns, replacement, fullPath);
437
+ }
438
+ }
439
+ }
440
+ function applyPatterns(value, patterns, replacement, path, key) {
441
+ let result = value;
442
+ for (const pattern of patterns) {
443
+ if (typeof replacement === "string") {
444
+ result = result.replace(pattern, replacement);
445
+ continue;
446
+ }
447
+ result = result.replace(pattern, (...args) => {
448
+ const match = args[0];
449
+ return resolveReplacement(replacement, match, {
450
+ path,
451
+ key,
452
+ groups: captureGroups(args)
453
+ });
454
+ });
455
+ }
456
+ return result;
457
+ }
458
+ function captureGroups(args) {
459
+ const last = args.at(-1);
460
+ const trailing = typeof last === "object" && last !== null ? 3 : 2;
461
+ return args.slice(1, Math.max(1, args.length - trailing));
462
+ }
463
+ function applyMaskersToTree(obj, maskers) {
464
+ if (obj === null || obj === undefined)
465
+ return;
466
+ if (Array.isArray(obj)) {
467
+ for (let i = 0;i < obj.length; i++)
468
+ if (typeof obj[i] === "string")
469
+ obj[i] = applyMaskers(obj[i], maskers);
470
+ else if (typeof obj[i] === "object")
471
+ applyMaskersToTree(obj[i], maskers);
472
+ return;
473
+ }
474
+ if (typeof obj === "object") {
475
+ const record = obj;
476
+ for (const key of redactableKeys(record)) {
477
+ const val = record[key];
478
+ if (typeof val === "string")
479
+ setRedacted(record, key, applyMaskers(val, maskers), key);
480
+ else if (typeof val === "object")
481
+ applyMaskersToTree(val, maskers);
482
+ }
483
+ }
484
+ }
485
+ function applyMaskers(value, maskers) {
486
+ let result = value;
487
+ for (const [pattern, mask] of maskers)
488
+ result = result.replace(pattern, mask);
489
+ return result;
490
+ }
491
+ var DEFAULT_REPLACEMENT = "[REDACTED]", builtinPatterns, globallyRedacted;
492
+ var init_redact_C7FmdhwI = __esm(() => {
493
+ init_utils();
494
+ builtinPatterns = {
495
+ creditCard: {
496
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
497
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
498
+ },
499
+ email: {
500
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
501
+ mask: (m) => {
502
+ if (m.indexOf("@") < 1)
503
+ return "***@***";
504
+ const tld = m.slice(m.lastIndexOf("."));
505
+ return `${m[0]}***@***${tld}`;
506
+ }
507
+ },
508
+ ipv4: {
509
+ pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
510
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
511
+ },
512
+ phone: {
513
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
514
+ mask: (m) => {
515
+ const digits = m.replace(/[^\d]/g, "");
516
+ if (m.startsWith("+") && digits.length > 4) {
517
+ const ccMatch = m.match(/^\+\d{1,3}/);
518
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
519
+ }
520
+ if (digits.length > 2)
521
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
522
+ return "***";
523
+ }
524
+ },
525
+ jwt: {
526
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
527
+ mask: () => "eyJ***.***"
528
+ },
529
+ bearer: {
530
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
531
+ mask: () => "Bearer ***"
532
+ },
533
+ iban: {
534
+ pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
535
+ mask: (m) => {
536
+ const clean = m.replace(/[\s-]/g, "");
537
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
538
+ }
539
+ }
540
+ };
541
+ globallyRedacted = Symbol.for("evlog.globallyRedacted");
542
+ });
543
+
544
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
545
+ function logPluginError(name, hook, err) {
546
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
547
+ }
548
+ function createPluginRunner(plugins = []) {
549
+ const byName = /* @__PURE__ */ new Map;
550
+ for (const plugin of plugins)
551
+ byName.set(plugin.name, plugin);
552
+ const list = Array.from(byName.values());
553
+ return {
554
+ plugins: list,
555
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
556
+ hasDrain: list.some((p) => typeof p.drain === "function"),
557
+ hasKeep: list.some((p) => typeof p.keep === "function"),
558
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
559
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
560
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
561
+ applyExtendLogger(logger) {
562
+ for (const plugin of list) {
563
+ if (!plugin.extendLogger)
564
+ continue;
565
+ try {
566
+ plugin.extendLogger(logger);
567
+ } catch (err) {
568
+ logPluginError(plugin.name, "extendLogger", err);
569
+ }
570
+ }
571
+ },
572
+ runOnRequestStart(ctx) {
573
+ for (const plugin of list) {
574
+ if (!plugin.onRequestStart)
575
+ continue;
576
+ try {
577
+ plugin.onRequestStart(ctx);
578
+ } catch (err) {
579
+ logPluginError(plugin.name, "onRequestStart", err);
580
+ }
581
+ }
582
+ },
583
+ runOnRequestFinish(ctx) {
584
+ for (const plugin of list) {
585
+ if (!plugin.onRequestFinish)
586
+ continue;
587
+ try {
588
+ plugin.onRequestFinish(ctx);
589
+ } catch (err) {
590
+ logPluginError(plugin.name, "onRequestFinish", err);
591
+ }
592
+ }
593
+ },
594
+ async runEnrich(ctx) {
595
+ for (const plugin of list) {
596
+ if (!plugin.enrich)
597
+ continue;
598
+ try {
599
+ await plugin.enrich(ctx);
600
+ } catch (err) {
601
+ logPluginError(plugin.name, "enrich", err);
602
+ }
603
+ }
604
+ },
605
+ async runDrain(ctx) {
606
+ const drains = list.filter((p) => typeof p.drain === "function");
607
+ if (drains.length === 0)
608
+ return;
609
+ await Promise.allSettled(drains.map(async (plugin) => {
610
+ try {
611
+ await plugin.drain(ctx);
612
+ } catch (err) {
613
+ logPluginError(plugin.name, "drain", err);
614
+ }
615
+ }));
616
+ },
617
+ async runKeep(ctx) {
618
+ for (const plugin of list) {
619
+ if (!plugin.keep)
620
+ continue;
621
+ try {
622
+ await plugin.keep(ctx);
623
+ } catch (err) {
624
+ logPluginError(plugin.name, "keep", err);
625
+ }
626
+ }
627
+ },
628
+ runOnClientLog(ctx) {
629
+ for (const plugin of list) {
630
+ if (!plugin.onClientLog)
631
+ continue;
632
+ try {
633
+ plugin.onClientLog(ctx);
634
+ } catch (err) {
635
+ logPluginError(plugin.name, "onClientLog", err);
636
+ }
637
+ }
638
+ },
639
+ async runSetup(ctx) {
640
+ for (const plugin of list) {
641
+ if (!plugin.setup)
642
+ continue;
643
+ try {
644
+ await plugin.setup(ctx);
645
+ } catch (err) {
646
+ logPluginError(plugin.name, "setup", err);
647
+ }
648
+ }
649
+ }
650
+ };
651
+ }
652
+ function getEmptyPluginRunner() {
653
+ return emptyRunner;
654
+ }
655
+ function createConfig() {
656
+ return {
657
+ env: {
658
+ service: "app",
659
+ environment: "development"
660
+ },
661
+ pretty: isDev(),
662
+ prettyError: {
663
+ snippet: isDev(),
664
+ stackDepth: 2,
665
+ compact: isDev(),
666
+ detail: "full"
667
+ },
668
+ sampling: {},
669
+ stringify: true,
670
+ drain: undefined,
671
+ redact: undefined,
672
+ enabled: true,
673
+ silent: false,
674
+ minLevel: "debug",
675
+ locked: false,
676
+ initialized: false,
677
+ pluginRunner: getEmptyPluginRunner()
678
+ };
679
+ }
680
+ function warnOnMultiMajor(host) {
681
+ const majors = host[MAJORS_KEY] ??= /* @__PURE__ */ new Set;
682
+ if (majors.has(EVLOG_MAJOR))
683
+ return;
684
+ majors.add(EVLOG_MAJOR);
685
+ if (majors.size > 1)
686
+ console.warn(`[evlog] Multiple major versions of evlog are loaded in this process (${[...majors].map((m) => `${m}.x`).join(", ")}). They cannot share request scope or logger configuration: events emitted through the other copy will be undrained and unredacted, and useLogger() may throw. Deduplicate evlog to a single major.`);
687
+ }
688
+ function getRegistry() {
689
+ const host = globalThis;
690
+ warnOnMultiMajor(host);
691
+ return host[REGISTRY_KEY] ??= {
692
+ config: createConfig(),
693
+ storages: /* @__PURE__ */ new Map
694
+ };
695
+ }
696
+ function getSharedStorage(id, create) {
697
+ const { storages } = getRegistry();
698
+ let storage = storages.get(id);
699
+ if (!storage) {
700
+ storage = create();
701
+ storages.set(id, storage);
702
+ }
703
+ return storage;
704
+ }
705
+ var emptyRunner, EVLOG_MAJOR = 2, REGISTRY_KEY, MAJORS_KEY, globalConfig;
706
+ var init_globalRegistry_Bh3bIGwA = __esm(() => {
707
+ init_utils();
708
+ emptyRunner = createPluginRunner([]);
709
+ REGISTRY_KEY = Symbol.for(`evlog.registry.v${EVLOG_MAJOR}`);
710
+ MAJORS_KEY = Symbol.for("evlog.majors");
711
+ globalConfig = getRegistry().config;
712
+ });
713
+
714
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
715
+ function pushTreeSpacer(children) {
716
+ children.push(PRETTY_ERROR_TREE_SPACER);
717
+ }
718
+ function isPlainObject(val) {
719
+ return val !== null && typeof val === "object" && !Array.isArray(val);
720
+ }
721
+ function pickString(obj, key) {
722
+ const val = obj[key];
723
+ return typeof val === "string" && val.length > 0 ? val : undefined;
724
+ }
725
+ function pickNumber(obj, key) {
726
+ const val = obj[key];
727
+ return typeof val === "number" ? val : undefined;
728
+ }
729
+ function extractGuidance(data) {
730
+ return {
731
+ code: pickString(data, "code"),
732
+ why: pickString(data, "why"),
733
+ fix: pickString(data, "fix"),
734
+ link: pickString(data, "link")
735
+ };
736
+ }
737
+ function normalizeErrorContext(error) {
738
+ if (error === null || error === undefined)
739
+ return null;
740
+ if (typeof error === "string")
741
+ return { message: error };
742
+ if (!isPlainObject(error))
743
+ return { message: String(error) };
744
+ const result = {
745
+ message: pickString(error, "message") ?? pickString(error, "statusText") ?? pickString(error, "statusMessage") ?? "Unknown error",
746
+ name: pickString(error, "name"),
747
+ code: pickString(error, "code"),
748
+ why: pickString(error, "why"),
749
+ fix: pickString(error, "fix"),
750
+ link: pickString(error, "link"),
751
+ status: pickNumber(error, "status") ?? pickNumber(error, "statusCode"),
752
+ stack: pickString(error, "stack")
753
+ };
754
+ const { data, cause } = error;
755
+ if (isPlainObject(data)) {
756
+ const guidance = extractGuidance(data);
757
+ if (!result.code)
758
+ result.code = guidance.code;
759
+ if (!result.why)
760
+ result.why = guidance.why;
761
+ if (!result.fix)
762
+ result.fix = guidance.fix;
763
+ if (!result.link)
764
+ result.link = guidance.link;
765
+ }
766
+ if (cause instanceof Error)
767
+ result.cause = cause.message;
768
+ else if (isPlainObject(cause) && pickString(cause, "message"))
769
+ result.cause = pickString(cause, "message");
770
+ return result;
771
+ }
772
+ function decodeFileUrl(file) {
773
+ if (file.startsWith("file://"))
774
+ try {
775
+ return decodeURIComponent(new URL(file).pathname);
776
+ } catch {
777
+ return file.slice(7);
778
+ }
779
+ return file;
780
+ }
781
+ function isAppPath(file) {
782
+ const normalized = decodeFileUrl(file).replace(/\\/g, "/");
783
+ if (normalized.startsWith("node:"))
784
+ return false;
785
+ if (SKIP_PATH_RE.test(normalized))
786
+ return false;
787
+ if (normalized.includes("/node_modules/"))
788
+ return false;
789
+ if (isFrameworkRuntimePath(normalized))
790
+ return false;
791
+ return true;
792
+ }
793
+ function formatDisplayPath(file, cwd) {
794
+ const decoded = decodeFileUrl(file).replace(/\\/g, "/");
795
+ const cwdNorm = cwd.replace(/\\/g, "/").replace(/\/$/, "");
796
+ if (cwdNorm && decoded.startsWith(`${cwdNorm}/`)) {
797
+ const rel = decoded.slice(cwdNorm.length + 1);
798
+ return rel.startsWith("./") ? rel.slice(2) : rel;
799
+ }
800
+ const serverIdx = decoded.indexOf("/server/");
801
+ if (serverIdx >= 0)
802
+ return decoded.slice(serverIdx + 1);
803
+ const srcIdx = decoded.indexOf("/src/");
804
+ if (srcIdx >= 0)
805
+ return decoded.slice(srcIdx + 1);
806
+ return decoded;
807
+ }
808
+ function compactStackForStorage(stack, maxFrames = 5) {
809
+ if (!stack)
810
+ return;
811
+ const head = stack.split(`
812
+ `)[0] ?? "";
813
+ const useful = parseStackFrames(stack).filter((f) => f.file && f.line && f.isApp && !isInternalErrorFrame(f)).slice(0, maxFrames);
814
+ if (useful.length === 0)
815
+ return stack;
816
+ return [head, ...useful.map((f) => f.raw)].join(`
817
+ `);
818
+ }
819
+ function parseStackFrames(stack) {
820
+ if (!stack)
821
+ return [];
822
+ const lines = stack.split(`
823
+ `);
824
+ const frames = [];
825
+ for (const line of lines) {
826
+ const trimmed = line.trim();
827
+ if (!trimmed.startsWith("at "))
828
+ continue;
829
+ const withFn = trimmed.match(/^at (.+?) \((.+):(\d+):(\d+)\)$/);
830
+ if (withFn) {
831
+ const [, fn, file, lineStr, colStr] = withFn;
832
+ frames.push({
833
+ raw: trimmed,
834
+ fn,
835
+ file,
836
+ line: Number(lineStr),
837
+ column: Number(colStr),
838
+ isApp: isAppPath(file)
839
+ });
840
+ continue;
841
+ }
842
+ const withoutFn = trimmed.match(/^at (.+):(\d+):(\d+)$/);
843
+ if (withoutFn) {
844
+ const [, file, lineStr, colStr] = withoutFn;
845
+ frames.push({
846
+ raw: trimmed,
847
+ file,
848
+ line: Number(lineStr),
849
+ column: Number(colStr),
850
+ isApp: isAppPath(file)
851
+ });
852
+ continue;
853
+ }
854
+ const asyncFn = trimmed.match(/^at async (.+?) \((.+):(\d+):(\d+)\)$/);
855
+ if (asyncFn) {
856
+ const [, fn, file, lineStr, colStr] = asyncFn;
857
+ frames.push({
858
+ raw: trimmed,
859
+ fn: `async ${fn}`,
860
+ file,
861
+ line: Number(lineStr),
862
+ column: Number(colStr),
863
+ isApp: isAppPath(file)
864
+ });
865
+ }
866
+ }
867
+ return frames;
868
+ }
869
+ function isFrameworkRuntimePath(path) {
870
+ const normalized = path.replace(/\\/g, "/");
871
+ return normalized.includes("route-modules/") || normalized.includes("webpack://next/") || normalized.includes("/next/dist/") || normalized.includes("/compiled/next-server/");
872
+ }
873
+ function isFrameworkRuntimeFrame(frame) {
874
+ if (!frame.file)
875
+ return false;
876
+ return isFrameworkRuntimePath(decodeFileUrl(frame.file));
877
+ }
878
+ function isInternalErrorFrame(frame) {
879
+ if (isFrameworkRuntimeFrame(frame))
880
+ return true;
881
+ if (frame.fn) {
882
+ const fn = frame.fn.replace(/^async /, "");
883
+ if (SKIP_FRAME_FN_RE.test(fn))
884
+ return true;
885
+ }
886
+ if (!frame.file)
887
+ return true;
888
+ const path = decodeFileUrl(frame.file).replace(/\\/g, "/");
889
+ if (SKIP_FRAME_PATH_RE.test(path))
890
+ return true;
891
+ if (path.includes(".nuxt/"))
892
+ return true;
893
+ if (path.includes(".next/"))
894
+ return true;
895
+ return false;
896
+ }
897
+ function pickPrimaryFrame(frames) {
898
+ for (const frame of frames)
899
+ if (frame.isApp && frame.file && frame.line && !isInternalErrorFrame(frame))
900
+ return frame;
901
+ }
902
+ function readCodeSnippet(file, line, contextLines = 2) {
903
+ if (!isDev() || isBrowser() || !snippetReader)
904
+ return null;
905
+ const path = decodeFileUrl(file).replace(/\\/g, "/");
906
+ if (path.includes(".next/") || path.includes(".nuxt/") || path.includes(".output/"))
907
+ return null;
908
+ return snippetReader(file, line, contextLines);
909
+ }
910
+ function formatSnippetLines(snippet) {
911
+ const width = String(snippet[snippet.length - 1]?.line ?? 0).length;
912
+ return snippet.map(({ line, content, isErrorLine }) => {
913
+ const marker = isErrorLine ? `${colors.red}\u276F${colors.reset}` : `${colors.dim} ${colors.reset}`;
914
+ const numColor = isErrorLine ? colors.red : colors.gray;
915
+ const trimmed = content.length > 120 ? `${content.slice(0, 117)}\u2026` : content;
916
+ return `${marker} ${numColor}${String(line).padStart(width, " ")}${colors.reset} ${colors.dim}\u2503${colors.reset} ${colors.dim}${trimmed}${colors.reset}`;
917
+ });
918
+ }
919
+ function formatFrameLocation(frame, cwd) {
920
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
921
+ const loc = frame.line ? `${file}:${frame.line}` : file;
922
+ const fn = frame.fn && frame.fn !== "<unknown>" ? frame.fn : undefined;
923
+ return fn ? `at ${fn} (${loc})` : `at ${loc}`;
924
+ }
925
+ function formatCollapsedFrame(frame, cwd) {
926
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
927
+ const loc = frame.line ? `${file}:${frame.line}` : file;
928
+ const prefix = frame.fn?.startsWith("async") ? "at async " : "at ";
929
+ const fn = frame.fn?.replace(/^async /, "");
930
+ if (fn && fn !== "<unknown>" && fn !== loc)
931
+ return `${prefix}${fn} (${loc})`;
932
+ return `${prefix}${loc}`;
933
+ }
934
+ function formatGuidanceLine(label, text, labelColor) {
935
+ const prefix = `${labelColor}${label}:${colors.reset} `;
936
+ const lines = [];
937
+ let remaining = text.trim();
938
+ let first = true;
939
+ while (remaining.length > 0) {
940
+ const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, 71);
941
+ if (remaining.length <= budget) {
942
+ lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
943
+ break;
944
+ }
945
+ let split = remaining.lastIndexOf(" ", budget);
946
+ if (split <= 0)
947
+ split = budget;
948
+ const chunk = remaining.slice(0, split).trimEnd();
949
+ lines.push(first ? `${prefix}${chunk}` : `${GUIDANCE_CONTINUATION}${chunk}`);
950
+ remaining = remaining.slice(split).trimStart();
951
+ first = false;
952
+ }
953
+ return lines;
954
+ }
955
+ function buildErrorEntries(error, options = {}) {
956
+ const normalized = normalizeErrorContext(error);
957
+ if (!normalized)
958
+ return [];
959
+ const cwd = options.cwd ?? (typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ".");
960
+ const compact = options.compact ?? isDev();
961
+ const guidanceOnly = (options.detail ?? "full") === "guidance";
962
+ const showFrames = !guidanceOnly && !isBrowser() && (options.snippet ?? isDev());
963
+ const stackDepth = guidanceOnly ? 0 : options.stackDepth ?? (compact ? 2 : 3);
964
+ const snippetContextLines = compact ? 1 : 2;
965
+ const children = [];
966
+ const frames = guidanceOnly ? [] : parseStackFrames(normalized.stack);
967
+ const primary = guidanceOnly ? undefined : pickPrimaryFrame(frames);
968
+ if (!guidanceOnly && primary?.file && primary.line) {
969
+ pushTreeSpacer(children);
970
+ if (showFrames) {
971
+ const snippet = readCodeSnippet(primary.file, primary.line, snippetContextLines);
972
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
973
+ if (snippet)
974
+ children.push(...formatSnippetLines(snippet));
975
+ } else
976
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
977
+ }
978
+ if (normalized.code)
979
+ children.push(`${colors.dim}Code:${colors.reset} ${normalized.code}`);
980
+ if (Boolean(normalized.why || normalized.fix || normalized.link))
981
+ pushTreeSpacer(children);
982
+ if (normalized.why)
983
+ children.push(...formatGuidanceLine("Why", normalized.why, colors.yellow));
984
+ if (normalized.fix)
985
+ children.push(...formatGuidanceLine("Fix", normalized.fix, colors.cyan));
986
+ if (normalized.link)
987
+ children.push(`${colors.dim}More:${colors.reset} ${normalized.link}`);
988
+ if (normalized.cause && normalized.cause !== normalized.message)
989
+ children.push(`${colors.dim}Caused by:${colors.reset} ${normalized.cause}`);
990
+ const hiddenCount = guidanceOnly ? 0 : frames.filter((f) => !f.isApp || isInternalErrorFrame(f)).length;
991
+ const tailFrames = stackDepth > 0 ? frames.filter((f) => f !== primary && !isInternalErrorFrame(f)).slice(0, stackDepth) : [];
992
+ if (!guidanceOnly && (hiddenCount > 0 || tailFrames.length > 0)) {
993
+ pushTreeSpacer(children);
994
+ if (hiddenCount > 0)
995
+ children.push(`${colors.gray}stack (${hiddenCount} frame${hiddenCount === 1 ? "" : "s"} hidden in node_modules)${colors.reset}`);
996
+ else
997
+ children.push(`${colors.gray}stack${colors.reset}`);
998
+ for (const frame of tailFrames)
999
+ children.push(`${colors.gray} ${formatCollapsedFrame(frame, cwd)}${colors.reset}`);
1000
+ }
1001
+ return [{
1002
+ key: "error",
1003
+ value: `${colors.red}${colors.bold}${normalized.message}${colors.reset}`,
1004
+ children: children.length > 0 ? children : undefined
1005
+ }];
1006
+ }
1007
+ var snippetReader = null, PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__", SKIP_PATH_RE, SKIP_FRAME_PATH_RE, SKIP_FRAME_FN_RE, GUIDANCE_WRAP_WIDTH = 76, GUIDANCE_CONTINUATION = " ";
1008
+ var init_pretty_error_D8rlWNL1 = __esm(() => {
1009
+ init_utils();
1010
+ SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
1011
+ SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
1012
+ SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
1013
+ });
1014
+
1015
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1016
+ function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1017
+ const compact = partial.compact ?? (inDev && pretty);
1018
+ const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
1019
+ const stackDepth = detail === "guidance" ? 0 : partial.stackDepth ?? (compact ? 2 : 3);
1020
+ return {
1021
+ snippet: partial.snippet ?? (detail === "full" && pretty && inDev),
1022
+ stackDepth,
1023
+ compact,
1024
+ detail
1025
+ };
1026
+ }
1027
+ function resolveDevTerminal(input = {}) {
1028
+ const pretty = input.pretty ?? isDev();
1029
+ const inDev = isDev();
1030
+ let frameworkOverlay;
1031
+ let prettyError = {};
1032
+ if (typeof input.dev === "string" && input.dev in DEV_PRESETS) {
1033
+ const { frameworkOverlay: presetOverlay, detail } = DEV_PRESETS[input.dev];
1034
+ frameworkOverlay = presetOverlay;
1035
+ prettyError = { detail };
1036
+ } else if (input.dev && typeof input.dev === "object") {
1037
+ const { frameworkOverlay: devOverlay, prettyError: devPrettyError } = input.dev;
1038
+ frameworkOverlay = devOverlay;
1039
+ if (devPrettyError)
1040
+ prettyError = devPrettyError;
1041
+ }
1042
+ if (frameworkOverlay === undefined)
1043
+ frameworkOverlay = !(pretty && inDev);
1044
+ return {
1045
+ frameworkOverlay,
1046
+ prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
1047
+ };
1048
+ }
1049
+ var DEV_PRESETS;
1050
+ var init_dev_terminal_Brarc6vc = __esm(() => {
1051
+ init_utils();
1052
+ DEV_PRESETS = {
1053
+ evlog: {
1054
+ frameworkOverlay: false,
1055
+ detail: "full"
1056
+ },
1057
+ nitro: {
1058
+ frameworkOverlay: true,
1059
+ detail: "guidance"
1060
+ },
1061
+ both: {
1062
+ frameworkOverlay: true,
1063
+ detail: "full"
1064
+ }
1065
+ };
1066
+ });
1067
+
1068
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1069
+ function hasWideEventPublisher() {
1070
+ return publisher !== null;
1071
+ }
1072
+ function publishWideEvent(event) {
1073
+ if (!publisher)
1074
+ return;
1075
+ try {
1076
+ publisher(event);
1077
+ } catch (err) {
1078
+ console.error("[evlog] diagnostics channel publish failed:", err);
1079
+ }
1080
+ }
1081
+ var publisher = null;
1082
+ var init_wideEventChannel_BUDW48oP = () => {};
1083
+
1084
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1085
+ function isEvlogError(error) {
1086
+ return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
1087
+ }
1088
+ var evlogErrorBrand;
1089
+ var init_error_brand_D0_DCPvr = __esm(() => {
1090
+ evlogErrorBrand = Symbol.for("evlog.error.brand");
1091
+ });
1092
+
1093
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error.mjs
1094
+ var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
1095
+ var init_error = __esm(() => {
1096
+ init_utils();
1097
+ init_error_brand_D0_DCPvr();
1098
+ evlogErrorInternalKey = Symbol.for("evlog.error.internal");
1099
+ evlogErrorDataKey = Symbol.for("evlog.error.data");
1100
+ EvlogError = class EvlogError extends Error {
1101
+ static isEvlogError(error) {
1102
+ return isEvlogError(error);
1103
+ }
1104
+ code;
1105
+ status;
1106
+ why;
1107
+ fix;
1108
+ link;
1109
+ get internal() {
1110
+ return this[evlogErrorInternalKey];
1111
+ }
1112
+ constructor(options) {
1113
+ const opts = typeof options === "string" ? { message: options } : options;
1114
+ super(opts.message, { cause: opts.cause });
1115
+ this.name = "EvlogError";
1116
+ this.code = opts.code;
1117
+ this.status = opts.status ?? 500;
1118
+ this.why = opts.why;
1119
+ this.fix = opts.fix;
1120
+ this.link = opts.link;
1121
+ if (opts.internal !== undefined)
1122
+ Object.defineProperty(this, evlogErrorInternalKey, {
1123
+ value: opts.internal,
1124
+ enumerable: false,
1125
+ writable: false,
1126
+ configurable: true
1127
+ });
1128
+ if (opts.data !== undefined)
1129
+ Object.defineProperty(this, evlogErrorDataKey, {
1130
+ value: opts.data,
1131
+ enumerable: false,
1132
+ writable: false,
1133
+ configurable: true
1134
+ });
1135
+ if (Error.captureStackTrace)
1136
+ Error.captureStackTrace(this, EvlogError);
1137
+ }
1138
+ get statusText() {
1139
+ return this.message;
1140
+ }
1141
+ get statusCode() {
1142
+ return this.status;
1143
+ }
1144
+ get statusMessage() {
1145
+ return this.message;
1146
+ }
1147
+ get data() {
1148
+ const extra = this[evlogErrorDataKey];
1149
+ if (!extra && !this.code && !this.why && !this.fix && !this.link)
1150
+ return;
1151
+ return {
1152
+ ...extra,
1153
+ ...this.code !== undefined && { code: this.code },
1154
+ ...this.why !== undefined && { why: this.why },
1155
+ ...this.fix !== undefined && { fix: this.fix },
1156
+ ...this.link !== undefined && { link: this.link }
1157
+ };
1158
+ }
1159
+ toString() {
1160
+ const useColors = isServer();
1161
+ const red = useColors ? colors.red : "";
1162
+ const yellow = useColors ? colors.yellow : "";
1163
+ const cyan = useColors ? colors.cyan : "";
1164
+ const dim = useColors ? colors.dim : "";
1165
+ const reset = useColors ? colors.reset : "";
1166
+ const bold = useColors ? colors.bold : "";
1167
+ const lines = [];
1168
+ lines.push(`${red}${bold}Error:${reset} ${this.message}`);
1169
+ if (this.code)
1170
+ lines.push(`${dim}Code:${reset} ${this.code}`);
1171
+ if (this.why)
1172
+ lines.push(`${yellow}Why:${reset} ${this.why}`);
1173
+ if (this.fix)
1174
+ lines.push(`${cyan}Fix:${reset} ${this.fix}`);
1175
+ if (this.link)
1176
+ lines.push(`${dim}More info:${reset} ${this.link}`);
1177
+ if (this.cause)
1178
+ lines.push(`${dim}Caused by:${reset} ${this.cause.message}`);
1179
+ return lines.join(`
1180
+ `);
1181
+ }
1182
+ toJSON() {
1183
+ const { data } = this;
1184
+ return {
1185
+ name: this.name,
1186
+ message: this.message,
1187
+ status: this.status,
1188
+ ...data && { data },
1189
+ ...this.cause instanceof Error && { cause: {
1190
+ name: this.cause.name,
1191
+ message: this.cause.message
1192
+ } }
1193
+ };
1194
+ }
1195
+ };
1196
+ Object.defineProperty(EvlogError.prototype, evlogErrorBrand, {
1197
+ value: true,
1198
+ enumerable: false
1199
+ });
1200
+ });
1201
+
1202
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1203
+ function extractSafeHeaders(headers) {
1204
+ const raw = {};
1205
+ headers.forEach((value, key) => {
1206
+ raw[key] = value;
1207
+ });
1208
+ return filterSafeHeaders(raw);
1209
+ }
1210
+ function extractSafeNodeHeaders(headers) {
1211
+ const raw = {};
1212
+ for (const [key, value] of Object.entries(headers)) {
1213
+ if (value === undefined)
1214
+ continue;
1215
+ raw[key] = Array.isArray(value) ? value.join(", ") : value;
1216
+ }
1217
+ return filterSafeHeaders(raw);
1218
+ }
1219
+ var init_headers_Bx1ieR_m = __esm(() => {
1220
+ init_utils();
1221
+ });
1222
+
1223
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/audit-C8euLMvu.mjs
1224
+ function writePrettyStdout(text) {
1225
+ (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
1226
+ }
1227
+ function isPlainObject$1(val) {
1228
+ return val !== null && typeof val === "object" && !Array.isArray(val);
1229
+ }
1230
+ function warnPostEmit(method, detail) {
1231
+ console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
1232
+ }
1233
+ function mergeInto(target, source) {
1234
+ for (const key in source) {
1235
+ const sourceVal = source[key];
1236
+ if (sourceVal === undefined || sourceVal === null)
1237
+ continue;
1238
+ const targetVal = target[key];
1239
+ if (sourceVal === targetVal)
1240
+ continue;
1241
+ if (isPlainObject$1(sourceVal) && isPlainObject$1(targetVal))
1242
+ mergeInto(targetVal, sourceVal);
1243
+ else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
1244
+ target[key] = [...targetVal, ...sourceVal];
1245
+ else
1246
+ Reflect.set(target, key, sourceVal);
1247
+ }
1248
+ }
1249
+ function isAiOnlyFieldUpdate(data) {
1250
+ const keys = Object.keys(data);
1251
+ return keys.length === 1 && keys[0] === "ai";
1252
+ }
1253
+ function markWideEventDrainStarted(event) {
1254
+ if (!event)
1255
+ return;
1256
+ const state = pendingDrainState.get(event);
1257
+ if (state)
1258
+ state.drainStarted = true;
1259
+ }
1260
+ function initLogger(config = {}) {
1261
+ state.enabled = config.enabled ?? true;
1262
+ const detected = detectEnvironment();
1263
+ state.env = {
1264
+ service: config.env?.service ?? detected.service ?? "app",
1265
+ environment: config.env?.environment ?? detected.environment ?? "development",
1266
+ version: config.env?.version ?? detected.version,
1267
+ commitHash: config.env?.commitHash ?? detected.commitHash,
1268
+ region: config.env?.region ?? detected.region
1269
+ };
1270
+ state.pretty = config.pretty ?? isDev();
1271
+ state.prettyError = resolveDevTerminal(config).prettyError;
1272
+ state.sampling = config.sampling ?? {};
1273
+ state.stringify = config.stringify ?? true;
1274
+ state.drain = config.drain;
1275
+ state.redact = resolveRedactConfig(config.redact ?? !isDev());
1276
+ state.silent = config.silent ?? false;
1277
+ state.minLevel = config.minLevel ?? "debug";
1278
+ state.pluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
1279
+ if (state.pluginRunner.plugins.length > 0)
1280
+ state.pluginRunner.runSetup({ env: { ...state.env } });
1281
+ const hasAnyDrain = !!state.drain || state.pluginRunner.hasDrain;
1282
+ if (state.silent && !hasAnyDrain && !config._suppressDrainWarning)
1283
+ console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
1284
+ state.initialized = true;
1285
+ }
1286
+ function getGlobalPluginRunner() {
1287
+ return state.pluginRunner;
1288
+ }
1289
+ function isEnabled() {
1290
+ return state.enabled;
1291
+ }
1292
+ function getGlobalDrain() {
1293
+ return state.drain;
1294
+ }
1295
+ function shouldSample(level) {
1296
+ const { rates } = state.sampling;
1297
+ if (!rates)
1298
+ return true;
1299
+ const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
1300
+ if (percentage <= 0)
1301
+ return false;
1302
+ if (percentage >= 100)
1303
+ return true;
1304
+ return Math.random() * 100 < percentage;
1305
+ }
1306
+ function shouldKeep(ctx) {
1307
+ const { keep } = state.sampling;
1308
+ if (!keep?.length)
1309
+ return false;
1310
+ return keep.some((condition) => {
1311
+ if (condition.status !== undefined && ctx.status !== undefined && ctx.status >= condition.status)
1312
+ return true;
1313
+ if (condition.duration !== undefined && ctx.duration !== undefined && ctx.duration >= condition.duration)
1314
+ return true;
1315
+ if (condition.path && ctx.path && matchesPattern(ctx.path, condition.path))
1316
+ return true;
1317
+ return false;
1318
+ });
1319
+ }
1320
+ function emitWideEvent(level, event, options = {}) {
1321
+ const { deferDrain = false, ownsEvent = false, waitUntil } = options;
1322
+ if (!state.enabled)
1323
+ return null;
1324
+ if (!ownsEvent) {
1325
+ if (!isLevelEnabled(level, state.minLevel))
1326
+ return null;
1327
+ if (!shouldSample(level))
1328
+ return null;
1329
+ }
1330
+ let formatted;
1331
+ if (ownsEvent) {
1332
+ event.timestamp = isoNow();
1333
+ event.level = level;
1334
+ if (event.service === undefined)
1335
+ event.service = state.env.service;
1336
+ if (event.environment === undefined)
1337
+ event.environment = state.env.environment;
1338
+ if (state.env.version !== undefined && event.version === undefined)
1339
+ event.version = state.env.version;
1340
+ if (state.env.commitHash !== undefined && event.commitHash === undefined)
1341
+ event.commitHash = state.env.commitHash;
1342
+ if (state.env.region !== undefined && event.region === undefined)
1343
+ event.region = state.env.region;
1344
+ formatted = event;
1345
+ } else
1346
+ formatted = {
1347
+ timestamp: isoNow(),
1348
+ level,
1349
+ ...state.env,
1350
+ ...event
1351
+ };
1352
+ finalizeAudit(formatted);
1353
+ if (state.redact) {
1354
+ formatted = redactEvent(formatted, state.redact);
1355
+ markGloballyRedacted(formatted);
1356
+ }
1357
+ if (!state.silent) {
1358
+ if (state.pretty)
1359
+ prettyPrintWideEvent(formatted);
1360
+ else if (state.stringify)
1361
+ console[getConsoleMethod(level)](JSON.stringify(formatted));
1362
+ else
1363
+ console[getConsoleMethod(level)](formatted);
1364
+ }
1365
+ if (!deferDrain) {
1366
+ publishWideEvent(formatted);
1367
+ const drainPromises = [];
1368
+ if (state.drain)
1369
+ drainPromises.push((async () => {
1370
+ try {
1371
+ await state.drain({ event: formatted });
1372
+ } catch (err) {
1373
+ console.error("[evlog] drain failed:", err);
1374
+ }
1375
+ })());
1376
+ if (state.pluginRunner.hasDrain)
1377
+ drainPromises.push(state.pluginRunner.runDrain({ event: formatted }));
1378
+ if (drainPromises.length > 0 && waitUntil)
1379
+ waitUntil(Promise.all(drainPromises));
1380
+ }
1381
+ return formatted;
1382
+ }
1383
+ function emitTaggedLog(level, tag, message) {
1384
+ if (!state.enabled)
1385
+ return;
1386
+ if (state.pretty && !state.silent) {
1387
+ if (!isLevelEnabled(level, state.minLevel))
1388
+ return;
1389
+ if (!shouldSample(level))
1390
+ return;
1391
+ if (isBrowser()) {
1392
+ const levelColor = getCssLevelColor(level);
1393
+ const timestamp = isoNow().slice(11, 23);
1394
+ console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
1395
+ } else {
1396
+ const color = getLevelColor(level);
1397
+ const timestamp = isoNow().slice(11, 23);
1398
+ console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
1399
+ }
1400
+ return;
1401
+ }
1402
+ emitWideEvent(level, {
1403
+ tag,
1404
+ message
1405
+ });
1406
+ }
1407
+ function formatValue(value) {
1408
+ if (value === null || value === undefined)
1409
+ return String(value);
1410
+ if (Array.isArray(value))
1411
+ return JSON.stringify(value);
1412
+ if (isPlainObject$1(value)) {
1413
+ const pairs = [];
1414
+ for (const [k, v] of Object.entries(value))
1415
+ if (v !== undefined && v !== null) {
1416
+ if (typeof v === "object")
1417
+ pairs.push(`${k}=${JSON.stringify(v)}`);
1418
+ else
1419
+ pairs.push(`${k}=${v}`);
1420
+ }
1421
+ return pairs.join(" ");
1422
+ }
1423
+ return String(value);
1424
+ }
1425
+ function formatCost(cost) {
1426
+ if (cost < 0.01)
1427
+ return `$${cost.toFixed(6)}`;
1428
+ if (cost < 1)
1429
+ return `$${cost.toFixed(4)}`;
1430
+ return `$${cost.toFixed(2)}`;
1431
+ }
1432
+ function asNumber(value) {
1433
+ return typeof value === "number" ? value : undefined;
1434
+ }
1435
+ function asStringArray(value) {
1436
+ if (!Array.isArray(value))
1437
+ return;
1438
+ return value.every((item) => typeof item === "string") ? value : undefined;
1439
+ }
1440
+ function isToolUsageEntry(value) {
1441
+ return isPlainObject$1(value) && typeof value.name === "string" && typeof value.durationMs === "number" && typeof value.success === "boolean";
1442
+ }
1443
+ function asToolUsageArray(value) {
1444
+ if (!Array.isArray(value))
1445
+ return;
1446
+ return value.every(isToolUsageEntry) ? value : undefined;
1447
+ }
1448
+ function serializeToolInput(input) {
1449
+ if (typeof input === "string")
1450
+ return input;
1451
+ const seen = /* @__PURE__ */ new WeakSet;
1452
+ try {
1453
+ return JSON.stringify(input, (_key, value) => {
1454
+ if (typeof value === "bigint")
1455
+ return value.toString();
1456
+ if (typeof value === "object" && value !== null) {
1457
+ if (seen.has(value))
1458
+ return "[Circular]";
1459
+ seen.add(value);
1460
+ }
1461
+ return value;
1462
+ }) ?? "";
1463
+ } catch {
1464
+ return "[unserializable tool input]";
1465
+ }
1466
+ }
1467
+ function isToolCallEntry(value) {
1468
+ return isPlainObject$1(value) && typeof value.name === "string" && "input" in value;
1469
+ }
1470
+ function asToolCallArray(value) {
1471
+ if (!Array.isArray(value))
1472
+ return;
1473
+ return value.every(isToolCallEntry) ? value : undefined;
1474
+ }
1475
+ function asCapturedLines(value) {
1476
+ if (typeof value !== "string" || value.length === 0)
1477
+ return;
1478
+ const lines = value.split(`
1479
+ `).map((line) => {
1480
+ return line.length > CAPTURED_LINE_MAX_LENGTH ? `${line.slice(0, CAPTURED_LINE_MAX_LENGTH)}\u2026` : line;
1481
+ });
1482
+ if (lines.length > CAPTURED_MAX_LINES) {
1483
+ lines.length = CAPTURED_MAX_LINES;
1484
+ lines.push(`+${value.split(`
1485
+ `).length - CAPTURED_MAX_LINES} more lines (full text in the event)`);
1486
+ }
1487
+ return lines;
1488
+ }
1489
+ function buildAIEntries(ai) {
1490
+ const entries = [];
1491
+ const headerParts = [];
1492
+ if (ai.model) {
1493
+ let m = String(ai.model);
1494
+ if (ai.provider)
1495
+ m += ` (${ai.provider})`;
1496
+ headerParts.push(m);
1497
+ }
1498
+ if (ai.calls) {
1499
+ const calls = asNumber(ai.calls);
1500
+ if (calls !== undefined)
1501
+ headerParts.push(`${calls} call${calls > 1 ? "s" : ""}`);
1502
+ }
1503
+ const steps = asNumber(ai.steps);
1504
+ if (steps !== undefined && steps > 1)
1505
+ headerParts.push(`${steps} steps`);
1506
+ entries.push({
1507
+ key: "ai",
1508
+ value: headerParts.join(" \xB7 ")
1509
+ });
1510
+ const inputTokens = asNumber(ai.inputTokens);
1511
+ const outputTokens = asNumber(ai.outputTokens);
1512
+ const totalTokens = asNumber(ai.totalTokens);
1513
+ if (inputTokens !== undefined && outputTokens !== undefined) {
1514
+ let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
1515
+ if (totalTokens)
1516
+ tokLine += ` (${totalTokens} total)`;
1517
+ const extras = [];
1518
+ if (ai.cacheReadTokens)
1519
+ extras.push(`${ai.cacheReadTokens} cache read`);
1520
+ if (ai.cacheWriteTokens)
1521
+ extras.push(`${ai.cacheWriteTokens} cache write`);
1522
+ if (ai.reasoningTokens)
1523
+ extras.push(`${ai.reasoningTokens} reasoning`);
1524
+ if (extras.length)
1525
+ tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
1526
+ entries.push({
1527
+ key: "ai.tokens",
1528
+ value: tokLine
1529
+ });
1530
+ }
1531
+ const msFirst = asNumber(ai.msToFirstChunk);
1532
+ const msFinish = asNumber(ai.msToFinish);
1533
+ const tps = asNumber(ai.tokensPerSecond);
1534
+ if (msFirst !== undefined || msFinish !== undefined) {
1535
+ const parts = [];
1536
+ if (msFirst !== undefined)
1537
+ parts.push(`${formatDuration(msFirst)} to first chunk`);
1538
+ if (msFinish !== undefined)
1539
+ parts.push(`${formatDuration(msFinish)} total`);
1540
+ let streamLine = parts.join(" \u2192 ");
1541
+ if (tps)
1542
+ streamLine += ` \xB7 ${tps} tok/s`;
1543
+ entries.push({
1544
+ key: "ai.streaming",
1545
+ value: streamLine
1546
+ });
1547
+ }
1548
+ const estimatedCost = asNumber(ai.estimatedCost);
1549
+ if (estimatedCost !== undefined)
1550
+ entries.push({
1551
+ key: "ai.cost",
1552
+ value: formatCost(estimatedCost)
1553
+ });
1554
+ const totalDurationMs = asNumber(ai.totalDurationMs);
1555
+ if (totalDurationMs !== undefined)
1556
+ entries.push({
1557
+ key: "ai.totalDuration",
1558
+ value: formatDuration(totalDurationMs)
1559
+ });
1560
+ const toolCalls = Array.isArray(ai.toolCalls) ? ai.toolCalls : undefined;
1561
+ const tools = asToolUsageArray(ai.tools);
1562
+ const toolCallEntries = toolCalls ? asToolCallArray(toolCalls) : undefined;
1563
+ const hasInputs = toolCallEntries !== undefined && toolCallEntries.length > 0;
1564
+ if (tools?.length) {
1565
+ const children = tools.map((t, idx) => {
1566
+ const mark = t.success ? "\u2713" : "\u2717";
1567
+ let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
1568
+ if (t.error)
1569
+ line += ` ${t.error}`;
1570
+ if (hasInputs && toolCallEntries && idx < toolCallEntries.length) {
1571
+ const tc = toolCallEntries[idx];
1572
+ const inputStr = serializeToolInput(tc.input);
1573
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
1574
+ line += ` ${truncated}`;
1575
+ }
1576
+ return line;
1577
+ });
1578
+ entries.push({
1579
+ key: "ai.tools",
1580
+ value: "",
1581
+ children
1582
+ });
1583
+ } else if (toolCalls?.length) {
1584
+ if (toolCallEntries?.length) {
1585
+ const children = toolCallEntries.map((tc) => {
1586
+ const inputStr = serializeToolInput(tc.input);
1587
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
1588
+ return `${tc.name}(${truncated})`;
1589
+ });
1590
+ entries.push({
1591
+ key: "ai.tools",
1592
+ value: "",
1593
+ children
1594
+ });
1595
+ } else {
1596
+ const names = asStringArray(toolCalls);
1597
+ if (names?.length)
1598
+ entries.push({
1599
+ key: "ai.tools",
1600
+ value: names.join(", ")
1601
+ });
1602
+ }
1603
+ }
1604
+ const stepsUsage = Array.isArray(ai.stepsUsage) ? ai.stepsUsage.filter(isPlainObject$1) : undefined;
1605
+ if (stepsUsage?.length) {
1606
+ const firstModel = stepsUsage[0]?.model;
1607
+ const allSameModel = firstModel !== undefined && stepsUsage.every((s) => s.model === firstModel);
1608
+ const children = stepsUsage.map((s) => {
1609
+ let line = `${allSameModel ? "" : `${String(s.model)} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
1610
+ const stepTools = asStringArray(s.toolCalls);
1611
+ if (stepTools?.length)
1612
+ line += ` [${stepTools.join(", ")}]`;
1613
+ return line;
1614
+ });
1615
+ entries.push({
1616
+ key: "ai.steps",
1617
+ value: "",
1618
+ children
1619
+ });
1620
+ } else if (steps !== undefined && steps > 1)
1621
+ entries.push({
1622
+ key: "ai.steps",
1623
+ value: String(steps)
1624
+ });
1625
+ const promptLines = asCapturedLines(ai.prompt);
1626
+ if (promptLines)
1627
+ entries.push({
1628
+ key: "ai.prompt",
1629
+ value: "",
1630
+ children: promptLines
1631
+ });
1632
+ const outputLines = asCapturedLines(ai.output);
1633
+ if (outputLines)
1634
+ entries.push({
1635
+ key: "ai.output",
1636
+ value: "",
1637
+ children: outputLines
1638
+ });
1639
+ const embedding = isPlainObject$1(ai.embedding) ? ai.embedding : undefined;
1640
+ if (embedding) {
1641
+ const parts = [];
1642
+ if (embedding.model)
1643
+ parts.push(String(embedding.model));
1644
+ parts.push(`${embedding.tokens} tokens`);
1645
+ if (embedding.dimensions)
1646
+ parts.push(`${embedding.dimensions}d`);
1647
+ if (embedding.count)
1648
+ parts.push(`${embedding.count} items`);
1649
+ entries.push({
1650
+ key: "ai.embedding",
1651
+ value: parts.join(" \xB7 ")
1652
+ });
1653
+ }
1654
+ if (ai.finishReason)
1655
+ entries.push({
1656
+ key: "ai.finishReason",
1657
+ value: String(ai.finishReason)
1658
+ });
1659
+ if (ai.error)
1660
+ entries.push({
1661
+ key: "ai.error",
1662
+ value: String(ai.error)
1663
+ });
1664
+ if (ai.responseId)
1665
+ entries.push({
1666
+ key: "ai.responseId",
1667
+ value: String(ai.responseId)
1668
+ });
1669
+ return entries;
1670
+ }
1671
+ function flushPrettyLines(lines) {
1672
+ if (lines.length === 0)
1673
+ return;
1674
+ const text = `${lines.join(`
1675
+ `)}
1676
+ `;
1677
+ if (nativeStdoutWrite && !isBrowser() && process.env.VITEST !== "true") {
1678
+ writePrettyStdout(text);
1679
+ return;
1680
+ }
1681
+ console.log(lines.join(`
1682
+ `));
1683
+ }
1684
+ function prettyPrintWideEvent(event) {
1685
+ const { timestamp, level, service, environment, version, ...rest } = event;
1686
+ const ts = typeof timestamp === "string" ? timestamp.slice(11, 23) : "";
1687
+ const levelLabel = typeof level === "string" ? level : "info";
1688
+ const browser = isBrowser();
1689
+ const lines = [];
1690
+ const writeLine = (...args) => {
1691
+ if (browser) {
1692
+ console.log(...args);
1693
+ return;
1694
+ }
1695
+ const [line] = args;
1696
+ if (typeof line === "string")
1697
+ lines.push(line);
1698
+ };
1699
+ const parts = [];
1700
+ const styles = [];
1701
+ if (browser) {
1702
+ const lc = getCssLevelColor(levelLabel);
1703
+ parts.push(`%c${ts}%c %c${levelLabel.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
1704
+ styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
1705
+ } else {
1706
+ const lc = getLevelColor(levelLabel);
1707
+ parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
1708
+ }
1709
+ if (rest.method && rest.path) {
1710
+ parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
1711
+ delete rest.method;
1712
+ delete rest.path;
1713
+ }
1714
+ if (rest.status) {
1715
+ const statusCode = asNumber(rest.status) ?? Number(rest.status);
1716
+ const sc = browser ? statusCode >= 400 ? cssColors.red : cssColors.green : statusCode >= 400 ? colors.red : colors.green;
1717
+ if (browser) {
1718
+ parts.push(` %c${rest.status}%c`);
1719
+ styles.push(sc, cssColors.reset);
1720
+ } else
1721
+ parts.push(` ${sc}${rest.status}${colors.reset}`);
1722
+ delete rest.status;
1723
+ }
1724
+ if (rest.duration) {
1725
+ if (browser) {
1726
+ parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
1727
+ styles.push(cssColors.dim, cssColors.reset);
1728
+ } else
1729
+ parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
1730
+ delete rest.duration;
1731
+ }
1732
+ delete rest.durationMs;
1733
+ writeLine(parts.join(""), ...styles);
1734
+ const aiData = isPlainObject$1(rest.ai) ? rest.ai : undefined;
1735
+ if (aiData)
1736
+ delete rest.ai;
1737
+ const errorData = rest.error;
1738
+ if (errorData !== undefined)
1739
+ delete rest.error;
1740
+ const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
1741
+ const aiEntries = aiData ? buildAIEntries(aiData) : [];
1742
+ const errorEntries = errorData !== undefined ? buildErrorEntries(errorData, state.prettyError) : [];
1743
+ const contextEntries = [...restEntries.map(([key, value]) => ({
1744
+ key,
1745
+ value: formatValue(value)
1746
+ })), ...aiEntries];
1747
+ const allEntries = errorEntries.length > 0 ? [...errorEntries, ...contextEntries] : contextEntries;
1748
+ for (let i = 0;i < allEntries.length; i++) {
1749
+ const entry = allEntries[i];
1750
+ if (!entry)
1751
+ continue;
1752
+ const { children } = entry;
1753
+ const hasChildren = children !== undefined && children.length > 0;
1754
+ const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
1755
+ if (browser) {
1756
+ const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
1757
+ writeLine(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
1758
+ } else {
1759
+ const val = entry.value ? ` ${entry.value}` : "";
1760
+ writeLine(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
1761
+ }
1762
+ if (hasChildren && children) {
1763
+ const connector = i === allEntries.length - 1 ? " " : "\u2502";
1764
+ for (let j = 0;j < children.length; j++) {
1765
+ const child = children[j];
1766
+ if (child === undefined)
1767
+ continue;
1768
+ if (child === "__EVLOG_TREE_SPACER__") {
1769
+ writeLine(` ${colors.dim}${connector}${colors.reset}`);
1770
+ continue;
1771
+ }
1772
+ const childPrefix = j === children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
1773
+ if (child === "") {
1774
+ writeLine("");
1775
+ continue;
1776
+ }
1777
+ if (browser)
1778
+ writeLine(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
1779
+ else if (child.startsWith(" ") || child.startsWith("\x1B"))
1780
+ writeLine(` ${colors.dim}${connector}${colors.reset}${child}`);
1781
+ else
1782
+ writeLine(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
1783
+ }
1784
+ }
1785
+ }
1786
+ if (!browser && lines.length > 0)
1787
+ flushPrettyLines(lines);
1788
+ }
1789
+ function removeErrorCycles(value, ancestors) {
1790
+ if (value === null || typeof value !== "object")
1791
+ return value;
1792
+ if (ancestors.has(value))
1793
+ return "[Circular]";
1794
+ ancestors.add(value);
1795
+ let changed = false;
1796
+ const visit = (item) => {
1797
+ const result = removeErrorCycles(item, ancestors);
1798
+ if (!Object.is(result, item))
1799
+ changed = true;
1800
+ return result;
1801
+ };
1802
+ const copy = Array.isArray(value) ? value.map(visit) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
1803
+ ancestors.delete(value);
1804
+ return changed ? copy : value;
1805
+ }
1806
+ function serializeError(err) {
1807
+ const errorObj = {
1808
+ name: err.name,
1809
+ message: err.message,
1810
+ stack: isDev() ? compactStackForStorage(err.stack) : err.stack
1811
+ };
1812
+ const errRecord = err;
1813
+ const ancestors = new WeakSet([err]);
1814
+ for (const k of [
1815
+ "code",
1816
+ "status",
1817
+ "statusText",
1818
+ "statusCode",
1819
+ "statusMessage",
1820
+ "data",
1821
+ "cause",
1822
+ "internal"
1823
+ ])
1824
+ if (k in err)
1825
+ errorObj[k] = removeErrorCycles(errRecord[k], ancestors);
1826
+ if (EvlogError.isEvlogError(err)) {
1827
+ if (err.code)
1828
+ errorObj.code = err.code;
1829
+ if (err.why)
1830
+ errorObj.why = err.why;
1831
+ if (err.fix)
1832
+ errorObj.fix = err.fix;
1833
+ if (err.link)
1834
+ errorObj.link = err.link;
1835
+ if (err.status)
1836
+ errorObj.status = err.status;
1837
+ }
1838
+ return errorObj;
1839
+ }
1840
+ function createLogMethod(level) {
1841
+ return function logMethod(tagOrEvent, message) {
1842
+ if (typeof tagOrEvent === "string" && message !== undefined)
1843
+ emitTaggedLog(level, tagOrEvent, message);
1844
+ else if (tagOrEvent instanceof Error)
1845
+ emitWideEvent(level, { error: serializeError(tagOrEvent) });
1846
+ else if (typeof tagOrEvent === "object")
1847
+ emitWideEvent(level, tagOrEvent);
1848
+ else
1849
+ emitTaggedLog(level, "log", String(tagOrEvent));
1850
+ };
1851
+ }
1852
+ function createLogger(initialContext = {}, internalOptions) {
1853
+ if (!state.enabled)
1854
+ return noopLogger;
1855
+ const deferDrain = internalOptions?._deferDrain ?? false;
1856
+ const waitUntil = internalOptions?.waitUntil;
1857
+ const startTime = Date.now();
1858
+ const context = { ...initialContext };
1859
+ let hasError = false;
1860
+ let hasWarn = false;
1861
+ let manualLevel;
1862
+ let emitted = false;
1863
+ let pendingWideEvent = null;
1864
+ function addLog(level, message) {
1865
+ if (!Array.isArray(context.requestLogs))
1866
+ context.requestLogs = [];
1867
+ context.requestLogs.push({
1868
+ level,
1869
+ message,
1870
+ timestamp: isoNow()
1871
+ });
1872
+ }
1873
+ const auditMethod = function audit(input) {
1874
+ if (emitted) {
1875
+ warnPostEmit("log.audit()", `Audit dropped: action=${input.action}.`);
1876
+ return;
1877
+ }
1878
+ const fields = buildAuditFields(input);
1879
+ if (!isPlainObject$1(context.audit))
1880
+ context.audit = fields;
1881
+ else
1882
+ mergeInto(context.audit, fields);
1883
+ context._auditForceKeep = true;
1884
+ };
1885
+ auditMethod.deny = function deny(reason, input) {
1886
+ auditMethod({
1887
+ ...input,
1888
+ outcome: "denied",
1889
+ reason
1890
+ });
1891
+ };
1892
+ return {
1893
+ audit: auditMethod,
1894
+ set(data) {
1895
+ if (emitted) {
1896
+ const record = data;
1897
+ const pendingState = pendingWideEvent ? pendingDrainState.get(pendingWideEvent) : undefined;
1898
+ if (pendingWideEvent && pendingState && !pendingState.drainStarted && isAiOnlyFieldUpdate(record)) {
1899
+ mergeInto(pendingWideEvent, record);
1900
+ return;
1901
+ }
1902
+ const keys = Object.keys(record);
1903
+ warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
1904
+ return;
1905
+ }
1906
+ mergeInto(context, data);
1907
+ },
1908
+ setLevel(level) {
1909
+ if (emitted) {
1910
+ warnPostEmit("log.setLevel()", `Level dropped: ${level}.`);
1911
+ return;
1912
+ }
1913
+ manualLevel = level;
1914
+ },
1915
+ error(error, errorContext) {
1916
+ if (emitted) {
1917
+ warnPostEmit("log.error()", `Keys dropped: ${(errorContext ? [...Object.keys(errorContext), "error"] : ["error"]).join(", ")}.`);
1918
+ return;
1919
+ }
1920
+ hasError = true;
1921
+ const err = typeof error === "string" ? new Error(error) : error;
1922
+ if (errorContext)
1923
+ mergeInto(context, errorContext);
1924
+ const errorObj = serializeError(err);
1925
+ if (isPlainObject$1(context.error))
1926
+ mergeInto(context.error, errorObj);
1927
+ else
1928
+ context.error = errorObj;
1929
+ },
1930
+ info(message, infoContext) {
1931
+ if (emitted) {
1932
+ warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
1933
+ return;
1934
+ }
1935
+ addLog("info", message);
1936
+ if (infoContext) {
1937
+ const { requestLogs: _, ...rest } = infoContext;
1938
+ mergeInto(context, rest);
1939
+ }
1940
+ },
1941
+ warn(message, warnContext) {
1942
+ if (emitted) {
1943
+ warnPostEmit("log.warn()", `Keys dropped: ${(warnContext ? ["message", ...Object.keys(warnContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
1944
+ return;
1945
+ }
1946
+ hasWarn = true;
1947
+ addLog("warn", message);
1948
+ if (warnContext) {
1949
+ const { requestLogs: _, ...rest } = warnContext;
1950
+ mergeInto(context, rest);
1951
+ }
1952
+ },
1953
+ emit(overrides) {
1954
+ if (emitted) {
1955
+ warnPostEmit("log.emit()", "Ignoring duplicate emit.");
1956
+ return null;
1957
+ }
1958
+ const durationMs = elapsedMs(startTime);
1959
+ const level = manualLevel ?? (hasError ? "error" : hasWarn ? "warn" : "info");
1960
+ let forceKeep = false;
1961
+ const auditForceKeep = consumeAuditForceKeep(context);
1962
+ if (overrides?._forceKeep)
1963
+ forceKeep = true;
1964
+ else if (auditForceKeep)
1965
+ forceKeep = true;
1966
+ else if (state.sampling.keep?.length)
1967
+ forceKeep = shouldKeep({
1968
+ status: overrides?.status ?? context.status,
1969
+ duration: durationMs,
1970
+ path: context.path,
1971
+ method: context.method,
1972
+ context
1973
+ });
1974
+ if (!forceKeep && !shouldSample(level)) {
1975
+ emitted = true;
1976
+ pendingWideEvent = null;
1977
+ return null;
1978
+ }
1979
+ if (overrides) {
1980
+ const obj = overrides;
1981
+ for (const key in obj)
1982
+ if (key !== "_forceKeep")
1983
+ context[key] = obj[key];
1984
+ }
1985
+ context.durationMs = durationMs;
1986
+ context.duration = formatDuration(durationMs);
1987
+ const wide = emitWideEvent(level, context, {
1988
+ deferDrain,
1989
+ ownsEvent: true,
1990
+ waitUntil
1991
+ });
1992
+ emitted = true;
1993
+ pendingWideEvent = wide;
1994
+ if (wide)
1995
+ pendingDrainState.set(wide, { drainStarted: !deferDrain });
1996
+ return wide;
1997
+ },
1998
+ getContext() {
1999
+ return { ...context };
2000
+ }
2001
+ };
2002
+ }
2003
+ function createRequestLogger(options = {}, internalOptions) {
2004
+ const { method, path, requestId, waitUntil: optionsWaitUntil } = options;
2005
+ const initial = {};
2006
+ if (method !== undefined)
2007
+ initial.method = method;
2008
+ if (path !== undefined)
2009
+ initial.path = path;
2010
+ if (requestId !== undefined)
2011
+ initial.requestId = requestId;
2012
+ return createLogger(initial, {
2013
+ ...internalOptions,
2014
+ waitUntil: internalOptions?.waitUntil ?? optionsWaitUntil
2015
+ });
2016
+ }
2017
+ function isPlainObject2(value) {
2018
+ if (typeof value !== "object" || value === null || Array.isArray(value))
2019
+ return false;
2020
+ if (Object.prototype.toString.call(value) !== "[object Object]")
2021
+ return false;
2022
+ return Object.getPrototypeOf(value) === Object.prototype || value.constructor === Object;
2023
+ }
2024
+ function stableStringify(value, ancestors = /* @__PURE__ */ new WeakSet) {
2025
+ if (value === null || typeof value !== "object")
2026
+ return JSON.stringify(value);
2027
+ if (ancestors.has(value))
2028
+ return '"[Circular]"';
2029
+ if (!Array.isArray(value) && !isPlainObject2(value))
2030
+ return JSON.stringify(value);
2031
+ ancestors.add(value);
2032
+ const out = Array.isArray(value) ? `[${value.map((v) => stableStringify(v, ancestors)).join(",")}]` : `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k], ancestors)}`).join(",")}}`;
2033
+ ancestors.delete(value);
2034
+ return out;
2035
+ }
2036
+ function fnv1a32(input, seed) {
2037
+ let h = seed >>> 0;
2038
+ for (let i = 0;i < input.length; i++) {
2039
+ h ^= input.charCodeAt(i) & 255;
2040
+ h = Math.imul(h, 16777619) >>> 0;
2041
+ }
2042
+ return h >>> 0;
2043
+ }
2044
+ function computeIdempotencyKey(audit, timestamp) {
2045
+ const seconds = timestamp.slice(0, 19);
2046
+ const payload = stableStringify({
2047
+ action: audit.action,
2048
+ actor: {
2049
+ type: audit.actor.type,
2050
+ id: audit.actor.id
2051
+ },
2052
+ target: audit.target ? {
2053
+ type: audit.target.type,
2054
+ id: audit.target.id
2055
+ } : undefined,
2056
+ outcome: audit.outcome,
2057
+ timestamp: seconds
2058
+ });
2059
+ const a = fnv1a32(payload, 2166136261).toString(16).padStart(8, "0");
2060
+ const b = fnv1a32(payload, 3735928559).toString(16).padStart(8, "0");
2061
+ const c = fnv1a32(payload, 528734635).toString(16).padStart(8, "0");
2062
+ const d = fnv1a32(payload, 1541459225).toString(16).padStart(8, "0");
2063
+ return a + b + c + d;
2064
+ }
2065
+ function buildAuditFields(input) {
2066
+ return {
2067
+ action: input.action,
2068
+ actor: input.actor,
2069
+ target: input.target,
2070
+ outcome: input.outcome ?? "success",
2071
+ reason: input.reason,
2072
+ changes: input.changes,
2073
+ causationId: input.causationId,
2074
+ correlationId: input.correlationId,
2075
+ version: input.version ?? 1
2076
+ };
2077
+ }
2078
+ function decorateAudit(audit, timestamp) {
2079
+ if (audit.idempotencyKey)
2080
+ return audit;
2081
+ return {
2082
+ ...audit,
2083
+ idempotencyKey: computeIdempotencyKey(audit, timestamp)
2084
+ };
2085
+ }
2086
+ function consumeAuditForceKeep(context) {
2087
+ if (context._auditForceKeep) {
2088
+ delete context._auditForceKeep;
2089
+ return true;
2090
+ }
2091
+ if (context.audit)
2092
+ return true;
2093
+ return false;
2094
+ }
2095
+ function isCompleteAuditFields(a) {
2096
+ if (!a || typeof a !== "object")
2097
+ return false;
2098
+ const audit = a;
2099
+ return typeof audit.action === "string" && typeof audit.actor?.type === "string" && typeof audit.actor?.id === "string";
2100
+ }
2101
+ function finalizeAudit(event) {
2102
+ const a = event.audit;
2103
+ if (!isCompleteAuditFields(a))
2104
+ return;
2105
+ const decorated = decorateAudit(a, String(event.timestamp));
2106
+ event.audit = decorated;
2107
+ _testCollector?.(decorated, event);
2108
+ }
2109
+ var nativeStdoutWrite, POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).", pendingDrainState, state, CAPTURED_LINE_MAX_LENGTH = 160, CAPTURED_MAX_LINES = 8, _log, noopLogger, _testCollector = null;
2110
+ var init_audit_C8euLMvu = __esm(() => {
2111
+ init_utils();
2112
+ init_redact_C7FmdhwI();
2113
+ init_globalRegistry_Bh3bIGwA();
2114
+ init_pretty_error_D8rlWNL1();
2115
+ init_dev_terminal_Brarc6vc();
2116
+ init_wideEventChannel_BUDW48oP();
2117
+ init_error();
2118
+ nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
2119
+ pendingDrainState = /* @__PURE__ */ new WeakMap;
2120
+ state = globalConfig;
2121
+ _log = {
2122
+ info: createLogMethod("info"),
2123
+ error: createLogMethod("error"),
2124
+ warn: createLogMethod("warn"),
2125
+ debug: createLogMethod("debug")
2126
+ };
2127
+ noopLogger = {
2128
+ set() {},
2129
+ setLevel() {},
2130
+ error() {},
2131
+ info() {},
2132
+ warn() {},
2133
+ emit() {
2134
+ return null;
2135
+ },
2136
+ getContext() {
2137
+ return {};
2138
+ },
2139
+ audit: Object.assign(() => {}, { deny: () => {} })
2140
+ };
2141
+ if (typeof __EVLOG_CONFIG__ !== "undefined")
2142
+ initLogger(__EVLOG_CONFIG__);
2143
+ });
2144
+
2145
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2146
+ function extractErrorStatus(error) {
2147
+ if (error === null || typeof error !== "object")
2148
+ return 500;
2149
+ const raw = error.status ?? error.statusCode;
2150
+ const status = Number(raw);
2151
+ return Number.isFinite(status) ? status : 500;
2152
+ }
2153
+ var init_errors_CL8dDgIi = () => {};
2154
+
2155
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2156
+ function shouldLog(path, include, exclude) {
2157
+ if (exclude && exclude.length > 0) {
2158
+ if (exclude.some((pattern) => matchesPattern(path, pattern)))
2159
+ return false;
2160
+ }
2161
+ if (!include || include.length === 0)
2162
+ return true;
2163
+ return include.some((pattern) => matchesPattern(path, pattern));
2164
+ }
2165
+ function getServiceForPath(path, routes) {
2166
+ if (!routes)
2167
+ return;
2168
+ for (const [pattern, config] of Object.entries(routes))
2169
+ if (matchesPattern(path, pattern))
2170
+ return config.service;
2171
+ }
2172
+ function extendDeferredDrain(drainPromise, waitUntil) {
2173
+ drainPromise.catch((err) => {
2174
+ console.error("[evlog] background drain failed:", err);
2175
+ });
2176
+ if (typeof waitUntil === "function")
2177
+ waitUntil(drainPromise);
2178
+ }
2179
+ var init_deferred_drain_CfRYimo5 = __esm(() => {
2180
+ init_utils();
2181
+ });
2182
+
2183
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/middleware-fam3VyaL.mjs
2184
+ function resolveMiddlewarePluginRunner(options) {
2185
+ const global = getGlobalPluginRunner();
2186
+ const local = options.plugins;
2187
+ if (!local || local.length === 0)
2188
+ return global;
2189
+ const cached = runnerCache.get(local);
2190
+ if (cached && cached.global === global)
2191
+ return cached.merged;
2192
+ const merged = /* @__PURE__ */ new Map;
2193
+ for (const plugin of global.plugins)
2194
+ merged.set(plugin.name, plugin);
2195
+ for (const plugin of local)
2196
+ merged.set(plugin.name, plugin);
2197
+ if (merged.size === 0)
2198
+ return getEmptyPluginRunner();
2199
+ const runner = createPluginRunner(Array.from(merged.values()));
2200
+ runnerCache.set(local, {
2201
+ global,
2202
+ merged: runner
2203
+ });
2204
+ return runner;
2205
+ }
2206
+ function assignRedactedEvent(target, redacted) {
2207
+ for (const key of Object.keys(target))
2208
+ if (!(key in redacted))
2209
+ delete target[key];
2210
+ Object.assign(target, redacted);
2211
+ }
2212
+ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus, plugins) {
2213
+ const runner = plugins ?? resolveMiddlewarePluginRunner(options);
2214
+ const resolvedRedact = resolveRedactConfig(options.redact);
2215
+ if (resolvedRedact && !isGloballyRedacted(emittedEvent))
2216
+ assignRedactedEvent(emittedEvent, redactEvent(emittedEvent, resolvedRedact));
2217
+ if (options.enrich || runner.hasEnrich) {
2218
+ const enrichCtx = {
2219
+ event: emittedEvent,
2220
+ request: requestInfo,
2221
+ headers: options.headers,
2222
+ response: { status: responseStatus }
2223
+ };
2224
+ if (options.enrich)
2225
+ try {
2226
+ await options.enrich(enrichCtx);
2227
+ } catch (err) {
2228
+ console.error("[evlog] enrich failed:", err);
2229
+ }
2230
+ if (runner.hasEnrich)
2231
+ await runner.runEnrich(enrichCtx);
2232
+ }
2233
+ publishWideEvent(emittedEvent);
2234
+ markWideEventDrainStarted(emittedEvent);
2235
+ const drain = options.drain ?? getGlobalDrain();
2236
+ const hasUserDrain = !!drain;
2237
+ const hasPluginDrain = runner.hasDrain;
2238
+ if (hasUserDrain || hasPluginDrain) {
2239
+ const drainCtx = {
2240
+ event: emittedEvent,
2241
+ request: requestInfo,
2242
+ headers: options.headers
2243
+ };
2244
+ const tasks = [];
2245
+ if (hasUserDrain)
2246
+ tasks.push((async () => {
2247
+ try {
2248
+ await drain(drainCtx);
2249
+ } catch (err) {
2250
+ console.error("[evlog] drain failed:", err);
2251
+ }
2252
+ })());
2253
+ if (hasPluginDrain)
2254
+ tasks.push(runner.runDrain(drainCtx));
2255
+ const drainPromise = Promise.all(tasks);
2256
+ if (options.waitUntil) {
2257
+ extendDeferredDrain(drainPromise, options.waitUntil);
2258
+ if (hasUserDrain) {
2259
+ const { settled } = drain;
2260
+ if (typeof settled === "function")
2261
+ extendDeferredDrain(settled(), options.waitUntil);
2262
+ }
2263
+ return;
2264
+ }
2265
+ await drainPromise;
2266
+ }
2267
+ }
2268
+ function createMiddlewareLogger(options) {
2269
+ if (!isEnabled())
2270
+ return noopResult;
2271
+ const { method, path, requestId, include, exclude, routes, keep } = options;
2272
+ if (!shouldLog(path, include, exclude))
2273
+ return noopResult;
2274
+ const resolvedRequestId = requestId || crypto.randomUUID();
2275
+ const logger = createRequestLogger({
2276
+ method,
2277
+ path,
2278
+ requestId: resolvedRequestId
2279
+ }, { _deferDrain: true });
2280
+ const routeService = getServiceForPath(path, routes);
2281
+ if (routeService)
2282
+ logger.set({ service: routeService });
2283
+ const pluginRunner = resolveMiddlewarePluginRunner(options);
2284
+ if (pluginRunner.hasExtendLogger)
2285
+ pluginRunner.applyExtendLogger(logger);
2286
+ const startTime = Date.now();
2287
+ const requestInfo = {
2288
+ method,
2289
+ path,
2290
+ requestId: resolvedRequestId
2291
+ };
2292
+ if (pluginRunner.hasRequestLifecycle)
2293
+ pluginRunner.runOnRequestStart({
2294
+ logger,
2295
+ request: requestInfo,
2296
+ headers: options.headers
2297
+ });
2298
+ const finish = (opts) => {
2299
+ return performFinish(logger, opts);
2300
+ };
2301
+ const finishResponse = async (response, opts) => {
2302
+ const status = opts?.status ?? response.status;
2303
+ if (!shouldDeferEmitForResponse(response)) {
2304
+ await performFinish(logger, { status });
2305
+ return response;
2306
+ }
2307
+ return bindStreamingResponseLifecycle(response, async (meta) => {
2308
+ await performFinish(logger, {
2309
+ status: meta.status ?? status,
2310
+ error: meta.error
2311
+ });
2312
+ });
2313
+ };
2314
+ async function performFinish(requestLogger, opts) {
2315
+ const { status, error } = opts ?? {};
2316
+ if (error) {
2317
+ requestLogger.error(error);
2318
+ const errorStatus = extractErrorStatus(error);
2319
+ requestLogger.set({ status: errorStatus });
2320
+ } else if (status !== undefined)
2321
+ requestLogger.set({ status });
2322
+ const durationMs = elapsedMs(startTime);
2323
+ const resolvedStatus = error ? extractErrorStatus(error) : status ?? requestLogger.getContext().status;
2324
+ const tailCtx = {
2325
+ status: resolvedStatus,
2326
+ duration: durationMs,
2327
+ path,
2328
+ method,
2329
+ context: requestLogger.getContext(),
2330
+ shouldKeep: false
2331
+ };
2332
+ if (keep)
2333
+ await keep(tailCtx);
2334
+ if (pluginRunner.hasKeep)
2335
+ await pluginRunner.runKeep(tailCtx);
2336
+ const forceKeep = tailCtx.shouldKeep || shouldKeep(tailCtx);
2337
+ const emittedEvent = requestLogger.emit({ _forceKeep: forceKeep });
2338
+ if (emittedEvent && (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain() || hasWideEventPublisher()))
2339
+ await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus, pluginRunner);
2340
+ if (pluginRunner.hasRequestLifecycle)
2341
+ pluginRunner.runOnRequestFinish({
2342
+ logger: requestLogger,
2343
+ request: requestInfo,
2344
+ headers: options.headers,
2345
+ event: emittedEvent,
2346
+ status: resolvedStatus,
2347
+ durationMs,
2348
+ error
2349
+ });
2350
+ return emittedEvent;
2351
+ }
2352
+ return {
2353
+ logger,
2354
+ finish,
2355
+ finishResponse,
2356
+ skipped: false
2357
+ };
2358
+ }
2359
+ var noopResult, runnerCache;
2360
+ var init_middleware_fam3VyaL = __esm(() => {
2361
+ init_utils();
2362
+ init_redact_C7FmdhwI();
2363
+ init_globalRegistry_Bh3bIGwA();
2364
+ init_wideEventChannel_BUDW48oP();
2365
+ init_audit_C8euLMvu();
2366
+ init_errors_CL8dDgIi();
2367
+ init_deferred_drain_CfRYimo5();
2368
+ init_streamResponse_OlirMA5P();
2369
+ noopResult = {
2370
+ logger: noopLogger,
2371
+ finish: () => Promise.resolve(null),
2372
+ finishResponse: (response) => Promise.resolve(response),
2373
+ skipped: true
2374
+ };
2375
+ runnerCache = /* @__PURE__ */ new WeakMap;
2376
+ });
2377
+
2378
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/integration-CGD18W8r.mjs
2379
+ function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
2380
+ const log = parent;
2381
+ log.fork = (label, fn) => {
2382
+ forkBackgroundLogger({
2383
+ storage,
2384
+ parent,
2385
+ middlewareOptions,
2386
+ label,
2387
+ fn,
2388
+ lifecycle
2389
+ });
2390
+ };
2391
+ }
2392
+ function forkBackgroundLogger(options) {
2393
+ const { storage, parent, middlewareOptions, label, fn, lifecycle } = options;
2394
+ const parentCtx = parent.getContext();
2395
+ const parentRequestId = parentCtx.requestId;
2396
+ if (typeof parentRequestId !== "string" || parentRequestId.length === 0)
2397
+ throw new Error("[evlog] log.fork() requires the parent logger to have a requestId. Ensure the request was created by evlog middleware.");
2398
+ const method = String(parentCtx.method ?? middlewareOptions.method);
2399
+ const path = String(parentCtx.path ?? middlewareOptions.path);
2400
+ const child = createRequestLogger({
2401
+ method,
2402
+ path,
2403
+ requestId: crypto.randomUUID()
2404
+ }, { _deferDrain: true });
2405
+ child.set({
2406
+ operation: label,
2407
+ _parentRequestId: parentRequestId
2408
+ });
2409
+ const childRequestInfo = {
2410
+ method,
2411
+ path,
2412
+ requestId: child.getContext().requestId
2413
+ };
2414
+ storage.run(child, () => {
2415
+ lifecycle?.onChildEnter?.(child);
2416
+ Promise.resolve().then(() => fn()).then(async () => {
2417
+ const emittedEvent = child.emit();
2418
+ const ctxStatus = child.getContext().status;
2419
+ const status = emittedEvent?.status ?? (typeof ctxStatus === "number" ? ctxStatus : undefined);
2420
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2421
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2422
+ }).catch(async (err) => {
2423
+ const error = err instanceof Error ? err : new Error(String(err));
2424
+ child.error(error);
2425
+ child.set({ status: extractErrorStatus(error) });
2426
+ const emittedEvent = child.emit();
2427
+ const status = extractErrorStatus(error);
2428
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2429
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2430
+ }).finally(() => {
2431
+ lifecycle?.onChildExit?.(child);
2432
+ });
2433
+ });
2434
+ }
2435
+ function normalizeHeaders(headers) {
2436
+ if (!headers)
2437
+ return;
2438
+ if (typeof headers.forEach === "function" && typeof headers.get === "function")
2439
+ return extractSafeHeaders(headers);
2440
+ return extractSafeNodeHeaders(headers);
2441
+ }
2442
+ function defineFrameworkIntegration(spec) {
2443
+ return { start(ctx, options = {}) {
2444
+ const extracted = spec.extractRequest(ctx);
2445
+ const headers = normalizeHeaders(extracted.headers);
2446
+ const waitUntil = options.waitUntil ?? spec.extractWaitUntil?.(ctx);
2447
+ const middlewareOptions = {
2448
+ method: extracted.method,
2449
+ path: extracted.path,
2450
+ requestId: extracted.requestId || crypto.randomUUID(),
2451
+ headers,
2452
+ ...options,
2453
+ waitUntil
2454
+ };
2455
+ const result = createMiddlewareLogger(middlewareOptions);
2456
+ if (!result.skipped) {
2457
+ if (spec.storage)
2458
+ attachForkToLogger(spec.storage, result.logger, middlewareOptions, spec.forkLifecycle);
2459
+ spec.attachLogger(ctx, result.logger);
2460
+ }
2461
+ const { storage } = spec;
2462
+ const runWith = async (fn) => {
2463
+ if (!storage || result.skipped)
2464
+ return await fn();
2465
+ return await storage.run(result.logger, fn);
2466
+ };
2467
+ return {
2468
+ ...result,
2469
+ middlewareOptions,
2470
+ runWith
2471
+ };
2472
+ } };
2473
+ }
2474
+ var init_integration_CGD18W8r = __esm(() => {
2475
+ init_audit_C8euLMvu();
2476
+ init_headers_Bx1ieR_m();
2477
+ init_errors_CL8dDgIi();
2478
+ init_middleware_fam3VyaL();
2479
+ });
2480
+
2481
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit/storage.mjs
2482
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2483
+ function createLoggerStorage(contextHint, id = contextHint) {
2484
+ const storage = getSharedStorage(id, () => new AsyncLocalStorage2);
2485
+ function useLogger() {
2486
+ const logger = storage.getStore();
2487
+ if (!logger)
2488
+ throw new Error(`[evlog] useLogger() was called outside of an evlog ${contextHint}`);
2489
+ return logger;
2490
+ }
2491
+ return {
2492
+ storage,
2493
+ useLogger
2494
+ };
2495
+ }
2496
+ var init_storage = __esm(() => {
2497
+ init_globalRegistry_Bh3bIGwA();
2498
+ });
2499
+
2500
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit.mjs
2501
+ var init_toolkit = __esm(() => {
2502
+ init_integration_CGD18W8r();
2503
+ init_storage();
2504
+ });
2505
+
2506
+ // src/server/evlog.ts
2507
+ import { Elysia } from "elysia";
2508
+ function setRuntimeEvlogWaitUntil(waitUntil) {
2509
+ runtimeWaitUntil.add(waitUntil);
2510
+ return () => runtimeWaitUntil.delete(waitUntil);
2511
+ }
2512
+ var loggerStorage, integration, getRequestLogger, runtimeWaitUntil;
2513
+ var init_evlog = __esm(() => {
2514
+ init_toolkit();
2515
+ loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
2516
+ integration = defineFrameworkIntegration({
2517
+ attachLogger: () => {
2518
+ return;
2519
+ },
2520
+ extractRequest: ({ request }) => {
2521
+ const url = new URL(request.url);
2522
+ return {
2523
+ headers: request.headers,
2524
+ method: request.method,
2525
+ path: url.pathname,
2526
+ requestId: request.headers.get("x-request-id") ?? undefined
2527
+ };
2528
+ },
2529
+ name: "furin",
2530
+ storage: loggerStorage.storage
2531
+ });
2532
+ getRequestLogger = loggerStorage.useLogger;
2533
+ runtimeWaitUntil = new Set;
2534
+ });
2535
+
2
2536
  // src/server/instance.ts
3
2537
  import { AsyncLocalStorage } from "async_hooks";
4
2538
  var _requestScope = new AsyncLocalStorage;
@@ -376,6 +2910,9 @@ function setRuntimeCacheProvider(provider) {
376
2910
  runtimeCacheState().provider = provider;
377
2911
  }
378
2912
 
2913
+ // src/server/internal.ts
2914
+ init_evlog();
2915
+
379
2916
  // src/server/external-prerender.ts
380
2917
  var externalPrerenderRequests = new WeakSet;
381
2918
  function markExternalPrerenderRequest(request) {
@@ -433,6 +2970,7 @@ function markExternalPrerenderRequest2(request) {
433
2970
  function setRuntimeCacheProvider2(provider) {
434
2971
  setRuntimeCacheProvider(provider);
435
2972
  }
2973
+ var setRuntimeEvlogWaitUntil2 = setRuntimeEvlogWaitUntil;
436
2974
  function setCacheTagPurger2(purger) {
437
2975
  setCacheTagPurger(purger);
438
2976
  }
@@ -515,5 +3053,6 @@ export {
515
3053
  restorePprResumeRequest2 as restorePprResumeRequest,
516
3054
  setCacheTagPurger2 as setCacheTagPurger,
517
3055
  setRuntimeCacheProvider2 as setRuntimeCacheProvider,
3056
+ setRuntimeEvlogWaitUntil2 as setRuntimeEvlogWaitUntil,
518
3057
  waitForPendingISRRevalidations2 as waitForPendingISRRevalidations
519
3058
  };