diff --git a/.cursor/BUGBOT.md b/.cursor/BUGBOT.md index afbd17c05ff9..4f0a55cbe326 100644 --- a/.cursor/BUGBOT.md +++ b/.cursor/BUGBOT.md @@ -16,6 +16,7 @@ Keep reviews high-signal. Prefer actionable, high-confidence findings over specu - Exposed **real** secrets, API keys, tokens, or credentials in production code, comments, logs, or committed configs. Do **not** flag test fixtures, unit/integration/E2E helpers, or docs/examples that use obviously fake / placeholder DSNs and credentials (bogus DSNs in tests are expected). - Unsafe use of `eval()`, `Function()`, or `innerHTML` - Unsafe regular expressions that could cause ReDoS attacks +- `JSON.stringify` output that goes into generated code (bundler plugins, loaders, virtual modules, `define` values). Use `stringifyForCodeInjection` from `@sentry/core` instead. It escapes `<`, `>`, U+2028 and U+2029, so the code stays safe when inlined in a `` or ` after a comment', + 'quotes "\' and backslashes \\u003c with whitespace \n\r\t\u2028\u2029 and <>&', + ])('keeps %j inside one script element, with the same value', value => { + const input = { [value]: [value, { nested: value }] }; + const code = `globalThis.result = ${stringifyForCodeInjection(input)};`; + + const dom = new JSDOM(``); + const scripts = dom.window.document.querySelectorAll('script'); + dom.window.close(); + + expect(scripts).toHaveLength(1); + expect(scripts[0]?.textContent).toBe(code); + + const context: { result?: unknown } = {}; + runInNewContext(code, context); + expect(context.result).toEqual(input); + }); + + it('escapes the unsafe characters', () => { + expect(stringifyForCodeInjection('<>\u2028\u2029')).toBe('"\\u003c\\u003e\\u2028\\u2029"'); + }); + + it('gives the same result as JSON.stringify for other values', () => { + const value = { a: [1, 'two', null, true], b: { c: 'd/e\\f' } }; + expect(stringifyForCodeInjection(value)).toBe(JSON.stringify(value)); + expect(stringifyForCodeInjection(value, null, 2)).toBe(JSON.stringify(value, null, 2)); + expect(stringifyForCodeInjection(value, ['a'])).toBe(JSON.stringify(value, ['a'])); + expect(stringifyForCodeInjection(value, (_key, v) => (v === 'two' ? 2 : v))).toBe( + JSON.stringify(value, (_key, v) => (v === 'two' ? 2 : v)), + ); + }); + + it('returns undefined where JSON.stringify does', () => { + expect(stringifyForCodeInjection(undefined)).toBeUndefined(); + expect(stringifyForCodeInjection(() => undefined)).toBeUndefined(); + }); +}); diff --git a/packages/core/test/lib/tracing/sentrySpan.test.ts b/packages/core/test/lib/tracing/sentrySpan.test.ts index 5bf6e14c05c3..989c5820bea9 100644 --- a/packages/core/test/lib/tracing/sentrySpan.test.ts +++ b/packages/core/test/lib/tracing/sentrySpan.test.ts @@ -702,13 +702,14 @@ describe('SentrySpan', () => { describe('end', () => { it('works without endTimestamp', () => { + vi.useFakeTimers(); const span = new SentrySpan(); - const now = timestampInSeconds(); + vi.advanceTimersByTime(500); span.end(); + vi.useRealTimers(); const { start_timestamp, end_timestamp } = spanToJSON(span); - expect(end_timestamp).toBeGreaterThanOrEqual(start_timestamp); - expect(end_timestamp).toBeCloseTo(now, 2); + expect(end_timestamp).toBe(start_timestamp + 0.5); }); it('works with endTimestamp in seconds', () => { @@ -763,20 +764,26 @@ describe('SentrySpan', () => { }); it('uses the current time as end if the span was started with a start time', () => { - const startTimestamp = timestampInSeconds() - 10; - const span = new SentrySpan({ startTimestamp }); + const before = timestampInSeconds(); + const span = new SentrySpan({ startTimestamp: before - 10 }); span.end(); + const after = timestampInSeconds(); - expect(spanToStaticSpanJSON(span).timestamp! - startTimestamp).toBeCloseTo(10, 1); + const endTimestamp = spanToStaticSpanJSON(span).timestamp; + expect(endTimestamp).toBeGreaterThanOrEqual(before); + expect(endTimestamp).toBeLessThanOrEqual(after); }); it('uses the current time as end if the start time was updated', () => { const span = new SentrySpan(); - const startTimestamp = timestampInSeconds() - 10; - span.updateStartTime(startTimestamp); + const before = timestampInSeconds(); + span.updateStartTime(before - 10); span.end(); + const after = timestampInSeconds(); - expect(spanToStaticSpanJSON(span).timestamp! - startTimestamp).toBeCloseTo(10, 1); + const endTimestamp = spanToStaticSpanJSON(span).timestamp; + expect(endTimestamp).toBeGreaterThanOrEqual(before); + expect(endTimestamp).toBeLessThanOrEqual(after); }); it('skips if span is already ended', () => { diff --git a/packages/core/test/lib/utils/ratelimit.test.ts b/packages/core/test/lib/utils/ratelimit.test.ts index 772bd5e5c9d4..6897b3983d01 100644 --- a/packages/core/test/lib/utils/ratelimit.test.ts +++ b/packages/core/test/lib/utils/ratelimit.test.ts @@ -110,15 +110,29 @@ describe('updateRateLimits()', () => { expect(updatedRateLimits.transaction).toEqual(15 * 1000); }); - test('should use last entry from multi `x-sentry-rate-limits` header for a given category', () => { + test('should use longest entry from multi `x-sentry-rate-limits` header for a given category', () => { const rateLimits: RateLimits = {}; const headers = { 'retry-after': null, - 'x-sentry-rate-limits': '13:error,15:transaction;error', + 'x-sentry-rate-limits': '15:error,22:error,13:transaction;error', }; const updatedRateLimits = updateRateLimits(rateLimits, { headers }, 0); - expect(updatedRateLimits.error).toEqual(15 * 1000); - expect(updatedRateLimits.transaction).toEqual(15 * 1000); + expect(updatedRateLimits.error).toEqual(22 * 1000); + expect(updatedRateLimits.transaction).toEqual(13 * 1000); + }); + + test('should keep a stored limit when a new one is shorter, and replace it when a new one is longer', () => { + const rateLimits: RateLimits = { error: 15 * 1000 }; + const shorterHeaders = { + 'retry-after': null, + 'x-sentry-rate-limits': '13:error', + }; + const longerHeaders = { + 'retry-after': null, + 'x-sentry-rate-limits': '20:error', + }; + expect(updateRateLimits(rateLimits, { headers: shorterHeaders }, 0).error).toEqual(15 * 1000); + expect(updateRateLimits(rateLimits, { headers: longerHeaders }, 0).error).toEqual(20 * 1000); }); test('should fallback to `all` if `x-sentry-rate-limits` header is missing a category', () => { diff --git a/packages/deno/test/deno-serve.test.ts b/packages/deno/test/deno-serve.test.ts index e7749f3c39fb..8c2561cd4117 100644 --- a/packages/deno/test/deno-serve.test.ts +++ b/packages/deno/test/deno-serve.test.ts @@ -24,7 +24,7 @@ Deno.test('Deno.serve should create http.server spans', async () => { resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -47,6 +47,7 @@ Deno.test('Deno.serve should create http.server spans', async () => { abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); const [transaction] = transactionEvents; @@ -62,7 +63,7 @@ Deno.test('Deno.serve should instrument QUERY requests with bodies', async () => resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -91,6 +92,7 @@ Deno.test('Deno.serve should instrument QUERY requests with bodies', async () => abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); const [transaction] = transactionEvents; @@ -104,7 +106,7 @@ Deno.test('Deno.serve should capture incoming request bodies by default', async resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -133,6 +135,7 @@ Deno.test('Deno.serve should capture incoming request bodies by default', async abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); assertEquals(transactionEvents[0]?.request?.data, requestBody); @@ -142,7 +145,7 @@ Deno.test('Deno.serve should not capture incoming request bodies when disabled', resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -171,6 +174,7 @@ Deno.test('Deno.serve should not capture incoming request bodies when disabled', abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); assertEquals(transactionEvents[0]?.request?.data, undefined); @@ -180,7 +184,7 @@ Deno.test('Deno.serve should truncate incoming request bodies using an explicit resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -214,6 +218,7 @@ Deno.test('Deno.serve should truncate incoming request bodies using an explicit abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); assertEquals(transactionEvents[0]?.request?.data, `${'a'.repeat(997)}...`); @@ -223,7 +228,7 @@ Deno.test('Deno.serve should honor explicit none when incoming request bodies ar resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -256,6 +261,7 @@ Deno.test('Deno.serve should honor explicit none when incoming request bodies ar abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); assertEquals(transactionEvents[0]?.request?.data, undefined); @@ -266,7 +272,7 @@ Deno.test('Deno.serve should isolate context between concurrent requests', async const transactionEvents: TransactionEvent[] = []; const errorEvents: ErrorEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -314,6 +320,7 @@ Deno.test('Deno.serve should isolate context between concurrent requests', async abortController.abort(); await server.finished; + await client.flush(); // Should have 3 transaction events (one per request) assertEquals(transactionEvents.length, 3); @@ -338,7 +345,7 @@ Deno.test('Deno.serve should capture unhandled errors', async () => { resetGlobals(); const errorEvents: ErrorEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', beforeSend: (event: ErrorEvent) => { errorEvents.push(event); @@ -378,8 +385,7 @@ Deno.test('Deno.serve should capture unhandled errors', async () => { abortController.abort(); await server.finished; - // delay so that the error has a chance to be handled - await delay(100); + await client.flush(); assertEquals(errorEvents.length, 1); const [errorEvent] = errorEvents; @@ -393,7 +399,7 @@ Deno.test('Deno.serve should handle OPTIONS and HEAD requests without creating s resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -425,6 +431,7 @@ Deno.test('Deno.serve should handle OPTIONS and HEAD requests without creating s abortController.abort(); await server.finished; + await client.flush(); // OPTIONS and HEAD requests should not create transaction spans // (they are handled separately in wrap-deno-request-handler.ts) @@ -435,7 +442,7 @@ Deno.test('Deno.serve should work with handler in options object', async () => { resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -464,6 +471,7 @@ Deno.test('Deno.serve should work with handler in options object', async () => { abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); assertEquals(transactionEvents[0]?.contexts?.trace?.op, 'http.server'); @@ -473,7 +481,7 @@ Deno.test('Deno.serve should capture request headers and set response context', resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -508,6 +516,7 @@ Deno.test('Deno.serve should capture request headers and set response context', abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); const [transaction] = transactionEvents; @@ -525,7 +534,7 @@ Deno.test('Deno.serve should capture client address and port by default', async resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -548,6 +557,7 @@ Deno.test('Deno.serve should capture client address and port by default', async abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); const [transaction] = transactionEvents; @@ -560,7 +570,7 @@ Deno.test('Deno.serve should prefer the forwarded client address, without the so resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -585,6 +595,7 @@ Deno.test('Deno.serve should prefer the forwarded client address, without the so abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); const [transaction] = transactionEvents; @@ -597,7 +608,7 @@ Deno.test('Deno.serve should fall back to the socket address when the forwarding resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -622,6 +633,7 @@ Deno.test('Deno.serve should fall back to the socket address when the forwarding abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); const [transaction] = transactionEvents; @@ -634,7 +646,7 @@ Deno.test('Deno.serve should set the socket address as the user IP on error even resetGlobals(); const errorEvents: ErrorEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -658,6 +670,7 @@ Deno.test('Deno.serve should set the socket address as the user IP on error even abortController.abort(); await server.finished; + await client.flush(); assertEquals(errorEvents.length, 1); assertMatch(String(errorEvents[0]?.user?.ip_address), LOOPBACK_ADDRESS); @@ -667,7 +680,7 @@ Deno.test('Deno.serve should not capture client address when userInfo collection resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -691,6 +704,7 @@ Deno.test('Deno.serve should not capture client address when userInfo collection abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); const [transaction] = transactionEvents; @@ -703,7 +717,7 @@ Deno.test('Deno.serve should keep PII request headers by default', async () => { resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -728,6 +742,7 @@ Deno.test('Deno.serve should keep PII request headers by default', async () => { abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); const [transaction] = transactionEvents; @@ -739,7 +754,7 @@ Deno.test('Deno.serve should filter PII request headers when configured', async resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -765,6 +780,7 @@ Deno.test('Deno.serve should filter PII request headers when configured', async abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); const [transaction] = transactionEvents; @@ -776,7 +792,7 @@ Deno.test('Deno.serve should support distributed tracing with sentry-trace heade resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -811,6 +827,7 @@ Deno.test('Deno.serve should support distributed tracing with sentry-trace heade abortController.abort(); await server.finished; + await client.flush(); assertEquals(transactionEvents.length, 1); const [transaction] = transactionEvents; @@ -825,7 +842,7 @@ Deno.test('Deno.serve should handle streaming responses', async () => { resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -860,6 +877,7 @@ Deno.test('Deno.serve should handle streaming responses', async () => { abortController.abort(); await server.finished; + await client.flush(); // Span should still be created for streaming responses assertEquals(transactionEvents.length, 1); @@ -911,7 +929,7 @@ Deno.test('Deno.serve should work when manually capturing exceptions within hand const errorEvents: ErrorEvent[] = []; const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -947,6 +965,7 @@ Deno.test('Deno.serve should work when manually capturing exceptions within hand abortController.abort(); await server.finished; + await client.flush(); // Should have both transaction and manually captured error assertEquals(transactionEvents.length, 1); @@ -992,7 +1011,7 @@ Deno.test('Deno.serve should not capture request bodies that ignoreRequestBody m const transactionEvents: TransactionEvent[] = []; const ignoreRequestBodyCalls: [string, string][] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -1020,6 +1039,7 @@ Deno.test('Deno.serve should not capture request bodies that ignoreRequestBody m await (await fetch(`${server.url}/upload?id=1`, { method: 'POST', body: 'secret' })).text(); await (await fetch(`${server.url}/other`, { method: 'POST', body: 'public' })).text(); await server.close(); + await client.flush(); assertEquals(handlerBodies, ['secret', 'public']); assertEquals(ignoreRequestBodyCalls, [ @@ -1090,7 +1110,7 @@ Deno.test('Deno.serve should not create spans for static assets by default', asy resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -1107,6 +1127,7 @@ Deno.test('Deno.serve should not create spans for static assets by default', asy await (await fetch(`${server.url}/assets/app.js`, { method: 'POST' })).text(); await (await fetch(`${server.url}/page`)).text(); await server.close(); + await client.flush(); assertEquals(transactionEvents.map(event => event.transaction).sort(), ['GET /page', 'POST /assets/app.js']); }); @@ -1115,7 +1136,7 @@ Deno.test('Deno.serve should create spans for static assets when ignoreStaticAss resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -1132,6 +1153,7 @@ Deno.test('Deno.serve should create spans for static assets when ignoreStaticAss const server = await serveForTest(() => new Response('OK')); await (await fetch(`${server.url}/favicon.ico`)).text(); await server.close(); + await client.flush(); assertEquals( transactionEvents.map(event => event.transaction), @@ -1210,7 +1232,7 @@ Deno.test('Deno.serve should call onSpanCreated and onSpanEnd', async () => { const transactionEvents: TransactionEvent[] = []; const hookCalls: string[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -1239,6 +1261,7 @@ Deno.test('Deno.serve should call onSpanCreated and onSpanEnd', async () => { }); await (await fetch(`${server.url}/hooks`)).text(); await server.close(); + await client.flush(); assertEquals(hookCalls, ['created /hooks', 'handler', 'end /hooks 201']); assertEquals(transactionEvents.length, 1); @@ -1251,7 +1274,7 @@ Deno.test('Deno.serve should call onSpanEnd when a streamed response finishes', const transactionEvents: TransactionEvent[] = []; const hookCalls: string[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -1282,6 +1305,7 @@ Deno.test('Deno.serve should call onSpanEnd when a streamed response finishes', }); assertEquals(await (await fetch(`${server.url}/stream`)).text(), 'chunk\n'); await server.close(); + await client.flush(); assertEquals(hookCalls, ['chunk', 'end']); assertEquals(transactionEvents.length, 1); @@ -1292,7 +1316,7 @@ Deno.test('Deno.serve should still respond and end the span when onSpanCreated t resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -1315,6 +1339,7 @@ Deno.test('Deno.serve should still respond and end the span when onSpanCreated t assertEquals(response.status, 200); assertEquals(await response.text(), 'OK'); await server.close(); + await client.flush(); assertEquals( transactionEvents.map(event => event.transaction), @@ -1342,7 +1367,7 @@ for (const [label, makeResponse] of [ resetGlobals(); const transactionEvents: TransactionEvent[] = []; - init({ + const client = init({ dsn: 'https://username@domain/123', tracesSampleRate: 1, traceLifecycle: 'static', @@ -1365,6 +1390,7 @@ for (const [label, makeResponse] of [ assertEquals(response.status, 200); assertEquals(await response.text(), 'OK'); await server.close(); + await client.flush(); assertEquals( transactionEvents.map(event => event.transaction), diff --git a/packages/effect/test/tracer.test.ts b/packages/effect/test/tracer.test.ts index c706e6bc02c5..7865d134edee 100644 --- a/packages/effect/test/tracer.test.ts +++ b/packages/effect/test/tracer.test.ts @@ -210,11 +210,14 @@ describe.each(VARIANTS)('SentryEffectTracer ($variant)', ({ variant, tracer, spa // `it.effect` runs on Effect's `TestClock`, which is far from the wall clock. yield* TestClock.adjust('1 hour'); + const before = sentryCore.timestampInSeconds(); const span = yield* Effect.makeSpan('manual-span'); + const after = sentryCore.timestampInSeconds(); span.event('my-event', span.status.startTime + BigInt(1_000_000_000)); span.end(span.status.startTime + BigInt(2_500_000_000), Exit.void); - expect(sentryStartTime).toBeCloseTo(Date.now() / 1000, 0); + expect(sentryStartTime).toBeGreaterThanOrEqual(before); + expect(sentryStartTime).toBeLessThanOrEqual(after); expect(addEvent).toHaveBeenCalledWith('my-event', undefined, sentryStartTime! + 1); expect(end).toHaveBeenCalledWith(sentryStartTime! + 2.5); }).pipe(withSentryTracer), diff --git a/packages/integration-shims/src/TracingIntegrations.ts b/packages/integration-shims/src/TracingIntegrations.ts new file mode 100644 index 000000000000..d8f90bbca03c --- /dev/null +++ b/packages/integration-shims/src/TracingIntegrations.ts @@ -0,0 +1,52 @@ +import { consoleSandbox, defineIntegration } from '@sentry/core'; + +/** + * Creates a shim for one of the integrations that make up `browserTracingIntegration`. + * It is needed in order for the CDN bundles to continue working when users add/remove tracing + * from it, without changing their config. This is necessary for the loader mechanism. + */ +function makeTracingIntegrationShim(name: string, functionName: string): ReturnType { + return defineIntegration((_options?: unknown) => { + consoleSandbox(() => { + // eslint-disable-next-line no-console + console.warn(`You are using ${functionName}() even though this bundle does not include tracing.`); + }); + + return { + name, + }; + }); +} + +/** + * This is a shim for the `browserTracingCoreIntegration`. + */ +export const browserTracingCoreIntegrationShim = makeTracingIntegrationShim( + 'BrowserTracing', + 'browserTracingCoreIntegration', +); + +/** + * This is a shim for the `longTasksIntegration`. + */ +export const longTasksIntegrationShim = makeTracingIntegrationShim('LongTasks', 'longTasksIntegration'); + +/** + * This is a shim for the `resourcesIntegration`. + */ +export const resourcesIntegrationShim = makeTracingIntegrationShim('Resources', 'resourcesIntegration'); + +/** + * This is a shim for the `fetchTracingIntegration`. + */ +export const fetchTracingIntegrationShim = makeTracingIntegrationShim('FetchTracing', 'fetchTracingIntegration'); + +/** + * This is a shim for the `xhrTracingIntegration`. + */ +export const xhrTracingIntegrationShim = makeTracingIntegrationShim('XhrTracing', 'xhrTracingIntegration'); + +/** + * This is a shim for the `linkedTracesIntegration`. + */ +export const linkedTracesIntegrationShim = makeTracingIntegrationShim('LinkedTraces', 'linkedTracesIntegration'); diff --git a/packages/integration-shims/src/index.ts b/packages/integration-shims/src/index.ts index 051bda210c4f..aafb04cc82a3 100644 --- a/packages/integration-shims/src/index.ts +++ b/packages/integration-shims/src/index.ts @@ -7,3 +7,11 @@ export { loggerShim, consoleLoggingIntegrationShim } from './logs'; export { metricsShim } from './metrics'; export { spanStreamingIntegrationShim } from './SpanStreaming'; export { fetchStreamPerformanceIntegrationShim } from './FetchStreamPerformance'; +export { + browserTracingCoreIntegrationShim, + longTasksIntegrationShim, + resourcesIntegrationShim, + fetchTracingIntegrationShim, + xhrTracingIntegrationShim, + linkedTracesIntegrationShim, +} from './TracingIntegrations'; diff --git a/packages/nestjs/src/decorators.ts b/packages/nestjs/src/decorators.ts index 0a74734adb8b..f255e293fcb4 100644 --- a/packages/nestjs/src/decorators.ts +++ b/packages/nestjs/src/decorators.ts @@ -3,6 +3,7 @@ import { CODE_FUNCTION_NAME, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/convention import { captureException, debug } from '@sentry/core'; import * as Sentry from '@sentry/node'; import { startSpan } from '@sentry/node'; +import { _INTERNAL_cronExpressionToMonitorConfig as cronExpressionToMonitorConfig } from '@sentry/server-utils'; import { DEBUG_BUILD } from './debug-build'; import { isExpectedError } from './helpers'; import type { ReflectWithMetadata } from './integrations/helpers'; @@ -98,18 +99,6 @@ function resolveMonitorConfig( const SCHEDULE_CRON_OPTIONS = 'SCHEDULE_CRON_OPTIONS'; -// `cron` presets (case-insensitive). Sentry accepts only the first five, so the others are sent as crontabs. -const CRON_PRESETS: Record = { - '@yearly': '@yearly', - '@monthly': '@monthly', - '@weekly': '@weekly', - '@daily': '@daily', - '@hourly': '@hourly', - '@minutely': '* * * * *', - '@weekdays': '0 0 * * 1-5', - '@weekends': '0 0 * * 0,6', -}; - interface NestCronOptions { cronTime?: unknown; timeZone?: unknown; @@ -150,118 +139,15 @@ export function nestCronOptionsToMonitorConfig( return undefined; } + // `cron` 2.x (`@nestjs/schedule` 2 and 3) counts months from 0. Steps and names don't depend on that. const fields = cronTime.trim().split(/\s+/); - let crontab: string | undefined; - if (fields.length === 1) { - crontab = CRON_PRESETS[(fields[0] as string).toLowerCase()]; - } else if (fields.length === 5) { - crontab = isSupportedCrontab(fields, scheduleVersion) ? fields.join(' ') : undefined; - } else if (fields.length === 6 && /^\d+$/.test(fields[0] as string)) { - // Sentry schedules have minute granularity, so only a fixed second can be dropped. - crontab = isSupportedCrontab(fields.slice(1), scheduleVersion) ? fields.slice(1).join(' ') : undefined; - } - - if (!crontab) { - return undefined; - } - - // Without a `timeZone`, `cron` uses the server's time zone, but Sentry would assume UTC. - const timezone = toSentryTimeZone(typeof timeZone === 'string' && timeZone ? timeZone : getLocalTimeZone()); - if (!timezone) { - return undefined; - } - - return { - schedule: { type: 'crontab', value: crontab }, - timezone, - }; -} - -/** - * Whether Sentry reads the 5 crontab fields the same way `cron` (used by `@nestjs/schedule`) runs them. - */ -function isSupportedCrontab( - [, , dayOfMonth = '', month = '', dayOfWeek = '']: string[], - scheduleVersion: string | undefined, -): boolean { - // `cron` 2.x (`@nestjs/schedule` 2 and 3) counts months from 0. Steps don't depend on that. + const month = fields.length >= 5 ? (fields[fields.length - 2] as string) : ''; const countsMonthsFromOne = parseInt(scheduleVersion ?? '', 10) >= 4; if (!countsMonthsFromOne && /\d/.test(month.replace(/\/\d+/g, ''))) { - return false; - } - - const daysOfMonth = countCronValues(dayOfMonth, 1, 31); - const daysOfWeek = countCronValues(dayOfWeek, 0, 7); - if (daysOfMonth === undefined || daysOfWeek === undefined) { - return false; - } - - // `cron` ignores a day field that covers every day (like `1-31` or `sun-sat`) and runs on either day field - // otherwise. Sentry reads full ranges as they are and needs both day fields when one starts with `*` (like `*/2`). - const allDaysOfMonth = daysOfMonth === 31; - const allDaysOfWeek = daysOfWeek === 7; - const cronRunsOnEither = !allDaysOfMonth && !allDaysOfWeek; - const sentryRunsOnEither = !dayOfMonth.startsWith('*') && !dayOfWeek.startsWith('*'); - return (allDaysOfMonth && allDaysOfWeek) || cronRunsOnEither === sentryRunsOnEither; -} - -const DAY_NAMES: Record = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 }; - -/** - * How many days a day field matches, expanded the way `cron` does it, or `undefined` if `cron` can't parse it. - * Day of week `7` is Sunday, like `0`. - */ -function countCronValues(field: string, low: number, high: number): number | undefined { - let unknownName = false; - const numericField = field.replace(/[a-z]{1,3}/gi, name => { - const value = DAY_NAMES[name.toLowerCase()]; - unknownName ||= value === undefined; - return String(value); - }); - if (unknownName) { return undefined; } - const values = new Set(); - for (const part of numericField.split(',')) { - const match = part.match(/^(?:(\*)|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/); - if (!match) { - return undefined; - } - const [, wildcard, from, to, step] = match; - const lower = wildcard ? low : Number(from); - const upper = wildcard || (step && !to) ? high : Number(to ?? from); - const increment = Number(step ?? 1); - if (!increment || lower < low || upper > high || lower > upper) { - return undefined; - } - for (let value = lower; value <= upper; value += increment) { - values.add(high === 7 && value === 7 ? 0 : value); - } - } - return values.size; -} - -/** - * The canonical IANA name of the time zone, or `undefined` if Sentry won't accept it (like `UTC+3`). - */ -function toSentryTimeZone(timezone: string | undefined): string | undefined { - if (!timezone || timezone === 'Etc/Unknown' || /^(?:utc|gmt)?[+-]/i.test(timezone)) { - return undefined; - } - try { - return new Intl.DateTimeFormat('en-US', { timeZone: timezone }).resolvedOptions().timeZone || undefined; - } catch { - return undefined; - } -} - -function getLocalTimeZone(): string | undefined { - try { - return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined; - } catch { - return undefined; - } + return cronExpressionToMonitorConfig(cronTime, timeZone, 'cron'); } /** diff --git a/packages/nestjs/src/integrations/nest.ts b/packages/nestjs/src/integrations/nest.ts index 853caf825d71..003b9d6dae0d 100644 --- a/packages/nestjs/src/integrations/nest.ts +++ b/packages/nestjs/src/integrations/nest.ts @@ -1,9 +1,10 @@ -import { defineIntegration } from '@sentry/core'; +import { defineIntegration, SDK_VERSION } from '@sentry/core'; import type { NestCronMonitoringOptions } from './cron-monitoring'; import { setCronMonitoringOptions } from './cron-monitoring'; import { subscribeToNestChannels } from './orchestrion-subscriber'; const INTEGRATION_NAME = 'Nest' as const; +const SDK_NAME = 'sentry.javascript.nestjs'; export type NestIntegrationOptions = NestCronMonitoringOptions; @@ -18,6 +19,14 @@ export const nestIntegration = defineIntegration((options: NestIntegrationOption }, setup(client) { setCronMonitoringOptions(client, options); + + // On Bun, Deno and Cloudflare, the runtime's SDK inits the client and this integration is + // added to it. The runtime SDK stays in `packages`. + const sdk = client.getOptions()._metadata?.sdk; + if (sdk && sdk.name !== SDK_NAME) { + sdk.name = SDK_NAME; + sdk.packages = [{ name: 'npm:@sentry/nestjs', version: SDK_VERSION }, ...(sdk.packages || [])]; + } }, }; }); diff --git a/packages/nestjs/test/decorators.test.ts b/packages/nestjs/test/decorators.test.ts index 47bc07d14ab4..66f75a616a28 100644 --- a/packages/nestjs/test/decorators.test.ts +++ b/packages/nestjs/test/decorators.test.ts @@ -310,7 +310,7 @@ describe('SentryCron decorator with @Cron', () => { locales?: string | string[], options?: Intl.DateTimeFormatOptions, ) { - return new DateTimeFormat(locales, { timeZone: 'Asia/Tokyo', ...options }); + return new DateTimeFormat(locales, { ...options, timeZone: options?.timeZone ?? 'Asia/Tokyo' }); } as typeof Intl.DateTimeFormat); }); @@ -382,22 +382,13 @@ describe('SentryCron decorator with @Cron', () => { ['a numeric month range', Cron('0 9 1 1-6 *')], ['a numeric month list', Cron('0 9 1 1,7 *')], ['a numeric month with a step', Cron('0 9 1 2/3 *')], + ['a numeric month with seconds', Cron('0 0 9 1 5 *')], // `0 0 1 0 *` in `@nestjs/schedule` 3 ['CronExpression.EVERY_YEAR', Cron('0 0 1 1 *')], - ['a day-of-month step with a day of week', Cron('0 9 */2 * MON')], - ['a full day-of-month range with a day of week', Cron('0 9 1-31 * MON')], - ['a full day-of-week range with a day of month', Cron('0 9 1 * 0-6')], - ['a full 1-7 day-of-week range with a day of month', Cron('0 9 15 * 1-7')], ['a full day-of-week name range with a day of month', Cron('0 9 1 * sun-sat')], - ['a full upper-case day-of-week name range with a day of month', Cron('0 9 1 * SUN-SAT')], - ['a full mon-sun day-of-week range with a day of month', Cron('0 9 1 * mon-sun')], - ['a full day-of-week list with a day of month', Cron('0 9 1 * 0,1,2,3,4,5,6')], - ['a full day-of-month range with a step of 1 and a day of week', Cron('0 9 1-31/1 * MON')], ['an unknown day name', Cron('0 9 1 * sunday')], - ['an out-of-range day of month', Cron('0 9 32 * *')], ['a numeric month from @nestjs/schedule 3', VersionedCron('0 9 1 5 *', '3.0.4')], ['a fixed-offset time zone', Cron('0 * * * *', { timeZone: 'UTC+3' })], - ['an unknown time zone', Cron('0 * * * *', { timeZone: 'Mars/Olympus' })], ])('sends no monitor config for %s', async (_, cronDecorator) => { const withMonitorSpy = vi.spyOn(core, 'withMonitor'); const service = decorate(SentryCron('my-job'), cronDecorator); @@ -407,17 +398,17 @@ describe('SentryCron decorator with @Cron', () => { }); it.each([ - ['a month name', '0 9 1 MAY *'], - ['both day fields', '0 9 1-7 * MON'], - ['a day-of-week name list with a day of month', '0 9 1 * mon,fri'], - ['a full day-of-month range with a day-of-week step', '0 9 1-31 * */2'], - ['a day-of-month step of 1 with a day of week', '0 9 */1 * MON'], - ['both day fields covering every day', '0 9 1-31 * sun-sat'], - ['CronExpression.EVERY_QUARTER', '0 0 1 */3 *'], - ['CronExpression.EVERY_6_MONTHS', '0 0 1 */6 *'], - ])('sends a crontab with %s', async (_, crontab) => { + ['a month name', '0 9 1 MAY *', '0 9 1 5 *'], + ['a day-of-week name list with a day of month', '0 9 1 * mon,fri', '0 9 1 * 1,5'], + ['both day fields covering every day', '0 9 1-31 * sun-sat', '0 9 1-31 * 0-6'], + ['a day-of-month range of 29 days with a day of week', '0 9 1-29 * 1', '0 9 1-29 * 1'], + ['a day-of-month range of 30 days with a day of week', '0 9 2-31 * 1', '0 9 2-31 * 1'], + ['a day-of-month list of 30 days with a day of week', '0 9 1,3-31 * 1', '0 9 1,3-31 * 1'], + ['CronExpression.EVERY_QUARTER', '0 0 1 */3 *', '0 0 1 */3 *'], + ['a preset', '@WEEKLY', '0 0 * * 0'], + ])('sends a crontab with %s', async (_, cronTime, crontab) => { const withMonitorSpy = vi.spyOn(core, 'withMonitor'); - const service = decorate(SentryCron('my-job'), Cron(crontab)); + const service = decorate(SentryCron('my-job'), Cron(cronTime)); await service.job(); expect(withMonitorSpy).toHaveBeenCalledWith('my-job', expect.any(Function), { @@ -452,24 +443,6 @@ describe('SentryCron decorator with @Cron', () => { expect(withMonitorSpy).toHaveBeenCalledWith('my-job', expect.any(Function), undefined); }); - it.each([ - ['@hourly', '@hourly'], - ['@daily', '@daily'], - ['@WEEKLY', '@weekly'], - ['@monthly', '@monthly'], - ['@yearly', '@yearly'], - ['@weekdays', '0 0 * * 1-5'], - ])('sends the preset %s as %s', async (preset, value) => { - const withMonitorSpy = vi.spyOn(core, 'withMonitor'); - const service = decorate(SentryCron('my-job'), Cron(preset)); - - await service.job(); - expect(withMonitorSpy).toHaveBeenCalledWith('my-job', expect.any(Function), { - schedule: { type: 'crontab', value }, - timezone: 'Asia/Tokyo', - }); - }); - it('warns when monitor settings are passed but no schedule can be derived', async () => { const warnSpy = vi.spyOn(core.debug, 'warn').mockImplementation(() => undefined); const withMonitorSpy = vi.spyOn(core, 'withMonitor').mockImplementation((_, callback) => callback()); @@ -531,6 +504,21 @@ describe('SentryCron decorator with @Cron', () => { }); }); + it.each([undefined, 1, 5])( + 'sends only the checkinMargin passed for a dropped seconds value, given %s', + async checkinMargin => { + const withMonitorSpy = vi.spyOn(core, 'withMonitor'); + const service = decorate(SentryCron('my-job', { checkinMargin }), Cron('59 0 9 * * *')); + + await service.job(); + expect(withMonitorSpy).toHaveBeenCalledWith('my-job', expect.any(Function), { + schedule: { type: 'crontab', value: '0 9 * * *' }, + timezone: 'Asia/Tokyo', + checkinMargin, + }); + }, + ); + it('uses an explicit monitor config as is', async () => { const withMonitorSpy = vi.spyOn(core, 'withMonitor'); const monitorConfig: core.MonitorConfig = { schedule: { type: 'interval', value: 1, unit: 'hour' } }; diff --git a/packages/nestjs/test/integrations/nest.test.ts b/packages/nestjs/test/integrations/nest.test.ts index a369060ece3d..a72e58f4e866 100644 --- a/packages/nestjs/test/integrations/nest.test.ts +++ b/packages/nestjs/test/integrations/nest.test.ts @@ -1,7 +1,17 @@ +import type { Client, Options } from '@sentry/core'; +import { applySdkMetadata, SDK_VERSION } from '@sentry/core'; import { describe, expect, it } from 'vitest'; import { isTargetPatched } from '../../src/integrations/helpers'; +import { nestIntegration } from '../../src/integrations/nest'; import type { InjectableTarget } from '../../src/integrations/types'; +function setupWithRuntimeSdk(name: string, names?: string[]): Options { + const options: Options = {}; + applySdkMetadata(options, name, names); + nestIntegration().setup!({ getOptions: () => options } as unknown as Client); + return options; +} + describe('Nest', () => { describe('isTargetPatched', () => { it('should return true if target is already patched', () => { @@ -15,4 +25,32 @@ describe('Nest', () => { expect(target.sentryPatchedInjectable).toBe(true); }); }); + + describe('SDK metadata', () => { + it.each(['bun', 'deno', 'cloudflare', 'node'])('names the SDK `nestjs` when the %s SDK inits', runtime => { + expect(setupWithRuntimeSdk(runtime)._metadata).toEqual({ + sdk: { + name: 'sentry.javascript.nestjs', + packages: [ + { name: 'npm:@sentry/nestjs', version: SDK_VERSION }, + { name: `npm:@sentry/${runtime}`, version: SDK_VERSION }, + ], + version: SDK_VERSION, + }, + }); + }); + + it('keeps the metadata the NestJS SDK set', () => { + expect(setupWithRuntimeSdk('nestjs', ['nestjs', 'node'])._metadata).toEqual({ + sdk: { + name: 'sentry.javascript.nestjs', + packages: [ + { name: 'npm:@sentry/nestjs', version: SDK_VERSION }, + { name: 'npm:@sentry/node', version: SDK_VERSION }, + ], + version: SDK_VERSION, + }, + }); + }); + }); }); diff --git a/packages/nextjs/src/client/index.ts b/packages/nextjs/src/client/index.ts index bd98c6a78a99..e94f97b144b2 100644 --- a/packages/nextjs/src/client/index.ts +++ b/packages/nextjs/src/client/index.ts @@ -4,6 +4,7 @@ import type { BrowserTunnelOptions, Client, EventProcessor, Integration } from '@sentry/core'; import { _INTERNAL_applyBrowserTunnelDefaults as applyBrowserTunnelDefaults, + _INTERNAL_captureOptionsSetByUser, applySdkMetadata, consoleSandbox, getGlobalScope, @@ -39,7 +40,9 @@ const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { declare const __SENTRY_TRACING__: boolean; /** Inits the Sentry NextJS SDK on the browser with the React SDK. */ -export function init(options: BrowserOptions): Client | undefined { +export function init(userOptions: BrowserOptions): Client | undefined { + const options = _INTERNAL_captureOptionsSetByUser(userOptions); + if (!DEBUG_BUILD && options.debug) { consoleSandbox(() => { // TODO(v12): Remove the `webpack.treeshake` mention together with that option diff --git a/packages/nextjs/src/config/loaders/moduleMetadataInjectionLoader.ts b/packages/nextjs/src/config/loaders/moduleMetadataInjectionLoader.ts index 4232f1af7934..bcbe1c04a0b1 100644 --- a/packages/nextjs/src/config/loaders/moduleMetadataInjectionLoader.ts +++ b/packages/nextjs/src/config/loaders/moduleMetadataInjectionLoader.ts @@ -1,5 +1,6 @@ import { getCodeInjectionPosition } from '@sentry/bundler-plugins/loader-utils'; import type { LoaderThis } from './types'; +import { stringifyForCodeInjection } from '@sentry/core'; export type ModuleMetadataInjectionLoaderOptions = { applicationKey: string; @@ -31,7 +32,7 @@ export default function moduleMetadataInjectionLoader( // The IIFE resolves the global object and stores metadata keyed by (new Error).stack // so the SDK can map chunk filenames to metadata at runtime. // Not putting any newlines in the generated code will decrease the likelihood of sourcemaps breaking. - const metadata = JSON.stringify({ [`_sentryBundlerPluginAppKey:${applicationKey}`]: true }); + const metadata = stringifyForCodeInjection({ [`_sentryBundlerPluginAppKey:${applicationKey}`]: true }); const injectedCode = ';!function(){try{' + 'var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};' + diff --git a/packages/nextjs/src/config/loaders/valueInjectionLoader.ts b/packages/nextjs/src/config/loaders/valueInjectionLoader.ts index 9efd442e8d83..eb5dc10ac7cf 100644 --- a/packages/nextjs/src/config/loaders/valueInjectionLoader.ts +++ b/packages/nextjs/src/config/loaders/valueInjectionLoader.ts @@ -1,5 +1,6 @@ import { getCodeInjectionPosition } from '@sentry/bundler-plugins/loader-utils'; import type { LoaderThis } from './types'; +import { stringifyForCodeInjection } from '@sentry/core'; export type ValueInjectionLoaderOptions = { values: Record; @@ -24,7 +25,7 @@ export default function valueInjectionLoader(this: LoaderThis `globalThis["${key}"] = ${JSON.stringify(value)};`) + .map(([key, value]) => `globalThis["${key}"] = ${stringifyForCodeInjection(value)};`) .join(''); const injectionIndex = getCodeInjectionPosition(userCode); diff --git a/packages/nextjs/src/config/loaders/wrappingLoader.ts b/packages/nextjs/src/config/loaders/wrappingLoader.ts index 537957c91ad6..4ae0e160a2b7 100644 --- a/packages/nextjs/src/config/loaders/wrappingLoader.ts +++ b/packages/nextjs/src/config/loaders/wrappingLoader.ts @@ -1,5 +1,5 @@ import commonjs from '@rollup/plugin-commonjs'; -import { stringMatchesSomePattern } from '@sentry/core'; +import { stringifyForCodeInjection, stringMatchesSomePattern } from '@sentry/core'; import * as fs from 'fs'; import * as path from 'path'; import type { RollupBuild, RollupError } from 'rollup'; @@ -119,7 +119,10 @@ export default function wrappingLoader( throw new Error(`Invariant: Could not get template code of unknown kind "${wrappingTargetKind}"`); } - templateCode = templateCode.replace(/__VERCEL_CRONS_CONFIGURATION__/g, JSON.stringify(vercelCronsConfig)); + templateCode = templateCode.replace( + /__VERCEL_CRONS_CONFIGURATION__/g, + stringifyForCodeInjection(vercelCronsConfig), + ); // Inject the route and the path to the file we're wrapping into the template templateCode = templateCode.replace(/__ROUTE__/g, parameterizedPagesRoute.replace(/\\/g, '\\\\')); diff --git a/packages/nextjs/src/server/index.ts b/packages/nextjs/src/server/index.ts index 7c275903f622..548be02fa022 100644 --- a/packages/nextjs/src/server/index.ts +++ b/packages/nextjs/src/server/index.ts @@ -3,6 +3,7 @@ /* eslint-disable import/export */ import type { Scope } from '@sentry/core'; import { + _INTERNAL_captureOptionsSetByUser, _INTERNAL_getActiveClient, applySdkMetadata, debug, @@ -116,12 +117,14 @@ function getCloudflareRuntimeConfig(): { runtime: { name: string } } | undefined /** Inits the Sentry NextJS SDK on node. */ // eslint-disable-next-line complexity -export function init(options: NodeOptions): NodeClient | undefined { +export function init(userOptions: NodeOptions): NodeClient | undefined { prepareSafeIdGeneratorContext(); if (isBuild()) { return; } + const options = _INTERNAL_captureOptionsSetByUser(userOptions); + if (!DEBUG_BUILD && options.debug) { // TODO(v12): Remove the `webpack.treeshake` mention together with that option // eslint-disable-next-line no-console diff --git a/packages/nextjs/test/clientSdk.test.ts b/packages/nextjs/test/clientSdk.test.ts index cf0b8eca9568..293f18d758b8 100644 --- a/packages/nextjs/test/clientSdk.test.ts +++ b/packages/nextjs/test/clientSdk.test.ts @@ -56,6 +56,7 @@ describe('Client init()', () => { expect(reactInit).toHaveBeenCalledWith( expect.objectContaining({ _metadata: { + optionsSetByUser: [], sdk: { name: 'sentry.javascript.nextjs', version: expect.any(String), diff --git a/packages/nextjs/test/serverSdk.test.ts b/packages/nextjs/test/serverSdk.test.ts index 45460aa09f70..28f6e7a501d3 100644 --- a/packages/nextjs/test/serverSdk.test.ts +++ b/packages/nextjs/test/serverSdk.test.ts @@ -57,6 +57,7 @@ describe('Server init()', () => { expect(nodeInit).toHaveBeenLastCalledWith( expect.objectContaining({ _metadata: { + optionsSetByUser: [], sdk: { name: 'sentry.javascript.nextjs', version: expect.any(String), diff --git a/packages/node/src/cron/common.ts b/packages/node/src/cron/common.ts index c2f2cb088859..be0097ab7142 100644 --- a/packages/node/src/cron/common.ts +++ b/packages/node/src/cron/common.ts @@ -1,51 +1,27 @@ -const replacements: [string, string][] = [ - ['january', '1'], - ['february', '2'], - ['march', '3'], - ['april', '4'], - ['may', '5'], - ['june', '6'], - ['july', '7'], - ['august', '8'], - ['september', '9'], - ['october', '10'], - ['november', '11'], - ['december', '12'], - ['jan', '1'], - ['feb', '2'], - ['mar', '3'], - ['apr', '4'], - ['may', '5'], - ['jun', '6'], - ['jul', '7'], - ['aug', '8'], - ['sep', '9'], - ['oct', '10'], - ['nov', '11'], - ['dec', '12'], - ['sunday', '0'], - ['monday', '1'], - ['tuesday', '2'], - ['wednesday', '3'], - ['thursday', '4'], - ['friday', '5'], - ['saturday', '6'], - ['sun', '0'], - ['mon', '1'], - ['tue', '2'], - ['wed', '3'], - ['thu', '4'], - ['fri', '5'], - ['sat', '6'], -]; +import type { MonitorConfig } from '@sentry/core'; +import { debug } from '@sentry/core'; +import type { _INTERNAL_CronDialect as CronDialect } from '@sentry/server-utils'; +import { _INTERNAL_cronExpressionToMonitorConfig as cronExpressionToMonitorConfig } from '@sentry/server-utils'; +import { DEBUG_BUILD } from '../debug-build'; /** - * Replaces names in cron expressions + * The monitor config for a cron expression, or `undefined` if Sentry would read the expression differently than the + * scheduler runs it. */ -export function replaceCronNames(cronExpression: string): string { - return replacements.reduce( - // oxlint-disable-next-line sdk/no-regexp-constructor - (acc, [name, replacement]) => acc.replace(new RegExp(name, 'gi'), replacement), - cronExpression, - ); +export function getCronMonitorConfig( + expression: string, + timezone: unknown, + dialect: CronDialect, + isReadAlike: (expression: string) => boolean = () => true, +): MonitorConfig | undefined { + const monitorConfig = isReadAlike(expression) + ? cronExpressionToMonitorConfig(expression, timezone, dialect) + : undefined; + if (!monitorConfig) { + DEBUG_BUILD && + debug.warn( + `[Cron] Can't convert "${expression}" to a Sentry schedule, sending check-ins without a monitor config.`, + ); + } + return monitorConfig; } diff --git a/packages/node/src/cron/cron.ts b/packages/node/src/cron/cron.ts index dd3edf1c95b5..529d47b0aed0 100644 --- a/packages/node/src/cron/cron.ts +++ b/packages/node/src/cron/cron.ts @@ -1,5 +1,5 @@ import { addNonEnumerableProperty, captureException, withMonitor } from '@sentry/core'; -import { replaceCronNames } from './common'; +import { getCronMonitorConfig } from './common'; export type CronJobParams = { cronTime: string | Date; @@ -94,7 +94,8 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri jobScheduled = true; - const cronString = replaceCronNames(cronTime); + const utcOffset = args[7]; + const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'cron') : undefined; async function monitoredTick(context: unknown, onComplete?: unknown): Promise { return withMonitor( @@ -112,10 +113,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri throw e; } }, - { - schedule: { type: 'crontab', value: cronString }, - timezone: timeZone || undefined, - }, + monitorConfig, ); } @@ -127,7 +125,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri get(target, prop: keyof CronJobConstructor) { if (prop === 'from') { return (param: CronJobParams) => { - const { cronTime, onTick, timeZone } = param; + const { cronTime, onTick, timeZone, utcOffset } = param; if (typeof cronTime !== 'string') { throw new Error(ERROR_TEXT); @@ -139,7 +137,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri jobScheduled = true; - const cronString = replaceCronNames(cronTime); + const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'cron') : undefined; param.onTick = async (context: unknown, onComplete?: unknown) => { return withMonitor( @@ -157,10 +155,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri throw e; } }, - { - schedule: { type: 'crontab', value: cronString }, - timezone: timeZone || undefined, - }, + monitorConfig, ); }; diff --git a/packages/node/src/cron/index.ts b/packages/node/src/cron/index.ts index 890d88441ec1..56144101264c 100644 --- a/packages/node/src/cron/index.ts +++ b/packages/node/src/cron/index.ts @@ -6,6 +6,7 @@ import { instrumentNodeSchedule } from './node-schedule'; export const cron = { // oxlint-disable-next-line typescript/no-deprecated instrumentCron, + // oxlint-disable-next-line typescript/no-deprecated instrumentNodeCron, instrumentNodeSchedule, }; diff --git a/packages/node/src/cron/node-cron.ts b/packages/node/src/cron/node-cron.ts index ab3d935c1a89..f56b61b144cc 100644 --- a/packages/node/src/cron/node-cron.ts +++ b/packages/node/src/cron/node-cron.ts @@ -1,5 +1,12 @@ -import { addNonEnumerableProperty, captureException, type MonitorConfig, withMonitor } from '@sentry/core'; -import { replaceCronNames } from './common'; +import { + addNonEnumerableProperty, + captureException, + type MonitorConfig, + startNewTrace, + withMonitor, +} from '@sentry/core'; +import { _INTERNAL_isReadAlikeByNodeCron3 as isReadAlikeByNodeCron3 } from '@sentry/server-utils'; +import { getCronMonitorConfig } from './common'; export interface NodeCronOptions { name: string; @@ -31,6 +38,11 @@ export interface NodeCron { * { name: "my-cron-job" }, * ); * ``` + * + * On node-cron 4, steps on `*` in the day-of-month or month field (such as every second day) aren't sent as a + * schedule, because this wrapper can't tell the node-cron version. `nodeCronIntegration` can. + * + * @deprecated Use `nodeCronIntegration` instead. */ export function instrumentNodeCron( lib: Partial & T, @@ -51,31 +63,36 @@ export function instrumentNodeCron( throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.'); } + // The node-cron version is unknown here, so check for node-cron 3 quirks, which include those before 4.6. + const cronConfig = getCronMonitorConfig(expression, timezone, 'node-cron', isReadAlikeByNodeCron3); + const upsertMonitorConfig = cronConfig && { ...cronConfig, ...monitorConfig }; + const monitoredCallback = async (...args: Parameters): Promise => { - return withMonitor( - name, - async () => { - // We have to manually catch here and capture the exception because node-cron swallows errors - // https://github.com/node-cron/node-cron/issues/399 - try { - // oxlint-disable-next-line typescript/await-thenable, typescript/return-await -- callback may be async at runtime; awaiting inside the try lets us capture its rejection - return await callback(...args); - } catch (e) { - captureException(e, { - mechanism: { - handled: false, - type: 'auto.function.node-cron.instrumentNodeCron', - }, - }); - throw e; - } - }, - { - schedule: { type: 'crontab', value: replaceCronNames(expression) }, - timezone, - ...monitorConfig, - }, - ); + const runWithMonitor = (): Promise => + withMonitor( + name, + async () => { + // We have to manually catch here and capture the exception because node-cron swallows errors + // https://github.com/node-cron/node-cron/issues/399 + try { + // oxlint-disable-next-line typescript/await-thenable, typescript/return-await -- callback may be async at runtime; awaiting inside the try lets us capture its rejection + return await callback(...args); + } catch (e) { + captureException(e, { + mechanism: { + handled: false, + type: 'auto.function.node-cron.instrumentNodeCron', + }, + }); + throw e; + } + }, + upsertMonitorConfig, + ); + // `withMonitor` reads `isolateTrace` from the monitor config, which is not sent without a schedule. + return !upsertMonitorConfig && monitorConfig.isolateTrace + ? startNewTrace(runWithMonitor) + : runWithMonitor(); }; // Tells `nodeCronIntegration` that this task is already monitored. diff --git a/packages/node/src/cron/node-schedule.ts b/packages/node/src/cron/node-schedule.ts index 548f60ac48f8..7920350a5a34 100644 --- a/packages/node/src/cron/node-schedule.ts +++ b/packages/node/src/cron/node-schedule.ts @@ -1,5 +1,5 @@ import { addNonEnumerableProperty, withMonitor } from '@sentry/core'; -import { replaceCronNames } from './common'; +import { getCronMonitorConfig } from './common'; export interface NodeSchedule { scheduleJob( @@ -44,6 +44,7 @@ export function instrumentNodeSchedule(lib: T & NodeSchedule): T { const monitorSlug = nameOrExpression; const expression = expressionOrCallback; + const monitorConfig = getCronMonitorConfig(expression, undefined, 'cron-parser'); async function monitoredCallback(): Promise { return withMonitor( @@ -52,9 +53,7 @@ export function instrumentNodeSchedule(lib: T & NodeSchedule): T { // oxlint-disable-next-line typescript/await-thenable -- callback may be async at runtime await callback?.(); }, - { - schedule: { type: 'crontab', value: replaceCronNames(expression) }, - }, + monitorConfig, ); } diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts index 27c162b96f00..1a65d57b44ad 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -155,6 +155,7 @@ export { captureConsoleIntegration, dedupeIntegration, extraErrorDataIntegration, + experimentalReportSdkConfigIntegration, rewriteFramesIntegration, startSession, captureSession, diff --git a/packages/node/src/sdk/index.ts b/packages/node/src/sdk/index.ts index ccd4601bfc8b..8506c35a0fb1 100644 --- a/packages/node/src/sdk/index.ts +++ b/packages/node/src/sdk/index.ts @@ -1,5 +1,6 @@ import type { Integration, Options } from '@sentry/core'; import { + _INTERNAL_captureOptionsSetByUser, _INTERNAL_warnIfClientIsActive, applySdkMetadata, consoleSandbox, @@ -112,7 +113,7 @@ export function initWithoutDefaultIntegrations(options: NodeOptions | undefined * Internal initialization function. */ function _init( - options: NodeOptions | undefined = {}, + userOptions: NodeOptions | undefined = {}, getDefaultIntegrationsImpl: (options: Options) => Integration[], ): NodeClient | undefined { // Node re-runs `--require` preloads (though not `--import` ones) on the module loader thread it @@ -133,6 +134,7 @@ function _init( }); } + const options = _INTERNAL_captureOptionsSetByUser(userOptions); applySdkMetadata(options, 'node'); // Enable debug logging before the client is created, so failure modes during setup (e.g. the diff --git a/packages/node/test/cron.test.ts b/packages/node/test/cron.test.ts index f5178dc98e88..a0027520cef7 100644 --- a/packages/node/test/cron.test.ts +++ b/packages/node/test/cron.test.ts @@ -4,6 +4,8 @@ import { cron } from '../src'; import type { CronJob, CronJobParams } from '../src/cron/cron'; import type { NodeCron, NodeCronOptions } from '../src/cron/node-cron'; +const localTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; + describe('cron check-ins', () => { let withMonitorSpy: MockInstance; @@ -82,12 +84,27 @@ describe('cron check-ins', () => { expect(withMonitorSpy).toHaveBeenCalledTimes(1); expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), { schedule: { type: 'crontab', value: '* * * 1,9 0' }, + timezone: localTimezone, }); done(); }, }); })); + test('sends no monitor config with a utc offset', () => + new Promise(done => { + const CronJobWithCheckIn = cron.instrumentCron(CronJobMock, 'my-cron-job'); + + CronJobWithCheckIn.from({ + cronTime: '* * * Jan,Sep Sun', + utcOffset: 60, + onTick: () => { + expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), undefined); + done(); + }, + }); + })); + test('throws with multiple jobs same name', () => { const CronJobWithCheckIn = cron.instrumentCron(CronJobMock, 'my-cron-job'); @@ -131,6 +148,7 @@ describe('cron check-ins', () => { expect(withMonitorSpy).toHaveBeenCalledTimes(1); expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), { schedule: { type: 'crontab', value: '* * * 1,9 0' }, + timezone: localTimezone, }); done(); }, @@ -138,6 +156,61 @@ describe('cron check-ins', () => { ); })); + test('sends no monitor config for a schedule Sentry would read differently', () => + new Promise(done => { + const nodeCron: NodeCron = { + schedule: (_expression: string, callback: () => void): unknown => callback(), + }; + + cron.instrumentNodeCron(nodeCron).schedule( + '*/10 * * * * *', + () => { + expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), undefined); + done(); + }, + { name: 'my-cron-job' }, + ); + })); + + test.each(['0 9 * * 5-0', '0 9 * * sat-sun', '0 9 * * 1-7', '0 9 */2 * 1'])( + 'sends no monitor config for %s, which node-cron before 4.6 reads differently', + expression => + new Promise(done => { + const nodeCron: NodeCron = { + schedule: (_expression: string, callback: () => void): unknown => callback(), + }; + + cron.instrumentNodeCron(nodeCron).schedule( + expression, + () => { + expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), undefined); + done(); + }, + { name: 'my-cron-job' }, + ); + }), + ); + + test('keeps isolateTrace in the monitor config', () => + new Promise(done => { + const nodeCron: NodeCron = { + schedule: (_expression: string, callback: () => void): unknown => callback(), + }; + + cron.instrumentNodeCron(nodeCron, { isolateTrace: true }).schedule( + '0 9 * * *', + () => { + expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), { + schedule: { type: 'crontab', value: '0 9 * * *' }, + timezone: 'Europe/Vienna', + isolateTrace: true, + }); + done(); + }, + { name: 'my-cron-job', timezone: 'Europe/Vienna' }, + ); + })); + test('throws without supplied name', () => { const nodeCron: NodeCron = { schedule: (): unknown => { @@ -180,6 +253,7 @@ describe('cron check-ins', () => { expect(withMonitorSpy).toHaveBeenCalledTimes(1); expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), { schedule: { type: 'crontab', value: '* * * 1,9 0' }, + timezone: localTimezone, }); done(); }); diff --git a/packages/nuxt/src/module.ts b/packages/nuxt/src/module.ts index 578d5c68379f..4c7f9f576c92 100644 --- a/packages/nuxt/src/module.ts +++ b/packages/nuxt/src/module.ts @@ -10,6 +10,7 @@ import { setupOrchestrion } from './vite/orchestrion'; import { setupSourceMaps } from './vite/sourceMaps'; import { findDefaultSdkInitFile, resolveServerApi } from './vite/utils'; import { setupViteServer } from './vite/viteServer'; +import { stringifyForCodeInjection } from '@sentry/core'; export type ModuleOptions = SentryNuxtModuleOptions; type NuxtPageSubset = { file?: string; path: string }; @@ -92,17 +93,19 @@ export default defineNuxtModule({ } else { setupNitroServer(nuxt, serverApi, serverConfigFile, moduleOptions); } - - if (isMinNuxtV4) { - addPlugin({ src: moduleDirResolver.resolve('./runtime/plugins/route-detector.server'), mode: 'server' }); - } else { - addPlugin({ src: moduleDirResolver.resolve('./runtime/plugins/route-detector-legacy.server'), mode: 'server' }); - } } else { // The Cloudflare setup initializes the SDK from `sentryCloudflareNitroPlugin`, so it needs the tunnel too. addTunnelPlugin(serverApi); } + // Names the server spans of pages after their route, with the SDK set up from the server config or from + // `sentryCloudflareNitroPlugin`. + if (isMinNuxtV4) { + addPlugin({ src: moduleDirResolver.resolve('./runtime/plugins/route-detector.server'), mode: 'server' }); + } else { + addPlugin({ src: moduleDirResolver.resolve('./runtime/plugins/route-detector-legacy.server'), mode: 'server' }); + } + if (clientConfigFile || serverConfigFile) { setupSourceMaps(moduleOptions, nuxt, addVitePlugin); } @@ -126,13 +129,15 @@ export default defineNuxtModule({ name: 'sentry-nuxt-pages-data-virtual', resolveId: (id: string) => (id === pagesDataVirtualModuleId ? `\0${pagesDataVirtualModuleId}` : null), load: (id: string) => - id === `\0${pagesDataVirtualModuleId}` ? `export default ${JSON.stringify(pagesData, null, 2)};` : undefined, + id === `\0${pagesDataVirtualModuleId}` + ? `export default ${stringifyForCodeInjection(pagesData, null, 2)};` + : undefined, }); } else { // Nuxt v3: register as a build template (accessible via #build/) addTemplate({ filename: 'sentry--nuxt-pages-data.mjs', - getContents: () => `export default ${JSON.stringify(pagesData, null, 2)};`, + getContents: () => `export default ${stringifyForCodeInjection(pagesData, null, 2)};`, }); } diff --git a/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts b/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts index 4bdeca993ed0..890520e05494 100644 --- a/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts +++ b/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts @@ -2,8 +2,18 @@ import type { ExecutionContext } from '@cloudflare/workers-types'; import type { CloudflareOptions } from '@sentry/cloudflare'; import { getDefaultIntegrations, setAsyncLocalStorageAsyncContextStrategy } from '@sentry/cloudflare'; import { wrapRequestHandler } from '@sentry/cloudflare/request'; -import { debug, getDefaultIsolationScope, getIsolationScope, getTraceData } from '@sentry/core'; -import { _INTERNAL_isServedTunnelRequest as isServedTunnelRequest } from '@sentry/core/server'; +import { + applySdkMetadata, + debug, + getDefaultIsolationScope, + getIsolationScope, + getTraceData, + stripUrlQueryAndFragment, +} from '@sentry/core'; +import { + _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest, + _INTERNAL_isServedTunnelRequest as isServedTunnelRequest, +} from '@sentry/core/server'; import type { H3Event } from 'h3'; import type { NitroApp, NitroAppPlugin } from 'nitropack'; import type { NuxtRenderHTMLContext } from 'nuxt/app'; @@ -12,6 +22,18 @@ import { updateRouteBeforeResponse } from '../hooks/updateRouteBeforeResponse'; import { getCfProperties, getCloudflareProperties, hasCfProperty, isEventType } from '../utils/event-type-check'; import { addSentryPageMetaTags, recordRequestStart } from '../utils/pageMetaTags'; +function getRequestHandlerOptions(cloudflareOptions: CloudflareOptions): CloudflareOptions { + const options: CloudflareOptions = { + // `wrapRequestHandler` only sets up the integrations that work without `nodejs_compat`. + // Nitro's Cloudflare presets require the flag anyway, so opt into the full set. + defaultIntegrations: getDefaultIntegrations(cloudflareOptions), + _extendsDefaultIntegrations: cloudflareOptions.defaultIntegrations === undefined, + ...cloudflareOptions, + }; + applySdkMetadata(options, 'nuxt', ['nuxt', 'cloudflare']); + return options; +} + /** * Sentry Cloudflare Nitro plugin for when using the "cloudflare-pages" preset in Nuxt. * This plugin automatically sets up Sentry error monitoring and performance tracking for Cloudflare Pages projects. @@ -67,15 +89,14 @@ export const sentryCloudflareNitroPlugin = return wrapRequestHandler( { - options: { - defaultIntegrations: getDefaultIntegrations(cloudflareOptions), - _extendsDefaultIntegrations: cloudflareOptions.defaultIntegrations === undefined, - ...cloudflareOptions, - }, + options: getRequestHandlerOptions(cloudflareOptions), request, context: runtime.cloudflare.context, }, - () => appFetch(request), + () => { + setRequestTransactionName(request.method, new URL(request.url).pathname); + return appFetch(request); + }, ); }; nitroApp.hooks.hook('error', sentryCaptureErrorHook); @@ -97,29 +118,35 @@ export const sentryCloudflareNitroPlugin = } else { // Usually, the protocol already includes ":" const url = `${event.protocol}${event.protocol.endsWith(':') ? '' : ':'}//${event.host}${pathname}`; + // Nitro read the body before calling `localFetch`. This request has no body, so other requests' bodies + // don't end up on events. Only the managed tunnel needs it, see below. const request = new Request(url, { method: event.method, headers: event.headers, - // Nitro read the body before calling `localFetch`. Only the managed tunnel answers from this request, so - // only its requests get the body, and other requests' bodies don't end up on events. - body: isServedTunnelRequest({ method: event.method, url: pathname }) ? event.body : undefined, // @ts-expect-error - 'cf' is a valid property in the RequestInit type for Cloudflare cf: getCfProperties(event), }); const requestHandlerOptions = { - // `wrapRequestHandler` only sets up the integrations that work without `nodejs_compat`. - // Nitro's Cloudflare presets require the flag anyway, so opt into the full set. - options: { - defaultIntegrations: getDefaultIntegrations(cloudflareOptions), - _extendsDefaultIntegrations: cloudflareOptions.defaultIntegrations === undefined, - ...cloudflareOptions, - }, + options: getRequestHandlerOptions(cloudflareOptions), request, context: getCloudflareProperties(event).context, }; return wrapRequestHandler(requestHandlerOptions, () => { + // The served tunnel belongs to the client `wrapRequestHandler` creates, so it can only match from here. + // The wrapper records no span, session or body for a tunnel request. + if (event.body && isServedTunnelRequest(request)) { + const tunnelResponse = handleServedTunnelRequest( + new Request(url, { method: event.method, headers: event.headers, body: event.body }), + ); + if (tunnelResponse) { + return tunnelResponse; + } + } + + setRequestTransactionName(event.method, pathname); + const isolationScope = getIsolationScope(); const newIsolationScope = isolationScope === getDefaultIsolationScope() ? isolationScope.clone() : isolationScope; @@ -171,3 +198,11 @@ export const sentryCloudflareNitroPlugin = nitroApp.hooks.hook('error', sentryCaptureErrorHook); }; + +/** + * Names the events of the request after its method and path until a route names them, like the `node:http` + * instrumentation does on Node. Without it, events captured outside Nitro's `error` hook have no transaction. + */ +function setRequestTransactionName(method: string, path: string): void { + getIsolationScope().setTransactionName(`${method.toUpperCase()} ${stripUrlQueryAndFragment(path)}`); +} diff --git a/packages/nuxt/src/runtime/utils/database-span-data.ts b/packages/nuxt/src/runtime/utils/database-span-data.ts index ed3a4804a656..aa819fe62b74 100644 --- a/packages/nuxt/src/runtime/utils/database-span-data.ts +++ b/packages/nuxt/src/runtime/utils/database-span-data.ts @@ -45,7 +45,11 @@ export function getDatabaseSpanData(config?: DatabaseConnectionConfig): Partial< }; } - if ((['better-sqlite3', 'bun', 'sqlite', 'sqlite3'] as ConnectorName[]).includes(config.connector)) { + if ( + (['better-sqlite3', 'bun', 'bun-sqlite', 'node-sqlite', 'sqlite', 'sqlite3'] as ConnectorName[]).includes( + config.connector, + ) + ) { return { // DB is the default file name in nitro for sqlite-like connectors [DB_NAMESPACE]: `${config.options?.name ?? 'db'}.sqlite`, diff --git a/packages/nuxt/src/runtime/utils/instrumentDatabase.ts b/packages/nuxt/src/runtime/utils/instrumentDatabase.ts index 6dc9a4d84818..9d5e2ca8a610 100644 --- a/packages/nuxt/src/runtime/utils/instrumentDatabase.ts +++ b/packages/nuxt/src/runtime/utils/instrumentDatabase.ts @@ -73,7 +73,8 @@ function instrumentDatabase(db: MaybeInstrumentedDatabase, config?: DatabaseConn } const metadata: DatabaseSpanData = { - [DB_SYSTEM_NAME]: config?.connector ?? db.dialect, + // A connector name like `bun-sqlite` or `mysql2` names the driver, the dialect names the database system. + [DB_SYSTEM_NAME]: db.dialect ?? config?.connector, ...getDatabaseSpanData(config), }; @@ -85,7 +86,18 @@ function instrumentDatabase(db: MaybeInstrumentedDatabase, config?: DatabaseConn apply(target, thisArg, args: Parameters) { const [query] = args; - return instrumentPreparedStatement(target.apply(thisArg, args), query, metadata, dialect); + let statement: PreparedStatement; + try { + statement = target.apply(thisArg, args); + } catch (error) { + // Connectors like `bun-sqlite` and `better-sqlite3` compile the statement in `prepare`, so an invalid query + // throws here and not when the statement runs. + startSpan(createStartSpanOptions(query, metadata, dialect), span => captureDatabaseError(span, error)); + void flushIfServerless(); + throw error; + } + + return instrumentPreparedStatement(statement, query, metadata, dialect); }, }); @@ -224,13 +236,7 @@ function handleSpanStart(fn: () => unknown, breadcrumbOpts?: { query: string; di return result; } catch (error) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); - captureException(error, { - mechanism: { - handled: false, - type: NUXT_DATABASE_ORIGIN, - }, - }); + captureDatabaseError(span, error); // Re-throw the error to be handled by the caller throw error; @@ -240,6 +246,16 @@ function handleSpanStart(fn: () => unknown, breadcrumbOpts?: { query: string; di }; } +function captureDatabaseError(span: Span, error: unknown): void { + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + captureException(error, { + mechanism: { + handled: false, + type: NUXT_DATABASE_ORIGIN, + }, + }); +} + function createBreadcrumb(query: string, dialect: SqlDialect | undefined): void { // The breadcrumb carries the same query text as the span, so it is sanitized and guarded the same way. const queryText = query ? sanitizeSqlQuery(query, dialect) : undefined; diff --git a/packages/nuxt/src/vite/addServerConfig.ts b/packages/nuxt/src/vite/addServerConfig.ts index a6d22cbc48a9..e37b2c5f66e5 100644 --- a/packages/nuxt/src/vite/addServerConfig.ts +++ b/packages/nuxt/src/vite/addServerConfig.ts @@ -3,7 +3,7 @@ import { basename } from 'node:path'; import { pathToFileURL } from 'node:url'; import { addNitroPlugin, addTemplate, createResolver } from '@nuxt/kit'; import type { Nuxt } from '@nuxt/schema'; -import { consoleSandbox, debug } from '@sentry/core'; +import { consoleSandbox, debug, stringifyForCodeInjection } from '@sentry/core'; import * as fs from 'fs'; import type { Nitro } from 'nitropack'; import type { InputPluginOption } from 'rollup'; @@ -116,7 +116,7 @@ export function addServerConfigPlugin(nuxt: Nuxt, serverConfigFile: string, isLe filename: 'sentry-server-config-plugin.mjs', write: true, getContents: () => - `import ${JSON.stringify(runtimeFlagsTemplate.dst)};\nimport ${JSON.stringify(configPath)};\nexport default () => {};\n`, + `import ${stringifyForCodeInjection(runtimeFlagsTemplate.dst)};\nimport ${stringifyForCodeInjection(configPath)};\nexport default () => {};\n`, }); addNitroPlugin(configPluginTemplate.dst); @@ -368,10 +368,10 @@ export function wrapEntryWithDynamicImport({ return ( // Regular `import` of the Sentry config - `import ${JSON.stringify(configUrl)};\n` + + `import ${stringifyForCodeInjection(configUrl)};\n` + // Dynamic `import()` for the previous, actual entry point. // `import()` can be used for any code that should be run after the hooks are registered (https://nodejs.org/api/module.html#enabling) - `import(${JSON.stringify(entryIdUrl)});\n` + + `import(${stringifyForCodeInjection(entryIdUrl)});\n` + `${reExportedFunctions}\n` ); } diff --git a/packages/nuxt/src/vite/databaseConfig.ts b/packages/nuxt/src/vite/databaseConfig.ts index 54f83943191f..159d42b093c3 100644 --- a/packages/nuxt/src/vite/databaseConfig.ts +++ b/packages/nuxt/src/vite/databaseConfig.ts @@ -1,5 +1,5 @@ import { addNitroPlugin, createResolver } from '@nuxt/kit'; -import { consoleSandbox } from '@sentry/core'; +import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core'; import type { NitroConfig } from 'nitropack/types'; import type { SentryNuxtModuleOptions } from '../common/types'; import { addServerTemplate } from '../vendor/server-template'; @@ -38,7 +38,7 @@ export function addDatabaseInstrumentation( addServerTemplate({ filename: '#sentry/database-config.mjs', getContents: () => { - return `export const databaseConfig = ${JSON.stringify(databaseConfig)};`; + return `export const databaseConfig = ${stringifyForCodeInjection(databaseConfig)};`; }, }); diff --git a/packages/nuxt/src/vite/storageConfig.ts b/packages/nuxt/src/vite/storageConfig.ts index da94ea4ad1ab..ba72d10b0de7 100644 --- a/packages/nuxt/src/vite/storageConfig.ts +++ b/packages/nuxt/src/vite/storageConfig.ts @@ -3,6 +3,7 @@ import type { Nuxt } from '@nuxt/schema'; import type { Nitro } from 'nitropack/types'; import type { InputPluginOption } from 'rollup'; import { addServerTemplate } from '../vendor/server-template'; +import { stringifyForCodeInjection } from '@sentry/core'; const NITRO_CACHE_VIRTUAL_MODULE_ID = '#nitro/virtual/cache'; const CREATE_CACHE_STORAGE_EXPORT = 'export const createCacheStorage ='; @@ -18,7 +19,7 @@ export function addStorageInstrumentation(nuxt: Nuxt, isLegacyNitro: boolean): v addServerTemplate({ filename: '#sentry/storage-config.mjs', getContents: () => { - return `export const userStorageMounts = ${JSON.stringify(userStorageMounts)};`; + return `export const userStorageMounts = ${stringifyForCodeInjection(userStorageMounts)};`; }, }); diff --git a/packages/nuxt/src/vite/utils.ts b/packages/nuxt/src/vite/utils.ts index ee00b95a95c1..9619318907c0 100644 --- a/packages/nuxt/src/vite/utils.ts +++ b/packages/nuxt/src/vite/utils.ts @@ -1,5 +1,5 @@ import type { Nuxt, ResolvedNuxtTemplate } from '@nuxt/schema'; -import { consoleSandbox } from '@sentry/core'; +import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core'; import * as fs from 'fs'; import * as path from 'path'; import { fileURLToPath } from 'node:url'; @@ -186,7 +186,7 @@ export function constructFunctionReExport(pathWithQuery: string, entryId: string (functionsCode, currFunctionName) => functionsCode.concat( `async function ${currFunctionName}_sentryWrapped(...args) {\n` + - ` const res = await import(${JSON.stringify(entryId)});\n` + + ` const res = await import(${stringifyForCodeInjection(entryId)});\n` + ` return res.${currFunctionName}.call(this, ...args);\n` + '}\n' + `export { ${currFunctionName}_sentryWrapped as ${currFunctionName} };\n`, @@ -196,7 +196,7 @@ export function constructFunctionReExport(pathWithQuery: string, entryId: string .concat( reexportFunctions.reduce( (functionsCode, currFunctionName) => - functionsCode.concat(`export { ${currFunctionName} } from ${JSON.stringify(entryId)};`), + functionsCode.concat(`export { ${currFunctionName} } from ${stringifyForCodeInjection(entryId)};`), '', ), ); diff --git a/packages/nuxt/src/vite/viteServer.ts b/packages/nuxt/src/vite/viteServer.ts index 033dcdc99ce4..56257f79d72e 100644 --- a/packages/nuxt/src/vite/viteServer.ts +++ b/packages/nuxt/src/vite/viteServer.ts @@ -1,6 +1,6 @@ import { addVitePlugin, createResolver } from '@nuxt/kit'; import type { Nuxt } from '@nuxt/schema'; -import { consoleSandbox } from '@sentry/core'; +import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core'; import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite'; import type { Plugin } from 'vite'; import type { SentryNuxtModuleOptions } from '../common/types'; @@ -77,7 +77,7 @@ function sentryServerEntryPlugin(importPaths: string[], onBundled: () => void): } onBundled(); - const imports = importPaths.map(path => `import ${JSON.stringify(path)};`).join(''); + const imports = importPaths.map(path => `import ${stringifyForCodeInjection(path)};`).join(''); return { code: `${imports}${code}`, map: null }; }, }, diff --git a/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts b/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts index 33de134f47cc..09b29813a801 100644 --- a/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts +++ b/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts @@ -1,7 +1,9 @@ import type { CloudflareOptions } from '@sentry/cloudflare'; +import { serveTunnelIntegration } from '@sentry/cloudflare'; import { wrapRequestHandler } from '@sentry/cloudflare/request'; +import { getTunnelPath, SDK_VERSION } from '@sentry/core'; import type { NitroApp } from 'nitropack'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { sentryCloudflareNitroPlugin } from '../../../src/runtime/plugins/sentry-cloudflare.server'; vi.mock('@sentry/cloudflare/request', () => ({ @@ -10,18 +12,36 @@ vi.mock('@sentry/cloudflare/request', () => ({ const DSN = 'https://public@dsn.ingest.sentry.io/1337'; -async function handleRequest(options: CloudflareOptions): Promise { - const nitroApp = { localFetch: vi.fn(), hooks: { hook: vi.fn() } } as unknown as NitroApp; +const NUXT_SDK_METADATA = { + sdk: { + name: 'sentry.javascript.nuxt', + packages: [ + { name: 'npm:@sentry/nuxt', version: SDK_VERSION }, + { name: 'npm:@sentry/cloudflare', version: SDK_VERSION }, + ], + version: SDK_VERSION, + }, +}; + +async function handleRequest( + options: CloudflareOptions, + { path = '/api/db-mysql', method = 'GET', body }: { path?: string; method?: string; body?: string } = {}, +): Promise<{ response: unknown; localFetch: ReturnType }> { + const localFetch = vi.fn(() => new Response('app')); + const nitroApp = { localFetch, hooks: { hook: vi.fn() } } as unknown as NitroApp; sentryCloudflareNitroPlugin(options)(nitroApp); const event = { protocol: 'https:', host: 'example.com', - method: 'GET', - headers: {}, - context: { cf: {}, cloudflare: { context: {} } }, + method, + headers: body ? { 'content-length': String(body.length) } : {}, + body, + context: { cf: {}, cloudflare: { context: { waitUntil: vi.fn(), passThroughOnException: vi.fn() } } }, }; - await nitroApp.localFetch('/api/db-mysql', event as unknown as RequestInit); + const response = await nitroApp.localFetch(path, event as unknown as RequestInit); + + return { response, localFetch }; } describe('sentryCloudflareNitroPlugin', () => { @@ -29,6 +49,10 @@ describe('sentryCloudflareNitroPlugin', () => { vi.mocked(wrapRequestHandler).mockClear(); }); + afterEach(() => { + vi.restoreAllMocks(); + }); + it('passes a defaultIntegrations list that extends the SDK defaults', async () => { await handleRequest({ dsn: DSN }); @@ -53,4 +77,49 @@ describe('sentryCloudflareNitroPlugin', () => { expect.any(Function), ); }); + + it('answers a managed tunnel request with the body Nitro read', async () => { + const actual = await vi.importActual<{ wrapRequestHandler: typeof wrapRequestHandler }>( + '@sentry/cloudflare/request', + ); + vi.mocked(wrapRequestHandler).mockImplementationOnce(actual.wrapRequestHandler); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 200 })); + const envelope = `${JSON.stringify({ dsn: DSN })}\n${JSON.stringify({ type: 'event' })}\n{}`; + + const { response, localFetch } = await handleRequest( + { dsn: DSN, integrations: [serveTunnelIntegration()] }, + { path: getTunnelPath(DSN), method: 'POST', body: envelope }, + ); + + expect((response as Response).status).toBe(200); + expect(fetchSpy).toHaveBeenCalledWith( + expect.stringContaining('dsn.ingest.sentry.io/api/1337/envelope/'), + expect.objectContaining({ method: 'POST' }), + ); + expect(localFetch).not.toHaveBeenCalled(); + }); + + it('sets the Nuxt SDK metadata', async () => { + await handleRequest({ dsn: DSN }); + + expect(wrapRequestHandler).toHaveBeenCalledWith( + expect.objectContaining({ options: expect.objectContaining({ _metadata: NUXT_SDK_METADATA }) }), + expect.any(Function), + ); + }); + + it('sets the Nuxt SDK metadata on Nitro v3', async () => { + const nitroApp = { fetch: vi.fn(), hooks: { hook: vi.fn() } } as unknown as NitroApp & { + fetch: (request: Request) => Promise; + }; + sentryCloudflareNitroPlugin({ dsn: DSN })(nitroApp); + + const request = Object.assign(new Request('https://example.com/'), { runtime: { cloudflare: { context: {} } } }); + await nitroApp.fetch(request); + + expect(wrapRequestHandler).toHaveBeenCalledWith( + expect.objectContaining({ options: expect.objectContaining({ _metadata: NUXT_SDK_METADATA }) }), + expect.any(Function), + ); + }); }); diff --git a/packages/nuxt/test/runtime/utils/database-span-data.test.ts b/packages/nuxt/test/runtime/utils/database-span-data.test.ts index fc4f4b376af8..8d4e19bc82e2 100644 --- a/packages/nuxt/test/runtime/utils/database-span-data.test.ts +++ b/packages/nuxt/test/runtime/utils/database-span-data.test.ts @@ -124,7 +124,7 @@ describe('getDatabaseSpanData', () => { }); describe('SQLite-like connectors', () => { - it.each(['better-sqlite3', 'bun', 'sqlite', 'sqlite3'] as ConnectorName[])( + it.each(['better-sqlite3', 'bun', 'bun-sqlite', 'node-sqlite', 'sqlite', 'sqlite3'] as ConnectorName[])( 'should extract database name for %s', connector => { const config: DatabaseConfig = { @@ -141,7 +141,7 @@ describe('getDatabaseSpanData', () => { }, ); - it.each(['better-sqlite3', 'bun', 'sqlite', 'sqlite3'] as ConnectorName[])( + it.each(['better-sqlite3', 'bun', 'bun-sqlite', 'node-sqlite', 'sqlite', 'sqlite3'] as ConnectorName[])( 'should use default name for %s when name is not provided', connector => { const config: DatabaseConfig = { @@ -156,7 +156,7 @@ describe('getDatabaseSpanData', () => { }, ); - it.each(['better-sqlite3', 'bun', 'sqlite', 'sqlite3'] as ConnectorName[])( + it.each(['better-sqlite3', 'bun', 'bun-sqlite', 'node-sqlite', 'sqlite', 'sqlite3'] as ConnectorName[])( 'should handle missing options for %s', connector => { const config: DatabaseConfig = { diff --git a/packages/nuxt/test/runtime/utils/instrumentDatabase.test.ts b/packages/nuxt/test/runtime/utils/instrumentDatabase.test.ts new file mode 100644 index 000000000000..92e69fab3e22 --- /dev/null +++ b/packages/nuxt/test/runtime/utils/instrumentDatabase.test.ts @@ -0,0 +1,71 @@ +import { DB_NAMESPACE, DB_QUERY_TEXT, DB_SYSTEM_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import * as SentryCore from '@sentry/core'; +import type * as SentryCoreServer from '@sentry/core/server'; +import { flushIfServerless } from '@sentry/core/server'; +import type { Database } from 'db0'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { createDatabasePlugin } from '../../../src/runtime/utils/instrumentDatabase'; + +const span = { setStatus: vi.fn() }; + +vi.mock('@sentry/core/server', async importOriginal => ({ + ...(await importOriginal()), + flushIfServerless: vi.fn(), +})); + +vi.mock('@sentry/core', async importOriginal => ({ + ...(await importOriginal()), + captureException: vi.fn(), + startSpan: vi.fn((_options, callback) => callback(span)), +})); + +function createDatabase(prepare: Database['prepare']): Database { + return { dialect: 'sqlite', prepare, sql: vi.fn(), exec: vi.fn() } as unknown as Database; +} + +describe('createDatabasePlugin', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('captures an error that `prepare` throws and rethrows it', () => { + const error = new Error('no such table: missing'); + const db = createDatabase(() => { + throw error; + }); + + createDatabasePlugin(() => db, { default: { connector: 'bun-sqlite' } }); + + expect(() => db.prepare('SELECT * FROM missing')).toThrow(error); + expect(SentryCore.startSpan).toHaveBeenCalledWith( + expect.objectContaining({ + attributes: expect.objectContaining({ + [DB_QUERY_TEXT]: 'SELECT * FROM missing', + [DB_SYSTEM_NAME]: 'sqlite', + [SENTRY_ORIGIN]: 'auto.db.nuxt', + }), + }), + expect.any(Function), + ); + expect(span.setStatus).toHaveBeenCalledWith({ code: SentryCore.SPAN_STATUS_ERROR, message: 'internal_error' }); + expect(SentryCore.captureException).toHaveBeenCalledWith(error, { + mechanism: { handled: false, type: 'auto.db.nuxt' }, + }); + expect(flushIfServerless).toHaveBeenCalledTimes(1); + }); + + it('names the database system after the dialect, not the connector', async () => { + const statement = { all: vi.fn(), get: vi.fn(), run: vi.fn(), bind: vi.fn() }; + const db = createDatabase(() => statement as unknown as ReturnType); + + createDatabasePlugin(() => db, { default: { connector: 'bun-sqlite' } }); + await db.prepare('SELECT 1').all(); + + expect(SentryCore.startSpan).toHaveBeenCalledWith( + expect.objectContaining({ + attributes: expect.objectContaining({ [DB_SYSTEM_NAME]: 'sqlite', [DB_NAMESPACE]: 'db.sqlite' }), + }), + expect.any(Function), + ); + }); +}); diff --git a/packages/opentelemetry/test/tracerProvider.test.ts b/packages/opentelemetry/test/tracerProvider.test.ts index a844f33e1f37..6dc4f13506ad 100644 --- a/packages/opentelemetry/test/tracerProvider.test.ts +++ b/packages/opentelemetry/test/tracerProvider.test.ts @@ -6,6 +6,7 @@ import { getRootSpan, spanToJSON, startSpanManual, + timestampInSeconds, type Span, withIsolationScope, } from '@sentry/core'; @@ -18,12 +19,15 @@ describe('SentryTracerProvider', () => { }); it('converts `performance.now()` start and end times', () => { + const before = timestampInSeconds(); const start = performance.now(); + const after = timestampInSeconds(); const span = trace.getTracer('test').startSpan('span', { startTime: start }); span.end(start + 25); const { start_timestamp, end_timestamp } = spanToJSON(span as Span); - expect(start_timestamp).toBeCloseTo(Date.now() / 1000, 0); + expect(start_timestamp).toBeGreaterThanOrEqual(before); + expect(start_timestamp).toBeLessThanOrEqual(after); expect(end_timestamp! - start_timestamp).toBeCloseTo(0.025, 6); }); diff --git a/packages/profiling-node/src/utils.ts b/packages/profiling-node/src/utils.ts index 39f95fad1c71..9360c970a634 100644 --- a/packages/profiling-node/src/utils.ts +++ b/packages/profiling-node/src/utils.ts @@ -9,7 +9,14 @@ import type { ProfileChunkItem, SdkInfo, } from '@sentry/core'; -import { createEnvelope, debug, dsnToString, getDebugImagesForResources, uuid4 } from '@sentry/core'; +import { + _INTERNAL_safeDateNow as safeDateNow, + createEnvelope, + debug, + dsnToString, + getDebugImagesForResources, + uuid4, +} from '@sentry/core'; import type { RawChunkCpuProfile } from '@sentry/node-cpu-profiler'; import { isMainThread, threadId } from 'worker_threads'; import { DEBUG_BUILD } from './debug-build'; @@ -164,7 +171,7 @@ export function createEventEnvelopeHeaders( ): EventEnvelopeHeaders { return { event_id: uuid4(), - sent_at: new Date().toISOString(), + sent_at: new Date(safeDateNow()).toISOString(), ...(sdkInfo && { sdk: sdkInfo }), ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }), }; diff --git a/packages/profiling-node/test/envelope-safe-timestamp.test.ts b/packages/profiling-node/test/envelope-safe-timestamp.test.ts new file mode 100644 index 000000000000..c813b7fdff98 --- /dev/null +++ b/packages/profiling-node/test/envelope-safe-timestamp.test.ts @@ -0,0 +1,59 @@ +import { GLOBAL_OBJ } from '@sentry/core'; +import { afterAll, describe, expect, it } from 'vitest'; +import { createEventEnvelopeHeaders } from '../src/utils'; + +const SAFE_RANDOM_SYMBOL = Symbol.for('__SENTRY_SAFE_RANDOM_ID_WRAPPER__'); +const globals = GLOBAL_OBJ as unknown as Record; +const originalRunner = globals[SAFE_RANDOM_SYMBOL]; +const RealDate = Date; +let inSafeContext = false; + +globals[SAFE_RANDOM_SYMBOL] = (callback: () => T): T => { + const previous = inSafeContext; + inSafeContext = true; + try { + return callback(); + } finally { + inSafeContext = previous; + } +}; + +afterAll(() => { + if (originalRunner === undefined) { + Reflect.deleteProperty(globals, SAFE_RANDOM_SYMBOL); + } else { + globals[SAFE_RANDOM_SYMBOL] = originalRunner; + } +}); + +describe('profile envelope timestamp', () => { + it('reads the clock only inside the safe context', () => { + const now = 1_700_000_000_000; + const GuardedDate = class extends RealDate { + public constructor(...args: unknown[]) { + if (args.length === 0 && !inSafeContext) { + throw new Error('Read new Date() outside the safe context'); + } + super(...(args as [number | string | Date])); + } + + public static now(): number { + if (!inSafeContext) { + throw new Error('Read Date.now() outside the safe context'); + } + return now; + } + }; + + (globalThis as { Date: DateConstructor }).Date = GuardedDate as DateConstructor; + try { + expect(createEventEnvelopeHeaders(undefined, undefined)).toMatchObject({ + event_id: expect.any(String), + sent_at: new RealDate(now).toISOString(), + }); + expect(inSafeContext).toBe(false); + } finally { + (globalThis as { Date: DateConstructor }).Date = RealDate; + } + }); +}); diff --git a/packages/react/src/sdk.ts b/packages/react/src/sdk.ts index 3e4768ae42ed..4b868f7858ec 100644 --- a/packages/react/src/sdk.ts +++ b/packages/react/src/sdk.ts @@ -5,7 +5,7 @@ import { setContext, } from '@sentry/browser'; import type { Client } from '@sentry/core'; -import { applySdkMetadata, setNormalizeStringifier } from '@sentry/core'; +import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, setNormalizeStringifier } from '@sentry/core'; import { version } from 'react'; import { isSyntheticEvent } from './isSyntheticEvent'; @@ -14,7 +14,7 @@ import { isSyntheticEvent } from './isSyntheticEvent'; */ export function init(options: BrowserOptions): Client | undefined { const opts = { - ...options, + ..._INTERNAL_captureOptionsSetByUser(options), }; applySdkMetadata(opts, 'react'); diff --git a/packages/remix/src/vite/routeManifestPlugin.ts b/packages/remix/src/vite/routeManifestPlugin.ts index 8328af5de060..6134dede7933 100644 --- a/packages/remix/src/vite/routeManifestPlugin.ts +++ b/packages/remix/src/vite/routeManifestPlugin.ts @@ -1,18 +1,9 @@ +import { stringifyForCodeInjection } from '@sentry/core'; import * as path from 'path'; import type { Plugin } from 'vite'; import { createRemixRouteManifest } from '../config/createRemixRouteManifest'; import type { SentryRemixVitePluginOptions } from './types'; -/** - * Escapes a JSON string for safe embedding in HTML script tags. - * JSON.stringify alone doesn't escape or