bugwatch-cli 0.3.1 → 0.4.1
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 +47 -4
- package/dist/{chunk-YSCPONSJ.js → chunk-ODCYZAF4.js} +51 -2
- package/dist/chunk-T5NSQVQH.js +362 -0
- package/dist/{chunk-NJEKNSX4.js → chunk-UIBXO6IR.js} +1 -1
- package/dist/cli.js +3 -2
- package/dist/index.d.ts +75 -2
- package/dist/index.js +25 -1
- package/dist/main.js +3 -2
- package/dist/vite.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
# bugwatch-cli
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
original file, line, function, and the
|
|
5
|
-
minified frames.
|
|
3
|
+
Set up Bugwatch in your app, and upload your build's source maps to
|
|
4
|
+
Bugwatch, so errors show the original file, line, function, and the
|
|
5
|
+
code around them instead of minified frames.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Three ways to use it, from the same package:
|
|
8
8
|
|
|
9
|
+
- **`bugwatch-cli init`** adds Bugwatch to an app for "Add from
|
|
10
|
+
GitHub" (see [Set up a project from GitHub](#set-up-a-project-from-github))
|
|
9
11
|
- a **CLI** for any build tool: `bugwatch-cli sourcemaps upload`
|
|
10
12
|
- a **Vite plugin** that uploads at the end of `vite build`
|
|
11
13
|
|
|
@@ -15,6 +17,47 @@ Node 18 or later. No runtime dependencies.
|
|
|
15
17
|
npm install --save-dev bugwatch-cli
|
|
16
18
|
```
|
|
17
19
|
|
|
20
|
+
## Set up a project from GitHub
|
|
21
|
+
|
|
22
|
+
In Bugwatch, **Add from GitHub** connects your GitHub account, lets you
|
|
23
|
+
pick a repository, and shows a command with a one-time setup code. Run
|
|
24
|
+
it in your local clone of that repository:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npx bugwatch-cli@latest init --setup bws_…
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
It:
|
|
31
|
+
|
|
32
|
+
1. fetches the pending project (name, API key) for the setup code
|
|
33
|
+
2. installs the `bugwatch` SDK with your package manager (npm, pnpm,
|
|
34
|
+
yarn, or bun, from the lockfile)
|
|
35
|
+
3. writes the `Bugwatch.init({ apiKey })` code:
|
|
36
|
+
- **Next.js**: `instrumentation-client.ts` (or `src/…` when you use a
|
|
37
|
+
`src` folder; Next.js 15.3+). An existing file keeps its code; ours
|
|
38
|
+
goes first
|
|
39
|
+
- **Vite** / **Create React App** / others: `src/bugwatch.ts` (or
|
|
40
|
+
`.js`), imported first in your entry file (Vite's `index.html`
|
|
41
|
+
module script, else `src/main.*` / `src/index.*`)
|
|
42
|
+
4. writes `.bugwatch.json` at the git root. Bugwatch reads it to verify
|
|
43
|
+
the setup; it holds the setup id, never the setup code or a secret
|
|
44
|
+
|
|
45
|
+
It **never commits or pushes**. Review the changes, commit, and push,
|
|
46
|
+
then press **Verify** in Bugwatch: it checks the branch (the default
|
|
47
|
+
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.
|
|
49
|
+
|
|
50
|
+
| Option | Description |
|
|
51
|
+
| --- | --- |
|
|
52
|
+
| `--setup <code>` | The `bws_…` code from Add from GitHub. Required |
|
|
53
|
+
| `--api-url <url>` | Bugwatch API (default: `$BUGWATCH_API_URL` or the hosted API); the command Bugwatch shows includes it when needed |
|
|
54
|
+
| `--entry <file>` | Your app's entry file, when it can't be detected |
|
|
55
|
+
| `--skip-install` | Add `bugwatch` to `package.json` without running the package manager |
|
|
56
|
+
| `--dry-run` | Show what would change; installs and writes nothing |
|
|
57
|
+
|
|
58
|
+
The API key ends up in your browser bundle; that is expected (it can
|
|
59
|
+
only send errors to this project). Setup codes expire after 7 days.
|
|
60
|
+
|
|
18
61
|
## Before you start
|
|
19
62
|
|
|
20
63
|
0. **Turn on source maps for the project**: project → Settings →
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
initProject
|
|
3
|
+
} from "./chunk-T5NSQVQH.js";
|
|
1
4
|
import {
|
|
2
5
|
DEFAULT_API_URL,
|
|
3
6
|
DEFAULT_URL_PREFIX,
|
|
@@ -9,10 +12,26 @@ import {
|
|
|
9
12
|
isCiToken,
|
|
10
13
|
isDeprecatedUploadToken,
|
|
11
14
|
uploadSourceMaps
|
|
12
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-UIBXO6IR.js";
|
|
13
16
|
|
|
14
17
|
// src/main.ts
|
|
15
18
|
import { parseArgs } from "util";
|
|
19
|
+
var INIT_USAGE = `Usage: bugwatch-cli init --setup <code> [options]
|
|
20
|
+
|
|
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
|
|
23
|
+
.bugwatch.json at the git root. It never commits or pushes: review, commit,
|
|
24
|
+
and push the changes, then press Verify in Bugwatch.
|
|
25
|
+
|
|
26
|
+
Options:
|
|
27
|
+
--setup <code> The setup code (bws_\u2026) from Add from GitHub. Required
|
|
28
|
+
--api-url <url> Bugwatch API (default: $BUGWATCH_API_URL or ${DEFAULT_API_URL})
|
|
29
|
+
--entry <file> Your app's entry file, when it can't be detected
|
|
30
|
+
--skip-install Add bugwatch to package.json instead of running the package manager
|
|
31
|
+
--dry-run Show what would change; installs and writes nothing
|
|
32
|
+
-h, --help Show this help
|
|
33
|
+
|
|
34
|
+
Exit codes: 0 done, 1 failed (network, install), 2 usage error.`;
|
|
16
35
|
var USAGE = `Usage: bugwatch-cli sourcemaps upload <dir> --release <version> [options]
|
|
17
36
|
|
|
18
37
|
Uploads every .map file under <dir> to Bugwatch for the release.
|
|
@@ -30,7 +49,9 @@ Options:
|
|
|
30
49
|
-h, --help Show this help
|
|
31
50
|
-v, --version Show the version
|
|
32
51
|
|
|
33
|
-
Exit codes: 0 all uploaded, 1 an upload failed, 2 usage error
|
|
52
|
+
Exit codes: 0 all uploaded, 1 an upload failed, 2 usage error.
|
|
53
|
+
|
|
54
|
+
Set up a new project from GitHub: bugwatch-cli init --setup <code> (see bugwatch-cli init --help).`;
|
|
34
55
|
async function main(argv, env = process.env, out = (line) => process.stdout.write(`${line}
|
|
35
56
|
`), err = (line) => process.stderr.write(`${line}
|
|
36
57
|
`)) {
|
|
@@ -47,6 +68,9 @@ async function main(argv, env = process.env, out = (line) => process.stdout.writ
|
|
|
47
68
|
project: { type: "string" },
|
|
48
69
|
"delete-after-upload": { type: "boolean" },
|
|
49
70
|
"dry-run": { type: "boolean" },
|
|
71
|
+
setup: { type: "string" },
|
|
72
|
+
entry: { type: "string" },
|
|
73
|
+
"skip-install": { type: "boolean" },
|
|
50
74
|
help: { type: "boolean", short: "h" },
|
|
51
75
|
version: { type: "boolean", short: "v" }
|
|
52
76
|
}
|
|
@@ -62,6 +86,31 @@ ${USAGE}`);
|
|
|
62
86
|
out(VERSION);
|
|
63
87
|
return 0;
|
|
64
88
|
}
|
|
89
|
+
if (positionals[0] === "init") {
|
|
90
|
+
if (values.help) {
|
|
91
|
+
out(INIT_USAGE);
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
if (positionals.length > 1) {
|
|
95
|
+
err(INIT_USAGE);
|
|
96
|
+
return 2;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
await initProject({
|
|
100
|
+
setupCode: values.setup ?? "",
|
|
101
|
+
apiUrl: values["api-url"] || env.BUGWATCH_API_URL || DEFAULT_API_URL,
|
|
102
|
+
...values.entry ? { entry: values.entry } : {},
|
|
103
|
+
skipInstall: values["skip-install"] === true,
|
|
104
|
+
dryRun: values["dry-run"] === true,
|
|
105
|
+
out,
|
|
106
|
+
err
|
|
107
|
+
});
|
|
108
|
+
return 0;
|
|
109
|
+
} catch (error) {
|
|
110
|
+
err(`Error: ${error instanceof Error ? error.message : String(error)}`);
|
|
111
|
+
return error instanceof UsageError ? 2 : 1;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
65
114
|
if (values.help) {
|
|
66
115
|
out(USAGE);
|
|
67
116
|
return 0;
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_API_URL,
|
|
3
|
+
UsageError,
|
|
4
|
+
VERSION
|
|
5
|
+
} from "./chunk-UIBXO6IR.js";
|
|
6
|
+
|
|
7
|
+
// src/init.ts
|
|
8
|
+
import { execFile, spawn } from "child_process";
|
|
9
|
+
import { existsSync, statSync } from "fs";
|
|
10
|
+
import { readFile, writeFile } from "fs/promises";
|
|
11
|
+
import { dirname, join, posix, relative, resolve, sep } from "path";
|
|
12
|
+
var MARKER_FILE = ".bugwatch.json";
|
|
13
|
+
var DEFAULT_INGEST_URL = `${DEFAULT_API_URL}/api/ingest`;
|
|
14
|
+
var SDK_VERSION_RANGE = "^0.4.0";
|
|
15
|
+
var FETCH_TIMEOUT_MS = 9e4;
|
|
16
|
+
var SLOW_NOTICE_MS = 5e3;
|
|
17
|
+
var SETUP_CODE = /^bws_[0-9a-f]{32}$/;
|
|
18
|
+
var ENTRY_EXTENSIONS = ["tsx", "ts", "jsx", "js", "mts", "mjs"];
|
|
19
|
+
function setupCodeProblem(code) {
|
|
20
|
+
if (!code) return "A setup code is required (--setup bws_\u2026). Copy the command from Add from GitHub in Bugwatch";
|
|
21
|
+
return SETUP_CODE.test(code) ? null : "The setup code must look like bws_ followed by 32 hex characters";
|
|
22
|
+
}
|
|
23
|
+
function toPosix(path) {
|
|
24
|
+
return path.split(sep).join(posix.sep);
|
|
25
|
+
}
|
|
26
|
+
function findUp(from, name, stopAt) {
|
|
27
|
+
let dir = resolve(from);
|
|
28
|
+
for (; ; ) {
|
|
29
|
+
if (existsSync(join(dir, name))) return dir;
|
|
30
|
+
if (stopAt && dir === stopAt) return null;
|
|
31
|
+
const parent = dirname(dir);
|
|
32
|
+
if (parent === dir) return null;
|
|
33
|
+
dir = parent;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async function readJson(path) {
|
|
37
|
+
const text = await readFile(path, "utf8");
|
|
38
|
+
const value = JSON.parse(text);
|
|
39
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${path} is not a JSON object`);
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
function deps(pkg) {
|
|
43
|
+
const all = {};
|
|
44
|
+
for (const key of ["dependencies", "devDependencies"]) {
|
|
45
|
+
const value = pkg[key];
|
|
46
|
+
if (typeof value === "object" && value !== null) Object.assign(all, value);
|
|
47
|
+
}
|
|
48
|
+
return all;
|
|
49
|
+
}
|
|
50
|
+
function detectFramework(pkg) {
|
|
51
|
+
const all = deps(pkg);
|
|
52
|
+
if (all.next) return "nextjs";
|
|
53
|
+
if (all.vite) return "vite";
|
|
54
|
+
if (all["react-scripts"]) return "cra";
|
|
55
|
+
return "other";
|
|
56
|
+
}
|
|
57
|
+
function detectPackageManager(packageDir, gitRoot) {
|
|
58
|
+
let dir = packageDir;
|
|
59
|
+
for (; ; ) {
|
|
60
|
+
if (existsSync(join(dir, "pnpm-lock.yaml"))) return "pnpm";
|
|
61
|
+
if (existsSync(join(dir, "yarn.lock"))) return "yarn";
|
|
62
|
+
if (existsSync(join(dir, "bun.lockb")) || existsSync(join(dir, "bun.lock"))) return "bun";
|
|
63
|
+
if (existsSync(join(dir, "package-lock.json"))) return "npm";
|
|
64
|
+
if (dir === gitRoot) return "npm";
|
|
65
|
+
const parent = dirname(dir);
|
|
66
|
+
if (parent === dir) return "npm";
|
|
67
|
+
dir = parent;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function installCommand(pm) {
|
|
71
|
+
if (pm === "npm") return { command: "npm", args: ["install", "bugwatch"] };
|
|
72
|
+
return { command: pm, args: ["add", "bugwatch"] };
|
|
73
|
+
}
|
|
74
|
+
function defaultRunInstall(command, args, cwd) {
|
|
75
|
+
return new Promise((done) => {
|
|
76
|
+
const child = spawn(command, args, { cwd, stdio: "inherit", shell: process.platform === "win32" });
|
|
77
|
+
child.on("error", () => done(127));
|
|
78
|
+
child.on("close", (code) => done(code ?? 1));
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
async function fetchSetup(apiUrl, setupCode, notice, timeouts = {}) {
|
|
82
|
+
const url = `${apiUrl.replace(/\/+$/, "")}/api/cli/setup`;
|
|
83
|
+
const fetchMs = timeouts.fetchMs ?? FETCH_TIMEOUT_MS;
|
|
84
|
+
const slow = setTimeout(
|
|
85
|
+
() => notice("Waiting for Bugwatch to answer (a sleeping server can take up to a minute to wake up)\u2026"),
|
|
86
|
+
timeouts.slowNoticeMs ?? SLOW_NOTICE_MS
|
|
87
|
+
);
|
|
88
|
+
let response;
|
|
89
|
+
let body = {};
|
|
90
|
+
try {
|
|
91
|
+
response = await fetch(url, {
|
|
92
|
+
method: "POST",
|
|
93
|
+
headers: { "Content-Type": "application/json", "User-Agent": `bugwatch-cli/${VERSION}` },
|
|
94
|
+
body: JSON.stringify({ setupCode }),
|
|
95
|
+
signal: AbortSignal.timeout(fetchMs)
|
|
96
|
+
});
|
|
97
|
+
try {
|
|
98
|
+
body = await response.json();
|
|
99
|
+
} catch {
|
|
100
|
+
}
|
|
101
|
+
} catch (error) {
|
|
102
|
+
const name = error?.name;
|
|
103
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
104
|
+
throw new Error(`Bugwatch at ${apiUrl} did not answer within ${Math.ceil(fetchMs / 1e3)} s. Try again in a minute`);
|
|
105
|
+
}
|
|
106
|
+
throw new Error(`Could not reach Bugwatch at ${apiUrl}: ${error instanceof Error ? error.message : String(error)}`);
|
|
107
|
+
} finally {
|
|
108
|
+
clearTimeout(slow);
|
|
109
|
+
}
|
|
110
|
+
if (!response.ok || !body.ok || !body.data) {
|
|
111
|
+
const message = body.error?.message ?? `Bugwatch answered ${response.status}`;
|
|
112
|
+
if (response.status === 404 || response.status === 400) throw new UsageError(message);
|
|
113
|
+
throw new Error(message);
|
|
114
|
+
}
|
|
115
|
+
return body.data;
|
|
116
|
+
}
|
|
117
|
+
function gitRemote(cwd) {
|
|
118
|
+
return new Promise((done) => {
|
|
119
|
+
execFile("git", ["remote", "get-url", "origin"], { cwd, timeout: 5e3 }, (error, stdout) => {
|
|
120
|
+
done(error ? null : stdout.trim() || null);
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
function remoteRepo(remote) {
|
|
125
|
+
const match = /github\.com[:/]+([^/]+\/[^/]+?)(?:\.git)?\/?$/i.exec(remote.trim());
|
|
126
|
+
return match ? match[1].toLowerCase() : null;
|
|
127
|
+
}
|
|
128
|
+
function existing(base, stem) {
|
|
129
|
+
for (const ext of ENTRY_EXTENSIONS) {
|
|
130
|
+
const file = `${stem}.${ext}`;
|
|
131
|
+
if (existsSync(join(base, file))) return file;
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
async function viteEntry(packageDir) {
|
|
136
|
+
const html = join(packageDir, "index.html");
|
|
137
|
+
if (existsSync(html)) {
|
|
138
|
+
const text = await readFile(html, "utf8");
|
|
139
|
+
const match = /<script[^>]*type=["']module["'][^>]*src=["']\/?([^"']+)["']/i.exec(text) ?? /<script[^>]*src=["']\/?([^"']+)["'][^>]*type=["']module["']/i.exec(text);
|
|
140
|
+
if (match && existsSync(join(packageDir, match[1]))) return match[1];
|
|
141
|
+
}
|
|
142
|
+
return existing(packageDir, "src/main") ?? existing(packageDir, "src/index");
|
|
143
|
+
}
|
|
144
|
+
function initSource(setup) {
|
|
145
|
+
const endpoint = setup.ingestUrl !== DEFAULT_INGEST_URL ? `
|
|
146
|
+
endpoint: ${JSON.stringify(setup.ingestUrl)},` : "";
|
|
147
|
+
return [
|
|
148
|
+
`import { Bugwatch } from "bugwatch";`,
|
|
149
|
+
``,
|
|
150
|
+
`// Bugwatch error tracking for the project ${JSON.stringify(setup.projectName)} (added by bugwatch-cli init).`,
|
|
151
|
+
`// The API key is safe to ship in browser code: it can only send errors to this project.`,
|
|
152
|
+
`Bugwatch.init({`,
|
|
153
|
+
` apiKey: ${JSON.stringify(setup.apiKey)},${endpoint}`,
|
|
154
|
+
`});`,
|
|
155
|
+
``
|
|
156
|
+
].join("\n");
|
|
157
|
+
}
|
|
158
|
+
function replaceApiKey(text, apiKey) {
|
|
159
|
+
const pattern = /(apiKey\s*:\s*)(["'`])bw_[^"'`]*\2/;
|
|
160
|
+
return pattern.test(text) ? text.replace(pattern, `$1$2${apiKey}$2`) : null;
|
|
161
|
+
}
|
|
162
|
+
function importSpecifier(entry, initFile) {
|
|
163
|
+
let spec = posix.relative(posix.dirname(entry), initFile.replace(/\.(m?[jt]sx?)$/, ""));
|
|
164
|
+
if (!spec.startsWith(".")) spec = `./${spec}`;
|
|
165
|
+
return spec;
|
|
166
|
+
}
|
|
167
|
+
function addImport(text, spec) {
|
|
168
|
+
const escaped = spec.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
169
|
+
if (new RegExp(`import\\s+["']${escaped}(\\.m?[jt]sx?)?["']`).test(text)) return null;
|
|
170
|
+
const lines = text.split("\n");
|
|
171
|
+
let at = 0;
|
|
172
|
+
while (at < lines.length && (/^#!/.test(lines[at]) || /^\s*["']use (client|strict)["'];?\s*$/.test(lines[at]))) at += 1;
|
|
173
|
+
lines.splice(at, 0, `import "${spec}";`);
|
|
174
|
+
return lines.join("\n");
|
|
175
|
+
}
|
|
176
|
+
function detectIndent(text) {
|
|
177
|
+
const match = /^[ \t]+(?=")/m.exec(text);
|
|
178
|
+
return match ? match[0] : 2;
|
|
179
|
+
}
|
|
180
|
+
async function plan(packageDir, pkg, setup, entryOverride, cwd) {
|
|
181
|
+
const framework = detectFramework(pkg);
|
|
182
|
+
const typescript = existsSync(join(packageDir, "tsconfig.json"));
|
|
183
|
+
const ext = typescript ? "ts" : "js";
|
|
184
|
+
const warnings = [];
|
|
185
|
+
const source = initSource(setup);
|
|
186
|
+
let initFile;
|
|
187
|
+
let entryFile = null;
|
|
188
|
+
if (framework === "nextjs" && !entryOverride) {
|
|
189
|
+
const useSrc = existsSync(join(packageDir, "src/app")) || existsSync(join(packageDir, "src/pages"));
|
|
190
|
+
initFile = existing(packageDir, useSrc ? "src/instrumentation-client" : "instrumentation-client") ?? `${useSrc ? "src/" : ""}instrumentation-client.${ext}`;
|
|
191
|
+
const version = /(\d+)\.(\d+)/.exec(deps(pkg).next ?? "");
|
|
192
|
+
if (version && (Number(version[1]) < 15 || Number(version[1]) === 15 && Number(version[2]) < 3)) {
|
|
193
|
+
warnings.push(
|
|
194
|
+
`Next.js ${version[0]} does not load ${initFile} (needs 15.3+). Import it at the top of your root layout or _app, or upgrade Next.js`
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
} else {
|
|
198
|
+
if (entryOverride) {
|
|
199
|
+
const abs = resolve(cwd, entryOverride);
|
|
200
|
+
if (!existsSync(abs) || !statSync(abs).isFile()) throw new UsageError(`--entry ${entryOverride} is not a file`);
|
|
201
|
+
entryFile = toPosix(relative(packageDir, abs));
|
|
202
|
+
if (entryFile.startsWith("..")) throw new UsageError(`--entry must be inside ${packageDir}`);
|
|
203
|
+
} else if (framework === "vite") {
|
|
204
|
+
entryFile = await viteEntry(packageDir);
|
|
205
|
+
} else {
|
|
206
|
+
entryFile = existing(packageDir, "src/index") ?? existing(packageDir, "src/main");
|
|
207
|
+
}
|
|
208
|
+
const dir = entryFile ? posix.dirname(entryFile) : existsSync(join(packageDir, "src")) ? "src" : ".";
|
|
209
|
+
const entryExt = entryFile && /\.(m?ts|tsx)$/.test(entryFile) ? "ts" : entryFile ? "js" : ext;
|
|
210
|
+
initFile = existing(packageDir, posix.join(dir, "bugwatch")) ?? posix.join(dir, `bugwatch.${entryExt}`);
|
|
211
|
+
if (!entryFile) {
|
|
212
|
+
warnings.push(`Could not find your app's entry file. Import ./${initFile} first thing in it (or re-run with --entry <file>)`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
let initContent = source;
|
|
216
|
+
let initAction = "create";
|
|
217
|
+
const initPath = join(packageDir, initFile);
|
|
218
|
+
if (existsSync(initPath)) {
|
|
219
|
+
const current = await readFile(initPath, "utf8");
|
|
220
|
+
if (current.includes("Bugwatch.init")) {
|
|
221
|
+
const replaced = replaceApiKey(current, setup.apiKey);
|
|
222
|
+
if (replaced === null) {
|
|
223
|
+
warnings.push(`${initFile} already calls Bugwatch.init without an apiKey string; check it uses ${setup.apiKey}`);
|
|
224
|
+
initAction = "keep";
|
|
225
|
+
initContent = current;
|
|
226
|
+
} else {
|
|
227
|
+
initAction = replaced === current ? "keep" : "update";
|
|
228
|
+
initContent = replaced;
|
|
229
|
+
}
|
|
230
|
+
} else {
|
|
231
|
+
initAction = "update";
|
|
232
|
+
initContent = `${source}
|
|
233
|
+
${current}`;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
let entry;
|
|
237
|
+
if (entryFile && entryFile !== initFile) {
|
|
238
|
+
const text = await readFile(join(packageDir, entryFile), "utf8");
|
|
239
|
+
const updated = addImport(text, importSpecifier(entryFile, initFile));
|
|
240
|
+
if (updated !== null) entry = { file: entryFile, content: updated };
|
|
241
|
+
}
|
|
242
|
+
return { framework, initFile, initContent, initAction, ...entry ? { entry } : {}, warnings };
|
|
243
|
+
}
|
|
244
|
+
async function initProject(options) {
|
|
245
|
+
const out = options.out ?? ((line) => process.stdout.write(`${line}
|
|
246
|
+
`));
|
|
247
|
+
const err = options.err ?? ((line) => process.stderr.write(`${line}
|
|
248
|
+
`));
|
|
249
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
250
|
+
const apiUrl = options.apiUrl || DEFAULT_API_URL;
|
|
251
|
+
const dryRun = options.dryRun === true;
|
|
252
|
+
const problem = setupCodeProblem(options.setupCode);
|
|
253
|
+
if (problem) throw new UsageError(problem);
|
|
254
|
+
const gitRoot = findUp(cwd, ".git");
|
|
255
|
+
if (!gitRoot) throw new UsageError("Run this inside your project's git repository (no .git folder found)");
|
|
256
|
+
const packageDir = findUp(cwd, "package.json", gitRoot);
|
|
257
|
+
if (!packageDir) throw new UsageError("No package.json found. Run this in your JavaScript app's folder");
|
|
258
|
+
const setup = await fetchSetup(apiUrl, options.setupCode, err, options.timeouts);
|
|
259
|
+
out(`Bugwatch project "${setup.projectName}" for ${setup.repo.fullName}`);
|
|
260
|
+
const warnings = [];
|
|
261
|
+
const remote = await gitRemote(gitRoot);
|
|
262
|
+
const remoteName = remote ? remoteRepo(remote) : null;
|
|
263
|
+
if (remoteName && remoteName !== setup.repo.fullName.toLowerCase()) {
|
|
264
|
+
warnings.push(`This repository's origin is ${remoteName}, but the setup is for ${setup.repo.fullName}. Bugwatch verifies ${setup.repo.fullName}`);
|
|
265
|
+
}
|
|
266
|
+
const pkgPath = join(packageDir, "package.json");
|
|
267
|
+
const pkgText = await readFile(pkgPath, "utf8");
|
|
268
|
+
const pkg = await readJson(pkgPath);
|
|
269
|
+
const steps = await plan(packageDir, pkg, setup, options.entry, cwd);
|
|
270
|
+
warnings.push(...steps.warnings);
|
|
271
|
+
const packageManager = detectPackageManager(packageDir, gitRoot);
|
|
272
|
+
const hasSdk = Boolean(deps(pkg).bugwatch);
|
|
273
|
+
const fromRoot = (file) => toPosix(relative(gitRoot, join(packageDir, file))) || ".";
|
|
274
|
+
const packageDirRel = toPosix(relative(gitRoot, packageDir)) || ".";
|
|
275
|
+
const changed = [];
|
|
276
|
+
let installed = false;
|
|
277
|
+
if (!hasSdk) {
|
|
278
|
+
const { command, args } = installCommand(packageManager);
|
|
279
|
+
if (dryRun) {
|
|
280
|
+
out(`would run ${options.skipInstall ? `(skipped) add bugwatch@${SDK_VERSION_RANGE} to package.json` : `${command} ${args.join(" ")}`}`);
|
|
281
|
+
} else if (options.skipInstall) {
|
|
282
|
+
const dependencies = typeof pkg.dependencies === "object" && pkg.dependencies !== null ? pkg.dependencies : {};
|
|
283
|
+
pkg.dependencies = { ...dependencies, bugwatch: SDK_VERSION_RANGE };
|
|
284
|
+
await writeFile(pkgPath, `${JSON.stringify(pkg, null, detectIndent(pkgText))}
|
|
285
|
+
`);
|
|
286
|
+
out(`added bugwatch@${SDK_VERSION_RANGE} to ${fromRoot("package.json")} (run ${command} install yourself)`);
|
|
287
|
+
changed.push(fromRoot("package.json"));
|
|
288
|
+
} else {
|
|
289
|
+
out(`running ${command} ${args.join(" ")}`);
|
|
290
|
+
const code = await (options.runInstall ?? defaultRunInstall)(command, args, packageDir);
|
|
291
|
+
if (code !== 0) {
|
|
292
|
+
throw new Error(`${command} ${args.join(" ")} failed (exit ${code}). Fix the install and run this command again`);
|
|
293
|
+
}
|
|
294
|
+
installed = true;
|
|
295
|
+
changed.push(fromRoot("package.json"));
|
|
296
|
+
}
|
|
297
|
+
} else {
|
|
298
|
+
out(`kept bugwatch is already in ${fromRoot("package.json")}`);
|
|
299
|
+
}
|
|
300
|
+
const verb = dryRun ? "would " : "";
|
|
301
|
+
if (steps.initAction === "keep") {
|
|
302
|
+
out(`kept ${fromRoot(steps.initFile)} (already calls Bugwatch.init)`);
|
|
303
|
+
} else {
|
|
304
|
+
if (!dryRun) await writeFile(join(packageDir, steps.initFile), steps.initContent);
|
|
305
|
+
out(`${verb}${steps.initAction === "create" ? "create" : "update"}`.padEnd(12) + fromRoot(steps.initFile));
|
|
306
|
+
changed.push(fromRoot(steps.initFile));
|
|
307
|
+
}
|
|
308
|
+
if (steps.entry) {
|
|
309
|
+
if (!dryRun) await writeFile(join(packageDir, steps.entry.file), steps.entry.content);
|
|
310
|
+
out(`${verb}update`.padEnd(12) + `${fromRoot(steps.entry.file)} (imports the Bugwatch setup first)`);
|
|
311
|
+
changed.push(fromRoot(steps.entry.file));
|
|
312
|
+
}
|
|
313
|
+
const marker = {
|
|
314
|
+
$comment: "Written by bugwatch-cli init. Bugwatch reads this file to verify the setup; it holds no secrets.",
|
|
315
|
+
setupId: setup.setupId,
|
|
316
|
+
project: setup.projectName,
|
|
317
|
+
packageDir: packageDirRel,
|
|
318
|
+
initFile: steps.initFile,
|
|
319
|
+
framework: steps.framework
|
|
320
|
+
};
|
|
321
|
+
if (!dryRun) await writeFile(join(gitRoot, MARKER_FILE), `${JSON.stringify(marker, null, 2)}
|
|
322
|
+
`);
|
|
323
|
+
out(`${verb}write`.padEnd(12) + MARKER_FILE);
|
|
324
|
+
changed.push(MARKER_FILE);
|
|
325
|
+
for (const warning of warnings) err(`Warning: ${warning}`);
|
|
326
|
+
out("");
|
|
327
|
+
if (dryRun) {
|
|
328
|
+
out("Dry run: nothing was installed or written.");
|
|
329
|
+
} else {
|
|
330
|
+
out("Done. Review the changes, then commit and push them:");
|
|
331
|
+
out("");
|
|
332
|
+
out(` git add ${[...new Set(changed)].map((file) => /\s/.test(file) ? JSON.stringify(file) : file).join(" ")}`);
|
|
333
|
+
out(` git commit -m "Add Bugwatch error tracking"`);
|
|
334
|
+
out(` git push origin ${setup.repo.defaultBranch}`);
|
|
335
|
+
out("");
|
|
336
|
+
out("Then press Verify in Bugwatch. If you push to another branch, enter it next to Verify.");
|
|
337
|
+
}
|
|
338
|
+
return {
|
|
339
|
+
setup,
|
|
340
|
+
framework: steps.framework,
|
|
341
|
+
packageManager,
|
|
342
|
+
packageDir: packageDirRel,
|
|
343
|
+
initFile: steps.initFile,
|
|
344
|
+
changed: [...new Set(changed)],
|
|
345
|
+
installed,
|
|
346
|
+
warnings
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
export {
|
|
351
|
+
MARKER_FILE,
|
|
352
|
+
DEFAULT_INGEST_URL,
|
|
353
|
+
setupCodeProblem,
|
|
354
|
+
detectFramework,
|
|
355
|
+
detectPackageManager,
|
|
356
|
+
installCommand,
|
|
357
|
+
remoteRepo,
|
|
358
|
+
replaceApiKey,
|
|
359
|
+
importSpecifier,
|
|
360
|
+
addImport,
|
|
361
|
+
initProject
|
|
362
|
+
};
|
package/dist/cli.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
main
|
|
4
|
-
} from "./chunk-
|
|
5
|
-
import "./chunk-
|
|
4
|
+
} from "./chunk-ODCYZAF4.js";
|
|
5
|
+
import "./chunk-T5NSQVQH.js";
|
|
6
|
+
import "./chunk-UIBXO6IR.js";
|
|
6
7
|
|
|
7
8
|
// src/cli.ts
|
|
8
9
|
main(process.argv.slice(2)).then((code) => {
|
package/dist/index.d.ts
CHANGED
|
@@ -139,7 +139,80 @@ declare function formatSummary(summary: UploadSummary, { dryRun, release, files
|
|
|
139
139
|
files: number;
|
|
140
140
|
}): string;
|
|
141
141
|
|
|
142
|
+
/**
|
|
143
|
+
* `bugwatch-cli init --setup bws_…` (Bugwatch "Add from GitHub", backend Step 53):
|
|
144
|
+
* fetches a pending setup, installs the `bugwatch` SDK, writes the
|
|
145
|
+
* `Bugwatch.init` code, and writes `.bugwatch.json` at the git root so Bugwatch
|
|
146
|
+
* can verify the push. It never commits or pushes.
|
|
147
|
+
*/
|
|
148
|
+
declare const MARKER_FILE = ".bugwatch.json";
|
|
149
|
+
/** The SDK's default ingest endpoint; `endpoint` is only written for another one. */
|
|
150
|
+
declare const DEFAULT_INGEST_URL = "https://sentry-like.vercel.app/api/ingest";
|
|
151
|
+
type Framework = "nextjs" | "vite" | "cra" | "other";
|
|
152
|
+
type PackageManager = "npm" | "pnpm" | "yarn" | "bun";
|
|
153
|
+
interface CliSetup {
|
|
154
|
+
setupId: string;
|
|
155
|
+
projectName: string;
|
|
156
|
+
apiKey: string;
|
|
157
|
+
ingestUrl: string;
|
|
158
|
+
repo: {
|
|
159
|
+
fullName: string;
|
|
160
|
+
defaultBranch: string;
|
|
161
|
+
};
|
|
162
|
+
expiresAt: string;
|
|
163
|
+
}
|
|
164
|
+
interface InitOptions {
|
|
165
|
+
setupCode: string;
|
|
166
|
+
apiUrl?: string;
|
|
167
|
+
/** Where the command runs; the nearest package.json at or above it is the app. Default: process.cwd(). */
|
|
168
|
+
cwd?: string;
|
|
169
|
+
/** The app's entry file (relative to cwd) to import the init file from, instead of detecting it. */
|
|
170
|
+
entry?: string;
|
|
171
|
+
/** Do not run the package manager; add `bugwatch` to package.json instead. */
|
|
172
|
+
skipInstall?: boolean;
|
|
173
|
+
dryRun?: boolean;
|
|
174
|
+
out?: (line: string) => void;
|
|
175
|
+
err?: (line: string) => void;
|
|
176
|
+
/** Runs the install command; returns its exit code. Tests replace it. */
|
|
177
|
+
runInstall?: (command: string, args: string[], cwd: string) => Promise<number>;
|
|
178
|
+
/** How long to wait for Bugwatch (default 90 s) and when to say it is waking up (default 5 s). Tests shorten them. */
|
|
179
|
+
timeouts?: {
|
|
180
|
+
fetchMs?: number;
|
|
181
|
+
slowNoticeMs?: number;
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
interface InitReport {
|
|
185
|
+
setup: CliSetup;
|
|
186
|
+
framework: Framework;
|
|
187
|
+
packageManager: PackageManager;
|
|
188
|
+
/** Folder with package.json, relative to the git root (`.` at the root). */
|
|
189
|
+
packageDir: string;
|
|
190
|
+
/** The file that calls Bugwatch.init, relative to packageDir. */
|
|
191
|
+
initFile: string;
|
|
192
|
+
/** Files written or changed, relative to the git root. */
|
|
193
|
+
changed: string[];
|
|
194
|
+
installed: boolean;
|
|
195
|
+
warnings: string[];
|
|
196
|
+
}
|
|
197
|
+
declare function setupCodeProblem(code: string | undefined): string | null;
|
|
198
|
+
declare function detectFramework(pkg: Record<string, unknown>): Framework;
|
|
199
|
+
declare function detectPackageManager(packageDir: string, gitRoot: string): PackageManager;
|
|
200
|
+
declare function installCommand(pm: PackageManager): {
|
|
201
|
+
command: string;
|
|
202
|
+
args: string[];
|
|
203
|
+
};
|
|
204
|
+
/** `git@github.com:acme/shop.git` / `https://github.com/acme/shop` → `acme/shop`. */
|
|
205
|
+
declare function remoteRepo(remote: string): string | null;
|
|
206
|
+
/** Replaces the apiKey string literal in an existing init call; null when there is none to replace. */
|
|
207
|
+
declare function replaceApiKey(text: string, apiKey: string): string | null;
|
|
208
|
+
/** `import "./bugwatch";` from `entry` to `initFile` (both relative to packageDir), without the extension. */
|
|
209
|
+
declare function importSpecifier(entry: string, initFile: string): string;
|
|
210
|
+
/** Puts `import "<spec>";` first in the file, after any "use client" / shebang lines. */
|
|
211
|
+
declare function addImport(text: string, spec: string): string | null;
|
|
212
|
+
/** Runs `init`. Throws UsageError for user mistakes, Error for failures. */
|
|
213
|
+
declare function initProject(options: InitOptions): Promise<InitReport>;
|
|
214
|
+
|
|
142
215
|
/** Keep in sync with package.json (a test checks it). */
|
|
143
|
-
declare const VERSION = "0.
|
|
216
|
+
declare const VERSION = "0.4.1";
|
|
144
217
|
|
|
145
|
-
export { CONCURRENCY, DEFAULT_API_URL, DEFAULT_URL_PREFIX, type FileResult, MAX_MAP_BYTES, MAX_RETRIES, type Outcome, type PlannedUpload, STOP_CODES, UPLOAD_TOKEN_DEPRECATED, type UploadOptions, type UploadReport, type UploadSummary, UsageError, VERSION, findMapOwners, findSourceMaps, formatBytes, formatResult, formatSummary, isCiToken, isCssMap, isDeprecatedUploadToken, mapName, planUploads, projectProblem, releaseProblem, sendableMapFile, sourceMappingUrlOf, uploadSourceMaps, urlPrefixProblem };
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_INGEST_URL,
|
|
3
|
+
MARKER_FILE,
|
|
4
|
+
addImport,
|
|
5
|
+
detectFramework,
|
|
6
|
+
detectPackageManager,
|
|
7
|
+
importSpecifier,
|
|
8
|
+
initProject,
|
|
9
|
+
installCommand,
|
|
10
|
+
remoteRepo,
|
|
11
|
+
replaceApiKey,
|
|
12
|
+
setupCodeProblem
|
|
13
|
+
} from "./chunk-T5NSQVQH.js";
|
|
1
14
|
import {
|
|
2
15
|
CONCURRENCY,
|
|
3
16
|
DEFAULT_API_URL,
|
|
@@ -24,22 +37,30 @@ import {
|
|
|
24
37
|
sourceMappingUrlOf,
|
|
25
38
|
uploadSourceMaps,
|
|
26
39
|
urlPrefixProblem
|
|
27
|
-
} from "./chunk-
|
|
40
|
+
} from "./chunk-UIBXO6IR.js";
|
|
28
41
|
export {
|
|
29
42
|
CONCURRENCY,
|
|
30
43
|
DEFAULT_API_URL,
|
|
44
|
+
DEFAULT_INGEST_URL,
|
|
31
45
|
DEFAULT_URL_PREFIX,
|
|
46
|
+
MARKER_FILE,
|
|
32
47
|
MAX_MAP_BYTES,
|
|
33
48
|
MAX_RETRIES,
|
|
34
49
|
STOP_CODES,
|
|
35
50
|
UPLOAD_TOKEN_DEPRECATED,
|
|
36
51
|
UsageError,
|
|
37
52
|
VERSION,
|
|
53
|
+
addImport,
|
|
54
|
+
detectFramework,
|
|
55
|
+
detectPackageManager,
|
|
38
56
|
findMapOwners,
|
|
39
57
|
findSourceMaps,
|
|
40
58
|
formatBytes,
|
|
41
59
|
formatResult,
|
|
42
60
|
formatSummary,
|
|
61
|
+
importSpecifier,
|
|
62
|
+
initProject,
|
|
63
|
+
installCommand,
|
|
43
64
|
isCiToken,
|
|
44
65
|
isCssMap,
|
|
45
66
|
isDeprecatedUploadToken,
|
|
@@ -47,7 +68,10 @@ export {
|
|
|
47
68
|
planUploads,
|
|
48
69
|
projectProblem,
|
|
49
70
|
releaseProblem,
|
|
71
|
+
remoteRepo,
|
|
72
|
+
replaceApiKey,
|
|
50
73
|
sendableMapFile,
|
|
74
|
+
setupCodeProblem,
|
|
51
75
|
sourceMappingUrlOf,
|
|
52
76
|
uploadSourceMaps,
|
|
53
77
|
urlPrefixProblem
|
package/dist/main.js
CHANGED
package/dist/vite.js
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bugwatch-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.4.1",
|
|
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": {
|
|
7
7
|
"bugwatch-cli": "dist/cli.js"
|