diff --git a/.changeset/in-build-stamping.md b/.changeset/in-build-stamping.md new file mode 100644 index 000000000..40176813f --- /dev/null +++ b/.changeset/in-build-stamping.md @@ -0,0 +1,5 @@ +--- +'@bugsee/bundler-plugin-core': patch +--- + +Vite, Rollup and Rspack now stamp debug-IDs INSIDE the build (Vite/Rollup in `generateBundle`, `order: 'pre'`; Rspack at `PROCESS_ASSETS_STAGE_DEV_TOOLING + 1`, as webpack 5 already did), so Subresource Integrity hashes taken later describe the stamped bytes and a page that pins them keeps loading, with its maps uploaded. List the Bugsee plugin before any SRI plugin. A failed or impossible in-build stamp (an older Rollup, `sourcemap: 'inline'`) falls back to stamping after emit, where the SRI refusal still applies; esbuild and the standalone CLI stay post-emit. Every stamp is now verified (each bundle still parses, its sourceMappingURL is intact, the bytes are the original plus the appended stamp, and the map carries the bundle's debugId; a failure leaves or restores the original bytes and is reported), an in-build stamp is re-checked on disk and against the page's integrity pins, and `.map` files are deleted only after a confirmed upload and only when they carry a debugId. Adds `acorn` as a dependency for the parse check. diff --git a/.changeset/nextjs-with-bugsee.md b/.changeset/nextjs-with-bugsee.md new file mode 100644 index 000000000..4c61addc0 --- /dev/null +++ b/.changeset/nextjs-with-bugsee.md @@ -0,0 +1,6 @@ +--- +'@bugsee/nextjs': minor +'@bugsee/bundler-plugin-core': minor +--- + +`@bugsee/nextjs/config` adds `withBugsee(nextConfig, options)`: `next build` now stamps debug-IDs and uploads source maps on both webpack and Turbopack (Next 15.4.0+ for Turbopack, through `compiler.runAfterProductionCompile`). Browser maps are deleted after a confirmed upload; server and edge maps are kept. `@bugsee/bundler-plugin-core` exports `stampAssets`, `AssetStore`, `notify`, `resolveIdentity`, `loadBuildPluginEnv` and `mergeBuildPluginEnv` for it. diff --git a/.gitignore b/.gitignore index 266576e0b..c3215bf0b 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,10 @@ reports/ # `biome check .` by the thousand. .next/ +# Fixture apps the Next source-map e2e generates and builds (packages/nextjs-e2e/test/source-maps.e2e.ts). +packages/nextjs-e2e/.fixtures/ +packages/nextjs-e2e/.scratch/ + # tsup writes a bundled config next to the package when tsup.config.ts needs transpiling, and leaves # it behind if the build is interrupted. Untracked, it fails `biome check .` on a formatting rule. tsup.config.bundled_*.mjs diff --git a/CLAUDE.md b/CLAUDE.md index c0f47b62d..cf56c8e41 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -23,6 +23,7 @@ Runnable SDKs exist for **Node, Browser, Bun, Electron, Cloudflare/Vercel edge, - Electron platform: `@bugsee/electron` (`docs/design/electron.md`, slices E0–E8, convergent-reviewed) — converges main (Node/`@bugsee/node`) + renderers (Chromium/`@bugsee/browser`) + native (`crashReporter` minidumps) into ONE session. Main OWNS the session; renderers stream capture UP over IPC (reusing the WebView **streaming CaptureStore** core, extracted to `@bugsee/core`) and are driven DOWN via a control channel (session handshake + pause/resume/flush/stop). Native crashes via Electron's built-in `crashReporter` (Crashpad), session-correlated `extra` (no bespoke native SDK). Visual capture D8: **rrweb DOM-replay is the DEFAULT** (rides the renderer streaming path free); **opt-in pixel video** (`video:{source}`) is a permission-gated report-time snapshot source (added the mobile-canonical `video` FileType + a generic node `reportSnapshots`/`fileEncoders` forwarding seam) supporting capturePage + MediaRecorder. Entries: `.`/`./main`/`./renderer`/`./preload`. `electron`/DOM taken as injected args — the package has **no electron/DOM dependency**. - Extensions / umbrella: `@bugsee/performance` (APM — web-vitals + metric catalog, on-by-default via the umbrella) and `@bugsee/bugsee` (umbrella, with per-runtime browser/node `exports` conditions). - E2E: `@bugsee/instrumentation-tests` — boots the REAL SDK in real node/bun processes against a mock collector and asserts the uploaded bundle (`pnpm test:e2e`; not in `pnpm test`). +- Build integration (source maps): **`@bugsee/nextjs/config`** `withBugsee()` — webpack (per-compilation plugin) AND Turbopack (`compiler.runAfterProductionCompile`) upload, real-Next e2e in `@bugsee/nextjs-e2e` (`docs/design/source-maps.md` §7.3). - Framework adapters: the **per-request context foundation** (portable `RequestContext` + `ContextProvider` in core; `AsyncLocalStorage` binding in node, with `run` + `enterWith`; **correlation-by-tagging** — entries stamped with `contextId`/trace, reports merge the active context) + **`@bugsee/express`** (`requestHandler`/`errorHandler`/`setupExpress`) + **`@bugsee/fastify`** (hook-based `setupFastify`) + **`@bugsee/nestjs`** (`setupNest`: `enterWith` context middleware + a configurable error seam — default non-intrusive interceptor, opt-in global ExceptionFilter or `both` deduped; real-Nest e2e on express+fastify) + **`@bugsee/hono`/`elysia`/`hapi`/`koa`** (each structural-peer, per-framework error-capture probed before building; real-framework e2e) are built. (Restify was built then dropped — unmaintained, doesn't import on Node ≥18.) Plus **incoming-server auto-instrumentation** (`docs/design/incoming-server-instrumentation.md`): a **shared server-instrument core in `@bugsee/node`** (`server-instrument.ts` — plain values → `ServerRequestSpan`; `runServerRequest`/`openServerRequest`/split `openServerContext`+`startServerSpan`/`getActiveServerSpan`; **first-owner-wins re-entrancy** = one context + one `http.server` txn even when the http layer AND an adapter both run; only a `run`-scoped owner is refinable) auto-instruments incoming requests via the **`node:http` `Server.prototype.emit` patch** + native **`Bun.serve`** wraps, **ON BY DEFAULT** (`instrumentIncomingRequests`, default `true`; `false` opts out). **All 7 adapters were refactored onto this core** (each keeps its own `shouldReport`/route extraction). `@bugsee/server-adapters` was **retired** (engine absorbed; `openBugsee*`→`server*`). See `docs/design/framework-adapters.md` + `docs/design/incoming-server-instrumentation.md` (`generic-server-adapter.md` is superseded). - `launch(appToken, options)` returns the started client (every platform). diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 7e9c5aa9d..c909a11ca 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1528,3 +1528,9 @@ Verified against current majors, all green with no adapter code changes: `@bugse `launch(undefined)` on Node/Bun died with an opaque `TypeError ... reading 'length'` inside `hashAppToken`, crashing the host at startup. Every runtime composition root (`@bugsee/node` + bun, `@bugsee/electron` `launchMain`/`launchRenderer` (guard before any wiring; a bad-token renderer sends no hello and takes no page slot), `@bugsee/browser` + umbrella/electron-renderer, `@bugsee/vercel-edge` + cloudflare, `@bugsee/webworker`) now calls the shared `createDisabledClientForMissingToken` (`@bugsee/core` `app-token.ts`) first: a missing / empty / whitespace-only / non-string token reports ONE `Bugsee: the app token is missing ...` error through `onError` (else `console.warn`) and returns a DISABLED client (never started, `launch()` is a no-op, claims no carrier slot, so a later valid launch works; the browser one resolves it, `showReportDialog()` resolves `null`). `@bugsee/webview` is untouched (the native host owns the token; the JS side never uses it on the wire). Tests: `app-token.test.ts` + `launch-missing-token.test.ts` per entry. **Follow-up 2 (issue #11).** `sveltekit-e2e` now wires `sveltekit({ preprocess: [componentAnnotatePreprocessor()] })` (the `@bugsee/sveltekit` README Kit 3 call, with the plugin imported by path) and asserts the SSR HTML carries `data-bugsee-component` (mutation-checked: removing `preprocess` fails it). The plugin is imported from its built dist (the e2e builds it first) because Kit 3 re-loads `vite.config.ts` in a plain-Node post-build process that cannot resolve the workspace's extensionless TS source. The README nits were already fixed (#157). Only Rollup 5 (still prerelease, `5.0.0-2` on the `beta` tag) remains open: keep watching. + +### Debug-ID stamping inside the build for Vite, Rollup and Rspack; verified stamps; safe map deletion (2026-11-23) +`@bugsee/bundler-plugin-core` now stamps INSIDE the build wherever the bundler has a pre-write hook, so Subresource Integrity hashes taken later describe the stamped bytes: webpack 5 and **Rspack** at `PROCESS_ASSETS_STAGE_DEV_TOOLING + 1` (shared `tapProcessAssetsStamp`), **Vite and Rollup** in `generateBundle` (`order: 'pre'`; `rollupAssetStore` over chunks + `.map` assets; the stamped id is also put on `chunk.map` because Vite regenerates the map of a lazy-loading chunk after user hooks). esbuild and the standalone CLI stay post-emit with the SRI refusal (its message now names the workaround). Every stamp is verified (`verify-stamp.ts`: parses, sourceMappingURL intact, map debugId matches, original bytes + appended stamp): in-build all-or-nothing, post-emit snapshot + restore of the failing pair (`stamp-files.ts`); an in-build stamp is re-checked on disk (`verifyStampedPairs`) and against the HTML (`findIntegrityMismatches`). `.map` deletion now requires a confirmed upload AND a debugId on the map (`partitionByKeyed`). Real-build proof: `plugin.in-build.real-build.test.ts` (Vite 7 + 8, Rollup, Rspack with its built-in SRI plugin) and a Chromium run in `instrumentation-tests/test/sri-vite-rollup.e2e.ts`. Measured ordering limits and what the guards do not see: `docs/design/source-maps.md` §7.1. + +### Next.js build integration: `withBugsee` (`@bugsee/nextjs/config`), webpack AND Turbopack (2026-11-23) +`withBugsee(nextConfig, options)` makes `next build` stamp debug-IDs and upload source maps (gap #1 of the source-map gap analysis). Design + measured limits: `docs/design/source-maps.md` §7.3; user docs: `packages/nextjs/README.md`. **webpack** (`--webpack`, default <= 15): one per-compilation plugin (client, server, edge) stamping inside the compilation (`PROCESS_ASSETS_STAGE_DEV_TOOLING + 1`, SRI-safe) and uploading exactly the files that compilation emitted (`files` mode, nothing walks `.next`). The generic `@bugsee/webpack-plugin` was NOT reused for Next: measured against a real build it cannot stamp the server compilation (assets named `../app/page.js`, output path `.next/server/chunks`) and its directory-wide upload of `.next` collides across the three compilations. **Turbopack** (default 16; `--turbopack` 15.x): `compiler.runAfterProductionCompile` (15.4.0+) runs the real `inject` + upload over `.next/static` and `.next/server`, bundles paired with maps by the `sourceMappingURL` pointer (Turbopack does not name a map after its bundle; Next 15.5 shares one map between two runtime chunks, which are left unstamped with a notice). Measured limits: Turbopack writes the SRI hashes BEFORE the hook, so an `experimental.sri` Turbopack build is left unmodified with a notice (webpack handles SRI); Next 16 errors on a `webpack` function without a `turbopack` config, so none is added on Turbopack builds; `compiler.define` (not `defineServer`) bakes the app identity. Policy: browser maps deleted after a confirmed upload, server/edge maps kept (`deleteServerMaps`). Composes with a user's `webpack`, `compiler.runAfterProductionCompile`, `compiler.define`, `productionBrowserSourceMaps`, function/async configs; inert for dev/start/export. Core change: `@bugsee/bundler-plugin-core` now also exports `stampAssets`, `AssetStore`, `notify`, `resolveIdentity`, `loadBuildPluginEnv`, `mergeBuildPluginEnv`. Found by the independent reviews and fixed: stamped webpack assets are written as STRING sources (a Buffer is opaque to webpack's RealContentHashPlugin, which renames `[contenthash]` chunks after the stamp, so every lazy chunk 404'd; the e2e now opens each build in headless Chromium and asserts the lazy chunk runs), the baked define is the RAW value (Next JSON-encodes `compiler.define` itself; a JSON string arrived double-quoted), own-files-only deletion on Turbopack, contained post-build hook, version floors (hook 15.4.0, define 15.1.0), idempotent application. Real builds (`@bugsee/nextjs-e2e`, `test/source-maps.e2e.ts`, `next` 15.5.28 and 16.4.6 x webpack/Turbopack + SRI cases, real `bugsee-cli`, mock collector, `next start` smoke): see the PR for the run. diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 3de0c2085..91d2c6a8e 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -130,8 +130,8 @@ are Rollup `writeBundle`, esbuild `onEnd` (registered through unplugin's `esbuil or `write: false`, which is what tsup always sets, with a notice; the plugin sets `sourcemap: 'external'` only when it is unset, and says so when it is `false`) and Rspack `afterEmit`, each calling `runPluginUpload` with the same SRI guard as Vite and webpack (#184; real esbuild and Rspack builds are exercised in -`plugin.real-build.test.ts`). Rspack has no in-compilation stamp stage wired, so it takes the post-emit inject path -(an SRI build is refused, not stamped). They do **not** cover **Angular**: its builder does not accept esbuild +`plugin.real-build.test.ts`). Rollup and Rspack stamp INSIDE the build like Vite and webpack 5 (§7.1); only esbuild +takes the post-emit inject path (an SRI build is refused there, not stamped). They do **not** cover **Angular**: its builder does not accept esbuild plugins, so Angular uses the documented CLI post-build recipe (`docs/source-maps-usage.md §2`). Next.js on webpack uses the webpack plugin. Bun, tsup and `tsc`/`swc` stay CLI-post-build (tsup via `onSuccess`). esbuild builds work on **per-build file lists**: the plugin sets `metafile: true` and, in `onEnd`, takes the build's own @@ -162,13 +162,11 @@ SDK's concern (needs `hermes-compose-source-map` + a preserved bundle id). ## 7.1 Subresource Integrity -**The plugin refuses to stamp a build that pins its own script hashes** (`sri.ts`, -`findSriProtectedScripts`). This is not a precaution — it is measured. - `sourcemaps inject` appends the debug-ID comment and the `_bugseeDebugIds` registration to every emitted `.js`. -A build that computed SRI hashes during emit — `webpack-subresource-integrity`, Angular's -`subresourceIntegrity: true` — has already written a hash of the PRE-stamp bytes into the HTML. Measured on a -real webpack 5.111 build loaded in **Chromium 151.0.7922.34**: +Done AFTER the bundler wrote its output, that changes bytes a build step may already have hashed: a build that +computed SRI hashes during emit (`webpack-subresource-integrity`, Rspack's `SubresourceIntegrityPlugin`, a Vite SRI +plugin, Angular's `subresourceIntegrity: true`) has written a hash of the PRE-stamp bytes into the HTML. Measured on +a real webpack 5.111 build loaded in **Chromium 151.0.7922.34**: | | `window.__ran` | console | |---|---|---| @@ -176,28 +174,301 @@ real webpack 5.111 build loaded in **Chromium 151.0.7922.34**: | after inject | **`false`** | `Failed to find a valid digest in the 'integrity' attribute for resource '…/main..js' … The resource has been blocked.` | `index.html` is byte-identical across that pair; only the JS grew, 114 → 472 bytes. The page loads and nothing -runs — strictly worse than having no source maps. +runs — strictly worse than having no source maps. Two mechanisms keep that from happening. + +### Stamp inside the build (the fix) -So `uploadSourcemaps` scans the output directory's HTML *before* anything is written, and when a `\n', + ); + writeFileSync(join(dir, 'greet.js'), "export const greet = (n) => 'hello ' + n;\n"); + writeFileSync(join(dir, 'lazy.js'), "export default 'lazy chunk ' + Date.now();\n"); + writeFileSync( + join(dir, 'index.js'), + `import { greet } from './greet.js';\nconsole.log(greet('world'));\n${ + lazy ? "import('./lazy.js').then((m) => console.log(m.default));\n" : '' + }`, + ); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name, version: '1.2.3' })); + return { dir, out: join(dir, 'dist') }; +} + +const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + +interface Pin { + tag: string; + file: string; + integrity: string; +} + +/** Every script / modulepreload in `/index.html` with an integrity, resolved to its file in `out`. */ +function pinsOf(out: string): Pin[] { + const html = readFileSync(join(out, 'index.html'), 'utf8'); + const pins: Pin[] = []; + for (const tag of html.match(/<(?:script|link)\b[^>]*>/gi) ?? []) { + const integrity = /\bintegrity="([^"]+)"/i.exec(tag)?.[1]; + const url = /\b(?:src|href)="([^"]+)"/i.exec(tag)?.[1]; + if (integrity !== undefined && url !== undefined) { + pins.push({ tag, file: join(out, url.replace(/^\.?\//, '')), integrity }); + } + } + return pins; +} + +/** The comparison the browser makes: the pinned digest against the digest of the bytes on disk. */ +function expectPinsMatchDisk(out: string, atLeast = 1): void { + const pins = pinsOf(out); + expect(pins.length).toBeGreaterThanOrEqual(atLeast); + for (const pin of pins) { + expect(sri(readFileSync(pin.file)), `${pin.file} vs ${pin.integrity}`).toBe(pin.integrity); + } +} + +function expectStampedAndUploaded(out: string, before: number, atLeast = 2): void { + const files = readdirSync(out, { recursive: true }) as string[]; + const bundles = files.filter((f) => /\.[cm]?js$/.test(f)); + expect(bundles.length).toBeGreaterThanOrEqual(atLeast); // entry (+ lazy chunk) + for (const bundle of bundles) { + const code = readFileSync(join(out, bundle), 'utf8'); + expect(code, bundle).toMatch(/\/\/# debugId=[0-9a-f-]{36}/); + expect(code, bundle).toContain('_bugseeDebugIds'); + } + // Uploaded, then the client maps were deleted. + expect(requests.length).toBeGreaterThan(before); + expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); +} + +/** Add `integrity` to every script / modulepreload tag whose file is a chunk of the bundle. */ +function pinChunks(html: string, bundle: Record): string { + return html.replace( + /<(?:script|link)\b[^>]*?(?:src|href)="\.?\/?([^"]+\.js)"[^>]*>/gi, + (tag, file: string) => { + const entry = bundle[file]; + return entry?.type === 'chunk' && entry.code !== undefined + ? tag.replace(/>$/, ` integrity="${sri(entry.code)}">`) + : tag; + }, + ); +} + +/** A hand-rolled SRI step for Vite that hashes in `transformIndexHtml`, as vite-plugin-sri does. */ +const viteSri = (): VitePlugin => ({ + name: 'hand-rolled-sri', + enforce: 'post', + transformIndexHtml: { + order: 'post', + handler: (html, ctx) => pinChunks(html, (ctx.bundle ?? {}) as never), + }, +}); + +/** A hand-rolled SRI step that hashes LAST, in generateBundle (order post), into the emitted page. */ +const viteLateSri = (): VitePlugin => ({ + name: 'hand-rolled-late-sri', + enforce: 'post', + generateBundle: { + order: 'post', + handler(_options, bundle) { + const page = bundle['index.html']; + if (page?.type === 'asset') { + page.source = pinChunks(String(page.source), bundle as never); + } + }, + }, +}); + +const viteConfig = (app: { dir: string; out: string }, plugins: unknown[], build: object = {}) => + ({ + root: app.dir, + configFile: false, + logLevel: 'silent', + base: './', + plugins, + build: { outDir: app.out, emptyOutDir: true, minify: false, sourcemap: true, ...build }, + }) as never; + +const bugseeVite = (extra: object = {}) => + bugseeUnplugin.vite({ ...pluginOptions(), ...extra }) as VitePlugin; + +describeReal('real Vite builds with an SRI step', () => { + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + const slug = label.replace(/\W+/g, ''); + + it(`${label}: an SRI step in transformIndexHtml pins the STAMPED bytes; maps uploaded and removed`, async () => { + const app = makeApp(`vite-html-${slug}`, { lazy: false }); + const before = requests.length; + const warnings: unknown[] = []; + await build( + viteConfig(app, [ + bugseeVite({ failOnError: false, onError: (e: unknown) => warnings.push(e) }), + viteSri(), + ]), + ); + expect(warnings).toEqual([]); + expectStampedAndUploaded(app.out, before, 1); + expectPinsMatchDisk(app.out); + expect(await findIntegrityMismatches(app.out)).toEqual([]); + }); + + it(`${label}: an app with a lazy chunk and an SRI step that hashes last (generateBundle, post)`, async () => { + const app = makeApp(`vite-late-${slug}`); + const before = requests.length; + const warnings: unknown[] = []; + await build( + viteConfig(app, [ + bugseeVite({ failOnError: false, onError: (e: unknown) => warnings.push(e) }), + viteLateSri(), + ]), + ); + expect(warnings.map(String)).toEqual([]); + expectStampedAndUploaded(app.out, before); + expectPinsMatchDisk(app.out); + expect(await findIntegrityMismatches(app.out)).toEqual([]); + }); + } + + it('Vite 8: the match is not an accident of nothing being stamped (a disabled build pins other bytes)', async () => { + const stamped = makeApp('vite-compare-stamped', { lazy: false }); + const plain = makeApp('vite-compare-plain', { lazy: false }); + for (const [app, disabled] of [ + [stamped, false], + [plain, true], + ] as const) { + await viteBuild(viteConfig(app, [bugseeVite({ disabled }), viteSri()])); + } + const entry = (out: string): string => + readFileSync( + join( + out, + 'assets', + readdirSync(join(out, 'assets')).find((f) => f.endsWith('.js')) as string, + ), + 'utf8', + ); + expect(entry(stamped.out)).toContain('debugId'); + expect(entry(plain.out)).not.toContain('debugId'); + expectPinsMatchDisk(stamped.out); + expectPinsMatchDisk(plain.out); + expect(pinsOf(stamped.out)[0]?.integrity).not.toBe(pinsOf(plain.out)[0]?.integrity); + }); + + it('Vite 8: a build whose maps cannot be stamped in memory (inline) falls back to post-emit, where the SRI guard still refuses', async () => { + const app = makeApp('vite-inline', { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const notices: string[] = []; + await viteBuild( + viteConfig( + app, + [ + bugseeVite({ + failOnError: false, + onError: (e: unknown) => errors.push(e), + onNotice: (m: string) => notices.push(m), + }), + viteSri(), + ], + { sourcemap: 'inline' }, + ), + ); + expect(notices.join('\n')).toContain('after emit'); + expect(errors.map(String).join('\n')).toContain('refusing to stamp debug-IDs'); + // Nothing stamped, nothing uploaded, and the page's pins are intact. + expect(requests.length).toBe(before); + for (const f of readdirSync(join(app.out, 'assets'))) { + expect(readFileSync(join(app.out, 'assets', f), 'utf8')).not.toContain('_bugseeDebugIds'); + } + expectPinsMatchDisk(app.out); + }); +}); + +describeReal('real Rollup build with an SRI step', () => { + it('the pinned hashes match the STAMPED bytes, maps uploaded and removed', async () => { + const app = makeApp('rollup-sri'); + const before = requests.length; + const sriHtml = { + name: 'sri-html', + generateBundle( + this: { emitFile(file: object): void }, + _output: unknown, + bundle: Record< + string, + { type: string; code?: string; isEntry?: boolean; fileName: string } + >, + ) { + const tags = Object.values(bundle) + .filter((entry) => entry.type === 'chunk') + .map((entry) => + entry.isEntry + ? `` + : ``, + ); + this.emitFile({ + type: 'asset', + fileName: 'index.html', + source: `${tags.join('')}`, + }); + }, + }; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin({ ...pluginOptions() }), sriHtml], + }); + await bundle.write({ dir: app.out, sourcemap: true }); + await bundle.close(); + expectStampedAndUploaded(app.out, before); + expectPinsMatchDisk(app.out, 2); + expect(await findIntegrityMismatches(app.out)).toEqual([]); + }); +}); + +describeReal('real Rspack build with the built-in SubresourceIntegrityPlugin', () => { + function runRspack(config: Parameters[0]): Promise<{ errors: unknown[] }> { + return new Promise((resolve, reject) => { + const compiler = rspack(config); + compiler.run((err, stats) => { + compiler.close(() => { + if (err) { + reject(err); + } else { + resolve({ + errors: (stats as { compilation: { errors: unknown[] } }).compilation.errors, + }); + } + }); + }); + }); + } + + it('the pinned hashes (page AND the lazy-chunk table in the runtime) match the STAMPED bytes', async () => { + const app = makeApp('rspack-sri-built-in'); + const before = requests.length; + const warnings: unknown[] = []; + const { errors } = await runRspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: 'source-map', + output: { path: app.out, crossOriginLoading: 'anonymous' }, + plugins: [ + bugseeRspackPlugin({ ...pluginOptions(), onError: (e: unknown) => warnings.push(e) }), + new rspack.HtmlRspackPlugin({ + template: join(app.dir, 'index.html'), + scriptLoading: 'defer', + }), + new rspack.SubresourceIntegrityPlugin({ hashFuncNames: ['sha384'] }), + ], + }); + console.log('RSERR', errors.map(String)); + expect(errors.map((e) => String((e as Error).message ?? e))).toEqual([]); + expect(warnings.map(String)).toEqual([]); + expectStampedAndUploaded(app.out, before); + expectPinsMatchDisk(app.out); + expect(await findIntegrityMismatches(app.out)).toEqual([]); + // The lazy chunk is not in the HTML; the plugin embeds ITS hash in the runtime. That hash must be of the + // stamped bytes too, or `import()` of the chunk fails in the browser. + const files = readdirSync(app.out).filter((f) => f.endsWith('.js')); + const runtimeText = files.map((f) => readFileSync(join(app.out, f), 'utf8')).join('\n'); + const pinned = new Set(pinsOf(app.out).map((pin) => pin.file)); + const lazy = files.filter((f) => !pinned.has(join(app.out, f))); + expect(lazy.length).toBeGreaterThan(0); + for (const f of lazy) { + expect(runtimeText, `${f} hash is in the runtime table`).toContain( + createHash('sha384') + .update(readFileSync(join(app.out, f))) + .digest('base64'), + ); + } + expect(existsSync(join(app.out, 'index.html'))).toBe(true); + }); +}); + +// A script that is NOT part of the bundle (a `publicDir` copy, a stale file with `emptyOutDir: false`) has no +// debug-id, and the real bugsee-cli exits non-zero for a directory that holds a map without one ("nothing was +// uploaded"). Uploading the DIRECTORY would therefore lose every map of the build; the pre-stamped path names +// its files instead. Real CLI, no --dry-run, failOnError on. +describeReal('an unstamped vendor script + map beside a stamped build', () => { + const VENDOR_MAP = '{"version":3,"sources":["vendor.src.js"],"names":[],"mappings":"AAAA"}'; + const addVendor = (dir: string): void => { + mkdirSync(dir, { recursive: true }); + writeFileSync( + join(dir, 'vendor.js'), + 'window.__vendor = 1;\n//# sourceMappingURL=vendor.js.map\n', + ); + writeFileSync(join(dir, 'vendor.js.map'), VENDOR_MAP); + }; + const expectVendorUntouched = (out: string): void => { + expect(readFileSync(join(out, 'vendor.js.map'), 'utf8')).toBe(VENDOR_MAP); + expect(readFileSync(join(out, 'vendor.js'), 'utf8')).not.toContain('debugId'); + }; + + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + it(`${label}: publicDir/vendor.js is left alone and said; the stamped maps still upload; failOnError does not fail`, async () => { + const app = makeApp(`vite-vendor-${label.replace(/\W+/g, '')}`, { lazy: false }); + addVendor(join(app.dir, 'public')); + const before = requests.length; + const notices: string[] = []; + const errors: unknown[] = []; + await build( + viteConfig(app, [ + bugseeVite({ + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ]), + ); + expect(errors.map(String)).toEqual([]); + expect(requests.length).toBeGreaterThan(before); + expect(readdirSync(join(app.out, 'assets')).filter((f) => f.endsWith('.map'))).toEqual([]); + expectVendorUntouched(app.out); + expect(notices.join('\n')).toContain('vendor.js.map'); + }); + } + + it('Rollup: a stale vendor script in the output directory is left alone and said', async () => { + const app = makeApp('rollup-vendor'); + addVendor(app.out); + const before = requests.length; + const notices: string[] = []; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await bundle.write({ dir: app.out, sourcemap: true }); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect(requests.length).toBeGreaterThan(before); + const maps = readdirSync(app.out).filter((f) => f.endsWith('.map')); + expect(maps).toEqual(['vendor.js.map']); + expectVendorUntouched(app.out); + expect(notices.join('\n')).toContain('vendor.js.map'); + }); +}); + +// The stamp keys a map whatever it is called (`sourcemapFileName(s)`, `[name].map`), so the upload set must be +// everything the CLI scans a directory for, not just `*.js.map`, and a map is deleted only if it was uploaded. +// Real bugsee-cli, no dry run. +describeReal('maps with custom names (sourcemapFileNames: "[name].map")', () => { + for (const failOnError of [true, false]) { + const tag = `failOnError ${failOnError}`; + const expectUploadedAndGone = (out: string, before: number): void => { + const files = readdirSync(out, { recursive: true }) as string[]; + expect(requests.length, 'uploaded').toBeGreaterThan(before); + expect( + files.filter((f) => f.endsWith('.map')), + 'deleted after the confirmed upload', + ).toEqual([]); + for (const bundle of files.filter((f) => /\.[cm]?js$/.test(f))) { + const code = readFileSync(join(out, bundle), 'utf8'); + expect(code, bundle).toMatch(/\/\/# debugId=[0-9a-f-]{36}/); + expect(code, bundle).toMatch(/sourceMappingURL=[^\s]*\.map(?!\.)/); + expect(code, bundle).not.toMatch(/sourceMappingURL=[^\s]*\.js\.map/); + } + }; + + it(`Rollup (${tag})`, async () => { + const app = makeApp(`rollup-custom-${failOnError}`, { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + failOnError, + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await bundle.write({ dir: app.out, sourcemap: true, sourcemapFileNames: '[name].map' }); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expectUploadedAndGone(app.out, before); + }); + + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + it(`${label} (${tag})`, async () => { + const app = makeApp(`vite-custom-${label.replace(/\W+/g, '')}-${failOnError}`, { + lazy: false, + }); + const before = requests.length; + const errors: unknown[] = []; + await build( + viteConfig(app, [bugseeVite({ failOnError, onError: (e: unknown) => errors.push(e) })], { + rollupOptions: { output: { sourcemapFileNames: 'assets/[name].map' } }, + }), + ); + expect(errors.map(String)).toEqual([]); + expectUploadedAndGone(app.out, before); + }); + } + + it(`Rspack (${tag})`, async () => { + const app = makeApp(`rspack-custom-${failOnError}`, { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const compile = await new Promise<{ errors: unknown[] }>((resolve, reject) => { + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: false, + output: { path: app.out }, + plugins: [ + new rspack.SourceMapDevToolPlugin({ filename: '[name].map' }), + bugseeRspackPlugin({ + ...pluginOptions(), + failOnError, + onError: (e: unknown) => errors.push(e), + }), + ], + }); + compiler.run((err, stats) => { + compiler.close(() => + err + ? reject(err) + : resolve({ + errors: [...(stats as { compilation: { errors: unknown[] } }).compilation.errors], + }), + ); + }); + }); + expect(compile.errors.map(String)).toEqual([]); + expect(errors.map(String)).toEqual([]); + expectUploadedAndGone(app.out, before); + }); + } +}); + +// A stylesheet map is never uploaded, but it embeds the source: it is still deleted with the rest. +describeReal('a stylesheet map beside the stamped maps (Rspack, [file].map)', () => { + it('uploads the keyed js map and deletes the css map too (real CLI, failOnError on)', async () => { + const app = makeApp('rspack-css', { lazy: false }); + writeFileSync(join(app.dir, 'style.css'), 'body { color: red; }\n'); + writeFileSync(join(app.dir, 'index.js'), "import './style.css';\nconsole.log('css');\n"); + const before = requests.length; + const errors: unknown[] = []; + const out = await new Promise<{ errors: unknown[]; files: string[] }>((resolve, reject) => { + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: false, + output: { path: app.out }, + module: { rules: [{ test: /\.css$/, type: 'css' }] }, + experiments: { css: true }, + plugins: [ + new rspack.SourceMapDevToolPlugin({ filename: '[file].map' }), + bugseeRspackPlugin({ ...pluginOptions(), onError: (e: unknown) => errors.push(e) }), + ], + }); + compiler.run((err, stats) => { + compiler.close(() => + err + ? reject(err) + : resolve({ + errors: [...(stats as { compilation: { errors: unknown[] } }).compilation.errors], + files: readdirSync(app.out), + }), + ); + }); + }); + expect(out.errors.map(String)).toEqual([]); + expect(errors.map(String)).toEqual([]); + expect(requests.length, 'the keyed js map was uploaded').toBeGreaterThan(before); + expect(out.files.some((f) => f.endsWith('.css'))).toBe(true); + expect(out.files.filter((f) => f.endsWith('.map'))).toEqual([]); + }); +}); + +// A map can be MOVED by `sourcemapFileNames` (another directory of the output). inject pairs a staged bundle +// with its map by the sourceMappingURL comment or the sibling name, so the stamp must make the pairing work +// for any location, or the bundle is stamped with an id that is never uploaded and the map is left behind. +describeReal('maps moved to another directory (sourcemapFileNames: "maps/[name].js.map")', () => { + const shapes = [ + ['same directory tree, maps/ beside the bundles', {}], + [ + 'bundles in js/, maps in maps/', + { entryFileNames: 'js/[name].js', chunkFileNames: 'js/[name].js' }, + ], + ] as const; + for (const failOnError of [true, false]) { + for (const [shape, extraOutput] of shapes) { + const tag = `${shape}, failOnError ${failOnError}`; + const check = (out: string, before: number, notices: string[], errors: unknown[]): void => { + const files = readdirSync(out, { recursive: true }) as string[]; + expect(errors.map(String)).toEqual([]); + expect(notices.join('\n')).not.toContain('not part of this build'); + expect(requests.length, 'uploaded').toBeGreaterThan(before); + expect( + files.filter((f) => f.endsWith('.map')), + 'maps deleted after the upload', + ).toEqual([]); + const bundles = files.filter((f) => /\.[cm]?js$/.test(f)); + expect(bundles.length).toBeGreaterThan(0); + for (const bundle of bundles) { + expect(readFileSync(join(out, bundle), 'utf8'), bundle).toMatch( + /\/\/# debugId=[0-9a-f-]{36}/, + ); + } + }; + + it(`Rollup (${tag})`, async () => { + const app = makeApp(`rollup-moved-${shape.length}-${failOnError}`, { lazy: false }); + const before = requests.length; + const [notices, errors]: [string[], unknown[]] = [[], []]; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + failOnError, + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await bundle.write({ + dir: app.out, + sourcemap: true, + sourcemapFileNames: 'maps/[name].js.map', + ...extraOutput, + }); + await bundle.close(); + check(app.out, before, notices, errors); + }); + + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + it(`${label} (${tag})`, async () => { + const app = makeApp( + `vite-moved-${label.replace(/\W+/g, '')}-${shape.length}-${failOnError}`, + { lazy: false }, + ); + const before = requests.length; + const [notices, errors]: [string[], unknown[]] = [[], []]; + await build( + viteConfig( + app, + [ + bugseeVite({ + failOnError, + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ], + { + rollupOptions: { + output: { sourcemapFileNames: 'maps/[name].js.map', ...extraOutput }, + }, + }, + ), + ); + check(app.out, before, notices, errors); + }); + } + } + } +}); + +// The CLI's directory scan has no depth limit and inject stamps a bundle however deep it is. +describeReal('a bundle deeper than the walk depth cap', () => { + it('Rollup: entryFileNames a/b/c/d/e/f/g/[name].js is stamped, uploaded and its map deleted', async () => { + const app = makeApp('rollup-deep', { lazy: false }); + const before = requests.length; + const [notices, errors]: [string[], unknown[]] = [[], []]; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await bundle.write({ + dir: app.out, + sourcemap: true, + entryFileNames: 'a/b/c/d/e/f/g/[name].js', + }); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect(notices).toEqual([]); + expect(requests.length).toBeGreaterThan(before); + const files = readdirSync(app.out, { recursive: true }) as string[]; + expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); + expect(readFileSync(join(app.out, 'a/b/c/d/e/f/g/index.js'), 'utf8')).toMatch(/debugId=/); + }); +}); + +// Maps this build did not produce, in directories that are not its output, must survive (the CLI's directory +// scan reaches them; deleting them is not this build's business). +describeReal('foreign css/declaration maps in an existing output directory', () => { + it("Rollup: dist/node_modules, src, dot-dirs are untouched; this build's own maps are gone", async () => { + const app = makeApp('rollup-foreign', { lazy: false }); + const foreign = [ + 'node_modules/pkg/style.css.map', + 'node_modules/pkg/types.d.ts.map', + '.cache/x.d.ts.map', + 'src/old.d.ts.map', + ]; + for (const rel of foreign) { + mkdirSync(join(app.out, rel, '..'), { recursive: true }); + writeFileSync(join(app.out, rel), '{}'); + } + const before = requests.length; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await bundle.write({ dir: app.out, sourcemap: true }); + await bundle.close(); + expect(requests.length).toBeGreaterThan(before); + const left = (readdirSync(app.out, { recursive: true }) as string[]) + .filter((f) => f.endsWith('.map')) + .sort(); + expect(left).toEqual([...foreign].sort()); + }); +}); + +// A map the bundle points at but that cannot be stamped with it (outside the output, or an unencoded space) must +// never leave a stamped bundle whose id never reaches its map: the stamp is refused/restored and reported. +describeReal('Rspack: a source map the stamp cannot reach', () => { + const build = ( + app: { dir: string; out: string }, + output: object, + filename: string, + failOnError: boolean, + errors: unknown[], + ) => + new Promise<{ errors: unknown[] }>((resolve, reject) => { + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: false, + output: { path: app.out, ...output }, + plugins: [ + new rspack.SourceMapDevToolPlugin({ filename }), + bugseeRspackPlugin({ + ...pluginOptions(), + failOnError, + onError: (e: unknown) => errors.push(e), + }), + ], + }); + compiler.run((err, stats) => { + compiler.close(() => + err + ? reject(err) + : resolve({ + errors: [...(stats as { compilation: { errors: unknown[] } }).compilation.errors], + }), + ); + }); + }); + + it('a map OUTSIDE the output directory: nothing is stamped or uploaded, and it is said (never a silent half-stamp)', async () => { + const app = makeApp('rspack-outside', { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + await build(app, { filename: 'js/[name].js' }, '../maps/[file].map', false, errors); + expect(errors.map((e) => String((e as Error).message ?? e)).join('\n')).toContain( + 'outside the output directory', + ); + expect(readFileSync(join(app.out, 'js', 'main.js'), 'utf8')).not.toContain('debugId'); + expect(requests.length).toBe(before); + }); + + it('a map OUTSIDE the output directory fails the build under failOnError', async () => { + const app = makeApp('rspack-outside-strict', { lazy: false }); + const before = requests.length; + await expect( + build(app, { filename: 'js/[name].js' }, '../maps/[file].map', true, []), + ).rejects.toThrow(/outside the output directory/); + expect(requests.length).toBe(before); + }); + + it('a map under a directory with a space, pointer emitted unencoded: stamped (mapOf) and uploaded', async () => { + const app = makeApp('rspack-space', { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const result = await build( + app, + { filename: 'j s/[name].js' }, + 'my maps/[file].map', + true, + errors, + ); + expect(result.errors.map(String)).toEqual([]); + expect(errors.map(String)).toEqual([]); + expect(requests.length).toBeGreaterThan(before); + const files = readdirSync(app.out, { recursive: true }) as string[]; + expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); + expect(readFileSync(join(app.out, 'j s', 'main.js'), 'utf8')).toMatch(/debugId=/); + }); + + it('a map moved into another directory of the output (maps/[file].map, bundles in js/): stamped and uploaded', async () => { + const app = makeApp('rspack-moved', { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const result = await build(app, { filename: 'js/[name].js' }, 'maps/[file].map', true, errors); + expect(result.errors.map(String)).toEqual([]); + expect(errors.map(String)).toEqual([]); + expect(requests.length).toBeGreaterThan(before); + expect( + (readdirSync(app.out, { recursive: true }) as string[]).filter((f) => f.endsWith('.map')), + ).toEqual([]); + }); +}); + +// Identity, not directory names: this build's own css/declaration maps are deleted wherever they are (even under +// dist/src from preserveModules), and files it did not emit are never deleted, even under an innocent name. +describeReal('ownership: only what this build emitted is deleted', () => { + const seed = (out: string, rels: string[]): void => { + for (const rel of rels) { + mkdirSync(join(out, rel, '..'), { recursive: true }); + writeFileSync(join(out, rel), '{}'); + } + }; + const mapsLeft = (out: string): string[] => + (readdirSync(out, { recursive: true }) as string[]).filter((f) => f.endsWith('.map')).sort(); + const emitExtraMaps = (names: string[]) => ({ + name: 'emit-extra-maps', + generateBundle(this: { emitFile(f: object): void }) { + for (const fileName of names) { + this.emitFile({ type: 'asset', fileName, source: '{}' }); + } + }, + }); + + it('Rollup preserveModules: dist/src/** css + declaration maps of THIS build are deleted; seeded foreign ones survive', async () => { + const app = makeApp('rollup-own', { lazy: false }); + const foreign = ['node_modules/pkg/style.css.map', '.cache/x.d.ts.map', 'src/old.d.ts.map']; + seed(app.out, foreign); + const before = requests.length; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin(pluginOptions()), + emitExtraMaps(['src/style.css.map', 'src/a.d.ts.map']), + ], + }); + await bundle.write({ + dir: app.out, + sourcemap: true, + preserveModules: true, + entryFileNames: 'src/[name].js', + }); + await bundle.close(); + expect(requests.length).toBeGreaterThan(before); + expect(mapsLeft(app.out)).toEqual([...foreign].sort()); + }); + + it('Vite 8: foreign public/vendor/bootstrap.css.map and a foreign KEYED public/x.js.map are not deleted', async () => { + const app = makeApp('vite-own', { lazy: false }); + mkdirSync(join(app.dir, 'public', 'vendor'), { recursive: true }); + writeFileSync(join(app.dir, 'public', 'vendor', 'bootstrap.css.map'), '{}'); + writeFileSync( + join(app.dir, 'public', 'x.js.map'), + '{"version":3,"debugId":"b039c7fb-d958-5fe6-b76f-136179e9a728"}', + ); + const notices: string[] = []; + const before = requests.length; + await viteBuild(viteConfig(app, [bugseeVite({ onNotice: (m: string) => notices.push(m) })])); + expect(requests.length).toBeGreaterThan(before); + expect(mapsLeft(app.out)).toEqual(['vendor/bootstrap.css.map', 'x.js.map']); + expect(notices.join('\n')).toContain('x.js.map'); + }); + + it("Rspack: a pre-seeded foreign css map survives, this build's own js map is deleted", async () => { + const app = makeApp('rspack-own', { lazy: false }); + seed(app.out, ['vendor/foreign.css.map', 'src/old.d.ts.map']); + const before = requests.length; + const compile = await new Promise((resolve, reject) => { + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: 'source-map', + output: { path: app.out }, + plugins: [bugseeRspackPlugin(pluginOptions())], + }); + compiler.run((err) => compiler.close(() => (err ? reject(err) : resolve()))); + }); + void compile; + expect(requests.length).toBeGreaterThan(before); + expect(mapsLeft(app.out)).toEqual(['src/old.d.ts.map', 'vendor/foreign.css.map']); + }); +}); + +// webpack/Rspack asset names can carry a ?query (`[name].js?[contenthash]`); the disk name does not. The stamp +// must match, stage and write back through the query, and the deletion by identity must too. +describeReal('Rspack: asset names with a ?query', () => { + for (const failOnError of [true, false]) { + it(`[name].js?[contenthash] and a chunkFilename query: stamped, uploaded, all of this build's maps deleted (failOnError ${failOnError})`, async () => { + const app = makeApp(`rspack-query-${failOnError}`); + const before = requests.length; + const errors: unknown[] = []; + const result = await new Promise<{ errors: unknown[] }>((resolve, reject) => { + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: 'source-map', + output: { + path: app.out, + filename: '[name].js?[contenthash]', + chunkFilename: '[name].js?[contenthash]', + }, + plugins: [ + bugseeRspackPlugin({ + ...pluginOptions(), + failOnError, + onError: (e: unknown) => errors.push(e), + }), + ], + }); + compiler.run((err, stats) => + compiler.close(() => + err + ? reject(err) + : resolve({ + errors: [...(stats as { compilation: { errors: unknown[] } }).compilation.errors], + }), + ), + ); + }); + expect(result.errors.map(String)).toEqual([]); + expect(errors.map(String)).toEqual([]); + expect(requests.length, 'uploaded').toBeGreaterThan(before); + const files = readdirSync(app.out, { recursive: true }) as string[]; + expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); + const bundles = files.filter((f) => /\.js$/.test(f)); + expect(bundles.length).toBeGreaterThanOrEqual(2); + for (const bundle of bundles) { + expect(readFileSync(join(app.out, bundle), 'utf8'), bundle).toMatch(/\/\/# debugId=/); + } + }); + } +}); + +// GROUND TRUTH: webpack/Rspack write `a#1.js` as `a#1.js` (the `#` stays); only `?...` is dropped. +describeReal('Rspack: # in a file name is part of the name', () => { + const run = ( + app: { dir: string; out: string }, + filename: unknown, + failOnError: boolean, + errors: unknown[], + ) => + new Promise<{ errors: unknown[] }>((resolve, reject) => { + writeFileSync(join(app.dir, 'other.js'), "console.log('other');\n"); + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: { main: join(app.dir, 'index.js'), a: join(app.dir, 'other.js') }, + devtool: 'source-map', + output: { path: app.out, filename: filename as never }, + plugins: [ + bugseeRspackPlugin({ + ...pluginOptions(), + failOnError, + onError: (e: unknown) => errors.push(e), + }), + ], + }); + compiler.run((err, stats) => + compiler.close(() => + err + ? reject(err) + : resolve({ + errors: [...(stats as { compilation: { errors: unknown[] } }).compilation.errors], + }), + ), + ); + }); + const expectAllStampedAndGone = (out: string, before: number, atLeast: number): void => { + const files = readdirSync(out, { recursive: true }) as string[]; + expect(requests.length, 'uploaded').toBeGreaterThan(before); + expect( + files.filter((f) => f.endsWith('.map')), + 'every own map deleted', + ).toEqual([]); + const bundles = files.filter((f) => /\.js$/.test(f)); + expect(bundles.length).toBeGreaterThanOrEqual(atLeast); + for (const bundle of bundles) { + expect(readFileSync(join(out, bundle), 'utf8'), bundle).toMatch(/\/\/# debugId=/); + } + }; + + for (const failOnError of [true, false]) { + it(`one entry emitted as a#1.js beside normal bundles (failOnError ${failOnError})`, async () => { + const app = makeApp(`rspack-hash-mixed-${failOnError}`, { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const result = await run( + app, + (p: { chunk?: { name?: string } }) => (p.chunk?.name === 'a' ? 'a#1.js' : '[name].js'), + failOnError, + errors, + ); + expect(result.errors.map(String)).toEqual([]); + expect(errors.map(String)).toEqual([]); + expect(readdirSync(app.out)).toContain('a#1.js'); + expectAllStampedAndGone(app.out, before, 2); + }); + + it(`every file named [name]#[contenthash:6].js (failOnError ${failOnError})`, async () => { + const app = makeApp(`rspack-hash-all-${failOnError}`, { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const result = await run(app, '[name]#[contenthash:6].js', failOnError, errors); + expect(result.errors.map(String)).toEqual([]); + expect(errors.map(String)).toEqual([]); + expectAllStampedAndGone(app.out, before, 2); + }); + } +}); + +// Vite builds a worker through its OWN sub-build and then copies the worker code into the main output while +// REGENERATING the worker's `.map` (Vite 8) or emitting both after our generateBundle (Vite 7): the worker file is +// stamped without its map carrying the id, or not stamped at all. The upload catches up the build's OWN unkeyed +// script maps (inject is idempotent on an already-stamped bundle and puts its id in the map). +describeReal('Vite workers: the worker bundle and its map carry the same debug-id', () => { + const workerApp = (name: string, form: 'url' | 'query'): { dir: string; out: string } => { + const app = makeApp(name, { lazy: false }); + writeFileSync(join(app.dir, 'w.js'), "postMessage('worker-ok');\n"); + writeFileSync( + join(app.dir, 'index.js'), + form === 'url' + ? "const w = new Worker(new URL('./w.js', import.meta.url), { type: 'module' });\nw.onmessage = (e) => console.log(e.data);\n" + : "import W from './w.js?worker';\nconst w = new W();\nw.onmessage = (e) => console.log(e.data);\n", + ); + return app; + }; + const idOf = (code: string): string | undefined => + /\/\/# debugId=([0-9a-f-]{36})/.exec(code)?.[1]; + + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + for (const form of ['url', 'query'] as const) { + for (const failOnError of [true, false]) { + it(`${label}, ${form} worker (failOnError ${failOnError}): stamped, same id in its map, uploaded and deleted`, async () => { + const app = workerApp( + `vite-worker-${label.replace(/\W+/g, '')}-${form}-${failOnError}`, + form, + ); + const before = requests.length; + const errors: unknown[] = []; + // Keep the maps for the first build so their ids can be compared. + await build( + viteConfig(app, [ + bugseeVite({ + failOnError, + deleteMaps: false, + onError: (e: unknown) => errors.push(e), + onNotice: () => undefined, + }), + ]), + ); + expect(errors.map(String)).toEqual([]); + expect(requests.length, 'uploaded').toBeGreaterThan(before); + const files = readdirSync(join(app.out, 'assets')); + const bundles = files.filter((f) => f.endsWith('.js')); + expect(bundles.length).toBeGreaterThanOrEqual(2); // main + worker + for (const bundle of bundles) { + const id = idOf(readFileSync(join(app.out, 'assets', bundle), 'utf8')); + expect(id, `${bundle} stamped`).toBeDefined(); + const map = JSON.parse( + readFileSync(join(app.out, 'assets', `${bundle}.map`), 'utf8'), + ) as { debugId?: string }; + expect(map.debugId, `${bundle}.map carries the same id`).toBe(id); + } + // And with the default (delete after a confirmed upload) nothing is left behind. + const app2 = workerApp( + `vite-worker-del-${label.replace(/\W+/g, '')}-${form}-${failOnError}`, + form, + ); + await build(viteConfig(app2, [bugseeVite({ failOnError, onNotice: () => undefined })])); + expect( + (readdirSync(join(app2.out, 'assets')) as string[]).filter((f) => f.endsWith('.map')), + ).toEqual([]); + }); + } + } + } +}); + +// A plugin that emits its own script + a map that is not a source map (after our stamp) must cost the build nothing: +// the real CLI rejects a batch containing a non-object map, which used to lose the upload of every stamped map. +describeReal('Vite: an own script with a broken map does not cost the other maps', () => { + const extPlugin = (map: string): VitePlugin => ({ + name: 'emit-ext', + generateBundle: { + order: 'post', + handler() { + (this as unknown as { emitFile(f: object): void }).emitFile({ + type: 'asset', + fileName: 'ext.js', + source: 'ext();\n//# sourceMappingURL=ext.js.map\n', + }); + (this as unknown as { emitFile(f: object): void }).emitFile({ + type: 'asset', + fileName: 'ext.js.map', + source: map, + }); + }, + }, + }); + for (const [label, build] of [ + ['Vite 8', viteBuild], + ['Vite 7', vite7Build], + ] as const) { + for (const bad of ['', 'not json', '[]', 'null']) { + for (const failOnError of [true, false]) { + it(`${label}, map ${JSON.stringify(bad)} (failOnError ${failOnError}): the main maps still upload and are deleted`, async () => { + const app = makeApp( + `vite-badmap-${label.replace(/\W+/g, '')}-${bad.length}-${failOnError}-${Math.abs(bad.charCodeAt(0) || 0)}`, + { lazy: false }, + ); + const before = requests.length; + const errors: unknown[] = []; + await build( + viteConfig(app, [ + bugseeVite({ + failOnError, + onError: (e: unknown) => errors.push(e), + onNotice: () => undefined, + }), + extPlugin(bad), + ]), + ); + expect(errors.map(String)).toEqual([]); + expect(requests.length, 'uploaded').toBeGreaterThan(before); + const files = readdirSync(app.out, { recursive: true }) as string[]; + expect(files.filter((f) => f.endsWith('.map'))).toEqual(['ext.js.map']); + expect(readFileSync(join(app.out, 'ext.js.map'), 'utf8')).toBe(bad); + }); + } + } + } +}); + +// N Rollup outputs written CONCURRENTLY into one directory: each uploads and deletes ITS OWN maps, once, and none +// reports another's maps as foreign. +describeReal('several Rollup outputs written concurrently into one directory', () => { + it("uploads once per output (not N times everything) and never says another output's maps are foreign", async () => { + const app = makeApp('rollup-many-outputs', { lazy: false }); + const names = ['a', 'b', 'c', 'd', 'e', 'f']; + const before = requests.length; + const notices: string[] = []; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await Promise.all( + names.map((n) => + bundle.write({ + file: join(app.out, `${n}.js`), + format: 'iife', + name: `app_${n}`, + sourcemap: true, + }), + ), + ); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect(notices.filter((m) => m.includes('not produced by this build'))).toEqual([]); + const files = readdirSync(app.out); + expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); + expect(files.filter((f) => f.endsWith('.js')).sort()).toEqual(names.map((n) => `${n}.js`)); + // every output's map was uploaded exactly once (by debug-id), not merely "some upload happened" + for (const n of names) { + const id = debugIdOf(join(app.out, `${n}.js`)); + expect(id).not.toBe(''); + expect(requests.slice(before).filter((r) => r.body.includes(id))).toHaveLength(1); + } + }); +}); + +describeReal('Rollup generate() before write() into the same directory', () => { + it('the written output still uploads and deletes its own maps (a generated-only output is not a sibling)', async () => { + const app = makeApp('rollup-generate-then-write', { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ ...pluginOptions(), onError: (e: unknown) => errors.push(e) }), + ], + }); + await bundle.generate({ dir: app.out, sourcemap: true }); // e.g. to measure size: never written + await bundle.write({ dir: app.out, sourcemap: true }); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect(requests.length).toBeGreaterThan(before); + expect((readdirSync(app.out) as string[]).filter((f) => f.endsWith('.map'))).toEqual([]); + }); +}); + +describeReal('one directory spelled several ways', () => { + it('outputs into `dist`, `dist/`, a symlink to it and a relative spelling coordinate as ONE directory', async () => { + const app = makeApp('rollup-spellings', { lazy: false }); + const link = `${app.out}-link`; + mkdirSync(app.out); // first: Rollup creating a directory through a still-dangling link races the others + symlinkSync(app.out, link); + const spellings = [app.out, `${app.out}/`, link, relative(process.cwd(), app.out)]; + const before = requests.length; + const notices: string[] = []; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await Promise.all( + spellings.map((dir, i) => + bundle.write({ + dir, + entryFileNames: `s${i}.js`, + format: 'iife', + name: `s${i}`, + sourcemap: true, + }), + ), + ); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect(notices.filter((m) => m.includes('not produced by this build'))).toEqual([]); + expect((readdirSync(app.out) as string[]).filter((f) => f.endsWith('.map'))).toEqual([]); + for (let i = 0; i < spellings.length; i++) { + const id = debugIdOf(join(app.out, `s${i}.js`)); + expect(id).not.toBe(''); + expect(requests.slice(before).filter((r) => r.body.includes(id))).toHaveLength(1); + } + }); +}); + +describeReal('a mapped and an unmapped output into one directory under failOnError', () => { + it('the unmapped output has nothing to do and does not fail the build', async () => { + const app = makeApp('rollup-mapped-unmapped', { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + failOnError: true, + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await Promise.all([ + bundle.write({ + dir: app.out, + entryFileNames: 'm.js', + format: 'iife', + name: 'm', + sourcemap: true, + }), + bundle.write({ + dir: app.out, + entryFileNames: 'u.js', + format: 'iife', + name: 'u', + sourcemap: false, + }), + ]); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect((readdirSync(app.out) as string[]).filter((f) => f.endsWith('.map'))).toEqual([]); + // the mapped output really uploaded its map, once; the unmapped one uploaded nothing + const id = debugIdOf(join(app.out, 'm.js')); + expect(id).not.toBe(''); + expect(requests.slice(before)).toHaveLength(1); + expect(requests.slice(before)[0]?.body.includes(id)).toBe(true); + }); +}); + +describeReal('a generate()-only output is not a sibling', () => { + it('an unmapped write after a never-written mapped generate() still fails under failOnError', async () => { + const app = makeApp('rollup-generate-unmapped', { lazy: false }); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin({ ...pluginOptions(), failOnError: true })], + }); + await bundle.generate({ + dir: app.out, + entryFileNames: 'g.js', + format: 'iife', + name: 'g', + sourcemap: true, + }); + await expect( + bundle.write({ + dir: app.out, + entryFileNames: 'u.js', + format: 'iife', + name: 'u', + sourcemap: false, + }), + ).rejects.toThrow(/no source maps with a debug-ID were found/); + await bundle.close(); + }); +}); + +describeReal('a generate()-only output is not stamped', () => { + it('bundle.generate() with a missing CLI does not spawn it or fail under failOnError, while write() still fails', async () => { + const app = makeApp('rollup-generate-nocli', { lazy: false }); + const saved = process.env.BUGSEE_CLI_PATH; + process.env.BUGSEE_CLI_PATH = join(app.dir, 'no-such-bugsee-cli'); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin({ ...pluginOptions(), failOnError: true })], + }); + try { + const generated = await bundle.generate({ + dir: app.out, + format: 'iife', + name: 'g', + sourcemap: true, + }); + expect(generated.output.length).toBeGreaterThan(0); + // the same build that WRITES is stamped, so the missing CLI is a hard failure there + await expect( + bundle.write({ dir: app.out, format: 'iife', name: 'w', sourcemap: true }), + ).rejects.toThrow(); + } finally { + if (saved === undefined) { + delete process.env.BUGSEE_CLI_PATH; + } else { + process.env.BUGSEE_CLI_PATH = saved; + } + await bundle.close(); + } + }); +}); + +describeReal('an output into a nested directory of another output', () => { + it('the parent output neither uploads nor reports the nested output maps as foreign', async () => { + const app = makeApp('rollup-nested-dirs', { lazy: false }); + const before = requests.length; + const notices: string[] = []; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await Promise.all([ + bundle.write({ + dir: app.out, + entryFileNames: 'p.js', + format: 'iife', + name: 'p', + sourcemap: true, + }), + bundle.write({ + dir: join(app.out, 'b'), + entryFileNames: 'c.js', + format: 'iife', + name: 'c', + sourcemap: true, + }), + ]); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect(notices.filter((m) => m.includes('not produced by this build'))).toEqual([]); + expect( + readdirSync(app.out, { recursive: true }).filter((f) => String(f).endsWith('.map')), + ).toEqual([]); + expect(requests.length - before).toBeLessThanOrEqual(2); + }); +}); + +describeReal('a mapped output that FINISHED before an unmapped one, under failOnError', () => { + it('the later unmapped output has nothing to do and does not fail', async () => { + const app = makeApp('rollup-mapped-then-unmapped', { lazy: false }); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin({ ...pluginOptions(), failOnError: true })], + }); + await bundle.write({ + dir: app.out, + entryFileNames: 'm.js', + format: 'iife', + name: 'm', + sourcemap: true, + }); + await bundle.write({ + dir: app.out, + entryFileNames: 'u.js', + format: 'iife', + name: 'u', + sourcemap: false, + }); + await bundle.close(); + }); +}); + +describeReal('a finished sibling whose maps stay on disk (deleteMaps: false)', () => { + it('a later output does not upload them again or call them foreign', async () => { + const app = makeApp('rollup-finished-sibling', { lazy: false }); + const before = requests.length; + const notices: string[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + deleteMaps: false, + onNotice: (m: string) => notices.push(m), + }), + ], + }); + await bundle.write({ + dir: app.out, + entryFileNames: 'm.js', + format: 'iife', + name: 'm', + sourcemap: true, + }); + await bundle.write({ + dir: app.out, + entryFileNames: 'u.js', + format: 'iife', + name: 'u', + sourcemap: false, + }); + await bundle.close(); + expect(notices.filter((m) => m.includes('not produced by this build'))).toEqual([]); + expect(requests.slice(before)).toHaveLength(1); + expect(requests.slice(before)[0]?.body.includes(debugIdOf(join(app.out, 'm.js')))).toBe(true); + expect(readdirSync(app.out)).toContain('m.js.map'); // deleteMaps: false + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.real-build.test.ts index da0963891..f1a9a592e 100644 --- a/packages/bundler-plugin-core/src/plugin.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.real-build.test.ts @@ -35,8 +35,12 @@ let delayMs = 0; // with a reason; CI (or BUGSEE_REQUIRE_CLI=1) requires it, so a CI run can never go green testing less. const cli = resolveBugseeCli(); const cliProbe = cli.endsWith('.js') - ? spawnSync(process.execPath, [cli, '--version'], { encoding: 'utf8' }) - : spawnSync(cli, ['--version'], { encoding: 'utf8' }); + ? spawnSync(process.execPath, [cli, '--version'], { + encoding: 'utf8', + timeout: 15_000, + killSignal: 'SIGKILL', + }) + : spawnSync(cli, ['--version'], { encoding: 'utf8', timeout: 15_000, killSignal: 'SIGKILL' }); const cliAvailable = cliProbe.status === 0; const cliRequired = process.env.CI !== undefined || process.env.BUGSEE_REQUIRE_CLI !== undefined; if (!cliAvailable && !cliRequired) { @@ -175,10 +179,14 @@ describeReal('real Rspack build', () => { expectUploaded(app.out, before); }); - it('REFUSES an SRI build: nothing is stamped or uploaded and the maps stay', async () => { + it('stamps IN the build, so a page pinning a hash the build cannot satisfy is REPORTED (the build still uploads)', async () => { + // Since the in-build stamp (Rspack stamps at PROCESS_ASSETS_STAGE_DEV_TOOLING + 1) nothing is rewritten + // after emit, so the post-emit SRI refusal no longer applies. What can still be wrong is a pin that + // never matched (here: a hand-written page with a made-up hash), and the post-stamp integrity check + // says so instead of shipping it silently. The real-SRI-plugin builds are in + // plugin.in-build.real-build.test.ts. const app = makeApp('rspack-sri'); mkdirSync(app.out, { recursive: true }); - // What an SRI plugin leaves behind: a page pinning the hash of the entry script. writeFileSync( join(app.out, 'index.html'), '', @@ -197,10 +205,9 @@ describeReal('real Rspack build', () => { ], }), ); - expect(errors.map(String).join()).toContain('refusing to stamp debug-IDs'); - expect(requests.length).toBe(before); - expect(readFileSync(join(app.out, 'main.js'), 'utf8')).not.toContain('debugId'); - expect(existsSync(join(app.out, 'main.js.map'))).toBe(true); + expect(errors.map(String).join()).toContain('no longer matches the integrity hash'); + expect(requests.length).toBeGreaterThan(before); + expect(readFileSync(join(app.out, 'main.js'), 'utf8')).toContain('debugId'); }); it('a build with a compile error uploads nothing', async () => { diff --git a/packages/bundler-plugin-core/src/plugin.stamp.test.ts b/packages/bundler-plugin-core/src/plugin.stamp.test.ts new file mode 100644 index 000000000..659089a10 --- /dev/null +++ b/packages/bundler-plugin-core/src/plugin.stamp.test.ts @@ -0,0 +1,1122 @@ +import type { UnpluginOptions } from 'unplugin'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { BugseePluginOptions } from './resolve'; + +// Hook wiring for stamping INSIDE the build on Rspack (processAssets), and on Vite / Rollup +// (generateBundle). The stamp itself is stubbed: stamp-assets.test.ts runs the real CLI and +// plugin.in-build.real-build.test.ts runs real Vite / Rollup / Rspack builds end to end. +const { uploadSpy } = vi.hoisted(() => ({ + uploadSpy: vi.fn(async (_resolved: unknown, _outDir: string, _deps?: unknown) => undefined), +})); +vi.mock('./resolve', async (importOriginal) => ({ + ...(await importOriginal()), + runPluginUpload: uploadSpy, +})); +const { stampSpy } = vi.hoisted(() => ({ + stampSpy: vi.fn(async (_store: unknown, _options?: unknown) => ({ stamped: [] as string[] })), +})); +vi.mock('./stamp-assets', async (importOriginal) => ({ + ...(await importOriginal()), + stampAssets: stampSpy, +})); + +const { bugseeUnpluginFactory } = await import('./plugin'); +const { StampVerificationError } = await import('./stamp-assets'); +const outsideError = () => + new StampVerificationError([ + { name: '../maps/a.js.map', reason: 'lies outside the output directory', outside: true }, + ]); +const makePlugin = (options?: BugseePluginOptions, framework = 'rollup'): UnpluginOptions => + bugseeUnpluginFactory(options, { framework } as never) as UnpluginOptions; + +/** The deps of the nth upload call. A missing call FAILS the test: "the upload was skipped" is never a pass. */ +const depsOf = (call: number) => { + const entry = uploadSpy.mock.calls[call]; + if (entry === undefined) { + throw new Error( + `expected an upload call #${call}, but only ${uploadSpy.mock.calls.length} happened`, + ); + } + return entry[2] as { preStamped?: boolean; bundler?: unknown; stampedBundles?: string[] }; +}; + +beforeEach(() => { + uploadSpy.mockClear(); + stampSpy.mockReset(); + stampSpy.mockImplementation(async () => ({ stamped: [] })); +}); + +describe('rspack: stamps inside the compilation', () => { + const DEV_TOOLING = 500; + // Faithful: a Buffer source is NOT rewritten by RealContentHashPlugin, so the fake refuses one. + class RawSource { + constructor(readonly value: string) { + if (typeof value !== 'string') { + throw new TypeError('a Buffer source would keep stale content-hash references'); + } + } + } + + function rspackCompiler(options: { mode?: string; withApi?: boolean } = {}) { + const afterEmit: Array<() => Promise> = []; + const processAssets: Array<{ name: string; stage: number; fn: () => Promise }> = []; + const updated: Array<{ name: string; source: unknown }> = []; + const compilation = { + hooks: { + processAssets: { + tapPromise: (opts: { name: string; stage: number }, fn: () => Promise) => { + processAssets.push({ ...opts, fn }); + }, + }, + }, + getAssets: () => [{ name: 'main.js' }, { name: 'main.js.map' }], + getAsset: (name: string) => ({ source: { buffer: () => Buffer.from(`content of ${name}`) } }), + updateAsset: (name: string, source: unknown, info?: unknown) => { + updated.push({ name, source, info } as never); + }, + }; + const compilations: Array<(c: unknown) => void> = []; + const compiler = { + options: { + output: { path: '/build/out' }, + mode: options.mode ?? 'production', + devtool: 'source-map', + }, + hooks: { + afterEmit: { tapPromise: (_n: string, fn: () => Promise) => afterEmit.push(fn) }, + thisCompilation: { tap: (_n: string, fn: (c: unknown) => void) => compilations.push(fn) }, + }, + ...(options.withApi === false + ? {} + : { + rspack: { + Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: DEV_TOOLING }, + sources: { RawSource }, + DefinePlugin: class { + apply() {} + }, + }, + }), + }; + return { + compiler, + compilation, + processAssets, + updated, + afterEmit: () => afterEmit[0]?.(), + afterEmitWith: (c: unknown) => (afterEmit[0] as (c: unknown) => Promise)(c), + compile: async () => { + // Each compilation runs ITS OWN processAssets taps only (taps registered by earlier ones are gone). + const first = processAssets.length; + for (const fn of compilations) { + fn(compilation); + } + for (const tap of processAssets.slice(first)) { + await tap.fn(); + } + }, + /** A compilation that starts but never reaches its processAssets stage (an earlier error). */ + startOnly: () => { + for (const fn of compilations) { + fn(compilation); + } + }, + }; + } + const apply = (options: BugseePluginOptions, compiler: unknown): void => + (makePlugin(options, 'rspack').rspack as (c: unknown) => void)(compiler); + + it('taps processAssets one stage after the maps are emitted, before an SRI plugin hashes', async () => { + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + expect(r.processAssets).toHaveLength(1); + expect(r.processAssets[0]?.stage).toBe(DEV_TOOLING + 1); + expect(r.processAssets[0]?.name).toBe('bugsee'); + expect(stampSpy).toHaveBeenCalledOnce(); + }); + + it("the compilation asset store names a bundle's map from the asset info (related.sourceMap), string or array", async () => { + const seen: Array = []; + stampSpy.mockImplementation(async (store) => { + const st = store as { mapOf(n: string): string | undefined }; + seen.push( + st.mapOf('main.js'), + st.mapOf('other.js'), + st.mapOf('multi.js'), + st.mapOf('none.js'), + ); + return { stamped: [], maps: {} }; + }); + const r = rspackCompiler(); + const infos: Record = { + 'main.js': { related: { sourceMap: 'maps/main.js.map' } }, + 'other.js': { related: { sourceMap: null } }, + 'multi.js': { related: { sourceMap: ['m1.map', 'm2.map'] } }, + }; + (r.compilation as { getAsset: unknown }).getAsset = (name: string) => ({ + source: { buffer: () => Buffer.from('x') }, + info: infos[name], + }); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + expect(seen).toEqual(['maps/main.js.map', undefined, 'm1.map', undefined]); + }); + + it('the compilation store strips ONLY ?query (webpack keeps # on disk), and writes back under the REAL name', async () => { + const seen: Record = {}; + stampSpy.mockImplementation(async (store) => { + const st = store as { + names(): string[]; + read(n: string): Buffer; + update(n: string, c: Buffer): void; + mapOf(n: string): string | undefined; + }; + seen.names = st.names(); + seen.read = st.read('main.js').toString(); + seen.map = st.mapOf('main.js'); + st.update('main.js', Buffer.from('stamped')); + st.update('main.js.map', Buffer.from('{}')); + return { stamped: ['main.js'], maps: {}, bundles: 1 }; + }); + const r = rspackCompiler(); + (r.compilation as Record).getAssets = () => [ + { name: 'main.js?h1' }, + { name: 'main.js.map?h2' }, + { name: 'dup.js?a' }, + { name: 'dup.js?b' }, + { name: 'a#1.js?z' }, + ]; + (r.compilation as Record).getAsset = (name: string) => ({ + source: { buffer: () => Buffer.from(`content of ${name}`) }, + info: name === 'main.js?h1' ? { related: { sourceMap: 'main.js.map?h2' } } : undefined, + }); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + // dup.js?a and dup.js?b would collide once cleaned: both keep their real (unmatchable) names. + expect(seen.names).toEqual(['main.js', 'main.js.map', 'dup.js?a', 'dup.js?b', 'a#1.js']); + expect(seen.read).toBe('content of main.js?h1'); + expect(seen.map).toBe('main.js.map'); + expect(r.updated.map((u) => u.name)).toEqual(['main.js?h1', 'main.js.map?h2']); + }); + + it('uploads without re-injecting after emit (preStamped), naming the bundles it stamped', async () => { + stampSpy.mockImplementation(async () => ({ + stamped: ['main.js'], + maps: { 'main.js': 'm/main.js.map' }, + })); + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + await r.afterEmit(); + expect(depsOf(0)?.preStamped).toBe(true); + expect(depsOf(0)?.stampedBundles).toEqual(['main.js']); + expect((depsOf(0) as { stampedMaps?: unknown }).stampedMaps).toEqual({ + 'main.js': 'm/main.js.map', + }); + }); + + it('reads and writes the compilation asset table, through rspack own RawSource', async () => { + stampSpy.mockImplementation(async (store) => { + const s = store as { + names(): string[]; + read(n: string): Buffer; + update(n: string, c: Buffer): void; + }; + expect(s.names()).toEqual(['main.js', 'main.js.map']); + expect(s.read('main.js').toString()).toBe('content of main.js'); + s.update('main.js', Buffer.from('stamped')); + return { stamped: ['main.js'] }; + }); + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + expect(r.updated[0]?.source).toBeInstanceOf(RawSource); + expect((r.updated[0]?.source as RawSource).value).toBe('stamped'); + }); + + it('passes the dry-run flag on', async () => { + const r = rspackCompiler(); + apply({ appToken: 'tok', dryRun: true }, r.compiler); + await r.compile(); + expect(stampSpy.mock.calls[0]?.[1]).toEqual({ dryRun: true }); + }); + + it('falls back to the post-emit path (SRI refusal included) when the stamp fails', async () => { + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli exited 20'); + }); + const onError = vi.fn(); + const r = rspackCompiler(); + apply({ appToken: 'tok', onError }, r.compiler); + await r.compile(); + await r.afterEmit(); + expect(onError).toHaveBeenCalledOnce(); + expect(depsOf(0)?.preStamped).toBe(false); + }); + + it('fails the compilation under failOnError', async () => { + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli exited 20'); + }); + const r = rspackCompiler(); + apply({ appToken: 'tok', failOnError: true }, r.compiler); + await expect(r.compile()).rejects.toThrow(/exited 20/); + }); + + it('starts each compilation unstamped (watch mode)', async () => { + const r = rspackCompiler(); + apply({ appToken: 'tok', onError: () => undefined }, r.compiler); + await r.compile(); + await r.afterEmit(); + stampSpy.mockImplementation(async () => { + throw new Error('second build failed to stamp'); + }); + await r.compile(); + await r.afterEmit(); + expect(stampSpy).toHaveBeenCalledTimes(2); // once per compilation, not once per accumulated tap + expect(depsOf(1)?.preStamped).toBe(false); + }); + + it('a compilation that never reaches the stamp stage is not vouched for by the previous one', async () => { + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + r.startOnly(); + await r.afterEmit(); + expect(depsOf(0)?.preStamped).toBe(false); + }); + + it('does not stamp a development build that is not uploaded (rspack serve/watch), and does when uploadInDevelopment is set', async () => { + const dev = rspackCompiler({ mode: 'development' }); + apply({ appToken: 'tok', onNotice: () => undefined }, dev.compiler); + await dev.compile(); + expect(dev.processAssets).toHaveLength(0); + expect(stampSpy).not.toHaveBeenCalled(); + + const optIn = rspackCompiler({ mode: 'development' }); + apply({ appToken: 'tok', uploadInDevelopment: true }, optIn.compiler); + await optIn.compile(); + expect(optIn.processAssets).toHaveLength(1); + + for (const mode of ['production', 'none']) { + const r = rspackCompiler({ mode }); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + expect(r.processAssets).toHaveLength(1); + } + }); + + it('hands updateAsset a string, byte-for-byte what was stamped (multi-byte text survives)', async () => { + stampSpy.mockImplementation(async (store) => { + (store as { update(n: string, c: Buffer): void }).update( + 'main.js', + Buffer.from('héllo ✓ 日本 stamped', 'utf8'), + ); + return { stamped: ['main.js'], maps: {}, bundles: 1 }; + }); + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + expect(typeof (r.updated[0]?.source as { value: unknown }).value).toBe('string'); + expect((r.updated[0]?.source as { value: string }).value).toBe('héllo ✓ 日本 stamped'); + }); + + it('refuses bytes that are not valid UTF-8 (never corrupts an asset): the stamp fails and the post-emit path takes over', async () => { + stampSpy.mockImplementation(async (store) => { + (store as { update(n: string, c: Buffer): void }).update( + 'main.js', + Buffer.from([0xff, 0xfe, 0x00, 0x61]), + ); + return { stamped: ['main.js'], maps: {}, bundles: 1 }; + }); + const onError = vi.fn(); + const r = rspackCompiler(); + apply({ appToken: 'tok', onError }, r.compiler); + await r.compile(); + await r.afterEmit(); + expect(r.updated).toEqual([]); + expect(String(onError.mock.calls[0]?.[0])).toContain('UTF-8'); + expect(depsOf(0)?.preStamped).toBe(false); + }); + + it('the store check refuses invalid UTF-8 WITHOUT writing, and passes text; a BOM is preserved', async () => { + const outcome: string[] = []; + stampSpy.mockImplementation(async (store) => { + const st = store as { check(n: string, c: Buffer): void; update(n: string, c: Buffer): void }; + st.check('main.js', Buffer.from('fine ✓', 'utf8')); + outcome.push('text ok'); + try { + st.check('main.js', Buffer.from([0xc3, 0x28])); + } catch (error) { + outcome.push(String(error)); + } + st.update('main.js', Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from('bom')])); + return { stamped: ['main.js'], maps: {}, bundles: 1 }; + }); + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + expect(outcome[0]).toBe('text ok'); + expect(outcome[1]).toContain('not valid UTF-8'); + expect(r.updated).toHaveLength(1); // only the explicit update wrote anything + expect((r.updated[0]?.source as { value: string }).value).toBe('\uFEFFbom'); + }); + + it('after [contenthash] renames, the on-disk re-check is told the FINAL script names (the stamp ran before the rename)', async () => { + stampSpy.mockImplementation(async () => ({ + stamped: ['main.OLDHASH.js'], + maps: { 'main.OLDHASH.js': 'main.OLDHASH.js.map' }, + bundles: 1, + })); + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + await (r.afterEmitWith as (c: unknown) => Promise)({ + getAssets: () => [ + { name: 'main.NEWHASH.js', info: { bugseeStamped: true } }, + { name: 'main.NEWHASH.js.map' }, + { name: 'x.css' }, + { name: 'q.js?h', info: { bugseeStamped: true } }, + { name: 'sw.js' }, // emitted after the stamp stage: never staged, never stamped + { name: 'sw.js.map' }, + ], + }); + const deps = depsOf(0) as { stampedBundles?: string[]; stampedMaps?: unknown }; + expect(deps.stampedBundles).toEqual(['main.NEWHASH.js', 'q.js']); + expect(deps.stampedMaps).toBeUndefined(); + }); + + it('marks every asset it writes back (asset info survives the contenthash rename)', async () => { + stampSpy.mockImplementation(async (store) => { + (store as { update(n: string, c: Buffer): void }).update('main.js', Buffer.from('stamped')); + return { stamped: ['main.js'], maps: {}, bundles: 1 }; + }); + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + expect((r.updated[0] as { info?: unknown }).info).toEqual({ bugseeStamped: true }); + }); + + it('does not stamp for a disabled plugin', async () => { + const r = rspackCompiler(); + apply({ disabled: true }, r.compiler); + await r.compile(); + expect(r.processAssets).toHaveLength(0); + }); + + it('keeps the post-emit path on a compiler without the rspack API or thisCompilation', async () => { + const r = rspackCompiler({ withApi: false }); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + await r.afterEmit(); + expect(stampSpy).not.toHaveBeenCalled(); + expect(depsOf(0)?.preStamped).toBe(false); + }); +}); + +describe('vite / rollup: stamps in generateBundle, before anything is written or hashed', () => { + type Handler = ( + output: { dir?: string; file?: string }, + bundle: Record, + ) => Promise; + type Hook = { order?: string; handler: Handler }; + const hooksOf = (p: UnpluginOptions, kind: 'vite' | 'rollup') => + p[kind] as unknown as { generateBundle: Hook; writeBundle: (o: object) => Promise }; + + const bundle = (): Record => ({ + 'a.js': { type: 'chunk', fileName: 'a.js', code: 'x', map: {} }, + 'a.js.map': { type: 'asset', fileName: 'a.js.map', source: '{}' }, + }); + + for (const kind of ['vite', 'rollup'] as const) { + describe(kind, () => { + it('runs FIRST (order: pre), so Vite html build and later SRI hashing see stamped bytes', () => { + expect(hooksOf(makePlugin({ appToken: 'tok' }), kind).generateBundle.order).toBe('pre'); + }); + + it('stamps the output bundle through a store over it', async () => { + stampSpy.mockImplementation(async (store) => { + const s = store as { + names(): string[]; + read(n: string): Buffer; + update(n: string, c: Buffer): void; + }; + expect(s.names()).toEqual(['a.js', 'a.js.map']); + expect(s.read('a.js').toString()).toBe('x'); + s.update('a.js', Buffer.from('stamped')); + return { stamped: ['a.js'] }; + }); + const b = bundle(); + await hooksOf(makePlugin({ appToken: 'tok' }), kind).generateBundle.handler( + { dir: '/out' }, + b, + ); + expect((b['a.js'] as { code: string }).code).toBe('stamped'); + }); + + it('then uploads without re-injecting, once: the flag is consumed by the write', async () => { + stampSpy.mockImplementation(async () => ({ stamped: ['a.js'] })); + const p = makePlugin({ appToken: 'tok' }); + const h = hooksOf(p, kind); + const output = { dir: '/out' }; + await h.generateBundle.handler(output, bundle()); + await h.writeBundle(output); + await h.writeBundle(output); // a write with no generateBundle before it: not stamped + expect(depsOf(0)?.preStamped).toBe(true); + // The on-disk re-check is told exactly which bundles the stamp wrote. + expect(depsOf(0)?.stampedBundles).toEqual(['a.js']); + expect(depsOf(1)?.preStamped).toBeUndefined(); + expect(depsOf(1)?.stampedBundles).toBeUndefined(); + }); + + it('tracks each output on its own', async () => { + stampSpy.mockImplementationOnce(async () => ({ stamped: [] })); + stampSpy.mockImplementationOnce(async () => { + throw new Error('second output failed'); + }); + const p = makePlugin({ appToken: 'tok', onError: () => undefined }); + const h = hooksOf(p, kind); + const [first, second] = [{ dir: '/a' }, { file: '/b/out.js' }]; + await h.generateBundle.handler(first, bundle()); + await h.generateBundle.handler(second, bundle()); + await h.writeBundle(first); + await h.writeBundle(second); + expect(depsOf(0)?.preStamped).toBe(true); + expect(depsOf(1)?.preStamped).toBeUndefined(); + }); + + it("two outputs written CONCURRENTLY into one directory never consume each other's answer", async () => { + // A stamped output beside one that could not be stamped (inline maps), same folder. + const p = makePlugin({ appToken: 'tok', onNotice: () => undefined }); + const h = hooksOf(p, kind); + const [stamped, unstamped] = [{ file: '/out/a.js' }, { file: '/out/b.js' }]; + const inline = bundle(); + delete inline['a.js.map']; + await h.generateBundle.handler(stamped, bundle()); + await h.generateBundle.handler(unstamped, inline); + // Writes land in the opposite order of the generateBundles. + await h.writeBundle(unstamped); + await h.writeBundle(stamped); + expect(depsOf(0)?.preStamped).toBeUndefined(); // the unstamped output keeps the post-emit path + SRI refusal + expect(depsOf(1)?.preStamped).toBe(true); + }); + + it('a write whose generateBundle used a different options object is not vouched for', async () => { + const h = hooksOf(makePlugin({ appToken: 'tok' }), kind); + await h.generateBundle.handler({ dir: '/out' }, bundle()); + await h.writeBundle({ dir: '/out' }); + expect(depsOf(0)?.preStamped).toBeUndefined(); + }); + + it('a stale success never vouches for the next build of the same output', async () => { + const p = makePlugin({ appToken: 'tok', onError: () => undefined }); + const h = hooksOf(p, kind); + const output = { dir: '/out' }; + await h.generateBundle.handler(output, bundle()); + // (the write of build 1 never happened) build 2's stamp fails: + stampSpy.mockImplementationOnce(async () => { + throw new Error('boom'); + }); + await h.generateBundle.handler(output, bundle()); + await h.writeBundle(output); + expect(depsOf(0)?.preStamped).toBeUndefined(); + }); + + it('a build that cannot be stamped in memory is not vouched for by the previous stamp either', async () => { + const h = hooksOf(makePlugin({ appToken: 'tok', onNotice: () => undefined }), kind); + const output = { dir: '/out' }; + await h.generateBundle.handler(output, bundle()); // stamped; its write never happened + const unstampable = bundle(); + delete unstampable['a.js.map']; + await h.generateBundle.handler(output, unstampable); + await h.writeBundle(output); + expect(depsOf(0)?.preStamped).toBeUndefined(); + }); + + it('falls back to the post-emit path, reported, when the stamp fails', async () => { + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli exited 20'); + }); + const onError = vi.fn(); + const h = hooksOf(makePlugin({ appToken: 'tok', onError }), kind); + const output = { dir: '/out' }; + await h.generateBundle.handler(output, bundle()); + await h.writeBundle(output); + expect(onError).toHaveBeenCalledOnce(); + expect(depsOf(0)?.preStamped).toBeUndefined(); + }); + + it('says what happens next when a stamp fails and no handler is set', async () => { + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli exited 20'); + }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + await hooksOf(makePlugin({ appToken: 'tok' }), kind).generateBundle.handler( + { dir: '/out' }, + bundle(), + ); + expect(String(warn.mock.calls[0]?.[0])).toMatch( + /in-build debug-ID stamping failed; falling back to stamping after emit: .*exited 20/, + ); + } finally { + warn.mockRestore(); + } + }); + + it('fails the build under failOnError', async () => { + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli exited 20'); + }); + await expect( + hooksOf(makePlugin({ appToken: 'tok', failOnError: true }), kind).generateBundle.handler( + { dir: '/out' }, + bundle(), + ), + ).rejects.toThrow(/exited 20/); + }); + + it('passes the dry-run flag on', async () => { + await hooksOf(makePlugin({ appToken: 'tok', dryRun: true }), kind).generateBundle.handler( + { dir: '/out' }, + bundle(), + ); + expect(stampSpy.mock.calls[0]?.[1]).toEqual({ dryRun: true }); + }); + + it('does nothing for a disabled plugin, or an output with no directory', async () => { + await hooksOf(makePlugin({ disabled: true }), kind).generateBundle.handler( + { dir: '/out' }, + bundle(), + ); + await hooksOf(makePlugin({ appToken: 'tok' }), kind).generateBundle.handler({}, bundle()); + expect(stampSpy).not.toHaveBeenCalled(); + }); + + it('a chunk whose map is not a bundle asset cannot be stamped in memory: post-emit fallback, said once', async () => { + const notices: string[] = []; + const h = hooksOf( + makePlugin({ appToken: 'tok', onNotice: (m: string) => notices.push(m) }), + kind, + ); + const b = bundle(); + delete b['a.js.map']; + const output = { dir: '/out' }; + await h.generateBundle.handler(output, b); + await h.generateBundle.handler(output, b); + await h.writeBundle(output); + expect(stampSpy).not.toHaveBeenCalled(); + expect(notices).toHaveLength(1); + expect(notices[0]).toContain('a.js'); + expect(notices[0]).toContain('after emit'); + expect(depsOf(0)?.preStamped).toBeUndefined(); + }); + }); + } +}); + +describe('a map the stamp can never reach is not retried after emit (that would half-stamp)', () => { + const hooks = (p: UnpluginOptions, kind: 'vite' | 'rollup') => + p[kind] as unknown as { + generateBundle: { handler: (o: object, b: Record) => Promise }; + writeBundle: (o: object) => Promise; + }; + const bundle = () => ({ + 'a.js': { type: 'chunk', fileName: 'a.js', code: 'x', map: {} }, + 'a.js.map': { type: 'asset', fileName: 'a.js.map', source: '{}' }, + }); + + for (const kind of ['vite', 'rollup'] as const) { + it(`${kind}: reported, and the write does NOT upload or inject; under failOnError the build fails`, async () => { + stampSpy.mockImplementation(async () => { + throw outsideError(); + }); + const onError = vi.fn(); + const h = hooks(makePlugin({ appToken: 'tok', onError }), kind); + const output = { dir: '/out' }; + await h.generateBundle.handler(output, bundle()); + await h.writeBundle(output); + expect(String(onError.mock.calls[0]?.[0])).toContain('outside the output directory'); + expect(String(onError.mock.calls[0]?.[0])).not.toContain('falling back'); + expect(uploadSpy).not.toHaveBeenCalled(); + + const strict = hooks(makePlugin({ appToken: 'tok', failOnError: true }), kind); + await expect(strict.generateBundle.handler({ dir: '/o2' }, bundle())).rejects.toThrow( + /outside/, + ); + }); + } + + for (const hook of ['rspack', 'webpack'] as const) { + it(`${hook}: the afterEmit upload is skipped too`, async () => { + stampSpy.mockImplementation(async () => { + throw outsideError(); + }); + const compilations: Array<(c: unknown) => void> = []; + const taps: Array<() => Promise> = []; + const after: Array<() => Promise> = []; + const compilation = { + hooks: { + processAssets: { tapPromise: (_o: unknown, fn: () => Promise) => taps.push(fn) }, + }, + getAssets: () => [], + getAsset: () => undefined, + updateAsset: () => undefined, + }; + const compiler = { + options: { output: { path: '/o' }, mode: 'production', devtool: 'source-map' }, + hooks: { + afterEmit: { tapPromise: (_n: string, fn: () => Promise) => after.push(fn) }, + thisCompilation: { tap: (_n: string, fn: (c: unknown) => void) => compilations.push(fn) }, + }, + [hook]: { + Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: 500 }, + sources: { RawSource: class {} }, + }, + }; + ( + makePlugin({ appToken: 'tok', onError: () => undefined, onNotice: () => undefined }, hook)[ + hook + ] as (c: unknown) => void + )(compiler); + for (const fn of compilations) fn(compilation); + for (const t of taps) await t(); + await after[0]?.(); + expect(uploadSpy).not.toHaveBeenCalled(); + }); + } +}); + +describe("the plugin hands the build's emitted names to the upload (ownFiles)", () => { + it('vite/rollup: the final bundle at writeBundle', async () => { + for (const kind of ['vite', 'rollup'] as const) { + uploadSpy.mockClear(); + const p = makePlugin({ appToken: 'tok' })[kind] as unknown as { + writeBundle: (o: object, b?: object) => Promise; + }; + await p.writeBundle({ dir: '/out' }, { 'a.js': {}, 'src/a.css.map': {} }); + expect((uploadSpy.mock.calls[0]?.[2] as { ownFiles?: string[] }).ownFiles).toEqual([ + 'a.js', + 'src/a.css.map', + ]); + uploadSpy.mockClear(); + await p.writeBundle({ dir: '/out' }); + expect((uploadSpy.mock.calls[0]?.[2] as { ownFiles?: string[] }).ownFiles).toBeUndefined(); + } + }); + + for (const hook of ['rspack', 'webpack'] as const) { + it(`${hook}: the compilation assets at afterEmit`, async () => { + const after: Array<(c?: unknown) => Promise> = []; + const compiler = { + options: { output: { path: '/o' }, mode: 'production', devtool: 'source-map' }, + hooks: { + afterEmit: { + tapPromise: (_n: string, fn: (c?: unknown) => Promise) => after.push(fn), + }, + }, + }; + (makePlugin({ appToken: 'tok' }, hook)[hook] as (c: unknown) => void)(compiler); + await after[0]?.({ getAssets: () => [{ name: 'main.js' }, { name: 'maps/main.js.map' }] }); + expect((uploadSpy.mock.calls[0]?.[2] as { ownFiles?: string[] }).ownFiles).toEqual([ + 'main.js', + 'maps/main.js.map', + ]); + uploadSpy.mockClear(); + await after[0]?.(); + expect((uploadSpy.mock.calls[0]?.[2] as { ownFiles?: string[] }).ownFiles).toBeUndefined(); + }); + } +}); + +describe('an in-build stamp that staged NO bundle although the build emitted scripts never claims preStamped', () => { + it('falls back to the post-emit path and says so (never a silent skip)', async () => { + stampSpy.mockImplementation(async () => ({ stamped: [], maps: {}, bundles: 0 })); + const notices: string[] = []; + const hooks = makePlugin({ appToken: 'tok', onNotice: (m: string) => notices.push(m) }) + .rollup as unknown as { + generateBundle: { handler: (o: object, b: Record) => Promise }; + writeBundle: (o: object, b?: object) => Promise; + }; + const output = { dir: '/out' }; + await hooks.generateBundle.handler(output, { + 'a.js?h': { type: 'asset', fileName: 'a.js?h', source: 'x' }, + }); + await hooks.writeBundle(output); + expect((uploadSpy.mock.calls[0]?.[2] as { preStamped?: boolean }).preStamped).toBeUndefined(); + expect(notices.join('\n')).toContain('a.js?h'); + expect(notices.join('\n')).toContain('after emit'); + }); + + it('a build with no scripts at all (css only) is simply pre-stamped, with no notice', async () => { + stampSpy.mockImplementation(async () => ({ stamped: [], maps: {}, bundles: 0 })); + const notices: string[] = []; + const hooks = makePlugin({ appToken: 'tok', onNotice: (m: string) => notices.push(m) }) + .rollup as unknown as { + generateBundle: { handler: (o: object, b: Record) => Promise }; + writeBundle: (o: object, b?: object) => Promise; + }; + const output = { dir: '/out' }; + await hooks.generateBundle.handler(output, { + 'a.css': { type: 'asset', fileName: 'a.css', source: 'x' }, + }); + await hooks.writeBundle(output); + expect((uploadSpy.mock.calls[0]?.[2] as { preStamped?: boolean }).preStamped).toBe(true); + expect(notices).toEqual([]); + }); +}); + +describe('webpack/Rspack: the zero-staged guard looks at the REAL asset names', () => { + it('says so when scripts exist but none staged (names the first), and runs the post-emit path', async () => { + stampSpy.mockImplementation(async () => ({ stamped: [], maps: {}, bundles: 0 })); + const notices: string[] = []; + const after: Array<(c?: unknown) => Promise> = []; + const taps: Array<() => Promise> = []; + const compilations: Array<(c: unknown) => void> = []; + const compilation = { + hooks: { + processAssets: { tapPromise: (_o: unknown, fn: () => Promise) => taps.push(fn) }, + }, + getAssets: () => [{ name: 'main.js?h' }, { name: 'main.js.map?h' }, { name: 'style.css' }], + getAsset: () => undefined, + updateAsset: () => undefined, + }; + const compiler = { + options: { output: { path: '/o' }, mode: 'production', devtool: 'source-map' }, + hooks: { + afterEmit: { + tapPromise: (_n: string, fn: (c?: unknown) => Promise) => after.push(fn), + }, + thisCompilation: { tap: (_n: string, fn: (c: unknown) => void) => compilations.push(fn) }, + }, + rspack: { + Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: 500 }, + sources: { RawSource: class {} }, + }, + }; + ( + makePlugin({ appToken: 'tok', onNotice: (m: string) => notices.push(m) }, 'rspack') + .rspack as (c: unknown) => void + )(compiler); + for (const fn of compilations) fn(compilation); + for (const t of taps) await t(); + await after[0]?.(compilation); + expect(notices.join('\n')).toContain('main.js'); + expect(notices.join('\n')).toContain('after emit'); + expect((uploadSpy.mock.calls[0]?.[2] as { preStamped?: boolean }).preStamped).toBe(false); + }); + + it('the store follows the compilation: an asset that disappears is no longer listed', async () => { + const seen: string[][] = []; + let assets = [{ name: 'a.js' }, { name: 'b.js' }]; + stampSpy.mockImplementation(async (store) => { + const st = store as { names(): string[] }; + seen.push(st.names()); + assets = [{ name: 'a.js' }]; + seen.push(st.names()); + return { stamped: [], maps: {}, bundles: 1 }; + }); + const compilations: Array<(c: unknown) => void> = []; + const taps: Array<() => Promise> = []; + const compilation = { + hooks: { + processAssets: { tapPromise: (_o: unknown, fn: () => Promise) => taps.push(fn) }, + }, + getAssets: () => assets, + getAsset: () => undefined, + updateAsset: () => undefined, + }; + const compiler = { + options: { output: { path: '/o' }, mode: 'production', devtool: 'source-map' }, + hooks: { + afterEmit: { tapPromise: () => undefined }, + thisCompilation: { tap: (_n: string, fn: (c: unknown) => void) => compilations.push(fn) }, + }, + rspack: { + Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: 500 }, + sources: { RawSource: class {} }, + }, + }; + (makePlugin({ appToken: 'tok' }, 'rspack').rspack as (c: unknown) => void)(compiler); + for (const fn of compilations) fn(compilation); + for (const t of taps) await t(); + expect(seen).toEqual([['a.js', 'b.js'], ['a.js']]); + }); +}); + +describe('the zero-staged guard: only ? ends a webpack extension (# is part of the name)', () => { + it('x.js#frag is not script-like, so no notice and the build stays pre-stamped', async () => { + stampSpy.mockImplementation(async () => ({ stamped: [], maps: {}, bundles: 0 })); + const notices: string[] = []; + const hooks = makePlugin({ appToken: 'tok', onNotice: (m: string) => notices.push(m) }) + .rollup as unknown as { + generateBundle: { handler: (o: object, b: Record) => Promise }; + writeBundle: (o: object, b?: object) => Promise; + }; + const output = { dir: '/out' }; + await hooks.generateBundle.handler(output, { + 'x.js#frag': { type: 'asset', fileName: 'x.js#frag', source: 'x' }, + }); + await hooks.writeBundle(output); + expect(notices).toEqual([]); + expect((uploadSpy.mock.calls[0]?.[2] as { preStamped?: boolean }).preStamped).toBe(true); + }); +}); + +describe('webpack: after [contenthash] renames, the on-disk re-check gets the FINAL script names', () => { + it('passes the final script asset names (query cut) and no stale map names', async () => { + stampSpy.mockImplementation(async () => ({ + stamped: ['m.OLD.js'], + maps: { 'm.OLD.js': 'm.OLD.js.map' }, + bundles: 1, + })); + const after: Array<(c?: unknown) => Promise> = []; + const taps: Array<() => Promise> = []; + const compilations: Array<(c: unknown) => void> = []; + const compilation = { + hooks: { + processAssets: { tapPromise: (_o: unknown, fn: () => Promise) => taps.push(fn) }, + }, + getAssets: () => [ + { name: 'm.NEW.js', info: { bugseeStamped: true } }, + { name: 'm.NEW.js.map' }, + { name: 'q.js?h', info: { bugseeStamped: true } }, + { name: 'sw.js' }, + ], + getAsset: () => undefined, + updateAsset: () => undefined, + }; + const compiler = { + options: { output: { path: '/o' }, mode: 'production', devtool: 'source-map' }, + hooks: { + afterEmit: { + tapPromise: (_n: string, fn: (c?: unknown) => Promise) => after.push(fn), + }, + thisCompilation: { tap: (_n: string, fn: (c: unknown) => void) => compilations.push(fn) }, + }, + webpack: { + Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: 500 }, + sources: { RawSource: class {} }, + }, + }; + ( + makePlugin({ appToken: 'tok', onNotice: () => undefined }, 'webpack').webpack as ( + c: unknown, + ) => void + )(compiler); + for (const fn of compilations) fn(compilation); + for (const t of taps) await t(); + await after[0]?.(compilation); + const deps = depsOf(0) as { stampedBundles?: string[]; stampedMaps?: unknown }; + expect(deps.stampedBundles).toEqual(['m.NEW.js', 'q.js']); + expect(deps.stampedMaps).toBeUndefined(); + }); +}); + +describe('vite/rollup: the on-disk re-check judges only stamped chunks that are still in the FINAL bundle', () => { + it('drops a stamped chunk a later plugin removed from the bundle', async () => { + stampSpy.mockImplementation(async () => ({ + stamped: ['a.js', 'gone.js'], + maps: { 'a.js': 'a.js.map', 'gone.js': 'gone.js.map' }, + bundles: 2, + })); + for (const kind of ['vite', 'rollup'] as const) { + uploadSpy.mockClear(); + const hooks = makePlugin({ appToken: 'tok' })[kind] as unknown as { + generateBundle: { handler: (o: object, b: Record) => Promise }; + writeBundle: (o: object, b?: object) => Promise; + }; + const output = { dir: '/out' }; + await hooks.generateBundle.handler(output, { + 'a.js': { type: 'chunk', fileName: 'a.js', code: 'x', map: {} }, + 'a.js.map': { type: 'asset', fileName: 'a.js.map', source: '{}' }, + }); + await hooks.writeBundle(output, { 'a.js': {}, 'a.js.map': {} }); // gone.js was deleted by a later generateBundle + const deps = depsOf(0) as { stampedBundles?: string[]; stampedMaps?: Record }; + expect(deps.stampedBundles).toEqual(['a.js']); + expect(deps.stampedMaps).toEqual({ 'a.js': 'a.js.map' }); + } + }); +}); + +describe("vite/rollup: without a final bundle the stamp's own names are used unchanged", () => { + it('passes stampedBundles and stampedMaps through when writeBundle gets no bundle', async () => { + stampSpy.mockImplementation(async () => ({ + stamped: ['a.js'], + maps: { 'a.js': 'a.js.map' }, + bundles: 1, + })); + const hooks = makePlugin({ appToken: 'tok' }).rollup as unknown as { + generateBundle: { handler: (o: object, b: Record) => Promise }; + writeBundle: (o: object, b?: object) => Promise; + }; + const output = { dir: '/out' }; + await hooks.generateBundle.handler(output, { + 'a.js': { type: 'chunk', fileName: 'a.js', code: 'x', map: {} }, + 'a.js.map': { type: 'asset', fileName: 'a.js.map', source: '{}' }, + }); + await hooks.writeBundle(output); + const deps = depsOf(0) as { stampedBundles?: string[]; stampedMaps?: Record }; + expect(deps.stampedBundles).toEqual(['a.js']); + expect(deps.stampedMaps).toEqual({ 'a.js': 'a.js.map' }); + }); +}); + +describe('outputs announce their names at generateBundle, so the first write already knows its siblings', () => { + const hooksOf2 = (kind: 'vite' | 'rollup') => + makePlugin({ appToken: 'tok', onNotice: () => undefined })[kind] as unknown as { + generateBundle: { + handler: (o: object, b: Record, isWrite?: boolean) => Promise; + }; + writeBundle: (o: object, b?: object) => Promise; + buildStart?: () => void; + }; + const bundleOf = (name: string) => ({ + [`${name}.js`]: { type: 'chunk', fileName: `${name}.js`, code: 'x', map: {} }, + [`${name}.js.map`]: { type: 'asset', fileName: `${name}.js.map`, source: '{}' }, + }); + const siblingsOf = (call: number) => + (uploadSpy.mock.calls[call]?.[2] as { siblingOwnFiles?: string[] }).siblingOwnFiles; + + for (const kind of ['vite', 'rollup'] as const) { + it(`${kind}: the first output to write is told the others' names; the last is told none`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + const [a, b] = [{ file: '/out/a.js' }, { file: '/out/b.js' }]; + await h.generateBundle.handler(a, bundleOf('a')); + await h.generateBundle.handler(b, bundleOf('b')); + await h.writeBundle(a, bundleOf('a')); + await h.writeBundle(b, bundleOf('b')); + expect(siblingsOf(0)?.slice().sort()).toEqual(['b.js', 'b.js.map']); + // a already finished, but its names stay known: its maps (left on disk by `deleteMaps: false`) are not b's + expect(siblingsOf(1)?.slice().sort()).toEqual(['a.js', 'a.js.map']); + }); + + it(`${kind}: an output that only GENERATED (bundle.generate never writes) cannot hide this one's own maps`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + await h.generateBundle.handler({ dir: '/out' }, bundleOf('a')); // generate(): same names, never written + const written = { dir: '/out' }; + await h.generateBundle.handler(written, bundleOf('a')); + await h.writeBundle(written, bundleOf('a')); + expect(siblingsOf(0)).toEqual([]); // a name this output emitted is never a "sibling's" + }); + + it(`${kind}: a generate()-only output (isWrite false) is never announced as a sibling`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + await h.generateBundle.handler({ dir: '/out' }, bundleOf('g'), false); + const written = { dir: '/out' }; + await h.generateBundle.handler(written, bundleOf('w'), true); + await h.writeBundle(written, bundleOf('w')); + expect(siblingsOf(0)).toEqual([]); + }); + + it(`${kind}: a generate()-only output (isWrite false) is not stamped at all: no CLI, no staging, no failOnError throw`, async () => { + stampSpy.mockReset(); + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli is missing'); + }); + const strict = makePlugin({ appToken: 'tok', failOnError: true, onNotice: () => undefined })[ + kind + ] as unknown as ReturnType; + await expect( + strict.generateBundle.handler({ dir: '/out' }, bundleOf('g'), false), + ).resolves.toBeUndefined(); + expect(stampSpy).not.toHaveBeenCalled(); + // the same output that WILL write is stamped, and its failure surfaces under failOnError + await expect( + strict.generateBundle.handler({ dir: '/out' }, bundleOf('g'), true), + ).rejects.toThrow(/bugsee-cli is missing/); + expect(stampSpy).toHaveBeenCalledOnce(); + }); + + it(`${kind}: an output written into a NESTED directory is a sibling under its relative path`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + const [parent, child] = [{ dir: '/out' }, { dir: '/out/b' }]; + await h.generateBundle.handler(parent, bundleOf('p')); + await h.generateBundle.handler(child, bundleOf('c')); + await h.writeBundle(parent, bundleOf('p')); + await h.writeBundle(child, bundleOf('c')); + expect(siblingsOf(0)?.slice().sort()).toEqual(['b/c.js', 'b/c.js.map']); + expect(siblingsOf(1)).toEqual([]); // the child's walk never sees the parent's files + }); + + it(`${kind}: an unmapped output after a mapped one FINISHED is told a sibling had maps (only for a real write)`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + const flag = (call: number) => + (uploadSpy.mock.calls[call]?.[2] as { siblingsHaveMaps?: boolean }).siblingsHaveMaps; + const [m, u] = [{ dir: '/out' }, { dir: '/out' }]; + await h.generateBundle.handler(m, bundleOf('m'), true); + await h.writeBundle(m, bundleOf('m')); + await h.generateBundle.handler(u, { 'u.js': bundleOf('u')['u.js'] }, true); + await h.writeBundle(u, { 'u.js': bundleOf('u')['u.js'] }); + expect(flag(0)).toBeUndefined(); // an output is not its own sibling + expect(flag(1)).toBe(true); + // a new build forgets it + h.buildStart?.(); + const lone = { dir: '/out' }; + await h.generateBundle.handler(lone, { 'l.js': bundleOf('l')['l.js'] }, true); + await h.writeBundle(lone, { 'l.js': bundleOf('l')['l.js'] }); + expect(flag(2)).toBeUndefined(); + }); + + it(`${kind}: an output WITHOUT maps does not count as one that had maps; an unrelated directory is no sibling`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + const flag = (call: number) => + (uploadSpy.mock.calls[call]?.[2] as { siblingsHaveMaps?: boolean }).siblingsHaveMaps; + const js = (n: string) => ({ [`${n}.js`]: bundleOf(n)[`${n}.js`] }); + const [a, b, other, c] = [ + { dir: '/out' }, + { dir: '/out' }, + { dir: '/other' }, + { dir: '/out' }, + ]; + await h.generateBundle.handler(a, js('a'), true); + await h.writeBundle(a, js('a')); + await h.generateBundle.handler(other, bundleOf('o'), true); // mapped, but another directory + await h.generateBundle.handler(b, js('b'), true); + await h.writeBundle(b, js('b')); + expect(flag(0)).toBeUndefined(); + expect(flag(1)).toBeUndefined(); // 'a' had no maps, and '/other' is not this directory + expect(siblingsOf(1)).toEqual(['a.js']); // a finished sibling stays known; the unrelated announced output is no sibling + await h.writeBundle(other, bundleOf('o')); + await h.generateBundle.handler(c, js('c'), true); + await h.writeBundle(c, js('c')); + expect(flag(3)).toBeUndefined(); // '/other' wrote maps, in a different directory + }); + + it(`${kind}: every finished output stays known (not only the last), and a re-write of the same names is not its own sibling`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + const [a, b, c, again] = [{ dir: '/out' }, { dir: '/out' }, { dir: '/out' }, { dir: '/out' }]; + for (const [o, n] of [ + [a, 'a'], + [b, 'b'], + [c, 'c'], + ] as const) { + await h.generateBundle.handler(o, bundleOf(n), true); + await h.writeBundle(o, bundleOf(n)); + } + expect(siblingsOf(2)?.slice().sort()).toEqual(['a.js', 'a.js.map', 'b.js', 'b.js.map']); + await h.generateBundle.handler(again, bundleOf('a'), true); + await h.writeBundle(again, bundleOf('a')); // same names as the first output + expect(siblingsOf(3)?.slice().sort()).toEqual(['b.js', 'b.js.map', 'c.js', 'c.js.map']); + }); + + it(`${kind}: a new build forgets outputs that never wrote (buildStart)`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + await h.generateBundle.handler({ file: '/out/dead.js' }, bundleOf('dead')); // never written + h.buildStart?.(); + const live = { file: '/out/live.js' }; + await h.generateBundle.handler(live, bundleOf('live')); + await h.writeBundle(live, bundleOf('live')); + expect(siblingsOf(0)).toEqual([]); + }); + } +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 90dd9f5b7..4abb59aed 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -16,13 +16,22 @@ import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; import type { BundlerBuildContext } from './register-build'; import { type BugseePluginOptions, + dirKey, notify, type ResolvedIdentity, + relativeUnder, resolveIdentity, resolvePluginOptions, runPluginUpload, } from './resolve'; -import { type AssetStore, stampAssets } from './stamp-assets'; +import { + type AssetStore, + type RollupBundleLike, + rollupAssetStore, + rollupUnstampableMaps, + stampAssets, +} from './stamp-assets'; +import { cutAtQuery } from './stamp-files'; /** The subset of a rollup/vite output-options object we read. */ export interface OutputLike { @@ -53,8 +62,13 @@ interface WebpackCompilationLike { }; }; getAssets(): ReadonlyArray<{ name: string }>; - getAsset(name: string): { source: { buffer(): Buffer } } | undefined; - updateAsset(name: string, source: unknown): void; + getAsset(name: string): + | { + source: { buffer(): Buffer }; + info?: { related?: { sourceMap?: string | string[] | null } }; + } + | undefined; + updateAsset(name: string, source: unknown, info?: object): void; } /** Minimal shape of the webpack compiler we tap (avoids a webpack type dependency in the core). */ @@ -63,7 +77,9 @@ interface WebpackCompilerLike { /** The base directory of the build (webpack's `context`, default the cwd). */ context?: string; hooks: { - afterEmit: { tapPromise: (name: string, fn: () => Promise) => void }; + afterEmit: { + tapPromise: (name: string, fn: (compilation?: AssetNamesLike) => Promise) => void; + }; /** webpack 5 only. */ thisCompilation?: { tap: (name: string, fn: (compilation: WebpackCompilationLike) => void) => void; @@ -74,13 +90,19 @@ interface WebpackCompilerLike { * `RawSource` class must be the ones this compilation uses, not a second copy of webpack or * webpack-sources that happens to resolve from this package. */ - webpack?: { - Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: number }; - sources: { RawSource: new (buffer: Buffer) => unknown }; - DefinePlugin?: DefinePluginCtor; - }; - /** Rspack's own API object (webpack-compatible `DefinePlugin`). */ - rspack?: { DefinePlugin?: DefinePluginCtor }; + webpack?: BundlerApi; + /** + * Rspack's own API object: the same webpack-compatible surface (`Compilation` stages, `sources.RawSource`, + * `DefinePlugin`), which is what lets one in-build stamp stage serve both. + */ + rspack?: BundlerApi; +} + +/** The webpack-compatible API a compiler exposes (webpack 5 as `compiler.webpack`, Rspack as `compiler.rspack`). */ +interface BundlerApi { + Compilation?: { PROCESS_ASSETS_STAGE_DEV_TOOLING: number }; + sources?: { RawSource: new (source: string) => unknown }; + DefinePlugin?: DefinePluginCtor; } /** webpack's / rspack's `DefinePlugin`, as far as the identity injection uses it. */ @@ -173,15 +195,72 @@ function unreadableIdentityNotices( return notices; } -/** A compilation's asset table as the core's `AssetStore`. */ +/** Strict, BOM-preserving UTF-8 (a lenient decode would silently corrupt an asset). */ +const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + +/** The text of an asset's bytes, or a refusal: bytes that are not valid UTF-8 are never turned into a source. */ +function asText(name: string, content: Buffer): string { + try { + return utf8.decode(content); + } catch { + throw new Error(`${name} is not valid UTF-8, so it cannot be stamped as a text source`); + } +} + +/** + * An asset name without its `?query`. Measured on real Rspack builds: webpack/Rspack drop `?...` when they write + * a file (`x.js?h` is written as `x.js`) and KEEP `#` (`a#1.js` is written as `a#1.js`), so only `?` is cut. + */ +const withoutQuery = cutAtQuery; + +/** + * A compilation's asset table as the core's `AssetStore`. + * + * Asset names can carry a `?query` (`[name].js?[contenthash]`) that the file on disk does not, and inject + * matches by extension, so the store presents (and stages) the QUERY-FREE name and maps it back to the real + * asset name for every read and write. Two assets that would collide once cleaned keep their real names. + */ function webpackAssetStore( compilation: WebpackCompilationLike, - RawSource: new (buffer: Buffer) => unknown, + RawSource: new (source: string) => unknown, ): AssetStore { + const real = new Map(); + const refresh = (): void => { + real.clear(); + const counts = new Map(); + const names = compilation.getAssets().map((asset) => asset.name); + for (const name of names) { + counts.set(withoutQuery(name), (counts.get(withoutQuery(name)) ?? 0) + 1); + } + for (const name of names) { + const clean = withoutQuery(name); + real.set(counts.get(clean) === 1 ? clean : name, name); + } + }; + const realName = (name: string): string => real.get(name) ?? name; return { - names: () => compilation.getAssets().map((asset) => asset.name), - read: (name) => compilation.getAsset(name)?.source.buffer() ?? Buffer.alloc(0), - update: (name, content) => compilation.updateAsset(name, new RawSource(content)), + names: () => { + refresh(); + return [...real.keys()]; + }, + read: (name) => compilation.getAsset(realName(name))?.source.buffer() ?? Buffer.alloc(0), + // STRING sources, never a Buffer: the stamp runs before webpack's RealContentHashPlugin renames + // `[contenthash]` chunks from their final bytes, and that plugin rewrites hash references (in the runtime, + // the sourceMappingURL comment, ...) only inside string sources. A Buffer kept the stale pre-rename names + // (the runtime asked for a chunk that did not exist: ChunkLoadError). JS and its map are UTF-8 text. + check: (name, content) => void asText(name, content), + update: (name, content) => + // The info marks what was stamped; it is carried across RealContentHashPlugin's rename (measured on real + // webpack and Rspack), which is how the final names are recovered at `afterEmit`. + compilation.updateAsset(realName(name), new RawSource(asText(name, content)), { + bugseeStamped: true, + }), + // The compilation records which asset is a bundle's source map (SourceMapDevToolPlugin: info.related). + mapOf: (name) => { + const related = compilation.getAsset(realName(name))?.info?.related?.sourceMap; + const map = Array.isArray(related) ? related[0] : related; + return map === undefined || map === null ? undefined : withoutQuery(map); + }, }; } @@ -258,6 +337,67 @@ function esbuildOutputDir(options: EsbuildBuildLike['initialOptions']): string | } } +/** The compilation handed to `afterEmit`: enough to list every asset this build emitted. */ +interface AssetNamesLike { + getAssets?(): ReadonlyArray<{ name: string; info?: object }>; +} + +/** + * The stamp's bundle / map names as the DISK has them. webpack's RealContentHashPlugin renames `[contenthash]` + * assets AFTER the in-build stamp, so the names the stamp reported are stale; when the compilation is known, + * the on-disk re-check is given the final names of the assets the stamp wrote (marked in their asset info) and + * finds each map by its pointer. + */ +const finalStampNames = ( + compilation: AssetNamesLike | undefined, +): { stampedBundles?: string[]; stampedMaps?: undefined } => { + const assets = compilation?.getAssets?.(); + return assets === undefined + ? {} + : { + // Only assets the stamp itself wrote (marked in their info): a script a plugin emitted after the stamp + // stage was never stamped and must not be judged as if it had been. + stampedBundles: assets + .filter( + (asset) => + (asset.info as { bugseeStamped?: boolean } | undefined)?.bugseeStamped === true, + ) + .map((asset) => cutAtQuery(asset.name)) + .filter((name) => /\.[cm]?js$/i.test(name)), + stampedMaps: undefined, + }; +}; + +/** The stamped bundle names that are still in the final bundle (all of them when the bundle is unknown). */ +const stampedStillPresent = ( + names: string[] | undefined, + bundle: object | undefined, +): string[] | undefined => (bundle === undefined ? names : names?.filter((name) => name in bundle)); + +/** The stamped bundle -> map names whose bundle is still in the final bundle. */ +const stampedMapsStillPresent = ( + maps: Record | undefined, + bundle: object | undefined, +): Record | undefined => + bundle === undefined || maps === undefined + ? maps + : Object.fromEntries(Object.entries(maps).filter(([name]) => name in bundle)); + +/** The names this build emitted, as the `ownFiles` the upload deletes by (absent when not known). */ +const ownFilesOf = (compilation: AssetNamesLike | undefined): { ownFiles?: string[] } => { + const assets = compilation?.getAssets?.(); + return assets === undefined ? {} : { ownFiles: assets.map((asset) => asset.name) }; +}; + +/** What an in-build stamp reports: whether it took, and which bundles it wrote (relative to the output). */ +interface InBuildStamp { + preStamped: boolean; + stampedBundles?: string[]; + stampedMaps?: Record; + /** A map lies outside the output: nothing was stamped and stamping after emit would half-stamp, so skip it. */ + abandoned?: boolean; +} + export const bugseeUnpluginFactory: UnpluginFactory = ( options = {}, ) => { @@ -296,6 +436,9 @@ export const bugseeUnpluginFactory: UnpluginFactory + compiler.options.mode === 'development' && !resolved.uploadInDevelopment; // `resolved` is assigned right below; `loadFile` only reads it after that (it is `let` for the hook refresh). let resolved = resolvePluginOptions(options, process.env); let env = mergeBuildPluginEnv(process.env, loadFile(undefined)); @@ -351,13 +494,195 @@ export const bugseeUnpluginFactory: UnpluginFactory => { + try { + const { stamped, maps, bundles } = await stampAssets(store, { dryRun: resolved.dryRun }); + // Never claim a stamp that staged nothing while the build emitted scripts: the post-emit path (which + // reads real file names off the disk) has to run, and it is said. + const scripts = emitted.filter((name) => /\.[cm]?js(\?|$)/i.test(name)); + if (bundles === 0 && scripts.length > 0) { + say( + `no debug-ID could be stamped inside the build (none of its ${scripts.length} script asset(s), e.g. ${scripts[0]}, matched), so stamping after emit instead.`, + ); + return { preStamped: false }; + } + // Stamped on a dry run too: the preview must follow the path the real run takes, and the real run + // would not refuse an SRI build — it would stamp it here. + return { preStamped: true, stampedBundles: stamped, stampedMaps: maps }; + } catch (error) { + if (resolved.failOnError) { + throw error; + } + const abandoned = (error as { unreachableMap?: boolean } | null)?.unreachableMap === true; + ( + resolved.onError ?? + ((e: unknown) => + console.warn( + abandoned + ? `[bugsee] debug-IDs were NOT stamped, and stamping after emit would half-stamp this build: ${String(e)}` + : `[bugsee] in-build debug-ID stamping failed; falling back to stamping after emit: ${String(e)}`, + )) + )(error); + return { preStamped: false, ...(abandoned ? { abandoned: true } : {}) }; + } + }; + + // webpack 5 and Rspack share the stage: stamp at PROCESS_ASSETS_STAGE_DEV_TOOLING + 1. The source-map + // plugin emits the maps AT 500 (after minification at 400) and webpack-subresource-integrity / + // Rspack's SubresourceIntegrityPlugin hash later (measured: after 700), so one stage past 500 sees the + // final bytes and the SRI plugin then hashes the STAMPED bytes — for the HTML and for the lazy-chunk + // table alike. Nothing is rewritten after emit. Returns whether THIS compilation was stamped; reset per + // compilation, so in watch mode a stamp from the previous build cannot vouch for this one. + const tapProcessAssetsStamp = ( + compiler: WebpackCompilerLike, + /** A build that will not be uploaded is not stamped either. */ + skip = false, + ): (() => InBuildStamp) => { + let state: InBuildStamp = { preStamped: false }; + const api = compiler.webpack ?? compiler.rspack; + const stage = api?.Compilation?.PROCESS_ASSETS_STAGE_DEV_TOOLING; + const RawSource = api?.sources?.RawSource; + const thisCompilation = compiler.hooks.thisCompilation; + if ( + resolved.enabled && + !skip && + stage !== undefined && + RawSource !== undefined && + thisCompilation + ) { + thisCompilation.tap(name, (compilation) => { + state = { preStamped: false }; + compilation.hooks.processAssets.tapPromise({ name, stage: stage + 1 }, async () => { + state = await stampInBuild(webpackAssetStore(compilation, RawSource)); + }); + }); + } + return () => state; + }; + + // Vite and Rollup: stamp in `generateBundle`, where chunks (`code`) and their `.map` assets are in memory. + // Whether an output was stamped is kept per OUTPUT (the options object both hooks receive), not per + // directory: two outputs written concurrently into one folder (`output.file` siblings, a stamped output + // beside an inline-map one) must not consume each other's answer, or an unstamped one would skip the + // post-emit inject and its SRI refusal. Set by every generateBundle, CONSUMED by the matching write, so + // a stamp can never carry over to a later build. An output whose write cannot be matched is simply + // not stamped: the safe answer. + const stampedOutputs = new WeakMap(); + // Outputs written into one directory announce their names at generateBundle (before ANY of them writes), so + // the first to write already knows its siblings and leaves their maps to them. Per plugin instance; a new + // build forgets outputs that never wrote. + const announced = new Map>(); + // Directories an output WITH maps has already written in this build: an unmapped output that comes after it + // (its sibling already finished and left the registry) still has nothing to do. Cleared with a new build. + const finishedNames = new Map(); + const stampBundle = async ( + output: OutputLike, + bundle: RollupBundleLike, + isWrite?: boolean, + ): Promise => { + // `bundle.generate()` / Vite `build({ write: false })` (isWrite === false) never reaches writeBundle, so + // nothing consumes a stamp: spawning the CLI (and, under failOnError, throwing) would be pure cost for a + // build that writes nothing. It is not announced either: as a stale sibling it would hide maps that + // belong to nobody. + const outDir = resolveOutputDir(output); + if (isWrite === false || outDir === undefined || !resolved.enabled) { + return; + } + const key = dirKey(outDir); + const group = announced.get(key) ?? new Map(); + group.set(output, Object.keys(bundle)); + announced.set(key, group); + stampedOutputs.set(output, { preStamped: false }); + const unstampable = rollupUnstampableMaps(bundle); + if (unstampable.length > 0) { + say( + `${unstampable.join(', ')} ${unstampable.length > 1 ? 'have' : 'has'} a source map that is not a bundle asset ` + + '(an older Rollup, or `sourcemap: "inline"`), so debug-IDs cannot be stamped inside the build; ' + + 'stamping after emit instead (a build that pins Subresource Integrity hashes is then refused).', + ); + return; + } + stampedOutputs.set(output, await stampInBuild(rollupAssetStore(bundle), Object.keys(bundle))); + }; + // Not `order: 'pre'` by taste: Vite builds `index.html` (and runs `transformIndexHtml`, where an SRI + // plugin hashes the chunks) in its own generateBundle, so ours must run first. Plugins sharing the + // `pre` order run in the order they appear in `plugins`: list this plugin BEFORE any SRI plugin. + const generateBundleHook = { + order: 'pre' as const, + handler: (output: OutputLike, bundle: RollupBundleLike, isWrite?: boolean) => + stampBundle(output, bundle, isWrite), + }; + const uploadForOutput = async ( output: OutputLike, bundler: BundlerBuildContext, + /** The final bundle at writeBundle: every name this build emitted. */ + bundle?: object, ): Promise => { const outDir = resolveOutputDir(output); if (outDir !== undefined) { - await runPluginUpload(forOutput(outDir), outDir, { bundler }); + const stamp = stampedOutputs.get(output); + stampedOutputs.delete(output); + const key = dirKey(outDir); + const group = announced.get(key); + const nested = [...announced].filter( + ([dir]) => dir !== key && relativeUnder(key, dir) !== undefined, + ); + // A name THIS output emitted is never a sibling's: a leftover announcement from `bundle.generate()` (which + // never writes) has the same names and must not hide this output's own maps. + const mine = new Set(Object.keys(bundle ?? {})); + // Outputs that already wrote in this build: their names stay known (with `deleteMaps: false` their maps + // are still on disk, and a later output must not take them for foreign and upload them again). + const finished = [...finishedNames].flatMap(([dir, names]) => { + const prefix = relativeUnder(key, dir); + return prefix === undefined + ? [] + : names.filter((n) => !mine.has(n)).map((n) => (prefix === '' ? n : `${prefix}/${n}`)); + }); + const siblingsHaveMaps = finished.some((name) => name.endsWith('.map')); + if (bundle !== undefined) { + finishedNames.set(key, [...(finishedNames.get(key) ?? []), ...mine]); + } + const siblings = [...(group ?? [])] + .filter(([other]) => other !== output) + .flatMap(([, names]) => names) + .filter((name) => !mine.has(name)) + .concat( + nested.flatMap(([dir, g]) => + [...g.values()].flat().map((name) => `${relativeUnder(key, dir)}/${name}`), + ), + ) + .concat(finished); + group?.delete(output); + if (group?.size === 0) { + announced.delete(key); + } + if (stamp?.abandoned === true) { + return; + } + await runPluginUpload(forOutput(outDir), outDir, { + bundler, + ...(bundle !== undefined ? { siblingOwnFiles: siblings } : {}), + ...(bundle !== undefined && siblingsHaveMaps ? { siblingsHaveMaps: true } : {}), + ...(bundle !== undefined ? { ownFiles: Object.keys(bundle) } : {}), + ...(stamp?.preStamped === true + ? { + preStamped: true, + // Only chunks still in the FINAL bundle: a later plugin may have removed (or inlined) one. + stampedBundles: stampedStillPresent(stamp.stampedBundles, bundle), + stampedMaps: stampedMapsStillPresent(stamp.stampedMaps, bundle), + } + : {}), + }); } }; @@ -417,7 +742,13 @@ export const bugseeUnpluginFactory: UnpluginFactory uploadForOutput(output, viteBuild), + buildStart() { + announced.clear(); + finishedNames.clear(); + }, + generateBundle: generateBundleHook, + writeBundle: (output: OutputLike, bundle?: object) => + uploadForOutput(output, viteBuild, bundle), }, rollup: { // Rollup has no `define`: bake the constants into each rendered chunk (with a source map), from the same @@ -454,8 +785,11 @@ export const bugseeUnpluginFactory: UnpluginFactory uploadForOutput(output, {}), + generateBundle: generateBundleHook, + writeBundle: (output: OutputLike, bundle?: object) => uploadForOutput(output, {}, bundle), }, esbuild: { // esbuild's `define` is a plain string map; a key the user already set is kept. @@ -566,23 +900,22 @@ export const bugseeUnpluginFactory: UnpluginFactory { + compiler.hooks.afterEmit.tapPromise(name, async (compilation?: AssetNamesLike) => { const dir = compiler.options.output?.path; const bundler = webpackBuild(compiler.options.mode); // Only `development` is skipped: `mode: 'none'` is a legitimate release setting (own minification). @@ -591,7 +924,15 @@ export const bugseeUnpluginFactory: UnpluginFactory { - preStamped = false; - compilation.hooks.processAssets.tapPromise( - { name, stage: api.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING + 1 }, - async () => { - try { - await stampAssets(webpackAssetStore(compilation, api.sources.RawSource), { - dryRun: resolved.dryRun, - }); - // True on a dry run too: the preview must follow the path the real run takes, and the - // real run would not refuse an SRI build — it would stamp it here. - preStamped = true; - } catch (error) { - if (resolved.failOnError) { - throw error; - } - // Contained, and NOT silent about what happens next: the post-emit path takes over, - // and it still carries the SRI refusal, so a failed in-build stamp degrades to the old - // safe behaviour rather than to an unchecked page. - ( - resolved.onError ?? - ((e: unknown) => - console.warn( - `[bugsee] in-build debug-ID stamping failed; falling back to stamping after emit: ${String(e)}`, - )) - )(error); - } - }, - ); - }); - } + // THE SRI FIX on webpack 5: stamp inside the compilation (see tapProcessAssetsStamp), in every mode. + // Unlike Rspack, webpack's `afterEmit` upload has no development gate (and `resolve.ts` documents that + // webpack is not gated), so skipping the stamp in development would not avoid the CLI: it would only + // move it to `afterEmit` (inject on disk, then upload) and lose the SRI protection there. + const preStamped = tapProcessAssetsStamp(compiler); - compiler.hooks.afterEmit.tapPromise(name, async () => { + compiler.hooks.afterEmit.tapPromise(name, async (compilation?: AssetNamesLike) => { const dir = compiler.options.output?.path; if (typeof dir === 'string' && dir !== '') { - await runPluginUpload(forOutput(dir), dir, { - bundler: webpackBuild(compiler.options.mode), - preStamped, - }); + const stamp = preStamped(); + if (stamp.abandoned !== true) { + await runPluginUpload(forOutput(dir), dir, { + bundler: webpackBuild(compiler.options.mode), + ...ownFilesOf(compilation), + ...stamp, + ...(stamp.preStamped ? finalStampNames(compilation) : {}), + }); + } } }); }, diff --git a/packages/bundler-plugin-core/src/plugin.upload.test.ts b/packages/bundler-plugin-core/src/plugin.upload.test.ts index 5b249b2a3..df1088a46 100644 --- a/packages/bundler-plugin-core/src/plugin.upload.test.ts +++ b/packages/bundler-plugin-core/src/plugin.upload.test.ts @@ -160,8 +160,13 @@ describe('the output hooks actually drive the upload', () => { describe('webpack 5: stamps inside the compilation', () => { const DEV_TOOLING = 500; + // Faithful: a Buffer source is NOT rewritten by RealContentHashPlugin, so the fake refuses one. class RawSource { - constructor(readonly bytes: Buffer) {} + constructor(readonly value: string) { + if (typeof value !== 'string') { + throw new TypeError('a Buffer source would keep stale content-hash references'); + } + } } function webpack5Compiler(options: { mode?: string } = {}) { @@ -237,6 +242,23 @@ describe('the output hooks actually drive the upload', () => { expect(stampSpy).toHaveBeenCalledOnce(); }); + it('stamps in every mode, development included, and uploads after emit as already stamped', async () => { + // webpack has no development gate on its afterEmit upload (unlike Rspack), so skipping the in-build + // stamp there would only move the CLI to afterEmit and lose the SRI protection. + for (const mode of ['development', 'production', 'none', undefined]) { + stampSpy.mockClear(); + uploadSpy.mockClear(); + const w = webpack5Compiler(mode === undefined ? {} : { mode }); + apply({ appToken: 'tok' }, w.compiler); + await w.compile(); + expect(w.processAssets).toHaveLength(1); + expect(stampSpy).toHaveBeenCalledOnce(); + await w.taps[0]?.fn(); + expect(uploadSpy).toHaveBeenCalledOnce(); + expect((uploadSpy.mock.calls[0]?.[2] as { preStamped?: boolean }).preStamped).toBe(true); + } + }); + it('then uploads WITHOUT re-injecting after emit', async () => { const w = webpack5Compiler({ mode: 'production' }); apply({ appToken: 'tok' }, w.compiler); @@ -268,7 +290,7 @@ describe('the output hooks actually drive the upload', () => { expect(w.updated).toHaveLength(1); expect(w.updated[0]?.name).toBe('main.js'); expect(w.updated[0]?.source).toBeInstanceOf(RawSource); - expect((w.updated[0]?.source as RawSource).bytes.toString()).toBe('stamped'); + expect((w.updated[0]?.source as RawSource).value).toBe('stamped'); }); it('passes the dry-run flag to the stamp', async () => { diff --git a/packages/bundler-plugin-core/src/resolve.test.ts b/packages/bundler-plugin-core/src/resolve.test.ts index dc0f7272c..539dedf9d 100644 --- a/packages/bundler-plugin-core/src/resolve.test.ts +++ b/packages/bundler-plugin-core/src/resolve.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; import type { UploadSourcemapsOptions, UploadSourcemapsResult } from './orchestrate'; -import { resolvePluginOptions, runPluginUpload } from './resolve'; +import { relativeUnder, resolvePluginOptions, runPluginUpload } from './resolve'; import type { ResolveVcsMetadataOptions, VcsMetadata } from './vcs'; /** @@ -162,6 +162,7 @@ describe('runPluginUpload', () => { dryRun: false, stripSourcesContent: false, failOnError: false, + onNotice: expect.any(Function), // the plugin's notice sink (resolved.onNotice, else console.warn) }); }); @@ -245,6 +246,171 @@ describe('one pipeline per output directory', () => { expect(await a).toEqual(await b); // …and the joiner gets the same result, not `undefined` }); + it('a second OUTPUT with its own ownFiles waits for the in-flight run and then runs itself (its maps are not "foreign")', async () => { + const h = held(); + const seen: Array<{ ownFiles?: readonly string[] }> = []; + const upload = async (opts: { outDir: string; ownFiles?: readonly string[] }) => { + seen.push(opts); + return h.uploadSourcemaps(opts); + }; + const a = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['a.js', 'a.js.map'], + ...noVcs, + }); + const b = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['b.js', 'b.js.map'], + ...noVcs, + }); + await tick(); + expect(seen.map((o) => o.ownFiles)).toEqual([['a.js', 'a.js.map']]); // B has not started: no race over the tree + h.release(); + await a; + await tick(); + h.release(); + await b; + expect(seen.map((o) => o.ownFiles)).toEqual([ + ['a.js', 'a.js.map'], + ['b.js', 'b.js.map'], + ]); + }); + + it("every output of one directory is told the OTHER outputs' names (so none uploads or reports another's maps)", async () => { + const seen: Array<{ ownFiles?: readonly string[]; siblingOwnFiles?: readonly string[] }> = []; + const upload = async (opts: { + outDir: string; + ownFiles?: readonly string[]; + siblingOwnFiles?: readonly string[]; + }) => { + seen.push({ ownFiles: opts.ownFiles, siblingOwnFiles: opts.siblingOwnFiles }); + return { injected: true, uploaded: true, deletedMaps: [] }; + }; + const calls = ['a', 'b', 'c'].map((n) => + runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: [`${n}.js`, `${n}.js.map`], + ...noVcs, + }), + ); + await Promise.all(calls); + expect(seen).toHaveLength(3); // sequential: one pipeline per output, never concurrent + expect(seen.map((x) => x.ownFiles?.[0])).toEqual(['a.js', 'b.js', 'c.js']); + expect(seen[0]?.siblingOwnFiles?.slice().sort()).toEqual([ + 'b.js', + 'b.js.map', + 'c.js', + 'c.js.map', + ]); + // a already finished (and handled its own maps), so only c is still pending when b runs + expect(seen[1]?.siblingOwnFiles?.slice().sort()).toEqual(['c.js', 'c.js.map']); + expect(seen[2]?.siblingOwnFiles).toEqual([]); + // once everything settled, a later run sees no leftover siblings + const later = await runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['z.js'], + ...noVcs, + }); + expect(later).toBeDefined(); + expect(seen[3]?.siblingOwnFiles).toEqual([]); + }); + + it('explicit siblings (announced at generateBundle) and pending ones are BOTH passed; another spelling of the directory is the same directory', async () => { + const seen: Array = []; + const upload = async (opts: { siblingOwnFiles?: readonly string[] }) => { + seen.push(opts.siblingOwnFiles); + return { injected: true, uploaded: true, deletedMaps: [] }; + }; + const a = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['a.js'], + siblingOwnFiles: ['announced.js.map'], + ...noVcs, + }); + const b = runPluginUpload(resolved, './dist/', { + uploadSourcemaps: upload as never, + ownFiles: ['b.js'], + ...noVcs, + }); + await Promise.all([a, b]); + expect(seen[0]?.slice().sort()).toEqual(['announced.js.map', 'b.js']); + expect(seen[1]).toEqual([]); + }); + + it('a pending output of a NESTED directory is a sibling of the parent run, under its relative path', async () => { + const seen: Array = []; + const upload = async (opts: { siblingOwnFiles?: readonly string[] }) => { + seen.push(opts.siblingOwnFiles); + return { injected: true, uploaded: true, deletedMaps: [] }; + }; + await Promise.all([ + runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['p.js'], + ...noVcs, + }), + runPluginUpload(resolved, 'dist/b', { + uploadSourcemaps: upload as never, + ownFiles: ['c.js'], + ...noVcs, + }), + runPluginUpload(resolved, 'dist-other', { + uploadSourcemaps: upload as never, + ownFiles: ['o.js'], + ...noVcs, + }), + ]); + expect(seen[0]).toEqual(['b/c.js']); // not dist-other's (a prefix-named sibling directory) + expect(seen[1]).toEqual([]); + }); + + it('a disabled plugin returns before any path resolution (a removed cwd must not make it reject)', async () => { + const cwd = vi.spyOn(process, 'cwd').mockImplementation(() => { + throw new Error('ENOENT: uv_cwd'); + }); + try { + const off = { ...resolved, enabled: false }; + await expect( + runPluginUpload(off, 'relative/dist', { ownFiles: ['a.js'] }), + ).resolves.toBeUndefined(); + } finally { + cwd.mockRestore(); + } + }); + + it('relativeUnder: a child directory whose NAME starts with two dots is still inside the parent', () => { + expect(relativeUnder('/build/dist', '/build/dist/..chunks')).toBe('..chunks'); + expect(relativeUnder('/build/dist', '/build/dist')).toBe(''); + expect(relativeUnder('/build/dist', '/build/dist-other')).toBeUndefined(); + expect(relativeUnder('/build/dist', '/build')).toBeUndefined(); + }); + + it('a failed in-flight run does not stop the waiting second output from running', async () => { + const calls: string[] = []; + let first = true; + const upload = async (opts: { outDir: string; ownFiles?: readonly string[] }) => { + calls.push(String(opts.ownFiles)); + if (first) { + first = false; + throw new Error('first run failed'); + } + return { injected: true, uploaded: true, deletedMaps: [] }; + }; + const a = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['a.js'], + ...noVcs, + }); + const b = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['b.js'], + ...noVcs, + }); + await expect(a).rejects.toThrow('first run failed'); + await b; + expect(calls).toEqual(['a.js', 'b.js']); + }); + it("a run over the build's own files neither joins nor is joined, and registers from those bundles only", async () => { const h = held(); const files = { scripts: ['dist/a.mjs'], maps: ['dist/a.mjs.map'] }; @@ -447,6 +613,7 @@ describe('runPluginUpload — VCS metadata collection', () => { dryRun: false, stripSourcesContent: false, failOnError: false, + onNotice: expect.any(Function), vcs: { commit_sha: sha, branch: 'main' }, }); }); diff --git a/packages/bundler-plugin-core/src/resolve.ts b/packages/bundler-plugin-core/src/resolve.ts index 9a40d2692..9ab6a520a 100644 --- a/packages/bundler-plugin-core/src/resolve.ts +++ b/packages/bundler-plugin-core/src/resolve.ts @@ -2,6 +2,16 @@ // with environment variables, applies defaults, and decides whether the plugin is active (a token is // required; a build without one is a no-op rather than an error). Pure + injectable for testing. +import { readlinkSync, realpathSync } from 'node:fs'; +import { + basename, + dirname, + isAbsolute, + join, + relative, + resolve as resolvePath, + sep, +} from 'node:path'; import { type AppIdentityDeps, appIdentityDefines, @@ -265,8 +275,92 @@ export function resolvePluginOptions( /** What a plugin run reports: the source-map upload, plus the build registration when it ran. */ export type PluginRunResult = UploadSourcemapsResult & { build?: RegisterJsBuildResult }; -/** Run the upload for a resolved config against a build output dir — a no-op when the plugin is disabled. */ +/** + * One key per physical directory, whatever the spelling (`dist`, `dist/`, `./dist`, an absolute path, a symlink): + * the real path of the deepest ancestor that exists, plus the not-yet-created rest (a directory that does not + * exist yet when the first output announces itself must key the same once it does). + */ +export function dirKey(dir: string, depth = 0): string { + let head = resolvePath(dir); + const rest: string[] = []; + for (;;) { + try { + return join(realpathSync.native(head), ...rest); // native: the canonical spelling (case-folded on APFS/NTFS) + } catch { + // A symlink whose target does not exist YET (the build will create it) still names that target. + const target = depth < 40 ? readLinkTarget(head) : undefined; + if (target !== undefined) { + return join(dirKey(target, depth + 1), ...rest); + } + const parent = dirname(head); + /* v8 ignore next 3 -- only when even the filesystem root cannot be resolved */ + if (parent === head) { + return join(head, ...rest); + } + rest.unshift(basename(head)); + head = parent; + } + } +} + +function readLinkTarget(path: string): string | undefined { + try { + return resolvePath(dirname(path), readlinkSync(path)); + } catch { + return undefined; // not a symlink (or not there) + } +} + +/** + * The path of `child` relative to `parent` when it is `parent` itself ('') or inside it, else undefined. A parent + * output's directory walk also covers the maps of an output written into a nested directory (`dist` and + * `dist/b`), so those are siblings too, under their relative path. + */ +export function relativeUnder(parent: string, child: string): string | undefined { + const rel = relative(parent, child); + return rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) + ? undefined + : rel.split(sep).join('/'); +} + +/** The ownFiles of every output of a directory that is pending or running (see {@link runPluginUpload}). */ +const ownersByDir = new Map>(); + +/** + * Run the upload for a resolved config against a build output dir — a no-op when the plugin is disabled. + * + * Every output of one directory that knows its own names (`ownFiles`) registers them while it is pending or + * running, so each run can leave the OTHERS' maps to their own output (N outputs: N uploads, not N times all). + */ export async function runPluginUpload( + resolved: ResolvedPluginOptions, + outDir: string, + deps: Parameters[2] = {}, +): Promise { + if (!resolved.enabled) { + return undefined; // before any path resolution: a disabled plugin does nothing, whatever the cwd + } + const mine = deps.files === undefined ? deps.ownFiles : undefined; + const key = dirKey(outDir); + if (mine !== undefined) { + const group = ownersByDir.get(key) ?? new Set(); + group.add(mine); + ownersByDir.set(key, group); + } + try { + return await runPluginUploadInner(resolved, outDir, deps, mine); + } finally { + if (mine !== undefined) { + const group = ownersByDir.get(key); + group?.delete(mine); + if (group?.size === 0) { + ownersByDir.delete(key); + } + } + } +} + +async function runPluginUploadInner( resolved: ResolvedPluginOptions, outDir: string, deps: { @@ -277,6 +371,16 @@ export async function runPluginUpload( bundler?: BundlerBuildContext; /** The bundles were stamped inside the build (stamp-assets.ts); skip the post-emit inject. */ preStamped?: boolean; + /** The bundles the in-build stamp wrote (relative to the output directory), for the on-disk re-check. */ + stampedBundles?: readonly string[]; + /** The in-build stamp's bundle -> map names, for the on-disk re-check. */ + stampedMaps?: Readonly>; + /** The names this build emitted (relative to the output directory): what it may delete. */ + ownFiles?: readonly string[]; + /** Names other outputs of the same directory announced (their maps are theirs to upload and delete). */ + siblingOwnFiles?: readonly string[]; + /** An output of this directory that has maps already wrote and finished in this build. */ + siblingsHaveMaps?: boolean; /** * The build's own outputs (esbuild's metafile). The run then touches exactly these files, never joins another * run of the same directory, and registers from these bundles only. @@ -287,20 +391,29 @@ export async function runPluginUpload( stylesheetMaps?: readonly string[]; }; } = {}, + mine?: readonly string[], ): Promise { - if (!resolved.enabled) { - return undefined; - } + // (the caller, runPluginUpload, has already returned for a disabled plugin) // One pipeline per output DIRECTORY. `writeBundle` fires once per OUTPUT, so a multi-output // config whose entries resolve to the same directory — `[{ dir: 'dist' }, { file: 'dist/legacy.js' }]`, // both `dist` — used to start two concurrent pipelines over one tree, with one deleting maps // while the other was still reading them. A concurrent caller JOINS the in-flight run and // gets its result; the entry is released on settle, so `vite build --watch` still uploads every rebuild. + const dirKey0 = dirKey(outDir); // once: a directory created meanwhile must not change the key // A run over a build's OWN files (`deps.files`) neither joins nor is joined: it touches nothing another run // of the directory touches, so there is nothing to coordinate. - const inFlight = deps.files === undefined ? runsByDir.get(outDir) : undefined; - if (inFlight !== undefined) { - return inFlight; + // A caller that knows which files ITS output emitted (`ownFiles`) does not join: the in-flight run was + // started with another output's names, and would treat this one's maps as "not produced by this build". + // It WAITS for that run (no concurrent pipelines over one tree) and then runs itself. + for (;;) { + const inFlight = deps.files === undefined ? runsByDir.get(dirKey0) : undefined; + if (inFlight === undefined) { + break; + } + if (deps.ownFiles === undefined) { + return inFlight; + } + await inFlight.catch(() => undefined); } const uploadSourcemaps = deps.uploadSourcemaps ?? defaultUploadSourcemaps; const registerJsBuild = deps.registerJsBuild ?? defaultRegisterJsBuild; @@ -315,12 +428,33 @@ export async function runPluginUpload( dryRun: resolved.dryRun, stripSourcesContent: resolved.stripSourcesContent, failOnError: resolved.failOnError, + onNotice: notify(resolved), ...(resolved.onError !== undefined ? { onError: resolved.onError } : {}), // Omitted, not sent empty: absence is how the backend tells "no VCS context" from "known empty". ...(vcs !== undefined ? { vcs } : {}), // Omitted unless true, so the orchestrator's argument stays exactly what it was for every // build that did not take the in-build path. ...(deps.preStamped === true ? { preStamped: true } : {}), + ...(deps.stampedBundles !== undefined ? { stampedBundles: deps.stampedBundles } : {}), + ...(deps.stampedMaps !== undefined ? { stampedMaps: deps.stampedMaps } : {}), + ...(deps.siblingsHaveMaps === true ? { siblingsHaveMaps: true } : {}), + ...(deps.ownFiles !== undefined + ? { + ownFiles: deps.ownFiles, + siblingOwnFiles: [ + ...(deps.siblingOwnFiles ?? []), + ...[...ownersByDir].flatMap(([dir, group]) => { + const prefix = relativeUnder(dirKey0, dir); + return prefix === undefined + ? [] + : [...group] + .filter((names) => names !== mine) + .flat() + .map((name) => (prefix === '' ? name : `${prefix}/${name}`)); + }), + ], + } + : {}), ...(deps.files !== undefined ? { files: deps.files } : {}), }); // AFTER the upload, because the build id is derived from the debug-ids its inject step stamps @@ -365,11 +499,11 @@ export async function runPluginUpload( if (deps.files !== undefined) { return run; } - runsByDir.set(outDir, run); + runsByDir.set(dirKey0, run); void run .catch(() => undefined) .finally(() => { - runsByDir.delete(outDir); + runsByDir.delete(dirKey0); }); return run; } diff --git a/packages/bundler-plugin-core/src/stamp-assets.test.ts b/packages/bundler-plugin-core/src/stamp-assets.test.ts index 646205fe2..9da260da7 100644 --- a/packages/bundler-plugin-core/src/stamp-assets.test.ts +++ b/packages/bundler-plugin-core/src/stamp-assets.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it, vi } from 'vitest'; import { readDebugId } from './debug-ids'; -import { type AssetStore, stampAssets } from './stamp-assets'; +import { + type AssetStore, + rollupAssetStore, + rollupUnstampableMaps, + StampVerificationError, + stampAssets, +} from './stamp-assets'; /** An in-memory stand-in for a webpack compilation's asset table. */ function memoryStore(initial: Record): AssetStore & { @@ -75,6 +81,8 @@ describe('stampAssets — with the real bugsee-cli', () => { }); }); +const STAMP_COMMENT = '//# debugId=b039c7fb-d958-5fe6-b76f-136179e9a728'; + describe('stampAssets — the round trip', () => { const fakeInject = (edit: (path: string, content: string) => string | undefined) => async (args: string[]) => { @@ -162,7 +170,9 @@ describe('stampAssets — the round trip', () => { // map information it carries survive untouched. const store = memoryStore({ 'a.js': 'x()\n', 'b.js': 'y()\n' }); await stampAssets(store, { - run: fakeInject((path, content) => (path === 'a.js' ? `${content}//# stamped\n` : undefined)), + run: fakeInject((path, content) => + path === 'a.js' ? `${content};1;\n${STAMP_COMMENT}\n` : undefined, + ), }); expect(store.updates).toEqual(['a.js']); }); @@ -225,3 +235,520 @@ describe('stampAssets — the round trip', () => { await expect(access(staged)).rejects.toMatchObject({ code: 'ENOENT' }); }); }); + +describe('stampAssets — names that collide when staged', () => { + it('refuses assets whose names differ only by case (they would overwrite each other on a case-insensitive disk), before running inject', async () => { + const run = vi.fn(async () => ({ code: 0, stdout: '', stderr: '' })); + const store = memoryStore({ 'A.js': 'one();\n', 'a.js': 'two();\n' }); + await expect(stampAssets(store, { run })).rejects.toThrow( + /A\.js and a\.js differ only by case/, + ); + // Whichever comes second, upper or lower case. + await expect( + stampAssets(memoryStore({ 'a.js': 'one();\n', 'A.js': 'two();\n' }), { run }), + ).rejects.toThrow(/a\.js and A\.js differ only by case/); + expect(run).not.toHaveBeenCalled(); + expect(store.updates).toEqual([]); + }); + + it('distinct names, and the same name in different directories, are fine', async () => { + const run = vi.fn(async () => ({ code: 0, stdout: '', stderr: '' })); + await stampAssets(memoryStore({ 'a.js': 'x\n', 'b/a.js': 'y\n', 'a.js.map': '{}' }), { run }); + expect(run).toHaveBeenCalledOnce(); + }); +}); + +describe('stampAssets — verifying the stamp before it is written back', () => { + const inject = + (edit: (path: string, content: string) => string | undefined) => async (args: string[]) => { + const { readdir, readFile, writeFile } = await import('node:fs/promises'); + const { join } = await import('node:path'); + const root = args[2] as string; + for (const entry of await readdir(root, { withFileTypes: true })) { + const next = edit(entry.name, await readFile(join(root, entry.name), 'utf8')); + if (next !== undefined) { + await writeFile(join(root, entry.name), next); + } + } + return { code: 0, stdout: '', stderr: '' }; + }; + + it('writes NOTHING back when any stamped bundle no longer parses (all or nothing)', async () => { + const store = memoryStore({ 'a.js': 'a();\n', 'b.js': 'b();\n' }); + await expect( + stampAssets(store, { + run: inject((path, content) => + path === 'a.js' + ? `${content};1;\n${STAMP_COMMENT}\n` + : `${content}{{\n${STAMP_COMMENT}\n`, + ), + }), + ).rejects.toThrow(StampVerificationError); + expect(store.updates).toEqual([]); + expect(store.assets.get('a.js')).toBe('a();\n'); + }); + + it('names the asset and the reason, and keeps every issue on the error', async () => { + const store = memoryStore({ 'a.js': 'a();\n' }); + const error = (await stampAssets(store, { run: inject((_p, c) => `${c}{{\n`) }).catch( + (e: unknown) => e, + )) as StampVerificationError; + expect(error).toBeInstanceOf(StampVerificationError); + expect(error.message).toContain('a.js'); + expect(error.message).toContain('no longer parses'); + expect(error.issues.map((i) => i.name)).toContain('a.js'); + expect(error.name).toBe('StampVerificationError'); + }); + + it('flags a stamp whose bundle and map disagree', async () => { + const store = memoryStore({ + 'a.js': 'a();\n//# sourceMappingURL=a.js.map\n', + 'a.js.map': '{"version":3,"sources":[],"names":[],"mappings":""}', + }); + await expect( + stampAssets(store, { + run: inject((path, content) => + path === 'a.js' + ? `${content};1;\n${STAMP_COMMENT}\n` + : content.replace(/\}$/, ',"debugId":"4adb7053-e754-594c-96b5-09c18263b153"}'), + ), + }), + ).rejects.toThrow(/does not match/); + expect(store.updates).toEqual([]); + }); + + it('a dry run is not verified (it writes nothing, whatever it finds)', async () => { + const store = memoryStore({ 'a.js': 'a();\n' }); + await expect( + stampAssets(store, { dryRun: true, run: inject((_p, c) => `${c}{{\n`) }), + ).resolves.toEqual({ stamped: [], maps: {}, bundles: 1 }); + }); + + it('uses an injected parser', async () => { + const store = memoryStore({ 'a.js': 'a();\n' }); + const parse = vi.fn(() => true); + await stampAssets(store, { + parse, + run: inject((_p, c) => `${c};1;\n${STAMP_COMMENT}\n`), + }); + expect(parse).toHaveBeenCalled(); + }); +}); + +describe('rollupAssetStore — a Rollup / Vite output bundle as an asset table', () => { + const chunk = (fileName: string, code: string, extra: object = {}) => ({ + type: 'chunk' as const, + fileName, + code, + map: { version: 3 }, + ...extra, + }); + const asset = (fileName: string, source: string | Uint8Array) => ({ + type: 'asset' as const, + fileName, + source, + }); + + it('lists chunks and the map / script assets, and nothing else', () => { + const store = rollupAssetStore({ + 'a.js': chunk('a.js', 'x'), + 'a.js.map': asset('a.js.map', '{}'), + 'index.html': asset('index.html', '

'), + 'vendor.js': asset('vendor.js', 'v'), + 'logo.png': asset('logo.png', new Uint8Array([1])), + }); + expect(store.names().sort()).toEqual(['a.js', 'a.js.map', 'vendor.js']); + }); + + it('reads a chunk as its code and an asset as its source, string or bytes', () => { + const store = rollupAssetStore({ + 'a.js': chunk('a.js', 'héllo'), + 'a.js.map': asset('a.js.map', '{"a":1}'), + 'b.js.map': asset('b.js.map', new Uint8Array(Buffer.from('{"b":2}'))), + }); + expect(store.read('a.js').toString('utf8')).toBe('héllo'); + expect(store.read('a.js.map').toString('utf8')).toBe('{"a":1}'); + expect(store.read('b.js.map').toString('utf8')).toBe('{"b":2}'); + }); + + it('writes a chunk back to .code, and an asset back in the type it had', () => { + const bundle = { + 'a.js': chunk('a.js', 'x'), + 'a.js.map': asset('a.js.map', '{}'), + 'b.js.map': asset('b.js.map', new Uint8Array([1])), + }; + const store = rollupAssetStore(bundle); + store.update('a.js', Buffer.from('stamped ✓')); + store.update('a.js.map', Buffer.from('{"debugId":"x"}')); + store.update('b.js.map', Buffer.from('bytes')); + expect(bundle['a.js'].code).toBe('stamped ✓'); + expect(bundle['a.js.map'].source).toBe('{"debugId":"x"}'); + expect(bundle['b.js.map'].source).toBeInstanceOf(Uint8Array); + expect(Buffer.from(bundle['b.js.map'].source as Uint8Array).toString()).toBe('bytes'); + }); + + it('carries the stamped ids onto chunk.map too, so a bundler that rebuilds the map from it keeps them', () => { + // Vite rewrites a chunk with dynamic imports AFTER generateBundle hooks and regenerates its `.map` + // asset from `chunk.map`, keeping only what `chunk.map` carries (its `debugId`). Measured, Vite 7.3/8.3. + const map: Record = { version: 3 }; + const bundle = { + 'a.js': chunk('a.js', 'x', { map }), + 'a.js.map': asset('a.js.map', '{}'), + 'b.js': chunk('b.js', 'y', { map: null }), + 'b.js.map': asset('b.js.map', '{}'), + 'c.js': chunk('c.js', 'z', { map: { version: 3 }, sourcemapFileName: 'maps/c.map' }), + 'maps/c.map': asset('maps/c.map', '{}'), + }; + const store = rollupAssetStore(bundle); + store.update('a.js.map', Buffer.from('{"debugId":"ID-1","debug_id":"ID-1"}')); + store.update('b.js.map', Buffer.from('{"debugId":"ID-2"}')); + store.update('maps/c.map', Buffer.from('{"debug_id":"ID-3"}')); + expect(map).toEqual({ version: 3, debugId: 'ID-1', debug_id: 'ID-1' }); + expect(bundle['b.js'].map).toBeNull(); // nothing to carry onto + expect(bundle['c.js'].map).toEqual({ version: 3, debug_id: 'ID-3', debugId: 'ID-3' }); + }); + + it('leaves chunk.map alone when the new map is not JSON or has no id', () => { + const map: Record = { version: 3 }; + const bundle = { 'a.js': chunk('a.js', 'x', { map }), 'a.js.map': asset('a.js.map', '{}') }; + const store = rollupAssetStore(bundle); + store.update('a.js.map', Buffer.from('not json')); + store.update('a.js.map', Buffer.from('{"version":3}')); + store.update('a.js.map', Buffer.from('[1]')); + expect(map).toEqual({ version: 3 }); + }); + + it('reads an unknown name as empty rather than throwing', () => { + expect(rollupAssetStore({}).read('nope.js').length).toBe(0); + }); + + it('stamps a Rollup bundle through the real bugsee-cli, map included', async () => { + const bundle = { + 'a.js': chunk('a.js', 'console.log(1);\n//# sourceMappingURL=a.js.map'), + 'a.js.map': asset( + 'a.js.map', + '{"version":3,"file":"a.js","sources":["a.ts"],"names":[],"mappings":"AAAA"}', + ), + }; + const result = await stampAssets(rollupAssetStore(bundle)); + const id = readDebugId(bundle['a.js'].code); + expect(id).toMatch(/^[0-9a-f-]{36}$/); + expect(JSON.parse(bundle['a.js.map'].source as string).debugId).toBe(id); + expect(result.stamped).toEqual(['a.js']); + }); +}); + +describe('rollupUnstampableMaps — chunks whose map cannot be stamped in memory', () => { + it('is empty when every mapped chunk has its map as a bundle asset', () => { + expect( + rollupUnstampableMaps({ + 'a.js': { type: 'chunk', fileName: 'a.js', code: '', map: {} }, + 'a.js.map': { type: 'asset', fileName: 'a.js.map', source: '{}' }, + 'b.js': { type: 'chunk', fileName: 'b.js', code: '', map: null }, + }), + ).toEqual([]); + }); + + it('names a chunk that has a map but no map asset (older Rollup, inline maps)', () => { + expect( + rollupUnstampableMaps({ + 'a.js': { type: 'chunk', fileName: 'a.js', code: '', map: {} }, + 'b.js': { type: 'chunk', fileName: 'b.js', code: '', map: {} }, + 'b.js.map': { type: 'asset', fileName: 'b.js.map', source: '{}' }, + }), + ).toEqual(['a.js']); + }); + + it('honours a custom sourcemapFileName', () => { + expect( + rollupUnstampableMaps({ + 'a.js': { + type: 'chunk', + fileName: 'a.js', + code: '', + map: {}, + sourcemapFileName: 'maps/a.map', + }, + 'maps/a.map': { type: 'asset', fileName: 'maps/a.map', source: '{}' }, + }), + ).toEqual([]); + }); + + it('only considers script chunks', () => { + expect( + rollupUnstampableMaps({ + 'a.css': { type: 'chunk', fileName: 'a.css', code: '', map: {} }, + }), + ).toEqual([]); + }); +}); + +describe('stampAssets — a map that is not the bundle sibling (sourcemapFileNames moved it)', () => { + const chunk = (fileName: string, code: string, extra: object = {}) => ({ + type: 'chunk' as const, + fileName, + code, + map: { version: 3 }, + ...extra, + }); + const asset = (fileName: string, source: string) => ({ + type: 'asset' as const, + fileName, + source, + }); + const MAP = '{"version":3,"file":"a.js","sources":["a.ts"],"names":[],"mappings":"AAAA"}'; + const moved = () => ({ + 'js/a.js': chunk('js/a.js', 'console.log(1);\n//# sourceMappingURL=a.js.map\n', { + sourcemapFileName: 'maps/a.js.map', + }), + 'maps/a.js.map': asset('maps/a.js.map', MAP), + }); + + it('stamps the bundle AND its moved map with the same id, through the real bugsee-cli', async () => { + const bundle = moved(); + const result = await stampAssets(rollupAssetStore(bundle)); + const id = readDebugId(bundle['js/a.js'].code); + expect(id).toMatch(/^[0-9a-f-]{36}$/); + expect(JSON.parse(bundle['maps/a.js.map'].source).debugId).toBe(id); + expect(result.stamped).toEqual(['js/a.js']); + }); + + it('stages the map as the bundle sibling (that is how inject pairs them), and writes it back at its real name', async () => { + const seen: string[] = []; + const bundle = moved(); + await stampAssets(rollupAssetStore(bundle), { + run: async (args) => { + const { readdir, writeFile, readFile } = await import('node:fs/promises'); + const { join } = await import('node:path'); + const root = args[2] as string; + for (const dir of ['js']) { + for (const f of await readdir(join(root, dir))) { + seen.push(`${dir}/${f}`); + } + } + await writeFile( + join(root, 'js/a.js'), + `${await readFile(join(root, 'js/a.js'), 'utf8')};1;\n${STAMP_COMMENT}\n`, + ); + await writeFile( + join(root, 'js/a.js.map'), + MAP.replace(/\}$/, `,"debugId":"b039c7fb-d958-5fe6-b76f-136179e9a728"}`), + ); + return { code: 0, stdout: '', stderr: '' }; + }, + }); + expect(seen.sort()).toEqual(['js/a.js', 'js/a.js.map']); + expect(bundle['maps/a.js.map'].source).toContain('debugId'); + }); + + it('refuses (before inject) when the sibling name is already taken by another asset', async () => { + const run = vi.fn(async () => ({ code: 0, stdout: '', stderr: '' })); + const bundle = { ...moved(), 'js/a.js.map': asset('js/a.js.map', '{}') }; + await expect(stampAssets(rollupAssetStore(bundle), { run })).rejects.toThrow(/js\/a\.js\.map/); + expect(run).not.toHaveBeenCalled(); + }); + + it('refuses a stamped bundle whose map cannot be staged at all (not a .map name): never a silent half-stamp', async () => { + const bundle = { + 'a.js': chunk('a.js', 'x();\n', { sourcemapFileName: 'maps/a.json' }), + 'maps/a.json': asset('maps/a.json', MAP), + }; + const run = vi.fn(async () => ({ code: 0, stdout: '', stderr: '' })); + const error = (await stampAssets(rollupAssetStore(bundle), { run }).catch( + (e: unknown) => e, + )) as StampVerificationError; + expect(error).toBeInstanceOf(StampVerificationError); + expect(error.message).toContain('maps/a.json'); + }); + + it('a store with no mapOf behaves exactly as before', async () => { + const store = memoryStore({ + 'a.js': 'x()\n//# sourceMappingURL=a.js.map', + 'a.js.map': '{"version":3,"sources":["x.ts"],"names":[],"mappings":"AAAA"}', + }); + await stampAssets(store); + expect(JSON.parse(store.assets.get('a.js.map') as string).debugId).toMatch(/^[0-9a-f-]{36}$/); + }); + + it('rollupAssetStore.mapOf names the map asset of a chunk, or nothing', () => { + const store = rollupAssetStore({ + ...moved(), + 'b.js': chunk('b.js', 'x'), + 'c.js': chunk('c.js', 'x'), + 'c.js.map': asset('c.js.map', '{}'), + 'logo.png': asset('logo.png', 'x'), + }); + expect(store.mapOf?.('js/a.js')).toBe('maps/a.js.map'); + expect(store.mapOf?.('b.js')).toBeUndefined(); // no map asset + expect(store.mapOf?.('c.js')).toBe('c.js.map'); + expect(store.mapOf?.('logo.png')).toBeUndefined(); // not a chunk + expect(store.mapOf?.('nope.js')).toBeUndefined(); + }); +}); + +describe('stampAssets — result details', () => { + const run = async (args: string[]) => { + const { readdir, readFile, writeFile } = await import('node:fs/promises'); + const { join } = await import('node:path'); + const root = args[2] as string; + for (const f of await readdir(root)) { + if (f.endsWith('.js')) { + await writeFile( + join(root, f), + `${await readFile(join(root, f), 'utf8')};1;\n${STAMP_COMMENT}\n`, + ); + } + } + return { code: 0, stdout: '', stderr: '' }; + }; + + it('lists the stamped bundles SORTED whatever order the store names them in', async () => { + const store = memoryStore({ 'c.js': 'c\n', 'a.js': 'a\n', 'b.js': 'b\n' }); + expect((await stampAssets(store, { run })).stamped).toEqual(['a.js', 'b.js', 'c.js']); + }); + + it('stages and stamps an UPPERCASE .JS bundle (the CLI stamps it too)', async () => { + const store = memoryStore({ + 'A.JS': 'x();\n//# sourceMappingURL=A.JS.map\n', + 'A.JS.map': '{"version":3,"sources":["a.ts"],"names":[],"mappings":"AAAA"}', + }); + const result = await stampAssets(store); + expect(result.stamped).toEqual(['A.JS']); + expect(readDebugId(store.assets.get('A.JS') as string)).toMatch(/^[0-9a-f-]{36}$/); + }); + + it('refuses a stamped bundle whose map pointer leaves the output (never a silent half-stamp)', async () => { + const store = memoryStore({ 'js/a.js': 'x();\n//# sourceMappingURL=../../maps/a.js.map\n' }); + const error = (await stampAssets(store).catch((e: unknown) => e)) as StampVerificationError; + expect(error).toBeInstanceOf(StampVerificationError); + expect(error.message).toContain('outside the output directory'); + expect(error.unreachableMap).toBe(true); + expect(error.message).toContain('bugsee-cli'); + expect(store.updates).toEqual([]); + }); + + it('result.maps: bundle -> its real map name', async () => { + const bundle = { + 'js/a.js': { + type: 'chunk' as const, + fileName: 'js/a.js', + code: 'x();\n', + map: {}, + sourcemapFileName: 'maps/a.js.map', + }, + 'maps/a.js.map': { + type: 'asset' as const, + fileName: 'maps/a.js.map', + source: '{"version":3,"sources":["a.ts"],"names":[],"mappings":"AAAA"}', + }, + 'b.js': { type: 'chunk' as const, fileName: 'b.js', code: 'y();\n', map: null }, + }; + const result = await stampAssets(rollupAssetStore(bundle)); + expect(result.maps).toEqual({ 'js/a.js': 'maps/a.js.map' }); + expect(result.stamped).toEqual(['b.js', 'js/a.js']); + }); +}); + +describe('stampAssets — a store whose map is named outside the output', () => { + it('says so (outside the output directory) rather than a generic staging failure', async () => { + const store = { + ...memoryStore({ 'js/a.js': 'x();\n' }), + mapOf: () => '../maps/a.js.map', + }; + const error = (await stampAssets(store).catch((e: unknown) => e)) as StampVerificationError; + expect(error.message).toContain('lies outside the output directory'); + expect(error.message).toContain('inside the output directory'); + expect(error.message).toContain('bugsee-cli'); + }); +}); + +describe('stampAssets — how many bundles it staged', () => { + const run = async () => ({ code: 0, stdout: '', stderr: '' }); + it('is 0 for an asset it cannot match', async () => { + expect((await stampAssets(memoryStore({ 'a.css': 'x' }), { run })).bundles).toBe(0); + expect((await stampAssets(memoryStore({ 'main.js?h': 'x' }), { run })).bundles).toBe(0); + }); + it('counts the BUNDLES staged, not the maps staged with them (real bugsee-cli)', async () => { + const MAP = '{"version":3,"sources":["x.ts"],"names":[],"mappings":"AAAA"}'; + const store = memoryStore({ + 'a.js': 'a();\n//# sourceMappingURL=a.js.map\n', + 'a.js.map': MAP, + 'b.mjs': 'b();\n//# sourceMappingURL=b.mjs.map\n', + 'b.mjs.map': MAP, + 'c.css': 'c{}', + }); + const result = await stampAssets(store); + expect(result.bundles).toBe(2); // four assets were staged + expect(result.stamped).toEqual(['a.js', 'b.mjs']); + }); + it('a dry run reports the count too', async () => { + const store = memoryStore({ 'a.js': 'a\n', 'a.js.map': '{}', 'b.js': 'b\n' }); + expect((await stampAssets(store, { run, dryRun: true })).bundles).toBe(2); + }); +}); + +describe('stampAssets — a store can refuse the write-back (store.check), before anything is written', () => { + it('writes NOTHING back when check throws for any asset', async () => { + const MAP = '{"version":3,"sources":["x.ts"],"names":[],"mappings":"AAAA"}'; + const store = memoryStore({ + 'a.js': 'a();\n//# sourceMappingURL=a.js.map\n', + 'a.js.map': MAP, + 'b.js': 'b();\n//# sourceMappingURL=b.js.map\n', + 'b.js.map': MAP, + }); + const checked: string[] = []; + await expect( + stampAssets({ + ...store, + check: (name: string) => { + checked.push(name); + if (name === 'b.js') throw new Error('not text'); + }, + }), + ).rejects.toThrow('not text'); + expect(store.updates).toEqual([]); // a.js was checked first and is fine, yet NOTHING was written + expect(checked).toContain('a.js'); + expect(checked).toContain('b.js'); + }); + + it('check is not asked about an asset inject left unchanged', async () => { + const checked: string[] = []; + const store = memoryStore({ 'a.css': 'x', 'a.js': 'a();\n' }); + await stampAssets( + { ...store, check: (n: string) => void checked.push(n) }, + { + run: async () => ({ code: 0, stdout: '', stderr: '' }), + }, + ); + expect(checked).toEqual([]); + }); +}); + +describe('stampAssets — two bundles that claim the same map', () => { + it('refuses (before inject) rather than stage the map for only one of them', async () => { + const run = vi.fn(async () => ({ code: 0, stdout: '', stderr: '' })); + const store = { + ...memoryStore({ 'a.js': 'a\n', 'b.js': 'b\n', 'shared.map': '{}' }), + mapOf: () => 'shared.map', + }; + await expect(stampAssets(store, { run })).rejects.toThrow( + 'the map shared.map is claimed by more than one bundle (a.js and b.js), so it cannot be stamped', + ); + expect(run).not.toHaveBeenCalled(); + }); +}); + +describe("stampAssets — a map that is another bundle's own sibling is claimed too", () => { + it("refuses when b.js names a.js.map (a.js's own sibling map) as its map", async () => { + const run = vi.fn(async () => ({ code: 0, stdout: '', stderr: '' })); + const store = { + ...memoryStore({ 'a.js': 'a\n', 'a.js.map': '{}', 'b.js': 'b\n' }), + // both bundles name a.js.map: it is a.js's own sibling, and b.js claims it too + mapOf: () => 'a.js.map', + }; + await expect(stampAssets(store, { run })).rejects.toThrow( + 'the map a.js.map is claimed by more than one bundle (a.js and b.js), so it cannot be stamped', + ); + expect(run).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/bundler-plugin-core/src/stamp-assets.ts b/packages/bundler-plugin-core/src/stamp-assets.ts index 791732ca6..41a09588e 100644 --- a/packages/bundler-plugin-core/src/stamp-assets.ts +++ b/packages/bundler-plugin-core/src/stamp-assets.ts @@ -18,28 +18,64 @@ import { tmpdir } from 'node:os'; import { dirname, isAbsolute, join, normalize, sep } from 'node:path'; import type { RunFn } from './orchestrate'; import { runBugseeCli } from './run-cli'; +import { formatIssues, type StampIssue, verifyStamp } from './verify-stamp'; /** The slice of a compilation's asset table this needs — no bundler types in the core. */ export interface AssetStore { names(): string[]; - read(name: string): Buffer | string; + read(name: string): Buffer; update(name: string, content: Buffer): void; + /** + * Called for EVERY asset about to be written back, before ANY is: throw to refuse the whole stamp (a store + * that can only hold text refuses bytes that are not valid text), so a refusal never leaves a half-written build. + */ + check?(name: string, content: Buffer): void; + /** + * The asset that is the source map of the bundle `name`, when the bundler can say (a Rollup chunk's + * `sourcemapFileName`). inject pairs a bundle with its map by the sibling name `.map`, so a map + * the bundler MOVED is staged under that name; without this a moved map is simply not found and the + * bundle would be stamped with an id that was never put in the map. + */ + mapOf?(name: string): string | undefined; } export interface StampAssetsOptions { /** Preview only: run `inject --dry-run` and write nothing back. */ dryRun?: boolean; run?: RunFn; + /** Injectable JavaScript parser for the post-stamp check (default: acorn, see verify-stamp.ts). */ + parse?: (code: string) => boolean; +} + +/** + * The stamp did not verify (verify-stamp.ts): something inject produced is not safe to ship. Nothing was + * written back. Carries every issue, so a caller can say exactly which asset and why. + */ +export class StampVerificationError extends Error { + readonly issues: StampIssue[]; + /** A map lies outside the output: stamping after emit cannot reach it either, so a retry would half-stamp. */ + get unreachableMap(): boolean { + return this.issues.some((issue) => issue.outside === true); + } + constructor(issues: StampIssue[]) { + super(`the debug-ID stamp did not verify, so none of it was applied (${formatIssues(issues)})`); + this.name = 'StampVerificationError'; + this.issues = issues; + } } export interface StampAssetsResult { - /** The bundles inject rewrote (their maps are rewritten alongside, and not listed). */ + /** The bundles inject rewrote (their maps are rewritten alongside, and not listed), sorted. */ stamped: string[]; + /** How many bundles were staged for inject (0: nothing the stamp could match, whatever the store holds). */ + bundles: number; + /** Each stamped bundle's source map, by real asset name, where it has one: what the on-disk re-check uses. */ + maps: Record; } /** What inject stamps (`.js`/`.cjs`/`.mjs`), and the maps it pairs them with. */ -const BUNDLE = /\.[cm]?js$/; -const STAGED = /\.([cm]?js|map)$/; +const BUNDLE = /\.[cm]?js$/i; +const STAGED = /\.([cm]?js|map)$/i; /** A relative asset name that stays inside the staging directory once joined to it. */ function staysInside(name: string): boolean { @@ -60,17 +96,72 @@ export async function stampAssets( ): Promise { const staged = store.names().filter((name) => STAGED.test(name) && staysInside(name)); if (!staged.some((name) => BUNDLE.test(name))) { - return { stamped: [] }; + return { stamped: [], maps: {}, bundles: 0 }; + } + // A map that is not the bundle's sibling is staged AS the sibling (and written back at its real name). + const stageName = new Map(); + const stagedSet = new Set(staged); + // Every map a bundle names (its own sibling included) belongs to ONE bundle: two claimants would be + // verified against the same file and one of them accepted with no map of its own. + const claimed = new Map(); + for (const bundle of staged.filter((name) => BUNDLE.test(name))) { + const map = store.mapOf?.(bundle); + const sibling = `${bundle}.map`; + if (map !== undefined) { + const other = claimed.get(map); + if (other !== undefined) { + throw new Error( + `the map ${map} is claimed by more than one bundle (${other} and ${bundle}), so it cannot be stamped`, + ); + } + claimed.set(map, bundle); + } + if (map === undefined || map === sibling) { + continue; + } + if (!stagedSet.has(map)) { + // Not something that can be staged (not a .map name): stamping the bundle alone would be a silent + // half-stamp, so the whole stamp is refused and the caller falls back. + throw new StampVerificationError([ + { + name: map, + reason: staysInside(map) + ? `the map of ${bundle} cannot be staged for stamping (not a .map file)` + : `the map of ${bundle} lies outside the output directory, so it cannot be stamped with the bundle. Emit the maps inside the output directory, or upload them yourself with bugsee-cli (sourcemaps inject, then debug-files upload).`, + ...(staysInside(map) ? {} : { outside: true as const }), + }, + ]); + } + if (stagedSet.has(sibling)) { + throw new Error( + `the map ${map} of ${bundle} cannot be staged as ${sibling}: another asset already has that name`, + ); + } + stageName.set(map, sibling); + } + const stagedAs = (name: string): string => stageName.get(name) ?? name; + // Staging writes each asset to a file named after it. Two names that differ only by case are two + // assets in the bundler but ONE file on a case-insensitive disk (macOS, Windows), where the second would + // overwrite the first and verification would compare the wrong bytes. Refuse rather than guess: the + // caller's fallback stamps the real output directory, where such a collision cannot exist. + const seen = new Map(); + for (const name of staged.map(stagedAs)) { + const clash = seen.get(name.toLowerCase()); + if (clash !== undefined && clash !== name) { + throw new Error( + `assets ${clash} and ${name} differ only by case, so they cannot be staged side by side on a case-insensitive file system`, + ); + } + seen.set(name.toLowerCase(), name); } const dryRun = options.dryRun ?? false; const root = await mkdtemp(join(tmpdir(), 'bugsee-stamp-')); try { const before = new Map(); for (const name of staged) { - const content = store.read(name); - const bytes = typeof content === 'string' ? Buffer.from(content) : content; - before.set(name, bytes); - const path = join(root, name); + const bytes = store.read(name); + before.set(stagedAs(name), bytes); + const path = join(root, stagedAs(name)); await mkdir(dirname(path), { recursive: true }); await writeFile(path, bytes); } @@ -81,23 +172,154 @@ export async function stampAssets( {}, ); + const bundles = staged.filter((name) => BUNDLE.test(name)).length; if (dryRun) { - return { stamped: [] }; + return { stamped: [], maps: {}, bundles }; + } + // Read everything back and verify BEFORE writing anything: a bad stamp must leave the build exactly + // as the bundler produced it, which an interleaved read-and-update could not promise. + const after = new Map(); + for (const name of staged) { + after.set(stagedAs(name), await readFile(join(root, stagedAs(name)))); + } + const issues = verifyStamp(before, after, options.parse); + if (issues.length > 0) { + throw new StampVerificationError(issues); + } + for (const name of staged) { + const afterBytes = after.get(stagedAs(name)) as Buffer; + if (!afterBytes.equals(before.get(stagedAs(name)) as Buffer)) { + store.check?.(name, afterBytes); + } } const stamped: string[] = []; for (const name of staged) { - const after = await readFile(join(root, name)); + const afterBytes = after.get(stagedAs(name)) as Buffer; // Only what inject actually changed goes back. An untouched asset keeps its original Source // object, so webpack's caching and any map information it carries are not disturbed. - if (!after.equals(before.get(name) as Buffer)) { - store.update(name, after); + if (!afterBytes.equals(before.get(stagedAs(name)) as Buffer)) { + store.update(name, afterBytes); if (BUNDLE.test(name)) { stamped.push(name); } } } - return { stamped: stamped.sort() }; + const maps: Record = {}; + for (const bundle of stamped) { + const map = store.mapOf?.(bundle) ?? `${bundle}.map`; + if (stagedSet.has(map)) { + maps[bundle] = map; + } + } + return { stamped: stamped.sort(), maps, bundles }; } finally { await rm(root, { recursive: true, force: true }); } } + +/** A Rollup / Vite / Rolldown output chunk, as far as stamping reads or writes it. */ +interface RollupChunkLike { + type: 'chunk'; + fileName: string; + code: string; + map?: unknown; + sourcemapFileName?: string | null; +} + +/** An emitted asset (a `.map` file, a copied script, an image, the HTML). */ +interface RollupAssetLike { + type: 'asset'; + fileName: string; + source: string | Uint8Array; +} + +/** The `bundle` object `generateBundle` receives, keyed by output file name. */ +export type RollupBundleLike = Record; + +/** + * A Rollup / Vite output bundle as an {@link AssetStore}, so `generateBundle` can stamp what is about to + * be written. Chunks are read and written through `.code`; the `.map` files are bundle ASSETS (measured: + * Rollup 4.65, Vite 7.3 and Vite 8.3/Rolldown all list `.map` in the bundle, and their + * `source` is what reaches disk — `chunk.map` is NOT written back, so editing it would silently do + * nothing). An asset keeps the type it had (string or bytes). + */ +export function rollupAssetStore(bundle: RollupBundleLike): AssetStore { + return { + names: () => Object.keys(bundle).filter((name) => STAGED.test(name)), + mapOf: (name) => { + const entry = bundle[name]; + if (entry?.type !== 'chunk') { + return undefined; + } + const map = entry.sourcemapFileName ?? `${name}.map`; + return bundle[map] === undefined ? undefined : map; + }, + read: (name) => { + const entry = bundle[name]; + if (entry === undefined) { + return Buffer.alloc(0); + } + const content = entry.type === 'chunk' ? entry.code : entry.source; + return typeof content === 'string' ? Buffer.from(content, 'utf8') : Buffer.from(content); + }, + update: (name, content) => { + const entry = bundle[name] as RollupChunkLike | RollupAssetLike; + if (entry.type === 'chunk') { + entry.code = content.toString('utf8'); + } else { + entry.source = + typeof entry.source === 'string' ? content.toString('utf8') : new Uint8Array(content); + carryDebugId(bundle, name, content); + } + }, + }; +} + +/** + * Put a stamped map's debug-id on the `chunk.map` object that belongs to it. Vite rewrites a chunk with + * dynamic imports after the `generateBundle` hooks (its preload-marker substitution) and REGENERATES the + * `.map` asset from `chunk.map`, keeping only what that object carries — its `debugId` — so an id that + * lives only in the asset would be silently dropped (measured, Vite 7.3 and 8.3). + */ +function carryDebugId(bundle: RollupBundleLike, mapName: string, content: Buffer): void { + let parsed: { debugId?: unknown; debug_id?: unknown }; + try { + parsed = JSON.parse(content.toString('utf8')) as typeof parsed; + } catch { + return; + } + const id = [parsed?.debugId, parsed?.debug_id].find((v) => typeof v === 'string' && v !== ''); + if (id === undefined) { + return; + } + for (const [name, entry] of Object.entries(bundle)) { + if ( + entry.type === 'chunk' && + (entry.sourcemapFileName ?? `${name}.map`) === mapName && + typeof entry.map === 'object' && + entry.map !== null + ) { + Object.assign(entry.map, { debugId: id, debug_id: id }); + } + } +} + +/** + * The script chunks that HAVE a source map (`chunk.map`) but whose map is not a bundle asset, so stamping + * the code in memory could not stamp the map that reaches disk. An older Rollup that writes the `.map` file + * from `chunk.map` at write time, or `sourcemap: 'inline'`. Such a build cannot be stamped in the + * build; it falls back to stamping after emit, exactly as before. + */ +export function rollupUnstampableMaps(bundle: RollupBundleLike): string[] { + const names: string[] = []; + for (const [name, entry] of Object.entries(bundle)) { + if (entry.type !== 'chunk' || !BUNDLE.test(name) || !entry.map) { + continue; + } + const mapName = entry.sourcemapFileName ?? `${name}.map`; + if (bundle[mapName] === undefined) { + names.push(name); + } + } + return names.sort(); +} diff --git a/packages/bundler-plugin-core/src/stamp-files.fail.test.ts b/packages/bundler-plugin-core/src/stamp-files.fail.test.ts new file mode 100644 index 000000000..44220f49e --- /dev/null +++ b/packages/bundler-plugin-core/src/stamp-files.fail.test.ts @@ -0,0 +1,125 @@ +import { mkdtemp, readdir, writeFile as realWriteFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { uploadSourcemaps } from './orchestrate'; + +// A disk that fills up while the originals are being spilled (ENOSPC). +const { failSpill } = vi.hoisted(() => ({ failSpill: { on: false, rm: false } })); +vi.mock('node:fs/promises', async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + rm: (async (path: string, ...rest: unknown[]) => { + if (failSpill.rm && String(path).includes('bugsee-orig-')) { + throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' }); + } + return (real.rm as (...a: unknown[]) => Promise)(path, ...rest); + }) as typeof real.rm, + writeFile: (async (path: string, ...rest: unknown[]) => { + if (failSpill.on && String(path).includes('bugsee-orig-')) { + throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }); + } + return (real.writeFile as (...a: unknown[]) => Promise)(path, ...rest); + }) as typeof real.writeFile, + }; +}); + +let dir: string; +let spillRoot: string; +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-fail-')); + spillRoot = await mkdtemp(join(tmpdir(), 'bugsee-failspill-')); + await realWriteFile(join(dir, 'a.js'), 'a();\n'); + failSpill.on = true; +}); +afterEach(async () => { + failSpill.on = false; + failSpill.rm = false; + await rm(dir, { recursive: true, force: true }); + await rm(spillRoot, { recursive: true, force: true }); +}); + +describe('a snapshot that fails midway', () => { + it('removes its spill directory, runs NO inject (an unverifiable stamp is not applied) and reports it', async () => { + const run = vi.fn(async () => ({ code: 0, stdout: '', stderr: '' })); + const errors: unknown[] = []; + const result = await uploadSourcemaps({ + outDir: dir, + appToken: 'tok', + appVersion: '1', + appBuild: '1', + run, + spillRoot, + findSri: async () => [], + onError: (e) => errors.push(e), + }); + expect(await readdir(spillRoot)).toEqual([]); // nothing leaked + expect(run).not.toHaveBeenCalled(); + expect(String(errors[0])).toContain('ENOSPC'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + }); + + it('throws under failOnError', async () => { + await expect( + uploadSourcemaps({ + outDir: dir, + appToken: 'tok', + appVersion: '1', + appBuild: '1', + run: vi.fn(), + spillRoot, + findSri: async () => [], + failOnError: true, + }), + ).rejects.toThrow(/ENOSPC/); + expect(await readdir(spillRoot)).toEqual([]); + }); +}); + +describe('a spill directory that cannot be removed (EPERM / EBUSY)', () => { + const ok = async () => ({ code: 0, stdout: '', stderr: '' }); + const base = () => ({ + outDir: dir, + appToken: 'tok', + appVersion: '1', + appBuild: '1', + run: ok, + deleteMaps: false, + findSri: async () => [], + }); + + it('never fails a build whose upload succeeded: reported, not thrown (even under failOnError)', async () => { + failSpill.on = false; + failSpill.rm = true; + const errors: unknown[] = []; + const result = await uploadSourcemaps({ + ...base(), + spillRoot, + failOnError: true, + onError: (e) => errors.push(e), + }); + expect(result.uploaded).toBe(true); + expect(String(errors[0])).toContain('EPERM'); + expect(String(errors[0])).toContain('spill'); + failSpill.rm = false; + }); + + it('does not mask the error that was already being reported', async () => { + failSpill.on = false; + failSpill.rm = true; + const errors: unknown[] = []; + const result = await uploadSourcemaps({ + ...base(), + spillRoot, + run: async () => { + throw new Error('cli exploded'); + }, + onError: (e) => errors.push(e), + }); + expect(result.uploaded).toBe(false); + expect(errors.map(String).join('|')).toContain('cli exploded'); + expect(errors.map(String).join('|')).toContain('EPERM'); + failSpill.rm = false; + }); +}); diff --git a/packages/bundler-plugin-core/src/stamp-files.test.ts b/packages/bundler-plugin-core/src/stamp-files.test.ts new file mode 100644 index 000000000..7c0eb7823 --- /dev/null +++ b/packages/bundler-plugin-core/src/stamp-files.test.ts @@ -0,0 +1,1028 @@ +import { randomBytes } from 'node:crypto'; +import { + chmod, + lstat, + mkdir, + mkdtemp, + readdir, + readFile, + rm, + stat, + symlink, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + cutAtQuery, + isFencedPath, + isProjectRootOrAbove, + isUploadableMap, + listOutputMaps, + ownedBy, + partitionByKeyed, + restoreAtomically, + restorePaths, + sameAsSnapshot, + snapshotStampFiles, + verifyAndRestore, + verifyStampedOnDisk, +} from './stamp-files'; + +vi.mock('node:crypto', async (importOriginal) => { + const real = await importOriginal(); + return { ...real, randomBytes: vi.fn(real.randomBytes) }; +}); + +/** A root runner (CAP_DAC_OVERRIDE) writes into a 0o555 directory anyway: such tests cannot run there. */ +async function cannotBlockWrites(): Promise { + const probe = await mkdtemp(join(tmpdir(), 'bugsee-perm-probe-')); + try { + await chmod(probe, 0o555); + await writeFile(join(probe, 'x'), ''); + return true; + } catch { + return false; + } finally { + await chmod(probe, 0o755).catch(() => undefined); + await rm(probe, { recursive: true, force: true }); + } +} + +const ID = 'b039c7fb-d958-5fe6-b76f-136179e9a728'; +const STAMP = `\n;1;\n//# debugId=${ID}\n`; +const plainMap = '{"version":3,"sources":[],"mappings":""}'; +const stampedMap = JSON.stringify({ version: 3, sources: [], mappings: '', debugId: ID }); + +let dir: string; +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-sf-')); +}); +afterEach(async () => { + await rm(dir, { recursive: true, force: true }); +}); + +describe('snapshot + verifyAndRestore', () => { + it('keeps the originals OUTSIDE memory: a spill directory that is removed on dispose', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + const snap = await snapshotStampFiles({ dir }); + expect(snap.entries.get(join(dir, 'a.js'))?.hash).toMatch(/^[0-9a-f]{40}$/); + const spill = snap.spillDir; + expect((await readdir(spill)).length).toBe(1); + await snap.dispose(); + await expect(readdir(spill)).rejects.toMatchObject({ code: 'ENOENT' }); + }); + + it('verifies a faithful stamp, including a map named by the pointer, restoring nothing', async () => { + await mkdir(join(dir, 'maps')); + await writeFile(join(dir, 'a.js'), 'a();\n//# sourceMappingURL=maps/a.map\n'); + await writeFile(join(dir, 'maps', 'a.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=maps/a.map\n${STAMP}`); + await writeFile(join(dir, 'maps', 'a.map'), stampedMap); + const result = await verifyAndRestore(snap); + expect(result).toEqual({ issues: [], restored: [], failed: [] }); + await snap.dispose(); + }); + + it('restores a failing bundle and its custom-named map as a pair, bundle first', async () => { + await mkdir(join(dir, 'maps')); + const original = 'a();\n//# sourceMappingURL=maps/a.map\n'; + await writeFile(join(dir, 'a.js'), original); + await writeFile(join(dir, 'maps', 'a.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), `${original}{{${STAMP}`); + await writeFile(join(dir, 'maps', 'a.map'), stampedMap); + const { issues, restored, failed } = await verifyAndRestore(snap); + expect(issues.length).toBeGreaterThan(0); + expect(restored).toEqual([join(dir, 'a.js'), join(dir, 'maps', 'a.map')]); + expect(failed).toEqual([]); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe(original); + expect(await readFile(join(dir, 'maps', 'a.map'), 'utf8')).toBe(plainMap); + // No temp file is left behind by the atomic restore. + expect((await readdir(dir)).sort()).toEqual(['a.js', 'maps']); + await snap.dispose(); + }); + + it('a map-only failure restores its bundle too', async () => { + const original = 'a();\n//# sourceMappingURL=a.js.map\n'; + await writeFile(join(dir, 'a.js'), original); + await writeFile(join(dir, 'a.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), `${original}${STAMP}`); + await writeFile(join(dir, 'a.js.map'), 'not json'); + const { restored, issues } = await verifyAndRestore(snap); + expect(issues).toHaveLength(1); // the bad map once, not once per loop + expect(restored).toEqual([join(dir, 'a.js'), join(dir, 'a.js.map')]); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe(original); + await snap.dispose(); + }); + + describe('a changed map beside an UNCHANGED, already-stamped bundle is held to that bundle id', () => { + const OTHER = '11111111-2222-5333-8444-555555555555'; + const stamped = `a();\n//# sourceMappingURL=a.js.map\n${STAMP}`; + const mapWith = (id: string) => + JSON.stringify({ version: 3, sources: [], mappings: '', debugId: id }); + + it('fails and restores a map whose debugId differs from the bundle, leaving the bundle alone', async () => { + await writeFile(join(dir, 'a.js'), stamped); + await writeFile(join(dir, 'a.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js.map'), mapWith(OTHER)); // rewritten, valid JSON, WRONG id + const { issues, restored, failed } = await verifyAndRestore(snap); + expect(issues.map((i) => i.name)).toEqual([join(dir, 'a.js.map')]); + expect(issues[0]?.reason).toContain(`${OTHER} does not match`); + expect(restored).toEqual([join(dir, 'a.js.map')]); + expect(failed).toEqual([]); + expect(await readFile(join(dir, 'a.js.map'), 'utf8')).toBe(plainMap); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe(stamped); + await snap.dispose(); + }); + + it('resolves the bundle through a custom-named map pointer too', async () => { + await mkdir(join(dir, 'maps')); + const code = `a();\n//# sourceMappingURL=maps/a.map\n${STAMP}`; + await writeFile(join(dir, 'a.js'), code); + await writeFile(join(dir, 'maps', 'a.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'maps', 'a.map'), mapWith(OTHER)); + const { issues, restored } = await verifyAndRestore(snap); + expect(issues).toHaveLength(1); + expect(restored).toEqual([join(dir, 'maps', 'a.map')]); + await snap.dispose(); + }); + + it('falls back to the .map sibling when the pointer names a file that is not there', async () => { + const code = `a();\n//# sourceMappingURL=missing.map\n${STAMP}`; + await writeFile(join(dir, 'a.js'), code); + await writeFile(join(dir, 'a.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js.map'), mapWith(OTHER)); + const { issues, restored } = await verifyAndRestore(snap); + expect(issues).toHaveLength(1); + expect(restored).toEqual([join(dir, 'a.js.map')]); + await snap.dispose(); + }); + + it('accepts a map that carries the bundle id', async () => { + await writeFile(join(dir, 'a.js'), stamped); + await writeFile(join(dir, 'a.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js.map'), mapWith(ID)); + expect(await verifyAndRestore(snap)).toEqual({ issues: [], restored: [], failed: [] }); + await snap.dispose(); + }); + + it('ignores a bundle that points at a different map, and one deleted meanwhile', async () => { + await writeFile(join(dir, 'a.js'), stamped); // points at a.js.map + await writeFile(join(dir, 'gone.js'), `g();\n//# sourceMappingURL=a.js.map\n${STAMP}`); + await writeFile(join(dir, 'a.js.map'), plainMap); + await writeFile(join(dir, 'b.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await rm(join(dir, 'gone.js')); + await writeFile(join(dir, 'b.js.map'), mapWith(OTHER)); // no bundle names b.js.map: only JSON-checked + expect(await verifyAndRestore(snap)).toEqual({ issues: [], restored: [], failed: [] }); + await snap.dispose(); + }); + }); + + it('a changed map with no changed bundle is held to being JSON, and is restored when it is not', async () => { + await writeFile(join(dir, 'x.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'x.js.map'), 'garbage'); + const { issues, restored } = await verifyAndRestore(snap); + expect(issues.map((i) => i.name)).toEqual([join(dir, 'x.js.map')]); + expect(restored).toEqual([join(dir, 'x.js.map')]); + expect(await readFile(join(dir, 'x.js.map'), 'utf8')).toBe(plainMap); + await snap.dispose(); + }); + + it('a file deleted meanwhile is not part of the comparison', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + const snap = await snapshotStampFiles({ dir }); + await rm(join(dir, 'a.js')); + expect(await verifyAndRestore(snap)).toEqual({ issues: [], restored: [], failed: [] }); + await snap.dispose(); + }); + + it('a file that vanishes before the snapshot read is skipped', async () => { + const snap = await snapshotStampFiles({ files: [join(dir, 'never-there.js')] }); + expect(snap.entries.size).toBe(0); + await snap.dispose(); + }); + + it('a restore that fails midway is REPORTED by name and leaves no temp file; the others still restore', async () => { + const original = 'a();\n//# sourceMappingURL=a.js.map\n'; + await writeFile(join(dir, 'a.js'), original); + await writeFile(join(dir, 'a.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), `${original}{{${STAMP}`); + await writeFile(join(dir, 'a.js.map'), stampedMap); + const attempted: string[] = []; + const { restored, failed } = await verifyAndRestore(snap, { + restoreFile: async (spill, path) => { + attempted.push(path); + if (path.endsWith('.js')) { + throw new Error('EIO: disk gone'); + } + await writeFile(path, await readFile(spill)); + }, + }); + expect(attempted).toEqual([join(dir, 'a.js')]); // bundle first; its map is NOT tried once the bundle failed + expect(failed.map((f) => f.path)).toEqual([join(dir, 'a.js'), join(dir, 'a.js.map')]); + expect(failed[0]?.error).toContain('EIO'); + expect(failed[1]?.error).toContain('bundle'); // its map is not restored under a still-stamped bundle + expect(restored).toEqual([]); + await snap.dispose(); + }); + + it('the default restore is write-temp-then-rename: when it cannot write, the target is left as it was and no temp file remains', async (ctx) => { + if (await cannotBlockWrites()) { + ctx.skip(); + } + const original = 'a();\n'; + await writeFile(join(dir, 'a.js'), original); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), `a();\n{{${STAMP}`); + await chmod(dir, 0o555); // the directory refuses new files, so the temp write fails + try { + const { failed, restored } = await verifyAndRestore(snap); + expect(restored).toEqual([]); + expect(failed.map((f) => f.path)).toEqual([join(dir, 'a.js')]); + } finally { + await chmod(dir, 0o755); + } + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe(`a();\n{{${STAMP}`); // intact, not half-written + expect(await readdir(dir)).toEqual(['a.js']); + await snap.dispose(); + }); + + it('only one pair is in memory at a time: the snapshot holds hashes, not bytes', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + const snap = await snapshotStampFiles({ dir }); + for (const entry of snap.entries.values()) { + expect(Object.keys(entry).sort()).toEqual(['hash', 'spill']); + } + await snap.dispose(); + }); +}); + +describe("restoreAtomically keeps the target's identity", () => { + it('keeps the file mode (a 0755 shebang bundle stays executable)', async () => { + await writeFile(join(dir, 'spill'), '#!/usr/bin/env node\n'); + await writeFile(join(dir, 'cli.js'), 'stamped'); + await chmod(join(dir, 'cli.js'), 0o755); + await restoreAtomically(join(dir, 'spill'), join(dir, 'cli.js')); + if (process.platform !== 'win32') { + // Windows cannot set the execute bits: the exact mode is a POSIX property + expect((await stat(join(dir, 'cli.js'))).mode & 0o777).toBe(0o755); + } + expect(await readFile(join(dir, 'cli.js'), 'utf8')).toBe('#!/usr/bin/env node\n'); + }); + it('restores THROUGH a symlink: the link stays a link and its real file is replaced', async () => { + await writeFile(join(dir, 'spill'), 'original'); + await writeFile(join(dir, 'real.js'), 'stamped'); + await symlink('real.js', join(dir, 'link.js')); + await restoreAtomically(join(dir, 'spill'), join(dir, 'link.js')); + expect((await lstat(join(dir, 'link.js'))).isSymbolicLink()).toBe(true); + expect(await readFile(join(dir, 'real.js'), 'utf8')).toBe('original'); + expect((await readdir(dir)).sort()).toEqual(['link.js', 'real.js', 'spill']); + }); + it('a target that no longer exists is simply recreated', async () => { + await writeFile(join(dir, 'spill'), 'original'); + await restoreAtomically(join(dir, 'spill'), join(dir, 'gone.js')); + expect(await readFile(join(dir, 'gone.js'), 'utf8')).toBe('original'); + }); +}); + +describe('restore order: the bundle goes back before its map, whatever they are called', () => { + it('records bundle-then-map for a map that sorts BEFORE its bundle', async () => { + const pairs = [ + ['b.js', 'a.map'], + ['z.js', 'a.js.map'], + ] as const; + for (const [bundle, map] of pairs) { + const original = `x();\n//# sourceMappingURL=${map}\n`; + await writeFile(join(dir, bundle), original); + await writeFile(join(dir, map), plainMap); + } + const snap = await snapshotStampFiles({ dir }); + for (const [bundle, map] of pairs) { + await writeFile(join(dir, bundle), `x();\n//# sourceMappingURL=${map}\n{{${STAMP}`); + await writeFile(join(dir, map), stampedMap); + } + const order: string[] = []; + await verifyAndRestore(snap, { + restoreFile: async (spill, path) => { + order.push(path.slice(dir.length + 1)); + await writeFile(path, await readFile(spill)); + }, + }); + expect(order).toEqual(['b.js', 'z.js', 'a.js.map', 'a.map']); + await snap.dispose(); + }); +}); + +describe('restoreAtomically', () => { + it('replaces the target via a temp file, and removes the temp file when the rename fails', async () => { + await writeFile(join(dir, 'spill'), 'original'); + await writeFile(join(dir, 'target.js'), 'stamped'); + await restoreAtomically(join(dir, 'spill'), join(dir, 'target.js')); + expect(await readFile(join(dir, 'target.js'), 'utf8')).toBe('original'); + expect((await readdir(dir)).sort()).toEqual(['spill', 'target.js']); + + // A non-empty directory in the target's place: the temp write succeeds, the rename cannot. + await mkdir(join(dir, 'blocked')); + await writeFile(join(dir, 'blocked', 'x'), 'x'); + await expect(restoreAtomically(join(dir, 'spill'), join(dir, 'blocked'))).rejects.toThrow(); + expect((await readdir(dir)).sort()).toEqual(['blocked', 'spill', 'target.js']); + }); +}); + +describe('isProjectRootOrAbove — the working directory itself', () => { + it('is true for the cwd (and "."), false for a child, even without a package.json', async () => { + const start = process.cwd(); + await mkdir(join(dir, 'child')); + process.chdir(dir); + try { + expect(await isProjectRootOrAbove(dir)).toBe(true); + expect(await isProjectRootOrAbove('.')).toBe(true); + expect(await isProjectRootOrAbove(join(dir, 'child'))).toBe(false); + } finally { + process.chdir(start); + } + }); +}); + +describe('isProjectRootOrAbove', () => { + it('is true for the cwd, "." and any ancestor of the cwd', async () => { + expect(await isProjectRootOrAbove(process.cwd())).toBe(true); + expect(await isProjectRootOrAbove(dirname(process.cwd()))).toBe(true); + expect(await isProjectRootOrAbove('.')).toBe(true); + }); + it('is false for an ordinary output directory, even one with a package.json marker (dist/cjs, ng-packagr)', async () => { + await mkdir(join(dir, 'dist', 'cjs'), { recursive: true }); + await writeFile(join(dir, 'dist', 'cjs', 'package.json'), '{"type":"commonjs"}'); + await writeFile(join(dir, 'dist', 'package.json'), '{"name":"copied"}'); + expect(await isProjectRootOrAbove(join(dir, 'dist', 'cjs'))).toBe(false); + expect(await isProjectRootOrAbove(join(dir, 'dist'))).toBe(false); + }); + it('is false for a directory that merely shares a name prefix with the cwd', async () => { + expect(await isProjectRootOrAbove(`${process.cwd()}-sibling`)).toBe(false); + expect(await isProjectRootOrAbove(process.cwd().slice(0, -1))).toBe(false); // a prefix of the name, not an ancestor + }); +}); + +describe('isProjectRootOrAbove — a working directory that no longer exists', () => { + it('is false rather than throwing', async () => { + const start = process.cwd(); + const gone = join(dir, 'gone'); + await mkdir(gone); + process.chdir(gone); + await rm(gone, { recursive: true }); + try { + expect(await isProjectRootOrAbove(dir)).toBe(false); + } finally { + process.chdir(start); + } + }); +}); + +describe('a dist/cjs with a package.json marker is snapshotted and verified like any output dir', () => { + it('restores a bad stamp there', async () => { + await mkdir(join(dir, 'cjs')); + await writeFile(join(dir, 'cjs', 'package.json'), '{"type":"commonjs"}'); + await writeFile(join(dir, 'cjs', 'a.js'), 'a();\n'); + const snap = await snapshotStampFiles({ dir: join(dir, 'cjs') }); + expect(snap.entries.has(join(dir, 'cjs', 'a.js'))).toBe(true); + await writeFile(join(dir, 'cjs', 'a.js'), `a();\n{{${STAMP}`); + expect((await verifyAndRestore(snap)).restored).toEqual([join(dir, 'cjs', 'a.js')]); + await snap.dispose(); + }); +}); + +describe('snapshot walk fence (4): only a project root is fenced', () => { + it('walks src, test and dot-directories of an ordinary output dir (preserveModules: dist/src/a.js)', async () => { + await mkdir(join(dir, 'out', 'src'), { recursive: true }); + await mkdir(join(dir, 'out', '.hidden')); + await mkdir(join(dir, 'out', 'node_modules')); + await writeFile(join(dir, 'out', 'src', 'a.js'), 'a();\n'); + await writeFile(join(dir, 'out', '.hidden', 'h.js'), 'h();\n'); + await writeFile(join(dir, 'out', 'node_modules', 'n.js'), 'n();\n'); + const snap = await snapshotStampFiles({ dir: join(dir, 'out') }); + const names = [...snap.entries.keys()] + .map((k) => k.slice(join(dir, 'out').length + 1).replace(/\\/g, '/')) + .sort(); + expect(names).toEqual(['.hidden/h.js', 'node_modules/n.js', 'src/a.js']); + await writeFile(join(dir, 'out', 'src', 'a.js'), `a();\n{{${STAMP}`); + expect((await verifyAndRestore(snap)).restored).toEqual([join(dir, 'out', 'src', 'a.js')]); + await snap.dispose(); + }); + it('fences src, test, node_modules and dot-directories when the directory IS the project root', async () => { + const start = process.cwd(); + await mkdir(join(dir, 'src')); + await mkdir(join(dir, '.hidden')); + await mkdir(join(dir, 'lib')); + await writeFile(join(dir, 'src', 's.js'), 's();\n'); + await writeFile(join(dir, '.hidden', 'g.js'), 'g();\n'); + await writeFile(join(dir, 'lib', 'l.js'), 'l();\n'); + process.chdir(dir); + try { + const snap = await snapshotStampFiles({ dir }); + expect([...snap.entries.keys()].map((k) => k.slice(dir.length + 1))).toEqual(['lib/l.js']); + await snap.dispose(); + } finally { + process.chdir(start); + } + }); +}); + +describe('verifyStampedOnDisk', () => { + it('checks only the named bundles, resolving each pair from its pointer, one at a time', async () => { + await mkdir(join(dir, 'maps')); + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=maps/a.map\n${STAMP}`); + await writeFile(join(dir, 'maps', 'a.map'), stampedMap); + // Never part of the bundle: unstamped, with a map — must not be judged. + await writeFile(join(dir, 'vendor.js'), 'v();\n'); + await writeFile(join(dir, 'vendor.js.map'), plainMap); + expect(await verifyStampedOnDisk([join(dir, 'a.js')])).toEqual([]); + await writeFile(join(dir, 'maps', 'a.map'), plainMap); + expect((await verifyStampedOnDisk([join(dir, 'a.js')])).map((i) => i.name)).toEqual([ + join(dir, 'maps', 'a.map'), + ]); + }); + it('falls back to the sibling .map when the pointer names a file that is not there', async () => { + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=gone.map\n${STAMP}`); + await writeFile(join(dir, 'a.js.map'), stampedMap); + expect(await verifyStampedOnDisk([join(dir, 'a.js')])).toEqual([]); + }); + it('the sibling fallback is really used: a pointer at a missing file, an UNSTAMPED .map beside it', async () => { + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=gone.map\n${STAMP}`); + await writeFile(join(dir, 'a.js.map'), plainMap); + expect((await verifyStampedOnDisk([join(dir, 'a.js')])).map((i) => i.name)).toEqual([ + join(dir, 'a.js.map'), + ]); + }); + + it('a pointer at an existing map wins, and a missing sibling is no problem', async () => { + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=real.map\n${STAMP}`); + await writeFile(join(dir, 'real.map'), plainMap); + expect((await verifyStampedOnDisk([join(dir, 'a.js')])).map((i) => i.name)).toEqual([ + join(dir, 'real.map'), + ]); + await writeFile(join(dir, 'real.map'), stampedMap); + expect(await verifyStampedOnDisk([join(dir, 'a.js')])).toEqual([]); + }); + + it('a bundle with no map at all is left alone', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + expect(await verifyStampedOnDisk([join(dir, 'a.js')])).toEqual([]); + }); +}); + +describe('isUploadableMap — what the CLI scans a directory for', () => { + it('is every .map except stylesheet and declaration maps', () => { + for (const yes of ['a.js.map', 'a.mjs.map', 'index.map', 'dir/b.cjs.map', 'x.bundle.jsx.map']) { + expect(isUploadableMap(yes), yes).toBe(true); + } + for (const no of ['a.css.map', 'a.d.ts.map', 'a.d.mts.map', 'a.d.cts.map', 'a.js', 'map']) { + expect(isUploadableMap(no), no).toBe(false); + } + }); +}); + +describe('partitionByKeyed — any uploadable map needs a key, whatever it is called', () => { + it('keeps an unkeyed index.map, deletes a keyed one, and deletes a stylesheet/declaration map', async () => { + await writeFile(join(dir, 'keyed.map'), stampedMap); + await writeFile(join(dir, 'unkeyed.map'), plainMap); + await writeFile(join(dir, 'a.css.map'), plainMap); + await writeFile(join(dir, 'a.d.ts.map'), plainMap); + const names = ['keyed.map', 'unkeyed.map', 'a.css.map', 'a.d.ts.map'].map((n) => join(dir, n)); + const { deletable, kept } = await partitionByKeyed(names); + expect(kept).toEqual([join(dir, 'unkeyed.map')]); + expect(deletable.sort()).toEqual( + [join(dir, 'a.css.map'), join(dir, 'a.d.ts.map'), join(dir, 'keyed.map')].sort(), + ); + }); +}); + +describe('partitionByKeyed — a map that cannot be read is not "gone"', () => { + it('keeps (never silently drops) a map that fails to read with anything but ENOENT', async () => { + await writeFile(join(dir, 'locked.js.map'), stampedMap); + await chmod(join(dir, 'locked.js.map'), 0o000); + try { + const { deletable, kept } = await partitionByKeyed([ + join(dir, 'locked.js.map'), + join(dir, 'vanished.js.map'), + ]); + expect(kept).toEqual([join(dir, 'locked.js.map')]); + expect(deletable).toEqual([]); // the vanished one is neither kept nor deleted + } finally { + await chmod(join(dir, 'locked.js.map'), 0o644); + } + }); +}); + +describe('listOutputMaps', () => { + it('lists EVERY map of the whole output directory (any name, src/ and dot-dirs included), sorted, stylesheet and declaration maps too', async () => { + await mkdir(join(dir, 'src')); + await mkdir(join(dir, '.hidden')); + await mkdir(join(dir, 'test')); + await writeFile(join(dir, 'src', 'a.js.map'), '{}'); + await writeFile(join(dir, '.hidden', 'b.mjs.map'), '{}'); + await writeFile(join(dir, 'test', 't.map'), '{}'); + await writeFile(join(dir, 'index.map'), '{}'); + await writeFile(join(dir, 'c.css.map'), '{}'); + await writeFile(join(dir, 'd.d.ts.map'), '{}'); + await writeFile(join(dir, 'e.js'), 'x'); + expect( + (await listOutputMaps(dir)).map((f) => f.slice(dir.length + 1).replace(/\\/g, '/')).sort(), + ).toEqual([ + '.hidden/b.mjs.map', + 'c.css.map', + 'd.d.ts.map', + 'index.map', + 'src/a.js.map', + 'test/t.map', + ]); + }); + it('is fenced at the project root', async () => { + const start = process.cwd(); + await mkdir(join(dir, 'src')); + await writeFile(join(dir, 'src', 'a.js.map'), '{}'); + await writeFile(join(dir, 'ok.map'), '{}'); + process.chdir(dir); + try { + expect( + (await listOutputMaps(dir)).map((f) => f.slice(dir.length + 1).replace(/\\/g, '/')).sort(), + ).toEqual(['ok.map']); + } finally { + process.chdir(start); + } + }); +}); + +describe('depth: an ordinary output directory is walked to any depth (the CLI scan and inject have no cap)', () => { + const deepDir = async (levels: number): Promise => { + let d = dir; + for (let i = 0; i < levels; i++) { + d = join(d, `d${i}`); + await mkdir(d); + } + return d; + }; + it('lists a map 8 levels down and snapshots + restores the bundle beside it', async () => { + const deep = await deepDir(8); + await writeFile(join(deep, 'deep.js.map'), '{}'); + await writeFile(join(deep, 'deep.js'), 'a();\n'); + expect(await listOutputMaps(dir)).toEqual([join(deep, 'deep.js.map')]); + const snap = await snapshotStampFiles({ dir }); + expect(snap.entries.has(join(deep, 'deep.js'))).toBe(true); + await writeFile(join(deep, 'deep.js'), `a();\n{{${STAMP}`); + expect((await verifyAndRestore(snap)).restored).toEqual([ + join(deep, 'deep.js'), + join(deep, 'deep.js.map'), + ]); + await snap.dispose(); + }); + it('at a PROJECT ROOT the depth cap still bounds the walk', async () => { + const start = process.cwd(); + const deep = await deepDir(8); + await writeFile(join(deep, 'deep.js.map'), '{}'); + process.chdir(dir); + try { + expect(await listOutputMaps(dir)).toEqual([]); + } finally { + process.chdir(start); + } + }); +}); + +describe("isFencedPath — directories that are not this build's output", () => { + it('is true when any directory segment is a never-walk name or a dot-directory', () => { + for (const rel of [ + 'node_modules/p/a.css.map', + 'a/src/b.d.ts.map', + '.cache/x.map', + 'x/.well-known/y.map', + 'test/t.map', + '__tests__/a.map', + ]) { + expect(isFencedPath(rel), rel).toBe(true); + } + for (const rel of ['a.css.map', 'assets/a.css.map', 'srcs/a.map', 'a/b/.hidden.map']) { + expect(isFencedPath(rel), rel).toBe(false); + } + }); +}); + +describe('verifyAndRestore — a map that lives OUTSIDE the snapshotted output', () => { + it('flags and restores a stamped bundle whose pointer reaches a map outside the directory', async () => { + await mkdir(join(dir, 'out', 'js'), { recursive: true }); + await mkdir(join(dir, 'maps')); + await writeFile(join(dir, 'maps', 'a.js.map'), plainMap); + const original = 'a();\n//# sourceMappingURL=../../maps/a.js.map\n'; + await writeFile(join(dir, 'out', 'js', 'a.js'), original); + const snap = await snapshotStampFiles({ dir: join(dir, 'out') }); + await writeFile(join(dir, 'out', 'js', 'a.js'), `${original}${STAMP}`); + const { issues, restored } = await verifyAndRestore(snap); + expect(issues[0]?.reason).toContain('outside the output directory'); + expect(restored).toEqual([join(dir, 'out', 'js', 'a.js')]); + expect(await readFile(join(dir, 'out', 'js', 'a.js'), 'utf8')).toBe(original); + await snap.dispose(); + }); +}); + +describe("verifyStampedOnDisk — the build's own bundle -> map mapping", () => { + it('checks a map the pointer and sibling both miss (Rollup moved map), and flags a lost id', async () => { + await mkdir(join(dir, 'js')); + await mkdir(join(dir, 'maps')); + await writeFile(join(dir, 'js', 'a.js'), `a();\n//# sourceMappingURL=a.map\n${STAMP}`); + await writeFile(join(dir, 'maps', 'a.js.map'), plainMap); + const hint = new Map([[join(dir, 'js', 'a.js'), join(dir, 'maps', 'a.js.map')]]); + expect(await verifyStampedOnDisk([join(dir, 'js', 'a.js')])).toEqual([]); // without the hint: blind + expect((await verifyStampedOnDisk([join(dir, 'js', 'a.js')], hint)).map((i) => i.name)).toEqual( + [join(dir, 'maps', 'a.js.map')], + ); + await writeFile(join(dir, 'maps', 'a.js.map'), stampedMap); + expect(await verifyStampedOnDisk([join(dir, 'js', 'a.js')], hint)).toEqual([]); + }); +}); + +describe('verifyStampedOnDisk — when the known map is gone', () => { + it('falls back to the bundle pointer, then reports a map the stamp named that cannot be read at all', async () => { + await mkdir(join(dir, 'maps')); + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=maps/current.map\n${STAMP}`); + await writeFile(join(dir, 'maps', 'current.map'), plainMap); // the pointed map exists and lost its id + const known = new Map([[join(dir, 'a.js'), join(dir, 'gone.map')]]); + // the missing known map must not leave the pointed one unchecked + expect((await verifyStampedOnDisk([join(dir, 'a.js')], known)).map((i) => i.name)).toEqual([ + join(dir, 'maps', 'current.map'), + ]); + await rm(join(dir, 'maps', 'current.map')); + const lost = await verifyStampedOnDisk([join(dir, 'a.js')], known); + expect(lost.map((i) => i.name)).toEqual([join(dir, 'gone.map')]); + expect(lost[0]?.reason).toContain('could not be read'); + // a bundle that never had a known map is no issue + expect(await verifyStampedOnDisk([join(dir, 'a.js')])).toEqual([]); + }); +}); + +describe('verifyStampedOnDisk — the known map wins over the pointer', () => { + it('verifies the known map when both it and the pointed map exist', async () => { + await mkdir(join(dir, 'maps')); + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=maps/pointed.map\n${STAMP}`); + await writeFile(join(dir, 'maps', 'pointed.map'), stampedMap); + await writeFile(join(dir, 'maps', 'known.map'), plainMap); // lost its id: only the known map reveals it + const known = new Map([[join(dir, 'a.js'), join(dir, 'maps', 'known.map')]]); + expect((await verifyStampedOnDisk([join(dir, 'a.js')], known)).map((i) => i.name)).toEqual([ + join(dir, 'maps', 'known.map'), + ]); + }); +}); + +describe('verifyAndRestore — a dangling pointer is not an outside map', () => { + it('raises nothing for a pointer at a file that does not exist anywhere', async () => { + const original = 'a();\n//# sourceMappingURL=../../nowhere/a.js.map\n'; + await mkdir(join(dir, 'out')); + await writeFile(join(dir, 'out', 'a.js'), original); + const snap = await snapshotStampFiles({ dir: join(dir, 'out') }); + await writeFile(join(dir, 'out', 'a.js'), `${original}${STAMP}`); + expect(await verifyAndRestore(snap)).toEqual({ issues: [], restored: [], failed: [] }); + await snap.dispose(); + }); +}); + +describe('ownedBy — is this file one THIS build emitted?', () => { + it('matches by identity: normalised separators, ./ prefixes, exact case', () => { + const own = ownedBy('/o/dist', ['src/style.css.map', './assets\\a.d.ts.map', 'Case.js.map']); + expect(own('/o/dist/src/style.css.map')).toBe(true); + expect(own('/o/dist/assets/a.d.ts.map')).toBe(true); + expect(own('/o/dist/case.js.map')).toBe(false); // case-sensitive + expect(own('/o/dist/Case.js.map')).toBe(true); + expect(own('/o/dist/src/old.d.ts.map')).toBe(false); // there, but not emitted by this build + expect(own('/o/dist/node_modules/p/style.css.map')).toBe(false); + }); + it('an empty set owns nothing', () => { + expect(ownedBy('/o', [])('/o/a.css.map')).toBe(false); + }); + it('without a set it falls back to the directory-name fence', () => { + const own = ownedBy('/o/dist', undefined); + expect(own('/o/dist/src/a.css.map')).toBe(false); + expect(own('/o/dist/.cache/a.css.map')).toBe(false); + expect(own('/o/dist/assets/a.css.map')).toBe(true); + }); +}); + +describe('an uppercase A.JS / A.JS.map pair goes through snapshot, verify and restore', () => { + it('is snapshotted, and a bad stamp is restored with its map', async () => { + const original = 'a();\n//# sourceMappingURL=A.JS.map\n'; + await writeFile(join(dir, 'A.JS'), original); + await writeFile(join(dir, 'A.JS.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + expect([...snap.entries.keys()].map((k) => k.slice(dir.length + 1)).sort()).toEqual([ + 'A.JS', + 'A.JS.map', + ]); + await writeFile(join(dir, 'A.JS'), `${original}{{${STAMP}`); + await writeFile(join(dir, 'A.JS.map'), stampedMap); + const { restored } = await verifyAndRestore(snap); + expect(restored).toEqual([join(dir, 'A.JS'), join(dir, 'A.JS.map')]); + expect(await readFile(join(dir, 'A.JS'), 'utf8')).toBe(original); + await snap.dispose(); + }); + it('a faithful stamp of the pair verifies', async () => { + const original = 'a();\n//# sourceMappingURL=A.JS.map\n'; + await writeFile(join(dir, 'A.JS'), original); + await writeFile(join(dir, 'A.JS.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'A.JS'), `${original}${STAMP}`); + await writeFile(join(dir, 'A.JS.map'), stampedMap); + expect(await verifyAndRestore(snap)).toEqual({ issues: [], restored: [], failed: [] }); + await snap.dispose(); + }); +}); + +// GROUND TRUTH (real builds): webpack/Rspack drop `?...` when they write a file (`x.js.map?h` -> `x.js.map`) and KEEP +// `#` (`a#1.js` is written as `a#1.js`). Rollup/Vite write every name literally, `?` and `#` included +// (`index.js?v=1` -> `index.js?v=1`). +describe('ownedBy — what the bundlers really write', () => { + it('matches a webpack ?query own-name to the file on disk without the query, and a literal name to itself', () => { + const own = ownedBy('/o/dist', ['main.js.map?abc123', 'index.js?v=1', 'index.js?v=1.map']); + expect(own('/o/dist/main.js.map')).toBe(true); // webpack: query dropped + expect(own('/o/dist/index.js?v=1')).toBe(true); // Rollup: written literally + expect(own('/o/dist/index.js?v=1.map')).toBe(true); + expect(own('/o/dist/index.js?old')).toBe(false); // a stale foreign sibling is not this build's + expect(own('/o/dist/other.js.map')).toBe(false); + }); + it('treats # as part of the name: a#1 is not a#2, and x#old is not x#new', () => { + const own = ownedBy('/o/dist', ['main#new.js.map', 'a#1.js']); + expect(own('/o/dist/main#new.js.map')).toBe(true); + expect(own('/o/dist/main#old.js.map')).toBe(false); + expect(own('/o/dist/main.js.map')).toBe(false); + expect(own('/o/dist/a#1.js')).toBe(true); + expect(own('/o/dist/a#2.js')).toBe(false); + expect(own('/o/dist/a')).toBe(false); // nothing is cut at the # + }); +}); + +describe('ownedBy — Windows separators and ./ prefixes (win32 path API, on any host)', () => { + it('matches own names written with / or \\ or a leading ./ against win32 disk paths', async () => { + const { win32 } = await import('node:path'); + const own = ownedBy('C:\\o\\dist', ['src/a.css.map', './b.css.map', 'c\\d.css.map'], win32); + expect(own('C:\\o\\dist\\src\\a.css.map')).toBe(true); + expect(own('C:\\o\\dist\\b.css.map')).toBe(true); + expect(own('C:\\o\\dist\\c\\d.css.map')).toBe(true); + expect(own('C:\\o\\dist\\src\\other.css.map')).toBe(false); + // the directory-name fallback uses the same API + const fenced = ownedBy('C:\\o\\dist', undefined, win32); + expect(fenced('C:\\o\\dist\\node_modules\\p\\a.css.map')).toBe(false); + expect(fenced('C:\\o\\dist\\assets\\a.css.map')).toBe(true); + }); +}); + +describe('cutAtQuery', () => { + it('cuts at the first ? only (a # stays), and leaves a name with no ? alone', () => { + expect(cutAtQuery('main.js?abc?d')).toBe('main.js'); + expect(cutAtQuery('a#1.js')).toBe('a#1.js'); + expect(cutAtQuery('x.js')).toBe('x.js'); + expect(cutAtQuery('?q')).toBe(''); + }); +}); + +describe('review hardening of the snapshot / restore / on-disk check', () => { + it('a snapshot aborts (and removes its spill) on a read error that is NOT a missing file', async () => { + const spillRoot = await mkdtemp(join(tmpdir(), 'bugsee-spill-abort-')); + try { + await mkdir(join(dir, 'adir')); // readFile(directory) -> EISDIR, not ENOENT + await expect(snapshotStampFiles({ files: [join(dir, 'adir')] }, spillRoot)).rejects.toThrow(); + expect(await readdir(spillRoot)).toEqual([]); + } finally { + await rm(spillRoot, { recursive: true, force: true }); + } + }); + + it('a bundle that disappears after the change scan is skipped; the other bad pair is still restored', async () => { + const aOriginal = 'a();\n//# sourceMappingURL=a.js.map\n'; + await writeFile(join(dir, 'a.js'), aOriginal); + await writeFile(join(dir, 'a.js.map'), plainMap); + await writeFile(join(dir, 'b.js'), 'b();\n//# sourceMappingURL=b.js.map\n'); + await writeFile(join(dir, 'b.js.map'), plainMap); + // explicit order (a before b): the walk order of a directory is not guaranteed + const snap = await snapshotStampFiles({ + files: ['a.js', 'a.js.map', 'b.js', 'b.js.map'].map((n) => join(dir, n)), + }); + await writeFile(join(dir, 'a.js'), `${aOriginal}{{${STAMP}`); + await writeFile(join(dir, 'b.js'), `b();\n//# sourceMappingURL=b.js.map\n${STAMP}`); + const { rmSync } = await import('node:fs'); + let removedWhileParsingA = false; + const result = await verifyAndRestore(snap, { + parse: (code) => { + // verifying a.js: b.js vanishes before its own turn + if (code.includes('{{')) { + rmSync(join(dir, 'b.js'), { force: true }); + removedWhileParsingA = true; + } + return !code.includes('{{'); + }, + }); + expect(removedWhileParsingA).toBe(true); + expect(result.restored).not.toContain(join(dir, 'b.js')); + expect(result.restored).toContain(join(dir, 'a.js')); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe(aOriginal); + await snap.dispose(); + }); + + it('the rollback partner is chosen by the ORIGINAL pointer, even if the bad stamp changed it', async () => { + await mkdir(join(dir, 'maps')); + const original = 'm();\n//# sourceMappingURL=maps/m.map\n'; + await writeFile(join(dir, 'm.js'), original); + await writeFile(join(dir, 'maps', 'm.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + // the bad stamp breaks the bundle AND points it somewhere else; the real map got stamped + await writeFile(join(dir, 'm.js'), `m();\n//# sourceMappingURL=elsewhere.map\n{{${STAMP}`); + await writeFile(join(dir, 'maps', 'm.map'), stampedMap); + const { restored } = await verifyAndRestore(snap); + expect(restored).toEqual([join(dir, 'm.js'), join(dir, 'maps', 'm.map')]); + expect(await readFile(join(dir, 'maps', 'm.map'), 'utf8')).toBe(plainMap); + await snap.dispose(); + }); + + it('a map is NOT restored when its bundle could not be (that would leave a stamped bundle beside an unstamped map)', async () => { + const original = 'a();\n//# sourceMappingURL=a.js.map\n'; + await writeFile(join(dir, 'a.js'), original); + await writeFile(join(dir, 'a.js.map'), plainMap); + await writeFile(join(dir, 'z.js'), 'z();\n//# sourceMappingURL=z.js.map\n'); + await writeFile(join(dir, 'z.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), `${original}{{${STAMP}`); + await writeFile(join(dir, 'a.js.map'), stampedMap); + await writeFile(join(dir, 'z.js'), `z();\n//# sourceMappingURL=z.js.map\n{{${STAMP}`); + await writeFile(join(dir, 'z.js.map'), stampedMap); + const { restored, failed } = await verifyAndRestore(snap, { + restoreFile: async (spill, target) => { + if (target === join(dir, 'a.js')) throw new Error('EIO'); + await writeFile(target, await readFile(spill)); + }, + }); + expect(restored).toEqual([join(dir, 'z.js'), join(dir, 'z.js.map')]); // the unrelated pair still restores + expect(failed.map((f) => f.path).sort()).toEqual([join(dir, 'a.js'), join(dir, 'a.js.map')]); + expect(failed.find((f) => f.path === join(dir, 'a.js.map'))?.error).toContain('bundle'); + expect(await readFile(join(dir, 'a.js.map'), 'utf8')).toBe(stampedMap); // untouched, reported incomplete + await snap.dispose(); + }); + + it('verifyStampedOnDisk reports a bundle the stamp named that is missing or unreadable', async () => { + const issues = await verifyStampedOnDisk([join(dir, 'gone.js')]); + expect(issues).toEqual([ + { name: join(dir, 'gone.js'), reason: expect.stringContaining('could not be read') }, + ]); + }); + + it('verifyStampedOnDisk verifies the map the fallback ACTUALLY loaded when the known one is missing', async () => { + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=a.js.map\n${STAMP}`); + await writeFile(join(dir, 'a.js.map'), plainMap); // sibling, unkeyed + const known = new Map([[join(dir, 'a.js'), join(dir, 'missing.map')]]); + const issues = await verifyStampedOnDisk([join(dir, 'a.js')], known); + expect(issues.map((i) => i.name)).toEqual([join(dir, 'a.js.map')]); + }); +}); + +describe('sameAsSnapshot / restorePaths', () => { + it('sameAsSnapshot: true for an unchanged or unknown file, false for a changed or removed one', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + const snap = await snapshotStampFiles({ dir }); + expect(await sameAsSnapshot(snap, join(dir, 'a.js'))).toBe(true); + expect(await sameAsSnapshot(snap, join(dir, 'not-in-snapshot.js'))).toBe(true); + await writeFile(join(dir, 'a.js'), 'changed'); + expect(await sameAsSnapshot(snap, join(dir, 'a.js'))).toBe(false); + await rm(join(dir, 'a.js')); + expect(await sameAsSnapshot(snap, join(dir, 'a.js'))).toBe(false); + await snap.dispose(); + }); + + it('restorePaths puts the originals back, skips unknown files, and returns what it could not restore', async (ctx) => { + if (await cannotBlockWrites()) { + ctx.skip(); + } + await writeFile(join(dir, 'a.js'), 'orig'); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), 'stamped'); + expect(await restorePaths(snap, [join(dir, 'a.js'), join(dir, 'unknown.js')])).toEqual([]); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe('orig'); + await writeFile(join(dir, 'a.js'), 'stamped'); + await chmod(dir, 0o555); + try { + const failed = await restorePaths(snap, [join(dir, 'a.js')]); + expect(failed.map((f) => f.path)).toEqual([join(dir, 'a.js')]); + } finally { + await chmod(dir, 0o755); + } + await snap.dispose(); + }); +}); + +describe("the rollback partner is the ORIGINAL pointer's map even when the changed pointer names ANOTHER snapshotted map", () => { + it('restores maps/m.map (original partner), not x.map (where the bad stamp pointed)', async () => { + await mkdir(join(dir, 'maps')); + const original = 'm();\n//# sourceMappingURL=maps/m.map\n'; + await writeFile(join(dir, 'm.js'), original); + await writeFile(join(dir, 'maps', 'm.map'), plainMap); + await writeFile(join(dir, 'x.map'), plainMap); // an unrelated, snapshotted map + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'm.js'), `m();\n//# sourceMappingURL=x.map\n{{${STAMP}`); + await writeFile(join(dir, 'maps', 'm.map'), stampedMap); // the real map got stamped + const { restored } = await verifyAndRestore(snap); + expect(restored).toContain(join(dir, 'maps', 'm.map')); + expect(await readFile(join(dir, 'maps', 'm.map'), 'utf8')).toBe(plainMap); + await snap.dispose(); + }); +}); + +describe('restoreAtomically — concurrent restores never share a temp file', () => { + it('two restores in one directory started in the same millisecond both land their own bytes', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000); + try { + await writeFile(join(dir, 'spill-a'), 'original-a'); + await writeFile(join(dir, 'spill-b'), 'original-b'); + await writeFile(join(dir, 'a.js'), 'stamped-a'); + await writeFile(join(dir, 'b.js'), 'stamped-b'); + await Promise.all([ + restoreAtomically(join(dir, 'spill-a'), join(dir, 'a.js')), + restoreAtomically(join(dir, 'spill-b'), join(dir, 'b.js')), + ]); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe('original-a'); + expect(await readFile(join(dir, 'b.js'), 'utf8')).toBe('original-b'); + expect((await readdir(dir)).sort()).toEqual(['a.js', 'b.js', 'spill-a', 'spill-b']); + } finally { + now.mockRestore(); + } + }); + it('never removes a temp file it does not own (an exclusive create that finds one fails clean)', async () => { + await writeFile(join(dir, 'spill'), 'original'); + await writeFile(join(dir, 'a.js'), 'stamped'); + (randomBytes as unknown as ReturnType).mockReturnValueOnce(Buffer.alloc(8)); + const temp = join(dir, `.bugsee-restore-${process.pid}-0000000000000000`); + await writeFile(temp, 'someone else'); + await expect(restoreAtomically(join(dir, 'spill'), join(dir, 'a.js'))).rejects.toThrow( + /EEXIST/, + ); + expect(await readFile(temp, 'utf8')).toBe('someone else'); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe('stamped'); + }); +}); + +describe('verifyAndRestore — a changed file that cannot be read is not "deleted"', () => { + it('reports a non-ENOENT read failure as an issue (and restores it); a deleted file stays silent', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + await writeFile(join(dir, 'gone.js'), 'g();\n'); + const snap = await snapshotStampFiles({ dir }); + await rm(join(dir, 'gone.js')); + await rm(join(dir, 'a.js')); + await mkdir(join(dir, 'a.js')); // reading a directory: EISDIR, not ENOENT + const result = await verifyAndRestore(snap, { restoreFile: async () => undefined }); + expect(result.issues).toEqual([ + { name: join(dir, 'a.js'), reason: expect.stringMatching(/could not be read.*EISDIR/s) }, + ]); + expect(result.restored).toEqual([join(dir, 'a.js')]); + await snap.dispose(); + }); + it('a failed restore of the unreadable file is returned in `failed` (what failOnError acts on)', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + const snap = await snapshotStampFiles({ dir }); + await rm(join(dir, 'a.js')); + await mkdir(join(dir, 'a.js')); + const result = await verifyAndRestore(snap); + expect(result.issues).toHaveLength(1); + expect(result.failed.map((f) => f.path)).toEqual([join(dir, 'a.js')]); + await snap.dispose(); + }); +}); + +describe("verifyAndRestore — a rewrite that points at ANOTHER bundle's map does not take that map over", () => { + it("restores the other bundle's map when the pointing bundle cannot be restored", async () => { + // a.js is processed first and owns a.js.map; b.js's bad stamp then points at a.js.map. + await writeFile(join(dir, 'a.js'), 'a();\n//# sourceMappingURL=a.js.map\n'); + await writeFile(join(dir, 'b.js'), 'b();\n//# sourceMappingURL=b.js.map\n'); + await writeFile(join(dir, 'a.js.map'), plainMap); + await writeFile(join(dir, 'b.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=a.js.map\n{{${STAMP}`); + await writeFile(join(dir, 'b.js'), `b();\n//# sourceMappingURL=a.js.map\n{{${STAMP}`); + await writeFile(join(dir, 'a.js.map'), stampedMap); + await writeFile(join(dir, 'b.js.map'), stampedMap); + const { restored, failed } = await verifyAndRestore(snap, { + restoreFile: async (spill, target) => { + if (target === join(dir, 'b.js')) { + throw new Error('EPERM'); + } + await writeFile(target, await readFile(spill)); + }, + }); + expect(failed.map((f) => f.path)).toContain(join(dir, 'b.js')); + expect(restored).toContain(join(dir, 'a.js')); + expect(restored).toContain(join(dir, 'a.js.map')); + await snap.dispose(); + }); +}); diff --git a/packages/bundler-plugin-core/src/stamp-files.ts b/packages/bundler-plugin-core/src/stamp-files.ts new file mode 100644 index 000000000..eb9acdbbe --- /dev/null +++ b/packages/bundler-plugin-core/src/stamp-files.ts @@ -0,0 +1,592 @@ +// The on-disk side of stamp verification and of map deletion (orchestrate.ts drives it). +// +// The in-build path verifies in memory (stamp-assets.ts). The POST-EMIT path lets `bugsee-cli` rewrite the +// output in place, so to be able to say "that stamp is not safe, put the original back" the original bytes +// have to be taken BEFORE the rewrite. That is what the snapshot is for: it covers the build's own scripts +// and maps (bounded by the same walk rules the map deletion uses), and nothing else. +// +// The originals are SPILLED to a temp directory with a content hash beside them, not held in memory: a +// build can have hundreds of megabytes of scripts and maps, and the verification only ever needs one +// bundle and its map at a time. +import { createHash, randomBytes } from 'node:crypto'; +import type { Dirent } from 'node:fs'; +import { + chmod, + mkdtemp, + readdir, + readFile, + realpath, + rename, + rm, + stat, + unlink, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path, { dirname, join, posix, resolve, sep } from 'node:path'; +import { + localPointerTarget, + resolveMapName, + type StampIssue, + verifyStamp, + verifyStampedPairs, +} from './verify-stamp'; + +/** + * Directories never descended into when walking build output. + * + * A relative `output.file` resolves the output dir to `'.'` — `path.dirname('bundle.js') === '.'`, an + * entirely ordinary Rollup library config — so a walk started at the PROJECT ROOT. With no exclusions the + * map deletion unlinked dependency source maps under `node_modules/` and a developer's own authored maps + * under `src/`: silent, unrecoverable loss in the working tree. The same walk now also feeds the + * pre-stamp snapshot, and a restore writes files, so it must have the same fence. + */ +export const NEVER_WALK = new Set([ + 'node_modules', + 'src', + '.git', + '.next', + '.nuxt', + '.svelte-kit', + '.cache', + 'test', + 'tests', + '__tests__', +]); + +/** + * Depth limit for the walk. Build output is shallow (`dist/assets/chunk.js.map` is 2); an unbounded walk + * from a mis-resolved root could traverse an entire disk. + */ +export const MAX_WALK_DEPTH = 6; + +/** + * Whether a path RELATIVE to an output directory runs through a directory that is not this build's output: + * a never-walk name (`node_modules`, `src`, `test`, …) or a dot-directory. Files there are not this build's to + * delete (the CLI's directory scan does reach them, which is why the upload is not the reference). + */ +export function isFencedPath(relative: string): boolean { + return relative + .split(/[\\/]/) + .slice(0, -1) + .some((segment) => NEVER_WALK.has(segment) || segment.startsWith('.')); +} + +/** The name up to its `?query` (webpack drops it on disk). indexOf, not a regex: it runs on library input. */ +export function cutAtQuery(name: string): string { + const at = name.indexOf('?'); + return at === -1 ? name : name.slice(0, at); +} + +/** + * Whether a file under `outDir` is one THIS build emitted. By IDENTITY: the names the bundler reports for its + * own output (relative to the output directory; separators and a leading `./` normalised, case exact), not + * by what a directory is called. A foreign file can sit anywhere, under any name. With no names (a directory + * run where the build's output is not known) it falls back to the directory-name fence. + */ +export function ownedBy( + outDir: string, + ownFiles: readonly string[] | undefined, + /** The path implementation `outDir` and the files follow (the host's by default). */ + api: Pick = path, +): (file: string) => boolean { + if (ownFiles === undefined) { + return (file) => !isFencedPath(api.relative(outDir, file)); + } + // GROUND TRUTH (real builds): webpack/Rspack drop `?...` when they write a file (`x.js.map?h` -> `x.js.map`) + // and KEEP `#` (`a#1.js` stays); Rollup/Vite write every name literally (`index.js?v=1` stays). So each + // own name is known both literally and without its `?query`, and a file on disk is compared literally: + // a stale `x#old.js.map` or `index.js?old` is never mistaken for this build's. + const normal = (name: string): string => posix.normalize(name.replace(/\\/g, '/')); + const owned = new Set(ownFiles.flatMap((name) => [normal(name), normal(cutAtQuery(name))])); + return (file) => owned.has(normal(api.relative(outDir, file))); +} + +/** What inject can change: the scripts it stamps and the maps it pairs with them. */ +const STAMPABLE = /\.([cm]?js|map)$/i; + +/** Every stampable file under `dir`. An unreadable directory contributes nothing (never throws). */ +async function walkStampable(dir: string, fenced: boolean, depth = 0): Promise { + // The depth cap bounds a walk from a PROJECT ROOT only. In an ordinary output directory the CLI's scan and + // inject have no limit, so a cap here would leave a deep bundle stamped but never verified, uploaded or deleted. + if (fenced && depth > MAX_WALK_DEPTH) { + return []; + } + let entries: Dirent[]; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + // Not this layer's error to raise: the CLI reports a missing output directory properly, and + // throwing here would replace that with a worse message. + return []; + } + const found: string[] = []; + for (const entry of entries) { + const full = join(dir, entry.name); + if (entry.isDirectory()) { + if (!fenced || (!NEVER_WALK.has(entry.name) && !entry.name.startsWith('.'))) { + found.push(...(await walkStampable(full, fenced, depth + 1))); + } + } else if (entry.isFile() && STAMPABLE.test(entry.name)) { + found.push(full); + } + } + return found; +} + +/** Where to look: a directory (walked), or exactly the files a build reported as its own. */ +export type SnapshotTarget = { dir: string } | { files: readonly string[] }; + +/** What is kept of one original: where it was spilled, and its content hash (to tell what changed). */ +export interface SnapshotEntry { + spill: string; + hash: string; +} + +/** The originals of the build's scripts and maps, on disk in a private temp directory. */ +export interface StampSnapshot { + entries: Map; + spillDir: string; + /** Remove the spill directory. Always call it. */ + dispose(): Promise; +} + +const sha1 = (bytes: Buffer): string => createHash('sha1').update(bytes).digest('hex'); + +/** + * Whether `dir` IS the working directory or CONTAINS it. That is what a mis-resolved output directory + * looks like (a bare `output.file: 'bundle.js'` resolves to `'.'`), and a snapshot-and-restore there would + * reach across the project tree, so callers refuse to snapshot or restore it. + * + * Deliberately not "has a package.json": `dist/cjs` with a `{"type":"commonjs"}` marker, or a `dist/` with + * a copied manifest (ng-packagr), are ordinary output directories and must be verified like any other. + */ +export async function isProjectRootOrAbove(dir: string): Promise { + // Real paths: the cwd is reported resolved (macOS /private/var), an output directory may be spelled + // through a symlink. + const full = await realpath(dir).catch(() => resolve(dir)); + let cwd: string; + try { + cwd = await realpath(process.cwd()); + } catch { + // The working directory is gone: nothing can be the project root. + return false; + } + return cwd === full || cwd.startsWith(full.endsWith(sep) ? full : full + sep); +} + +/** + * Spill the originals of every stampable file in `target`. A file that is gone is skipped. If spilling + * fails (a full disk), the spill directory is removed and the error propagates: the caller has not + * injected yet, and an unverifiable, unrestorable stamp is exactly what this layer exists to prevent. + * + * The walk is fenced (`src`, `test`, `node_modules`, dot-directories skipped) ONLY when the directory is + * the project root or above: there it keeps the walk out of the source tree. In an ordinary output + * directory inject stamps everything (Rollup `preserveModules` writes `dist/src/*.js`), so the snapshot + * must see everything inject can change. + */ +export async function snapshotStampFiles( + target: SnapshotTarget, + /** Where the spill directory is created (default: the OS temp directory). */ + spillRoot: string = tmpdir(), +): Promise { + const paths = + 'dir' in target + ? await walkStampable(target.dir, await isProjectRootOrAbove(target.dir)) + : target.files; + const spillDir = await mkdtemp(join(spillRoot, 'bugsee-orig-')); + const entries = new Map(); + try { + let index = 0; + for (const original of paths) { + let bytes: Buffer; + try { + bytes = await readFile(original); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + // Gone between listing and reading (a concurrent build's cleanup): nothing to verify or restore. + continue; + } + // Anything else (EACCES, EISDIR, a transient I/O error) is NOT "gone": injecting with an incomplete + // snapshot would leave a file nothing can verify or restore. Abort (the spill is removed below). + throw error; + } + const spill = join(spillDir, String(index++)); + await writeFile(spill, bytes); + entries.set(original, { spill, hash: sha1(bytes) }); + } + } catch (error) { + await rm(spillDir, { recursive: true, force: true }); + throw error; + } + return { + entries, + spillDir, + dispose: () => rm(spillDir, { recursive: true, force: true }), + }; +} + +/** Whether `file` still has the bytes it had when the snapshot was taken (false when it changed or is gone). */ +export async function sameAsSnapshot(snapshot: StampSnapshot, file: string): Promise { + const entry = snapshot.entries.get(file); + if (entry === undefined) { + return true; + } + try { + return sha1(await readFile(file)) === entry.hash; + } catch { + return false; + } +} + +/** Put the ORIGINAL bytes of these files back (atomically); returns the ones that could not be restored. */ +export async function restorePaths( + snapshot: StampSnapshot, + files: readonly string[], +): Promise> { + const failed: Array<{ path: string; error: string }> = []; + for (const file of files) { + const entry = snapshot.entries.get(file); + if (entry === undefined) { + continue; + } + try { + await restoreAtomically(entry.spill, file); + } catch (error) { + failed.push({ path: file, error: String(error) }); + } + } + return failed; +} + +export interface RestoreOptions { + /** Injectable JavaScript parser for the verification (default: acorn). */ + parse?: (code: string) => boolean; + /** Injectable restore of one file from its spilled original (default: write temp, then rename). */ + restoreFile?: (spill: string, target: string) => Promise; +} + +/** + * Atomic restore: the target is either the stamped file or the original, never half of either, and it + * keeps its identity — the file mode (a 0755 shebang bundle stays executable) and, when the path is a + * symlink, the link itself (the real file behind it is replaced). + */ +export async function restoreAtomically(spill: string, target: string): Promise { + const real = await realpath(target).catch(() => target); + const mode = await stat(real).then( + (info) => info.mode & 0o7777, + () => undefined, + ); + // Unique per call (concurrent runs of one process restore into the same directory) and created exclusively + // (`wx`): a name that already exists is never written to, and never removed by a call that did not create it. + const temp = join( + dirname(real), + `.bugsee-restore-${process.pid}-${randomBytes(8).toString('hex')}`, + ); + const bytes = await readFile(spill); + try { + await writeFile(temp, bytes, { flag: 'wx' }); + if (mode !== undefined) { + await chmod(temp, mode); + } + await rename(temp, real); + } catch (error) { + // A temp file that already existed (EEXIST) is someone else's: only one this call created is removed. + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') { + await unlink(temp).catch(() => undefined); + } + throw error; + } +} + +/** + * Verify what inject left on disk against the snapshot, and put the ORIGINAL bytes back for every file that + * failed — together with its partner (a bundle and its map are restored as a pair, so a build is never + * left half-stamped: a bundle with an id and a map without one is worse than neither). The bundle goes back + * first. A restore that fails is not swallowed: it is returned by name in `failed`, and the others still run. + * + * Only one bundle and its map are held in memory at a time. The pair is resolved from the bundle's own + * `sourceMappingURL`, so a map with a custom name is held to its bundle too. + */ +export async function verifyAndRestore( + snapshot: StampSnapshot, + options: RestoreOptions = {}, +): Promise<{ + issues: StampIssue[]; + restored: string[]; + failed: Array<{ path: string; error: string }>; +}> { + const { entries } = snapshot; + const unreadable = new Map(); + const read = async (file: string): Promise => { + try { + return await readFile(file); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + // Not "deleted": a file that cannot be read cannot be verified, and it may still carry a bad rewrite. + unreadable.set(file, String(error)); + } + return undefined; // deleted meanwhile: not part of the comparison + } + }; + const original = (file: string): Promise => + readFile((entries.get(file) as SnapshotEntry).spill); + + // What changed, by hash — one file in memory at a time. + const changed: string[] = []; + for (const [file, entry] of entries) { + const now = await read(file); + if (now !== undefined && sha1(now) !== entry.hash) { + changed.push(file); + } + } + + const issues: StampIssue[] = []; + const partner = new Map(); + const paired = new Set(); + const stampedBundles = changed.filter((file) => /\.[cm]?js$/i.test(file)); + for (const bundle of stampedBundles) { + const after = await read(bundle); + if (after === undefined) { + continue; // removed since the change scan: nothing to compare, and a restore would not recreate it + } + const map = resolveMapName(bundle, after.toString('utf8'), (n) => entries.has(n), path); + paired.add(map); + const originalBundle = await original(bundle); + // The ROLLBACK partner is the map the ORIGINAL bundle pointed at (a bad stamp may have changed the pointer); + // verification still looks at the current one. + const originalMap = resolveMapName( + bundle, + originalBundle.toString('utf8'), + (n) => entries.has(n), + path, + ); + if (entries.has(originalMap)) { + partner.set(bundle, originalMap); + partner.set(originalMap, bundle); + } + const before = new Map([[bundle, originalBundle]]); + const now = new Map([[bundle, after]]); + if (entries.has(map)) { + partner.set(bundle, partner.get(bundle) ?? map); + // A rollback relationship the ORIGINAL pointers established is never replaced by a changed pointer. + if (!partner.has(map)) { + partner.set(map, bundle); + } + before.set(map, await original(map)); + const mapNow = await read(map); + if (mapNow !== undefined) { + now.set(map, mapNow); + } + } + issues.push(...verifyStamp(before, now, options.parse, path)); + // A pointer that reaches a map OUTSIDE the snapshotted output: inject cannot have stamped it. + const target = localPointerTarget(bundle, after.toString('utf8'), path); + if ( + target !== undefined && + !entries.has(target) && + (await stat(target).then( + () => true, + () => false, + )) + ) { + issues.push({ + name: bundle, + reason: `its source map (${target}) lies outside the output directory, so it cannot be stamped with the bundle`, + }); + } + } + for (const file of changed) { + if (file.endsWith('.map') && !paired.has(file)) { + const before = new Map([[file, await original(file)]]); + const now = new Map([[file, (await read(file)) as Buffer]]); + // A map rewritten beside an UNCHANGED bundle (one stamped earlier, which inject left alone) must still + // agree with that bundle's id: hand the bundle to the verifier, as the paired path does. (A CHANGED bundle that + // names this map would have paired it above, so every bundle reaching the check here is unchanged.) + for (const name of entries.keys()) { + if (!/\.[cm]?js$/i.test(name)) { + continue; + } + const bytes = await read(name); + if (bytes === undefined) { + continue; + } + if (resolveMapName(name, bytes.toString('utf8'), (n) => entries.has(n), path) === file) { + before.set(name, bytes); + now.set(name, bytes); + } + } + issues.push(...verifyStamp(before, now, options.parse, path)); + } + } + + // A file that cannot be read now is an incomplete verification: reported (and restored from its original), + // never silently skipped. Unrelated pairs were still checked above. + for (const [file, error] of unreadable) { + issues.push({ name: file, reason: `it could not be read to verify the stamp: ${error}` }); + } + + const toRestore = new Set(); + for (const { name } of issues) { + toRestore.add(name); + const other = partner.get(name); + if (other !== undefined) { + toRestore.add(other); + } + } + const restoreFile = options.restoreFile ?? restoreAtomically; + const restored: string[] = []; + const failed: Array<{ path: string; error: string }> = []; + // Bundles before maps: if the run dies halfway, a bundle with no id beside a map with one is the + // lesser harm (the upload then fails loudly) than a stamped bundle beside an unstamped map. + const order = [...toRestore].sort( + (a, b) => Number(a.endsWith('.map')) - Number(b.endsWith('.map')) || a.localeCompare(b), + ); + const failedPaths = new Set(); + for (const file of order) { + // A map is not restored when its bundle could not be: the stamped bundle would then point at an + // original map that does not carry its new id. Reported as incomplete; unrelated pairs still restore. + const pairedBundle = file.endsWith('.map') ? partner.get(file) : undefined; + if (pairedBundle !== undefined && failedPaths.has(pairedBundle)) { + failedPaths.add(file); + failed.push({ + path: file, + error: `not restored: its bundle ${pairedBundle} could not be restored`, + }); + continue; + } + try { + await restoreFile((entries.get(file) as SnapshotEntry).spill, file); + restored.push(file); + } catch (error) { + failedPaths.add(file); + failed.push({ path: file, error: String(error) }); + } + } + return { issues, restored, failed }; +} + +/** + * Check the named bundles AS THEY ARE ON DISK after the bundler wrote them (the in-build path): each bundle + * with a map must carry a debugId its map shares (verifyStampedPairs). Only these bundles are judged — never + * the directory — so a file that was not part of the bundle (a `public/` script, a stale file with + * `emptyOutDir: false`) is not mistaken for one the stamp missed. One bundle and its map in memory at a time. + */ +export async function verifyStampedOnDisk( + bundles: readonly string[], + /** The build's own bundle -> map mapping (absolute paths), tried before the pointer and the sibling. */ + known: ReadonlyMap = new Map(), +): Promise { + const issues: StampIssue[] = []; + for (const bundle of bundles) { + let code: Buffer; + try { + code = await readFile(bundle); + } catch (error) { + // The stamp named this bundle, so it must be there: say so rather than skip it (a stale or public + // script is never in `bundles`, so this does not judge them). + issues.push({ + name: bundle, + reason: `the stamped bundle could not be read: ${String(error)}`, + }); + continue; + } + const files = new Map([[bundle, code]]); + const pointed = resolveMapName(bundle, code.toString('utf8'), () => true, path); + const hinted = known.get(bundle); + // The pair that was ACTUALLY loaded is the one verified (a missing known map must not make a loaded + // sibling go unchecked). + let hint: ReadonlyMap = new Map(); + // Candidates in order: the build's own map, the bundle's pointer, the `.map` sibling inject pairs by + // default. The first that loads is the one verified. + const candidates = [...new Set([hinted, pointed, `${bundle}.map`])].filter( + (name): name is string => name !== undefined, + ); + let loaded = false; + for (const candidate of candidates) { + try { + files.set(candidate, await readFile(candidate)); + loaded = true; + if (candidate === hinted) { + hint = known; // only once the known map was really loaded + } + break; + } catch { + // try the next candidate + } + } + if (!loaded && hinted !== undefined) { + issues.push({ name: hinted, reason: 'the stamped map could not be read' }); + continue; + } + issues.push(...verifyStampedPairs(files, hint)); + } + return issues; +} + +/** Maps `debug-files upload` never takes: stylesheet and declaration maps have no debug-id. */ +const NOT_UPLOADED_MAP = /\.(css|d\.ts|d\.mts|d\.cts)\.map$/; + +/** + * Whether `path` is a map the CLI scans a directory for: every `*.map` except stylesheet and declaration + * maps. NOT only `*.js.map`: the stamp keys a map whatever it is called (`sourcemapFileName(s)`, webpack's + * `[name].map`), so a narrower filter would silently drop a stamped build's maps. + */ +export function isUploadableMap(path: string): boolean { + return path.endsWith('.map') && !NOT_UPLOADED_MAP.test(path); +} + +/** + * Every map under `dir` (`*.map`, whatever its name), walked like the snapshot: the whole output directory, + * fenced only at a project root. The SINGLE walk behind what a pre-stamped build uploads and deletes; the + * caller splits it with {@link isUploadableMap}. + */ +export async function listOutputMaps(dir: string): Promise { + const all = await walkStampable(dir, await isProjectRootOrAbove(dir)); + return all.filter((file) => file.endsWith('.map')); +} + +/** + * Split `maps` into those that may be deleted after an upload and those that must be kept. + * + * `debug-files upload` skips a map with no debug-id and still exits 0 (it counts it as `unkeyed`), so "the + * upload command succeeded" does NOT mean "this map was uploaded". Deleting on that evidence destroys the + * only copy of a mapping whose symbols never left the build machine. A script map is therefore deletable + * only if it carries a `debugId`/`debug_id` — what makes it keyed. Anything else (a stylesheet map, which + * is never uploaded and embeds the source, so privacy still wants it gone) is deletable as before. A map + * that cannot be read or parsed is kept: not confirmed means not deleted. + */ +export async function partitionByKeyed( + maps: readonly string[], +): Promise<{ deletable: string[]; kept: string[] }> { + const deletable: string[] = []; + const kept: string[] = []; + for (const path of maps) { + if (!isUploadableMap(path)) { + deletable.push(path); + continue; + } + let text: string; + try { + text = await readFile(path, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + // Already gone: nothing to delete and nothing to keep. + continue; + } + // Anything else (EACCES, a map too large to read as a string) is NOT "gone": it cannot be confirmed + // keyed, so it is neither uploaded nor deleted, and the caller says so. + kept.push(path); + continue; + } + let keyed = false; + try { + const parsed = JSON.parse(text) as { debugId?: unknown; debug_id?: unknown } | null; + keyed = [parsed?.debugId, parsed?.debug_id].some((id) => typeof id === 'string' && id !== ''); + } catch { + // Not JSON: cannot have been keyed. + } + (keyed ? deletable : kept).push(path); + } + return { deletable, kept }; +} diff --git a/packages/bundler-plugin-core/src/verify-stamp.test.ts b/packages/bundler-plugin-core/src/verify-stamp.test.ts new file mode 100644 index 000000000..156b65f20 --- /dev/null +++ b/packages/bundler-plugin-core/src/verify-stamp.test.ts @@ -0,0 +1,572 @@ +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { + formatIssues, + parseScript, + resolveMapName, + verifyStamp, + verifyStampedPairs, +} from './verify-stamp'; + +const ID = 'b039c7fb-d958-5fe6-b76f-136179e9a728'; +const OTHER_ID = '4adb7053-e754-594c-96b5-09c18263b153'; +const STUB = + '\n;!function(){try{var e="undefined"!=typeof window?window:{},n=(new e.Error).stack;n&&(e._bugseeDebugIds=e._bugseeDebugIds||{},e._bugseeDebugIds[n]="' + + ID + + '")}catch(e){}}();\n//# debugId=' + + ID + + '\n'; + +const buf = (text: string): Buffer => Buffer.from(text); +const mapJson = (extra: object = {}): string => + JSON.stringify({ version: 3, sources: ['a.ts'], names: [], mappings: 'AAAA', ...extra }); +const stampedMap = (id = ID): string => mapJson({ debug_id: id, debugId: id }); + +/** One bundle + its map, before and after a faithful stamp. */ +function faithful(): { before: Map; after: Map } { + const code = 'console.log(1);\n//# sourceMappingURL=a.js.map\n'; + return { + before: new Map([ + ['a.js', buf(code)], + ['a.js.map', buf(mapJson())], + ]), + after: new Map([ + ['a.js', buf(code + STUB)], + ['a.js.map', buf(stampedMap())], + ]), + }; +} + +describe('verifyStamp', () => { + it('accepts exactly what `sourcemaps inject` produces', () => { + const { before, after } = faithful(); + expect(verifyStamp(before, after)).toEqual([]); + }); + + it('ignores assets inject did not change (even a bundle that does not parse)', () => { + const bytes = buf('this is not ( javascript'); + expect(verifyStamp(new Map([['x.js', bytes]]), new Map([['x.js', bytes]]))).toEqual([]); + }); + + describe('(i) a stamped bundle still parses', () => { + it('flags a bundle the stamp broke', () => { + const { before, after } = faithful(); + after.set('a.js', buf(`console.log(1);\n//# sourceMappingURL=a.js.map\n${STUB} {{`)); + const issues = verifyStamp(before, after); + expect(issues.map((i) => i.name)).toContain('a.js'); + expect(issues.find((i) => i.name === 'a.js')?.reason).toMatch(/no longer parses/); + }); + + it('does not blame the stamp for a bundle the parser could not read to begin with', () => { + const original = 'const x = 1 +;\n'; // already invalid + const issues = verifyStamp( + new Map([['a.js', buf(original)]]), + new Map([['a.js', buf(original + STUB)]]), + ); + expect(issues).toEqual([]); + }); + + it('parses ES modules, CommonJS and hashbang scripts', () => { + expect(parseScript('import a from "a"; export default a;')).toBe(true); + expect(parseScript('module.exports = 1; return 2;')).toBe(true); + expect(parseScript('#!/usr/bin/env node\nawait 1;')).toBe(true); + expect(parseScript('with (x) { y }')).toBe(true); // sloppy script, not a module + expect(parseScript('let = ;')).toBe(false); + }); + + it('uses an injected parser', () => { + const { before, after } = faithful(); + const seen: string[] = []; + const issues = verifyStamp(before, after, (code) => { + seen.push(code); + return false; + }); + // Parsed once after, and (because that failed) once before to see who is to blame: it failed too. + expect(seen).toHaveLength(2); + expect(issues).toEqual([]); + }); + }); + + describe('(ii) the sourceMappingURL comment', () => { + it('flags a lost sourceMappingURL comment', () => { + const { before, after } = faithful(); + after.set('a.js', buf(`console.log(1);\n${STUB}`)); + expect(verifyStamp(before, after).some((i) => /sourceMappingURL/.test(i.reason))).toBe(true); + }); + + it('flags a changed sourceMappingURL target', () => { + const { before, after } = faithful(); + after.set('a.js', buf(`console.log(1);\n//# sourceMappingURL=b.js.map\n${STUB}`)); + expect(verifyStamp(before, after).some((i) => /sourceMappingURL/.test(i.reason))).toBe(true); + }); + + it('flags a second sourceMappingURL comment sneaking in after the original', () => { + const { before, after } = faithful(); + after.set( + 'a.js', + buf(`console.log(1);\n//# sourceMappingURL=a.js.map\n${STUB}//# sourceMappingURL=z.map\n`), + ); + expect(verifyStamp(before, after).some((i) => /sourceMappingURL/.test(i.reason))).toBe(true); + }); + + it('is not required of a bundle that never had one', () => { + const code = 'console.log(1);\n'; + const issues = verifyStamp( + new Map([['a.js', buf(code)]]), + new Map([['a.js', buf(code + STUB)]]), + ); + expect(issues).toEqual([]); + }); + + it('does not object to a pointer appearing where there was none (only a lost or changed one is a problem)', () => { + const code = 'console.log(1);\n'; + expect( + verifyStamp( + new Map([['a.js', buf(code)]]), + new Map([['a.js', buf(`${code}${STUB}//# sourceMappingURL=a.js.map\n`)]]), + ), + ).toEqual([]); + }); + + it('accepts the legacy //@ spelling and compares by value', () => { + const code = 'console.log(1);\n//@ sourceMappingURL=a.js.map\n'; + expect( + verifyStamp(new Map([['a.js', buf(code)]]), new Map([['a.js', buf(code + STUB)]])), + ).toEqual([]); + }); + }); + + describe('(iii) the map', () => { + it('flags a map that is not valid JSON', () => { + const { before, after } = faithful(); + after.set('a.js.map', buf('{"version":3,')); + const issue = verifyStamp(before, after).find((i) => i.name === 'a.js.map'); + expect(issue?.reason).toMatch(/not valid JSON/); + }); + + it('flags a map that is not an object', () => { + const { before, after } = faithful(); + after.set('a.js.map', buf('[1]')); + expect(verifyStamp(before, after).find((i) => i.name === 'a.js.map')?.reason).toMatch( + /not valid JSON/, + ); + }); + + it('flags a map with no debugId', () => { + const { before, after } = faithful(); + after.set('a.js.map', buf(mapJson({ debug_id: ID }))); + expect(verifyStamp(before, after).find((i) => i.name === 'a.js.map')?.reason).toMatch( + /no debugId/, + ); + }); + + it("flags a map whose debugId differs from its bundle's comment", () => { + const { before, after } = faithful(); + after.set('a.js.map', buf(stampedMap(OTHER_ID))); + const reason = verifyStamp(before, after).find((i) => i.name === 'a.js.map')?.reason; + expect(reason).toContain(OTHER_ID); + expect(reason).toContain(ID); + }); + + it('flags a stamped bundle whose map was left unstamped', () => { + const { before, after } = faithful(); + after.set('a.js.map', before.get('a.js.map') as Buffer); + expect(verifyStamp(before, after).find((i) => i.name === 'a.js.map')?.reason).toMatch( + /no debugId/, + ); + }); + + it('does not require a map for a bundle that has none', () => { + const code = 'console.log(1);\n'; + expect( + verifyStamp(new Map([['a.js', buf(code)]]), new Map([['a.js', buf(code + STUB)]])), + ).toEqual([]); + }); + + it('flags a bundle with no debugId comment at all when it was changed', () => { + const { before, after } = faithful(); + after.set('a.js', buf('console.log(1);\n//# sourceMappingURL=a.js.map\n;1;\n')); + expect(verifyStamp(before, after).find((i) => i.name === 'a.js')?.reason).toMatch( + /no debugId comment/, + ); + }); + + it('checks a changed map that has no changed bundle for JSON validity only', () => { + const bytes = buf(mapJson()); + expect( + verifyStamp(new Map([['a.js.map', bytes]]), new Map([['a.js.map', buf(stampedMap())]])), + ).toEqual([]); + expect( + verifyStamp(new Map([['a.js.map', bytes]]), new Map([['a.js.map', buf('nope')]])).map( + (i) => i.name, + ), + ).toEqual(['a.js.map']); + }); + }); + + describe('(iv) nothing but the stamp was appended', () => { + it('flags a bundle whose original bytes were altered', () => { + const { before, after } = faithful(); + after.set('a.js', buf(`console.log(2);\n//# sourceMappingURL=a.js.map\n${STUB}`)); + expect(verifyStamp(before, after).find((i) => i.name === 'a.js')?.reason).toMatch( + /original bytes/, + ); + }); + + it('does not apply to a bundle that was already stamped (a re-stamp replaces the old stamp)', () => { + const old = `console.log(1);\n;1;\n//# debugId=${OTHER_ID}\n`; + const fresh = `console.log(1);\n;1;\n//# debugId=${ID}\n`; + const issues = verifyStamp( + new Map([ + ['a.js', buf(old)], + ['a.js.map', buf(stampedMap(OTHER_ID))], + ]), + new Map([ + ['a.js', buf(fresh)], + ['a.js.map', buf(stampedMap())], + ]), + ); + expect(issues).toEqual([]); + }); + }); + + it('only looks at .js/.cjs/.mjs bundles and their .map', () => { + const issues = verifyStamp( + new Map([['a.css', buf('a{}')]]), + new Map([['a.css', buf('changed')]]), + ); + expect(issues).toEqual([]); + const cjs = verifyStamp( + new Map([['a.cjs', buf('1;')]]), + new Map([['a.cjs', buf(`1;${STUB}`)]]), + ); + expect(cjs).toEqual([]); + const mjs = verifyStamp(new Map([['a.mjs', buf('1;')]]), new Map([['a.mjs', buf('1;{{')]])); + expect(mjs.map((i) => i.name)).toContain('a.mjs'); + }); + + it('reports every problem, one entry per file and reason', () => { + const { before, after } = faithful(); + after.set('a.js', buf('{{')); + after.set('a.js.map', buf('x')); + const names = verifyStamp(before, after).map((i) => i.name); + expect(names).toContain('a.js'); + expect(names).toContain('a.js.map'); + }); +}); + +describe('verifyStampedPairs — a build as it is on disk, after the bundler wrote it', () => { + const stamped = (id = ID) => + buf(`x();\n//# sourceMappingURL=a.js.map\n${STUB.replace(new RegExp(ID, 'g'), id)}`); + + it('accepts a bundle and a map that agree', () => { + expect( + verifyStampedPairs( + new Map([ + ['/o/a.js', stamped()], + ['/o/a.js.map', buf(stampedMap())], + ]), + ), + ).toEqual([]); + }); + + it('flags a map whose id was lost after the stamp (another plugin regenerated it)', () => { + const issues = verifyStampedPairs( + new Map([ + ['/o/a.js', stamped()], + ['/o/a.js.map', buf(mapJson())], + ]), + ); + expect(issues).toEqual([{ name: '/o/a.js.map', reason: expect.stringMatching(/no debugId/) }]); + }); + + it('flags a map with a different id', () => { + const issues = verifyStampedPairs( + new Map([ + ['/o/a.js', stamped()], + ['/o/a.js.map', buf(stampedMap(OTHER_ID))], + ]), + ); + expect(issues[0]?.reason).toMatch(/does not match/); + }); + + it('flags a map that is not JSON, and a bundle with a map but no stamp at all', () => { + expect( + verifyStampedPairs( + new Map([ + ['/o/a.js', stamped()], + ['/o/a.js.map', buf('nope')], + ]), + )[0]?.reason, + ).toMatch(/not valid JSON/); + const missed = verifyStampedPairs( + new Map([ + ['/o/b.js', buf('y();\n')], + ['/o/b.js.map', buf(mapJson())], + ]), + ); + expect(missed).toEqual([{ name: '/o/b.js', reason: expect.stringMatching(/not stamped/) }]); + }); + + it('flags a map that carries an id while its bundle lost the comment', () => { + const issues = verifyStampedPairs( + new Map([ + ['/o/c.js', buf('z();\n')], + ['/o/c.js.map', buf(stampedMap())], + ]), + ); + expect(issues[0]?.name).toBe('/o/c.js'); + }); + + it('ignores a bundle with no map, a stylesheet map, and files that are not bundles', () => { + expect( + verifyStampedPairs( + new Map([ + ['/o/vendor.js', buf('v();\n')], + ['/o/a.css.map', buf('{}')], + ['/o/a.css', buf('a{}')], + ]), + ), + ).toEqual([]); + }); +}); + +describe('formatIssues', () => { + it('lists the first three and counts the rest', () => { + const issues = ['a', 'b', 'c', 'd', 'e'].map((name) => ({ name, reason: `bad ${name}` })); + expect(formatIssues(issues)).toBe('a: bad a; b: bad b; c: bad c; and 2 more'); + expect(formatIssues(issues.slice(0, 2))).toBe('a: bad a; b: bad b'); + }); +}); + +describe('resolveMapName — which map belongs to a bundle', () => { + const has = + (...names: string[]) => + (n: string) => + names.includes(n); + it('follows a relative sourceMappingURL from the bundle directory', () => { + expect( + resolveMapName( + 'assets/a.js', + 'x\n//# sourceMappingURL=maps/a.map\n', + has('assets/maps/a.map'), + ), + ).toBe('assets/maps/a.map'); + expect( + resolveMapName('assets/a.js', 'x\n//# sourceMappingURL=../m/a%20b.map\n', has('m/a b.map')), + ).toBe('m/a b.map'); + }); + it('falls back to .map when the pointer is absent, remote, data:, absolute, malformed, or names nothing', () => { + for (const pointer of [ + '', + 'https://cdn.test/a.map', + 'data:application/json;base64,e30=', + '/abs/a.map', + '%E0%A4%A.map', + ]) { + const text = pointer === '' ? 'x\n' : `x\n//# sourceMappingURL=${pointer}\n`; + expect(resolveMapName('a.js', text, has('a.js.map'))).toBe('a.js.map'); + } + expect(resolveMapName('a.js', 'x\n//# sourceMappingURL=gone.map\n', has('a.js.map'))).toBe( + 'a.js.map', + ); + }); +}); + +describe('resolveMapName — never follows a pointer that is not a local file', () => { + it('ignores a remote, data: or root-absolute pointer even when every candidate "exists"', () => { + for (const pointer of [ + 'https://cdn.test/a.map', + 'data:application/json;base64,e30=', + '/abs/a.map', + ]) { + expect(resolveMapName('a.js', `x\n//# sourceMappingURL=${pointer}\n`, () => true)).toBe( + 'a.js.map', + ); + } + }); +}); + +describe('a bad map of a changed bundle is reported once, not twice', () => { + it('verifyStamp', () => { + const code = 'a();\n//# sourceMappingURL=a.js.map\n'; + const issues = verifyStamp( + new Map([ + ['a.js', buf(code)], + ['a.js.map', buf(mapJson())], + ]), + new Map([ + ['a.js', buf(code + STUB)], + ['a.js.map', buf('nope')], + ]), + ); + expect(issues.filter((i) => i.name === 'a.js.map')).toHaveLength(1); + }); +}); + +describe('custom map names (sourcemapFileName / Rolldown)', () => { + const code = 'x();\n//# sourceMappingURL=maps/a.map\n'; + it('verifyStamp holds a map named by the pointer to the bundle id', () => { + const before = new Map([ + ['a.js', buf(code)], + ['maps/a.map', buf(mapJson())], + ]); + const bad = new Map([ + ['a.js', buf(code + STUB)], + ['maps/a.map', buf(mapJson())], + ]); + expect(verifyStamp(before, bad).map((i) => i.name)).toEqual(['maps/a.map']); + const good = new Map([ + ['a.js', buf(code + STUB)], + ['maps/a.map', buf(stampedMap())], + ]); + expect(verifyStamp(before, good)).toEqual([]); + }); + it('verifyStampedPairs resolves the pair from the pointer too', () => { + const files = (map: string) => + new Map([ + ['/o/a.js', buf(code + STUB)], + ['/o/maps/a.map', buf(map)], + ]); + expect(verifyStampedPairs(files(stampedMap()))).toEqual([]); + expect(verifyStampedPairs(files(mapJson())).map((i) => i.name)).toEqual(['/o/maps/a.map']); + }); +}); + +describe('verifyStamp with a native path API (Windows paths)', () => { + it('still resolves a custom-named map from the pointer, so a map without the bundle id is flagged', () => { + const code = 'x();\n//# sourceMappingURL=maps/a.map\n'; + const [bundle, map] = ['C:\\out\\a.js', 'C:\\out\\maps\\a.map']; + const before = new Map([ + [bundle, buf(code)], + [map, buf(mapJson())], + ]); + const bad = new Map([ + [bundle, buf(code + STUB)], + [map, buf(mapJson())], + ]); + expect(verifyStamp(before, bad, undefined, path.win32).map((i) => i.name)).toEqual([map]); + // The default (posix) API cannot follow that pointer, which is why callers on native paths pass theirs. + expect(verifyStamp(before, bad)).toEqual([]); + const good = new Map([ + [bundle, buf(code + STUB)], + [map, buf(stampedMap())], + ]); + expect(verifyStamp(before, good, undefined, path.win32)).toEqual([]); + }); +}); + +describe('pointers with whitespace, and pointers that leave the output', () => { + it('reads a sourceMappingURL with spaces to the end of the line (an unencoded pointer is still a pointer)', () => { + expect( + resolveMapName( + 'j s/a.js', + 'x\n//# sourceMappingURL=../my maps/a.map \n', + (n) => n === 'my maps/a.map', + ), + ).toBe('my maps/a.map'); + }); + + it('flags a stamped bundle whose pointer resolves OUTSIDE the staged output (a silent half-stamp otherwise)', () => { + const code = 'x();\n//# sourceMappingURL=../../maps/a.js.map\n'; + const issues = verifyStamp( + new Map([['js/a.js', buf(code)]]), + new Map([['js/a.js', buf(code + STUB)]]), + ); + expect(issues).toHaveLength(1); + expect(issues[0]).toMatchObject({ name: 'js/a.js' }); + expect(issues[0]?.reason).toContain('outside the output directory'); + expect(issues[0]?.reason).toContain('Emit the maps inside the output directory'); + expect(issues[0]?.reason).toContain('bugsee-cli'); + }); + + it('does not flag a dangling pointer that stays inside the output, a remote or data: one, or a bundle with no pointer', () => { + for (const pointer of [ + 'gone.map', + 'https://cdn.test/a.map', + 'data:application/json;base64,e30=', + '/abs/a.map', + ]) { + const code = `x();\\n//# sourceMappingURL=${pointer}\\n`; + expect( + verifyStamp(new Map([['js/a.js', buf(code)]]), new Map([['js/a.js', buf(code + STUB)]])), + ).toEqual([]); + } + }); + + it('treats an uppercase .JS bundle as a bundle (inject stamps it too)', () => { + const issues = verifyStamp( + new Map([['A.JS', buf('a();\n')]]), + new Map([['A.JS', buf('a();\n{{')]]), + ); + expect(issues.length).toBeGreaterThan(0); + }); +}); + +describe('a changed map is held to an UNCHANGED stamped bundle', () => { + const REG = + '!function(){try{var e=globalThis;e._bugseeDebugIds=e._bugseeDebugIds||{}}catch(e){}}();'; + const stampedCode = (id: string) => + `a();\n//# sourceMappingURL=a.js.map\n\n;${REG}\n//# debugId=${id}\n`; + it('flags a map that now carries a DIFFERENT id than its (unchanged, already stamped) bundle', () => { + const code = buf(stampedCode(ID)); + const issues = verifyStamp( + new Map([ + ['a.js', code], + ['a.js.map', buf(mapJson())], + ]), + new Map([ + ['a.js', code], + ['a.js.map', buf(stampedMap(OTHER_ID))], + ]), + ); + expect(issues).toHaveLength(1); + expect(issues[0]).toMatchObject({ name: 'a.js.map' }); + expect(issues[0]?.reason).toContain(OTHER_ID); + }); + it('flags a changed map that LOST its id beside an unchanged stamped bundle (valid JSON, no debugId)', () => { + const code = buf(stampedCode(ID)); + const issues = verifyStamp( + new Map([ + ['a.js', code], + ['a.js.map', buf(stampedMap(ID))], + ]), + new Map([ + ['a.js', code], + ['a.js.map', buf(mapJson())], + ]), + ); + expect(issues).toHaveLength(1); + expect(issues[0]).toMatchObject({ name: 'a.js.map' }); + expect(issues[0]?.reason).toMatch(/no debugId/); + expect(issues[0]?.reason).toContain(ID); + }); + it('accepts the map that matches it, and a map beside an unstamped bundle (JSON only)', () => { + const code = buf(stampedCode(ID)); + expect( + verifyStamp( + new Map([ + ['a.js', code], + ['a.js.map', buf(mapJson())], + ]), + new Map([ + ['a.js', code], + ['a.js.map', buf(stampedMap(ID))], + ]), + ), + ).toEqual([]); + const plain = buf('a();\n//# sourceMappingURL=a.js.map\n'); + expect( + verifyStamp( + new Map([ + ['a.js', plain], + ['a.js.map', buf(mapJson())], + ]), + new Map([ + ['a.js', plain], + ['a.js.map', buf(stampedMap(OTHER_ID))], + ]), + ), + ).toEqual([]); + }); +}); diff --git a/packages/bundler-plugin-core/src/verify-stamp.ts b/packages/bundler-plugin-core/src/verify-stamp.ts new file mode 100644 index 000000000..b48fb3f68 --- /dev/null +++ b/packages/bundler-plugin-core/src/verify-stamp.ts @@ -0,0 +1,337 @@ +// Check what `bugsee-cli sourcemaps inject` did, before the result is trusted. +// +// Stamping rewrites the user's shipped JavaScript. The Rust inject is well tested, but "well tested" +// is not "verified on THIS build": a bundle with an unusual tail, a map that is not what its +// extension says, or a future inject regression would otherwise ship a script that no longer parses +// (a blank page) or a map whose id does not match its bundle (a crash that silently never +// symbolicates). Both are cheap to rule out on the bytes in hand, and expensive to find in production. +// +// Pure: it takes the bytes from before and after and returns what is wrong. What to DO about it +// (leave the asset alone in-build, restore the file after emit) is the caller's. +import path, { posix } from 'node:path'; +import { parse } from 'acorn'; +import { readDebugId } from './debug-ids'; + +/** One thing that is wrong with a stamped asset. */ +export interface StampIssue { + /** The asset, as named in the staged set (its path relative to the output root). */ + name: string; + reason: string; + /** The asset's source map lies outside the output: no later attempt can stamp it either. */ + outside?: true; +} + +/** The first few issues as one line, for an error message. */ +export function formatIssues(issues: readonly StampIssue[]): string { + return ( + issues + .slice(0, 3) + .map((issue) => `${issue.name}: ${issue.reason}`) + .join('; ') + (issues.length > 3 ? `; and ${issues.length - 3} more` : '') + ); +} + +/** What inject stamps (`.js`/`.cjs`/`.mjs`); the map of `x.js` is `x.js.map`. */ +const BUNDLE = /\.[cm]?js$/i; + +/** A source-map pointer comment, `//# sourceMappingURL=…` or the legacy `//@` spelling. */ +const SOURCE_MAPPING_URL = /^[ \t]*\/\/[#@][ \t]*sourceMappingURL=(.*?)[ \t\r]*$/gm; + +/** + * Whether `code` is syntactically valid JavaScript, as a module or as a classic script. + * + * Tried as a module first (an ES bundle has `import`/`export`), then as a script, because the two + * grammars differ (`with`, octal escapes and a bare `await` identifier are script-only). Return and + * top-level await are allowed so a CommonJS wrapper body and a worker entry are not false alarms. + */ +export function parseScript(code: string): boolean { + for (const sourceType of ['module', 'script'] as const) { + try { + parse(code, { + ecmaVersion: 'latest', + sourceType, + allowHashBang: true, + allowReturnOutsideFunction: true, + allowAwaitOutsideFunction: true, + }); + return true; + } catch { + // try the other grammar + } + } + return false; +} + +/** The value of the LAST sourceMappingURL comment in `code` — the one a debugger honours. */ +function lastSourceMappingUrl(code: string): string | undefined { + let last: string | undefined; + for (const match of code.matchAll(SOURCE_MAPPING_URL)) { + last = match[1]; + } + return last; +} + +/** + * The name of the map that belongs to the bundle `name` whose text is `text`. + * + * The map a debugger loads is the one the bundle's `sourceMappingURL` points at, and a bundler may name it + * anything (`sourcemapFileName(s)`, Rolldown), so the pair is resolved from the pointer, relative to the + * bundle's directory. A pointer that is absent, remote, `data:`, root-absolute, malformed or that names a + * file `exists` does not know falls back to the `.map` sibling inject pairs by default. + */ +export function resolveMapName( + name: string, + text: string, + exists: (candidate: string) => boolean, + api: Pick = posix, +): string { + const candidate = localPointerTarget(name, text, api); + return candidate !== undefined && exists(candidate) ? candidate : `${name}.map`; +} + +/** + * Where a bundle's LOCAL `sourceMappingURL` points, resolved from the bundle's directory (and + * percent-decoded). Undefined for no pointer, a remote or `data:` one, a root-absolute one, or a malformed + * escape. The pointer is read to the end of the line: a bundler can emit an unencoded space. + */ +export function localPointerTarget( + name: string, + text: string, + api: Pick = posix, +): string | undefined { + const pointer = lastSourceMappingUrl(text); + if (pointer === undefined || pointer === '' || /^([a-z][a-z0-9+.-]*:|\/)/i.test(pointer)) { + return undefined; + } + try { + return api.join(api.dirname(name), decodeURI(pointer)); + } catch { + return undefined; + } +} + +/** Whether a relative path climbs out of its root (`../x`). */ +const escapesRoot = (relative: string): boolean => /^\.\.([\\/]|$)/.test(relative); + +/** Reasons a changed bundle is not a faithful stamp of `before`. */ +function bundleIssues( + before: Buffer, + after: Buffer, + parser: (code: string) => boolean, +): { reasons: string[]; id: string | undefined } { + const reasons: string[] = []; + const beforeText = before.toString('utf8'); + const afterText = after.toString('utf8'); + + // (i) Still parses. Judged against the original: a bundle the parser could not read to begin with + // (syntax newer than it knows) says nothing about the stamp, and must not block the build. + if (!parser(afterText) && parser(beforeText)) { + reasons.push('no longer parses as JavaScript after stamping'); + } + + // (iv) Nothing but an appended stamp. A bundle that was ALREADY stamped is re-stamped in place (the + // old stamp is replaced, not extended), so only a first stamp can be held to "bytes appended". + if (readDebugId(beforeText) === undefined && !after.subarray(0, before.length).equals(before)) { + reasons.push('the original bytes were altered, not just appended to'); + } + + // (ii) The map pointer survived untouched. Inject appends AFTER it (measured, bugsee-cli 0.9.0: the + // runtime stub and the debugId comment follow the sourceMappingURL line), so "still last" would be + // wrong; what must hold is that the comment a debugger resolves is the same one. + const pointer = lastSourceMappingUrl(beforeText); + if (pointer !== undefined && lastSourceMappingUrl(afterText) !== pointer) { + reasons.push(`the sourceMappingURL comment (${pointer}) was lost or changed by stamping`); + } + + const id = readDebugId(afterText); + if (id === undefined) { + reasons.push('no debugId comment after stamping'); + } + return { reasons, id }; +} + +/** The `debugId` of a source map's JSON, `null` when it is not a JSON object, `undefined` when it has none. */ +function mapDebugId(bytes: Buffer): string | null | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(bytes.toString('utf8')); + } catch { + return null; + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + return null; + } + const id = (parsed as { debugId?: unknown }).debugId; + return typeof id === 'string' && id !== '' ? id : undefined; +} + +/** + * Verify a stamp. `before` / `after` map each asset name to its bytes; only assets that DIFFER are + * examined (inject leaves the rest untouched), so `after` may simply be the whole post-inject set. + * + * - every changed bundle still parses, keeps its sourceMappingURL comment, carries a debugId comment, + * and (unless it was already stamped) is the original with bytes appended; + * - every changed map is a JSON object, and the map of a changed bundle carries a `debugId` equal to + * the bundle's comment. + */ +export function verifyStamp( + before: ReadonlyMap, + after: ReadonlyMap, + parser: (code: string) => boolean = parseScript, + /** The path implementation the names follow: posix for bundler asset names, the native one for disk paths. */ + api: Pick = posix, +): StampIssue[] { + const issues: StampIssue[] = []; + const changed = (name: string): boolean => { + const was = before.get(name); + const now = after.get(name); + return was !== undefined && now !== undefined && !now.equals(was); + }; + const ids = new Map(); + const mapOf = new Map(); + + for (const name of before.keys()) { + if (!BUNDLE.test(name) || !changed(name)) { + continue; + } + const { reasons, id } = bundleIssues( + before.get(name) as Buffer, + after.get(name) as Buffer, + parser, + ); + ids.set(name, id); + const target = localPointerTarget(name, (after.get(name) as Buffer).toString('utf8'), api); + if (target !== undefined && escapesRoot(target)) { + // The map is outside what is staged: inject cannot stamp it, so this bundle would carry an id that + // never reaches its map. Refused, so the caller falls back (post-emit) or restores. + issues.push({ + name, + reason: `its source map (${target}) lies outside the output directory, so it cannot be stamped with the bundle. Emit the maps inside the output directory, or upload them yourself with bugsee-cli (sourcemaps inject, then debug-files upload).`, + outside: true, + }); + } + mapOf.set( + name, + resolveMapName(name, (after.get(name) as Buffer).toString('utf8'), (n) => after.has(n), api), + ); + for (const reason of reasons) { + issues.push({ name, reason }); + } + } + + // Every stamped bundle's map (changed or not) must now carry the bundle's id. + for (const [bundle, bundleId] of ids) { + const map = mapOf.get(bundle) as string; + const bytes = after.get(map); + if (bytes === undefined) { + continue; // a bundle with no map: nothing to symbolicate against, nothing to match + } + const mapId = mapDebugId(bytes); + if (mapId === null) { + issues.push({ name: map, reason: 'the stamped map is not valid JSON (an object)' }); + } else if (mapId === undefined) { + issues.push({ name: map, reason: 'the stamped map has no debugId' }); + } else if (bundleId !== undefined && mapId !== bundleId) { + issues.push({ + name: map, + reason: `the map's debugId ${mapId} does not match its bundle's debugId comment ${bundleId}`, + }); + } + } + + // A changed map whose bundle was not stamped in this run: only held to being a JSON object. + const pairedMaps = new Set(mapOf.values()); + // The id of an UNCHANGED bundle that already carries one, by the map it points at: a map that changed + // must agree with it (the bundle pass skipped it because its bytes did not change). + const unchangedIds = new Map(); + for (const [bundle, bytes] of after) { + if (BUNDLE.test(bundle) && before.has(bundle) && !changed(bundle)) { + const text = bytes.toString('utf8'); + const id = readDebugId(text); + if (id !== undefined) { + unchangedIds.set( + resolveMapName(bundle, text, (n) => after.has(n), api), + id, + ); + } + } + } + for (const name of before.keys()) { + if (name.endsWith('.map') && changed(name) && !pairedMaps.has(name)) { + const mapId = mapDebugId(after.get(name) as Buffer); + if (mapId === null) { + issues.push({ name, reason: 'the stamped map is not valid JSON (an object)' }); + } else if (mapId === undefined && unchangedIds.has(name)) { + issues.push({ + name, + reason: `the map has no debugId (its bundle carries ${unchangedIds.get(name)})`, + }); + } else if ( + mapId !== undefined && + unchangedIds.has(name) && + unchangedIds.get(name) !== mapId + ) { + issues.push({ + name, + reason: `the map's debugId ${mapId} does not match its bundle's debugId comment ${unchangedIds.get(name)}`, + }); + } + } + } + return issues; +} + +/** + * Check a build AS IT IS ON DISK, with no "before" to compare against — what the in-build path can + * still verify once the bundler has written its output. + * + * Stamping in memory is only as good as what happens to the bytes afterwards: Vite, for one, rewrites + * a chunk's code and REGENERATES its `.map` asset after a `generateBundle` hook has run (its + * dynamic-import preload substitution), which can drop a debugId the stamp put in the map. A bundle with a + * map must carry a debugId comment, and the map the SAME id, or the build ships bytes that look stamped + * and cannot be symbolicated. Bundles without a map are left alone (nothing to match). + */ +export function verifyStampedPairs( + files: ReadonlyMap, + /** The build's own bundle -> map mapping, where the pointer and sibling cannot say. */ + known: ReadonlyMap = new Map(), +): StampIssue[] { + const issues: StampIssue[] = []; + for (const [name, bytes] of files) { + if (!BUNDLE.test(name)) { + continue; + } + const text = bytes.toString('utf8'); + const map = known.get(name) ?? resolveMapName(name, text, (n) => files.has(n), path); + const mapBytes = files.get(map); + if (mapBytes === undefined) { + continue; + } + const bundleId = readDebugId(text); + const mapId = mapDebugId(mapBytes); + if (mapId === null) { + issues.push({ name: map, reason: 'the map is not valid JSON (an object)' }); + } else if (bundleId === undefined && mapId === undefined) { + issues.push({ + name, + reason: 'the bundle was not stamped (no debugId comment, and its map has none)', + }); + } else if (bundleId === undefined) { + issues.push({ + name, + reason: `the bundle lost its debugId comment (its map carries ${mapId})`, + }); + } else if (mapId === undefined) { + issues.push({ + name: map, + reason: `the map has no debugId (its bundle carries ${bundleId})`, + }); + } else if (mapId !== bundleId) { + issues.push({ + name: map, + reason: `the map's debugId ${mapId} does not match its bundle's debugId comment ${bundleId}`, + }); + } + } + return issues; +} diff --git a/packages/instrumentation-tests/package.json b/packages/instrumentation-tests/package.json index 3663fd6bf..6e7958865 100644 --- a/packages/instrumentation-tests/package.json +++ b/packages/instrumentation-tests/package.json @@ -38,6 +38,7 @@ "@edge-runtime/vm": "^5.0.0", "@opentelemetry/api": "^1.10.0", "@opentelemetry/sdk-trace-base": "^2.12.0", + "@rspack/core": "2.2.9", "@types/jsdom": "^21.1.7", "@types/node": "^22.20.5", "@types/react": "^18.3.31", @@ -57,6 +58,7 @@ "tsx": "^4.23.15", "typescript": "^6.0.3", "vite": "^8.3.5", + "vite7": "npm:vite@7.3.6", "vue": "^3.5.0", "webpack": "^5.112.2", "webpack-subresource-integrity": "^5.1.0", diff --git a/packages/instrumentation-tests/test/lazy-chunk.e2e.ts b/packages/instrumentation-tests/test/lazy-chunk.e2e.ts new file mode 100644 index 000000000..05c6e81a8 --- /dev/null +++ b/packages/instrumentation-tests/test/lazy-chunk.e2e.ts @@ -0,0 +1,476 @@ +// Stamping inside the build must not break a page that lazy-loads a content-hashed chunk. +// +// The in-build stamp runs at PROCESS_ASSETS_STAGE_DEV_TOOLING + 1, BEFORE webpack's RealContentHashPlugin renames +// `[contenthash]` chunks from their final bytes. That plugin rewrites hash references only inside STRING +// sources: stamped bytes handed back as a Buffer kept stale references (the runtime asked for +// `x..js` while `x..js` was on disk: ChunkLoadError, a broken page). The stamp therefore writes +// its result back as a string source. +// +// Real webpack and Rspack builds, the real bugsee-cli, a real Chromium that triggers the lazy `import()`. +import { createHash } from 'node:crypto'; +import { + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { tmpdir } from 'node:os'; +import { dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'; +import { bugseeRollupPlugin, bugseeRspackPlugin } from '@bugsee/bundler-plugin-core'; +import { bugseeVitePlugin } from '@bugsee/vite-plugin'; +import { bugseeWebpackPlugin } from '@bugsee/webpack-plugin'; +import { rspack } from '@rspack/core'; +import HtmlWebpackPlugin from 'html-webpack-plugin'; +import { type Browser, chromium } from 'playwright'; +import { rollup } from 'rollup'; +import { build as viteBuild } from 'vite'; +import { build as vite7Build } from 'vite7'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import webpack from 'webpack'; + +const requests: string[] = []; +let collector: Server | undefined; +let endpoint: string; +let root: string; +let browser: Browser; + +const TYPES: Record = { + '.html': 'text/html', + '.js': 'text/javascript', + '.map': 'application/json', +}; + +async function serve(dir: string): Promise<{ url: string; server: Server }> { + const server = createServer((req, res) => { + // Contain the request inside `dir`: a path-aware check (a raw prefix also accepts a sibling directory). + const requested = (req.url ?? '/').split('?')[0] as string; + const path = resolve(dir, `.${requested === '/' ? '/index.html' : requested}`); + const inside = relative(dir, path); + if (inside.startsWith('..') || isAbsolute(inside)) { + res.statusCode = 403; + res.end(); + return; + } + try { + res.setHeader('content-type', TYPES[extname(path)] ?? 'application/octet-stream'); + res.end(readFileSync(path)); + } catch { + res.statusCode = 404; + res.end(); + } + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + return { url: `http://127.0.0.1:${(server.address() as { port: number }).port}/`, server }; +} + +interface PageOutcome { + ran: boolean; + lazy: string | undefined; + debugIds: number; + failed: string[]; +} + +async function load(dir: string): Promise { + const { url, server } = await serve(dir); + const failed: string[] = []; + let page: Awaited> | undefined; + try { + page = await browser.newPage(); + page.on('response', (r) => { + if (r.status() >= 400) failed.push(`${r.status()} ${r.url()}`); + }); + page.on('console', (m) => { + if (/ChunkLoadError|Loading chunk|Failed to load resource/i.test(m.text())) + failed.push(m.text()); + }); + page.on('pageerror', (e) => failed.push(String(e))); + await page.goto(url); + await page + .waitForFunction(() => (window as { __lazy?: string }).__lazy !== undefined, null, { + timeout: 5_000, + }) + .catch(() => undefined); + const state = await page.evaluate(() => { + const w = window as { __ran?: boolean; __lazy?: string; _bugseeDebugIds?: object }; + return { + ran: w.__ran === true, + lazy: w.__lazy, + debugIds: Object.keys(w._bugseeDebugIds ?? {}).length, + }; + }); + return { ...state, failed }; + } finally { + try { + await page?.close(); + } finally { + await new Promise((r) => server.close(() => r())); + } + } +} + +const pluginOptions = () => ({ + appToken: 'lazy-e2e-token', + endpoint, + appVersion: '1.0.0', + appBuild: '1', + vcs: false, + registerBuild: false as const, + failOnError: true, + // Keep the maps: this test inspects their names. + deleteMaps: false, +}); + +/** Every emitted bundle points at a map that exists, whose `file` and debugId match the bundle. */ +function expectConsistentNames(out: string): void { + const files = readdirSync(out, { recursive: true }) as string[]; + const bundles = files.filter((f) => f.endsWith('.js')); + expect(bundles.length).toBeGreaterThanOrEqual(2); + for (const bundle of bundles) { + const code = readFileSync(join(out, bundle), 'utf8'); + const pointer = [...code.matchAll(/^\/\/# sourceMappingURL=(.+)$/gm)].pop()?.[1]?.trim(); + expect(pointer, `${bundle} has a sourceMappingURL`).toBeDefined(); + const mapPath = join(dirname(bundle), (pointer as string).split('?')[0] as string); + expect(files, `${bundle} -> ${mapPath}`).toContain(mapPath); + const map = JSON.parse(readFileSync(join(out, mapPath), 'utf8')) as { + file?: string; + debugId?: string; + }; + if (map.file !== undefined) { + expect(map.file.split('?')[0], `${mapPath} file`).toBe(bundle.split('/').pop()); + } + const id = /\/\/# debugId=([0-9a-f-]{36})/.exec(code)?.[1]; + expect(id, `${bundle} stamped`).toBeDefined(); + expect(map.debugId, `${mapPath} debugId`).toBe(id); + } +} + +describe('a content-hashed lazy chunk still loads after the in-build stamp', () => { + beforeAll(async () => { + root = mkdtempSync(join(tmpdir(), 'bugsee-lazy-e2e-')); + mkdirSync(join(root, 'src')); + writeFileSync( + join(root, 'src', 'index.js'), + "window.__ran = true;\nimport('./lazy.js').then((m) => { window.__lazy = m.value; });\n", + ); + writeFileSync(join(root, 'src', 'lazy.js'), "export const value = 'lazy-ok';\n"); + const created = createServer((req, res) => { + requests.push(req.url ?? ''); + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ ok: false, error: { type: 'DuplicateSymbolsFoundError', code: 16004 } }), + ); + }); + }); + collector = created; + await new Promise((r) => created.listen(0, '127.0.0.1', r)); + endpoint = `http://127.0.0.1:${(created.address() as { port: number }).port}`; + browser = await chromium.launch({ headless: true }); + }, 60_000); + + afterAll(async () => { + await browser?.close(); + const done = collector; + collector = undefined; // a failed later setup must not reuse a closed server + if (done) await new Promise((r) => done.close(() => r())); + if (root) rmSync(root, { recursive: true, force: true }); + }); + + const expectHealthy = async (out: string, before: number): Promise => { + expect(requests.length, 'maps uploaded').toBeGreaterThan(before); + expectConsistentNames(out); + const outcome = await load(out); + expect(outcome.failed).toEqual([]); + expect(outcome.ran).toBe(true); + expect(outcome.lazy).toBe('lazy-ok'); + expect(outcome.debugIds).toBeGreaterThanOrEqual(2); + }; + + it('webpack 5 (realContentHash)', async () => { + const out = join(root, 'dist-webpack'); + const before = requests.length; + await new Promise((resolve, reject) => { + webpack( + { + mode: 'production', + context: root, + entry: './src/index.js', + devtool: 'source-map', + optimization: { + realContentHash: true, + moduleIds: 'deterministic', + chunkIds: 'deterministic', + }, + output: { + path: out, + filename: '[name].[contenthash].js', + chunkFilename: '[name].[contenthash].js', + publicPath: '/', + clean: true, + }, + plugins: [ + new HtmlWebpackPlugin(), + bugseeWebpackPlugin(pluginOptions()) as unknown as webpack.WebpackPluginInstance, + ], + infrastructureLogging: { level: 'error' }, + }, + (error, stats) => { + if (error) reject(error); + else if (stats?.hasErrors()) + reject(new Error(stats.toString({ all: false, errors: true }))); + else resolve(); + }, + ); + }); + await expectHealthy(out, before); + }, 120_000); + + it('Rspack', async () => { + const out = join(root, 'dist-rspack'); + const before = requests.length; + await new Promise((resolve, reject) => { + const compiler = rspack({ + mode: 'production', + context: root, + entry: './src/index.js', + devtool: 'source-map', + output: { + path: out, + filename: '[name].[contenthash].js', + chunkFilename: '[name].[contenthash].js', + publicPath: '/', + clean: true, + }, + plugins: [new rspack.HtmlRspackPlugin(), bugseeRspackPlugin(pluginOptions())], + }); + compiler.run((err, stats) => + compiler.close(() => { + if (err) reject(err); + else if (stats?.hasErrors()) + reject(new Error(stats.toString({ all: false, errors: true }))); + else resolve(); + }), + ); + }); + await expectHealthy(out, before); + }, 120_000); + + it('Rspack + SubresourceIntegrityPlugin + contenthash: the lazy chunk executes and every pin matches', async () => { + const out = join(root, 'dist-rspack-sri'); + const before = requests.length; + await new Promise((resolve, reject) => { + const compiler = rspack({ + mode: 'production', + context: root, + entry: './src/index.js', + devtool: 'source-map', + output: { + path: out, + filename: '[name].[contenthash].js', + chunkFilename: '[name].[contenthash].js', + publicPath: '/', + crossOriginLoading: 'anonymous', + clean: true, + }, + plugins: [ + new rspack.HtmlRspackPlugin(), + new rspack.SubresourceIntegrityPlugin({ hashFuncNames: ['sha384'] }), + bugseeRspackPlugin(pluginOptions()), + ], + }); + compiler.run((err, stats) => + compiler.close(() => { + if (err) reject(err); + else if (stats?.hasErrors()) + reject(new Error(stats.toString({ all: false, errors: true }))); + else resolve(); + }), + ); + }); + expect(readFileSync(join(out, 'index.html'), 'utf8')).toMatch(/integrity="?sha384-/); + // the LAZY chunk is pinned too: its digest (of the stamped bytes on disk) sits in the runtime's table + const scripts = readdirSync(out).filter((f) => f.endsWith('.js')); + const runtimeText = scripts.map((f) => readFileSync(join(out, f), 'utf8')).join('\n'); + const lazyChunks = scripts.filter( + (f) => !readFileSync(join(out, 'index.html'), 'utf8').includes(f), + ); + expect(lazyChunks.length, 'a lazy chunk exists').toBeGreaterThan(0); + for (const f of lazyChunks) { + const digest = `sha384-${createHash('sha384') + .update(readFileSync(join(out, f))) + .digest('base64')}`; + expect(runtimeText, `${f} pinned by its stamped bytes`).toContain(digest); + } + await expectHealthy(out, before); + }, 120_000); + + it('Rollup: hashed chunk file names are final at generateBundle, so the lazy chunk and pointers are consistent', async () => { + const out = join(root, 'dist-rollup'); + const before = requests.length; + const html = { + name: 'html', + generateBundle( + this: { emitFile(f: object): void }, + _o: unknown, + bundle: Record, + ) { + const tags = Object.values(bundle) + .filter((e) => e.type === 'chunk' && e.isEntry) + .map((e) => ``); + this.emitFile({ + type: 'asset', + fileName: 'index.html', + source: `${tags.join('')}`, + }); + }, + }; + const bundle = await rollup({ + input: join(root, 'src', 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions()), html], + }); + await bundle.write({ + dir: out, + sourcemap: true, + entryFileNames: '[name]-[hash].js', + chunkFileNames: '[name]-[hash].js', + }); + await bundle.close(); + await expectHealthy(out, before); + }, 120_000); + + it('Vite: hashed chunk file names, the lazy chunk executes and pointers are consistent', async () => { + const out = join(root, 'dist-vite'); + const before = requests.length; + writeFileSync( + join(root, 'index.html'), + '\n', + ); + await viteBuild({ + root, + configFile: false, + logLevel: 'silent', + plugins: [bugseeVitePlugin(pluginOptions()) as never], + build: { outDir: out, emptyOutDir: true, minify: false, sourcemap: true }, + } as never); + await expectHealthy(out, before); + }, 120_000); +}); + +// Vite builds a worker through its own sub-build and copies it into the output, regenerating (Vite 8) or +// emitting after our generateBundle (Vite 7) its map: the worker bundle must still carry the SAME debug id as its +// map, and the worker must run in a real browser and register its id. +describe('Vite workers in a real browser', () => { + let wroot: string; + let wbrowser: Browser; + beforeAll(async () => { + wroot = realpathSync(mkdtempSync(join(tmpdir(), 'bugsee-worker-e2e-'))); + // The previous describe closed the shared collector in its afterAll: start our own. + const created = createServer((req, res) => { + requests.push(req.url ?? ''); + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ ok: false, error: { type: 'DuplicateSymbolsFoundError', code: 16004 } }), + ); + }); + }); + collector = created; + await new Promise((r) => created.listen(0, '127.0.0.1', r)); + endpoint = `http://127.0.0.1:${(created.address() as { port: number }).port}`; + wbrowser = await chromium.launch({ headless: true }); + }, 60_000); + afterAll(async () => { + await wbrowser?.close(); + const done = collector; + collector = undefined; // a failed later setup must not reuse a closed server + if (done) await new Promise((r) => done.close(() => r())); + if (wroot) rmSync(wroot, { recursive: true, force: true }); + }); + + // The registration stub is appended AFTER the worker's own code, so report on a later task. + const WORKER = + 'setTimeout(() => postMessage({ ok: true, ids: Object.keys(self._bugseeDebugIds ?? {}).length }), 0);\n'; + const forms = { + url: "const w = new Worker(new URL('./w.js', import.meta.url), { type: 'module' });\nw.onmessage = (e) => { window.__worker = e.data; };\n", + query: + "import W from './w.js?worker';\nconst w = new W();\nw.onmessage = (e) => { window.__worker = e.data; };\n", + } as const; + + for (const [label, build] of [ + ['Vite 8', viteBuild], + ['Vite 7', vite7Build], + ] as const) { + for (const form of ['url', 'query'] as const) { + for (const failOnError of [true, false]) { + it(`${label}, ${form} worker (failOnError ${failOnError}): runs, registers its id, map carries the same id`, async () => { + const dir = join(wroot, `${label}-${form}-${failOnError}`.replace(/\W+/g, '-')); + mkdirSync(join(dir, 'src'), { recursive: true }); + writeFileSync( + join(dir, 'index.html'), + '\n', + ); + writeFileSync(join(dir, 'src', 'index.js'), forms[form]); + writeFileSync(join(dir, 'src', 'w.js'), WORKER); + const out = join(dir, 'dist'); + const before = requests.length; + const errors: unknown[] = []; + await build({ + root: dir, + configFile: false, + logLevel: 'silent', + plugins: [ + bugseeVitePlugin({ + ...pluginOptions(), + failOnError, + onError: (e: unknown) => errors.push(e), + }) as never, + ], + build: { outDir: out, emptyOutDir: true, minify: false, sourcemap: true }, + } as never); + expect(errors.map(String)).toEqual([]); + expect(requests.length, 'maps uploaded').toBeGreaterThan(before); + // every bundle (main + worker) has a map with the SAME id + const assets = readdirSync(join(out, 'assets')); + const bundles = assets.filter((f) => f.endsWith('.js')); + expect(bundles.length).toBeGreaterThanOrEqual(2); + for (const bundle of bundles) { + const id = /\/\/# debugId=([0-9a-f-]{36})/.exec( + readFileSync(join(out, 'assets', bundle), 'utf8'), + )?.[1]; + expect(id, `${bundle} stamped`).toBeDefined(); + const map = JSON.parse(readFileSync(join(out, 'assets', `${bundle}.map`), 'utf8')) as { + debugId?: string; + }; + expect(map.debugId, `${bundle}.map`).toBe(id); + } + const { url, server } = await serve(out); + const page = await wbrowser.newPage(); + try { + await page.goto(url); + await page + .waitForFunction( + () => (window as { __worker?: unknown }).__worker !== undefined, + null, + { timeout: 5_000 }, + ) + .catch(() => undefined); + const worker = await page.evaluate( + () => (window as { __worker?: { ok: boolean; ids: number } }).__worker, + ); + expect(worker?.ok).toBe(true); + expect(worker?.ids, 'the worker registered its debug id').toBeGreaterThanOrEqual(1); + } finally { + await page.close(); + await new Promise((r) => server.close(() => r())); + } + }, 120_000); + } + } + } +}); diff --git a/packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts b/packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts new file mode 100644 index 000000000..0b221c0d6 --- /dev/null +++ b/packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts @@ -0,0 +1,254 @@ +// Subresource Integrity with Vite and Rollup, end to end in a REAL browser. +// +// sri.e2e.ts proves it for webpack. Vite and Rollup used to stamp AFTER emit (`writeBundle`), so a page whose +// hashes were taken in the build was refused. They now stamp in `generateBundle` (order 'pre'), before the +// hashes are taken. This builds a real app with the real plugin and the real bugsee-cli, pins hashes with a +// hand-rolled SRI step, loads the result in Chromium, and requires: the entry runs, the lazy chunk runs, the +// browser blocks nothing, and the SDK's debug-id registrations are live. +// +// The CONTROL stamps the same Vite build AFTER emit, as the plugin used to; it must be blocked, or a page +// that loads would prove nothing about whether this harness can see the defect. +import { createHash } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { tmpdir } from 'node:os'; +import { extname, isAbsolute, join, relative, resolve } from 'node:path'; +import { runBugseeCli } from '@bugsee/bundler-plugin-core'; +import { bugseeVitePlugin } from '@bugsee/vite-plugin'; +import { type Browser, chromium } from 'playwright'; +import { rollup } from 'rollup'; +import { type Plugin as VitePlugin, build as viteBuild } from 'vite'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +async function startCollector(): Promise<{ url: string; close: () => Promise }> { + const server = createServer((req, res) => { + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ ok: false, error: { type: 'DuplicateSymbolsFoundError', code: 16004 } }), + ); + }); + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + return { + url: `http://127.0.0.1:${(server.address() as { port: number }).port}`, + close: () => new Promise((r) => server.close(() => r())), + }; +} + +const TYPES: Record = { + '.html': 'text/html', + '.js': 'text/javascript', + '.map': 'application/json', +}; + +async function serve(dir: string): Promise<{ url: string; server: Server }> { + const server = createServer((req, res) => { + // Contain the request inside `dir`: a path-aware check (a raw prefix also accepts a sibling directory). + const requested = (req.url ?? '/').split('?')[0] as string; + const path = resolve(dir, `.${requested === '/' ? '/index.html' : requested}`); + const inside = relative(dir, path); + if (inside.startsWith('..') || isAbsolute(inside)) { + res.statusCode = 403; + res.end(); + return; + } + try { + const body = readFileSync(path); + res.setHeader('content-type', TYPES[extname(path)] ?? 'application/octet-stream'); + res.end(body); + } catch { + res.statusCode = 404; + res.end(); + } + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + return { url: `http://127.0.0.1:${(server.address() as { port: number }).port}/`, server }; +} + +interface PageOutcome { + ran: boolean; + lazy: string | undefined; + debugIds: number; + blocked: string[]; +} + +async function load(browser: Browser, dir: string): Promise { + const { url, server } = await serve(dir); + const page = await browser.newPage(); + const blocked: string[] = []; + page.on('console', (message) => { + if (/integrity|digest/i.test(message.text())) { + blocked.push(message.text()); + } + }); + try { + await page.goto(url); + await page + .waitForFunction(() => (window as { __lazy?: string }).__lazy !== undefined, null, { + timeout: 5_000, + }) + .catch(() => undefined); + const state = await page.evaluate(() => { + const w = window as { __ran?: boolean; __lazy?: string; _bugseeDebugIds?: object }; + return { + ran: w.__ran === true, + lazy: w.__lazy, + debugIds: Object.keys(w._bugseeDebugIds ?? {}).length, + }; + }); + return { ...state, blocked }; + } finally { + await page.close(); + await new Promise((r) => server.close(() => r())); + } +} + +const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + +/** Pin every script / modulepreload that is a chunk of the bundle. */ +function pinChunks(html: string, bundle: Record): string { + return html.replace( + /<(?:script|link)\b[^>]*?(?:src|href)="\/?([^"]+\.js)"[^>]*>/g, + (tag, file: string) => { + const entry = bundle[file]; + return entry?.type === 'chunk' && entry.code !== undefined + ? tag.replace(/>$/, ` integrity="${sri(entry.code)}">`) + : tag; + }, + ); +} + +/** A hand-rolled SRI step that hashes LAST (generateBundle, order post), into the emitted page. */ +const lateSri = (): VitePlugin => ({ + name: 'hand-rolled-late-sri', + enforce: 'post', + generateBundle: { + order: 'post', + handler(_options, bundle) { + const page = bundle['index.html']; + if (page?.type === 'asset') { + page.source = pinChunks(String(page.source), bundle as never); + } + }, + }, +}); + +describe('SRI: a Vite / Rollup page still loads after Bugsee stamps it', () => { + let root: string; + let browser: Browser; + let collector: { url: string; close: () => Promise }; + + const pluginOptions = () => ({ + appToken: 'sri-e2e-token', + endpoint: collector.url, + appVersion: '1.0.0', + appBuild: '1', + vcs: false, + registerBuild: false as const, + failOnError: true, + }); + + beforeAll(async () => { + root = mkdtempSync(join(tmpdir(), 'bugsee-sri-vite-e2e-')); + mkdirSync(join(root, 'src')); + writeFileSync( + join(root, 'index.html'), + '\n', + ); + writeFileSync( + join(root, 'src', 'index.js'), + `window.__ran = true;\nimport('./lazy.js').then((m) => { window.__lazy = m.value; });\n`, + ); + writeFileSync(join(root, 'src', 'lazy.js'), `export const value = 'lazy-ok';\n`); + collector = await startCollector(); + browser = await chromium.launch({ headless: true }); + }, 60_000); + + afterAll(async () => { + await browser?.close(); + await collector?.close(); + if (root) rmSync(root, { recursive: true, force: true }); + }); + + const viteApp = (outDir: string, plugins: unknown[]) => + ({ + root, + configFile: false, + logLevel: 'silent', + plugins, + build: { outDir, emptyOutDir: true, minify: false, sourcemap: true }, + }) as never; + + it('Vite: runs the entry AND the lazy chunk, every bundle stamped, hashes taken after the stamp', async () => { + const outDir = join(root, 'dist-vite'); + await viteBuild(viteApp(outDir, [bugseeVitePlugin(pluginOptions()) as VitePlugin, lateSri()])); + + const bundles = readdirSync(join(outDir, 'assets')).filter((f) => f.endsWith('.js')); + expect(bundles.length).toBeGreaterThanOrEqual(2); + for (const file of bundles) { + expect(readFileSync(join(outDir, 'assets', file), 'utf8'), file).toMatch( + /\/\/# debugId=[0-9a-f-]{36}/, + ); + } + expect(readFileSync(join(outDir, 'index.html'), 'utf8')).toMatch(/integrity="sha384-/); + + const outcome = await load(browser, outDir); + expect(outcome.blocked).toEqual([]); + expect(outcome.ran).toBe(true); + expect(outcome.lazy).toBe('lazy-ok'); + expect(outcome.debugIds).toBeGreaterThanOrEqual(2); + }, 120_000); + + it('Rollup: the same, with a page emitted by a plugin that hashes what Rollup is about to write', async () => { + const outDir = join(root, 'dist-rollup'); + const sriHtml = { + name: 'sri-html', + generateBundle( + this: { emitFile(file: object): void }, + _output: unknown, + bundle: Record< + string, + { type: string; code?: string; isEntry?: boolean; fileName: string } + >, + ) { + const tags = Object.values(bundle) + .filter((entry) => entry.type === 'chunk' && entry.isEntry) + .map( + (entry) => + ``, + ); + this.emitFile({ + type: 'asset', + fileName: 'index.html', + source: `${tags.join('')}`, + }); + }, + }; + const { bugseeRollupPlugin } = await import('@bugsee/bundler-plugin-core'); + const bundle = await rollup({ + input: join(root, 'src', 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions()), sriHtml], + }); + await bundle.write({ dir: outDir, sourcemap: true }); + await bundle.close(); + + const outcome = await load(browser, outDir); + expect(outcome.blocked).toEqual([]); + expect(outcome.ran).toBe(true); + expect(outcome.lazy).toBe('lazy-ok'); + expect(outcome.debugIds).toBeGreaterThanOrEqual(2); + }, 120_000); + + it('CONTROL: the same Vite page stamped AFTER emit is blocked — the bug this exists to prevent', async () => { + const outDir = join(root, 'dist-vite-control'); + await viteBuild(viteApp(outDir, [lateSri()])); + await runBugseeCli(['sourcemaps', 'inject', outDir, '--allow-sri'], {}); + + const outcome = await load(browser, outDir); + expect(outcome.ran).toBe(false); + expect(outcome.blocked.length).toBeGreaterThan(0); + }, 120_000); +}); diff --git a/packages/instrumentation-tests/test/sri.e2e.ts b/packages/instrumentation-tests/test/sri.e2e.ts index c62744159..a50bc57ba 100644 --- a/packages/instrumentation-tests/test/sri.e2e.ts +++ b/packages/instrumentation-tests/test/sri.e2e.ts @@ -18,7 +18,7 @@ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; import { tmpdir } from 'node:os'; -import { extname, isAbsolute, join, normalize } from 'node:path'; +import { extname, isAbsolute, join, relative, resolve } from 'node:path'; import { resolveBugseeCli, runBugseeCli } from '@bugsee/bundler-plugin-core'; import { bugseeWebpackPlugin } from '@bugsee/webpack-plugin'; import HtmlWebpackPlugin from 'html-webpack-plugin'; @@ -55,10 +55,11 @@ const TYPES: Record = { /** Serve a build directory over HTTP — SRI with `crossorigin` is not exercised over file://. */ async function serve(dir: string): Promise<{ url: string; server: Server }> { const server = createServer((req, res) => { - const path = normalize( - join(dir, (req.url ?? '/').split('?')[0] === '/' ? 'index.html' : (req.url as string)), - ); - if (!path.startsWith(dir)) { + // Contain the request inside `dir`: a path-aware check (a raw prefix also accepts a sibling directory). + const requested = (req.url ?? '/').split('?')[0] as string; + const path = resolve(dir, `.${requested === '/' ? '/index.html' : requested}`); + const inside = relative(dir, path); + if (inside.startsWith('..') || isAbsolute(inside)) { res.statusCode = 403; res.end(); return; diff --git a/packages/nextjs-e2e/package.json b/packages/nextjs-e2e/package.json index 267d738ff..529d55136 100644 --- a/packages/nextjs-e2e/package.json +++ b/packages/nextjs-e2e/package.json @@ -14,8 +14,11 @@ }, "devDependencies": { "next": "^15.5.28", + "next16": "npm:next@16.4.6", + "playwright": "^1.64.1", "react": "^18.3.1", "react-dom": "^18.3.1", + "tsx": "4.23.15", "vitest": "^4.0.0" } } diff --git a/packages/nextjs-e2e/test/edge-build.e2e.ts b/packages/nextjs-e2e/test/edge-build.e2e.ts index d48ff8744..c15bcc17c 100644 --- a/packages/nextjs-e2e/test/edge-build.e2e.ts +++ b/packages/nextjs-e2e/test/edge-build.e2e.ts @@ -31,11 +31,17 @@ describe('@bugsee/nextjs — real `next build`', () => { beforeAll(() => { rmSync(outDir, { recursive: true, force: true }); - build = spawnSync('pnpm', ['exec', 'next', 'build'], { - cwd: appDir, - encoding: 'utf8', - env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1' }, - }); + // The `next` binary is invoked by path: this package also installs Next 16 (as `next16`, for the source-map + // e2e), whose bin of the same name would win a `pnpm exec next`. + build = spawnSync( + process.execPath, + [join(appDir, 'node_modules', 'next', 'dist', 'bin', 'next'), 'build'], + { + cwd: appDir, + encoding: 'utf8', + env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1' }, + }, + ); }); afterAll(() => { diff --git a/packages/nextjs-e2e/test/packed-config.e2e.ts b/packages/nextjs-e2e/test/packed-config.e2e.ts new file mode 100644 index 000000000..5e8bb1621 --- /dev/null +++ b/packages/nextjs-e2e/test/packed-config.e2e.ts @@ -0,0 +1,136 @@ +// The PUBLISHED shape of `@bugsee/nextjs/config`: packs `@bugsee/nextjs` and every workspace package it depends on +// (pnpm applies each `publishConfig`, so `exports` point at `dist`), unpacks them as an app's node_modules, and +// loads the config entry the way a real next.config does: `require()` from a CJS `next.config.js` and `import` from +// an ESM `next.config.mjs`. In the repo everything resolves to `src`, so this is the only check of the dual build. +import { execFileSync } from 'node:child_process'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +const repo = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..'); +const packages = join(repo, 'packages'); +let app: string; + +/** `@bugsee/*` workspace packages reachable from `name` through `dependencies`, `name` included. */ +function workspaceClosure(name: string, seen = new Map()): Map { + const dir = join(packages, name.replace('@bugsee/', '')); + if (seen.has(name)) return seen; + seen.set(name, dir); + const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { + dependencies?: Record; + optionalDependencies?: Record; + }; + const wanted = { ...manifest.dependencies, ...manifest.optionalDependencies }; + for (const [dep, range] of Object.entries(wanted)) { + if (range.startsWith('workspace:')) workspaceClosure(dep, seen); + } + return seen; +} + +beforeAll(() => { + const closure = workspaceClosure('@bugsee/nextjs'); + const filters = [...closure.keys()].flatMap((n) => ['--filter', n]); + execFileSync('pnpm', ['--dir', repo, ...filters, 'run', '--if-present', 'build'], { + stdio: 'ignore', + }); + app = mkdtempSync(join(tmpdir(), 'bugsee-packed-')); + const modules = join(app, 'node_modules'); + mkdirSync(join(modules, '@bugsee'), { recursive: true }); + // The packed tarballs, unpacked as an app's node_modules (pnpm applies each `publishConfig`). + for (const [name, dir] of closure) { + const target = join(modules, name); + mkdirSync(target, { recursive: true }); + const out = mkdtempSync(join(tmpdir(), 'bugsee-pack-')); + execFileSync('pnpm', ['pack', '--pack-destination', out], { cwd: dir, stdio: 'ignore' }); + execFileSync('tar', [ + '-xzf', + join(out, readdirSync(out)[0] as string), + '-C', + target, + '--strip-components=1', + ]); + rmSync(out, { recursive: true, force: true }); + } + // Third-party dependencies, and ONLY the ones the packed manifests DECLARE. No registry, no package store: each + // declared dependency is linked from where the monorepo installed it (its own transitive dependencies resolve from + // that real location). A dependency a package uses but forgot to declare is therefore missing here, exactly as it + // would be for a user, which a monorepo-wide node_modules would hide. + for (const [name] of closure) { + const packed = JSON.parse(readFileSync(join(modules, name, 'package.json'), 'utf8')) as { + dependencies?: Record; + optionalDependencies?: Record; + }; + for (const dep of Object.keys({ ...packed.dependencies, ...packed.optionalDependencies })) { + if (closure.has(dep)) continue; + const installed = join(closure.get(name) as string, 'node_modules', dep); + const link = join(modules, dep); + if (!existsSync(installed) || existsSync(link)) continue; + mkdirSync(dirname(link), { recursive: true }); + symlinkSync(realpathSync(installed), link); + } + } + writeFileSync(join(app, 'package.json'), JSON.stringify({ name: 'app', version: '3.2.1' })); +}, 900_000); + +afterAll(() => { + if (app) rmSync(app, { recursive: true, force: true }); +}); + +const probe = ` + const out = withBugsee({ reactStrictMode: true }, { appToken: 't', vcs: false }); + console.log(JSON.stringify({ + kind: typeof withBugsee, + strict: out.reactStrictMode, + maps: out.productionBrowserSourceMaps, + version: out.compiler && out.compiler.define && out.compiler.define.__BUGSEE_APP_VERSION__, + })); +`; +const expected = { kind: 'function', strict: true, maps: true, version: '3.2.1' }; + +describe('the published @bugsee/nextjs/config', () => { + it('exports map to dist, with an import and a require build', () => { + const manifest = JSON.parse( + readFileSync(join(app, 'node_modules', '@bugsee', 'nextjs', 'package.json'), 'utf8'), + ) as { exports: Record }; + const entry = manifest.exports['./config']; + expect(entry?.require.default).toBe('./dist/config.cjs'); + expect(entry?.import.default).toBe('./dist/config.js'); + for (const file of [entry?.require.default, entry?.import.default]) { + expect(existsSync(join(app, 'node_modules', '@bugsee', 'nextjs', file as string))).toBe(true); + } + }); + + it('works from a CommonJS next.config.js (require)', () => { + const out = execFileSync( + process.execPath, + ['-e', `const { withBugsee } = require('@bugsee/nextjs/config');${probe}`], + { cwd: app, encoding: 'utf8', env: { ...process.env, TURBOPACK: '' } }, + ); + expect(JSON.parse(out.trim().split('\n').pop() as string)).toEqual(expected); + }); + + it('works from an ESM next.config.mjs (import)', () => { + writeFileSync( + join(app, 'probe.mjs'), + `import { withBugsee } from '@bugsee/nextjs/config';${probe}`, + ); + const out = execFileSync(process.execPath, ['probe.mjs'], { + cwd: app, + encoding: 'utf8', + env: { ...process.env, TURBOPACK: '' }, + }); + expect(JSON.parse(out.trim().split('\n').pop() as string)).toEqual(expected); + }); +}); diff --git a/packages/nextjs-e2e/test/source-maps.e2e.ts b/packages/nextjs-e2e/test/source-maps.e2e.ts new file mode 100644 index 000000000..22f04dae8 --- /dev/null +++ b/packages/nextjs-e2e/test/source-maps.e2e.ts @@ -0,0 +1,683 @@ +// `withBugsee` against REAL `next build`s, for both bundlers and both Next generations that matter: +// +// next 15.5 + webpack (its default) next 15.5 + `--turbopack` +// next 16.4 + Turbopack (its default) next 16.4 + `--webpack` +// +// Each builds a tiny app (a client page with a lazy chunk, a node route, an edge route) through the REAL +// `@bugsee/nextjs/config`, the REAL `bugsee-cli` and a mock collector, then asserts the outcome on disk and on the +// wire: the bundles are stamped, the maps reached the collector keyed by those exact debug-IDs, the public maps are +// gone, the server maps are kept, the version is baked into the bundle, and the build still RUNS (`next start`). +// +// Plus the Subresource-Integrity cases: webpack stamps inside the build so the hashes stay right; Turbopack hashes +// before its post-build hook, so the build is left unmodified and says so. +import { type ChildProcess, spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { createRequire } from 'node:module'; +import { dirname, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { type Browser, chromium } from 'playwright'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +const here = dirname(fileURLToPath(import.meta.url)); +const pkgDir = join(here, '..'); +const fixturesRoot = join(pkgDir, '.fixtures'); +const require_ = createRequire(import.meta.url); +// A file URL: NODE_OPTIONS is split on spaces, so a checkout path containing one would break the raw path. +const tsxLoader = pathToFileURL( + join(dirname(require_.resolve('tsx/package.json')), 'dist', 'loader.mjs'), +).href; + +let server: Server; +let browser: Browser; +let endpoint: string; +const bodies: string[] = []; + +beforeAll(async () => { + browser = await chromium.launch({ headless: true }); + rmSync(fixturesRoot, { recursive: true, force: true }); + mkdirSync(fixturesRoot, { recursive: true }); + // Every upload is answered "already have it", so it succeeds without a backend; the body is kept, so a test + // can look for the exact debug-IDs that were sent. + server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + bodies.push(Buffer.concat(chunks).toString('latin1')); + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ ok: false, error: { type: 'DuplicateSymbolsFoundError', code: 16004 } }), + ); + }); + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + endpoint = `http://127.0.0.1:${(server.address() as { port: number }).port}`; +}); +afterAll(async () => { + await browser?.close(); + await new Promise((r) => server.close(() => r())); + // BUGSEE_E2E_KEEP=1 leaves the built fixtures behind for inspection. + if (process.env.BUGSEE_E2E_KEEP === undefined) { + rmSync(fixturesRoot, { recursive: true, force: true }); + } +}); + +interface Spec { + name: string; + /** The dependency name of the Next copy to build with (`next` = 15.5, `next16` = 16.4). */ + next: 'next' | 'next16'; + args: string[]; + /** Extra source for the `withBugsee` options object and the Next config. */ + options?: string; + nextConfig?: string; + /** Pre-seed FOREIGN source-map files (stylesheet and declaration maps nothing in this build produced). */ + seedForeign?: boolean; + /** Make `bugsee-cli sourcemaps inject` fail for the IN-BUILD stamp only (the post-emit one reaches the real CLI). */ + failInBuildStamp?: boolean; +} + +/** The real bugsee-cli binary, as the core resolves it. */ +const realCli = ( + createRequire(join(pkgDir, '..', 'bundler-plugin-core', 'package.json'))('@bugsee/cli') as { + binaryPath(): string; + } +).binaryPath(); + +/** Where the foreign files are written, relative to the dist dir, and what they contain. */ +const FOREIGN = [ + ['static', 'foreign.css.map'], + ['static', 'foreign.d.ts.map'], + ['server', 'foreign.css.map'], + ['server', 'foreign.d.ts.map'], +] as const; +const FOREIGN_BODY = '{"version":3,"sources":["foreign.css"],"names":[],"mappings":""}'; + +/** Next config source that writes the foreign files from BOTH bundlers' paths, before Bugsee's step runs. */ +const SEED_HOOK = ` + compiler: { runAfterProductionCompile: async ({ distDir }) => seed(distDir) },`; +const SEED_WEBPACK = ` + webpack(config, { isServer }) { + config.plugins.push({ apply(compiler) { + compiler.hooks.afterEmit.tap('seed', () => { + const out = compiler.options.output.path; + seed(isServer ? join(out, '..', '..') : out); + }); + } }); + return config; + },`; +const SEED_PRELUDE = ` +import { mkdirSync as mk, writeFileSync as wr } from 'node:fs'; +import { join } from 'node:path'; +function seed(dist) { + for (const [dir, name] of ${JSON.stringify(FOREIGN)}) { + mk(join(dist, dir), { recursive: true }); + wr(join(dist, dir, name), ${JSON.stringify(FOREIGN_BODY)}); + } +} +`; + +interface Built { + dir: string; + status: number | null; + log: string; + uploads: string[]; +} + +const link = (target: string, path: string): void => { + mkdirSync(dirname(path), { recursive: true }); + symlinkSync(realpathSync(target), path, 'dir'); +}; + +/** Write a fixture app, build it with `spec`, and return what happened. */ +async function build(spec: Spec): Promise { + const dir = join(fixturesRoot, spec.name); + mkdirSync(join(dir, 'app', 'lazy'), { recursive: true }); + mkdirSync(join(dir, 'app', 'api', 'hi'), { recursive: true }); + mkdirSync(join(dir, 'app', 'edge'), { recursive: true }); + const modules = join(dir, 'node_modules'); + link(join(pkgDir, 'node_modules', spec.next), join(modules, 'next')); + link(join(pkgDir, 'node_modules', 'react'), join(modules, 'react')); + link(join(pkgDir, 'node_modules', 'react-dom'), join(modules, 'react-dom')); + link(join(pkgDir, '..', 'nextjs'), join(modules, '@bugsee', 'nextjs')); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: spec.name, version: '1.2.3' })); + // Plain JavaScript on purpose: a `.ts` file makes Next install TypeScript into the project. + writeFileSync( + join(dir, 'app', 'layout.jsx'), + "import './style.css';\nexport default function Layout({ children }) { return {children}; }\n", + ); + writeFileSync(join(dir, 'app', 'style.css'), 'body { margin: 0; color: rebeccapurple; }\n'); + writeFileSync( + join(dir, 'app', 'page.jsx'), + `'use client'; +import { useState } from 'react'; +import dynamic from 'next/dynamic'; +const Lazy = dynamic(() => import('./lazy/lazy.jsx'), { ssr: false }); +const version = typeof __BUGSEE_APP_VERSION__ === 'undefined' ? 'none' : __BUGSEE_APP_VERSION__; +export default function Page() { + const [n, setN] = useState(0); + return

; +} +`, + ); + writeFileSync( + join(dir, 'app', 'lazy', 'lazy.jsx'), + 'export default function Lazy() { return

lazy-ok

; }\n', + ); + writeFileSync( + join(dir, 'app', 'api', 'hi', 'route.js'), + "export const GET = () => new Response('hi');\n", + ); + writeFileSync( + join(dir, 'app', 'edge', 'route.js'), + "export const runtime = 'edge';\nexport const GET = () => new Response('edge');\n", + ); + writeFileSync( + join(dir, 'next.config.mjs'), + `import { withBugsee } from '@bugsee/nextjs/config';${spec.seedForeign ? SEED_PRELUDE : ''} +export default withBugsee( + { ${spec.next === 'next' ? 'eslint: { ignoreDuringBuilds: true },' : ''} ${spec.nextConfig ?? ''}${spec.seedForeign ? SEED_HOOK + (spec.args.includes('--webpack') ? SEED_WEBPACK : '') : ''} }, + { appToken: 'e2e-token', endpoint: ${JSON.stringify(endpoint)}, appVersion: '9.8.7', appBuild: '42', + vcs: false, registerBuild: false, failOnError: true, ${spec.options ?? ''} }, +); +`, + ); + const stub = join(dir, 'cli-stub.js'); + if (spec.failInBuildStamp) { + writeFileSync( + stub, + `const { spawnSync } = require('node:child_process'); +const args = process.argv.slice(2); +if (args[0] === 'sourcemaps' && args[1] === 'inject' && String(args[2]).includes('bugsee-stamp-')) { + process.stderr.write('stub: the in-build inject is refused\\n'); + process.exit(11); +} +process.exit(spawnSync(${JSON.stringify(realCli)}, args, { stdio: 'inherit' }).status ?? 1); +`, + ); + } + const before = bodies.length; + // Asynchronous on purpose: the mock collector lives in THIS process, and a blocking spawn would starve it. + const child = spawn( + process.execPath, + [join(modules, 'next', 'dist', 'bin', 'next'), 'build', ...spec.args], + { + cwd: dir, + env: { + ...process.env, + NEXT_TELEMETRY_DISABLED: '1', + NODE_OPTIONS: `--import ${tsxLoader}`, + ...(spec.failInBuildStamp ? { BUGSEE_CLI_PATH: stub } : {}), + }, + }, + ); + let log = ''; + child.stdout.on('data', (c: Buffer) => (log += c.toString())); + child.stderr.on('data', (c: Buffer) => (log += c.toString())); + const status = await new Promise((r) => child.on('close', r)); + return { dir, status, log, uploads: bodies.slice(before) }; +} + +const walk = (dir: string): string[] => + existsSync(dir) + ? readdirSync(dir).flatMap((name) => { + const full = join(dir, name); + return statSync(full).isDirectory() ? walk(full) : [full]; + }) + : []; + +const DEBUG_ID = /\/\/# debugId=([0-9a-f-]{36})/; +const debugIdOf = (file: string): string | undefined => + DEBUG_ID.exec(readFileSync(file, 'utf8'))?.[1]; + +/** Every bundle under `dir` that points at a map, with the path it points at (the map may be deleted by now). */ +const pointing = (dir: string): Array<{ file: string; map: string }> => + walk(dir) + .filter((f) => f.endsWith('.js')) + .flatMap((file) => { + const ref = /\/\/# sourceMappingURL=(\S+)\s*$/m.exec(readFileSync(file, 'utf8'))?.[1]; + return ref === undefined ? [] : [{ file, map: join(dirname(file), decodeURIComponent(ref)) }]; + }); + +/** + * Bundles whose map belongs to them alone, and bundles that share a map with another (Next 15.5's Turbopack does + * that for its runtime chunks: a map carries one debug-id, so those are deliberately left unstamped). + */ +const split = (dir: string): { unique: string[]; shared: string[]; referenced: Set } => { + const all = pointing(dir); + const count = new Map(); + for (const { map } of all) count.set(map, (count.get(map) ?? 0) + 1); + return { + unique: all.filter(({ map }) => count.get(map) === 1).map(({ file }) => file), + shared: all.filter(({ map }) => (count.get(map) as number) > 1).map(({ file }) => file), + referenced: new Set(all.map(({ map }) => map)), + }; +}; + +const clientBundles = (dir: string): string[] => split(join(dir, '.next', 'static')).unique; + +const maps = (dir: string): string[] => walk(dir).filter((f) => f.endsWith('.map')); + +/** `next start` the build and fetch the paths; resolves their statuses. */ +async function runBuild(dir: string, paths: string[]): Promise { + const port = 41000 + Math.floor(Math.random() * 2000); + const child: ChildProcess = spawn( + process.execPath, + [join(dir, 'node_modules', 'next', 'dist', 'bin', 'next'), 'start', '-p', String(port)], + { + cwd: dir, + // `next start` loads next.config too, which imports the TypeScript source of @bugsee/nextjs/config. + env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1', NODE_OPTIONS: `--import ${tsxLoader}` }, + stdio: 'ignore', + }, + ); + try { + const statuses: number[] = []; + for (const path of paths) { + let status = 0; + for (let attempt = 0; attempt < 60 && status === 0; attempt++) { + try { + status = (await fetch(`http://127.0.0.1:${port}${path}`)).status; + } catch { + await new Promise((r) => setTimeout(r, 500)); + } + } + statuses.push(status); + } + return statuses; + } finally { + child.kill('SIGKILL'); + } +} + +interface Page { + /** What the page printed to the console as an error, plus uncaught exceptions. */ + errors: string[]; + /** Same-origin requests that answered 4xx/5xx (the favicon is not the app's). */ + failed: string[]; + /** The text of the lazily loaded component, which renders only if its chunk loaded and ran. */ + lazy: string | null; + /** The text of the page after hydration. */ + body: string; + /** How many bundles registered a debug-id with the runtime (`globalThis._bugseeDebugIds`). */ + debugIds: number; + /** Next's error overlay / error page text, when it replaced the app. */ + crashed: boolean; +} + +/** `next start` the build and open `/` in headless Chromium: does the app, lazy chunk included, actually RUN? */ +async function openInBrowser(dir: string): Promise { + const port = 43000 + Math.floor(Math.random() * 2000); + const child: ChildProcess = spawn( + process.execPath, + [join(dir, 'node_modules', 'next', 'dist', 'bin', 'next'), 'start', '-p', String(port)], + { + cwd: dir, + env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1', NODE_OPTIONS: `--import ${tsxLoader}` }, + stdio: 'ignore', + }, + ); + const context = await browser.newContext(); + try { + const page = await context.newPage(); + const errors: string[] = []; + const failed: string[] = []; + page.on('console', (m) => { + if (m.type() === 'error' && !m.text().includes('favicon')) errors.push(m.text()); + }); + page.on('pageerror', (e) => errors.push(String(e))); + page.on('response', (r) => { + if (r.status() >= 400 && !r.url().includes('favicon')) + failed.push(`${r.status()} ${r.url()}`); + }); + let loaded = false; + for (let attempt = 0; attempt < 60 && !loaded; attempt++) { + try { + await page.goto(`http://127.0.0.1:${port}/`, { waitUntil: 'load' }); + loaded = true; + } catch { + await new Promise((r) => setTimeout(r, 500)); + } + } + expect(loaded, 'next start never answered').toBe(true); + // Hydrate, then give the lazy chunk its chance to load and run. + await page + .locator('button') + .first() + .click({ timeout: 15_000 }) + .catch(() => undefined); + await page.waitForSelector('#lazy', { timeout: 10_000 }).catch(() => undefined); + const body = await page.evaluate(() => document.body.innerText); + return { + errors, + failed, + lazy: await page + .locator('#lazy') + .textContent({ timeout: 1000 }) + .catch(() => null), + body, + debugIds: await page.evaluate( + () => + Object.keys((globalThis as { _bugseeDebugIds?: object })._bugseeDebugIds ?? {}).length, + ), + crashed: /Application error|This page couldn.t load|Unhandled Runtime Error/.test(body), + }; + } finally { + await context.close(); + child.kill('SIGKILL'); + } +} + +/** The assertions every build that was stamped must satisfy once it is OPEN in a browser. */ +function expectRuns(page: Page, options: { stamped: boolean }): void { + expect(page.failed, 'a request failed (a stale chunk URL 404s)').toEqual([]); + expect(page.errors).toEqual([]); + expect(page.crashed, page.body).toBe(false); + expect(page.lazy, 'the lazy chunk did not load and run').toBe('lazy-ok'); + expect(page.body).toContain('v9.8.7'); + if (options.stamped) { + expect(page.debugIds, 'no bundle registered a debug-id').toBeGreaterThan(0); + } +} + +const MATRIX: Spec[] = [ + { name: 'next15-webpack', next: 'next', args: [] }, + { name: 'next15-turbopack', next: 'next', args: ['--turbopack'] }, + { name: 'next16-turbopack', next: 'next16', args: [] }, + { name: 'next16-webpack', next: 'next16', args: ['--webpack'] }, +]; + +describe.each(MATRIX)('withBugsee — real `next build` ($name)', (spec) => { + let built: Built; + beforeAll(async () => { + built = await build(spec); + }); + + it('builds, and says nothing was skipped or failed', () => { + expect(built.status, built.log.split('\n').slice(-60).join('\n')).toBe(0); + // The one expected notice: bundles sharing a map are left alone (asserted below). + const notices = built.log.split('\n').filter((l) => l.includes('[bugsee]')); + expect(notices.filter((l) => !l.includes('share one source map'))).toEqual([]); + }); + + it('stamps every client bundle that has a map of its own, and none that share one', () => { + const { unique, shared } = split(join(built.dir, '.next', 'static')); + expect(unique.length).toBeGreaterThan(2); + for (const bundle of unique) { + expect(debugIdOf(bundle), bundle).toBeDefined(); + } + for (const bundle of shared) { + expect(debugIdOf(bundle), `${bundle} shares a map`).toBeUndefined(); + } + expect(built.log.includes('share one source map')).toBe(shared.length > 0); + }); + + it('uploaded the maps keyed by exactly those debug-IDs, client and server', () => { + expect(built.uploads.length).toBeGreaterThan(0); + const sent = built.uploads.join('\n'); + const ids = split(join(built.dir, '.next')) + .unique.map(debugIdOf) + .filter((id): id is string => id !== undefined); + // Server bundles as well as browser ones carry an id, and every id reached the collector. + expect(ids.length).toBeGreaterThan(clientBundles(built.dir).length); + for (const id of ids) { + expect(sent, `debug-id ${id} was not uploaded`).toContain(id); + } + }); + + it('removes the publicly served client maps and keeps the server maps', () => { + // What may remain in `.next/static` is a map no bundle points at (Next ships a polyfill that way) or the map + // two unstamped Turbopack runtime chunks share (Next 15.5). Neither is the app's code, neither was uploaded. + const staticDir = join(built.dir, '.next', 'static'); + const { shared, referenced } = split(staticDir); + const sharedMaps = new Set( + pointing(staticDir) + .filter((p) => shared.includes(p.file)) + .map((p) => p.map), + ); + for (const map of maps(staticDir)) { + expect(referenced.has(map) && !sharedMaps.has(map), `${map} is still served`).toBe(false); + } + const server = split(join(built.dir, '.next', 'server')); + const kept = maps(join(built.dir, '.next', 'server')).filter((m) => server.referenced.has(m)); + expect(kept.length).toBeGreaterThan(0); + for (const map of kept) { + expect(JSON.parse(readFileSync(map, 'utf8')).debugId, map).toMatch(/^[0-9a-f-]{36}$/); + } + }); + + it('covers the edge route too', () => { + const edgeBundles = split(join(built.dir, '.next', 'server')).unique.filter((f) => + /edge/.test(f), + ); + expect(edgeBundles.length).toBeGreaterThan(0); + for (const bundle of edgeBundles) { + expect(debugIdOf(bundle), bundle).toBeDefined(); + } + }); + + it('bakes the app version and build into the bundle', () => { + const text = clientBundles(built.dir) + .map((f) => readFileSync(f, 'utf8')) + .join('\n'); + expect(text).toContain('9.8.7'); + }); + + it('produces a build that still runs', async () => { + expect(await runBuild(built.dir, ['/', '/api/hi', '/edge'])).toEqual([200, 200, 200]); + }); + + it('runs in a real browser: the lazy chunk loads and executes, debug-ids register, no errors', async () => { + expectRuns(await openInBrowser(built.dir), { stamped: true }); + }); +}); + +describe('withBugsee — Subresource Integrity', () => { + it('webpack: stamps inside the build, so every pinned hash still matches the bytes on disk', async () => { + const built = await build({ + name: 'sri-webpack', + next: 'next16', + args: ['--webpack'], + nextConfig: "experimental: { sri: { algorithm: 'sha256' } },", + }); + expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0); + expect(built.log).not.toMatch(/\[bugsee\]/); + const html = readFileSync(join(built.dir, '.next', 'server', 'app', 'index.html'), 'utf8'); + const pins = [ + ...html.matchAll( + /]*?(?:src="([^"]+)"[^>]*?integrity="([^"]+)"|integrity="([^"]+)"[^>]*?src="([^"]+)")/g, + ), + ]; + expect(pins.length).toBeGreaterThan(0); + for (const m of pins) { + const src = (m[1] ?? m[4]) as string; + const integrity = (m[2] ?? m[3]) as string; + const file = join(built.dir, '.next', src.replace(/^\/_next\//, '')); + const [algo] = integrity.split('-'); + const digest = createHash(algo as string) + .update(readFileSync(file)) + .digest('base64'); + expect(integrity, src).toBe(`${algo}-${digest}`); + expect(debugIdOf(file), `${src} was not stamped`).toBeDefined(); + } + expect(built.uploads.length).toBeGreaterThan(0); + // The browser enforces the hashes: the stamped, SRI-pinned page must still run, lazy chunk included. + expectRuns(await openInBrowser(built.dir), { stamped: true }); + }); + + it('turbopack: leaves an SRI build exactly as Next wrote it, and says why', async () => { + const built = await build({ + name: 'sri-turbopack', + next: 'next16', + args: [], + nextConfig: "experimental: { sri: { algorithm: 'sha256' } },", + options: 'failOnError: false,', + }); + expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0); + expect(built.log).toMatch(/Subresource Integrity/); + expect(built.uploads).toEqual([]); + // Unstamped, so the page's hashes still match. + for (const bundle of clientBundles(built.dir)) { + expect(debugIdOf(bundle), bundle).toBeUndefined(); + } + expectRuns(await openInBrowser(built.dir), { stamped: false }); + // Bugsee did not turn browser maps on for a build it cannot upload for: none are written, none are public. + expect(maps(join(built.dir, '.next', 'static'))).toEqual([]); + }); + + it('webpack: a failed in-build stamp does NOT fall back to stamping the written files of an SRI build', async () => { + const built = await build({ + name: 'sri-webpack-fallback', + next: 'next16', + args: ['--webpack'], + options: 'failOnError: false,', + nextConfig: "experimental: { sri: { algorithm: 'sha256' } },", + failInBuildStamp: true, + }); + expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0); + // ONE accurate message: the stamp failed and the fallback was refused. Never "falling back". + expect(built.log).not.toMatch(/falling back to stamping after emit/); + expect(built.log.split('\n').filter((l) => l.includes('Subresource Integrity'))).toHaveLength( + 3, + ); // client, server, edge: one notice each + expect(built.log).toMatch(/nothing was stamped or uploaded/); + expect(built.uploads).toEqual([]); + // Nothing was rewritten, so the pinned hashes still describe the bytes on disk and the page runs. + for (const bundle of walk(join(built.dir, '.next', 'static')).filter((f) => + f.endsWith('.js'), + )) { + expect(debugIdOf(bundle), bundle).toBeUndefined(); + } + expectRuns(await openInBrowser(built.dir), { stamped: false }); + // Bugsee had turned the browser maps on (the app did not ask); with no upload they must not stay public. + expect(maps(join(built.dir, '.next', 'static'))).toEqual([]); + expect(built.log).toMatch(/browser source maps Bugsee had turned on were removed/); + }); + + const sriFailing = (name: string, options: string) => + build({ + name, + next: 'next16', + args: ['--webpack'], + options, + nextConfig: "experimental: { sri: { algorithm: 'sha256' } },", + failInBuildStamp: true, + }); + + it('webpack + SRI + failOnError: a failed stamp fails the build, and no maps are left behind', async () => { + const built = await sriFailing('sri-webpack-strict', 'failOnError: true,'); + expect(built.status).not.toBe(0); + expect(built.log).toMatch(/inject/); + expect(maps(join(built.dir, '.next', 'static'))).toEqual([]); + }); + + it('webpack + SRI + silent: the notices are muted, the cause is still audible', async () => { + const built = await sriFailing('sri-webpack-silent', 'failOnError: false, silent: true,'); + expect(built.status, built.log.split('\n').slice(-30).join('\n')).toBe(0); + expect(built.log).not.toMatch(/Subresource Integrity/); + expect(built.log).toMatch(/in-build debug-ID stamping did not apply/); + expect(maps(join(built.dir, '.next', 'static'))).toEqual([]); + }); + + it('webpack + SRI + dryRun: browser maps are not forced on, so none are written or left public', async () => { + const built = await sriFailing('sri-webpack-dry', 'failOnError: false, dryRun: true,'); + expect(built.status, built.log.split('\n').slice(-30).join('\n')).toBe(0); + expect(built.uploads).toEqual([]); + expect(maps(join(built.dir, '.next', 'static'))).toEqual([]); + expect(built.log).not.toMatch(/Dry run: nothing was deleted/); + }); + + it('turbopack + SRI + maps the APP asked for: they stay, the notice says they are public, said once', async () => { + const built = await build({ + name: 'sri-turbopack-own-maps', + next: 'next16', + args: [], + nextConfig: + "experimental: { sri: { algorithm: 'sha256' } }, productionBrowserSourceMaps: true,", + options: 'failOnError: false,', + }); + expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0); + expect(built.uploads).toEqual([]); + expect(maps(join(built.dir, '.next', 'static')).length).toBeGreaterThan(0); + const said = built.log.split('\n').filter((l) => l.includes('Subresource Integrity')); + expect(said).toHaveLength(1); + expect(said[0]).toMatch(/publicly served/); + expectRuns(await openInBrowser(built.dir), { stamped: false }); + }); +}); + +describe.each([ + { name: 'foreign-webpack', next: 'next16', args: ['--webpack'] }, + { name: 'foreign-turbopack', next: 'next16', args: [] }, +] as Spec[])('withBugsee — files this build did not produce ($name)', (spec) => { + let built: Built; + beforeAll(async () => { + built = await build({ ...spec, seedForeign: true }); + }); + + it('builds', () => { + expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0); + }); + + it('never deletes a stylesheet or declaration map it did not produce', () => { + for (const [dir, name] of FOREIGN) { + const file = join(built.dir, '.next', dir, name); + expect(existsSync(file), `${dir}/${name} was deleted`).toBe(true); + expect(readFileSync(file, 'utf8')).toBe(FOREIGN_BODY); + } + }); + + it('still uploaded and deleted its own maps', () => { + expect(built.uploads.length).toBeGreaterThan(0); + const { unique } = split(join(built.dir, '.next', 'static')); + expect(unique.length).toBeGreaterThan(2); + for (const bundle of unique) { + expect(debugIdOf(bundle), bundle).toBeDefined(); + } + const own = maps(join(built.dir, '.next', 'static')).filter( + (m) => !m.includes('foreign.') && split(join(built.dir, '.next', 'static')).referenced.has(m), + ); + expect(own).toEqual([]); + }); +}); + +// A collector that is down: the upload fails (contained, failOnError false), and the browser maps Bugsee itself turned +// on must not be left in `.next/static`, which `next start` and CDNs serve publicly. +describe.each([ + { name: 'upload-down-turbopack', next: 'next16' as const, args: [] as string[] }, + { name: 'upload-down-webpack', next: 'next16' as const, args: ['--webpack'] }, +])('withBugsee — the upload fails ($name)', (spec) => { + let built: Built; + beforeAll(async () => { + built = await build({ + ...spec, + options: "failOnError: false, endpoint: 'http://127.0.0.1:1',", + }); + }); + + it('still builds, and leaves no public browser map behind', () => { + expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0); + // Same allowance as the happy path: a map no bundle points at, or the one two unstamped Turbopack runtime chunks + // share, is not the app's code and was never forced on by Bugsee. + const staticDir = join(built.dir, '.next', 'static'); + const { shared, referenced } = split(staticDir); + const sharedMaps = new Set( + pointing(staticDir) + .filter((p) => shared.includes(p.file)) + .map((p) => p.map), + ); + for (const map of maps(staticDir)) { + expect(referenced.has(map) && !sharedMaps.has(map), `${map} is still served`).toBe(false); + } + }); +}); diff --git a/packages/nextjs/README.md b/packages/nextjs/README.md index 0d6bd2f00..2833968a8 100644 --- a/packages/nextjs/README.md +++ b/packages/nextjs/README.md @@ -63,6 +63,59 @@ export const middleware = withBugseeMiddleware((request, event) => { }); ``` +## Source maps (build integration) + +`withBugsee` makes `next build` upload source maps to Bugsee, so a minified browser, server or edge stack trace is shown against your original source. It handles both bundlers: webpack (`next build --webpack`, the default up to Next 15) and Turbopack (the default in Next 16). + +```js +// next.config.mjs +import { withBugsee } from "@bugsee/nextjs/config"; + +export default withBugsee( + { + // your Next config: an object, a (phase) function, or an async one + }, + { + // BUGSEE_APP_TOKEN in the environment (or .env.bugsee-build-plugin) works too + appToken: process.env.BUGSEE_APP_TOKEN, + }, +); +``` + +CommonJS works as well: `const { withBugsee } = require("@bugsee/nextjs/config");` in `next.config.js`. + +What it does, for a production build: + +- Turns on `productionBrowserSourceMaps` (only when you did not set it, and only when this build can actually upload: not for Turbopack with `experimental.sri`, not for Turbopack on Next older than 15.4.0, not on a `dryRun`) so the browser bundles have maps to upload. Where it cannot upload it leaves the option as you set it and says so. +- **webpack**: adds one Bugsee plugin to each of the client, server and edge compilations. Each stamps a debug ID into its bundles inside the build (before Subresource Integrity hashes are taken) and, after emit, uploads the maps of exactly the files that compilation wrote. +- **Turbopack**: has no plugin API, so the upload runs from Next's `compiler.runAfterProductionCompile` hook (Next 15.4.0 or later): after Turbopack wrote `.next` and before Next generates the static pages, it stamps the written bundles with the real `bugsee-cli sourcemaps inject` (verified, and undone if a stamp does not verify), uploads the maps and removes them. +- Deletes the browser maps (`.next/static/**/*.map`, which `next start` and CDNs serve publicly) after a confirmed upload, unless you set `deleteMaps: false` (then they stay in `.next/static` and are served). If `withBugsee` itself turned `productionBrowserSourceMaps` on and the upload is not confirmed, it removes the maps it caused (unless `deleteMaps: false` or `dryRun`). Server and edge maps stay on disk (`deleteServerMaps` to remove them). +- Bakes `appVersion` / `appBuild` into every bundle (`compiler.define`) for the runtime SDK. + +Your own config is kept: your `webpack` function runs first and its result is extended (Next itself needs a synchronous `webpack` function; an async one fails in Next 16), your `compiler.runAfterProductionCompile` runs before ours, `compiler.define` keys you set win, and `productionBrowserSourceMaps: false` is respected. `next dev`, `next start` and `next export` are not touched. + +Options are those of the Bugsee bundler plugins (`appToken`, `appVersion`, `appBuild`, `endpoint`, `deleteMaps`, `dryRun`, `failOnError`, `stripSourcesContent`, `disabled`, `vcs`, `commit`, `registerBuild`, `onError`, `onNotice`, see `@bugsee/webpack-plugin`), plus: + +| Option | Default | | +| --- | --- | --- | +| `serverSourceMaps` | `true` | Emit and upload server and edge maps. With webpack the server and edge compilations get `devtool: "source-map"` if you left it unset; Next's own `experimental.serverSourceMaps` is never changed. | +| `deleteServerMaps` | `false` | Delete server and edge maps after a confirmed upload. | +| `silent` | `false` | Suppress configuration notices (failures are still reported). | + +Without a token the integration changes nothing about what Next emits (it adds no source maps, no define, no hook) and uploads nothing. + +Things to know: + +- The config is resolved once, at load, from the working directory: the token file, the app version and the installed Next version are looked up there. Run `next build` from the project directory. For a Turbopack build the hook is told which project Next is building, and prints a notice if that differs (for example `next build apps/web` from a monorepo root). +- `withBugsee` turns `productionBrowserSourceMaps` on, so the browser maps are written to `.next/static`, which is served publicly. They are deleted after a confirmed upload. If the upload fails (and `failOnError` is off) they stay there, publicly served, so you can retry. If that is not acceptable, set `failOnError: true` so a failed upload stops the build, or delete `.next/static/**/*.map` in your deploy step. +- Next 15's Turbopack builds point two runtime chunks at one shared map. Those chunks are left unstamped and that map is neither uploaded nor deleted: it stays in `.next/static`, public. It contains Turbopack's runtime source, not your code. +- Build registration follows the source-map pipeline: the build id is derived from the debug-IDs stamped into the bundles, so an app with source maps turned off (nothing stamped) registers nothing. +- If your own `compiler.define` sets `__BUGSEE_APP_VERSION__` or `__BUGSEE_APP_BUILD__` to a string, that is the value the runtime SDK reports, and the upload and the build registration are labelled with it too. A non-string value is ignored (the resolved version is used). +- `compiler.define` (the baked version and build) needs Next 15.1.0 or later; the Turbopack upload needs 15.4.0 or later. +- `@bugsee/nextjs` depends on `@bugsee/bundler-plugin-core` (which brings `@bugsee/cli`, acorn, magic-string and unplugin) so that `withBugsee` works with no extra install. Only `next.config` loads it; your app bundles never import it. Making it an optional peer would force every user of the config to install it by hand and break `next build` out of the box, so it stays a regular dependency. + +Turbopack and Subresource Integrity: Turbopack hashes its output (`experimental.sri`) before the post-build hook runs, so stamping afterwards would make the browser refuse your scripts. An SRI build under Turbopack is therefore left exactly as Next wrote it, with a notice, and no maps are uploaded; build with `--webpack` to upload maps for an SRI build (webpack stamps before the hashes are taken). On webpack with `experimental.sri`, if the in-build stamp itself fails, the fallback of stamping the written files is skipped (it would invalidate the pinned hashes) and nothing is uploaded for that compilation, with a notice. The browser maps Bugsee itself turned on are then deleted again; maps you enabled yourself (`productionBrowserSourceMaps: true`) stay in `.next/static`, publicly served, and the notice says so. "Maps you enabled yourself" means `productionBrowserSourceMaps` was set when `withBugsee` ran: if a wrapper applied after `withBugsee` turns it on, Bugsee still counts the maps as its own and removes them in this failure case. A `//# sourceMappingURL` comment may then point at a map that no longer exists (harmless: only devtools ask for it). On a dry run nothing is deleted. + ## Options Both `register(appToken, options)` and `registerClient(appToken, options)` accept the SDK launch options. The most relevant ones: @@ -76,6 +129,7 @@ Both `register(appToken, options)` and `registerClient(appToken, options)` accep - `@bugsee/nextjs`: `register`, `onRequestError`, `createOnRequestError`, `getBugseeTraceData`. - `@bugsee/nextjs/client`: `registerClient`, `onRouterTransitionStart`, plus the React adapter. - `@bugsee/nextjs/middleware`: `withBugseeMiddleware`. +- `@bugsee/nextjs/config`: `withBugsee` (build-time; import it from `next.config`, never from app code). - `@bugsee/nextjs/server` and `@bugsee/nextjs/edge`: the Node.js and Edge compositions that `register()` loads for you. ## Links diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 18f984e32..3d4bbc6c1 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -7,7 +7,7 @@ "url": "git+https://github.com/bugsee/bugsee-javascript.git", "directory": "packages/nextjs" }, - "description": "Next.js meta-adapter: client + server + edge entries", + "description": "Next.js meta-adapter: client + server + edge entries, plus the withBugsee() build integration (source-map upload)", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", @@ -31,6 +31,10 @@ "./middleware": { "types": "./src/middleware.ts", "import": "./src/middleware.ts" + }, + "./config": { + "types": "./src/config/index.ts", + "import": "./src/config/index.ts" } }, "files": [ @@ -49,7 +53,8 @@ "@bugsee/protocol": "workspace:*", "@bugsee/react": "workspace:*", "@bugsee/vercel-edge": "workspace:*", - "@bugsee/bugsee": "workspace:*" + "@bugsee/bugsee": "workspace:*", + "@bugsee/bundler-plugin-core": "workspace:*" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0", @@ -133,6 +138,16 @@ "types": "./dist/middleware.d.cts", "default": "./dist/middleware.cjs" } + }, + "./config": { + "import": { + "types": "./dist/config.d.ts", + "default": "./dist/config.js" + }, + "require": { + "types": "./dist/config.d.cts", + "default": "./dist/config.cjs" + } } }, "access": "public" diff --git a/packages/nextjs/src/config/build-files.test.ts b/packages/nextjs/src/config/build-files.test.ts new file mode 100644 index 000000000..068e1df29 --- /dev/null +++ b/packages/nextjs/src/config/build-files.test.ts @@ -0,0 +1,280 @@ +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { collectBuildFiles, mapPointerOf, pairByPointer, partitionBuildFiles } from './build-files'; + +// `mapPointerOf` resolves against the host's path API, so the pointer fixtures use native absolute paths (win32: `C:\\o\\a.js`). +const p = (path: string): string => resolve(path); + +describe('partitionBuildFiles', () => { + it('pairs each bundle with its map and sorts both', () => { + const files = ['/o/b.js.map', '/o/a.js', '/o/b.js', '/o/a.js.map']; + expect(partitionBuildFiles(files)).toEqual({ + scripts: ['/o/a.js', '/o/b.js'], + maps: ['/o/a.js.map', '/o/b.js.map'], + stylesheetMaps: [], + }); + }); + + it('accepts an upper-case extension, as the core does', () => { + expect(partitionBuildFiles(['/o/A.JS', '/o/A.JS.map']).scripts).toEqual(['/o/A.JS']); + }); + + it('accepts .mjs and .cjs bundles', () => { + const files = ['/o/a.mjs', '/o/a.mjs.map', '/o/b.cjs', '/o/b.cjs.map']; + expect(partitionBuildFiles(files).scripts).toEqual(['/o/a.mjs', '/o/b.cjs']); + }); + + it('never stamps a bundle that has no map, and never sends a map that has no bundle', () => { + const files = ['/o/lonely.js', '/o/orphan.js.map', '/o/ok.js', '/o/ok.js.map']; + const parts = partitionBuildFiles(files); + expect(parts.scripts).toEqual(['/o/ok.js']); + expect(parts.maps).toEqual(['/o/ok.js.map']); + }); + + it('keeps stylesheet maps apart: deleted with the rest, never sent', () => { + const files = ['/o/a.css', '/o/a.css.map', '/o/a.js', '/o/a.js.map']; + const parts = partitionBuildFiles(files); + expect(parts.stylesheetMaps).toEqual(['/o/a.css.map']); + expect(parts.maps).toEqual(['/o/a.js.map']); + }); + + it('ignores everything else', () => { + expect(partitionBuildFiles(['/o/a.html', '/o/a.json', '/o/a.png'])).toEqual({ + scripts: [], + maps: [], + stylesheetMaps: [], + }); + }); +}); + +describe('mapPointerOf', () => { + it('resolves the pointer against the bundle directory', () => { + expect(mapPointerOf(p('/o/chunks/a.js'), 'code();\n//# sourceMappingURL=other.js.map\n')).toBe( + p('/o/chunks/other.js.map'), + ); + expect(mapPointerOf(p('/o/chunks/a.js'), 'x\n//@ sourceMappingURL=../m/a.map')).toBe( + p('/o/m/a.map'), + ); + }); + + it('decodes a percent-encoded pointer (Turbopack names contain brackets)', () => { + expect(mapPointerOf(p('/o/a.js'), 'x\n//# sourceMappingURL=%5Broot%5D__a._.js.map\n')).toBe( + p('/o/[root]__a._.js.map'), + ); + }); + + it('uses a pointer as written when it is not valid percent-encoding', () => { + expect(mapPointerOf(p('/o/a.js'), 'x\n//# sourceMappingURL=100%.js.map')).toBe( + p('/o/100%.js.map'), + ); + }); + + it('reads a stylesheet pointer from its /*# */ comment, not the // form', () => { + expect(mapPointerOf(p('/o/a.css'), 'a{}\n/*# sourceMappingURL=a.css.map */')).toBe( + p('/o/a.css.map'), + ); + expect(mapPointerOf(p('/o/a.css'), 'a{}\n//# sourceMappingURL=a.css.map')).toBeUndefined(); + expect(mapPointerOf(p('/o/a.js'), 'x\n/*# sourceMappingURL=a.js.map */')).toBeUndefined(); + }); + + it('reads the legacy /*@ */ stylesheet form too', () => { + expect(mapPointerOf(p('/o/a.css'), 'a{}\n/*@ sourceMappingURL=x.css.map*/')).toBe( + p('/o/x.css.map'), + ); + }); + + it('has no pointer for a bundle without a comment, or with an inline map', () => { + expect(mapPointerOf(p('/o/a.js'), 'no comment')).toBeUndefined(); + expect( + mapPointerOf(p('/o/a.js'), 'x\n//# sourceMappingURL=data:application/json;base64,e30='), + ).toBeUndefined(); + }); + + it('only counts the comment that ends the bundle', () => { + expect(mapPointerOf(p('/o/a.js'), '//# sourceMappingURL=a.map\nmore();')).toBeUndefined(); + }); +}); + +describe('pairByPointer', () => { + const code = (map: string): string => `code();\n//# sourceMappingURL=${map}\n`; + const reader = (sources: Record) => async (file: string) => sources[file] ?? ''; + + it('pairs a bundle with a map that is NOT named after it', async () => { + const files = [p('/o/0ihtw.js'), p('/o/1wkfrb.js.map')]; + const parts = await pairByPointer(files, reader({ [p('/o/0ihtw.js')]: code('1wkfrb.js.map') })); + expect(parts).toEqual({ + scripts: [p('/o/0ihtw.js')], + maps: [p('/o/1wkfrb.js.map')], + stylesheetMaps: [], + shared: [], + }); + }); + + it('ignores a pointer to a file that is not there', async () => { + const parts = await pairByPointer( + [p('/o/a.js')], + reader({ [p('/o/a.js')]: code('gone.js.map') }), + ); + expect(parts.scripts).toEqual([]); + }); + + it('ignores a pointer to something that is not a map', async () => { + const parts = await pairByPointer( + [p('/o/a.js'), p('/o/b.js')], + reader({ [p('/o/a.js')]: code('b.js') }), + ); + expect(parts.scripts).toEqual([]); + expect(parts.maps).toEqual([]); + }); + + it('pairs neither bundle of a map two bundles share, and reports them', async () => { + const parts = await pairByPointer( + [p('/o/a.js'), p('/o/b.js'), p('/o/shared.js.map'), p('/o/c.js'), p('/o/c.js.map')], + reader({ + [p('/o/a.js')]: code('shared.js.map'), + [p('/o/b.js')]: code('shared.js.map'), + [p('/o/c.js')]: code('c.js.map'), + }), + ); + expect(parts.scripts).toEqual([p('/o/c.js')]); + expect(parts.maps).toEqual([p('/o/c.js.map')]); + expect(parts.shared).toEqual([p('/o/a.js'), p('/o/b.js')]); + }); + + it('does not read files that are not scripts', async () => { + const read = vi.fn(async () => ''); + await pairByPointer([p('/o/a.json'), p('/o/a.js.map'), p('/o/a.txt')], read); + expect(read).not.toHaveBeenCalled(); + }); + + it("keeps this build's stylesheet maps apart (a stylesheet points at them): deleted, never sent", async () => { + const css = (map: string): string => `a{}\n/*# sourceMappingURL=${map} */\n`; + const parts = await pairByPointer( + [p('/o/a.css'), p('/o/x1.map')], + reader({ [p('/o/a.css')]: css('x1.map') }), + ); + expect(parts.stylesheetMaps).toEqual([p('/o/x1.map')]); + expect(parts.maps).toEqual([]); + }); + + it("leaves a stylesheet or declaration map nothing points at alone: it is not this build's", async () => { + const parts = await pairByPointer( + [p('/o/a.css'), p('/o/a.css.map'), p('/o/foreign.css.map'), p('/o/types.d.ts.map')], + reader({ [p('/o/a.css')]: 'a{}\n/*# sourceMappingURL=a.css.map */' }), + ); + expect(parts.stylesheetMaps).toEqual([p('/o/a.css.map')]); + }); + + it('ignores a stylesheet pointer to a missing or non-map file, or an inline map', async () => { + const parts = await pairByPointer( + [p('/o/a.css'), p('/o/b.css'), p('/o/c.css'), p('/o/c.txt')], + reader({ + [p('/o/a.css')]: 'a{}/*# sourceMappingURL=gone.css.map */', + [p('/o/b.css')]: 'a{}/*# sourceMappingURL=c.txt */', + [p('/o/c.css')]: 'a{}/*# sourceMappingURL=data:application/json;base64,e30= */', + }), + ); + expect(parts.stylesheetMaps).toEqual([]); + }); + + it('sorts its output', async () => { + const parts = await pairByPointer( + [p('/o/z.js'), p('/o/a.js'), p('/o/m1.map'), p('/o/m0.map')], + reader({ [p('/o/z.js')]: code('m1.map'), [p('/o/a.js')]: code('m0.map') }), + ); + expect(parts.scripts).toEqual([p('/o/a.js'), p('/o/z.js')]); + expect(parts.maps).toEqual([p('/o/m0.map'), p('/o/m1.map')]); + }); +}); + +describe('collectBuildFiles', () => { + let root: string; + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-bf-')); + }); + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + const put = (rel: string, content = 'x'): void => { + mkdirSync(join(root, rel, '..'), { recursive: true }); + writeFileSync(join(root, rel), content); + }; + const bundle = (rel: string, mapName = `${rel.split('/').pop()}.map`): void => { + put(rel, `code();\n//# sourceMappingURL=${encodeURIComponent(mapName)}\n`); + put(`${rel}/../${mapName}`); + }; + + it('walks nested directories, bracketed names included', async () => { + bundle('chunks/[root-of-the-server]__a._.js'); + bundle('chunks/ssr/b.js'); + const parts = await collectBuildFiles(root); + expect(parts.scripts).toEqual([ + join(root, 'chunks/[root-of-the-server]__a._.js'), + join(root, 'chunks/ssr/b.js'), + ]); + expect(parts.maps).toHaveLength(2); + }); + + it('pairs by the pointer inside the bundle when the map has another name', async () => { + bundle('chunks/0ihtw.js', '1wkfrb.js.map'); + const parts = await collectBuildFiles(root); + expect(parts.scripts).toEqual([join(root, 'chunks/0ihtw.js')]); + expect(parts.maps).toEqual([join(root, 'chunks/1wkfrb.js.map')]); + }); + + it('never descends into node_modules', async () => { + bundle('node_modules/x/a.js'); + bundle('ok.js'); + expect((await collectBuildFiles(root)).scripts).toEqual([join(root, 'ok.js')]); + }); + + it('does descend into a route directory that happens to be called cache', async () => { + bundle('chunks/app/cache/page.js'); + expect((await collectBuildFiles(root)).scripts).toEqual([ + join(root, 'chunks/app/cache/page.js'), + ]); + }); + + it('returns nothing for a directory that does not exist', async () => { + expect(await collectBuildFiles(join(root, 'absent'))).toEqual({ + scripts: [], + maps: [], + stylesheetMaps: [], + shared: [], + }); + }); + + it('collects deeply nested output: no depth cutoff silently drops a route\u2019s bundle', async () => { + const deep = `${Array.from({ length: 30 }, (_, i) => `d${i}`).join('/')}/page.js`; + bundle(deep); + bundle('top.js'); + const scripts = (await collectBuildFiles(root)).scripts; + expect(scripts).toHaveLength(2); + expect(scripts).toContain(join(root, deep)); + }); + + it('reads only the END of a bundle to find its pointer', async () => { + // A pointer-looking comment at the START of a large file is not the bundle\u2019s pointer; only the tail counts. + put('big.js', `//# sourceMappingURL=big.js.map\n${'x'.repeat(40_000)}\nend();\n`); + put('big.js.map'); + expect((await collectBuildFiles(root)).scripts).toEqual([]); + put('big2.js', `${'x'.repeat(40_000)}\n//# sourceMappingURL=big2.js.map\n`); + put('big2.js.map'); + expect((await collectBuildFiles(root)).scripts).toEqual([join(root, 'big2.js')]); + }); + + it('reports a directory it cannot read instead of calling it empty', async () => { + put('locked/a.js'); + chmodSync(join(root, 'locked'), 0o000); + try { + if (process.getuid?.() === 0 || process.platform === 'win32') { + return; // root reads it anyway, and Windows ignores the mode bits + } + await expect(collectBuildFiles(root)).rejects.toThrow(/EACCES/); + } finally { + chmodSync(join(root, 'locked'), 0o755); + } + }); +}); diff --git a/packages/nextjs/src/config/build-files.ts b/packages/nextjs/src/config/build-files.ts new file mode 100644 index 000000000..b36087b2d --- /dev/null +++ b/packages/nextjs/src/config/build-files.ts @@ -0,0 +1,145 @@ +// Which files of a Next build the upload covers, named explicitly. The upload never walks `.next` and never +// takes a directory: it is handed exactly these paths, so it cannot stamp, upload or delete a file that is not +// part of the build it is looking at (the webpack compilations and the Turbopack output share `.next`). +import { open, readdir } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; + +/** A build's bundles and the maps that belong to them. */ +export interface BuildFiles { + /** Bundles that have a map. A bundle without one cannot be symbolicated, so it is never stamped. */ + scripts: string[]; + /** The maps of those bundles. */ + maps: string[]; + /** Stylesheet maps: never sent, but deleted with the rest after a confirmed upload (they embed the source). */ + stylesheetMaps: string[]; + /** Bundles left out because their map is shared with another bundle (see {@link pairByPointer}). */ + shared?: string[]; + /** Each script's map, where the caller knows the pairing (webpack: sibling name or recorded relationship). */ + pairs?: Record; +} + +const SCRIPT = /\.[cm]?js$/i; +/** How much of the END of a file is read to find its source-map comment (the comment is a line or two). */ +const TAIL_BYTES = 16 * 1024; +/** Directories that are never build output, wherever they appear (a route may well be called `cache`). */ +const SKIP = new Set(['node_modules']); + +/** The last {@link TAIL_BYTES} of a file as text (the whole file when it is smaller). */ +export async function readTail(file: string): Promise { + const handle = await open(file, 'r'); + try { + const { size } = await handle.stat(); + const length = Math.min(size, TAIL_BYTES); + const buffer = Buffer.alloc(length); + await handle.read(buffer, 0, length, size - length); + return buffer.toString('utf8'); + } finally { + await handle.close(); + } +} + +async function listFiles(dir: string): Promise { + let entries: import('node:fs').Dirent[]; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch (error) { + // A directory the build did not produce (no `server` output, say) contributes nothing; any other failure + // (EACCES, EIO) is NOT "nothing to upload" and is left to the caller's failure policy. + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return []; + } + throw error; + } + const found: string[] = []; + for (const entry of entries) { + const full = join(dir, entry.name); + if (entry.isDirectory()) { + if (!SKIP.has(entry.name)) { + found.push(...(await listFiles(full))); + } + } else if (entry.isFile()) { + found.push(full); + } + } + return found; +} + +/** Split a list of files into the bundles that have a map, their maps, and the stylesheet maps. */ +export function partitionBuildFiles(files: readonly string[]): BuildFiles { + const present = new Set(files); + const scripts = files.filter((file) => SCRIPT.test(file) && present.has(`${file}.map`)); + const owned = new Set(scripts); + return { + scripts: scripts.sort(), + maps: files.filter((file) => file.endsWith('.map') && owned.has(file.slice(0, -4))).sort(), + stylesheetMaps: files.filter((file) => file.endsWith('.css.map')).sort(), + }; +} + +/** A bundle's source-map pointer: the last `//# sourceMappingURL=` comment (a `/*# ... *\/` comment in a stylesheet). */ +const POINTER = /\/\/[#@] sourceMappingURL=([^\s'"]+)\s*$/; +const CSS_POINTER = /\/\*[#@] sourceMappingURL=([^\s'"*]+)\s*\*\/\s*$/; + +/** The path a bundle's source-map comment names, or `undefined` when it has none or the map is inline. */ +export function mapPointerOf(file: string, code: string): string | undefined { + const reference = (file.endsWith('.css') ? CSS_POINTER : POINTER).exec(code)?.[1]; + if (reference === undefined || reference.startsWith('data:')) { + return undefined; + } + let decoded = reference; + try { + decoded = decodeURIComponent(reference); + } catch { + // Not percent-encoded after all: use it as written. + } + return resolve(dirname(file), decoded); +} + +/** + * Pair bundles with their maps by the pointer inside each bundle, not by name. Turbopack does not name a map after + * its bundle (measured, Next 16.4: `chunks/0ihtwxitjxx9w.js` ends in `sourceMappingURL=1wkfrb_3m2k-z.js.map`), so + * `.map` finds nothing there. Only a pointer that names a `.map` file that exists counts. + */ +export async function pairByPointer( + files: readonly string[], + read: (file: string) => Promise = readTail, +): Promise { + const present = new Set(files); + const pointers = new Map(); + const users = new Map(); + for (const file of files.filter((f) => SCRIPT.test(f))) { + const map = mapPointerOf(file, await read(file)); + if (map?.endsWith('.map') && present.has(map)) { + pointers.set(file, map); + users.set(map, (users.get(map) ?? 0) + 1); + } + } + // Stylesheet maps are never uploaded but embed the source, so they are deleted with the rest, and only THIS + // build's: a stylesheet map is this build's when one of its stylesheets points at it. A `.css.map` (or a + // `.d.ts.map`) that nothing here points at was put there by something else, and is left alone. + const styles = new Set(); + for (const file of files.filter((f) => f.endsWith('.css'))) { + const map = mapPointerOf(file, await read(file)); + if (map?.endsWith('.map') && present.has(map)) { + styles.add(map); + } + } + // A map belongs to one bundle: a debug-ID is the hash of the bundle AND its map, and a map carries one. Two + // bundles pointing at the same map (Next 15.5's Turbopack does this for its runtime chunks, measured) cannot both + // be keyed to it, so neither is paired: stamping one would leave the other with an id no map answers to. + const paired = [...pointers].filter(([, map]) => users.get(map) === 1); + return { + scripts: paired.map(([file]) => file).sort(), + maps: paired.map(([, map]) => map).sort(), + stylesheetMaps: [...styles].sort(), + shared: [...pointers] + .filter(([, map]) => (users.get(map) as number) > 1) + .map(([file]) => file) + .sort(), + }; +} + +/** The build files under `dir` (recursively), paired by pointer; none when `dir` does not exist. */ +export async function collectBuildFiles(dir: string): Promise { + return pairByPointer(await listFiles(dir)); +} diff --git a/packages/nextjs/src/config/context.test.ts b/packages/nextjs/src/config/context.test.ts new file mode 100644 index 000000000..0c12eb8b6 --- /dev/null +++ b/packages/nextjs/src/config/context.test.ts @@ -0,0 +1,133 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createBugseeContext } from './context'; + +let dir: string; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'bugsee-ctx-')); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'app', version: '4.5.6' })); +}); +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + delete (globalThis as { __BUGSEE_REAL_ENV_FILE__?: boolean }).__BUGSEE_REAL_ENV_FILE__; +}); + +describe('createBugseeContext', () => { + it('takes the token from the option, then the environment', () => { + expect(createBugseeContext({ appToken: 'opt' }, dir, { env: {} }).resolved.appToken).toBe( + 'opt', + ); + expect( + createBugseeContext({}, dir, { env: { BUGSEE_APP_TOKEN: 'from-env' } }).resolved, + ).toMatchObject({ appToken: 'from-env', enabled: true }); + }); + + it('is disabled without a token, and with disabled: true', () => { + expect(createBugseeContext({}, dir, { env: {} }).resolved.enabled).toBe(false); + expect( + createBugseeContext({ appToken: 't', disabled: true }, dir, { env: {} }).resolved.enabled, + ).toBe(false); + }); + + it('reads the token from .env.bugsee-build-plugin in the project directory', () => { + // The shared test setup hides this file from every test; opt in, as the core's env-file tests do. + (globalThis as { __BUGSEE_REAL_ENV_FILE__?: boolean }).__BUGSEE_REAL_ENV_FILE__ = true; + writeFileSync(join(dir, '.env.bugsee-build-plugin'), 'BUGSEE_APP_TOKEN=from-file\n'); + expect(createBugseeContext({}, dir, { env: {} }).resolved).toMatchObject({ + appToken: 'from-file', + enabled: true, + }); + }); + + it('does not read the env file at all when disabled', () => { + (globalThis as { __BUGSEE_REAL_ENV_FILE__?: boolean }).__BUGSEE_REAL_ENV_FILE__ = true; + writeFileSync(join(dir, '.env.bugsee-build-plugin'), 'BUGSEE_APP_TOKEN=from-file\n'); + expect(createBugseeContext({ disabled: true }, dir, { env: {} }).resolved.appToken).toBe(''); + }); + + it('says once when the env file was found but gave nothing', () => { + (globalThis as { __BUGSEE_REAL_ENV_FILE__?: boolean }).__BUGSEE_REAL_ENV_FILE__ = true; + writeFileSync(join(dir, '.env.bugsee-build-plugin'), Buffer.from([0xff, 0xfe, 0x41, 0x00])); + const notices: string[] = []; + createBugseeContext({ onNotice: (m) => notices.push(m) }, dir, { env: {} }); + expect(notices).toHaveLength(1); + expect(notices[0]).toMatch(/^\[bugsee\] /); + }); + + it('resolves the identity from the project directory, option first', () => { + expect(createBugseeContext({ appToken: 't' }, dir, { env: {} }).resolved).toMatchObject({ + appVersion: '4.5.6', + identityDefines: expect.objectContaining({ __BUGSEE_APP_VERSION__: '"4.5.6"' }), + }); + expect( + createBugseeContext({ appToken: 't', appVersion: '9.9.9', appBuild: '7' }, dir, { env: {} }) + .resolved, + ).toMatchObject({ appVersion: '9.9.9', appBuild: '7' }); + }); + + it('points the VCS root at the project unless told otherwise', () => { + expect(createBugseeContext({}, dir, { env: {} }).resolved.projectRoot).toBe(dir); + expect( + createBugseeContext({ projectRoot: '/repo' }, dir, { env: {} }).resolved.projectRoot, + ).toBe('/repo'); + }); + + it('defaults the Next policy: server maps on, server maps kept', () => { + const context = createBugseeContext({}, dir, { env: {} }); + expect(context.serverSourceMaps).toBe(true); + expect(context.deleteServerMaps).toBe(false); + const custom = createBugseeContext({ serverSourceMaps: false, deleteServerMaps: true }, dir, { + env: {}, + }); + expect(custom.serverSourceMaps).toBe(false); + expect(custom.deleteServerMaps).toBe(true); + }); + + it('sends notices to onNotice with one [bugsee] prefix, de-duplicated', () => { + const notices: string[] = []; + const context = createBugseeContext({ onNotice: (m) => notices.push(m) }, dir, { env: {} }); + context.say('hello'); + context.say('hello'); + context.resolved.onNotice?.('[bugsee] from core'); + expect(notices).toEqual(['[bugsee] hello', '[bugsee] from core']); + }); + + it('warns on the console by default', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + createBugseeContext({}, dir, { env: {} }).say('careful'); + expect(warn).toHaveBeenCalledWith('[bugsee] careful'); + warn.mockRestore(); + }); + + it('says nothing when silent', () => { + const onNotice = vi.fn(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const context = createBugseeContext({ silent: true, onNotice }, dir, { env: {} }); + context.say('quiet'); + context.resolved.onNotice?.('[bugsee] quiet too'); + expect(onNotice).not.toHaveBeenCalled(); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it('survives a throwing notice sink', () => { + const context = createBugseeContext( + { + onNotice: () => { + throw new Error('logger down'); + }, + }, + dir, + { env: {} }, + ); + expect(() => context.say('x')).not.toThrow(); + }); + + it('reads process.env when no environment is injected', () => { + vi.stubEnv('BUGSEE_APP_TOKEN', 'ambient'); + expect(createBugseeContext({}, dir).resolved.appToken).toBe('ambient'); + vi.unstubAllEnvs(); + }); +}); diff --git a/packages/nextjs/src/config/context.ts b/packages/nextjs/src/config/context.ts new file mode 100644 index 000000000..6a976c97e --- /dev/null +++ b/packages/nextjs/src/config/context.ts @@ -0,0 +1,104 @@ +// The one place `withBugsee` turns its options into a resolved build context: the plugin options merged with the +// environment (and `.env.bugsee-build-plugin`), the app identity, and the Next-specific policy. Resolved ONCE, at +// config-evaluation time, from the project directory: the define baked into the bundle and the identity the upload +// is labelled with come from this single resolution, so they cannot disagree. +import { + type BugseePluginOptions, + loadBuildPluginEnv, + mergeBuildPluginEnv, + type ResolvedPluginOptions, + resolveIdentity, + resolvePluginOptions, +} from '@bugsee/bundler-plugin-core'; + +/** Options for {@link withBugsee}: everything the bundler plugins take, plus the Next-specific switches. */ +export interface WithBugseeOptions extends BugseePluginOptions { + /** + * Emit AND upload source maps for the server and edge bundles too. Default `true`. + * + * Next only writes server maps with `experimental.serverSourceMaps`; with this on, the webpack server and + * edge compilations get `devtool: 'source-map'` (set after your own `webpack` function ran, only when you + * left `devtool` unset), and Turbopack always emits them. Turn it off to symbolicate browser crashes only. + * This never sets Next's `experimental.serverSourceMaps`, so the server's runtime behaviour is unchanged. + */ + serverSourceMaps?: boolean; + /** + * Delete the server and edge `.map` files after a confirmed upload. Default `false`. + * + * Unlike `.next/static` (served to every visitor, so `deleteMaps` removes those), `.next/server` is never + * served, and a server running with `--enable-source-maps` reads these files at runtime. + */ + deleteServerMaps?: boolean; + /** + * Say nothing about configuration notices (a skipped upload, source maps switched off, a dry run's + * capture). Failures are still reported through `onError` / the console. Default `false`. + */ + silent?: boolean; +} + +/** What every part of the integration reads. */ +export interface BugseeNextContext { + /** The plugin options after env / env-file / identity resolution. */ + resolved: ResolvedPluginOptions; + /** Whether server/edge maps are emitted and uploaded. */ + serverSourceMaps: boolean; + /** Whether server/edge maps are deleted after a confirmed upload. */ + deleteServerMaps: boolean; + /** The app uses `experimental.sri` (set by `withBugsee` from the Next config it wraps). */ + sri?: boolean; + /** `withBugsee` itself turned `productionBrowserSourceMaps` on (the app did not ask for browser maps). */ + forcedMaps?: boolean; + /** Browser source maps are written for this build (the app asked for them, or Bugsee turned them on). */ + browserMaps?: boolean; + /** A notice said once per distinct text (a no-op when `silent`). */ + say(message: string): void; +} + +/** Seams for tests. */ +export interface ContextDeps { + env?: Record; +} + +/** Resolve the integration's context for `projectDir`. Never throws. */ +export function createBugseeContext( + options: WithBugseeOptions, + projectDir: string, + deps: ContextDeps = {}, +): BugseeNextContext { + const said = new Set(); + // `text` already carries the `[bugsee]` prefix: that is what the core hands an `onNotice` sink. + const emit = (text: string): void => { + if (options.silent === true || said.has(text)) { + return; + } + said.add(text); + try { + (options.onNotice ?? console.warn)(text); + } catch { + // A throwing host logger must not cost the build (the same containment the core's notify applies). + } + }; + const sink = (message: string): void => emit(`[bugsee] ${message}`); + const { values, problem } = + options.disabled === true ? { values: {}, problem: undefined } : loadBuildPluginEnv(projectDir); + if (problem !== undefined) { + sink(problem); + } + const merged = mergeBuildPluginEnv(deps.env ?? process.env, values); + const base = resolvePluginOptions(options, merged); + const identity = resolveIdentity(options, merged, projectDir); + return { + resolved: { + ...base, + ...identity, + // The repository the VCS resolver inspects, unless the caller chose one: the project, not the + // process cwd (which in a monorepo is usually the workspace root). + projectRoot: base.projectRoot ?? projectDir, + // Routed through the integration's own sink so `silent` and de-duplication apply to every notice. + onNotice: emit, + }, + serverSourceMaps: options.serverSourceMaps ?? true, + deleteServerMaps: options.deleteServerMaps ?? false, + say: sink, + }; +} diff --git a/packages/nextjs/src/config/index.ts b/packages/nextjs/src/config/index.ts new file mode 100644 index 000000000..ec949c946 --- /dev/null +++ b/packages/nextjs/src/config/index.ts @@ -0,0 +1,10 @@ +// `@bugsee/nextjs/config` — the build-time half of the Next.js integration (source-map upload). Node-only: import it +// from `next.config.{js,mjs,ts}`, never from application code. +export type { BugseeNextContext, WithBugseeOptions } from './context'; +export type { + NextConfigFunction, + NextConfigInput, + NextConfigObject, + WithBugseeDeps, +} from './with-bugsee'; +export { withBugsee } from './with-bugsee'; diff --git a/packages/nextjs/src/config/post-build.test.ts b/packages/nextjs/src/config/post-build.test.ts new file mode 100644 index 000000000..1624f65f1 --- /dev/null +++ b/packages/nextjs/src/config/post-build.test.ts @@ -0,0 +1,359 @@ +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { describe, expect, it, vi } from 'vitest'; +import type { BuildFiles } from './build-files'; +import type { BugseeNextContext } from './context'; +import { runPostBuild } from './post-build'; + +// Native absolute paths: `runPostBuild` resolves and joins with the host's path API (win32: `C:\\app\\.next`). +const p = (path: string): string => resolve(path); + +const files = (name: string): BuildFiles => ({ + scripts: [`/d/${name}.js`], + maps: [`/d/${name}.js.map`], + stylesheetMaps: [], +}); +const none: BuildFiles = { scripts: [], maps: [], stylesheetMaps: [] }; + +function context( + overrides: Partial = {}, + extra: Partial = {}, +): BugseeNextContext { + return { + resolved: { + enabled: true, + appToken: 't', + deleteMaps: true, + registerBuild: 'release', + ...overrides, + } as BugseeNextContext['resolved'], + serverSourceMaps: true, + deleteServerMaps: false, + say: vi.fn(), + ...extra, + }; +} + +const metadata = { projectDir: p('/app'), distDir: p('/app/.next') }; + +function deps(map: Record, sri = false) { + return { + // the browser run registered the build (see `registerBuild` below) + upload: vi.fn(async () => ({ build: { registered: true } }) as never), + collect: vi.fn(async (dir: string) => map[dir] ?? none), + exists: vi.fn(async () => sri), + }; +} + +describe('runPostBuild', () => { + it('does nothing when disabled', async () => { + const d = deps({}); + await runPostBuild(context({ enabled: false }), metadata, d); + expect(d.collect).not.toHaveBeenCalled(); + expect(d.upload).not.toHaveBeenCalled(); + }); + + it('uploads the browser output, then the server output, each over its own explicit files', async () => { + const client = files('client'); + const server = files('server'); + const d = deps({ [p('/app/.next/static')]: client, [p('/app/.next/server')]: server }); + await runPostBuild(context(), metadata, d); + expect(d.upload).toHaveBeenCalledTimes(2); + type Call = [ + Record, + string, + { files: BuildFiles; preStamped?: boolean; bundler: unknown }, + ]; + const [first, second] = (d.upload as ReturnType).mock.calls as [Call, Call]; + expect(first[1]).toBe(p('/app/.next/static')); + expect(first[2].files).toBe(client); + expect(first[0]).toMatchObject({ deleteMaps: true, registerBuild: 'release' }); + expect(second[1]).toBe(p('/app/.next/server')); + expect(second[2].files).toBe(server); + // Server output: the server deletion policy, and the build is registered once (by the browser run). + expect(second[0]).toMatchObject({ deleteMaps: false, registerBuild: false }); + // Stamped AFTER emit: not pre-stamped. + expect(first[2].preStamped).toBeUndefined(); + expect(first[2].bundler).toEqual({ isProduction: true, configuration: 'production' }); + }); + + it('keeps the registration for the server run when the browser run did NOT register the build', async () => { + for (const browserResult of [ + { build: { registered: false, reason: 'failed' } }, + { build: undefined }, + undefined, + ]) { + const d = deps({ + [p('/app/.next/static')]: files('client'), + [p('/app/.next/server')]: files('server'), + }); + d.upload = vi.fn(async (_r: unknown, dir: string) => + dir === p('/app/.next/static') ? browserResult : undefined, + ) as never; + await runPostBuild(context(), metadata, d); + const [, second] = (d.upload as ReturnType).mock.calls as [ + [unknown], + [Record], + ]; + expect(second[0]).toMatchObject({ registerBuild: 'release' }); + } + }); + + it('resolves a relative distDir against the project directory', async () => { + const d = deps({ [p('/app/.next/static')]: files('c') }); + await runPostBuild(context(), { projectDir: p('/app'), distDir: '.next' }, d); + expect(d.collect).toHaveBeenCalledWith(p('/app/.next/static')); + }); + + it('honours deleteServerMaps', async () => { + const d = deps({ [p('/app/.next/server')]: files('s') }); + await runPostBuild(context({}, { deleteServerMaps: true }), metadata, d); + const [resolved] = (d.upload as ReturnType).mock.calls[0] as [ + Record, + ]; + expect(resolved).toMatchObject({ deleteMaps: true }); + }); + + it('skips the server output entirely when server maps are off', async () => { + const d = deps({ [p('/app/.next/static')]: files('c'), [p('/app/.next/server')]: files('s') }); + await runPostBuild(context({}, { serverSourceMaps: false }), metadata, d); + expect(d.collect).not.toHaveBeenCalledWith(p('/app/.next/server')); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('says so, and uploads nothing for the browser, when it emitted no maps', async () => { + const ctx = context(); + const d = deps({ [p('/app/.next/server')]: files('s') }); + await runPostBuild(ctx, metadata, d); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('productionBrowserSourceMaps')); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('says how many bundles were left unstamped because they share a map', async () => { + const ctx = context(); + const d = deps({ + [p('/app/.next/static')]: { ...files('c'), shared: ['/d/x.js'] }, + [p('/app/.next/server')]: { ...files('s'), shared: ['/d/y.js', '/d/z.js'] }, + }); + await runPostBuild(ctx, metadata, d); + expect(ctx.say).toHaveBeenCalledWith( + expect.stringContaining('3 bundle(s) share one source map'), + ); + expect(d.upload).toHaveBeenCalledTimes(2); + }); + + it('only says the browser emitted no maps when maps were expected', async () => { + const off = context({}, { browserMaps: false }); + await runPostBuild(off, metadata, deps({ [p('/app/.next/server')]: files('s') })); + expect(off.say).not.toHaveBeenCalled(); + const expected = context({}, { browserMaps: true }); + await runPostBuild(expected, metadata, deps({ [p('/app/.next/server')]: files('s') })); + expect(expected.say).toHaveBeenCalledWith(expect.stringContaining('emitted no source maps')); + }); + + it('says the shared map itself stays (and is public) when it is in .next/static', async () => { + const ctx = context(); + const d = deps({ [p('/app/.next/static')]: { ...files('c'), shared: ['/d/x.js'] } }); + await runPostBuild(ctx, metadata, d); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('neither uploaded nor deleted')); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + }); + + it('registers the build from the server run when the browser had nothing to upload', async () => { + const d = deps({ [p('/app/.next/server')]: files('s') }); + await runPostBuild(context(), metadata, d); + const [resolved] = (d.upload as ReturnType).mock.calls[0] as [ + Record, + ]; + expect(resolved.registerBuild).toBe('release'); + }); + + it('stays quiet about shared maps when there are none', async () => { + const ctx = context(); + await runPostBuild(ctx, metadata, deps({ [p('/app/.next/static')]: files('c') })); + expect(ctx.say).not.toHaveBeenCalled(); + }); + + it('leaves an SRI build exactly as Next wrote it, and says why', async () => { + const ctx = context(); + const d = deps( + { [p('/app/.next/static')]: files('c'), [p('/app/.next/server')]: files('s') }, + true, + ); + await runPostBuild(ctx, metadata, d); + expect(d.exists).toHaveBeenCalledWith( + p('/app/.next/server/subresource-integrity-manifest.json'), + ); + expect(d.collect).not.toHaveBeenCalled(); + expect(d.upload).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('Subresource Integrity')); + }); + + it('leaves the build alone, without looking at the disk, when the config says SRI', async () => { + const ctx = context({}, { sri: true }); + const d = deps({ [p('/app/.next/static')]: files('c') }); + await runPostBuild(ctx, metadata, d); + expect(d.exists).not.toHaveBeenCalled(); + expect(d.upload).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + }); + + it('uses the real upload, collector and filesystem when none are injected', async () => { + const ctx = context(); + // Nothing exists under this directory: no SRI manifest, no files, so no upload, only the notice. + await expect( + runPostBuild(ctx, { projectDir: '/definitely/not/here', distDir: '.next' }), + ).resolves.toBeUndefined(); + expect(ctx.say).toHaveBeenCalledTimes(1); + }); +}); + +describe('runPostBuild: containment', () => { + const boom = (): never => { + throw new Error('disk on fire'); + }; + + it('a failure in collecting files never fails the build by default, and goes to onError', async () => { + const onError = vi.fn(); + const d = { ...deps({}), collect: vi.fn(async () => boom()) }; + await expect(runPostBuild(context({ onError }), metadata, d)).resolves.toBeUndefined(); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'disk on fire' })); + }); + + it('warns on the console when there is no onError', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const d = { ...deps({}), collect: vi.fn(async () => boom()) }; + await runPostBuild(context(), metadata, d); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('disk on fire')); + warn.mockRestore(); + }); + + it('a failure in the upload is contained the same way', async () => { + const onError = vi.fn(); + const d = { + ...deps({ [p('/app/.next/static')]: files('c') }), + upload: vi.fn(async () => boom()), + }; + await expect(runPostBuild(context({ onError }), metadata, d)).resolves.toBeUndefined(); + expect(onError).toHaveBeenCalledTimes(1); + }); + + it('rethrows under failOnError', async () => { + const d = { ...deps({}), collect: vi.fn(async () => boom()) }; + await expect(runPostBuild(context({ failOnError: true }), metadata, d)).rejects.toThrow( + 'disk on fire', + ); + }); + + it('an unreadable bundle on disk does not fail the build', async () => { + const dir = mkdtempSync(join(tmpdir(), 'bugsee-pb-')); + try { + mkdirSync(join(dir, '.next', 'static'), { recursive: true }); + const bundle = join(dir, '.next', 'static', 'a.js'); + writeFileSync(bundle, 'x'); + chmodSync(bundle, 0o000); + const onError = vi.fn(); + await expect( + runPostBuild(context({ onError }), { projectDir: dir, distDir: '.next' }), + ).resolves.toBeUndefined(); + // Root can read it anyway; everyone else must see the failure reported, not thrown. + expect(onError).toHaveBeenCalledTimes(process.getuid?.() === 0 ? 0 : 1); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + describe('the browser maps Bugsee forced on', () => { + const client = { + scripts: ['/d/c.js'], + maps: ['/d/c.js.map'], + stylesheetMaps: ['/d/c.css.map'], + }; + const setup = ( + upload: () => Promise, + overrides = {}, + extra: Partial = {}, + ) => { + const remove = vi.fn(async (_path: string): Promise => undefined); + const d = { + upload: vi.fn(upload) as never, + collect: vi.fn(async (dir: string) => (dir === p('/app/.next/static') ? client : none)), + exists: vi.fn(async () => false), + remove, + }; + return { d, remove, ctx: context(overrides, { forcedMaps: true, ...extra }) }; + }; + + it('are removed when the upload is not confirmed', async () => { + const { d, remove, ctx } = setup(async () => ({ uploaded: false })); + await runPostBuild(ctx, metadata, d); + expect(remove).toHaveBeenCalledWith('/d/c.js.map'); + expect(remove).toHaveBeenCalledWith('/d/c.css.map'); + }); + + it('are removed when the upload throws (reported, or rethrown under failOnError)', async () => { + const boom = async () => { + throw new Error('upload broke'); + }; + const lenient = setup(boom, { onError: vi.fn() }); + await runPostBuild(lenient.ctx, metadata, lenient.d); + expect(lenient.remove).toHaveBeenCalledTimes(2); + const strict = setup(boom, { failOnError: true }); + await expect(runPostBuild(strict.ctx, metadata, strict.d)).rejects.toThrow('upload broke'); + expect(strict.remove).toHaveBeenCalledTimes(2); + }); + + it('a confirmed upload still sweeps a forced map that was kept (unkeyed), and a failing SERVER collect cannot skip the sweep', async () => { + const confirmed = setup(async () => ({ uploaded: true })); + await runPostBuild(confirmed.ctx, metadata, confirmed.d); + expect(confirmed.remove).toHaveBeenCalledWith('/d/c.js.map'); + + const lenient = setup(async () => undefined, { onError: vi.fn() }); + lenient.d.collect = vi.fn(async (dir: string) => { + if (dir === p('/app/.next/server')) throw new Error('EACCES'); + return client; + }); + await runPostBuild(lenient.ctx, metadata, lenient.d); + expect(lenient.d.upload).not.toHaveBeenCalled(); + expect(lenient.remove).toHaveBeenCalledTimes(2); + }); + + it('stay on a dry run, with deleteMaps: false, or when the app asked for them', async () => { + for (const [upload, overrides, extra] of [ + [async () => undefined, { dryRun: true }, {}], + [async () => undefined, { deleteMaps: false }, {}], + [async () => undefined, {}, { forcedMaps: false }], + ] as const) { + const { d, remove, ctx } = setup(upload, overrides, extra); + await runPostBuild(ctx, metadata, d); + expect(remove).not.toHaveBeenCalled(); + } + }); + + it('a removal that fails with no onError is a console warning', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + const { d, ctx } = setup(async () => undefined); + d.remove = vi.fn(async () => { + throw new Error('EPERM'); + }); + await runPostBuild(ctx, metadata, d); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not remove')); + } finally { + warn.mockRestore(); + } + }); + + it('a removal that fails is reported and does not stop the others', async () => { + const onError = vi.fn(); + const { d, ctx } = setup(async () => undefined, { onError }); + d.remove = vi.fn(async (path: string) => { + if (path.endsWith('.js.map')) throw new Error('EPERM'); + }); + await runPostBuild(ctx, metadata, d); + expect(d.remove).toHaveBeenCalledTimes(2); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'EPERM' })); + }); + }); +}); diff --git a/packages/nextjs/src/config/post-build.ts b/packages/nextjs/src/config/post-build.ts new file mode 100644 index 000000000..aafe91d13 --- /dev/null +++ b/packages/nextjs/src/config/post-build.ts @@ -0,0 +1,142 @@ +// The Turbopack side of `withBugsee`. Turbopack has no plugin API, so the upload runs from Next's own +// `compiler.runAfterProductionCompile` hook: after the bundler finished writing `.next` and before Next generates +// the static pages. Everything the hook needs is on disk by then, so this stamps the debug-IDs into the written +// bundles (the real `bugsee-cli sourcemaps inject`, with the same verify-and-restore the post-emit path has), +// uploads the maps and deletes them per policy. +// +// What it cannot do is stamp a build that pins Subresource Integrity (`experimental.sri`): Turbopack writes the +// hashes BEFORE this hook runs (measured, Next 16.4.6: appending a byte to a chunk in the hook makes every +// `integrity` the page carries wrong), so stamping afterwards would ship a page whose scripts the browser +// refuses to run. That build is left exactly as Next wrote it, and the notice says why. +import { join, resolve } from 'node:path'; +import { + type PluginRunResult, + type ResolvedPluginOptions, + runPluginUpload, +} from '@bugsee/bundler-plugin-core'; +import { type BuildFiles, collectBuildFiles } from './build-files'; +import type { BugseeNextContext } from './context'; +import { isFile, SRI_MANIFEST, TURBOPACK_SRI_NOTICE } from './sri'; +import { removeFile } from './webpack-plugin'; + +/** What Next hands `compiler.runAfterProductionCompile`. */ +export interface PostBuildMetadata { + projectDir: string; + distDir: string; +} + +/** Seams for tests. */ +export interface PostBuildDeps { + upload?: typeof runPluginUpload; + collect?: (dir: string) => Promise; + exists?: (path: string) => Promise; + remove?: (path: string) => Promise; +} + +/** Stamp, upload and delete for a finished Turbopack build. Skips (and says why) when it cannot be done safely. */ +export async function runPostBuild( + context: BugseeNextContext, + metadata: PostBuildMetadata, + deps: PostBuildDeps = {}, +): Promise { + const { resolved } = context; + if (!resolved.enabled) { + return; + } + // Next rethrows whatever this hook throws and fails the build, so a telemetry step must not throw (an unreadable + // bundle, a full disk): it is reported, and only `failOnError` lets it stop the build. + try { + await postBuild(context, metadata, deps); + } catch (error) { + if (resolved.failOnError) { + throw error; + } + ( + resolved.onError ?? + ((e: unknown) => console.warn(`[bugsee] source-map upload skipped: ${String(e)}`)) + )(error); + } +} + +async function postBuild( + context: BugseeNextContext, + metadata: PostBuildMetadata, + deps: PostBuildDeps, +): Promise { + const { resolved } = context; + const upload = deps.upload ?? runPluginUpload; + const collect = deps.collect ?? collectBuildFiles; + const exists = deps.exists ?? isFile; + const distDir = resolve(metadata.projectDir, metadata.distDir); + + if (context.sri === true || (await exists(join(distDir, SRI_MANIFEST)))) { + context.say(TURBOPACK_SRI_NOTICE); + return; + } + + const client = await collect(join(distDir, 'static')); + // The browser maps Bugsee itself turned on are public in `.next/static`: whatever is still there once the run is + // over (an upload that failed or threw, a map that was never keyed so was kept) must not stay. Maps a confirmed + // upload already deleted are simply gone. Not on a dry run, and not with `deleteMaps: false` (an explicit "keep"). + const discardForced = async (): Promise => { + if (context.forcedMaps !== true || resolved.dryRun || resolved.deleteMaps === false) { + return; + } + const remove = deps.remove ?? removeFile; + for (const map of [...client.maps, ...client.stylesheetMaps]) { + try { + await remove(map); + } catch (error) { + ( + resolved.onError ?? + ((e: unknown) => + console.warn( + `[bugsee] could not remove the browser source maps Bugsee turned on: ${String(e)}`, + )) + )(error); + } + } + }; + // The same cleanup covers a failing server collect, the client upload and the server run. + try { + const server = context.serverSourceMaps ? await collect(join(distDir, 'server')) : undefined; + // Only when maps were EXPECTED: an app that turned them off (or a dry run, which never forces them on) chose that. + if (client.scripts.length === 0 && context.browserMaps !== false) { + context.say( + 'the browser build emitted no source maps, so nothing was uploaded for it. Set `productionBrowserSourceMaps: true` (withBugsee does this unless you set it to false).', + ); + } + + const shared = (client.shared?.length ?? 0) + (server?.shared?.length ?? 0); + if (shared > 0) { + context.say( + `${shared} bundle(s) share one source map with another bundle (Next 15's Turbopack does this for its runtime chunks), so they were left unstamped: a map carries one debug-ID. The shared map itself was neither uploaded nor deleted: if it is in \`.next/static\` it is publicly served (it holds Turbopack's runtime source, not yours).`, + ); + } + + const bundler = { isProduction: true, configuration: 'production' }; + const runFor = async ( + dir: string, + files: BuildFiles, + options: Partial, + ): Promise => { + if (files.scripts.length === 0) { + return undefined; + } + return upload({ ...resolved, ...options }, dir, { bundler, files }); + }; + // Browser first (it registers the build once); the server and edge output follows its own deletion policy. + const browser = await runFor(join(distDir, 'static'), client, {}); + if (server !== undefined) { + await runFor(join(distDir, 'server'), server, { + deleteMaps: context.deleteServerMaps, + // The build is registered once. When the browser run did not register it (it had nothing to upload because + // the app turned browser maps off, or its registration failed without `failOnError`), the server run + // registers it instead, so the build record is not lost. + ...(browser?.build?.registered === true ? { registerBuild: false } : {}), + }); + } + } finally { + await discardForced(); + } +} diff --git a/packages/nextjs/src/config/sri.test.ts b/packages/nextjs/src/config/sri.test.ts new file mode 100644 index 000000000..1080d92c4 --- /dev/null +++ b/packages/nextjs/src/config/sri.test.ts @@ -0,0 +1,53 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { isFile, SRI_MANIFEST, sriManifestNear } from './sri'; + +describe('sriManifestNear', () => { + const only = (path: string) => async (candidate: string) => candidate === path; + + it('finds the manifest from the client, server and edge output directories', async () => { + expect(await sriManifestNear('/o/.next', only(`/o/.next/${SRI_MANIFEST}`))).toBe(true); + const server = '/o/.next/server/subresource-integrity-manifest.json'; + expect(await sriManifestNear('/o/.next/server/chunks', only(server))).toBe(true); + expect(await sriManifestNear('/o/.next/server', only(server))).toBe(true); + }); + + it('does not mistake a root file of that name for Next\u2019s manifest', async () => { + const root = '/o/.next/subresource-integrity-manifest.json'; + expect(await sriManifestNear('/o/.next/chunks', only(root))).toBe(false); + expect( + await sriManifestNear( + '/o/.next/server/app/x', + only('/o/.next/server/app/subresource-integrity-manifest.json'), + ), + ).toBe(false); + expect(await sriManifestNear('/o/proj', only('/o/subresource-integrity-manifest.json'))).toBe( + false, + ); + }); + + it('a manifest-named file in a plain directory is not Next\u2019s', async () => { + expect( + await sriManifestNear('/o/proj', only('/o/proj/subresource-integrity-manifest.json')), + ).toBe(false); + }); + + it('finds nothing when there is none', async () => { + expect(await sriManifestNear('/o/.next', async () => false)).toBe(false); + }); + + it('looks on the real disk by default', async () => { + const dir = mkdtempSync(join(tmpdir(), 'bugsee-sri-')); + try { + expect(await sriManifestNear(dir)).toBe(false); + mkdirSync(join(dir, 'server')); + writeFileSync(join(dir, SRI_MANIFEST), '{}'); + expect(await sriManifestNear(dir)).toBe(true); + expect(await isFile(join(dir, 'server'))).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/nextjs/src/config/sri.ts b/packages/nextjs/src/config/sri.ts new file mode 100644 index 000000000..fc8583e84 --- /dev/null +++ b/packages/nextjs/src/config/sri.ts @@ -0,0 +1,76 @@ +// Subresource Integrity (`experimental.sri`) and what stamping may do about it, in one place. +// +// Turbopack hashes its output BEFORE the post-build hook runs, so stamping afterwards breaks the page (measured: +// every `integrity` wrong). webpack stamps inside the compilation, before anything hashes, so a stamp that took is +// safe; but a stamp that FAILED and falls back to stamping after emit is not (measured on Next 16.4.6 --webpack: +// the fallback rewrote real bundles and Chromium blocked every script, "Failed to find a valid digest"). The core's +// own SRI scan only sees HTML under the output directory, and Next keeps the integrity manifest elsewhere. +import { stat } from 'node:fs/promises'; +import { basename, dirname, join } from 'node:path'; + +/** Where Next records the integrity hashes it pinned, relative to the dist directory. */ +export const SRI_MANIFEST = join('server', 'subresource-integrity-manifest.json'); + +/** Whether a path is an existing file. */ +export async function isFile(path: string): Promise { + try { + return (await stat(path)).isFile(); + } catch { + return false; + } +} + +/** Whether an integrity manifest sits next to a webpack compilation's output (client `.next`, server `.next/server/chunks`, edge `.next/server`). */ +export async function sriManifestNear( + outDir: string, + exists: (path: string) => Promise = isFile, +): Promise { + const name = 'subresource-integrity-manifest.json'; + // The manifest lives in `/server`. A file of that name anywhere else is not Next's. + const candidates = [join(outDir, SRI_MANIFEST)]; + if (basename(outDir) === 'server') { + candidates.push(join(outDir, name)); + } + if (basename(dirname(outDir)) === 'server') { + candidates.push(join(dirname(outDir), name)); + } + for (const candidate of candidates) { + if (await exists(candidate)) { + return true; + } + } + return false; +} + +const PUBLIC_MAPS = + 'Browser source maps, if Next emits any (`productionBrowserSourceMaps`), stay in `.next/static` and are publicly served.'; + +/** Turbopack + SRI: not stampable, so nothing is uploaded. */ +export const TURBOPACK_SRI_NOTICE = `this build uses Subresource Integrity (\`experimental.sri\`). Turbopack hashes its output before the post-build hook runs, so stamping debug-IDs now would make the browser refuse the scripts. Source maps were NOT uploaded and the build was left unmodified. Build with \`next build --webpack\` to upload source maps for an SRI build. ${PUBLIC_MAPS}`; + +/** + * A webpack in-build stamp failed on an SRI build: the post-emit fallback would break the page, so nothing is + * stamped or uploaded. `mapsRemoved`: the browser maps Bugsee itself had turned on were deleted again, so they are + * not left public; otherwise (the app asked for them) they stay, and the notice says so. + */ +export const FALLBACK_SRI_NOTICE = ( + kind: string, + mapsRemoved: boolean, + options: { dryRun?: boolean; removalFailed?: boolean; retained?: boolean } = {}, +): string => + `the ${kind} build uses Subresource Integrity (\`experimental.sri\`) and its in-build debug-ID stamp did not apply (the reason is reported separately), so nothing was stamped or uploaded: stamping after emit would invalidate the pinned hashes and make the browser refuse the scripts.` + + (kind !== 'client' + ? '' + : mapsRemoved + ? ' The browser source maps Bugsee had turned on were removed from `.next/static`.' + : options.dryRun === true + ? ` Dry run: nothing was deleted. ${PUBLIC_MAPS}` + : options.retained === true + ? ` \`deleteMaps: false\` keeps the browser source maps Bugsee turned on. ${PUBLIC_MAPS}` + : options.removalFailed === true + ? ` The browser maps Bugsee turned on could not all be removed. ${PUBLIC_MAPS}` + : ` ${PUBLIC_MAPS}`); + +/** Turbopack on a Next without the post-build hook. */ +export const NO_HOOK_NOTICE = (version: string): string => + `Next ${version} builds with Turbopack but has no post-build hook to upload from; source maps were NOT uploaded. Upgrade to Next 15.4.0 or later, or build with webpack. Bugsee did not turn browser source maps on for this build.`; diff --git a/packages/nextjs/src/config/webpack-plugin.test.ts b/packages/nextjs/src/config/webpack-plugin.test.ts new file mode 100644 index 000000000..078338140 --- /dev/null +++ b/packages/nextjs/src/config/webpack-plugin.test.ts @@ -0,0 +1,1412 @@ +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { describe, expect, it, vi } from 'vitest'; + +import type { BugseeNextContext } from './context'; +import { + type CompilerLike, + createNextWebpackPlugin, + nextAssetStore, + pairRecorded, + removeFile, + type WebpackPluginDeps, +} from './webpack-plugin'; + +// Native absolute paths: the plugin resolves and joins with the host's path API (win32: `C:\out\.next`). +// Compilation asset names (`../app/page.js`) stay as the bundler reports them. +const p = (path: string): string => resolve(path); + +/** + * webpack-sources' RawSource, as far as it matters here: a STRING source is text webpack can still rewrite after + * the stamp (RealContentHashPlugin renames `[contenthash]` references in string sources only), a Buffer source is + * opaque to it. A stamp that hands a Buffer to `updateAsset` leaves lazy-chunk URLs pointing at files that were + * renamed afterwards (measured on real Next builds: ChunkLoadError), so the fake refuses one. + */ +class RawSource { + constructor(readonly content: string | Buffer) {} +} + +type Processor = () => Promise; + +/** A fake webpack compilation holding named assets, recording updates. */ +function fakeCompilation( + assets: Record, + related: Record = {}, +) { + const store = new Map( + Object.entries(assets).map(([k, v]) => [k, Buffer.from(v)]), + ); + let processor: Processor | undefined; + let stage: number | undefined; + return { + store, + run: () => (processor as Processor)(), + stage: () => stage, + compilation: { + hooks: { + processAssets: { + tapPromise: (o: { name: string; stage: number }, fn: Processor) => { + stage = o.stage; + processor = fn; + }, + }, + }, + getAssets: () => [...store.keys()].map((name) => ({ name })), + getAsset: (name: string) => + store.has(name) + ? { + source: { buffer: () => store.get(name) as Buffer }, + info: related[name] === undefined ? {} : { related: { sourceMap: related[name] } }, + } + : undefined, + updateAsset: vi.fn((name: string, source: unknown) => { + const { content } = source as RawSource; + if (typeof content !== 'string') { + throw new Error(`${name}: a Buffer source cannot be rewritten by RealContentHashPlugin`); + } + store.set(name, Buffer.from(content, 'utf8')); + }), + }, + }; +} + +type Compilation = ReturnType['compilation']; + +/** A fake compiler: records taps and lets the test fire them. */ +function fakeCompiler(options: { path?: string; api?: boolean } = {}) { + let onThis: ((c: Compilation) => void) | undefined; + let onEmit: ((c: Compilation) => Promise) | undefined; + const compiler = { + options: { output: { path: options.path ?? p('/out/.next/server/chunks') } }, + hooks: { + thisCompilation: { tap: (_n: string, fn: (c: Compilation) => void) => (onThis = fn) }, + afterEmit: { + tapPromise: (_n: string, fn: (c: Compilation) => Promise) => (onEmit = fn), + }, + }, + ...(options.api === false + ? {} + : { + webpack: { + Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: 100 }, + sources: { RawSource }, + }, + }), + } as unknown as CompilerLike; + return { + compiler, + startCompilation: (c: Compilation) => (onThis as (c: Compilation) => void)(c), + emit: (c: Compilation) => (onEmit as (c: Compilation) => Promise)(c), + hasThis: () => onThis !== undefined, + hasEmit: () => onEmit !== undefined, + }; +} + +function context( + overrides: Partial = {}, + extra = {}, +): BugseeNextContext { + return { + resolved: { + enabled: true, + appToken: 't', + deleteMaps: true, + registerBuild: 'release', + dryRun: false, + failOnError: false, + ...overrides, + } as BugseeNextContext['resolved'], + serverSourceMaps: true, + deleteServerMaps: false, + say: vi.fn(), + ...extra, + }; +} + +const deps = (over: WebpackPluginDeps = {}): WebpackPluginDeps => ({ + stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 1 })), + upload: vi.fn(async () => undefined), + exists: vi.fn(async () => true), + hasSriManifest: vi.fn(async () => false), + tail: vi.fn(async () => 'code();\n//# debugId=00000000-0000-5000-8000-000000000001\n'), + remove: vi.fn(async () => undefined), + ...over, +}); + +describe('nextAssetStore', () => { + it('stages `../` asset names under a stand-in directory and maps them back', () => { + const { compilation, store } = fakeCompilation({ + '../app/page.js': 'code', + '../app/page.js.map': 'map', + 'chunks/1.js': 'one', + '../../deep.js': 'deep', + }); + const assets = nextAssetStore(compilation, RawSource); + const names = assets.names(); + expect(names).toEqual([ + '__bugsee_up__/app/page.js', + '__bugsee_up__/app/page.js.map', + 'chunks/1.js', + '__bugsee_up__/__bugsee_up__/deep.js', + ]); + // Nothing staged escapes the staging directory. + expect(names.some((n) => n.startsWith('..') || n.includes('/../'))).toBe(false); + expect(assets.read('__bugsee_up__/app/page.js').toString()).toBe('code'); + expect(assets.read('chunks/1.js').toString()).toBe('one'); + assets.update('__bugsee_up__/app/page.js', Buffer.from('stamped')); + expect(store.get('../app/page.js')?.toString()).toBe('stamped'); + assets.update('chunks/1.js', Buffer.from('stamped-one')); + expect(store.get('chunks/1.js')?.toString()).toBe('stamped-one'); + }); + + it('reads an unknown asset as empty rather than throwing', () => { + const { compilation } = fakeCompilation({}); + expect(nextAssetStore(compilation, RawSource).read('nope.js')).toEqual(Buffer.alloc(0)); + }); +}); + +describe('createNextWebpackPlugin', () => { + it('does nothing when the plugin is not enabled', () => { + const fake = fakeCompiler(); + createNextWebpackPlugin(context({ enabled: false }), 'client', deps()).apply(fake.compiler); + expect(fake.hasThis()).toBe(false); + expect(fake.hasEmit()).toBe(false); + }); + + it('does nothing for server and edge when server maps are off, but still serves the client', () => { + const off = context({}, { serverSourceMaps: false }); + for (const kind of ['server', 'edge'] as const) { + const fake = fakeCompiler(); + createNextWebpackPlugin(off, kind, deps()).apply(fake.compiler); + expect(fake.hasEmit()).toBe(false); + } + const client = fakeCompiler(); + createNextWebpackPlugin(off, 'client', deps()).apply(client.compiler); + expect(client.hasEmit()).toBe(true); + }); + + it('stamps the compilation one stage after dev-tooling', async () => { + const d = deps(); + const fake = fakeCompiler(); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + fake.startCompilation(c.compilation); + expect(c.stage()).toBe(101); + await c.run(); + expect(d.stamp).toHaveBeenCalledTimes(1); + expect(d.stamp).toHaveBeenCalledWith(expect.any(Object), { dryRun: false }); + }); + + it('passes dryRun to the stamp', async () => { + const d = deps(); + const fake = fakeCompiler(); + createNextWebpackPlugin(context({ dryRun: true }), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + fake.startCompilation(c.compilation); + await c.run(); + expect(d.stamp).toHaveBeenCalledWith(expect.any(Object), { dryRun: true }); + }); + + it('uploads after emit with the stamped flag, over exactly this compilation’s own files', async () => { + const d = deps(); + const fake = fakeCompiler({ path: p('/out/.next/server/chunks') }); + createNextWebpackPlugin(context(), 'server', d).apply(fake.compiler); + const c = fakeCompilation({ + '../app/page.js': 'x', + '../app/page.js.map': 'm', + 'chunks/1.js': 'x', + 'chunks/1.js.map': 'm', + 'no-map.js': 'x', + }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(d.upload).toHaveBeenCalledTimes(1); + const [resolved, outDir, options] = (d.upload as ReturnType).mock.calls[0] as [ + Record, + string, + { bundler: unknown; preStamped: boolean; files: Record }, + ]; + expect(outDir).toBe(p('/out/.next/server/chunks')); + expect(options.preStamped).toBe(true); + expect(options.bundler).toEqual({ isProduction: true, configuration: 'server' }); + expect(options.files.scripts).toEqual([ + p('/out/.next/server/app/page.js'), + p('/out/.next/server/chunks/chunks/1.js'), + ]); + expect(options.files.maps).toEqual([ + p('/out/.next/server/app/page.js.map'), + p('/out/.next/server/chunks/chunks/1.js.map'), + ]); + // The server follows the server deletion policy and never registers the build. + expect(resolved).toMatchObject({ deleteMaps: false, registerBuild: false }); + }); + + it('gives the client the client policy: deleted maps, the build registered', async () => { + const d = deps(); + const fake = fakeCompiler({ path: p('/out/.next') }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js': 'x', 'static/a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + const [resolved] = (d.upload as ReturnType).mock.calls[0] as [ + Record, + ]; + expect(resolved).toMatchObject({ deleteMaps: true, registerBuild: 'release' }); + }); + + it('honours deleteServerMaps for server and edge', async () => { + const d = deps(); + const fake = fakeCompiler(); + createNextWebpackPlugin(context({}, { deleteServerMaps: true }), 'edge', d).apply( + fake.compiler, + ); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + const [resolved] = (d.upload as ReturnType).mock.calls[0] as [ + Record, + ]; + expect(resolved).toMatchObject({ deleteMaps: true }); + }); + + it('only counts assets that exist on disk', async () => { + const d = deps({ exists: vi.fn(async (p: string) => !p.endsWith('gone.js')) }); + const fake = fakeCompiler(); + createNextWebpackPlugin(context(), 'server', d).apply(fake.compiler); + const c = fakeCompilation({ + 'gone.js': 'x', + 'gone.js.map': 'm', + 'here.js': 'x', + 'here.js.map': 'm', + }); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { files: { scripts: string[] } }, + ]; + expect(options.files.scripts).toEqual([p('/out/.next/server/chunks/here.js')]); + }); + + it('falls back to the post-emit stamp (preStamped false) and warns when the in-build stamp fails', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const d = deps({ + stamp: vi.fn(async () => { + throw new Error('inject broke'); + }), + }); + const fake = fakeCompiler(); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('inject broke')); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { preStamped: boolean }, + ]; + expect(options.preStamped).toBe(false); + warn.mockRestore(); + }); + + it('reports a stamp failure through onError, once the build knows what follows', async () => { + const onError = vi.fn(); + const d = deps({ + stamp: vi.fn(async () => { + throw new Error('boom'); + }), + }); + const fake = fakeCompiler(); + createNextWebpackPlugin(context({ onError }), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + fake.startCompilation(c.compilation); + await c.run(); + expect(onError).not.toHaveBeenCalled(); + await fake.emit(c.compilation); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' })); + expect(onError).toHaveBeenCalledTimes(1); + }); + + it('rethrows a stamp failure under failOnError', async () => { + const d = deps({ + stamp: vi.fn(async () => { + throw new Error('strict'); + }), + }); + const fake = fakeCompiler(); + createNextWebpackPlugin(context({ failOnError: true }), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + fake.startCompilation(c.compilation); + await expect(c.run()).rejects.toThrow('strict'); + }); + + it('a stamp from the previous compilation cannot vouch for the next one (watch mode)', async () => { + const d = deps(); + const fake = fakeCompiler(); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const first = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(first.compilation); + await first.run(); + const second = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(second.compilation); + await fake.emit(second.compilation); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { preStamped: boolean }, + ]; + expect(options.preStamped).toBe(false); + }); + + it('skips the in-build stamp when the compiler exposes no webpack API, and still uploads', async () => { + const d = deps(); + const fake = fakeCompiler({ api: false }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + expect(fake.hasThis()).toBe(false); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + await fake.emit(c.compilation); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('works through Rspack’s API object', async () => { + const d = deps(); + const fake = fakeCompiler(); + const raw = fake.compiler as unknown as { webpack?: unknown; rspack?: unknown }; + raw.rspack = raw.webpack; + raw.webpack = undefined; + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + expect(fake.hasThis()).toBe(true); + }); + + it('says so when the browser build emitted no maps, and does not upload', async () => { + const d = deps(); + const ctx = context(); + const fake = fakeCompiler(); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + expect(d.upload).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('productionBrowserSourceMaps')); + }); + + it('is quiet when a server compilation emitted no maps', async () => { + const d = deps(); + const ctx = context(); + const fake = fakeCompiler(); + createNextWebpackPlugin(ctx, 'server', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + await fake.emit(c.compilation); + expect(d.upload).not.toHaveBeenCalled(); + expect(ctx.say).not.toHaveBeenCalled(); + }); + + it('does nothing after emit when the compiler has no output path', async () => { + const d = deps(); + const fake = fakeCompiler(); + (fake.compiler as unknown as { options: unknown }).options = {}; + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + await fake.emit(fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }).compilation); + expect(d.upload).not.toHaveBeenCalled(); + }); + + it('uses the real stamp, upload and filesystem when none are injected', async () => { + const fake = fakeCompiler({ path: '/definitely/not/here' }); + createNextWebpackPlugin(context({ enabled: true }), 'server').apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + // Nothing exists on disk, so the real `exists` filters everything out and nothing is uploaded. + await expect(fake.emit(c.compilation)).resolves.toBeUndefined(); + }); +}); + +describe('nextAssetStore: sources webpack can still rewrite', () => { + it('updates an asset with a STRING source, never a Buffer', () => { + const { compilation, store } = fakeCompilation({ 'static/a.js': 'old' }); + const assets = nextAssetStore(compilation, RawSource); + assets.names(); + assets.update('static/a.js', Buffer.from('new \u00e9 text', 'utf8')); + expect(compilation.updateAsset).toHaveBeenCalledTimes(1); + const [, source] = compilation.updateAsset.mock.calls[0] as [string, RawSource]; + expect(source.content).toBe('new \u00e9 text'); + expect(store.get('static/a.js')?.toString('utf8')).toBe('new \u00e9 text'); + }); + + it('refuses bytes that are not valid UTF-8 up front (a string source would corrupt them)', () => { + const { compilation } = fakeCompilation({ 'a.js': 'ok' }); + const assets = nextAssetStore(compilation, RawSource); + expect(() => assets.check?.('a.js', Buffer.from([0xff, 0xfe, 0x00, 0x80]))).toThrow( + /not valid UTF-8/, + ); + expect(() => assets.update('a.js', Buffer.from([0xff, 0xfe]))).toThrow(/not valid UTF-8/); + expect(compilation.updateAsset).not.toHaveBeenCalled(); + expect(() => assets.check?.('a.js', Buffer.from('fine \u00e9'))).not.toThrow(); + }); + + it('keeps a byte-order mark instead of dropping it', () => { + const { compilation, store } = fakeCompilation({ 'b.js': 'y' }); + const assets = nextAssetStore(compilation, RawSource); + assets.update('b.js', Buffer.from('\ufeffwith bom')); + expect(store.get('b.js')?.toString('utf8')).toBe('\ufeffwith bom'); + }); +}); + +describe('nextAssetStore: query-free names and moved maps', () => { + it('presents names without their ?query and maps them back to the real asset', () => { + const { compilation, store } = fakeCompilation({ + 'static/a.js?h1': 'a', + 'static/a.js.map?h1': 'm', + 'static/a#1.js': 'hash kept', + }); + const assets = nextAssetStore(compilation, RawSource); + expect(assets.names()).toEqual(['static/a.js', 'static/a.js.map', 'static/a#1.js']); + expect(assets.read('static/a.js').toString()).toBe('a'); + assets.update('static/a.js', Buffer.from('b')); + expect(store.get('static/a.js?h1')?.toString()).toBe('b'); + expect(assets.real('static/a.js')).toBe('static/a.js?h1'); + expect(assets.real('static/a#1.js')).toBe('static/a#1.js'); + expect(assets.real('unknown.js')).toBe('unknown.js'); + }); + + it('keeps the real names of two assets that would collide once cleaned', () => { + const { compilation } = fakeCompilation({ 'a.js?x': '1', 'a.js?y': '2' }); + expect(nextAssetStore(compilation, RawSource).names()).toEqual(['a.js?x', 'a.js?y']); + }); + + it('names the map the compilation recorded for a bundle, staged like the bundle', () => { + const { compilation } = fakeCompilation( + { + '../app/page.js': 'x', + '../maps/page.js.map?v': 'm', + 'a.js': 'x', + 'a.js.map': 'm', + 'b.js': 'x', + }, + { '../app/page.js': '../maps/page.js.map?v', 'a.js': ['a.js.map', 'other'] }, + ); + const assets = nextAssetStore(compilation, RawSource); + assets.names(); + expect(assets.mapOf?.('__bugsee_up__/app/page.js')).toBe('__bugsee_up__/maps/page.js.map'); + expect(assets.mapOf?.('a.js')).toBe('a.js.map'); + expect(assets.mapOf?.('b.js')).toBeUndefined(); + }); +}); + +describe('createNextWebpackPlugin: the new core contract', () => { + const asset = { + '../app/page.js': 'x', + '../app/page.js.map': 'm', + 'static/c.js': 'x', + 'static/c.js.map': 'm', + }; + + it('hands the on-disk re-check the FINAL names on disk: the bundles that carry a debug-ID now, with their maps', async () => { + // The stamp saw `chunks/1.[old].js`; webpack renamed it afterwards, so the check goes by what is on disk. + const d = deps({ + stamp: vi.fn(async () => ({ + stamped: ['chunks/1.OLDHASH.js'], + maps: { 'chunks/1.OLDHASH.js': 'chunks/1.OLDHASH.js.map' }, + bundles: 1, + })), + tail: vi.fn(async (path: string) => + path.endsWith('1.NEWHASH.js') + ? 'x\n//# debugId=00000000-0000-5000-8000-000000000009\n' + : 'plain', + ), + }); + const fake = fakeCompiler({ path: p('/out/.next/server/chunks') }); + createNextWebpackPlugin(context(), 'server', d).apply(fake.compiler); + const c = fakeCompilation({ + '../app/page.js': 'x', + '../app/page.js.map': 'm', + '1.NEWHASH.js': 'x', + '1.NEWHASH.js.map': 'm', + }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { stampedBundles: string[]; stampedMaps: Record }, + ]; + expect(options.stampedBundles).toEqual(['1.NEWHASH.js']); + expect(options.stampedMaps).toEqual({ '1.NEWHASH.js': '1.NEWHASH.js.map' }); + }); + + it('reports a stamped bundle that lost its debug-ID on the way (instead of silently dropping it from the check)', async () => { + const onError = vi.fn(); + const d = deps({ + stamp: vi.fn(async () => ({ stamped: ['a.js'], maps: { 'a.js': 'a.js.map' }, bundles: 1 })), + tail: vi.fn(async () => 'plain, no id'), + }); + const fake = fakeCompiler({ path: p('/o') }); + createNextWebpackPlugin(context({ onError }), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('1 of the 1 bundle(s)') }), + ); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('warns on the console for it without onError, and rethrows under failOnError', async () => { + const make = (ctx: BugseeNextContext) => { + const d = deps({ + stamp: vi.fn(async () => ({ stamped: ['a.js'], maps: { 'a.js': 'a.js.map' }, bundles: 1 })), + tail: vi.fn(async () => 'plain'), + }); + const fake = fakeCompiler({ path: p('/o') }); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + return { + run: async () => { + await c.run(); + await fake.emit(c.compilation); + }, + }; + }; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + await make(context()).run(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('do not carry their debug-ID')); + warn.mockRestore(); + await expect(make(context({ failOnError: true })).run()).rejects.toThrow('do not carry'); + }); + + it('pairs a recorded map elsewhere for the re-check', async () => { + const d = deps({ + stamp: vi.fn(async () => ({ + stamped: ['static/a.js'], + maps: { 'static/a.js': 'maps/a.js.map' }, + bundles: 1, + })), + }); + const fake = fakeCompiler({ path: p('/o') }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation( + { 'static/a.js': 'x', 'maps/a.js.map': 'm' }, + { 'static/a.js': 'maps/a.js.map' }, + ); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { stampedMaps: Record }, + ]; + expect(options.stampedMaps).toEqual({ 'static/a.js': 'maps/a.js.map' }); + }); + + it('does not claim a stamp that staged nothing while the build emitted scripts: says so, stamps after emit', async () => { + const d = deps({ stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })) }); + const ctx = context(); + const fake = fakeCompiler(); + createNextWebpackPlugin(ctx, 'server', d).apply(fake.compiler); + const c = fakeCompilation(asset); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('no debug-ID could be stamped')); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('server build')); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { preStamped: boolean; stampedBundles?: string[] }, + ]; + expect(options.preStamped).toBe(false); + expect(options.stampedBundles).toBeUndefined(); + }); + + it('a compilation with no scripts at all and nothing staged is not an alarm', async () => { + const d = deps({ stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })) }); + const ctx = context(); + const fake = fakeCompiler(); + createNextWebpackPlugin(ctx, 'server', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.json': '{}' }); + fake.startCompilation(c.compilation); + await c.run(); + expect(ctx.say).not.toHaveBeenCalled(); + }); + + it('stamps and uploads nothing when the stamp is refused because a map lies outside the output', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const refusal = Object.assign(new Error('map outside the output'), { unreachableMap: true }); + const d = deps({ + stamp: vi.fn(async () => { + throw refusal; + }), + }); + const fake = fakeCompiler(); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('half-stamp')); + expect(d.upload).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it('looks for an asset whose name carries a ?query at the query-free path on disk', async () => { + const seen: string[] = []; + const d = deps({ + exists: vi.fn(async (path: string) => { + seen.push(path); + return true; + }), + }); + const fake = fakeCompiler({ path: p('/out/.next') }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js?h': 'x', 'static/a.js.map?h': 'm' }); + await fake.emit(c.compilation); + expect(seen).toEqual([p('/out/.next/static/a.js'), p('/out/.next/static/a.js.map')]); + }); +}); + +describe('createNextWebpackPlugin: the post-emit fallback on an SRI build', () => { + const failing = () => + vi.fn(async () => { + throw new Error('inject broke'); + }); + const run = async (ctx: BugseeNextContext, d: WebpackPluginDeps) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const fake = fakeCompiler(); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + warn.mockRestore(); + }; + + it('does not stamp the written files when the app uses SRI (the config says so)', async () => { + const ctx = context({}, { sri: true }); + const d = deps({ stamp: failing() }); + await run(ctx, d); + expect(d.upload).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('Subresource Integrity')); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('client build')); + }); + + it('nor when Next\u2019s integrity manifest sits next to the output', async () => { + const ctx = context(); + const d = deps({ stamp: failing(), hasSriManifest: vi.fn(async () => true) }); + await run(ctx, d); + expect(d.upload).not.toHaveBeenCalled(); + expect(d.hasSriManifest).toHaveBeenCalledWith(p('/out/.next/server/chunks')); + }); + + it('still falls back without SRI', async () => { + const d = deps({ stamp: failing() }); + await run(context(), d); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('uploads a stamp that took, SRI or not (it ran before anything hashed)', async () => { + const d = deps(); + await run(context({}, { sri: true }), d); + expect(d.upload).toHaveBeenCalledTimes(1); + expect(d.hasSriManifest).not.toHaveBeenCalled(); + }); +}); + +describe('createNextWebpackPlugin: no public maps Bugsee asked for when nothing is uploaded', () => { + const failing = () => + vi.fn(async () => { + throw new Error('inject broke'); + }); + const assets = { + 'static/a.js': 'x', + 'static/a.js.map': 'm', + 'static/a.css': 'c', + 'static/a.css.map': 'cm', + }; + const run = async (kind: 'client' | 'server', ctx: BugseeNextContext, d: WebpackPluginDeps) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + const fake = fakeCompiler({ path: p('/out/.next') }); + createNextWebpackPlugin(ctx, kind, d).apply(fake.compiler); + const c = fakeCompilation(assets); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + return warn.mock.calls.map((call) => String(call[0])); + } finally { + warn.mockRestore(); // also when the hook rejects + } + }; + + it('deletes the browser maps it turned on when an SRI build\u2019s stamp failed (nothing is uploaded)', async () => { + const ctx = context({}, { sri: true, forcedMaps: true }); + const d = deps({ stamp: failing() }); + await run('client', ctx, d); + expect(d.upload).not.toHaveBeenCalled(); + expect(d.remove).toHaveBeenCalledTimes(2); + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/a.js.map')); + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/a.css.map')); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('were removed')); + }); + + it('keeps maps the app asked for, and says they are public', async () => { + const ctx = context({}, { sri: true }); + const d = deps({ stamp: failing() }); + await run('client', ctx, d); + expect(d.remove).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + }); + + it('never touches a server compilation\u2019s maps (not public)', async () => { + const ctx = context({}, { sri: true, forcedMaps: true }); + const d = deps({ stamp: failing() }); + await run('server', ctx, d); + expect(d.remove).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.not.stringContaining('browser source maps')); + }); + + it('deletes them when the stamp was abandoned (a map outside the output), too', async () => { + const d = deps({ + stamp: vi.fn(async () => { + throw Object.assign(new Error('outside'), { unreachableMap: true }); + }), + }); + await run('client', context({}, { forcedMaps: true }), d); + expect(d.upload).not.toHaveBeenCalled(); + expect(d.remove).toHaveBeenCalledTimes(2); + }); + + it('after a CONFIRMED upload it still removes a forced map that was kept on disk (an unkeyed, restored one)', async () => { + const d = deps({ upload: vi.fn(async () => ({ uploaded: true }) as never) }); + await run('client', context({}, { forcedMaps: true }), d); + expect(d.upload).toHaveBeenCalledTimes(1); + // the sweep tolerates what the upload already deleted (removeFile ignores ENOENT) and takes what is left + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/a.js.map')); + }); + + it('deletes them when the upload ran but was NOT confirmed (contained failure), and when it throws', async () => { + const unconfirmed = deps(); // resolves undefined: nothing confirmed + await run('client', context({}, { forcedMaps: true }), unconfirmed); + expect(unconfirmed.remove).toHaveBeenCalledWith(p('/out/.next/static/a.js.map')); + expect(unconfirmed.remove).toHaveBeenCalledWith(p('/out/.next/static/a.css.map')); + + const notUploaded = deps({ upload: vi.fn(async () => ({ uploaded: false }) as never) }); + await run('client', context({}, { forcedMaps: true }), notUploaded); + expect(notUploaded.remove).toHaveBeenCalledTimes(2); + + const throwing = deps({ + upload: vi.fn(async () => { + throw new Error('upload broke'); + }), + }); + await expect(run('client', context({}, { forcedMaps: true }), throwing)).rejects.toThrow( + 'upload broke', + ); + expect(throwing.remove).toHaveBeenCalledTimes(2); + }); + + it('keeps them with deleteMaps: false, on a dry run, when the app asked for them, and on a server compilation', async () => { + for (const [overrides, extra, kind] of [ + [{ deleteMaps: false }, { forcedMaps: true }, 'client'], + [{ dryRun: true }, { forcedMaps: true }, 'client'], + [{}, {}, 'client'], + [{}, { forcedMaps: true }, 'server'], + ] as const) { + const d = deps(); + await run(kind, context({ ...overrides }, { ...extra }), d); + expect(d.upload).toHaveBeenCalledTimes(1); + expect(d.remove).not.toHaveBeenCalled(); + } + }); + + it('an SRI refusal removes forced maps whose script a later stage dropped, too', async () => { + const ctx = context({}, { sri: true, forcedMaps: true }); + const d = deps({ stamp: failing() }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + const fake = fakeCompiler({ path: p('/out/.next') }); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js': 'x', 'static/orphan.js.map': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + } finally { + warn.mockRestore(); + } + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/orphan.js.map')); + }); + + it('strict: an SRI build whose scripts could not be staged fails (nothing was rewritten or uploaded)', async () => { + const ctx = context({ failOnError: true }, { sri: true }); + const d = deps({ stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })) }); + await expect(run('client', ctx, d)).rejects.toThrow(/could be staged/); + expect(d.upload).not.toHaveBeenCalled(); + // not strict: reported, returns + const lenient = deps({ stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })) }); + await expect(run('client', context({}, { sri: true }), lenient)).resolves.toBeDefined(); + }); + + it('strict: a stamped bundle whose map vanished before the upload is a failure, otherwise reported', async () => { + const stampedOne = () => + vi.fn(async () => ({ stamped: [], maps: { 'static/a.js': 'static/a.js.map' }, bundles: 1 })); + const emitOnlyScript = async (ctx: BugseeNextContext, d: WebpackPluginDeps) => { + const fake = fakeCompiler({ path: p('/out/.next') }); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js': 'x' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + }; + await expect( + emitOnlyScript(context({ failOnError: true }), deps({ stamp: stampedOne() })), + ).rejects.toThrow(/no map left on disk/); + const onError = vi.fn(); + await emitOnlyScript(context({ onError }), deps({ stamp: stampedOne() })); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('no map left') }), + ); + }); + + it('a lost pair with no onError is a console warning; an upload failure wins over a failing cleanup', async () => { + const lostPair = deps({ + stamp: vi.fn(async () => ({ + stamped: [], + maps: { 'static/a.js': 'static/a.js.map' }, + bundles: 1, + })), + }); + const fake = fakeCompiler({ path: p('/out/.next') }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + createNextWebpackPlugin(context(), 'client', lostPair).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js': 'x' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('no map left on disk')); + } finally { + warn.mockRestore(); + } + const both = deps({ + upload: vi.fn(async () => { + throw new Error('upload broke'); + }), + remove: vi.fn(async () => { + throw new Error('EPERM'); + }), + }); + await expect( + run('client', context({ failOnError: true }, { forcedMaps: true }), both), + ).rejects.toThrow('upload broke'); + }); + + it('an existence check that fails for a reason other than "not there" is reported (strict: thrown), not read as "no maps"', async () => { + const eio = () => + vi.fn(async () => { + throw Object.assign(new Error('EIO'), { code: 'EIO' }); + }); + await expect( + run('client', context({ failOnError: true }), deps({ exists: eio() })), + ).rejects.toThrow('EIO'); + const onError = vi.fn(); + await run('client', context({ onError }), deps({ exists: eio() })); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'EIO' })); + const warned = await run('client', context(), deps({ exists: eio() })); + expect(warned.join('\n')).toContain('could not look for an emitted asset'); + }); + + it('prints ONE accurate message on an SRI build, never "falling back"', async () => { + const onError = vi.fn(); + const ctx = context({ onError }, { sri: true, forcedMaps: true }); + const warned = await run('client', ctx, deps({ stamp: failing() })); + expect(warned.join('\n')).not.toMatch(/falling back/); + expect(ctx.say).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'inject broke' })); + }); + + it('the CAUSE is never hidden by `silent`: with no onError it is a console warning, not a notice', async () => { + const ctx = context({}, { sri: true, forcedMaps: true }); + const warned = await run('client', ctx, deps({ stamp: failing() })); + expect(warned).toHaveLength(1); + expect(warned[0]).toMatch(/in-build debug-ID stamping did not apply: Error: inject broke/); + // The notice does not carry the cause (so a silenced notice cannot be the only place it lives). + expect(vi.mocked(ctx.say).mock.calls[0]?.[0]).not.toContain('inject broke'); + }); + + it('a maps-removal failure never fails the build: reported through onError, then the notice says so', async () => { + const onError = vi.fn(); + const ctx = context({ onError }, { sri: true, forcedMaps: true }); + const d = deps({ + stamp: failing(), + remove: vi.fn(async () => { + throw Object.assign(new Error('EPERM'), { code: 'EPERM' }); + }), + }); + await expect(run('client', ctx, d)).resolves.toBeDefined(); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'EPERM' })); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('could not all be removed')); + }); + + it('warns on the console when removal fails and there is no onError', async () => { + const ctx = context({}, { sri: true, forcedMaps: true }); + const d = deps({ + stamp: failing(), + remove: vi.fn(async () => { + throw new Error('EPERM'); + }), + }); + const warned = await run('client', ctx, d); + expect(warned.some((w) => w.includes('could not remove the browser source maps'))).toBe(true); + }); + + it('rethrows a removal failure under failOnError (reachable when nothing could be staged on an SRI build)', async () => { + const ctx = context({ failOnError: true }, { sri: true, forcedMaps: true }); + const d = deps({ + stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })), + remove: vi.fn(async () => { + throw new Error('EPERM'); + }), + }); + await expect(run('client', ctx, d)).rejects.toThrow('EPERM'); + }); + + it('deletes nothing on a dry run, and says so', async () => { + const ctx = context({ dryRun: true }, { sri: true, forcedMaps: true }); + const d = deps({ stamp: failing() }); + await run('client', ctx, d); + expect(d.remove).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('Dry run: nothing was deleted')); + }); + + it('an abandoned stamp deletes nothing on a dry run either', async () => { + const d = deps({ + stamp: vi.fn(async () => { + throw Object.assign(new Error('outside'), { unreachableMap: true }); + }), + }); + await run('client', context({ dryRun: true }, { forcedMaps: true }), d); + expect(d.remove).not.toHaveBeenCalled(); + }); + + it('an SRI build where nothing could be staged (no thrown cause) still reports through onError / console.warn', async () => { + const nothing = () => vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })); + const onError = vi.fn(); + await run( + 'client', + context({ onError }, { sri: true, forcedMaps: true }), + deps({ stamp: nothing() }), + ); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('could be staged') }), + ); + const warned = await run( + 'client', + context({}, { sri: true, forcedMaps: true }), + deps({ stamp: nothing() }), + ); + expect(warned.some((w) => w.includes('could be staged'))).toBe(true); + }); + + it('tries every removal, then reports each failure (partial removal is reported, not hidden)', async () => { + const onError = vi.fn(); + const remove = vi.fn(async (path: string) => { + if (path.endsWith('a.js.map')) throw new Error(`EPERM ${path}`); + }); + const ctx = context({ onError }, { sri: true, forcedMaps: true }); + await run('client', ctx, deps({ stamp: failing(), remove })); + expect(remove).toHaveBeenCalledTimes(2); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('a.js.map') }), + ); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('could not all be removed')); + }); + + it('a throwing onError aborts the hook, as the core\u2019s own does', async () => { + const onError = vi.fn(() => { + throw new Error('host logger down'); + }); + const ctx = context({ onError }, { sri: true, forcedMaps: true }); + await expect( + run( + 'client', + ctx, + deps({ + stamp: failing(), + remove: vi.fn(async () => { + throw new Error('EPERM'); + }), + }), + ), + ).rejects.toThrow('host logger down'); + }); + + it('only claims a dry run deleted nothing when something would have been deleted', async () => { + const forced = context({ dryRun: true }, { sri: true, forcedMaps: true }); + await run('client', forced, deps({ stamp: failing() })); + expect(forced.say).toHaveBeenCalledWith( + expect.stringContaining('Dry run: nothing was deleted'), + ); + const own = context({ dryRun: true }, { sri: true }); + await run('client', own, deps({ stamp: failing() })); + expect(own.say).toHaveBeenCalledWith(expect.not.stringContaining('Dry run')); + expect(own.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + }); + + it('an abandoned stamp on a dry run says the forced maps remain public', async () => { + const abandon = () => + vi.fn(async () => { + throw Object.assign(new Error('outside'), { unreachableMap: true }); + }); + const forced = context({ dryRun: true }, { forcedMaps: true }); + await run('client', forced, deps({ stamp: abandon() })); + expect(forced.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + const own = context({ dryRun: true }); + await run('client', own, deps({ stamp: abandon() })); + expect(own.say).not.toHaveBeenCalled(); + }); + + it('deleteMaps: false keeps the forced browser maps when stamping is refused or abandoned, and the notice says so', async () => { + const keep = context({ deleteMaps: false }, { sri: true, forcedMaps: true }); + const d = deps({ stamp: failing() }); + await run('client', keep, d); + expect(d.remove).not.toHaveBeenCalled(); + expect(keep.say).toHaveBeenCalledWith(expect.stringContaining('`deleteMaps: false`')); + expect(keep.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + expect(keep.say).toHaveBeenCalledWith(expect.not.stringContaining('were removed')); + + // maps the app asked for are not "the ones Bugsee turned on": the notice does not claim them + const own = context({ deleteMaps: false }, { sri: true }); + await run('client', own, deps({ stamp: failing() })); + expect(own.say).toHaveBeenCalledWith(expect.not.stringContaining('`deleteMaps: false`')); + + const abandoned = deps({ + stamp: vi.fn(async () => { + throw Object.assign(new Error('outside'), { unreachableMap: true }); + }), + }); + const keepAbandoned = context({ deleteMaps: false }, { forcedMaps: true }); + await run('client', keepAbandoned, abandoned); + expect(abandoned.remove).not.toHaveBeenCalled(); + expect(keepAbandoned.say).toHaveBeenCalledWith(expect.stringContaining('`deleteMaps: false`')); + }); + + it('sweeps the forced browser maps when a later stage dropped the last client script but left its map', async () => { + const orphanRun = async (ctx: BugseeNextContext, d: WebpackPluginDeps) => { + const fake = fakeCompiler({ path: p('/out/.next') }); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js.map': 'm', 'static/a.css.map': 'cm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + }; + const d = deps(); + await orphanRun(context({}, { forcedMaps: true }), d); + expect(d.upload).not.toHaveBeenCalled(); + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/a.js.map')); + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/a.css.map')); + + // not on a dry run, not with deleteMaps: false, not for maps the app asked for, not for a server compilation + for (const [resolved, extra] of [ + [{ dryRun: true }, { forcedMaps: true }], + [{ deleteMaps: false }, { forcedMaps: true }], + [{}, {}], + ] as const) { + const kept = deps(); + await orphanRun(context(resolved, extra), kept); + expect(kept.remove).not.toHaveBeenCalled(); + } + }); + + it('on a build without SRI the fallback message is printed, once', async () => { + const warned = await run('client', context(), deps({ stamp: failing() })); + expect(warned.filter((w) => w.includes('falling back to stamping after emit'))).toHaveLength(1); + }); + + it('the default remover tolerates a file that is already gone and reports other errors', async () => { + const { mkdtempSync, rmSync, writeFileSync, existsSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + const dir = mkdtempSync(join(tmpdir(), 'bugsee-rm-')); + try { + writeFileSync(join(dir, 'a.js'), 'x'); + writeFileSync(join(dir, 'a.js.map'), 'm'); + const ctx = context({}, { sri: true, forcedMaps: true }); + const fake = fakeCompiler({ path: dir }); + createNextWebpackPlugin(ctx, 'client', { + ...deps({ stamp: failing() }), + remove: undefined, + exists: undefined, + }).apply(fake.compiler); + const c = fakeCompilation({ + 'a.js': 'x', + 'a.js.map': 'm', + 'gone.js': 'x', + 'gone.js.map': 'm', + }); + fake.startCompilation(c.compilation); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + await c.run(); + await fake.emit(c.compilation); + warn.mockRestore(); + expect(existsSync(join(dir, 'a.js.map'))).toBe(false); + expect(existsSync(join(dir, 'a.js'))).toBe(true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe('removeFile', () => { + it('deletes a file, ignores one that is gone, and reports anything else', async () => { + const { mkdirSync, mkdtempSync, rmSync, writeFileSync, existsSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + const dir = mkdtempSync(join(tmpdir(), 'bugsee-rmf-')); + try { + writeFileSync(join(dir, 'a.map'), 'm'); + await removeFile(join(dir, 'a.map')); + expect(existsSync(join(dir, 'a.map'))).toBe(false); + await expect(removeFile(join(dir, 'gone.map'))).resolves.toBeUndefined(); + mkdirSync(join(dir, 'd')); + await expect(removeFile(join(dir, 'd'))).rejects.toThrow(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe('pairRecorded', () => { + const emitted = (names: string[]) => names.map((n) => p(`/o/${n}`)); + + it('pairs a script with the map the compilation recorded for it, wherever that map is', () => { + const { compilation } = fakeCompilation( + { 'static/a.js': 'x', 'maps/a.js.map': 'm', 'static/b.js': 'x', 'static/b.js.map': 'm' }, + { 'static/a.js': 'maps/a.js.map' }, + ); + const files = pairRecorded( + compilation, + p('/o'), + emitted(['static/a.js', 'maps/a.js.map', 'static/b.js', 'static/b.js.map']), + ); + expect(files.scripts).toEqual([p('/o/static/a.js'), p('/o/static/b.js')]); + expect(files.maps).toEqual([p('/o/maps/a.js.map'), p('/o/static/b.js.map')]); + }); + + it('the map the compilation recorded wins over a same-named sibling a later stage emitted', () => { + const { compilation } = fakeCompilation( + { 'a.js': 'x', 'a.js.map': 'unrelated', 'maps/original.map': 'm' }, + { 'a.js': 'maps/original.map' }, + ); + const files = pairRecorded( + compilation, + p('/o'), + emitted(['a.js', 'a.js.map', 'maps/original.map']), + ); + expect(files.pairs?.[p('/o/a.js')]).toBe(p('/o/maps/original.map')); + }); + + it('accepts a recorded list and a ?query on the recorded map', () => { + const { compilation } = fakeCompilation( + { 'a.js': 'x', 'm/a.js.map?v': 'm' }, + { 'a.js': ['m/a.js.map?v', 'other'] }, + ); + expect(pairRecorded(compilation, p('/o'), emitted(['a.js', 'm/a.js.map'])).maps).toEqual([ + p('/o/m/a.js.map'), + ]); + }); + + it('ignores a recorded map that was not emitted, and scripts with none recorded', () => { + const { compilation } = fakeCompilation( + { 'a.js': 'x', 'b.js': 'x', 'c.txt': 'x' }, + { 'a.js': 'gone.js.map' }, + ); + const files = pairRecorded(compilation, p('/o'), emitted(['a.js', 'b.js', 'c.txt'])); + expect(files.scripts).toEqual([]); + expect(files.maps).toEqual([]); + }); + + it('does not pair a script that was not itself emitted', () => { + const { compilation } = fakeCompilation( + { 'a.js': 'x', 'm/a.js.map': 'm' }, + { 'a.js': 'm/a.js.map' }, + ); + expect(pairRecorded(compilation, p('/o'), emitted(['m/a.js.map'])).scripts).toEqual([]); + }); +}); + +describe('createNextWebpackPlugin: queries, recorded maps, registration', () => { + it('goes by the query-free names on disk (webpack drops ?query when it writes the file)', async () => { + const d = deps({ + stamp: vi.fn(async () => ({ + stamped: ['static/a.js'], + maps: { 'static/a.js': 'static/a.js.map' }, + bundles: 1, + })), + }); + const fake = fakeCompiler({ path: p('/o') }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js?v=1': 'x', 'static/a.js.map?v=1': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { stampedBundles: string[]; stampedMaps: Record }, + ]; + expect(options.stampedBundles).toEqual(['static/a.js']); + expect(options.stampedMaps).toEqual({ 'static/a.js': 'static/a.js.map' }); + }); + + it('uploads maps a script\u2019s recorded relationship names even when none sits beside it', async () => { + const d = deps(); + const fake = fakeCompiler({ path: p('/o') }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation( + { 'static/a.js': 'x', 'maps/a.js.map': 'm' }, + { 'static/a.js': 'maps/a.js.map' }, + ); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('the server compilation registers the build only when the app writes no browser maps', async () => { + const reg = async (browserMaps: boolean | undefined, kind: 'client' | 'server' | 'edge') => { + const d = deps(); + const fake = fakeCompiler({ path: p('/o') }); + createNextWebpackPlugin( + context({}, { ...(browserMaps === undefined ? {} : { browserMaps }) }), + kind, + d, + ).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + return (d.upload as ReturnType).mock.calls[0]?.[0] as { + registerBuild: unknown; + }; + }; + expect((await reg(false, 'server')).registerBuild).toBe('release'); + expect((await reg(true, 'server')).registerBuild).toBe(false); + expect((await reg(undefined, 'server')).registerBuild).toBe(false); + expect((await reg(false, 'edge')).registerBuild).toBe(false); + expect((await reg(false, 'client')).registerBuild).toBe('release'); + }); +}); + +describe('createNextWebpackPlugin: the on-disk scan and the no-maps notice', () => { + const stampedDeps = (over: WebpackPluginDeps = {}) => + deps({ + stamp: vi.fn(async () => ({ stamped: ['a.js'], maps: { 'a.js': 'a.js.map' }, bundles: 1 })), + ...over, + }); + const emitWith = async ( + ctx: BugseeNextContext, + d: WebpackPluginDeps, + assets: Record, + ) => { + const fake = fakeCompiler({ path: p('/o') }); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation(assets); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + }; + + it('an unreadable bundle never fails the build: reported through onError, not counted as lost', async () => { + const onError = vi.fn(); + const d = stampedDeps({ + tail: vi.fn(async () => { + throw Object.assign(new Error('EBUSY'), { code: 'EBUSY' }); + }), + }); + await expect( + emitWith(context({ onError }), d, { 'a.js': 'x', 'a.js.map': 'm' }), + ).resolves.toBeUndefined(); + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'EBUSY' })); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('warns on the console for it without onError', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const d = stampedDeps({ + tail: vi.fn(async () => { + throw new Error('EMFILE'); + }), + }); + await emitWith(context(), d, { 'a.js': 'x', 'a.js.map': 'm' }); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('could not read a stamped client bundle'), + ); + warn.mockRestore(); + }); + + it('rethrows an unreadable bundle under failOnError', async () => { + const d = stampedDeps({ + tail: vi.fn(async () => { + throw new Error('EBUSY'); + }), + }); + await expect( + emitWith(context({ failOnError: true }), d, { 'a.js': 'x', 'a.js.map': 'm' }), + ).rejects.toThrow('EBUSY'); + }); + + it('says nothing about missing browser maps when the app chose that (or on a dry run)', async () => { + const off = context({}, { browserMaps: false }); + await emitWith(off, deps(), { 'a.js': 'x' }); + expect(off.say).not.toHaveBeenCalled(); + const expected = context({}, { browserMaps: true }); + await emitWith(expected, deps(), { 'a.js': 'x' }); + expect(expected.say).toHaveBeenCalledWith(expect.stringContaining('emitted no source maps')); + }); +}); + +describe('the real existence check', () => { + it('"not there" (ENOENT, ENOTDIR) is absent; an unreadable parent (EACCES) is reported', async () => { + const dir = mkdtempSync(join(tmpdir(), 'bugsee-next-exists-')); + try { + writeFileSync(join(dir, 'file'), 'x'); + mkdirSync(join(dir, 'locked')); + writeFileSync(join(dir, 'locked', 'a.js'), 'x'); + const emit = async (name: string, onError: (e: unknown) => void) => { + const fake = fakeCompiler({ path: dir }); + const ctx = context({ onError }); + createNextWebpackPlugin(ctx, 'client', { + stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })), + upload: vi.fn(async () => undefined), + hasSriManifest: vi.fn(async () => false), + }).apply(fake.compiler); + const c = fakeCompilation({ [name]: 'x' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + }; + const quiet = vi.fn(); + await emit('missing.js', quiet); // ENOENT + await emit('file/inside.js', quiet); // ENOTDIR + expect(quiet).not.toHaveBeenCalled(); + if (process.getuid?.() !== 0 && process.platform !== 'win32') { + chmodSync(join(dir, 'locked'), 0o000); + const loud = vi.fn(); + try { + await emit('locked/a.js', loud); + } finally { + chmodSync(join(dir, 'locked'), 0o755); + } + expect(loud).toHaveBeenCalledWith(expect.objectContaining({ code: 'EACCES' })); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/nextjs/src/config/webpack-plugin.ts b/packages/nextjs/src/config/webpack-plugin.ts new file mode 100644 index 000000000..263bd35fc --- /dev/null +++ b/packages/nextjs/src/config/webpack-plugin.ts @@ -0,0 +1,529 @@ +// The webpack side of `withBugsee` (`next build --webpack`, and the default for Next <= 15). One plugin instance per +// Next compilation (client, server, edge), each doing two things for ITS OWN assets only: +// +// 1. stamp the debug-IDs inside the compilation, before anything hashes the output (Subresource Integrity), and +// 2. after emit, upload the maps of exactly the files this compilation wrote, then delete them per policy. +// +// It deliberately does not reuse the generic webpack plugin of `@bugsee/webpack-plugin`: measured against a real +// `next build`, that plugin assumes one compilation per output directory. Next's server compilation emits to +// `.next/server/chunks` with asset names like `../app/page.js` (outside its own output path), so the generic +// plugin neither stamped them (an asset name may not escape the staging directory) nor found their maps, and its +// directory-wide upload of `.next` swept up the server compilation's half-written files. +import { stat, unlink } from 'node:fs/promises'; +import { relative, resolve } from 'node:path'; +import { + type AssetStore, + cutAtQuery, + type ResolvedPluginOptions, + runPluginUpload, + stampAssets, +} from '@bugsee/bundler-plugin-core'; +import { type BuildFiles, partitionBuildFiles, readTail } from './build-files'; +import type { BugseeNextContext } from './context'; +import { FALLBACK_SRI_NOTICE, sriManifestNear } from './sri'; + +/** Which of Next's three webpack compilations a plugin instance serves. */ +export type NextCompilationKind = 'client' | 'server' | 'edge'; + +/** The slice of a webpack compilation the stamp and the file list read and write. */ +interface CompilationLike { + hooks: { + processAssets: { + tapPromise: (options: { name: string; stage: number }, fn: () => Promise) => void; + }; + }; + getAssets(): ReadonlyArray<{ name: string }>; + getAsset(name: string): + | { + source: { buffer(): Buffer }; + /** `related.sourceMap` is how SourceMapDevToolPlugin records which asset is a bundle's map. */ + info?: { related?: { sourceMap?: string | string[] | null } }; + } + | undefined; + updateAsset(name: string, source: unknown): void; +} + +/** The slice of a webpack compiler this taps. Read from the compiler, never imported (see core's plugin.ts). */ +export interface CompilerLike { + options: { output?: { path?: string } }; + hooks: { + thisCompilation: { tap: (name: string, fn: (compilation: CompilationLike) => void) => void }; + afterEmit: { + tapPromise: (name: string, fn: (compilation: CompilationLike) => Promise) => void; + }; + }; + webpack?: WebpackApi; + rspack?: WebpackApi; +} + +interface WebpackApi { + Compilation?: { PROCESS_ASSETS_STAGE_DEV_TOOLING?: number }; + sources?: { RawSource?: new (content: string) => unknown }; +} + +/** Seams for tests. */ +export interface WebpackPluginDeps { + stamp?: typeof stampAssets; + upload?: typeof runPluginUpload; + /** Whether a path exists on disk (default `fs.stat`). */ + exists?: (path: string) => Promise; + /** Whether Next's integrity manifest sits next to this output (default: looks on disk). */ + hasSriManifest?: (outDir: string) => Promise; + /** The end of a file as text (default: reads the last 16 KiB). */ + tail?: (path: string) => Promise; + /** Delete a file (default `fs.unlink`; a file that is already gone is fine). */ + remove?: (path: string) => Promise; +} + +const PLUGIN = 'bugsee-next'; +/** The debug-ID comment `bugsee-cli sourcemaps inject` appends to a stamped bundle. */ +const DEBUG_ID = /\/\/# debugId=[0-9a-f-]{36}/; +/** A script asset, query and upper-case extension included (what the core's own plugin counts). */ +const SCRIPT_ASSET = /\.[cm]?js(\?|$)/i; + +/** What the in-build stamp of one compilation established. */ +interface InBuildStamp { + preStamped: boolean; + /** The bundles it stamped and their maps, by real asset name, for the on-disk re-check. */ + /** How many stamped bundles have a map: what must still carry its debug-ID on disk. */ + stampedWithMaps?: number; + /** Why the in-build stamp failed, reported once the build knows what happens next (fallback or not). */ + failure?: unknown; + /** The stamp was refused in a way that makes stamping after emit unsafe too. */ + abandoned?: boolean; +} +/** Stands in for each leading `../` of an asset name inside the staging directory. */ +const UP = '__bugsee_up__'; + +/** Delete a file; one that is already gone is not an error. */ +export async function removeFile(path: string): Promise { + try { + await unlink(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + throw error; + } + } +} + +async function fileExists(path: string): Promise { + try { + return (await stat(path)).isFile(); + } catch (error) { + // Only "not there" means absent: an EIO / EACCES is a failure to look, which must not read as "no maps". + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT' || code === 'ENOTDIR') { + return false; + } + throw error; + } +} + +/** + * An asset name without its `?query`: webpack drops `?...` when it writes a file and keeps `#` (measured on real + * builds by the core's own asset store, which this follows). + */ +const withoutQuery = cutAtQuery; + +/** Strict, BOM-preserving UTF-8: a lenient decode would silently corrupt an asset. */ +const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + +/** The text of an asset's bytes, or a refusal: bytes that are not valid UTF-8 never become a source. */ +function asText(name: string, content: Buffer): string { + try { + return utf8.decode(content); + } catch { + throw new Error(`${name} is not valid UTF-8, so it cannot be stamped as a text source`); + } +} + +/** A compilation's asset table as the core's {@link AssetStore}, plus the way back to real asset names. */ +export interface NextAssetStore extends AssetStore { + /** The real asset name behind a name this store presented. */ + real(name: string): string; +} + +/** + * A compilation's assets as an {@link AssetStore}. Names are presented query-free, and a name that starts with + * `../` (Next's server output sits one level above the compilation's output path) is staged under a stand-in + * directory, consistently for a bundle and its map, so their relative layout survives and nothing can escape the + * staging directory. Two assets that would collide once cleaned keep their real names. + */ +export function nextAssetStore( + compilation: CompilationLike, + RawSource: new (content: string) => unknown, +): NextAssetStore { + const up = (name: string): string => + name.replace(/^(?:\.\.\/)+/, (dots) => `${UP}/`.repeat(dots.length / 3)); + const actual = new Map(); + const refresh = (): void => { + actual.clear(); + const names = compilation.getAssets().map((asset) => asset.name); + const counts = new Map(); + for (const name of names) { + counts.set(up(withoutQuery(name)), (counts.get(up(withoutQuery(name))) ?? 0) + 1); + } + for (const name of names) { + const clean = up(withoutQuery(name)); + actual.set(counts.get(clean) === 1 ? clean : up(name), name); + } + }; + const real = (name: string): string => actual.get(name) ?? name; + return { + names: () => { + refresh(); + return [...actual.keys()]; + }, + read: (name) => compilation.getAsset(real(name))?.source.buffer() ?? Buffer.alloc(0), + // A STRING source on purpose: the stamp runs before webpack's RealContentHashPlugin renames `[contenthash]` + // chunks, and that plugin rewrites the hashed names inside string sources only. A Buffer would keep the + // pre-rename chunk URLs (measured on real Next builds: every lazy chunk 404s, ChunkLoadError). + // Asked by the stamp for every asset BEFORE anything is written, so a bad asset refuses the whole stamp + // instead of leaving half of it applied. + check: (name, content) => void asText(name, content), + update: (name, content) => + compilation.updateAsset(real(name), new RawSource(asText(name, content))), + mapOf: (name) => { + const related = compilation.getAsset(real(name))?.info?.related?.sourceMap; + const map = Array.isArray(related) ? related[0] : related; + return map === undefined || map === null ? undefined : up(withoutQuery(map)); + }, + real, + }; +} + +/** + * The emitted scripts paired with their maps: a map named `