diff --git a/.changeset/angular-sourcemaps.md b/.changeset/angular-sourcemaps.md
new file mode 100644
index 00000000..d998f154
--- /dev/null
+++ b/.changeset/angular-sourcemaps.md
@@ -0,0 +1,8 @@
+---
+'@bugsee/angular': minor
+'@bugsee/bundler-plugin-core': minor
+---
+
+`ng add @bugsee/angular` and Angular source maps. The schematic enables hidden script source maps in the production configuration, launches the SDK in `main.ts`, registers `BugseeErrorHandler` through Angular's own `addRootProvider` (standalone and NgModule apps; it prints what to add by hand rather than guess when it cannot find the bootstrap), and adds a `build:bugsee` script: `ng build`, then the new `bugsee-angular-upload` command (also `@bugsee/angular/sourcemaps`), which stamps debug-IDs into the browser output, uploads the maps and registers the build. Works on Angular's esbuild `application` builder and the webpack `browser` builder.
+
+`subresourceIntegrity: true` is supported rather than refused: `@bugsee/bundler-plugin-core` gains `resealSri`, which snapshots every script's digests, stamps with `--allow-sri`, swaps each changed script's old digests for its new ones in the pages, an import map, the copy of the page an SSR build embeds in its server modules and the webpack builder's runtime hash table, then verifies the pages. The SRI scan now also reads `` in the same page, pinning EVERY lazy chunk. A stamped lazy chunk is blocked
+ (`Failed to find a valid digest in the 'integrity' attribute for resource '…/chunk-X.js' … has been blocked`,
+ and `Failed to fetch dynamically imported module`) while the entry scripts still run — which is what made this a
+ finding: the first version of the scan read tags only;
+- with SSR/prerender, a second copy of the page as a string in `server/assets-chunks/index*.html.mjs` and in
+ `server/index.server.html`, which the Node server answers requests from.
+
+Nothing else in the esbuild builder's output (no runtime table). The legacy webpack `browser` builder differs:
+its `runtime.*.js` carries the lazy chunks' hashes (`sriHashes`), which NO page pins (measured on
+`@angular-devkit/build-angular` 19: a stamped lazy chunk was blocked while the entry scripts ran). So the stale
+hashes cannot be found by reading the pages. They are found by what the files WERE: `snapshotScriptDigests` records
+the sha256/384/512 of every script under the output before the stamp, and `resealIntegrity` swaps each changed
+script's old digests for its new ones in every HTML, `.mjs` and `.js` file (same length, so no byte offset moves and
+the maps stay valid), repeating (bounded) because rewriting the runtime's table changes the runtime's own hash.
+
+The order that works is the one the CLI documents for `--allow-sri`: stamp, then recompute the hashes.
+`uploadSourcemaps({ resealSri: true })` does: snapshot, `inject --allow-sri`, verify the stamp, re-seal, then verify
+with `findIntegrityMismatches` (the pages' pins, the one thing a browser checks first). A page that still does not
+verify is reported, or thrown under `failOnError`, never silent. A hash computed at run time, or kept in a file
+outside the directories given, is not covered and is not claimed to be.
+
+**Verified for real** (`npm run build:bugsee` from `ng add`, the packed `@bugsee/angular` + `@bugsee/bundler-plugin-core`,
+the real `bugsee-cli`, a mock collector, Chromium via Playwright; `outputHashing: all`, `subresourceIntegrity: true`):
+
+| App | Result |
+|---|---|
+| Angular 22.3, esbuild `application`, lazy route | every pin matches its file; 5 maps uploaded and deleted; the page runs, the lazy chunk loads, 4 debug-IDs registered, no console error |
+| same, stamped with `--allow-sri` and NOT re-sealed (control) | blocked outright: nothing runs |
+| Angular 22.3, SSR + prerender | 24 pins across `browser/`, `server/index.server.html` and the 3 `assets-chunks` modules all match; the real `server.mjs` serves a page that runs, 5 debug-IDs, no console error |
+| Angular 19.2, webpack `browser` builder | the lazy chunk (blocked before the digest snapshot) now loads; 4 debug-IDs, no console error; control blocked |
+
+CI keeps the bytes half of this: `upload.real-build.test.ts` runs the real CLI over two real Angular 22.3 chunks with
+the SRI page shapes above (script tag, import map, SSR copy); the browser half is not in CI.
+
+**Service worker manifests.** `ngsw.json` (one per locale for a localized build; measured on `@angular/build` 22.3 with
+`@angular/service-worker`) carries `hashTable`: SHA-1 hex of each cached file's bytes, keyed by path from the manifest's
+directory. A service worker that finds a mismatch treats the app as corrupt and stops serving it, and the SRI re-seal
+(sha256/384/512) never touched it: the first version only refused a top-level manifest and so missed the per-locale
+ones. `resealIntegrity` now recomputes every entry after the last pass (a targeted text swap, formatting untouched;
+the file is found by dropping leading URL segments, which covers a base href), `findStaleServiceWorkerEntries` verifies,
+and an entry that cannot be reconciled rolls the build back like a stale SRI hash. No other manifest field depends on
+file contents in the version checked. **What it refuses:** nothing for a service worker now. It also stamps `browser/` only: a server bundle's errors are the Node
+SDK's, symbolicated by `@bugsee/node`.
+
+**The legacy webpack `browser` builder** (`@angular-devkit/build-angular:browser`) takes the same route: the post-build
+step needs nothing from the builder, and its output is flat (`outputPath` IS the browser directory). Its SRI is the
+reason for the digest snapshot above. `@angular-builders/custom-webpack` + `bugseeWebpackPlugin` (the route Sentry
+documents) was considered and not built: it would need the plugin's in-build stamp to run before Angular's own SRI
+plugin hashes, an ordering nobody verified for Angular's compilation, to cover one legacy builder that the post-build
+step already covers with a measured result.
---
diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md
index 8a8afa48..30bd358f 100644
--- a/docs/source-maps-usage.md
+++ b/docs/source-maps-usage.md
@@ -72,7 +72,7 @@ For **Rspack**, set `devtool: 'source-map'`: its production default is `devtool:
there is nothing to upload (the plugin says so through `onNotice`).
**What these do not cover.** **Angular's builder does not accept esbuild plugins**, so `bugseeEsbuildPlugin`
-cannot be used with `ng build`: use the post-build recipe in §2. Bun's bundler, `tsc` and `swc` have no hook
+cannot be used with `ng build`: use `ng add @bugsee/angular` (§2). Bun's bundler, `tsc` and `swc` have no hook
either (also §2). Next.js on webpack uses the webpack plugin.
**Where the settings come from.** The lookup order is: the **plugin option**, then the **process environment**,
@@ -184,20 +184,51 @@ BUGSEE_APP_TOKEN=… bugsee-cli debug-files upload ./dist \
--type sourcemaps --version "$APP_VERSION" --build "$APP_BUILD"
```
-**Angular (17+, `ng build` with the esbuild application builder).** There is no plugin hook, so add the CLI as a
-step after the build (for example an npm script or a CI step):
+**Angular — `ng add @bugsee/angular`.** Run it once in the workspace (`ng add @bugsee/angular --app-token `):
```bash
-ng build --source-map # or "sourceMap": true in angular.json; the output lands in dist//browser
-export BUGSEE_APP_TOKEN=… # the CLI does not read .env.bugsee-build-plugin
-bugsee-cli sourcemaps inject dist//browser
-bugsee-cli debug-files upload dist//browser \
- --type sourcemaps --version "$APP_VERSION" --build "$APP_BUILD"
+ng add @bugsee/angular
+npm run build:bugsee # ng build --configuration production, then bugsee-angular-upload
+```
+
+It turns on hidden script source maps in the production configuration
+(`"sourceMap": { "scripts": true, "styles": false, "hidden": true }`), launches the SDK in `main.ts`, registers
+`BugseeErrorHandler` in your providers, adds the `build:bugsee` script, and keeps the token in
+`.env.bugsee-build-plugin` (added to `.gitignore`). Where it cannot find your bootstrap it changes no source and prints
+the lines to add. Running it again changes nothing. A plain `ng build` does not upload; run `build:bugsee` where you
+build for release, with `BUGSEE_APP_TOKEN` set (or the env file present).
+
+`bugsee-angular-upload` is the step the script runs, and you can run it yourself after any `ng build` (it finds the
+output from `angular.json`): `--project`, `--configuration`, `--dist `, `--dry-run`, `--keep-maps`,
+`--fail-on-error`, `--strip-sources-content`, `--help`. The same thing is a function:
+`import { uploadAngularSourcemaps } from '@bugsee/angular/sourcemaps'`. It works on both Angular builders — the
+esbuild `application` builder (the default since 17, output in `dist//browser`) and the webpack
+`browser` builder (`outputPath` is the browser directory) — because it only needs the finished output.
+
+- **`subresourceIntegrity: true` is supported.** Angular writes a hash of every script into `index.html` (the lazy
+ chunks in an import map, or in the runtime chunk on the webpack builder) and, with SSR, into the copy of that page
+ its server serves. The step stamps the bundles,
+ then re-writes those hashes to match and checks them, so the page keeps loading. (The CLI on its own refuses such a
+ build; this is what `--allow-sri` assumes you do.)
+- **A build with a service worker works.** `ngsw.json` (one per locale for a localized build) lists the SHA-1 of every
+ file it caches and the service worker rejects a changed one, so after stamping the step re-computes those entries
+ and checks them; if one cannot be reconciled it restores the build and uploads nothing.
+- **If the output moved** (`ng build --output-path other`), pass `--output-path other` (or `--dist `). When the output is named by its browser directory (also `browser/`) and a sibling `server/` exists inside the project, the output root is re-sealed, because the server embeds the page (for one locale of several, only that locale and its `server/` pages: Angular emits identical shared scripts into every locale, and the others must keep pinning their unstamped copies); if the output root is the project root itself (or outside it) the tool says it cannot, and you should build into its own directory and use `--output-path`. A
+ problem locating the output is printed and the command exits 0, so it cannot fail a pipeline whose build
+ succeeded; `--fail-on-error` makes it exit non-zero.
+- **Only `browser/` is uploaded.** An SSR server bundle's errors are reported by the Node SDK.
+- `outputHashing: "all"` (the default in production) keeps the file names unique per build; the debug-ID, not the
+ file name, is what links a frame to its map.
+
+By hand, without the schematic (any Angular version), the same two steps are:
+
+```bash
+ng build --configuration production # with sourceMap.scripts true in angular.json
+BUGSEE_APP_TOKEN=… npx bugsee-angular-upload --configuration production
```
-If you enable `"subresourceIntegrity": true`, bugsee-cli 0.7.13 `inject` refuses to run (it would invalidate the
-integrity hashes Angular writes into `index.html`) unless you pass `--allow-sri`, which you should only do if
-the hashes are recomputed after it runs; otherwise turn that option off for builds you symbolicate.
+Do not run `bugsee-cli sourcemaps inject` yourself on an Angular build that has `subresourceIntegrity`: it refuses
+(or, with `--allow-sri`, leaves a page whose hashes no longer match, which the browser blocks).
`inject` must run **before deployment** so the shipped bundle carries the debug-ID + the `_bugseeDebugIds` runtime
stub the SDK reads. This is exactly what the plugins automate; the CLI is the same engine, just invoked by hand.
diff --git a/packages/angular/README.md b/packages/angular/README.md
index 08ed7338..ef326f13 100644
--- a/packages/angular/README.md
+++ b/packages/angular/README.md
@@ -16,11 +16,56 @@ pnpm add @bugsee/angular
yarn add @bugsee/angular
```
-Peer dependencies: `@angular/core` >= 16 and `@angular/router` >= 16 (both optional).
+Peer dependencies: `@angular/core` >= 16 and `@angular/router` >= 16 (both optional). `@angular-devkit/schematics` and `@schematics/angular` (>= 16.1, optional) are only used by `ng add` and are already in every Angular workspace.
-## Usage
+## Quick start: `ng add`
-Launch Bugsee as early as possible, at the top of your entry module. In the browser `launch()` returns a Promise of the client. Await it only if you need the client right away.
+```sh
+ng add @bugsee/angular
+```
+
+It asks for your app token and then, in the workspace's application:
+
+- turns on hidden script source maps in the production configuration of `angular.json` (`"sourceMap": { "scripts": true, "styles": false, "hidden": true }`), unless it already produces maps;
+- launches the SDK in `main.ts`, before the bootstrap;
+- registers `BugseeErrorHandler` as your `ErrorHandler` (standalone `app.config.ts` or `AppModule`);
+- adds a `build:bugsee` script, and keeps the token for it in `.env.bugsee-build-plugin` (added to `.gitignore`).
+
+Where it cannot find your bootstrap it changes no source and prints the lines to add by hand. Running it again changes nothing. With several applications pass `--project `.
+
+## Source maps
+
+Build for release with the script it added:
+
+```sh
+npm run build:bugsee # ng build --configuration production && bugsee-angular-upload --configuration production
+```
+
+`bugsee-angular-upload` stamps debug-IDs into `dist//browser`, uploads the maps, registers the build and removes the local maps, so a crash from the shipped bundle shows your original source. Set `BUGSEE_APP_TOKEN` (or keep the env file) where you run it. A plain `ng build` does not upload.
+
+You can also run it by hand after any `ng build` (`bugsee-angular-upload --help` lists the options: `--project`, `--configuration`, `--dist`, `--dry-run`, `--keep-maps`, `--fail-on-error`, …), or call it from code:
+
+```ts
+import { uploadAngularSourcemaps } from "@bugsee/angular/sourcemaps";
+
+await uploadAngularSourcemaps({ project: "my-app", configuration: "production" });
+```
+
+It works with the esbuild `application` builder and the webpack `browser` builder. Notes:
+
+- `subresourceIntegrity: true` is supported: after stamping, the integrity hashes in `index.html`, in the import map and in the SSR server modules are re-written to match, so the page keeps loading.
+- A build with a service worker works: `ngsw.json` (one per locale for a localized build) lists the SHA-1 of every file it caches, so after stamping those entries are re-computed and checked; if one cannot be reconciled the build is restored and nothing is uploaded.
+- If the output is not where `angular.json` says (`ng build --output-path other`), pass `--output-path other` (or `--dist `). When the output is named by its browser directory (also `browser/`) and a sibling `server/` exists inside the project, the output root is re-sealed, because the server embeds the page (for one locale of several, only that locale and its `server/` pages: Angular emits identical shared scripts into every locale, and the others must keep pinning their unstamped copies); if the output root is the project root itself (or outside it) the tool says it cannot, and you should build into its own directory and use `--output-path`. A problem locating the output (no `angular.json`, several applications without `--project`, no build output yet) is printed and the command still exits 0, so it cannot fail a pipeline whose build succeeded; add `--fail-on-error` to make it exit non-zero.
+- Install weight: `@bugsee/angular` depends on `@bugsee/bundler-plugin-core` (and through it `@bugsee/cli`, `acorn`, `magic-string`, `unplugin`), because the `bugsee-angular-upload` bin and `@bugsee/angular/sourcemaps` need them. They are build-time only and never reach a browser bundle, but they are installed with the package. Making them an optional peer that `ng add` installs as a devDependency was considered and not done: `ng add` saves the package itself under `dependencies`, the bin would fail for anyone who skips `ng add`, and the extra install step has to be verified against every package manager.
+- If your app already provides its own `ErrorHandler`, `ng add` does not add a second one (the last provider wins and would silence yours); it prints how to report from yours with `reportAngularError(error)`, or to wrap it with `createAngularErrorHandler({ delegate })`.
+- Known limits: the `ErrorHandler` check scans only the project's `sourceRoot`, so a handler provided from a shared (Nx) library is not seen; the deletion rule assumes Angular cleans its output directory (`deleteOutputPath`, default true), so with `deleteOutputPath: false` or a wider `--dist`, a stale foreign map that carries a debug-ID could be deleted; the integrity check does not follow `` for nested prerendered pages (the digest swap still fixes them).
+- Only the browser output is uploaded; errors from an SSR server are reported by the Node SDK.
+
+Details and the measurements behind them: [source maps](https://github.com/bugsee/bugsee-javascript/blob/main/docs/source-maps-usage.md).
+
+## Usage by hand
+
+`ng add` does this for you. To do it yourself, launch Bugsee as early as possible, at the top of your entry module. In the browser `launch()` returns a Promise of the client. Await it only if you need the client right away.
```ts
// main.ts
diff --git a/packages/angular/package.json b/packages/angular/package.json
index b37b4ab3..8818e44a 100644
--- a/packages/angular/package.json
+++ b/packages/angular/package.json
@@ -7,7 +7,7 @@
"url": "git+https://github.com/bugsee/bugsee-javascript.git",
"directory": "packages/angular"
},
- "description": "Angular adapter: ErrorHandler + Router naming",
+ "description": "Angular adapter: ErrorHandler + Router naming, plus `ng add` and a source-map upload step",
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
@@ -15,14 +15,19 @@
".": {
"types": "./src/index.ts",
"import": "./src/index.ts"
- }
+ },
+ "./sourcemaps": {
+ "types": "./src/sourcemaps/index.ts",
+ "import": "./src/sourcemaps/index.ts"
+ },
+ "./package.json": "./package.json"
},
"files": [
"dist"
],
"sideEffects": false,
"scripts": {
- "build": "tsup",
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:coverage": "vitest run --coverage"
@@ -30,11 +35,14 @@
"dependencies": {
"@bugsee/bugsee": "workspace:*",
"@bugsee/browser": "workspace:*",
- "@bugsee/web-adapter": "workspace:*"
+ "@bugsee/web-adapter": "workspace:*",
+ "@bugsee/bundler-plugin-core": "workspace:*"
},
"peerDependencies": {
"@angular/core": ">=16",
- "@angular/router": ">=16"
+ "@angular/router": ">=16",
+ "@angular-devkit/schematics": ">=16.1",
+ "@schematics/angular": ">=16.1"
},
"peerDependenciesMeta": {
"@angular/core": {
@@ -42,6 +50,12 @@
},
"@angular/router": {
"optional": true
+ },
+ "@angular-devkit/schematics": {
+ "optional": true
+ },
+ "@schematics/angular": {
+ "optional": true
}
},
"publishConfig": {
@@ -58,11 +72,32 @@
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
- }
+ },
+ "./sourcemaps": {
+ "import": {
+ "types": "./dist/sourcemaps/index.d.ts",
+ "default": "./dist/sourcemaps/index.js"
+ },
+ "require": {
+ "types": "./dist/sourcemaps/index.d.cts",
+ "default": "./dist/sourcemaps/index.cjs"
+ }
+ },
+ "./package.json": "./package.json"
},
- "access": "public"
+ "access": "public",
+ "bin": {
+ "bugsee-angular-upload": "./dist/sourcemaps/bin.js"
+ }
},
"devDependencies": {
- "@bugsee/core": "workspace:*"
+ "@bugsee/core": "workspace:*",
+ "@angular-devkit/schematics": "22.0.0",
+ "@schematics/angular": "22.0.0",
+ "@types/node": "^22.20.5"
+ },
+ "schematics": "./dist/schematics/collection.json",
+ "ng-add": {
+ "save": "dependencies"
}
}
diff --git a/packages/angular/src/schematics/collection.json b/packages/angular/src/schematics/collection.json
new file mode 100644
index 00000000..169c469b
--- /dev/null
+++ b/packages/angular/src/schematics/collection.json
@@ -0,0 +1,10 @@
+{
+ "$schema": "../../../../node_modules/@angular-devkit/schematics/collection-schema.json",
+ "schematics": {
+ "ng-add": {
+ "description": "Set up Bugsee in an Angular application: launch the SDK, report errors through Angular's ErrorHandler, and upload source maps after the production build.",
+ "factory": "./ng-add/index.cjs#ngAdd",
+ "schema": "./ng-add/schema.json"
+ }
+ }
+}
diff --git a/packages/angular/src/schematics/ng-add/index.test.ts b/packages/angular/src/schematics/ng-add/index.test.ts
new file mode 100644
index 00000000..65106f85
--- /dev/null
+++ b/packages/angular/src/schematics/ng-add/index.test.ts
@@ -0,0 +1,660 @@
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { callRule, type Rule, type Tree } from '@angular-devkit/schematics';
+import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { ngAdd } from './index';
+import type { Schema } from './schema';
+
+// A real Angular workspace and application are generated by Angular's own schematics into a virtual tree, so the
+// rule is tested against the files `ng new` writes, not against hand-made imitations of them.
+const here = fileURLToPath(new URL('.', import.meta.url));
+const collection = join(here, '..', 'collection.json');
+
+let runner: SchematicTestRunner;
+let logs: { level: string; message: string }[];
+
+beforeEach(() => {
+ runner = new SchematicTestRunner('@bugsee/angular', collection);
+ logs = [];
+ runner.logger.subscribe((entry) => logs.push({ level: entry.level, message: entry.message }));
+});
+
+const logged = (level?: string) =>
+ logs
+ .filter((l) => level === undefined || l.level === level)
+ .map((l) => l.message)
+ .join('\n');
+
+// biome-ignore lint/suspicious/noExplicitAny: angular.json is edited ad hoc throughout these tests
+type Loose = Record;
+
+const NG = '@schematics/angular';
+
+async function workspace(
+ apps: { name: string; standalone?: boolean; ssr?: boolean }[] = [{ name: 'demo' }],
+): Promise {
+ let tree = await runner.runExternalSchematic(NG, 'workspace', {
+ name: 'ws',
+ version: '22.0.0',
+ newProjectRoot: 'projects',
+ });
+ for (const app of apps) {
+ tree = await runner.runExternalSchematic(
+ NG,
+ 'application',
+ {
+ name: app.name,
+ projectRoot: apps.length === 1 ? '' : `projects/${app.name}`,
+ standalone: app.standalone ?? true,
+ routing: false,
+ style: 'css',
+ skipTests: true,
+ ssr: app.ssr ?? false,
+ },
+ tree,
+ );
+ }
+ tree.delete('/.gitignore');
+ if (!tree.exists('/package.json')) {
+ tree.create(
+ '/package.json',
+ JSON.stringify({ name: 'ws', version: '1.2.3', scripts: { ng: 'ng' } }, null, 2),
+ );
+ }
+ return tree;
+}
+
+/** Run a rule against `tree` and resolve to the resulting tree (callRule hands back an Observable). */
+const run = (tree: UnitTestTree, options: Schema = {}, rule: Rule = ngAdd(options)) =>
+ new Promise((resolve, reject) => {
+ let result: Tree | undefined;
+ // The runner's own context has a logger nobody can read; this one writes to `runner.logger` (see `logs`).
+ const context = {
+ ...runner.engine.createContext({ description: { name: 'ng-add' } } as never),
+ logger: runner.logger,
+ };
+ callRule(rule, tree, context).subscribe({
+ next: (next) => {
+ result = next;
+ },
+ error: reject,
+ complete: () => resolve(new UnitTestTree(result as Tree)),
+ });
+ });
+
+const json = (tree: UnitTestTree, path: string) => JSON.parse(tree.readContent(path));
+const snapshot = (tree: UnitTestTree) =>
+ Object.fromEntries(tree.files.map((file) => [file, tree.readContent(file)]));
+
+const prodOf = (tree: UnitTestTree, project = 'demo') =>
+ json(tree, '/angular.json').projects[project].architect.build.configurations.production;
+
+describe('ng add @bugsee/angular — a standalone application', () => {
+ it('turns on hidden script source maps in the production configuration', async () => {
+ const tree = await run(await workspace(), { appToken: 'TOKEN' });
+ expect(prodOf(tree).sourceMap).toEqual({ scripts: true, styles: false, hidden: true });
+ });
+
+ it('launches the SDK in main.ts, after the imports and before the bootstrap', async () => {
+ const tree = await run(await workspace(), { appToken: 'TOKEN' });
+ const main = tree.readContent('/src/main.ts');
+ expect(main).toContain(`import { launch } from '@bugsee/angular';`);
+ expect(main).toContain(`launch('TOKEN');`);
+ expect(main.indexOf(`launch('TOKEN')`)).toBeLessThan(main.indexOf('bootstrapApplication('));
+ expect(main.indexOf(`launch('TOKEN')`)).toBeGreaterThan(main.lastIndexOf('import '));
+ });
+
+ it('registers BugseeErrorHandler as the ErrorHandler in the application config', async () => {
+ const tree = await run(await workspace(), { appToken: 'TOKEN' });
+ const config = tree.readContent('/src/app/app.config.ts');
+ expect(config).toContain('BugseeErrorHandler');
+ expect(config).toMatch(/provide:\s*ErrorHandler,\s*useClass:\s*BugseeErrorHandler\b/);
+ expect(config).toContain(`from '@bugsee/angular'`);
+ expect(config).toMatch(/import \{[^}]*ErrorHandler[^}]*\} from '@angular\/core'/);
+ });
+
+ it('adds the build:bugsee script', async () => {
+ const tree = await run(await workspace(), { appToken: 'TOKEN' });
+ expect(json(tree, '/package.json').scripts['build:bugsee']).toBe(
+ 'ng build --configuration production && bugsee-angular-upload --configuration production',
+ );
+ expect(json(tree, '/package.json').scripts.ng).toBe('ng');
+ });
+
+ it('keeps the token for the build in .env.bugsee-build-plugin, out of git', async () => {
+ const tree = await workspace();
+ tree.create('/.gitignore', 'node_modules\n');
+ await run(tree, { appToken: 'TOKEN' });
+ expect(tree.readContent('/.env.bugsee-build-plugin')).toBe('BUGSEE_APP_TOKEN=TOKEN\n');
+ expect(tree.readContent('/.gitignore')).toBe('node_modules\n.env.bugsee-build-plugin\n');
+ });
+
+ it('creates a .gitignore when there is none, and does not duplicate the entry', async () => {
+ const tree = await run(await workspace(), { appToken: 'TOKEN' });
+ expect(tree.readContent('/.gitignore')).toBe('.env.bugsee-build-plugin\n');
+ const again = await run(tree, { appToken: 'TOKEN' });
+ expect(again.readContent('/.gitignore')).toBe('.env.bugsee-build-plugin\n');
+ });
+
+ it('adds a missing newline before the .gitignore entry', async () => {
+ const tree = await workspace();
+ tree.create('/.gitignore', 'dist');
+ await run(tree, { appToken: 'TOKEN' });
+ expect(tree.readContent('/.gitignore')).toBe('dist\n.env.bugsee-build-plugin\n');
+ });
+
+ it('is idempotent: a second run changes nothing', async () => {
+ const first = await run(await workspace(), { appToken: 'TOKEN' });
+ const before = snapshot(first);
+ const second = await run(first, { appToken: 'TOKEN' });
+ expect(snapshot(second)).toEqual(before);
+ });
+
+ it('does not touch what is already set up, even with another token', async () => {
+ const first = await run(await workspace(), { appToken: 'TOKEN' });
+ const before = snapshot(first);
+ const second = await run(first, { appToken: 'OTHER' });
+ expect(snapshot(second)).toEqual(before);
+ expect(second.readContent('/src/main.ts')).toContain(`launch('TOKEN')`);
+ });
+});
+
+describe('ng add @bugsee/angular — an NgModule application', () => {
+ it('registers the ErrorHandler in AppModule and launches in main.ts', async () => {
+ const tree = await run(await workspace([{ name: 'demo', standalone: false }]), {
+ appToken: 'T',
+ });
+ const modulePath = tree.files.find((f) => /app[.-]module\.ts$/.test(f)) as string;
+ const module = tree.readContent(modulePath);
+ expect(module).toContain('BugseeErrorHandler');
+ expect(module).toMatch(/provide:\s*ErrorHandler,\s*useClass:\s*BugseeErrorHandler\b/);
+ expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`);
+ expect(tree.readContent('/src/main.ts')).toContain('bootstrapModule');
+ });
+
+ it('is idempotent', async () => {
+ const first = await run(await workspace([{ name: 'demo', standalone: false }]), {
+ appToken: 'T',
+ });
+ const second = await run(first, { appToken: 'T' });
+ expect(snapshot(second)).toEqual(snapshot(first));
+ });
+});
+
+describe('ng add @bugsee/angular — without a token', () => {
+ it('writes a placeholder, creates no env file, and says what to do', async () => {
+ const tree = await run(await workspace(), {});
+ expect(tree.readContent('/src/main.ts')).toContain(`launch('YOUR_APP_TOKEN');`);
+ expect(tree.exists('/.env.bugsee-build-plugin')).toBe(false);
+ expect(logged('warn')).toMatch(/YOUR_APP_TOKEN/);
+ expect(logged('warn')).toMatch(/BUGSEE_APP_TOKEN/);
+ });
+
+ it('treats a blank token as none', async () => {
+ const tree = await run(await workspace(), { appToken: ' ' });
+ expect(tree.readContent('/src/main.ts')).toContain(`launch('YOUR_APP_TOKEN');`);
+ });
+
+ it.each([
+ ['a line break', 'abc\nBUGSEE_ENDPOINT=https://evil'],
+ ['a carriage return', 'abc\rdef'],
+ ['a unicode line separator', 'abc\u2028def'],
+ ['a space', 'abc def'],
+ ['a # (the env parser reads it as a comment)', 'abc#def'],
+ ['a single quote', "a'b"],
+ ['a double quote', 'a"b'],
+ ['a backtick', 'a`b'],
+ ['a backslash', 'a\\b'],
+ ])('rejects a token with %s, which the env file or the launch call cannot carry safely', async (_name, token) => {
+ const tree = await workspace();
+ await expect(run(tree, { appToken: token })).rejects.toThrow(/must not contain/);
+ expect(tree.exists('/.env.bugsee-build-plugin')).toBe(false);
+ expect(tree.readContent('/src/main.ts')).not.toContain('launch(');
+ });
+});
+
+describe('ng add @bugsee/angular — the .env file', () => {
+ it('warns when the env file already holds a DIFFERENT token than the one given, and leaves it', async () => {
+ const tree = await workspace();
+ tree.create('/.env.bugsee-build-plugin', 'BUGSEE_APP_TOKEN=OLD\n');
+ await run(tree, { appToken: 'NEW' });
+ expect(tree.readContent('/.env.bugsee-build-plugin')).toBe('BUGSEE_APP_TOKEN=OLD\n');
+ expect(logged('warn')).toMatch(/different BUGSEE_APP_TOKEN/);
+ expect(tree.readContent('/src/main.ts')).toContain(`launch('NEW');`);
+ });
+
+ it('says nothing when the env file already holds the same token', async () => {
+ const tree = await workspace();
+ tree.create('/.env.bugsee-build-plugin', 'BUGSEE_APP_TOKEN=SAME\n');
+ await run(tree, { appToken: 'SAME' });
+ expect(logged('warn')).not.toMatch(/different/);
+ });
+
+ it('appends the token to an env file that has other settings, and leaves one that has a token alone', async () => {
+ const tree = await workspace();
+ tree.create('/.env.bugsee-build-plugin', 'BUGSEE_ENDPOINT=https://x');
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/.env.bugsee-build-plugin')).toBe(
+ 'BUGSEE_ENDPOINT=https://x\nBUGSEE_APP_TOKEN=T\n',
+ );
+ const kept = await workspace();
+ kept.create('/.env.bugsee-build-plugin', 'BUGSEE_APP_TOKEN=mine\n');
+ await run(kept, { appToken: 'T' });
+ expect(kept.readContent('/.env.bugsee-build-plugin')).toBe('BUGSEE_APP_TOKEN=mine\n');
+ });
+});
+
+describe('ng add @bugsee/angular — source maps in angular.json', () => {
+ const setBuild = (tree: UnitTestTree, edit: (build: Loose) => void) => {
+ const ws = json(tree, '/angular.json');
+ edit(ws.projects.demo.architect.build);
+ tree.overwrite('/angular.json', JSON.stringify(ws, null, 2));
+ };
+
+ it('replaces a production sourceMap that is off', async () => {
+ const tree = await workspace();
+ setBuild(tree, (b) => {
+ b.configurations.production.sourceMap = false;
+ });
+ await run(tree, { appToken: 'T' });
+ expect(prodOf(tree).sourceMap).toEqual({ scripts: true, styles: false, hidden: true });
+ });
+
+ it('replaces an object with scripts off, but keeps the rest of the object', async () => {
+ const tree = await workspace();
+ setBuild(tree, (b) => {
+ b.configurations.production.sourceMap = { scripts: false, styles: true, vendor: true };
+ });
+ await run(tree, { appToken: 'T' });
+ expect(prodOf(tree).sourceMap).toEqual({
+ scripts: true,
+ styles: true,
+ vendor: true,
+ hidden: true,
+ });
+ });
+
+ it('leaves a production sourceMap that already includes scripts exactly as the user wrote it', async () => {
+ for (const value of [true, { scripts: true, hidden: false }, { styles: false }]) {
+ const tree = await workspace();
+ setBuild(tree, (b) => {
+ b.configurations.production.sourceMap = value;
+ });
+ await run(tree, { appToken: 'T' });
+ expect(prodOf(tree).sourceMap).toEqual(value);
+ }
+ });
+
+ it('leaves it alone when the build options already turn maps on for every configuration', async () => {
+ const tree = await workspace();
+ setBuild(tree, (b) => {
+ b.options.sourceMap = true;
+ });
+ await run(tree, { appToken: 'T' });
+ expect(prodOf(tree).sourceMap).toBeUndefined();
+ });
+
+ it('creates the production configuration when the project has none', async () => {
+ const tree = await workspace();
+ setBuild(tree, (b) => {
+ delete b.configurations;
+ delete b.defaultConfiguration;
+ });
+ await run(tree, { appToken: 'T' });
+ expect(prodOf(tree).sourceMap).toEqual({ scripts: true, styles: false, hidden: true });
+ });
+
+ it('adds the production configuration next to a development-only set', async () => {
+ const tree = await workspace();
+ setBuild(tree, (b) => {
+ b.configurations = { development: { optimization: false } };
+ });
+ await run(tree, { appToken: 'T' });
+ const configs = json(tree, '/angular.json').projects.demo.architect.build.configurations;
+ expect(configs.development).toEqual({ optimization: false });
+ expect(configs.production.sourceMap).toEqual({ scripts: true, styles: false, hidden: true });
+ });
+});
+
+describe('ng add @bugsee/angular — choosing the project', () => {
+ it('uses the only application, ignoring libraries', async () => {
+ const tree = await workspace();
+ const ws = json(tree, '/angular.json');
+ ws.projects.lib = { projectType: 'library', root: 'projects/lib', architect: {} };
+ tree.overwrite('/angular.json', JSON.stringify(ws));
+ const out = await run(tree, { appToken: 'T' });
+ expect(prodOf(out).sourceMap.scripts).toBe(true);
+ });
+
+ it('asks for --project when there are several applications', async () => {
+ const tree = await workspace([{ name: 'one' }, { name: 'two' }]);
+ await expect(run(tree, { appToken: 'T' })).rejects.toThrow(/--project.*one, two/);
+ });
+
+ it('sets up the named application and puts its name in the script', async () => {
+ const tree = await run(await workspace([{ name: 'one' }, { name: 'two' }]), {
+ project: 'two',
+ appToken: 'T',
+ });
+ expect(prodOf(tree, 'two').sourceMap.scripts).toBe(true);
+ expect(prodOf(tree, 'one').sourceMap).toBeUndefined();
+ expect(tree.readContent('/projects/two/src/main.ts')).toContain(`launch('T')`);
+ expect(tree.readContent('/projects/one/src/main.ts')).not.toContain('launch');
+ expect(json(tree, '/package.json').scripts['build:bugsee']).toBe(
+ 'ng build two --configuration production && bugsee-angular-upload --project two --configuration production',
+ );
+ });
+
+ it('rejects a project that does not exist', async () => {
+ await expect(run(await workspace(), { project: 'nope' })).rejects.toThrow(/no project "nope"/);
+ });
+
+ it('rejects a workspace with no application', async () => {
+ const tree = await workspace();
+ tree.overwrite('/angular.json', JSON.stringify({ version: 1, projects: {} }));
+ await expect(run(tree, {})).rejects.toThrow(/no application project/);
+ });
+
+ it('rejects a project that has no build target', async () => {
+ const tree = await workspace();
+ const ws = json(tree, '/angular.json');
+ delete ws.projects.demo.architect.build;
+ tree.overwrite('/angular.json', JSON.stringify(ws));
+ await expect(run(tree, {})).rejects.toThrow(/no "build" target/);
+ });
+});
+
+describe('ng add @bugsee/angular — when it cannot tell how the app starts', () => {
+ it('changes no source, says what to add by hand, and still sets up the build', async () => {
+ const tree = await workspace();
+ tree.overwrite('/src/main.ts', `import('./boot').then((m) => m.start());\n`);
+ const before = tree.readContent('/src/app/app.config.ts');
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/main.ts')).toBe(`import('./boot').then((m) => m.start());\n`);
+ expect(tree.readContent('/src/app/app.config.ts')).toBe(before);
+ expect(logged('warn')).toMatch(/could not find where the app bootstraps/);
+ expect(logged('warn')).toMatch(/launch\('T'\)/);
+ expect(logged('warn')).toMatch(/BugseeErrorHandler/);
+ expect(prodOf(tree).sourceMap.scripts).toBe(true);
+ expect(json(tree, '/package.json').scripts['build:bugsee']).toBeDefined();
+ });
+
+ it('says so when the entry file is missing', async () => {
+ const tree = await workspace();
+ tree.delete('/src/main.ts');
+ await run(tree, { appToken: 'T' });
+ expect(logged('warn')).toMatch(/could not find where the app bootstraps/);
+ });
+
+ it('launches but explains the ErrorHandler step when the provider cannot be added', async () => {
+ const tree = await workspace();
+ tree.overwrite(
+ '/src/main.ts',
+ `import { bootstrapApplication } from '@angular/platform-browser';\nimport { App } from './app/app';\n\nbootstrapApplication(App, makeConfig());\n`,
+ );
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`);
+ expect(logged('warn')).toMatch(/could not register BugseeErrorHandler/);
+ expect(logged('warn')).toMatch(/provide: ErrorHandler, useClass: BugseeErrorHandler/);
+ });
+
+ it('puts the launch first in a main.ts that has no imports', async () => {
+ const tree = await workspace();
+ tree.overwrite('/src/main.ts', `platformBrowser().bootstrapModule(AppModule);\n`);
+ await run(tree, { appToken: 'T' });
+ expect(
+ tree.readContent('/src/main.ts').startsWith(`import { launch } from '@bugsee/angular';`),
+ ).toBe(true);
+ });
+
+ it('inserts after the last of several imports, including a side-effect import', async () => {
+ const tree = await workspace();
+ tree.overwrite(
+ '/src/main.ts',
+ `import { a } from 'a';\nimport {\n b,\n c,\n} from 'b';\nimport 'zone.js';\n\nbootstrapApplication(App, appConfig);\n`,
+ );
+ await run(tree, { appToken: 'T' });
+ const main = tree.readContent('/src/main.ts');
+ expect(main.indexOf(`from '@bugsee/angular'`)).toBeGreaterThan(
+ main.indexOf(`import 'zone.js'`),
+ );
+ expect(main.indexOf(`launch('T')`)).toBeLessThan(main.indexOf('bootstrapApplication'));
+ });
+
+ it('does not mistake a call that merely starts with "import" for an import', async () => {
+ const tree = await workspace();
+ tree.overwrite(
+ '/src/main.ts',
+ `import { a } from 'a';\nimportScripts('worker.js');\nbootstrapApplication(App, appConfig);\n`,
+ );
+ await run(tree, { appToken: 'T' });
+ const main = tree.readContent('/src/main.ts');
+ expect(main.indexOf(`from '@bugsee/angular'`)).toBeLessThan(main.indexOf('importScripts'));
+ });
+
+ it('finds the entry file when angular.json spells it with a leading ./', async () => {
+ const tree = await workspace();
+ const ws = json(tree, '/angular.json');
+ ws.projects.demo.architect.build.options.browser = './src/main.ts';
+ tree.overwrite('/angular.json', JSON.stringify(ws, null, 2));
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`);
+ });
+});
+
+describe('ng add @bugsee/angular — an app already using Bugsee', () => {
+ it('does not launch twice, and does not add a second handler', async () => {
+ const tree = await workspace();
+ tree.overwrite(
+ '/src/main.ts',
+ `import { launch } from '@bugsee/bugsee';\nimport { bootstrapApplication } from '@angular/platform-browser';\nlaunch('mine');\nbootstrapApplication(App, appConfig);\n`,
+ );
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/main.ts')).not.toContain(`launch('T')`);
+ expect(tree.readContent('/src/main.ts').match(/launch\(/g)).toHaveLength(1);
+ });
+
+ it('does not add a handler when the app already PROVIDES BugseeErrorHandler somewhere', async () => {
+ const tree = await workspace();
+ tree.create(
+ '/src/app/errors.ts',
+ `import { ErrorHandler } from '@angular/core';\nimport { BugseeErrorHandler } from '@bugsee/angular';\nexport const p = { provide: ErrorHandler, useClass: BugseeErrorHandler };\n`,
+ );
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/app/app.config.ts')).not.toContain('BugseeErrorHandler');
+ });
+
+ it('an unused mention of BugseeErrorHandler (an export, a spec, a comment) is not a registration', async () => {
+ const tree = await workspace();
+ tree.create(
+ '/src/app/errors.ts',
+ `import { BugseeErrorHandler } from '@bugsee/angular';\nexport const X = BugseeErrorHandler;\n`,
+ );
+ tree.create('/src/app/x.spec.ts', `{ provide: ErrorHandler, useClass: BugseeErrorHandler }\n`);
+ tree.create('/src/app/c.ts', `// { provide: ErrorHandler, useClass: BugseeErrorHandler }\n`);
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/app/app.config.ts')).toMatch(
+ /provide:\s*ErrorHandler,\s*useClass:\s*BugseeErrorHandler\b/,
+ );
+ });
+
+ it("recognises an aliased ErrorHandler import as the app's own handler", async () => {
+ const tree = await workspace();
+ tree.create(
+ '/src/app/mine.ts',
+ `import { ErrorHandler as AngularErrorHandler } from '@angular/core';\nexport const p = { provide: AngularErrorHandler, useClass: MyHandler };\n`,
+ );
+ const before = tree.readContent('/src/app/app.config.ts');
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/app/app.config.ts')).toBe(before);
+ expect(logged('warn')).toMatch(/already provides its own ErrorHandler/);
+ });
+
+ it('a comment mentioning @bugsee/angular in main.ts does not stop the launch from being added', async () => {
+ const tree = await workspace();
+ const main = tree.readContent('/src/main.ts');
+ tree.overwrite('/src/main.ts', `// TODO: add @bugsee/angular later\n${main}`);
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`);
+ });
+
+ it('a main.ts that imports a Bugsee helper but never calls launch gets the call (and no second launch import)', async () => {
+ const tree = await workspace();
+ const main = tree.readContent('/src/main.ts');
+ tree.overwrite(
+ '/src/main.ts',
+ `import { launch } from '@bugsee/bugsee';\nimport { reportAngularError } from '@bugsee/angular';\n${main}`,
+ );
+ await run(tree, { appToken: 'T' });
+ const out = tree.readContent('/src/main.ts');
+ expect(out).toContain(`launch('T');`);
+ expect(out.match(/import \{ launch \}/g)).toHaveLength(1);
+ });
+});
+
+describe('ng add @bugsee/angular — an app that already has its own ErrorHandler', () => {
+ const MINE = `{ provide: ErrorHandler, useClass: MyHandler }`;
+
+ it('standalone: does not add a second handler (the last one wins and would silence theirs), and says what to do', async () => {
+ const tree = await workspace();
+ const config = tree
+ .readContent('/src/app/app.config.ts')
+ .replace('providers: [', `providers: [\n ${MINE},`)
+ .replace(/^/, `import { ErrorHandler } from '@angular/core';\nclass MyHandler {}\n`);
+ tree.overwrite('/src/app/app.config.ts', config);
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/app/app.config.ts')).toBe(config);
+ expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`);
+ expect(logged('warn')).toMatch(/already provides its own ErrorHandler/);
+ expect(logged('warn')).toMatch(/reportAngularError\(error\)/);
+ expect(logged('warn')).toMatch(/createAngularErrorHandler\(\{ delegate/);
+ });
+
+ it('NgModule: the same', async () => {
+ const tree = await workspace([{ name: 'demo', standalone: false }]);
+ const modulePath = tree.files.find((f) => /app[.-]module\.ts$/.test(f)) as string;
+ const module = tree
+ .readContent(modulePath)
+ .replace('providers: [', `providers: [\n ${MINE},`)
+ .replace(/^/, `import { ErrorHandler } from '@angular/core';\nclass MyHandler {}\n`);
+ tree.overwrite(modulePath, module);
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent(modulePath)).toBe(module);
+ expect(logged('warn')).toMatch(/already provides its own ErrorHandler/);
+ });
+
+ it('is idempotent with it', async () => {
+ const tree = await workspace();
+ tree.create(
+ '/src/app/handler.ts',
+ `export const p = { provide: ErrorHandler,\n useClass: MyHandler };\n`,
+ );
+ const first = await run(tree, { appToken: 'T' });
+ const before = snapshot(first);
+ const second = await run(first, { appToken: 'T' });
+ expect(snapshot(second)).toEqual(before);
+ });
+
+ it('does not mistake another token that starts with ErrorHandler for it', async () => {
+ const tree = await workspace();
+ tree.create('/src/app/x.ts', `export const p = { provide: ErrorHandlerLike, useClass: X };\n`);
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/app/app.config.ts')).toContain('BugseeErrorHandler');
+ });
+
+ it('ignores a test double in a spec file', async () => {
+ const tree = await workspace();
+ tree.create(
+ '/src/app/x.spec.ts',
+ `TestBed.configureTestingModule({ providers: [${MINE}] });\n`,
+ );
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/app/app.config.ts')).toContain('BugseeErrorHandler');
+ });
+});
+
+describe('ng add @bugsee/angular — the build script', () => {
+ const setScripts = (tree: UnitTestTree, scripts: Record, indent = 2) => {
+ tree.overwrite('/package.json', `${JSON.stringify({ name: 'x', scripts }, null, indent)}\n`);
+ };
+
+ it('keeps a build:bugsee script the user already has, and says so', async () => {
+ const tree = await workspace();
+ setScripts(tree, { 'build:bugsee': 'custom' });
+ await run(tree, { appToken: 'T' });
+ expect(json(tree, '/package.json').scripts['build:bugsee']).toBe('custom');
+ expect(logged('info')).toMatch(/build:bugsee.*already/);
+ });
+
+ it('preserves the file indentation and trailing newline', async () => {
+ const tree = await workspace();
+ setScripts(tree, { start: 'ng serve' }, 4);
+ await run(tree, { appToken: 'T' });
+ const text = tree.readContent('/package.json');
+ expect(text).toContain('\n "scripts": {');
+ expect(text.endsWith('}\n')).toBe(true);
+ });
+
+ it('creates the scripts object when package.json has none', async () => {
+ const tree = await workspace();
+ tree.overwrite('/package.json', '{"name":"x"}');
+ await run(tree, { appToken: 'T' });
+ expect(json(tree, '/package.json').scripts['build:bugsee']).toBeDefined();
+ expect(tree.readContent('/package.json').endsWith('\n')).toBe(false);
+ });
+
+ it('warns instead of failing when there is no package.json', async () => {
+ const tree = await workspace();
+ tree.delete('/package.json');
+ await run(tree, { appToken: 'T' });
+ expect(logged('warn')).toMatch(/no package\.json/);
+ });
+});
+
+describe('ng add @bugsee/angular — what the build step cannot do, said up front', () => {
+ const setBuild = (tree: UnitTestTree, edit: (build: Loose) => void) => {
+ const ws = json(tree, '/angular.json');
+ edit(ws.projects.demo.architect.build);
+ tree.overwrite('/angular.json', JSON.stringify(ws, null, 2));
+ };
+
+ it('explains that subresourceIntegrity is handled', async () => {
+ const tree = await workspace();
+ setBuild(tree, (b) => {
+ b.configurations.production.subresourceIntegrity = true;
+ });
+ await run(tree, { appToken: 'T' });
+ expect(logged('info')).toMatch(/subresourceIntegrity.*re-written/);
+ });
+
+ it('explains that service worker manifests are re-computed', async () => {
+ const tree = await workspace();
+ setBuild(tree, (b) => {
+ b.options.serviceWorker = 'ngsw-config.json';
+ });
+ await run(tree, { appToken: 'T' });
+ expect(logged('info')).toMatch(/serviceWorker.*re-computes/);
+ });
+
+ it('says nothing about either when neither is on', async () => {
+ await run(await workspace(), { appToken: 'T' });
+ expect(logged()).not.toMatch(/subresourceIntegrity|serviceWorker/);
+ });
+});
+
+describe('ng add @bugsee/angular — the webpack browser builder', () => {
+ it('reads the entry from `main`, sets up the same way, and names the builder in the notes', async () => {
+ const tree = await workspace();
+ const ws = json(tree, '/angular.json');
+ const build = ws.projects.demo.architect.build;
+ build.builder = '@angular-devkit/build-angular:browser';
+ build.options.main = build.options.browser;
+ delete build.options.browser;
+ tree.overwrite('/angular.json', JSON.stringify(ws, null, 2));
+ await run(tree, { appToken: 'T' });
+ expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`);
+ expect(prodOf(tree).sourceMap.scripts).toBe(true);
+ expect(logged('info')).toMatch(/@angular-devkit\/build-angular:browser/);
+ });
+});
diff --git a/packages/angular/src/schematics/ng-add/index.ts b/packages/angular/src/schematics/ng-add/index.ts
new file mode 100644
index 00000000..26d95ed6
--- /dev/null
+++ b/packages/angular/src/schematics/ng-add/index.ts
@@ -0,0 +1,353 @@
+// `ng add @bugsee/angular` — set an Angular application up for Bugsee. Build-time only: this entry is built
+// separately (CommonJS, loaded by the Angular CLI) and nothing in the runtime entry imports it, so it cannot
+// reach a browser bundle.
+//
+// What it does, and what it deliberately does not guess:
+// - angular.json: hidden script source maps in the production configuration (never overriding a setting that
+// already produces maps).
+// - main.ts: `launch(token)` before the bootstrap; the app config / AppModule: `BugseeErrorHandler` as the
+// ErrorHandler (through Angular's own `addRootProvider`, which understands standalone and NgModule apps).
+// If the bootstrap cannot be found, nothing in the source is changed and the exact lines to add are printed.
+// - package.json: a `build:bugsee` script — `ng build`, then `bugsee-angular-upload` (see ../../sourcemaps).
+// Angular's esbuild builder has no plugin hook, so the upload is a step after the build.
+// - `.env.bugsee-build-plugin` (git-ignored) with the token for that step, when one was given.
+// Every step is idempotent: running it again changes nothing.
+import {
+ callRule,
+ chain,
+ type Rule,
+ type SchematicContext,
+ SchematicsException,
+ type Tree,
+} from '@angular-devkit/schematics';
+import {
+ addRootProvider,
+ readWorkspace,
+ type TargetDefinition,
+ updateWorkspace,
+} from '@schematics/angular/utility';
+import type { Schema } from './schema';
+
+const PLACEHOLDER = 'YOUR_APP_TOKEN';
+const ENV_FILE = '.env.bugsee-build-plugin';
+const SCRIPT = 'build:bugsee';
+const SOURCE_MAP = { scripts: true, styles: false, hidden: true };
+
+type Obj = Record;
+
+/** Whether a `sourceMap` value turns script maps on: `true`, or an object that does not turn scripts off. */
+const mapsScripts = (value: unknown): boolean =>
+ value === true ||
+ (typeof value === 'object' && value !== null && (value as Obj).scripts !== false);
+
+const quote = (text: string): string => `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
+
+/** Run a rule now and wait for it, so its failure can be handled here. */
+function apply(rule: Rule, tree: Tree, context: SchematicContext): Promise {
+ return new Promise((resolve, reject) => {
+ callRule(rule, tree, context).subscribe({ error: reject, complete: () => resolve() });
+ });
+}
+
+interface Located {
+ name: string;
+ /** Application projects in the workspace — more than one means the script must name this one. */
+ applications: number;
+ builder: string | undefined;
+ options: Obj;
+ production: Obj;
+ mainPath: string | undefined;
+ sourceRoot: string;
+}
+
+async function locate(tree: Tree, requested: string | undefined): Promise {
+ const workspace = await readWorkspace(tree);
+ const apps = [...workspace.projects.entries()]
+ .filter(([, project]) => project.extensions.projectType === 'application')
+ .map(([name]) => name);
+ let name = requested;
+ if (name === undefined) {
+ if (apps.length === 0) {
+ throw new SchematicsException('The workspace has no application project to set up.');
+ }
+ if (apps.length > 1) {
+ throw new SchematicsException(
+ `The workspace has several applications; choose one with --project (${apps.join(', ')}).`,
+ );
+ }
+ name = apps[0] as string;
+ }
+ const project = workspace.projects.get(name);
+ if (project === undefined) {
+ throw new SchematicsException(
+ `The workspace has no project "${name}" (it has: ${[...workspace.projects.keys()].join(', ')}).`,
+ );
+ }
+ const build = project.targets.get('build');
+ if (build === undefined) {
+ throw new SchematicsException(`Project "${name}" has no "build" target.`);
+ }
+ const options = (build.options ?? {}) as Obj;
+ const entry = (options.browser ?? options.main) as string | undefined;
+ return {
+ name,
+ applications: apps.length,
+ builder: build.builder,
+ options,
+ production: (build.configurations?.production ?? {}) as Obj,
+ mainPath: entry === undefined ? undefined : `/${entry}`,
+ sourceRoot: `/${(project.sourceRoot ?? `${project.root}/src`).replace(/^\/+/, '')}`,
+ };
+}
+
+/** angular.json: hidden script maps in the production configuration, unless it already produces them. */
+function enableSourceMaps(project: string): Rule {
+ return updateWorkspace((workspace) => {
+ // `locate` already proved the project and its build target exist.
+ const build = workspace.projects.get(project)?.targets.get('build') as TargetDefinition;
+ const production = (build.configurations?.production ?? {}) as Obj;
+ const effective = 'sourceMap' in production ? production.sourceMap : build.options?.sourceMap;
+ if (mapsScripts(effective)) {
+ return;
+ }
+ const current = production.sourceMap;
+ const sourceMap =
+ typeof current === 'object' && current !== null
+ ? { ...(current as Obj), scripts: true, hidden: true }
+ : SOURCE_MAP;
+ build.configurations = {
+ ...build.configurations,
+ production: { ...production, sourceMap },
+ } as typeof build.configurations;
+ });
+}
+
+/** The end of the last top-level import in `source`, or -1. */
+function endOfImports(source: string): number {
+ let end = -1;
+ for (const match of source.matchAll(/^import\s[^;]*?['"][^'"]+['"]\s*;?/gm)) {
+ end = (match.index as number) + match[0].length;
+ }
+ return end;
+}
+
+/** Source without comments, so a mention in one is not read as code. */
+const withoutComments = (text: string): string =>
+ text.replace(/\/\*[\s\S]*?\*\/|(^|[^:'"`])\/\/.*$/gm, '$1');
+
+/** The names ErrorHandler is imported under from @angular/core in `text`: `ErrorHandler` and any `as` alias. */
+function errorHandlerNames(text: string): string[] {
+ const names = ['ErrorHandler'];
+ for (const [, list] of text.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]@angular\/core['"]/g)) {
+ for (const [, alias] of (list ?? '').matchAll(/\bErrorHandler\s+as\s+(\w+)/g)) {
+ names.push(alias as string);
+ }
+ }
+ return names;
+}
+
+const BOOTSTRAP = /\bbootstrap(Application|Module|ModuleFactory)\s*\(/;
+
+function manualSteps(token: string): string {
+ return (
+ ` // main.ts, before the app starts\n import { launch } from '@bugsee/angular';\n launch(${quote(token)});\n\n` +
+ ` // your providers (app.config.ts or AppModule)\n import { ErrorHandler } from '@angular/core';\n` +
+ ` import { BugseeErrorHandler } from '@bugsee/angular';\n { provide: ErrorHandler, useClass: BugseeErrorHandler }`
+ );
+}
+
+/** main.ts: launch before the bootstrap; the providers: BugseeErrorHandler. Explains instead of guessing. */
+function instrument(located: Located, token: string): Rule {
+ return async (tree, context) => {
+ const main =
+ located.mainPath !== undefined && tree.exists(located.mainPath)
+ ? located.mainPath
+ : undefined;
+ const source = main === undefined ? undefined : tree.readText(main);
+ if (main === undefined || source === undefined || !BOOTSTRAP.test(source)) {
+ context.logger.warn(
+ `Bugsee: could not find where the app bootstraps (looked for bootstrapApplication / bootstrapModule in ` +
+ `${located.mainPath ?? "the build target's entry"}), so no source was changed. Add this yourself:\n\n${manualSteps(token)}\n`,
+ );
+ return;
+ }
+ const code = withoutComments(source);
+ // An existing launch CALL (not a mention of the package, not an imported helper) is left exactly as it is.
+ if (!(/@bugsee\//.test(code) && /\blaunch\s*\(/.test(code))) {
+ const call = `// Launch Bugsee before the app starts, so startup errors are captured.\nlaunch(${quote(token)});`;
+ const importsLaunch = /import\s*\{[^}]*\blaunch\b[^}]*\}\s*from\s*['"]@bugsee\//.test(code);
+ const statement = importsLaunch ? '' : `import { launch } from '@bugsee/angular';\n\n`;
+ const end = endOfImports(source);
+ tree.overwrite(
+ main,
+ end === -1
+ ? `${statement}${call}\n\n${source}`
+ : `${source.slice(0, end)}\n${statement === '' ? '\n' : statement}${call}${source.slice(end)}`,
+ );
+ }
+ let provided = false;
+ let foreign = false;
+ tree.getDir(located.sourceRoot).visit((path) => {
+ if (!path.endsWith('.ts')) {
+ return;
+ }
+ if (path.endsWith('.spec.ts')) {
+ return;
+ }
+ const text = withoutComments(tree.readText(path));
+ const tokens = errorHandlerNames(text).join('|');
+ if (new RegExp(`provide\\s*:\\s*(?:${tokens})\\b[^}]*\\bBugseeErrorHandler\\b`).test(text)) {
+ provided = true;
+ } else if (new RegExp(`provide\\s*:\\s*(?:${tokens})\\b`).test(text)) {
+ foreign = true;
+ }
+ });
+ if (provided) {
+ return;
+ }
+ if (foreign) {
+ // Providers are last-wins: adding ours would silently replace theirs. They choose how to combine them.
+ context.logger.warn(
+ `Bugsee: your app already provides its own ErrorHandler, so BugseeErrorHandler was not added (it would replace ` +
+ `yours). Report from inside it instead:\n\n import { reportAngularError } from '@bugsee/angular';\n` +
+ ` handleError(error: unknown) { reportAngularError(error); /* then your handling */ }\n\n` +
+ `or wrap yours:\n\n { provide: ErrorHandler, useFactory: () => createAngularErrorHandler({ delegate: new MyHandler() }) }\n`,
+ );
+ return;
+ }
+ try {
+ await apply(
+ addRootProvider(
+ located.name,
+ ({ code, external }) =>
+ code`{ provide: ${external('ErrorHandler', '@angular/core')}, useClass: ${external('BugseeErrorHandler', '@bugsee/angular')} }`,
+ ),
+ tree,
+ context,
+ );
+ } catch (error) {
+ context.logger.warn(
+ `Bugsee: could not register BugseeErrorHandler (${(error as Error).message}). Add it to your providers ` +
+ `yourself:\n\n { provide: ErrorHandler, useClass: BugseeErrorHandler } // both from '@angular/core' / '@bugsee/angular'\n`,
+ );
+ }
+ };
+}
+
+/** package.json: the `build:bugsee` script. */
+function addBuildScript(located: Located): Rule {
+ return (tree, context) => {
+ if (!tree.exists('/package.json')) {
+ context.logger.warn(
+ `Bugsee: no package.json found, so the ${SCRIPT} script was not added. Run:\n ng build --configuration production && bugsee-angular-upload --configuration production`,
+ );
+ return;
+ }
+ const text = tree.readText('/package.json');
+ const pkg = JSON.parse(text) as { scripts?: Record };
+ if (pkg.scripts?.[SCRIPT] !== undefined) {
+ context.logger.info(`Bugsee: the ${SCRIPT} script is already there; left as it is.`);
+ return;
+ }
+ const several = located.applications > 1;
+ pkg.scripts = {
+ ...pkg.scripts,
+ [SCRIPT]:
+ `ng build${several ? ` ${located.name}` : ''} --configuration production && ` +
+ `bugsee-angular-upload${several ? ` --project ${located.name}` : ''} --configuration production`,
+ };
+ const indent = /^([ \t]+)"/m.exec(text)?.[1] ?? ' ';
+ tree.overwrite(
+ '/package.json',
+ `${JSON.stringify(pkg, null, indent)}${text.endsWith('\n') ? '\n' : ''}`,
+ );
+ };
+}
+
+/** `.env.bugsee-build-plugin` with the token for the build step, git-ignored. */
+function keepToken(token: string | undefined): Rule {
+ return (tree, context) => {
+ if (token === undefined) {
+ return;
+ }
+ if (!tree.exists(`/${ENV_FILE}`)) {
+ tree.create(`/${ENV_FILE}`, `BUGSEE_APP_TOKEN=${token}\n`);
+ } else {
+ const text = tree.readText(`/${ENV_FILE}`);
+ const existing = /^\s*BUGSEE_APP_TOKEN\s*=\s*(.*?)\s*$/m.exec(text)?.[1];
+ if (existing !== undefined && existing !== token) {
+ context.logger.warn(
+ `Bugsee: ${ENV_FILE} already has a different BUGSEE_APP_TOKEN than the one you gave, and it was left as it is. ` +
+ `launch() uses the token you gave, the source-map upload uses the file's: if they are not the same app, ` +
+ `crash reports cannot be symbolicated. Make them match.`,
+ );
+ }
+ if (!/^\s*BUGSEE_APP_TOKEN\s*=/m.test(text)) {
+ tree.overwrite(
+ `/${ENV_FILE}`,
+ `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}BUGSEE_APP_TOKEN=${token}\n`,
+ );
+ }
+ }
+ if (!tree.exists('/.gitignore')) {
+ tree.create('/.gitignore', `${ENV_FILE}\n`);
+ } else {
+ const ignored = tree.readText('/.gitignore');
+ if (!ignored.split(/\r?\n/).some((line) => line.trim() === ENV_FILE)) {
+ tree.overwrite(
+ '/.gitignore',
+ `${ignored}${ignored.endsWith('\n') ? '' : '\n'}${ENV_FILE}\n`,
+ );
+ }
+ }
+ };
+}
+
+/** Say what the build step does for this project's configuration. */
+function explain(located: Located, token: string | undefined): Rule {
+ return (_tree, context) => {
+ const effective = { ...located.options, ...located.production } as Obj;
+ context.logger.info(
+ `Bugsee: source maps are uploaded by \`npm run ${SCRIPT}\` (builder: ${located.builder ?? 'unknown'}); ` +
+ `plain \`ng build\` does not upload.`,
+ );
+ if (effective.subresourceIntegrity === true) {
+ context.logger.info(
+ `Bugsee: subresourceIntegrity is on. The upload step stamps the bundles, then the integrity hashes in ` +
+ `index.html are re-written to match, so the page keeps loading.`,
+ );
+ }
+ if (effective.serviceWorker) {
+ context.logger.info(
+ `Bugsee: serviceWorker is on. ngsw.json (one per locale) pins a SHA-1 of every file, so the upload step ` +
+ `re-computes those hashes after stamping and checks them; if one cannot be reconciled it restores the build and uploads nothing.`,
+ );
+ }
+ if (token === undefined) {
+ context.logger.warn(
+ `Bugsee: no app token was given, so launch() has the placeholder ${PLACEHOLDER}. Put your token there, and set ` +
+ `BUGSEE_APP_TOKEN (or ${ENV_FILE}) wherever you run \`npm run ${SCRIPT}\`.`,
+ );
+ }
+ };
+}
+
+export function ngAdd(options: Schema = {}): Rule {
+ return async (tree) => {
+ const located = await locate(tree, options.project);
+ const trimmed = options.appToken?.trim();
+ const token = trimmed === undefined || trimmed === '' ? undefined : trimmed;
+ if (token !== undefined && /[\s"'`#\\]/.test(token)) {
+ throw new SchematicsException(
+ 'The app token must not contain whitespace, a line break, quotes, backticks, backslashes or #.',
+ );
+ }
+ return chain([
+ enableSourceMaps(located.name),
+ instrument(located, token ?? PLACEHOLDER),
+ addBuildScript(located),
+ keepToken(token),
+ explain(located, token),
+ ]);
+ };
+}
diff --git a/packages/angular/src/schematics/ng-add/schema.json b/packages/angular/src/schematics/ng-add/schema.json
new file mode 100644
index 00000000..84e148ce
--- /dev/null
+++ b/packages/angular/src/schematics/ng-add/schema.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "http://json-schema.org/schema",
+ "$id": "BugseeAngularNgAdd",
+ "title": "Bugsee ng-add options",
+ "type": "object",
+ "properties": {
+ "project": {
+ "type": "string",
+ "description": "The application project to set up. Defaults to the workspace's only application.",
+ "$default": { "$source": "projectName" }
+ },
+ "appToken": {
+ "type": "string",
+ "description": "Your Bugsee app token. Written into the launch call and, for the build step, into .env.bugsee-build-plugin (kept out of git).",
+ "x-prompt": "Your Bugsee app token (press Enter to fill it in later):"
+ }
+ },
+ "required": []
+}
diff --git a/packages/angular/src/schematics/ng-add/schema.ts b/packages/angular/src/schematics/ng-add/schema.ts
new file mode 100644
index 00000000..d86ee5b3
--- /dev/null
+++ b/packages/angular/src/schematics/ng-add/schema.ts
@@ -0,0 +1,7 @@
+/** Options of `ng add @bugsee/angular` (see schema.json). */
+export interface Schema {
+ /** The application project to set up. Default: the workspace's only application. */
+ project?: string;
+ /** Your Bugsee app token. Empty or absent: a placeholder is written and you are told to fill it in. */
+ appToken?: string;
+}
diff --git a/packages/angular/src/sourcemaps/bin.ts b/packages/angular/src/sourcemaps/bin.ts
new file mode 100644
index 00000000..17d6754f
--- /dev/null
+++ b/packages/angular/src/sourcemaps/bin.ts
@@ -0,0 +1,12 @@
+#!/usr/bin/env node
+/* v8 ignore start -- the executable shell: the logic is in cli.ts (unit-tested); the built bin is exercised by
+ the real-build test (angular.real-build.test.ts), which runs in a child process coverage does not see. */
+import { runCli } from './cli';
+
+process.exitCode = await runCli(process.argv.slice(2), {
+ cwd: process.cwd(),
+ env: process.env,
+ stdout: (message) => process.stdout.write(message),
+ stderr: (message) => process.stderr.write(message),
+});
+/* v8 ignore stop */
diff --git a/packages/angular/src/sourcemaps/cli.test.ts b/packages/angular/src/sourcemaps/cli.test.ts
new file mode 100644
index 00000000..ccaa046b
--- /dev/null
+++ b/packages/angular/src/sourcemaps/cli.test.ts
@@ -0,0 +1,192 @@
+import { describe, expect, it, vi } from 'vitest';
+import { HELP, parseArgs, runCli } from './cli';
+import type { AngularUploadOptions, AngularUploadResult } from './upload';
+
+describe('parseArgs', () => {
+ it('reads every option, in both the spaced and the = form', () => {
+ expect(
+ parseArgs([
+ '--project',
+ 'demo',
+ '--configuration=production',
+ '--dist',
+ 'out',
+ '--output-path=moved',
+ '--app-version=1.0.0',
+ '--app-build',
+ '42',
+ '--endpoint',
+ 'https://api.test',
+ '--dry-run',
+ '--keep-maps',
+ '--fail-on-error',
+ '--strip-sources-content',
+ '--upload-in-development',
+ '--no-vcs',
+ ]),
+ ).toEqual({
+ options: {
+ project: 'demo',
+ configuration: 'production',
+ dist: 'out',
+ outputPath: 'moved',
+ appVersion: '1.0.0',
+ appBuild: '42',
+ endpoint: 'https://api.test',
+ dryRun: true,
+ deleteMaps: false,
+ failOnError: true,
+ stripSourcesContent: true,
+ uploadInDevelopment: true,
+ vcs: false,
+ },
+ });
+ });
+
+ it('accepts -c for --configuration and -h for help', () => {
+ expect(parseArgs(['-c', 'staging'])).toEqual({ options: { configuration: 'staging' } });
+ expect(parseArgs(['-h'])).toEqual({ options: {}, help: true });
+ expect(parseArgs(['--help'])).toEqual({ options: {}, help: true });
+ });
+
+ it('returns nothing for no arguments', () => {
+ expect(parseArgs([])).toEqual({ options: {} });
+ });
+
+ it('rejects an unknown flag, a missing value and a stray argument', () => {
+ expect(() => parseArgs(['--nope'])).toThrow(/unknown option "--nope"/);
+ expect(() => parseArgs(['--project'])).toThrow(/--project needs a value/);
+ expect(() => parseArgs(['--project', '--dry-run'])).toThrow(/--project needs a value/);
+ expect(() => parseArgs(['stray'])).toThrow(/unexpected argument "stray"/);
+ expect(() => parseArgs(['--dry-run=yes'])).toThrow(/--dry-run does not take a value/);
+ });
+
+ it('does not take the token on the command line', () => {
+ expect(() => parseArgs(['--app-token', 'x'])).toThrow(/BUGSEE_APP_TOKEN/);
+ });
+});
+
+describe('runCli', () => {
+ const io = () => {
+ const out: string[] = [];
+ const err: string[] = [];
+ return {
+ out,
+ err,
+ io: {
+ cwd: '/ws',
+ env: { BUGSEE_APP_TOKEN: 'tok' },
+ stdout: (m: string) => out.push(m),
+ stderr: (m: string) => err.push(m),
+ },
+ };
+ };
+ const uploaded = (over: Partial = {}) =>
+ vi.fn(
+ async (_o: AngularUploadOptions): Promise => ({
+ status: 'uploaded',
+ outDir: '/ws/dist/demo/browser',
+ configuration: 'production',
+ result: { injected: true, uploaded: true, deletedMaps: ['a.map', 'b.map'] },
+ ...over,
+ }),
+ );
+
+ it('prints the help and does not upload', async () => {
+ const { io: i, out } = io();
+ const upload = uploaded();
+ expect(await runCli(['--help'], i, upload)).toBe(0);
+ expect(out.join('')).toBe(HELP);
+ expect(upload).not.toHaveBeenCalled();
+ });
+
+ it('hands the parsed options, the working directory and the environment to the upload', async () => {
+ const { io: i } = io();
+ const upload = uploaded();
+ await runCli(['--project', 'demo', '--dry-run'], i, upload);
+ expect(upload).toHaveBeenCalledWith({
+ project: 'demo',
+ dryRun: true,
+ cwd: '/ws',
+ env: { BUGSEE_APP_TOKEN: 'tok' },
+ });
+ });
+
+ it('reports what was uploaded and how many maps were removed', async () => {
+ const { io: i, out } = io();
+ expect(await runCli([], i, uploaded())).toBe(0);
+ expect(out.join('')).toContain('uploaded the source maps of /ws/dist/demo/browser');
+ expect(out.join('')).toContain('removed 2 local map(s)');
+ });
+
+ it('reports a dry run as checked, and a kept-maps upload without a removal count', async () => {
+ const { io: i, out } = io();
+ await runCli(
+ ['--dry-run'],
+ i,
+ uploaded({ result: { injected: true, uploaded: false, deletedMaps: [] } }),
+ );
+ expect(out.join('')).toContain('dry run: checked the source maps');
+ expect(out.join('')).not.toContain('uploaded the source maps');
+ const kept = io();
+ await runCli(
+ ['--keep-maps'],
+ kept.io,
+ uploaded({ result: { injected: true, uploaded: true, deletedMaps: [] } }),
+ );
+ expect(kept.out.join('')).toBe('[bugsee] uploaded the source maps of /ws/dist/demo/browser.\n');
+ });
+
+ it('says the upload did not complete when the pipeline contained a failure (already reported)', async () => {
+ const { io: i, out, err } = io();
+ expect(
+ await runCli(
+ [],
+ i,
+ uploaded({ result: { injected: false, uploaded: false, deletedMaps: [] } }),
+ ),
+ ).toBe(0);
+ expect(out.join('')).toBe('');
+ expect(err.join('')).toContain('did not complete');
+ });
+
+ it('is quiet for a skipped, disabled or misconfigured run, whose notice was already printed', async () => {
+ for (const status of ['skipped', 'disabled', 'misconfigured'] as const) {
+ const { io: i, out, err } = io();
+ const { result: _drop, ...rest } = (await uploaded()({})) as AngularUploadResult;
+ expect(
+ await runCli(
+ [],
+ i,
+ vi.fn(async () => ({ ...rest, status })),
+ ),
+ ).toBe(0);
+ expect(out.join('') + err.join('')).toBe('');
+ }
+ });
+
+ it('exits 1 with the message on an error', async () => {
+ const { io: i, err } = io();
+ const upload = vi.fn(async () => {
+ throw new Error('boom');
+ });
+ expect(await runCli([], i, upload)).toBe(1);
+ expect(err.join('')).toContain('[bugsee] boom');
+ });
+
+ it('exits 2 on a usage error, with the help hint', async () => {
+ const { io: i, err } = io();
+ expect(await runCli(['--nope'], i, uploaded())).toBe(2);
+ expect(err.join('')).toContain('unknown option');
+ expect(err.join('')).toContain('--help');
+ });
+
+ it('reports a non-Error throw', async () => {
+ const { io: i, err } = io();
+ const upload = vi.fn(async () => {
+ throw 'plain';
+ });
+ expect(await runCli([], i, upload)).toBe(1);
+ expect(err.join('')).toContain('plain');
+ });
+});
diff --git a/packages/angular/src/sourcemaps/cli.ts b/packages/angular/src/sourcemaps/cli.ts
new file mode 100644
index 00000000..c93d8458
--- /dev/null
+++ b/packages/angular/src/sourcemaps/cli.ts
@@ -0,0 +1,140 @@
+// The `bugsee-angular-upload` command: argument parsing and reporting around uploadAngularSourcemaps. Kept free of
+// process globals (the bin passes them in) so it is unit-tested; bin.ts is the three-line shell around it.
+import {
+ type AngularUploadOptions,
+ type AngularUploadResult,
+ uploadAngularSourcemaps,
+} from './upload';
+
+export const HELP = `bugsee-angular-upload — upload the source maps of an Angular build to Bugsee.
+
+Run it after \`ng build\` (the \`build:bugsee\` script that \`ng add @bugsee/angular\` adds does both):
+
+ ng build && bugsee-angular-upload
+
+It stamps debug-IDs into the bundles in dist//browser, uploads the maps, registers the build and
+removes the local maps. The app token comes from BUGSEE_APP_TOKEN or .env.bugsee-build-plugin.
+
+Options
+ --project Application project (default: the only application in angular.json)
+ -c, --configuration The ng build configuration the output came from (default: the target's default)
+ --dist The browser output directory, when it is not where angular.json says
+ --output-path What you gave ng build --output-path (browser/ below it is used when present)
+ --app-version App version (default: BUGSEE_APP_VERSION, then package.json)
+ --app-build Build number (default: BUGSEE_APP_BUILD, then the CI commit)
+ --endpoint API endpoint (default: BUGSEE_ENDPOINT)
+ --dry-run Run the whole flow without uploading or deleting anything
+ --keep-maps Keep the local .map files after uploading
+ --strip-sources-content Upload maps without their embedded source
+ --fail-on-error Exit non-zero when the upload fails (default: warn and exit 0)
+ --upload-in-development Also upload from a development configuration
+ --no-vcs Do not capture the commit / branch
+ -h, --help Show this help
+`;
+
+type Options = AngularUploadOptions;
+
+const VALUE_FLAGS: Record = {
+ '--project': 'project',
+ '--configuration': 'configuration',
+ '-c': 'configuration',
+ '--dist': 'dist',
+ '--output-path': 'outputPath',
+ '--app-version': 'appVersion',
+ '--app-build': 'appBuild',
+ '--endpoint': 'endpoint',
+};
+
+const SWITCHES: Record = {
+ '--dry-run': ['dryRun', true],
+ '--keep-maps': ['deleteMaps', false],
+ '--strip-sources-content': ['stripSourcesContent', true],
+ '--fail-on-error': ['failOnError', true],
+ '--upload-in-development': ['uploadInDevelopment', true],
+ '--no-vcs': ['vcs', false],
+};
+
+/** Parse argv (without the node and script entries). Throws a usage error for anything it does not know. */
+export function parseArgs(argv: readonly string[]): { options: Options; help?: true } {
+ const options: Record = {};
+ let help = false;
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i] as string;
+ const eq = arg.startsWith('--') ? arg.indexOf('=') : -1;
+ const flag = eq === -1 ? arg : arg.slice(0, eq);
+ if (flag === '-h' || flag === '--help') {
+ help = true;
+ } else if (flag === '--app-token') {
+ throw new Error(
+ 'the app token is not taken on the command line (it would land in shell history): set BUGSEE_APP_TOKEN',
+ );
+ } else if (flag in VALUE_FLAGS) {
+ const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
+ if (value === undefined || value.startsWith('-')) {
+ throw new Error(`${flag} needs a value`);
+ }
+ options[VALUE_FLAGS[flag] as string] = value;
+ } else if (flag in SWITCHES) {
+ if (eq !== -1) {
+ throw new Error(`${flag} does not take a value`);
+ }
+ const [key, value] = SWITCHES[flag] as [string, boolean];
+ options[key] = value;
+ } else if (arg.startsWith('-')) {
+ throw new Error(`unknown option "${flag}"`);
+ } else {
+ throw new Error(`unexpected argument "${arg}"`);
+ }
+ }
+ return help ? { options: options as Options, help: true } : { options: options as Options };
+}
+
+export interface CliIo {
+ cwd: string;
+ env: Record;
+ stdout(message: string): void;
+ stderr(message: string): void;
+}
+
+/** Run the command. Resolves to the process exit code: 0 done, 1 failed, 2 misused. */
+export async function runCli(
+ argv: readonly string[],
+ io: CliIo,
+ upload: (options: Options) => Promise = uploadAngularSourcemaps,
+): Promise {
+ let parsed: { options: Options; help?: true };
+ try {
+ parsed = parseArgs(argv);
+ } catch (error) {
+ io.stderr(`[bugsee] ${(error as Error).message}\nRun with --help for the options.\n`);
+ return 2;
+ }
+ if (parsed.help) {
+ io.stdout(HELP);
+ return 0;
+ }
+ try {
+ const out = await upload({ ...parsed.options, cwd: io.cwd, env: io.env });
+ if (out.status === 'uploaded') {
+ if (parsed.options.dryRun === true) {
+ io.stdout(
+ `[bugsee] dry run: checked the source maps of ${out.outDir}; nothing was uploaded or removed.\n`,
+ );
+ } else if (out.result?.uploaded === true) {
+ const removed = out.result.deletedMaps.length;
+ io.stdout(
+ `[bugsee] uploaded the source maps of ${out.outDir}` +
+ (removed > 0 ? `; removed ${removed} local map(s).\n` : '.\n'),
+ );
+ } else {
+ io.stderr(
+ `[bugsee] the source-map upload of ${out.outDir} did not complete (see above).\n`,
+ );
+ }
+ }
+ return 0;
+ } catch (error) {
+ io.stderr(`[bugsee] ${error instanceof Error ? error.message : String(error)}\n`);
+ return 1;
+ }
+}
diff --git a/packages/angular/src/sourcemaps/index.ts b/packages/angular/src/sourcemaps/index.ts
new file mode 100644
index 00000000..9ee54b58
--- /dev/null
+++ b/packages/angular/src/sourcemaps/index.ts
@@ -0,0 +1,14 @@
+// @bugsee/angular/sourcemaps — upload the source maps of an Angular build. Node-only: it is a build-time entry
+// and is never imported by the runtime entry (`@bugsee/angular`), so it cannot reach a browser bundle.
+export { type CliIo, HELP, parseArgs, runCli } from './cli';
+export {
+ type AngularOutput,
+ type ResolveAngularOutputOptions,
+ resolveAngularOutput,
+} from './output';
+export {
+ type AngularUploadDeps,
+ type AngularUploadOptions,
+ type AngularUploadResult,
+ uploadAngularSourcemaps,
+} from './upload';
diff --git a/packages/angular/src/sourcemaps/jsonc.test.ts b/packages/angular/src/sourcemaps/jsonc.test.ts
new file mode 100644
index 00000000..c3c868f5
--- /dev/null
+++ b/packages/angular/src/sourcemaps/jsonc.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+import { parseJsonc } from './jsonc';
+
+describe('parseJsonc', () => {
+ it('parses plain JSON', () => {
+ expect(parseJsonc('{"a":[1,2,{"b":null}]}')).toEqual({ a: [1, 2, { b: null }] });
+ });
+
+ it('ignores line and block comments, as angular.json allows', () => {
+ const text = `{
+ // the project
+ "a": 1, /* inline */ "b": 2
+ /* trailing
+ block */
+ }`;
+ expect(parseJsonc(text)).toEqual({ a: 1, b: 2 });
+ });
+
+ it('leaves comment-looking text inside a string alone, including an escaped quote before it', () => {
+ expect(parseJsonc('{"url":"http://x/*y*/","q":"a\\"//b"}')).toEqual({
+ url: 'http://x/*y*/',
+ q: 'a"//b',
+ });
+ });
+
+ it('accepts trailing commas', () => {
+ expect(parseJsonc('{"a":[1,2,],}')).toEqual({ a: [1, 2] });
+ });
+
+ it('keeps a comma that is followed by a value, and one inside a string', () => {
+ expect(parseJsonc('{"a":"x,]","b":[1,2]}')).toEqual({ a: 'x,]', b: [1, 2] });
+ });
+
+ it('strips a byte-order mark', () => {
+ expect(parseJsonc('{"a":1}')).toEqual({ a: 1 });
+ });
+
+ it('throws on text that is not JSON once the comments are gone', () => {
+ expect(() => parseJsonc('{"a":')).toThrow();
+ });
+
+ it('treats an unterminated block comment as running to the end', () => {
+ expect(parseJsonc('{"a":1} /* never closed')).toEqual({ a: 1 });
+ });
+});
diff --git a/packages/angular/src/sourcemaps/jsonc.ts b/packages/angular/src/sourcemaps/jsonc.ts
new file mode 100644
index 00000000..f5317a88
--- /dev/null
+++ b/packages/angular/src/sourcemaps/jsonc.ts
@@ -0,0 +1,40 @@
+// A small JSON-with-comments reader for `angular.json`, which Angular's own tooling accepts with `//` and
+// `/* */` comments and trailing commas. Reading only: the schematic edits through Angular's workspace API,
+// which preserves the file. Kept here so the upload tool needs no Angular dependency at run time.
+
+/** Remove comments and trailing commas, leaving string contents untouched. */
+function strip(text: string): string {
+ let out = '';
+ let i = text.charCodeAt(0) === 0xfeff ? 1 : 0;
+ while (i < text.length) {
+ const ch = text[i] as string;
+ if (ch === '"') {
+ let j = i + 1;
+ while (j < text.length && text[j] !== '"') {
+ j += text[j] === '\\' ? 2 : 1;
+ }
+ out += text.slice(i, j + 1);
+ i = j + 1;
+ } else if (ch === '/' && text[i + 1] === '/') {
+ while (i < text.length && text[i] !== '\n') {
+ i++;
+ }
+ } else if (ch === '/' && text[i + 1] === '*') {
+ const end = text.indexOf('*/', i + 2);
+ i = end === -1 ? text.length : end + 2;
+ } else {
+ out += ch;
+ i++;
+ }
+ }
+ // A comma directly before `]` or `}` (whitespace between is fine). Strings are matched first so a comma
+ // inside one is never touched.
+ return out.replace(/"(?:[^"\\]|\\.)*"|,(\s*[\]}])/g, (match, tail?: string) =>
+ tail === undefined ? match : tail,
+ );
+}
+
+/** Parse JSON that may carry comments and trailing commas. Throws on anything else that is not JSON. */
+export function parseJsonc(text: string): unknown {
+ return JSON.parse(strip(text));
+}
diff --git a/packages/angular/src/sourcemaps/output.test.ts b/packages/angular/src/sourcemaps/output.test.ts
new file mode 100644
index 00000000..3de93cec
--- /dev/null
+++ b/packages/angular/src/sourcemaps/output.test.ts
@@ -0,0 +1,251 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { resolveAngularOutput } from './output';
+
+let cwd: string;
+beforeEach(async () => {
+ cwd = await mkdtemp(join(tmpdir(), 'bugsee-ng-out-'));
+});
+afterEach(async () => {
+ await rm(cwd, { recursive: true, force: true });
+});
+
+const workspace = async (
+ projects: Record,
+ extra: Record = {},
+) => {
+ await writeFile(join(cwd, 'angular.json'), JSON.stringify({ version: 1, projects, ...extra }));
+};
+
+const app = (build: unknown, over: Record = {}) => ({
+ projectType: 'application',
+ root: '',
+ architect: { build },
+ ...over,
+});
+
+describe('resolveAngularOutput', () => {
+ it('finds the browser directory of an esbuild application build under dist/', async () => {
+ await workspace({ demo: app({ builder: '@angular/build:application', options: {} }) });
+ expect(resolveAngularOutput({ cwd })).toEqual({
+ project: 'demo',
+ builder: '@angular/build:application',
+ layout: 'application',
+ configuration: undefined,
+ baseDir: join(cwd, 'dist', 'demo'),
+ browserDir: join(cwd, 'dist', 'demo', 'browser'),
+ serverDir: join(cwd, 'dist', 'demo', 'server'),
+ });
+ });
+
+ it('treats the legacy @angular-devkit/build-angular:application builder the same way', async () => {
+ await workspace({
+ demo: app({
+ builder: '@angular-devkit/build-angular:application',
+ options: { outputPath: 'out/x' },
+ }),
+ });
+ const out = resolveAngularOutput({ cwd });
+ expect(out.layout).toBe('application');
+ expect(out.browserDir).toBe(join(cwd, 'out', 'x', 'browser'));
+ });
+
+ it('honours the object form of outputPath, including an empty browser folder', async () => {
+ await workspace({
+ demo: app({
+ builder: '@angular/build:application',
+ options: { outputPath: { base: 'out', browser: '', server: 'srv' } },
+ }),
+ });
+ const out = resolveAngularOutput({ cwd });
+ expect(out.browserDir).toBe(join(cwd, 'out'));
+ expect(out.serverDir).toBe(join(cwd, 'out', 'srv'));
+ });
+
+ it('defaults the browser and server folders when the object form leaves them out', async () => {
+ await workspace({
+ demo: app({
+ builder: '@angular/build:application',
+ options: { outputPath: { base: 'out' } },
+ }),
+ });
+ const out = resolveAngularOutput({ cwd });
+ expect(out.browserDir).toBe(join(cwd, 'out', 'browser'));
+ expect(out.serverDir).toBe(join(cwd, 'out', 'server'));
+ });
+
+ it('uses the outputPath of the chosen configuration over the options', async () => {
+ await workspace({
+ demo: app({
+ builder: '@angular/build:application',
+ options: { outputPath: 'dist/base' },
+ configurations: { production: { outputPath: 'dist/prod' } },
+ defaultConfiguration: 'production',
+ }),
+ });
+ expect(resolveAngularOutput({ cwd }).browserDir).toBe(join(cwd, 'dist', 'prod', 'browser'));
+ expect(resolveAngularOutput({ cwd }).configuration).toBe('production');
+ });
+
+ it('prefers an explicit configuration to the default, and merges a comma list in order', async () => {
+ await workspace({
+ demo: app({
+ builder: '@angular/build:application',
+ options: {},
+ configurations: {
+ production: { outputPath: 'dist/prod' },
+ staging: { outputPath: 'dist/stage' },
+ other: {},
+ },
+ defaultConfiguration: 'production',
+ }),
+ });
+ expect(resolveAngularOutput({ cwd, configuration: 'staging' }).baseDir).toBe(
+ join(cwd, 'dist', 'stage'),
+ );
+ expect(resolveAngularOutput({ cwd, configuration: 'production,other' }).baseDir).toBe(
+ join(cwd, 'dist', 'prod'),
+ );
+ expect(resolveAngularOutput({ cwd, configuration: 'production,staging' }).baseDir).toBe(
+ join(cwd, 'dist', 'stage'),
+ );
+ });
+
+ it('ignores a configuration name the target does not define', async () => {
+ await workspace({ demo: app({ builder: '@angular/build:application', options: {} }) });
+ expect(resolveAngularOutput({ cwd, configuration: 'nope' }).baseDir).toBe(
+ join(cwd, 'dist', 'demo'),
+ );
+ });
+
+ it('uses the flat output of a webpack browser build, which has no browser subfolder', async () => {
+ await workspace({
+ demo: app({
+ builder: '@angular-devkit/build-angular:browser',
+ options: { outputPath: 'dist/legacy' },
+ }),
+ });
+ expect(resolveAngularOutput({ cwd })).toEqual({
+ project: 'demo',
+ builder: '@angular-devkit/build-angular:browser',
+ layout: 'flat',
+ configuration: undefined,
+ baseDir: join(cwd, 'dist', 'legacy'),
+ browserDir: join(cwd, 'dist', 'legacy'),
+ });
+ });
+
+ it('reads the base of an object outputPath for a flat builder, and defaults to dist/', async () => {
+ await workspace({
+ a: app({
+ builder: '@angular-devkit/build-angular:browser',
+ options: { outputPath: { base: 'x' } },
+ }),
+ b: app({ builder: '@angular-devkit/build-angular:browser', options: {} }),
+ });
+ expect(resolveAngularOutput({ cwd, project: 'a' }).browserDir).toBe(join(cwd, 'x'));
+ expect(resolveAngularOutput({ cwd, project: 'b' }).browserDir).toBe(join(cwd, 'dist', 'b'));
+ });
+
+ it("reads the `targets` spelling of a project's targets (Angular accepts it beside `architect`)", async () => {
+ await writeFile(
+ join(cwd, 'angular.json'),
+ JSON.stringify({
+ projects: {
+ demo: {
+ projectType: 'application',
+ root: '',
+ targets: {
+ build: { builder: '@angular/build:application', options: { outputPath: 'out' } },
+ },
+ },
+ },
+ }),
+ );
+ expect(resolveAngularOutput({ cwd }).browserDir).toBe(join(cwd, 'out', 'browser'));
+ });
+
+ it('treats a target with no builder as flat', async () => {
+ await workspace({ demo: app({ options: {} }) });
+ const out = resolveAngularOutput({ cwd });
+ expect(out.layout).toBe('flat');
+ expect(out.builder).toBeUndefined();
+ });
+
+ it('keeps an absolute outputPath as it is', async () => {
+ const abs = join(cwd, 'elsewhere');
+ await workspace({
+ demo: app({ builder: '@angular-devkit/build-angular:browser', options: { outputPath: abs } }),
+ });
+ expect(resolveAngularOutput({ cwd }).browserDir).toBe(abs);
+ });
+
+ it('picks the only application project, ignoring libraries', async () => {
+ await workspace({
+ lib: { projectType: 'library', root: 'projects/lib', architect: { build: {} } },
+ demo: app({ builder: '@angular/build:application', options: {} }),
+ });
+ expect(resolveAngularOutput({ cwd }).project).toBe('demo');
+ });
+
+ it('asks for --project when several applications exist, naming them', async () => {
+ await workspace({
+ one: app({ builder: '@angular/build:application', options: {} }),
+ two: app({ builder: '@angular/build:application', options: {} }),
+ });
+ expect(() => resolveAngularOutput({ cwd })).toThrow(/--project.*one, two/);
+ });
+
+ it('uses the legacy defaultProject when several applications exist', async () => {
+ await workspace(
+ {
+ one: app({ builder: '@angular/build:application', options: {} }),
+ two: app({ builder: '@angular/build:application', options: {} }),
+ },
+ { defaultProject: 'two' },
+ );
+ expect(resolveAngularOutput({ cwd }).project).toBe('two');
+ });
+
+ it('rejects a project that is not in the workspace, listing what is', async () => {
+ await workspace({ demo: app({ builder: '@angular/build:application', options: {} }) });
+ expect(() => resolveAngularOutput({ cwd, project: 'nope' })).toThrow(/"nope".*demo/);
+ });
+
+ it('rejects a workspace with no application and a project with no build target', async () => {
+ await workspace({ lib: { projectType: 'library', root: 'x', architect: {} } });
+ expect(() => resolveAngularOutput({ cwd })).toThrow(/no application project/);
+ await workspace({ demo: { projectType: 'application', root: '', architect: {} } });
+ expect(() => resolveAngularOutput({ cwd })).toThrow(/no "build" target/);
+ await workspace({ demo: { projectType: 'application', root: '' } });
+ expect(() => resolveAngularOutput({ cwd })).toThrow(/no "build" target/);
+ });
+
+ it('says how to proceed when there is no angular.json, and when it is not parseable', async () => {
+ expect(() => resolveAngularOutput({ cwd })).toThrow(/angular\.json.*--dist/);
+ await writeFile(join(cwd, 'angular.json'), '{ nope');
+ expect(() => resolveAngularOutput({ cwd })).toThrow(/could not read.*angular\.json/);
+ });
+
+ it('finds angular.json in a parent directory of the working directory', async () => {
+ await workspace({ demo: app({ builder: '@angular/build:application', options: {} }) });
+ const nested = join(cwd, 'projects', 'demo');
+ await mkdir(nested, { recursive: true });
+ expect(resolveAngularOutput({ cwd: nested }).browserDir).toBe(
+ join(cwd, 'dist', 'demo', 'browser'),
+ );
+ });
+
+ it('reads an angular.json with comments', async () => {
+ await writeFile(
+ join(cwd, 'angular.json'),
+ `{ // c
+ "projects": { "demo": { "projectType": "application", "root": "",
+ "architect": { "build": { "builder": "@angular/build:application", "options": {}, }, }, }, },
+ }`,
+ );
+ expect(resolveAngularOutput({ cwd }).project).toBe('demo');
+ });
+});
diff --git a/packages/angular/src/sourcemaps/output.ts b/packages/angular/src/sourcemaps/output.ts
new file mode 100644
index 00000000..085d659f
--- /dev/null
+++ b/packages/angular/src/sourcemaps/output.ts
@@ -0,0 +1,140 @@
+// Where `ng build` writes its browser bundles, read from angular.json — so the upload step needs no path
+// from the user. The layouts are Angular's own (checked against @angular/build 22's `application` schema):
+// - `application` builders (esbuild; `@angular/build:application`, `@angular-devkit/build-angular:application`):
+// `outputPath` is a string (the base) or `{ base, browser, server, media }`; the browser bundles are in
+// `/` and an SSR server in `/`.
+// - everything else (the webpack `browser` builder, `browser-esbuild`): `outputPath` IS the browser directory.
+// The default base is `dist/`.
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, isAbsolute, join, resolve } from 'node:path';
+import { parseJsonc } from './jsonc';
+
+export interface AngularOutput {
+ project: string;
+ builder: string | undefined;
+ layout: 'application' | 'flat';
+ /** The configuration(s) the output was resolved under (`undefined`: none). */
+ configuration: string | undefined;
+ /** The build's output root: the browser directory, plus the server directory of an SSR build. */
+ baseDir: string;
+ /** Where the browser bundles (and `index.html`) are. */
+ browserDir: string;
+ /** Where an SSR build's server bundles would be. Application builders only; it may not exist. */
+ serverDir?: string;
+}
+
+export interface ResolveAngularOutputOptions {
+ /** The directory the command runs in; angular.json is looked for here and in its parents. */
+ cwd: string;
+ /** Application project name. Default: the only application, or the legacy `defaultProject`. */
+ project?: string;
+ /** `ng build --configuration`: one name or a comma list. Default: the target's `defaultConfiguration`. */
+ configuration?: string;
+}
+
+type Json = Record;
+
+const APPLICATION_BUILDERS = new Set([
+ '@angular/build:application',
+ '@angular-devkit/build-angular:application',
+]);
+
+function findWorkspaceFile(cwd: string): string | undefined {
+ for (let dir = resolve(cwd); ; dir = dirname(dir)) {
+ const candidate = join(dir, 'angular.json');
+ if (existsSync(candidate)) {
+ return candidate;
+ }
+ if (dirname(dir) === dir) {
+ return undefined;
+ }
+ }
+}
+
+function readWorkspace(cwd: string): { file: string; json: Json } {
+ const file = findWorkspaceFile(cwd);
+ if (file === undefined) {
+ throw new Error(
+ `no angular.json found in ${cwd} or above. Run this from your Angular workspace, or give the build output ` +
+ `directory yourself with --dist.`,
+ );
+ }
+ try {
+ return { file, json: parseJsonc(readFileSync(file, 'utf8')) as Json };
+ } catch (error) {
+ throw new Error(`could not read ${file}: ${String(error)}`);
+ }
+}
+
+function pickProject(json: Json, requested: string | undefined): string {
+ const projects = (json.projects ?? {}) as Record;
+ const names = Object.keys(projects);
+ if (requested !== undefined) {
+ if (!(requested in projects)) {
+ throw new Error(`the workspace has no project "${requested}" (it has: ${names.join(', ')})`);
+ }
+ return requested;
+ }
+ const apps = names.filter((name) => projects[name]?.projectType === 'application');
+ if (apps.length === 0) {
+ throw new Error('the workspace has no application project to upload source maps for');
+ }
+ const legacyDefault = json.defaultProject;
+ if (typeof legacyDefault === 'string' && apps.includes(legacyDefault)) {
+ return legacyDefault;
+ }
+ if (apps.length > 1) {
+ throw new Error(
+ `the workspace has several applications; pick one with --project (${apps.join(', ')})`,
+ );
+ }
+ return apps[0] as string;
+}
+
+/** Work out where `ng build` writes the browser bundles of a project, from angular.json. */
+export function resolveAngularOutput(options: ResolveAngularOutputOptions): AngularOutput {
+ const { file, json } = readWorkspace(options.cwd);
+ const root = dirname(file);
+ const project = pickProject(json, options.project);
+ const entry = (json.projects as Record)[project] as Json;
+ // Angular accepts `targets` as a spelling of `architect`.
+ const target = ((entry.architect ?? entry.targets) as Json | undefined)?.build as
+ | Json
+ | undefined;
+ if (target === undefined) {
+ throw new Error(`project "${project}" has no "build" target`);
+ }
+ const builder = target.builder as string | undefined;
+ const configurations = (target.configurations ?? {}) as Record;
+ const chosen =
+ options.configuration ??
+ (typeof target.defaultConfiguration === 'string' ? target.defaultConfiguration : undefined);
+ let merged: Json = { ...(target.options as Json | undefined) };
+ for (const name of chosen?.split(',') ?? []) {
+ merged = { ...merged, ...configurations[name.trim()] };
+ }
+
+ const layout =
+ builder !== undefined && APPLICATION_BUILDERS.has(builder) ? 'application' : 'flat';
+ const outputPath = merged.outputPath as
+ | string
+ | { base: string; browser?: string; server?: string }
+ | undefined;
+ const base =
+ typeof outputPath === 'string' ? outputPath : (outputPath?.base ?? join('dist', project));
+ const baseDir = isAbsolute(base) ? base : join(root, base);
+ if (layout === 'flat') {
+ return { project, builder, layout, configuration: chosen, baseDir, browserDir: baseDir };
+ }
+ const parts: { browser?: string; server?: string } =
+ typeof outputPath === 'object' ? outputPath : {};
+ return {
+ project,
+ builder,
+ layout,
+ configuration: chosen,
+ baseDir,
+ browserDir: join(baseDir, parts.browser ?? 'browser'),
+ serverDir: join(baseDir, parts.server ?? 'server'),
+ };
+}
diff --git a/packages/angular/src/sourcemaps/server-root.test.ts b/packages/angular/src/sourcemaps/server-root.test.ts
new file mode 100644
index 00000000..2a924515
--- /dev/null
+++ b/packages/angular/src/sourcemaps/server-root.test.ts
@@ -0,0 +1,257 @@
+import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, win32 } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { findServerRoot, isStrictlyInside } from './server-root';
+import { uploadAngularSourcemaps } from './upload';
+
+let cwd: string;
+beforeEach(async () => {
+ cwd = await mkdtemp(join(tmpdir(), 'bugsee-ng-root-'));
+});
+afterEach(async () => {
+ await rm(cwd, { recursive: true, force: true });
+});
+const dir = (rel: string) => mkdir(join(cwd, rel), { recursive: true });
+const file = async (rel: string) => {
+ await dir(join(rel, '..'));
+ await writeFile(join(cwd, rel), 'x();');
+};
+
+describe('isStrictlyInside', () => {
+ it('is true for a descendant, false for the directory itself, a parent, a sibling and another drive', () => {
+ expect(isStrictlyInside('/p/a/b', '/p')).toBe(true);
+ expect(isStrictlyInside('/p', '/p')).toBe(false);
+ expect(isStrictlyInside('/', '/p')).toBe(false);
+ expect(isStrictlyInside('/q/a', '/p')).toBe(false);
+ });
+
+ it('a directory whose name merely starts with two dots is inside', () => {
+ expect(isStrictlyInside('/p/..out/browser', '/p')).toBe(true);
+ });
+
+ it('on Windows a different drive is not inside (relative() answers with an absolute path)', () => {
+ expect(isStrictlyInside('D:\\out\\app', 'C:\\proj', win32)).toBe(false);
+ expect(isStrictlyInside('C:\\proj\\out\\app', 'C:\\proj', win32)).toBe(true);
+ });
+});
+
+describe('findServerRoot', () => {
+ it('finds the output root of an application build from its browser directory', async () => {
+ await file('o/browser/main.js');
+ await dir('o/server');
+ expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toEqual({
+ root: join(cwd, 'o'),
+ browser: join(cwd, 'o/browser'),
+ });
+ });
+
+ it('finds it from a locale directory of a localized build', async () => {
+ await file('o/browser/fr/main.js');
+ await dir('o/server/fr');
+ expect(findServerRoot(join(cwd, 'o/browser/fr'), cwd)).toEqual({
+ root: join(cwd, 'o'),
+ browser: join(cwd, 'o/browser'),
+ });
+ });
+
+ it('does not take an unrelated server/ for the output root, and says it could not tell', async () => {
+ await file('o/dist/main.js');
+ await file('o/server/server.mjs');
+ const found = findServerRoot(join(cwd, 'o/dist'), cwd);
+ expect(found).toMatchObject({ notice: expect.stringContaining('browser') });
+ expect((found as { notice: string }).notice).toMatch(/browser\/ name/);
+ });
+
+ it('a custom browser directory name (outputPath.browser) is not guessed: it is said', async () => {
+ await file('o/client/fr/main.js');
+ await file('o/server/fr/main.server.mjs');
+ expect(findServerRoot(join(cwd, 'o/client/fr'), cwd)).toMatchObject({
+ notice: expect.stringContaining('o/server'),
+ });
+ });
+
+ // A server/ that is not an Angular SSR output is nobody's business: no notice on every CI run.
+ it('says nothing about a hand-written server/ (Express beside Angular) or a backend next to a client dist', async () => {
+ await file('server/index.js'); // project root server/
+ await file('dist/main.js');
+ expect(findServerRoot(join(cwd, 'dist'), cwd)).toBeUndefined();
+ await file('apps/dist/client/main.js');
+ await file('apps/dist/server/app.js'); // a backend build, no Angular server markers
+ expect(findServerRoot(join(cwd, 'apps/dist/client'), cwd)).toBeUndefined();
+ });
+
+ it.each([
+ 'server.mjs',
+ 'main.server.mjs',
+ 'index.server.html',
+ 'angular-app-manifest.mjs',
+ 'angular-app-engine-manifest.mjs',
+ ])('recognises an Angular server output by %s', async (marker) => {
+ await file('o/client/main.js');
+ await file(`o/server/${marker}`);
+ expect(findServerRoot(join(cwd, 'o/client'), cwd)).toMatchObject({
+ notice: expect.any(String),
+ });
+ });
+
+ it.skipIf(process.getuid?.() === 0)(
+ 'an unreadable server/ is not taken for an Angular one',
+ async () => {
+ await file('o/client/main.js');
+ await file('o/server/server.mjs');
+ await chmod(join(cwd, 'o/server'), 0o000);
+ try {
+ expect(findServerRoot(join(cwd, 'o/client'), cwd)).toBeUndefined();
+ } finally {
+ await chmod(join(cwd, 'o/server'), 0o755);
+ }
+ },
+ );
+
+ it('an unmatched server/ outside the project is not reported either', async () => {
+ const outside = await mkdtemp(join(tmpdir(), 'bugsee-ng-outside2-'));
+ try {
+ await mkdir(join(outside, 'server'));
+ await writeFile(join(outside, 'server', 'server.mjs'), '');
+ await mkdir(join(outside, 'client'));
+ expect(findServerRoot(join(outside, 'client'), cwd)).toBeUndefined();
+ } finally {
+ await rm(outside, { recursive: true, force: true });
+ }
+ });
+
+ it('names the NEAREST unmatched server/ when two levels both have one', async () => {
+ await file('o/x/y/main.js');
+ await file('o/x/server/server.mjs');
+ await file('o/server/server.mjs');
+ const found = findServerRoot(join(cwd, 'o/x/y'), cwd) as { notice: string };
+ expect(found.notice).toContain(join(cwd, 'o/x/server'));
+ expect(found.notice).not.toContain(join(cwd, 'o/server'));
+ });
+
+ it('looks at most two levels up: a root three levels above is not found', async () => {
+ await file('o/browser/a/b/main.js');
+ await file('o/server/server.mjs');
+ expect(findServerRoot(join(cwd, 'o/browser/a/b'), cwd)).toBeUndefined();
+ });
+
+ it('finds nothing without a server/', async () => {
+ await file('o/browser/fr/main.js');
+ expect(findServerRoot(join(cwd, 'o/browser/fr'), cwd)).toBeUndefined();
+ expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toBeUndefined();
+ });
+
+ it('does not follow a symlinked server/, and says nothing', async () => {
+ await file('o/browser/main.js');
+ await dir('elsewhere');
+ await symlink(join(cwd, 'elsewhere'), join(cwd, 'o/server'));
+ expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toBeUndefined();
+ });
+
+ it('works under a directory whose name starts with two dots', async () => {
+ await file('..out/browser/main.js');
+ await dir('..out/server');
+ expect(findServerRoot(join(cwd, '..out/browser'), cwd)).toEqual({
+ root: join(cwd, '..out'),
+ browser: join(cwd, '..out/browser'),
+ });
+ });
+
+ it('says it cannot widen when the output root is the project root, instead of re-sealing the project', async () => {
+ await file('browser/main.js');
+ await dir('server');
+ const found = findServerRoot(join(cwd, 'browser'), cwd);
+ expect(found).toMatchObject({ notice: expect.stringContaining('server') });
+ expect((found as { notice: string }).notice).toMatch(/--output-path/);
+ });
+
+ it('says so when the output root is outside the project', async () => {
+ const outside = await mkdtemp(join(tmpdir(), 'bugsee-ng-outside-'));
+ try {
+ await mkdir(join(outside, 'browser'));
+ await mkdir(join(outside, 'server'));
+ const found = findServerRoot(join(outside, 'browser'), cwd);
+ expect(found).toMatchObject({ notice: expect.stringContaining('outside') });
+ } finally {
+ await rm(outside, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('uploadAngularSourcemaps: the server pages are re-sealed whichever way the output is named', () => {
+ const ran = () =>
+ vi.fn(async (_r: unknown, _d: string, _deps: Record) => ({
+ injected: true,
+ uploaded: true,
+ deletedMaps: [],
+ }));
+ const base = (extra: Record, notices: string[] = []) => ({
+ cwd,
+ appToken: 'tok',
+ vcs: false,
+ env: {},
+ onNotice: (m: string) => notices.push(m),
+ ...extra,
+ });
+ const build = async () => {
+ await file('o/browser/fr/main.js');
+ await file('o/browser/fr/main.js.map');
+ await dir('o/server/fr');
+ };
+
+ it('--dist /', async () => {
+ await build();
+ const run = ran();
+ await uploadAngularSourcemaps(base({ dist: 'o/browser/fr' }), { runPluginUpload: run });
+ // Only the stamped locale and ITS server counterpart: Angular emits byte-identical shared scripts into every
+ // locale, so re-sealing the whole root would pin never-stamped scripts of the other locales to stamped digests.
+ expect(run.mock.calls[0]?.[2]).toMatchObject({
+ resealDirs: [join(cwd, 'o/browser/fr'), join(cwd, 'o/server/fr')],
+ verifyDirs: [join(cwd, 'o')],
+ });
+ });
+
+ it('--dist (all locales stamped) re-seals the whole root and verifies it', async () => {
+ await build();
+ const run = ran();
+ await uploadAngularSourcemaps(base({ dist: 'o/browser' }), { runPluginUpload: run });
+ expect(run.mock.calls[0]?.[2]).toMatchObject({
+ resealDirs: [join(cwd, 'o')],
+ verifyDirs: [join(cwd, 'o')],
+ });
+ });
+
+ it('--output-path (a flat reading of an application output)', async () => {
+ await build();
+ const run = ran();
+ await uploadAngularSourcemaps(base({ outputPath: 'o/browser' }), { runPluginUpload: run });
+ expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'o')] });
+ });
+
+ it('--output-path with a browser/ but no server/ is browser-only, and verifies only it', async () => {
+ await file('b/browser/main.js');
+ const run = ran();
+ await uploadAngularSourcemaps(base({ outputPath: 'b' }), { runPluginUpload: run });
+ const deps = run.mock.calls[0]?.[2] as { resealDirs: string[]; verifyDirs?: string[] };
+ expect(deps.resealDirs).toEqual([join(cwd, 'b/browser')]);
+ expect(deps.verifyDirs).toEqual([join(cwd, 'b/browser')]);
+ });
+
+ it('a nested --dist with no server/ keeps the browser directory only', async () => {
+ await file('o/browser/fr/main.js');
+ const run = ran();
+ await uploadAngularSourcemaps(base({ dist: 'o/browser/fr' }), { runPluginUpload: run });
+ expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'o/browser/fr')] });
+ });
+
+ it('the project root as output root is said, and not widened', async () => {
+ await file('browser/main.js');
+ await dir('server');
+ const run = ran();
+ const notices: string[] = [];
+ await uploadAngularSourcemaps(base({ dist: 'browser' }, notices), { runPluginUpload: run });
+ expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'browser')] });
+ expect(notices.join('\n')).toMatch(/server.*project root/s);
+ });
+});
diff --git a/packages/angular/src/sourcemaps/server-root.ts b/packages/angular/src/sourcemaps/server-root.ts
new file mode 100644
index 00000000..f8de5384
--- /dev/null
+++ b/packages/angular/src/sourcemaps/server-root.ts
@@ -0,0 +1,88 @@
+// An SSR build's server modules embed the page, SRI hashes included, so re-sealing the browser directory alone leaves
+// the server serving stale hashes (measured: every script blocked). When the output is named by its browser directory
+// (`--dist`, or `--output-path` pointing at it) the output ROOT has to be found from it.
+import { lstatSync, readdirSync } from 'node:fs';
+import * as path from 'node:path';
+
+type PathApi = Pick;
+
+/** Whether `dir` is strictly below `root` (not equal to it, not above it, not on another drive). */
+export function isStrictlyInside(dir: string, root: string, api: PathApi = path): boolean {
+ const rel = api.relative(root, dir);
+ return rel !== '' && rel !== '..' && !rel.startsWith(`..${api.sep}`) && !api.isAbsolute(rel);
+}
+
+const isRealDirectory = (p: string): boolean => {
+ try {
+ const info = lstatSync(p);
+ return info.isDirectory(); // lstat does not follow a symlink, so a symlinked server/ is not a directory here
+ } catch {
+ return false;
+ }
+};
+
+/** Files an Angular SSR build writes to its server output (`server.mjs`, or the engine manifests and server entry). */
+const ANGULAR_SERVER_FILE =
+ /^(?:server|main\.server)\.mjs$|^index\.server\.html$|^angular-app(?:-engine)?-manifest\.mjs$/;
+
+/** Whether `dir` looks like Angular's server output: a marker file in it, or in a locale directory of it. */
+export function looksLikeAngularServer(dir: string): boolean {
+ try {
+ return readdirSync(dir, { withFileTypes: true }).some((entry) =>
+ entry.isDirectory()
+ ? readdirSync(path.join(dir, entry.name)).some((name) => ANGULAR_SERVER_FILE.test(name))
+ : ANGULAR_SERVER_FILE.test(entry.name),
+ );
+ } catch {
+ return false;
+ }
+}
+
+/** How far above the output directory the root is looked for: `browser/` -> root, `browser//` -> two. */
+const MAX_LEVELS_UP = 2;
+
+export type ServerRoot = { root: string; browser: string } | { notice: string } | undefined;
+
+/**
+ * The output root of the SSR build `outDir` belongs to: the nearest ancestor (at most {@link MAX_LEVELS_UP} up) that
+ * has both a `browser/` containing `outDir` and a real (not symlinked) `server/`. Requiring the `browser/` sibling
+ * keeps an unrelated `server/` from becoming the scope. A root that is the project itself, or outside it, is NOT
+ * returned (re-sealing a project root, or someone else's directory, is not this tool's call): a notice says so.
+ */
+export function findServerRoot(outDir: string, cwd: string, api: PathApi = path): ServerRoot {
+ let root = api.dirname(outDir);
+ let unmatched: string | undefined;
+ for (let level = 0; level < MAX_LEVELS_UP; level++, root = api.dirname(root)) {
+ if (!isRealDirectory(api.join(root, 'server'))) {
+ continue;
+ }
+ const browser = api.join(root, 'browser');
+ if (outDir !== browser && !isStrictlyInside(outDir, browser, api)) {
+ if (isStrictlyInside(root, cwd, api) && looksLikeAngularServer(api.join(root, 'server'))) {
+ unmatched ??= api.join(root, 'server');
+ }
+ continue;
+ }
+ if (isStrictlyInside(root, cwd, api)) {
+ return { root, browser };
+ }
+ return {
+ notice:
+ `found ${api.join(root, 'server')} next to the browser output, which embeds the page's integrity hashes, but ` +
+ (root === cwd
+ ? 'the output root is the project root'
+ : 'the output root is outside the project') +
+ `, so it was not re-sealed and a server-rendered page may keep stale hashes. Build into its own directory and ` +
+ `pass --output-path .`,
+ };
+ }
+ if (unmatched === undefined) {
+ return undefined;
+ }
+ return {
+ notice:
+ `found ${unmatched} near the output, but the output is not inside a browser/ directory next to it, so it cannot ` +
+ `tell which is the browser output and did not re-seal the server pages, which embed the page's integrity hashes. ` +
+ `A custom outputPath.browser name is not supported together with server pages: build with the default browser/ name.`,
+ };
+}
diff --git a/packages/angular/src/sourcemaps/upload.real-build.test.ts b/packages/angular/src/sourcemaps/upload.real-build.test.ts
new file mode 100644
index 00000000..9ebb557c
--- /dev/null
+++ b/packages/angular/src/sourcemaps/upload.real-build.test.ts
@@ -0,0 +1,371 @@
+// The upload step against REAL Angular 22.3 output and the REAL bugsee-cli. The two chunks in
+// test/fixtures/angular-22 are byte-for-byte what `ng build` (the esbuild `application` builder, production,
+// `sourceMap: { scripts: true, styles: false, hidden: true }`) wrote for an app with the Bugsee SDK, maps included —
+// Angular had already put its own `//# debugId` in each. The page around them is assembled here in the exact shape
+// `subresourceIntegrity: true` gives it (checked on the same build): `` +
+ `` +
+ `` +
+ `