diff --git a/.changeset/browser-failed-import-context.md b/.changeset/browser-failed-import-context.md new file mode 100644 index 00000000..b26125ce --- /dev/null +++ b/.changeset/browser-failed-import-context.md @@ -0,0 +1,5 @@ +--- +'@bugsee/browser': patch +--- + +A failed dynamic `import()` (and other errors a browser reports without a stack) no longer produces a report titled "TypeError at Unknown location". Safari rejects a failed module load with a bare `Importing a module script failed.` that has no stack and no URL; Chrome and Firefox name the module in the message but also ship no frames. The report now carries one frame naming the failed module, taken from the message where the browser gives it and otherwise inferred from the Resource Timing entry of the failed script fetch (same-origin only, flagged as inferred; one fixed `` frame when nothing identifies it, so those occurrences still group). The report description adds the page route (query string dropped), online state and the scripts that had just loaded. JavaScriptCore's own `sourceURL`/`line`/`column` on a stackless SyntaxError or evaluation error becomes a frame as well. A real stack, and the async-origin call site of a platform rejection, always take precedence. diff --git a/packages/browser/src/detection-providers.test.ts b/packages/browser/src/detection-providers.test.ts index 4b5f9329..e64a70fa 100644 --- a/packages/browser/src/detection-providers.test.ts +++ b/packages/browser/src/detection-providers.test.ts @@ -599,3 +599,37 @@ describe('async origin (a stackless platform rejection reported WITH its call si recorder.stop(); }); }); + +describe('a failed dynamic import', () => { + // Safari (and Chrome, for this error) ships no stack for it; Node would give the test's own. + const stackless = (message: string): TypeError => { + const error = new TypeError(message); + error.stack = undefined; + return error; + }; + + function reportOf(reason: unknown) { + const w = fakeWindow(); + const requests = started(createUnhandledRejectionProvider(w.win)); + w.emit('unhandledrejection', { reason }); + return requests[0]?.report as unknown as { description?: string; crash?: CrashJson }; + } + + it('names the module, and carries a frame, when the message names it (Chrome)', () => { + const report = reportOf( + stackless( + 'Failed to fetch dynamically imported module: https://app.example.com/chunk-LAZY.js', + ), + ); + expect(report.crash?.exception.frames).toHaveLength(1); + expect(report.crash?.exception.frames[0]?.trace).toContain('chunk-LAZY.js'); + expect(report.description).toContain('Failed module: https://app.example.com/chunk-LAZY.js'); + }); + + it('still gets one fixed frame when Safari names nothing, so occurrences group', () => { + const report = reportOf(stackless('Importing a module script failed.')); + expect(report.crash?.exception.frames).toHaveLength(1); + expect(report.crash?.exception.frames[0]?.trace).toContain(''); + expect(report.description).toContain('Failed module: unknown'); + }); +}); diff --git a/packages/browser/src/detection-providers.ts b/packages/browser/src/detection-providers.ts index 0301626d..bd4ddc47 100644 --- a/packages/browser/src/detection-providers.ts +++ b/packages/browser/src/detection-providers.ts @@ -3,6 +3,7 @@ import type { CrashJson, DetectionProvider, StackFrame } from '@bugsee/core'; import { applyDebugIds, buildCrashJson, + composeFrameEnrichers, DetectionProviderBase, describeThrown, formatStack, @@ -11,6 +12,11 @@ import { } from '@bugsee/core'; import { BugseeOption } from '@bugsee/protocol'; import { parseStack } from './stack'; +import { + createStacklessFrameEnricher, + describeStacklessContext, + stacklessFrames, +} from './stackless-error-context'; // Browser crash/error detection providers (globalErrorInterceptor on the browser, // mechanisms). Each subscribes to a window event and submits a ReportingRequest via @@ -42,7 +48,8 @@ function describeError( // No frames of its own (no stack, or only the `Name: message` header Chromium gives an async DOMException): an async platform // rejection (`video.play()`). Where the call was made, and on what, if the recorder saw it. const located = describeOrigin(value, origins); - return located === undefined ? { summary } : { summary, description: located }; + // Still nothing: a failed dynamic import, or an engine that reports a location instead of a stack (see stackless-error-context). + return withStacklessContext(value, summary, located); } // A value that is not an `Error` here may still be a platform rejection (a DOMException from another realm is not `instanceof Error`): // the recorder keys by reason, so it answers for an object too. @@ -55,6 +62,20 @@ function describeError( : { summary: describeThrown(value), description: located }; } +function withStacklessContext( + value: unknown, + summary: string, + located: string | undefined, +): { summary: string; description?: string } { + const frames = stacklessFrames(value); + const parts = [ + located, + frames.length > 0 ? formatStack(frames).trimEnd() : undefined, + describeStacklessContext(value), + ].filter((part) => part !== undefined && part !== ''); + return parts.length === 0 ? { summary } : { summary, description: parts.join('\n') }; +} + function describeOrigin(value: object, origins?: AsyncOriginReporting): string | undefined { if (origins === undefined) { return undefined; @@ -72,10 +93,15 @@ function describeOrigin(value: object, origins?: AsyncOriginReporting): string | /** Structured crash.json from a thrown value — `handled: false` (uncaught). A non-Error gets a * synthetic exception rather than nothing. Uses the browser's multi-engine stack parser. */ function crashOf(value: unknown, origins?: AsyncOriginReporting): CrashJson { + // The async-origin enricher first (a platform rejection's call site), then the stackless context for what is still empty. + const enrichFrames = composeFrameEnrichers([ + ...(origins !== undefined ? [origins.enrichFrames] : []), + createStacklessFrameEnricher(), + ]); return buildCrashJson(value, { parseStack, handled: false, - ...(origins !== undefined ? { enrichFrames: origins.enrichFrames } : {}), + ...(enrichFrames !== undefined ? { enrichFrames } : {}), }); } diff --git a/packages/browser/src/stackless-error-context.test.ts b/packages/browser/src/stackless-error-context.test.ts new file mode 100644 index 00000000..3e4c0e66 --- /dev/null +++ b/packages/browser/src/stackless-error-context.test.ts @@ -0,0 +1,314 @@ +import { describe, expect, it } from 'vitest'; +import { + createStacklessFrameEnricher, + describeStacklessContext, + detectModuleLoadFailure, + engineLocationFrame, + IMPORT_FRAME_FUNCTION, + type StacklessEnv, + stacklessFrames, + UNKNOWN_MODULE, +} from './stackless-error-context'; + +const ORIGIN = 'https://app.example.com'; + +function entry(name: string, overrides: Record = {}): Record { + return { + name, + initiatorType: 'script', + startTime: 0, + responseEnd: 900, + transferSize: 500, + encodedBodySize: 300, + decodedBodySize: 900, + ...overrides, + }; +} + +const FAILED = { transferSize: 0, encodedBodySize: 0, decodedBodySize: 0 }; + +function env(entries: Record[], extra: Partial = {}): StacklessEnv { + return { + performance: { getEntriesByType: () => entries, now: () => 1000 }, + location: { + href: `${ORIGIN}/#/apps/9?x=1`, + origin: ORIGIN, + pathname: '/', + hash: '#/apps/9?x=1', + }, + navigator: { onLine: true }, + ...extra, + }; +} + +const safari = () => new TypeError('Importing a module script failed.'); + +describe('detectModuleLoadFailure', () => { + it('is undefined for an ordinary error', () => { + expect(detectModuleLoadFailure(new Error('boom'), env([]))).toBeUndefined(); + expect(detectModuleLoadFailure('Importing a module script failed.', env([]))).toBeUndefined(); + expect(detectModuleLoadFailure(null, env([]))).toBeUndefined(); + }); + + it('reads the module from Chrome and Firefox messages', () => { + const chrome = new TypeError( + `Failed to fetch dynamically imported module: ${ORIGIN}/chunk-AAA.js?token=secret`, + ); + const firefox = new TypeError( + `error loading dynamically imported module: ${ORIGIN}/chunk-BBB.js`, + ); + expect(detectModuleLoadFailure(chrome, env([]))?.failedUrl).toContain(`${ORIGIN}/chunk-AAA.js`); + expect(detectModuleLoadFailure(chrome, env([]))?.failedUrl).not.toContain('secret'); + expect(detectModuleLoadFailure(chrome, env([]))?.source).toBe('message'); + expect(detectModuleLoadFailure(firefox, env([]))?.failedUrl).toBe(`${ORIGIN}/chunk-BBB.js`); + }); + + it("infers Safari's nameless failure from the newest zero-size same-origin script", () => { + const entries = [ + entry(`${ORIGIN}/main.js`), + entry(`${ORIGIN}/chunk-OLD.js`, FAILED), + entry(`${ORIGIN}/chunk-LAZY.js`, FAILED), + ]; + const failure = detectModuleLoadFailure(safari(), env(entries)); + expect(failure?.failedUrl).toBe(`${ORIGIN}/chunk-LAZY.js`); + expect(failure?.source).toBe('timing'); + expect(failure?.recentScripts).toEqual([`${ORIGIN}/main.js`]); + }); + + it('does not blame a cross-origin script, whose sizes are zero without Timing-Allow-Origin', () => { + const failure = detectModuleLoadFailure( + safari(), + env([entry('https://cdn.other.com/lib.js', FAILED)]), + ); + expect(failure?.failedUrl).toBeUndefined(); + }); + + it('trusts responseStatus over sizes, for any origin', () => { + const failure = detectModuleLoadFailure( + safari(), + env([entry('https://cdn.other.com/lib.js', { responseStatus: 404 })]), + ); + expect(failure?.failedUrl).toBe('https://cdn.other.com/lib.js'); + const ok = detectModuleLoadFailure( + safari(), + env([entry(`${ORIGIN}/ok.js`, { ...FAILED, responseStatus: 200 })]), + ); + expect(ok?.failedUrl).toBeUndefined(); + expect(ok?.recentScripts).toEqual([`${ORIGIN}/ok.js`]); + }); + + it('ignores a stale failed entry', () => { + const failure = detectModuleLoadFailure( + safari(), + env([entry(`${ORIGIN}/old.js`, { ...FAILED, responseEnd: 1 })], { + performance: { + getEntriesByType: () => [entry(`${ORIGIN}/old.js`, { ...FAILED, responseEnd: 1 })], + now: () => 600_000, + }, + }), + ); + expect(failure?.failedUrl).toBeUndefined(); + }); + + it('survives a performance API that throws', () => { + const throwing: StacklessEnv = { + performance: { + getEntriesByType: () => { + throw new Error('nope'); + }, + now: () => { + throw new Error('nope'); + }, + }, + }; + expect(detectModuleLoadFailure(safari(), throwing)).toEqual({ recentScripts: [] }); + }); +}); + +describe('stacklessFrames', () => { + it('stands a failed import in as one frame naming the module', () => { + const frames = stacklessFrames(safari(), env([entry(`${ORIGIN}/chunk-LAZY.js`, FAILED)])); + expect(frames).toEqual([{ function: IMPORT_FRAME_FUNCTION, file: `${ORIGIN}/chunk-LAZY.js` }]); + }); + + it('uses one fixed placeholder when the module is unknown, so occurrences group', () => { + expect(stacklessFrames(safari(), env([]))).toEqual([ + { function: IMPORT_FRAME_FUNCTION, file: UNKNOWN_MODULE }, + ]); + }); + + it("turns JavaScriptCore's sourceURL/line/column into a frame", () => { + const error = Object.assign(new SyntaxError('Unexpected token'), { + sourceURL: `${ORIGIN}/chunks/x.js`, + line: 3, + column: 9, + }); + expect(engineLocationFrame(error)).toMatchObject({ + file: `${ORIGIN}/chunks/x.js`, + line: 3, + column: 9, + }); + expect(stacklessFrames(error, env([]))).toHaveLength(1); + }); + + it('adds nothing for an ordinary stackless error', () => { + expect(stacklessFrames(new Error('x'), env([]))).toEqual([]); + }); +}); + +describe('createStacklessFrameEnricher', () => { + const enrich = createStacklessFrameEnricher(env([entry(`${ORIGIN}/chunk-LAZY.js`, FAILED)])); + + it('leaves a real stack alone', () => { + const real = [{ file: 'a.js', line: 1, column: 1 }]; + expect(enrich(safari(), real)).toBe(real); + }); + + it('fills an empty stack', () => { + expect(enrich(safari(), [])).toHaveLength(1); + }); + + it('keeps an empty stack empty when there is nothing to add', () => { + const empty: never[] = []; + expect(enrich(new Error('x'), empty)).toBe(empty); + }); +}); + +describe('describeStacklessContext', () => { + it('names the module, page, connectivity and recent scripts', () => { + const text = describeStacklessContext( + safari(), + env([entry(`${ORIGIN}/main.js`), entry(`${ORIGIN}/chunk-LAZY.js`, FAILED)], { + navigator: { onLine: false }, + }), + ); + expect(text).toBe( + [ + `Failed module: ${ORIGIN}/chunk-LAZY.js (inferred from resource timing)`, + `Page: ${ORIGIN}/#/apps/9`, + 'Online: false', + 'Recently loaded scripts (newest last):', + ` ${ORIGIN}/main.js`, + ].join('\n'), + ); + }); + + it('says so when the browser did not name the module', () => { + expect(describeStacklessContext(safari(), env([]))).toContain( + 'Failed module: unknown (the browser did not name it)', + ); + }); + + it('is undefined for anything that is not a failed import', () => { + expect(describeStacklessContext(new Error('x'), env([]))).toBeUndefined(); + }); +}); + +describe('hostile inputs never throw', () => { + const hostile = (): unknown => + Object.defineProperty({}, 'message', { + get() { + throw new Error('getter'); + }, + }); + + it('treats a same-origin responseStatus 0 as a failed fetch, a cross-origin one as unknown (an opaque success reports it too)', () => { + const same = detectModuleLoadFailure( + safari(), + env([entry(`${ORIGIN}/lazy.js`, { responseStatus: 0, transferSize: 10 })]), + ); + expect(same?.failedUrl).toBe(`${ORIGIN}/lazy.js`); + const cross = detectModuleLoadFailure( + safari(), + env([entry('https://cdn.other.com/lib.js', { responseStatus: 0 })]), + ); + expect(cross?.failedUrl).toBeUndefined(); + expect(cross?.recentScripts).toEqual(['https://cdn.other.com/lib.js']); + }); + + it('still trusts an explicit 4xx from another origin', () => { + const failure = detectModuleLoadFailure( + safari(), + env([entry('https://cdn.other.com/gone.js', { responseStatus: 404 })]), + ); + expect(failure?.failedUrl).toBe('https://cdn.other.com/gone.js'); + }); + + it('names the failure that ended last, not the request that started last', () => { + const failure = detectModuleLoadFailure( + safari(), + env([ + entry(`${ORIGIN}/a.js`, { ...FAILED, startTime: 0, responseEnd: 990 }), + entry(`${ORIGIN}/b.js`, { ...FAILED, startTime: 100, responseEnd: 200 }), + ]), + ); + expect(failure?.failedUrl).toBe(`${ORIGIN}/a.js`); + }); + + it('does not name a failure older than ten seconds', () => { + const failure = detectModuleLoadFailure( + safari(), + env([entry(`${ORIGIN}/old.js`, { ...FAILED, responseEnd: 1 })], { + performance: { + getEntriesByType: () => [entry(`${ORIGIN}/old.js`, { ...FAILED, responseEnd: 1 })], + now: () => 20_000, + }, + }), + ); + expect(failure?.failedUrl).toBeUndefined(); + }); + + it('keeps a hash route but never a fragment that carries a credential', () => { + const at = (hash: string) => + describeStacklessContext( + safari(), + env([], { + location: { href: '', origin: ORIGIN, pathname: '/auth/callback', hash }, + }), + ); + expect(at('#/apps/9')).toContain(`Page: ${ORIGIN}/auth/callback#/apps/9`); + const leaked = at('#access_token=eyJSECRET&refresh_token=r&token_type=bearer'); + expect(leaked).toContain(`Page: ${ORIGIN}/auth/callback`); + expect(leaked).not.toContain('SECRET'); + expect(leaked).not.toContain('access_token'); + }); + + it('survives global getters that throw while the environment is acquired', () => { + const keys = ['performance', 'location', 'navigator'] as const; + const saved = keys.map((k) => Object.getOwnPropertyDescriptor(globalThis, k)); + try { + for (const k of keys) { + Object.defineProperty(globalThis, k, { + configurable: true, + get() { + throw new Error('hostile'); + }, + }); + } + expect(() => stacklessFrames(safari())).not.toThrow(); + expect(describeStacklessContext(safari())).toContain('Failed module: unknown'); + } finally { + keys.forEach((k, i) => { + const descriptor = saved[i]; + if (descriptor === undefined) Reflect.deleteProperty(globalThis, k); + else Object.defineProperty(globalThis, k, descriptor); + }); + } + }); + + it('survives a message getter that throws', () => { + expect(stacklessFrames(hostile(), env([]))).toEqual([]); + expect(describeStacklessContext(hostile(), env([]))).toBeUndefined(); + }); + + it('leaves the page out when location cannot be read', () => { + const location = Object.defineProperty({ href: '', origin: ORIGIN, pathname: '/' }, 'hash', { + get() { + throw new Error('getter'); + }, + }) as StacklessEnv['location']; + const text = describeStacklessContext(safari(), env([], { location })); + expect(text).toContain('Failed module: unknown'); + expect(text).not.toContain('Page:'); + }); +}); diff --git a/packages/browser/src/stackless-error-context.ts b/packages/browser/src/stackless-error-context.ts new file mode 100644 index 00000000..d1f4da36 --- /dev/null +++ b/packages/browser/src/stackless-error-context.ts @@ -0,0 +1,271 @@ +import type { FrameEnricher, StackFrame } from '@bugsee/core'; +import { parseLocation } from '@bugsee/core'; +import { sanitizeLocationUrl } from '@bugsee/protocol'; + +// Context for an error the browser reports WITHOUT a stack, so the report is more than "TypeError at Unknown location". +// +// The case that motivated it is a failed dynamic `import()` (a lazy route chunk that 404s, or whose connection drops): +// - Safari rejects with a bare `TypeError: Importing a module script failed.` — no stack, no URL, and `window.onerror` never +// fires. Chrome ("Failed to fetch dynamically imported module: ") and Firefox ("error loading dynamically imported +// module: ") name the module in the MESSAGE but still ship no frames. +// - JavaScriptCore attaches `sourceURL` / `line` / `column` to a SyntaxError or an evaluation error instead of a stack. +// Both are recoverable from what the page still has: the message, the error's own location fields and the Resource Timing +// buffer (a failed module fetch leaves an entry whose transfer and body sizes are zero). Everything here is best-effort and +// pure reads: it never throws and never invents a module it cannot point at. +// Known limit: the Resource Timing buffer holds 250 entries and stops recording when full, so in a long-lived page "recent" +// scripts can be the oldest ones and a late failure may leave no entry; the module is then reported unknown, never guessed. + +const SAFARI_IMPORT_FAILED = /^importing a module script failed\.?$/i; +const CHROME_IMPORT_FAILED = /failed to fetch dynamically imported module:\s*(\S+)/i; +const FIREFOX_IMPORT_FAILED = /error loading dynamically imported module:?\s*(\S*)/i; + +/** + * How recent a failed-looking script entry must be to be blamed for a failure raised now. A rejection reaches the page within + * moments of its fetch failing, so a short window keeps an older, unrelated failure (a retry loop, a 404 handled earlier) from + * being named for a connection reset that left no entry of its own. + */ +const FAILED_ENTRY_MAX_AGE_MS = 10_000; +/** Successfully loaded scripts listed as "where the page was" — enough to name the current chunk, not a waterfall. */ +const RECENT_SCRIPTS = 5; + +/** The failed module's frame function. Frames of one unknown module share a file so they group together. */ +export const IMPORT_FRAME_FUNCTION = 'import()'; +export const UNKNOWN_MODULE = ''; + +interface ResourceEntryLike { + name: string; + initiatorType?: string; + startTime?: number; + responseEnd?: number; + transferSize?: number; + encodedBodySize?: number; + decodedBodySize?: number; + responseStatus?: number; +} + +export interface StacklessEnv { + /** `performance.getEntriesByType('resource')` and `performance.now()`. */ + performance?: { + getEntriesByType(type: string): unknown[]; + now(): number; + }; + location?: { href: string; origin: string; pathname: string; hash: string }; + navigator?: { onLine?: boolean }; +} + +export interface ModuleLoadFailure { + /** The module that failed, path-scrubbed; undefined when no source named it. */ + failedUrl?: string; + /** Where the URL came from: the message ("message"), or the Resource Timing buffer ("timing", an inference). */ + source?: 'message' | 'timing'; + /** The last scripts that DID load, newest last — the chunk the page was running is among them. */ + recentScripts: string[]; +} + +/** One global read that a hostile getter cannot turn into a thrown error. */ +function read(key: 'performance' | 'location' | 'navigator'): T | undefined { + try { + return (globalThis as unknown as Record)[key]; + } catch { + return undefined; + } +} + +function hostEnv(): StacklessEnv { + return { + performance: read('performance'), + location: read('location'), + navigator: read('navigator'), + }; +} + +function scrub(url: string): string { + return parseLocation(url).file ?? url; +} + +function messageOf(value: unknown): string | undefined { + if (typeof value !== 'object' || value === null) return undefined; + const message = (value as { message?: unknown }).message; + return typeof message === 'string' ? message : undefined; +} + +/** The module URL a Chrome/Firefox message names, `''` for Safari's nameless message, undefined when this is not an import failure. */ +function importFailureMessage(message: string | undefined): string | undefined { + if (message === undefined) return undefined; + if (SAFARI_IMPORT_FAILED.test(message.trim())) return ''; + const named = CHROME_IMPORT_FAILED.exec(message) ?? FIREFOX_IMPORT_FAILED.exec(message); + return named === null ? undefined : (named[1] ?? ''); +} + +function scriptEntries(env: StacklessEnv): ResourceEntryLike[] { + try { + const entries = env.performance?.getEntriesByType('resource') ?? []; + return entries.filter((entry): entry is ResourceEntryLike => { + const e = entry as ResourceEntryLike; + // `script` for a module import in Safari/Chrome, `other` for Firefox's module fetches. + return ( + typeof e.name === 'string' && + (e.initiatorType === 'script' || e.initiatorType === 'other') && + /\.m?js(?:$|[?#])/i.test(e.name) + ); + }); + } catch { + return []; + } +} + +function sameOrigin(env: StacklessEnv, url: string): boolean { + const origin = env.location?.origin; + return origin !== undefined && url.startsWith(`${origin}/`); +} + +/** + * Did this fetch fail? A `responseStatus` of 4xx/5xx (Chrome, newer Safari) is decisive for any origin. Everything else is + * limited to the page's own origin: a cross-origin entry without `Timing-Allow-Origin` reports zero sizes AND a zero status for + * a SUCCESS too (an opaque response), so neither can be read as a failure there. For a same-origin entry a zero status or a + * body of zero bytes with zero transfer is the signature of a failed request. + */ +function looksFailed(env: StacklessEnv, entry: ResourceEntryLike): boolean { + if (typeof entry.responseStatus === 'number' && entry.responseStatus !== 0) { + return entry.responseStatus >= 400; + } + if (!sameOrigin(env, entry.name)) return false; + if (entry.responseStatus === 0) return true; + return entry.transferSize === 0 && entry.encodedBodySize === 0 && entry.decodedBodySize === 0; +} + +/** + * Describe a failed dynamic import, or undefined when `value` is not one. Chrome/Firefox name the module in the message; + * Safari does not, so the newest recent same-origin script entry that looks failed is named instead (flagged as inferred). + */ +export function detectModuleLoadFailure( + value: unknown, + env: StacklessEnv = hostEnv(), +): ModuleLoadFailure | undefined { + const named = importFailureMessage(messageOf(value)); + if (named === undefined) return undefined; + + const entries = scriptEntries(env); + const now = (() => { + try { + return env.performance?.now(); + } catch { + return undefined; + } + })(); + const recentScripts = entries + .filter((entry) => !looksFailed(env, entry)) + .slice(-RECENT_SCRIPTS) + .map((entry) => scrub(entry.name)); + + if (named !== '') { + return { failedUrl: scrub(named), source: 'message', recentScripts }; + } + // The entry that FAILED most recently: the buffer is ordered by start time, and an older request can finish after a newer one. + const failed = entries + .filter((entry) => looksFailed(env, entry)) + .filter( + (entry) => + now === undefined || + entry.responseEnd === undefined || + now - entry.responseEnd <= FAILED_ENTRY_MAX_AGE_MS, + ) + .reduce( + (latest, entry) => + latest === undefined || (entry.responseEnd ?? 0) >= (latest.responseEnd ?? 0) + ? entry + : latest, + undefined, + ); + return failed === undefined + ? { recentScripts } + : { failedUrl: scrub(failed.name), source: 'timing', recentScripts }; +} + +/** JavaScriptCore's own location for an error that has no stack: `sourceURL`, `line`, `column`. */ +export function engineLocationFrame(value: unknown): StackFrame | undefined { + if (typeof value !== 'object' || value === null) return undefined; + const { sourceURL, line, column } = value as { + sourceURL?: unknown; + line?: unknown; + column?: unknown; + }; + if (typeof sourceURL !== 'string' || sourceURL === '' || typeof line !== 'number') + return undefined; + const frame = parseLocation(sourceURL); + frame.line = line; + if (typeof column === 'number') frame.column = column; + return frame; +} + +/** The frame that stands for a failed import: the module when known, else one fixed placeholder so occurrences group. */ +function importFrame(failure: ModuleLoadFailure): StackFrame { + return { function: IMPORT_FRAME_FUNCTION, file: failure.failedUrl ?? UNKNOWN_MODULE }; +} + +/** + * The route the user is on: path plus a HASH ROUTE (`#/a/b`), run through the SDK's own address sanitizer so a token in the + * path or the query is redacted by the same policy as the `url` trace. A fragment that is not a route (`#access_token=...`, the + * usual carrier of an OAuth or magic-link secret) and any query string are dropped before the sanitizer ever sees them. + */ +function pageOf(env: StacklessEnv): string | undefined { + const loc = env.location; + if (loc === undefined) return undefined; + try { + const hash = loc.hash.startsWith('#/') ? (loc.hash.split('?')[0] ?? '') : ''; + return sanitizeLocationUrl(`${loc.origin}${loc.pathname}${hash}`); + } catch { + return undefined; + } +} + +/** Frames for a stackless error, or `[]` when there is nothing to say. */ +export function stacklessFrames(value: unknown, env: StacklessEnv = hostEnv()): StackFrame[] { + try { + const failure = detectModuleLoadFailure(value, env); + if (failure !== undefined) return [importFrame(failure)]; + const located = engineLocationFrame(value); + return located === undefined ? [] : [located]; + } catch { + return []; + } +} + +/** A frame enricher that fills ONLY an empty stack, so a real stack and the async-origin enricher keep precedence. */ +export function createStacklessFrameEnricher(env?: StacklessEnv): FrameEnricher { + return (error, frames) => { + if (frames.length > 0) return frames; + const added = stacklessFrames(error, env); + return added.length > 0 ? added : frames; + }; +} + +/** Report-description lines for a failed import: which module, where the page was, what had just loaded, connectivity. */ +export function describeStacklessContext( + value: unknown, + env: StacklessEnv = hostEnv(), +): string | undefined { + try { + const failure = detectModuleLoadFailure(value, env); + if (failure === undefined) return undefined; + const lines: string[] = []; + if (failure.failedUrl === undefined) { + lines.push('Failed module: unknown (the browser did not name it)'); + } else if (failure.source === 'timing') { + lines.push(`Failed module: ${failure.failedUrl} (inferred from resource timing)`); + } else { + lines.push(`Failed module: ${failure.failedUrl}`); + } + const page = pageOf(env); + if (page !== undefined) lines.push(`Page: ${page}`); + const online = env.navigator?.onLine; + if (typeof online === 'boolean') lines.push(`Online: ${online}`); + if (failure.recentScripts.length > 0) { + lines.push('Recently loaded scripts (newest last):'); + for (const script of failure.recentScripts) lines.push(` ${script}`); + } + return lines.join('\n'); + } catch { + return undefined; + } +} diff --git a/packages/instrumentation-tests/test/webview-bundle.e2e.ts b/packages/instrumentation-tests/test/webview-bundle.e2e.ts index a6e32720..70e3771d 100644 --- a/packages/instrumentation-tests/test/webview-bundle.e2e.ts +++ b/packages/instrumentation-tests/test/webview-bundle.e2e.ts @@ -35,9 +35,13 @@ const KB = 1024; // field cost ~340 bytes gzip). Raised again, on purpose (2026-11-01), to 69 KiB gzip / 204 KiB raw: the shared core grew by about // 1 KB raw (~0.2 KB gzip) with the per-source visual lanes (lane routing in the chunk store, the per-lane members in the bundle // assembler, the lane in the part meta), which the webview bundles but does not use; the bundle measured 201.0 KB raw / 67.8 KB -// gzip against the old 200 / 68 limits. The artifact size stays logged by the test below. -const GZIP_BUDGET = 69 * KB; -const RAW_BUDGET = 204 * KB; +// gzip against the old 200 / 68 limits. Raised again, on purpose (2026-11-21), to 71 KiB gzip / 208 KiB raw: the browser tier's +// failed-module-import context (stackless-error-context: the failed module's frame, the page route and the recently loaded scripts +// for Safari's nameless `Importing a module script failed.`) is shared with the WebView's error providers and adds about 3.0 KB raw +// / 1.0 KB gzip; the bundle measured 206.2 KiB raw / 69.7 KiB gzip against 203.2 / 68.7 before it. A web page inside a WebView hits +// the same failure, so the context is kept rather than split out. The artifact size stays logged by the test below. +const GZIP_BUDGET = 71 * KB; +const RAW_BUDGET = 208 * KB; const IIFE_ENTRY = fileURLToPath(new URL('../../webview/src/iife.ts', import.meta.url));