UNPKG

8.92 kBJavaScriptView Raw
1Object.defineProperty(exports, "__esModule", { value: true });
2var tslib_1 = require("tslib");
3var core_1 = require("@sentry/core");
4var hub_1 = require("@sentry/hub");
5var types_1 = require("@sentry/types");
6var utils_1 = require("@sentry/utils");
7var domain = require("domain");
8var client_1 = require("./client");
9var integrations_1 = require("./integrations");
10exports.defaultIntegrations = [
11 // Common
12 new core_1.Integrations.InboundFilters(),
13 new core_1.Integrations.FunctionToString(),
14 // Native Wrappers
15 new integrations_1.Console(),
16 new integrations_1.Http(),
17 // Global Handlers
18 new integrations_1.OnUncaughtException(),
19 new integrations_1.OnUnhandledRejection(),
20 // Misc
21 new integrations_1.LinkedErrors(),
22];
23/**
24 * The Sentry Node SDK Client.
25 *
26 * To use this SDK, call the {@link init} function as early as possible in the
27 * main entry module. To set context information or send manual events, use the
28 * provided methods.
29 *
30 * @example
31 * ```
32 *
33 * const { init } = require('@sentry/node');
34 *
35 * init({
36 * dsn: '__DSN__',
37 * // ...
38 * });
39 * ```
40 *
41 * @example
42 * ```
43 *
44 * const { configureScope } = require('@sentry/node');
45 * configureScope((scope: Scope) => {
46 * scope.setExtra({ battery: 0.7 });
47 * scope.setTag({ user_mode: 'admin' });
48 * scope.setUser({ id: '4711' });
49 * });
50 * ```
51 *
52 * @example
53 * ```
54 *
55 * const { addBreadcrumb } = require('@sentry/node');
56 * addBreadcrumb({
57 * message: 'My Breadcrumb',
58 * // ...
59 * });
60 * ```
61 *
62 * @example
63 * ```
64 *
65 * const Sentry = require('@sentry/node');
66 * Sentry.captureMessage('Hello, world!');
67 * Sentry.captureException(new Error('Good bye'));
68 * Sentry.captureEvent({
69 * message: 'Manual',
70 * stacktrace: [
71 * // ...
72 * ],
73 * });
74 * ```
75 *
76 * @see {@link NodeOptions} for documentation on configuration options.
77 */
78function init(options) {
79 if (options === void 0) { options = {}; }
80 var _a;
81 var carrier = hub_1.getMainCarrier();
82 var autoloadedIntegrations = ((_a = carrier.__SENTRY__) === null || _a === void 0 ? void 0 : _a.integrations) || [];
83 options.defaultIntegrations =
84 options.defaultIntegrations === false
85 ? []
86 : tslib_1.__spread((Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : exports.defaultIntegrations), autoloadedIntegrations);
87 if (options.dsn === undefined && process.env.SENTRY_DSN) {
88 options.dsn = process.env.SENTRY_DSN;
89 }
90 if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) {
91 var tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE);
92 if (isFinite(tracesSampleRate)) {
93 options.tracesSampleRate = tracesSampleRate;
94 }
95 }
96 if (options.release === undefined) {
97 var detectedRelease = getSentryRelease();
98 if (detectedRelease !== undefined) {
99 options.release = detectedRelease;
100 }
101 else {
102 // If release is not provided, then we should disable autoSessionTracking
103 options.autoSessionTracking = false;
104 }
105 }
106 if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) {
107 options.environment = process.env.SENTRY_ENVIRONMENT;
108 }
109 if (options.autoSessionTracking === undefined) {
110 options.autoSessionTracking = true;
111 }
112 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
113 if (domain.active) {
114 hub_1.setHubOnCarrier(carrier, core_1.getCurrentHub());
115 }
116 core_1.initAndBind(client_1.NodeClient, options);
117 if (options.autoSessionTracking) {
118 startSessionTracking();
119 }
120}
121exports.init = init;
122/**
123 * This is the getter for lastEventId.
124 *
125 * @returns The last event id of a captured event.
126 */
127function lastEventId() {
128 return core_1.getCurrentHub().lastEventId();
129}
130exports.lastEventId = lastEventId;
131/**
132 * Call `flush()` on the current client, if there is one. See {@link Client.flush}.
133 *
134 * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause
135 * the client to wait until all events are sent before resolving the promise.
136 * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
137 * doesn't (or if there's no client defined).
138 */
139function flush(timeout) {
140 return tslib_1.__awaiter(this, void 0, void 0, function () {
141 var client;
142 return tslib_1.__generator(this, function (_a) {
143 client = core_1.getCurrentHub().getClient();
144 if (client) {
145 return [2 /*return*/, client.flush(timeout)];
146 }
147 utils_1.logger.warn('Cannot flush events. No client defined.');
148 return [2 /*return*/, Promise.resolve(false)];
149 });
150 });
151}
152exports.flush = flush;
153/**
154 * Call `close()` on the current client, if there is one. See {@link Client.close}.
155 *
156 * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this
157 * parameter will cause the client to wait until all events are sent before disabling itself.
158 * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
159 * doesn't (or if there's no client defined).
160 */
161function close(timeout) {
162 return tslib_1.__awaiter(this, void 0, void 0, function () {
163 var client;
164 return tslib_1.__generator(this, function (_a) {
165 client = core_1.getCurrentHub().getClient();
166 if (client) {
167 return [2 /*return*/, client.close(timeout)];
168 }
169 utils_1.logger.warn('Cannot flush events and disable SDK. No client defined.');
170 return [2 /*return*/, Promise.resolve(false)];
171 });
172 });
173}
174exports.close = close;
175/**
176 * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client
177 */
178function isAutoSessionTrackingEnabled(client) {
179 if (client === undefined) {
180 return false;
181 }
182 var clientOptions = client && client.getOptions();
183 if (clientOptions && clientOptions.autoSessionTracking !== undefined) {
184 return clientOptions.autoSessionTracking;
185 }
186 return false;
187}
188exports.isAutoSessionTrackingEnabled = isAutoSessionTrackingEnabled;
189/**
190 * Returns a release dynamically from environment variables.
191 */
192function getSentryRelease(fallback) {
193 // Always read first as Sentry takes this as precedence
194 if (process.env.SENTRY_RELEASE) {
195 return process.env.SENTRY_RELEASE;
196 }
197 // This supports the variable that sentry-webpack-plugin injects
198 var global = utils_1.getGlobalObject();
199 if (global.SENTRY_RELEASE && global.SENTRY_RELEASE.id) {
200 return global.SENTRY_RELEASE.id;
201 }
202 return (
203 // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
204 process.env.GITHUB_SHA ||
205 // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata
206 process.env.COMMIT_REF ||
207 // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables
208 process.env.VERCEL_GIT_COMMIT_SHA ||
209 process.env.VERCEL_GITHUB_COMMIT_SHA ||
210 process.env.VERCEL_GITLAB_COMMIT_SHA ||
211 process.env.VERCEL_BITBUCKET_COMMIT_SHA ||
212 // Zeit (now known as Vercel)
213 process.env.ZEIT_GITHUB_COMMIT_SHA ||
214 process.env.ZEIT_GITLAB_COMMIT_SHA ||
215 process.env.ZEIT_BITBUCKET_COMMIT_SHA ||
216 fallback);
217}
218exports.getSentryRelease = getSentryRelease;
219/**
220 * Enable automatic Session Tracking for the node process.
221 */
222function startSessionTracking() {
223 var hub = core_1.getCurrentHub();
224 hub.startSession();
225 // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because
226 // The 'beforeExit' event is not emitted for conditions causing explicit termination,
227 // such as calling process.exit() or uncaught exceptions.
228 // Ref: https://nodejs.org/api/process.html#process_event_beforeexit
229 process.on('beforeExit', function () {
230 var _a;
231 var session = (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.getSession();
232 var terminalStates = [types_1.SessionStatus.Exited, types_1.SessionStatus.Crashed];
233 // Only call endSession, if the Session exists on Scope and SessionStatus is not a
234 // Terminal Status i.e. Exited or Crashed because
235 // "When a session is moved away from ok it must not be updated anymore."
236 // Ref: https://develop.sentry.dev/sdk/sessions/
237 if (session && !terminalStates.includes(session.status))
238 hub.endSession();
239 });
240}
241//# sourceMappingURL=sdk.js.map
\No newline at end of file