vibesane 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,750 @@
1
+ import { toAsciiSafe } from '../text/ascii.js';
2
+ const KNOWN_SECRET_PREFIXES = [
3
+ 'sk_live_',
4
+ 'sk_test_',
5
+ 'rk_live_',
6
+ 'rk_test_',
7
+ 'AIzaSy',
8
+ 'ghp_',
9
+ 'sk-proj-',
10
+ 'sk-ant-',
11
+ ];
12
+ export function redactSecret(secret) {
13
+ for (const prefix of KNOWN_SECRET_PREFIXES) {
14
+ if (secret.startsWith(prefix)) {
15
+ if (secret.length <= prefix.length + 4) {
16
+ return `${prefix}****`;
17
+ }
18
+ return `${prefix}****${secret.slice(-4)}`;
19
+ }
20
+ }
21
+ if (secret.length <= 8) {
22
+ return '****';
23
+ }
24
+ return `${secret.slice(0, 3)}****${secret.slice(-2)}`;
25
+ }
26
+ export function redactPassword(raw) {
27
+ if (!raw || raw.length === 0) {
28
+ return '***';
29
+ }
30
+ return `${raw[0]}***`;
31
+ }
32
+ const CONN_URI_PARTS_RE = /^((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?):\/\/[^:\s"'`@]+:)([^@\s"'`]+)(@[^\s"'`]+)$/i;
33
+ export function redactConnectionUri(uri) {
34
+ if (!uri) {
35
+ return '****';
36
+ }
37
+ const trimmed = uri.trim();
38
+ const match = CONN_URI_PARTS_RE.exec(trimmed);
39
+ if (match) {
40
+ return `${match[1]}****${match[3]}`;
41
+ }
42
+ const replaced = trimmed.replace(/((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?):\/\/[^:\s"'`@]+:)([^@\s"'`]+)(@)/gi, '$1****$3');
43
+ if (replaced !== trimmed) {
44
+ return replaced;
45
+ }
46
+ return redactSecret(trimmed);
47
+ }
48
+ export function stripViteTimestampQuery(pathOrUrl) {
49
+ if (!pathOrUrl) {
50
+ return pathOrUrl;
51
+ }
52
+ return pathOrUrl
53
+ .replace(/\?t=\d+&/g, '?')
54
+ .replace(/\?t=\d+(?=#|$)/g, '')
55
+ .replace(/&t=\d+/g, '');
56
+ }
57
+ const NEXT_DATA_SCRIPT_RE = /<script\b[^>]*\bid=["']__NEXT_DATA__["'][^>]*>([\s\S]*?)<\/script>/gi;
58
+ const TITLE_500_RE = /<title\b[^>]*>\s*(?:500(?:\b|\s|:|-)|Internal Server Error\b)/i;
59
+ const H1_500_RE = /<h1\b[^>]*>\s*(?:500(?:\b|\s|:|-)|Internal Server Error\b)/i;
60
+ function hasNextDataError(html) {
61
+ NEXT_DATA_SCRIPT_RE.lastIndex = 0;
62
+ let match;
63
+ let foundClosedTag = false;
64
+ while ((match = NEXT_DATA_SCRIPT_RE.exec(html)) !== null) {
65
+ foundClosedTag = true;
66
+ const body = match[1] ?? '';
67
+ if (/"err"\s*:\s*\{\s*"name"\s*:/.test(body) ||
68
+ /"statusCode"\s*:\s*500\b/.test(body)) {
69
+ return true;
70
+ }
71
+ }
72
+ if (foundClosedTag) {
73
+ return false;
74
+ }
75
+ const nextDataIdx = html.indexOf('<script id="__NEXT_DATA__"');
76
+ if (nextDataIdx !== -1) {
77
+ const truncatedTail = html.slice(nextDataIdx);
78
+ if (/"err"\s*:\s*\{\s*"name"\s*:/.test(truncatedTail) ||
79
+ /"statusCode"\s*:\s*500\b/.test(truncatedTail)) {
80
+ return true;
81
+ }
82
+ }
83
+ return false;
84
+ }
85
+ function hasNextErrorContext(html) {
86
+ if (/id=["']__next_error__["']/.test(html)) {
87
+ return true;
88
+ }
89
+ if (html.includes('__next_error__') &&
90
+ (html.includes('Server Error') || html.includes('Unhandled Runtime Error'))) {
91
+ return true;
92
+ }
93
+ return false;
94
+ }
95
+ const MASKED_ERROR_RULES = [
96
+ {
97
+ label: 'nextjs__container_errors',
98
+ matches: (html) => html.includes('nextjs__container_errors'),
99
+ },
100
+ {
101
+ label: 'Unhandled Runtime Error',
102
+ matches: (html) => html.includes('Unhandled Runtime Error'),
103
+ },
104
+ {
105
+ label: 'Application error: a client-side exception has occurred',
106
+ matches: (html) => html.includes('Application error: a client-side exception has occurred'),
107
+ },
108
+ {
109
+ label: '__next_error__',
110
+ matches: (html) => hasNextErrorContext(html),
111
+ },
112
+ {
113
+ label: '<nextjs-portal',
114
+ matches: (html) => html.includes('<nextjs-portal'),
115
+ },
116
+ {
117
+ label: '__NEXT_DATA__ error payload',
118
+ matches: (html) => hasNextDataError(html),
119
+ },
120
+ {
121
+ label: 'vite-error-overlay',
122
+ matches: (html) => html.includes('<vite-error-overlay') || html.includes('vite-error-overlay'),
123
+ },
124
+ {
125
+ label: '[plugin:vite:',
126
+ matches: (html) => html.includes('[plugin:vite:'),
127
+ },
128
+ {
129
+ label: 'Pre-transform error:',
130
+ matches: (html) => html.includes('Pre-transform error:'),
131
+ },
132
+ {
133
+ label: 'HTML 500 / Internal Server Error heading',
134
+ matches: (html) => TITLE_500_RE.test(html) || H1_500_RE.test(html),
135
+ },
136
+ ];
137
+ export function detectMaskedError(html, route) {
138
+ if (!html) {
139
+ return [];
140
+ }
141
+ for (const rule of MASKED_ERROR_RULES) {
142
+ if (rule.matches(html)) {
143
+ const viteInfo = extractViteErrorInfo(html, route);
144
+ const nextInfo = !viteInfo ? extractNextErrorInfo(html, route) : null;
145
+ const structured = viteInfo ?? nextInfo;
146
+ const snippet = structured ? structured.summary : rule.label;
147
+ return [
148
+ {
149
+ kind: 'masked_error',
150
+ severity: 'error',
151
+ route,
152
+ detail: `Masked error overlay detected on ${route} (${snippet})`,
153
+ maskedSnippet: snippet,
154
+ ...(viteInfo?.codeFrame ? { codeFrame: viteInfo.codeFrame } : {}),
155
+ },
156
+ ];
157
+ }
158
+ }
159
+ return [];
160
+ }
161
+ const STRIPE_SECRET_RE = /\b((?:sk|rk)_(?:live|test)_[0-9a-zA-Z]{10,})\b/g;
162
+ const GOOGLE_API_KEY_RE = /\b(AIzaSy[0-9A-Za-z_-]{33})\b/g;
163
+ const PROVIDER_TOKEN_RE = /\b(ghp_[0-9A-Za-z]{20,}|sk-proj-[0-9A-Za-z_-]{16,}|sk-ant-[0-9A-Za-z_-]{16,})\b/g;
164
+ const ENV_SECRET_RE = /\b([A-Z][A-Z0-9_]*(?:_SECRET|_PRIVATE_KEY))(?:\\?["'`])?\s*[:=]\s*\\?["'`]([^"'`\\\r\n]{6,})\\?["'`]/g;
165
+ const DATABASE_URL_RE = /\b(DATABASE_URL)(?:\\?["'`])?\s*[:=]\s*\\?["'`]((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?):\/\/[^:\s"'`\\]+:[^@\s"'`\\]+@[^"'`\\\s]+)\\?["'`]/g;
166
+ const PASSWORD_FIELD_RE = /(?:\\?["'](password|passwd|pwd|senha)\\?["']|\b(password|passwd|pwd|senha))\s*:\s*\\?["']([^"'\\\r\n]{4,})\\?["']/gi;
167
+ const PLACEHOLDER_VALUES = new Set([
168
+ '***',
169
+ '****',
170
+ '<secret>',
171
+ '<password>',
172
+ 'your-secret',
173
+ 'your_secret',
174
+ 'your-password',
175
+ 'your_password',
176
+ 'changeme',
177
+ 'password',
178
+ 'passwd',
179
+ 'pwd',
180
+ 'senha',
181
+ 'example',
182
+ 'placeholder',
183
+ '••••••••',
184
+ 'process.env',
185
+ ]);
186
+ function isPlaceholderSecret(value) {
187
+ const trimmed = value.trim();
188
+ const normalized = trimmed.toLowerCase();
189
+ if (!trimmed) {
190
+ return true;
191
+ }
192
+ if (PLACEHOLDER_VALUES.has(normalized)) {
193
+ return true;
194
+ }
195
+ if (/^[*•xX._-]+$/.test(trimmed) || /^[^*]\*{3}$/.test(trimmed)) {
196
+ return true;
197
+ }
198
+ if (/^<[^>]+>$/.test(trimmed) || /^\$\{[^}]+\}$/.test(trimmed)) {
199
+ return true;
200
+ }
201
+ if (normalized.startsWith('process.env.') || normalized.startsWith('import.meta.env.')) {
202
+ return true;
203
+ }
204
+ if (normalized.includes('your-') || normalized.includes('your_') || normalized.includes('changeme')) {
205
+ return true;
206
+ }
207
+ return false;
208
+ }
209
+ function startsWithKnownTokenPrefix(value) {
210
+ return KNOWN_SECRET_PREFIXES.some((prefix) => value.startsWith(prefix));
211
+ }
212
+ function isPublicStripeKey(value) {
213
+ return value.startsWith('pk_live_') || value.startsWith('pk_test_');
214
+ }
215
+ function isHtmlAttributeContext(content, matchIndex) {
216
+ const lookbehindStart = Math.max(0, matchIndex - 120);
217
+ const before = content.slice(lookbehindStart, matchIndex);
218
+ const lastOpenTag = before.lastIndexOf('<');
219
+ const lastCloseTag = before.lastIndexOf('>');
220
+ if (lastOpenTag !== -1 && lastOpenTag > lastCloseTag) {
221
+ return true;
222
+ }
223
+ if (/(?:type|name|id|for|placeholder|autocomplete)\s*=\s*["']?$/i.test(before)) {
224
+ return true;
225
+ }
226
+ return false;
227
+ }
228
+ const TURBOPACK_MODULE_MARKER_RE = /\[project\]\/([A-Za-z0-9_./[\]-]+\.[A-Za-z0-9]+)(?:\s+\[[^\]]+\])?(?:\s+\((?:ecmascript|hmr-entry)\))?/g;
229
+ const WEBPACK_MODULE_MARKER_RE = /(?:\([A-Za-z0-9_-]+\)\/)?\.\.?\/((?:src|app|pages|components)\/[A-Za-z0-9_./[\]-]+\.[A-Za-z0-9]+)/g;
230
+ function isIgnoredBundledModulePath(candidatePath) {
231
+ const lower = candidatePath.toLowerCase();
232
+ return (lower.includes('node_modules') ||
233
+ lower.includes('next/dist') ||
234
+ lower.includes('next_dist'));
235
+ }
236
+ export function resolveBundledSourceFile(content, matchIndex) {
237
+ if (!content || matchIndex <= 0) {
238
+ return null;
239
+ }
240
+ const prefix = content.slice(0, matchIndex);
241
+ let bestIndex = -1;
242
+ let bestPath = null;
243
+ let match;
244
+ TURBOPACK_MODULE_MARKER_RE.lastIndex = 0;
245
+ while ((match = TURBOPACK_MODULE_MARKER_RE.exec(prefix)) !== null) {
246
+ const candidate = match[1]?.trim();
247
+ if (!candidate || isIgnoredBundledModulePath(candidate)) {
248
+ continue;
249
+ }
250
+ if (match.index > bestIndex) {
251
+ bestIndex = match.index;
252
+ bestPath = candidate.replace(/^\/+/, '');
253
+ }
254
+ }
255
+ WEBPACK_MODULE_MARKER_RE.lastIndex = 0;
256
+ while ((match = WEBPACK_MODULE_MARKER_RE.exec(prefix)) !== null) {
257
+ const candidate = match[1]?.trim();
258
+ if (!candidate || isIgnoredBundledModulePath(candidate)) {
259
+ continue;
260
+ }
261
+ if (match.index > bestIndex) {
262
+ bestIndex = match.index;
263
+ bestPath = candidate.replace(/^\/+/, '');
264
+ }
265
+ }
266
+ return bestPath;
267
+ }
268
+ export function scanSecrets(content, route) {
269
+ if (!content) {
270
+ return [];
271
+ }
272
+ const issues = [];
273
+ const seen = new Set();
274
+ const pushIssue = (label, rawSecret, customMasked, matchIndex) => {
275
+ if (isPublicStripeKey(rawSecret)) {
276
+ return;
277
+ }
278
+ const resolvedSource = (matchIndex !== undefined ? resolveBundledSourceFile(content, matchIndex) : null) ?? route;
279
+ const masked = customMasked ?? redactSecret(rawSecret);
280
+ const dedupeKey = `${resolvedSource}::${label}::${masked}`;
281
+ if (seen.has(dedupeKey)) {
282
+ return;
283
+ }
284
+ seen.add(dedupeKey);
285
+ issues.push({
286
+ kind: 'secret_leak',
287
+ severity: 'error',
288
+ route: resolvedSource,
289
+ detail: `Secret leak on ${resolvedSource}: ${label} (${masked})`,
290
+ maskedSnippet: masked,
291
+ });
292
+ };
293
+ let match;
294
+ STRIPE_SECRET_RE.lastIndex = 0;
295
+ while ((match = STRIPE_SECRET_RE.exec(content)) !== null) {
296
+ const token = match[1];
297
+ if (token) {
298
+ pushIssue('Stripe secret key', token, undefined, match.index);
299
+ }
300
+ }
301
+ GOOGLE_API_KEY_RE.lastIndex = 0;
302
+ while ((match = GOOGLE_API_KEY_RE.exec(content)) !== null) {
303
+ const token = match[1];
304
+ if (token) {
305
+ pushIssue('Google API key', token, undefined, match.index);
306
+ }
307
+ }
308
+ PROVIDER_TOKEN_RE.lastIndex = 0;
309
+ while ((match = PROVIDER_TOKEN_RE.exec(content)) !== null) {
310
+ const token = match[1];
311
+ if (!token) {
312
+ continue;
313
+ }
314
+ const label = token.startsWith('ghp_')
315
+ ? 'GitHub token'
316
+ : token.startsWith('sk-proj-')
317
+ ? 'OpenAI API key'
318
+ : 'Anthropic API key';
319
+ pushIssue(label, token, undefined, match.index);
320
+ }
321
+ ENV_SECRET_RE.lastIndex = 0;
322
+ while ((match = ENV_SECRET_RE.exec(content)) !== null) {
323
+ const varName = match[1];
324
+ const secretValue = match[2];
325
+ if (!varName || !secretValue) {
326
+ continue;
327
+ }
328
+ if (varName.startsWith('NEXT_PUBLIC_') || varName.startsWith('VITE_')) {
329
+ continue;
330
+ }
331
+ if (isPlaceholderSecret(secretValue) ||
332
+ isPublicStripeKey(secretValue) ||
333
+ startsWithKnownTokenPrefix(secretValue)) {
334
+ continue;
335
+ }
336
+ pushIssue(varName, secretValue, undefined, match.index);
337
+ }
338
+ DATABASE_URL_RE.lastIndex = 0;
339
+ while ((match = DATABASE_URL_RE.exec(content)) !== null) {
340
+ const varName = match[1];
341
+ const connString = match[2];
342
+ if (!varName || !connString) {
343
+ continue;
344
+ }
345
+ if (isPlaceholderSecret(connString)) {
346
+ continue;
347
+ }
348
+ pushIssue(varName, connString, redactConnectionUri(connString), match.index);
349
+ }
350
+ PASSWORD_FIELD_RE.lastIndex = 0;
351
+ while ((match = PASSWORD_FIELD_RE.exec(content)) !== null) {
352
+ const fieldName = match[1] ?? match[2] ?? 'password';
353
+ const passwordValue = match[3];
354
+ if (!passwordValue || /\s/.test(passwordValue)) {
355
+ continue;
356
+ }
357
+ if (isHtmlAttributeContext(content, match.index)) {
358
+ continue;
359
+ }
360
+ if (isPlaceholderSecret(passwordValue) ||
361
+ isPublicStripeKey(passwordValue) ||
362
+ startsWithKnownTokenPrefix(passwordValue)) {
363
+ continue;
364
+ }
365
+ pushIssue(`Hardcoded ${fieldName.toLowerCase()}`, passwordValue, redactPassword(passwordValue), match.index);
366
+ }
367
+ return issues;
368
+ }
369
+ const PEM_PRIVATE_KEY_RE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g;
370
+ const INLINE_CONN_URI_RE = /\b((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?):\/\/[^:\s"'`\\]+:[^@\s"'`\\]+@[^"'`\\\s]+)/g;
371
+ const EXTRA_TOKENS_RE = /\b(AKIA[0-9A-Z]{16}|glpat-[0-9A-Za-z_-]{20,}|xox[baprs]-[0-9A-Za-z-]{10,}|eyJ[0-9A-Za-z_-]{10,}\.[0-9A-Za-z_-]{10,}\.[0-9A-Za-z_-]{10,})\b/g;
372
+ export function sanitizeSecretsInText(raw) {
373
+ if (!raw) {
374
+ return '';
375
+ }
376
+ let sanitized = raw.replace(PEM_PRIVATE_KEY_RE, '[REDACTED PRIVATE KEY]');
377
+ sanitized = sanitized.replace(STRIPE_SECRET_RE, (m) => redactSecret(m));
378
+ sanitized = sanitized.replace(GOOGLE_API_KEY_RE, (m) => redactSecret(m));
379
+ sanitized = sanitized.replace(PROVIDER_TOKEN_RE, (m) => redactSecret(m));
380
+ sanitized = sanitized.replace(EXTRA_TOKENS_RE, (m) => redactSecret(m));
381
+ sanitized = sanitized.replace(INLINE_CONN_URI_RE, (m) => redactConnectionUri(m));
382
+ sanitized = sanitized.replace(ENV_SECRET_RE, (full, varName, secretValue) => {
383
+ if (varName.startsWith('NEXT_PUBLIC_') ||
384
+ varName.startsWith('VITE_') ||
385
+ isPlaceholderSecret(secretValue) ||
386
+ isPublicStripeKey(secretValue)) {
387
+ return full;
388
+ }
389
+ return full.replace(secretValue, redactSecret(secretValue));
390
+ });
391
+ sanitized = sanitized.replace(PASSWORD_FIELD_RE, (full, qField, bField, passwordValue) => {
392
+ void qField;
393
+ void bField;
394
+ if (!passwordValue ||
395
+ /\s/.test(passwordValue) ||
396
+ isPlaceholderSecret(passwordValue) ||
397
+ isPublicStripeKey(passwordValue)) {
398
+ return full;
399
+ }
400
+ return full.replace(passwordValue, redactPassword(passwordValue));
401
+ });
402
+ return sanitized;
403
+ }
404
+ export function sanitizeErrorSnippet(raw, maxLen = 140) {
405
+ if (!raw) {
406
+ return '';
407
+ }
408
+ let sanitized = sanitizeSecretsInText(raw);
409
+ sanitized = sanitized.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
410
+ sanitized = sanitizeSecretsInText(sanitized);
411
+ if (sanitized.length > maxLen) {
412
+ return `${sanitized.slice(0, maxLen)}...`;
413
+ }
414
+ return sanitized;
415
+ }
416
+ const ANSI_ESCAPE_RE = /\x1b\[[0-9;]*m/g;
417
+ const APP_DIR_SEGMENTS = ['/src/', '/app/', '/pages/', '/components/'];
418
+ const OS_ABSOLUTE_PREFIX_RE = /^(?:[A-Za-z]:\/|\/(?:Users|home|var|tmp|opt|private|mnt|root|etc|Volumes)\/)/i;
419
+ function extractSafeAppPath(rawPath) {
420
+ if (!rawPath) {
421
+ return null;
422
+ }
423
+ const normalized = stripViteTimestampQuery(rawPath.trim().replace(/\\/g, '/'));
424
+ if (!normalized) {
425
+ return null;
426
+ }
427
+ const withLeadingSlash = normalized.startsWith('/') ? normalized : `/${normalized}`;
428
+ for (const seg of APP_DIR_SEGMENTS) {
429
+ const idx = withLeadingSlash.lastIndexOf(seg);
430
+ if (idx !== -1) {
431
+ return withLeadingSlash.slice(idx);
432
+ }
433
+ }
434
+ if (!OS_ABSOLUTE_PREFIX_RE.test(normalized) && !/^[A-Za-z]:/.test(normalized)) {
435
+ if (normalized.startsWith('/') && normalized !== '/') {
436
+ return normalized;
437
+ }
438
+ }
439
+ return null;
440
+ }
441
+ function scrubAbsolutePathsInText(text) {
442
+ if (!text) {
443
+ return '';
444
+ }
445
+ return text.replace(/(?:[A-Za-z]:[\\/]|\/(?:Users|home|var|tmp|opt|private|mnt|root|etc|Volumes)[\\/])[^\s:"'`<>()]+/gi, (match) => {
446
+ const safe = extractSafeAppPath(match);
447
+ if (safe) {
448
+ return safe;
449
+ }
450
+ const norm = stripViteTimestampQuery(match.replace(/\\/g, '/'));
451
+ const parts = norm.split('/').filter(Boolean);
452
+ return parts.length > 0 ? `/${parts[parts.length - 1]}` : norm;
453
+ });
454
+ }
455
+ function extractBalancedJsonObject(source, startBraceIndex) {
456
+ if (startBraceIndex < 0 || startBraceIndex >= source.length || source[startBraceIndex] !== '{') {
457
+ return null;
458
+ }
459
+ let depth = 0;
460
+ let inString = false;
461
+ let escaped = false;
462
+ for (let i = startBraceIndex; i < source.length; i += 1) {
463
+ const ch = source[i];
464
+ if (inString) {
465
+ if (escaped) {
466
+ escaped = false;
467
+ }
468
+ else if (ch === '\\') {
469
+ escaped = true;
470
+ }
471
+ else if (ch === '"') {
472
+ inString = false;
473
+ }
474
+ continue;
475
+ }
476
+ if (ch === '"') {
477
+ inString = true;
478
+ }
479
+ else if (ch === '{') {
480
+ depth += 1;
481
+ }
482
+ else if (ch === '}') {
483
+ depth -= 1;
484
+ if (depth === 0) {
485
+ return source.slice(startBraceIndex, i + 1);
486
+ }
487
+ }
488
+ }
489
+ return null;
490
+ }
491
+ function formatCodeFrame(rawFrame) {
492
+ if (!rawFrame || typeof rawFrame !== 'string') {
493
+ return undefined;
494
+ }
495
+ const cleaned = toAsciiSafe(sanitizeSecretsInText(scrubAbsolutePathsInText(toAsciiSafe(rawFrame.replace(ANSI_ESCAPE_RE, '')))));
496
+ const lines = cleaned.split('\n');
497
+ while (lines.length > 0 && lines[0].trim() === '') {
498
+ lines.shift();
499
+ }
500
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
501
+ lines.pop();
502
+ }
503
+ if (lines.length === 0) {
504
+ return undefined;
505
+ }
506
+ return lines.slice(0, 10).join('\n');
507
+ }
508
+ function parseViteErrorObject(raw) {
509
+ const assignMatch = /\b(?:const|let|var)\s+error\s*=\s*\{/.exec(raw);
510
+ if (assignMatch) {
511
+ const braceIdx = raw.indexOf('{', assignMatch.index);
512
+ const jsonLiteral = extractBalancedJsonObject(raw, braceIdx);
513
+ if (jsonLiteral) {
514
+ try {
515
+ const parsed = JSON.parse(jsonLiteral);
516
+ if (parsed && typeof parsed === 'object') {
517
+ return parsed;
518
+ }
519
+ }
520
+ catch {
521
+ // fall through
522
+ }
523
+ }
524
+ }
525
+ const trimmed = raw.trim();
526
+ if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
527
+ try {
528
+ const parsed = JSON.parse(trimmed);
529
+ if (parsed && typeof parsed === 'object') {
530
+ if (parsed.error && typeof parsed.error === 'object') {
531
+ return parsed.error;
532
+ }
533
+ if (typeof parsed.message === 'string' &&
534
+ ('frame' in parsed || 'loc' in parsed || 'plugin' in parsed || 'id' in parsed)) {
535
+ return parsed;
536
+ }
537
+ }
538
+ }
539
+ catch {
540
+ // not valid JSON
541
+ }
542
+ }
543
+ return null;
544
+ }
545
+ export function extractViteErrorInfo(raw, servedRoute) {
546
+ if (!raw) {
547
+ return null;
548
+ }
549
+ const cleanServedRoute = servedRoute && servedRoute.startsWith('/') && servedRoute !== '/'
550
+ ? stripViteTimestampQuery(servedRoute)
551
+ : null;
552
+ const payload = parseViteErrorObject(raw);
553
+ if (payload && typeof payload.message === 'string' && payload.message.trim().length > 0) {
554
+ const locFile = typeof payload.loc?.file === 'string' ? payload.loc.file : undefined;
555
+ const idFile = typeof payload.id === 'string' ? payload.id : undefined;
556
+ const safeFile = (cleanServedRoute && /\.[A-Za-z0-9]+$/.test(cleanServedRoute) ? cleanServedRoute : null) ??
557
+ extractSafeAppPath(locFile) ??
558
+ extractSafeAppPath(idFile) ??
559
+ cleanServedRoute;
560
+ const line = typeof payload.loc?.line === 'number' ? payload.loc.line : undefined;
561
+ const column = typeof payload.loc?.column === 'number' ? payload.loc.column : undefined;
562
+ const lineColSuffix = line !== undefined ? `:${line}${column !== undefined ? `:${column}` : ''}` : '';
563
+ const safeLocation = safeFile ? `${safeFile}${lineColSuffix}` : '';
564
+ const rawMsgLines = toAsciiSafe(payload.message.replace(ANSI_ESCAPE_RE, '').replace(/\r\n/g, '\n')).split('\n');
565
+ const firstNonEmptyIdx = rawMsgLines.findIndex((line) => line.trim().length > 0);
566
+ const firstLine = firstNonEmptyIdx !== -1 ? rawMsgLines[firstNonEmptyIdx] : '';
567
+ let cleanMessage = toAsciiSafe(sanitizeSecretsInText(scrubAbsolutePathsInText(firstLine)))
568
+ .replace(/\s+/g, ' ')
569
+ .trim();
570
+ if (/^x\s+/.test(cleanMessage)) {
571
+ cleanMessage = cleanMessage.replace(/^x\s+/, '').trim();
572
+ }
573
+ if (safeFile && cleanMessage.startsWith(`${safeFile}:`)) {
574
+ cleanMessage = cleanMessage.slice(safeFile.length + 1).trim();
575
+ }
576
+ else if (safeLocation && cleanMessage.startsWith(`${safeLocation}:`)) {
577
+ cleanMessage = cleanMessage.slice(safeLocation.length + 1).trim();
578
+ }
579
+ const summary = safeLocation && !cleanMessage.startsWith(safeLocation)
580
+ ? `${safeLocation} - ${cleanMessage}`
581
+ : cleanMessage;
582
+ let codeFrame;
583
+ if (typeof payload.frame === 'string' && payload.frame.trim().length > 0) {
584
+ codeFrame = formatCodeFrame(payload.frame);
585
+ }
586
+ else if (firstNonEmptyIdx !== -1 && firstNonEmptyIdx + 1 < rawMsgLines.length) {
587
+ codeFrame = formatCodeFrame(rawMsgLines.slice(firstNonEmptyIdx + 1).join('\n'));
588
+ }
589
+ return {
590
+ summary,
591
+ ...(codeFrame ? { codeFrame } : {}),
592
+ };
593
+ }
594
+ if (raw.includes('Transform failed with') ||
595
+ raw.includes('[plugin:vite:') ||
596
+ raw.includes('Pre-transform error:')) {
597
+ const withoutAnsi = toAsciiSafe(raw.replace(ANSI_ESCAPE_RE, '').replace(/\r\n/g, '\n'));
598
+ const strippedTags = withoutAnsi.replace(/<[^>]*>/g, '\n');
599
+ const rawLines = strippedTags.split('\n');
600
+ const frameLines = [];
601
+ const messageLines = [];
602
+ for (const line of rawLines) {
603
+ const trimmedLine = line.trim();
604
+ if (!trimmedLine) {
605
+ continue;
606
+ }
607
+ if (/^(?:>\s*)?\d+\s*\|/.test(trimmedLine) ||
608
+ /^\|\s*\^/.test(trimmedLine) ||
609
+ /^\s*[+|]-/.test(line) ||
610
+ /^\s*\|/.test(line)) {
611
+ frameLines.push(line);
612
+ }
613
+ else if (trimmedLine.includes('Transform failed with') ||
614
+ trimmedLine.includes('[plugin:vite:') ||
615
+ trimmedLine.includes('Pre-transform error:')) {
616
+ messageLines.push(trimmedLine);
617
+ }
618
+ }
619
+ const baseMsg = messageLines.length > 0 ? messageLines.join(' ') : strippedTags;
620
+ const cleanMessage = toAsciiSafe(sanitizeSecretsInText(scrubAbsolutePathsInText(baseMsg)))
621
+ .replace(/\s+/g, ' ')
622
+ .trim();
623
+ if (!cleanMessage) {
624
+ return null;
625
+ }
626
+ const safeFile = cleanServedRoute ?? extractSafeAppPath(cleanMessage);
627
+ const summary = safeFile && !cleanMessage.includes(safeFile)
628
+ ? `${safeFile} - ${cleanMessage}`
629
+ : cleanMessage;
630
+ const codeFrame = frameLines.length > 0 ? formatCodeFrame(frameLines.join('\n')) : undefined;
631
+ return {
632
+ summary,
633
+ ...(codeFrame ? { codeFrame } : {}),
634
+ };
635
+ }
636
+ return null;
637
+ }
638
+ function cleanNextPagePath(rawPagePath, servedRoute) {
639
+ if (rawPagePath) {
640
+ const normalized = stripViteTimestampQuery(rawPagePath.trim().replace(/\\/g, '/'));
641
+ if (normalized) {
642
+ const withLeadingSlash = normalized.startsWith('/') ? normalized : `/${normalized}`;
643
+ for (const seg of APP_DIR_SEGMENTS) {
644
+ const idx = withLeadingSlash.lastIndexOf(seg);
645
+ if (idx !== -1) {
646
+ return withLeadingSlash.slice(idx + 1);
647
+ }
648
+ }
649
+ if (!OS_ABSOLUTE_PREFIX_RE.test(normalized) && !/^[A-Za-z]:/.test(normalized)) {
650
+ return normalized;
651
+ }
652
+ const parts = normalized.split('/').filter(Boolean);
653
+ if (parts.length >= 2) {
654
+ return parts.slice(-2).join('/');
655
+ }
656
+ }
657
+ }
658
+ if (servedRoute && servedRoute.startsWith('/') && servedRoute !== '/') {
659
+ return stripViteTimestampQuery(servedRoute);
660
+ }
661
+ return null;
662
+ }
663
+ const ERROR_NAME_RE = /(?:^Error$|Error$|Exception$|^Hydration)/i;
664
+ const TYPE_PAGE_THEN_PATH_RE = /"type"\s*:\s*"page"[^}{]{0,120}?"pagePath"\s*:\s*"([^"\r\n]+)"/g;
665
+ const PATH_THEN_TYPE_PAGE_RE = /"pagePath"\s*:\s*"([^"\r\n]+)"[^}{]{0,120}?"type"\s*:\s*"page"/g;
666
+ const ANY_PAGE_PATH_RE = /"pagePath"\s*:\s*"([^"\r\n]+)"/g;
667
+ function selectNextPagePath(normalized) {
668
+ let match;
669
+ let typedPageCandidate;
670
+ TYPE_PAGE_THEN_PATH_RE.lastIndex = 0;
671
+ while ((match = TYPE_PAGE_THEN_PATH_RE.exec(normalized)) !== null) {
672
+ const candidate = match[1]?.trim();
673
+ if (candidate && !candidate.includes('__next_builtin__')) {
674
+ typedPageCandidate = candidate;
675
+ }
676
+ }
677
+ PATH_THEN_TYPE_PAGE_RE.lastIndex = 0;
678
+ while ((match = PATH_THEN_TYPE_PAGE_RE.exec(normalized)) !== null) {
679
+ const candidate = match[1]?.trim();
680
+ if (candidate && !candidate.includes('__next_builtin__')) {
681
+ typedPageCandidate = candidate;
682
+ }
683
+ }
684
+ if (typedPageCandidate) {
685
+ return typedPageCandidate;
686
+ }
687
+ const validPaths = [];
688
+ ANY_PAGE_PATH_RE.lastIndex = 0;
689
+ while ((match = ANY_PAGE_PATH_RE.exec(normalized)) !== null) {
690
+ const candidate = match[1]?.trim();
691
+ if (candidate && !candidate.includes('__next_builtin__')) {
692
+ validPaths.push(candidate);
693
+ }
694
+ }
695
+ if (validPaths.length === 0) {
696
+ return undefined;
697
+ }
698
+ for (let i = validPaths.length - 1; i >= 0; i -= 1) {
699
+ const p = validPaths[i];
700
+ if (/(?:^|[\\/])page\.[A-Za-z0-9]+$/i.test(p)) {
701
+ return p;
702
+ }
703
+ }
704
+ return validPaths[validPaths.length - 1];
705
+ }
706
+ export function extractNextErrorInfo(raw, servedRoute) {
707
+ if (!raw) {
708
+ return null;
709
+ }
710
+ const normalized = raw
711
+ .replace(/\\\\"/g, "'")
712
+ .replace(/\\"/g, '"')
713
+ .replace(/\\\\/g, '/');
714
+ const rawPagePath = selectNextPagePath(normalized);
715
+ const pairRegexes = [
716
+ /"name"\s*:\s*"([^"\r\n]+)"\s*,\s*"message"\s*:\s*"([^"\r\n]+)"/g,
717
+ /"message"\s*:\s*"([^"\r\n]+)"\s*,\s*"name"\s*:\s*"([^"\r\n]+)"/g,
718
+ ];
719
+ for (let rIdx = 0; rIdx < pairRegexes.length; rIdx += 1) {
720
+ const regex = pairRegexes[rIdx];
721
+ regex.lastIndex = 0;
722
+ let match;
723
+ while ((match = regex.exec(normalized)) !== null) {
724
+ const errName = (rIdx === 0 ? match[1] : match[2])?.trim();
725
+ const errMsg = (rIdx === 0 ? match[2] : match[1])?.trim();
726
+ if (!errName || !errMsg) {
727
+ continue;
728
+ }
729
+ const windowStart = Math.max(0, match.index - 300);
730
+ const windowEnd = Math.min(normalized.length, match.index + match[0].length + 300);
731
+ const contextWindow = normalized.slice(windowStart, windowEnd);
732
+ const hasErrorContext = ERROR_NAME_RE.test(errName) ||
733
+ contextWindow.includes('"pagePath"') ||
734
+ contextWindow.includes('"digest"') ||
735
+ contextWindow.includes('"__next');
736
+ if (!hasErrorContext) {
737
+ continue;
738
+ }
739
+ const cleanMsg = toAsciiSafe(sanitizeSecretsInText(scrubAbsolutePathsInText(errMsg))
740
+ .replace(/\s+/g, ' ')
741
+ .trim());
742
+ const targetPath = cleanNextPagePath(rawPagePath, servedRoute);
743
+ const summary = targetPath
744
+ ? `${targetPath} - ${errName}: ${cleanMsg}`
745
+ : `${errName}: ${cleanMsg}`;
746
+ return { summary };
747
+ }
748
+ }
749
+ return null;
750
+ }