@domandigital/sentry 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,339 @@
1
+ // src/env.ts
2
+ var SENTRY_ORG = "domandigital";
3
+ var INGEST_HOST = "o4510784554991616.ingest.de.sentry.io";
4
+ var ENVIRONMENTS = ["production", "staging", "preview"];
5
+ var ENVIRONMENT_VARS = [
6
+ "SENTRY_ENVIRONMENT",
7
+ "PUBLIC_SENTRY_ENVIRONMENT",
8
+ "NEXT_PUBLIC_SENTRY_ENVIRONMENT",
9
+ // Vercel sets these itself, so a Vercel project is right without any setup.
10
+ "VERCEL_ENV",
11
+ "NEXT_PUBLIC_VERCEL_ENV"
12
+ ];
13
+ var RELEASE_VARS = [
14
+ "SENTRY_RELEASE",
15
+ "PUBLIC_SENTRY_RELEASE",
16
+ "NEXT_PUBLIC_SENTRY_RELEASE",
17
+ "CF_PAGES_COMMIT_SHA",
18
+ "WORKERS_CI_COMMIT_SHA",
19
+ "VERCEL_GIT_COMMIT_SHA",
20
+ "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA",
21
+ "GITHUB_SHA"
22
+ ];
23
+ var DSN_VARS = ["SENTRY_DSN", "PUBLIC_SENTRY_DSN", "NEXT_PUBLIC_SENTRY_DSN"];
24
+ function text(value) {
25
+ if (typeof value !== "string") return void 0;
26
+ const trimmed = value.trim();
27
+ return trimmed === "" ? void 0 : trimmed;
28
+ }
29
+ function firstOf(env, names) {
30
+ if (!env) return void 0;
31
+ for (const name of names) {
32
+ const value = text(env[name]);
33
+ if (value) return { value, from: name };
34
+ }
35
+ return void 0;
36
+ }
37
+ var ALIASES = {
38
+ production: "production",
39
+ prod: "production",
40
+ live: "production",
41
+ staging: "staging",
42
+ stage: "staging",
43
+ stg: "staging",
44
+ preview: "preview"
45
+ };
46
+ var LOCAL = /* @__PURE__ */ new Set(["development", "dev", "local", "test"]);
47
+ function resolveEnvironment(input = {}) {
48
+ const explicit = text(input.environment);
49
+ const found = explicit ? { value: explicit, from: "explicit" } : firstOf(input.env, ENVIRONMENT_VARS);
50
+ if (!found) return { environment: "preview", enabled: true, from: null };
51
+ const key = found.value.toLowerCase();
52
+ if (LOCAL.has(key)) return { environment: "preview", enabled: false, from: found.from };
53
+ return { environment: ALIASES[key] ?? "preview", enabled: true, from: found.from };
54
+ }
55
+ function resolveRelease(input = {}) {
56
+ return text(input.release) ?? firstOf(input.env, RELEASE_VARS)?.value;
57
+ }
58
+ var OLD_INGEST = /^(https?:\/\/[^@/]+@)(o\d+\.ingest\.de\.sentry\.io)(\/.*)$/i;
59
+ function normaliseDsn(dsn) {
60
+ const value = text(dsn);
61
+ if (!value) return void 0;
62
+ const match = OLD_INGEST.exec(value);
63
+ return match ? `${match[1]}${INGEST_HOST}${match[3]}` : value;
64
+ }
65
+ function resolveDsn(input = {}) {
66
+ return normaliseDsn(text(input.dsn) ?? firstOf(input.env, DSN_VARS)?.value);
67
+ }
68
+
69
+ // src/filters.ts
70
+ var IGNORE_ERRORS = [
71
+ // In-app browsers and wallet extensions poking at objects they injected.
72
+ /\bethereum\b/i,
73
+ "__firefox__",
74
+ "webkit.messageHandlers",
75
+ "Java object is gone",
76
+ // Globals that tag managers, extensions and injected bars expect to exist.
77
+ /\b(?:googletag|jQuery|zaius|eventTracker) is not defined\b/,
78
+ /(?:^|[^\w$])\$ is not defined\b/,
79
+ /Can't find variable: (?:googletag|jQuery|zaius|eventTracker|\$)(?![\w$])/,
80
+ // Next.js after a deploy: an open tab posts to a server action the new build no longer has.
81
+ "Failed to find Server Action",
82
+ // The browser skipped a view transition (a second navigation, a hidden tab). Nothing broke.
83
+ "Skipping view transition",
84
+ "Transition was skipped"
85
+ ];
86
+ var DENY_URLS = [
87
+ // Errors whose top frame is in a browser extension, or Safari's mask for one.
88
+ /^(?:chrome|moz|safari|safari-web|ms-browser)-extension:\/\//i,
89
+ /^webkit-masked-url:/i,
90
+ // Third-party scripts a site embeds and cannot fix.
91
+ /googletagmanager\.com/i,
92
+ /google-analytics\.com/i,
93
+ /googlesyndication\.com/i,
94
+ /connect\.facebook\.net/i,
95
+ /static\.hotjar\.com/i,
96
+ /clarity\.ms/i
97
+ ];
98
+ var NETWORK_FAILURE = /^(?:Failed to fetch|Load failed|NetworkError when attempting to fetch resource\.)(?: \(([^)\s]+)\))?$/;
99
+ var isRec = (value) => typeof value === "object" && value !== null;
100
+ function bareHost(host) {
101
+ return host.toLowerCase().replace(/:\d+$/, "").replace(/^www\./, "");
102
+ }
103
+ function hostOf(url) {
104
+ if (typeof url !== "string") return void 0;
105
+ try {
106
+ return new URL(url).host;
107
+ } catch {
108
+ return void 0;
109
+ }
110
+ }
111
+ function sameSite(a, b) {
112
+ const x = bareHost(a);
113
+ const y = bareHost(b);
114
+ return x === y || x.endsWith(`.${y}`) || y.endsWith(`.${x}`);
115
+ }
116
+ function isThirdPartyNetworkError(event, hint, firstPartyHosts = []) {
117
+ if (!isRec(event) || !isRec(event.exception) || !Array.isArray(event.exception.values)) return false;
118
+ const values = event.exception.values.filter(isRec);
119
+ const last = values[values.length - 1];
120
+ if (!last || last.type !== "TypeError" || typeof last.value !== "string") return false;
121
+ const match = NETWORK_FAILURE.exec(last.value);
122
+ if (!match) return false;
123
+ const original = isRec(hint) && isRec(hint.originalException) ? hint.originalException : void 0;
124
+ const target = match[1] ?? (typeof original?.__sentry_fetch_url_host__ === "string" ? original.__sentry_fetch_url_host__ : void 0);
125
+ if (!target) return false;
126
+ const page = isRec(event.request) ? hostOf(event.request.url) : void 0;
127
+ const ours = [...firstPartyHosts, ...page ? [page] : []];
128
+ if (ours.length === 0) return false;
129
+ return !ours.some((host) => sameSite(host, target));
130
+ }
131
+
132
+ // src/scrub.ts
133
+ import { scrubSentryEvent as scrubSynthetic } from "@domandigital/synthetic";
134
+ var REDACTED = "[REDACTED]";
135
+ var REDACT_KEYS = /email|token|cookie|authori[sz]ation|^auth$|password|passwd|secret|session|signature|api[-_]?key|phone/i;
136
+ var EMAIL = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/gi;
137
+ var BEARER = /bearer\s+[a-z0-9._\-~+/]+=*/gi;
138
+ var PHONE = /(?<![\w.+])(?:\+44\s?(?:\(0\)\s?)?|0)\d(?:[\s-]?\d){8,9}(?![\w.])/g;
139
+ var MAX_DEPTH = 8;
140
+ var MAX_ITEMS = 100;
141
+ function scrubString(input) {
142
+ return input.replace(EMAIL, "[REDACTED_EMAIL]").replace(BEARER, "Bearer [REDACTED_TOKEN]").replace(PHONE, "[REDACTED_PHONE]");
143
+ }
144
+ function scrubValue(value, depth = 0) {
145
+ if (depth > MAX_DEPTH) return "[TRUNCATED_DEPTH]";
146
+ if (value == null) return value;
147
+ if (typeof value === "string") return scrubString(value);
148
+ if (typeof value === "number" || typeof value === "boolean") return value;
149
+ if (typeof value === "bigint") return value.toString();
150
+ if (value instanceof Error) return { name: value.name, message: scrubString(value.message) };
151
+ if (Array.isArray(value)) return value.slice(0, MAX_ITEMS).map((item) => scrubValue(item, depth + 1));
152
+ if (typeof value === "object") {
153
+ const out = {};
154
+ for (const [key, item] of Object.entries(value)) {
155
+ out[key] = REDACT_KEYS.test(key) ? REDACTED : scrubValue(item, depth + 1);
156
+ }
157
+ return out;
158
+ }
159
+ return String(value);
160
+ }
161
+ var isRec2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
162
+ function scrubRequest(request) {
163
+ const out = { ...request };
164
+ if ("headers" in out) out.headers = scrubValue(out.headers);
165
+ if ("cookies" in out && out.cookies) out.cookies = REDACTED;
166
+ if ("data" in out) out.data = scrubValue(out.data);
167
+ if (typeof out.query_string === "string") out.query_string = scrubString(out.query_string);
168
+ else if ("query_string" in out) out.query_string = scrubValue(out.query_string);
169
+ if (typeof out.url === "string") out.url = scrubString(out.url);
170
+ return out;
171
+ }
172
+ function scrubException(exception) {
173
+ if (!Array.isArray(exception.values)) return exception;
174
+ return {
175
+ ...exception,
176
+ // Only the message: stack frames, types and mechanisms are code, not customer data.
177
+ values: exception.values.map((v) => isRec2(v) && typeof v.value === "string" ? { ...v, value: scrubString(v.value) } : v)
178
+ };
179
+ }
180
+ function scrubBreadcrumb(crumb) {
181
+ if (!isRec2(crumb)) return crumb;
182
+ const out = { ...crumb };
183
+ if (typeof out.message === "string") out.message = scrubString(out.message);
184
+ if ("data" in out) out.data = scrubValue(out.data);
185
+ return out;
186
+ }
187
+ function scrubPii(event) {
188
+ const out = { ...event };
189
+ if (isRec2(out.request)) out.request = scrubRequest(out.request);
190
+ for (const key of ["user", "extra", "contexts", "tags"]) {
191
+ if (key in out) out[key] = scrubValue(out[key]);
192
+ }
193
+ if (typeof out.message === "string") out.message = scrubString(out.message);
194
+ if (isRec2(out.logentry) && typeof out.logentry.message === "string") {
195
+ out.logentry = { ...out.logentry, message: scrubString(out.logentry.message) };
196
+ }
197
+ if (isRec2(out.exception)) out.exception = scrubException(out.exception);
198
+ if (Array.isArray(out.breadcrumbs)) out.breadcrumbs = out.breadcrumbs.map(scrubBreadcrumb);
199
+ return out;
200
+ }
201
+ var SPAN_REDACT_KEYS = /x-dd-synth|cookie|authori[sz]ation|token|secret|password|email|phone/i;
202
+ function scrubAttributes(attributes) {
203
+ const out = {};
204
+ for (const [key, value] of Object.entries(attributes)) {
205
+ if (SPAN_REDACT_KEYS.test(key)) out[key] = REDACTED;
206
+ else if (typeof value === "string") out[key] = scrubString(value);
207
+ else if (Array.isArray(value)) out[key] = value.map((v) => typeof v === "string" ? scrubString(v) : v);
208
+ else out[key] = value;
209
+ }
210
+ return out;
211
+ }
212
+ function scrubSpan(span) {
213
+ try {
214
+ const out = { ...span };
215
+ if (typeof out.name === "string") out.name = scrubString(out.name);
216
+ if (typeof out.description === "string") out.description = scrubString(out.description);
217
+ if (isRec2(out.attributes)) out.attributes = scrubAttributes(out.attributes);
218
+ if (isRec2(out.data)) out.data = scrubAttributes(out.data);
219
+ return out;
220
+ } catch {
221
+ return span;
222
+ }
223
+ }
224
+ function scrubEvent(event) {
225
+ try {
226
+ return scrubSynthetic(scrubPii(event));
227
+ } catch {
228
+ const { request: _request, user: _user, extra: _extra, breadcrumbs: _breadcrumbs, ...rest } = event;
229
+ return rest;
230
+ }
231
+ }
232
+
233
+ // src/preset.ts
234
+ var DATA_COLLECTION = {
235
+ userInfo: false,
236
+ cookies: false,
237
+ httpHeaders: { request: true, response: false },
238
+ httpBodies: [],
239
+ urlQueryParams: true,
240
+ graphQL: { document: true, variables: false },
241
+ genAI: { inputs: false, outputs: false },
242
+ databaseQueryData: false,
243
+ queues: false,
244
+ stackFrameVariables: false
245
+ };
246
+ function isThenable(value) {
247
+ return typeof value === "object" && value !== null && typeof value.then === "function";
248
+ }
249
+ function scrubbingHook(user, drop) {
250
+ return ((event, hint) => {
251
+ if (drop?.(event, hint)) return null;
252
+ const out = user ? user(event, hint) : event;
253
+ if (isThenable(out)) return Promise.resolve(out).then((e) => e ? scrubEvent(e) : null);
254
+ return out ? scrubEvent(out) : null;
255
+ });
256
+ }
257
+ var SCRUB_TRANSACTIONS = {
258
+ name: "DomanDigitalScrubTransactions",
259
+ processEvent: (event) => event.type === "transaction" ? scrubEvent(event) : event
260
+ };
261
+ function withScrubber(integrations) {
262
+ if (typeof integrations === "function") {
263
+ return (defaults) => [...integrations(defaults), SCRUB_TRANSACTIONS];
264
+ }
265
+ return [...Array.isArray(integrations) ? integrations : [], SCRUB_TRANSACTIONS];
266
+ }
267
+ function hasReplay(integrations) {
268
+ return Array.isArray(integrations) && integrations.some((i) => typeof i === "object" && i !== null && i.name === "Replay");
269
+ }
270
+ function buildPreset(input, runtime) {
271
+ const {
272
+ dsn: dsnIn,
273
+ env,
274
+ environment: environmentIn,
275
+ release: releaseIn,
276
+ firstPartyHosts = [],
277
+ ignoreErrors = [],
278
+ denyUrls = [],
279
+ integrations,
280
+ beforeSend,
281
+ beforeSendSpan,
282
+ dataCollection,
283
+ tracesSampleRate,
284
+ replaysSessionSampleRate,
285
+ replaysOnErrorSampleRate,
286
+ sendDefaultPii: _sendDefaultPii,
287
+ ...rest
288
+ } = input;
289
+ const { environment, enabled } = resolveEnvironment({ environment: environmentIn, env });
290
+ const dsn = resolveDsn({ dsn: dsnIn, env });
291
+ const release = resolveRelease({ release: releaseIn, env });
292
+ const out = {
293
+ ...rest,
294
+ environment,
295
+ dataCollection: { ...DATA_COLLECTION, ...dataCollection },
296
+ ignoreErrors: [...IGNORE_ERRORS, ...ignoreErrors],
297
+ denyUrls: [...DENY_URLS, ...denyUrls],
298
+ integrations: withScrubber(integrations),
299
+ beforeSend: scrubbingHook(
300
+ beforeSend,
301
+ runtime.browser ? (event, hint) => isThirdPartyNetworkError(event, hint, firstPartyHosts) : void 0
302
+ ),
303
+ // A site's own hook replaces this one rather than being wrapped: v11 marks
304
+ // a static-span hook (`withStaticSpan`), and a wrapper would lose the mark.
305
+ beforeSendSpan: beforeSendSpan ?? scrubSpan,
306
+ tracesSampleRate: tracesSampleRate ?? runtime.tracesSampleRate
307
+ };
308
+ if (dsn) out.dsn = dsn;
309
+ if (release) out.release = release;
310
+ if (!enabled) out.enabled = false;
311
+ if (runtime.browser && hasReplay(integrations)) {
312
+ out.replaysSessionSampleRate = replaysSessionSampleRate ?? 0;
313
+ out.replaysOnErrorSampleRate = replaysOnErrorSampleRate ?? 1;
314
+ }
315
+ return out;
316
+ }
317
+
318
+ export {
319
+ SENTRY_ORG,
320
+ INGEST_HOST,
321
+ ENVIRONMENTS,
322
+ ENVIRONMENT_VARS,
323
+ RELEASE_VARS,
324
+ DSN_VARS,
325
+ resolveEnvironment,
326
+ resolveRelease,
327
+ normaliseDsn,
328
+ resolveDsn,
329
+ IGNORE_ERRORS,
330
+ DENY_URLS,
331
+ isThirdPartyNetworkError,
332
+ REDACTED,
333
+ scrubString,
334
+ scrubValue,
335
+ scrubSpan,
336
+ scrubEvent,
337
+ DATA_COLLECTION,
338
+ buildPreset
339
+ };
@@ -0,0 +1,15 @@
1
+ // src/third-party.ts
2
+ function applicationKey(project) {
3
+ return `dd-${project}`;
4
+ }
5
+ function thirdPartyFilterOptions(project) {
6
+ return {
7
+ filterKeys: [applicationKey(project)],
8
+ behaviour: "drop-error-if-exclusively-contains-third-party-frames"
9
+ };
10
+ }
11
+
12
+ export {
13
+ applicationKey,
14
+ thirdPartyFilterOptions
15
+ };
@@ -0,0 +1,14 @@
1
+ import {
2
+ buildPreset
3
+ } from "./chunk-BICH2PO4.js";
4
+
5
+ // src/cloudflare.ts
6
+ var SERVER_TRACES_SAMPLE_RATE = 0.1;
7
+ function cloudflareOptions(input = {}) {
8
+ return buildPreset(input, { tracesSampleRate: SERVER_TRACES_SAMPLE_RATE, browser: false });
9
+ }
10
+
11
+ export {
12
+ SERVER_TRACES_SAMPLE_RATE,
13
+ cloudflareOptions
14
+ };
package/dist/cli.js ADDED
@@ -0,0 +1,236 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { spawnSync } from "child_process";
5
+ import { existsSync, readdirSync, statSync, unlinkSync } from "fs";
6
+ import { join, resolve } from "path";
7
+
8
+ // src/env.ts
9
+ var SENTRY_ORG = "domandigital";
10
+ var ENVIRONMENT_VARS = [
11
+ "SENTRY_ENVIRONMENT",
12
+ "PUBLIC_SENTRY_ENVIRONMENT",
13
+ "NEXT_PUBLIC_SENTRY_ENVIRONMENT",
14
+ // Vercel sets these itself, so a Vercel project is right without any setup.
15
+ "VERCEL_ENV",
16
+ "NEXT_PUBLIC_VERCEL_ENV"
17
+ ];
18
+ var RELEASE_VARS = [
19
+ "SENTRY_RELEASE",
20
+ "PUBLIC_SENTRY_RELEASE",
21
+ "NEXT_PUBLIC_SENTRY_RELEASE",
22
+ "CF_PAGES_COMMIT_SHA",
23
+ "WORKERS_CI_COMMIT_SHA",
24
+ "VERCEL_GIT_COMMIT_SHA",
25
+ "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA",
26
+ "GITHUB_SHA"
27
+ ];
28
+ function text(value) {
29
+ if (typeof value !== "string") return void 0;
30
+ const trimmed = value.trim();
31
+ return trimmed === "" ? void 0 : trimmed;
32
+ }
33
+ function firstOf(env, names) {
34
+ if (!env) return void 0;
35
+ for (const name of names) {
36
+ const value = text(env[name]);
37
+ if (value) return { value, from: name };
38
+ }
39
+ return void 0;
40
+ }
41
+ var ALIASES = {
42
+ production: "production",
43
+ prod: "production",
44
+ live: "production",
45
+ staging: "staging",
46
+ stage: "staging",
47
+ stg: "staging",
48
+ preview: "preview"
49
+ };
50
+ var LOCAL = /* @__PURE__ */ new Set(["development", "dev", "local", "test"]);
51
+ function resolveEnvironment(input = {}) {
52
+ const explicit = text(input.environment);
53
+ const found = explicit ? { value: explicit, from: "explicit" } : firstOf(input.env, ENVIRONMENT_VARS);
54
+ if (!found) return { environment: "preview", enabled: true, from: null };
55
+ const key = found.value.toLowerCase();
56
+ if (LOCAL.has(key)) return { environment: "preview", enabled: false, from: found.from };
57
+ return { environment: ALIASES[key] ?? "preview", enabled: true, from: found.from };
58
+ }
59
+ function resolveRelease(input = {}) {
60
+ return text(input.release) ?? firstOf(input.env, RELEASE_VARS)?.value;
61
+ }
62
+
63
+ // src/cli.ts
64
+ var HELP = `dd-sentry-release: upload source maps and record a release in Sentry (org ${SENTRY_ORG})
65
+
66
+ Usage:
67
+ dd-sentry-release upload <dir>... [options] before deploying
68
+ dd-sentry-release finalize [options] after a successful deploy
69
+
70
+ upload Creates the release, injects debug IDs into each <dir>, uploads its
71
+ maps, then deletes every .map file in each <dir> not named by
72
+ --keep-maps.
73
+ finalize Marks the release finished and records a deploy to the environment.
74
+
75
+ Options:
76
+ --release <sha> Default: SENTRY_RELEASE, CF_PAGES_COMMIT_SHA,
77
+ WORKERS_CI_COMMIT_SHA, VERCEL_GIT_COMMIT_SHA, GITHUB_SHA.
78
+ --project <slug> Default: SENTRY_PROJECT.
79
+ --environment <env> finalize: production, staging or preview.
80
+ Default: SENTRY_ENVIRONMENT (or PUBLIC_/NEXT_PUBLIC_).
81
+ --keep-maps <dir> upload: leave this directory's maps in place (a Worker
82
+ bundle wrangler still reads). Repeatable.
83
+ --strict Exit 1 when a Sentry step fails or is skipped.
84
+ --dry-run Print the sentry commands instead of running them.
85
+ Maps are still not deleted.
86
+ -h, --help This text.
87
+
88
+ Needs SENTRY_AUTH_TOKEN (Doppler; an org token). Without it nothing is sent,
89
+ the maps are still deleted, and the build carries on.
90
+ `;
91
+ function parse(argv) {
92
+ const args = { dirs: [], keep: [], strict: false, dryRun: false, help: false };
93
+ const value = (i, flag) => {
94
+ const v = argv[i + 1];
95
+ if (v === void 0 || v.startsWith("--")) throw new Error(`${flag} needs a value`);
96
+ return v;
97
+ };
98
+ for (let i = 0; i < argv.length; i++) {
99
+ const a = argv[i];
100
+ if (a === "-h" || a === "--help") args.help = true;
101
+ else if (a === "--strict") args.strict = true;
102
+ else if (a === "--dry-run") args.dryRun = true;
103
+ else if (a === "--release") args.release = value(i++, a);
104
+ else if (a === "--project") args.project = value(i++, a);
105
+ else if (a === "--environment") args.environment = value(i++, a);
106
+ else if (a === "--keep-maps") args.keep.push(value(i++, a));
107
+ else if (a.startsWith("-")) throw new Error(`unknown option ${a}`);
108
+ else if (!args.command) args.command = a;
109
+ else args.dirs.push(a);
110
+ }
111
+ return args;
112
+ }
113
+ var log = (msg) => console.log(`[dd-sentry-release] ${msg}`);
114
+ var warn = (msg) => console.warn(`[dd-sentry-release] ${msg}`);
115
+ function maps(dir) {
116
+ const out = [];
117
+ for (const name of readdirSync(dir)) {
118
+ const path = join(dir, name);
119
+ if (statSync(path).isDirectory()) out.push(...maps(path));
120
+ else if (name.endsWith(".map")) out.push(path);
121
+ }
122
+ return out;
123
+ }
124
+ function main(argv) {
125
+ let args;
126
+ try {
127
+ args = parse(argv);
128
+ } catch (err) {
129
+ console.error(`dd-sentry-release: ${err.message}
130
+
131
+ ${HELP}`);
132
+ return 2;
133
+ }
134
+ if (args.help || !args.command) {
135
+ console.log(HELP);
136
+ return args.help ? 0 : 2;
137
+ }
138
+ if (args.command !== "upload" && args.command !== "finalize") {
139
+ console.error(`dd-sentry-release: unknown command ${args.command}
140
+
141
+ ${HELP}`);
142
+ return 2;
143
+ }
144
+ const env = process.env;
145
+ const release = resolveRelease({ release: args.release, env });
146
+ const project = args.project ?? env.SENTRY_PROJECT;
147
+ const token = env.SENTRY_AUTH_TOKEN?.trim();
148
+ let failed = false;
149
+ if (env.SENTRY_ORG && env.SENTRY_ORG !== SENTRY_ORG) warn(`SENTRY_ORG is ${env.SENTRY_ORG}; using ${SENTRY_ORG}, the only org.`);
150
+ const childEnv = { ...env, SENTRY_ORG, ...project ? { SENTRY_PROJECT: project } : {} };
151
+ const sentry = (...cmd) => {
152
+ if (args.dryRun) {
153
+ log(`would run: sentry ${cmd.join(" ")}`);
154
+ return true;
155
+ }
156
+ log(`sentry ${cmd.join(" ")}`);
157
+ const r = spawnSync("sentry", cmd, { env: childEnv, stdio: "inherit" });
158
+ if (r.error && r.error.code === "ENOENT") {
159
+ warn("the `sentry` CLI is not installed. Add it to the site: pnpm add -D sentry");
160
+ failed = true;
161
+ return false;
162
+ }
163
+ if (r.status !== 0) {
164
+ warn(`sentry ${cmd[0]} ${cmd[1] ?? ""} failed (exit ${r.status ?? r.signal}); carrying on.`);
165
+ failed = true;
166
+ return false;
167
+ }
168
+ return true;
169
+ };
170
+ const ready = (() => {
171
+ if (!token && !args.dryRun) return "SENTRY_AUTH_TOKEN is not set";
172
+ if (!project) return "no project: set SENTRY_PROJECT or pass --project";
173
+ return null;
174
+ })();
175
+ if (ready) {
176
+ warn(`${ready}; nothing sent to Sentry.`);
177
+ failed = true;
178
+ }
179
+ if (args.command === "upload") {
180
+ if (args.dirs.length === 0) {
181
+ console.error("dd-sentry-release upload: name at least one build directory.");
182
+ return 2;
183
+ }
184
+ const missing = args.dirs.filter((d) => !existsSync(d));
185
+ if (missing.length) {
186
+ console.error(`dd-sentry-release upload: no such directory: ${missing.join(", ")}`);
187
+ return 2;
188
+ }
189
+ if (!ready) {
190
+ if (release) sentry("release", "create", `${SENTRY_ORG}/${release}`, "--project", project);
191
+ else warn("no release SHA found; maps go up matched by debug ID only, with no release to finalize.");
192
+ for (const dir of args.dirs) {
193
+ if (sentry("sourcemap", "inject", dir)) {
194
+ sentry("sourcemap", "upload", dir, ...release ? ["--release", release] : []);
195
+ }
196
+ }
197
+ }
198
+ const keep = new Set(args.keep.map((d) => resolve(d)));
199
+ for (const dir of args.dirs) {
200
+ if (keep.has(resolve(dir))) {
201
+ log(`kept the maps in ${dir}`);
202
+ continue;
203
+ }
204
+ const found = maps(dir);
205
+ if (args.dryRun) {
206
+ log(`would delete ${found.length} map(s) in ${dir}`);
207
+ continue;
208
+ }
209
+ try {
210
+ for (const file of found) unlinkSync(file);
211
+ log(`deleted ${found.length} map(s) in ${dir}`);
212
+ } catch (err) {
213
+ console.error(`dd-sentry-release: could not delete the maps in ${dir}: ${err.message}`);
214
+ return 1;
215
+ }
216
+ }
217
+ } else {
218
+ const { environment, enabled, from } = resolveEnvironment({ environment: args.environment, env });
219
+ if (!ready && !release) {
220
+ warn("no release SHA found; nothing to finalize.");
221
+ failed = true;
222
+ } else if (!ready && release) {
223
+ sentry("release", "finalize", `${SENTRY_ORG}/${release}`);
224
+ if (!from) {
225
+ warn("no environment set (SENTRY_ENVIRONMENT or --environment); no deploy recorded rather than a guessed one.");
226
+ failed = true;
227
+ } else if (!enabled) {
228
+ log(`environment ${args.environment ?? "from " + from} is local; no deploy recorded.`);
229
+ } else {
230
+ sentry("release", "deploy", `${SENTRY_ORG}/${release}`, environment);
231
+ }
232
+ }
233
+ }
234
+ return failed && args.strict ? 1 : 0;
235
+ }
236
+ process.exitCode = main(process.argv.slice(2));