bugwatch-cli 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -39,13 +39,24 @@ It:
39
39
  - **Vite** / **Create React App** / others: `src/bugwatch.ts` (or
40
40
  `.js`), imported first in your entry file (Vite's `index.html`
41
41
  module script, else `src/main.*` / `src/index.*`)
42
- 4. writes `.bugwatch.json` at the git root. Bugwatch reads it to verify
42
+ 4. **Next.js 15+** (0.5.0+): also the server side, `instrumentation.ts`
43
+ next to `instrumentation-client` (same folder), with
44
+ [`bugwatch/node`](../README.md#nodejs) and the same key, so errors in
45
+ Server Components, route handlers, and server actions are reported.
46
+ An existing `instrumentation.ts` keeps its code: the import goes
47
+ first, the init and `onRequestError` at the end (if the file already
48
+ exports `onRequestError`, it warns you to call
49
+ `Bugwatch.nextOnRequestError` from yours). A `bugwatch` older than
50
+ 0.5.0 is upgraded, since `bugwatch/node` needs it. `--skip-server`
51
+ leaves the server out
52
+ 5. writes `.bugwatch.json` at the git root. Bugwatch reads it to verify
43
53
  the setup; it holds the setup id, never the setup code or a secret
44
54
 
45
55
  It **never commits or pushes**. Review the changes, commit, and push,
46
56
  then press **Verify** in Bugwatch: it checks the branch (the default
47
57
  branch unless you enter another) and creates the project. Running it
48
- again is safe: it updates the API key and does not add a second import.
58
+ again is safe: it updates the API key (in both files) and does not add a
59
+ second import.
49
60
 
50
61
  | Option | Description |
51
62
  | --- | --- |
@@ -53,6 +64,7 @@ again is safe: it updates the API key and does not add a second import.
53
64
  | `--api-url <url>` | Bugwatch API (default: `$BUGWATCH_API_URL` or the hosted API); the command Bugwatch shows includes it when needed |
54
65
  | `--entry <file>` | Your app's entry file, when it can't be detected |
55
66
  | `--skip-install` | Add `bugwatch` to `package.json` without running the package manager |
67
+ | `--skip-server` | Next.js: don't write the server setup (`instrumentation.ts`) |
56
68
  | `--dry-run` | Show what would change; installs and writes nothing |
57
69
 
58
70
  The API key ends up in your browser bundle; that is expected (it can
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  initProject
3
- } from "./chunk-T5NSQVQH.js";
3
+ } from "./chunk-TI67SCUE.js";
4
4
  import {
5
5
  DEFAULT_API_URL,
6
6
  DEFAULT_URL_PREFIX,
@@ -12,14 +12,15 @@ import {
12
12
  isCiToken,
13
13
  isDeprecatedUploadToken,
14
14
  uploadSourceMaps
15
- } from "./chunk-UIBXO6IR.js";
15
+ } from "./chunk-TIAPESCR.js";
16
16
 
17
17
  // src/main.ts
18
18
  import { parseArgs } from "util";
19
19
  var INIT_USAGE = `Usage: bugwatch-cli init --setup <code> [options]
20
20
 
21
21
  Adds Bugwatch to this app for "Add from GitHub": installs the bugwatch SDK,
22
- writes the Bugwatch.init code with the project's API key, and writes
22
+ writes the Bugwatch.init code with the project's API key (for Next.js 15+
23
+ also the server side, instrumentation.ts with bugwatch/node), and writes
23
24
  .bugwatch.json at the git root. It never commits or pushes: review, commit,
24
25
  and push the changes, then press Verify in Bugwatch.
25
26
 
@@ -28,6 +29,7 @@ Options:
28
29
  --api-url <url> Bugwatch API (default: $BUGWATCH_API_URL or ${DEFAULT_API_URL})
29
30
  --entry <file> Your app's entry file, when it can't be detected
30
31
  --skip-install Add bugwatch to package.json instead of running the package manager
32
+ --skip-server Next.js: don't write the server setup (instrumentation.ts)
31
33
  --dry-run Show what would change; installs and writes nothing
32
34
  -h, --help Show this help
33
35
 
@@ -71,6 +73,7 @@ async function main(argv, env = process.env, out = (line) => process.stdout.writ
71
73
  setup: { type: "string" },
72
74
  entry: { type: "string" },
73
75
  "skip-install": { type: "boolean" },
76
+ "skip-server": { type: "boolean" },
74
77
  help: { type: "boolean", short: "h" },
75
78
  version: { type: "boolean", short: "v" }
76
79
  }
@@ -101,6 +104,7 @@ ${USAGE}`);
101
104
  apiUrl: values["api-url"] || env.BUGWATCH_API_URL || DEFAULT_API_URL,
