@getmonitor/cli 0.3.2 → 0.3.4

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
@@ -9,7 +9,7 @@ as part of a customer's build.
9
9
  For every `*.js` file with a resolvable source map under a directory, `processSourceMaps`:
10
10
 
11
11
  1. Generates a debug ID and injects it into both the JS file and its source map.
12
- 2. Uploads the tagged source map to `https://ingest.getmonitor.io/api/v1/sourcemaps` — the
12
+ 2. Uploads the tagged source map to `https://track.getmonitor.io/api/v1/sourcemaps` — the
13
13
  upload host is fixed and not customer-configurable.
14
14
  3. On a successful upload: deletes the `.map` file and strips the `//# sourceMappingURL=`
15
15
  comment from the JS file, so nothing readable ships publicly.
package/dist/bin.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ interface ParsedArgs {
2
+ directory: string;
3
+ release?: string;
4
+ authToken?: string;
5
+ }
6
+ /** Exported (not just used internally) so it's unit-testable without spawning a process. */
7
+ export declare function parseArgs(argv: string[]): ParsedArgs;
8
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,346 @@
1
+ #!/usr/bin/env node
2
+ import { randomUUID } from 'node:crypto';
3
+ import { readdirSync, existsSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
4
+ import { join, dirname, relative } from 'node:path';
5
+ import { execFileSync } from 'node:child_process';
6
+
7
+ // packages/cli/src/discoverArtifacts.ts
8
+ const SOURCE_MAPPING_URL = /^\s*\/\/#\s*sourceMappingURL=(\S+)\s*$/gm;
9
+ // Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit
10
+ // ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's "type") — all three
11
+ // show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e
12
+ // test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real
13
+ // `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and
14
+ // unstripped even though `.output/` itself was already fully written by the time discovery ran.
15
+ const JS_EXTENSIONS = ['.js', '.mjs', '.cjs'];
16
+ /** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its
17
+ * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the
18
+ * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,
19
+ * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no
20
+ * resolvable map either way is skipped. */
21
+ function discoverArtifacts(directory) {
22
+ const artifacts = [];
23
+ walk(directory, artifacts);
24
+ return artifacts;
25
+ }
26
+ function walk(dir, artifacts) {
27
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
28
+ const fullPath = join(dir, entry.name);
29
+ if (entry.isDirectory()) {
30
+ walk(fullPath, artifacts);
31
+ }
32
+ else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
33
+ const mapPath = resolveMapPath(fullPath);
34
+ if (mapPath)
35
+ artifacts.push({ jsPath: fullPath, mapPath });
36
+ }
37
+ }
38
+ }
39
+ function resolveMapPath(jsPath) {
40
+ const commentMapPath = readSourceMappingUrlComment(jsPath);
41
+ if (commentMapPath && existsSync(commentMapPath))
42
+ return commentMapPath;
43
+ const fallbackMapPath = `${jsPath}.map`;
44
+ if (existsSync(fallbackMapPath))
45
+ return fallbackMapPath;
46
+ return undefined;
47
+ }
48
+ function readSourceMappingUrlComment(jsPath) {
49
+ let content;
50
+ try {
51
+ content = readFileSync(jsPath, 'utf8');
52
+ }
53
+ catch {
54
+ // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it
55
+ // like "no comment found" rather than aborting the whole discoverArtifacts() walk.
56
+ return undefined;
57
+ }
58
+ const matches = [...content.matchAll(SOURCE_MAPPING_URL)];
59
+ if (matches.length === 0)
60
+ return undefined;
61
+ // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat
62
+ // concatenated/reprocessed output — later comments supersede earlier ones.
63
+ const reference = matches.at(-1)[1];
64
+ if (reference.startsWith('data:'))
65
+ return undefined; // embedded map, nothing to discover on disk
66
+ return join(dirname(jsPath), reference);
67
+ }
68
+
69
+ // packages/cli/src/injectDebugId.ts
70
+ /** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in
71
+ * memory — callers decide whether/when to persist the result to disk (processSourceMaps
72
+ * only writes it after a successful upload, so a failed upload never leaves partially
73
+ * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)
74
+ * removed, since the source map it names is only ever kept in GetMonitor's backend after
75
+ * a successful upload — never served publicly alongside it.
76
+ *
77
+ * `originalMapJson` must be valid JSON — this is a pure function with no fallback to
78
+ * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's
79
+ * caller expects a definite result), so a malformed map is left to throw via JSON.parse
80
+ * rather than being swallowed here. */
81
+ function injectDebugId(originalJs, originalMapJson, debugId) {
82
+ const withoutMapComment = originalJs
83
+ .split('\n')
84
+ .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))
85
+ .join('\n');
86
+ const map = JSON.parse(originalMapJson);
87
+ map.debugId = debugId;
88
+ return {
89
+ js: `${withoutMapComment}\n${buildInjectedSnippet(debugId)}`,
90
+ map: JSON.stringify(map),
91
+ };
92
+ }
93
+ /** At load time, captures this statement's own `Error().stack`, extracts this file's
94
+ * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for
95
+ * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's
96
+ * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,
97
+ * it scans every stack line and takes the first one that matches any of those shapes, rather
98
+ * than assuming a fixed line index — V8 prefixes an `"ErrorType: message"` header line that
99
+ * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong
100
+ * file's identity) on non-V8 engines; the header line simply fails to match any frame regex
101
+ * and is skipped automatically. A later real error whose frame.filename is parsed from the
102
+ * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any
103
+ * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak
104
+ * into the file's module scope.
105
+ *
106
+ * `debugId` is interpolated unescaped into the generated snippet's string literal. That's
107
+ * safe today because every caller in this system sources `debugId` from
108
+ * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but
109
+ * this function itself doesn't enforce that shape, so a caller passing an arbitrary string
110
+ * containing `'` or `\` would produce invalid/injected JS here. Flagged, not fixed, since
111
+ * validating/escaping isn't part of this function's specified contract. */
112
+ function buildInjectedSnippet(debugId) {
113
+ return (";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\n');var m=null;" +
114
+ 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +
115
+ "m=l.match(/\\((.*):(\\d+):(\\d+)\\)\\s*$/)||l.match(/at (.*):(\\d+):(\\d+)\\s*$/)||l.match(/@(.*):(\\d+):(\\d+)\\s*$/)}" +
116
+ "var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);" +
117
+ `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +
118
+ '}}catch(e){}})();');
119
+ }
120
+
121
+ // packages/cli/src/resolveRelease.ts
122
+ /** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit
123
+ * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside
124
+ * a git working tree) -> `version` field of the nearest package.json walking up from
125
+ * `directory`. Matches the SDKs' own optional `release` field so events and source maps
126
+ * for the same deploy carry the same value. */
127
+ function resolveRelease(directory, explicit) {
128
+ if (explicit)
129
+ return explicit;
130
+ if (process.env.GETMONITOR_RELEASE)
131
+ return process.env.GETMONITOR_RELEASE;
132
+ const gitSha = tryGitSha(directory);
133
+ if (gitSha)
134
+ return gitSha;
135
+ const packageVersion = tryPackageVersion(directory);
136
+ if (packageVersion)
137
+ return packageVersion;
138
+ throw new Error('Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a "version" field.');
139
+ }
140
+ function tryGitSha(directory) {
141
+ try {
142
+ return execFileSync('git', ['rev-parse', 'HEAD'], {
143
+ cwd: directory,
144
+ encoding: 'utf8',
145
+ stdio: ['ignore', 'pipe', 'ignore'],
146
+ }).trim();
147
+ }
148
+ catch {
149
+ return undefined;
150
+ }
151
+ }
152
+ function tryPackageVersion(directory) {
153
+ let dir = directory;
154
+ for (let i = 0; i < 20; i++) {
155
+ const pkgPath = join(dir, 'package.json');
156
+ if (existsSync(pkgPath)) {
157
+ try {
158
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
159
+ return typeof pkg.version === 'string' ? pkg.version : undefined;
160
+ }
161
+ catch {
162
+ return undefined;
163
+ }
164
+ }
165
+ const parent = dirname(dir);
166
+ if (parent === dir)
167
+ return undefined;
168
+ dir = parent;
169
+ }
170
+ return undefined;
171
+ }
172
+
173
+ // packages/cli/src/uploadSourceMap.ts
174
+ /** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */
175
+ const DEFAULT_API_HOST = 'https://track.getmonitor.io';
176
+ /** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.
177
+ * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides
178
+ * what "failed" means for its own result reporting and disk-write ordering. */
179
+ async function uploadSourceMap(params) {
180
+ // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native
181
+ // fetch() throws "Illegal invocation" if called with a `this` other than
182
+ // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below
183
+ // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this
184
+ // bind is defensive/consistent rather than load-bearing for this particular call site — but
185
+ // keeping the same default expression as HttpTransport avoids a divergent default if this
186
+ // code is ever refactored into a method.
187
+ const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis);
188
+ const apiHost = params.apiHost ?? DEFAULT_API_HOST;
189
+ const form = new FormData();
190
+ form.set('release', params.release);
191
+ form.set('debugId', params.debugId);
192
+ form.set('filename', params.filename);
193
+ form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`);
194
+ const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {
195
+ method: 'POST',
196
+ headers: { Authorization: `Bearer ${params.authToken}` },
197
+ body: form,
198
+ });
199
+ if (!response.ok) {
200
+ throw new Error(`Source map upload failed for ${params.filename}: ${response.status} ${response.statusText}`);
201
+ }
202
+ }
203
+
204
+ // packages/cli/src/processSourceMaps.ts
205
+ /** Number of artifacts uploaded at once. Each upload is an independent network round trip to
206
+ * ingester-api, so processing them one at a time made wall-clock time scale linearly with
207
+ * artifact count for no reason — a real Next.js build can emit well over a thousand of them,
208
+ * turning a few hundred ms of per-file latency into many minutes of serial waiting. */
209
+ const UPLOAD_CONCURRENCY = 20;
210
+ /** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a
211
+ * debug ID, uploads the tagged source map, and — only on a successful upload — writes the
212
+ * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload
213
+ * fails is left completely untouched on disk, so it can be retried by re-running this
214
+ * function against the same directory. Artifacts are uploaded concurrently (bounded by
215
+ * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match
216
+ * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */
217
+ async function processSourceMaps(options) {
218
+ const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN;
219
+ if (!authToken) {
220
+ throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.');
221
+ }
222
+ const release = resolveRelease(options.directory, options.release);
223
+ const artifacts = discoverArtifacts(options.directory);
224
+ // Indexed by each artifact's position in `artifacts` rather than appended in completion
225
+ // order, so the final result below is deterministic no matter which worker finishes first.
226
+ const outcomes = new Array(artifacts.length);
227
+ const processOne = async (index) => {
228
+ const artifact = artifacts[index];
229
+ const debugId = randomUUID();
230
+ let injected;
231
+ try {
232
+ const originalJs = readFileSync(artifact.jsPath, 'utf8');
233
+ const originalMap = readFileSync(artifact.mapPath, 'utf8');
234
+ // injectDebugId is a pure function that throws on malformed map JSON (by design — see
235
+ // its own doc comment). That's deliberately caught here, alongside upload failures: one
236
+ // corrupt/unreadable artifact on disk must not abort processing of every other artifact
237
+ // in the directory, the same failure-isolation principle discoverArtifacts applies to
238
+ // unreadable files during its walk. Nothing has been uploaded or written yet at this
239
+ // point, so a thrown injectDebugId or upload failure leaves the artifact's files
240
+ // completely untouched, and it's safe to report it as `failed` for a retry.
241
+ injected = injectDebugId(originalJs, originalMap, debugId);
242
+ await uploadSourceMap({
243
+ apiHost: options.apiHost,
244
+ authToken,
245
+ release,
246
+ debugId,
247
+ // Relative to options.directory, not the absolute on-disk path — the backend has no
248
+ // use for (and shouldn't see) the build machine's local filesystem layout.
249
+ filename: relative(options.directory, artifact.jsPath),
250
+ mapContent: injected.map,
251
+ fetchImpl: options.fetchImpl,
252
+ });
253
+ }
254
+ catch (error) {
255
+ // Surfaced here rather than swallowed: this is the only place the actual failure reason
256
+ // (injectDebugId's malformed-JSON error, or uploadSourceMap's `status statusText` message)
257
+ // is available. Without logging it, callers only ever see a bare list of failed paths with
258
+ // no way to tell an auth failure from a malformed map from a network error.
259
+ console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error);
260
+ outcomes[index] = { path: artifact.jsPath, ok: false };
261
+ return;
262
+ }
263
+ try {
264
+ writeFileSync(artifact.jsPath, injected.js);
265
+ rmSync(artifact.mapPath);
266
+ outcomes[index] = { path: artifact.jsPath, ok: true };
267
+ }
268
+ catch (cleanupError) {
269
+ // The upload above already succeeded, so this must never land in `failed` — a caller
270
+ // retrying failed artifacts would mint a fresh debugId and re-upload, orphaning this
271
+ // upload server-side under the old one with no way to reconcile the two. The local
272
+ // cleanup failure (disk full, permission error, file lock) is real and worth knowing
273
+ // about, so it's surfaced here rather than silently swallowed, but it doesn't change
274
+ // the artifact's outcome.
275
+ outcomes[index] = { path: artifact.jsPath, ok: true };
276
+ console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError);
277
+ }
278
+ };
279
+ // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared
280
+ // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.
281
+ let nextIndex = 0;
282
+ const runWorker = async () => {
283
+ while (nextIndex < artifacts.length) {
284
+ const index = nextIndex++;
285
+ await processOne(index);
286
+ }
287
+ };
288
+ const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length);
289
+ await Promise.all(Array.from({ length: workerCount }, runWorker));
290
+ const result = { uploaded: [], failed: [] };
291
+ for (const outcome of outcomes) {
292
+ (outcome.ok ? result.uploaded : result.failed).push(outcome.path);
293
+ }
294
+ return result;
295
+ }
296
+
297
+ // packages/cli/src/bin.ts
298
+ /** Exported (not just used internally) so it's unit-testable without spawning a process. */
299
+ function parseArgs(argv) {
300
+ const [command, subcommand, directory, ...rest] = argv;
301
+ if (command !== 'sourcemaps' || subcommand !== 'upload' || !directory) {
302
+ throw new Error('Usage: getmonitor sourcemaps upload <directory> [--release <release>] [--auth-token <token>]');
303
+ }
304
+ let release;
305
+ let authToken;
306
+ for (let i = 0; i < rest.length; i += 2) {
307
+ const flag = rest[i];
308
+ const value = rest[i + 1];
309
+ if (flag === '--release')
310
+ release = value;
311
+ else if (flag === '--auth-token')
312
+ authToken = value;
313
+ else
314
+ throw new Error(`Unknown flag: ${flag}`);
315
+ }
316
+ return { directory, release, authToken };
317
+ }
318
+ async function main() {
319
+ const args = parseArgs(process.argv.slice(2));
320
+ const result = await processSourceMaps({
321
+ directory: args.directory,
322
+ release: args.release,
323
+ authToken: args.authToken,
324
+ });
325
+ console.log(`Uploaded ${result.uploaded.length} source map(s).`);
326
+ if (result.failed.length > 0) {
327
+ console.error(`Failed to upload ${result.failed.length} source map(s):`);
328
+ for (const file of result.failed)
329
+ console.error(` ${file}`);
330
+ process.exitCode = 1;
331
+ }
332
+ }
333
+ // Skipped under Vitest (which imports this module to test parseArgs) — only run when
334
+ // invoked directly as the built dist/bin.js executable. Confirmed empirically that Vitest
335
+ // sets process.env.VITEST = 'true' in the process that loads this module, so this check
336
+ // reliably prevents main() (which does real I/O and can set process.exitCode) from running
337
+ // during `pnpm test`.
338
+ if (process.env.VITEST === undefined) {
339
+ main().catch((error) => {
340
+ console.error(error instanceof Error ? error.message : error);
341
+ process.exitCode = 1;
342
+ });
343
+ }
344
+
345
+ export { parseArgs };
346
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","sources":["../src/discoverArtifacts.ts","../src/injectDebugId.ts","../src/resolveRelease.ts","../src/uploadSourceMap.ts","../src/processSourceMaps.ts","../src/bin.ts"],"sourcesContent":["// packages/cli/src/discoverArtifacts.ts\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Artifact {\n jsPath: string\n mapPath: string\n}\n\nconst SOURCE_MAPPING_URL = /^\\s*\\/\\/#\\s*sourceMappingURL=(\\S+)\\s*$/gm\n\n// Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit\n// ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's \"type\") — all three\n// show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e\n// test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real\n// `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and\n// unstripped even though `.output/` itself was already fully written by the time discovery ran.\nconst JS_EXTENSIONS = ['.js', '.mjs', '.cjs']\n\n/** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its\n * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the\n * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,\n * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no\n * resolvable map either way is skipped. */\nexport function discoverArtifacts(directory: string): Artifact[] {\n const artifacts: Artifact[] = []\n walk(directory, artifacts)\n return artifacts\n}\n\nfunction walk(dir: string, artifacts: Artifact[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(fullPath, artifacts)\n } else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {\n const mapPath = resolveMapPath(fullPath)\n if (mapPath) artifacts.push({ jsPath: fullPath, mapPath })\n }\n }\n}\n\nfunction resolveMapPath(jsPath: string): string | undefined {\n const commentMapPath = readSourceMappingUrlComment(jsPath)\n if (commentMapPath && existsSync(commentMapPath)) return commentMapPath\n\n const fallbackMapPath = `${jsPath}.map`\n if (existsSync(fallbackMapPath)) return fallbackMapPath\n\n return undefined\n}\n\nfunction readSourceMappingUrlComment(jsPath: string): string | undefined {\n let content: string\n try {\n content = readFileSync(jsPath, 'utf8')\n } catch {\n // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it\n // like \"no comment found\" rather than aborting the whole discoverArtifacts() walk.\n return undefined\n }\n\n const matches = [...content.matchAll(SOURCE_MAPPING_URL)]\n if (matches.length === 0) return undefined\n\n // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat\n // concatenated/reprocessed output — later comments supersede earlier ones.\n const reference = matches.at(-1)![1]\n if (reference.startsWith('data:')) return undefined // embedded map, nothing to discover on disk\n\n return join(dirname(jsPath), reference)\n}\n","// packages/cli/src/injectDebugId.ts\n\nexport interface InjectedArtifact {\n js: string\n map: string\n}\n\n/** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in\n * memory — callers decide whether/when to persist the result to disk (processSourceMaps\n * only writes it after a successful upload, so a failed upload never leaves partially\n * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)\n * removed, since the source map it names is only ever kept in GetMonitor's backend after\n * a successful upload — never served publicly alongside it.\n *\n * `originalMapJson` must be valid JSON — this is a pure function with no fallback to\n * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's\n * caller expects a definite result), so a malformed map is left to throw via JSON.parse\n * rather than being swallowed here. */\nexport function injectDebugId(originalJs: string, originalMapJson: string, debugId: string): InjectedArtifact {\n const withoutMapComment = originalJs\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))\n .join('\\n')\n\n const map = JSON.parse(originalMapJson)\n map.debugId = debugId\n\n return {\n js: `${withoutMapComment}\\n${buildInjectedSnippet(debugId)}`,\n map: JSON.stringify(map),\n }\n}\n\n/** At load time, captures this statement's own `Error().stack`, extracts this file's\n * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for\n * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's\n * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,\n * it scans every stack line and takes the first one that matches any of those shapes, rather\n * than assuming a fixed line index — V8 prefixes an `\"ErrorType: message\"` header line that\n * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong\n * file's identity) on non-V8 engines; the header line simply fails to match any frame regex\n * and is skipped automatically. A later real error whose frame.filename is parsed from the\n * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any\n * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak\n * into the file's module scope.\n *\n * `debugId` is interpolated unescaped into the generated snippet's string literal. That's\n * safe today because every caller in this system sources `debugId` from\n * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but\n * this function itself doesn't enforce that shape, so a caller passing an arbitrary string\n * containing `'` or `\\` would produce invalid/injected JS here. Flagged, not fixed, since\n * validating/escaping isn't part of this function's specified contract. */\nfunction buildInjectedSnippet(debugId: string): string {\n return (\n \";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\\\n');var m=null;\" +\n 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +\n \"m=l.match(/\\\\((.*):(\\\\d+):(\\\\d+)\\\\)\\\\s*$/)||l.match(/at (.*):(\\\\d+):(\\\\d+)\\\\s*$/)||l.match(/@(.*):(\\\\d+):(\\\\d+)\\\\s*$/)}\" +\n \"var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);\" +\n `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +\n '}}catch(e){}})();'\n )\n}\n","// packages/cli/src/resolveRelease.ts\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit\n * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside\n * a git working tree) -> `version` field of the nearest package.json walking up from\n * `directory`. Matches the SDKs' own optional `release` field so events and source maps\n * for the same deploy carry the same value. */\nexport function resolveRelease(directory: string, explicit?: string): string {\n if (explicit) return explicit\n if (process.env.GETMONITOR_RELEASE) return process.env.GETMONITOR_RELEASE\n\n const gitSha = tryGitSha(directory)\n if (gitSha) return gitSha\n\n const packageVersion = tryPackageVersion(directory)\n if (packageVersion) return packageVersion\n\n throw new Error(\n 'Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a \"version\" field.',\n )\n}\n\nfunction tryGitSha(directory: string): string | undefined {\n try {\n return execFileSync('git', ['rev-parse', 'HEAD'], {\n cwd: directory,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim()\n } catch {\n return undefined\n }\n}\n\nfunction tryPackageVersion(directory: string): string | undefined {\n let dir = directory\n for (let i = 0; i < 20; i++) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n return typeof pkg.version === 'string' ? pkg.version : undefined\n } catch {\n return undefined\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n return undefined\n}\n","// packages/cli/src/uploadSourceMap.ts\n\n/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */\nexport const DEFAULT_API_HOST = 'https://track.getmonitor.io'\n\nexport interface UploadSourceMapParams {\n /**\n * @internal Test-only override for redirecting delivery to a local mock server (see\n * cli/e2e/processSourceMaps.spec.ts and the nextjs-config/nuxt e2e suites). Never exposed\n * through the public CLI/programmatic surface — real usage always ships to\n * {@link DEFAULT_API_HOST}.\n */\n apiHost?: string\n authToken: string\n release: string\n debugId: string\n filename: string\n mapContent: string\n fetchImpl?: typeof fetch\n}\n\n/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.\n * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides\n * what \"failed\" means for its own result reporting and disk-write ordering. */\nexport async function uploadSourceMap(params: UploadSourceMapParams): Promise<void> {\n // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native\n // fetch() throws \"Illegal invocation\" if called with a `this` other than\n // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below\n // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this\n // bind is defensive/consistent rather than load-bearing for this particular call site — but\n // keeping the same default expression as HttpTransport avoids a divergent default if this\n // code is ever refactored into a method.\n const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis)\n const apiHost = params.apiHost ?? DEFAULT_API_HOST\n\n const form = new FormData()\n form.set('release', params.release)\n form.set('debugId', params.debugId)\n form.set('filename', params.filename)\n form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`)\n\n const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${params.authToken}` },\n body: form,\n })\n\n if (!response.ok) {\n throw new Error(`Source map upload failed for ${params.filename}: ${response.status} ${response.statusText}`)\n }\n}\n","// packages/cli/src/processSourceMaps.ts\nimport { randomUUID } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { relative } from 'node:path'\nimport { discoverArtifacts } from './discoverArtifacts'\nimport { injectDebugId, InjectedArtifact } from './injectDebugId'\nimport { resolveRelease } from './resolveRelease'\nimport { uploadSourceMap } from './uploadSourceMap'\nimport { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types'\n\n/**\n * @internal Test-only host override, intersected into `processSourceMaps`'s options but\n * deliberately not part of the exported `ProcessSourceMapsOptions` type — see\n * `uploadSourceMap`'s `UploadSourceMapParams.apiHost`. Used by this package's own e2e suite\n * and by nextjs-config/nuxt's e2e suites (via their own internal overrides) to redirect\n * delivery to a local mock server; real callers must never set it.\n */\ninterface InternalTestOverrides {\n apiHost?: string\n}\n\n/** Number of artifacts uploaded at once. Each upload is an independent network round trip to\n * ingester-api, so processing them one at a time made wall-clock time scale linearly with\n * artifact count for no reason — a real Next.js build can emit well over a thousand of them,\n * turning a few hundred ms of per-file latency into many minutes of serial waiting. */\nconst UPLOAD_CONCURRENCY = 20\n\n/** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a\n * debug ID, uploads the tagged source map, and — only on a successful upload — writes the\n * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload\n * fails is left completely untouched on disk, so it can be retried by re-running this\n * function against the same directory. Artifacts are uploaded concurrently (bounded by\n * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match\n * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */\nexport async function processSourceMaps(\n options: ProcessSourceMapsOptions & InternalTestOverrides\n): Promise<ProcessSourceMapsResult> {\n const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN\n if (!authToken) {\n throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.')\n }\n\n const release = resolveRelease(options.directory, options.release)\n const artifacts = discoverArtifacts(options.directory)\n // Indexed by each artifact's position in `artifacts` rather than appended in completion\n // order, so the final result below is deterministic no matter which worker finishes first.\n const outcomes: Array<{ path: string; ok: boolean }> = new Array(artifacts.length)\n\n const processOne = async (index: number): Promise<void> => {\n const artifact = artifacts[index]\n const debugId = randomUUID()\n let injected: InjectedArtifact\n\n try {\n const originalJs = readFileSync(artifact.jsPath, 'utf8')\n const originalMap = readFileSync(artifact.mapPath, 'utf8')\n // injectDebugId is a pure function that throws on malformed map JSON (by design — see\n // its own doc comment). That's deliberately caught here, alongside upload failures: one\n // corrupt/unreadable artifact on disk must not abort processing of every other artifact\n // in the directory, the same failure-isolation principle discoverArtifacts applies to\n // unreadable files during its walk. Nothing has been uploaded or written yet at this\n // point, so a thrown injectDebugId or upload failure leaves the artifact's files\n // completely untouched, and it's safe to report it as `failed` for a retry.\n injected = injectDebugId(originalJs, originalMap, debugId)\n\n await uploadSourceMap({\n apiHost: options.apiHost,\n authToken,\n release,\n debugId,\n // Relative to options.directory, not the absolute on-disk path — the backend has no\n // use for (and shouldn't see) the build machine's local filesystem layout.\n filename: relative(options.directory, artifact.jsPath),\n mapContent: injected.map,\n fetchImpl: options.fetchImpl,\n })\n } catch (error) {\n // Surfaced here rather than swallowed: this is the only place the actual failure reason\n // (injectDebugId's malformed-JSON error, or uploadSourceMap's `status statusText` message)\n // is available. Without logging it, callers only ever see a bare list of failed paths with\n // no way to tell an auth failure from a malformed map from a network error.\n console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error)\n outcomes[index] = { path: artifact.jsPath, ok: false }\n return\n }\n\n try {\n writeFileSync(artifact.jsPath, injected.js)\n rmSync(artifact.mapPath)\n outcomes[index] = { path: artifact.jsPath, ok: true }\n } catch (cleanupError) {\n // The upload above already succeeded, so this must never land in `failed` — a caller\n // retrying failed artifacts would mint a fresh debugId and re-upload, orphaning this\n // upload server-side under the old one with no way to reconcile the two. The local\n // cleanup failure (disk full, permission error, file lock) is real and worth knowing\n // about, so it's surfaced here rather than silently swallowed, but it doesn't change\n // the artifact's outcome.\n outcomes[index] = { path: artifact.jsPath, ok: true }\n console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError)\n }\n }\n\n // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared\n // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.\n let nextIndex = 0\n const runWorker = async (): Promise<void> => {\n while (nextIndex < artifacts.length) {\n const index = nextIndex++\n await processOne(index)\n }\n }\n const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length)\n await Promise.all(Array.from({ length: workerCount }, runWorker))\n\n const result: ProcessSourceMapsResult = { uploaded: [], failed: [] }\n for (const outcome of outcomes) {\n ;(outcome.ok ? result.uploaded : result.failed).push(outcome.path)\n }\n return result\n}\n","// packages/cli/src/bin.ts\nimport { processSourceMaps } from './processSourceMaps'\n\ninterface ParsedArgs {\n directory: string\n release?: string\n authToken?: string\n}\n\n/** Exported (not just used internally) so it's unit-testable without spawning a process. */\nexport function parseArgs(argv: string[]): ParsedArgs {\n const [command, subcommand, directory, ...rest] = argv\n if (command !== 'sourcemaps' || subcommand !== 'upload' || !directory) {\n throw new Error(\n 'Usage: getmonitor sourcemaps upload <directory> [--release <release>] [--auth-token <token>]',\n )\n }\n\n let release: string | undefined\n let authToken: string | undefined\n\n for (let i = 0; i < rest.length; i += 2) {\n const flag = rest[i]\n const value = rest[i + 1]\n if (flag === '--release') release = value\n else if (flag === '--auth-token') authToken = value\n else throw new Error(`Unknown flag: ${flag}`)\n }\n\n return { directory, release, authToken }\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2))\n\n const result = await processSourceMaps({\n directory: args.directory,\n release: args.release,\n authToken: args.authToken,\n })\n\n console.log(`Uploaded ${result.uploaded.length} source map(s).`)\n if (result.failed.length > 0) {\n console.error(`Failed to upload ${result.failed.length} source map(s):`)\n for (const file of result.failed) console.error(` ${file}`)\n process.exitCode = 1\n }\n}\n\n// Skipped under Vitest (which imports this module to test parseArgs) — only run when\n// invoked directly as the built dist/bin.js executable. Confirmed empirically that Vitest\n// sets process.env.VITEST = 'true' in the process that loads this module, so this check\n// reliably prevents main() (which does real I/O and can set process.exitCode) from running\n// during `pnpm test`.\nif (process.env.VITEST === undefined) {\n main().catch((error) => {\n console.error(error instanceof Error ? error.message : error)\n process.exitCode = 1\n })\n}\n"],"names":[],"mappings":";;;;;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KAAK,CAAC,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC;AAC7D,QAAA,OAAO,CAAC,QAAQ,GAAG,CAAC;AACtB,IAAA,CAAC,CAAC;AACJ;;;;"}
@@ -0,0 +1,10 @@
1
+ export interface Artifact {
2
+ jsPath: string;
3
+ mapPath: string;
4
+ }
5
+ /** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its
6
+ * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the
7
+ * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,
8
+ * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no
9
+ * resolvable map either way is skipped. */
10
+ export declare function discoverArtifacts(directory: string): Artifact[];
package/dist/index.cjs ADDED
@@ -0,0 +1,299 @@
1
+ 'use strict';
2
+
3
+ var node_crypto = require('node:crypto');
4
+ var node_fs = require('node:fs');
5
+ var node_path = require('node:path');
6
+ var node_child_process = require('node:child_process');
7
+
8
+ // packages/cli/src/discoverArtifacts.ts
9
+ const SOURCE_MAPPING_URL = /^\s*\/\/#\s*sourceMappingURL=(\S+)\s*$/gm;
10
+ // Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit
11
+ // ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's "type") — all three
12
+ // show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e
13
+ // test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real
14
+ // `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and
15
+ // unstripped even though `.output/` itself was already fully written by the time discovery ran.
16
+ const JS_EXTENSIONS = ['.js', '.mjs', '.cjs'];
17
+ /** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its
18
+ * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the
19
+ * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,
20
+ * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no
21
+ * resolvable map either way is skipped. */
22
+ function discoverArtifacts(directory) {
23
+ const artifacts = [];
24
+ walk(directory, artifacts);
25
+ return artifacts;
26
+ }
27
+ function walk(dir, artifacts) {
28
+ for (const entry of node_fs.readdirSync(dir, { withFileTypes: true })) {
29
+ const fullPath = node_path.join(dir, entry.name);
30
+ if (entry.isDirectory()) {
31
+ walk(fullPath, artifacts);
32
+ }
33
+ else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
34
+ const mapPath = resolveMapPath(fullPath);
35
+ if (mapPath)
36
+ artifacts.push({ jsPath: fullPath, mapPath });
37
+ }
38
+ }
39
+ }
40
+ function resolveMapPath(jsPath) {
41
+ const commentMapPath = readSourceMappingUrlComment(jsPath);
42
+ if (commentMapPath && node_fs.existsSync(commentMapPath))
43
+ return commentMapPath;
44
+ const fallbackMapPath = `${jsPath}.map`;
45
+ if (node_fs.existsSync(fallbackMapPath))
46
+ return fallbackMapPath;
47
+ return undefined;
48
+ }
49
+ function readSourceMappingUrlComment(jsPath) {
50
+ let content;
51
+ try {
52
+ content = node_fs.readFileSync(jsPath, 'utf8');
53
+ }
54
+ catch {
55
+ // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it
56
+ // like "no comment found" rather than aborting the whole discoverArtifacts() walk.
57
+ return undefined;
58
+ }
59
+ const matches = [...content.matchAll(SOURCE_MAPPING_URL)];
60
+ if (matches.length === 0)
61
+ return undefined;
62
+ // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat
63
+ // concatenated/reprocessed output — later comments supersede earlier ones.
64
+ const reference = matches.at(-1)[1];
65
+ if (reference.startsWith('data:'))
66
+ return undefined; // embedded map, nothing to discover on disk
67
+ return node_path.join(node_path.dirname(jsPath), reference);
68
+ }
69
+
70
+ // packages/cli/src/injectDebugId.ts
71
+ /** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in
72
+ * memory — callers decide whether/when to persist the result to disk (processSourceMaps
73
+ * only writes it after a successful upload, so a failed upload never leaves partially
74
+ * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)
75
+ * removed, since the source map it names is only ever kept in GetMonitor's backend after
76
+ * a successful upload — never served publicly alongside it.
77
+ *
78
+ * `originalMapJson` must be valid JSON — this is a pure function with no fallback to
79
+ * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's
80
+ * caller expects a definite result), so a malformed map is left to throw via JSON.parse
81
+ * rather than being swallowed here. */
82
+ function injectDebugId(originalJs, originalMapJson, debugId) {
83
+ const withoutMapComment = originalJs
84
+ .split('\n')
85
+ .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))
86
+ .join('\n');
87
+ const map = JSON.parse(originalMapJson);
88
+ map.debugId = debugId;
89
+ return {
90
+ js: `${withoutMapComment}\n${buildInjectedSnippet(debugId)}`,
91
+ map: JSON.stringify(map),
92
+ };
93
+ }
94
+ /** At load time, captures this statement's own `Error().stack`, extracts this file's
95
+ * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for
96
+ * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's
97
+ * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,
98
+ * it scans every stack line and takes the first one that matches any of those shapes, rather
99
+ * than assuming a fixed line index — V8 prefixes an `"ErrorType: message"` header line that
100
+ * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong
101
+ * file's identity) on non-V8 engines; the header line simply fails to match any frame regex
102
+ * and is skipped automatically. A later real error whose frame.filename is parsed from the
103
+ * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any
104
+ * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak
105
+ * into the file's module scope.
106
+ *
107
+ * `debugId` is interpolated unescaped into the generated snippet's string literal. That's
108
+ * safe today because every caller in this system sources `debugId` from
109
+ * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but
110
+ * this function itself doesn't enforce that shape, so a caller passing an arbitrary string
111
+ * containing `'` or `\` would produce invalid/injected JS here. Flagged, not fixed, since
112
+ * validating/escaping isn't part of this function's specified contract. */
113
+ function buildInjectedSnippet(debugId) {
114
+ return (";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\n');var m=null;" +
115
+ 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +
116
+ "m=l.match(/\\((.*):(\\d+):(\\d+)\\)\\s*$/)||l.match(/at (.*):(\\d+):(\\d+)\\s*$/)||l.match(/@(.*):(\\d+):(\\d+)\\s*$/)}" +
117
+ "var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);" +
118
+ `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +
119
+ '}}catch(e){}})();');
120
+ }
121
+
122
+ // packages/cli/src/resolveRelease.ts
123
+ /** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit
124
+ * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside
125
+ * a git working tree) -> `version` field of the nearest package.json walking up from
126
+ * `directory`. Matches the SDKs' own optional `release` field so events and source maps
127
+ * for the same deploy carry the same value. */
128
+ function resolveRelease(directory, explicit) {
129
+ if (explicit)
130
+ return explicit;
131
+ if (process.env.GETMONITOR_RELEASE)
132
+ return process.env.GETMONITOR_RELEASE;
133
+ const gitSha = tryGitSha(directory);
134
+ if (gitSha)
135
+ return gitSha;
136
+ const packageVersion = tryPackageVersion(directory);
137
+ if (packageVersion)
138
+ return packageVersion;
139
+ throw new Error('Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a "version" field.');
140
+ }
141
+ function tryGitSha(directory) {
142
+ try {
143
+ return node_child_process.execFileSync('git', ['rev-parse', 'HEAD'], {
144
+ cwd: directory,
145
+ encoding: 'utf8',
146
+ stdio: ['ignore', 'pipe', 'ignore'],
147
+ }).trim();
148
+ }
149
+ catch {
150
+ return undefined;
151
+ }
152
+ }
153
+ function tryPackageVersion(directory) {
154
+ let dir = directory;
155
+ for (let i = 0; i < 20; i++) {
156
+ const pkgPath = node_path.join(dir, 'package.json');
157
+ if (node_fs.existsSync(pkgPath)) {
158
+ try {
159
+ const pkg = JSON.parse(node_fs.readFileSync(pkgPath, 'utf8'));
160
+ return typeof pkg.version === 'string' ? pkg.version : undefined;
161
+ }
162
+ catch {
163
+ return undefined;
164
+ }
165
+ }
166
+ const parent = node_path.dirname(dir);
167
+ if (parent === dir)
168
+ return undefined;
169
+ dir = parent;
170
+ }
171
+ return undefined;
172
+ }
173
+
174
+ // packages/cli/src/uploadSourceMap.ts
175
+ /** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */
176
+ const DEFAULT_API_HOST = 'https://track.getmonitor.io';
177
+ /** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.
178
+ * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides
179
+ * what "failed" means for its own result reporting and disk-write ordering. */
180
+ async function uploadSourceMap(params) {
181
+ // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native
182
+ // fetch() throws "Illegal invocation" if called with a `this` other than
183
+ // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below
184
+ // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this
185
+ // bind is defensive/consistent rather than load-bearing for this particular call site — but
186
+ // keeping the same default expression as HttpTransport avoids a divergent default if this
187
+ // code is ever refactored into a method.
188
+ const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis);
189
+ const apiHost = params.apiHost ?? DEFAULT_API_HOST;
190
+ const form = new FormData();
191
+ form.set('release', params.release);
192
+ form.set('debugId', params.debugId);
193
+ form.set('filename', params.filename);
194
+ form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`);
195
+ const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {
196
+ method: 'POST',
197
+ headers: { Authorization: `Bearer ${params.authToken}` },
198
+ body: form,
199
+ });
200
+ if (!response.ok) {
201
+ throw new Error(`Source map upload failed for ${params.filename}: ${response.status} ${response.statusText}`);
202
+ }
203
+ }
204
+
205
+ // packages/cli/src/processSourceMaps.ts
206
+ /** Number of artifacts uploaded at once. Each upload is an independent network round trip to
207
+ * ingester-api, so processing them one at a time made wall-clock time scale linearly with
208
+ * artifact count for no reason — a real Next.js build can emit well over a thousand of them,
209
+ * turning a few hundred ms of per-file latency into many minutes of serial waiting. */
210
+ const UPLOAD_CONCURRENCY = 20;
211
+ /** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a
212
+ * debug ID, uploads the tagged source map, and — only on a successful upload — writes the
213
+ * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload
214
+ * fails is left completely untouched on disk, so it can be retried by re-running this
215
+ * function against the same directory. Artifacts are uploaded concurrently (bounded by
216
+ * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match
217
+ * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */
218
+ async function processSourceMaps(options) {
219
+ const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN;
220
+ if (!authToken) {
221
+ throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.');
222
+ }
223
+ const release = resolveRelease(options.directory, options.release);
224
+ const artifacts = discoverArtifacts(options.directory);
225
+ // Indexed by each artifact's position in `artifacts` rather than appended in completion
226
+ // order, so the final result below is deterministic no matter which worker finishes first.
227
+ const outcomes = new Array(artifacts.length);
228
+ const processOne = async (index) => {
229
+ const artifact = artifacts[index];
230
+ const debugId = node_crypto.randomUUID();
231
+ let injected;
232
+ try {
233
+ const originalJs = node_fs.readFileSync(artifact.jsPath, 'utf8');
234
+ const originalMap = node_fs.readFileSync(artifact.mapPath, 'utf8');
235
+ // injectDebugId is a pure function that throws on malformed map JSON (by design — see
236
+ // its own doc comment). That's deliberately caught here, alongside upload failures: one
237
+ // corrupt/unreadable artifact on disk must not abort processing of every other artifact
238
+ // in the directory, the same failure-isolation principle discoverArtifacts applies to
239
+ // unreadable files during its walk. Nothing has been uploaded or written yet at this
240
+ // point, so a thrown injectDebugId or upload failure leaves the artifact's files
241
+ // completely untouched, and it's safe to report it as `failed` for a retry.
242
+ injected = injectDebugId(originalJs, originalMap, debugId);
243
+ await uploadSourceMap({
244
+ apiHost: options.apiHost,
245
+ authToken,
246
+ release,
247
+ debugId,
248
+ // Relative to options.directory, not the absolute on-disk path — the backend has no
249
+ // use for (and shouldn't see) the build machine's local filesystem layout.
250
+ filename: node_path.relative(options.directory, artifact.jsPath),
251
+ mapContent: injected.map,
252
+ fetchImpl: options.fetchImpl,
253
+ });
254
+ }
255
+ catch (error) {
256
+ // Surfaced here rather than swallowed: this is the only place the actual failure reason
257
+ // (injectDebugId's malformed-JSON error, or uploadSourceMap's `status statusText` message)
258
+ // is available. Without logging it, callers only ever see a bare list of failed paths with
259
+ // no way to tell an auth failure from a malformed map from a network error.
260
+ console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error);
261
+ outcomes[index] = { path: artifact.jsPath, ok: false };
262
+ return;
263
+ }
264
+ try {
265
+ node_fs.writeFileSync(artifact.jsPath, injected.js);
266
+ node_fs.rmSync(artifact.mapPath);
267
+ outcomes[index] = { path: artifact.jsPath, ok: true };
268
+ }
269
+ catch (cleanupError) {
270
+ // The upload above already succeeded, so this must never land in `failed` — a caller
271
+ // retrying failed artifacts would mint a fresh debugId and re-upload, orphaning this
272
+ // upload server-side under the old one with no way to reconcile the two. The local
273
+ // cleanup failure (disk full, permission error, file lock) is real and worth knowing
274
+ // about, so it's surfaced here rather than silently swallowed, but it doesn't change
275
+ // the artifact's outcome.
276
+ outcomes[index] = { path: artifact.jsPath, ok: true };
277
+ console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError);
278
+ }
279
+ };
280
+ // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared
281
+ // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.
282
+ let nextIndex = 0;
283
+ const runWorker = async () => {
284
+ while (nextIndex < artifacts.length) {
285
+ const index = nextIndex++;
286
+ await processOne(index);
287
+ }
288
+ };
289
+ const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length);
290
+ await Promise.all(Array.from({ length: workerCount }, runWorker));
291
+ const result = { uploaded: [], failed: [] };
292
+ for (const outcome of outcomes) {
293
+ (outcome.ok ? result.uploaded : result.failed).push(outcome.path);
294
+ }
295
+ return result;
296
+ }
297
+
298
+ exports.processSourceMaps = processSourceMaps;
299
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/discoverArtifacts.ts","../src/injectDebugId.ts","../src/resolveRelease.ts","../src/uploadSourceMap.ts","../src/processSourceMaps.ts"],"sourcesContent":["// packages/cli/src/discoverArtifacts.ts\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Artifact {\n jsPath: string\n mapPath: string\n}\n\nconst SOURCE_MAPPING_URL = /^\\s*\\/\\/#\\s*sourceMappingURL=(\\S+)\\s*$/gm\n\n// Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit\n// ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's \"type\") — all three\n// show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e\n// test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real\n// `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and\n// unstripped even though `.output/` itself was already fully written by the time discovery ran.\nconst JS_EXTENSIONS = ['.js', '.mjs', '.cjs']\n\n/** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its\n * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the\n * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,\n * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no\n * resolvable map either way is skipped. */\nexport function discoverArtifacts(directory: string): Artifact[] {\n const artifacts: Artifact[] = []\n walk(directory, artifacts)\n return artifacts\n}\n\nfunction walk(dir: string, artifacts: Artifact[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(fullPath, artifacts)\n } else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {\n const mapPath = resolveMapPath(fullPath)\n if (mapPath) artifacts.push({ jsPath: fullPath, mapPath })\n }\n }\n}\n\nfunction resolveMapPath(jsPath: string): string | undefined {\n const commentMapPath = readSourceMappingUrlComment(jsPath)\n if (commentMapPath && existsSync(commentMapPath)) return commentMapPath\n\n const fallbackMapPath = `${jsPath}.map`\n if (existsSync(fallbackMapPath)) return fallbackMapPath\n\n return undefined\n}\n\nfunction readSourceMappingUrlComment(jsPath: string): string | undefined {\n let content: string\n try {\n content = readFileSync(jsPath, 'utf8')\n } catch {\n // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it\n // like \"no comment found\" rather than aborting the whole discoverArtifacts() walk.\n return undefined\n }\n\n const matches = [...content.matchAll(SOURCE_MAPPING_URL)]\n if (matches.length === 0) return undefined\n\n // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat\n // concatenated/reprocessed output — later comments supersede earlier ones.\n const reference = matches.at(-1)![1]\n if (reference.startsWith('data:')) return undefined // embedded map, nothing to discover on disk\n\n return join(dirname(jsPath), reference)\n}\n","// packages/cli/src/injectDebugId.ts\n\nexport interface InjectedArtifact {\n js: string\n map: string\n}\n\n/** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in\n * memory — callers decide whether/when to persist the result to disk (processSourceMaps\n * only writes it after a successful upload, so a failed upload never leaves partially\n * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)\n * removed, since the source map it names is only ever kept in GetMonitor's backend after\n * a successful upload — never served publicly alongside it.\n *\n * `originalMapJson` must be valid JSON — this is a pure function with no fallback to\n * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's\n * caller expects a definite result), so a malformed map is left to throw via JSON.parse\n * rather than being swallowed here. */\nexport function injectDebugId(originalJs: string, originalMapJson: string, debugId: string): InjectedArtifact {\n const withoutMapComment = originalJs\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))\n .join('\\n')\n\n const map = JSON.parse(originalMapJson)\n map.debugId = debugId\n\n return {\n js: `${withoutMapComment}\\n${buildInjectedSnippet(debugId)}`,\n map: JSON.stringify(map),\n }\n}\n\n/** At load time, captures this statement's own `Error().stack`, extracts this file's\n * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for\n * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's\n * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,\n * it scans every stack line and takes the first one that matches any of those shapes, rather\n * than assuming a fixed line index — V8 prefixes an `\"ErrorType: message\"` header line that\n * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong\n * file's identity) on non-V8 engines; the header line simply fails to match any frame regex\n * and is skipped automatically. A later real error whose frame.filename is parsed from the\n * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any\n * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak\n * into the file's module scope.\n *\n * `debugId` is interpolated unescaped into the generated snippet's string literal. That's\n * safe today because every caller in this system sources `debugId` from\n * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but\n * this function itself doesn't enforce that shape, so a caller passing an arbitrary string\n * containing `'` or `\\` would produce invalid/injected JS here. Flagged, not fixed, since\n * validating/escaping isn't part of this function's specified contract. */\nfunction buildInjectedSnippet(debugId: string): string {\n return (\n \";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\\\n');var m=null;\" +\n 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +\n \"m=l.match(/\\\\((.*):(\\\\d+):(\\\\d+)\\\\)\\\\s*$/)||l.match(/at (.*):(\\\\d+):(\\\\d+)\\\\s*$/)||l.match(/@(.*):(\\\\d+):(\\\\d+)\\\\s*$/)}\" +\n \"var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);\" +\n `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +\n '}}catch(e){}})();'\n )\n}\n","// packages/cli/src/resolveRelease.ts\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit\n * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside\n * a git working tree) -> `version` field of the nearest package.json walking up from\n * `directory`. Matches the SDKs' own optional `release` field so events and source maps\n * for the same deploy carry the same value. */\nexport function resolveRelease(directory: string, explicit?: string): string {\n if (explicit) return explicit\n if (process.env.GETMONITOR_RELEASE) return process.env.GETMONITOR_RELEASE\n\n const gitSha = tryGitSha(directory)\n if (gitSha) return gitSha\n\n const packageVersion = tryPackageVersion(directory)\n if (packageVersion) return packageVersion\n\n throw new Error(\n 'Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a \"version\" field.',\n )\n}\n\nfunction tryGitSha(directory: string): string | undefined {\n try {\n return execFileSync('git', ['rev-parse', 'HEAD'], {\n cwd: directory,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim()\n } catch {\n return undefined\n }\n}\n\nfunction tryPackageVersion(directory: string): string | undefined {\n let dir = directory\n for (let i = 0; i < 20; i++) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n return typeof pkg.version === 'string' ? pkg.version : undefined\n } catch {\n return undefined\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n return undefined\n}\n","// packages/cli/src/uploadSourceMap.ts\n\n/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */\nexport const DEFAULT_API_HOST = 'https://track.getmonitor.io'\n\nexport interface UploadSourceMapParams {\n /**\n * @internal Test-only override for redirecting delivery to a local mock server (see\n * cli/e2e/processSourceMaps.spec.ts and the nextjs-config/nuxt e2e suites). Never exposed\n * through the public CLI/programmatic surface — real usage always ships to\n * {@link DEFAULT_API_HOST}.\n */\n apiHost?: string\n authToken: string\n release: string\n debugId: string\n filename: string\n mapContent: string\n fetchImpl?: typeof fetch\n}\n\n/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.\n * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides\n * what \"failed\" means for its own result reporting and disk-write ordering. */\nexport async function uploadSourceMap(params: UploadSourceMapParams): Promise<void> {\n // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native\n // fetch() throws \"Illegal invocation\" if called with a `this` other than\n // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below\n // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this\n // bind is defensive/consistent rather than load-bearing for this particular call site — but\n // keeping the same default expression as HttpTransport avoids a divergent default if this\n // code is ever refactored into a method.\n const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis)\n const apiHost = params.apiHost ?? DEFAULT_API_HOST\n\n const form = new FormData()\n form.set('release', params.release)\n form.set('debugId', params.debugId)\n form.set('filename', params.filename)\n form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`)\n\n const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${params.authToken}` },\n body: form,\n })\n\n if (!response.ok) {\n throw new Error(`Source map upload failed for ${params.filename}: ${response.status} ${response.statusText}`)\n }\n}\n","// packages/cli/src/processSourceMaps.ts\nimport { randomUUID } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { relative } from 'node:path'\nimport { discoverArtifacts } from './discoverArtifacts'\nimport { injectDebugId, InjectedArtifact } from './injectDebugId'\nimport { resolveRelease } from './resolveRelease'\nimport { uploadSourceMap } from './uploadSourceMap'\nimport { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types'\n\n/**\n * @internal Test-only host override, intersected into `processSourceMaps`'s options but\n * deliberately not part of the exported `ProcessSourceMapsOptions` type — see\n * `uploadSourceMap`'s `UploadSourceMapParams.apiHost`. Used by this package's own e2e suite\n * and by nextjs-config/nuxt's e2e suites (via their own internal overrides) to redirect\n * delivery to a local mock server; real callers must never set it.\n */\ninterface InternalTestOverrides {\n apiHost?: string\n}\n\n/** Number of artifacts uploaded at once. Each upload is an independent network round trip to\n * ingester-api, so processing them one at a time made wall-clock time scale linearly with\n * artifact count for no reason — a real Next.js build can emit well over a thousand of them,\n * turning a few hundred ms of per-file latency into many minutes of serial waiting. */\nconst UPLOAD_CONCURRENCY = 20\n\n/** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a\n * debug ID, uploads the tagged source map, and — only on a successful upload — writes the\n * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload\n * fails is left completely untouched on disk, so it can be retried by re-running this\n * function against the same directory. Artifacts are uploaded concurrently (bounded by\n * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match\n * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */\nexport async function processSourceMaps(\n options: ProcessSourceMapsOptions & InternalTestOverrides\n): Promise<ProcessSourceMapsResult> {\n const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN\n if (!authToken) {\n throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.')\n }\n\n const release = resolveRelease(options.directory, options.release)\n const artifacts = discoverArtifacts(options.directory)\n // Indexed by each artifact's position in `artifacts` rather than appended in completion\n // order, so the final result below is deterministic no matter which worker finishes first.\n const outcomes: Array<{ path: string; ok: boolean }> = new Array(artifacts.length)\n\n const processOne = async (index: number): Promise<void> => {\n const artifact = artifacts[index]\n const debugId = randomUUID()\n let injected: InjectedArtifact\n\n try {\n const originalJs = readFileSync(artifact.jsPath, 'utf8')\n const originalMap = readFileSync(artifact.mapPath, 'utf8')\n // injectDebugId is a pure function that throws on malformed map JSON (by design — see\n // its own doc comment). That's deliberately caught here, alongside upload failures: one\n // corrupt/unreadable artifact on disk must not abort processing of every other artifact\n // in the directory, the same failure-isolation principle discoverArtifacts applies to\n // unreadable files during its walk. Nothing has been uploaded or written yet at this\n // point, so a thrown injectDebugId or upload failure leaves the artifact's files\n // completely untouched, and it's safe to report it as `failed` for a retry.\n injected = injectDebugId(originalJs, originalMap, debugId)\n\n await uploadSourceMap({\n apiHost: options.apiHost,\n authToken,\n release,\n debugId,\n // Relative to options.directory, not the absolute on-disk path — the backend has no\n // use for (and shouldn't see) the build machine's local filesystem layout.\n filename: relative(options.directory, artifact.jsPath),\n mapContent: injected.map,\n fetchImpl: options.fetchImpl,\n })\n } catch (error) {\n // Surfaced here rather than swallowed: this is the only place the actual failure reason\n // (injectDebugId's malformed-JSON error, or uploadSourceMap's `status statusText` message)\n // is available. Without logging it, callers only ever see a bare list of failed paths with\n // no way to tell an auth failure from a malformed map from a network error.\n console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error)\n outcomes[index] = { path: artifact.jsPath, ok: false }\n return\n }\n\n try {\n writeFileSync(artifact.jsPath, injected.js)\n rmSync(artifact.mapPath)\n outcomes[index] = { path: artifact.jsPath, ok: true }\n } catch (cleanupError) {\n // The upload above already succeeded, so this must never land in `failed` — a caller\n // retrying failed artifacts would mint a fresh debugId and re-upload, orphaning this\n // upload server-side under the old one with no way to reconcile the two. The local\n // cleanup failure (disk full, permission error, file lock) is real and worth knowing\n // about, so it's surfaced here rather than silently swallowed, but it doesn't change\n // the artifact's outcome.\n outcomes[index] = { path: artifact.jsPath, ok: true }\n console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError)\n }\n }\n\n // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared\n // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.\n let nextIndex = 0\n const runWorker = async (): Promise<void> => {\n while (nextIndex < artifacts.length) {\n const index = nextIndex++\n await processOne(index)\n }\n }\n const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length)\n await Promise.all(Array.from({ length: workerCount }, runWorker))\n\n const result: ProcessSourceMapsResult = { uploaded: [], failed: [] }\n for (const outcome of outcomes) {\n ;(outcome.ok ? result.uploaded : result.failed).push(outcome.path)\n }\n return result\n}\n"],"names":["readdirSync","join","existsSync","readFileSync","dirname","execFileSync","randomUUID","relative","writeFileSync","rmSync"],"mappings":";;;;;;;AAAA;AASA,MAAM,kBAAkB,GAAG,0CAA0C;AAErE;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;AAE7C;;;;AAI2C;AACrC,SAAU,iBAAiB,CAAC,SAAiB,EAAA;IACjD,MAAM,SAAS,GAAe,EAAE;AAChC,IAAA,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC;AAC1B,IAAA,OAAO,SAAS;AAClB;AAEA,SAAS,IAAI,CAAC,GAAW,EAAE,SAAqB,EAAA;AAC9C,IAAA,KAAK,MAAM,KAAK,IAAIA,mBAAW,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,EAAE;QAC7D,MAAM,QAAQ,GAAGC,cAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC;AACtC,QAAA,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE;AACvB,YAAA,IAAI,CAAC,QAAQ,EAAE,SAAS,CAAC;QAC3B;aAAO,IAAI,KAAK,CAAC,MAAM,EAAE,IAAI,aAAa,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE;AAClF,YAAA,MAAM,OAAO,GAAG,cAAc,CA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aps } from './processSourceMaps';
2
+ export type { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types';
package/dist/index.js ADDED
@@ -0,0 +1,297 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readdirSync, existsSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
3
+ import { join, dirname, relative } from 'node:path';
4
+ import { execFileSync } from 'node:child_process';
5
+
6
+ // packages/cli/src/discoverArtifacts.ts
7
+ const SOURCE_MAPPING_URL = /^\s*\/\/#\s*sourceMappingURL=(\S+)\s*$/gm;
8
+ // Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit
9
+ // ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's "type") — all three
10
+ // show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e
11
+ // test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real
12
+ // `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and
13
+ // unstripped even though `.output/` itself was already fully written by the time discovery ran.
14
+ const JS_EXTENSIONS = ['.js', '.mjs', '.cjs'];
15
+ /** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its
16
+ * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the
17
+ * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,
18
+ * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no
19
+ * resolvable map either way is skipped. */
20
+ function discoverArtifacts(directory) {
21
+ const artifacts = [];
22
+ walk(directory, artifacts);
23
+ return artifacts;
24
+ }
25
+ function walk(dir, artifacts) {
26
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
27
+ const fullPath = join(dir, entry.name);
28
+ if (entry.isDirectory()) {
29
+ walk(fullPath, artifacts);
30
+ }
31
+ else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
32
+ const mapPath = resolveMapPath(fullPath);
33
+ if (mapPath)
34
+ artifacts.push({ jsPath: fullPath, mapPath });
35
+ }
36
+ }
37
+ }
38
+ function resolveMapPath(jsPath) {
39
+ const commentMapPath = readSourceMappingUrlComment(jsPath);
40
+ if (commentMapPath && existsSync(commentMapPath))
41
+ return commentMapPath;
42
+ const fallbackMapPath = `${jsPath}.map`;
43
+ if (existsSync(fallbackMapPath))
44
+ return fallbackMapPath;
45
+ return undefined;
46
+ }
47
+ function readSourceMappingUrlComment(jsPath) {
48
+ let content;
49
+ try {
50
+ content = readFileSync(jsPath, 'utf8');
51
+ }
52
+ catch {
53
+ // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it
54
+ // like "no comment found" rather than aborting the whole discoverArtifacts() walk.
55
+ return undefined;
56
+ }
57
+ const matches = [...content.matchAll(SOURCE_MAPPING_URL)];
58
+ if (matches.length === 0)
59
+ return undefined;
60
+ // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat
61
+ // concatenated/reprocessed output — later comments supersede earlier ones.
62
+ const reference = matches.at(-1)[1];
63
+ if (reference.startsWith('data:'))
64
+ return undefined; // embedded map, nothing to discover on disk
65
+ return join(dirname(jsPath), reference);
66
+ }
67
+
68
+ // packages/cli/src/injectDebugId.ts
69
+ /** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in
70
+ * memory — callers decide whether/when to persist the result to disk (processSourceMaps
71
+ * only writes it after a successful upload, so a failed upload never leaves partially
72
+ * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)
73
+ * removed, since the source map it names is only ever kept in GetMonitor's backend after
74
+ * a successful upload — never served publicly alongside it.
75
+ *
76
+ * `originalMapJson` must be valid JSON — this is a pure function with no fallback to
77
+ * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's
78
+ * caller expects a definite result), so a malformed map is left to throw via JSON.parse
79
+ * rather than being swallowed here. */
80
+ function injectDebugId(originalJs, originalMapJson, debugId) {
81
+ const withoutMapComment = originalJs
82
+ .split('\n')
83
+ .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))
84
+ .join('\n');
85
+ const map = JSON.parse(originalMapJson);
86
+ map.debugId = debugId;
87
+ return {
88
+ js: `${withoutMapComment}\n${buildInjectedSnippet(debugId)}`,
89
+ map: JSON.stringify(map),
90
+ };
91
+ }
92
+ /** At load time, captures this statement's own `Error().stack`, extracts this file's
93
+ * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for
94
+ * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's
95
+ * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,
96
+ * it scans every stack line and takes the first one that matches any of those shapes, rather
97
+ * than assuming a fixed line index — V8 prefixes an `"ErrorType: message"` header line that
98
+ * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong
99
+ * file's identity) on non-V8 engines; the header line simply fails to match any frame regex
100
+ * and is skipped automatically. A later real error whose frame.filename is parsed from the
101
+ * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any
102
+ * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak
103
+ * into the file's module scope.
104
+ *
105
+ * `debugId` is interpolated unescaped into the generated snippet's string literal. That's
106
+ * safe today because every caller in this system sources `debugId` from
107
+ * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but
108
+ * this function itself doesn't enforce that shape, so a caller passing an arbitrary string
109
+ * containing `'` or `\` would produce invalid/injected JS here. Flagged, not fixed, since
110
+ * validating/escaping isn't part of this function's specified contract. */
111
+ function buildInjectedSnippet(debugId) {
112
+ return (";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\n');var m=null;" +
113
+ 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +
114
+ "m=l.match(/\\((.*):(\\d+):(\\d+)\\)\\s*$/)||l.match(/at (.*):(\\d+):(\\d+)\\s*$/)||l.match(/@(.*):(\\d+):(\\d+)\\s*$/)}" +
115
+ "var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);" +
116
+ `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +
117
+ '}}catch(e){}})();');
118
+ }
119
+
120
+ // packages/cli/src/resolveRelease.ts
121
+ /** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit
122
+ * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside
123
+ * a git working tree) -> `version` field of the nearest package.json walking up from
124
+ * `directory`. Matches the SDKs' own optional `release` field so events and source maps
125
+ * for the same deploy carry the same value. */
126
+ function resolveRelease(directory, explicit) {
127
+ if (explicit)
128
+ return explicit;
129
+ if (process.env.GETMONITOR_RELEASE)
130
+ return process.env.GETMONITOR_RELEASE;
131
+ const gitSha = tryGitSha(directory);
132
+ if (gitSha)
133
+ return gitSha;
134
+ const packageVersion = tryPackageVersion(directory);
135
+ if (packageVersion)
136
+ return packageVersion;
137
+ throw new Error('Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a "version" field.');
138
+ }
139
+ function tryGitSha(directory) {
140
+ try {
141
+ return execFileSync('git', ['rev-parse', 'HEAD'], {
142
+ cwd: directory,
143
+ encoding: 'utf8',
144
+ stdio: ['ignore', 'pipe', 'ignore'],
145
+ }).trim();
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ }
151
+ function tryPackageVersion(directory) {
152
+ let dir = directory;
153
+ for (let i = 0; i < 20; i++) {
154
+ const pkgPath = join(dir, 'package.json');
155
+ if (existsSync(pkgPath)) {
156
+ try {
157
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
158
+ return typeof pkg.version === 'string' ? pkg.version : undefined;
159
+ }
160
+ catch {
161
+ return undefined;
162
+ }
163
+ }
164
+ const parent = dirname(dir);
165
+ if (parent === dir)
166
+ return undefined;
167
+ dir = parent;
168
+ }
169
+ return undefined;
170
+ }
171
+
172
+ // packages/cli/src/uploadSourceMap.ts
173
+ /** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */
174
+ const DEFAULT_API_HOST = 'https://track.getmonitor.io';
175
+ /** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.
176
+ * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides
177
+ * what "failed" means for its own result reporting and disk-write ordering. */
178
+ async function uploadSourceMap(params) {
179
+ // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native
180
+ // fetch() throws "Illegal invocation" if called with a `this` other than
181
+ // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below
182
+ // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this
183
+ // bind is defensive/consistent rather than load-bearing for this particular call site — but
184
+ // keeping the same default expression as HttpTransport avoids a divergent default if this
185
+ // code is ever refactored into a method.
186
+ const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis);
187
+ const apiHost = params.apiHost ?? DEFAULT_API_HOST;
188
+ const form = new FormData();
189
+ form.set('release', params.release);
190
+ form.set('debugId', params.debugId);
191
+ form.set('filename', params.filename);
192
+ form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`);
193
+ const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {
194
+ method: 'POST',
195
+ headers: { Authorization: `Bearer ${params.authToken}` },
196
+ body: form,
197
+ });
198
+ if (!response.ok) {
199
+ throw new Error(`Source map upload failed for ${params.filename}: ${response.status} ${response.statusText}`);
200
+ }
201
+ }
202
+
203
+ // packages/cli/src/processSourceMaps.ts
204
+ /** Number of artifacts uploaded at once. Each upload is an independent network round trip to
205
+ * ingester-api, so processing them one at a time made wall-clock time scale linearly with
206
+ * artifact count for no reason — a real Next.js build can emit well over a thousand of them,
207
+ * turning a few hundred ms of per-file latency into many minutes of serial waiting. */
208
+ const UPLOAD_CONCURRENCY = 20;
209
+ /** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a
210
+ * debug ID, uploads the tagged source map, and — only on a successful upload — writes the
211
+ * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload
212
+ * fails is left completely untouched on disk, so it can be retried by re-running this
213
+ * function against the same directory. Artifacts are uploaded concurrently (bounded by
214
+ * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match
215
+ * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */
216
+ async function processSourceMaps(options) {
217
+ const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN;
218
+ if (!authToken) {
219
+ throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.');
220
+ }
221
+ const release = resolveRelease(options.directory, options.release);
222
+ const artifacts = discoverArtifacts(options.directory);
223
+ // Indexed by each artifact's position in `artifacts` rather than appended in completion
224
+ // order, so the final result below is deterministic no matter which worker finishes first.
225
+ const outcomes = new Array(artifacts.length);
226
+ const processOne = async (index) => {
227
+ const artifact = artifacts[index];
228
+ const debugId = randomUUID();
229
+ let injected;
230
+ try {
231
+ const originalJs = readFileSync(artifact.jsPath, 'utf8');
232
+ const originalMap = readFileSync(artifact.mapPath, 'utf8');
233
+ // injectDebugId is a pure function that throws on malformed map JSON (by design — see
234
+ // its own doc comment). That's deliberately caught here, alongside upload failures: one
235
+ // corrupt/unreadable artifact on disk must not abort processing of every other artifact
236
+ // in the directory, the same failure-isolation principle discoverArtifacts applies to
237
+ // unreadable files during its walk. Nothing has been uploaded or written yet at this
238
+ // point, so a thrown injectDebugId or upload failure leaves the artifact's files
239
+ // completely untouched, and it's safe to report it as `failed` for a retry.
240
+ injected = injectDebugId(originalJs, originalMap, debugId);
241
+ await uploadSourceMap({
242
+ apiHost: options.apiHost,
243
+ authToken,
244
+ release,
245
+ debugId,
246
+ // Relative to options.directory, not the absolute on-disk path — the backend has no
247
+ // use for (and shouldn't see) the build machine's local filesystem layout.
248
+ filename: relative(options.directory, artifact.jsPath),
249
+ mapContent: injected.map,
250
+ fetchImpl: options.fetchImpl,
251
+ });
252
+ }
253
+ catch (error) {
254
+ // Surfaced here rather than swallowed: this is the only place the actual failure reason
255
+ // (injectDebugId's malformed-JSON error, or uploadSourceMap's `status statusText` message)
256
+ // is available. Without logging it, callers only ever see a bare list of failed paths with
257
+ // no way to tell an auth failure from a malformed map from a network error.
258
+ console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error);
259
+ outcomes[index] = { path: artifact.jsPath, ok: false };
260
+ return;
261
+ }
262
+ try {
263
+ writeFileSync(artifact.jsPath, injected.js);
264
+ rmSync(artifact.mapPath);
265
+ outcomes[index] = { path: artifact.jsPath, ok: true };
266
+ }
267
+ catch (cleanupError) {
268
+ // The upload above already succeeded, so this must never land in `failed` — a caller
269
+ // retrying failed artifacts would mint a fresh debugId and re-upload, orphaning this
270
+ // upload server-side under the old one with no way to reconcile the two. The local
271
+ // cleanup failure (disk full, permission error, file lock) is real and worth knowing
272
+ // about, so it's surfaced here rather than silently swallowed, but it doesn't change
273
+ // the artifact's outcome.
274
+ outcomes[index] = { path: artifact.jsPath, ok: true };
275
+ console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError);
276
+ }
277
+ };
278
+ // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared
279
+ // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.
280
+ let nextIndex = 0;
281
+ const runWorker = async () => {
282
+ while (nextIndex < artifacts.length) {
283
+ const index = nextIndex++;
284
+ await processOne(index);
285
+ }
286
+ };
287
+ const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length);
288
+ await Promise.all(Array.from({ length: workerCount }, runWorker));
289
+ const result = { uploaded: [], failed: [] };
290
+ for (const outcome of outcomes) {
291
+ (outcome.ok ? result.uploaded : result.failed).push(outcome.path);
292
+ }
293
+ return result;
294
+ }
295
+
296
+ export { processSourceMaps };
297
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/discoverArtifacts.ts","../src/injectDebugId.ts","../src/resolveRelease.ts","../src/uploadSourceMap.ts","../src/processSourceMaps.ts"],"sourcesContent":["// packages/cli/src/discoverArtifacts.ts\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Artifact {\n jsPath: string\n mapPath: string\n}\n\nconst SOURCE_MAPPING_URL = /^\\s*\\/\\/#\\s*sourceMappingURL=(\\S+)\\s*$/gm\n\n// Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit\n// ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's \"type\") — all three\n// show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e\n// test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real\n// `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and\n// unstripped even though `.output/` itself was already fully written by the time discovery ran.\nconst JS_EXTENSIONS = ['.js', '.mjs', '.cjs']\n\n/** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its\n * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the\n * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,\n * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no\n * resolvable map either way is skipped. */\nexport function discoverArtifacts(directory: string): Artifact[] {\n const artifacts: Artifact[] = []\n walk(directory, artifacts)\n return artifacts\n}\n\nfunction walk(dir: string, artifacts: Artifact[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(fullPath, artifacts)\n } else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {\n const mapPath = resolveMapPath(fullPath)\n if (mapPath) artifacts.push({ jsPath: fullPath, mapPath })\n }\n }\n}\n\nfunction resolveMapPath(jsPath: string): string | undefined {\n const commentMapPath = readSourceMappingUrlComment(jsPath)\n if (commentMapPath && existsSync(commentMapPath)) return commentMapPath\n\n const fallbackMapPath = `${jsPath}.map`\n if (existsSync(fallbackMapPath)) return fallbackMapPath\n\n return undefined\n}\n\nfunction readSourceMappingUrlComment(jsPath: string): string | undefined {\n let content: string\n try {\n content = readFileSync(jsPath, 'utf8')\n } catch {\n // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it\n // like \"no comment found\" rather than aborting the whole discoverArtifacts() walk.\n return undefined\n }\n\n const matches = [...content.matchAll(SOURCE_MAPPING_URL)]\n if (matches.length === 0) return undefined\n\n // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat\n // concatenated/reprocessed output — later comments supersede earlier ones.\n const reference = matches.at(-1)![1]\n if (reference.startsWith('data:')) return undefined // embedded map, nothing to discover on disk\n\n return join(dirname(jsPath), reference)\n}\n","// packages/cli/src/injectDebugId.ts\n\nexport interface InjectedArtifact {\n js: string\n map: string\n}\n\n/** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in\n * memory — callers decide whether/when to persist the result to disk (processSourceMaps\n * only writes it after a successful upload, so a failed upload never leaves partially\n * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)\n * removed, since the source map it names is only ever kept in GetMonitor's backend after\n * a successful upload — never served publicly alongside it.\n *\n * `originalMapJson` must be valid JSON — this is a pure function with no fallback to\n * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's\n * caller expects a definite result), so a malformed map is left to throw via JSON.parse\n * rather than being swallowed here. */\nexport function injectDebugId(originalJs: string, originalMapJson: string, debugId: string): InjectedArtifact {\n const withoutMapComment = originalJs\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))\n .join('\\n')\n\n const map = JSON.parse(originalMapJson)\n map.debugId = debugId\n\n return {\n js: `${withoutMapComment}\\n${buildInjectedSnippet(debugId)}`,\n map: JSON.stringify(map),\n }\n}\n\n/** At load time, captures this statement's own `Error().stack`, extracts this file's\n * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for\n * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's\n * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,\n * it scans every stack line and takes the first one that matches any of those shapes, rather\n * than assuming a fixed line index — V8 prefixes an `\"ErrorType: message\"` header line that\n * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong\n * file's identity) on non-V8 engines; the header line simply fails to match any frame regex\n * and is skipped automatically. A later real error whose frame.filename is parsed from the\n * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any\n * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak\n * into the file's module scope.\n *\n * `debugId` is interpolated unescaped into the generated snippet's string literal. That's\n * safe today because every caller in this system sources `debugId` from\n * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but\n * this function itself doesn't enforce that shape, so a caller passing an arbitrary string\n * containing `'` or `\\` would produce invalid/injected JS here. Flagged, not fixed, since\n * validating/escaping isn't part of this function's specified contract. */\nfunction buildInjectedSnippet(debugId: string): string {\n return (\n \";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\\\n');var m=null;\" +\n 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +\n \"m=l.match(/\\\\((.*):(\\\\d+):(\\\\d+)\\\\)\\\\s*$/)||l.match(/at (.*):(\\\\d+):(\\\\d+)\\\\s*$/)||l.match(/@(.*):(\\\\d+):(\\\\d+)\\\\s*$/)}\" +\n \"var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);\" +\n `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +\n '}}catch(e){}})();'\n )\n}\n","// packages/cli/src/resolveRelease.ts\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit\n * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside\n * a git working tree) -> `version` field of the nearest package.json walking up from\n * `directory`. Matches the SDKs' own optional `release` field so events and source maps\n * for the same deploy carry the same value. */\nexport function resolveRelease(directory: string, explicit?: string): string {\n if (explicit) return explicit\n if (process.env.GETMONITOR_RELEASE) return process.env.GETMONITOR_RELEASE\n\n const gitSha = tryGitSha(directory)\n if (gitSha) return gitSha\n\n const packageVersion = tryPackageVersion(directory)\n if (packageVersion) return packageVersion\n\n throw new Error(\n 'Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a \"version\" field.',\n )\n}\n\nfunction tryGitSha(directory: string): string | undefined {\n try {\n return execFileSync('git', ['rev-parse', 'HEAD'], {\n cwd: directory,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim()\n } catch {\n return undefined\n }\n}\n\nfunction tryPackageVersion(directory: string): string | undefined {\n let dir = directory\n for (let i = 0; i < 20; i++) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n return typeof pkg.version === 'string' ? pkg.version : undefined\n } catch {\n return undefined\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n return undefined\n}\n","// packages/cli/src/uploadSourceMap.ts\n\n/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */\nexport const DEFAULT_API_HOST = 'https://track.getmonitor.io'\n\nexport interface UploadSourceMapParams {\n /**\n * @internal Test-only override for redirecting delivery to a local mock server (see\n * cli/e2e/processSourceMaps.spec.ts and the nextjs-config/nuxt e2e suites). Never exposed\n * through the public CLI/programmatic surface — real usage always ships to\n * {@link DEFAULT_API_HOST}.\n */\n apiHost?: string\n authToken: string\n release: string\n debugId: string\n filename: string\n mapContent: string\n fetchImpl?: typeof fetch\n}\n\n/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.\n * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides\n * what \"failed\" means for its own result reporting and disk-write ordering. */\nexport async function uploadSourceMap(params: UploadSourceMapParams): Promise<void> {\n // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native\n // fetch() throws \"Illegal invocation\" if called with a `this` other than\n // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below\n // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this\n // bind is defensive/consistent rather than load-bearing for this particular call site — but\n // keeping the same default expression as HttpTransport avoids a divergent default if this\n // code is ever refactored into a method.\n const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis)\n const apiHost = params.apiHost ?? DEFAULT_API_HOST\n\n const form = new FormData()\n form.set('release', params.release)\n form.set('debugId', params.debugId)\n form.set('filename', params.filename)\n form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`)\n\n const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${params.authToken}` },\n body: form,\n })\n\n if (!response.ok) {\n throw new Error(`Source map upload failed for ${params.filename}: ${response.status} ${response.statusText}`)\n }\n}\n","// packages/cli/src/processSourceMaps.ts\nimport { randomUUID } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { relative } from 'node:path'\nimport { discoverArtifacts } from './discoverArtifacts'\nimport { injectDebugId, InjectedArtifact } from './injectDebugId'\nimport { resolveRelease } from './resolveRelease'\nimport { uploadSourceMap } from './uploadSourceMap'\nimport { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types'\n\n/**\n * @internal Test-only host override, intersected into `processSourceMaps`'s options but\n * deliberately not part of the exported `ProcessSourceMapsOptions` type — see\n * `uploadSourceMap`'s `UploadSourceMapParams.apiHost`. Used by this package's own e2e suite\n * and by nextjs-config/nuxt's e2e suites (via their own internal overrides) to redirect\n * delivery to a local mock server; real callers must never set it.\n */\ninterface InternalTestOverrides {\n apiHost?: string\n}\n\n/** Number of artifacts uploaded at once. Each upload is an independent network round trip to\n * ingester-api, so processing them one at a time made wall-clock time scale linearly with\n * artifact count for no reason — a real Next.js build can emit well over a thousand of them,\n * turning a few hundred ms of per-file latency into many minutes of serial waiting. */\nconst UPLOAD_CONCURRENCY = 20\n\n/** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a\n * debug ID, uploads the tagged source map, and — only on a successful upload — writes the\n * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload\n * fails is left completely untouched on disk, so it can be retried by re-running this\n * function against the same directory. Artifacts are uploaded concurrently (bounded by\n * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match\n * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */\nexport async function processSourceMaps(\n options: ProcessSourceMapsOptions & InternalTestOverrides\n): Promise<ProcessSourceMapsResult> {\n const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN\n if (!authToken) {\n throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.')\n }\n\n const release = resolveRelease(options.directory, options.release)\n const artifacts = discoverArtifacts(options.directory)\n // Indexed by each artifact's position in `artifacts` rather than appended in completion\n // order, so the final result below is deterministic no matter which worker finishes first.\n const outcomes: Array<{ path: string; ok: boolean }> = new Array(artifacts.length)\n\n const processOne = async (index: number): Promise<void> => {\n const artifact = artifacts[index]\n const debugId = randomUUID()\n let injected: InjectedArtifact\n\n try {\n const originalJs = readFileSync(artifact.jsPath, 'utf8')\n const originalMap = readFileSync(artifact.mapPath, 'utf8')\n // injectDebugId is a pure function that throws on malformed map JSON (by design — see\n // its own doc comment). That's deliberately caught here, alongside upload failures: one\n // corrupt/unreadable artifact on disk must not abort processing of every other artifact\n // in the directory, the same failure-isolation principle discoverArtifacts applies to\n // unreadable files during its walk. Nothing has been uploaded or written yet at this\n // point, so a thrown injectDebugId or upload failure leaves the artifact's files\n // completely untouched, and it's safe to report it as `failed` for a retry.\n injected = injectDebugId(originalJs, originalMap, debugId)\n\n await uploadSourceMap({\n apiHost: options.apiHost,\n authToken,\n release,\n debugId,\n // Relative to options.directory, not the absolute on-disk path — the backend has no\n // use for (and shouldn't see) the build machine's local filesystem layout.\n filename: relative(options.directory, artifact.jsPath),\n mapContent: injected.map,\n fetchImpl: options.fetchImpl,\n })\n } catch (error) {\n // Surfaced here rather than swallowed: this is the only place the actual failure reason\n // (injectDebugId's malformed-JSON error, or uploadSourceMap's `status statusText` message)\n // is available. Without logging it, callers only ever see a bare list of failed paths with\n // no way to tell an auth failure from a malformed map from a network error.\n console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error)\n outcomes[index] = { path: artifact.jsPath, ok: false }\n return\n }\n\n try {\n writeFileSync(artifact.jsPath, injected.js)\n rmSync(artifact.mapPath)\n outcomes[index] = { path: artifact.jsPath, ok: true }\n } catch (cleanupError) {\n // The upload above already succeeded, so this must never land in `failed` — a caller\n // retrying failed artifacts would mint a fresh debugId and re-upload, orphaning this\n // upload server-side under the old one with no way to reconcile the two. The local\n // cleanup failure (disk full, permission error, file lock) is real and worth knowing\n // about, so it's surfaced here rather than silently swallowed, but it doesn't change\n // the artifact's outcome.\n outcomes[index] = { path: artifact.jsPath, ok: true }\n console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError)\n }\n }\n\n // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared\n // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.\n let nextIndex = 0\n const runWorker = async (): Promise<void> => {\n while (nextIndex < artifacts.length) {\n const index = nextIndex++\n await processOne(index)\n }\n }\n const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length)\n await Promise.all(Array.from({ length: workerCount }, runWorker))\n\n const result: ProcessSourceMapsResult = { uploaded: [], failed: [] }\n for (const outcome of outcomes) {\n ;(outcome.ok ? result.uploaded : result.failed).push(outcome.path)\n }\n return result\n}\n"],"names":[],"mappings":";;;;;AAAA;AASA,MAAM,kBAAkB,GAAG,0CAA0C;AAErE;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;AAE7C;;;;AAI2C;A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M,KAAK,GAAG,SAAS,EAAE;AACzB,YAAA,MAAM,UAAU,CAAC,KAAK,CAAC;QACzB;AACF,IAAA,CAAC;AACD,IAAA,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,kBAAkB,EAAE,SAAS,CAAC,MAAM,CAAC;AAClE,IAAA,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,SAAS,CAAC,CAAC;IAEjE,MAAM,MAAM,GAA4B,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE;AACpE,IAAA,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;QAC7B,CAAC,OAAO,CAAC,EAAE,GAAG,MAAM,CAAC,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IACpE;AACA,IAAA,OAAO,MAAM;AACf;;;;"}
@@ -0,0 +1,16 @@
1
+ export interface InjectedArtifact {
2
+ js: string;
3
+ map: string;
4
+ }
5
+ /** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in
6
+ * memory — callers decide whether/when to persist the result to disk (processSourceMaps
7
+ * only writes it after a successful upload, so a failed upload never leaves partially
8
+ * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)
9
+ * removed, since the source map it names is only ever kept in GetMonitor's backend after
10
+ * a successful upload — never served publicly alongside it.
11
+ *
12
+ * `originalMapJson` must be valid JSON — this is a pure function with no fallback to
13
+ * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's
14
+ * caller expects a definite result), so a malformed map is left to throw via JSON.parse
15
+ * rather than being swallowed here. */
16
+ export declare function injectDebugId(originalJs: string, originalMapJson: string, debugId: string): InjectedArtifact;
@@ -0,0 +1,20 @@
1
+ import { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types';
2
+ /**
3
+ * @internal Test-only host override, intersected into `processSourceMaps`'s options but
4
+ * deliberately not part of the exported `ProcessSourceMapsOptions` type — see
5
+ * `uploadSourceMap`'s `UploadSourceMapParams.apiHost`. Used by this package's own e2e suite
6
+ * and by nextjs-config/nuxt's e2e suites (via their own internal overrides) to redirect
7
+ * delivery to a local mock server; real callers must never set it.
8
+ */
9
+ interface InternalTestOverrides {
10
+ apiHost?: string;
11
+ }
12
+ /** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a
13
+ * debug ID, uploads the tagged source map, and — only on a successful upload — writes the
14
+ * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload
15
+ * fails is left completely untouched on disk, so it can be retried by re-running this
16
+ * function against the same directory. Artifacts are uploaded concurrently (bounded by
17
+ * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match
18
+ * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */
19
+ export declare function processSourceMaps(options: ProcessSourceMapsOptions & InternalTestOverrides): Promise<ProcessSourceMapsResult>;
20
+ export {};
@@ -0,0 +1,6 @@
1
+ /** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit
2
+ * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside
3
+ * a git working tree) -> `version` field of the nearest package.json walking up from
4
+ * `directory`. Matches the SDKs' own optional `release` field so events and source maps
5
+ * for the same deploy carry the same value. */
6
+ export declare function resolveRelease(directory: string, explicit?: string): string;
@@ -0,0 +1,10 @@
1
+ export interface ProcessSourceMapsOptions {
2
+ directory: string;
3
+ release?: string;
4
+ authToken?: string;
5
+ fetchImpl?: typeof fetch;
6
+ }
7
+ export interface ProcessSourceMapsResult {
8
+ uploaded: string[];
9
+ failed: string[];
10
+ }
@@ -0,0 +1,21 @@
1
+ /** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */
2
+ export declare const DEFAULT_API_HOST = "https://track.getmonitor.io";
3
+ export interface UploadSourceMapParams {
4
+ /**
5
+ * @internal Test-only override for redirecting delivery to a local mock server (see
6
+ * cli/e2e/processSourceMaps.spec.ts and the nextjs-config/nuxt e2e suites). Never exposed
7
+ * through the public CLI/programmatic surface — real usage always ships to
8
+ * {@link DEFAULT_API_HOST}.
9
+ */
10
+ apiHost?: string;
11
+ authToken: string;
12
+ release: string;
13
+ debugId: string;
14
+ filename: string;
15
+ mapContent: string;
16
+ fetchImpl?: typeof fetch;
17
+ }
18
+ /** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.
19
+ * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides
20
+ * what "failed" means for its own result reporting and disk-write ordering. */
21
+ export declare function uploadSourceMap(params: UploadSourceMapParams): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getmonitor/cli",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",