@getmonitor/cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +84 -0
- package/dist/bin.d.ts +9 -0
- package/dist/bin.js +321 -0
- package/dist/bin.js.map +1 -0
- package/dist/discoverArtifacts.d.ts +10 -0
- package/dist/index.cjs +267 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +265 -0
- package/dist/index.js.map +1 -0
- package/dist/injectDebugId.d.ts +16 -0
- package/dist/processSourceMaps.d.ts +7 -0
- package/dist/resolveRelease.d.ts +6 -0
- package/dist/types.d.ts +11 -0
- package/dist/uploadSourceMap.d.ts +14 -0
- package/package.json +33 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# @getmonitor/cli
|
|
2
|
+
|
|
3
|
+
Framework-agnostic source map upload tool for GetMonitor error tracking. Used directly, or via
|
|
4
|
+
`@getmonitor/nextjs-config` / `@getmonitor/nuxt`, which call its programmatic API automatically
|
|
5
|
+
as part of a customer's build.
|
|
6
|
+
|
|
7
|
+
## What it does
|
|
8
|
+
|
|
9
|
+
For every `*.js` file with a resolvable source map under a directory, `processSourceMaps`:
|
|
10
|
+
|
|
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 `{apiHost}/api/v1/sourcemaps`.
|
|
13
|
+
3. On a successful upload: deletes the `.map` file and strips the `//# sourceMappingURL=`
|
|
14
|
+
comment from the JS file, so nothing readable ships publicly.
|
|
15
|
+
4. On a failed upload: leaves both files untouched, so the artifact can be retried.
|
|
16
|
+
|
|
17
|
+
A source map is resolved primarily via the JS file's `//# sourceMappingURL=` comment, falling
|
|
18
|
+
back to same-basename-plus-`.map` when there's no comment, it's a `data:` URI, or the referenced
|
|
19
|
+
file doesn't exist — this matters because bundlers don't always name maps predictably (content
|
|
20
|
+
hashes, CDN rewrites).
|
|
21
|
+
|
|
22
|
+
See the [Phase 2 design spec](../../docs/superpowers/specs/2026-08-09-phase-2-source-maps-design.md)
|
|
23
|
+
for the full architecture and upload contract.
|
|
24
|
+
|
|
25
|
+
## CLI usage
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npm install --save-dev @getmonitor/cli
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
getmonitor sourcemaps upload ./dist \
|
|
33
|
+
--api-host https://ingest.getmonitor.com \
|
|
34
|
+
--release 1.4.2 \
|
|
35
|
+
--auth-token $GETMONITOR_AUTH_TOKEN
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`--release` and `--auth-token` are optional if `GETMONITOR_RELEASE` / `GETMONITOR_AUTH_TOKEN`
|
|
39
|
+
are set, or (for release) if the directory is inside a git working tree or has a reachable
|
|
40
|
+
`package.json` with a `version` field. Release resolution precedence: `--release` flag >
|
|
41
|
+
`GETMONITOR_RELEASE` env var > current git commit SHA > nearest `package.json`'s `version` field.
|
|
42
|
+
|
|
43
|
+
The auth token is a **secret credential**, separate from the public `gm_xxx` key the SDKs use —
|
|
44
|
+
never commit it or expose it client-side.
|
|
45
|
+
|
|
46
|
+
## Programmatic usage
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { processSourceMaps } from '@getmonitor/cli'
|
|
50
|
+
|
|
51
|
+
const result = await processSourceMaps({
|
|
52
|
+
directory: './dist',
|
|
53
|
+
apiHost: 'https://ingest.getmonitor.com',
|
|
54
|
+
authToken: process.env.GETMONITOR_AUTH_TOKEN,
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
console.log(result.uploaded, result.failed)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
This is what `@getmonitor/nextjs-config` and `@getmonitor/nuxt` call from their bundler's
|
|
61
|
+
build-finished hook — see those packages for the build-tool-integrated version of this flow.
|
|
62
|
+
|
|
63
|
+
## API reference
|
|
64
|
+
|
|
65
|
+
| Export | Signature |
|
|
66
|
+
| --- | --- |
|
|
67
|
+
| `processSourceMaps(options)` | `(ProcessSourceMapsOptions) => Promise<ProcessSourceMapsResult>` |
|
|
68
|
+
|
|
69
|
+
`ProcessSourceMapsOptions` = `{ directory: string; apiHost: string; release?: string; authToken?: string; fetchImpl?: typeof fetch }`
|
|
70
|
+
(`fetchImpl` is a test/dependency-injection hook — most consumers won't need it).
|
|
71
|
+
`ProcessSourceMapsResult` = `{ uploaded: string[]; failed: string[] }` — full on-disk paths of
|
|
72
|
+
each processed artifact, split by outcome.
|
|
73
|
+
|
|
74
|
+
## Development
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pnpm --filter @getmonitor/cli build # rollup -> dist/ (library ESM+CJS+.d.ts, plus dist/bin.js)
|
|
78
|
+
pnpm --filter @getmonitor/cli test # vitest run (excludes e2e/)
|
|
79
|
+
pnpm --filter @getmonitor/cli test:e2e # vitest run e2e/processSourceMaps.spec.ts — real esbuild output + real HTTP server
|
|
80
|
+
pnpm --filter @getmonitor/cli lint # tsc --noEmit (src/) + tsc --noEmit -p e2e
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The `e2e/` suite builds a real fixture through `esbuild`, runs `processSourceMaps` against the
|
|
84
|
+
real output, and asserts against a real (in-process) mock ingestion server — no mocked `fetch`.
|
package/dist/bin.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
interface ParsedArgs {
|
|
2
|
+
directory: string;
|
|
3
|
+
apiHost: string;
|
|
4
|
+
release?: string;
|
|
5
|
+
authToken?: string;
|
|
6
|
+
}
|
|
7
|
+
/** Exported (not just used internally) so it's unit-testable without spawning a process. */
|
|
8
|
+
export declare function parseArgs(argv: string[]): ParsedArgs;
|
|
9
|
+
export {};
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
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
|
+
/** POSTs a single source map artifact to the (not-yet-implemented) backend contract
|
|
175
|
+
* documented in docs/superpowers/specs/2026-08-09-phase-2-source-maps-design.md. Throws on
|
|
176
|
+
* any non-2xx response or network failure — the caller (processSourceMaps) decides what
|
|
177
|
+
* "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 form = new FormData();
|
|
188
|
+
form.set('release', params.release);
|
|
189
|
+
form.set('debugId', params.debugId);
|
|
190
|
+
form.set('filename', params.filename);
|
|
191
|
+
form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`);
|
|
192
|
+
const response = await fetchImpl(`${params.apiHost}/api/v1/sourcemaps`, {
|
|
193
|
+
method: 'POST',
|
|
194
|
+
headers: { Authorization: `Bearer ${params.authToken}` },
|
|
195
|
+
body: form,
|
|
196
|
+
});
|
|
197
|
+
if (!response.ok) {
|
|
198
|
+
throw new Error(`Source map upload failed for ${params.filename}: ${response.status} ${response.statusText}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// packages/cli/src/processSourceMaps.ts
|
|
203
|
+
/** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a
|
|
204
|
+
* debug ID, uploads the tagged source map, and — only on a successful upload — writes the
|
|
205
|
+
* debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload
|
|
206
|
+
* fails is left completely untouched on disk, so it can be retried by re-running this
|
|
207
|
+
* function against the same directory. */
|
|
208
|
+
async function processSourceMaps(options) {
|
|
209
|
+
const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN;
|
|
210
|
+
if (!authToken) {
|
|
211
|
+
throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.');
|
|
212
|
+
}
|
|
213
|
+
const release = resolveRelease(options.directory, options.release);
|
|
214
|
+
const artifacts = discoverArtifacts(options.directory);
|
|
215
|
+
const result = { uploaded: [], failed: [] };
|
|
216
|
+
for (const artifact of artifacts) {
|
|
217
|
+
const debugId = randomUUID();
|
|
218
|
+
let injected;
|
|
219
|
+
try {
|
|
220
|
+
const originalJs = readFileSync(artifact.jsPath, 'utf8');
|
|
221
|
+
const originalMap = readFileSync(artifact.mapPath, 'utf8');
|
|
222
|
+
// injectDebugId is a pure function that throws on malformed map JSON (by design — see
|
|
223
|
+
// its own doc comment). That's deliberately caught here, alongside upload failures: one
|
|
224
|
+
// corrupt/unreadable artifact on disk must not abort processing of every other artifact
|
|
225
|
+
// in the directory, the same failure-isolation principle discoverArtifacts applies to
|
|
226
|
+
// unreadable files during its walk. Nothing has been uploaded or written yet at this
|
|
227
|
+
// point, so a thrown injectDebugId or upload failure leaves the artifact's files
|
|
228
|
+
// completely untouched, and it's safe to report it as `failed` for a retry.
|
|
229
|
+
injected = injectDebugId(originalJs, originalMap, debugId);
|
|
230
|
+
await uploadSourceMap({
|
|
231
|
+
apiHost: options.apiHost,
|
|
232
|
+
authToken,
|
|
233
|
+
release,
|
|
234
|
+
debugId,
|
|
235
|
+
// Relative to options.directory, not the absolute on-disk path — the backend has no
|
|
236
|
+
// use for (and shouldn't see) the build machine's local filesystem layout.
|
|
237
|
+
filename: relative(options.directory, artifact.jsPath),
|
|
238
|
+
mapContent: injected.map,
|
|
239
|
+
fetchImpl: options.fetchImpl,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
result.failed.push(artifact.jsPath);
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
writeFileSync(artifact.jsPath, injected.js);
|
|
248
|
+
rmSync(artifact.mapPath);
|
|
249
|
+
result.uploaded.push(artifact.jsPath);
|
|
250
|
+
}
|
|
251
|
+
catch (cleanupError) {
|
|
252
|
+
// The upload above already succeeded, so this must never land in `failed` — a caller
|
|
253
|
+
// retrying failed artifacts would mint a fresh debugId and re-upload, orphaning this
|
|
254
|
+
// upload server-side under the old one with no way to reconcile the two. The local
|
|
255
|
+
// cleanup failure (disk full, permission error, file lock) is real and worth knowing
|
|
256
|
+
// about, so it's surfaced here rather than silently swallowed, but it doesn't change
|
|
257
|
+
// the artifact's outcome.
|
|
258
|
+
result.uploaded.push(artifact.jsPath);
|
|
259
|
+
console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return result;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// packages/cli/src/bin.ts
|
|
266
|
+
/** Exported (not just used internally) so it's unit-testable without spawning a process. */
|
|
267
|
+
function parseArgs(argv) {
|
|
268
|
+
const [command, subcommand, directory, ...rest] = argv;
|
|
269
|
+
if (command !== 'sourcemaps' || subcommand !== 'upload' || !directory) {
|
|
270
|
+
throw new Error('Usage: getmonitor sourcemaps upload <directory> --api-host <url> [--release <release>] [--auth-token <token>]');
|
|
271
|
+
}
|
|
272
|
+
let release;
|
|
273
|
+
let authToken;
|
|
274
|
+
let apiHost;
|
|
275
|
+
for (let i = 0; i < rest.length; i += 2) {
|
|
276
|
+
const flag = rest[i];
|
|
277
|
+
const value = rest[i + 1];
|
|
278
|
+
if (flag === '--release')
|
|
279
|
+
release = value;
|
|
280
|
+
else if (flag === '--auth-token')
|
|
281
|
+
authToken = value;
|
|
282
|
+
else if (flag === '--api-host')
|
|
283
|
+
apiHost = value;
|
|
284
|
+
else
|
|
285
|
+
throw new Error(`Unknown flag: ${flag}`);
|
|
286
|
+
}
|
|
287
|
+
if (!apiHost) {
|
|
288
|
+
throw new Error('Usage: getmonitor sourcemaps upload <directory> --api-host <url> [...]');
|
|
289
|
+
}
|
|
290
|
+
return { directory, apiHost, release, authToken };
|
|
291
|
+
}
|
|
292
|
+
async function main() {
|
|
293
|
+
const args = parseArgs(process.argv.slice(2));
|
|
294
|
+
const result = await processSourceMaps({
|
|
295
|
+
directory: args.directory,
|
|
296
|
+
release: args.release,
|
|
297
|
+
authToken: args.authToken,
|
|
298
|
+
apiHost: args.apiHost,
|
|
299
|
+
});
|
|
300
|
+
console.log(`Uploaded ${result.uploaded.length} source map(s).`);
|
|
301
|
+
if (result.failed.length > 0) {
|
|
302
|
+
console.error(`Failed to upload ${result.failed.length} source map(s):`);
|
|
303
|
+
for (const file of result.failed)
|
|
304
|
+
console.error(` ${file}`);
|
|
305
|
+
process.exitCode = 1;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
// Skipped under Vitest (which imports this module to test parseArgs) — only run when
|
|
309
|
+
// invoked directly as the built dist/bin.js executable. Confirmed empirically that Vitest
|
|
310
|
+
// sets process.env.VITEST = 'true' in the process that loads this module, so this check
|
|
311
|
+
// reliably prevents main() (which does real I/O and can set process.exitCode) from running
|
|
312
|
+
// during `pnpm test`.
|
|
313
|
+
if (process.env.VITEST === undefined) {
|
|
314
|
+
main().catch((error) => {
|
|
315
|
+
console.error(error instanceof Error ? error.message : error);
|
|
316
|
+
process.exitCode = 1;
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export { parseArgs };
|
|
321
|
+
//# sourceMappingURL=bin.js.map
|