102
105
  ...values.entry ? { entry: values.entry } : {},
103
106
  skipInstall: values["skip-install"] === true,
107
+ skipServer: values["skip-server"] === true,
104
108
  dryRun: values["dry-run"] === true,
105
109
  out,
106
110
  err
@@ -2,7 +2,7 @@ import {
2
2
  DEFAULT_API_URL,
3
3
  UsageError,
4
4
  VERSION
5
- } from "./chunk-UIBXO6IR.js";
5
+ } from "./chunk-TIAPESCR.js";
6
6
 
7
7
  // src/init.ts
8
8
  import { execFile, spawn } from "child_process";
@@ -11,7 +11,7 @@ import { readFile, writeFile } from "fs/promises";
11
11
  import { dirname, join, posix, relative, resolve, sep } from "path";
12
12
  var MARKER_FILE = ".bugwatch.json";
13
13
  var DEFAULT_INGEST_URL = `${DEFAULT_API_URL}/api/ingest`;
14
- var SDK_VERSION_RANGE = "^0.4.0";
14
+ var SDK_VERSION_RANGE = "^0.5.0";
15
15
  var FETCH_TIMEOUT_MS = 9e4;
16
16
  var SLOW_NOTICE_MS = 5e3;
17
17
  var SETUP_CODE = /^bws_[0-9a-f]{32}$/;
@@ -68,9 +68,21 @@ function detectPackageManager(packageDir, gitRoot) {
68
68
  }
69
69
  }
70
70
  function installCommand(pm) {
71
- if (pm === "npm") return { command: "npm", args: ["install", "bugwatch"] };
72
- return { command: pm, args: ["add", "bugwatch"] };
71
+ const spec = `bugwatch@${SDK_VERSION_RANGE}`;
72
+ if (pm === "npm") return { command: "npm", args: ["install", spec] };
73
+ return { command: pm, args: ["add", spec] };
73
74
  }
