-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathindex.ts
More file actions
487 lines (429 loc) · 17.6 KB
/
Copy pathindex.ts
File metadata and controls
487 lines (429 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import { createUnplugin } from "unplugin";
import MagicString from "magic-string";
import { Options, BuildContext } from "./types";
import {
createNewRelease,
cleanArtifacts,
addDeploy,
finalizeRelease,
setCommits,
uploadSourceMaps,
uploadDebugIdSourcemaps,
} from "./sentry/releasePipeline";
import "@sentry/tracing";
import SentryCli from "@sentry/cli";
import {
addPluginOptionInformationToHub,
addSpanToTransaction,
makeSentryClient,
shouldSendTelemetry,
} from "./sentry/telemetry";
import { Span, Transaction } from "@sentry/types";
import { createLogger, Logger } from "./sentry/logger";
import { InternalOptions, normalizeUserOptions, validateOptions } from "./options-mapping";
import { getSentryCli } from "./sentry/cli";
import { makeMain } from "@sentry/node";
import os from "os";
import path from "path";
import fs from "fs";
import util from "util";
import { getDependencies, getPackageJson, parseMajorVersion } from "./utils";
import { glob } from "glob";
import { injectDebugIdSnippetIntoChunk, prepareBundleForDebugIdUpload } from "./debug-id";
const ALLOWED_TRANSFORMATION_FILE_ENDINGS = [".js", ".ts", ".jsx", ".tsx", ".mjs"];
const releaseInjectionFilePath = require.resolve(
"@sentry/bundler-plugin-core/sentry-release-injection-file"
);
/**
* The sentry bundler plugin concerns itself with two things:
* - Release injection
* - Sourcemaps upload
*
* Release injection:
* Per default the sentry bundler plugin will inject a global `SENTRY_RELEASE` into each JavaScript/TypeScript module
* that is part of the bundle. On a technical level this is done by appending an import (`import "sentry-release-injector;"`)
* to all entrypoint files of the user code (see `transformInclude` and `transform` hooks). This import is then resolved
* by the sentry plugin to a virtual module that sets the global variable (see `resolveId` and `load` hooks).
* If a user wants to inject the release into a particular set of modules they can use the `releaseInjectionTargets` option.
*
* Source maps upload:
*
* The sentry bundler plugin will also take care of uploading source maps to Sentry. This
* is all done in the `writeBundle` hook. In this hook the sentry plugin will execute the
* release creation pipeline:
*
* 1. Create a new release
* 2. Delete already uploaded artifacts for this release (if `cleanArtifacts` is enabled)
* 3. Upload sourcemaps based on `include` and source-map-specific options
* 4. Associate a range of commits with the release (if `setCommits` is specified)
* 5. Finalize the release (unless `finalize` is disabled)
* 6. Add deploy information to the release (if `deploy` is specified)
*
* This release creation pipeline relies on Sentry CLI to execute the different steps.
*/
const unplugin = createUnplugin<Options>((options, unpluginMetaContext) => {
const internalOptions = normalizeUserOptions(options);
const allowedToSendTelemetryPromise = shouldSendTelemetry(internalOptions);
const { sentryHub, sentryClient } = makeSentryClient(
"https://4c2bae7d9fbc413e8f7385f55c515d51@o1.ingest.sentry.io/6690737",
allowedToSendTelemetryPromise,
internalOptions.project
);
addPluginOptionInformationToHub(internalOptions, sentryHub, unpluginMetaContext.framework);
//TODO: This call is problematic because as soon as we set our hub as the current hub
// we might interfere with other plugins that use Sentry. However, for now, we'll
// leave it in because without it, we can't get distributed traces (which are pretty nice)
// Let's keep it until someone complains about interference.
// The ideal solution would be a code change in the JS SDK but it's not a straight-forward fix.
makeMain(sentryHub);
const logger = createLogger({
prefix: `[sentry-${unpluginMetaContext.framework}-plugin]`,
silent: internalOptions.silent,
debug: internalOptions.debug,
});
if (!validateOptions(internalOptions, logger)) {
handleError(
new Error("Options were not set correctly. See output above for more details."),
logger,
internalOptions.errorHandler
);
}
const cli = getSentryCli(internalOptions, logger);
const releaseNamePromise = new Promise<string>((resolve) => {
if (options.release) {
resolve(options.release);
} else {
resolve(cli.releases.proposeVersion());
}
});
let transaction: Transaction | undefined;
let releaseInjectionSpan: Span | undefined;
return {
name: "sentry-plugin",
enforce: "pre", // needed for Vite to call resolveId hook
/**
* Responsible for starting the plugin execution transaction and the release injection span
*/
async buildStart() {
logger.debug("Called 'buildStart'");
const isAllowedToSendToSendTelemetry = await allowedToSendTelemetryPromise;
if (isAllowedToSendToSendTelemetry) {
logger.info("Sending error and performance telemetry data to Sentry.");
logger.info("To disable telemetry, set `options.telemetry` to `false`.");
sentryHub.addBreadcrumb({ level: "info", message: "Telemetry enabled." });
} else {
sentryHub.addBreadcrumb({
level: "info",
message: "Telemetry disabled. This should never show up in a Sentry event.",
});
}
const releaseName = await releaseNamePromise;
// At this point, we either have determined a release or we have to bail
if (!releaseName) {
handleError(
new Error(
"Unable to determine a release name. Make sure to set the `release` option or use an environment that supports auto-detection https://docs.sentry.io/cli/releases/#creating-releases`"
),
logger,
internalOptions.errorHandler
);
}
transaction = sentryHub.startTransaction({
op: "function.plugin",
name: "Sentry Bundler Plugin execution",
});
releaseInjectionSpan = addSpanToTransaction(
{ hub: sentryHub, parentSpan: transaction, logger, cli },
"function.plugin.inject_release",
"Release injection"
);
},
/**
* Responsible for returning the "sentry-release-injector" ID when we encounter it. We return the ID so load is
* called and we can "virtually" load the module. See `load` hook for more info on why it's virtual.
*
* We also record the id (i.e. absolute path) of any non-entrypoint.
*
* @param id For imports: The absolute path of the module to be imported. For entrypoints: The path the user defined as entrypoint - may also be relative.
* @param importer For imports: The absolute path of the module that imported this module. For entrypoints: `undefined`.
* @param options Additional information to use for making a resolving decision.
* @returns `"sentry-release-injector"` when the imported file is called `"sentry-release-injector"`. Otherwise returns `undefined`.
*/
resolveId(id, importer, { isEntry }) {
logger.debug('Called "resolveId":', { id, importer, isEntry });
return undefined;
},
/**
* This hook determines whether we want to transform a module. In the sentry bundler plugin we want to transform every entrypoint
* unless configured otherwise with the `releaseInjectionTargets` option.
*
* @param id Always the absolute (fully resolved) path to the module.
* @returns `true` or `false` depending on whether we want to transform the module. For the sentry bundler plugin we only
* want to transform the release injector file.
*/
transformInclude(id) {
logger.debug('Called "transformInclude":', { id });
// We normalize the id because vite always passes `id` as a unix style path which causes problems when a user passes
// a windows style path to `releaseInjectionTargets`
const normalizedId = path.normalize(id);
if (id.includes("sentry-release-injection-file")) {
return true;
}
if (internalOptions.releaseInjectionTargets) {
// If there's an `releaseInjectionTargets` option transform (ie. inject the release varible) when the file path matches the option.
if (typeof internalOptions.releaseInjectionTargets === "function") {
return internalOptions.releaseInjectionTargets(normalizedId);
}
return internalOptions.releaseInjectionTargets.some((entry) => {
if (entry instanceof RegExp) {
return entry.test(normalizedId);
} else {
const normalizedEntry = path.normalize(entry);
return normalizedId === normalizedEntry;
}
});
} else {
const pathIsOrdinary = !normalizedId.includes("?") && !normalizedId.includes("#");
const pathHasAllowedFileEnding = ALLOWED_TRANSFORMATION_FILE_ENDINGS.some(
(allowedFileEnding) => normalizedId.endsWith(allowedFileEnding)
);
return pathIsOrdinary && pathHasAllowedFileEnding;
}
},
/**
* This hook is responsible for injecting the "sentry release injector" imoprt statement into each entrypoint unless
* configured otherwise with the `releaseInjectionTargets` option (logic for that is in the `transformInclude` hook).
*
* @param code Code of the file to transform.
* @param id Always the absolute (fully resolved) path to the module.
* @returns transformed code + source map
*/
async transform(code, id) {
logger.debug('Called "transform":', { id });
if (!internalOptions.injectRelease) {
return;
}
// The MagicString library allows us to generate sourcemaps for the changes we make to the user code.
const ms = new MagicString(code);
if (code.includes("_sentry_release_injection_file")) {
// Appending instead of prepending has less probability of mucking with user's source maps.
ms.append(
generateGlobalInjectorCode({
release: await releaseNamePromise,
injectReleasesMap: internalOptions.injectReleasesMap,
injectBuildInformation: internalOptions._experiments.injectBuildInformation || false,
org: internalOptions.org,
project: internalOptions.project,
})
);
} else {
// Appending instead of prepending has less probability of mucking with user's source maps.
// Luckily import statements get hoisted to the top anyways.
// The import needs to be an absolute path because Rollup doesn't bundle stuff in `node_modules` by default when bundling CJS (unless the import path is absolute or the node-resolve-plugin is used).
ms.append(`;\nimport "${releaseInjectionFilePath.replace(/\\/g, "\\\\")}";`);
}
if (unpluginMetaContext.framework === "esbuild") {
// esbuild + unplugin is buggy at the moment when we return an object with a `map` (sourcemap) property.
// Currently just returning a string here seems to work and even correctly sourcemaps the code we generate.
// However, other bundlers need the `map` property
return ms.toString();
} else {
return {
code: ms.toString(),
map: ms.generateMap(),
};
}
},
/**
* Responsible for executing the sentry release creation pipeline (i.e. creating a release on
* Sentry.io, uploading sourcemaps, associating commits and deploys and finalizing the release)
*/
async writeBundle() {
logger.debug('Called "writeBundle"');
releaseInjectionSpan?.finish();
const releasePipelineSpan =
transaction &&
addSpanToTransaction(
{ hub: sentryHub, parentSpan: transaction, logger, cli },
"function.plugin.release",
"Release pipeline"
);
sentryHub.addBreadcrumb({
category: "writeBundle:start",
level: "info",
});
const ctx: BuildContext = { hub: sentryHub, parentSpan: releasePipelineSpan, logger, cli };
const releaseName = await releaseNamePromise;
let tmpUploadFolder: string | undefined;
try {
if (internalOptions._experiments.debugIdUpload) {
const debugIdChunkFilePaths = (
await glob(internalOptions._experiments.debugIdUpload.include, {
absolute: true,
nodir: true,
ignore: internalOptions._experiments.debugIdUpload.ignore,
})
).filter((p) => p.endsWith(".js") || p.endsWith(".mjs"));
const sourceFileUploadFolderPromise = util.promisify(fs.mkdtemp)(
path.join(os.tmpdir(), "sentry-bundler-plugin-upload-")
);
await Promise.all(
debugIdChunkFilePaths.map(async (chunkFilePath, chunkIndex): Promise<void> => {
await prepareBundleForDebugIdUpload(
chunkFilePath,
await sourceFileUploadFolderPromise,
String(chunkIndex),
logger
);
})
);
tmpUploadFolder = await sourceFileUploadFolderPromise;
await uploadDebugIdSourcemaps(internalOptions, ctx, tmpUploadFolder, releaseName);
}
await createNewRelease(internalOptions, ctx, releaseName);
await cleanArtifacts(internalOptions, ctx, releaseName);
await uploadSourceMaps(internalOptions, ctx, releaseName);
await setCommits(internalOptions, ctx, releaseName);
await finalizeRelease(internalOptions, ctx, releaseName);
await addDeploy(internalOptions, ctx, releaseName);
transaction?.setStatus("ok");
} catch (e: unknown) {
transaction?.setStatus("cancelled");
sentryHub.addBreadcrumb({
level: "error",
message: "Error during writeBundle",
});
handleError(e, logger, internalOptions.errorHandler);
} finally {
if (tmpUploadFolder) {
fs.rm(tmpUploadFolder, { recursive: true, force: true }, () => {
// We don't care if this errors
});
}
releasePipelineSpan?.finish();
transaction?.finish();
await sentryClient.flush().then(null, () => {
logger.warn("Sending of telemetry failed");
});
}
sentryHub.addBreadcrumb({
category: "writeBundle:finish",
level: "info",
});
},
rollup: {
renderChunk(code, chunk) {
if (
options._experiments?.debugIdUpload &&
[".js", ".mjs"].some((ending) => chunk.fileName.endsWith(ending))
) {
return injectDebugIdSnippetIntoChunk(code);
} else {
return null;
}
},
},
vite: {
renderChunk(code, chunk) {
if (
options._experiments?.debugIdUpload &&
[".js", ".mjs"].some((ending) => chunk.fileName.endsWith(ending))
) {
return injectDebugIdSnippetIntoChunk(code);
} else {
return null;
}
},
},
};
});
function handleError(
unknownError: unknown,
logger: Logger,
errorHandler: InternalOptions["errorHandler"]
) {
if (unknownError instanceof Error) {
logger.error(unknownError.message);
} else {
logger.error(String(unknownError));
}
if (errorHandler) {
if (unknownError instanceof Error) {
errorHandler(unknownError);
} else {
errorHandler(new Error("An unknown error occured"));
}
} else {
throw unknownError;
}
}
/**
* Generates code for the global injector which is responsible for setting the global
* `SENTRY_RELEASE` & `SENTRY_BUILD_INFO` variables.
*/
function generateGlobalInjectorCode({
release,
injectReleasesMap,
injectBuildInformation,
org,
project,
}: {
release: string;
injectReleasesMap: boolean;
injectBuildInformation: boolean;
org?: string;
project?: string;
}) {
// The code below is mostly ternary operators because it saves bundle size.
// The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
let code = `
var _global =
typeof window !== 'undefined' ?
window :
typeof global !== 'undefined' ?
global :
typeof self !== 'undefined' ?
self :
{};
_global.SENTRY_RELEASE={id:"${release}"};`;
if (injectReleasesMap && project) {
const key = org ? `${project}@${org}` : project;
code += `
_global.SENTRY_RELEASES=_global.SENTRY_RELEASES || {};
_global.SENTRY_RELEASES["${key}"]={id:"${release}"};`;
}
if (injectBuildInformation) {
const buildInfo = getBuildInformation();
code += `
_global.SENTRY_BUILD_INFO=${JSON.stringify(buildInfo)};`;
}
return code;
}
export function getBuildInformation() {
const packageJson = getPackageJson();
const { deps, depsVersions } = packageJson
? getDependencies(packageJson)
: { deps: [], depsVersions: {} };
return {
deps,
depsVersions,
nodeVersion: parseMajorVersion(process.version),
};
}
/**
* Determines whether the Sentry CLI binary is in its expected location.
* This function is useful since `@sentry/cli` installs the binary via a post-install
* script and post-install scripts may not always run. E.g. with `npm i --ignore-scripts`.
*/
export function sentryCliBinaryExists(): boolean {
return fs.existsSync(SentryCli.getPath());
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const sentryVitePlugin: (options: Options) => any = unplugin.vite;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const sentryRollupPlugin: (options: Options) => any = unplugin.rollup;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const sentryWebpackPlugin: (options: Options) => any = unplugin.webpack;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const sentryEsbuildPlugin: (options: Options) => any = unplugin.esbuild;
export type { Options } from "./types";