@libo11y/sourcemaps 0.0.0-stage → 0.6.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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # @libo11y/sourcemaps
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Uploads JavaScript source maps to the libo11y RUM gateway (`o11yrum`). The
4
+ gateway uses them to symbolicate the stack traces of browser and React
5
+ Native errors before it exports them, and to give each error a stable
6
+ fingerprint. It runs on Bun 1.3.13 and Node 24.
7
+
8
+ ```sh
9
+ npm install --save-dev @libo11y/sourcemaps
10
+ ```
11
+
12
+ The package first ships in `ts/v0.3.0` and is published on npm at `0.6.0`
13
+ (also attached as a tarball to the
14
+ [`ts/v0.6.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.6.0)).
15
+
16
+ The gateway stores each map under the app's `service.name`, the release's
17
+ `service.version`, the over-the-air update ID when there is one, and the
18
+ path of the script the map describes. It never serves a map back, so maps
19
+ can be deleted from the build output once they are uploaded.
20
+
21
+ ## The command
22
+
23
+ ```sh
24
+ export O11Y_SOURCEMAPS_TOKEN=... # the app's upload token
25
+ libo11y-sourcemaps upload \
26
+ --endpoint https://shop.example \
27
+ --service shop-web \
28
+ --release 1.4.2 \
29
+ --url-prefix /assets/ \
30
+ --delete \
31
+ dist/assets
32
+ ```
33
+
34
+ | Flag | Meaning |
35
+ | --------------------- | -------------------------------------------------------------------------------------- |
36
+ | `--endpoint URL` | the gateway's base URL, under which it serves `/_o11y/v1/` |
37
+ | `--service NAME` | the app's `service.name` |
38
+ | `--release VERSION` | the release's `service.version` |
39
+ | `--url-prefix PREFIX` | the URL path the directory is served at, such as `/assets/`, or `~/` for the site root |
40
+ | `--update-id ID` | the over-the-air update the maps belong to (`o11y.rum.app.update_id`) |
41
+ | `--token-env VAR` | the environment variable holding the upload token. Default `O11Y_SOURCEMAPS_TOKEN` |
42
+ | `--concurrency N` | uploads in flight at once. Default 4 |
43
+ | `--delete` | removes each uploaded map, and its script's `sourceMappingURL` comment, from the build |
44
+
45
+ The token is read only from the environment, so it never appears in a
46
+ process list. The flag is `--release` so that `--version` prints the
47
+ tool's version. The command prints `uploaded <url> -> <key>` for each map
48
+ that uploaded, also when a later one fails.
49
+ It exits 0 when every map uploaded, 1 when an upload failed or the
50
+ directory holds no maps, and 2 on a usage error.
51
+
52
+ ## The library
53
+
54
+ ```ts
55
+ import { uploadSourceMaps } from "@libo11y/sourcemaps";
56
+
57
+ const uploaded = await uploadSourceMaps({
58
+ endpoint: "https://shop.example",
59
+ token: process.env.O11Y_SOURCEMAPS_TOKEN ?? "",
60
+ service: "shop-web",
61
+ version: "1.4.2",
62
+ urlPrefix: "/assets/",
63
+ directory: "dist/assets",
64
+ });
65
+ ```
66
+
67
+ `findSourceMaps(directory, urlPrefix)` lists the scripts that have an
68
+ external source map, without uploading anything. A script's map is the
69
+ file its last-line `//# sourceMappingURL=` comment names, or a sibling
70
+ `<script>.map` when it has no comment. Inline `data:` maps, maps whose
71
+ real path is outside the directory, `node_modules`, and symbolically
72
+ linked scripts and directories are skipped. URLs are percent-encoded the
73
+ way browsers report them, so `a b.js` is uploaded as `a%20b.js`. Android
74
+ (`index.android.bundle`) and iOS (`main.jsbundle`) React Native bundles
75
+ are found too.
76
+
77
+ Each map is sent gzipped to `POST /_o11y/v1/sourcemaps` with the token as
78
+ a bearer token. An attempt that takes longer than two minutes is
79
+ abandoned. A 429, a 5xx, a timeout or a network failure is retried, up to
80
+ three attempts, after the response's `Retry-After` (at most ten seconds)
81
+ or a short backoff. Once an upload fails no further upload starts, and
82
+ the first failure is thrown as an `UploadError` carrying the HTTP
83
+ `status` (0 when the gateway could not be reached or the map could not be
84
+ read), the `script`, and the maps that did upload in `uploaded`. A token
85
+ that holds white space or characters an HTTP header cannot carry is
86
+ refused before anything is sent, and no message ever includes the token.
87
+ With `deleteAfterUpload`, a map is removed only once every script it
88
+ describes has uploaded.
89
+
90
+ ## The gateway side
91
+
92
+ An app accepts uploads when the gateway configuration names its token
93
+ file and an object store:
94
+
95
+ ```yaml
96
+ object_store:
97
+ s3: { bucket: shop-sourcemaps, prefix: o11yrum/ }
98
+ apps:
99
+ - service_name: shop-web
100
+ origins: ["https://shop.example"]
101
+ sourcemaps: { upload_token_file: /run/secrets/shop-web-sourcemaps }
102
+ ```
103
+
104
+ See the [o11yrum README](../../../go/o11yrum/README.md) for the gateway.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { type UploadOptions } from "./upload.ts";
3
+ /** Runs the command and returns its exit status. */
4
+ export declare function run(args: readonly string[], env: Readonly<Record<string, string | undefined>>, out: (line: string) => void, err: (line: string) => void, upload?: (options: UploadOptions) => Promise<readonly {
5
+ url: string;
6
+ key: string;
7
+ }[]>): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,159 @@
1
+ #!/usr/bin/env node
2
+ /// <reference types="node" />
3
+ /**
4
+ * The libo11y-sourcemaps command. `libo11y-sourcemaps upload ... DIR` uploads the source maps of a
5
+ * build to the libo11y RUM gateway, for use in a build or deploy job.
6
+ *
7
+ * The upload token is read only from an environment variable, never from a flag, so it never
8
+ * appears in a process list.
9
+ *
10
+ * Exit status: 0 when every map uploaded, 1 when an upload failed or the directory holds no maps,
11
+ * 2 on a usage error.
12
+ */
13
+ import { realpathSync } from "node:fs";
14
+ import { fileURLToPath } from "node:url";
15
+ import { parseArgs } from "node:util";
16
+ import { checkToken, UploadError, uploadSourceMaps } from "./upload.js";
17
+ import { VERSION } from "./version.js";
18
+ const USAGE = `usage: libo11y-sourcemaps upload --endpoint URL --service NAME --release VERSION --url-prefix PREFIX
19
+ [--update-id ID] [--token-env VAR] [--concurrency N] [--delete] DIR
20
+
21
+ Uploads every source map under DIR to the RUM gateway at URL, for the app NAME at release VERSION.
22
+
23
+ --endpoint URL the gateway's base URL, under which it serves /_o11y/v1/
24
+ --service NAME the app's service.name
25
+ --release VERSION the release's service.version
26
+ --url-prefix PREFIX the URL path DIR is served at, such as /assets/, or ~/ for the site root
27
+ --update-id ID the over-the-air update the maps belong to (o11y.rum.app.update_id)
28
+ --token-env VAR the environment variable holding the upload token (default O11Y_SOURCEMAPS_TOKEN)
29
+ --concurrency N uploads in flight at once (default 4)
30
+ --delete remove each uploaded map and its sourceMappingURL comment from DIR
31
+ --help print this help
32
+ --version print the version`;
33
+ const DEFAULT_TOKEN_ENV = "O11Y_SOURCEMAPS_TOKEN";
34
+ function message(err) {
35
+ return err instanceof Error ? err.message : String(err);
36
+ }
37
+ /** Runs the command and returns its exit status. */
38
+ export async function run(args, env, out, err, upload = uploadSourceMaps) {
39
+ let parsed;
40
+ try {
41
+ parsed = parse(args);
42
+ }
43
+ catch (e) {
44
+ err(`libo11y-sourcemaps: ${message(e)}`);
45
+ err(USAGE);
46
+ return 2;
47
+ }
48
+ const { values, positionals } = parsed;
49
+ if (values.help === true) {
50
+ out(USAGE);
51
+ return 0;
52
+ }
53
+ if (values.version === true) {
54
+ out(VERSION);
55
+ return 0;
56
+ }
57
+ if (positionals[0] !== "upload" || positionals.length !== 2) {
58
+ err(USAGE);
59
+ return 2;
60
+ }
61
+ const directory = positionals[1] ?? "";
62
+ for (const flag of ["endpoint", "service", "release", "url-prefix"]) {
63
+ if (values[flag] === undefined || values[flag] === "") {
64
+ err(`libo11y-sourcemaps: --${flag} is required`);
65
+ err(USAGE);
66
+ return 2;
67
+ }
68
+ }
69
+ const concurrency = values.concurrency === undefined ? 4 : Number(values.concurrency);
70
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
71
+ err(`libo11y-sourcemaps: --concurrency must be a positive integer, got ${values.concurrency}`);
72
+ return 2;
73
+ }
74
+ try {
75
+ new URL(values.endpoint ?? "");
76
+ }
77
+ catch {
78
+ err(`libo11y-sourcemaps: --endpoint ${values.endpoint} is not a URL`);
79
+ return 2;
80
+ }
81
+ const tokenEnv = values["token-env"] ?? DEFAULT_TOKEN_ENV;
82
+ const token = (env[tokenEnv] ?? "").trim();
83
+ if (token === "") {
84
+ err(`libo11y-sourcemaps: the upload token variable ${tokenEnv} is not set`);
85
+ return 2;
86
+ }
87
+ try {
88
+ checkToken(token);
89
+ }
90
+ catch (e) {
91
+ err(`libo11y-sourcemaps: ${tokenEnv}: ${message(e)}`);
92
+ return 2;
93
+ }
94
+ const options = {
95
+ endpoint: values.endpoint ?? "",
96
+ token,
97
+ service: values.service ?? "",
98
+ version: values.release ?? "",
99
+ urlPrefix: values["url-prefix"] ?? "",
100
+ directory,
101
+ deleteAfterUpload: values.delete === true,
102
+ concurrency,
103
+ ...(values["update-id"] === undefined ? {} : { updateId: values["update-id"] }),
104
+ };
105
+ let uploaded;
106
+ try {
107
+ uploaded = await upload(options);
108
+ }
109
+ catch (e) {
110
+ if (e instanceof UploadError) {
111
+ for (const u of e.uploaded)
112
+ out(`uploaded ${u.url} -> ${u.key}`);
113
+ }
114
+ err(`libo11y-sourcemaps: ${message(e)}`);
115
+ return 1;
116
+ }
117
+ if (uploaded.length === 0) {
118
+ err(`libo11y-sourcemaps: no source maps found under ${directory}`);
119
+ return 1;
120
+ }
121
+ for (const u of uploaded)
122
+ out(`uploaded ${u.url} -> ${u.key}`);
123
+ return 0;
124
+ }
125
+ function parse(args) {
126
+ return parseArgs({
127
+ args: [...args],
128
+ allowPositionals: true,
129
+ strict: true,
130
+ options: {
131
+ endpoint: { type: "string" },
132
+ service: { type: "string" },
133
+ release: { type: "string" },
134
+ "url-prefix": { type: "string" },
135
+ "update-id": { type: "string" },
136
+ "token-env": { type: "string" },
137
+ concurrency: { type: "string" },
138
+ delete: { type: "boolean" },
139
+ help: { type: "boolean", short: "h" },
140
+ version: { type: "boolean" },
141
+ },
142
+ });
143
+ }
144
+ // isEntry reports whether this module is the program being run. It compares the resolved script path,
145
+ // which follows the bin symlink npm installs, because import.meta.main needs Node 24.2 or later.
146
+ function isEntry() {
147
+ const script = process.argv[1];
148
+ if (script === undefined)
149
+ return false;
150
+ try {
151
+ return realpathSync(script) === fileURLToPath(import.meta.url);
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ }
157
+ if (isEntry()) {
158
+ process.exitCode = await run(process.argv.slice(2), process.env, (line) => process.stdout.write(`${line}\n`), (line) => process.stderr.write(`${line}\n`));
159
+ }
package/dist/find.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /** A script and the source map that describes it. */
2
+ export interface SourceMapFile {
3
+ /** Absolute path of the generated script. */
4
+ readonly script: string;
5
+ /** Absolute path of its source map. */
6
+ readonly map: string;
7
+ /** The URL path the script is served at, as stack traces report it. */
8
+ readonly url: string;
9
+ }
10
+ /**
11
+ * Finds every script under directory that has an external source map: the file its
12
+ * `//# sourceMappingURL=` comment names, or a sibling `<script>.map` when it has no comment. Scripts
13
+ * with an inline `data:` map are skipped, and so is a map outside directory, symbolic links
14
+ * resolved. `node_modules`, symbolically linked scripts and symbolically linked directories are not
15
+ * searched. Each script's URL is urlPrefix joined to its path relative to directory, percent-encoded
16
+ * as a browser reports it, so with urlPrefix "/assets/" the file `app.js` is served at
17
+ * "/assets/app.js". A "~/" prefix stands for the site root. The result is sorted by URL.
18
+ */
19
+ export declare function findSourceMaps(directory: string, urlPrefix: string): Promise<SourceMapFile[]>;
20
+ /** The sourceMappingURL comment on a script's last non-empty line, if any. */
21
+ export declare function mapComment(text: string): string | undefined;
package/dist/find.js ADDED
@@ -0,0 +1,95 @@
1
+ import { readdir, readFile, realpath, stat } from "node:fs/promises";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ const SCRIPT = /\.(?:m?js|cjs|bundle|jsbundle)$/;
4
+ const MAP_COMMENT = /^\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/;
5
+ /**
6
+ * Finds every script under directory that has an external source map: the file its
7
+ * `//# sourceMappingURL=` comment names, or a sibling `<script>.map` when it has no comment. Scripts
8
+ * with an inline `data:` map are skipped, and so is a map outside directory, symbolic links
9
+ * resolved. `node_modules`, symbolically linked scripts and symbolically linked directories are not
10
+ * searched. Each script's URL is urlPrefix joined to its path relative to directory, percent-encoded
11
+ * as a browser reports it, so with urlPrefix "/assets/" the file `app.js` is served at
12
+ * "/assets/app.js". A "~/" prefix stands for the site root. The result is sorted by URL.
13
+ */
14
+ export async function findSourceMaps(directory, urlPrefix) {
15
+ const root = resolve(directory);
16
+ const realRoot = await realpath(root);
17
+ const out = [];
18
+ for (const script of await walk(root)) {
19
+ if (!SCRIPT.test(script))
20
+ continue;
21
+ const map = await mapFor(realRoot, script);
22
+ if (map === undefined)
23
+ continue;
24
+ const rel = relative(root, script).split(sep).map(encodeURIComponent).join("/");
25
+ out.push({ script, map, url: joinUrl(urlPrefix, rel) });
26
+ }
27
+ return out.sort((a, b) => (a.url < b.url ? -1 : a.url > b.url ? 1 : 0));
28
+ }
29
+ /** The sourceMappingURL comment on a script's last non-empty line, if any. */
30
+ export function mapComment(text) {
31
+ const tail = text.trimEnd().split("\n").at(-1) ?? "";
32
+ return MAP_COMMENT.exec(tail.trim())?.[1];
33
+ }
34
+ // mapFor returns the map of script, when it is a file whose real path is inside realRoot.
35
+ async function mapFor(realRoot, script) {
36
+ const ref = mapComment(await readFile(script, "utf8"));
37
+ let candidate;
38
+ if (ref !== undefined) {
39
+ if (ref.startsWith("data:") || /^[a-z][a-z0-9+.-]*:\/\//i.test(ref))
40
+ return undefined;
41
+ const path = ref.split(/[?#]/)[0] ?? "";
42
+ let decoded;
43
+ try {
44
+ decoded = decodeURIComponent(path);
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ candidate = resolve(dirname(script), decoded);
50
+ }
51
+ else {
52
+ candidate = `${script}.map`;
53
+ }
54
+ let real;
55
+ try {
56
+ real = await realpath(candidate);
57
+ }
58
+ catch {
59
+ return undefined;
60
+ }
61
+ if (!inside(realRoot, real))
62
+ return undefined;
63
+ return (await isFile(real)) ? candidate : undefined;
64
+ }
65
+ // inside reports whether path is root or below it.
66
+ function inside(root, path) {
67
+ const rel = relative(root, path);
68
+ return rel !== "" && !rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel);
69
+ }
70
+ async function walk(dir) {
71
+ const out = [];
72
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
73
+ const path = join(dir, entry.name);
74
+ if (entry.isDirectory()) {
75
+ if (entry.name !== "node_modules")
76
+ out.push(...(await walk(path)));
77
+ }
78
+ else if (entry.isFile()) {
79
+ out.push(path);
80
+ }
81
+ }
82
+ return out;
83
+ }
84
+ async function isFile(path) {
85
+ try {
86
+ return (await stat(path)).isFile();
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ }
92
+ // joinUrl joins prefix and a relative path with exactly one slash.
93
+ function joinUrl(prefix, rel) {
94
+ return `${prefix.replace(/\/+$/, "")}/${rel.replace(/^\/+/, "")}`;
95
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Uploads JavaScript source maps to the libo11y RUM gateway, which uses them to symbolicate the
3
+ * stack traces of browser and React Native errors. It runs on Bun and Node.
4
+ *
5
+ * ```ts
6
+ * import { uploadSourceMaps } from "@libo11y/sourcemaps";
7
+ *
8
+ * await uploadSourceMaps({
9
+ * endpoint: "https://shop.example",
10
+ * token: process.env.O11Y_SOURCEMAPS_TOKEN ?? "",
11
+ * service: "shop-web",
12
+ * version: "1.4.2",
13
+ * urlPrefix: "/assets/",
14
+ * directory: "dist/assets",
15
+ * deleteAfterUpload: true,
16
+ * });
17
+ * ```
18
+ *
19
+ * The `libo11y-sourcemaps` command does the same from a build job.
20
+ *
21
+ * @packageDocumentation
22
+ */
23
+ export { findSourceMaps, type SourceMapFile } from "./find.ts";
24
+ export { UploadError, type UploadedMap, type UploadOptions, uploadSourceMaps } from "./upload.ts";
25
+ export { VERSION } from "./version.ts";
package/dist/index.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Uploads JavaScript source maps to the libo11y RUM gateway, which uses them to symbolicate the
3
+ * stack traces of browser and React Native errors. It runs on Bun and Node.
4
+ *
5
+ * ```ts
6
+ * import { uploadSourceMaps } from "@libo11y/sourcemaps";
7
+ *
8
+ * await uploadSourceMaps({
9
+ * endpoint: "https://shop.example",
10
+ * token: process.env.O11Y_SOURCEMAPS_TOKEN ?? "",
11
+ * service: "shop-web",
12
+ * version: "1.4.2",
13
+ * urlPrefix: "/assets/",
14
+ * directory: "dist/assets",
15
+ * deleteAfterUpload: true,
16
+ * });
17
+ * ```
18
+ *
19
+ * The `libo11y-sourcemaps` command does the same from a build job.
20
+ *
21
+ * @packageDocumentation
22
+ */
23
+ export { findSourceMaps } from "./find.js";
24
+ export { UploadError, uploadSourceMaps } from "./upload.js";
25
+ export { VERSION } from "./version.js";
@@ -0,0 +1,65 @@
1
+ /** Options for uploadSourceMaps. */
2
+ export interface UploadOptions {
3
+ /** The gateway's base URL, under which it serves /_o11y/v1/, such as "https://app.example.com". */
4
+ readonly endpoint: string;
5
+ /** The app's upload token, sent as a bearer token. */
6
+ readonly token: string;
7
+ /** The app's service.name. */
8
+ readonly service: string;
9
+ /** The release's service.version. */
10
+ readonly version: string;
11
+ /** The over-the-air update the maps belong to, o11y.rum.app.update_id, when there is one. */
12
+ readonly updateId?: string;
13
+ /** The URL path the directory is served at, such as "/assets/", or "~/" for the site root. */
14
+ readonly urlPrefix: string;
15
+ /** The build output directory to search. */
16
+ readonly directory: string;
17
+ /**
18
+ * Removes each uploaded map and the sourceMappingURL comment of its script, so the maps are not
19
+ * deployed. A map is left in place when the upload of any script it describes failed or did not
20
+ * run. Default false.
21
+ */
22
+ readonly deleteAfterUpload?: boolean;
23
+ /** The uploads in flight at once. Default 4. */
24
+ readonly concurrency?: number;
25
+ /** The fetch to use. Default globalThis.fetch. */
26
+ readonly fetch?: typeof fetch;
27
+ }
28
+ /** A map the gateway stored. */
29
+ export interface UploadedMap {
30
+ /** Absolute path of the script the map describes. */
31
+ readonly script: string;
32
+ /** The URL path the map was uploaded for. */
33
+ readonly url: string;
34
+ /** The object key the gateway stored the map under. */
35
+ readonly key: string;
36
+ }
37
+ /** An upload the gateway refused, or that could not reach it. */
38
+ export declare class UploadError extends Error {
39
+ /** The HTTP status, or 0 when the gateway could not be reached or the map could not be read. */
40
+ readonly status: number;
41
+ /** Absolute path of the script whose map failed to upload. */
42
+ readonly script: string;
43
+ /** The maps that did upload before the failure stopped the run. */
44
+ readonly uploaded: readonly UploadedMap[];
45
+ constructor(message: string, status: number, script: string, uploaded?: readonly UploadedMap[], options?: ErrorOptions);
46
+ }
47
+ /** Seams for tests. */
48
+ export interface UploadDeps {
49
+ readonly sleep: (ms: number) => Promise<void>;
50
+ /** How long one attempt may take. Default 120000. */
51
+ readonly timeoutMillis?: number;
52
+ }
53
+ /**
54
+ * Finds the scripts with external source maps under options.directory and uploads each map to the
55
+ * gateway's POST /_o11y/v1/sourcemaps, gzipped. A 429, a 5xx, a timeout or a network failure is
56
+ * retried, up to three attempts in all, waiting for the response's Retry-After (at most ten
57
+ * seconds) when it has one. Once an upload fails no further upload starts, and the first failure
58
+ * is thrown as an UploadError, listing the maps that did upload, after the uploads in flight
59
+ * settle.
60
+ */
61
+ export declare function uploadSourceMaps(options: UploadOptions): Promise<UploadedMap[]>;
62
+ /** uploadSourceMaps with its seams, for tests. */
63
+ export declare function uploadSourceMapsWith(options: UploadOptions, deps: UploadDeps): Promise<UploadedMap[]>;
64
+ /** Throws when token is empty or holds a character an HTTP header cannot carry. It never echoes it. */
65
+ export declare function checkToken(token: string): void;
package/dist/upload.js ADDED
@@ -0,0 +1,250 @@
1
+ import { readFile, realpath, rm, writeFile } from "node:fs/promises";
2
+ import { gzipSync } from "node:zlib";
3
+ import { findSourceMaps, mapComment } from "./find.js";
4
+ /** An upload the gateway refused, or that could not reach it. */
5
+ export class UploadError extends Error {
6
+ /** The HTTP status, or 0 when the gateway could not be reached or the map could not be read. */
7
+ status;
8
+ /** Absolute path of the script whose map failed to upload. */
9
+ script;
10
+ /** The maps that did upload before the failure stopped the run. */
11
+ uploaded;
12
+ constructor(message, status, script, uploaded = [], options) {
13
+ super(message, options);
14
+ this.name = "UploadError";
15
+ this.status = status;
16
+ this.script = script;
17
+ this.uploaded = uploaded;
18
+ }
19
+ }
20
+ const UPLOAD_PATH = "_o11y/v1/sourcemaps";
21
+ const MAX_ATTEMPTS = 3;
22
+ const BACKOFF_MILLIS = [200, 400];
23
+ const MAX_RETRY_AFTER_MILLIS = 10_000;
24
+ const DEFAULT_TIMEOUT_MILLIS = 120_000;
25
+ // An HTTP header value can carry only visible ASCII without surprises. A token with anything else,
26
+ // such as a line break pasted into a CI secret, would make fetch throw an error quoting it.
27
+ const TOKEN = /^[\x21-\x7e]+$/;
28
+ const defaultDeps = {
29
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
30
+ };
31
+ /**
32
+ * Finds the scripts with external source maps under options.directory and uploads each map to the
33
+ * gateway's POST /_o11y/v1/sourcemaps, gzipped. A 429, a 5xx, a timeout or a network failure is
34
+ * retried, up to three attempts in all, waiting for the response's Retry-After (at most ten
35
+ * seconds) when it has one. Once an upload fails no further upload starts, and the first failure
36
+ * is thrown as an UploadError, listing the maps that did upload, after the uploads in flight
37
+ * settle.
38
+ */
39
+ export function uploadSourceMaps(options) {
40
+ return uploadSourceMapsWith(options, defaultDeps);
41
+ }
42
+ /** uploadSourceMaps with its seams, for tests. */
43
+ export async function uploadSourceMapsWith(options, deps) {
44
+ const concurrency = options.concurrency ?? 4;
45
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
46
+ throw new RangeError(`@libo11y/sourcemaps: concurrency must be a positive integer, got ${concurrency}`);
47
+ }
48
+ checkToken(options.token);
49
+ const base = endpointURL(options.endpoint);
50
+ const doFetch = options.fetch ?? globalThis.fetch;
51
+ const files = await findSourceMaps(options.directory, options.urlPrefix);
52
+ const uploaded = new Array(files.length);
53
+ let failure;
54
+ let next = 0;
55
+ const worker = async () => {
56
+ while (failure === undefined && next < files.length) {
57
+ const i = next++;
58
+ const file = files[i];
59
+ if (file === undefined)
60
+ continue;
61
+ try {
62
+ uploaded[i] = await uploadOne(base, options, file, doFetch, deps);
63
+ }
64
+ catch (err) {
65
+ failure ??=
66
+ err instanceof UploadError
67
+ ? err
68
+ : new UploadError(`reading ${file.map} failed: ${redact(describe(err), options.token)}`, 0, file.script, [], { cause: sanitizeCause(err, options.token) });
69
+ }
70
+ }
71
+ };
72
+ await Promise.all(Array.from({ length: Math.min(concurrency, files.length) }, worker));
73
+ const done = uploaded.filter((u) => u !== undefined);
74
+ if (options.deleteAfterUpload === true)
75
+ await removeUploaded(files, uploaded);
76
+ if (failure !== undefined) {
77
+ throw new UploadError(failure.message, failure.status, failure.script, done, { cause: failure.cause });
78
+ }
79
+ return done;
80
+ }
81
+ /** Throws when token is empty or holds a character an HTTP header cannot carry. It never echoes it. */
82
+ export function checkToken(token) {
83
+ if (token === "")
84
+ throw new TypeError("@libo11y/sourcemaps: the upload token is empty");
85
+ if (!TOKEN.test(token)) {
86
+ throw new TypeError("@libo11y/sourcemaps: the upload token holds white space or characters an HTTP header cannot carry");
87
+ }
88
+ }
89
+ function endpointURL(endpoint) {
90
+ let url;
91
+ try {
92
+ url = new URL(endpoint);
93
+ }
94
+ catch {
95
+ throw new TypeError(`@libo11y/sourcemaps: endpoint ${JSON.stringify(endpoint)} is not a URL`);
96
+ }
97
+ if (!url.pathname.endsWith("/"))
98
+ url.pathname += "/";
99
+ return new URL(UPLOAD_PATH, url);
100
+ }
101
+ // describe renders an error with its cause, where fetch keeps the reason a request failed, such as
102
+ // ECONNREFUSED or a certificate error.
103
+ function describe(err) {
104
+ if (!(err instanceof Error))
105
+ return String(err);
106
+ const cause = err.cause;
107
+ if (cause instanceof Error)
108
+ return `${err.message}: ${cause.message}`;
109
+ if (cause !== undefined && cause !== null)
110
+ return `${err.message}: ${String(cause)}`;
111
+ return err.message;
112
+ }
113
+ // redact removes the token from a message, whatever a runtime put in its error.
114
+ function redact(message, token) {
115
+ return token === "" ? message : message.split(token).join("[token]");
116
+ }
117
+ // sanitizeCause clones an error chain with the token redacted so UploadError.cause never leaks it.
118
+ function sanitizeCause(err, token, seen = new Set()) {
119
+ if (err === undefined || err === null)
120
+ return undefined;
121
+ if (err instanceof Error) {
122
+ if (seen.has(err))
123
+ return undefined;
124
+ seen.add(err);
125
+ const cause = sanitizeCause(err.cause, token, seen);
126
+ const clean = new Error(redact(err.message, token), cause === undefined ? undefined : { cause });
127
+ clean.name = redact(err.name, token);
128
+ return clean;
129
+ }
130
+ return new Error(redact(String(err), token));
131
+ }
132
+ // retryDelay is the wait before attempt+1: the response's Retry-After in seconds, capped, or the
133
+ // backoff for the attempt.
134
+ function retryDelay(attempt, retryAfter) {
135
+ const backoff = BACKOFF_MILLIS[attempt - 1] ?? 400;
136
+ if (retryAfter === null || !/^\d+$/.test(retryAfter.trim()))
137
+ return backoff;
138
+ return Math.min(Number(retryAfter.trim()) * 1000, MAX_RETRY_AFTER_MILLIS);
139
+ }
140
+ async function uploadOne(base, options, file, doFetch, deps) {
141
+ const url = new URL(base);
142
+ url.searchParams.set("service", options.service);
143
+ url.searchParams.set("version", options.version);
144
+ if (options.updateId !== undefined && options.updateId !== "") {
145
+ url.searchParams.set("update_id", options.updateId);
146
+ }
147
+ url.searchParams.set("url", file.url);
148
+ const body = gzipSync(await readFile(file.map));
149
+ const timeoutMillis = deps.timeoutMillis ?? DEFAULT_TIMEOUT_MILLIS;
150
+ for (let attempt = 1;; attempt++) {
151
+ let res;
152
+ let body201;
153
+ try {
154
+ res = await doFetch(url, {
155
+ method: "POST",
156
+ headers: {
157
+ authorization: `Bearer ${options.token}`,
158
+ "content-type": "application/json",
159
+ "content-encoding": "gzip",
160
+ },
161
+ body,
162
+ signal: AbortSignal.timeout(timeoutMillis),
163
+ });
164
+ if (res.status === 201)
165
+ body201 = await res.text();
166
+ }
167
+ catch (err) {
168
+ if (attempt < MAX_ATTEMPTS) {
169
+ await deps.sleep(retryDelay(attempt, null));
170
+ continue;
171
+ }
172
+ const reason = err instanceof Error && err.name === "TimeoutError"
173
+ ? `timed out after ${timeoutMillis} ms`
174
+ : redact(describe(err), options.token);
175
+ throw new UploadError(`upload of ${file.url} could not reach the gateway: ${reason}`, 0, file.script, [], {
176
+ cause: sanitizeCause(err, options.token),
177
+ });
178
+ }
179
+ if (res.status === 201) {
180
+ const text = body201 ?? "";
181
+ const key = keyOf(text);
182
+ if (key !== "")
183
+ return { script: file.script, url: file.url, key };
184
+ const detail = redact(text, options.token).trim().slice(0, 200);
185
+ throw new UploadError(`upload of ${file.url} returned 201 without an object key${detail === "" ? "" : `: ${detail}`}`, res.status, file.script);
186
+ }
187
+ if ((res.status === 429 || res.status >= 500) && attempt < MAX_ATTEMPTS) {
188
+ await res.body?.cancel().catch(() => { });
189
+ await deps.sleep(retryDelay(attempt, res.headers.get("retry-after")));
190
+ continue;
191
+ }
192
+ const text = await res.text().catch(() => "");
193
+ const detail = redact(text, options.token).trim().slice(0, 200);
194
+ throw new UploadError(`upload of ${file.url} failed with ${res.status}${detail === "" ? "" : `: ${detail}`}`, res.status, file.script);
195
+ }
196
+ }
197
+ function keyOf(text) {
198
+ try {
199
+ const parsed = JSON.parse(text);
200
+ if (typeof parsed === "object" &&
201
+ parsed !== null &&
202
+ "key" in parsed &&
203
+ typeof parsed.key === "string" &&
204
+ parsed.key.trim() !== "") {
205
+ return parsed.key;
206
+ }
207
+ }
208
+ catch {
209
+ // Non-JSON responses cannot confirm the gateway stored the map.
210
+ }
211
+ return "";
212
+ }
213
+ // removeUploaded strips the sourceMappingURL comment of every uploaded script, and deletes each map
214
+ // once every script it describes has uploaded.
215
+ async function removeUploaded(files, uploaded) {
216
+ // Resolve aliases before deleting anything, since removing the target can break a symlink.
217
+ const canonical = new Map();
218
+ for (const { map } of files) {
219
+ if (!canonical.has(map)) {
220
+ // A path that has already disappeared still groups with entries using the same path.
221
+ canonical.set(map, await realpath(map).catch(() => map));
222
+ }
223
+ }
224
+ const pending = new Set();
225
+ for (const [i, f] of files.entries()) {
226
+ if (uploaded[i] === undefined)
227
+ pending.add(canonical.get(f.map) ?? f.map);
228
+ }
229
+ const removed = new Set();
230
+ for (const [i, f] of files.entries()) {
231
+ if (uploaded[i] === undefined)
232
+ continue;
233
+ await stripComment(f.script);
234
+ if (!pending.has(canonical.get(f.map) ?? f.map) && !removed.has(f.map)) {
235
+ removed.add(f.map);
236
+ await rm(f.map, { force: true });
237
+ }
238
+ }
239
+ }
240
+ // stripComment removes a script's sourceMappingURL comment when it is the last line. It works on
241
+ // latin1 text, which maps every byte to one character, so a script that is not UTF-8 keeps its
242
+ // bytes.
243
+ async function stripComment(script) {
244
+ const text = await readFile(script, "latin1");
245
+ if (mapComment(text) === undefined)
246
+ return;
247
+ const trimmed = text.trimEnd();
248
+ const cut = trimmed.lastIndexOf("\n");
249
+ await writeFile(script, cut < 0 ? "" : trimmed.slice(0, cut + 1), "latin1");
250
+ }
@@ -0,0 +1,2 @@
1
+ /** The `@libo11y/sourcemaps` package version. scripts/release.ts keeps it equal to package.json. */
2
+ export declare const VERSION = "0.6.0";
@@ -0,0 +1,2 @@
1
+ /** The `@libo11y/sourcemaps` package version. scripts/release.ts keeps it equal to package.json. */
2
+ export const VERSION = "0.6.0";
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@libo11y/sourcemaps",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.0",
4
+ "description": "Uploads JavaScript source maps to the libo11y RUM gateway so it can symbolicate browser and React Native stack traces. A library and the libo11y-sourcemaps command for Bun and Node.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "bin": {
15
+ "libo11y-sourcemaps": "./dist/cli.js"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/libo11y/libo11y.git",
20
+ "directory": "ts/packages/sourcemaps"
21
+ },
22
+ "devDependencies": {
23
+ "@libo11y/test": "0.6.0"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public",
32
+ "provenance": true
33
+ }
34
+ }