75
+ function sdkTooOld(range) {
76
+ if (!range) return false;
77
+ const match = /(\d+)\.(\d+)/.exec(range);
78
+ if (!match) return false;
79
+ return Number(match[1]) === 0 && Number(match[2]) < 5;
80
+ }
81
+ function nextMajor(pkg) {
82
+ const match = /(\d+)\./.exec(deps(pkg).next ?? "");
83
+ return match ? Number(match[1]) : null;
84
+ }
85
+ var ON_REQUEST_ERROR_EXPORT = /export\s+(?:const|let|var|function|async\s+function)\s+onRequestError\b|export\s*\{[^}]*\bonRequestError\b/;
74
86
  function defaultRunInstall(command, args, cwd) {
75
87
  return new Promise((done) => {
76
88
  const child = spawn(command, args, { cwd, stdio: "inherit", shell: process.platform === "win32" });
@@ -155,6 +167,42 @@ function initSource(setup) {
155
167
  ``
156
168
  ].join("\n");
157
169
  }
170
+ function serverSource(setup) {
171
+ const endpoint = setup.ingestUrl !== DEFAULT_INGEST_URL ? `
172
+ endpoint: ${JSON.stringify(setup.ingestUrl)},` : "";
173
+ return [
174
+ `import { Bugwatch } from "bugwatch/node";`,
175
+ ``,
176
+ `// Bugwatch on the server for the project ${JSON.stringify(setup.projectName)} (added by bugwatch-cli init):`,
177
+ `// errors in Server Components, route handlers, and server actions. Same key as`,
178
+ `// instrumentation-client: it is public and can only send errors to this project.`,
179
+ `export function register() {`,
180
+ ` if (process.env.NEXT_RUNTIME === "nodejs") {`,
181
+ ` Bugwatch.init({`,
182
+ ` apiKey: ${JSON.stringify(setup.apiKey)},${endpoint}`,
183
+ ` });`,
184
+ ` }`,
185
+ `}`,
186
+ ``,
187
+ `export const onRequestError = Bugwatch.nextOnRequestError;`,
188
+ ``
189
+ ].join("\n");
190
+ }
191
+ function addServerSetup(current, setup) {
192
+ const endpoint = setup.ingestUrl !== DEFAULT_INGEST_URL ? `, endpoint: ${JSON.stringify(setup.ingestUrl)}` : "";
193
+ const ownOnRequestError = ON_REQUEST_ERROR_EXPORT.test(current);
194
+ const tail = [
195
+ ``,
196
+ `// Bugwatch on the server for the project ${JSON.stringify(setup.projectName)} (added by bugwatch-cli init).`,
197
+ `if (process.env.NEXT_RUNTIME === "nodejs") {`,
198
+ ` Bugwatch.init({ apiKey: ${JSON.stringify(setup.apiKey)}${endpoint} });`,
199
+ `}`,
200
+ ...ownOnRequestError ? [] : [``, `export const onRequestError = Bugwatch.nextOnRequestError;`],
201
+ ``
202
+ ].join("\n");
203
+ return { content: `import { Bugwatch } from "bugwatch/node";
204
+ ${current.replace(/\s*$/, "\n")}${tail}`, ownOnRequestError };
205
+ }
158
206
  function replaceApiKey(text, apiKey) {
159
207
  const pattern = /(apiKey\s*:\s*)(["'`])bw_[^"'`]*\2/;
160
208
  return pattern.test(text) ? text.replace(pattern, `$1$2${apiKey}$2`) : null;
@@ -177,7 +225,7 @@ function detectIndent(text) {
177
225
  const match = /^[ \t]+(?=")/m.exec(text);
178
226
  return match ? match[0] : 2;
179
227
  }
180
- async function plan(packageDir, pkg, setup, entryOverride, cwd) {
228
+ async function plan(packageDir, pkg, setup, entryOverride, cwd, skipServer) {
181
229
  const framework = detectFramework(pkg);
182
230
  const typescript = existsSync(join(packageDir, "tsconfig.json"));
183
231
  const ext = typescript ? "ts" : "js";
@@ -239,7 +287,40 @@ ${current}`;
239
287
  const updated = addImport(text, importSpecifier(entryFile, initFile));
240
288
  if (updated !== null) entry = { file: entryFile, content: updated };
241
289
  }
242
- return { framework, initFile, initContent, initAction, ...entry ? { entry } : {}, warnings };
290
+ let server;
291
+ if (framework === "nextjs" && !entryOverride && !skipServer) {
292
+ const major = nextMajor(pkg);
293
+ if (major !== null && major < 15) {
294
+ warnings.push(`Next.js ${major} has no onRequestError (needs 15+): server errors are not set up. See the bugwatch/node docs`);
295
+ } else {
296
+ const dir = posix.dirname(initFile) === "." ? "" : `${posix.dirname(initFile)}/`;
297
+ const file = existing(packageDir, `${dir}instrumentation`) ?? `${dir}instrumentation.${ext}`;
298
+ const path = join(packageDir, file);
299
+ if (!existsSync(path)) {
300
+ server = { file, content: serverSource(setup), action: "create" };
301
+ } else {
302
+ const current = await readFile(path, "utf8");
303
+ if (current.includes("bugwatch/node")) {
304
+ const replaced = replaceApiKey(current, setup.apiKey);
305
+ if (replaced === null) {
306
+ warnings.push(`${file} already uses bugwatch/node without an apiKey string; check it uses ${setup.apiKey}`);
307
+ server = { file, content: current, action: "keep" };
308
+ } else {
309
+ server = { file, content: replaced, action: replaced === current ? "keep" : "update" };
310
+ }
311
+ } else {
312
+ const added = addServerSetup(current, setup);
313
+ server = { file, content: added.content, action: "update" };
314
+ if (added.ownOnRequestError) {
315
+ warnings.push(
316
+ `${file} already exports onRequestError: call Bugwatch.nextOnRequestError(error, request, context) inside it to report server errors`
317
+ );
318
+ }
319
+ }
320
+ }
321
+ }
322
+ }
323
+ return { framework, initFile, initContent, initAction, ...entry ? { entry } : {}, ...server ? { server } : {}, warnings };
243
324
  }
244
325
  async function initProject(options) {
245
326
  const out = options.out ?? ((line) => process.stdout.write(`${line}
@@ -266,21 +347,26 @@ async function initProject(options) {
266
347
  const pkgPath = join(packageDir, "package.json");
267
348
  const pkgText = await readFile(pkgPath, "utf8");
268
349
  const pkg = await readJson(pkgPath);
269
- const steps = await plan(packageDir, pkg, setup, options.entry, cwd);
350
+ const steps = await plan(packageDir, pkg, setup, options.entry, cwd, options.skipServer === true);
270
351
  warnings.push(...steps.warnings);
271
352
  const packageManager = detectPackageManager(packageDir, gitRoot);
272
- const hasSdk = Boolean(deps(pkg).bugwatch);
353
+ const currentRange = deps(pkg).bugwatch;
354
+ const needsUpgrade = Boolean(steps.server) && sdkTooOld(currentRange);
355
+ const hasSdk = Boolean(currentRange) && !needsUpgrade;
273
356
  const fromRoot = (file) => toPosix(relative(gitRoot, join(packageDir, file))) || ".";
274
357
  const packageDirRel = toPosix(relative(gitRoot, packageDir)) || ".";
275
358
  const changed = [];
276
359
  let installed = false;
277
360
  if (!hasSdk) {
278
361
  const { command, args } = installCommand(packageManager);
362
+ if (needsUpgrade) out(`upgrade bugwatch ${currentRange} \u2192 ${SDK_VERSION_RANGE} (the server setup needs bugwatch/node)`);
279
363
  if (dryRun) {
280
364
  out(`would run ${options.skipInstall ? `(skipped) add bugwatch@${SDK_VERSION_RANGE} to package.json` : `${command} ${args.join(" ")}`}`);
281
365
  } else if (options.skipInstall) {
282
366
  const dependencies = typeof pkg.dependencies === "object" && pkg.dependencies !== null ? pkg.dependencies : {};
283
367
  pkg.dependencies = { ...dependencies, bugwatch: SDK_VERSION_RANGE };
368
+ const devDependencies = pkg.devDependencies;
369
+ if (devDependencies && typeof devDependencies === "object" && devDependencies.bugwatch) delete devDependencies.bugwatch;
284
370
  await writeFile(pkgPath, `${JSON.stringify(pkg, null, detectIndent(pkgText))}
285
371
  `);
286
372
  out(`added bugwatch@${SDK_VERSION_RANGE} to ${fromRoot("package.json")} (run ${command} install yourself)`);
@@ -310,12 +396,22 @@ async function initProject(options) {
310
396
  out(`${verb}update`.padEnd(12) + `${fromRoot(steps.entry.file)} (imports the Bugwatch setup first)`);
311
397
  changed.push(fromRoot(steps.entry.file));
312
398
  }
399
+ if (steps.server) {
400
+ if (steps.server.action === "keep") {
401
+ out(`kept ${fromRoot(steps.server.file)} (server: already uses bugwatch/node)`);
402
+ } else {
403
+ if (!dryRun) await writeFile(join(packageDir, steps.server.file), steps.server.content);
404
+ out(`${verb}${steps.server.action}`.padEnd(12) + `${fromRoot(steps.server.file)} (server errors)`);
405
+ changed.push(fromRoot(steps.server.file));
406
+ }
407
+ }
313
408
  const marker = {
314
409
  $comment: "Written by bugwatch-cli init. Bugwatch reads this file to verify the setup; it holds no secrets.",
315
410
  setupId: setup.setupId,
316
411
  project: setup.projectName,
317
412
  packageDir: packageDirRel,
318
413
  initFile: steps.initFile,
414
+ ...steps.server ? { serverFile: steps.server.file } : {},
319
415
  framework: steps.framework
320
416
  };
321
417
  if (!dryRun) await writeFile(join(gitRoot, MARKER_FILE), `${JSON.stringify(marker, null, 2)}
@@ -341,6 +437,7 @@ async function initProject(options) {
341
437
  packageManager,
342
438
  packageDir: packageDirRel,
343
439
  initFile: steps.initFile,
440
+ ...steps.server ? { serverFile: steps.server.file } : {},
344
441
  changed: [...new Set(changed)],
345
442
  installed,
346
443
  warnings
@@ -354,6 +451,7 @@ export {
354
451
  detectFramework,
355
452
  detectPackageManager,
356
453
  installCommand,
454
+ sdkTooOld,
357
455
  remoteRepo,
358
456
  replaceApiKey,
359
457
  importSpecifier,
@@ -26,7 +26,7 @@ function formatSummary(summary, { dryRun, release, files }) {
26
26
  }
27
27
 
28
28
  // src/version.ts
29
- var VERSION = "0.4.1";
29
+ var VERSION = "0.5.0";
30
30
 
31
31
  // src/upload.ts
32
32
  import { open, readdir, readFile, stat, unlink } from "fs/promises";
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  main
4
- } from "./chunk-ODCYZAF4.js";
5
- import "./chunk-T5NSQVQH.js";
6
- import "./chunk-UIBXO6IR.js";
4
+ } from "./chunk-A3FVZYMN.js";
5
+ import "./chunk-TI67SCUE.js";
6
+ import "./chunk-TIAPESCR.js";
7
7
 
8
8
  // src/cli.ts
9
9
  main(process.argv.slice(2)).then((code) => {
package/dist/index.d.ts CHANGED
@@ -170,6 +170,8 @@ interface InitOptions {
170
170
  entry?: string;
171
171
  /** Do not run the package manager; add `bugwatch` to package.json instead. */
172
172
  skipInstall?: boolean;
173
+ /** Next.js: do not write the server setup (`instrumentation.ts` with `bugwatch/node`). */
174
+ skipServer?: boolean;
173
175
  dryRun?: boolean;
174
176
  out?: (line: string) => void;
175
177
  err?: (line: string) => void;
@@ -189,6 +191,8 @@ interface InitReport {
189
191
  packageDir: string;
190
192
  /** The file that calls Bugwatch.init, relative to packageDir. */
191
193
  initFile: string;
194
+ /** Next.js: the server setup file (`instrumentation.ts`), relative to packageDir, when written or kept. */
195
+ serverFile?: string;
192
196
  /** Files written or changed, relative to the git root. */
193
197
  changed: string[];
194
198
  installed: boolean;
@@ -201,6 +205,8 @@ declare function installCommand(pm: PackageManager): {
201
205
  command: string;
202
206
  args: string[];
203
207
  };
208
+ /** True when a `bugwatch` range in package.json cannot include 0.5.0 (which adds `bugwatch/node`). */
209
+ declare function sdkTooOld(range: string | undefined): boolean;
204
210
  /** `git@github.com:acme/shop.git` / `https://github.com/acme/shop` → `acme/shop`. */
205
211
  declare function remoteRepo(remote: string): string | null;
206
212
  /** Replaces the apiKey string literal in an existing init call; null when there is none to replace. */
@@ -213,6 +219,6 @@ declare function addImport(text: string, spec: string): string | null;
213
219
  declare function initProject(options: InitOptions): Promise<InitReport>;
214
220
 
215
221
  /** Keep in sync with package.json (a test checks it). */
216
- declare const VERSION = "0.4.1";
222
+ declare const VERSION = "0.5.0";
217
223
 
218
- export { CONCURRENCY, type CliSetup, DEFAULT_API_URL, DEFAULT_INGEST_URL, DEFAULT_URL_PREFIX, type FileResult, type Framework, type InitOptions, type InitReport, MARKER_FILE, MAX_MAP_BYTES, MAX_RETRIES, type Outcome, type PackageManager, type PlannedUpload, STOP_CODES, UPLOAD_TOKEN_DEPRECATED, type UploadOptions, type UploadReport, type UploadSummary, UsageError, VERSION, addImport, detectFramework, detectPackageManager, findMapOwners, findSourceMaps, formatBytes, formatResult, formatSummary, importSpecifier, initProject, installCommand, isCiToken, isCssMap, isDeprecatedUploadToken, mapName, planUploads, projectProblem, releaseProblem, remoteRepo, replaceApiKey, sendableMapFile, setupCodeProblem, sourceMappingUrlOf, uploadSourceMaps, urlPrefixProblem };
224
+ export { CONCURRENCY, type CliSetup, DEFAULT_API_URL, DEFAULT_INGEST_URL, DEFAULT_URL_PREFIX, type FileResult, type Framework, type InitOptions, type InitReport, MARKER_FILE, MAX_MAP_BYTES, MAX_RETRIES, type Outcome, type PackageManager, type PlannedUpload, STOP_CODES, UPLOAD_TOKEN_DEPRECATED, type UploadOptions, type UploadReport, type UploadSummary, UsageError, VERSION, addImport, detectFramework, detectPackageManager, findMapOwners, findSourceMaps, formatBytes, formatResult, formatSummary, importSpecifier, initProject, installCommand, isCiToken, isCssMap, isDeprecatedUploadToken, mapName, planUploads, projectProblem, releaseProblem, remoteRepo, replaceApiKey, sdkTooOld, sendableMapFile, setupCodeProblem, sourceMappingUrlOf, uploadSourceMaps, urlPrefixProblem };
package/dist/index.js CHANGED
@@ -9,8 +9,9 @@ import {
9
9
  installCommand,
10
10
  remoteRepo,
11
11
  replaceApiKey,
12
+ sdkTooOld,
12
13
  setupCodeProblem
13
- } from "./chunk-T5NSQVQH.js";
14
+ } from "./chunk-TI67SCUE.js";
14
15
  import {
15
16
  CONCURRENCY,
16
17
  DEFAULT_API_URL,
@@ -37,7 +38,7 @@ import {
37
38
  sourceMappingUrlOf,
38
39
  uploadSourceMaps,
39
40
  urlPrefixProblem
40
- } from "./chunk-UIBXO6IR.js";
41
+ } from "./chunk-TIAPESCR.js";
41
42
  export {
42
43
  CONCURRENCY,
43
44
  DEFAULT_API_URL,
@@ -70,6 +71,7 @@ export {
70
71
  releaseProblem,
71
72
  remoteRepo,
72
73
  replaceApiKey,
74
+ sdkTooOld,
73
75
  sendableMapFile,
74
76
  setupCodeProblem,
75
77
  sourceMappingUrlOf,
package/dist/main.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  main
3
- } from "./chunk-ODCYZAF4.js";
4
- import "./chunk-T5NSQVQH.js";
5
- import "./chunk-UIBXO6IR.js";
3
+ } from "./chunk-A3FVZYMN.js";
4
+ import "./chunk-TI67SCUE.js";
5
+ import "./chunk-TIAPESCR.js";
6
6
  export {
7
7
  main
8
8
  };
package/dist/vite.js CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  isCiToken,
8
8
  isDeprecatedUploadToken,
9
9
  uploadSourceMaps
10
- } from "./chunk-UIBXO6IR.js";
10
+ } from "./chunk-TIAPESCR.js";
11
11
 
12
12
  // src/vite.ts
13
13
  import { resolve } from "path";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bugwatch-cli",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Set up Bugwatch in your app and upload source maps from CI (CLI and Vite plugin)",
5
5
  "type": "module",
6
6
  "bin": {