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,670 @@
1
+ import { performance } from 'node:perf_hooks';
2
+ import { assertValidTimeout, MAX_BODY_BYTES, DEFAULT_BODY_READ_TIMEOUT_MS, readBoundedTextBody, } from './port-detector.js';
3
+ import { detectMaskedError, extractNextErrorInfo, extractViteErrorInfo, scanSecrets, sanitizeErrorSnippet, stripViteTimestampQuery, } from './security-scan.js';
4
+ export const DEFAULT_SCAN_BUDGET_MS = 2500;
5
+ export const DEFAULT_ROUTE_TIMEOUT_MS = 2000;
6
+ export const DEFAULT_SLOW_ROUTE_MS = 1500;
7
+ export const DEFAULT_MAX_ROUTES = 10;
8
+ export const DEFAULT_MAX_SCRIPTS = 5;
9
+ export const DEFAULT_MAX_CONCURRENCY = 4;
10
+ export const MAX_REDIRECTS = 3;
11
+ const ANCHOR_HREF_RE = /<a\b[^>]*?\bhref\s*=\s*(?:["']([^"']+)["']|([^\s>]+))/gi;
12
+ const SCRIPT_SRC_RE = /<script\b[^>]*?\bsrc\s*=\s*(?:["']([^"']+)["']|([^\s>]+))/gi;
13
+ const STATIC_IMPORT_RE = /(?:import|export)\s+(?:[^"'\r\n;]{1,256}?\s+from\s+)?["']([^"'\r\n]+)["']/g;
14
+ const DYNAMIC_IMPORT_RE = /import\s*\(\s*["']([^"']+)["']\s*\)/g;
15
+ const IGNORED_HREF_PREFIXES = ['#', 'mailto:', 'tel:', 'javascript:', 'data:'];
16
+ const IGNORED_ROUTE_PATH_PREFIXES = ['/_next/', '/@vite/', '/node_modules/'];
17
+ const STATIC_ASSET_EXT_RE = /\.(?:css|js|mjs|cjs|ts|tsx|jsx|png|jpg|jpeg|gif|svg|webp|ico|woff|woff2|ttf|eot|map|pdf|zip|mp4|webm)$/i;
18
+ const IGNORED_MODULE_EXT_RE = /\.(?:css|svg|png|json)$/i;
19
+ const EXCLUDED_SCRIPT_SUBSTRINGS = [
20
+ '/node_modules/',
21
+ 'node_modules_',
22
+ 'next_dist',
23
+ '/@vite/',
24
+ '/@react-refresh',
25
+ 'webpack',
26
+ 'main-app',
27
+ 'polyfill',
28
+ 'react-refresh',
29
+ 'framework-',
30
+ 'turbopack',
31
+ '%5bturbopack%5d',
32
+ '_buildmanifest',
33
+ '_ssgmanifest',
34
+ ];
35
+ const PRIORITY_SCRIPT_SUBSTRINGS = [
36
+ '/src/',
37
+ 'app/page',
38
+ 'app/layout',
39
+ '/_next/static/chunks/app/',
40
+ '/_next/static/chunks/pages/',
41
+ '/pages/',
42
+ ];
43
+ const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);
44
+ const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']);
45
+ function isSameLocalOrigin(candidate, base) {
46
+ if (candidate.origin === base.origin) {
47
+ return true;
48
+ }
49
+ return (candidate.protocol === base.protocol &&
50
+ candidate.port === base.port &&
51
+ LOOPBACK_HOSTNAMES.has(candidate.hostname) &&
52
+ LOOPBACK_HOSTNAMES.has(base.hostname));
53
+ }
54
+ export function isExcludedFrameworkScript(pathOrUrl) {
55
+ const lower = pathOrUrl.toLowerCase();
56
+ return EXCLUDED_SCRIPT_SUBSTRINGS.some((token) => lower.includes(token));
57
+ }
58
+ export function getScriptPriority(pathOrUrl) {
59
+ for (const token of PRIORITY_SCRIPT_SUBSTRINGS) {
60
+ if (pathOrUrl.includes(token)) {
61
+ return 1;
62
+ }
63
+ }
64
+ return 2;
65
+ }
66
+ export function extractInternalLinks(html, baseOrigin, maxSubRoutes) {
67
+ if (!html || maxSubRoutes <= 0) {
68
+ return [];
69
+ }
70
+ let baseUrl;
71
+ try {
72
+ baseUrl = new URL(baseOrigin);
73
+ }
74
+ catch {
75
+ return [];
76
+ }
77
+ const results = [];
78
+ const seen = new Set(['/']);
79
+ ANCHOR_HREF_RE.lastIndex = 0;
80
+ let match;
81
+ while ((match = ANCHOR_HREF_RE.exec(html)) !== null) {
82
+ if (results.length >= maxSubRoutes) {
83
+ break;
84
+ }
85
+ const rawHref = (match[1] ?? match[2] ?? '').trim();
86
+ if (!rawHref) {
87
+ continue;
88
+ }
89
+ const lowerHref = rawHref.toLowerCase();
90
+ if (IGNORED_HREF_PREFIXES.some((prefix) => lowerHref.startsWith(prefix))) {
91
+ continue;
92
+ }
93
+ let resolved;
94
+ try {
95
+ resolved = new URL(rawHref, baseUrl);
96
+ }
97
+ catch {
98
+ continue;
99
+ }
100
+ if (!isSameLocalOrigin(resolved, baseUrl)) {
101
+ continue;
102
+ }
103
+ const pathname = resolved.pathname;
104
+ if (IGNORED_ROUTE_PATH_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {
105
+ continue;
106
+ }
107
+ if (STATIC_ASSET_EXT_RE.test(pathname)) {
108
+ continue;
109
+ }
110
+ const normalized = `${pathname}${resolved.search}`;
111
+ if (seen.has(normalized)) {
112
+ continue;
113
+ }
114
+ seen.add(normalized);
115
+ results.push(normalized);
116
+ }
117
+ return results;
118
+ }
119
+ export function extractCandidateScripts(html, baseOrigin, maxScripts) {
120
+ if (!html || maxScripts <= 0) {
121
+ return [];
122
+ }
123
+ let baseUrl;
124
+ try {
125
+ baseUrl = new URL(baseOrigin);
126
+ }
127
+ catch {
128
+ return [];
129
+ }
130
+ const candidates = [];
131
+ const seen = new Set();
132
+ SCRIPT_SRC_RE.lastIndex = 0;
133
+ let match;
134
+ let idx = 0;
135
+ while ((match = SCRIPT_SRC_RE.exec(html)) !== null) {
136
+ const rawSrc = (match[1] ?? match[2] ?? '').trim();
137
+ if (!rawSrc) {
138
+ continue;
139
+ }
140
+ let resolved;
141
+ try {
142
+ resolved = new URL(rawSrc, baseUrl);
143
+ }
144
+ catch {
145
+ continue;
146
+ }
147
+ if (!isSameLocalOrigin(resolved, baseUrl)) {
148
+ continue;
149
+ }
150
+ const normalized = stripViteTimestampQuery(`${resolved.pathname}${resolved.search}`);
151
+ if (seen.has(normalized)) {
152
+ continue;
153
+ }
154
+ if (isExcludedFrameworkScript(normalized)) {
155
+ continue;
156
+ }
157
+ seen.add(normalized);
158
+ candidates.push({
159
+ path: normalized,
160
+ priority: getScriptPriority(normalized),
161
+ index: idx++,
162
+ });
163
+ }
164
+ candidates.sort((a, b) => {
165
+ if (a.priority !== b.priority) {
166
+ return a.priority - b.priority;
167
+ }
168
+ return a.index - b.index;
169
+ });
170
+ return candidates.slice(0, maxScripts).map((c) => c.path);
171
+ }
172
+ export function selectScriptsToFetch(input, baseOriginOrMaxScripts = 'http://localhost:3000', maxScripts = DEFAULT_MAX_SCRIPTS) {
173
+ if (typeof input === 'string') {
174
+ const baseOrigin = typeof baseOriginOrMaxScripts === 'string'
175
+ ? baseOriginOrMaxScripts
176
+ : 'http://localhost:3000';
177
+ const limit = typeof baseOriginOrMaxScripts === 'number'
178
+ ? baseOriginOrMaxScripts
179
+ : maxScripts;
180
+ return extractCandidateScripts(input, baseOrigin, limit);
181
+ }
182
+ const limit = typeof baseOriginOrMaxScripts === 'number'
183
+ ? baseOriginOrMaxScripts
184
+ : maxScripts;
185
+ if (limit <= 0) {
186
+ return [];
187
+ }
188
+ const candidates = [];
189
+ const seen = new Set();
190
+ let idx = 0;
191
+ for (const raw of input) {
192
+ const trimmed = stripViteTimestampQuery(raw.trim());
193
+ if (!trimmed || seen.has(trimmed) || isExcludedFrameworkScript(trimmed)) {
194
+ continue;
195
+ }
196
+ seen.add(trimmed);
197
+ candidates.push({
198
+ path: trimmed,
199
+ priority: getScriptPriority(trimmed),
200
+ index: idx++,
201
+ });
202
+ }
203
+ candidates.sort((a, b) => {
204
+ if (a.priority !== b.priority) {
205
+ return a.priority - b.priority;
206
+ }
207
+ return a.index - b.index;
208
+ });
209
+ return candidates.slice(0, limit).map((c) => c.path);
210
+ }
211
+ export function extractModuleImports(jsContent, scriptPath, baseOrigin) {
212
+ if (!jsContent) {
213
+ return [];
214
+ }
215
+ let baseUrl;
216
+ let scriptUrl;
217
+ try {
218
+ baseUrl = new URL(baseOrigin);
219
+ scriptUrl = new URL(scriptPath, baseUrl);
220
+ }
221
+ catch {
222
+ return [];
223
+ }
224
+ const specifiers = [];
225
+ let match;
226
+ STATIC_IMPORT_RE.lastIndex = 0;
227
+ while ((match = STATIC_IMPORT_RE.exec(jsContent)) !== null) {
228
+ if (match[1]) {
229
+ specifiers.push(match[1].trim());
230
+ }
231
+ }
232
+ DYNAMIC_IMPORT_RE.lastIndex = 0;
233
+ while ((match = DYNAMIC_IMPORT_RE.exec(jsContent)) !== null) {
234
+ if (match[1]) {
235
+ specifiers.push(match[1].trim());
236
+ }
237
+ }
238
+ const results = [];
239
+ const seen = new Set();
240
+ for (const spec of specifiers) {
241
+ if (!spec.startsWith('/src/') &&
242
+ !spec.startsWith('./') &&
243
+ !spec.startsWith('../')) {
244
+ continue;
245
+ }
246
+ let resolved;
247
+ try {
248
+ resolved = new URL(spec, scriptUrl);
249
+ }
250
+ catch {
251
+ continue;
252
+ }
253
+ if (!isSameLocalOrigin(resolved, baseUrl)) {
254
+ continue;
255
+ }
256
+ if (IGNORED_MODULE_EXT_RE.test(resolved.pathname)) {
257
+ continue;
258
+ }
259
+ const normalized = stripViteTimestampQuery(`${resolved.pathname}${resolved.search}`);
260
+ if (isExcludedFrameworkScript(normalized) || seen.has(normalized)) {
261
+ continue;
262
+ }
263
+ seen.add(normalized);
264
+ results.push(normalized);
265
+ }
266
+ return results;
267
+ }
268
+ export async function fetchSameOriginHop(baseUrl, initialPath, signal, routeTimeoutMs, followRedirects = true) {
269
+ const base = new URL(baseUrl);
270
+ let currentUrl = new URL(initialPath, base);
271
+ let hops = 0;
272
+ while (true) {
273
+ const hopSignal = AbortSignal.any([signal, AbortSignal.timeout(routeTimeoutMs)]);
274
+ const hopStart = performance.now();
275
+ const res = await fetch(currentUrl.toString(), {
276
+ method: 'GET',
277
+ redirect: 'manual',
278
+ signal: hopSignal,
279
+ });
280
+ const headersElapsedMs = Math.max(0, Math.round(performance.now() - hopStart));
281
+ const statusCode = res.status;
282
+ const contentType = res.headers.get('content-type') ?? '';
283
+ const location = res.headers.get('location') ?? undefined;
284
+ if (followRedirects &&
285
+ REDIRECT_STATUS_CODES.has(statusCode) &&
286
+ location !== undefined) {
287
+ let nextUrl = null;
288
+ try {
289
+ nextUrl = new URL(location, currentUrl);
290
+ }
291
+ catch {
292
+ nextUrl = null;
293
+ }
294
+ if (nextUrl && isSameLocalOrigin(nextUrl, base)) {
295
+ await res.body?.cancel().catch(() => { });
296
+ if (hops >= MAX_REDIRECTS) {
297
+ throw new Error(`Exceeded maximum redirects (${MAX_REDIRECTS}) on ${initialPath}`);
298
+ }
299
+ currentUrl = new URL(`${nextUrl.pathname}${nextUrl.search}`, base);
300
+ hops += 1;
301
+ continue;
302
+ }
303
+ }
304
+ const { body, truncated } = await readBoundedTextBody(res, MAX_BODY_BYTES, DEFAULT_BODY_READ_TIMEOUT_MS);
305
+ return {
306
+ path: initialPath,
307
+ statusCode,
308
+ contentType,
309
+ location,
310
+ body,
311
+ headersElapsedMs,
312
+ truncated,
313
+ };
314
+ }
315
+ }
316
+ function isHtmlLike(contentType, body) {
317
+ const lower = contentType.toLowerCase();
318
+ if (lower.includes('text/html') || lower.includes('application/xhtml+xml')) {
319
+ return true;
320
+ }
321
+ const trimmed = body.trimStart();
322
+ return (trimmed.startsWith('<!DOCTYPE') ||
323
+ trimmed.startsWith('<!doctype') ||
324
+ trimmed.startsWith('<html') ||
325
+ trimmed.startsWith('<HTML') ||
326
+ trimmed.startsWith('<'));
327
+ }
328
+ export async function runSanityScan(host, port, rootResponse, options = {}) {
329
+ const scanBudgetMs = options.scanBudgetMs ?? DEFAULT_SCAN_BUDGET_MS;
330
+ const routeTimeoutMs = options.routeTimeoutMs ?? DEFAULT_ROUTE_TIMEOUT_MS;
331
+ const slowRouteMs = options.slowRouteMs ?? DEFAULT_SLOW_ROUTE_MS;
332
+ const maxRoutes = options.maxRoutes ?? DEFAULT_MAX_ROUTES;
333
+ const maxScripts = options.maxScripts ?? DEFAULT_MAX_SCRIPTS;
334
+ const maxConcurrency = options.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY;
335
+ assertValidTimeout(scanBudgetMs, 'scanBudgetMs');
336
+ assertValidTimeout(routeTimeoutMs, 'routeTimeoutMs');
337
+ assertValidTimeout(slowRouteMs, 'slowRouteMs');
338
+ if (!Number.isInteger(maxRoutes) || maxRoutes < 1) {
339
+ throw new RangeError(`Invalid maxRoutes "${maxRoutes}": expected integer >= 1`);
340
+ }
341
+ if (!Number.isInteger(maxScripts) || maxScripts < 0) {
342
+ throw new RangeError(`Invalid maxScripts "${maxScripts}": expected integer >= 0`);
343
+ }
344
+ if (!Number.isInteger(maxConcurrency) || maxConcurrency < 1) {
345
+ throw new RangeError(`Invalid maxConcurrency "${maxConcurrency}": expected integer >= 1`);
346
+ }
347
+ const fetchHost = host === '::1' ? '[::1]' : '127.0.0.1';
348
+ const baseOrigin = `http://${fetchHost}:${port}`;
349
+ const baseUrlObj = new URL(baseOrigin);
350
+ const routes = [];
351
+ const scannedScripts = [];
352
+ const skippedRoutes = [];
353
+ const issues = [];
354
+ const budgetController = new AbortController();
355
+ const budgetTimer = setTimeout(() => {
356
+ budgetController.abort();
357
+ }, scanBudgetMs);
358
+ try {
359
+ let finalRoot = rootResponse;
360
+ if (REDIRECT_STATUS_CODES.has(rootResponse.statusCode) &&
361
+ rootResponse.location !== undefined) {
362
+ let redirectTarget = null;
363
+ try {
364
+ redirectTarget = new URL(rootResponse.location, baseUrlObj);
365
+ }
366
+ catch {
367
+ redirectTarget = null;
368
+ }
369
+ if (redirectTarget && isSameLocalOrigin(redirectTarget, baseUrlObj)) {
370
+ const nextPath = `${redirectTarget.pathname}${redirectTarget.search}`;
371
+ try {
372
+ const followed = await fetchSameOriginHop(baseOrigin, nextPath, budgetController.signal, routeTimeoutMs, true);
373
+ finalRoot = {
374
+ ...followed,
375
+ path: '/',
376
+ };
377
+ }
378
+ catch (err) {
379
+ if (!budgetController.signal.aborted) {
380
+ const isTimeout = err instanceof Error &&
381
+ (err.name === 'TimeoutError' || err.name === 'AbortError');
382
+ if (isTimeout) {
383
+ issues.push({
384
+ kind: 'slow_route',
385
+ severity: 'warning',
386
+ route: '/',
387
+ elapsedMs: routeTimeoutMs,
388
+ detail: `slow route / (did not respond within ${routeTimeoutMs}ms - may be dev server compilation; re-run to confirm)`,
389
+ });
390
+ }
391
+ else {
392
+ issues.push({
393
+ kind: 'http_error',
394
+ severity: 'error',
395
+ route: '/',
396
+ detail: 'Connection failed on route /',
397
+ });
398
+ }
399
+ }
400
+ }
401
+ }
402
+ }
403
+ routes.push({
404
+ path: '/',
405
+ statusCode: finalRoot.statusCode,
406
+ contentType: finalRoot.contentType,
407
+ headersElapsedMs: finalRoot.headersElapsedMs,
408
+ truncated: finalRoot.truncated,
409
+ });
410
+ if (finalRoot.statusCode >= 400) {
411
+ const structured = extractNextErrorInfo(finalRoot.body, '/') ??
412
+ extractViteErrorInfo(finalRoot.body, '/');
413
+ if (structured) {
414
+ issues.push({
415
+ kind: 'http_error',
416
+ severity: 'error',
417
+ route: '/',
418
+ statusCode: finalRoot.statusCode,
419
+ detail: `HTTP ${finalRoot.statusCode} on route / (${structured.summary})`,
420
+ maskedSnippet: structured.summary,
421
+ ...(structured.codeFrame ? { codeFrame: structured.codeFrame } : {}),
422
+ });
423
+ }
424
+ else {
425
+ const masked = isHtmlLike(finalRoot.contentType, finalRoot.body)
426
+ ? detectMaskedError(finalRoot.body, '/')
427
+ : [];
428
+ const snippet = masked[0]?.maskedSnippet;
429
+ const codeFrame = masked[0]?.codeFrame;
430
+ issues.push({
431
+ kind: 'http_error',
432
+ severity: 'error',
433
+ route: '/',
434
+ statusCode: finalRoot.statusCode,
435
+ detail: snippet
436
+ ? `HTTP ${finalRoot.statusCode} on route / (${snippet})`
437
+ : `HTTP ${finalRoot.statusCode} on route /`,
438
+ ...(snippet ? { maskedSnippet: snippet } : {}),
439
+ ...(codeFrame ? { codeFrame } : {}),
440
+ });
441
+ }
442
+ }
443
+ else if (isHtmlLike(finalRoot.contentType, finalRoot.body)) {
444
+ issues.push(...detectMaskedError(finalRoot.body, '/'));
445
+ }
446
+ if (finalRoot.body.length > 0) {
447
+ issues.push(...scanSecrets(finalRoot.body, '/'));
448
+ }
449
+ const candidateScripts = extractCandidateScripts(finalRoot.body, baseOrigin, maxScripts);
450
+ const subRoutes = extractInternalLinks(finalRoot.body, baseOrigin, Math.max(0, maxRoutes - 1));
451
+ const scheduledScripts = new Set(candidateScripts);
452
+ const subRouteOutcomes = new Map();
453
+ const taskQueue = [];
454
+ let activeCount = 0;
455
+ let resolvePool;
456
+ const poolDone = new Promise((resolve) => {
457
+ resolvePool = resolve;
458
+ });
459
+ const pump = () => {
460
+ if (taskQueue.length === 0 && activeCount === 0) {
461
+ resolvePool();
462
+ return;
463
+ }
464
+ while (activeCount < maxConcurrency && taskQueue.length > 0) {
465
+ const task = taskQueue.shift();
466
+ activeCount += 1;
467
+ task()
468
+ .catch(() => { })
469
+ .finally(() => {
470
+ activeCount -= 1;
471
+ pump();
472
+ });
473
+ }
474
+ };
475
+ const enqueueScriptTask = (scriptPath) => {
476
+ const cleanScriptPath = stripViteTimestampQuery(scriptPath);
477
+ taskQueue.push(async () => {
478
+ if (budgetController.signal.aborted) {
479
+ return;
480
+ }
481
+ try {
482
+ const snap = await fetchSameOriginHop(baseOrigin, scriptPath, budgetController.signal, routeTimeoutMs, true);
483
+ scannedScripts.push(cleanScriptPath);
484
+ if (snap.statusCode >= 400) {
485
+ const structured = extractViteErrorInfo(snap.body, cleanScriptPath);
486
+ const snippet = structured ? structured.summary : sanitizeErrorSnippet(snap.body);
487
+ let detail;
488
+ if (snippet && snippet.startsWith(cleanScriptPath)) {
489
+ detail = `HTTP ${snap.statusCode} on script ${snippet}`;
490
+ }
491
+ else if (snippet) {
492
+ detail = `HTTP ${snap.statusCode} on script ${cleanScriptPath}: ${snippet}`;
493
+ }
494
+ else {
495
+ detail = `HTTP ${snap.statusCode} on script ${cleanScriptPath}`;
496
+ }
497
+ issues.push({
498
+ kind: 'http_error',
499
+ severity: 'error',
500
+ route: cleanScriptPath,
501
+ statusCode: snap.statusCode,
502
+ detail,
503
+ ...(snippet ? { maskedSnippet: snippet } : {}),
504
+ ...(structured?.codeFrame ? { codeFrame: structured.codeFrame } : {}),
505
+ });
506
+ }
507
+ if (snap.body.length > 0) {
508
+ issues.push(...scanSecrets(snap.body, cleanScriptPath));
509
+ }
510
+ if (!budgetController.signal.aborted &&
511
+ snap.statusCode >= 200 &&
512
+ snap.statusCode < 300 &&
513
+ scheduledScripts.size < maxScripts &&
514
+ cleanScriptPath.includes('/src/') &&
515
+ snap.body.length > 0) {
516
+ const imported = extractModuleImports(snap.body, cleanScriptPath, baseOrigin);
517
+ for (const imp of imported) {
518
+ if (scheduledScripts.size >= maxScripts) {
519
+ break;
520
+ }
521
+ if (!scheduledScripts.has(imp)) {
522
+ scheduledScripts.add(imp);
523
+ enqueueScriptTask(imp);
524
+ pump();
525
+ }
526
+ }
527
+ }
528
+ }
529
+ catch (err) {
530
+ if (budgetController.signal.aborted) {
531
+ return;
532
+ }
533
+ const isTimeout = err instanceof Error &&
534
+ (err.name === 'TimeoutError' || err.name === 'AbortError');
535
+ if (!isTimeout) {
536
+ issues.push({
537
+ kind: 'http_error',
538
+ severity: 'error',
539
+ route: cleanScriptPath,
540
+ detail: `Request failed on script ${cleanScriptPath}`,
541
+ });
542
+ }
543
+ }
544
+ });
545
+ };
546
+ const enqueueSubRouteTask = (routePath) => {
547
+ taskQueue.push(async () => {
548
+ if (budgetController.signal.aborted) {
549
+ subRouteOutcomes.set(routePath, { path: routePath, skipped: true });
550
+ return;
551
+ }
552
+ try {
553
+ const snap = await fetchSameOriginHop(baseOrigin, routePath, budgetController.signal, routeTimeoutMs, true);
554
+ subRouteOutcomes.set(routePath, {
555
+ path: routePath,
556
+ statusCode: snap.statusCode,
557
+ contentType: snap.contentType,
558
+ headersElapsedMs: snap.headersElapsedMs,
559
+ truncated: snap.truncated,
560
+ });
561
+ if (snap.statusCode >= 400) {
562
+ const structured = extractNextErrorInfo(snap.body, routePath) ??
563
+ extractViteErrorInfo(snap.body, routePath);
564
+ if (structured) {
565
+ issues.push({
566
+ kind: 'http_error',
567
+ severity: 'error',
568
+ route: routePath,
569
+ statusCode: snap.statusCode,
570
+ detail: `HTTP ${snap.statusCode} on route ${routePath} (${structured.summary})`,
571
+ maskedSnippet: structured.summary,
572
+ ...(structured.codeFrame ? { codeFrame: structured.codeFrame } : {}),
573
+ });
574
+ }
575
+ else {
576
+ const masked = isHtmlLike(snap.contentType, snap.body)
577
+ ? detectMaskedError(snap.body, routePath)
578
+ : [];
579
+ const snippet = masked[0]?.maskedSnippet;
580
+ const codeFrame = masked[0]?.codeFrame;
581
+ issues.push({
582
+ kind: 'http_error',
583
+ severity: 'error',
584
+ route: routePath,
585
+ statusCode: snap.statusCode,
586
+ detail: snippet
587
+ ? `HTTP ${snap.statusCode} on route ${routePath} (${snippet})`
588
+ : `HTTP ${snap.statusCode} on route ${routePath}`,
589
+ ...(snippet ? { maskedSnippet: snippet } : {}),
590
+ ...(codeFrame ? { codeFrame } : {}),
591
+ });
592
+ }
593
+ }
594
+ else if (isHtmlLike(snap.contentType, snap.body)) {
595
+ issues.push(...detectMaskedError(snap.body, routePath));
596
+ }
597
+ if (snap.headersElapsedMs > slowRouteMs) {
598
+ issues.push({
599
+ kind: 'slow_route',
600
+ severity: 'warning',
601
+ route: routePath,
602
+ elapsedMs: snap.headersElapsedMs,
603
+ detail: `slow route ${routePath} (${snap.headersElapsedMs}ms - may be dev server compilation; re-run to confirm)`,
604
+ });
605
+ }
606
+ if (snap.body.length > 0) {
607
+ issues.push(...scanSecrets(snap.body, routePath));
608
+ }
609
+ }
610
+ catch (err) {
611
+ if (budgetController.signal.aborted) {
612
+ subRouteOutcomes.set(routePath, { path: routePath, skipped: true });
613
+ }
614
+ else {
615
+ const isTimeout = err instanceof Error &&
616
+ (err.name === 'TimeoutError' || err.name === 'AbortError');
617
+ if (isTimeout) {
618
+ subRouteOutcomes.set(routePath, {
619
+ path: routePath,
620
+ headersElapsedMs: routeTimeoutMs,
621
+ });
622
+ issues.push({
623
+ kind: 'slow_route',
624
+ severity: 'warning',
625
+ route: routePath,
626
+ elapsedMs: routeTimeoutMs,
627
+ detail: `slow route ${routePath} (did not respond within ${routeTimeoutMs}ms - may be dev server compilation; re-run to confirm)`,
628
+ });
629
+ }
630
+ else {
631
+ subRouteOutcomes.set(routePath, { path: routePath });
632
+ issues.push({
633
+ kind: 'http_error',
634
+ severity: 'error',
635
+ route: routePath,
636
+ detail: `Connection failed on route ${routePath}`,
637
+ });
638
+ }
639
+ }
640
+ }
641
+ });
642
+ };
643
+ for (const scriptPath of candidateScripts) {
644
+ enqueueScriptTask(scriptPath);
645
+ }
646
+ for (const routePath of subRoutes) {
647
+ enqueueSubRouteTask(routePath);
648
+ }
649
+ pump();
650
+ await poolDone;
651
+ for (const routePath of subRoutes) {
652
+ const item = subRouteOutcomes.get(routePath);
653
+ if (item) {
654
+ routes.push(item);
655
+ if (item.skipped) {
656
+ skippedRoutes.push(routePath);
657
+ }
658
+ }
659
+ }
660
+ }
661
+ finally {
662
+ clearTimeout(budgetTimer);
663
+ }
664
+ return {
665
+ routes,
666
+ scannedScripts,
667
+ skippedRoutes,
668
+ issues,
669
+ };
670
+ }
@@ -0,0 +1,29 @@
1
+ export type SanitySeverity = 'error' | 'warning';
2
+ export type SanityIssueKind = 'http_error' | 'masked_error' | 'secret_leak' | 'slow_route';
3
+ export interface SanityIssue {
4
+ kind: SanityIssueKind;
5
+ severity: SanitySeverity;
6
+ route: string;
7
+ detail: string;
8
+ maskedSnippet?: string;
9
+ codeFrame?: string;
10
+ statusCode?: number;
11
+ elapsedMs?: number;
12
+ }
13
+ export declare function redactSecret(secret: string): string;
14
+ export declare function redactPassword(raw: string): string;
15
+ export declare function redactConnectionUri(uri: string): string;
16
+ export declare function stripViteTimestampQuery(pathOrUrl: string): string;
17
+ export declare function detectMaskedError(html: string, route: string): SanityIssue[];
18
+ export declare function resolveBundledSourceFile(content: string, matchIndex: number): string | null;
19
+ export declare function scanSecrets(content: string, route: string): SanityIssue[];
20
+ export declare function sanitizeSecretsInText(raw: string): string;
21
+ export declare function sanitizeErrorSnippet(raw: string, maxLen?: number): string;
22
+ export declare function extractViteErrorInfo(raw: string, servedRoute?: string): {
23
+ summary: string;
24
+ codeFrame?: string;
25
+ } | null;
26
+ export declare function extractNextErrorInfo(raw: string, servedRoute?: string): {
27
+ summary: string;
28
+ codeFrame?: string;
29
+ } | null;