diff --git a/.cursor/BUGBOT.md b/.cursor/BUGBOT.md
index 4f0a55cbe326..29f9a82844ea 100644
--- a/.cursor/BUGBOT.md
+++ b/.cursor/BUGBOT.md
@@ -14,7 +14,6 @@ Keep reviews high-signal. Prefer actionable, high-confidence findings over specu
### Security Vulnerabilities
- 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 `
@@ -20,4 +24,5 @@ const fetchData = async () => {
+
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/cloudflare/sentry.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/cloudflare/sentry.ts
deleted file mode 100644
index 35f7567b28cf..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/cloudflare/sentry.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { defineNitroPlugin } from '#imports';
-import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins';
-
-export default defineNitroPlugin(
- sentryCloudflareNitroPlugin({
- dsn: 'https://public@dsn.ingest.sentry.io/1337',
- tracesSampleRate: 1.0,
- enableLogs: true,
- tunnel: 'http://localhost:3031/', // proxy server
- // Several tests trigger the same server error one after another, which Dedupe would drop.
- integrations: integrations => [...integrations.filter(integration => integration.name !== 'Dedupe')],
- }),
-);
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/nuxt.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/nuxt.config.ts
index 267dbff7e478..e819ea167be6 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/nuxt.config.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/nuxt.config.ts
@@ -36,10 +36,10 @@ export default defineNuxtConfig({
},
nitro: {
...(cloudflare && {
- preset: 'cloudflare_module',
+ // Like `cloudflare_module`, and also exports the `$DurableObject` class from the Worker. The Sentry module sets
+ // up the SDK from `sentry.cloudflare.config.ts`, because the Nitro preset does not use `sentry.server.config.ts`.
+ preset: 'cloudflare_durable',
cloudflare: { nodeCompat: true, deployConfig: false },
- // Sets up the SDK on Cloudflare, where the Nitro preset does not use `sentry.server.config.ts`.
- plugins: ['~~/cloudflare/sentry.ts'],
// The bundled `mysql` driver pulls in `readable-stream`, whose base `require('stream')` has no
// usable prototype under Nitro's unenv polyfill (throws `superCtor.prototype ... undefined`).
// Alias it to workerd's native `node:stream`, which has a real `Readable`.
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/package.json b/dev-packages/e2e-tests/test-applications/nuxt-4/package.json
index aa77c0425098..dd4d1000d40d 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/package.json
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/package.json
@@ -36,7 +36,7 @@
},
"devDependencies": {
"@playwright/test": "1.64.1",
- "@sentry/conventions": "0.35.0",
+ "@sentry/conventions": "0.36.0",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
"wrangler": "^4.72.0"
},
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/public/humans.txt b/dev-packages/e2e-tests/test-applications/nuxt-4/public/humans.txt
new file mode 100644
index 000000000000..445ab6da73d9
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/public/humans.txt
@@ -0,0 +1 @@
+Team: Sentry
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/sentry.cloudflare.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/sentry.cloudflare.config.ts
new file mode 100644
index 000000000000..df5881da2623
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/sentry.cloudflare.config.ts
@@ -0,0 +1,12 @@
+import { defineCloudflareOptions } from '@sentry/cloudflare';
+
+// On Cloudflare, the Sentry Nuxt module wraps the Worker with `withSentry` and these options. Node, Bun and Deno use
+// `sentry.server.config.ts`.
+export default defineCloudflareOptions({
+ dsn: 'https://public@dsn.ingest.sentry.io/1337',
+ tracesSampleRate: 1.0,
+ enableLogs: true,
+ tunnel: 'http://localhost:3031/', // proxy server
+ // Several tests trigger the same server error one after another, which Dedupe would drop.
+ integrations: integrations => integrations.filter(integration => integration.name !== 'Dedupe'),
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/index.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/index.ts
new file mode 100644
index 000000000000..9a1e123d07a1
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/index.ts
@@ -0,0 +1,10 @@
+import { defineEventHandler, getRequestURL } from '#imports';
+
+// With the `cloudflare_durable` preset, `durableFetch` sends a request to the Durable Object of Nitro, which handles it
+// with the same Nitro app.
+export default defineEventHandler(async event => {
+ const { durableFetch } = event.context.cloudflare as { durableFetch: (request: Request) => Promise };
+ const response = await durableFetch(new Request(new URL('/api/durable-object/target', getRequestURL(event))));
+
+ return response.json();
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/target.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/target.ts
new file mode 100644
index 000000000000..f454c84cba34
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/target.ts
@@ -0,0 +1,5 @@
+import { defineEventHandler } from '#imports';
+
+export default defineEventHandler(event => {
+ return { durable: !!(event.context.cloudflare as { durable?: unknown } | undefined)?.durable };
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/build-injection.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/build-injection.test.ts
index 6aeef1e31e88..698206fea06d 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/build-injection.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/build-injection.test.ts
@@ -57,7 +57,7 @@ test.describe('Orchestrion build-time injection', () => {
});
});
-const NO_SERVER_CONFIG = 'Cloudflare: `sentryCloudflareNitroPlugin` sets up the SDK, not `sentry.server.config.ts`';
+const NO_SERVER_CONFIG = 'Cloudflare: `sentry.cloudflare.config.ts` sets up the SDK, not `sentry.server.config.ts`';
test.describe('Sentry server config injection', () => {
test('evaluates Sentry.init before nitro runs its plugins', () => {
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts
index 644a371447c0..a1e9672587d7 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts
@@ -1,10 +1,8 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';
import { isViteServer, NITRO_ONLY } from './isViteServer';
-import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime';
test.skip(isViteServer, NITRO_ONLY);
-test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION);
test.describe('Cache Instrumentation', () => {
const SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key';
@@ -14,6 +12,7 @@ test.describe('Cache Instrumentation', () => {
const spans = await collectStreamedSpansUntilSegment(
'nuxt-4',
span => span.attributes['url.path']?.value === '/api/cache-test',
+ span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt',
);
return spans.filter(span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt');
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database-multi.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database-multi.streaming-lifecycle.test.ts
index 70fe76fb4c5c..2a59b09a22dc 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database-multi.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database-multi.streaming-lifecycle.test.ts
@@ -1,15 +1,15 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils';
import { isViteServer, NITRO_ONLY } from './isViteServer';
-import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime';
+import { DB_ORIGIN, DB_SYSTEM_NAME, RUNTIME } from './runtime';
test.skip(isViteServer, NITRO_ONLY);
-test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION);
async function collectDbSpans() {
const spans = await collectStreamedSpansUntilSegment(
'nuxt-4',
span => span.attributes['url.path']?.value === '/api/db-multi-test',
+ span => getSpanOp(span) === 'db.query',
);
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-multi-test');
@@ -30,9 +30,9 @@ test.describe('multiple database instances', () => {
expect(selectSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT default_table' },
'db.query.text': { type: 'string', value: 'SELECT * FROM default_table WHERE id = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'db.sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }),
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -49,9 +49,9 @@ test.describe('multiple database instances', () => {
expect(selectSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT user_profiles' },
'db.query.text': { type: 'string', value: 'SELECT * FROM user_profiles WHERE id = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'users_db.sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }),
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -68,9 +68,9 @@ test.describe('multiple database instances', () => {
expect(selectSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT events' },
'db.query.text': { type: 'string', value: 'SELECT * FROM events WHERE id = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' } }),
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -90,23 +90,23 @@ test.describe('multiple database instances', () => {
expect(sessionSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT sessions' },
'db.query.text': { type: 'string', value: 'SELECT * FROM sessions WHERE id = ?' },
- 'db.namespace': { type: 'string', value: 'db.sqlite' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }),
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
expect(accountSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT accounts' },
'db.query.text': { type: 'string', value: 'SELECT * FROM accounts WHERE id = ?' },
- 'db.namespace': { type: 'string', value: 'users_db.sqlite' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }),
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
expect(metricSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT metrics' },
'db.query.text': { type: 'string', value: 'SELECT * FROM metrics WHERE id = ?' },
- 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' } }),
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
// All spans belong to the same trace as the request's root span
@@ -129,18 +129,18 @@ test.describe('multiple database instances', () => {
expect(logsInsertSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'INSERT logs' },
'db.query.text': { type: 'string', value: 'INSERT INTO logs (message) VALUES (?)' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'db.sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }),
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
expect(auditLogsInsertSpan).toBeDefined();
expect(auditLogsInsertSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'INSERT audit_logs' },
'db.query.text': { type: 'string', value: 'INSERT INTO audit_logs (action) VALUES (?)' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'users_db.sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }),
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts
index 74ca13e02b93..7729f0e5251c 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts
@@ -1,15 +1,22 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils';
import { isViteServer, NITRO_ONLY } from './isViteServer';
-import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime';
+import { DB_ORIGIN, DB_SYSTEM_NAME, RUNTIME } from './runtime';
test.skip(isViteServer, NITRO_ONLY);
-test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION);
+
+// `@sentry/cloudflare` does not capture D1 errors, so the error hook of Nitro captures them on Cloudflare. The D1
+// error has a `cause`, so the event links the errors with an `exception_id`.
+const DB_ERROR_MECHANISM =
+ RUNTIME === 'cloudflare'
+ ? { handled: false, type: 'auto.function.nuxt.nitro', exception_id: 0 }
+ : { handled: false, type: 'auto.db.nuxt' };
async function collectDbSpans() {
const spans = await collectStreamedSpansUntilSegment(
'nuxt-4',
span => span.attributes['url.path']?.value === '/api/db-test',
+ span => getSpanOp(span) === 'db.query',
);
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-test');
@@ -22,17 +29,20 @@ test.describe('database integration', () => {
await request.get('/api/db-test?method=prepare-get');
- const dbSpan = (await dbSpansPromise).find(span => span.name === 'SELECT users');
+ const dbSpans = await dbSpansPromise;
+ const dbSpan = dbSpans.find(span => span.name === 'SELECT users');
- expect(dbSpan).toBeDefined();
+ // On Cloudflare, `@sentry/cloudflare` and the database instrumentation of `@sentry/nuxt` must not both create a
+ // span for the same D1 query.
+ expect(dbSpans.filter(span => span.name === 'SELECT users')).toHaveLength(1);
expect(dbSpan?.status).toBe('ok');
expect(dbSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT users' },
'db.query.text': { type: 'string', value: 'SELECT * FROM users WHERE id = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'db.sqlite' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }),
'sentry.op': { type: 'string', value: 'db.query' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -47,8 +57,8 @@ test.describe('database integration', () => {
expect(dbSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT products' },
'db.query.text': { type: 'string', value: 'SELECT * FROM products WHERE price > ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -63,8 +73,8 @@ test.describe('database integration', () => {
expect(dbSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'INSERT orders' },
'db.query.text': { type: 'string', value: 'INSERT INTO orders (customer, amount) VALUES (?, ?)' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -79,8 +89,8 @@ test.describe('database integration', () => {
expect(dbSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT items' },
'db.query.text': { type: 'string', value: 'SELECT * FROM items WHERE category = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -98,8 +108,8 @@ test.describe('database integration', () => {
type: 'string',
value: 'INSERT INTO messages (content, created_at) VALUES (?, ?)',
},
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -115,8 +125,8 @@ test.describe('database integration', () => {
expect(insertSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'INSERT logs' },
'db.query.text': { type: 'string', value: `INSERT INTO logs (message, level) VALUES (?, ?)` },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
// DDL statements are summarized as `{operation} {table}` as well, with the statement on the attribute
@@ -134,7 +144,7 @@ test.describe('database integration', () => {
test('captures database error and marks span as failed', async ({ request }) => {
const errorPromise = waitForError('nuxt-4', errorEvent => {
return !!errorEvent?.exception?.values?.some(
- value => value.mechanism?.type === 'auto.db.nuxt' && value.value?.includes('no such table'),
+ value => value.mechanism?.type === DB_ERROR_MECHANISM.type && value.value?.includes('no such table'),
);
});
@@ -146,14 +156,11 @@ test.describe('database integration', () => {
const [error, dbSpans] = await Promise.all([errorPromise, dbSpansPromise]);
- const dbException = error.exception?.values?.find(value => value.mechanism?.type === 'auto.db.nuxt');
+ const dbException = error.exception?.values?.find(value => value.mechanism?.type === DB_ERROR_MECHANISM.type);
expect(dbException).toBeDefined();
expect(dbException?.value).toContain('no such table');
- expect(dbException?.mechanism).toEqual({
- handled: false,
- type: 'auto.db.nuxt',
- });
+ expect(dbException?.mechanism).toEqual(DB_ERROR_MECHANISM);
const dbSpan = dbSpans.find(span => span.name === 'SELECT nonexistent_table');
@@ -162,14 +169,16 @@ test.describe('database integration', () => {
expect(dbSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT nonexistent_table' },
'db.query.text': { type: 'string', value: 'SELECT * FROM nonexistent_table WHERE invalid_column = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
test('captures breadcrumb for db.exec() queries', async ({ request }) => {
const errorPromise = waitForError('nuxt-4', errorEvent => {
- return !!errorEvent?.exception?.values?.some(value => value.mechanism?.type === 'auto.db.nuxt');
+ return !!errorEvent?.exception?.values?.some(
+ value => value.mechanism?.type === DB_ERROR_MECHANISM.type && value.value?.includes('no such table'),
+ );
});
await request.get('/api/db-test?method=error').catch(() => {
@@ -184,7 +193,11 @@ test.describe('database integration', () => {
expect(dbBreadcrumb).toBeDefined();
expect(dbBreadcrumb?.message).toBe(`INSERT INTO logs (message, level) VALUES (?, ?)`);
- expect(dbBreadcrumb?.data?.['db.query.text']).toBe(`INSERT INTO logs (message, level) VALUES (?, ?)`);
+ expect(dbBreadcrumb?.data).toMatchObject(
+ RUNTIME === 'cloudflare'
+ ? { 'db.operation.name': 'exec' }
+ : { 'db.query.text': `INSERT INTO logs (message, level) VALUES (?, ?)` },
+ );
});
test('multiple database operations in single request create multiple spans', async ({ request }) => {
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/durable-object.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/durable-object.streaming-lifecycle.test.ts
new file mode 100644
index 000000000000..72449a714ea9
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/durable-object.streaming-lifecycle.test.ts
@@ -0,0 +1,24 @@
+import { expect, test } from '@playwright/test';
+import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+import { RUNTIME } from './runtime';
+
+test.skip(RUNTIME !== 'cloudflare', 'Only the Cloudflare build has the Durable Object of Nitro');
+
+test('traces the request that the Worker sends to the Durable Object of Nitro', async ({ request }) => {
+ const workerSpanPromise = waitForStreamedSpan(
+ 'nuxt-4',
+ span => span.is_segment === true && span.attributes['url.path']?.value === '/api/durable-object',
+ );
+ const durableObjectSpanPromise = waitForStreamedSpan(
+ 'nuxt-4',
+ span => span.is_segment === true && span.attributes['url.path']?.value === '/api/durable-object/target',
+ );
+
+ const response = await request.get('/api/durable-object');
+ expect(await response.json()).toEqual({ durable: true });
+
+ const [workerSpan, durableObjectSpan] = await Promise.all([workerSpanPromise, durableObjectSpanPromise]);
+
+ expect(getSpanOp(durableObjectSpan)).toBe('http.server');
+ expect(durableObjectSpan.trace_id).toBe(workerSpan.trace_id);
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts
index 195cc9b10567..d74f31e64e13 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts
@@ -2,10 +2,8 @@ import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils';
import { IMPORT_SURFACES } from './importSurfaces';
import { isViteServer, NITRO_ONLY } from './isViteServer';
-import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime';
test.skip(isViteServer, NITRO_ONLY);
-test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION);
// Nitro runs every file in `server/middleware/` on every request, so each surface tells its spans apart by
// middleware name. `nuxt/server` has no object syntax (`onRequest`, `onBeforeResponse`) and no `eventHandler`
@@ -31,7 +29,11 @@ const MIDDLEWARE = {
} as const;
async function collectRequestSpans(path = '/api/middleware-test') {
- const spans = await collectStreamedSpansUntilSegment('nuxt-4', span => span.attributes['url.path']?.value === path);
+ const spans = await collectStreamedSpansUntilSegment(
+ 'nuxt-4',
+ span => span.attributes['url.path']?.value === path,
+ span => getSpanOp(span) === 'middleware',
+ );
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === path);
return spans.filter(span => span.trace_id === rootSpan?.trace_id);
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/runtime.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/runtime.ts
index f3640262c4db..ceb8bafa41b7 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/runtime.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/runtime.ts
@@ -10,10 +10,10 @@ export const MONGOOSE_UNSUPPORTED = 'Cloudflare: Nitro cannot bundle the `mongod
export const SERVER_ORIGIN = RUNTIME === 'cloudflare' ? 'auto.http.cloudflare' : 'auto.http.http_server';
-// The Cloudflare variant builds without `sentry.server.config.ts`, as the Cloudflare setup of `@sentry/nuxt` documents.
-// The module adds the db0, storage, cache and middleware instrumentation only with that file.
-export const NO_SERVER_CONFIG_INSTRUMENTATION =
- 'Cloudflare: `@sentry/nuxt` instruments db0, storage, cache and middleware only with a `sentry.server.config.ts`';
+// On Cloudflare, the databases are D1 databases. `@sentry/cloudflare` creates the spans of their queries, and
+// `@sentry/nuxt` leaves them out of its database instrumentation.
+export const DB_SYSTEM_NAME = RUNTIME === 'cloudflare' ? 'cloudflare-d1' : 'sqlite';
+export const DB_ORIGIN = RUNTIME === 'cloudflare' ? 'auto.db.cloudflare.d1' : 'auto.db.nuxt';
/** The command and arguments that start the built server on the runtime of the variant. */
export function getServerCommand(preload?: string): [string, string[]] {
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage-aliases.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage-aliases.streaming-lifecycle.test.ts
index b9eb33fc8f1d..94ff4270e4e4 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage-aliases.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage-aliases.streaming-lifecycle.test.ts
@@ -1,13 +1,15 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';
import { isViteServer, NITRO_ONLY } from './isViteServer';
-import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime';
test.skip(isViteServer, NITRO_ONLY);
-test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION);
async function collectStorageSpans(route: string) {
- const spans = await collectStreamedSpansUntilSegment('nuxt-4', span => span.attributes['url.path']?.value === route);
+ const spans = await collectStreamedSpansUntilSegment(
+ 'nuxt-4',
+ span => span.attributes['url.path']?.value === route,
+ span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt',
+ );
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === route);
return spans.filter(
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts
index a602f881c3cc..5f8ef9ccd540 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts
@@ -1,13 +1,15 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';
import { isViteServer, NITRO_ONLY } from './isViteServer';
-import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime';
test.skip(isViteServer, NITRO_ONLY);
-test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION);
async function collectStorageSpans(route: string) {
- const spans = await collectStreamedSpansUntilSegment('nuxt-4', span => span.attributes['url.path']?.value === route);
+ const spans = await collectStreamedSpansUntilSegment(
+ 'nuxt-4',
+ span => span.attributes['url.path']?.value === route,
+ span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt',
+ );
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === route);
return spans.filter(
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.client.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.client.streaming-lifecycle.test.ts
index 2563dd037d2c..cc0161fab24d 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.client.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.client.streaming-lifecycle.test.ts
@@ -1,5 +1,12 @@
+import { URL_FULL } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
-import { collectStreamedSpansUntilSegment, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+import {
+ collectStreamedSpansUntilSegment,
+ getSpanOp,
+ waitForStreamedSpan,
+ waitForStreamedSpans,
+} from '@sentry-internal/test-utils';
+import { isViteServer } from './isViteServer';
test('sends a pageload root span with a parameterized URL', async ({ page }) => {
const pageloadSpanPromise = waitForStreamedSpan('nuxt-4', span => {
@@ -126,3 +133,27 @@ test('sends component tracking spans when `trackComponents` is enabled', async (
}),
});
});
+
+// Nuxt fetches its build manifest in the browser, for example to find prerendered pages. A span for it can prolong the pageload.
+test('does not send a span for the build manifest request', async ({ page }) => {
+ test.skip(isViteServer, 'The Vite server builds no app manifest when it prerenders no routes');
+
+ const httpClientUrls: string[] = [];
+ const dataRequestSpanPromise = waitForStreamedSpans('nuxt-4', spans => {
+ httpClientUrls.push(
+ ...spans.filter(span => getSpanOp(span) === 'http.client').map(span => `${span.attributes[URL_FULL]?.value}`),
+ );
+ return httpClientUrls.some(url => url.includes('/api/test-param/build-manifest'));
+ });
+ const manifestResponsePromise = page.waitForResponse(response => response.url().includes('/_nuxt/builds/meta/'));
+
+ await page.goto('/test-param/build-manifest');
+ // Only fetches the manifest if Nuxt has not fetched it already.
+ await page.getByText('Fetch App Manifest').click();
+ await manifestResponsePromise;
+ // A manifest span would arrive before the span of this later request.
+ await page.getByText('Fetch Server Data').click();
+ await dataRequestSpanPromise;
+
+ expect(httpClientUrls).not.toContainEqual(expect.stringContaining('/_nuxt/builds/'));
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.static-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.static-lifecycle.test.ts
index 96fedb422257..451ab2f1a4d9 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.static-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.static-lifecycle.test.ts
@@ -1,4 +1,4 @@
-import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
+import { SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
import { waitForError, waitForTransaction } from '@sentry-internal/test-utils';
@@ -21,27 +21,30 @@ test('sends a server action transaction on pageload', async ({ page }) => {
);
});
-test('does not send transactions for build asset folder "_nuxt"', async ({ page }) => {
- let buildAssetFolderOccurred = false;
-
- waitForTransaction('nuxt-4', transactionEvent => {
- if (transactionEvent.transaction?.match(/^GET \/_nuxt\//)) {
- buildAssetFolderOccurred = true;
- }
- return false; // expects to return a boolean (but not relevant here)
- });
-
- const transactionEventPromise = waitForTransaction('nuxt-4', transactionEvent => {
- return transactionEvent.transaction.includes('GET /test-param/');
+[
+ // Nuxt build output that the HTTP integration does not ignore.
+ '/_nuxt/builds/latest.json',
+ '/_nuxt/entry.js.map',
+ // File from `public/` that the HTTP integration does not ignore.
+ '/humans.txt',
+ // Common static file that the HTTP integration ignores.
+ '/favicon.ico',
+].forEach(path => {
+ test(`does not send a server transaction for the file ${path}`, async ({ baseURL }) => {
+ const transactionPaths = await getServerTransactionPathsUntilPage(`${baseURL}`, path);
+
+ expect(transactionPaths).not.toContain(path);
});
+});
- await page.goto('/test-param/1234');
-
- const transactionEvent = await transactionEventPromise;
-
- expect(buildAssetFolderOccurred).toBe(false);
+// Routes that look like build output. They also show that the helper sees sent transactions, so the tests above cannot
+// pass by accident.
+['/test-param/jane.doe', '/api/test-param/data.json', '/test-param/_nuxt/'].forEach(path => {
+ test(`sends a server transaction for the route ${path}`, async ({ baseURL }) => {
+ const transactionPaths = await getServerTransactionPathsUntilPage(`${baseURL}`, path);
- expect(transactionEvent.transaction).toBe('GET /test-param/:param()');
+ expect(transactionPaths).toContain(path);
+ });
});
test('captures server API calls made with Nitro $fetch', async ({ page }) => {
@@ -61,3 +64,22 @@ test('captures server API calls made with Nitro $fetch', async ({ page }) => {
expect(httpClientSpan.parent_span_id).toEqual(httpServerFetchSpan.contexts.trace.span_id);
expect(httpClientSpan.op).toEqual('http.client');
});
+
+/**
+ * Requests `path`, then a page. Returns the `url.path` of each server transaction up to the page's transaction,
+ * which arrives after any transaction for `path`.
+ */
+async function getServerTransactionPathsUntilPage(baseURL: string, path: string): Promise {
+ const pagePath = `/test-param/after${path.replace(/\W+/g, '-')}`;
+ const transactionPaths: string[] = [];
+ const pageTransactionPromise = waitForTransaction('nuxt-4', transactionEvent => {
+ transactionPaths.push(`${transactionEvent.contexts?.trace?.data?.[URL_PATH]}`);
+ return transactionPaths.includes(pagePath);
+ });
+
+ await fetch(`${baseURL}${path}`);
+ await fetch(`${baseURL}${pagePath}`);
+ await pageTransactionPromise;
+
+ return transactionPaths;
+}
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.streaming-lifecycle.test.ts
index 25d54633ebf7..5523bced86b5 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.streaming-lifecycle.test.ts
@@ -1,5 +1,11 @@
+import { URL_PATH } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
-import { collectStreamedSpans, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+import {
+ collectStreamedSpans,
+ getSpanOp,
+ waitForStreamedSpan,
+ waitForStreamedSpans,
+} from '@sentry-internal/test-utils';
import { IMPORT_SURFACES } from './importSurfaces';
import { isViteServer, NITRO_ONLY } from './isViteServer';
import { SERVER_ORIGIN } from './runtime';
@@ -17,28 +23,30 @@ test('sends a server root span on pageload', async ({ page }) => {
expect(serverSpan.attributes['sentry.origin']?.value).toBe(SERVER_ORIGIN);
});
-test('does not send spans for build asset folder "_nuxt"', async ({ page }) => {
- let buildAssetFolderOccurred = false;
-
- waitForStreamedSpan('nuxt-4', span => {
- if (span.is_segment && /^GET \/_nuxt\//.test(span.name)) {
- buildAssetFolderOccurred = true;
- }
- return false; // expects to return a boolean (but not relevant here)
- });
-
- const serverSpanPromise = waitForStreamedSpan('nuxt-4', span => {
- return span.is_segment && span.name.includes('GET /test-param/');
+[
+ // Nuxt build output that the HTTP integration does not ignore.
+ '/_nuxt/builds/latest.json',
+ '/_nuxt/entry.js.map',
+ // File from `public/` that the HTTP integration does not ignore.
+ '/humans.txt',
+ // Common static file that the HTTP integration ignores.
+ '/favicon.ico',
+].forEach(path => {
+ test(`does not send a server span for the file ${path}`, async ({ baseURL }) => {
+ const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);
+
+ expect(segmentPaths).not.toContain(path);
});
+});
- await page.goto('/test-param/1234');
-
- const serverSpan = await serverSpanPromise;
-
- expect(buildAssetFolderOccurred).toBe(false);
+// Routes that look like build output. They also show that the helper sees sent segments, so the tests above cannot
+// pass by accident.
+['/test-param/jane.doe', '/api/test-param/data.json', '/test-param/_nuxt/'].forEach(path => {
+ test(`sends a server span for the route ${path}`, async ({ baseURL }) => {
+ const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);
- expect(serverSpan.name).toBe('GET /test-param/:param()');
- expect(serverSpan.attributes['sentry.segment.name.source']?.value).toBe('route');
+ expect(segmentPaths).toContain(path);
+ });
});
IMPORT_SURFACES.forEach(({ name, apiPrefix }) => {
@@ -76,3 +84,22 @@ IMPORT_SURFACES.forEach(({ name, apiPrefix }) => {
expect(httpClientSpan?.parent_span_id).toBe(serverSegmentSpan?.span_id);
});
});
+
+/**
+ * Requests `path`, then a page. Returns the `url.path` of each server segment up to the page's segment, which arrives
+ * after any segment for `path`.
+ */
+async function getServerSegmentPathsUntilPage(baseURL: string, path: string): Promise {
+ const pagePath = `/test-param/after${path.replace(/\W+/g, '-')}`;
+ const segmentPaths: string[] = [];
+ const pageSegmentPromise = waitForStreamedSpans('nuxt-4', spans => {
+ segmentPaths.push(...spans.filter(span => span.is_segment).map(span => `${span.attributes[URL_PATH]?.value}`));
+ return segmentPaths.includes(pagePath);
+ });
+
+ await fetch(`${baseURL}${path}`);
+ await fetch(`${baseURL}${pagePath}`);
+ await pageSegmentPromise;
+
+ return segmentPaths;
+}
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.streaming-lifecycle.test.ts
index 696f7752d3c9..ab4781e5950e 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.streaming-lifecycle.test.ts
@@ -3,11 +3,7 @@ import { expect, test } from '@playwright/test';
import { collectStreamedSpans, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
import { IMPORT_SURFACES } from './importSurfaces';
import { isViteServer, NITRO_ONLY } from './isViteServer';
-import { RUNTIME, SERVER_ORIGIN } from './runtime';
-
-// `sentryCloudflareNitroPlugin` takes the trace data of the meta tags when the request starts, before the route
-// names the segment.
-const CLOUDFLARE_META_TAGS_BEFORE_ROUTE = 'Cloudflare meta tags are created before the route is known';
+import { SERVER_ORIGIN } from './runtime';
async function getBaggageMetaTagAndServerSpan(request: APIRequestContext, path: string) {
const serverSpanPromise = waitForStreamedSpan('nuxt-4', span => {
@@ -25,22 +21,12 @@ test.describe('distributed tracing', () => {
const PARAM = 's0me-param';
test('puts the parametrized route in the baggage meta tag', async ({ request }) => {
- test.skip(RUNTIME === 'cloudflare', CLOUDFLARE_META_TAGS_BEFORE_ROUTE);
-
const { baggageMetaTagContent, serverSpan } = await getBaggageMetaTagAndServerSpan(request, `/test-param/${PARAM}`);
expect(baggageMetaTagContent).toContain(`sentry-trace_id=${serverSpan.trace_id}`);
// URL-encoded for parametrized 'GET /test-param/s0me-param' -> `GET /test-param/:param`
expect(baggageMetaTagContent).toContain(`sentry-transaction=GET%20%2Ftest-param%2F%3Aparam`);
});
- test('leaves the transaction out of the baggage meta tag on Cloudflare', async ({ request }) => {
- test.skip(RUNTIME !== 'cloudflare', CLOUDFLARE_META_TAGS_BEFORE_ROUTE);
-
- const { baggageMetaTagContent, serverSpan } = await getBaggageMetaTagAndServerSpan(request, `/test-param/${PARAM}`);
- expect(baggageMetaTagContent).toContain(`sentry-trace_id=${serverSpan.trace_id}`);
- expect(baggageMetaTagContent).not.toContain('sentry-transaction=');
- });
-
test('capture a distributed pageload trace', async ({ page }) => {
const clientSpanPromise = waitForStreamedSpan('nuxt-4', span => {
return (
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/wrangler.jsonc b/dev-packages/e2e-tests/test-applications/nuxt-4/wrangler.jsonc
index 35ba0deb951f..39972b0ef6ad 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-4/wrangler.jsonc
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/wrangler.jsonc
@@ -20,4 +20,9 @@
"database_id": "00000000-0000-0000-0000-000000000003",
},
],
+ // The binding name and the class that the `cloudflare_durable` preset of Nitro use.
+ "durable_objects": {
+ "bindings": [{ "name": "$DurableObject", "class_name": "$DurableObject" }],
+ },
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["$DurableObject"] }],
}
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/app/app.vue b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/app/app.vue
deleted file mode 100644
index edd3b5d91e9a..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/app/app.vue
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
Nuxt on Cloudflare
-
{{ data }}
-
-
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/nuxt.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/nuxt.config.ts
deleted file mode 100644
index 107f439a3c53..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/nuxt.config.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-// https://nuxt.com/docs/api/configuration/nuxt-config
-export default defineNuxtConfig({
- compatibilityDate: '2025-06-06',
- modules: ['@sentry/nuxt/module'],
- nitro: {
- preset: 'cloudflare_module',
- cloudflare: {
- nodeCompat: true,
- deployConfig: false,
- },
- },
-});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/package.json b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/package.json
deleted file mode 100644
index b681f9ed4b51..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/package.json
+++ /dev/null
@@ -1,32 +0,0 @@
-{
- "name": "nuxt-5-cloudflare",
- "type": "module",
- "private": true,
- "scripts": {
- "build": "nuxt build",
- "dev": "nuxt dev",
- "preview": "wrangler dev --var \"E2E_TEST_DSN:$E2E_TEST_DSN\" --port 3030 --log-level=$(test $CI && echo 'none' || echo 'log')",
- "test": "playwright test",
- "test:build": "pnpm install && pnpm build",
- "test:assert": "pnpm test"
- },
- "//": [
- "Nuxt v5 is only on the Nuxt nightlies, like the `nuxt-5` app.",
- "`ofetch` is a dependency of `nuxt`, which Nuxt's virtual `fetch.server.mjs` can't resolve from the app, see `nuxt-5`."
- ],
- "dependencies": {
- "@sentry/nuxt": "file:../../packed/sentry-nuxt-packed.tgz",
- "@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz",
- "nuxt": "npm:nuxt-nightly@5x",
- "ofetch": "^2.0.0-alpha.3",
- "vue": "^3.5.41"
- },
- "devDependencies": {
- "@playwright/test": "1.64.1",
- "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "wrangler": "^4.72.0"
- },
- "sentryTest": {
- "optional": true
- }
-}
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/playwright.config.mjs
deleted file mode 100644
index 4a688103e068..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/playwright.config.mjs
+++ /dev/null
@@ -1,5 +0,0 @@
-import { getPlaywrightConfig } from '@sentry-internal/test-utils';
-
-const config = getPlaywrightConfig({ startCommand: 'pnpm preview', port: 3030 });
-
-export default config;
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/anchor.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/anchor.ts
deleted file mode 100644
index dbaf5fea80d5..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/anchor.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { defineHandler } from 'nitro';
-
-// A plain route for tests to request.
-export default defineHandler(() => 'ok');
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/internal.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/internal.ts
deleted file mode 100644
index fd0ec635de08..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/internal.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { defineHandler } from 'nitro';
-
-// Fetched internally while the page renders on the server.
-export default defineHandler(() => 'internal');
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/plugins/sentry.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/plugins/sentry.ts
deleted file mode 100644
index 36ce35d46765..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/plugins/sentry.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { definePlugin } from 'nitro';
-import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins';
-
-export default definePlugin(
- sentryCloudflareNitroPlugin({
- dsn: 'https://public@dsn.ingest.sentry.io/1337',
- tracesSampleRate: 1.0,
- tunnel: 'http://localhost:3031/', // proxy server
- }),
-);
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tests/internal-fetch.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tests/internal-fetch.test.ts
deleted file mode 100644
index f3eed2d6e10e..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tests/internal-fetch.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { expect, test } from '@playwright/test';
-import type { SerializedStreamedSpan } from '@sentry-internal/test-utils';
-import { getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils';
-
-function getUrlPath(span: SerializedStreamedSpan): string | undefined {
- const attribute = span.attributes['url.path'];
-
- return attribute?.type === 'string' ? attribute.value : undefined;
-}
-
-test('does not instrument the internal `$fetch` of a server-rendered page as its own request', async ({ request }) => {
- // One listener, so it gets every span that the proxy received before the barrier span.
- const spans: SerializedStreamedSpan[] = [];
- const barrierPromise = waitForStreamedSpans('nuxt-5-cloudflare', batch => {
- spans.push(...batch);
- return batch.some(span => span.is_segment && getUrlPath(span) === '/api/anchor');
- });
-
- await request.get('/');
- await request.get('/api/anchor');
- await barrierPromise;
-
- const serverSpanPaths = spans.filter(span => getSpanOp(span) === 'http.server').map(getUrlPath);
- expect(serverSpanPaths).toContain('/');
- expect(serverSpanPaths).not.toContain('/api/internal');
-
- const rootSpan = spans.find(span => span.is_segment && getUrlPath(span) === '/');
- expect(rootSpan?.attributes['sentry.sdk.name']).toEqual({ type: 'string', value: 'sentry.javascript.nuxt' });
-});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tsconfig.json b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tsconfig.json
deleted file mode 100644
index a746f2a70c28..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tsconfig.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- // https://nuxt.com/docs/guide/concepts/typescript
- "extends": "./.nuxt/tsconfig.json"
-}
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/wrangler.jsonc b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/wrangler.jsonc
deleted file mode 100644
index da71d4978e33..000000000000
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/wrangler.jsonc
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "$schema": "node_modules/wrangler/config-schema.json",
- "name": "nuxt-5-cloudflare",
- "main": "./.output/server/index.mjs",
- "compatibility_date": "2026-06-29",
- "compatibility_flags": ["nodejs_compat"],
- "assets": {
- "directory": "./.output/public",
- "binding": "ASSETS",
- },
-}
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/assert-build.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/assert-build.ts
index 4dc1e34c400a..06aff0008baa 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/assert-build.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/assert-build.ts
@@ -16,6 +16,9 @@ import {
/** This variant omits `sourcemaps.filesToDeleteAfterUpload`, so Sentry must upload but not delete. */
const keepClientSourceMaps = process.env.E2E_KEEP_CLIENT_SOURCEMAPS === 'true';
+/** This variant has no auth token, so Sentry uploads nothing but still removes the client maps it enabled. */
+const noUpload = process.env.E2E_NO_UPLOAD === 'true';
+
/** `nuxt generate` emits no `.output/server`. Keyed on the command so a missing one under `nuxt build` still fails. */
const isStaticBuild = process.env.NUXT_COMMAND === 'generate';
@@ -59,121 +62,123 @@ function debugIdsOfChunksWithoutSourceMap(dir: string): Set {
console.log(
`Variant: ${isStaticBuild ? 'nuxt generate' : 'nuxt build'}, ` +
- `client source maps ${keepClientSourceMaps ? 'kept' : 'deleted'}\n`,
-);
-
-// Nuxt 5 writes the client build to `CLIENT_OUTPUT` directly. After Sentry deletes the client maps there, a chunk
-// that never had a map looks the same as one whose map was deleted. So the client upload is checked only when the
-// maps are kept. The upload is the same in all variants.
-const outputDirsWithSourceMaps = [
- ...(keepClientSourceMaps ? [CLIENT_OUTPUT] : []),
- ...(isStaticBuild ? [] : [SERVER_OUTPUT]),
-];
-const debugIdsWithoutSourceMap = new Set(
- outputDirsWithSourceMaps.flatMap(dir => [...debugIdsOfChunksWithoutSourceMap(dir)]),
+ `client source maps ${keepClientSourceMaps ? 'kept' : 'deleted'}${noUpload ? ', no upload' : ''}\n`,
);
-const { requests, bundles, sourcemaps, uploadedDebugIds } = assertSourceMapUpload({
- outputDirs: outputDirsWithSourceMaps,
- // The client output is checked below, because the "kept" variant expects its maps to stay.
- strippedDirs: [],
- // Vite builds the client and Nitro builds the server. Counting bundles would still pass with either
- // plugin dropped, so each side is pinned to a marker only that side's source supplies.
- // Nitro 3 deletes `sourcesContent` from the server maps unless `experimental.sourcemapMinify` is `false`. The module
- // sets it to `false`, which is the only reason the server marker survives into `sourcesContent`.
- markers: { 'client source (Vite plugin)': CLIENT_MARKER, 'server source (Rollup plugin)': SERVER_MARKER },
- debugIdsWithoutSourceMap: [...debugIdsWithoutSourceMap],
-});
-console.log(`Found ${bundles.length} artifact bundle(s)\n`);
-
-// --- Nuxt-specific checks on the upload ---
-
-// Sentry rejects a release that names no project with a 400, and the mock server accepts anything,
-// so assert on the body rather than on the call alone.
-const releaseCreates = requests.filter(r => r.url?.includes('/releases') && r.method === 'POST');
-assert.ok(releaseCreates.length > 0, 'Expected a POST to create the release');
-for (const request of releaseCreates) {
- const body = request.jsonBody as { version?: string; projects?: string[] } | undefined;
- assert.equal(
- body?.version,
- 'test-release',
- `Expected the release create body to carry the version, got ${JSON.stringify(body)}`,
- );
- assert.deepEqual(
- body?.projects,
- ['test-project'],
- `Expected the release create body to name the project, got ${JSON.stringify(body)}`,
+if (!noUpload) {
+ // Nuxt 5 writes the client build to `CLIENT_OUTPUT` directly. After Sentry deletes the client maps there, a chunk
+ // that never had a map looks the same as one whose map was deleted. So the client upload is checked only when the
+ // maps are kept. The upload is the same in all variants.
+ const outputDirsWithSourceMaps = [
+ ...(keepClientSourceMaps ? [CLIENT_OUTPUT] : []),
+ ...(isStaticBuild ? [] : [SERVER_OUTPUT]),
+ ];
+ const debugIdsWithoutSourceMap = new Set(
+ outputDirsWithSourceMaps.flatMap(dir => [...debugIdsOfChunksWithoutSourceMap(dir)]),
);
-}
-assert.ok(
- requests.some(r => r.url?.includes('/releases/') && r.method === 'PUT'),
- 'Expected a PUT to finalize the release',
-);
+ const { requests, bundles, sourcemaps, uploadedDebugIds } = assertSourceMapUpload({
+ outputDirs: outputDirsWithSourceMaps,
+ // The client output is checked below, because the "kept" variant expects its maps to stay.
+ strippedDirs: [],
+ // Vite builds the client and Nitro builds the server. Counting bundles would still pass with either
+ // plugin dropped, so each side is pinned to a marker only that side's source supplies.
+ // Nitro 3 deletes `sourcesContent` from the server maps unless `experimental.sourcemapMinify` is `false`. The module
+ // sets it to `false`, which is the only reason the server marker survives into `sourcesContent`.
+ markers: { 'client source (Vite plugin)': CLIENT_MARKER, 'server source (Rollup plugin)': SERVER_MARKER },
+ debugIdsWithoutSourceMap: [...debugIdsWithoutSourceMap],
+ });
+ console.log(`Found ${bundles.length} artifact bundle(s)\n`);
+
+ // --- Nuxt-specific checks on the upload ---
+
+ // Sentry rejects a release that names no project with a 400, and the mock server accepts anything,
+ // so assert on the body rather than on the call alone.
+ const releaseCreates = requests.filter(r => r.url?.includes('/releases') && r.method === 'POST');
+ assert.ok(releaseCreates.length > 0, 'Expected a POST to create the release');
+ for (const request of releaseCreates) {
+ const body = request.jsonBody as { version?: string; projects?: string[] } | undefined;
+ assert.equal(
+ body?.version,
+ 'test-release',
+ `Expected the release create body to carry the version, got ${JSON.stringify(body)}`,
+ );
+ assert.deepEqual(
+ body?.projects,
+ ['test-project'],
+ `Expected the release create body to name the project, got ${JSON.stringify(body)}`,
+ );
+ }
-assert.ok(
- requests.some(r => r.url?.includes('/chunk-upload/') && r.method === 'GET'),
- 'Expected a GET for the chunk-upload options',
-);
+ assert.ok(
+ requests.some(r => r.url?.includes('/releases/') && r.method === 'PUT'),
+ 'Expected a PUT to finalize the release',
+ );
+
+ assert.ok(
+ requests.some(r => r.url?.includes('/chunk-upload/') && r.method === 'GET'),
+ 'Expected a GET for the chunk-upload options',
+ );
-for (const request of getAssembleRequests(requests)) {
- assert.ok((request.assembleBody?.chunks?.length ?? 0) > 0, 'Expected assemble request to have chunk checksums');
- for (const chunk of request.assembleBody?.chunks ?? []) {
- assert.match(chunk, /^[\da-f]{40}$/i, `Expected a SHA-1 chunk checksum, got: ${chunk}`);
+ for (const request of getAssembleRequests(requests)) {
+ assert.ok((request.assembleBody?.chunks?.length ?? 0) > 0, 'Expected assemble request to have chunk checksums');
+ for (const chunk of request.assembleBody?.chunks ?? []) {
+ assert.match(chunk, /^[\da-f]{40}$/i, `Expected a SHA-1 chunk checksum, got: ${chunk}`);
+ }
}
-}
-// `rewriteSources` normalizes `../../../foo` to `./foo` so paths stay resolvable in Sentry.
-const unnormalizedSources = [...new Set(sourcemaps.flatMap(map => map.sourcemap.sources ?? []))].filter(
- source => source.startsWith('../') || path.isAbsolute(source),
-);
-assert.deepEqual(unnormalizedSources, [], `Expected every uploaded source to be normalized to './…'`);
+ // `rewriteSources` normalizes `../../../foo` to `./foo` so paths stay resolvable in Sentry.
+ const unnormalizedSources = [...new Set(sourcemaps.flatMap(map => map.sourcemap.sources ?? []))].filter(
+ source => source.startsWith('../') || path.isAbsolute(source),
+ );
+ assert.deepEqual(unnormalizedSources, [], `Expected every uploaded source to be normalized to './…'`);
-const malformedDebugIds = [...uploadedDebugIds].filter(debugId => !UUID_REGEX.test(debugId));
-assert.deepEqual(malformedDebugIds, [], 'Expected every uploaded debug ID to be a UUID');
+ const malformedDebugIds = [...uploadedDebugIds].filter(debugId => !UUID_REGEX.test(debugId));
+ assert.deepEqual(malformedDebugIds, [], 'Expected every uploaded debug ID to be a UUID');
-// --- Every output directory ships at least one uploaded debug ID ---
+ // --- Every output directory ships at least one uploaded debug ID ---
-// The shared assertions cover the directories that keep their maps. A directory whose maps are deleted
-// must still ship a debug ID with an uploaded map, or a build that uploads nothing would pass.
-for (const outputDir of isStaticBuild ? [CLIENT_OUTPUT] : [CLIENT_OUTPUT, SERVER_OUTPUT]) {
- const injectedDebugIds = findInjectedDebugIds({ outputDir });
- assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`);
- assert.ok(
- injectedDebugIds.some(debugId => uploadedDebugIds.has(debugId)),
- `Expected at least one debug ID in ${outputDir} to have an uploaded sourcemap`,
- );
+ // The shared assertions cover the directories that keep their maps. A directory whose maps are deleted
+ // must still ship a debug ID with an uploaded map, or a build that uploads nothing would pass.
+ for (const outputDir of isStaticBuild ? [CLIENT_OUTPUT] : [CLIENT_OUTPUT, SERVER_OUTPUT]) {
+ const injectedDebugIds = findInjectedDebugIds({ outputDir });
+ assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`);
+ assert.ok(
+ injectedDebugIds.some(debugId => uploadedDebugIds.has(debugId)),
+ `Expected at least one debug ID in ${outputDir} to have an uploaded sourcemap`,
+ );
- console.log(` ${outputDir}: ${injectedDebugIds.length} injected debug ID(s)`);
+ console.log(` ${outputDir}: ${injectedDebugIds.length} injected debug ID(s)`);
- // Nitro bundles the SSR build again, so its debug IDs can end up next to Nitro's own.
- // Reference issue: https://github.com/getsentry/sentry-javascript/issues/18519
- const filesWithMultipleDebugIds = findFilesWithMultipleDebugIds({ outputDir });
- assert.deepEqual(filesWithMultipleDebugIds, [], `Expected at most one debug ID per file in ${outputDir}`);
+ // Nitro bundles the SSR build again, so its debug IDs can end up next to Nitro's own.
+ // Reference issue: https://github.com/getsentry/sentry-javascript/issues/18519
+ const filesWithMultipleDebugIds = findFilesWithMultipleDebugIds({ outputDir });
+ assert.deepEqual(filesWithMultipleDebugIds, [], `Expected at most one debug ID per file in ${outputDir}`);
- // A server file can borrow the debug ID of its SSR build chunk. Then the upload check above passes on
- // Vite's map even if Nitro uploaded nothing.
- const filesWithForeignSourcemaps = findFilesWithForeignSourcemaps({ outputDir }, sourcemaps);
- assert.deepEqual(
- filesWithForeignSourcemaps,
- [],
- `Expected the source map uploaded for each file in ${outputDir} to be generated for that file`,
- );
-}
+ // A server file can borrow the debug ID of its SSR build chunk. Then the upload check above passes on
+ // Vite's map even if Nitro uploaded nothing.
+ const filesWithForeignSourcemaps = findFilesWithForeignSourcemaps({ outputDir }, sourcemaps);
+ assert.deepEqual(
+ filesWithForeignSourcemaps,
+ [],
+ `Expected the source map uploaded for each file in ${outputDir} to be generated for that file`,
+ );
+ }
-// If both builds upload a map under a borrowed debug ID, Sentry can resolve with the wrong one.
-const conflictingDebugIds = findDebugIdsWithConflictingSourcemaps(sourcemaps);
-assert.deepEqual(conflictingDebugIds, [], 'Expected every uploaded debug ID to resolve to exactly one source map');
-
-// TODO: Nitro 3 bundles the SSR build's output again, but its maps stop at that output
-// (`.nuxt/vite/services/ssr/...`) and do not chain to the SSR build's own maps. So server frames do not reach
-// `.vue` files. Assert this when the server maps reach the original sources:
-// const serverDebugIds = new Set(findInjectedDebugIds({ outputDir: SERVER_OUTPUT }));
-// const serverSources = sourcemaps
-// .filter(map => map.debugId && serverDebugIds.has(map.debugId))
-// .flatMap(map => getSourcemapSources(map.sourcemap));
-// assert.ok(serverSources.some(source => source.endsWith('app/pages/index.vue')));
-console.log('');
+ // If both builds upload a map under a borrowed debug ID, Sentry can resolve with the wrong one.
+ const conflictingDebugIds = findDebugIdsWithConflictingSourcemaps(sourcemaps);
+ assert.deepEqual(conflictingDebugIds, [], 'Expected every uploaded debug ID to resolve to exactly one source map');
+
+ // TODO: Nitro 3 bundles the SSR build's output again, but its maps stop at that output
+ // (`.nuxt/vite/services/ssr/...`) and do not chain to the SSR build's own maps. So server frames do not reach
+ // `.vue` files. Assert this when the server maps reach the original sources:
+ // const serverDebugIds = new Set(findInjectedDebugIds({ outputDir: SERVER_OUTPUT }));
+ // const serverSources = sourcemaps
+ // .filter(map => map.debugId && serverDebugIds.has(map.debugId))
+ // .flatMap(map => getSourcemapSources(map.sourcemap));
+ // assert.ok(serverSources.some(source => source.endsWith('app/pages/index.vue')));
+ console.log('');
+}
// --- What the build leaves behind in the client output ---
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/nuxt.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/nuxt.config.ts
index f2f14911dde3..550dd0526694 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/nuxt.config.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/nuxt.config.ts
@@ -3,11 +3,17 @@
// own warning tells users to set, which makes it the setup worth regression-testing.
const keepClientSourceMaps = process.env.E2E_KEEP_CLIENT_SOURCEMAPS === 'true';
+// Without an auth token nothing is uploaded, but Sentry still removes the client maps it enabled.
+const noUpload = process.env.E2E_NO_UPLOAD === 'true';
+
+// With `sourcemap.client` unset, Sentry enables the client maps, uploads them and removes them itself.
+const sdkClientSourceMaps = process.env.E2E_SDK_CLIENT_SOURCEMAPS === 'true';
+
export default defineNuxtConfig({
compatibilityDate: '2025-06-06',
imports: { autoImport: false },
- sourcemap: { client: 'hidden' },
+ sourcemap: { client: noUpload || sdkClientSourceMaps ? undefined : 'hidden' },
modules: ['@sentry/nuxt/module'],
@@ -21,13 +27,16 @@ export default defineNuxtConfig({
sentry: {
sentryUrl: 'http://localhost:3032',
- authToken: 'fake-auth-token',
+ authToken: noUpload ? undefined : 'fake-auth-token',
org: 'test-org',
project: 'test-project',
release: { name: 'test-release' },
// Dropping `filesToDeleteAfterUpload` is the whole point of the "kept" variant: Sentry should
// upload the maps and leave the emitted files alone.
- sourcemaps: keepClientSourceMaps ? {} : { filesToDeleteAfterUpload: ['.output/public/**/*.map'] },
+ sourcemaps:
+ keepClientSourceMaps || noUpload || sdkClientSourceMaps
+ ? {}
+ : { filesToDeleteAfterUpload: ['.output/public/**/*.map'] },
debug: true,
},
});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/package.json b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/package.json
index af833ac3a1bf..0f49c72b9be1 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/package.json
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/package.json
@@ -10,6 +10,10 @@
"test:assert": "pnpm ts-node --script-mode assert-build.ts",
"test:build:keep-client-sourcemaps": "E2E_KEEP_CLIENT_SOURCEMAPS=true pnpm test:build",
"test:assert:keep-client-sourcemaps": "E2E_KEEP_CLIENT_SOURCEMAPS=true pnpm test:assert",
+ "test:build:no-upload": "E2E_NO_UPLOAD=true pnpm test:build",
+ "test:assert:no-upload": "E2E_NO_UPLOAD=true pnpm test:assert",
+ "test:build:sdk-client-sourcemaps": "E2E_SDK_CLIENT_SOURCEMAPS=true pnpm test:build",
+ "test:assert:sdk-client-sourcemaps": "pnpm test:assert",
"test:build:static": "NUXT_COMMAND=generate pnpm test:build",
"test:assert:static": "NUXT_COMMAND=generate pnpm test:assert"
},
@@ -23,7 +27,7 @@
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
"@types/node": "^22.20.0",
- "ts-node": "10.9.1",
+ "ts-node": "10.9.2",
"typescript": "~5.0.0"
},
"sentryTest": {
@@ -34,6 +38,16 @@
"assert-command": "pnpm test:assert:keep-client-sourcemaps",
"label": "nuxt-5-sourcemaps (client source maps kept)"
},
+ {
+ "build-command": "pnpm test:build:no-upload",
+ "assert-command": "pnpm test:assert:no-upload",
+ "label": "nuxt-5-sourcemaps (no upload)"
+ },
+ {
+ "build-command": "pnpm test:build:sdk-client-sourcemaps",
+ "assert-command": "pnpm test:assert:sdk-client-sourcemaps",
+ "label": "nuxt-5-sourcemaps (client source maps enabled by Sentry)"
+ },
{
"build-command": "pnpm test:build:static",
"assert-command": "pnpm test:assert:static",
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/app/components/SSRErrorComponent.vue b/dev-packages/e2e-tests/test-applications/nuxt-5/app/components/SSRErrorComponent.vue
new file mode 100644
index 000000000000..23d21e84878d
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/app/components/SSRErrorComponent.vue
@@ -0,0 +1,9 @@
+
+
+
+
+
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/nuxt.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/nuxt.config.ts
index f81873ea0b21..37c91d4425e5 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/nuxt.config.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/nuxt.config.ts
@@ -1,4 +1,15 @@
// https://nuxt.com/docs/api/configuration/nuxt-config
+// The runtime variants set `RUNTIME` for the build, see dev-packages/e2e-tests/README.md.
+const runtime = process.env.RUNTIME || 'node';
+const cloudflare = runtime === 'cloudflare';
+
+// `node:sqlite` is not available on Bun, which has its own SQLite module, and on Cloudflare, which has D1.
+function database(name: string, binding: string) {
+ if (cloudflare) {
+ return { connector: 'cloudflare-d1', options: { bindingName: binding } } as const;
+ }
+ return { connector: runtime === 'bun' ? 'bun-sqlite' : 'sqlite', options: { name } } as const;
+}
export default defineNuxtConfig({
compatibilityDate: '2025-07-15',
@@ -22,23 +33,23 @@ export default defineNuxtConfig({
},
},
nitro: {
+ ...(cloudflare && {
+ // The Sentry module sets up the SDK from `sentry.cloudflare.config.ts`, because the Nitro preset does not use
+ // `sentry.server.config.ts`.
+ preset: 'cloudflare_module',
+ cloudflare: { nodeCompat: true, deployConfig: false },
+ }),
+ // Files for one runtime replace their counterpart in the copy of the app for that runtime, see
+ // dev-packages/e2e-tests/README.md, and are no routes of their own.
+ ignore: ['**/*.cloudflare.ts'],
...(process.env.E2E_TEST_CACHE_DRIVER && { cache: { driver: process.env.E2E_TEST_CACHE_DRIVER } }),
experimental: {
database: true,
},
database: {
- default: {
- connector: 'sqlite',
- options: { name: 'db' },
- },
- users: {
- connector: 'sqlite',
- options: { name: 'users_db' },
- },
- analytics: {
- connector: 'sqlite',
- options: { name: 'analytics_db' },
- },
+ default: database('db', 'DB'),
+ users: database('users_db', 'USERS_DB'),
+ analytics: database('analytics_db', 'ANALYTICS_DB'),
},
storage: {
'test-storage': {
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json
index aa4f306f2cf8..f6a43458c82f 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json
@@ -8,6 +8,9 @@
"generate": "nuxt generate",
"preview": "nuxt preview",
"start": "node .output/server/index.mjs",
+ "start:bun": "bun .output/server/index.mjs",
+ "start:deno": "deno run -A .output/server/index.mjs",
+ "start:cloudflare": "wrangler dev --port 3030",
"start:import": "node --import ./.output/server/sentry.server.config.mjs .output/server/index.mjs",
"clean": "npx nuxi cleanup",
"test": "playwright test",
@@ -17,7 +20,9 @@
"test:build-canary": "pnpm add nuxt@npm:nuxt-nightly@latest && pnpm add nitro@npm:nitro-nightly@latest && pnpm install --force && pnpm build",
"test:assert": "pnpm test:prod && pnpm test:dev",
"test:build:kv-cache": "pnpm install && E2E_TEST_CACHE_DRIVER=kv pnpm build",
- "test:assert:kv-cache": "E2E_TEST_CACHE_DRIVER=kv TEST_ENV=production playwright test cache"
+ "test:assert:kv-cache": "E2E_TEST_CACHE_DRIVER=kv TEST_ENV=production playwright test cache",
+ "test:build:bun": "pnpm install && bun --bun nuxt build",
+ "test:build:cloudflare": "rm sentry.server.config.ts && pnpm test:build"
},
"//": [
"Currently, we need to install the Nuxt nightlies as those contain Nuxt v5",
@@ -27,6 +32,9 @@
],
"dependencies": {
"@pinia/nuxt": "^0.11.3",
+ "@sentry/bun": "file:../../packed/sentry-bun-packed.tgz",
+ "@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz",
+ "@sentry/deno": "file:../../packed/sentry-deno-packed.tgz",
"@sentry/nuxt": "file:../../packed/sentry-nuxt-packed.tgz",
"db0": "^0.4.2",
"mongoose": "^9.10.2",
@@ -37,8 +45,9 @@
},
"devDependencies": {
"@playwright/test": "1.64.1",
- "@sentry/conventions": "0.35.0",
- "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz"
+ "@sentry/conventions": "0.36.0",
+ "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
+ "wrangler": "^4.72.0"
},
"sentryTest": {
"optional": true,
@@ -55,6 +64,24 @@
"build-command": "pnpm test:build:kv-cache",
"assert-command": "pnpm test:assert:kv-cache",
"label": "nuxt-5 (kv-cache)"
+ },
+ {
+ "runtime": "bun",
+ "build-command": "pnpm test:build:bun",
+ "assert-command": "pnpm test:prod",
+ "label": "nuxt-5 (bun)"
+ },
+ {
+ "runtime": "deno",
+ "deno-version": "v2.9.0",
+ "assert-command": "pnpm test:prod",
+ "label": "nuxt-5 (deno)"
+ },
+ {
+ "runtime": "cloudflare",
+ "build-command": "pnpm test:build:cloudflare",
+ "assert-command": "pnpm test:prod",
+ "label": "nuxt-5 (cloudflare)"
}
]
}
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/playwright.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/playwright.config.ts
index e539cfa89cd3..c02b05ea3fc1 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/playwright.config.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/playwright.config.ts
@@ -1,4 +1,4 @@
-import { getPlaywrightConfig } from '@sentry-internal/test-utils';
+import { getPlaywrightConfig, getRuntime } from '@sentry-internal/test-utils';
const testEnv = process.env.TEST_ENV;
@@ -6,6 +6,14 @@ if (!testEnv) {
throw new Error('No test env defined');
}
+// The server config is bundled into the Nitro output, so every runtime starts the server entry without a preload.
+const productionStartCommands = {
+ node: 'pnpm start',
+ bun: 'pnpm start:bun',
+ deno: 'pnpm start:deno',
+ cloudflare: 'pnpm start:cloudflare',
+};
+
const getStartCommand = () => {
if (testEnv === 'development') {
// The Sentry server config is bundled into the dev server via a nitro plugin, so no preload is needed.
@@ -13,7 +21,7 @@ const getStartCommand = () => {
}
if (testEnv === 'production') {
- return 'pnpm start';
+ return productionStartCommands[getRuntime()];
}
throw new Error(`Unknown test env: ${testEnv}`);
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/pnpm-workspace.yaml b/dev-packages/e2e-tests/test-applications/nuxt-5/pnpm-workspace.yaml
index 4210a62a804d..2e21551db362 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/pnpm-workspace.yaml
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/pnpm-workspace.yaml
@@ -1,3 +1,5 @@
allowBuilds:
'@sentry/cli': true
+ esbuild: true
+ workerd: true
minimumReleaseAge: 0
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/public/humans.txt b/dev-packages/e2e-tests/test-applications/nuxt-5/public/humans.txt
new file mode 100644
index 000000000000..445ab6da73d9
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/public/humans.txt
@@ -0,0 +1 @@
+Team: Sentry
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.cloudflare.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.cloudflare.config.ts
new file mode 100644
index 000000000000..c77b6dc33a99
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.cloudflare.config.ts
@@ -0,0 +1,11 @@
+import { defineCloudflareOptions } from '@sentry/cloudflare';
+
+// On Cloudflare, the Sentry Nuxt module wraps the Worker with `withSentry` and these options. Node, Bun and Deno use
+// `sentry.server.config.ts`.
+export default defineCloudflareOptions({
+ dsn: 'https://public@dsn.ingest.sentry.io/1337',
+ tracesSampleRate: 1.0,
+ tunnel: 'http://localhost:3031/', // proxy server
+ // Several tests trigger the same server error one after another, which Dedupe would drop.
+ integrations: integrations => integrations.filter(integration => integration.name !== 'Dedupe'),
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.bun.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.bun.ts
new file mode 100644
index 000000000000..eadb5d6e4647
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.bun.ts
@@ -0,0 +1,16 @@
+import { bunServerIntegration, fetchIntegration } from '@sentry/bun';
+import * as Sentry from '@sentry/nuxt';
+
+Sentry.init({
+ dsn: 'https://public@dsn.ingest.sentry.io/1337',
+ tracesSampleRate: 1.0, // Capture 100% of the transactions
+ tunnel: 'http://localhost:3031/', // proxy server
+ // Several tests trigger the same server error one after another, which Dedupe would drop.
+ integrations: integrations => [
+ ...integrations.filter(integration => integration.name !== 'Dedupe'),
+ // On Bun, Nitro 3 builds with its `bun` preset, which serves with `Bun.serve`. Bun emits none of the undici channels
+ // the Node SDK listens to, so these add the incoming request and outgoing `fetch` instrumentation.
+ bunServerIntegration(),
+ fetchIntegration(),
+ ],
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.deno.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.deno.ts
new file mode 100644
index 000000000000..a0647a774c99
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.deno.ts
@@ -0,0 +1,14 @@
+import { fetchIntegration } from '@sentry/deno';
+import * as Sentry from '@sentry/nuxt';
+
+Sentry.init({
+ dsn: 'https://public@dsn.ingest.sentry.io/1337',
+ tracesSampleRate: 1.0, // Capture 100% of the transactions
+ tunnel: 'http://localhost:3031/', // proxy server
+ // Several tests trigger the same server error one after another, which Dedupe would drop.
+ integrations: integrations => [
+ ...integrations.filter(integration => integration.name !== 'Dedupe'),
+ // The `fetch` of Deno is not undici, so the Node SDK does not see outgoing requests.
+ fetchIntegration(),
+ ],
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-mongoose.cloudflare.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-mongoose.cloudflare.ts
new file mode 100644
index 000000000000..bba737796b18
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-mongoose.cloudflare.ts
@@ -0,0 +1,7 @@
+import { defineHandler } from 'nitro';
+import { HTTPError } from 'nitro/h3';
+
+// Replaces `db-mongoose.ts` on Cloudflare, see `MONGOOSE_UNSUPPORTED` in `tests/runtime.ts`.
+export default defineHandler(() => {
+ throw new HTTPError({ status: 501 });
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-test.ts
index e814c930311b..9bd704b2349f 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-test.ts
@@ -18,10 +18,10 @@ export default defineHandler(async event => {
case 'prepare-all': {
await db.exec('CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT, price REAL)');
- await db.exec(`INSERT OR REPLACE INTO products (id, name, price) VALUES
- (1, 'Product A', 10.99),
- (2, 'Product B', 20.50),
- (3, 'Product C', 15.25)`);
+ // One line, because D1 runs every line of `exec` as a statement of its own.
+ await db.exec(
+ `INSERT OR REPLACE INTO products (id, name, price) VALUES (1, 'Product A', 10.99), (2, 'Product B', 20.50), (3, 'Product C', 15.25)`,
+ );
const stmt = db.prepare('SELECT * FROM products WHERE price > ?');
const results = await stmt.all(10);
return { success: true, count: results.length, results };
@@ -36,10 +36,9 @@ export default defineHandler(async event => {
case 'prepare-bind': {
await db.exec('CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, category TEXT, value INTEGER)');
- await db.exec(`INSERT OR REPLACE INTO items (id, category, value) VALUES
- (1, 'electronics', 100),
- (2, 'books', 50),
- (3, 'electronics', 200)`);
+ await db.exec(
+ `INSERT OR REPLACE INTO items (id, category, value) VALUES (1, 'electronics', 100), (2, 'books', 50), (3, 'electronics', 200)`,
+ );
const stmt = db.prepare('SELECT * FROM items WHERE category = ?');
const boundStmt = stmt.bind('electronics');
const results = await boundStmt.all();
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts
index 1cd62dbae4da..e5163a76f359 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts
@@ -18,6 +18,7 @@ test.describe('Cache Instrumentation', () => {
const spans = await collectStreamedSpansUntilSegment(
'nuxt-5',
span => span.attributes['url.path']?.value === '/api/cache-test',
+ span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt',
);
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/cache-test');
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database-multi.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database-multi.test.ts
index 62e233af87d6..98d9a8ccde2a 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database-multi.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database-multi.test.ts
@@ -1,10 +1,12 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils';
+import { DB_ORIGIN, DB_SYSTEM_NAME, RUNTIME } from './runtime';
async function collectDbSpans() {
const spans = await collectStreamedSpansUntilSegment(
'nuxt-5',
span => span.attributes['url.path']?.value === '/api/db-multi-test',
+ span => getSpanOp(span) === 'db.query',
);
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-multi-test');
@@ -25,9 +27,9 @@ test.describe('multiple database instances', () => {
expect(selectSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT default_table' },
'db.query.text': { type: 'string', value: 'SELECT * FROM default_table WHERE id = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'db.sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }),
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -44,9 +46,9 @@ test.describe('multiple database instances', () => {
expect(selectSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT user_profiles' },
'db.query.text': { type: 'string', value: 'SELECT * FROM user_profiles WHERE id = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'users_db.sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }),
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -63,9 +65,9 @@ test.describe('multiple database instances', () => {
expect(selectSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT events' },
'db.query.text': { type: 'string', value: 'SELECT * FROM events WHERE id = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' } }),
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -85,23 +87,23 @@ test.describe('multiple database instances', () => {
expect(sessionSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT sessions' },
'db.query.text': { type: 'string', value: 'SELECT * FROM sessions WHERE id = ?' },
- 'db.namespace': { type: 'string', value: 'db.sqlite' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }),
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
expect(accountSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT accounts' },
'db.query.text': { type: 'string', value: 'SELECT * FROM accounts WHERE id = ?' },
- 'db.namespace': { type: 'string', value: 'users_db.sqlite' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }),
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
expect(metricSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT metrics' },
'db.query.text': { type: 'string', value: 'SELECT * FROM metrics WHERE id = ?' },
- 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' } }),
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
// All spans belong to the same trace as the request's root span
@@ -124,18 +126,18 @@ test.describe('multiple database instances', () => {
expect(logsInsertSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'INSERT logs' },
'db.query.text': { type: 'string', value: 'INSERT INTO logs (message) VALUES (?)' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'db.sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }),
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
expect(auditLogsInsertSpan).toBeDefined();
expect(auditLogsInsertSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'INSERT audit_logs' },
'db.query.text': { type: 'string', value: 'INSERT INTO audit_logs (action) VALUES (?)' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'users_db.sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }),
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts
index de55b7ce8df4..184eac58bb50 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts
@@ -1,10 +1,19 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils';
+import { DB_ORIGIN, DB_SYSTEM_NAME, RUNTIME } from './runtime';
+
+// `@sentry/cloudflare` does not capture D1 errors, so the error hook of Nitro captures them on Cloudflare. The D1
+// error has a `cause`, so the event links the errors with an `exception_id`.
+const DB_ERROR_MECHANISM =
+ RUNTIME === 'cloudflare'
+ ? { handled: false, type: 'auto.function.nuxt.nitro', exception_id: 0 }
+ : { handled: false, type: 'auto.db.nuxt' };
async function collectDbSpans() {
const spans = await collectStreamedSpansUntilSegment(
'nuxt-5',
span => span.attributes['url.path']?.value === '/api/db-test',
+ span => getSpanOp(span) === 'db.query',
);
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-test');
@@ -17,17 +26,20 @@ test.describe('database integration', () => {
await request.get('/api/db-test?method=prepare-get');
- const dbSpan = (await dbSpansPromise).find(span => span.name === 'SELECT users');
+ const dbSpans = await dbSpansPromise;
+ const dbSpan = dbSpans.find(span => span.name === 'SELECT users');
- expect(dbSpan).toBeDefined();
+ // On Cloudflare, `@sentry/cloudflare` and the database instrumentation of `@sentry/nuxt` must not both create a
+ // span for the same D1 query.
+ expect(dbSpans.filter(span => span.name === 'SELECT users')).toHaveLength(1);
expect(dbSpan?.status).toBe('ok');
expect(dbSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT users' },
'db.query.text': { type: 'string', value: 'SELECT * FROM users WHERE id = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'db.namespace': { type: 'string', value: 'db.sqlite' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }),
'sentry.op': { type: 'string', value: 'db.query' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -42,8 +54,8 @@ test.describe('database integration', () => {
expect(dbSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT products' },
'db.query.text': { type: 'string', value: 'SELECT * FROM products WHERE price > ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -58,8 +70,8 @@ test.describe('database integration', () => {
expect(dbSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'INSERT orders' },
'db.query.text': { type: 'string', value: 'INSERT INTO orders (customer, amount) VALUES (?, ?)' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -74,8 +86,8 @@ test.describe('database integration', () => {
expect(dbSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT items' },
'db.query.text': { type: 'string', value: 'SELECT * FROM items WHERE category = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -93,8 +105,8 @@ test.describe('database integration', () => {
type: 'string',
value: 'INSERT INTO messages (content, created_at) VALUES (?, ?)',
},
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
@@ -110,8 +122,8 @@ test.describe('database integration', () => {
expect(insertSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'INSERT logs' },
'db.query.text': { type: 'string', value: `INSERT INTO logs (message, level) VALUES (?, ?)` },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
// DDL statements are summarized as `{operation} {table}` as well, with the statement on the attribute
@@ -129,7 +141,7 @@ test.describe('database integration', () => {
test('captures database error and marks span as failed', async ({ request }) => {
const errorPromise = waitForError('nuxt-5', errorEvent => {
return !!errorEvent?.exception?.values?.some(
- value => value.mechanism?.type === 'auto.db.nuxt' && value.value?.includes('no such table'),
+ value => value.mechanism?.type === DB_ERROR_MECHANISM.type && value.value?.includes('no such table'),
);
});
@@ -141,14 +153,11 @@ test.describe('database integration', () => {
const [error, dbSpans] = await Promise.all([errorPromise, dbSpansPromise]);
- const dbException = error.exception?.values?.find(value => value.mechanism?.type === 'auto.db.nuxt');
+ const dbException = error.exception?.values?.find(value => value.mechanism?.type === DB_ERROR_MECHANISM.type);
expect(dbException).toBeDefined();
expect(dbException?.value).toContain('no such table');
- expect(dbException?.mechanism).toEqual({
- handled: false,
- type: 'auto.db.nuxt',
- });
+ expect(dbException?.mechanism).toEqual(DB_ERROR_MECHANISM);
const dbSpan = dbSpans.find(span => span.name === 'SELECT nonexistent_table');
@@ -157,14 +166,16 @@ test.describe('database integration', () => {
expect(dbSpan?.attributes).toMatchObject({
'db.query.summary': { type: 'string', value: 'SELECT nonexistent_table' },
'db.query.text': { type: 'string', value: 'SELECT * FROM nonexistent_table WHERE invalid_column = ?' },
- 'db.system.name': { type: 'string', value: 'sqlite' },
- 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' },
+ 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME },
+ 'sentry.origin': { type: 'string', value: DB_ORIGIN },
});
});
test('captures breadcrumb for db.exec() queries', async ({ request }) => {
const errorPromise = waitForError('nuxt-5', errorEvent => {
- return !!errorEvent?.exception?.values?.some(value => value.mechanism?.type === 'auto.db.nuxt');
+ return !!errorEvent?.exception?.values?.some(
+ value => value.mechanism?.type === DB_ERROR_MECHANISM.type && value.value?.includes('no such table'),
+ );
});
await request.get('/api/db-test?method=error').catch(() => {
@@ -179,7 +190,11 @@ test.describe('database integration', () => {
expect(dbBreadcrumb).toBeDefined();
expect(dbBreadcrumb?.message).toBe(`INSERT INTO logs (message, level) VALUES (?, ?)`);
- expect(dbBreadcrumb?.data?.['db.query.text']).toBe(`INSERT INTO logs (message, level) VALUES (?, ?)`);
+ expect(dbBreadcrumb?.data).toMatchObject(
+ RUNTIME === 'cloudflare'
+ ? { 'db.operation.name': 'exec' }
+ : { 'db.query.text': `INSERT INTO logs (message, level) VALUES (?, ?)` },
+ );
});
test('multiple database operations in single request create multiple spans', async ({ request }) => {
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/db-mongoose.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/db-mongoose.test.ts
index 5d3ba010670f..856be6be6c0f 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/db-mongoose.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/db-mongoose.test.ts
@@ -1,5 +1,8 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';
+import { MONGOOSE_UNSUPPORTED, RUNTIME } from './runtime';
+
+test.skip(RUNTIME === 'cloudflare', MONGOOSE_UNSUPPORTED);
// The Nitro bundle force-inlines the instrumented drivers while their CommonJS dependencies and
// Node builtins stay external, and every `require()` across that boundary needs working interop
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.server.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.server.test.ts
index 2dcc253a98d1..e24e004a1ad9 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.server.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.server.test.ts
@@ -1,6 +1,7 @@
import { expect, test } from '@playwright/test';
import { waitForError } from '@sentry-internal/test-utils';
import { IMPORT_SURFACES } from './importSurfaces';
+import { RUNTIME } from './runtime';
import { waitForHydration } from './waitForHydration';
IMPORT_SURFACES.forEach(({ name, apiPrefix }) => {
@@ -114,3 +115,30 @@ IMPORT_SURFACES.forEach(({ name, apiPrefix }) => {
});
});
});
+
+test.describe('SSR error boundary', () => {
+ test('captures error thrown in NuxtErrorBoundary during SSR with 200 response', async ({ page }) => {
+ const errorPromise = waitForError('nuxt-5', async errorEvent => {
+ return errorEvent?.exception?.values?.[0]?.value === 'SSR Error inside NuxtErrorBoundary';
+ });
+
+ const response = await page.goto('/ssr-error-boundary');
+ expect(response?.status()).toBe(200);
+
+ const error = await errorPromise;
+
+ if (RUNTIME !== 'bun') {
+ expect(error.transaction).toEqual('GET /ssr-error-boundary');
+ }
+ expect(error.exception.values[0]).toMatchObject({
+ type: 'Error',
+ value: 'SSR Error inside NuxtErrorBoundary',
+ mechanism: {
+ handled: false,
+ type: 'auto.function.nuxt.vue-error',
+ },
+ });
+
+ await expect(page.locator('#error-fallback')).toBeVisible();
+ });
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/internal-fetch.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/internal-fetch.test.ts
new file mode 100644
index 000000000000..e69775e11489
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/internal-fetch.test.ts
@@ -0,0 +1,31 @@
+import { expect, test } from '@playwright/test';
+import type { SerializedStreamedSpan } from '@sentry-internal/test-utils';
+import { getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils';
+
+test('does not instrument the internal `$fetch` of a server-rendered page as its own request', async ({ request }) => {
+ // One listener, so it gets every span that the proxy received before the barrier span.
+ const spans: SerializedStreamedSpan[] = [];
+ const barrierPromise = waitForStreamedSpans('nuxt-5', batch => {
+ spans.push(...batch);
+ return batch.some(span => span.is_segment && span.attributes['url.path']?.value === '/api/test-param/barrier');
+ });
+
+ const response = await request.get('/internal-fetch');
+ expect(await response.text()).toContain('Param: internal!');
+ await request.get('/api/test-param/barrier');
+ await barrierPromise;
+
+ const pageServerSpans = spans.filter(
+ span => getSpanOp(span) === 'http.server' && span.attributes['url.path']?.value === '/internal-fetch',
+ );
+ const internalFetchServerSpans = spans.filter(
+ span => getSpanOp(span) === 'http.server' && span.attributes['url.path']?.value === '/api/test-param/internal',
+ );
+
+ expect(pageServerSpans).toHaveLength(1);
+ expect(pageServerSpans[0]?.attributes['sentry.sdk.name']).toEqual({
+ type: 'string',
+ value: 'sentry.javascript.nuxt',
+ });
+ expect(internalFetchServerSpans).toHaveLength(0);
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts
index 8add88c82f06..3d1c14c1cb64 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts
@@ -2,6 +2,7 @@ import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils';
import type { SerializedStreamedSpan } from '@sentry-internal/test-utils';
import { IMPORT_SURFACES } from './importSurfaces';
+import { RUNTIME } from './runtime';
// Nitro runs every file in `server/middleware/` on every request, so each surface tells its spans apart by
// middleware name. `nuxt/server` has no object syntax (`middleware`) and no `eventHandler` alias, so only the
@@ -27,7 +28,11 @@ const MIDDLEWARE = {
} as const;
async function collectRequestSpans(path = '/api/middleware-test') {
- const spans = await collectStreamedSpansUntilSegment('nuxt-5', span => span.attributes['url.path']?.value === path);
+ const spans = await collectStreamedSpansUntilSegment(
+ 'nuxt-5',
+ span => span.attributes['url.path']?.value === path,
+ span => getSpanOp(span) === 'middleware',
+ );
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === path);
return spans.filter(span => span.trace_id === rootSpan?.trace_id);
@@ -98,6 +103,11 @@ IMPORT_SURFACES.forEach(({ name, apiPrefix }) => {
});
test('captures a middleware error and marks its span as errored', async ({ request }) => {
+ test.fail(
+ RUNTIME === 'bun',
+ 'Bun: the `Bun.serve` instrumentation sets no transaction name on the isolation scope, so the error has none',
+ );
+
const spansPromise = collectRequestSpans(path);
const errorEventPromise = waitForError('nuxt-5', errorEvent => {
return errorEvent?.exception?.values?.[0]?.value === middleware.authErrorMessage;
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime-injection.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime-injection.test.ts
index c16c103126d6..fbda046aeb09 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime-injection.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime-injection.test.ts
@@ -1,6 +1,7 @@
import { execFileSync } from 'node:child_process';
import { expect, test } from '@playwright/test';
import { isDevMode } from './isDevMode';
+import { RUNTIME } from './runtime';
// Nitro v3 bundles every dependency, including the SDK's copy of `@sentry/server-runtime-injection`.
// On Node versions without `Module.registerHooks` (< 24.13), that bundled copy registers its ESM
@@ -9,6 +10,7 @@ import { isDevMode } from './isDevMode';
// resolution directly instead of the missing warning.
test('keeps the runtime injection loader hook resolvable from the server output', () => {
test.skip(isDevMode, 'nuxt dev has no server output');
+ test.skip(RUNTIME === 'cloudflare', 'Cloudflare: the Worker bundle has no `node_modules` and no loader hook');
const resolved = execFileSync(
'node',
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime.ts
new file mode 100644
index 000000000000..631286dde6d2
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime.ts
@@ -0,0 +1,38 @@
+import { getRuntime } from '@sentry-internal/test-utils';
+
+export const RUNTIME = getRuntime();
+
+export const NO_PROCESS = 'Cloudflare: the Worker is no process the tests can start or watch exit';
+
+// Without Sentry too, the Cloudflare preset of Nitro cannot bundle the `mongodb` driver for Workers.
+export const MONGOOSE_UNSUPPORTED = 'Cloudflare: Nitro cannot bundle the `mongodb` driver for Workers';
+
+// Nitro 3 serves with `Bun.serve` on Bun and with `node:http` on Node and Deno.
+const SERVER_ORIGINS = {
+ node: 'auto.http.http_server',
+ bun: 'auto.http.bun.serve',
+ deno: 'auto.http.http_server',
+ cloudflare: 'auto.http.cloudflare',
+};
+
+export const SERVER_ORIGIN = SERVER_ORIGINS[RUNTIME];
+
+// On Cloudflare, the databases are D1 databases. `@sentry/cloudflare` creates the spans of their queries, and
+// `@sentry/nuxt` leaves them out of its database instrumentation.
+export const DB_SYSTEM_NAME = RUNTIME === 'cloudflare' ? 'cloudflare-d1' : 'sqlite';
+export const DB_ORIGIN = RUNTIME === 'cloudflare' ? 'auto.db.cloudflare.d1' : 'auto.db.nuxt';
+
+/** The command and arguments that start the built server on the runtime of the variant. */
+export function getServerCommand(): [string, string[]] {
+ const entry = '.output/server/index.mjs';
+
+ if (RUNTIME === 'bun') {
+ return ['bun', [entry]];
+ }
+
+ if (RUNTIME === 'deno') {
+ return ['deno', ['run', '-A', entry]];
+ }
+
+ return ['node', [entry]];
+}
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/startup-error.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/startup-error.test.ts
index 3ea755529149..239fd2651f0b 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/startup-error.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/startup-error.test.ts
@@ -1,15 +1,24 @@
import { spawn } from 'node:child_process';
import { expect, test } from '@playwright/test';
import { waitForError, waitForSession } from '@sentry-internal/test-utils';
+import { getServerCommand, NO_PROCESS, RUNTIME } from './runtime';
+
+test.skip(RUNTIME === 'cloudflare', NO_PROCESS);
// Errors thrown between server start and `listen` (module evaluation, nitro plugin runs) must be
// captured and flushed before the process exits. Each test spawns its own server process because
// the crash kills it; events still reach the shared event proxy via the tunnel.
+// Deno hands an error thrown while the modules evaluate to the `unhandledRejection` listeners, where Node and Bun
+// treat it as an uncaught exception. The listener of the SDK (mode `warn`) keeps the process alive, so on Deno it
+// exits with 0 once it has nothing left to do.
+const CRASH_EXIT_CODE = RUNTIME === 'deno' ? 0 : 1;
+
/** Starts the built server and resolves with its exit code. */
function spawnCrashingServer(env: Record): Promise {
return new Promise((resolve, reject) => {
- const child = spawn('node', ['.output/server/index.mjs'], {
+ const [command, args] = getServerCommand();
+ const child = spawn(command, args, {
// Session tracking needs a release; builds without git (e.g. the E2E runner's temp copy)
// have none injected, so pin one for the crashed-session assertion.
env: { ...process.env, SENTRY_RELEASE: 'startup-error-test', ...env },
@@ -27,7 +36,7 @@ test('captures error and crashed session when a nitro plugin throws during start
const [errorEvent, session] = await Promise.all([errorPromise, sessionPromise]);
- expect(exitCode).toBe(1);
+ expect(exitCode).toBe(CRASH_EXIT_CODE);
expect(errorEvent.exception?.values?.[0]?.value).toBe('startup-crash-test');
expect(errorEvent.exception?.values?.[0]?.mechanism?.handled).toBe(false);
expect(session.status).toBe('crashed');
@@ -41,7 +50,7 @@ test('captures error when a server module throws during bundle evaluation', asyn
const errorEvent = await errorPromise;
- expect(exitCode).toBe(1);
+ expect(exitCode).toBe(CRASH_EXIT_CODE);
expect(errorEvent.exception?.values?.[0]?.value).toBe('eval-crash-test');
expect(errorEvent.exception?.values?.[0]?.mechanism?.handled).toBe(false);
});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage-aliases.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage-aliases.test.ts
index 0dc4353a927f..76c8b4bbf464 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage-aliases.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage-aliases.test.ts
@@ -2,7 +2,11 @@ import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';
async function collectStorageSpans(route: string) {
- const spans = await collectStreamedSpansUntilSegment('nuxt-5', span => span.attributes['url.path']?.value === route);
+ const spans = await collectStreamedSpansUntilSegment(
+ 'nuxt-5',
+ span => span.attributes['url.path']?.value === route,
+ span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt',
+ );
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === route);
return spans.filter(
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts
index e8c10e66901d..ab3b3f63456c 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts
@@ -2,7 +2,11 @@ import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';
async function collectStorageSpans(route: string) {
- const spans = await collectStreamedSpansUntilSegment('nuxt-5', span => span.attributes['url.path']?.value === route);
+ const spans = await collectStreamedSpansUntilSegment(
+ 'nuxt-5',
+ span => span.attributes['url.path']?.value === route,
+ span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt',
+ );
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === route);
return spans.filter(
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.server.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.server.test.ts
index 2a0dcebe48c4..100ca864b4ff 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.server.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.server.test.ts
@@ -1,6 +1,13 @@
+import { URL_PATH } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
-import { collectStreamedSpans, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+import {
+ collectStreamedSpans,
+ getSpanOp,
+ waitForStreamedSpan,
+ waitForStreamedSpans,
+} from '@sentry-internal/test-utils';
import { IMPORT_SURFACES } from './importSurfaces';
+import { SERVER_ORIGIN } from './runtime';
test('sends a server root span on pageload', async ({ page }) => {
const serverSpanPromise = waitForStreamedSpan('nuxt-5', span => {
@@ -12,31 +19,33 @@ test('sends a server root span on pageload', async ({ page }) => {
const serverSpan = await serverSpanPromise;
expect(getSpanOp(serverSpan)).toBe('http.server');
- expect(serverSpan.attributes['sentry.origin']?.value).toBe('auto.http.http_server');
+ expect(serverSpan.attributes['sentry.origin']?.value).toBe(SERVER_ORIGIN);
});
-test('does not send spans for build asset folder "_nuxt"', async ({ page }) => {
- let buildAssetFolderOccurred = false;
-
- waitForStreamedSpan('nuxt-5', span => {
- if (span.is_segment && /^GET \/_nuxt\//.test(span.name)) {
- buildAssetFolderOccurred = true;
- }
- return false; // expects to return a boolean (but not relevant here)
- });
-
- const serverSpanPromise = waitForStreamedSpan('nuxt-5', span => {
- return span.is_segment && span.name.includes('GET /test-param/');
+[
+ // Nuxt build output that the HTTP integration does not ignore.
+ '/_nuxt/builds/latest.json',
+ '/_nuxt/entry.js.map',
+ // File from `public/` that the HTTP integration does not ignore.
+ '/humans.txt',
+ // Common static file that the HTTP integration ignores.
+ '/favicon.ico',
+].forEach(path => {
+ test(`does not send a server span for the file ${path}`, async ({ baseURL }) => {
+ const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);
+
+ expect(segmentPaths).not.toContain(path);
});
+});
- await page.goto('/test-param/1234');
-
- const serverSpan = await serverSpanPromise;
-
- expect(buildAssetFolderOccurred).toBe(false);
+// Routes that look like build output. They also show that the helper sees sent segments, so the tests above cannot
+// pass by accident.
+['/test-param/jane.doe', '/api/test-param/data.json', '/test-param/_nuxt/'].forEach(path => {
+ test(`sends a server span for the route ${path}`, async ({ baseURL }) => {
+ const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);
- expect(serverSpan.name).toBe('GET /test-param/:param()');
- expect(serverSpan.attributes['sentry.segment.name.source']?.value).toBe('route');
+ expect(segmentPaths).toContain(path);
+ });
});
IMPORT_SURFACES.forEach(({ name, apiPrefix }) => {
@@ -72,3 +81,22 @@ IMPORT_SURFACES.forEach(({ name, apiPrefix }) => {
expect(httpClientSpan?.parent_span_id).toBe(serverSegmentSpan?.span_id);
});
});
+
+/**
+ * Requests `path`, then a page. Returns the `url.path` of each server segment up to the page's segment, which arrives
+ * after any segment for `path`.
+ */
+async function getServerSegmentPathsUntilPage(baseURL: string, path: string): Promise {
+ const pagePath = `/test-param/after${path.replace(/\W+/g, '-')}`;
+ const segmentPaths: string[] = [];
+ const pageSegmentPromise = waitForStreamedSpans('nuxt-5', spans => {
+ segmentPaths.push(...spans.filter(span => span.is_segment).map(span => `${span.attributes[URL_PATH]?.value}`));
+ return segmentPaths.includes(pagePath);
+ });
+
+ await fetch(`${baseURL}${path}`);
+ await fetch(`${baseURL}${pagePath}`);
+ await pageSegmentPromise;
+
+ return segmentPaths;
+}
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.test.ts
index 5580819bec1f..c704cd39b2e0 100644
--- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.test.ts
@@ -2,6 +2,7 @@ import { expect, test } from '@playwright/test';
import { collectStreamedSpans, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
import type { SerializedStreamedSpan } from '@sentry-internal/test-utils';
import { IMPORT_SURFACES } from './importSurfaces';
+import { SERVER_ORIGIN } from './runtime';
function expectSegmentSpan(
span: SerializedStreamedSpan | undefined,
@@ -53,7 +54,7 @@ test.describe('distributed tracing', () => {
expectSegmentSpan(serverSpan, {
name: 'GET /test-param/:param()',
op: 'http.server',
- origin: 'auto.http.http_server',
+ origin: SERVER_ORIGIN,
});
expect(serverSpan.trace_id).toBe(metaTraceId);
expect(clientSpan.parent_span_id).toBe(serverSpan.span_id);
@@ -117,13 +118,13 @@ test.describe('distributed tracing', () => {
expectSegmentSpan(ssrSpan, {
name: 'GET /test-param/user/:userId()',
op: 'http.server',
- origin: 'auto.http.http_server',
+ origin: SERVER_ORIGIN,
});
expectSegmentSpan(serverReqSpan, {
name: `GET ${apiPrefix}/user/:userId`,
op: 'http.server',
- origin: 'auto.http.http_server',
+ origin: SERVER_ORIGIN,
});
expect(serverReqSpan.parent_span_id).toBe(httpClientSpan?.span_id);
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/wrangler.jsonc b/dev-packages/e2e-tests/test-applications/nuxt-5/wrangler.jsonc
new file mode 100644
index 000000000000..f2af1eb45c25
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/wrangler.jsonc
@@ -0,0 +1,23 @@
+{
+ "$schema": "node_modules/wrangler/config-schema.json",
+ "name": "nuxt-5",
+ "main": "./.output/server/index.mjs",
+ "compatibility_date": "2026-06-29",
+ "compatibility_flags": ["nodejs_compat"],
+ "assets": {
+ "directory": "./.output/public",
+ "binding": "ASSETS",
+ // Like Nitro on Node, serve pre-rendered pages at their path instead of redirecting to a trailing slash.
+ "html_handling": "drop-trailing-slash",
+ },
+ // `wrangler dev` keeps these in a local SQLite file, so they need no real database.
+ "d1_databases": [
+ { "binding": "DB", "database_name": "db", "database_id": "00000000-0000-0000-0000-000000000001" },
+ { "binding": "USERS_DB", "database_name": "users_db", "database_id": "00000000-0000-0000-0000-000000000002" },
+ {
+ "binding": "ANALYTICS_DB",
+ "database_name": "analytics_db",
+ "database_id": "00000000-0000-0000-0000-000000000003",
+ },
+ ],
+}
diff --git a/dev-packages/e2e-tests/test-applications/react-17/package.json b/dev-packages/e2e-tests/test-applications/react-17/package.json
index 99e9368fef2f..e3b6133cf145 100644
--- a/dev-packages/e2e-tests/test-applications/react-17/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-17/package.json
@@ -43,7 +43,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
},
"sentryTest": {
"variants": [
diff --git a/dev-packages/e2e-tests/test-applications/react-19/package.json b/dev-packages/e2e-tests/test-applications/react-19/package.json
index 592f1dab46e1..f61ab8c0194b 100644
--- a/dev-packages/e2e-tests/test-applications/react-19/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-19/package.json
@@ -42,6 +42,6 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
}
}
diff --git a/dev-packages/e2e-tests/test-applications/react-create-browser-router/package.json b/dev-packages/e2e-tests/test-applications/react-create-browser-router/package.json
index 4405ba83c8c8..c2341146f6bb 100644
--- a/dev-packages/e2e-tests/test-applications/react-create-browser-router/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-create-browser-router/package.json
@@ -43,6 +43,6 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
}
}
diff --git a/dev-packages/e2e-tests/test-applications/react-create-hash-router/package.json b/dev-packages/e2e-tests/test-applications/react-create-hash-router/package.json
index 80481c626bd4..68d9a04800ea 100644
--- a/dev-packages/e2e-tests/test-applications/react-create-hash-router/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-create-hash-router/package.json
@@ -44,7 +44,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
},
"sentryTest": {
"canaryVariants": [
diff --git a/dev-packages/e2e-tests/test-applications/react-create-memory-router/package.json b/dev-packages/e2e-tests/test-applications/react-create-memory-router/package.json
index 419a9e289d61..c9c7b04d522c 100644
--- a/dev-packages/e2e-tests/test-applications/react-create-memory-router/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-create-memory-router/package.json
@@ -43,6 +43,6 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
}
}
diff --git a/dev-packages/e2e-tests/test-applications/react-router-5/package.json b/dev-packages/e2e-tests/test-applications/react-router-5/package.json
index 1ceea6c66961..13627f545a57 100644
--- a/dev-packages/e2e-tests/test-applications/react-router-5/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-router-5/package.json
@@ -45,6 +45,6 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
}
}
diff --git a/dev-packages/e2e-tests/test-applications/react-router-6-descendant-routes/package.json b/dev-packages/e2e-tests/test-applications/react-router-6-descendant-routes/package.json
index 0500b51516b1..7a557f62ed7b 100644
--- a/dev-packages/e2e-tests/test-applications/react-router-6-descendant-routes/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-router-6-descendant-routes/package.json
@@ -45,6 +45,6 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
}
}
diff --git a/dev-packages/e2e-tests/test-applications/react-router-6-use-routes/package.json b/dev-packages/e2e-tests/test-applications/react-router-6-use-routes/package.json
index 87ddbf4ab3f8..96ca48541b92 100644
--- a/dev-packages/e2e-tests/test-applications/react-router-6-use-routes/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-router-6-use-routes/package.json
@@ -42,6 +42,6 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
}
}
diff --git a/dev-packages/e2e-tests/test-applications/react-router-6/package.json b/dev-packages/e2e-tests/test-applications/react-router-6/package.json
index 2101a3aa1a62..cfcdafba1382 100644
--- a/dev-packages/e2e-tests/test-applications/react-router-6/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-router-6/package.json
@@ -45,7 +45,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
},
"sentryTest": {
"canaryVariants": [
diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes.ts b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes.ts
index 5a9fa9c841aa..315b794cb70a 100644
--- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes.ts
+++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes.ts
@@ -5,6 +5,7 @@ export default [
...prefix('performance', [
index('routes/performance/index.tsx'),
route('ssr', 'routes/performance/ssr.tsx'),
+ route('single-segment', 'routes/performance/single-segment.tsx'),
route('with/:param', 'routes/performance/dynamic-param.tsx'),
route('static', 'routes/performance/static.tsx'),
route('server-loader', 'routes/performance/server-loader.tsx'),
diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes/performance/single-segment.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes/performance/single-segment.tsx
new file mode 100644
index 000000000000..0fb1943c6723
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes/performance/single-segment.tsx
@@ -0,0 +1,7 @@
+export default function SingleSegmentPage() {
+ return (
+
+
Single Segment Page
+
+ );
+}
diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/tests/performance/performance.server.test.ts b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/tests/performance/performance.server.test.ts
index bf3cb1682ca2..98db532433db 100644
--- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/tests/performance/performance.server.test.ts
+++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/tests/performance/performance.server.test.ts
@@ -137,38 +137,35 @@ test.describe('server - instrumentation API performance', () => {
'Dev server emits extra http.server segments for module requests',
);
- // Navigate to `/performance/` with the trailing slash: `/performance` is answered with a 301 to
- // it, and that redirect is a second request with a second `http.server` segment. It should not
- // be sent at all — `ignoreStatusCodes` covers 301 — but that option is only applied to
- // transactions, so span streaming emits it. Going straight to the final URL keeps this test
- // about double-instrumentation instead of failing on the redirect.
+ // The route is only requested by this test, and segments are filtered by its path: the event
+ // proxy receives the segments of every test running in parallel, so without the filter
+ // requests from other tests would show up as duplicates.
//
// A streamed server segment is named after the method alone until a route is matched, so a
- // duplicate shows up as a bare `GET`. Collect the origin and path alongside the name — they are
- // what says which instrumentation emitted the extra segment, and for which request.
+ // duplicate shows up as a bare `GET`. Collect the origin alongside the name — it is what says
+ // which instrumentation emitted the extra segment.
+ const urlPath = '/performance/single-segment';
const httpServerSegments: Array> = [];
void waitForStreamedSpans(APP_NAME, spans => {
for (const span of spans) {
- if (getSpanOp(span) === 'http.server' && span.is_segment) {
+ if (getSpanOp(span) === 'http.server' && span.is_segment && span.attributes['url.path']?.value === urlPath) {
httpServerSegments.push({
name: span.name,
origin: span.attributes['sentry.origin']?.value,
- urlPath: span.attributes['url.path']?.value,
});
}
}
return false;
});
- await page.goto(`/performance/`);
+ await page.goto(urlPath);
// Give any (erroneous) duplicate span time to arrive before asserting.
await page.waitForTimeout(3000);
expect(httpServerSegments).toEqual([
{
- name: 'GET /performance',
+ name: 'GET /performance/single-segment',
origin: 'auto.http.react_router.instrumentation_api',
- urlPath: '/performance/',
},
]);
});
diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-lazy-routes/package.json b/dev-packages/e2e-tests/test-applications/react-router-7-lazy-routes/package.json
index 4c0333dac6bf..cf4f7afdd31a 100644
--- a/dev-packages/e2e-tests/test-applications/react-router-7-lazy-routes/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-router-7-lazy-routes/package.json
@@ -42,6 +42,6 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
}
}
diff --git a/dev-packages/e2e-tests/test-applications/react-router-cross-usage/package.json b/dev-packages/e2e-tests/test-applications/react-router-cross-usage/package.json
index 9069a62bfe86..0eb7e8d48267 100644
--- a/dev-packages/e2e-tests/test-applications/react-router-cross-usage/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-router-cross-usage/package.json
@@ -43,7 +43,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "serve": "14.0.1"
+ "serve": "14.2.8"
},
"sentryTest": {
"baseVariant": {
diff --git a/dev-packages/e2e-tests/test-applications/react-send-to-sentry/package.json b/dev-packages/e2e-tests/test-applications/react-send-to-sentry/package.json
index 78309062e685..79df7bc26d6c 100644
--- a/dev-packages/e2e-tests/test-applications/react-send-to-sentry/package.json
+++ b/dev-packages/e2e-tests/test-applications/react-send-to-sentry/package.json
@@ -42,9 +42,10 @@
},
"devDependencies": {
"@playwright/test": "1.64.1",
- "serve": "14.0.1"
+ "serve": "14.2.8"
},
"sentryTest": {
- "optional": true
+ "optional": true,
+ "needsSecrets": true
}
}
diff --git a/dev-packages/e2e-tests/test-applications/remix-sourcemaps/assert-build.ts b/dev-packages/e2e-tests/test-applications/remix-sourcemaps/assert-build.ts
index bac48fb868dd..607a789fc0e9 100644
--- a/dev-packages/e2e-tests/test-applications/remix-sourcemaps/assert-build.ts
+++ b/dev-packages/e2e-tests/test-applications/remix-sourcemaps/assert-build.ts
@@ -46,8 +46,7 @@ for (const chunk of chunks) {
}
console.log(`no client chunk carries more than one debug ID (${chunks.length} chunks)\n`);
-// The SDK turns on hidden source maps when the app sets none, and asks the bundler plugin to
-// remove them from both the client and the SSR output, also when no upload runs.
+// Without an auth token the SDK turns no source maps on, so the build writes none.
if (process.env.E2E_NO_UPLOAD) {
// The mock server only writes its results file when a request reaches it.
const requests = fs.existsSync('.tmp_mock_uploads.json') ? loadMockServerResults() : [];
diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json b/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json
index 7e4b61b95afa..76a006213b41 100644
--- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json
+++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json
@@ -17,6 +17,7 @@
"@sentry/solid": "file:../../packed/sentry-solid-packed.tgz",
"@solidjs/router": "^2.0.0",
"@solidjs/web": "^2.0.0",
+ "graphql": "16.9.0",
"solid-js": "^2.0.0"
},
"devDependencies": {
@@ -24,7 +25,8 @@
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
"@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz",
- "@sentry/conventions": "0.35.0",
+ "@sentry/conventions": "0.36.0",
+ "@sentry/node": "file:../../packed/sentry-node-packed.tgz",
"@solidjs/vite-plugin": "^3.0.0",
"typescript": "^5.4.5",
"vite": "^8.1.5",
diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/Home.tsx b/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/Home.tsx
index 65ef2fc1eced..4a4e2e891f2c 100644
--- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/Home.tsx
+++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/Home.tsx
@@ -1,5 +1,5 @@
import { createSignal } from 'solid-js';
-import { failingServerFunction } from './server-functions';
+import { failingServerFunction, graphqlServerFunction } from './server-functions';
export default function Home() {
const [result, setResult] = createSignal('');
@@ -17,6 +17,14 @@ export default function Home() {
>
Call failing server function
+
{result()}
);
diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/server-functions.ts b/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/server-functions.ts
index cab935d77837..3544aa2a6e9e 100644
--- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/server-functions.ts
+++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/server-functions.ts
@@ -1,4 +1,13 @@
+import { buildSchema, graphql } from 'graphql';
+
export async function failingServerFunction(): Promise {
'use server';
throw new Error('Error thrown from a server function in Solid 2 SSR E2E test app');
}
+
+export async function graphqlServerFunction(): Promise {
+ 'use server';
+ const schema = buildSchema('type Query { hello: String }');
+ const result = await graphql({ schema, source: 'query Hello { hello }', rootValue: { hello: () => 'world' } });
+ return String(result.data?.hello);
+}
diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/bundled-dependency.server.test.ts b/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/bundled-dependency.server.test.ts
new file mode 100644
index 000000000000..67b01772bd8d
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/bundled-dependency.server.test.ts
@@ -0,0 +1,33 @@
+import { expect, test } from '@playwright/test';
+import { GRAPHQL_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
+import { GRAPHQL, HTTP_SERVER } from '@sentry/conventions/op';
+import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+
+test('instruments a dependency the server build bundles', async ({ page }) => {
+ const graphqlSpanPromise = waitForStreamedSpan('solid-2-ssr', span => {
+ return getSpanOp(span) === GRAPHQL && span.attributes?.[GRAPHQL_OPERATION_NAME]?.value === 'Hello';
+ });
+ // The server function's request span. It continues the pageload's trace, as the page request does, so it is
+ // found by its method within the trace of the graphql span.
+ const serverSpanPromise = graphqlSpanPromise.then(graphqlSpan =>
+ waitForStreamedSpan(
+ 'solid-2-ssr',
+ span =>
+ getSpanOp(span) === HTTP_SERVER &&
+ span.is_segment &&
+ span.trace_id === graphqlSpan.trace_id &&
+ span.name.startsWith('POST'),
+ 0,
+ ),
+ );
+
+ await page.goto('/');
+ await page.locator('#graphqlBtn').click();
+ await expect(page.locator('#result')).toHaveText('world');
+
+ const [graphqlSpan, serverSpan] = await Promise.all([graphqlSpanPromise, serverSpanPromise]);
+
+ expect(graphqlSpan.attributes?.[SENTRY_ORIGIN]?.value).toMatch(/^auto\.graphql\./);
+ expect(graphqlSpan.parent_span_id).toBeDefined();
+ expect(serverSpan.status).not.toBe('error');
+});
diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/trace-propagation.test.ts b/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/trace-propagation.test.ts
index a5719de334fd..a1ccc3007f28 100644
--- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/trace-propagation.test.ts
+++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/trace-propagation.test.ts
@@ -1,12 +1,9 @@
import { expect, test } from '@playwright/test';
import { URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_SERVER, PAGELOAD } from '@sentry/conventions/op';
-import { getRuntime, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
test('continues the server trace in the pageload', async ({ page }) => {
- // On Cloudflare, nothing sends the trace to the browser yet: `addServerTimingTraceHeader` only covers Node.
- test.skip(getRuntime() === 'cloudflare', 'No trace propagation to the browser on Cloudflare yet');
-
// Other tests request `/user/:id` too, so both spans are matched on a path no other test uses.
const path = `/user/trace-${Date.now()}`;
diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/vite.config.ts b/dev-packages/e2e-tests/test-applications/solid-2-ssr/vite.config.ts
index 77919094f2f5..5aee3f41c812 100644
--- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/vite.config.ts
+++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/vite.config.ts
@@ -1,3 +1,4 @@
+import { sentryVitePlugin } from '@sentry/node/vite';
import solid from '@solidjs/vite-plugin';
import { defineConfig } from 'vite';
@@ -13,6 +14,12 @@ export default defineConfig({
serverFunctions: true,
observe: process.env.SOLID_OBSERVE === '1',
}),
+ // Instruments the dependencies the server build bundles, such as `graphql`. No auth token, so nothing is uploaded.
+ sentryVitePlugin({
+ telemetry: false,
+ sourcemaps: { disable: true },
+ release: { create: false, finalize: false, inject: false },
+ }),
],
build: {
target: 'esnext',
diff --git a/dev-packages/e2e-tests/test-applications/solid-2/package.json b/dev-packages/e2e-tests/test-applications/solid-2/package.json
index b316900a2e21..c9433e77f520 100644
--- a/dev-packages/e2e-tests/test-applications/solid-2/package.json
+++ b/dev-packages/e2e-tests/test-applications/solid-2/package.json
@@ -23,7 +23,7 @@
},
"devDependencies": {
"@playwright/test": "1.64.1",
- "@sentry/conventions": "0.35.0",
+ "@sentry/conventions": "0.36.0",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
"@solidjs/vite-plugin": "^3.0.0",
"typescript": "^5.4.5",
diff --git a/dev-packages/e2e-tests/test-applications/solidstart-1-tunnel/tests/build-assets.test.ts b/dev-packages/e2e-tests/test-applications/solidstart-1-tunnel/tests/build-assets.test.ts
new file mode 100644
index 000000000000..8c08e841fa29
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/solidstart-1-tunnel/tests/build-assets.test.ts
@@ -0,0 +1,28 @@
+import { expect, test } from '@playwright/test';
+import { getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils';
+
+// This app runs under a base path (`/app/`), so it also tests the build file filter with a base path.
+const BUILD_FILE_PATH = '/app/_build/assets/entry.js.map';
+const PAGE_PATH = '/app/after-build-file';
+
+// In development, the server SDK does not know the base path when it initializes.
+test.skip(process.env.TEST_ENV === 'development', 'Production only');
+
+test('does not send a server span for a build file under the base path', async ({ baseURL }) => {
+ const segmentPaths: string[] = [];
+ const pageSegmentPromise = waitForStreamedSpans('solidstart-1-tunnel', spans => {
+ segmentPaths.push(
+ ...spans
+ .filter(span => span.is_segment && getSpanOp(span) === 'http.server')
+ .map(span => `${span.attributes['url.path']?.value}`),
+ );
+ return segmentPaths.includes(PAGE_PATH);
+ });
+
+ await fetch(`${baseURL}${BUILD_FILE_PATH}`);
+ // A span for the build file would arrive before the span of this later request.
+ await fetch(`${baseURL}${PAGE_PATH}`);
+ await pageSegmentPromise;
+
+ expect(segmentPaths).not.toContain(BUILD_FILE_PATH);
+});
diff --git a/dev-packages/e2e-tests/test-applications/solidstart-2-tunnel/tests/build-assets.test.ts b/dev-packages/e2e-tests/test-applications/solidstart-2-tunnel/tests/build-assets.test.ts
new file mode 100644
index 000000000000..b651f5a1adae
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/solidstart-2-tunnel/tests/build-assets.test.ts
@@ -0,0 +1,28 @@
+import { expect, test } from '@playwright/test';
+import { getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils';
+
+// This app runs under a base path (`/app/`), so it also tests the build file filter with a base path.
+const BUILD_FILE_PATH = '/app/_build/assets/entry.js.map';
+const PAGE_PATH = '/app/after-build-file';
+
+// In development, the server SDK does not know the base path when it initializes.
+test.skip(process.env.TEST_ENV === 'development', 'Production only');
+
+test('does not send a server span for a build file under the base path', async ({ baseURL }) => {
+ const segmentPaths: string[] = [];
+ const pageSegmentPromise = waitForStreamedSpans('solidstart-2-tunnel', spans => {
+ segmentPaths.push(
+ ...spans
+ .filter(span => span.is_segment && getSpanOp(span) === 'http.server')
+ .map(span => `${span.attributes['url.path']?.value}`),
+ );
+ return segmentPaths.includes(PAGE_PATH);
+ });
+
+ await fetch(`${baseURL}${BUILD_FILE_PATH}`);
+ // A span for the build file would arrive before the span of this later request.
+ await fetch(`${baseURL}${PAGE_PATH}`);
+ await pageSegmentPromise;
+
+ expect(segmentPaths).not.toContain(BUILD_FILE_PATH);
+});
diff --git a/dev-packages/e2e-tests/test-applications/solidstart-2/assert-build.ts b/dev-packages/e2e-tests/test-applications/solidstart-2/assert-build.ts
index a36e573063dc..f65997d009a2 100644
--- a/dev-packages/e2e-tests/test-applications/solidstart-2/assert-build.ts
+++ b/dev-packages/e2e-tests/test-applications/solidstart-2/assert-build.ts
@@ -1,25 +1,77 @@
+import * as assert from 'node:assert/strict';
import * as fs from 'node:fs';
import * as path from 'node:path';
-import { assertSourceMapUpload, findDebugIdsInFilesWithGlobCharacters } from '@sentry-internal/test-utils';
+import {
+ assertSourceMapUpload,
+ findDebugIdsInFilesWithGlobCharacters,
+ findInjectedDebugIds,
+ findSourceMapFiles,
+ findSourceMappingUrlComments,
+ getChunkUploadPosts,
+ loadMockServerResults,
+} from '@sentry-internal/test-utils';
const CLIENT_OUTPUT = path.join('.output', 'public');
const SERVER_OUTPUT = path.join('.output', 'server');
-// The app does not set `build.sourcemap`, so the SDK enables hidden maps and must delete them after upload.
-// TODO: The client maps stay in `.output/public`, because the SDK's deletion glob `./**/*.map` skips dot
-// folders. Add `CLIENT_OUTPUT` to `strippedDirs` once the SDK deletes them.
-assertSourceMapUpload({
- outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT],
- strippedDirs: [SERVER_OUTPUT],
- markers: { 'client source': 'SOURCEMAP_MARKER_CLIENT', 'server source': 'SOURCEMAP_MARKER_SERVER' },
- debugIdsWithoutSourceMap: [
- // Written by the build, see `recordChunksWithoutSourceMap` in `vite.config.ts`.
- ...(fs.existsSync('.tmp_debug_ids_without_source_map')
- ? fs.readFileSync('.tmp_debug_ids_without_source_map', 'utf8').split('\n').filter(Boolean)
- : []),
- ...findDebugIdsInFilesWithGlobCharacters({ outputDir: SERVER_OUTPUT }),
- ],
-});
+/** Debug IDs of chunks for which no source map can be uploaded. */
+const debugIdsWithoutSourceMap = [
+ // Written by the build, see `recordChunksWithoutSourceMap` in `vite.config.ts`.
+ ...(fs.existsSync('.tmp_debug_ids_without_source_map')
+ ? fs.readFileSync('.tmp_debug_ids_without_source_map', 'utf8').split('\n').filter(Boolean)
+ : []),
+ ...findDebugIdsInFilesWithGlobCharacters({ outputDir: SERVER_OUTPUT }),
+];
+
+// The app does not set `build.sourcemap`, so the SDK enables hidden maps and asks the bundler plugin to
+// remove them from the client output, also when no upload runs. `@sentry/nitro` handles the server output.
+if (process.env.E2E_NO_UPLOAD) {
+ assert.deepEqual(findSourceMapFiles({ outputDir: CLIENT_OUTPUT }), [], `Expected no source maps in ${CLIENT_OUTPUT}`);
+ assert.deepEqual(
+ findSourceMappingUrlComments({ outputDir: CLIENT_OUTPUT }),
+ [],
+ `Expected no sourceMappingURL comments in ${CLIENT_OUTPUT}`,
+ );
+} else if (process.env.E2E_VARIANT === 'manual-upload') {
+ // `upload: false` with `delete: false`: nothing reaches Sentry, and the hidden maps Sentry turned on
+ // stay with the debug IDs of their chunks, ready for an upload with the CLI.
+ assert.deepEqual(getChunkUploadPosts(loadMockServerResults()), [], 'Expected no source map upload');
+
+ for (const outputDir of [CLIENT_OUTPUT, SERVER_OUTPUT]) {
+ assert.deepEqual(
+ findSourceMappingUrlComments({ outputDir }),
+ [],
+ `Expected no sourceMappingURL comments in ${outputDir}`,
+ );
+
+ const mapDebugIds = new Set(
+ findSourceMapFiles({ outputDir }).map(file => {
+ const map = JSON.parse(fs.readFileSync(file, 'utf8')) as { debug_id?: string; debugId?: string };
+ return (map.debug_id ?? map.debugId)?.toLowerCase();
+ }),
+ );
+ const injectedDebugIds = findInjectedDebugIds({ outputDir });
+
+ assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`);
+ assert.deepEqual(
+ injectedDebugIds.filter(debugId => !mapDebugIds.has(debugId) && !debugIdsWithoutSourceMap.includes(debugId)),
+ [],
+ `Expected a source map with the same debug ID for every chunk in ${outputDir}`,
+ );
+ assert.ok(
+ injectedDebugIds.some(debugId => mapDebugIds.has(debugId)),
+ `Expected at least one chunk in ${outputDir} to have a kept source map`,
+ );
+ console.log(` ${outputDir}: ${injectedDebugIds.length} debug ID(s), ${mapDebugIds.size} kept source map(s)`);
+ }
+} else {
+ // Also covers the `delete-all` variant: the maps the app turned on are uploaded and removed.
+ assertSourceMapUpload({
+ outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT],
+ markers: { 'client source': 'SOURCEMAP_MARKER_CLIENT', 'server source': 'SOURCEMAP_MARKER_SERVER' },
+ debugIdsWithoutSourceMap,
+ });
+}
// The server adds the release to the page, so no content-hashed client file may contain it.
const clientFilesWithRelease = fs
diff --git a/dev-packages/e2e-tests/test-applications/solidstart-2/package.json b/dev-packages/e2e-tests/test-applications/solidstart-2/package.json
index bcb170291a94..9dbce23d24d2 100644
--- a/dev-packages/e2e-tests/test-applications/solidstart-2/package.json
+++ b/dev-packages/e2e-tests/test-applications/solidstart-2/package.json
@@ -9,7 +9,13 @@
"start": "HOST=localhost PORT=3030 node .output/server/index.mjs",
"test:prod": "TEST_ENV=production playwright test",
"test:build": "pnpm install && pnpm build",
- "test:assert": "node assert-build.ts && pnpm test:prod"
+ "test:assert": "node assert-build.ts && pnpm test:prod",
+ "test:build:no-upload": "pnpm install && E2E_NO_UPLOAD=1 pnpm build",
+ "test:assert:no-upload": "E2E_NO_UPLOAD=1 node assert-build.ts",
+ "test:build:manual-upload": "pnpm install && E2E_VARIANT=manual-upload pnpm build",
+ "test:assert:manual-upload": "E2E_VARIANT=manual-upload node assert-build.ts",
+ "test:build:delete-all": "pnpm install && E2E_VARIANT=delete-all pnpm build",
+ "test:assert:delete-all": "E2E_VARIANT=delete-all node assert-build.ts"
},
"type": "module",
"dependencies": {
@@ -31,6 +37,23 @@
"node": ">=24"
},
"sentryTest": {
- "optional": true
+ "optional": true,
+ "optionalVariants": [
+ {
+ "build-command": "pnpm test:build:no-upload",
+ "assert-command": "pnpm test:assert:no-upload",
+ "label": "solidstart-2 (no upload)"
+ },
+ {
+ "build-command": "pnpm test:build:manual-upload",
+ "assert-command": "pnpm test:assert:manual-upload",
+ "label": "solidstart-2 (manual upload)"
+ },
+ {
+ "build-command": "pnpm test:build:delete-all",
+ "assert-command": "pnpm test:assert:delete-all",
+ "label": "solidstart-2 (delete all)"
+ }
+ ]
}
}
diff --git a/dev-packages/e2e-tests/test-applications/solidstart-2/tests/performance.server.test.ts b/dev-packages/e2e-tests/test-applications/solidstart-2/tests/performance.server.test.ts
index e2e668c9ec90..d175ad0b25fd 100644
--- a/dev-packages/e2e-tests/test-applications/solidstart-2/tests/performance.server.test.ts
+++ b/dev-packages/e2e-tests/test-applications/solidstart-2/tests/performance.server.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from '@playwright/test';
-import { collectStreamedSpans, getSpanOp } from '@sentry-internal/test-utils';
+import { collectStreamedSpans, getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils';
test('sends a server action span on pageload', async ({ page }) => {
const spansPromise = collectStreamedSpans(
@@ -46,3 +46,40 @@ test('sends a server action span on client navigation', async ({ page }) => {
'code.function.name': { value: 'getPrefecture', type: 'string' },
});
});
+
+['/_build/assets/entry.js.map', '/_build/.vite/manifest.json'].forEach(path => {
+ test(`does not send a server span for the file ${path}`, async ({ baseURL }) => {
+ const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);
+
+ expect(segmentPaths).not.toContain(path);
+ });
+});
+
+// Routes that look like build output. They also show that the helper sees sent segments, so the tests above cannot
+// pass by accident.
+['/users/jane.doe', '/users/_build/'].forEach(path => {
+ test(`sends a server span for the route ${path}`, async ({ baseURL }) => {
+ const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);
+
+ expect(segmentPaths).toContain(path);
+ });
+});
+
+/**
+ * Requests `path`, then a page. Returns the `url.path` of each server segment up to the page's segment, which arrives
+ * after any segment for `path`.
+ */
+async function getServerSegmentPathsUntilPage(baseURL: string, path: string): Promise {
+ const pagePath = `/users/after${path.replace(/\W+/g, '-')}`;
+ const segmentPaths: string[] = [];
+ const pageSegmentPromise = waitForStreamedSpans('solidstart-2', spans => {
+ segmentPaths.push(...spans.filter(span => span.is_segment).map(span => `${span.attributes['url.path']?.value}`));
+ return segmentPaths.includes(pagePath);
+ });
+
+ await fetch(`${baseURL}${path}`);
+ await fetch(`${baseURL}${pagePath}`);
+ await pageSegmentPromise;
+
+ return segmentPaths;
+}
diff --git a/dev-packages/e2e-tests/test-applications/solidstart-2/vite.config.ts b/dev-packages/e2e-tests/test-applications/solidstart-2/vite.config.ts
index 74811201d2cf..8135f882102d 100644
--- a/dev-packages/e2e-tests/test-applications/solidstart-2/vite.config.ts
+++ b/dev-packages/e2e-tests/test-applications/solidstart-2/vite.config.ts
@@ -5,26 +5,34 @@ import { defineConfig } from 'vite';
import * as fs from 'node:fs';
// Rolldown emits no map for chunks without mappable source (e.g. Vite's preload helper), so their debug
-// IDs can't be uploaded. Recorded here because the SDK deletes all maps after the upload.
+// IDs can't be uploaded. Recorded before the bundler plugin removes the maps from the bundle.
function recordChunksWithoutSourceMap() {
return {
name: 'record-chunks-without-source-map',
apply: 'build' as const,
enforce: 'post' as const,
- writeBundle(_options: unknown, bundle: Record) {
- for (const output of Object.values(bundle)) {
- if (output.type !== 'chunk' || !output.code || bundle[`${output.fileName}.map`]) {
- continue;
+ generateBundle: {
+ order: 'pre' as const,
+ handler(_options: unknown, bundle: Record) {
+ for (const output of Object.values(bundle)) {
+ if (output.type !== 'chunk' || !output.code || bundle[`${output.fileName}.map`]) {
+ continue;
+ }
+ for (const match of output.code.matchAll(/sentry-dbid-([\da-f-]{36})/gi)) {
+ fs.appendFileSync('.tmp_debug_ids_without_source_map', `${match[1]!.toLowerCase()}\n`);
+ }
}
- for (const match of output.code.matchAll(/sentry-dbid-([\da-f-]{36})/gi)) {
- fs.appendFileSync('.tmp_debug_ids_without_source_map', `${match[1]!.toLowerCase()}\n`);
- }
- }
+ },
},
};
}
+// `manual-upload`: Sentry uploads nothing and keeps the maps it turned on, for an upload with the CLI.
+// `delete-all`: the app turns source maps on itself, and Sentry removes them.
+const variant = process.env.E2E_VARIANT;
+
export default defineConfig({
+ build: variant === 'delete-all' ? { sourcemap: true } : undefined,
plugins: [
solidStart({
appRoot: './src',
@@ -32,11 +40,17 @@ export default defineConfig({
}),
sentrySolidStart({
sentryUrl: 'http://localhost:3032',
- authToken: 'fake-auth-token',
+ authToken: process.env.E2E_NO_UPLOAD ? undefined : 'fake-auth-token',
org: 'test-org',
project: 'test-project',
release: { name: 'test-release' },
debug: true,
+ sourcemaps:
+ variant === 'manual-upload'
+ ? { upload: false, delete: false }
+ : variant === 'delete-all'
+ ? { delete: true }
+ : undefined,
}),
// `serverDir` defaults to `false`, which skips plugin scanning entirely.
nitro({ serverDir: './server' }),
diff --git a/dev-packages/e2e-tests/test-applications/solidstart/app.config.ts b/dev-packages/e2e-tests/test-applications/solidstart/app.config.ts
index 176403391980..21b532bdf292 100644
--- a/dev-packages/e2e-tests/test-applications/solidstart/app.config.ts
+++ b/dev-packages/e2e-tests/test-applications/solidstart/app.config.ts
@@ -4,19 +4,30 @@ import { defineConfig } from '@solidjs/start/config';
// The inject mode variants set `E2E_TEST_INJECT_MODE` for the build and the test run.
const injectMode = process.env.E2E_TEST_INJECT_MODE as 'top-level-import' | 'experimental_dynamic-import' | undefined;
+// `manual-upload`: Sentry uploads nothing and keeps the maps it turned on, for an upload with the CLI.
+// `delete-all`: the app turns source maps on itself, and Sentry removes them.
+const variant = process.env.E2E_VARIANT;
+
export default defineConfig(
withSentry(
{
middleware: './src/middleware.ts',
+ ...(variant === 'delete-all' && { vite: { build: { sourcemap: true } } }),
},
{
sentryUrl: 'http://localhost:3032',
- authToken: 'fake-auth-token',
+ authToken: process.env.E2E_NO_UPLOAD ? undefined : 'fake-auth-token',
org: 'test-org',
project: 'test-project',
release: { name: 'test-release' },
debug: true,
autoInjectServerSentry: injectMode,
+ sourcemaps:
+ variant === 'manual-upload'
+ ? { upload: false, delete: false }
+ : variant === 'delete-all'
+ ? { delete: true }
+ : undefined,
},
),
);
diff --git a/dev-packages/e2e-tests/test-applications/solidstart/assert-build.ts b/dev-packages/e2e-tests/test-applications/solidstart/assert-build.ts
index 243960c51ac5..c6f189e4b6c4 100644
--- a/dev-packages/e2e-tests/test-applications/solidstart/assert-build.ts
+++ b/dev-packages/e2e-tests/test-applications/solidstart/assert-build.ts
@@ -1,18 +1,69 @@
+import * as assert from 'node:assert/strict';
import * as fs from 'node:fs';
import * as path from 'node:path';
-import { assertSourceMapUpload } from '@sentry-internal/test-utils';
+import {
+ assertSourceMapUpload,
+ findInjectedDebugIds,
+ findSourceMapFiles,
+ findSourceMappingUrlComments,
+ getChunkUploadPosts,
+ loadMockServerResults,
+} from '@sentry-internal/test-utils';
const CLIENT_OUTPUT = path.join('.output', 'public');
const SERVER_OUTPUT = path.join('.output', 'server');
-// The app does not set `build.sourcemap`, so the SDK enables hidden maps and must delete them after upload.
-// Vinxi writes the server output after the SDK deleted the maps, so `.output/server` keeps Nitro's own maps,
-// which carry no mappings. They are not served, so only the client output must be free of maps.
-assertSourceMapUpload({
- outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT],
- strippedDirs: [CLIENT_OUTPUT],
- markers: { 'client source': 'SOURCEMAP_MARKER_CLIENT', 'server source': 'SOURCEMAP_MARKER_SERVER' },
-});
+// The app does not set `build.sourcemap`, so the SDK enables hidden maps and asks the bundler plugin to
+// remove them, also when no upload runs. Vinxi writes the server output after that, so `.output/server`
+// keeps Nitro's own maps, which carry no mappings. They are not served, so only the client output must
+// be free of maps.
+if (process.env.E2E_NO_UPLOAD) {
+ assert.deepEqual(findSourceMapFiles({ outputDir: CLIENT_OUTPUT }), [], `Expected no source maps in ${CLIENT_OUTPUT}`);
+ assert.deepEqual(
+ findSourceMappingUrlComments({ outputDir: CLIENT_OUTPUT }),
+ [],
+ `Expected no sourceMappingURL comments in ${CLIENT_OUTPUT}`,
+ );
+} else if (process.env.E2E_VARIANT === 'manual-upload') {
+ // `upload: false` with `delete: false`: nothing reaches Sentry, and the hidden maps Sentry turned on
+ // stay with the debug IDs of their chunks, ready for an upload with the CLI.
+ assert.deepEqual(getChunkUploadPosts(loadMockServerResults()), [], 'Expected no source map upload');
+
+ for (const outputDir of [CLIENT_OUTPUT]) {
+ assert.deepEqual(
+ findSourceMappingUrlComments({ outputDir }),
+ [],
+ `Expected no sourceMappingURL comments in ${outputDir}`,
+ );
+
+ const mapDebugIds = new Set(
+ findSourceMapFiles({ outputDir }).map(file => {
+ const map = JSON.parse(fs.readFileSync(file, 'utf8')) as { debug_id?: string; debugId?: string };
+ return (map.debug_id ?? map.debugId)?.toLowerCase();
+ }),
+ );
+ const injectedDebugIds = findInjectedDebugIds({ outputDir });
+
+ assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`);
+ assert.deepEqual(
+ injectedDebugIds.filter(debugId => !mapDebugIds.has(debugId)),
+ [],
+ `Expected a source map with the same debug ID for every chunk in ${outputDir}`,
+ );
+ assert.ok(
+ injectedDebugIds.some(debugId => mapDebugIds.has(debugId)),
+ `Expected at least one chunk in ${outputDir} to have a kept source map`,
+ );
+ console.log(` ${outputDir}: ${injectedDebugIds.length} debug ID(s), ${mapDebugIds.size} kept source map(s)`);
+ }
+} else {
+ // Also covers the `delete-all` variant: the maps the app turned on are uploaded and removed.
+ assertSourceMapUpload({
+ outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT],
+ strippedDirs: [CLIENT_OUTPUT],
+ markers: { 'client source': 'SOURCEMAP_MARKER_CLIENT', 'server source': 'SOURCEMAP_MARKER_SERVER' },
+ });
+}
// The server adds the release to the page, so no content-hashed client file may contain it.
const clientFilesWithRelease = fs
diff --git a/dev-packages/e2e-tests/test-applications/solidstart/package.json b/dev-packages/e2e-tests/test-applications/solidstart/package.json
index c703e71a8568..a7293add49ee 100644
--- a/dev-packages/e2e-tests/test-applications/solidstart/package.json
+++ b/dev-packages/e2e-tests/test-applications/solidstart/package.json
@@ -10,7 +10,13 @@
"test:prod": "TEST_ENV=production playwright test",
"test:build": "pnpm install && pnpm build",
"test:assert": "node assert-build.ts && pnpm test:prod && pnpm test:dev",
- "test:dev": "TEST_ENV=development playwright test db"
+ "test:dev": "TEST_ENV=development playwright test db",
+ "test:build:no-upload": "pnpm install && E2E_NO_UPLOAD=1 pnpm build",
+ "test:assert:no-upload": "E2E_NO_UPLOAD=1 node assert-build.ts",
+ "test:build:manual-upload": "pnpm install && E2E_VARIANT=manual-upload pnpm build",
+ "test:assert:manual-upload": "E2E_VARIANT=manual-upload node assert-build.ts",
+ "test:build:delete-all": "pnpm install && E2E_VARIANT=delete-all pnpm build",
+ "test:assert:delete-all": "E2E_VARIANT=delete-all node assert-build.ts"
},
"type": "module",
"dependencies": {
@@ -21,7 +27,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "@sentry/conventions": "0.35.0",
+ "@sentry/conventions": "0.36.0",
"@solidjs/meta": "^0.29.4",
"@solidjs/router": "^1.0.0",
"@solidjs/start": "^1.0.2",
@@ -47,6 +53,21 @@
"build-command": "VITE_E2E_TEST_TRACE_LIFECYCLE=static pnpm test:build",
"assert-command": "E2E_TEST_TRACE_LIFECYCLE=static pnpm test:prod",
"label": "solidstart (static trace lifecycle)"
+ },
+ {
+ "build-command": "pnpm test:build:no-upload",
+ "assert-command": "pnpm test:assert:no-upload",
+ "label": "solidstart (no upload)"
+ },
+ {
+ "build-command": "pnpm test:build:manual-upload",
+ "assert-command": "pnpm test:assert:manual-upload",
+ "label": "solidstart (manual upload)"
+ },
+ {
+ "build-command": "pnpm test:build:delete-all",
+ "assert-command": "pnpm test:assert:delete-all",
+ "label": "solidstart (delete all)"
}
]
}
diff --git a/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.static-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.static-lifecycle.test.ts
index bbac70d1abcb..c6adae79775e 100644
--- a/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.static-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.static-lifecycle.test.ts
@@ -1,4 +1,4 @@
-import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
+import { SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
import { waitForTransaction } from '@sentry-internal/test-utils';
@@ -49,3 +49,46 @@ test('sends a server action transaction on client navigation', async ({ page })
]),
);
});
+
+[
+ // SolidStart build output that the HTTP integration does not ignore.
+ '/_build/assets/entry.js.map',
+ '/_build/.vite/manifest.json',
+ // Common static file that the HTTP integration ignores.
+ '/favicon.ico',
+].forEach(path => {
+ test(`does not send a server transaction for the file ${path}`, async ({ baseURL }) => {
+ const transactionPaths = await getServerTransactionPathsUntilPage(`${baseURL}`, path);
+
+ expect(transactionPaths).not.toContain(path);
+ });
+});
+
+// Routes that look like build output. They also show that the helper sees sent transactions, so the tests above cannot
+// pass by accident.
+['/users/jane.doe', '/users/_build/'].forEach(path => {
+ test(`sends a server transaction for the route ${path}`, async ({ baseURL }) => {
+ const transactionPaths = await getServerTransactionPathsUntilPage(`${baseURL}`, path);
+
+ expect(transactionPaths).toContain(path);
+ });
+});
+
+/**
+ * Requests `path`, then a page. Returns the `url.path` of each server transaction up to the page's transaction,
+ * which arrives after any transaction for `path`.
+ */
+async function getServerTransactionPathsUntilPage(baseURL: string, path: string): Promise {
+ const pagePath = `/users/after${path.replace(/\W+/g, '-')}`;
+ const transactionPaths: string[] = [];
+ const pageTransactionPromise = waitForTransaction('solidstart', transactionEvent => {
+ transactionPaths.push(`${transactionEvent.contexts?.trace?.data?.[URL_PATH]}`);
+ return transactionPaths.includes(pagePath);
+ });
+
+ await fetch(`${baseURL}${path}`);
+ await fetch(`${baseURL}${pagePath}`);
+ await pageTransactionPromise;
+
+ return transactionPaths;
+}
diff --git a/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.streaming-lifecycle.test.ts
index 251a1601ae53..fb2886396856 100644
--- a/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.streaming-lifecycle.test.ts
@@ -1,5 +1,6 @@
+import { URL_PATH } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
-import { collectStreamedSpans, getSpanOp } from '@sentry-internal/test-utils';
+import { collectStreamedSpans, getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils';
test('sends a server action span on pageload', async ({ page }) => {
const spansPromise = collectStreamedSpans(
@@ -46,3 +47,46 @@ test('sends a server action span on client navigation', async ({ page }) => {
'code.function.name': { value: 'getPrefecture', type: 'string' },
});
});
+
+[
+ // SolidStart build output that the HTTP integration does not ignore.
+ '/_build/assets/entry.js.map',
+ '/_build/.vite/manifest.json',
+ // Common static file that the HTTP integration ignores.
+ '/favicon.ico',
+].forEach(path => {
+ test(`does not send a server span for the file ${path}`, async ({ baseURL }) => {
+ const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);
+
+ expect(segmentPaths).not.toContain(path);
+ });
+});
+
+// Routes that look like build output. They also show that the helper sees sent segments, so the tests above cannot
+// pass by accident.
+['/users/jane.doe', '/users/_build/'].forEach(path => {
+ test(`sends a server span for the route ${path}`, async ({ baseURL }) => {
+ const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);
+
+ expect(segmentPaths).toContain(path);
+ });
+});
+
+/**
+ * Requests `path`, then a page. Returns the `url.path` of each server segment up to the page's segment, which arrives
+ * after any segment for `path`.
+ */
+async function getServerSegmentPathsUntilPage(baseURL: string, path: string): Promise {
+ const pagePath = `/users/after${path.replace(/\W+/g, '-')}`;
+ const segmentPaths: string[] = [];
+ const pageSegmentPromise = waitForStreamedSpans('solidstart', spans => {
+ segmentPaths.push(...spans.filter(span => span.is_segment).map(span => `${span.attributes[URL_PATH]?.value}`));
+ return segmentPaths.includes(pagePath);
+ });
+
+ await fetch(`${baseURL}${path}`);
+ await fetch(`${baseURL}${pagePath}`);
+ await pageSegmentPromise;
+
+ return segmentPaths;
+}
diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2.5.0-twp/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-2.5.0-twp/package.json
index 765d71dccb12..2889ad2612c6 100644
--- a/dev-packages/e2e-tests/test-applications/sveltekit-2.5.0-twp/package.json
+++ b/dev-packages/e2e-tests/test-applications/sveltekit-2.5.0-twp/package.json
@@ -24,7 +24,7 @@
"@sveltejs/kit": "2.8.3",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"svelte": "^5.0.0-next.115",
- "svelte-check": "^3.6.0",
+ "svelte-check": "^4.7.8",
"typescript": "^5.0.0",
"vite": "^5.4.11"
},
diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-2/package.json
index 6b7444a17ed4..6cd9feebb3c7 100644
--- a/dev-packages/e2e-tests/test-applications/sveltekit-2/package.json
+++ b/dev-packages/e2e-tests/test-applications/sveltekit-2/package.json
@@ -28,7 +28,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "@sentry/conventions": "0.35.0",
+ "@sentry/conventions": "0.36.0",
"@sveltejs/adapter-node": "^2.0.0",
"@sveltejs/kit": "2.70.4",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json
index 6d0d3f376fce..f147de3fd87b 100644
--- a/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json
+++ b/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json
@@ -21,7 +21,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "@sentry/conventions": "0.35.0",
+ "@sentry/conventions": "0.36.0",
"@sveltejs/adapter-node": "^6.0.0",
"@sveltejs/kit": "^3.0.0",
"@sveltejs/vite-plugin-svelte": "^7.3.1",
diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-cloudflare-pages/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-cloudflare-pages/package.json
index 7e983db34293..b8de6e77638c 100644
--- a/dev-packages/e2e-tests/test-applications/sveltekit-cloudflare-pages/package.json
+++ b/dev-packages/e2e-tests/test-applications/sveltekit-cloudflare-pages/package.json
@@ -21,7 +21,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
- "@sentry/conventions": "0.35.0",
+ "@sentry/conventions": "0.36.0",
"@sveltejs/adapter-cloudflare": "^5.0.3",
"@sveltejs/kit": "2.70.4",
"@sveltejs/vite-plugin-svelte": "^5.0.3",
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/.gitignore b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/.gitignore
index 4187ae735082..634fe9c9c6d9 100644
--- a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/.gitignore
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/.gitignore
@@ -9,3 +9,4 @@ src/routeTree.gen.ts
.tmp_chunks
.tmp_build_stdout
.tmp_build_stderr
+.tmp_debug_ids_without_source_map
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-build.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-build.ts
index d420d797a699..bf6de88af70b 100644
--- a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-build.ts
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-build.ts
@@ -24,12 +24,6 @@ const SERVER_OUTPUT = path.join('.output', 'server');
const CLIENT_MARKER = 'SOURCEMAP_MARKER_CLIENT';
const SERVER_MARKER = 'SOURCEMAP_MARKER_SERVER';
-const DEBUG_ID_PATTERN = /sentry-dbid-([\da-f-]{36})/gi;
-
-function readDebugIds(file: string): string[] {
- return [...fs.readFileSync(file, 'utf8').matchAll(DEBUG_ID_PATTERN)].map(match => (match[1] as string).toLowerCase());
-}
-
function emittedJsFiles(dir: string): string[] {
return fs
.readdirSync(dir, { recursive: true, withFileTypes: true })
@@ -37,22 +31,13 @@ function emittedJsFiles(dir: string): string[] {
.map(entry => path.join(entry.parentPath, entry.name));
}
-/** In debug mode, the Sentry plugin logs each file it deletes after the upload. */
-const deletedFiles = new Set(
- [...fs.readFileSync('.tmp_build_stdout', 'utf8').matchAll(/Deleting asset after upload: (.+)$/gm)].map(match =>
- path.relative(fs.realpathSync('.'), match[1] as string),
- ),
+/** Written by the build, see `recordChunksWithoutSourceMap` in `vite.config.ts`. */
+const debugIdsWithoutSourceMap = new Set(
+ fs.existsSync('.tmp_debug_ids_without_source_map')
+ ? fs.readFileSync('.tmp_debug_ids_without_source_map', 'utf8').split('\n').filter(Boolean)
+ : [],
);
-/** A chunk without mappable source, such as Nitro's runtime, gets a debug ID but no source map to upload. */
-function debugIdsOfChunksWithoutSourceMap(dir: string): Set {
- return new Set(
- emittedJsFiles(dir)
- .filter(file => !fs.existsSync(`${file}.map`) && !deletedFiles.has(`${file}.map`))
- .flatMap(readDebugIds),
- );
-}
-
function sourceMapsIn(dir: string): string[] {
return fs
.readdirSync(dir, { recursive: true, withFileTypes: true })
@@ -116,8 +101,9 @@ for (const outputDir of [CLIENT_OUTPUT, SERVER_OUTPUT]) {
const injectedDebugIds = findInjectedDebugIds({ outputDir });
assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`);
- const exemptDebugIds = debugIdsOfChunksWithoutSourceMap(outputDir);
- const unuploaded = injectedDebugIds.filter(debugId => !uploadedDebugIds.has(debugId) && !exemptDebugIds.has(debugId));
+ const unuploaded = injectedDebugIds.filter(
+ debugId => !uploadedDebugIds.has(debugId) && !debugIdsWithoutSourceMap.has(debugId),
+ );
assert.deepEqual(unuploaded, [], `Expected every debug ID in ${outputDir} to have an uploaded source map`);
// A file of Nitro's output can carry the debug ID of the SSR chunk it was built from.
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-manual-upload.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-manual-upload.ts
new file mode 100644
index 000000000000..5e53903c5fcf
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-manual-upload.ts
@@ -0,0 +1,51 @@
+import * as assert from 'assert/strict';
+import * as fs from 'fs';
+import * as path from 'path';
+import {
+ findInjectedDebugIds,
+ findSourceMapFiles,
+ findSourceMappingUrlComments,
+ getChunkUploadPosts,
+ loadMockServerResults,
+} from '@sentry-internal/test-utils';
+
+/** Written by the build, see `recordChunksWithoutSourceMap` in `vite.config.ts`. */
+const debugIdsWithoutSourceMap = new Set(
+ fs.existsSync('.tmp_debug_ids_without_source_map')
+ ? fs.readFileSync('.tmp_debug_ids_without_source_map', 'utf8').split('\n').filter(Boolean)
+ : [],
+);
+
+// `upload: false` with `delete: false`: nothing reaches Sentry, and the hidden maps Sentry turned on for
+// the client and the Nitro server stay with the debug IDs of their chunks, ready for an upload with the CLI.
+assert.deepEqual(getChunkUploadPosts(loadMockServerResults()), [], 'Expected no source map upload');
+
+for (const outputDir of [path.join('.output', 'public'), path.join('.output', 'server')]) {
+ assert.deepEqual(
+ findSourceMappingUrlComments({ outputDir }),
+ [],
+ `Expected no sourceMappingURL comments in ${outputDir}`,
+ );
+
+ const mapDebugIds = new Set(
+ findSourceMapFiles({ outputDir }).map(file => {
+ const map = JSON.parse(fs.readFileSync(file, 'utf8')) as { debug_id?: string; debugId?: string };
+ return (map.debug_id ?? map.debugId)?.toLowerCase();
+ }),
+ );
+ const injectedDebugIds = findInjectedDebugIds({ outputDir });
+
+ assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`);
+ assert.deepEqual(
+ injectedDebugIds.filter(debugId => !mapDebugIds.has(debugId) && !debugIdsWithoutSourceMap.has(debugId)),
+ [],
+ `Expected a source map with the same debug ID for every chunk in ${outputDir}`,
+ );
+ assert.ok(
+ injectedDebugIds.some(debugId => mapDebugIds.has(debugId)),
+ `Expected at least one chunk in ${outputDir} to have a kept source map`,
+ );
+ console.log(` ${outputDir}: ${injectedDebugIds.length} debug ID(s), ${mapDebugIds.size} kept source map(s)`);
+}
+
+console.log('All source map assertions passed!');
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-no-upload.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-no-upload.ts
new file mode 100644
index 000000000000..81ee63f2151a
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-no-upload.ts
@@ -0,0 +1,23 @@
+import * as assert from 'assert/strict';
+import * as fs from 'fs';
+import * as path from 'path';
+import { findSourceMapFiles, findSourceMappingUrlComments } from '@sentry-internal/test-utils';
+
+// Without an auth token no upload can run, so the SDK turns on no source maps for the client and the
+// Nitro server.
+for (const outputDir of [path.join('.output', 'public'), path.join('.output', 'server')]) {
+ assert.deepEqual(findSourceMapFiles({ outputDir }), [], `Expected no source maps in ${outputDir}`);
+ assert.deepEqual(
+ findSourceMappingUrlComments({ outputDir }),
+ [],
+ `Expected no sourceMappingURL comments in ${outputDir}`,
+ );
+}
+
+const buildLog = fs.readFileSync('.tmp_build_stdout', 'utf8') + fs.readFileSync('.tmp_build_stderr', 'utf8');
+assert.ok(
+ !buildLog.includes('deleteSourcemapsAfterUpload'),
+ 'Expected no message about `sourcemaps.deleteSourcemapsAfterUpload`, which the app does not set',
+);
+
+console.log('All source map assertions passed!');
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/package.json b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/package.json
index 1dd5050c0372..aa109970330d 100644
--- a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/package.json
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/package.json
@@ -7,7 +7,13 @@
"build": "node start-mock-sentry-server.mjs & vite build > .tmp_build_stdout 2> .tmp_build_stderr; BUILD_EXIT=$?; kill %1 2>/dev/null; if [ $BUILD_EXIT -ne 0 ]; then cat .tmp_build_stdout; cat .tmp_build_stderr >&2; fi; exit $BUILD_EXIT",
"clean": "npx rimraf node_modules pnpm-lock.yaml .output",
"test:build": "pnpm install && pnpm build",
- "test:assert": "pnpm ts-node --script-mode assert-build.ts"
+ "test:build:no-upload": "pnpm install && E2E_NO_UPLOAD=1 pnpm build",
+ "test:assert": "pnpm ts-node --script-mode assert-build.ts",
+ "test:assert:no-upload": "pnpm ts-node --script-mode assert-no-upload.ts",
+ "test:build:manual-upload": "pnpm install && E2E_VARIANT=manual-upload pnpm build",
+ "test:assert:manual-upload": "pnpm ts-node --script-mode assert-manual-upload.ts",
+ "test:build:delete-all": "pnpm install && E2E_VARIANT=delete-all pnpm build",
+ "test:assert:delete-all": "pnpm test:assert"
},
"dependencies": {
"@sentry/tanstackstart-react": "file:../../packed/sentry-tanstackstart-react-packed.tgz",
@@ -24,11 +30,28 @@
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react-swc": "^4.2.0",
- "ts-node": "10.9.1",
+ "ts-node": "10.9.2",
"typescript": "^5.9.0",
"vite": "^8.3.0"
},
"sentryTest": {
- "optional": true
+ "optional": true,
+ "optionalVariants": [
+ {
+ "build-command": "pnpm test:build:no-upload",
+ "assert-command": "pnpm test:assert:no-upload",
+ "label": "tanstackstart-react-sourcemaps (no upload)"
+ },
+ {
+ "build-command": "pnpm test:build:manual-upload",
+ "assert-command": "pnpm test:assert:manual-upload",
+ "label": "tanstackstart-react-sourcemaps (manual upload)"
+ },
+ {
+ "build-command": "pnpm test:build:delete-all",
+ "assert-command": "pnpm test:assert:delete-all",
+ "label": "tanstackstart-react-sourcemaps (delete all)"
+ }
+ ]
}
}
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/vite.config.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/vite.config.ts
index 34e4c52c56d4..898124522baf 100644
--- a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/vite.config.ts
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/vite.config.ts
@@ -2,21 +2,56 @@ import { sentryTanstackStart } from '@sentry/tanstackstart-react/vite';
import { tanstackStart } from '@tanstack/react-start/plugin/vite';
import viteReact from '@vitejs/plugin-react-swc';
import { nitro } from 'nitro/vite';
+import * as fs from 'node:fs';
import { defineConfig } from 'vite';
+// A chunk without mappable source, such as Nitro's runtime, gets a debug ID but no source map to
+// upload. Recorded before the Sentry plugin removes the maps in its own `generateBundle` hook.
+function recordChunksWithoutSourceMap() {
+ return {
+ name: 'record-chunks-without-source-map',
+ apply: 'build' as const,
+ generateBundle: {
+ order: 'pre' as const,
+ handler(_options: unknown, bundle: Record) {
+ for (const output of Object.values(bundle)) {
+ if (output.type !== 'chunk' || !output.code || bundle[`${output.fileName}.map`]) {
+ continue;
+ }
+ for (const match of output.code.matchAll(/sentry-dbid-([\da-f-]{36})/gi)) {
+ fs.appendFileSync('.tmp_debug_ids_without_source_map', `${match[1]!.toLowerCase()}\n`);
+ }
+ }
+ },
+ },
+ };
+}
+
+// `manual-upload`: Sentry uploads nothing and keeps the maps it turned on, for an upload with the CLI.
+// `delete-all`: the app turns source maps on itself, and Sentry removes them.
+const variant = process.env.E2E_VARIANT;
+
export default defineConfig({
+ build: variant === 'delete-all' ? { sourcemap: true } : undefined,
plugins: [
// Prerendering and the SPA shell render pages at build time, which must carry the release as well.
tanstackStart({ prerender: { enabled: true }, pages: [{ path: '/prerendered' }], spa: { enabled: true } }),
nitro(),
viteReact(),
+ recordChunksWithoutSourceMap(),
sentryTanstackStart({
sentryUrl: 'http://localhost:3032',
- authToken: 'fake-auth-token',
+ authToken: process.env.E2E_NO_UPLOAD ? undefined : 'fake-auth-token',
org: 'test-org',
project: 'test-project',
release: { name: 'test-release' },
debug: true,
+ sourcemaps:
+ variant === 'manual-upload'
+ ? { upload: false, delete: false }
+ : variant === 'delete-all'
+ ? { delete: true }
+ : undefined,
}),
],
});
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-static/package.json b/dev-packages/e2e-tests/test-applications/tanstackstart-react-static/package.json
index 878ce6975449..0b9e2a2f6f28 100644
--- a/dev-packages/e2e-tests/test-applications/tanstackstart-react-static/package.json
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-static/package.json
@@ -32,7 +32,7 @@
"@vitejs/plugin-react-swc": "^4.3.3",
"typescript": "^5.9.0",
"vite": "8.3.4",
- "vite-tsconfig-paths": "^5.1.4",
+ "vite-tsconfig-paths": "^6.1.1",
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz"
}
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json b/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json
index b6af9d9e98f7..4d127b218501 100644
--- a/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json
@@ -27,14 +27,14 @@
"mysql": "^2.18.1"
},
"devDependencies": {
- "@sentry/conventions": "0.35.0",
+ "@sentry/conventions": "0.36.0",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@types/node": "^24.10.0",
"@vitejs/plugin-react-swc": "^4.3.3",
"typescript": "^5.9.0",
"vite": "8.3.4",
- "vite-tsconfig-paths": "^5.1.4",
+ "vite-tsconfig-paths": "^6.1.1",
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz"
},
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/vite.config.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react/vite.config.ts
index 4c290a5899db..6de962e77b3e 100644
--- a/dev-packages/e2e-tests/test-applications/tanstackstart-react/vite.config.ts
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/vite.config.ts
@@ -7,21 +7,25 @@ import { nitro } from 'nitro/vite';
import { sentryTanstackStart } from '@sentry/tanstackstart-react/vite';
// Rolldown emits no map for chunks without mappable source (e.g. Vite's preload helper), so their debug
-// IDs can't be uploaded. Recorded here because the SDK deletes all maps after the upload.
+// IDs can't be uploaded. Recorded here because the Sentry plugin removes the maps from the bundle in its
+// own `generateBundle` hook.
function recordChunksWithoutSourceMap() {
return {
name: 'record-chunks-without-source-map',
apply: 'build' as const,
enforce: 'post' as const,
- writeBundle(_options: unknown, bundle: Record) {
- for (const output of Object.values(bundle)) {
- if (output.type !== 'chunk' || !output.code || bundle[`${output.fileName}.map`]) {
- continue;
+ generateBundle: {
+ order: 'pre' as const,
+ handler(_options: unknown, bundle: Record) {
+ for (const output of Object.values(bundle)) {
+ if (output.type !== 'chunk' || !output.code || bundle[`${output.fileName}.map`]) {
+ continue;
+ }
+ for (const match of output.code.matchAll(/sentry-dbid-([\da-f-]{36})/gi)) {
+ fs.appendFileSync('.tmp_debug_ids_without_source_map', `${match[1]!.toLowerCase()}\n`);
+ }
}
- for (const match of output.code.matchAll(/sentry-dbid-([\da-f-]{36})/gi)) {
- fs.appendFileSync('.tmp_debug_ids_without_source_map', `${match[1]!.toLowerCase()}\n`);
- }
- }
+ },
},
};
}
diff --git a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/package.json b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/package.json
index 054fbc9b378d..b15bd7ffb49a 100644
--- a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/package.json
+++ b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/package.json
@@ -24,6 +24,7 @@
"@types/node": "^26.1.2",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
+ "@vinext/cloudflare": "^1.4.0",
"@vitejs/plugin-react": "^6.1.1",
"@vitejs/plugin-rsc": "^0.5.35",
"react-server-dom-webpack": "^19.3.0",
@@ -31,5 +32,14 @@
"vinext": "^1.0.1",
"vite": "^8.3.0",
"wrangler": "^4.135.0"
+ },
+ "sentryTest": {
+ "optionalVariants": [
+ {
+ "build-command": "E2E_VINEXT_WORKERS_CACHE=1 pnpm test:build",
+ "assert-command": "pnpm test tests/page-errors.test.ts",
+ "label": "vinext-cf-workers (workers cache)"
+ }
+ ]
}
}
diff --git a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/src/app/page-error/page.tsx b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/src/app/page-error/page.tsx
new file mode 100644
index 000000000000..e1ac01c3a6c3
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/src/app/page-error/page.tsx
@@ -0,0 +1,6 @@
+import { connection } from 'next/server';
+
+export default async function PageError() {
+ await connection();
+ throw new Error('Page render error from vinext');
+}
diff --git a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/tests/page-errors.test.ts b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/tests/page-errors.test.ts
new file mode 100644
index 000000000000..a476a3059cd9
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/tests/page-errors.test.ts
@@ -0,0 +1,28 @@
+import { expect, test } from '@playwright/test';
+import { collectStreamedSpans, waitForError } from '@sentry-internal/test-utils';
+
+test('Captures an error thrown while a page renders', async ({ request }) => {
+ const errorPromise = waitForError('vinext-cf-workers', event => {
+ return event.exception?.values?.[0]?.value === 'Page render error from vinext';
+ });
+ // vinext's Workers Cache adapter renders the page in a second invocation, whose request URL has a
+ // `__vinext_cache_key` query parameter. The error must be in the trace of the incoming request.
+ const requestSpansPromise = collectStreamedSpans('vinext-cf-workers', spans =>
+ spans.some(span => span.is_segment && span.name === 'GET /page-error' && !span.attributes['url.query']),
+ );
+
+ const response = await request.get('/page-error');
+ expect(response.status()).toBe(500);
+
+ const errorEvent = await errorPromise;
+ const requestSpans = await requestSpansPromise;
+
+ expect(errorEvent.sdk?.name).toBe('sentry.javascript.nextjs');
+ expect(errorEvent.environment).toBe('qa');
+ expect(errorEvent.transaction).toBe('GET /page-error');
+ expect(errorEvent.exception?.values?.[0]?.mechanism).toEqual({
+ handled: false,
+ type: 'auto.function.nextjs.on_request_error',
+ });
+ expect(errorEvent.contexts?.trace?.trace_id).toBe(requestSpans[0]?.trace_id);
+});
diff --git a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/vite.config.ts b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/vite.config.ts
index 6bab8f3b5d74..2659b6c30ad6 100644
--- a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/vite.config.ts
+++ b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/vite.config.ts
@@ -1,5 +1,6 @@
import { cloudflare } from '@cloudflare/vite-plugin';
import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';
+import { workersCacheCdnAdapter } from '@vinext/cloudflare/cache/workers-cache-cdn-adapter';
import vinext from 'vinext';
import { defineConfig } from 'vite';
@@ -7,7 +8,9 @@ import { defineConfig } from 'vite';
// `@sentry/nextjs/cloudflare`.
export default defineConfig({
plugins: [
- vinext(),
+ // The `vinext-cf-workers (workers cache)` variant renders cacheable pages in the `VinextCachedResponse`
+ // entrypoint, which the default export calls through `ctx.exports`.
+ vinext(process.env.E2E_VINEXT_WORKERS_CACHE ? { cache: { cdn: workersCacheCdnAdapter() } } : {}),
cloudflare({ viteEnvironment: { name: 'rsc', childEnvironments: ['ssr'] } }),
sentryCloudflareVitePlugin(),
],
diff --git a/dev-packages/node-integration-tests/.oxlintrc.json b/dev-packages/node-integration-tests/.oxlintrc.json
index 56d441ab0c82..30c28284ed4d 100644
--- a/dev-packages/node-integration-tests/.oxlintrc.json
+++ b/dev-packages/node-integration-tests/.oxlintrc.json
@@ -20,6 +20,34 @@
],
"import/first": "off"
}
+ },
+ {
+ "files": ["suites/**/test.ts", "suites/**/*.test.ts"],
+ "rules": {
+ "no-restricted-properties": [
+ "error",
+ {
+ "object": "process",
+ "property": "version",
+ "message": "Gate the test with `test.runIf(supports({ ... }))` from `utils/index.ts` instead."
+ },
+ {
+ "object": "process",
+ "property": "versions",
+ "message": "Gate the test with `test.runIf(supports({ ... }))` from `utils/index.ts` instead."
+ },
+ {
+ "object": "ctx",
+ "property": "skip",
+ "message": "Gate the test with `test.runIf(supports({ ... }))` from `utils/index.ts` instead."
+ },
+ {
+ "object": "context",
+ "property": "skip",
+ "message": "Gate the test with `test.runIf(supports({ ... }))` from `utils/index.ts` instead."
+ }
+ ]
+ }
}
]
}
diff --git a/dev-packages/node-integration-tests/README.md b/dev-packages/node-integration-tests/README.md
index 26b2eab24a81..7442e5c19d67 100644
--- a/dev-packages/node-integration-tests/README.md
+++ b/dev-packages/node-integration-tests/README.md
@@ -9,7 +9,8 @@ suites/
|---- test.ts [assertions]
|---- scenario.ts [Sentry initialization and test subject]
|---- customTest/
- |---- test.ts [assertions]
+ |---- tracing.test.ts [tracing assertions]
+ |---- errors.test.ts [error assertions]
|---- scenario_1.ts [optional extra test scenario]
|---- scenario_2.ts [optional extra test scenario]
|---- server_with_mongo.ts [optional custom server]
@@ -22,12 +23,13 @@ folders containing test scenarios and assertions.
`scenario.ts` contains the initialization logic and the test subject. By default, `{TEST_DIR}/scenario.ts` is used, but
`runServer` also accepts an optional `scenarioPath` argument for non-standard usage.
-`test.ts` is required for each test case, and contains the server runner logic, request interceptors for Sentry
-requests, and assertions. Test server, interceptors and assertions are all run on the same Vitest thread.
+`test.ts` and descriptive `*.test.ts` files contain the server runner logic, request interceptors for Sentry requests,
+and assertions. A suite can use several named test files so Vitest can schedule them independently while sharing
+scenario files. Each test's server, interceptors and assertions run on the same Vitest thread.
### Utilities
-`utils/` contains helpers and Sentry-specific assertions that can be used in (`test.ts`).
+`utils/` contains helpers and Sentry-specific assertions for the test files.
Nock interceptors are internally used to capture envelope requests by `getEnvelopeRequest` and
`getMultipleEnvelopeRequest` helpers. After capturing required requests, the interceptors are removed. Nock can manually
diff --git a/dev-packages/node-integration-tests/package.json b/dev-packages/node-integration-tests/package.json
index 0351f33c48fc..0b1488d21a78 100644
--- a/dev-packages/node-integration-tests/package.json
+++ b/dev-packages/node-integration-tests/package.json
@@ -61,7 +61,7 @@
"@sentry-internal/rollup-utils": "11.17.0",
"@sentry-internal/test-utils": "11.17.0",
"@sentry/aws-serverless": "11.17.0",
- "@sentry/conventions": "0.35.0",
+ "@sentry/conventions": "0.36.0",
"@sentry/core": "11.17.0",
"@sentry/hono": "11.17.0",
"@sentry/node": "11.17.0",
@@ -124,6 +124,7 @@
"winston": "^3.17.0",
"winston-transport": "^4.9.0",
"ws": "^8.20.1",
+ "yaml": "^2.9.0",
"yargs": "^18.2.0",
"zod": "^4.6.7"
},
diff --git a/dev-packages/node-integration-tests/scripts/clean.js b/dev-packages/node-integration-tests/scripts/clean.js
index 1c0f4f27c095..f871d809b34f 100644
--- a/dev-packages/node-integration-tests/scripts/clean.js
+++ b/dev-packages/node-integration-tests/scripts/clean.js
@@ -1,6 +1,7 @@
const { execSync } = require('child_process');
const { globSync, rmSync } = require('fs');
+// `fs.globSync` needs Node 22. This is a local helper, and the repo pins Node 24 in `devEngines`.
for (const path of globSync(['suites/**/node_modules', 'suites/**/tmp_*'])) {
rmSync(path, { recursive: true, force: true });
}
diff --git a/dev-packages/node-integration-tests/src/index.ts b/dev-packages/node-integration-tests/src/index.ts
index 57369ec52d92..311805ae4bbb 100644
--- a/dev-packages/node-integration-tests/src/index.ts
+++ b/dev-packages/node-integration-tests/src/index.ts
@@ -7,6 +7,12 @@ export * from './mocks/anthropic';
export * from './mocks/google';
export * from './mocks/openai';
+/**
+ * Mirror the feature flag limits in `@sentry/core`.
+ */
+export const FLAG_BUFFER_SIZE = 100;
+export const MAX_FLAGS_PER_SPAN = 10;
+
/**
* Debug logging transport
*/
diff --git a/dev-packages/node-integration-tests/suites/docker-compose.test.ts b/dev-packages/node-integration-tests/suites/docker-compose.test.ts
new file mode 100644
index 000000000000..aed23bd28785
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/docker-compose.test.ts
@@ -0,0 +1,39 @@
+import { readdirSync, readFileSync } from 'fs';
+import { join, relative } from 'path';
+import { expect, test } from 'vitest';
+import { parse } from 'yaml';
+
+function findComposeFiles(dir: string): string[] {
+ return readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
+ if (entry.isDirectory()) {
+ return entry.name === 'node_modules' || entry.name.startsWith('tmp_')
+ ? []
+ : findComposeFiles(join(dir, entry.name));
+ }
+ return entry.name === 'docker-compose.yml' ? [join(dir, entry.name)] : [];
+ });
+}
+
+const composeFiles = findComposeFiles(__dirname);
+
+// `up --wait` returns as soon as a service without a healthcheck has started, so the test would race
+// the service's startup.
+test.each(composeFiles.map(file => relative(__dirname, file)))('every service in %s has a healthcheck', file => {
+ const config = parse(readFileSync(join(__dirname, file), 'utf8')) as {
+ services?: Record;
+ };
+
+ const missing = Object.entries(config.services ?? {})
+ .filter(([, service]) => {
+ const healthcheck = service?.healthcheck;
+ const command = [healthcheck?.test ?? []].flat();
+ return healthcheck?.disable === true || !command[0] || command[0] === 'NONE';
+ })
+ .map(([name]) => name);
+
+ expect(missing).toEqual([]);
+});
+
+test('finds the docker-compose files', () => {
+ expect(composeFiles.length).toBeGreaterThan(0);
+});
diff --git a/dev-packages/node-integration-tests/suites/esm/warn-esm/test.ts b/dev-packages/node-integration-tests/suites/esm/warn-esm/test.ts
index 5f52af14aaed..39d605af1c91 100644
--- a/dev-packages/node-integration-tests/suites/esm/warn-esm/test.ts
+++ b/dev-packages/node-integration-tests/suites/esm/warn-esm/test.ts
@@ -5,6 +5,7 @@ afterAll(() => {
cleanupChildProcesses();
});
+// eslint-disable-next-line no-restricted-properties -- builds the expected warning text, does not gate the test
const esmWarning = `[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`;
test('does not warn if using ESM on Node.js versions that support `register()`', async () => {
diff --git a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/scenario.ts b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/scenario.ts
index db7eb3a8815a..da7f756096e8 100644
--- a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/scenario.ts
+++ b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/scenario.ts
@@ -1,6 +1,5 @@
-import { _INTERNAL_FLAG_BUFFER_SIZE as FLAG_BUFFER_SIZE } from '@sentry/core';
import * as Sentry from '@sentry/node';
-import { loggingTransport } from '@sentry-internal/node-integration-tests';
+import { loggingTransport, FLAG_BUFFER_SIZE } from '@sentry-internal/node-integration-tests';
Sentry.init({
traceLifecycle: 'static',
diff --git a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/test.ts b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/test.ts
index 74ff1c125b45..edf859217675 100644
--- a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/test.ts
+++ b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/test.ts
@@ -1,5 +1,5 @@
-import { _INTERNAL_FLAG_BUFFER_SIZE as FLAG_BUFFER_SIZE } from '@sentry/core';
import { afterAll, test } from 'vitest';
+import { FLAG_BUFFER_SIZE } from '@sentry-internal/node-integration-tests';
import { cleanupChildProcesses, createRunner } from '../../../../../utils/runner';
afterAll(() => {
diff --git a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/scenario.ts b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/scenario.ts
index 2c07e46b40ed..44e632bf327f 100644
--- a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/scenario.ts
+++ b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/scenario.ts
@@ -1,6 +1,5 @@
-import { _INTERNAL_MAX_FLAGS_PER_SPAN as MAX_FLAGS_PER_SPAN } from '@sentry/core';
import * as Sentry from '@sentry/node';
-import { loggingTransport } from '@sentry-internal/node-integration-tests';
+import { loggingTransport, MAX_FLAGS_PER_SPAN } from '@sentry-internal/node-integration-tests';
Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
diff --git a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/test.ts b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/test.ts
index e2caf9ed4fc1..ade1ea5f9134 100644
--- a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/test.ts
+++ b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/test.ts
@@ -1,5 +1,5 @@
-import { _INTERNAL_MAX_FLAGS_PER_SPAN as MAX_FLAGS_PER_SPAN } from '@sentry/core';
import { afterAll, expect, test } from 'vitest';
+import { MAX_FLAGS_PER_SPAN } from '@sentry-internal/node-integration-tests';
import { cleanupChildProcesses, createRunner } from '../../../../utils/runner';
afterAll(() => {
diff --git a/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/scenario.ts b/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/scenario.ts
index 77aa7d912540..ba4f7cdcb5c6 100644
--- a/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/scenario.ts
+++ b/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/scenario.ts
@@ -1,8 +1,7 @@
import type { ClientOptions, UserContext } from '@growthbook/growthbook';
import { GrowthBookClient } from '@growthbook/growthbook';
-import { _INTERNAL_FLAG_BUFFER_SIZE as FLAG_BUFFER_SIZE } from '@sentry/core';
import * as Sentry from '@sentry/node';
-import { loggingTransport } from '@sentry-internal/node-integration-tests';
+import { loggingTransport, FLAG_BUFFER_SIZE } from '@sentry-internal/node-integration-tests';
// Wrapper class to instantiate GrowthBookClient
class GrowthBookWrapper {
diff --git a/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/test.ts b/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/test.ts
index 82e39eb62364..4fb9efb6d0d4 100644
--- a/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/test.ts
+++ b/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/test.ts
@@ -1,5 +1,5 @@
-import { _INTERNAL_FLAG_BUFFER_SIZE as FLAG_BUFFER_SIZE } from '@sentry/core';
import { afterAll, test } from 'vitest';
+import { FLAG_BUFFER_SIZE } from '@sentry-internal/node-integration-tests';
import { cleanupChildProcesses, createRunner } from '../../../../../utils/runner';
afterAll(() => {
diff --git a/dev-packages/node-integration-tests/suites/hono-sdk/test.ts b/dev-packages/node-integration-tests/suites/hono-sdk/test.ts
index e4293aa20ea9..fa14a71416dc 100644
--- a/dev-packages/node-integration-tests/suites/hono-sdk/test.ts
+++ b/dev-packages/node-integration-tests/suites/hono-sdk/test.ts
@@ -1,5 +1,7 @@
import { afterAll, describe, expect } from 'vitest';
import { cleanupChildProcesses, createEsmAndCjsTests } from '../../utils/runner';
+import { supports } from '../../utils';
+import { HONO_MAJORS } from '../hono/hono-majors';
const ROUTE_NAME_CASES: Array<{ method: 'get' | 'post'; path: string; name: string; route: string }> = [
{ method: 'get', path: '/users/me', name: 'GET /users/me', route: '/users/me' },
@@ -15,163 +17,173 @@ const ROUTE_NAME_CASES: Array<{ method: 'get' | 'post'; path: string; name: stri
{ method: 'get', path: '/outer/self-watering-plant', name: 'GET /outer/:itemId', route: '/outer/:itemId' },
];
-describe('hono-sdk (Node)', () => {
- afterAll(() => {
- cleanupChildProcesses();
- });
-
- createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => {
- let scenario: ReturnType | undefined;
- async function runScenario() {
- const requests: Array<{ method: 'get' | 'post' | 'put'; path: string; expectError?: boolean }> = [
- ...ROUTE_NAME_CASES,
- { method: 'get', path: '/does-not-exist', expectError: true },
- { method: 'get', path: '/' },
- { method: 'get', path: '/hello/world' },
- ];
- const runner = createRunner().expect({
- event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' },
- });
- const collectors = requests.map(({ path }) => {
- const key = path;
- return [
- key,
- runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === key),
- ] as const;
- });
+for (const { major, minNode, options } of HONO_MAJORS) {
+ describe.runIf(supports({ min: minNode }))(`hono-sdk (Node) on Hono ${major}`, () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
- const started = runner.start();
- for (const { method, path, expectError } of requests) {
- await started.makeRequest(method, path, { expectError });
- }
- await started.completed();
- return new Map(await Promise.all(collectors.map(async ([key, spans]) => [key, { items: await spans }] as const)));
- }
- async function getScenario(key: string) {
- scenario ??= runScenario();
- return (await scenario).get(key)!;
- }
+ createEsmAndCjsTests(
+ __dirname,
+ 'scenario.mjs',
+ 'instrument.mjs',
+ (createRunner, test) => {
+ let scenario: ReturnType | undefined;
+ async function runScenario() {
+ const requests: Array<{ method: 'get' | 'post' | 'put'; path: string; expectError?: boolean }> = [
+ ...ROUTE_NAME_CASES,
+ { method: 'get', path: '/does-not-exist', expectError: true },
+ { method: 'get', path: '/' },
+ { method: 'get', path: '/hello/world' },
+ ];
+ const runner = createRunner().expect({
+ event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' },
+ });
+ const collectors = requests.map(({ path }) => {
+ const key = path;
+ return [
+ key,
+ runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === key),
+ ] as const;
+ });
- test('names each request after the route of the handler that responded', async () => {
- for (const { path, name, route } of ROUTE_NAME_CASES) {
- const container = await getScenario(path);
- const segment = container.items.find(item => item.is_segment && item.name === name);
- if (!segment) {
- throw new Error(`segment for \`${name}\` not in this container`);
+ const started = runner.start();
+ for (const { method, path, expectError } of requests) {
+ await started.makeRequest(method, path, { expectError });
+ }
+ await started.completed();
+ return new Map(
+ await Promise.all(collectors.map(async ([key, spans]) => [key, { items: await spans }] as const)),
+ );
+ }
+ async function getScenario(key: string) {
+ scenario ??= runScenario();
+ return (await scenario).get(key)!;
}
- expect(segment.attributes?.['http.route']).toEqual({ type: 'string', value: route });
- expect(segment.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'route' });
- }
- });
- test('names an event captured in a route handler after that route', async () => {
- const runner = createRunner()
- .ignore('span')
- .expect({ event: { message: 'Message from a route handler', transaction: 'GET /users/:id/capture' } })
- .start();
- runner.makeRequest('get', '/users/42/capture');
- await runner.completed();
- });
+ test('names each request after the route of the handler that responded', async () => {
+ for (const { path, name, route } of ROUTE_NAME_CASES) {
+ const container = await getScenario(path);
+ const segment = container.items.find(item => item.is_segment && item.name === name);
+ if (!segment) {
+ throw new Error(`segment for \`${name}\` not in this container`);
+ }
+ expect(segment.attributes?.['http.route']).toEqual({ type: 'string', value: route });
+ expect(segment.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'route' });
+ }
+ });
- test('keeps the runtime name for a request without a route', async () => {
- const container = await getScenario('/does-not-exist');
- const segment = container.items.find(item => item.is_segment);
- expect(segment?.name).toBe('GET');
- expect(segment?.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'url' });
- expect(segment?.attributes?.['url.path']).toEqual({ type: 'string', value: '/does-not-exist' });
- expect(segment?.attributes?.['http.route']).toBeUndefined();
- });
+ test('names an event captured in a route handler after that route', async () => {
+ const runner = createRunner()
+ .ignore('span')
+ .expect({ event: { message: 'Message from a route handler', transaction: 'GET /users/:id/capture' } })
+ .start();
+ runner.makeRequest('get', '/users/42/capture');
+ await runner.completed();
+ });
- test('names an event from the route handler that runs after next() after that route', async () => {
- const runner = createRunner()
- .ignore('span')
- .expect({ event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' } })
- .start();
- runner.makeRequest('get', '/posts/draft');
- await runner.completed();
- });
+ test('keeps the runtime name for a request without a route', async () => {
+ const container = await getScenario('/does-not-exist');
+ const segment = container.items.find(item => item.is_segment);
+ expect(segment?.name).toBe('GET');
+ expect(segment?.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'url' });
+ expect(segment?.attributes?.['url.path']).toEqual({ type: 'string', value: '/does-not-exist' });
+ expect(segment?.attributes?.['http.route']).toBeUndefined();
+ });
- test('names a HEAD request after the GET route', async () => {
- const runner = createRunner()
- .ignore('span')
- .expect({
- event: {
- exception: { values: [{ value: 'Test error from a HEAD request' }] },
- transaction: 'HEAD /head-error/:id',
- },
- })
- .start();
- runner.makeRequest('head', '/head-error/1', { expectError: true });
- await runner.completed();
- });
+ test('names an event from the route handler that runs after next() after that route', async () => {
+ const runner = createRunner()
+ .ignore('span')
+ .expect({ event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' } })
+ .start();
+ runner.makeRequest('get', '/posts/draft');
+ await runner.completed();
+ });
- test('creates a segment span for a basic GET request', async () => {
- const container = await getScenario('/');
- expect(container.items.find(item => item.is_segment)).toMatchObject({
- name: 'GET /',
- status: 'ok',
- attributes: expect.objectContaining({
- 'sentry.op': { type: 'string', value: 'http.server' },
- }),
- });
- });
+ test('names a HEAD request after the GET route', async () => {
+ const runner = createRunner()
+ .ignore('span')
+ .expect({
+ event: {
+ exception: { values: [{ value: 'Test error from a HEAD request' }] },
+ transaction: 'HEAD /head-error/:id',
+ },
+ })
+ .start();
+ runner.makeRequest('head', '/head-error/1', { expectError: true });
+ await runner.completed();
+ });
- test('creates a segment span with a parametrized route name', async () => {
- const container = await getScenario('/hello/world');
- expect(container.items.find(item => item.is_segment)).toMatchObject({
- name: 'GET /hello/:name',
- status: 'ok',
- attributes: expect.objectContaining({
- 'sentry.op': { type: 'string', value: 'http.server' },
- 'sentry.segment.name.source': { type: 'string', value: 'route' },
- }),
- });
- });
+ test('creates a segment span for a basic GET request', async () => {
+ const container = await getScenario('/');
+ expect(container.items.find(item => item.is_segment)).toMatchObject({
+ name: 'GET /',
+ status: 'ok',
+ attributes: expect.objectContaining({
+ 'sentry.op': { type: 'string', value: 'http.server' },
+ }),
+ });
+ });
- test('captures an error with the correct mechanism', async () => {
- const runner = createRunner()
- .ignore('span')
- .expect({
- event: {
- exception: {
- values: [
- {
- type: 'Error',
- value: 'Test error from Hono app',
- mechanism: {
- type: 'auto.http.hono.context_error',
- handled: false,
- },
+ test('creates a segment span with a parametrized route name', async () => {
+ const container = await getScenario('/hello/world');
+ expect(container.items.find(item => item.is_segment)).toMatchObject({
+ name: 'GET /hello/:name',
+ status: 'ok',
+ attributes: expect.objectContaining({
+ 'sentry.op': { type: 'string', value: 'http.server' },
+ 'sentry.segment.name.source': { type: 'string', value: 'route' },
+ }),
+ });
+ });
+
+ test('captures an error with the correct mechanism', async () => {
+ const runner = createRunner()
+ .ignore('span')
+ .expect({
+ event: {
+ exception: {
+ values: [
+ {
+ type: 'Error',
+ value: 'Test error from Hono app',
+ mechanism: {
+ type: 'auto.http.hono.context_error',
+ handled: false,
+ },
+ },
+ ],
},
- ],
- },
- transaction: 'GET /error/:param',
- },
- })
- .start();
- runner.makeRequest('get', '/error/param-123', { expectError: true });
- await runner.completed();
- });
+ transaction: 'GET /error/:param',
+ },
+ })
+ .start();
+ runner.makeRequest('get', '/error/param-123', { expectError: true });
+ await runner.completed();
+ });
- test('creates a segment span with error status when an error occurs', async () => {
- const runner = createRunner()
- .ignore('event')
- .expect({
- span: container => {
- expect(container.items.find(item => item.is_segment)).toMatchObject({
- name: 'GET /error/:param',
- status: 'error',
- attributes: expect.objectContaining({
- 'sentry.op': { type: 'string', value: 'http.server' },
- 'sentry.status.message': { type: 'string', value: 'internal_error' },
- 'http.response.status_code': { type: 'integer', value: 500 },
- }),
- });
- },
- })
- .start();
- runner.makeRequest('get', '/error/param-456', { expectError: true });
- await runner.completed();
- });
+ test('creates a segment span with error status when an error occurs', async () => {
+ const runner = createRunner()
+ .ignore('event')
+ .expect({
+ span: container => {
+ expect(container.items.find(item => item.is_segment)).toMatchObject({
+ name: 'GET /error/:param',
+ status: 'error',
+ attributes: expect.objectContaining({
+ 'sentry.op': { type: 'string', value: 'http.server' },
+ 'sentry.status.message': { type: 'string', value: 'internal_error' },
+ 'http.response.status_code': { type: 'integer', value: 500 },
+ }),
+ });
+ },
+ })
+ .start();
+ runner.makeRequest('get', '/error/param-456', { expectError: true });
+ await runner.completed();
+ });
+ },
+ options,
+ );
});
-});
+}
diff --git a/dev-packages/node-integration-tests/suites/hono/hono-majors.ts b/dev-packages/node-integration-tests/suites/hono/hono-majors.ts
new file mode 100644
index 000000000000..0e19ca53bad9
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/hono/hono-majors.ts
@@ -0,0 +1,26 @@
+import { SUPPORTS_REQUIRE_OF_ESM } from '../../utils';
+
+type HonoMajor = {
+ major: 4 | 5;
+ minNode?: number;
+ options: {
+ /** Installed in the tmp dir of the suite. Without them, the scenario uses the root dependencies. */
+ additionalDependencies?: Record;
+ failsOnCjs?: boolean;
+ };
+};
+
+// Exact versions: these are required CI jobs, so a new Hono release must not break them.
+// The Hono E2E apps use version ranges and show new releases.
+export const HONO_MAJORS: HonoMajor[] = [
+ { major: 4, options: {} },
+ {
+ major: 5,
+ minNode: 22,
+ options: {
+ additionalDependencies: { hono: '5.0.0-rc.1', '@hono/node-server': '2.1.7' },
+ // Hono 5 ships only ES modules, and not every runtime can `require()` them.
+ failsOnCjs: !SUPPORTS_REQUIRE_OF_ESM,
+ },
+ },
+];
diff --git a/dev-packages/node-integration-tests/suites/hono/scenario-error-middleware.mjs b/dev-packages/node-integration-tests/suites/hono/scenario-error-middleware.mjs
new file mode 100644
index 000000000000..25bf91c46f6c
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/hono/scenario-error-middleware.mjs
@@ -0,0 +1,43 @@
+import { serve } from '@hono/node-server';
+import * as Sentry from '@sentry/node';
+import { sendPortToRunner } from '@sentry-internal/node-integration-tests';
+import { Hono } from 'hono';
+import { HTTPException } from 'hono/http-exception';
+
+// Hono 5 only: `onError()` and `notFound()` register `(c, next)` middleware that reads the error from
+// `c.error`. `honoMiddleware(app)` installs the route hook, so the sub-app below is instrumented at mount.
+const app = new Hono();
+app.use(Sentry.honoMiddleware(app));
+
+app.notFound('/not-found-error/*', () => {
+ throw new Error('Error from a not-found handler');
+});
+app.notFound('/not-found-http-exception/*', () => {
+ throw new HTTPException(404, { message: 'Not found from a not-found handler' });
+});
+
+app.get('/replace-error', () => {
+ throw new Error('Original error from a route handler');
+});
+app.onError('/replace-error', c => {
+ throw new Error('Replacement error from an error handler', { cause: c.error });
+});
+
+const subApp = new Hono();
+subApp.use(async function subAppMiddleware(_c, next) {
+ await next();
+});
+subApp.onError(
+ async function errorMiddleware(_c, next) {
+ await next();
+ },
+ c => c.text('Handled by the sub-app error handler', 500),
+);
+subApp.get('/fail', () => {
+ throw new Error('Error from a sub-app route');
+});
+app.route('/sub', subApp);
+
+serve({ fetch: app.fetch, port: 0 }, info => {
+ sendPortToRunner(info.port);
+});
diff --git a/dev-packages/node-integration-tests/suites/hono/test.ts b/dev-packages/node-integration-tests/suites/hono/test.ts
index 2ccb6a2f24f8..61efd29b8246 100644
--- a/dev-packages/node-integration-tests/suites/hono/test.ts
+++ b/dev-packages/node-integration-tests/suites/hono/test.ts
@@ -1,5 +1,9 @@
+import { URL_PATH } from '@sentry/conventions/attributes';
+import { MIDDLEWARE } from '@sentry/conventions/op';
import { afterAll, describe, expect } from 'vitest';
import { cleanupChildProcesses, createEsmAndCjsTests } from '../../utils/runner';
+import { supports } from '../../utils';
+import { HONO_MAJORS } from './hono-majors';
// Verifies that Hono is auto-instrumented out of the box by `@sentry/node` (the `honoIntegration`
// default), without importing `@sentry/hono` or registering the `sentry()` middleware manually.
@@ -50,344 +54,445 @@ function segmentNamed(name: string, route: string): { span: (container: { items:
};
}
-describe('hono auto-instrumentation', () => {
- afterAll(() => {
- cleanupChildProcesses();
- });
-
- createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => {
- let scenario: ReturnType | undefined;
- async function runScenario() {
- const requests: Array<{ method: 'get' | 'post'; path: string; expectError?: boolean }> = [
- ...ROUTE_NAME_CASES,
- { method: 'get', path: '/traced/1' },
- { method: 'get', path: '/does-not-exist', expectError: true },
- { method: 'get', path: '/' },
- { method: 'get', path: '/hello/world' },
- { method: 'get', path: '/arity-two-handler' },
- { method: 'get', path: '/test-basepath-mw/hello' },
- { method: 'get', path: '/sub/hello' },
- { method: 'get', path: '/outer/self-watering-plant' },
- ];
- const uniqueRequests = new Map(requests.map(request => [request.path, request]));
- const runner = createRunner().unordered();
- const collectors = [...uniqueRequests.keys()].map(
- path => [path, runner.collectStreamedSpansUntilSegment(span => attr(span, 'url.path') === path)] as const,
- );
- const started = runner.start();
- for (const { method, path, expectError } of uniqueRequests.values()) {
- await started.makeRequest(method, path, { expectError });
- }
- await started.completed();
- return new Map(await Promise.all(collectors.map(async ([path, spans]) => [path, await spans] as const)));
- }
- async function getSpans(path: string) {
- scenario ??= runScenario();
- return (await scenario).get(path)!;
- }
-
- test('names each request after the route of the handler that responded', async () => {
- for (const { path, name, route } of ROUTE_NAME_CASES) {
- segmentNamed(name, route).span({ items: await getSpans(path) });
- }
- });
-
- test('names an event captured in a route handler after that route', async () => {
- const runner = createRunner()
- .ignore('span')
- .expect({ event: { message: 'Message from a route handler', transaction: 'GET /users/:id/capture' } })
- .start();
- runner.makeRequest('get', '/users/42/capture');
- await runner.completed();
- });
-
- test('does not rename a span that a middleware starts around the route handler', async () => {
- const container = { items: await getSpans('/traced/1') };
-
- const segment = container.items.find(item => item.is_segment && item.name === 'GET /traced/:id');
- if (!segment) {
- throw new Error('segment for `GET /traced/:id` not in this container');
- }
- expect(container.items.filter(item => item.name === 'user span')).toHaveLength(1);
- });
-
- test('keeps the runtime name for a request without a route', async () => {
- const container = { items: await getSpans('/does-not-exist') };
-
- const segment = container.items.find(item => item.is_segment && attr(item, 'url.path') === '/does-not-exist');
- if (!segment) {
- throw new Error('segment for `/does-not-exist` not in this container');
- }
- expect(segment.name).toBe('GET');
- expect(attr(segment, 'sentry.segment.name.source')).toBe('url');
- expect(attr(segment, 'http.route')).toBeUndefined();
+for (const { major, minNode, options } of HONO_MAJORS) {
+ describe.runIf(supports({ min: minNode }))(`hono auto-instrumentation on Hono ${major}`, () => {
+ afterAll(() => {
+ cleanupChildProcesses();
});
- test('names an event from the route handler that runs after next() after that route', async () => {
- const runner = createRunner()
- .ignore('span')
- .expect({ event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' } })
- .start();
- runner.makeRequest('get', '/posts/draft');
- await runner.completed();
- });
-
- test('names a HEAD request after the GET route', async () => {
- const runner = createRunner()
- .unordered()
- .expect({
- event: {
- exception: { values: [{ value: 'Test error from a HEAD request' }] },
- transaction: 'HEAD /head-error/:id',
- },
- })
- .start();
- runner.makeRequest('head', '/head-error/1', { expectError: true });
- await runner.completed();
- });
-
- test('creates a transaction for a basic GET request', async () => {
- const container = { items: await getSpans('/') };
-
- const segment = container.items.find(item => item.is_segment && item.name === 'GET /');
- if (!segment) {
- throw new Error('segment for `GET /` not in this container');
- }
- expect(op(segment)).toBe('http.server');
- expect(segment.status).toBe('ok');
- });
-
- test('creates a transaction with a parametrized route name', async () => {
- const container = { items: await getSpans('/hello/world') };
-
- const segment = container.items.find(item => item.is_segment && item.name === 'GET /hello/:name');
- if (!segment) {
- throw new Error('segment for `GET /hello/:name` not in this container');
- }
- expect(op(segment)).toBe('http.server');
- expect(attr(segment, 'sentry.segment.name.source')).toBe('route');
- });
-
- test('captures an error with the correct mechanism', async () => {
- const runner = createRunner()
- .unordered()
- .expect({
- event: {
- exception: {
- values: [
- {
- type: 'Error',
- value: 'Test error from Hono app',
- mechanism: {
- type: 'auto.http.hono.context_error',
- handled: false,
- },
+ createEsmAndCjsTests(
+ __dirname,
+ 'scenario.mjs',
+ 'instrument.mjs',
+ (createRunner, test) => {
+ let scenario: ReturnType | undefined;
+ async function runScenario() {
+ const requests: Array<{ method: 'get' | 'post'; path: string; expectError?: boolean }> = [
+ ...ROUTE_NAME_CASES,
+ { method: 'get', path: '/traced/1' },
+ { method: 'get', path: '/does-not-exist', expectError: true },
+ { method: 'get', path: '/' },
+ { method: 'get', path: '/hello/world' },
+ { method: 'get', path: '/arity-two-handler' },
+ { method: 'get', path: '/test-basepath-mw/hello' },
+ { method: 'get', path: '/sub/hello' },
+ { method: 'get', path: '/outer/self-watering-plant' },
+ ];
+ const uniqueRequests = new Map(requests.map(request => [request.path, request]));
+ const runner = createRunner().unordered();
+ const collectors = [...uniqueRequests.keys()].map(
+ path => [path, runner.collectStreamedSpansUntilSegment(span => attr(span, 'url.path') === path)] as const,
+ );
+ const started = runner.start();
+ for (const { method, path, expectError } of uniqueRequests.values()) {
+ await started.makeRequest(method, path, { expectError });
+ }
+ await started.completed();
+ return new Map(await Promise.all(collectors.map(async ([path, spans]) => [path, await spans] as const)));
+ }
+ async function getSpans(path: string) {
+ scenario ??= runScenario();
+ return (await scenario).get(path)!;
+ }
+
+ test('names each request after the route of the handler that responded', async () => {
+ for (const { path, name, route } of ROUTE_NAME_CASES) {
+ segmentNamed(name, route).span({ items: await getSpans(path) });
+ }
+ });
+
+ test('names an event captured in a route handler after that route', async () => {
+ const runner = createRunner()
+ .ignore('span')
+ .expect({ event: { message: 'Message from a route handler', transaction: 'GET /users/:id/capture' } })
+ .start();
+ runner.makeRequest('get', '/users/42/capture');
+ await runner.completed();
+ });
+
+ test('does not rename a span that a middleware starts around the route handler', async () => {
+ const container = { items: await getSpans('/traced/1') };
+
+ const segment = container.items.find(item => item.is_segment && item.name === 'GET /traced/:id');
+ if (!segment) {
+ throw new Error('segment for `GET /traced/:id` not in this container');
+ }
+ expect(container.items.filter(item => item.name === 'user span')).toHaveLength(1);
+ });
+
+ test('keeps the runtime name for a request without a route', async () => {
+ const container = { items: await getSpans('/does-not-exist') };
+
+ const segment = container.items.find(item => item.is_segment && attr(item, 'url.path') === '/does-not-exist');
+ if (!segment) {
+ throw new Error('segment for `/does-not-exist` not in this container');
+ }
+ expect(segment.name).toBe('GET');
+ expect(attr(segment, 'sentry.segment.name.source')).toBe('url');
+ expect(attr(segment, 'http.route')).toBeUndefined();
+ });
+
+ test('names an event from the route handler that runs after next() after that route', async () => {
+ const runner = createRunner()
+ .ignore('span')
+ .expect({ event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' } })
+ .start();
+ runner.makeRequest('get', '/posts/draft');
+ await runner.completed();
+ });
+
+ test('names a HEAD request after the GET route', async () => {
+ const runner = createRunner()
+ .unordered()
+ .expect({
+ event: {
+ exception: { values: [{ value: 'Test error from a HEAD request' }] },
+ transaction: 'HEAD /head-error/:id',
+ },
+ })
+ .start();
+ runner.makeRequest('head', '/head-error/1', { expectError: true });
+ await runner.completed();
+ });
+
+ test('creates a transaction for a basic GET request', async () => {
+ const container = { items: await getSpans('/') };
+
+ const segment = container.items.find(item => item.is_segment && item.name === 'GET /');
+ if (!segment) {
+ throw new Error('segment for `GET /` not in this container');
+ }
+ expect(op(segment)).toBe('http.server');
+ expect(segment.status).toBe('ok');
+ });
+
+ test('creates a transaction with a parametrized route name', async () => {
+ const container = { items: await getSpans('/hello/world') };
+
+ const segment = container.items.find(item => item.is_segment && item.name === 'GET /hello/:name');
+ if (!segment) {
+ throw new Error('segment for `GET /hello/:name` not in this container');
+ }
+ expect(op(segment)).toBe('http.server');
+ expect(attr(segment, 'sentry.segment.name.source')).toBe('route');
+ });
+
+ test('captures an error with the correct mechanism', async () => {
+ const runner = createRunner()
+ .unordered()
+ .expect({
+ event: {
+ exception: {
+ values: [
+ {
+ type: 'Error',
+ value: 'Test error from Hono app',
+ mechanism: {
+ type: 'auto.http.hono.context_error',
+ handled: false,
+ },
+ },
+ ],
},
- ],
- },
- transaction: 'GET /error/:param',
- },
- })
- .start();
- runner.makeRequest('get', '/error/param-123', { expectError: true });
- await runner.completed();
- });
-
- test('creates a transaction with internal_error status when an error occurs', async () => {
- const runner = createRunner()
- .unordered()
- .expect({
- span: container => {
- const segment = container.items.find(item => item.is_segment && item.name === 'GET /error/:param');
- if (!segment) {
- throw new Error('segment for `GET /error/:param` not in this container');
- }
- expect(op(segment)).toBe('http.server');
- expect(segment.status).toBe('error');
- expect(attr(segment, 'http.response.status_code')).toBe(500);
- },
- })
- .start();
- runner.makeRequest('get', '/error/param-456', { expectError: true });
- await runner.completed();
- });
-
- test('does not wrap a route handler declared with an unused next param as middleware', async () => {
- const container = { items: await getSpans('/arity-two-handler') };
-
- const segment = container.items.find(item => item.is_segment && item.name === 'GET /arity-two-handler');
- if (!segment) {
- throw new Error('segment for `GET /arity-two-handler` not in this container');
- }
- // The arity-2 handler is the route handler (last in its method+path group), so it must not
- // produce a middleware span.
- const middlewareSpans = container.items.filter(item => op(item) === 'middleware');
- expect(middlewareSpans).toHaveLength(0);
- });
-
- test('creates a middleware span for .use() on a .basePath() clone', async () => {
- const container = { items: await getSpans('/test-basepath-mw/hello') };
-
- const segment = container.items.find(item => item.is_segment && item.name === 'GET /test-basepath-mw/hello');
- if (!segment) {
- throw new Error('segment for `GET /test-basepath-mw/hello` not in this container');
- }
- const middlewareSpan = container.items.find(
- item => op(item) === 'middleware' && item.name === 'basepathMiddleware',
- );
- expect(middlewareSpan).toBeDefined();
- expect(attr(middlewareSpan!, 'sentry.origin')).toBe('auto.middleware.hono');
- });
-
- test('does not create a middleware span for the Sentry middleware in a mounted sub-app', async () => {
- const container = { items: await getSpans('/sub/hello') };
-
- const segment = container.items.find(item => item.is_segment && item.name === 'GET /sub/hello');
- if (!segment) {
- throw new Error('segment for `GET /sub/hello` not in this container');
- }
- const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name);
- // The sub-app's user middleware is traced …
- expect(middlewareNames).toContain('subMiddleware');
- // … but the sub-app's own auto-registered Sentry middleware must not appear as a span
- // (it is copied into the parent at mount time and must stay unwrapped).
- expect(middlewareNames).not.toContain('');
- });
-
- test('traces an internal .request() call without the inner app re-instrumenting the request', async () => {
- const container = { items: await getSpans('/outer/self-watering-plant') };
-
- // Transaction is named after the outer route, not the internal one.
- const segment = container.items.find(item => item.is_segment && item.name === 'GET /outer/:itemId');
- if (!segment) {
- throw new Error('segment for `GET /outer/:itemId` not in this container');
- }
+ transaction: 'GET /error/:param',
+ },
+ })
+ .start();
+ runner.makeRequest('get', '/error/param-123', { expectError: true });
+ await runner.completed();
+ });
+
+ test('creates a transaction with internal_error status when an error occurs', async () => {
+ const runner = createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const segment = container.items.find(item => item.is_segment && item.name === 'GET /error/:param');
+ if (!segment) {
+ throw new Error('segment for `GET /error/:param` not in this container');
+ }
+ expect(op(segment)).toBe('http.server');
+ expect(segment.status).toBe('error');
+ expect(attr(segment, 'http.response.status_code')).toBe(500);
+ },
+ })
+ .start();
+ runner.makeRequest('get', '/error/param-456', { expectError: true });
+ await runner.completed();
+ });
+
+ test('does not wrap a route handler declared with an unused next param as middleware', async () => {
+ const container = { items: await getSpans('/arity-two-handler') };
+
+ const segment = container.items.find(item => item.is_segment && item.name === 'GET /arity-two-handler');
+ if (!segment) {
+ throw new Error('segment for `GET /arity-two-handler` not in this container');
+ }
+ // The arity-2 handler is the route handler (last in its method+path group), so it must not
+ // produce a middleware span.
+ const middlewareSpans = container.items.filter(item => op(item) === 'middleware');
+ expect(middlewareSpans).toHaveLength(0);
+ });
+
+ test('creates a middleware span for .use() on a .basePath() clone', async () => {
+ const container = { items: await getSpans('/test-basepath-mw/hello') };
+
+ const segment = container.items.find(item => item.is_segment && item.name === 'GET /test-basepath-mw/hello');
+ if (!segment) {
+ throw new Error('segment for `GET /test-basepath-mw/hello` not in this container');
+ }
+ const middlewareSpan = container.items.find(
+ item => op(item) === 'middleware' && item.name === 'basepathMiddleware',
+ );
+ expect(middlewareSpan).toBeDefined();
+ expect(attr(middlewareSpan!, 'sentry.origin')).toBe('auto.middleware.hono');
+ });
+
+ test('does not create a middleware span for the Sentry middleware in a mounted sub-app', async () => {
+ const container = { items: await getSpans('/sub/hello') };
+
+ const segment = container.items.find(item => item.is_segment && item.name === 'GET /sub/hello');
+ if (!segment) {
+ throw new Error('segment for `GET /sub/hello` not in this container');
+ }
+ const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name);
+ // The sub-app's user middleware is traced …
+ expect(middlewareNames).toContain('subMiddleware');
+ // … but the sub-app's own auto-registered Sentry middleware must not appear as a span
+ // (it is copied into the parent at mount time and must stay unwrapped).
+ expect(middlewareNames).not.toContain('');
+ });
+
+ test('traces an internal .request() call without the inner app re-instrumenting the request', async () => {
+ const container = { items: await getSpans('/outer/self-watering-plant') };
+
+ // Transaction is named after the outer route, not the internal one.
+ const segment = container.items.find(item => item.is_segment && item.name === 'GET /outer/:itemId');
+ if (!segment) {
+ throw new Error('segment for `GET /outer/:itemId` not in this container');
+ }
+
+ // The internal dispatch is traced with the raw inner path — the inner app's Sentry
+ // middleware must not re-name it to the parametrized route.
+ const internalRequestSpans = container.items.filter(
+ item => attr(item, 'sentry.origin') === 'auto.http.hono.internal_request',
+ );
+ expect(internalRequestSpans).toHaveLength(1);
+ expect(internalRequestSpans[0]?.name).toBe('GET /item/self-watering-plant');
+
+ // The inner app's Sentry middleware must not add a middleware span.
+ const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name);
+ expect(middlewareNames).not.toContain('');
+ });
+
+ test('captures an error thrown inside an internal .request() even when the outer handler degrades to 200', async () => {
+ const runner = createRunner()
+ .unordered()
+ .expect({
+ event: event => {
+ expect(event.exception?.values?.[0]?.value).toBe('inventory db is down');
+ expect(event.exception?.values?.[0]?.mechanism).toEqual(
+ expect.objectContaining({ type: 'auto.http.hono.context_error', handled: false }),
+ );
+ },
+ })
+ .start();
+ runner.makeRequest('get', '/degraded/self-watering-plant');
+ await runner.completed();
+ });
+
+ test('captures an error thrown after an internal .request() with the outer request data', async () => {
+ const runner = createRunner()
+ .unordered()
+ .expect({
+ event: event => {
+ expect(event.exception?.values?.[0]?.value).toBe(
+ 'Test error from outer Hono app after internal request',
+ );
+ // The internal `.request()` dispatch must not overwrite the request data with its own URL.
+ expect(event.request?.url).toContain('/outer-error/self-watering-plant');
+ expect(event.request?.url).not.toContain('/item/');
+ },
+ })
+ .start();
+ runner.makeRequest('get', '/outer-error/self-watering-plant', { expectError: true });
+ await runner.completed();
+ });
+
+ test('does not set the middleware span to error for a 3xx middleware error', async () => {
+ const runner = createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const middlewareSpan = container.items.find(
+ item => op(item) === 'middleware' && item.name === 'throwingMiddleware',
+ );
+ if (!middlewareSpan) {
+ throw new Error('middleware span `throwingMiddleware` not in this container');
+ }
+ expect(middlewareSpan.status).not.toBe('error');
+ },
+ })
+ .start();
+ runner.makeRequest('get', '/mw-throw/301', { expectError: true });
+ await runner.completed();
+ });
+
+ test('does not set the middleware span to error for a 4xx middleware error', async () => {
+ const runner = createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const middlewareSpan = container.items.find(
+ item => op(item) === 'middleware' && item.name === 'throwingMiddleware',
+ );
+ if (!middlewareSpan) {
+ throw new Error('middleware span `throwingMiddleware` not in this container');
+ }
+ expect(middlewareSpan.status).not.toBe('error');
+ },
+ })
+ .start();
+ runner.makeRequest('get', '/mw-throw/404', { expectError: true });
+ await runner.completed();
+ });
+
+ test('sets the middleware span to error for a 5xx middleware error', async () => {
+ const runner = createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const middlewareSpan = container.items.find(
+ item => op(item) === 'middleware' && item.name === 'throwingMiddleware',
+ );
+ if (!middlewareSpan) {
+ throw new Error('middleware span `throwingMiddleware` not in this container');
+ }
+ expect(middlewareSpan.status).toBe('error');
+ },
+ })
+ .start();
+ runner.makeRequest('get', '/mw-throw/503', { expectError: true });
+ await runner.completed();
+ });
+ },
+ options,
+ );
+ });
+}
- // The internal dispatch is traced with the raw inner path — the inner app's Sentry
- // middleware must not re-name it to the parametrized route.
- const internalRequestSpans = container.items.filter(
- item => attr(item, 'sentry.origin') === 'auto.http.hono.internal_request',
+for (const { major, minNode, options } of HONO_MAJORS) {
+ describe.runIf(supports({ min: minNode }))(
+ `hono auto-instrumentation with honoMiddleware(app) on Hono ${major}`,
+ () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ createEsmAndCjsTests(
+ __dirname,
+ 'scenario-honoMiddleware.mjs',
+ 'instrument.mjs',
+ (createRunner, test) => {
+ test('wraps route handlers only when more than one matches, and only once', async () => {
+ const runner = createRunner()
+ .unordered()
+ .expect(segmentNamed('GET /users/me', '/users/me'))
+ .expect(segmentNamed('GET /posts/:id', '/posts/:id'))
+ .expect(segmentNamed('GET /posts/:id', '/posts/:id'))
+ .expect(segmentNamed('GET /posts/*', '/posts/*'))
+ .start();
+
+ expect(await runner.makeRequest('get', '/users/me')).toEqual({ wrappers: 0 });
+ // The second request gets the same cached handler list.
+ expect(await runner.makeRequest('get', '/posts/1')).toEqual({ wrappers: 1 });
+ expect(await runner.makeRequest('get', '/posts/1')).toEqual({ wrappers: 1 });
+ expect(await runner.makeRequest('get', '/posts/draft')).toEqual({ wrappers: 1 });
+ await runner.completed();
+ });
+ },
+ options,
);
- expect(internalRequestSpans).toHaveLength(1);
- expect(internalRequestSpans[0]?.name).toBe('GET /item/self-watering-plant');
-
- // The inner app's Sentry middleware must not add a middleware span.
- const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name);
- expect(middlewareNames).not.toContain('');
- });
-
- test('captures an error thrown inside an internal .request() even when the outer handler degrades to 200', async () => {
- const runner = createRunner()
- .unordered()
- .expect({
- event: event => {
- expect(event.exception?.values?.[0]?.value).toBe('inventory db is down');
- expect(event.exception?.values?.[0]?.mechanism).toEqual(
- expect.objectContaining({ type: 'auto.http.hono.context_error', handled: false }),
- );
- },
- })
- .start();
- runner.makeRequest('get', '/degraded/self-watering-plant');
- await runner.completed();
- });
-
- test('captures an error thrown after an internal .request() with the outer request data', async () => {
- const runner = createRunner()
- .unordered()
- .expect({
- event: event => {
- expect(event.exception?.values?.[0]?.value).toBe('Test error from outer Hono app after internal request');
- // The internal `.request()` dispatch must not overwrite the request data with its own URL.
- expect(event.request?.url).toContain('/outer-error/self-watering-plant');
- expect(event.request?.url).not.toContain('/item/');
- },
- })
- .start();
- runner.makeRequest('get', '/outer-error/self-watering-plant', { expectError: true });
- await runner.completed();
- });
-
- test('does not set the middleware span to error for a 3xx middleware error', async () => {
- const runner = createRunner()
- .unordered()
- .expect({
- span: container => {
- const middlewareSpan = container.items.find(
- item => op(item) === 'middleware' && item.name === 'throwingMiddleware',
- );
- if (!middlewareSpan) {
- throw new Error('middleware span `throwingMiddleware` not in this container');
- }
- expect(middlewareSpan.status).not.toBe('error');
- },
- })
- .start();
- runner.makeRequest('get', '/mw-throw/301', { expectError: true });
- await runner.completed();
- });
-
- test('does not set the middleware span to error for a 4xx middleware error', async () => {
- const runner = createRunner()
- .unordered()
- .expect({
- span: container => {
- const middlewareSpan = container.items.find(
- item => op(item) === 'middleware' && item.name === 'throwingMiddleware',
- );
- if (!middlewareSpan) {
- throw new Error('middleware span `throwingMiddleware` not in this container');
- }
- expect(middlewareSpan.status).not.toBe('error');
- },
- })
- .start();
- runner.makeRequest('get', '/mw-throw/404', { expectError: true });
- await runner.completed();
- });
+ },
+ );
+}
- test('sets the middleware span to error for a 5xx middleware error', async () => {
- const runner = createRunner()
- .unordered()
- .expect({
- span: container => {
- const middlewareSpan = container.items.find(
- item => op(item) === 'middleware' && item.name === 'throwingMiddleware',
- );
- if (!middlewareSpan) {
- throw new Error('middleware span `throwingMiddleware` not in this container');
- }
- expect(middlewareSpan.status).toBe('error');
- },
- })
- .start();
- runner.makeRequest('get', '/mw-throw/503', { expectError: true });
- await runner.completed();
+// Hono 5 runs `onError()` and `notFound()` handlers as `(c, next)` middleware. Hono 4 has no such
+// middleware, so these cases run only on Hono 5.
+for (const { minNode, options } of HONO_MAJORS.filter(({ major }) => major === 5)) {
+ describe.runIf(supports({ min: minNode }))('hono error and not-found middleware on Hono 5', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
});
- });
-});
-
-describe('hono auto-instrumentation with honoMiddleware(app)', () => {
- afterAll(() => {
- cleanupChildProcesses();
- });
- createEsmAndCjsTests(__dirname, 'scenario-honoMiddleware.mjs', 'instrument.mjs', (createRunner, test) => {
- test('wraps route handlers only when more than one matches, and only once', async () => {
- const runner = createRunner()
- .unordered()
- .expect(segmentNamed('GET /users/me', '/users/me'))
- .expect(segmentNamed('GET /posts/:id', '/posts/:id'))
- .expect(segmentNamed('GET /posts/:id', '/posts/:id'))
- .expect(segmentNamed('GET /posts/*', '/posts/*'))
- .start();
-
- expect(await runner.makeRequest('get', '/users/me')).toEqual({ wrappers: 0 });
- // The second request gets the same cached handler list.
- expect(await runner.makeRequest('get', '/posts/1')).toEqual({ wrappers: 1 });
- expect(await runner.makeRequest('get', '/posts/1')).toEqual({ wrappers: 1 });
- expect(await runner.makeRequest('get', '/posts/draft')).toEqual({ wrappers: 1 });
- await runner.completed();
- });
+ createEsmAndCjsTests(
+ __dirname,
+ 'scenario-error-middleware.mjs',
+ 'instrument.mjs',
+ (createRunner, test) => {
+ test('captures an error from a not-found handler, but not a 404 HTTPException', async () => {
+ // In this order, an event for the 404 would arrive first and fail the expectation.
+ const runner = createRunner()
+ .ignore('span')
+ .expect({
+ event: {
+ exception: {
+ values: [
+ {
+ type: 'Error',
+ value: 'Error from a not-found handler',
+ mechanism: { type: 'auto.http.hono.context_error', handled: false },
+ },
+ ],
+ },
+ },
+ })
+ .start();
+ await runner.makeRequest('get', '/not-found-http-exception/1', { expectError: true });
+ await runner.makeRequest('get', '/not-found-error/1', { expectError: true });
+ await runner.completed();
+ });
+
+ test('captures the error that an error handler throws, with the original error as its cause', async () => {
+ const runner = createRunner()
+ .ignore('span')
+ .expect({
+ event: {
+ exception: {
+ values: [
+ {
+ value: 'Original error from a route handler',
+ mechanism: { exception_id: 1, handled: true, parent_id: 0, source: 'cause', type: 'chained' },
+ },
+ {
+ value: 'Replacement error from an error handler',
+ mechanism: { exception_id: 0, handled: false, type: 'auto.http.hono.context_error' },
+ },
+ ],
+ },
+ transaction: 'GET /replace-error',
+ },
+ })
+ .start();
+ await runner.makeRequest('get', '/replace-error', { expectError: true });
+ await runner.completed();
+ });
+
+ test('does not create a middleware span for error middleware in a sub-app', async () => {
+ const runner = createRunner().unordered();
+ const spans = runner.collectStreamedSpansUntilSegment(span => attr(span, URL_PATH) === '/sub/fail');
+ const started = runner.start();
+ await started.makeRequest('get', '/sub/fail', { expectError: true });
+ await started.completed();
+
+ const items = await spans;
+ expect(items.find(item => item.is_segment)?.name).toBe('GET /sub/fail');
+ const middlewareNames = items.filter(item => op(item) === MIDDLEWARE).map(item => item.name);
+ expect(middlewareNames).toContain('subAppMiddleware');
+ expect(middlewareNames).not.toContain('errorMiddleware');
+ });
+ },
+ options,
+ );
});
-});
+}
diff --git a/dev-packages/node-integration-tests/suites/modules/esm-app/lib/package.json b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/package.json
new file mode 100644
index 000000000000..3dbc1ca591c0
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/package.json
@@ -0,0 +1,3 @@
+{
+ "type": "module"
+}
diff --git a/dev-packages/node-integration-tests/suites/modules/instrument.mjs b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js
similarity index 53%
rename from dev-packages/node-integration-tests/suites/modules/instrument.mjs
rename to dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js
index c8cdc9cac0a2..115249cf6d38 100644
--- a/dev-packages/node-integration-tests/suites/modules/instrument.mjs
+++ b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js
@@ -1,11 +1,11 @@
import * as Sentry from '@sentry/node';
import { loggingTransport } from '@sentry-internal/node-integration-tests';
+import 'esm-app-transitive';
Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
release: '1.0',
transport: loggingTransport,
- // Tracing is off, so `expressIntegration()` is not a default integration; opt in explicitly to
- // capture the thrown route error this test inspects.
- integrations: [Sentry.expressIntegration()],
});
+
+Sentry.captureException(new Error('error_1'));
diff --git a/dev-packages/node-integration-tests/suites/modules/esm-app/package.json b/dev-packages/node-integration-tests/suites/modules/esm-app/package.json
new file mode 100644
index 000000000000..7c4e56ac3728
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/modules/esm-app/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "esm-app",
+ "private": true,
+ "dependencies": {
+ "esm-app-dependency": "^1.0.0"
+ },
+ "devDependencies": {
+ "esm-app-missing-dependency": "^2.0.0"
+ }
+}
diff --git a/dev-packages/node-integration-tests/suites/modules/scenario.js b/dev-packages/node-integration-tests/suites/modules/scenario.js
new file mode 100644
index 000000000000..fc966f0457fb
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/modules/scenario.js
@@ -0,0 +1,12 @@
+const { loggingTransport } = require('@sentry-internal/node-integration-tests');
+const Sentry = require('@sentry/node');
+
+Sentry.init({
+ dsn: 'https://public@dsn.ingest.sentry.io/1337',
+ release: '1.0',
+ transport: loggingTransport,
+});
+
+require('express');
+
+Sentry.captureException(new Error('error_1'));
diff --git a/dev-packages/node-integration-tests/suites/modules/scenario.mjs b/dev-packages/node-integration-tests/suites/modules/scenario.mjs
new file mode 100644
index 000000000000..874679d5b877
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/modules/scenario.mjs
@@ -0,0 +1,11 @@
+import * as Sentry from '@sentry/node';
+import { loggingTransport } from '@sentry-internal/node-integration-tests';
+import 'express';
+
+Sentry.init({
+ dsn: 'https://public@dsn.ingest.sentry.io/1337',
+ release: '1.0',
+ transport: loggingTransport,
+});
+
+Sentry.captureException(new Error('error_1'));
diff --git a/dev-packages/node-integration-tests/suites/modules/server.js b/dev-packages/node-integration-tests/suites/modules/server.js
deleted file mode 100644
index bf5ec659e060..000000000000
--- a/dev-packages/node-integration-tests/suites/modules/server.js
+++ /dev/null
@@ -1,23 +0,0 @@
-const { loggingTransport } = require('@sentry-internal/node-integration-tests');
-const Sentry = require('@sentry/node');
-
-Sentry.init({
- dsn: 'https://public@dsn.ingest.sentry.io/1337',
- release: '1.0',
- transport: loggingTransport,
- // Tracing is off, so `expressIntegration()` is not a default integration; opt in explicitly to
- // capture the thrown route error this test inspects.
- integrations: [Sentry.expressIntegration()],
-});
-
-// express must be required after Sentry is initialized
-const express = require('express');
-const { startExpressServerAndSendPortToRunner } = require('@sentry-internal/node-integration-tests');
-
-const app = express();
-
-app.get('/test1', () => {
- throw new Error('error_1');
-});
-
-startExpressServerAndSendPortToRunner(app);
diff --git a/dev-packages/node-integration-tests/suites/modules/server.mjs b/dev-packages/node-integration-tests/suites/modules/server.mjs
deleted file mode 100644
index d34710e81dad..000000000000
--- a/dev-packages/node-integration-tests/suites/modules/server.mjs
+++ /dev/null
@@ -1,10 +0,0 @@
-import { startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests';
-import express from 'express';
-
-const app = express();
-
-app.get('/test1', () => {
- throw new Error('error_1');
-});
-
-startExpressServerAndSendPortToRunner(app);
diff --git a/dev-packages/node-integration-tests/suites/modules/test.ts b/dev-packages/node-integration-tests/suites/modules/test.ts
index 5e6b65cc8672..cee120ea4f03 100644
--- a/dev-packages/node-integration-tests/suites/modules/test.ts
+++ b/dev-packages/node-integration-tests/suites/modules/test.ts
@@ -1,35 +1,42 @@
import { SDK_VERSION } from '@sentry/core';
-import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'fs';
+import { copyFileSync, cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs';
import { dirname, join } from 'path';
import { afterAll, describe, expect, test } from 'vitest';
import { cleanupChildProcesses, createRunner } from '../../utils/runner';
+// Each test writes its packages into a folder of its own, because the Bun integration tests run this suite in
+// several projects at the same time.
+function makeTempDir(): string {
+ return mkdtempSync(join(__dirname, 'tmp-'));
+}
+
describe('modulesIntegration', () => {
afterAll(() => {
cleanupChildProcesses();
});
test('CJS', async () => {
- const runner = createRunner(__dirname, 'server.js')
- .withMockSentryServer()
+ await createRunner(__dirname, 'scenario.js')
.expect({
event: {
modules: {
- // exact version comes from require.caches
express: expect.stringMatching(/^4\.\d+\.\d+$/),
- // this comes from package.json
'@sentry/node': SDK_VERSION,
- yargs: '^18.2.0',
+ // Declared in package.json and installed, but never loaded
+ yargs: expect.stringMatching(/^18\.\d+\.\d+$/),
+ // Not declared, but loaded by express, so it is in require.cache
+ finalhandler: expect.stringMatching(/^\d+\.\d+\.\d+$/),
},
},
})
- .start();
- runner.makeRequest('get', '/test1', { expectError: true });
- await runner.completed();
+ .start()
+ .completed();
});
test('CJS with the isolated layouts of pnpm and Bun', async () => {
- const nodeModulesDir = join(__dirname, 'node_modules');
+ const tempDir = makeTempDir();
+ copyFileSync(join(__dirname, 'scenario-isolated.js'), join(tempDir, 'scenario-isolated.js'));
+ const nodeModulesDir = join(tempDir, 'node_modules');
for (const [storeDir, name, version, linked] of [
['.pnpm', 'pnpm-isolated-package', '1.2.3', true],
// Only a dependency of the app uses this version, so it is not linked into `node_modules`
@@ -50,7 +57,7 @@ describe('modulesIntegration', () => {
}
try {
- await createRunner(__dirname, 'scenario-isolated.js')
+ await createRunner(tempDir, 'scenario-isolated.js')
.expect({
event: {
modules: {
@@ -64,26 +71,58 @@ describe('modulesIntegration', () => {
.start()
.completed();
} finally {
- rmSync(nodeModulesDir, { recursive: true, force: true });
+ rmSync(tempDir, { recursive: true, force: true });
}
});
test('ESM', async () => {
- const runner = createRunner(__dirname, 'server.mjs')
- .withInstrument(join(__dirname, 'instrument.mjs'))
- .withMockSentryServer()
+ await createRunner(__dirname, 'scenario.mjs')
.expect({
event: {
modules: {
- // this comes from package.json
- express: expect.stringMatching(/^\^4\.\d+\.\d+$/),
+ express: expect.stringMatching(/^4\.\d+\.\d+$/),
'@sentry/node': SDK_VERSION,
- yargs: '^18.2.0',
+ yargs: expect.stringMatching(/^18\.\d+\.\d+$/),
},
},
})
- .start();
- runner.makeRequest('get', '/test1', { expectError: true });
- await runner.completed();
+ .start()
+ .completed();
+ });
+
+ test('ESM app in a subfolder with its own package.json', async () => {
+ const tempDir = makeTempDir();
+ const appDir = join(tempDir, 'esm-app');
+ cpSync(join(__dirname, 'esm-app'), appDir, { recursive: true });
+ const packageDir = join(appDir, 'node_modules', 'esm-app-dependency');
+ mkdirSync(packageDir, { recursive: true });
+ writeFileSync(join(packageDir, 'package.json'), JSON.stringify({ name: 'esm-app-dependency', version: '1.4.0' }));
+ // A CommonJS package that the app imports but does not declare, like a transitive dependency
+ const transitiveDir = join(appDir, 'node_modules', 'esm-app-transitive');
+ mkdirSync(transitiveDir, { recursive: true });
+ writeFileSync(
+ join(transitiveDir, 'package.json'),
+ JSON.stringify({ name: 'esm-app-transitive', version: '3.1.0' }),
+ );
+ writeFileSync(join(transitiveDir, 'index.js'), 'module.exports = {};');
+
+ try {
+ await createRunner(appDir, 'lib', 'scenario.js')
+ .expect({
+ event: event => {
+ // Packages the SDK itself loads from the repo's node_modules can show up too
+ expect(event.modules).toMatchObject({
+ 'esm-app-dependency': '1.4.0',
+ 'esm-app-transitive': '3.1.0',
+ // Not installed, so the range from package.json is all there is
+ 'esm-app-missing-dependency': '^2.0.0',
+ });
+ },
+ })
+ .start()
+ .completed();
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
});
});
diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/embeddings.test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/embeddings.test.ts
new file mode 100644
index 000000000000..4fa31cfa130e
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/embeddings.test.ts
@@ -0,0 +1,102 @@
+import { afterAll, describe, expect } from 'vitest';
+import {
+ GEN_AI_EMBEDDINGS_INPUT,
+ GEN_AI_OPERATION_NAME,
+ GEN_AI_PROVIDER_NAME,
+ GEN_AI_REQUEST_MODEL,
+ SENTRY_OP,
+ SENTRY_ORIGIN,
+} from '@sentry/conventions/attributes';
+import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner';
+
+const EXPECTED_ORIGIN = 'auto.ai.google_genai';
+
+describe('Google GenAI integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('creates google genai embeddings spans with genAI recording disabled', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
+ const spans = container.items.filter(
+ span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
+ );
+ expect(spans).toHaveLength(3);
+ expect(spans.map(span => span.name).sort()).toEqual([
+ 'embeddings error-model',
+ 'embeddings text-embedding-004',
+ 'embeddings text-embedding-004',
+ ]);
+
+ const successfulSpans = spans.filter(
+ span => span.name === 'embeddings text-embedding-004' && span.status === 'ok',
+ );
+ expect(successfulSpans).toHaveLength(2);
+ for (const span of successfulSpans) {
+ expect(span.attributes[SENTRY_OP].value).toBe('gen_ai.embeddings');
+ expect(span.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings');
+ expect(span.attributes[SENTRY_ORIGIN].value).toBe(EXPECTED_ORIGIN);
+ expect(span.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
+ expect(span.attributes[GEN_AI_REQUEST_MODEL].value).toBe('text-embedding-004');
+ expect(span.attributes[GEN_AI_EMBEDDINGS_INPUT]).toBeUndefined();
+ }
+
+ const errorSpan = spans.find(span => span.name === 'embeddings error-model');
+ expect(errorSpan!.status).toBe('error');
+ expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.embeddings');
+ expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings');
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+
+ createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
+ test('creates google genai embeddings spans with genAI recording enabled', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
+ const spans = container.items.filter(
+ span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
+ );
+ expect(spans).toHaveLength(3);
+ expect(spans.map(span => span.name).sort()).toEqual([
+ 'embeddings error-model',
+ 'embeddings text-embedding-004',
+ 'embeddings text-embedding-004',
+ ]);
+
+ const stringInputSpan = spans.find(
+ span => span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value === 'What is the capital of France?',
+ );
+ expect(stringInputSpan!.name).toBe('embeddings text-embedding-004');
+ expect(stringInputSpan!.status).toBe('ok');
+ expect(stringInputSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings');
+ expect(stringInputSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
+
+ const errorSpan = spans.find(span => span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value === 'This will fail');
+ expect(errorSpan!.name).toBe('embeddings error-model');
+ expect(errorSpan!.status).toBe('error');
+ expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings');
+
+ const arrayInputSpan = spans.find(
+ span =>
+ span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value ===
+ '[{"role":"user","parts":[{"text":"First input text"}]},{"role":"user","parts":[{"text":"Second input text"}]}]',
+ );
+ expect(arrayInputSpan!.name).toBe('embeddings text-embedding-004');
+ expect(arrayInputSpan!.status).toBe('ok');
+ expect(arrayInputSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings');
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/generation.test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/generation.test.ts
new file mode 100644
index 000000000000..04f9a49a8157
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/generation.test.ts
@@ -0,0 +1,194 @@
+import { afterAll, describe, expect } from 'vitest';
+import {
+ GEN_AI_INPUT_MESSAGES,
+ GEN_AI_OPERATION_NAME,
+ GEN_AI_PROVIDER_NAME,
+ GEN_AI_REQUEST_MAX_TOKENS,
+ GEN_AI_REQUEST_MODEL,
+ GEN_AI_REQUEST_TEMPERATURE,
+ GEN_AI_REQUEST_TOP_P,
+ GEN_AI_RESPONSE_TEXT,
+ GEN_AI_SYSTEM_INSTRUCTIONS,
+ GEN_AI_USAGE_INPUT_TOKENS,
+ GEN_AI_USAGE_OUTPUT_TOKENS,
+ GEN_AI_USAGE_TOTAL_TOKENS,
+ SENTRY_OP,
+ SENTRY_ORIGIN,
+} from '@sentry/conventions/attributes';
+import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner';
+
+const EXPECTED_ORIGIN = 'auto.ai.google_genai';
+
+describe('Google GenAI integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('creates google genai related spans with genAI recording disabled', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
+ const spans = container.items.filter(
+ span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
+ );
+ expect(spans).toHaveLength(3);
+ expect(spans.map(span => span.name).sort()).toEqual([
+ 'chat gemini-1.5-pro',
+ 'generate_content error-model',
+ 'generate_content gemini-1.5-flash',
+ ]);
+
+ const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro');
+ expect(chatSpan!.status).toBe('ok');
+ expect(chatSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.chat');
+ expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat');
+ expect(chatSpan!.attributes[SENTRY_ORIGIN].value).toBe(EXPECTED_ORIGIN);
+ expect(chatSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-pro');
+ // Given once to `chats.create()` and reused for every message the chat sends.
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8);
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150);
+ expect(chatSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS]).toBeUndefined();
+ expect(chatSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8);
+ expect(chatSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12);
+ expect(chatSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20);
+
+ const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash');
+ expect(generateContentSpan!.status).toBe('ok');
+ expect(generateContentSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
+ expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(generateContentSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-flash');
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100);
+ expect(generateContentSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8);
+ expect(generateContentSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12);
+ expect(generateContentSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20);
+
+ const errorSpan = spans.find(span => span.name === 'generate_content error-model');
+ expect(errorSpan!.status).toBe('error');
+ expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
+ expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(errorSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
+ expect(errorSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('error-model');
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+
+ createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
+ test('creates google genai related spans with genAI recording enabled', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
+ const spans = container.items.filter(
+ span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
+ );
+ expect(spans).toHaveLength(3);
+ expect(spans.map(span => span.name).sort()).toEqual([
+ 'chat gemini-1.5-pro',
+ 'generate_content error-model',
+ 'generate_content gemini-1.5-flash',
+ ]);
+
+ const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro');
+ expect(chatSpan!.status).toBe('ok');
+ expect(chatSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.chat');
+ expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat');
+ expect(chatSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-pro');
+ expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ expect(chatSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
+ // Given once to `chats.create()` and reused for every message the chat sends.
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8);
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150);
+ expect(chatSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe(
+ '[{"type":"text","content":"You are a friendly robot who likes to be funny."}]',
+ );
+ expect(chatSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8);
+ expect(chatSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12);
+ expect(chatSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20);
+
+ const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash');
+ expect(generateContentSpan!.status).toBe('ok');
+ expect(generateContentSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
+ expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(generateContentSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-flash');
+ expect(generateContentSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100);
+
+ const errorSpan = spans.find(span => span.name === 'generate_content error-model');
+ expect(errorSpan!.status).toBe('error');
+ expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
+ expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(errorSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+
+ createEsmAndCjsTests(
+ __dirname,
+ 'scenario-system-instructions.mjs',
+ 'instrument-with-pii.mjs',
+ (createRunner, test) => {
+ test('extracts system instructions and normalizes messages', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
+ const spans = container.items.filter(
+ span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
+ );
+ expect(spans).toHaveLength(2);
+ const [firstSpan, secondSpan] = spans;
+
+ // [0] generate_content with a string system instruction
+ expect(firstSpan!.name).toBe('generate_content gemini-1.5-flash');
+ expect(firstSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(firstSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe(
+ JSON.stringify([{ type: 'text', content: 'You are a helpful assistant' }]),
+ );
+ expect(firstSpan!.attributes[GEN_AI_INPUT_MESSAGES].value).toBe(
+ JSON.stringify([{ role: 'user', parts: [{ type: 'text', content: 'Hello' }] }]),
+ );
+
+ // [1] generate_content with a `Content` system instruction and a tool-call turn
+ expect(secondSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe(
+ JSON.stringify([{ type: 'text', content: 'You are a helpful assistant' }]),
+ );
+ expect(secondSpan!.attributes[GEN_AI_INPUT_MESSAGES].value).toBe(
+ JSON.stringify([
+ { role: 'user', parts: [{ type: 'text', content: 'What time is it in Tokyo?' }] },
+ {
+ role: 'assistant',
+ parts: [{ type: 'tool_call', name: 'get_time', arguments: '{"timezone":"Asia/Tokyo"}' }],
+ },
+ {
+ role: 'user',
+ parts: [{ type: 'tool_call_response', name: 'get_time', result: '{"output":"10:00"}' }],
+ },
+ ]),
+ );
+ },
+ })
+ .start()
+ .completed();
+ });
+ },
+ );
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/options.test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/options.test.ts
new file mode 100644
index 000000000000..63274847115f
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/options.test.ts
@@ -0,0 +1,112 @@
+import { afterAll, describe, expect } from 'vitest';
+import {
+ GEN_AI_INPUT_MESSAGES,
+ GEN_AI_OPERATION_NAME,
+ GEN_AI_REQUEST_MODEL,
+ GEN_AI_RESPONSE_TEXT,
+ SENTRY_ORIGIN,
+} from '@sentry/conventions/attributes';
+import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner';
+
+const EXPECTED_ORIGIN = 'auto.ai.google_genai';
+
+describe('Google GenAI integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-with-options.mjs', (createRunner, test) => {
+ test('creates google genai related spans with custom options', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
+ const spans = container.items.filter(
+ span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
+ );
+ expect(spans).toHaveLength(3);
+ expect(spans.map(span => span.name).sort()).toEqual([
+ 'chat gemini-1.5-pro',
+ 'generate_content error-model',
+ 'generate_content gemini-1.5-flash',
+ ]);
+
+ const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro');
+ expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat');
+ expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ expect(chatSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
+
+ const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash');
+ expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+
+ const errorSpan = spans.find(span => span.name === 'generate_content error-model');
+ expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+
+ createEsmAndCjsTests(
+ __dirname,
+ 'scenario-recording-functions.mjs',
+ 'instrument-with-recording-functions.mjs',
+ (createRunner, test) => {
+ test('decides content recording per call when the options are functions', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN);
+ const recordedByModel = Object.fromEntries(
+ spans.map(span => [
+ span.attributes[GEN_AI_REQUEST_MODEL]?.value,
+ {
+ inputs: GEN_AI_INPUT_MESSAGES in span.attributes,
+ outputs: GEN_AI_RESPONSE_TEXT in span.attributes,
+ },
+ ]),
+ );
+ expect(recordedByModel).toEqual({
+ 'gemini-public': { inputs: true, outputs: true },
+ 'gemini-private': { inputs: false, outputs: false },
+ 'gemini-public-stream': { inputs: true, outputs: false },
+ });
+ },
+ })
+ .start()
+ .completed();
+ });
+ },
+ );
+
+ createEsmAndCjsTests(
+ __dirname,
+ 'scenario-recording-functions.mjs',
+ 'instrument-with-span-hooks.mjs',
+ (createRunner, test) => {
+ test('runs the span hooks at start in the caller context and at end with the response', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN);
+ const hooksByKey = Object.fromEntries(
+ spans.map(span => [
+ span.attributes[GEN_AI_REQUEST_MODEL]?.value,
+ [span.attributes['test.start']?.value, span.attributes['test.end']?.value],
+ ]),
+ );
+ expect(hooksByKey).toEqual({
+ 'gemini-public': ['gemini-public:public', 'Paris.'],
+ 'gemini-private': ['gemini-private:private', 'Paris.'],
+ // A stream has no single response object, and its tag changes only after the call started.
+ 'gemini-public-stream': ['gemini-public-stream:private', 'no response'],
+ });
+ },
+ })
+ .start()
+ .completed();
+ });
+ },
+ );
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/streaming.test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/streaming.test.ts
new file mode 100644
index 000000000000..978ef2041656
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/streaming.test.ts
@@ -0,0 +1,230 @@
+import type { Event, SerializedStreamedSpanContainer } from '@sentry/core';
+import { afterAll, describe, expect } from 'vitest';
+import {
+ GEN_AI_INPUT_MESSAGES,
+ GEN_AI_OPERATION_NAME,
+ GEN_AI_REQUEST_MAX_TOKENS,
+ GEN_AI_REQUEST_TEMPERATURE,
+ GEN_AI_REQUEST_TOP_P,
+ GEN_AI_RESPONSE_FINISH_REASONS,
+ GEN_AI_RESPONSE_ID,
+ GEN_AI_RESPONSE_MODEL,
+ GEN_AI_RESPONSE_STREAMING,
+ GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK,
+ GEN_AI_RESPONSE_TEXT,
+ GEN_AI_USAGE_INPUT_TOKENS,
+ GEN_AI_USAGE_OUTPUT_TOKENS,
+ GEN_AI_USAGE_TOTAL_TOKENS,
+ SENTRY_OP,
+ SENTRY_ORIGIN,
+} from '@sentry/conventions/attributes';
+import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner';
+
+const EXPECTED_ORIGIN = 'auto.ai.google_genai';
+
+describe('Google GenAI integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ createEsmAndCjsTests(__dirname, 'scenario-streaming.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('creates google genai streaming spans with genAI recording disabled', async () => {
+ let receivedEvent: Event | undefined;
+ let receivedSpans: SerializedStreamedSpanContainer['items'] = [];
+
+ await createRunner()
+ // The provider surfaces blocked content within the stream and never returns it to the caller as
+ // a thrown error, so the instrumentation intentionally captures it as an event.
+ .unordered()
+ .expect({
+ event: event => {
+ receivedEvent = event;
+ },
+ })
+ .expect({
+ span: container => {
+ expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
+ receivedSpans = container.items;
+ },
+ })
+ .start()
+ .completed();
+
+ expect(receivedEvent).toMatchObject({
+ event_id: expect.any(String),
+ exception: {
+ values: [
+ {
+ value: 'Content blocked: The prompt was blocked due to safety concerns',
+ mechanism: { type: 'auto.ai.google_genai', handled: false },
+ },
+ ],
+ },
+ });
+
+ const spans = receivedSpans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai');
+ expect(spans).toHaveLength(4);
+ expect(spans.map(span => span.name).sort()).toEqual([
+ 'chat gemini-1.5-pro',
+ 'generate_content blocked-model',
+ 'generate_content error-model',
+ 'generate_content gemini-1.5-flash',
+ ]);
+
+ const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash');
+ expect(generateContentSpan!.status).toBe('ok');
+ expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
+ expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK]?.value).toEqual(expect.any(Number));
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100);
+ expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-streaming-id');
+ expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-1.5-pro');
+ expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]');
+ expect(generateContentSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(10);
+ expect(generateContentSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12);
+ expect(generateContentSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(22);
+
+ const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro');
+ expect(chatSpan!.status).toBe('ok');
+ expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat');
+ expect(chatSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
+ // Given once to `chats.create()` and reused for every message the chat sends.
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8);
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150);
+ expect(chatSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-streaming-id');
+ expect(chatSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-1.5-pro');
+
+ const blockedSpan = spans.find(span => span.name === 'generate_content blocked-model');
+ expect(blockedSpan!.status).toBe('error');
+ expect(blockedSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
+ expect(blockedSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+
+ const errorSpan = spans.find(span => span.name === 'generate_content error-model');
+ expect(errorSpan!.status).toBe('error');
+ expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
+ expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ });
+ });
+
+ createEsmAndCjsTests(__dirname, 'scenario-streaming.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
+ test('creates google genai streaming spans with genAI recording enabled', async () => {
+ let receivedEvent: Event | undefined;
+ let receivedSpans: SerializedStreamedSpanContainer['items'] = [];
+
+ await createRunner()
+ // The provider surfaces blocked content within the stream and never returns it to the caller as
+ // a thrown error, so the instrumentation intentionally captures it as an event.
+ .unordered()
+ .expect({
+ event: event => {
+ receivedEvent = event;
+ },
+ })
+ .expect({
+ span: container => {
+ expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
+ receivedSpans = container.items;
+ },
+ })
+ .start()
+ .completed();
+
+ expect(receivedEvent).toMatchObject({
+ event_id: expect.any(String),
+ exception: {
+ values: [
+ {
+ value: 'Content blocked: The prompt was blocked due to safety concerns',
+ mechanism: { type: 'auto.ai.google_genai', handled: false },
+ },
+ ],
+ },
+ });
+
+ const spans = receivedSpans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai');
+ expect(spans).toHaveLength(4);
+ expect(spans.map(span => span.name).sort()).toEqual([
+ 'chat gemini-1.5-pro',
+ 'generate_content blocked-model',
+ 'generate_content error-model',
+ 'generate_content gemini-1.5-flash',
+ ]);
+
+ const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash');
+ expect(generateContentSpan!.status).toBe('ok');
+ expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
+ expect(generateContentSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
+ expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100);
+ expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]');
+
+ const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro');
+ expect(chatSpan!.status).toBe('ok');
+ expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat');
+ expect(chatSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
+ expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ // Given once to `chats.create()` and reused for every message the chat sends.
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8);
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
+ expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150);
+ expect(chatSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]');
+
+ const blockedSpan = spans.find(span => span.name === 'generate_content blocked-model');
+ expect(blockedSpan!.status).toBe('error');
+ expect(blockedSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(blockedSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
+ expect(blockedSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ expect(blockedSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
+
+ const errorSpan = spans.find(span => span.name === 'generate_content error-model');
+ expect(errorSpan!.status).toBe('error');
+ expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(errorSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
+ expect(errorSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ });
+ });
+
+ createEsmAndCjsTests(
+ __dirname,
+ 'scenario-stream-midway-error.mjs',
+ 'instrument-with-pii.mjs',
+ (createRunner, test) => {
+ test('marks the span as errored when the stream fails midway, but not when the caller breaks early', async () => {
+ await createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN);
+ expect(spans).toHaveLength(6);
+
+ const midwaySpan = spans.find(span => span.name === 'generate_content midway-error');
+ expect(midwaySpan!.status).toBe('error');
+ expect(midwaySpan!.attributes[GEN_AI_RESPONSE_STREAMING]?.value).toBe(true);
+ expect(midwaySpan!.attributes[GEN_AI_RESPONSE_ID]?.value).toBe('mock-midway-response-id');
+ expect(midwaySpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBe(8);
+ expect(midwaySpan!.attributes[GEN_AI_RESPONSE_TEXT]?.value).toBe('This stream will be cut off');
+
+ const earlyBreakSpan = spans.find(span => span.name === 'generate_content early-break');
+ expect(earlyBreakSpan!.status).toBe('ok');
+ expect(earlyBreakSpan!.attributes[GEN_AI_RESPONSE_TEXT]?.value).toBe('This stream will ');
+
+ // `cancelled` is sent as `ok` under span streaming, so a timeout must not be recorded as one.
+ expect(spans.find(span => span.name === 'generate_content caller-abort')!.status).toBe('ok');
+ expect(spans.find(span => span.name === 'generate_content timeout')!.status).toBe('error');
+ expect(spans.find(span => span.name === 'generate_content caller-abort-before-stream')!.status).toBe(
+ 'ok',
+ );
+ expect(spans.find(span => span.name === 'generate_content timeout-before-stream')!.status).toBe('error');
+ },
+ })
+ .start()
+ .completed();
+ });
+ },
+ );
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts
deleted file mode 100644
index dfbf4d8eb345..000000000000
--- a/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts
+++ /dev/null
@@ -1,691 +0,0 @@
-import type { Event, SerializedStreamedSpanContainer } from '@sentry/core';
-import { afterAll, describe, expect } from 'vitest';
-import {
- GEN_AI_EMBEDDINGS_INPUT,
- GEN_AI_INPUT_MESSAGES,
- GEN_AI_OPERATION_NAME,
- GEN_AI_OUTPUT_MESSAGES,
- GEN_AI_PROVIDER_NAME,
- GEN_AI_REQUEST_MAX_TOKENS,
- GEN_AI_REQUEST_MODEL,
- GEN_AI_REQUEST_TEMPERATURE,
- GEN_AI_REQUEST_TOP_P,
- GEN_AI_RESPONSE_FINISH_REASONS,
- GEN_AI_RESPONSE_ID,
- GEN_AI_RESPONSE_MODEL,
- GEN_AI_RESPONSE_STREAMING,
- GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK,
- GEN_AI_RESPONSE_TEXT,
- GEN_AI_RESPONSE_TOOL_CALLS,
- GEN_AI_SYSTEM_INSTRUCTIONS,
- GEN_AI_TOOL_DEFINITIONS,
- GEN_AI_USAGE_INPUT_TOKENS,
- GEN_AI_USAGE_OUTPUT_TOKENS,
- GEN_AI_USAGE_TOTAL_TOKENS,
- SENTRY_OP,
- SENTRY_ORIGIN,
-} from '@sentry/conventions/attributes';
-import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner';
-
-const EXPECTED_ORIGIN = 'auto.ai.google_genai';
-
-describe('Google GenAI integration', () => {
- afterAll(() => {
- cleanupChildProcesses();
- });
-
- createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => {
- test('creates google genai related spans with genAI recording disabled', async () => {
- await createRunner()
- .expect({
- span: container => {
- expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
- const spans = container.items.filter(
- span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
- );
- expect(spans).toHaveLength(3);
- expect(spans.map(span => span.name).sort()).toEqual([
- 'chat gemini-1.5-pro',
- 'generate_content error-model',
- 'generate_content gemini-1.5-flash',
- ]);
-
- const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro');
- expect(chatSpan!.status).toBe('ok');
- expect(chatSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.chat');
- expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat');
- expect(chatSpan!.attributes[SENTRY_ORIGIN].value).toBe(EXPECTED_ORIGIN);
- expect(chatSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
- expect(chatSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-pro');
- // Given once to `chats.create()` and reused for every message the chat sends.
- expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8);
- expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
- expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150);
- expect(chatSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS]).toBeUndefined();
- expect(chatSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8);
- expect(chatSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12);
- expect(chatSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20);
-
- const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash');
- expect(generateContentSpan!.status).toBe('ok');
- expect(generateContentSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
- expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(generateContentSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-flash');
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100);
- expect(generateContentSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8);
- expect(generateContentSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12);
- expect(generateContentSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20);
-
- const errorSpan = spans.find(span => span.name === 'generate_content error-model');
- expect(errorSpan!.status).toBe('error');
- expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
- expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(errorSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
- expect(errorSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('error-model');
- },
- })
- .start()
- .completed();
- });
- });
-
- createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
- test('creates google genai related spans with genAI recording enabled', async () => {
- await createRunner()
- .expect({
- span: container => {
- expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
- const spans = container.items.filter(
- span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
- );
- expect(spans).toHaveLength(3);
- expect(spans.map(span => span.name).sort()).toEqual([
- 'chat gemini-1.5-pro',
- 'generate_content error-model',
- 'generate_content gemini-1.5-flash',
- ]);
-
- const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro');
- expect(chatSpan!.status).toBe('ok');
- expect(chatSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.chat');
- expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat');
- expect(chatSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
- expect(chatSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-pro');
- expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- expect(chatSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
- // Given once to `chats.create()` and reused for every message the chat sends.
- expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8);
- expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
- expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150);
- expect(chatSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe(
- '[{"type":"text","content":"You are a friendly robot who likes to be funny."}]',
- );
- expect(chatSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8);
- expect(chatSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12);
- expect(chatSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20);
-
- const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash');
- expect(generateContentSpan!.status).toBe('ok');
- expect(generateContentSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
- expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(generateContentSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-flash');
- expect(generateContentSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100);
-
- const errorSpan = spans.find(span => span.name === 'generate_content error-model');
- expect(errorSpan!.status).toBe('error');
- expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
- expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(errorSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- },
- })
- .start()
- .completed();
- });
- });
-
- createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-with-options.mjs', (createRunner, test) => {
- test('creates google genai related spans with custom options', async () => {
- await createRunner()
- .expect({
- span: container => {
- expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
- const spans = container.items.filter(
- span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
- );
- expect(spans).toHaveLength(3);
- expect(spans.map(span => span.name).sort()).toEqual([
- 'chat gemini-1.5-pro',
- 'generate_content error-model',
- 'generate_content gemini-1.5-flash',
- ]);
-
- const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro');
- expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat');
- expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- expect(chatSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
-
- const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash');
- expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
-
- const errorSpan = spans.find(span => span.name === 'generate_content error-model');
- expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- },
- })
- .start()
- .completed();
- });
- });
-
- const EXPECTED_AVAILABLE_TOOLS_JSON =
- '[{"name":"controlLight","parametersJsonSchema":{"type":"object","properties":{"brightness":{"type":"number"},"colorTemperature":{"type":"string"}},"required":["brightness","colorTemperature"]}}]';
-
- createEsmAndCjsTests(__dirname, 'scenario-tools.mjs', 'instrument-with-options.mjs', (createRunner, test) => {
- test('creates google genai related spans with tool calls', async () => {
- await createRunner()
- .expect({
- span: container => {
- expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
- const spans = container.items.filter(
- span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
- );
- expect(spans).toHaveLength(3);
- const nonStreamingToolsSpan = spans.find(
- span =>
- span.attributes[GEN_AI_TOOL_DEFINITIONS]?.value === EXPECTED_AVAILABLE_TOOLS_JSON &&
- span.attributes[GEN_AI_RESPONSE_STREAMING] === undefined,
- );
- expect(nonStreamingToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001');
- expect(nonStreamingToolsSpan!.status).toBe('ok');
- expect(nonStreamingToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(nonStreamingToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- expect(nonStreamingToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
- expect(JSON.parse(nonStreamingToolsSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS].value as string)).toEqual([
- {
- id: 'call_light_control_1',
- name: 'controlLight',
- args: { brightness: 0.3, colorTemperature: 'warm' },
- },
- ]);
- expect(nonStreamingToolsSpan!.attributes[GEN_AI_OUTPUT_MESSAGES].value).toBe(
- JSON.stringify([
- {
- role: 'assistant',
- parts: [
- { type: 'text', content: 'I need to check the light status first.' },
- {
- type: 'tool_call',
- id: 'call_light_control_1',
- name: 'controlLight',
- arguments: '{"brightness":0.3,"colorTemperature":"warm"}',
- },
- ],
- },
- ]),
- );
- expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(15);
- expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(8);
- expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(23);
-
- const streamingToolsSpan = spans.find(
- span =>
- span.attributes[GEN_AI_TOOL_DEFINITIONS]?.value === EXPECTED_AVAILABLE_TOOLS_JSON &&
- span.attributes[GEN_AI_RESPONSE_STREAMING]?.value === true,
- );
- expect(streamingToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001');
- expect(streamingToolsSpan!.status).toBe('ok');
- expect(streamingToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(streamingToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
- expect(JSON.parse(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS].value as string)).toEqual([
- {
- id: 'call_light_stream_1',
- name: 'controlLight',
- args: { brightness: 0.5, colorTemperature: 'cool' },
- },
- ]);
- // The text arrives either side of the tool call, so it stays two parts.
- expect(streamingToolsSpan!.attributes[GEN_AI_OUTPUT_MESSAGES].value).toBe(
- JSON.stringify([
- {
- role: 'assistant',
- parts: [
- { type: 'text', content: 'Let me control the lights for you.' },
- {
- type: 'tool_call',
- id: 'call_light_stream_1',
- name: 'controlLight',
- arguments: '{"brightness":0.5,"colorTemperature":"cool"}',
- },
- { type: 'text', content: ' Done!' },
- ],
- },
- ]),
- );
- expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-tools-id');
- expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-2.0-flash-001');
- expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(12);
- expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(10);
- expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(22);
-
- const noToolsSpan = spans.find(span => span.attributes[GEN_AI_TOOL_DEFINITIONS] === undefined);
- expect(noToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001');
- expect(noToolsSpan!.status).toBe('ok');
- expect(noToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(noToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- expect(noToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
- expect(noToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8);
- expect(noToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12);
- expect(noToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20);
- },
- })
- .start()
- .completed();
- });
- });
-
- createEsmAndCjsTests(__dirname, 'scenario-streaming.mjs', 'instrument.mjs', (createRunner, test) => {
- test('creates google genai streaming spans with genAI recording disabled', async () => {
- let receivedEvent: Event | undefined;
- let receivedSpans: SerializedStreamedSpanContainer['items'] = [];
-
- await createRunner()
- // The provider surfaces blocked content within the stream and never returns it to the caller as
- // a thrown error, so the instrumentation intentionally captures it as an event.
- .unordered()
- .expect({
- event: event => {
- receivedEvent = event;
- },
- })
- .expect({
- span: container => {
- expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
- receivedSpans = container.items;
- },
- })
- .start()
- .completed();
-
- expect(receivedEvent).toMatchObject({
- event_id: expect.any(String),
- exception: {
- values: [
- {
- value: 'Content blocked: The prompt was blocked due to safety concerns',
- mechanism: { type: 'auto.ai.google_genai', handled: false },
- },
- ],
- },
- });
-
- const spans = receivedSpans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai');
- expect(spans).toHaveLength(4);
- expect(spans.map(span => span.name).sort()).toEqual([
- 'chat gemini-1.5-pro',
- 'generate_content blocked-model',
- 'generate_content error-model',
- 'generate_content gemini-1.5-flash',
- ]);
-
- const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash');
- expect(generateContentSpan!.status).toBe('ok');
- expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
- expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK]?.value).toEqual(expect.any(Number));
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100);
- expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-streaming-id');
- expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-1.5-pro');
- expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]');
- expect(generateContentSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(10);
- expect(generateContentSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12);
- expect(generateContentSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(22);
-
- const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro');
- expect(chatSpan!.status).toBe('ok');
- expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat');
- expect(chatSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
- // Given once to `chats.create()` and reused for every message the chat sends.
- expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8);
- expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
- expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150);
- expect(chatSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-streaming-id');
- expect(chatSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-1.5-pro');
-
- const blockedSpan = spans.find(span => span.name === 'generate_content blocked-model');
- expect(blockedSpan!.status).toBe('error');
- expect(blockedSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
- expect(blockedSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
-
- const errorSpan = spans.find(span => span.name === 'generate_content error-model');
- expect(errorSpan!.status).toBe('error');
- expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content');
- expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- });
- });
-
- createEsmAndCjsTests(__dirname, 'scenario-streaming.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
- test('creates google genai streaming spans with genAI recording enabled', async () => {
- let receivedEvent: Event | undefined;
- let receivedSpans: SerializedStreamedSpanContainer['items'] = [];
-
- await createRunner()
- // The provider surfaces blocked content within the stream and never returns it to the caller as
- // a thrown error, so the instrumentation intentionally captures it as an event.
- .unordered()
- .expect({
- event: event => {
- receivedEvent = event;
- },
- })
- .expect({
- span: container => {
- expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
- receivedSpans = container.items;
- },
- })
- .start()
- .completed();
-
- expect(receivedEvent).toMatchObject({
- event_id: expect.any(String),
- exception: {
- values: [
- {
- value: 'Content blocked: The prompt was blocked due to safety concerns',
- mechanism: { type: 'auto.ai.google_genai', handled: false },
- },
- ],
- },
- });
-
- const spans = receivedSpans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai');
- expect(spans).toHaveLength(4);
- expect(spans.map(span => span.name).sort()).toEqual([
- 'chat gemini-1.5-pro',
- 'generate_content blocked-model',
- 'generate_content error-model',
- 'generate_content gemini-1.5-flash',
- ]);
-
- const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash');
- expect(generateContentSpan!.status).toBe('ok');
- expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
- expect(generateContentSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
- expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100);
- expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]');
-
- const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro');
- expect(chatSpan!.status).toBe('ok');
- expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat');
- expect(chatSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
- expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- // Given once to `chats.create()` and reused for every message the chat sends.
- expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8);
- expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9);
- expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150);
- expect(chatSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]');
-
- const blockedSpan = spans.find(span => span.name === 'generate_content blocked-model');
- expect(blockedSpan!.status).toBe('error');
- expect(blockedSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(blockedSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
- expect(blockedSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- expect(blockedSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
-
- const errorSpan = spans.find(span => span.name === 'generate_content error-model');
- expect(errorSpan!.status).toBe('error');
- expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(errorSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7);
- expect(errorSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
- });
- });
-
- createEsmAndCjsTests(
- __dirname,
- 'scenario-system-instructions.mjs',
- 'instrument-with-pii.mjs',
- (createRunner, test) => {
- test('extracts system instructions and normalizes messages', async () => {
- await createRunner()
- .expect({
- span: container => {
- expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
- const spans = container.items.filter(
- span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
- );
- expect(spans).toHaveLength(2);
- const [firstSpan, secondSpan] = spans;
-
- // [0] generate_content with a string system instruction
- expect(firstSpan!.name).toBe('generate_content gemini-1.5-flash');
- expect(firstSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
- expect(firstSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe(
- JSON.stringify([{ type: 'text', content: 'You are a helpful assistant' }]),
- );
- expect(firstSpan!.attributes[GEN_AI_INPUT_MESSAGES].value).toBe(
- JSON.stringify([{ role: 'user', parts: [{ type: 'text', content: 'Hello' }] }]),
- );
-
- // [1] generate_content with a `Content` system instruction and a tool-call turn
- expect(secondSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe(
- JSON.stringify([{ type: 'text', content: 'You are a helpful assistant' }]),
- );
- expect(secondSpan!.attributes[GEN_AI_INPUT_MESSAGES].value).toBe(
- JSON.stringify([
- { role: 'user', parts: [{ type: 'text', content: 'What time is it in Tokyo?' }] },
- {
- role: 'assistant',
- parts: [{ type: 'tool_call', name: 'get_time', arguments: '{"timezone":"Asia/Tokyo"}' }],
- },
- {
- role: 'user',
- parts: [{ type: 'tool_call_response', name: 'get_time', result: '{"output":"10:00"}' }],
- },
- ]),
- );
- },
- })
- .start()
- .completed();
- });
- },
- );
-
- createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument.mjs', (createRunner, test) => {
- test('creates google genai embeddings spans with genAI recording disabled', async () => {
- await createRunner()
- .expect({
- span: container => {
- expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
- const spans = container.items.filter(
- span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
- );
- expect(spans).toHaveLength(3);
- expect(spans.map(span => span.name).sort()).toEqual([
- 'embeddings error-model',
- 'embeddings text-embedding-004',
- 'embeddings text-embedding-004',
- ]);
-
- const successfulSpans = spans.filter(
- span => span.name === 'embeddings text-embedding-004' && span.status === 'ok',
- );
- expect(successfulSpans).toHaveLength(2);
- for (const span of successfulSpans) {
- expect(span.attributes[SENTRY_OP].value).toBe('gen_ai.embeddings');
- expect(span.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings');
- expect(span.attributes[SENTRY_ORIGIN].value).toBe(EXPECTED_ORIGIN);
- expect(span.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
- expect(span.attributes[GEN_AI_REQUEST_MODEL].value).toBe('text-embedding-004');
- expect(span.attributes[GEN_AI_EMBEDDINGS_INPUT]).toBeUndefined();
- }
-
- const errorSpan = spans.find(span => span.name === 'embeddings error-model');
- expect(errorSpan!.status).toBe('error');
- expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.embeddings');
- expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings');
- },
- })
- .start()
- .completed();
- });
- });
-
- createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
- test('creates google genai embeddings spans with genAI recording enabled', async () => {
- await createRunner()
- .expect({
- span: container => {
- expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
- const spans = container.items.filter(
- span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
- );
- expect(spans).toHaveLength(3);
- expect(spans.map(span => span.name).sort()).toEqual([
- 'embeddings error-model',
- 'embeddings text-embedding-004',
- 'embeddings text-embedding-004',
- ]);
-
- const stringInputSpan = spans.find(
- span => span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value === 'What is the capital of France?',
- );
- expect(stringInputSpan!.name).toBe('embeddings text-embedding-004');
- expect(stringInputSpan!.status).toBe('ok');
- expect(stringInputSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings');
- expect(stringInputSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai');
-
- const errorSpan = spans.find(span => span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value === 'This will fail');
- expect(errorSpan!.name).toBe('embeddings error-model');
- expect(errorSpan!.status).toBe('error');
- expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings');
-
- const arrayInputSpan = spans.find(
- span =>
- span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value ===
- '[{"role":"user","parts":[{"text":"First input text"}]},{"role":"user","parts":[{"text":"Second input text"}]}]',
- );
- expect(arrayInputSpan!.name).toBe('embeddings text-embedding-004');
- expect(arrayInputSpan!.status).toBe('ok');
- expect(arrayInputSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings');
- },
- })
- .start()
- .completed();
- });
- });
-
- createEsmAndCjsTests(
- __dirname,
- 'scenario-stream-midway-error.mjs',
- 'instrument-with-pii.mjs',
- (createRunner, test) => {
- test('marks the span as errored when the stream fails midway, but not when the caller breaks early', async () => {
- await createRunner()
- .unordered()
- .expect({
- span: container => {
- const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN);
- expect(spans).toHaveLength(6);
-
- const midwaySpan = spans.find(span => span.name === 'generate_content midway-error');
- expect(midwaySpan!.status).toBe('error');
- expect(midwaySpan!.attributes[GEN_AI_RESPONSE_STREAMING]?.value).toBe(true);
- expect(midwaySpan!.attributes[GEN_AI_RESPONSE_ID]?.value).toBe('mock-midway-response-id');
- expect(midwaySpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBe(8);
- expect(midwaySpan!.attributes[GEN_AI_RESPONSE_TEXT]?.value).toBe('This stream will be cut off');
-
- const earlyBreakSpan = spans.find(span => span.name === 'generate_content early-break');
- expect(earlyBreakSpan!.status).toBe('ok');
- expect(earlyBreakSpan!.attributes[GEN_AI_RESPONSE_TEXT]?.value).toBe('This stream will ');
-
- // `cancelled` is sent as `ok` under span streaming, so a timeout must not be recorded as one.
- expect(spans.find(span => span.name === 'generate_content caller-abort')!.status).toBe('ok');
- expect(spans.find(span => span.name === 'generate_content timeout')!.status).toBe('error');
- expect(spans.find(span => span.name === 'generate_content caller-abort-before-stream')!.status).toBe(
- 'ok',
- );
- expect(spans.find(span => span.name === 'generate_content timeout-before-stream')!.status).toBe('error');
- },
- })
- .start()
- .completed();
- });
- },
- );
-
- createEsmAndCjsTests(
- __dirname,
- 'scenario-recording-functions.mjs',
- 'instrument-with-recording-functions.mjs',
- (createRunner, test) => {
- test('decides content recording per call when the options are functions', async () => {
- await createRunner()
- .expect({
- span: container => {
- const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN);
- const recordedByModel = Object.fromEntries(
- spans.map(span => [
- span.attributes[GEN_AI_REQUEST_MODEL]?.value,
- {
- inputs: GEN_AI_INPUT_MESSAGES in span.attributes,
- outputs: GEN_AI_RESPONSE_TEXT in span.attributes,
- },
- ]),
- );
- expect(recordedByModel).toEqual({
- 'gemini-public': { inputs: true, outputs: true },
- 'gemini-private': { inputs: false, outputs: false },
- 'gemini-public-stream': { inputs: true, outputs: false },
- });
- },
- })
- .start()
- .completed();
- });
- },
- );
-
- createEsmAndCjsTests(
- __dirname,
- 'scenario-recording-functions.mjs',
- 'instrument-with-span-hooks.mjs',
- (createRunner, test) => {
- test('runs the span hooks at start in the caller context and at end with the response', async () => {
- await createRunner()
- .expect({
- span: container => {
- const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN);
- const hooksByKey = Object.fromEntries(
- spans.map(span => [
- span.attributes[GEN_AI_REQUEST_MODEL]?.value,
- [span.attributes['test.start']?.value, span.attributes['test.end']?.value],
- ]),
- );
- expect(hooksByKey).toEqual({
- 'gemini-public': ['gemini-public:public', 'Paris.'],
- 'gemini-private': ['gemini-private:private', 'Paris.'],
- // A stream has no single response object, and its tag changes only after the call started.
- 'gemini-public-stream': ['gemini-public-stream:private', 'no response'],
- });
- },
- })
- .start()
- .completed();
- });
- },
- );
-});
diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/tools.test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/tools.test.ts
new file mode 100644
index 000000000000..188e1a07695d
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/tools.test.ts
@@ -0,0 +1,130 @@
+import { afterAll, describe, expect } from 'vitest';
+import {
+ GEN_AI_INPUT_MESSAGES,
+ GEN_AI_OPERATION_NAME,
+ GEN_AI_OUTPUT_MESSAGES,
+ GEN_AI_RESPONSE_ID,
+ GEN_AI_RESPONSE_MODEL,
+ GEN_AI_RESPONSE_STREAMING,
+ GEN_AI_RESPONSE_TEXT,
+ GEN_AI_RESPONSE_TOOL_CALLS,
+ GEN_AI_TOOL_DEFINITIONS,
+ GEN_AI_USAGE_INPUT_TOKENS,
+ GEN_AI_USAGE_OUTPUT_TOKENS,
+ GEN_AI_USAGE_TOTAL_TOKENS,
+ SENTRY_ORIGIN,
+} from '@sentry/conventions/attributes';
+import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner';
+
+describe('Google GenAI integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ const EXPECTED_AVAILABLE_TOOLS_JSON =
+ '[{"name":"controlLight","parametersJsonSchema":{"type":"object","properties":{"brightness":{"type":"number"},"colorTemperature":{"type":"string"}},"required":["brightness","colorTemperature"]}}]';
+
+ createEsmAndCjsTests(__dirname, 'scenario-tools.mjs', 'instrument-with-options.mjs', (createRunner, test) => {
+ test('creates google genai related spans with tool calls', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
+ const spans = container.items.filter(
+ span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai',
+ );
+ expect(spans).toHaveLength(3);
+ const nonStreamingToolsSpan = spans.find(
+ span =>
+ span.attributes[GEN_AI_TOOL_DEFINITIONS]?.value === EXPECTED_AVAILABLE_TOOLS_JSON &&
+ span.attributes[GEN_AI_RESPONSE_STREAMING] === undefined,
+ );
+ expect(nonStreamingToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001');
+ expect(nonStreamingToolsSpan!.status).toBe('ok');
+ expect(nonStreamingToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(nonStreamingToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ expect(nonStreamingToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
+ expect(JSON.parse(nonStreamingToolsSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS].value as string)).toEqual([
+ {
+ id: 'call_light_control_1',
+ name: 'controlLight',
+ args: { brightness: 0.3, colorTemperature: 'warm' },
+ },
+ ]);
+ expect(nonStreamingToolsSpan!.attributes[GEN_AI_OUTPUT_MESSAGES].value).toBe(
+ JSON.stringify([
+ {
+ role: 'assistant',
+ parts: [
+ { type: 'text', content: 'I need to check the light status first.' },
+ {
+ type: 'tool_call',
+ id: 'call_light_control_1',
+ name: 'controlLight',
+ arguments: '{"brightness":0.3,"colorTemperature":"warm"}',
+ },
+ ],
+ },
+ ]),
+ );
+ expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(15);
+ expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(8);
+ expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(23);
+
+ const streamingToolsSpan = spans.find(
+ span =>
+ span.attributes[GEN_AI_TOOL_DEFINITIONS]?.value === EXPECTED_AVAILABLE_TOOLS_JSON &&
+ span.attributes[GEN_AI_RESPONSE_STREAMING]?.value === true,
+ );
+ expect(streamingToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001');
+ expect(streamingToolsSpan!.status).toBe('ok');
+ expect(streamingToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(streamingToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
+ expect(JSON.parse(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS].value as string)).toEqual([
+ {
+ id: 'call_light_stream_1',
+ name: 'controlLight',
+ args: { brightness: 0.5, colorTemperature: 'cool' },
+ },
+ ]);
+ // The text arrives either side of the tool call, so it stays two parts.
+ expect(streamingToolsSpan!.attributes[GEN_AI_OUTPUT_MESSAGES].value).toBe(
+ JSON.stringify([
+ {
+ role: 'assistant',
+ parts: [
+ { type: 'text', content: 'Let me control the lights for you.' },
+ {
+ type: 'tool_call',
+ id: 'call_light_stream_1',
+ name: 'controlLight',
+ arguments: '{"brightness":0.5,"colorTemperature":"cool"}',
+ },
+ { type: 'text', content: ' Done!' },
+ ],
+ },
+ ]),
+ );
+ expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-tools-id');
+ expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-2.0-flash-001');
+ expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(12);
+ expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(10);
+ expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(22);
+
+ const noToolsSpan = spans.find(span => span.attributes[GEN_AI_TOOL_DEFINITIONS] === undefined);
+ expect(noToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001');
+ expect(noToolsSpan!.status).toBe('ok');
+ expect(noToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content');
+ expect(noToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined();
+ expect(noToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined();
+ expect(noToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8);
+ expect(noToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12);
+ expect(noToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20);
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/expected.ts b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/expected.ts
new file mode 100644
index 000000000000..1eaeabac76d6
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/expected.ts
@@ -0,0 +1,69 @@
+export const WEATHER_TOOL_DEFINITION = JSON.stringify([
+ {
+ type: 'function',
+ function: {
+ name: 'get_weather',
+ description: 'Get the current weather in a given location',
+ parameters: {
+ type: 'object',
+ properties: {
+ latitude: { type: 'number', description: 'The latitude of the location' },
+ longitude: { type: 'number', description: 'The longitude of the location' },
+ },
+ required: ['latitude', 'longitude'],
+ },
+ },
+ },
+]);
+
+export const CHAT_TOOL_CALLS = JSON.stringify([
+ {
+ id: 'call_12345xyz',
+ type: 'function',
+ function: {
+ name: 'get_weather',
+ arguments: '{"latitude":48.8566,"longitude":2.3522}',
+ },
+ },
+]);
+
+export const CHAT_STREAM_TOOL_CALLS = JSON.stringify([
+ {
+ index: 0,
+ id: 'call_12345xyz',
+ type: 'function',
+ function: {
+ name: 'get_weather',
+ arguments: '{"latitude":48.8566,"longitude":2.3522}',
+ },
+ },
+]);
+
+export const CHAT_GEMINI_STREAM_TOOL_CALLS = JSON.stringify([
+ {
+ id: 'call_paris',
+ type: 'function',
+ function: {
+ name: 'get_weather',
+ arguments: '{"latitude":48.8566,"longitude":2.3522}',
+ },
+ },
+ {
+ id: 'call_london',
+ type: 'function',
+ function: {
+ name: 'get_weather',
+ arguments: '{"latitude":51.5072,"longitude":-0.1276}',
+ },
+ },
+]);
+
+export const RESPONSES_TOOL_CALLS = JSON.stringify([
+ {
+ type: 'function_call',
+ id: 'fc_12345xyz',
+ call_id: 'call_12345xyz',
+ name: 'get_weather',
+ arguments: '{"latitude":48.8566,"longitude":2.3522}',
+ },
+]);
diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-disabled.test.ts b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-disabled.test.ts
new file mode 100644
index 000000000000..896f7eaf9e5e
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-disabled.test.ts
@@ -0,0 +1,265 @@
+import { afterAll, describe, expect } from 'vitest';
+import {
+ GEN_AI_OPERATION_NAME,
+ GEN_AI_PROVIDER_NAME,
+ GEN_AI_REQUEST_MODEL,
+ GEN_AI_RESPONSE_FINISH_REASONS,
+ GEN_AI_RESPONSE_ID,
+ GEN_AI_RESPONSE_MODEL,
+ GEN_AI_RESPONSE_STREAMING,
+ GEN_AI_RESPONSE_TOOL_CALLS,
+ GEN_AI_TOOL_DEFINITIONS,
+ GEN_AI_USAGE_INPUT_TOKENS,
+ GEN_AI_USAGE_OUTPUT_TOKENS,
+ GEN_AI_USAGE_TOTAL_TOKENS,
+ SENTRY_OP,
+ SENTRY_ORIGIN,
+} from '@sentry/conventions/attributes';
+import { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../../../../../../packages/server-utils/src/ai/core/gen-ai-attributes';
+import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner';
+
+describe('OpenAI Tool Calls integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('creates openai tool calls related spans with genAI recording disabled', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ const segment = container.items.find(span => span.is_segment && span.name === 'main');
+ expect(segment).toBeDefined();
+ const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.openai');
+ expect(spans).toHaveLength(5);
+ const chatToolsSpan = spans.find(
+ span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-tools-123',
+ );
+ expect(chatToolsSpan!.name).toBe('chat gpt-4');
+ expect(chatToolsSpan!.status).toBe('ok');
+ expect(chatToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({
+ type: 'string',
+ value: 'chat',
+ });
+ expect(chatToolsSpan!.attributes[SENTRY_OP]).toEqual({
+ type: 'string',
+ value: 'gen_ai.chat',
+ });
+ expect(chatToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({
+ type: 'string',
+ value: 'auto.ai.openai',
+ });
+ expect(chatToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({ type: 'string', value: 'openai' });
+ expect(chatToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({
+ type: 'string',
+ value: 'gpt-4',
+ });
+ // Tool definitions are gen AI input data, so `genAI.inputs: false` drops them.
+ expect(chatToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined();
+ expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({
+ type: 'string',
+ value: 'gpt-4',
+ });
+ expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({
+ type: 'string',
+ value: 'chatcmpl-tools-123',
+ });
+ expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({
+ type: 'string',
+ value: '["tool_calls"]',
+ });
+ expect(chatToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({
+ type: 'integer',
+ value: 15,
+ });
+ expect(chatToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({
+ type: 'integer',
+ value: 25,
+ });
+ expect(chatToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({
+ type: 'integer',
+ value: 40,
+ });
+
+ const streamingChatToolsSpan = spans.find(
+ span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-stream-tools-123',
+ );
+ expect(streamingChatToolsSpan!.name).toBe('chat gpt-4');
+ expect(streamingChatToolsSpan!.status).toBe('ok');
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({
+ type: 'string',
+ value: 'chat',
+ });
+ expect(streamingChatToolsSpan!.attributes[SENTRY_OP]).toEqual({
+ type: 'string',
+ value: 'gen_ai.chat',
+ });
+ expect(streamingChatToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({
+ type: 'string',
+ value: 'auto.ai.openai',
+ });
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({
+ type: 'string',
+ value: 'openai',
+ });
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({
+ type: 'string',
+ value: 'gpt-4',
+ });
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toEqual({
+ type: 'boolean',
+ value: true,
+ });
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined();
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({
+ type: 'string',
+ value: 'gpt-4',
+ });
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({
+ type: 'string',
+ value: 'chatcmpl-stream-tools-123',
+ });
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({
+ type: 'string',
+ value: '["tool_calls"]',
+ });
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_STREAMING]).toEqual({
+ type: 'boolean',
+ value: true,
+ });
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({
+ type: 'integer',
+ value: 15,
+ });
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({
+ type: 'integer',
+ value: 25,
+ });
+ expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({
+ type: 'integer',
+ value: 40,
+ });
+
+ const geminiStreamSpan = spans.find(
+ span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-stream-gemini-tools-123',
+ );
+ expect(geminiStreamSpan).toBeDefined();
+ expect(geminiStreamSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS]).toBeUndefined();
+
+ const responsesToolsSpan = spans.find(
+ span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'resp_tools_789',
+ );
+ expect(responsesToolsSpan!.name).toBe('chat gpt-4');
+ expect(responsesToolsSpan!.status).toBe('ok');
+ expect(responsesToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({
+ type: 'string',
+ value: 'chat',
+ });
+ expect(responsesToolsSpan!.attributes[SENTRY_OP]).toEqual({
+ type: 'string',
+ value: 'gen_ai.chat',
+ });
+ expect(responsesToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({
+ type: 'string',
+ value: 'auto.ai.openai',
+ });
+ expect(responsesToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({
+ type: 'string',
+ value: 'openai',
+ });
+ expect(responsesToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({
+ type: 'string',
+ value: 'gpt-4',
+ });
+ expect(responsesToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toBeUndefined();
+ expect(responsesToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined();
+ expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({
+ type: 'string',
+ value: 'gpt-4',
+ });
+ expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({
+ type: 'string',
+ value: 'resp_tools_789',
+ });
+ expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({
+ type: 'string',
+ value: '["completed"]',
+ });
+ expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({
+ type: 'integer',
+ value: 8,
+ });
+ expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({
+ type: 'integer',
+ value: 12,
+ });
+ expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({
+ type: 'integer',
+ value: 20,
+ });
+
+ const streamingResponsesToolsSpan = spans.find(
+ span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'resp_stream_tools_789',
+ );
+ expect(streamingResponsesToolsSpan!.name).toBe('chat gpt-4');
+ expect(streamingResponsesToolsSpan!.status).toBe('ok');
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({
+ type: 'string',
+ value: 'chat',
+ });
+ expect(streamingResponsesToolsSpan!.attributes[SENTRY_OP]).toEqual({
+ type: 'string',
+ value: 'gen_ai.chat',
+ });
+ expect(streamingResponsesToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({
+ type: 'string',
+ value: 'auto.ai.openai',
+ });
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({
+ type: 'string',
+ value: 'openai',
+ });
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({
+ type: 'string',
+ value: 'gpt-4',
+ });
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toEqual({
+ type: 'boolean',
+ value: true,
+ });
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined();
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({
+ type: 'string',
+ value: 'gpt-4',
+ });
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({
+ type: 'string',
+ value: 'resp_stream_tools_789',
+ });
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({
+ type: 'string',
+ value: '["in_progress","completed"]',
+ });
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_STREAMING]).toEqual({
+ type: 'boolean',
+ value: true,
+ });
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({
+ type: 'integer',
+ value: 8,
+ });
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({
+ type: 'integer',
+ value: 12,
+ });
+ expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({
+ type: 'integer',
+ value: 20,
+ });
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-enabled.test.ts
similarity index 52%
rename from dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts
rename to dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-enabled.test.ts
index cf5e050605da..45fc61b48419 100644
--- a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts
+++ b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-enabled.test.ts
@@ -1,3 +1,10 @@
+import {
+ WEATHER_TOOL_DEFINITION,
+ CHAT_TOOL_CALLS,
+ CHAT_STREAM_TOOL_CALLS,
+ CHAT_GEMINI_STREAM_TOOL_CALLS,
+ RESPONSES_TOOL_CALLS,
+} from './expected';
import { afterAll, describe, expect } from 'vitest';
import {
GEN_AI_INPUT_MESSAGES,
@@ -25,316 +32,6 @@ describe('OpenAI Tool Calls integration', () => {
cleanupChildProcesses();
});
- const WEATHER_TOOL_DEFINITION = JSON.stringify([
- {
- type: 'function',
- function: {
- name: 'get_weather',
- description: 'Get the current weather in a given location',
- parameters: {
- type: 'object',
- properties: {
- latitude: { type: 'number', description: 'The latitude of the location' },
- longitude: { type: 'number', description: 'The longitude of the location' },
- },
- required: ['latitude', 'longitude'],
- },
- },
- },
- ]);
-
- const CHAT_TOOL_CALLS = JSON.stringify([
- {
- id: 'call_12345xyz',
- type: 'function',
- function: {
- name: 'get_weather',
- arguments: '{"latitude":48.8566,"longitude":2.3522}',
- },
- },
- ]);
-
- const CHAT_STREAM_TOOL_CALLS = JSON.stringify([
- {
- index: 0,
- id: 'call_12345xyz',
- type: 'function',
- function: {
- name: 'get_weather',
- arguments: '{"latitude":48.8566,"longitude":2.3522}',
- },
- },
- ]);
-
- const CHAT_GEMINI_STREAM_TOOL_CALLS = JSON.stringify([
- {
- id: 'call_paris',
- type: 'function',
- function: {
- name: 'get_weather',
- arguments: '{"latitude":48.8566,"longitude":2.3522}',
- },
- },
- {
- id: 'call_london',
- type: 'function',
- function: {
- name: 'get_weather',
- arguments: '{"latitude":51.5072,"longitude":-0.1276}',
- },
- },
- ]);
-
- const RESPONSES_TOOL_CALLS = JSON.stringify([
- {
- type: 'function_call',
- id: 'fc_12345xyz',
- call_id: 'call_12345xyz',
- name: 'get_weather',
- arguments: '{"latitude":48.8566,"longitude":2.3522}',
- },
- ]);
-
- createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => {
- test('creates openai tool calls related spans with genAI recording disabled', async () => {
- await createRunner()
- .expect({
- span: container => {
- const segment = container.items.find(span => span.is_segment && span.name === 'main');
- expect(segment).toBeDefined();
- const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.openai');
- expect(spans).toHaveLength(5);
- const chatToolsSpan = spans.find(
- span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-tools-123',
- );
- expect(chatToolsSpan!.name).toBe('chat gpt-4');
- expect(chatToolsSpan!.status).toBe('ok');
- expect(chatToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({
- type: 'string',
- value: 'chat',
- });
- expect(chatToolsSpan!.attributes[SENTRY_OP]).toEqual({
- type: 'string',
- value: 'gen_ai.chat',
- });
- expect(chatToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({
- type: 'string',
- value: 'auto.ai.openai',
- });
- expect(chatToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({ type: 'string', value: 'openai' });
- expect(chatToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({
- type: 'string',
- value: 'gpt-4',
- });
- // Tool definitions are gen AI input data, so `genAI.inputs: false` drops them.
- expect(chatToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined();
- expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({
- type: 'string',
- value: 'gpt-4',
- });
- expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({
- type: 'string',
- value: 'chatcmpl-tools-123',
- });
- expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({
- type: 'string',
- value: '["tool_calls"]',
- });
- expect(chatToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({
- type: 'integer',
- value: 15,
- });
- expect(chatToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({
- type: 'integer',
- value: 25,
- });
- expect(chatToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({
- type: 'integer',
- value: 40,
- });
-
- const streamingChatToolsSpan = spans.find(
- span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-stream-tools-123',
- );
- expect(streamingChatToolsSpan!.name).toBe('chat gpt-4');
- expect(streamingChatToolsSpan!.status).toBe('ok');
- expect(streamingChatToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({
- type: 'string',
- value: 'chat',
- });
- expect(streamingChatToolsSpan!.attributes[SENTRY_OP]).toEqual({
- type: 'string',
- value: 'gen_ai.chat',
- });
- expect(streamingChatToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({
- type: 'string',
- value: 'auto.ai.openai',
- });
- expect(streamingChatToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({
- type: 'string',
- value: 'openai',
- });
- expect(streamingChatToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({
- type: 'string',
- value: 'gpt-4',
- });
- expect(streamingChatToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toEqual({
- type: 'boolean',
- value: true,
- });
- expect(streamingChatToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined();
- expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({
- type: 'string',
- value: 'gpt-4',
- });
- expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({
- type: 'string',
- value: 'chatcmpl-stream-tools-123',
- });
- expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({
- type: 'string',
- value: '["tool_calls"]',
- });
- expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_STREAMING]).toEqual({
- type: 'boolean',
- value: true,
- });
- expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({
- type: 'integer',
- value: 15,
- });
- expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({
- type: 'integer',
- value: 25,
- });
- expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({
- type: 'integer',
- value: 40,
- });
-
- const geminiStreamSpan = spans.find(
- span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-stream-gemini-tools-123',
- );
- expect(geminiStreamSpan).toBeDefined();
- expect(geminiStreamSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS]).toBeUndefined();
-
- const responsesToolsSpan = spans.find(
- span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'resp_tools_789',
- );
- expect(responsesToolsSpan!.name).toBe('chat gpt-4');
- expect(responsesToolsSpan!.status).toBe('ok');
- expect(responsesToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({
- type: 'string',
- value: 'chat',
- });
- expect(responsesToolsSpan!.attributes[SENTRY_OP]).toEqual({
- type: 'string',
- value: 'gen_ai.chat',
- });
- expect(responsesToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({
- type: 'string',
- value: 'auto.ai.openai',
- });
- expect(responsesToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({
- type: 'string',
- value: 'openai',
- });
- expect(responsesToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({
- type: 'string',
- value: 'gpt-4',
- });
- expect(responsesToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toBeUndefined();
- expect(responsesToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined();
- expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({
- type: 'string',
- value: 'gpt-4',
- });
- expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({
- type: 'string',
- value: 'resp_tools_789',
- });
- expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({
- type: 'string',
- value: '["completed"]',
- });
- expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({
- type: 'integer',
- value: 8,
- });
- expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({
- type: 'integer',
- value: 12,
- });
- expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({
- type: 'integer',
- value: 20,
- });
-
- const streamingResponsesToolsSpan = spans.find(
- span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'resp_stream_tools_789',
- );
- expect(streamingResponsesToolsSpan!.name).toBe('chat gpt-4');
- expect(streamingResponsesToolsSpan!.status).toBe('ok');
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({
- type: 'string',
- value: 'chat',
- });
- expect(streamingResponsesToolsSpan!.attributes[SENTRY_OP]).toEqual({
- type: 'string',
- value: 'gen_ai.chat',
- });
- expect(streamingResponsesToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({
- type: 'string',
- value: 'auto.ai.openai',
- });
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({
- type: 'string',
- value: 'openai',
- });
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({
- type: 'string',
- value: 'gpt-4',
- });
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toEqual({
- type: 'boolean',
- value: true,
- });
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined();
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({
- type: 'string',
- value: 'gpt-4',
- });
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({
- type: 'string',
- value: 'resp_stream_tools_789',
- });
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({
- type: 'string',
- value: '["in_progress","completed"]',
- });
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_STREAMING]).toEqual({
- type: 'boolean',
- value: true,
- });
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({
- type: 'integer',
- value: 8,
- });
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({
- type: 'integer',
- value: 12,
- });
- expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({
- type: 'integer',
- value: 20,
- });
- },
- })
- .start()
- .completed();
- });
- });
-
createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
test('creates openai tool calls related spans with genAI recording enabled', async () => {
await createRunner()
diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/lifecycle.test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-durable/lifecycle.test.ts
new file mode 100644
index 000000000000..c50d0a59733d
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/pi-durable/lifecycle.test.ts
@@ -0,0 +1,221 @@
+import {
+ GEN_AI_CONVERSATION_ID,
+ GEN_AI_INPUT_MESSAGES,
+ GEN_AI_OUTPUT_MESSAGES,
+ GEN_AI_RESPONSE_FINISH_REASONS,
+ GEN_AI_RESPONSE_STREAMING,
+ GEN_AI_TOOL_CALL_ARGUMENTS,
+ SENTRY_OP,
+ SENTRY_STATUS_MESSAGE,
+} from '@sentry/conventions/attributes';
+import { GEN_AI_CHAT } from '@sentry/conventions/op';
+import { afterAll, describe, expect } from 'vitest';
+
+import { supports } from '../../../utils';
+import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner';
+
+// The provider session id that pi-durable stores with each conversation, a UUIDv7.
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+// The pi packages declare `engines.node >= 22.19`.
+describe.runIf(supports({ min: 22 }))('pi-durable integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ createEsmTests(__dirname, 'scenario-reports.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('captures failures pi-durable does not propagate, and tags idle compaction with its conversation', async () => {
+ let runConversationId: unknown;
+ let compactionConversationId: unknown;
+
+ await createRunner()
+ .unordered()
+ .expect({
+ event: event => {
+ const exception = event.exception?.values?.[0];
+ expect(exception?.value).toBe('afterResponse hook failed');
+ expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false });
+ },
+ })
+ .expect({
+ event: event => {
+ const exception = event.exception?.values?.[0];
+ expect(exception?.value).toBe('card declined');
+ expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false });
+ },
+ })
+ .expect({
+ span: container => {
+ const agent = container.items.find(span => span.is_segment)!;
+ expect(agent.name).toBe('invoke_agent');
+ runConversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value;
+ },
+ })
+ .expect({
+ span: container => {
+ // A compaction started while idle belongs to no run, so its request is a trace of its own.
+ expect(container.items).toHaveLength(1);
+ const summary = container.items[0]!;
+ expect(summary.is_segment).toBe(true);
+ expect(summary.attributes[SENTRY_OP]?.value).toBe(GEN_AI_CHAT);
+ compactionConversationId = summary.attributes[GEN_AI_CONVERSATION_ID]?.value;
+ },
+ })
+ .start()
+ .completed();
+
+ expect(runConversationId).toMatch(UUID);
+ expect(compactionConversationId).toBe(runConversationId);
+ });
+ });
+
+ createEsmTests(__dirname, 'scenario-retention.mjs', 'instrument.mjs', (createRunner, test) => {
+ // Bun does not implement `v8.setFlagsFromString`, which the scenario needs to force GC.
+ test.runIf(supports({ runtimes: ['node', 'deno'] }))(
+ 'does not keep the traces of tool calls alive for subagent conversations that never run',
+ async () => {
+ await createRunner()
+ .ignore('span')
+ .expect({ event: { message: 'pi-durable retention', extra: { toolCalls: 3, alive: 0 } } })
+ .start()
+ .completed();
+ },
+ );
+ });
+
+ createEsmTests(__dirname, 'scenario-restart-abort.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('starts no run for an abort handler in a Harness that never saw the run', async () => {
+ await createRunner()
+ .ignore('span')
+ .expect({
+ event: {
+ message: 'pi-durable restart abort',
+ extra: { status: 'unanswered', reason: 'aborted', runsStarted: 0 },
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+
+ createEsmTests(__dirname, 'scenario-interrupted.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('reports a provider that throws as a fault, and nothing for failed, aborted or closed runs', async () => {
+ await createRunner()
+ .ignore('span')
+ .expect({
+ event: event => {
+ const exception = event.exception?.values?.[0];
+ expect(exception?.value).toBe('provider broke');
+ expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false });
+ },
+ })
+ .expect({
+ event: event => {
+ expect(event.message).toBe('pi-durable interrupted done');
+ },
+ })
+ .start()
+ .completed();
+ });
+
+ test('ends every run that does not end with an answer', async () => {
+ await createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ // 1. The model request failed: the run and the request are errors.
+ const chat = container.items.find(span => span.name === 'chat faux-model')!;
+ expect(chat.attributes[GEN_AI_INPUT_MESSAGES]?.value).toContain('Fail please.');
+ expect(chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).toBe('["error"]');
+ expect(chat.status).toBe('error');
+ expect(chat.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('internal_error');
+ const agent = container.items.find(span => span.is_segment)!;
+ expect(agent.name).toBe('invoke_agent');
+ expect(agent.status).toBe('error');
+ expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('model_error');
+ },
+ })
+ .expect({
+ span: container => {
+ // 2. The provider threw in front of pi-ai, so there is no request to report.
+ expect(container.items.find(span => span.name === 'chat faux-model')).toBeUndefined();
+ const agent = container.items.find(span => span.is_segment)!;
+ expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('internal_error');
+ },
+ })
+ .expect({
+ span: container => {
+ // 3. Aborted while the tool ran: cancelled, which streamed spans report as ok.
+ const slow = container.items.find(span => span.name === 'execute_tool slow')!;
+ expect(slow.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"job":"abort"}');
+ expect(slow.status).toBe('ok');
+ expect(container.items.find(span => span.is_segment)!.status).toBe('ok');
+ },
+ })
+ .expect({
+ span: container => {
+ // 4. Aborted while the model request ran.
+ const chat = container.items.find(span => span.name === 'chat faux-model')!;
+ expect(chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).toBe('["aborted"]');
+ expect(container.items).toHaveLength(2);
+ },
+ })
+ .expect({
+ span: container => {
+ // 5. The Harness closed while the tool ran: the run still ends, so the trace has a segment.
+ const slow = container.items.find(span => span.name === 'execute_tool slow')!;
+ expect(slow.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"job":"close"}');
+ const agent = container.items.find(span => span.is_segment)!;
+ expect(agent.name).toBe('invoke_agent');
+ expect(slow.parent_span_id).toBe(agent.span_id);
+ },
+ })
+ .expect({
+ span: container => {
+ // 6. The run failed, and the Harness closed right after `wait()`, before the commit that
+ // ended the run resolved: the run keeps its own status.
+ const chat = container.items.find(span => span.name === 'chat faux-model')!;
+ expect(chat.attributes[GEN_AI_INPUT_MESSAGES]?.value).toContain('Fail, then close.');
+ const agent = container.items.find(span => span.is_segment)!;
+ expect(agent.status).toBe('error');
+ expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('model_error');
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+
+ createEsmTests(__dirname, 'scenario-compaction.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('keeps a compaction that pi-durable starts for a run inside that run', async () => {
+ await createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const spans = container.items;
+ const summary = spans.find(span =>
+ String(span.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).includes('Summary'),
+ )!;
+ const agent = spans.find(span => span.is_segment)!;
+ expect(agent.name).toBe('invoke_agent');
+ expect(summary.parent_span_id).toBe(agent.span_id);
+ // pi-durable completes the summary without streaming; the run's own request streams.
+ expect(summary.attributes[GEN_AI_RESPONSE_STREAMING]).toBeUndefined();
+ const answer = spans.find(span =>
+ String(span.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).includes('Third answer'),
+ )!;
+ expect(answer.parent_span_id).toBe(agent.span_id);
+ expect(answer.attributes[GEN_AI_RESPONSE_STREAMING]?.value).toBe(true);
+ },
+ })
+ .expect({
+ span: container => expect(container.items.find(span => span.is_segment)!.name).toBe('invoke_agent'),
+ })
+ .expect({
+ span: container => expect(container.items.find(span => span.is_segment)!.name).toBe('invoke_agent'),
+ })
+ .start()
+ .completed();
+ });
+ });
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/options.test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-durable/options.test.ts
new file mode 100644
index 000000000000..ab5091b9fbcd
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/pi-durable/options.test.ts
@@ -0,0 +1,139 @@
+import {
+ GEN_AI_INPUT_MESSAGES,
+ GEN_AI_OUTPUT_MESSAGES,
+ GEN_AI_SYSTEM_INSTRUCTIONS,
+ GEN_AI_TOOL_CALL_ARGUMENTS,
+ GEN_AI_TOOL_CALL_RESULT,
+ GEN_AI_TOOL_DEFINITIONS,
+ GEN_AI_TOOL_DESCRIPTION,
+ GEN_AI_USAGE_INPUT_TOKENS,
+} from '@sentry/conventions/attributes';
+
+import { afterAll, describe, expect } from 'vitest';
+
+import { supports } from '../../../utils';
+import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner';
+
+const CONTENT_ATTRIBUTES = [
+ GEN_AI_INPUT_MESSAGES,
+ GEN_AI_OUTPUT_MESSAGES,
+ GEN_AI_SYSTEM_INSTRUCTIONS,
+ GEN_AI_TOOL_DEFINITIONS,
+ GEN_AI_TOOL_CALL_ARGUMENTS,
+ GEN_AI_TOOL_CALL_RESULT,
+];
+
+// The pi packages declare `engines.node >= 22.19`.
+describe.runIf(supports({ min: 22 }))('pi-durable integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ createEsmTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => {
+ for (const [setting, recording] of [
+ ['the client', 'off'],
+ ['`piDurableIntegration`', 'integration-off'],
+ ]) {
+ test(`records no message content when ${setting} turns gen_ai recording off`, async () => {
+ await createRunner()
+ .withEnv({ PI_DURABLE_RECORDING: recording })
+ .unordered()
+ .expect({
+ span: container => {
+ const spans = container.items;
+ expect(spans).toHaveLength(5);
+ for (const span of spans) {
+ for (const attribute of CONTENT_ATTRIBUTES) {
+ expect(span.attributes[attribute]).toBeUndefined();
+ }
+ }
+ const weather = spans.find(span => span.name === 'execute_tool get_weather')!;
+ expect(weather.attributes[GEN_AI_TOOL_DESCRIPTION]?.value).toBe('Get the current weather for a city.');
+ expect(
+ spans.find(span => span.name === 'chat faux-model')!.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value,
+ ).toBeGreaterThan(0);
+ },
+ })
+ .expect({
+ span: container => {
+ expect(container.items).toHaveLength(2);
+ for (const span of container.items) {
+ for (const attribute of CONTENT_ATTRIBUTES) {
+ expect(span.attributes[attribute]).toBeUndefined();
+ }
+ }
+ },
+ })
+ .expect({
+ span: container => {
+ expect(container.items).toHaveLength(1);
+ expect(container.items[0]!.name).toBe('pi-durable-request');
+ },
+ })
+ .expect({
+ event: event => {
+ expect(event.exception?.values?.[0]?.value).toBe('broken tool');
+ },
+ })
+ .start()
+ .completed();
+ });
+ }
+ });
+
+ createEsmTests(
+ __dirname,
+ 'scenario-recording-functions.mjs',
+ 'instrument-with-recording-functions.mjs',
+ (createRunner, test) => {
+ test('decides content recording per call when the options are functions', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ const recorded = container.items
+ .filter(span => /^(chat|execute_tool) /.test(span.name))
+ .sort((a, b) => a.start_timestamp - b.start_timestamp)
+ .map(({ name, attributes }) => [
+ name,
+ GEN_AI_INPUT_MESSAGES in attributes || GEN_AI_TOOL_CALL_ARGUMENTS in attributes,
+ GEN_AI_OUTPUT_MESSAGES in attributes || GEN_AI_TOOL_CALL_RESULT in attributes,
+ ]);
+ expect(recorded).toEqual([
+ ['chat faux-model', true, true],
+ ['execute_tool get_weather', false, false],
+ ['chat faux-model', true, false],
+ ]);
+ },
+ })
+ .start()
+ .completed();
+ });
+ },
+ );
+
+ createEsmTests(
+ __dirname,
+ 'scenario-recording-functions.mjs',
+ 'instrument-with-span-hooks.mjs',
+ (createRunner, test) => {
+ test('runs the span hooks of the model and tool calls', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ const hooks = container.items
+ .filter(span => /^(chat|execute_tool) /.test(span.name))
+ .sort((a, b) => a.start_timestamp - b.start_timestamp)
+ .map(({ attributes }) => [attributes['test.start']?.value, attributes['test.end']?.value]);
+ expect(hooks).toEqual([
+ ['chat', 'toolUse'],
+ ['Berlin', 'It is sunny in Berlin.'],
+ ['chat', 'stop'],
+ ]);
+ },
+ })
+ .start()
+ .completed();
+ });
+ },
+ );
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-durable/test.ts
deleted file mode 100644
index d646b7a59975..000000000000
--- a/dev-packages/node-integration-tests/suites/tracing/pi-durable/test.ts
+++ /dev/null
@@ -1,722 +0,0 @@
-import {
- GEN_AI_CONVERSATION_ID,
- GEN_AI_INPUT_MESSAGES,
- GEN_AI_OPERATION_NAME,
- GEN_AI_OUTPUT_MESSAGES,
- GEN_AI_PROVIDER_NAME,
- GEN_AI_REQUEST_MODEL,
- GEN_AI_RESPONSE_FINISH_REASONS,
- GEN_AI_RESPONSE_STREAMING,
- GEN_AI_SYSTEM_INSTRUCTIONS,
- GEN_AI_TOOL_CALL_ARGUMENTS,
- GEN_AI_TOOL_CALL_RESULT,
- GEN_AI_TOOL_DEFINITIONS,
- GEN_AI_TOOL_DESCRIPTION,
- GEN_AI_TOOL_NAME,
- GEN_AI_USAGE_INPUT_TOKENS,
- GEN_AI_USAGE_OUTPUT_TOKENS,
- SENTRY_OP,
- SENTRY_ORIGIN,
- SENTRY_STATUS_MESSAGE,
-} from '@sentry/conventions/attributes';
-import { GEN_AI_CHAT, GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';
-import { afterAll, describe, expect } from 'vitest';
-import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../../../../packages/server-utils/src/ai/core/gen-ai-attributes';
-import { supports } from '../../../utils';
-import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner';
-
-// The provider session id that pi-durable stores with each conversation, a UUIDv7.
-const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
-
-const CONTENT_ATTRIBUTES = [
- GEN_AI_INPUT_MESSAGES,
- GEN_AI_OUTPUT_MESSAGES,
- GEN_AI_SYSTEM_INSTRUCTIONS,
- GEN_AI_TOOL_DEFINITIONS,
- GEN_AI_TOOL_CALL_ARGUMENTS,
- GEN_AI_TOOL_CALL_RESULT,
-];
-
-// The pi packages declare `engines.node >= 22.19`.
-describe.runIf(supports({ min: 22 }))('pi-durable integration', () => {
- afterAll(() => {
- cleanupChildProcesses();
- });
-
- // The pi packages are ESM-only: their `exports` maps have no `require` condition.
- createEsmTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => {
- test('traces each run as its own invoke_agent trace with chat and execute_tool children', async () => {
- let toolRunTraceId: string | undefined;
- let brokenToolSpanId: string | undefined;
- let errorTraceId: string | undefined;
- let errorSpanId: string | undefined;
- const conversationIds: unknown[] = [];
-
- await createRunner()
- .unordered()
- .expect({
- span: container => {
- const spans = container.items;
- const agent = spans.find(span => span.is_segment)!;
- expect(agent.name).toBe('invoke_agent');
- expect(spans.filter(span => span.name === 'chat faux-model')).toHaveLength(2);
- // One span per run and tool call, and one per request from the pi-ai integration: a tool
- // wrapped twice, or a request reported by a provider SDK too, would add a span.
- expect(spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.pi_durable')).toHaveLength(
- 3,
- );
- expect(spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.pi_ai')).toHaveLength(2);
-
- expect(agent.attributes[SENTRY_OP]?.value).toBe(GEN_AI_INVOKE_AGENT);
- expect(agent.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_durable');
- expect(agent.attributes[GEN_AI_OPERATION_NAME]?.value).toBe('invoke_agent');
- const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value;
- expect(conversationId).toMatch(UUID);
-
- const chats = spans
- .filter(span => span.name === 'chat faux-model')
- .sort((a, b) => a.start_timestamp - b.start_timestamp);
- for (const chat of chats) {
- expect(chat.parent_span_id).toBe(agent.span_id);
- expect(chat.attributes[SENTRY_OP]?.value).toBe(GEN_AI_CHAT);
- expect(chat.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_ai');
- expect(chat.attributes[GEN_AI_PROVIDER_NAME]?.value).toBe('faux');
- expect(chat.attributes[GEN_AI_REQUEST_MODEL]?.value).toBe('faux-model');
- expect(chat.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId);
- expect(chat.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBeGreaterThan(0);
- expect(chat.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBeGreaterThan(0);
- // pi-durable sends the prompt and the tools as positional system messages.
- expect(chat.attributes[GEN_AI_SYSTEM_INSTRUCTIONS]?.value).toBe('You are a weather assistant.');
- expect(
- JSON.parse(String(chat.attributes[GEN_AI_TOOL_DEFINITIONS]?.value)).map(
- (tool: { name: string }) => tool.name,
- ),
- ).toEqual(['get_weather', 'broken']);
- }
-
- // Mapped from pi-ai's shape to the conventions: the tool calls and tool results the
- // second request carries are what Sentry's conversation view renders.
- expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))).toEqual([
- { role: 'user', parts: [{ type: 'text', content: 'What is the weather in Berlin?' }] },
- ]);
- const answerInput = JSON.parse(String(chats[1]!.attributes[GEN_AI_INPUT_MESSAGES]?.value));
- expect(answerInput.map((message: { role: string }) => message.role)).toEqual([
- 'user',
- 'assistant',
- 'tool',
- 'tool',
- ]);
- expect(answerInput[1].parts).toEqual([
- { type: 'tool_call', id: 'call_1', name: 'get_weather', arguments: '{"city":"Berlin"}' },
- { type: 'tool_call', id: 'call_2', name: 'broken', arguments: '{}' },
- ]);
- expect(answerInput[2].parts).toEqual([
- {
- type: 'tool_call_response',
- id: 'call_1',
- name: 'get_weather',
- result: 'It is 21 degrees and sunny in Berlin.',
- },
- ]);
- expect(chats.map(chat => chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).sort()).toEqual([
- '["stop"]',
- '["tool_call"]',
- ]);
- expect(chats.map(chat => chat.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).join()).toContain(
- 'It is 21 degrees and sunny in Berlin.',
- );
-
- const weather = spans.find(span => span.name === 'execute_tool get_weather')!;
- expect(weather.parent_span_id).toBe(agent.span_id);
- expect(weather.status).toBe('ok');
- expect(weather.attributes[SENTRY_OP]?.value).toBe(GEN_AI_EXECUTE_TOOL);
- expect(weather.attributes[GEN_AI_TOOL_NAME]?.value).toBe('get_weather');
- expect(weather.attributes[GEN_AI_TOOL_DESCRIPTION]?.value).toBe('Get the current weather for a city.');
- expect(weather.attributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE]?.value).toBe('call_1');
- expect(weather.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"city":"Berlin"}');
- expect(weather.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('sunny in Berlin');
- expect(weather.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId);
-
- const broken = spans.find(span => span.name === 'execute_tool broken')!;
- expect(broken.parent_span_id).toBe(agent.span_id);
- expect(broken.status).toBe('error');
- // The error result pi-durable gives the model, not the thrown error.
- expect(broken.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('[error] broken tool');
-
- toolRunTraceId = agent.trace_id;
- brokenToolSpanId = broken.span_id;
- conversationIds.push(conversationId);
- },
- })
- .expect({
- span: container => {
- const spans = container.items;
- const agent = spans.find(span => span.is_segment)!;
- expect(agent.name).toBe('invoke_agent');
- expect(spans).toHaveLength(2);
-
- const chat = spans.find(span => span.name === 'chat faux-model')!;
- expect(chat.parent_span_id).toBe(agent.span_id);
- expect(chat.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).toContain('Goodbye.');
-
- conversationIds.push(agent.attributes[GEN_AI_CONVERSATION_ID]?.value);
- },
- })
- .expect({
- span: container => {
- // The request that opened the Harness and submitted both inputs holds no agent work.
- expect(container.items).toHaveLength(1);
- expect(container.items[0]!.name).toBe('pi-durable-request');
- },
- })
- .expect({
- event: event => {
- const exception = event.exception?.values?.[0];
- expect(exception?.value).toBe('broken tool');
- expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false });
-
- errorTraceId = event.contexts?.trace?.trace_id;
- errorSpanId = event.contexts?.trace?.span_id;
- },
- })
- .start()
- .completed();
-
- // Both runs belong to the root conversation, so they share one conversation id.
- expect(conversationIds).toHaveLength(2);
- expect(conversationIds[0]).toBe(conversationIds[1]);
- // The tool error is reported on the failing call's span, in the run's trace.
- expect(errorTraceId).toBe(toolRunTraceId);
- expect(errorSpanId).toBe(brokenToolSpanId);
- });
-
- for (const [setting, recording] of [
- ['the client', 'off'],
- ['`piDurableIntegration`', 'integration-off'],
- ]) {
- test(`records no message content when ${setting} turns gen_ai recording off`, async () => {
- await createRunner()
- .withEnv({ PI_DURABLE_RECORDING: recording })
- .unordered()
- .expect({
- span: container => {
- const spans = container.items;
- expect(spans).toHaveLength(5);
- for (const span of spans) {
- for (const attribute of CONTENT_ATTRIBUTES) {
- expect(span.attributes[attribute]).toBeUndefined();
- }
- }
- const weather = spans.find(span => span.name === 'execute_tool get_weather')!;
- expect(weather.attributes[GEN_AI_TOOL_DESCRIPTION]?.value).toBe('Get the current weather for a city.');
- expect(
- spans.find(span => span.name === 'chat faux-model')!.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value,
- ).toBeGreaterThan(0);
- },
- })
- .expect({
- span: container => {
- expect(container.items).toHaveLength(2);
- for (const span of container.items) {
- for (const attribute of CONTENT_ATTRIBUTES) {
- expect(span.attributes[attribute]).toBeUndefined();
- }
- }
- },
- })
- .expect({
- span: container => {
- expect(container.items).toHaveLength(1);
- expect(container.items[0]!.name).toBe('pi-durable-request');
- },
- })
- .expect({
- event: event => {
- expect(event.exception?.values?.[0]?.value).toBe('broken tool');
- },
- })
- .start()
- .completed();
- });
- }
- });
-
- createEsmTests(__dirname, 'scenario-tools.mjs', 'instrument.mjs', (createRunner, test) => {
- test('reports app tool failures but not failures of the built-in coding tools', async () => {
- const appErrors: unknown[] = [];
-
- // Ordered, with spans ignored: a captured failure of the built-in `bash` tool would be an
- // extra event before the sentinel, which the scenario sends once everything else is sent.
- // The two app failures are processed concurrently, so they may arrive in either order.
- await createRunner()
- .ignore('span')
- .expect({
- event: event => {
- expect(['app read failed', 'Intentional pi-durable tool failure']).toContain(
- event.exception?.values?.[0]?.value,
- );
- appErrors.push(event.exception?.values?.[0]?.value);
- },
- })
- .expect({
- event: event => {
- expect(['app read failed', 'Intentional pi-durable tool failure']).toContain(
- event.exception?.values?.[0]?.value,
- );
- appErrors.push(event.exception?.values?.[0]?.value);
- },
- })
- .expect({
- event: event => {
- expect(event.message).toBe('pi-durable tools done');
- },
- })
- .start()
- .completed();
-
- expect(appErrors.sort()).toEqual(['Intentional pi-durable tool failure', 'app read failed']);
- });
-
- test('records the tool result the model receives', async () => {
- let errorSpanId: string | undefined;
- let failingToolSpanId: string | undefined;
-
- await createRunner()
- .unordered()
- .expect({
- event: event => {
- const exception = event.exception?.values?.[0];
- expect(exception?.value).toBe('Intentional pi-durable tool failure');
- expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false });
- errorSpanId = event.contexts?.trace?.span_id;
- },
- })
- .expect({
- event: event => {
- expect(event.exception?.values?.[0]?.value).toBe('app read failed');
- },
- })
- .expect({
- span: container => {
- const spans = container.items;
-
- const bash = spans.find(span => span.name === 'execute_tool bash')!;
- expect(bash.status).toBe('error');
- expect(bash.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toMatch(/Command exited with code \d+/);
-
- const read = spans.find(span => span.name === 'execute_tool read')!;
- expect(read.status).toBe('error');
- expect(read.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('app read failed');
-
- // The streamed output becomes the result, since the tool returns no content.
- const streamer = spans.find(span => span.name === 'execute_tool streamer')!;
- expect(streamer.status).toBe('ok');
- expect(streamer.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('line 1\nline 2\n');
-
- const secret = spans.find(span => span.name === 'execute_tool secret')!;
- expect(secret.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('redacted by afterTool');
-
- const failNow = spans.find(span => span.name === 'execute_tool fail_now')!;
- expect(failNow.status).toBe('error');
- failingToolSpanId = failNow.span_id;
- },
- })
- .start()
- .completed();
-
- expect(errorSpanId).toBe(failingToolSpanId);
- });
- });
-
- createEsmTests(__dirname, 'scenario-reports.mjs', 'instrument.mjs', (createRunner, test) => {
- test('captures failures pi-durable does not propagate, and tags idle compaction with its conversation', async () => {
- let runConversationId: unknown;
- let compactionConversationId: unknown;
-
- await createRunner()
- .unordered()
- .expect({
- event: event => {
- const exception = event.exception?.values?.[0];
- expect(exception?.value).toBe('afterResponse hook failed');
- expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false });
- },
- })
- .expect({
- event: event => {
- const exception = event.exception?.values?.[0];
- expect(exception?.value).toBe('card declined');
- expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false });
- },
- })
- .expect({
- span: container => {
- const agent = container.items.find(span => span.is_segment)!;
- expect(agent.name).toBe('invoke_agent');
- runConversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value;
- },
- })
- .expect({
- span: container => {
- // A compaction started while idle belongs to no run, so its request is a trace of its own.
- expect(container.items).toHaveLength(1);
- const summary = container.items[0]!;
- expect(summary.is_segment).toBe(true);
- expect(summary.attributes[SENTRY_OP]?.value).toBe(GEN_AI_CHAT);
- compactionConversationId = summary.attributes[GEN_AI_CONVERSATION_ID]?.value;
- },
- })
- .start()
- .completed();
-
- expect(runConversationId).toMatch(UUID);
- expect(compactionConversationId).toBe(runConversationId);
- });
- });
-
- createEsmTests(__dirname, 'scenario-subagent.mjs', 'instrument.mjs', (createRunner, test) => {
- test('nests subagent runs under the tool call that started them', async () => {
- await createRunner()
- .unordered()
- .expect({
- span: container => {
- const spans = container.items;
- const parent = spans.find(span => span.is_segment)!;
- const delegate = spans.find(span => span.name === 'execute_tool delegate')!;
- expect(parent.name).toBe('invoke_agent');
- expect(delegate.parent_span_id).toBe(parent.span_id);
-
- // The subagent's run is a child of the delegating call, in the same trace, on its own
- // conversation.
- const child = spans.find(span => span.name === 'invoke_agent' && !span.is_segment)!;
- expect(child.parent_span_id).toBe(delegate.span_id);
- const parentConversation = String(parent.attributes[GEN_AI_CONVERSATION_ID]?.value);
- const childConversation = String(child.attributes[GEN_AI_CONVERSATION_ID]?.value);
- expect(parentConversation).toMatch(UUID);
- expect(childConversation).toMatch(UUID);
- expect(childConversation).not.toBe(parentConversation);
-
- const childChat = spans.find(span => span.parent_span_id === child.span_id)!;
- expect(childChat.name).toBe('chat faux-model');
- expect(childChat.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(childConversation);
- expect(delegate.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('Answer: Weather in Vienna?');
- },
- })
- .expect({
- span: container => {
- const spans = container.items;
- const parent = spans.find(span => span.is_segment)!;
- const fork = spans.find(span => span.name === 'execute_tool fork_delegate')!;
- const child = spans.find(span => span.name === 'invoke_agent' && !span.is_segment)!;
- expect(fork.parent_span_id).toBe(parent.span_id);
- expect(child.parent_span_id).toBe(fork.span_id);
- expect(fork.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('Answer: Forked task.');
- },
- })
- .expect({
- span: container => {
- const spans = container.items;
- const batch = spans.find(span => span.name === 'execute_tool batch')!;
- const inner = spans.find(span => span.name === 'execute_tool inner')!;
- expect(batch.parent_span_id).toBe(spans.find(span => span.is_segment)!.span_id);
- // A tool that runs another tool itself: the inner call ends with its own result.
- expect(inner.parent_span_id).toBe(batch.span_id);
- expect(inner.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('INNER RESULT');
- expect(batch.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('OUTER RESULT');
- },
- })
- .expect({
- span: container => {
- const spans = container.items;
- const relay = spans.find(span => span.name === 'execute_tool relay')!;
- const inner = spans.find(span => span.name === 'execute_tool inner')!;
- expect(relay.parent_span_id).toBe(spans.find(span => span.is_segment)!.span_id);
- // A nested call is a task of its own: its span is a child of the calling tool's span.
- expect(inner.parent_span_id).toBe(relay.span_id);
- expect(inner.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('INNER RESULT');
- expect(relay.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('RELAY RESULT');
- },
- })
- .start()
- .completed();
- });
- });
-
- createEsmTests(__dirname, 'scenario-retention.mjs', 'instrument.mjs', (createRunner, test) => {
- // Bun does not implement `v8.setFlagsFromString`, which the scenario needs to force GC.
- test.runIf(supports({ runtimes: ['node', 'deno'] }))(
- 'does not keep the traces of tool calls alive for subagent conversations that never run',
- async () => {
- await createRunner()
- .ignore('span')
- .expect({ event: { message: 'pi-durable retention', extra: { toolCalls: 3, alive: 0 } } })
- .start()
- .completed();
- },
- );
- });
-
- createEsmTests(__dirname, 'scenario-restart-abort.mjs', 'instrument.mjs', (createRunner, test) => {
- test('starts no run for an abort handler in a Harness that never saw the run', async () => {
- await createRunner()
- .ignore('span')
- .expect({
- event: {
- message: 'pi-durable restart abort',
- extra: { status: 'unanswered', reason: 'aborted', runsStarted: 0 },
- },
- })
- .start()
- .completed();
- });
- });
-
- createEsmTests(__dirname, 'scenario-interrupted.mjs', 'instrument.mjs', (createRunner, test) => {
- test('reports a provider that throws as a fault, and nothing for failed, aborted or closed runs', async () => {
- await createRunner()
- .ignore('span')
- .expect({
- event: event => {
- const exception = event.exception?.values?.[0];
- expect(exception?.value).toBe('provider broke');
- expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false });
- },
- })
- .expect({
- event: event => {
- expect(event.message).toBe('pi-durable interrupted done');
- },
- })
- .start()
- .completed();
- });
-
- test('ends every run that does not end with an answer', async () => {
- await createRunner()
- .unordered()
- .expect({
- span: container => {
- // 1. The model request failed: the run and the request are errors.
- const chat = container.items.find(span => span.name === 'chat faux-model')!;
- expect(chat.attributes[GEN_AI_INPUT_MESSAGES]?.value).toContain('Fail please.');
- expect(chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).toBe('["error"]');
- expect(chat.status).toBe('error');
- expect(chat.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('internal_error');
- const agent = container.items.find(span => span.is_segment)!;
- expect(agent.name).toBe('invoke_agent');
- expect(agent.status).toBe('error');
- expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('model_error');
- },
- })
- .expect({
- span: container => {
- // 2. The provider threw in front of pi-ai, so there is no request to report.
- expect(container.items.find(span => span.name === 'chat faux-model')).toBeUndefined();
- const agent = container.items.find(span => span.is_segment)!;
- expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('internal_error');
- },
- })
- .expect({
- span: container => {
- // 3. Aborted while the tool ran: cancelled, which streamed spans report as ok.
- const slow = container.items.find(span => span.name === 'execute_tool slow')!;
- expect(slow.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"job":"abort"}');
- expect(slow.status).toBe('ok');
- expect(container.items.find(span => span.is_segment)!.status).toBe('ok');
- },
- })
- .expect({
- span: container => {
- // 4. Aborted while the model request ran.
- const chat = container.items.find(span => span.name === 'chat faux-model')!;
- expect(chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).toBe('["aborted"]');
- expect(container.items).toHaveLength(2);
- },
- })
- .expect({
- span: container => {
- // 5. The Harness closed while the tool ran: the run still ends, so the trace has a segment.
- const slow = container.items.find(span => span.name === 'execute_tool slow')!;
- expect(slow.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"job":"close"}');
- const agent = container.items.find(span => span.is_segment)!;
- expect(agent.name).toBe('invoke_agent');
- expect(slow.parent_span_id).toBe(agent.span_id);
- },
- })
- .expect({
- span: container => {
- // 6. The run failed, and the Harness closed right after `wait()`, before the commit that
- // ended the run resolved: the run keeps its own status.
- const chat = container.items.find(span => span.name === 'chat faux-model')!;
- expect(chat.attributes[GEN_AI_INPUT_MESSAGES]?.value).toContain('Fail, then close.');
- const agent = container.items.find(span => span.is_segment)!;
- expect(agent.status).toBe('error');
- expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('model_error');
- },
- })
- .start()
- .completed();
- });
- });
-
- createEsmTests(__dirname, 'scenario-concurrent.mjs', 'instrument.mjs', (createRunner, test) => {
- test('keeps concurrent runs apart and out of the scopes of the requests that submitted them', async () => {
- const runTraceIds = new Set();
- const errorTraceIds = new Set();
-
- await createRunner()
- .unordered()
- .expect({
- span: container => {
- const spans = container.items;
- const agent = spans.find(span => span.is_segment)!;
- expect(agent.name).toBe('invoke_agent');
- const chats = spans.filter(span => span.name === 'chat faux-model');
- expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))[0].parts[0].content).toBe(
- 'request A',
- );
- // The run's own conversation id, not the one the request set on its scope.
- const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value;
- expect(conversationId).toMatch(UUID);
- for (const span of spans) {
- expect(span.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId);
- expect(span.attributes['request']).toBeUndefined();
- }
- expect(
- spans.find(span => span.name === 'execute_tool work')!.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value,
- ).toBe('{"tag":"request A"}');
- runTraceIds.add(agent.trace_id);
- },
- })
- .expect({
- span: container => {
- const spans = container.items;
- const agent = spans.find(span => span.is_segment)!;
- expect(agent.name).toBe('invoke_agent');
- const chats = spans.filter(span => span.name === 'chat faux-model');
- expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))[0].parts[0].content).toBe(
- 'request B',
- );
- const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value;
- expect(conversationId).toMatch(UUID);
- for (const span of spans) {
- expect(span.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId);
- expect(span.attributes['request']).toBeUndefined();
- }
- expect(
- spans.find(span => span.name === 'execute_tool work')!.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value,
- ).toBe('{"tag":"request B"}');
- runTraceIds.add(agent.trace_id);
- },
- })
- .expect({
- event: event => {
- expect(event.exception?.values?.[0]?.value).toBe('work failed for request A');
- expect(event.tags?.request).toBeUndefined();
- errorTraceIds.add(String(event.contexts?.trace?.trace_id));
- },
- })
- .expect({
- event: event => {
- expect(event.exception?.values?.[0]?.value).toBe('work failed for request B');
- expect(event.tags?.request).toBeUndefined();
- errorTraceIds.add(String(event.contexts?.trace?.trace_id));
- },
- })
- .start()
- .completed();
-
- // Each tool error belongs to its run's trace.
- expect(errorTraceIds).toEqual(runTraceIds);
- });
- });
-
- createEsmTests(__dirname, 'scenario-compaction.mjs', 'instrument.mjs', (createRunner, test) => {
- test('keeps a compaction that pi-durable starts for a run inside that run', async () => {
- await createRunner()
- .unordered()
- .expect({
- span: container => {
- const spans = container.items;
- const summary = spans.find(span =>
- String(span.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).includes('Summary'),
- )!;
- const agent = spans.find(span => span.is_segment)!;
- expect(agent.name).toBe('invoke_agent');
- expect(summary.parent_span_id).toBe(agent.span_id);
- // pi-durable completes the summary without streaming; the run's own request streams.
- expect(summary.attributes[GEN_AI_RESPONSE_STREAMING]).toBeUndefined();
- const answer = spans.find(span =>
- String(span.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).includes('Third answer'),
- )!;
- expect(answer.parent_span_id).toBe(agent.span_id);
- expect(answer.attributes[GEN_AI_RESPONSE_STREAMING]?.value).toBe(true);
- },
- })
- .expect({
- span: container => expect(container.items.find(span => span.is_segment)!.name).toBe('invoke_agent'),
- })
- .expect({
- span: container => expect(container.items.find(span => span.is_segment)!.name).toBe('invoke_agent'),
- })
- .start()
- .completed();
- });
- });
-
- createEsmTests(
- __dirname,
- 'scenario-recording-functions.mjs',
- 'instrument-with-recording-functions.mjs',
- (createRunner, test) => {
- test('decides content recording per call when the options are functions', async () => {
- await createRunner()
- .expect({
- span: container => {
- const recorded = container.items
- .filter(span => /^(chat|execute_tool) /.test(span.name))
- .sort((a, b) => a.start_timestamp - b.start_timestamp)
- .map(({ name, attributes }) => [
- name,
- GEN_AI_INPUT_MESSAGES in attributes || GEN_AI_TOOL_CALL_ARGUMENTS in attributes,
- GEN_AI_OUTPUT_MESSAGES in attributes || GEN_AI_TOOL_CALL_RESULT in attributes,
- ]);
- expect(recorded).toEqual([
- ['chat faux-model', true, true],
- ['execute_tool get_weather', false, false],
- ['chat faux-model', true, false],
- ]);
- },
- })
- .start()
- .completed();
- });
- },
- );
-
- createEsmTests(
- __dirname,
- 'scenario-recording-functions.mjs',
- 'instrument-with-span-hooks.mjs',
- (createRunner, test) => {
- test('runs the span hooks of the model and tool calls', async () => {
- await createRunner()
- .expect({
- span: container => {
- const hooks = container.items
- .filter(span => /^(chat|execute_tool) /.test(span.name))
- .sort((a, b) => a.start_timestamp - b.start_timestamp)
- .map(({ attributes }) => [attributes['test.start']?.value, attributes['test.end']?.value]);
- expect(hooks).toEqual([
- ['chat', 'toolUse'],
- ['Berlin', 'It is sunny in Berlin.'],
- ['chat', 'stop'],
- ]);
- },
- })
- .start()
- .completed();
- });
- },
- );
-});
diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/tools.test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-durable/tools.test.ts
new file mode 100644
index 000000000000..fb4db7dcd553
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/pi-durable/tools.test.ts
@@ -0,0 +1,100 @@
+import { GEN_AI_TOOL_CALL_RESULT } from '@sentry/conventions/attributes';
+
+import { afterAll, describe, expect } from 'vitest';
+
+import { supports } from '../../../utils';
+import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner';
+
+// The pi packages declare `engines.node >= 22.19`.
+describe.runIf(supports({ min: 22 }))('pi-durable integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ createEsmTests(__dirname, 'scenario-tools.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('reports app tool failures but not failures of the built-in coding tools', async () => {
+ const appErrors: unknown[] = [];
+
+ // Ordered, with spans ignored: a captured failure of the built-in `bash` tool would be an
+ // extra event before the sentinel, which the scenario sends once everything else is sent.
+ // The two app failures are processed concurrently, so they may arrive in either order.
+ await createRunner()
+ .ignore('span')
+ .expect({
+ event: event => {
+ expect(['app read failed', 'Intentional pi-durable tool failure']).toContain(
+ event.exception?.values?.[0]?.value,
+ );
+ appErrors.push(event.exception?.values?.[0]?.value);
+ },
+ })
+ .expect({
+ event: event => {
+ expect(['app read failed', 'Intentional pi-durable tool failure']).toContain(
+ event.exception?.values?.[0]?.value,
+ );
+ appErrors.push(event.exception?.values?.[0]?.value);
+ },
+ })
+ .expect({
+ event: event => {
+ expect(event.message).toBe('pi-durable tools done');
+ },
+ })
+ .start()
+ .completed();
+
+ expect(appErrors.sort()).toEqual(['Intentional pi-durable tool failure', 'app read failed']);
+ });
+
+ test('records the tool result the model receives', async () => {
+ let errorSpanId: string | undefined;
+ let failingToolSpanId: string | undefined;
+
+ await createRunner()
+ .unordered()
+ .expect({
+ event: event => {
+ const exception = event.exception?.values?.[0];
+ expect(exception?.value).toBe('Intentional pi-durable tool failure');
+ expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false });
+ errorSpanId = event.contexts?.trace?.span_id;
+ },
+ })
+ .expect({
+ event: event => {
+ expect(event.exception?.values?.[0]?.value).toBe('app read failed');
+ },
+ })
+ .expect({
+ span: container => {
+ const spans = container.items;
+
+ const bash = spans.find(span => span.name === 'execute_tool bash')!;
+ expect(bash.status).toBe('error');
+ expect(bash.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toMatch(/Command exited with code \d+/);
+
+ const read = spans.find(span => span.name === 'execute_tool read')!;
+ expect(read.status).toBe('error');
+ expect(read.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('app read failed');
+
+ // The streamed output becomes the result, since the tool returns no content.
+ const streamer = spans.find(span => span.name === 'execute_tool streamer')!;
+ expect(streamer.status).toBe('ok');
+ expect(streamer.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('line 1\nline 2\n');
+
+ const secret = spans.find(span => span.name === 'execute_tool secret')!;
+ expect(secret.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('redacted by afterTool');
+
+ const failNow = spans.find(span => span.name === 'execute_tool fail_now')!;
+ expect(failNow.status).toBe('error');
+ failingToolSpanId = failNow.span_id;
+ },
+ })
+ .start()
+ .completed();
+
+ expect(errorSpanId).toBe(failingToolSpanId);
+ });
+ });
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/tracing.test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-durable/tracing.test.ts
new file mode 100644
index 000000000000..d431e01fa6cb
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/pi-durable/tracing.test.ts
@@ -0,0 +1,321 @@
+import {
+ GEN_AI_CONVERSATION_ID,
+ GEN_AI_INPUT_MESSAGES,
+ GEN_AI_OPERATION_NAME,
+ GEN_AI_OUTPUT_MESSAGES,
+ GEN_AI_PROVIDER_NAME,
+ GEN_AI_REQUEST_MODEL,
+ GEN_AI_RESPONSE_FINISH_REASONS,
+ GEN_AI_SYSTEM_INSTRUCTIONS,
+ GEN_AI_TOOL_CALL_ARGUMENTS,
+ GEN_AI_TOOL_CALL_RESULT,
+ GEN_AI_TOOL_DEFINITIONS,
+ GEN_AI_TOOL_DESCRIPTION,
+ GEN_AI_TOOL_NAME,
+ GEN_AI_USAGE_INPUT_TOKENS,
+ GEN_AI_USAGE_OUTPUT_TOKENS,
+ SENTRY_OP,
+ SENTRY_ORIGIN,
+} from '@sentry/conventions/attributes';
+import { GEN_AI_CHAT, GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';
+import { afterAll, describe, expect } from 'vitest';
+import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../../../../packages/server-utils/src/ai/core/gen-ai-attributes';
+import { supports } from '../../../utils';
+import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner';
+
+// The provider session id that pi-durable stores with each conversation, a UUIDv7.
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+// The pi packages declare `engines.node >= 22.19`.
+describe.runIf(supports({ min: 22 }))('pi-durable integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ createEsmTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('traces each run as its own invoke_agent trace with chat and execute_tool children', async () => {
+ let toolRunTraceId: string | undefined;
+ let brokenToolSpanId: string | undefined;
+ let errorTraceId: string | undefined;
+ let errorSpanId: string | undefined;
+ const conversationIds: unknown[] = [];
+
+ await createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const spans = container.items;
+ const agent = spans.find(span => span.is_segment)!;
+ expect(agent.name).toBe('invoke_agent');
+ expect(spans.filter(span => span.name === 'chat faux-model')).toHaveLength(2);
+ // One span per run and tool call, and one per request from the pi-ai integration: a tool
+ // wrapped twice, or a request reported by a provider SDK too, would add a span.
+ expect(spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.pi_durable')).toHaveLength(
+ 3,
+ );
+ expect(spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.pi_ai')).toHaveLength(2);
+
+ expect(agent.attributes[SENTRY_OP]?.value).toBe(GEN_AI_INVOKE_AGENT);
+ expect(agent.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_durable');
+ expect(agent.attributes[GEN_AI_OPERATION_NAME]?.value).toBe('invoke_agent');
+ const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value;
+ expect(conversationId).toMatch(UUID);
+
+ const chats = spans
+ .filter(span => span.name === 'chat faux-model')
+ .sort((a, b) => a.start_timestamp - b.start_timestamp);
+ for (const chat of chats) {
+ expect(chat.parent_span_id).toBe(agent.span_id);
+ expect(chat.attributes[SENTRY_OP]?.value).toBe(GEN_AI_CHAT);
+ expect(chat.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_ai');
+ expect(chat.attributes[GEN_AI_PROVIDER_NAME]?.value).toBe('faux');
+ expect(chat.attributes[GEN_AI_REQUEST_MODEL]?.value).toBe('faux-model');
+ expect(chat.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId);
+ expect(chat.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBeGreaterThan(0);
+ expect(chat.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBeGreaterThan(0);
+ // pi-durable sends the prompt and the tools as positional system messages.
+ expect(chat.attributes[GEN_AI_SYSTEM_INSTRUCTIONS]?.value).toBe('You are a weather assistant.');
+ expect(
+ JSON.parse(String(chat.attributes[GEN_AI_TOOL_DEFINITIONS]?.value)).map(
+ (tool: { name: string }) => tool.name,
+ ),
+ ).toEqual(['get_weather', 'broken']);
+ }
+
+ // Mapped from pi-ai's shape to the conventions: the tool calls and tool results the
+ // second request carries are what Sentry's conversation view renders.
+ expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))).toEqual([
+ { role: 'user', parts: [{ type: 'text', content: 'What is the weather in Berlin?' }] },
+ ]);
+ const answerInput = JSON.parse(String(chats[1]!.attributes[GEN_AI_INPUT_MESSAGES]?.value));
+ expect(answerInput.map((message: { role: string }) => message.role)).toEqual([
+ 'user',
+ 'assistant',
+ 'tool',
+ 'tool',
+ ]);
+ expect(answerInput[1].parts).toEqual([
+ { type: 'tool_call', id: 'call_1', name: 'get_weather', arguments: '{"city":"Berlin"}' },
+ { type: 'tool_call', id: 'call_2', name: 'broken', arguments: '{}' },
+ ]);
+ expect(answerInput[2].parts).toEqual([
+ {
+ type: 'tool_call_response',
+ id: 'call_1',
+ name: 'get_weather',
+ result: 'It is 21 degrees and sunny in Berlin.',
+ },
+ ]);
+ expect(chats.map(chat => chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).sort()).toEqual([
+ '["stop"]',
+ '["tool_call"]',
+ ]);
+ expect(chats.map(chat => chat.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).join()).toContain(
+ 'It is 21 degrees and sunny in Berlin.',
+ );
+
+ const weather = spans.find(span => span.name === 'execute_tool get_weather')!;
+ expect(weather.parent_span_id).toBe(agent.span_id);
+ expect(weather.status).toBe('ok');
+ expect(weather.attributes[SENTRY_OP]?.value).toBe(GEN_AI_EXECUTE_TOOL);
+ expect(weather.attributes[GEN_AI_TOOL_NAME]?.value).toBe('get_weather');
+ expect(weather.attributes[GEN_AI_TOOL_DESCRIPTION]?.value).toBe('Get the current weather for a city.');
+ expect(weather.attributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE]?.value).toBe('call_1');
+ expect(weather.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"city":"Berlin"}');
+ expect(weather.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('sunny in Berlin');
+ expect(weather.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId);
+
+ const broken = spans.find(span => span.name === 'execute_tool broken')!;
+ expect(broken.parent_span_id).toBe(agent.span_id);
+ expect(broken.status).toBe('error');
+ // The error result pi-durable gives the model, not the thrown error.
+ expect(broken.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('[error] broken tool');
+
+ toolRunTraceId = agent.trace_id;
+ brokenToolSpanId = broken.span_id;
+ conversationIds.push(conversationId);
+ },
+ })
+ .expect({
+ span: container => {
+ const spans = container.items;
+ const agent = spans.find(span => span.is_segment)!;
+ expect(agent.name).toBe('invoke_agent');
+ expect(spans).toHaveLength(2);
+
+ const chat = spans.find(span => span.name === 'chat faux-model')!;
+ expect(chat.parent_span_id).toBe(agent.span_id);
+ expect(chat.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).toContain('Goodbye.');
+
+ conversationIds.push(agent.attributes[GEN_AI_CONVERSATION_ID]?.value);
+ },
+ })
+ .expect({
+ span: container => {
+ // The request that opened the Harness and submitted both inputs holds no agent work.
+ expect(container.items).toHaveLength(1);
+ expect(container.items[0]!.name).toBe('pi-durable-request');
+ },
+ })
+ .expect({
+ event: event => {
+ const exception = event.exception?.values?.[0];
+ expect(exception?.value).toBe('broken tool');
+ expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false });
+
+ errorTraceId = event.contexts?.trace?.trace_id;
+ errorSpanId = event.contexts?.trace?.span_id;
+ },
+ })
+ .start()
+ .completed();
+
+ // Both runs belong to the root conversation, so they share one conversation id.
+ expect(conversationIds).toHaveLength(2);
+ expect(conversationIds[0]).toBe(conversationIds[1]);
+ // The tool error is reported on the failing call's span, in the run's trace.
+ expect(errorTraceId).toBe(toolRunTraceId);
+ expect(errorSpanId).toBe(brokenToolSpanId);
+ });
+ });
+
+ createEsmTests(__dirname, 'scenario-subagent.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('nests subagent runs under the tool call that started them', async () => {
+ await createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const spans = container.items;
+ const parent = spans.find(span => span.is_segment)!;
+ const delegate = spans.find(span => span.name === 'execute_tool delegate')!;
+ expect(parent.name).toBe('invoke_agent');
+ expect(delegate.parent_span_id).toBe(parent.span_id);
+
+ // The subagent's run is a child of the delegating call, in the same trace, on its own
+ // conversation.
+ const child = spans.find(span => span.name === 'invoke_agent' && !span.is_segment)!;
+ expect(child.parent_span_id).toBe(delegate.span_id);
+ const parentConversation = String(parent.attributes[GEN_AI_CONVERSATION_ID]?.value);
+ const childConversation = String(child.attributes[GEN_AI_CONVERSATION_ID]?.value);
+ expect(parentConversation).toMatch(UUID);
+ expect(childConversation).toMatch(UUID);
+ expect(childConversation).not.toBe(parentConversation);
+
+ const childChat = spans.find(span => span.parent_span_id === child.span_id)!;
+ expect(childChat.name).toBe('chat faux-model');
+ expect(childChat.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(childConversation);
+ expect(delegate.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('Answer: Weather in Vienna?');
+ },
+ })
+ .expect({
+ span: container => {
+ const spans = container.items;
+ const parent = spans.find(span => span.is_segment)!;
+ const fork = spans.find(span => span.name === 'execute_tool fork_delegate')!;
+ const child = spans.find(span => span.name === 'invoke_agent' && !span.is_segment)!;
+ expect(fork.parent_span_id).toBe(parent.span_id);
+ expect(child.parent_span_id).toBe(fork.span_id);
+ expect(fork.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('Answer: Forked task.');
+ },
+ })
+ .expect({
+ span: container => {
+ const spans = container.items;
+ const batch = spans.find(span => span.name === 'execute_tool batch')!;
+ const inner = spans.find(span => span.name === 'execute_tool inner')!;
+ expect(batch.parent_span_id).toBe(spans.find(span => span.is_segment)!.span_id);
+ // A tool that runs another tool itself: the inner call ends with its own result.
+ expect(inner.parent_span_id).toBe(batch.span_id);
+ expect(inner.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('INNER RESULT');
+ expect(batch.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('OUTER RESULT');
+ },
+ })
+ .expect({
+ span: container => {
+ const spans = container.items;
+ const relay = spans.find(span => span.name === 'execute_tool relay')!;
+ const inner = spans.find(span => span.name === 'execute_tool inner')!;
+ expect(relay.parent_span_id).toBe(spans.find(span => span.is_segment)!.span_id);
+ // A nested call is a task of its own: its span is a child of the calling tool's span.
+ expect(inner.parent_span_id).toBe(relay.span_id);
+ expect(inner.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('INNER RESULT');
+ expect(relay.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('RELAY RESULT');
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+
+ createEsmTests(__dirname, 'scenario-concurrent.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('keeps concurrent runs apart and out of the scopes of the requests that submitted them', async () => {
+ const runTraceIds = new Set();
+ const errorTraceIds = new Set();
+
+ await createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const spans = container.items;
+ const agent = spans.find(span => span.is_segment)!;
+ expect(agent.name).toBe('invoke_agent');
+ const chats = spans.filter(span => span.name === 'chat faux-model');
+ expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))[0].parts[0].content).toBe(
+ 'request A',
+ );
+ // The run's own conversation id, not the one the request set on its scope.
+ const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value;
+ expect(conversationId).toMatch(UUID);
+ for (const span of spans) {
+ expect(span.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId);
+ expect(span.attributes['request']).toBeUndefined();
+ }
+ expect(
+ spans.find(span => span.name === 'execute_tool work')!.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value,
+ ).toBe('{"tag":"request A"}');
+ runTraceIds.add(agent.trace_id);
+ },
+ })
+ .expect({
+ span: container => {
+ const spans = container.items;
+ const agent = spans.find(span => span.is_segment)!;
+ expect(agent.name).toBe('invoke_agent');
+ const chats = spans.filter(span => span.name === 'chat faux-model');
+ expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))[0].parts[0].content).toBe(
+ 'request B',
+ );
+ const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value;
+ expect(conversationId).toMatch(UUID);
+ for (const span of spans) {
+ expect(span.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId);
+ expect(span.attributes['request']).toBeUndefined();
+ }
+ expect(
+ spans.find(span => span.name === 'execute_tool work')!.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value,
+ ).toBe('{"tag":"request B"}');
+ runTraceIds.add(agent.trace_id);
+ },
+ })
+ .expect({
+ event: event => {
+ expect(event.exception?.values?.[0]?.value).toBe('work failed for request A');
+ expect(event.tags?.request).toBeUndefined();
+ errorTraceIds.add(String(event.contexts?.trace?.trace_id));
+ },
+ })
+ .expect({
+ event: event => {
+ expect(event.exception?.values?.[0]?.value).toBe('work failed for request B');
+ expect(event.tags?.request).toBeUndefined();
+ errorTraceIds.add(String(event.contexts?.trace?.trace_id));
+ },
+ })
+ .start()
+ .completed();
+
+ // Each tool error belongs to its run's trace.
+ expect(errorTraceIds).toEqual(runTraceIds);
+ });
+ });
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/scenario-extract.mjs b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/scenario-extract.mjs
new file mode 100644
index 000000000000..726f9e18f2c1
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/scenario-extract.mjs
@@ -0,0 +1,29 @@
+import * as Sentry from '@sentry/node';
+import { experimental_extract } from 'ai';
+import { Experimental_ExtractionMockModelV4 } from 'ai/test';
+
+async function run() {
+ await Sentry.startSpan({ op: 'function', name: 'main' }, async () => {
+ await experimental_extract({
+ model: new Experimental_ExtractionMockModelV4({
+ provider: 'gateway',
+ modelId: 'cloudflare/clairic',
+ doExtract: async () => ({
+ answers: {
+ invoiceNumber: { type: 'text', value: 'INV-2291', confidence: 0.98 },
+ total: { type: 'number', value: 1080, confidence: 0.95 },
+ },
+ usage: { inputTokens: 50, outputTokens: 4 },
+ warnings: [],
+ }),
+ }),
+ state: 'Invoice INV-2291 from Northwind Supply. Total due: $1,080.',
+ fields: {
+ invoiceNumber: { type: 'text', instructions: 'The invoice number' },
+ total: { type: 'number', instructions: 'The total amount due' },
+ },
+ });
+ });
+}
+
+run();
diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/v7/generation/test.ts b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/v7/generation/test.ts
index f6059b7ad0e0..4ee62ba8d1e7 100644
--- a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/v7/generation/test.ts
+++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/v7/generation/test.ts
@@ -11,16 +11,27 @@ import {
GEN_AI_USAGE_INPUT_TOKENS,
GEN_AI_USAGE_OUTPUT_TOKENS,
GEN_AI_USAGE_TOTAL_TOKENS,
+ SENTRY_ENVIRONMENT,
+ SENTRY_IS_LOCALHOST,
SENTRY_OP,
SENTRY_ORIGIN,
+ SENTRY_RELEASE,
+ SENTRY_SDK_NAME,
+ SENTRY_SDK_VERSION,
+ SENTRY_SEGMENT_ID,
+ SENTRY_SEGMENT_NAME,
+ SENTRY_TRACE_LIFECYCLE,
} from '@sentry/conventions/attributes';
import {
GEN_AI_DECIDE,
GEN_AI_EXECUTE_TOOL,
+ GEN_AI_EXTRACT,
GEN_AI_GENERATE_CONTENT,
GEN_AI_INVOKE_AGENT,
} from '@sentry/conventions/op';
-import { SUPPORTS_REQUIRE_OF_ESM } from '../../../../../../utils';
+import type { SerializedStreamedSpan } from '@sentry/core';
+import { SDK_VERSION } from '@sentry/core';
+import { EXPECTED_SDK_NAME, SUPPORTS_REQUIRE_OF_ESM } from '../../../../../../utils';
import { cleanupChildProcesses, createEsmAndCjsTests, createEsmTests } from '../../../../../../utils/runner';
import { registerVercelAiGenerationTests } from '../../suite';
import { join } from 'node:path';
@@ -134,6 +145,120 @@ describe('Vercel AI integration experimental_decide', () => {
);
});
+describe('Vercel AI integration experimental_extract', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ function getExtractSpans(container: { items: SerializedStreamedSpan[] }): {
+ extractSpan: SerializedStreamedSpan;
+ segmentSpan: SerializedStreamedSpan;
+ } {
+ const extractSpans = container.items.filter(span => span.attributes[SENTRY_OP]?.value === GEN_AI_EXTRACT);
+ expect(extractSpans).toHaveLength(1);
+ return { extractSpan: extractSpans[0]!, segmentSpan: container.items.find(span => span.is_segment)! };
+ }
+
+ function expectedBaseAttributes(segmentSpan: SerializedStreamedSpan): Record {
+ return {
+ [SENTRY_ORIGIN]: { type: 'string', value: 'auto.ai.vercelai' },
+ [SENTRY_OP]: { type: 'string', value: GEN_AI_EXTRACT },
+ [GEN_AI_OPERATION_NAME]: { type: 'string', value: 'extract' },
+ [GEN_AI_PROVIDER_NAME]: { type: 'string', value: 'gateway' },
+ 'vercel.ai.model.provider': { type: 'string', value: 'gateway' },
+ [GEN_AI_REQUEST_MODEL]: { type: 'string', value: 'cloudflare/clairic' },
+ 'vercel.ai.settings.maxRetries': { type: 'integer', value: 2 },
+ [GEN_AI_USAGE_INPUT_TOKENS]: { type: 'integer', value: 50 },
+ [GEN_AI_USAGE_OUTPUT_TOKENS]: { type: 'integer', value: 4 },
+ [GEN_AI_USAGE_TOTAL_TOKENS]: { type: 'integer', value: 54 },
+ [GEN_AI_RESPONSE_MODEL]: { type: 'string', value: 'cloudflare/clairic' },
+ [SENTRY_TRACE_LIFECYCLE]: { type: 'string', value: 'stream' },
+ [SENTRY_SEGMENT_NAME]: { type: 'string', value: segmentSpan.name },
+ [SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpan.span_id },
+ [SENTRY_SDK_NAME]: { type: 'string', value: EXPECTED_SDK_NAME },
+ [SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION },
+ [SENTRY_RELEASE]: { type: 'string', value: '1.0' },
+ [SENTRY_ENVIRONMENT]: { type: 'string', value: 'production' },
+ [SENTRY_IS_LOCALHOST]: { type: 'boolean', value: false },
+ };
+ }
+
+ createEsmTests(
+ join(__dirname, '../..'),
+ 'scenario-extract.mjs',
+ 'instrument-decide.mjs',
+ (createRunner, test) => {
+ test('creates an extract span', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ const { extractSpan, segmentSpan } = getExtractSpans(container);
+ expect(extractSpan.name).toBe('extract cloudflare/clairic');
+ expect(extractSpan.status).toBe('ok');
+ expect(extractSpan.attributes).toEqual({
+ ...expectedBaseAttributes(segmentSpan),
+ [GEN_AI_INPUT_MESSAGES]: {
+ type: 'string',
+ value: JSON.stringify([
+ {
+ state: 'Invoice INV-2291 from Northwind Supply. Total due: $1,080.',
+ fields: {
+ invoiceNumber: { type: 'text', instructions: 'The invoice number' },
+ total: { type: 'number', instructions: 'The total amount due' },
+ },
+ },
+ ]),
+ },
+ [GEN_AI_OUTPUT_MESSAGES]: {
+ type: 'string',
+ value: JSON.stringify([
+ {
+ answers: {
+ invoiceNumber: { type: 'text', value: 'INV-2291', confidence: 0.98 },
+ total: { type: 'number', value: 1080, confidence: 0.95 },
+ },
+ },
+ ]),
+ },
+ });
+ },
+ })
+ .start()
+ .completed();
+ });
+ },
+ {
+ additionalDependencies: {
+ ai: '^7.0.178',
+ },
+ },
+ );
+
+ createEsmTests(
+ join(__dirname, '../..'),
+ 'scenario-extract.mjs',
+ 'instrument-decide-no-recording.mjs',
+ (createRunner, test) => {
+ test('does not record inputs or outputs when recording is off', async () => {
+ await createRunner()
+ .expect({
+ span: container => {
+ const { extractSpan, segmentSpan } = getExtractSpans(container);
+ expect(extractSpan.attributes).toEqual(expectedBaseAttributes(segmentSpan));
+ },
+ })
+ .start()
+ .completed();
+ });
+ },
+ {
+ additionalDependencies: {
+ ai: '^7.0.178',
+ },
+ },
+ );
+});
+
describe('Vercel AI runtime and tool context (v7)', () => {
afterAll(() => {
cleanupChildProcesses();
diff --git a/dev-packages/node-integration-tests/utils/runner/createRunner.ts b/dev-packages/node-integration-tests/utils/runner/createRunner.ts
index e555f1d483df..f9a2258bd590 100644
--- a/dev-packages/node-integration-tests/utils/runner/createRunner.ts
+++ b/dev-packages/node-integration-tests/utils/runner/createRunner.ts
@@ -801,7 +801,16 @@ export function createRunner(...paths: string[]) {
} = {},
): Promise {
try {
- await waitForEvent(portReady.promise, PORT_TIMEOUT, 'Timed out waiting for server port');
+ await waitForEvent(
+ Promise.race([
+ portReady.promise,
+ Promise.race([completedDeferred.promise, exitedDeferred.promise]).then(() => {
+ throw completeError ?? new Error('Scenario stopped before reporting its server port');
+ }),
+ ]),
+ PORT_TIMEOUT,
+ 'Timed out waiting for server port',
+ );
} catch (e) {
complete(e as Error);
return;
diff --git a/dev-packages/node-integration-tests/vite.config.ts b/dev-packages/node-integration-tests/vite.config.ts
index cb56054fadcd..ad01a4483376 100644
--- a/dev-packages/node-integration-tests/vite.config.ts
+++ b/dev-packages/node-integration-tests/vite.config.ts
@@ -6,7 +6,7 @@ export default defineConfig({
test: {
...baseConfig.test,
isolate: false,
- include: ['./**/test.ts'],
+ include: ['./**/test.ts', './suites/**/*.test.ts'],
testTimeout: 15000,
// Ensure we can see debug output when DEBUG=true
...(process.env.DEBUG
diff --git a/dev-packages/size-limit-gh-action/index.mjs b/dev-packages/size-limit-gh-action/index.mjs
index b23a752b1e94..8331e61e6b15 100644
--- a/dev-packages/size-limit-gh-action/index.mjs
+++ b/dev-packages/size-limit-gh-action/index.mjs
@@ -7,8 +7,8 @@ import { getExecOutput } from '@actions/exec';
import { context, getOctokit } from '@actions/github';
import { markdownTable } from 'markdown-table';
import sizeConfig from '../../.size-limit.js';
-import { getArtifactsForBranchAndWorkflow } from './utils/getArtifactsForBranchAndWorkflow.mjs';
-import { MAX_INCREASE_BYTES, SizeLimitFormatter } from './utils/SizeLimitFormatter.mjs';
+import { getArtifactForBranch } from './utils/artifacts.mjs';
+import { formatResults, getSizeIncreases, MAX_INCREASE_BYTES, parseResults } from './utils/results.mjs';
const OVERRIDE_LABEL = 'Accept Bundlesize Increase';
const RELEASE_BRANCH_PREFIX = 'prepare-release/';
@@ -16,196 +16,210 @@ const SIZE_LIMIT_HEADING = '## size-limit report 📦 ';
const ARTIFACT_NAME = 'size-limit-action';
const ACTION_DIRECTORY = path.dirname(fileURLToPath(import.meta.url));
const RESULTS_FILE_PATH = path.join(ACTION_DIRECTORY, 'size-limit-results.json');
+const WORKFLOW_FILE = path.basename(process.env.GITHUB_WORKFLOW_REF.split('@')[0]);
+const REPO_URL = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}`;
-const { getInput, setFailed } = core;
+const NO_BASELINE_FAILURE = 'No baseline size measurements found. Re-run after the base build completes.';
+const INCREASE_FAILURE =
+ `One or more gzipped bundles increased by more than ${MAX_INCREASE_BYTES} bytes. ` +
+ `If this increase is intentional, add the **${OVERRIDE_LABEL}** label to this PR to rerun and accept the check.`;
+
+const artifactClient = new DefaultArtifactClient();
async function run() {
- try {
- const { payload, repo } = context;
- const pr = payload.pull_request;
+ // Only set on PRs, where it is the PR's base branch
+ const comparisonBranch = core.getInput('comparison_branch');
+ const githubToken = core.getInput('github_token');
+ const octokit = getOctokit(githubToken);
+ const pr = context.payload.pull_request;
+
+ if (comparisonBranch && !pr) {
+ throw new Error('No PR found. Only pull_request workflows are supported.');
+ }
- // The comparison branch is the base branch we are comparing against (in our case usually develop)
- const comparisonBranch = getInput('comparison_branch');
- const githubToken = getInput('github_token');
+ const { stdout } = await getExecOutput('pnpm', ['exec', 'size-limit', '--json']);
+ const current = parseResults(stdout);
- if (comparisonBranch && !pr) {
- throw new Error('No PR found. Only pull_request workflows are supported.');
- }
+ if (!comparisonBranch) {
+ await uploadResults(current);
+ return;
+ }
- const octokit = getOctokit(githubToken);
- let increaseAccepted = false;
+ const mergedBaseSha = await getMergedBaseSha(octokit);
+ const baseline = await downloadBaseline(octokit, githubToken, { comparisonBranch });
- if (comparisonBranch) {
- const { data: currentPr } = await octokit.rest.pulls.get({
- ...repo,
- pull_number: pr.number,
- });
- increaseAccepted = currentPr.labels.some(label => label.name === OVERRIDE_LABEL);
- }
+ const hasIncrease = baseline ? getSizeIncreases(baseline.results, current, sizeConfig).length > 0 : false;
+ const bodyParts = [SIZE_LIMIT_HEADING];
+ let failure;
- const limit = new SizeLimitFormatter();
- const artifactClient = new DefaultArtifactClient();
+ if (baseline) {
+ bodyParts.push(...(await describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch })));
+ }
- // Build and measure each bundle defined in .size-limit.js for the current branch
- const { stdout } = await getExecOutput('pnpm', ['exec', 'size-limit', '--json']);
- const current = limit.parseResults(stdout);
+ if (pr.head.ref.startsWith(RELEASE_BRANCH_PREFIX)) {
+ // Release PRs target master, which has no baseline and would include every change since the last release anyway
+ core.info('Release PR detected. Reporting bundle sizes without enforcing limits.');
+ } else if (!baseline) {
+ failure = NO_BASELINE_FAILURE;
+ bodyParts.push(failure);
+ } else if (hasIncrease && !(await hasLabel(octokit, pr, OVERRIDE_LABEL))) {
+ failure = INCREASE_FAILURE;
+ }
- // If we have no comparison branch, we only store the results as artifacts (likely running on develop)
- if (!comparisonBranch) {
- await fs.writeFile(RESULTS_FILE_PATH, JSON.stringify(current), 'utf8');
- await artifactClient.uploadArtifact(ARTIFACT_NAME, [RESULTS_FILE_PATH], ACTION_DIRECTORY);
- return;
- }
+ bodyParts.push(markdownTable(formatResults(baseline?.results, current)));
+ if (baseline) {
+ bodyParts.push(`[View base workflow run](${baseline.workflowRun.html_url})`);
+ }
- // Else, we fetch the results for the comparison branch and compare them with the current branch (likely running on a PR)
- let base;
- let baseWorkflowRun;
-
- try {
- const workflowName = process.env.GITHUB_WORKFLOW;
- core.startGroup(`getArtifactsForBranchAndWorkflow - workflow:"${workflowName}", branch:"${comparisonBranch}"`);
- const artifacts = await getArtifactsForBranchAndWorkflow(octokit, {
- ...repo,
- artifactName: ARTIFACT_NAME,
- branch: comparisonBranch,
- workflowName,
- });
- core.endGroup();
-
- if (!artifacts) {
- throw new Error('No artifacts found');
- }
-
- baseWorkflowRun = artifacts.workflowRun;
-
- await artifactClient.downloadArtifact(artifacts.artifact.id, {
- path: ACTION_DIRECTORY,
- findBy: {
- token: githubToken,
- workflowRunId: artifacts.workflowRun.id,
- repositoryOwner: repo.owner,
- repositoryName: repo.repo,
- },
- });
-
- base = JSON.parse(await fs.readFile(RESULTS_FILE_PATH, { encoding: 'utf8' }));
- } catch (error) {
- core.startGroup('Warning, unable to find base results');
- core.error(error);
- core.endGroup();
- }
+ const body = bodyParts.join('\n\n');
+ await core.summary.addRaw(body).write();
+ await updatePrComments(octokit, pr, { body, failure });
- const increases = base ? limit.getSizeIncreases(base, current, sizeConfig) : [];
- const bodyParts = [SIZE_LIMIT_HEADING];
-
- // Check if our baseline build is up to date with the target branch (likely develop) and report any mismatches
- if (base) {
- const baselineSha = baseWorkflowRun.head_sha; // The commit SHA of the baseline build (where we pull the size-limit results from)
- const repoUrl = `${context.serverUrl}/${repo.owner}/${repo.repo}`;
- const commitLink = sha => `[${sha.slice(0, 7)}](${repoUrl}/commit/${sha})`;
-
- try {
- const { data: mergeCommit } = await octokit.rest.repos.getCommit({ ...repo, ref: context.sha });
- const mergedBaseSha = mergeCommit.parents[0].sha; // The SHA of the target branch (likely develop) base commit that was used to test this PR
-
- bodyParts.push(
- `Compared: ${commitLink(context.sha)} (PR test merge using ${comparisonBranch} at ${commitLink(mergedBaseSha)})`,
- `Against: ${commitLink(baselineSha)} (${comparisonBranch}) · [base run #${baseWorkflowRun.run_number}](${baseWorkflowRun.html_url})`,
- );
-
- if (baselineSha === mergedBaseSha) {
- bodyParts.push("✅ Baseline matches: this diff contains only this PR's changes.");
- } else {
- const { data: comparison } = await octokit.rest.repos.compareCommitsWithBasehead({
- ...repo,
- basehead: `${baselineSha}...${mergedBaseSha}`,
- });
- const differences = [];
- if (comparison.ahead_by > 0) {
- differences.push(
- `${comparison.ahead_by} ${comparisonBranch} commit(s) in the PR build are missing from the baseline`,
- );
- }
- if (comparison.behind_by > 0) {
- differences.push(
- `${comparison.behind_by} ${comparisonBranch} commit(s) in the baseline are missing from the PR build`,
- );
- }
- const guidance =
- comparison.behind_by > 0
- ? `Rebase your PR onto the latest ${comparisonBranch} to compare against an up-to-date baseline.`
- : `Re-run once ${comparisonBranch}'s baseline build for ${commitLink(mergedBaseSha)} finishes.`;
- bodyParts.push(
- `⚠️ Baseline mismatch: ${differences.join('; ')}. Their size changes also affect this comparison. ` +
- `[Compare commits](${comparison.html_url}). ${guidance}`,
- );
- }
- } catch (error) {
- core.warning(`Unable to check baseline alignment: ${error.message}`);
- bodyParts.push('⚠️ Unable to verify whether the baseline matches the PR build.');
- }
- }
+ if (failure) {
+ core.setFailed(failure);
+ }
+}
- let failure;
- if (pr.head.ref.startsWith(RELEASE_BRANCH_PREFIX)) {
- // Release PRs target master, which has no baseline and would include every change since the last release anyway
- core.info('Release PR detected. Reporting bundle sizes without enforcing limits.');
- } else if (!base) {
- failure = 'No baseline size measurements found. Re-run after the base build completes.';
- bodyParts.push(failure);
- } else if (increases.length > 0 && !increaseAccepted) {
- failure =
- `One or more gzipped bundles increased by more than ${MAX_INCREASE_BYTES} bytes. ` +
- `If this increase is intentional, add the **${OVERRIDE_LABEL}** label to this PR to rerun and accept the check.`;
+async function uploadResults(results) {
+ await fs.writeFile(RESULTS_FILE_PATH, JSON.stringify(results), 'utf8');
+ await artifactClient.uploadArtifact(ARTIFACT_NAME, [RESULTS_FILE_PATH], ACTION_DIRECTORY);
+}
+
+/**
+ * On PRs, GitHub checks out a merge of the PR into its base branch (`refs/pull//merge`). Its first parent is the
+ * base branch commit this PR is compared against.
+ */
+async function getMergedBaseSha(octokit) {
+ try {
+ const { data } = await octokit.rest.repos.getCommit({ ...context.repo, ref: context.sha });
+ return data.parents[0].sha;
+ } catch (error) {
+ core.warning(`Unable to resolve the base commit of the PR test merge: ${error.message}`);
+ return undefined;
+ }
+}
+
+async function downloadBaseline(octokit, githubToken, { comparisonBranch }) {
+ try {
+ const found = await getArtifactForBranch(octokit, {
+ workflow: WORKFLOW_FILE,
+ branch: comparisonBranch,
+ artifactName: ARTIFACT_NAME,
+ });
+
+ if (!found) {
+ throw new Error('No artifacts found');
}
- bodyParts.push(markdownTable(limit.formatResults(base, current)));
- if (baseWorkflowRun) {
- bodyParts.push(`[View base workflow run](${baseWorkflowRun.html_url})`);
+ await artifactClient.downloadArtifact(found.artifact.id, {
+ path: ACTION_DIRECTORY,
+ findBy: {
+ token: githubToken,
+ workflowRunId: found.workflowRun.id,
+ repositoryOwner: context.repo.owner,
+ repositoryName: context.repo.repo,
+ },
+ });
+
+ return {
+ results: JSON.parse(await fs.readFile(RESULTS_FILE_PATH, 'utf8')),
+ sha: found.workflowRun.head_sha,
+ workflowRun: found.workflowRun,
+ };
+ } catch (error) {
+ core.warning(`Unable to find base results: ${error.message}`);
+ return undefined;
+ }
+}
+
+/**
+ * Report which commits were compared, and whether the baseline contains exactly what this PR was tested against.
+ */
+async function describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch }) {
+ const unverified = '⚠️ Unable to verify whether the baseline matches the PR build.';
+ if (!mergedBaseSha) {
+ return [unverified];
+ }
+
+ const { sha, workflowRun } = baseline;
+ const parts = [
+ `Compared: ${commitLink(context.sha)} (PR test merge using ${comparisonBranch} at ${commitLink(mergedBaseSha)})`,
+ `Against: ${commitLink(sha)} (${comparisonBranch}) · [base run #${workflowRun.run_number}](${workflowRun.html_url})`,
+ ];
+
+ if (sha === mergedBaseSha) {
+ parts.push("✅ Baseline matches: this diff contains only this PR's changes.");
+ return parts;
+ }
+
+ try {
+ const { data: comparison } = await octokit.rest.repos.compareCommitsWithBasehead({
+ ...context.repo,
+ basehead: `${sha}...${mergedBaseSha}`,
+ });
+ const differences = [];
+ if (comparison.ahead_by > 0) {
+ differences.push(
+ `${comparison.ahead_by} ${comparisonBranch} commit(s) in the PR build are missing from the baseline`,
+ );
+ }
+ if (comparison.behind_by > 0) {
+ differences.push(
+ `${comparison.behind_by} ${comparisonBranch} commit(s) in the baseline are missing from the PR build`,
+ );
}
+ const guidance =
+ comparison.behind_by > 0
+ ? `Rebase your PR onto the latest ${comparisonBranch} to compare against an up-to-date baseline.`
+ : `Re-run once ${comparisonBranch}'s baseline build for ${commitLink(mergedBaseSha)} finishes.`;
+ parts.push(
+ `⚠️ Baseline mismatch: ${differences.join('; ')}. Their size changes also affect this comparison. ` +
+ `[Compare commits](${comparison.html_url}). ${guidance}`,
+ );
+ } catch (error) {
+ core.warning(`Unable to check baseline alignment: ${error.message}`);
+ parts.push(unverified);
+ }
+
+ return parts;
+}
+
+async function hasLabel(octokit, pr, label) {
+ const { data } = await octokit.rest.pulls.get({ ...context.repo, pull_number: pr.number });
+ return data.labels.some(({ name }) => name === label);
+}
- const body = bodyParts.join('\n\n');
- await core.summary.addRaw(body).write();
-
- try {
- const comments = await octokit.paginate(octokit.rest.issues.listComments, {
- ...repo,
- issue_number: pr.number,
- per_page: 100,
- });
- const sizeLimitComment = comments.find(comment => comment.body.startsWith(SIZE_LIMIT_HEADING));
- if (sizeLimitComment) {
- await octokit.rest.issues.updateComment({
- ...repo,
- comment_id: sizeLimitComment.id,
- body,
- });
- } else {
- await octokit.rest.issues.createComment({
- ...repo,
- issue_number: pr.number,
- body,
- });
- }
-
- if (failure && increases.length > 0 && !comments.some(comment => comment.body === failure)) {
- await octokit.rest.issues.createComment({
- ...repo,
- issue_number: pr.number,
- body: failure,
- });
- }
- } catch {
- core.warning('Unable to update PR comments. The size report is available in the job summary.');
+/**
+ * Keep one size report comment up to date. A size increase also gets its own comment, which notifies the author.
+ */
+async function updatePrComments(octokit, pr, { body, failure }) {
+ try {
+ const comments = await octokit.paginate(octokit.rest.issues.listComments, {
+ ...context.repo,
+ issue_number: pr.number,
+ per_page: 100,
+ });
+
+ const report = comments.find(comment => comment.body.startsWith(SIZE_LIMIT_HEADING));
+ if (report) {
+ await octokit.rest.issues.updateComment({ ...context.repo, comment_id: report.id, body });
+ } else {
+ await octokit.rest.issues.createComment({ ...context.repo, issue_number: pr.number, body });
}
- if (failure) {
- setFailed(failure);
+ if (failure === INCREASE_FAILURE && !comments.some(comment => comment.body === failure)) {
+ await octokit.rest.issues.createComment({ ...context.repo, issue_number: pr.number, body: failure });
}
- } catch (error) {
- core.error(error);
- setFailed(error.message);
+ } catch {
+ core.warning('Unable to update PR comments. The size report is available in the job summary.');
}
}
-await run();
+function commitLink(sha) {
+ return `[${sha.slice(0, 7)}](${REPO_URL}/commit/${sha})`;
+}
+
+await run().catch(error => {
+ core.error(error);
+ core.setFailed(error.message);
+});
diff --git a/dev-packages/size-limit-gh-action/package.json b/dev-packages/size-limit-gh-action/package.json
index 828f16819b39..ed6d2eaa289c 100644
--- a/dev-packages/size-limit-gh-action/package.json
+++ b/dev-packages/size-limit-gh-action/package.json
@@ -1,6 +1,6 @@
{
"name": "@sentry-internal/size-limit-gh-action",
- "description": "An internal Github Action to compare the current size of a PR against the one on develop.",
+ "description": "An internal Github Action to compare the bundle sizes of a PR against its base.",
"version": "11.17.0",
"license": "MIT",
"engines": {
diff --git a/dev-packages/size-limit-gh-action/utils/SizeLimitFormatter.mjs b/dev-packages/size-limit-gh-action/utils/SizeLimitFormatter.mjs
deleted file mode 100644
index 8e1449f2df7a..000000000000
--- a/dev-packages/size-limit-gh-action/utils/SizeLimitFormatter.mjs
+++ /dev/null
@@ -1,106 +0,0 @@
-import bytes from 'bytes-iec';
-
-export const MAX_INCREASE_BYTES = 500;
-
-const SIZE_RESULTS_HEADER = ['Path', 'Size', '% Change', 'Change'];
-
-const EmptyResult = {
- name: '-',
- size: 0,
-};
-
-export class SizeLimitFormatter {
- formatBytes(size) {
- return bytes.format(size, { unitSeparator: ' ' });
- }
-
- formatPercentageChange(base = 0, current = 0) {
- if (base === 0) {
- return 'added';
- }
-
- if (current === 0) {
- return 'removed';
- }
-
- const value = ((current - base) / base) * 100;
- const formatted = (Math.sign(value) * Math.ceil(Math.abs(value) * 100)) / 100;
-
- if (value > 0) {
- return `+${formatted}%`;
- }
-
- if (value === 0) {
- return '-';
- }
-
- return `${formatted}%`;
- }
-
- formatChange(base = 0, current = 0) {
- if (base === 0) {
- return 'added';
- }
-
- if (current === 0) {
- return 'removed';
- }
-
- const value = current - base;
- const formatted = this.formatBytes(value);
-
- if (value > 0) {
- return `+${formatted} 🔺`;
- }
-
- if (value === 0) {
- return '-';
- }
-
- return `${formatted} 🔽`;
- }
-
- formatSizeResult(name, base, current) {
- return [
- name,
- this.formatBytes(current.size),
- this.formatPercentageChange(base.size, current.size),
- this.formatChange(base.size, current.size),
- ];
- }
-
- parseResults(output) {
- const results = JSON.parse(output);
-
- return results.reduce(
- (current, result) => ({
- ...current,
- [result.name]: {
- name: result.name,
- size: result.size,
- },
- }),
- {},
- );
- }
-
- getSizeIncreases(base, current, config) {
- return config
- .filter(({ name, gzip }) => gzip === true && base[name])
- .map(({ name }) => ({ name, increase: current[name].size - base[name].size }))
- .filter(({ increase }) => increase > MAX_INCREASE_BYTES);
- }
-
- formatResults(base, current) {
- const names = [...new Set([...(base ? Object.keys(base) : []), ...Object.keys(current)])];
- const header = SIZE_RESULTS_HEADER;
- const fields = names.map(name => {
- const baseResult = base?.[name] || EmptyResult;
- const currentResult = current[name] || EmptyResult;
-
- return this.formatSizeResult(name, baseResult, currentResult);
- });
-
- return [header, ...fields];
- }
-}
diff --git a/dev-packages/size-limit-gh-action/utils/artifacts.mjs b/dev-packages/size-limit-gh-action/utils/artifacts.mjs
new file mode 100644
index 000000000000..0dbe1ee48178
--- /dev/null
+++ b/dev-packages/size-limit-gh-action/utils/artifacts.mjs
@@ -0,0 +1,58 @@
+import * as core from '@actions/core';
+import { context } from '@actions/github';
+
+const MAX_COMMITS = 50;
+
+/**
+ * Find the newest `artifactName` artifact on `branch`. This walks the branch's commits, because listing workflow runs by
+ * branch is eventually consistent and can silently skip the most recent runs.
+ */
+export async function getArtifactForBranch(octokit, { workflow, branch, artifactName }) {
+ const { data: commits } = await octokit.rest.repos.listCommits({
+ ...context.repo,
+ sha: branch,
+ per_page: MAX_COMMITS,
+ });
+
+ for (const [index, { sha }] of commits.entries()) {
+ const found = await getArtifactForCommit(octokit, { workflow, sha, artifactName });
+ if (found) {
+ if (index > 0) {
+ core.info(`Using results from ${sha}, which is ${index} commit(s) behind the tip of "${branch}".`);
+ }
+ return found;
+ }
+ }
+
+ core.warning(`No "${artifactName}" artifact found in the last ${commits.length} commits of "${branch}".`);
+ return null;
+}
+
+async function getArtifactForCommit(octokit, { workflow, sha, artifactName }) {
+ for (const workflowRun of await listRunsForCommit(octokit, { workflow, sha })) {
+ const { data } = await octokit.rest.actions.listWorkflowRunArtifacts({ ...context.repo, run_id: workflowRun.id });
+ const artifact = data.artifacts.find(({ name }) => name === artifactName);
+ if (artifact) {
+ core.info(`Found "${artifactName}" for commit ${sha} in ${workflowRun.html_url}`);
+ return { artifact, workflowRun };
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Newest first. Runs from forks are never trusted.
+ */
+async function listRunsForCommit(octokit, { workflow, sha }) {
+ const { data } = await octokit.rest.actions.listWorkflowRuns({
+ ...context.repo,
+ workflow_id: workflow,
+ head_sha: sha,
+ per_page: 100,
+ });
+
+ return data.workflow_runs
+ .filter(run => run.head_repository?.full_name === `${context.repo.owner}/${context.repo.repo}`)
+ .sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at));
+}
diff --git a/dev-packages/size-limit-gh-action/utils/getArtifactsForBranchAndWorkflow.mjs b/dev-packages/size-limit-gh-action/utils/getArtifactsForBranchAndWorkflow.mjs
deleted file mode 100644
index 7e0b28d4c278..000000000000
--- a/dev-packages/size-limit-gh-action/utils/getArtifactsForBranchAndWorkflow.mjs
+++ /dev/null
@@ -1,118 +0,0 @@
-import * as core from '@actions/core';
-
-// How many commits to walk back on the branch before giving up on finding a build with a size-limit artifact.
-const DEFAULT_MAX_COMMITS = 50;
-const COMMITS_PER_PAGE = 100;
-const RUNS_PER_PAGE = 100;
-
-/**
- * Find the most recent build artifact for a branch by walking its git history.
- *
- * We deliberately drive this from `repos.listCommits` (authoritative, strictly ordered git history) rather than from
- * `listWorkflowRuns` filtered by branch + event. That listing is backed by an eventually-consistent index that can omit
- * or reorder very recent runs, which previously made us silently compare against a days-old baseline while still
- * reporting it as the latest one. Walking commits newest-first and pinning each run by `head_sha` sidesteps that: the
- * order is exact, and if the tip commit has no artifact yet we fall back to its parent and correctly report the baseline
- * as not-latest.
- */
-export async function getArtifactsForBranchAndWorkflow(octokit, { owner, repo, workflowName, branch, artifactName }) {
- const workflowId = await findWorkflowId(octokit, { owner, repo, workflowName });
-
- if (!workflowId) {
- return null;
- }
-
- let commitsChecked = 0;
-
- for await (const response of octokit.paginate.iterator(octokit.rest.repos.listCommits, {
- owner,
- repo,
- sha: branch,
- per_page: COMMITS_PER_PAGE,
- })) {
- for (const { sha } of response.data) {
- const isLatest = commitsChecked === 0;
- commitsChecked++;
-
- const found = await findArtifactForCommit(octokit, { owner, repo, workflowId, sha, artifactName });
-
- if (found) {
- if (!isLatest) {
- core.info(
- `Base artifact comes from commit ${sha}, which is ${commitsChecked - 1} commit(s) behind the tip of "${branch}".`,
- );
- }
- return { ...found, isLatest };
- }
-
- if (commitsChecked >= DEFAULT_MAX_COMMITS) {
- core.warning(
- `No "${artifactName}" artifact found within the last ${DEFAULT_MAX_COMMITS} commits of "${branch}".`,
- );
- return null;
- }
- }
- }
-
- core.warning(`No "${artifactName}" artifact found on branch "${branch}".`);
- return null;
-}
-
-/**
- * Resolve a workflow's numeric id from its display name.
- */
-async function findWorkflowId(octokit, { owner, repo, workflowName }) {
- const allWorkflows = [];
-
- for await (const response of octokit.paginate.iterator(octokit.rest.actions.listRepoWorkflows, { owner, repo })) {
- const targetWorkflow = response.data.find(({ name }) => name === workflowName);
- allWorkflows.push(...response.data.map(({ name }) => name));
-
- if (targetWorkflow) {
- return targetWorkflow.id;
- }
- }
-
- core.info(
- `Unable to find workflow with name "${workflowName}" in the repository. Found workflows: ${allWorkflows.join(', ')}`,
- );
- return null;
-}
-
-/**
- * Return the first `artifactName` artifact produced by any run of `workflowId` for the exact `sha`, preferring the most
- * recent run (in case of re-runs). Runs originating from a fork are never trusted.
- */
-async function findArtifactForCommit(octokit, { owner, repo, workflowId, sha, artifactName }) {
- const {
- data: { workflow_runs: workflowRuns },
- } = await octokit.rest.actions.listWorkflowRuns({
- owner,
- repo,
- workflow_id: workflowId,
- head_sha: sha,
- per_page: RUNS_PER_PAGE,
- });
-
- const runs = workflowRuns
- .filter(workflowRun => workflowRun.head_repository?.full_name === `${owner}/${repo}`)
- .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
-
- for (const workflowRun of runs) {
- const {
- data: { artifacts },
- } = await octokit.rest.actions.listWorkflowRunArtifacts({
- owner,
- repo,
- run_id: workflowRun.id,
- });
-
- const artifact = artifacts?.find(({ name }) => name === artifactName);
- if (artifact) {
- core.info(`Found suitable artifact for commit ${sha}: ${artifact.url} (run ${workflowRun.html_url})`);
- return { artifact, workflowRun };
- }
- }
-
- return null;
-}
diff --git a/dev-packages/size-limit-gh-action/utils/results.mjs b/dev-packages/size-limit-gh-action/utils/results.mjs
new file mode 100644
index 000000000000..9cbdfc145bb6
--- /dev/null
+++ b/dev-packages/size-limit-gh-action/utils/results.mjs
@@ -0,0 +1,69 @@
+import bytes from 'bytes-iec';
+
+export const MAX_INCREASE_BYTES = 500;
+
+export function parseResults(output) {
+ return Object.fromEntries(JSON.parse(output).map(({ name, size }) => [name, { name, size }]));
+}
+
+export function getSizeIncreases(base, current, config) {
+ return config
+ .filter(({ name, gzip }) => gzip === true && base[name])
+ .map(({ name }) => ({ name, increase: current[name].size - base[name].size }))
+ .filter(({ increase }) => increase > MAX_INCREASE_BYTES);
+}
+
+export function formatResults(base, current) {
+ const names = [...new Set([...Object.keys(base ?? {}), ...Object.keys(current)])];
+
+ return [
+ ['Path', 'Size', '% Change', 'Change'],
+ ...names.map(name => {
+ const baseSize = base?.[name]?.size ?? 0;
+ const currentSize = current[name]?.size ?? 0;
+ return [
+ name,
+ formatBytes(currentSize),
+ formatPercentageChange(baseSize, currentSize),
+ formatChange(baseSize, currentSize),
+ ];
+ }),
+ ];
+}
+
+function formatBytes(size) {
+ return bytes.format(size, { unitSeparator: ' ' });
+}
+
+function formatPercentageChange(base, current) {
+ if (base === 0) {
+ return 'added';
+ }
+ if (current === 0) {
+ return 'removed';
+ }
+
+ const value = ((current - base) / base) * 100;
+ const formatted = (Math.sign(value) * Math.ceil(Math.abs(value) * 100)) / 100;
+
+ if (value > 0) {
+ return `+${formatted}%`;
+ }
+ return value === 0 ? '-' : `${formatted}%`;
+}
+
+function formatChange(base, current) {
+ if (base === 0) {
+ return 'added';
+ }
+ if (current === 0) {
+ return 'removed';
+ }
+
+ const value = current - base;
+
+ if (value > 0) {
+ return `+${formatBytes(value)} 🔺`;
+ }
+ return value === 0 ? '-' : `${formatBytes(value)} 🔽`;
+}
diff --git a/dev-packages/test-utils/package.json b/dev-packages/test-utils/package.json
index 7ae64d616150..a5322ab61c31 100644
--- a/dev-packages/test-utils/package.json
+++ b/dev-packages/test-utils/package.json
@@ -71,7 +71,7 @@
"@playwright/test": "1.64.1"
},
"dependencies": {
- "@sentry/conventions": "^0.35.0",
+ "@sentry/conventions": "^0.36.0",
"express": "^4.22.3",
"ws": "^8.20.1"
},
diff --git a/packages/angular/.oxlintrc.json b/packages/angular/.oxlintrc.json
index 915515b69e92..9a229b793d98 100644
--- a/packages/angular/.oxlintrc.json
+++ b/packages/angular/.oxlintrc.json
@@ -1,6 +1,6 @@
{
"$schema": "../../node_modules/oxlint/configuration_schema.json",
- "extends": ["../../.oxlintrc.base.json"],
+ "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"],
"jsPlugins": [
{
"name": "sdk",
diff --git a/packages/angular/package.json b/packages/angular/package.json
index e2b36fbbc096..dacc9be2b282 100644
--- a/packages/angular/package.json
+++ b/packages/angular/package.json
@@ -23,7 +23,7 @@
"dependencies": {
"@sentry/browser": "11.17.0",
"@sentry/core": "11.17.0",
- "@sentry/conventions": "^0.35.0",
+ "@sentry/conventions": "^0.36.0",
"tslib": "^2.4.1"
},
"devDependencies": {
diff --git a/packages/astro/package.json b/packages/astro/package.json
index 56abcf9800b7..710d13c854a1 100644
--- a/packages/astro/package.json
+++ b/packages/astro/package.json
@@ -35,6 +35,14 @@
"import": "./build/esm/index.worker.js",
"require": "./build/cjs/index.worker.js"
},
+ "bun": {
+ "import": "./build/esm/index.bun.js",
+ "require": "./build/cjs/index.bun.js"
+ },
+ "deno": {
+ "import": "./build/esm/index.deno.js",
+ "require": "./build/cjs/index.deno.js"
+ },
"node": "./build/esm/index.server.js",
"browser": "./build/esm/index.client.js",
"import": "./build/esm/index.client.js",
@@ -62,13 +70,23 @@
"access": "public"
},
"peerDependencies": {
+ "@sentry/bun": "11.17.0",
+ "@sentry/deno": "11.17.0",
"astro": ">=4.0.0-beta || >=7.0.0-beta"
},
+ "peerDependenciesMeta": {
+ "@sentry/bun": {
+ "optional": true
+ },
+ "@sentry/deno": {
+ "optional": true
+ }
+ },
"dependencies": {
"@sentry/browser": "11.17.0",
"@sentry/cloudflare": "11.17.0",
"@sentry/core": "11.17.0",
- "@sentry/conventions": "^0.35.0",
+ "@sentry/conventions": "^0.36.0",
"@sentry/node": "11.17.0",
"@sentry/server-runtime-injection": "11.17.0",
"@sentry/server-utils": "11.17.0",
@@ -76,6 +94,8 @@
},
"devDependencies": {
"@sentry-internal/rollup-utils": "11.17.0",
+ "@sentry/bun": "11.17.0",
+ "@sentry/deno": "11.17.0",
"astro": "^4.16.19",
"vite": "^8.3.6"
},
diff --git a/packages/astro/rollup.npm.config.mjs b/packages/astro/rollup.npm.config.mjs
index 65e59feac11a..1736189e9008 100644
--- a/packages/astro/rollup.npm.config.mjs
+++ b/packages/astro/rollup.npm.config.mjs
@@ -4,6 +4,8 @@ const variants = makeNPMConfigVariants(
makeBaseNPMConfig({
entrypoints: [
'src/index.server.ts',
+ 'src/index.bun.ts',
+ 'src/index.deno.ts',
'src/index.client.ts',
'src/index.worker.ts',
'src/index.workerd.ts',
diff --git a/packages/astro/src/index.bun.ts b/packages/astro/src/index.bun.ts
new file mode 100644
index 000000000000..ecde81973b74
--- /dev/null
+++ b/packages/astro/src/index.bun.ts
@@ -0,0 +1,30 @@
+import { bunHttpServerIntegration, fetchIntegration } from '@sentry/bun';
+import { _INTERNAL_captureOptionsSetByUser } from '@sentry/core';
+import type { NodeClient, NodeOptions } from '@sentry/node';
+import { init as initServer } from './server/sdk';
+
+// oxlint-disable-next-line typescript/no-deprecated
+export { default } from './index.server';
+export * from './index.server';
+
+/** Inits the Sentry Astro SDK on Bun, with the integrations of `@sentry/bun` for what Bun does differently. */
+export function init(options: NodeOptions): NodeClient | undefined {
+ const userOptions = _INTERNAL_captureOptionsSetByUser(options);
+ const userIntegrations = userOptions.integrations;
+ return initServer({
+ runtime: { name: 'bun', version: process.versions.bun as string },
+ ...userOptions,
+ integrations: defaults => {
+ const integrations = [
+ // The `fetch` of Bun is not undici.
+ ...defaults.filter(integration => integration.name !== 'NodeFetch'),
+ fetchIntegration(),
+ // Bun does not publish `http.server.request.start`, which `httpIntegration` needs for request isolation and spans.
+ bunHttpServerIntegration(),
+ ];
+ return typeof userIntegrations === 'function'
+ ? userIntegrations(integrations)
+ : [...integrations, ...(userIntegrations || [])];
+ },
+ });
+}
diff --git a/packages/astro/src/index.deno.ts b/packages/astro/src/index.deno.ts
new file mode 100644
index 000000000000..42862026951f
--- /dev/null
+++ b/packages/astro/src/index.deno.ts
@@ -0,0 +1,28 @@
+import { _INTERNAL_captureOptionsSetByUser } from '@sentry/core';
+import { fetchIntegration } from '@sentry/deno';
+import type { NodeClient, NodeOptions } from '@sentry/node';
+import { init as initServer } from './server/sdk';
+
+// oxlint-disable-next-line typescript/no-deprecated
+export { default } from './index.server';
+export * from './index.server';
+
+/** Inits the Sentry Astro SDK on Deno, with the integrations of `@sentry/deno` for what Deno does differently. */
+export function init(options: NodeOptions): NodeClient | undefined {
+ const userOptions = _INTERNAL_captureOptionsSetByUser(options);
+ const userIntegrations = userOptions.integrations;
+ return initServer({
+ runtime: { name: 'deno', version: process.versions.deno as string },
+ ...userOptions,
+ integrations: defaults => {
+ const integrations = [
+ // The `fetch` of Deno is not undici.
+ ...defaults.filter(integration => integration.name !== 'NodeFetch'),
+ fetchIntegration(),
+ ];
+ return typeof userIntegrations === 'function'
+ ? userIntegrations(integrations)
+ : [...integrations, ...(userIntegrations || [])];
+ },
+ });
+}
diff --git a/packages/astro/src/integration/index.ts b/packages/astro/src/integration/index.ts
index 50f57a481cf8..19c38019cb68 100644
--- a/packages/astro/src/integration/index.ts
+++ b/packages/astro/src/integration/index.ts
@@ -1,7 +1,7 @@
import { sentryVitePlugin } from '@sentry/bundler-plugins/vite';
-import { warnOnRemovedBuildOptions } from '@sentry/core';
+import { resolveSourceMapsFeatures, warnOnRemovedBuildOptions } from '@sentry/core';
import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
-import type { AstroConfig, AstroIntegration, AstroIntegrationLogger } from 'astro';
+import type { AstroConfig, AstroIntegration } from 'astro';
import * as fs from 'fs';
import { createRequire } from 'module';
import * as path from 'path';
@@ -10,9 +10,13 @@ import { sentryCloudflareNodeWarningPlugin, sentryCloudflareVitePlugin } from '.
import { buildReleaseSnippet, getRuntimeRelease, makeServerReleaseVitePlugin } from './release';
import { makeServerInitVitePlugin, SENTRY_MIDDLEWARE_MODULE, SERVER_INIT_IMPORT } from './serverInit';
import { buildClientSnippet, buildSdkInitFileImportSnippet, buildServerSnippet } from './snippets';
+import { _getUpdatedSourceMapSettings, hasEnvironmentSourceMapSetting } from './sourceMaps';
import { getAstroTunnelOptions, makeTunnelOptionsVitePlugin, TUNNEL_OPTIONS_IMPORT } from './tunnel';
import type { SentryOptions } from './types';
+export { _getUpdatedSourceMapSettings } from './sourceMaps';
+export type { UserSourceMapSetting } from './sourceMaps';
+
const PKG_NAME = '@sentry/astro';
export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
@@ -62,74 +66,73 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
};
const sourceMapsNeeded = sdkEnabled.client || sdkEnabled.server;
- const shouldUploadSourcemaps = sourceMapsNeeded && sourcemaps?.disable !== true;
+ // TODO(v12): Add the Sentry plugin with `sourcemaps.disable: true` too, like with the options that replace it.
+ const shouldUploadSourcemaps = sourceMapsNeeded && resolveSourceMapsFeatures(sourcemaps).legacyDisable !== true;
// The plugin would inject the release into the client's startup chunks, which changes their hashes on every
// release and invalidates cached chunks. The page HTML carries it to the browser instead.
const runtimeRelease = shouldUploadSourcemaps && command !== 'dev' ? getRuntimeRelease(release) : undefined;
- // We don't need to check for AUTH_TOKEN here, because the plugin will pick it up from the env
if (shouldUploadSourcemaps && command !== 'dev') {
- const computedSourceMapSettings = _getUpdatedSourceMapSettings(config, options, logger);
+ const buildState: ViteBuildState = { writesCloudflareWorker: false };
+ const sourceMapState = { sdkEnabled: false };
+ const sdkEnabledSourceMaps = (environment?: string): boolean =>
+ sourceMapState.sdkEnabled && !hasEnvironmentSourceMapSetting(config, environment);
+ // A user's own glob replaces the SDK's deletion. Maps in a Cloudflare `_worker.js` folder
+ // stay, so that wrangler can read them for `upload_source_maps`.
+ // With `sourcemaps.delete` the bundler plugin ignores this option and warns if the user set it.
+ const deleteSourcemapsAfterUpload =
+ sourcemaps?.delete !== undefined
+ ? sourcemaps.deleteSourcemapsAfterUpload
+ : (sourcemaps?.deleteSourcemapsAfterUpload ??
+ (sourcemaps?.filesToDeleteAfterUpload === undefined
+ ? (environment?: string) =>
+ sdkEnabledSourceMaps(environment) && !buildState.writesCloudflareWorker ? true : undefined
+ : undefined));
+
+ const sentryPlugins = sentryVitePlugin({
+ applicationKey,
+ moduleMetadata,
+ // Priority: top-level options > env vars
+ org: org ?? env.SENTRY_ORG,
+ project: project ?? env.SENTRY_PROJECT,
+ authToken: authToken ?? env.SENTRY_AUTH_TOKEN,
+ url: sentryUrl ?? env.SENTRY_URL,
+ headers,
+ telemetry: telemetry ?? true,
+ silent: silent ?? false,
+ errorHandler,
+ _metaOptions: {
+ telemetry: {
+ metaFramework: 'astro',
+ },
+ },
+ debug: debug ?? false,
+ release: runtimeRelease ? { ...release, name: runtimeRelease, inject: false } : release,
+ sourcemaps: {
+ ...sourcemaps,
+ assets: sourcemaps?.assets ?? getSourcemapsAssetsGlobs(config),
+ deleteSourcemapsAfterUpload,
+ sdkEnabledSourceMaps,
+ },
+ bundleSizeOptimizations: {
+ ...bundleSizeOptimizations,
+ },
+ });
- let updatedFilesToDeleteAfterUpload: string[] | undefined = undefined;
-
- if (
- typeof sourcemaps?.filesToDeleteAfterUpload === 'undefined' &&
- computedSourceMapSettings.previousUserSourceMapSetting === 'unset'
- ) {
- // This also works for adapters, as the source maps are also copied to e.g. the .vercel folder.
- // Static output has no client folder and writes client assets to `/` instead.
- // Astro removes the hidden `.prerender` folder itself, but we don't want to rely on that.
- updatedFilesToDeleteAfterUpload = [
- './dist/**/client/**/*.map',
- './dist/**/server/**/*.map',
- `./dist/**/${config.build?.assets ?? '_astro'}/**/*.map`,
- './dist/**/.prerender/**/*.map',
- ];
-
- debug &&
- logger.info(
- `Automatically setting \`sourcemaps.filesToDeleteAfterUpload: ${JSON.stringify(
- updatedFilesToDeleteAfterUpload,
- )}\` to delete generated source maps after they were uploaded to Sentry.`,
- );
- }
+ const computedSourceMapSettings = _getUpdatedSourceMapSettings(config, options, logger);
+ sourceMapState.sdkEnabled =
+ computedSourceMapSettings.previousUserSourceMapSetting === 'unset' &&
+ computedSourceMapSettings.updatedSourceMapSetting === 'hidden';
updateConfig({
vite: {
- build: {
- sourcemap: computedSourceMapSettings.updatedSourceMapSetting,
- },
+ ...(computedSourceMapSettings.updatedSourceMapSetting === undefined
+ ? {}
+ : { build: { sourcemap: computedSourceMapSettings.updatedSourceMapSetting } }),
plugins: [
- sentryVitePlugin({
- applicationKey,
- moduleMetadata,
- // Priority: top-level options > env vars
- org: org ?? env.SENTRY_ORG,
- project: project ?? env.SENTRY_PROJECT,
- authToken: authToken ?? env.SENTRY_AUTH_TOKEN,
- url: sentryUrl ?? env.SENTRY_URL,
- headers,
- telemetry: telemetry ?? true,
- silent: silent ?? false,
- errorHandler,
- _metaOptions: {
- telemetry: {
- metaFramework: 'astro',
- },
- },
- debug: debug ?? false,
- release: runtimeRelease ? { ...release, name: runtimeRelease, inject: false } : release,
- sourcemaps: {
- ...sourcemaps,
- assets: sourcemaps?.assets ?? getSourcemapsAssetsGlobs(config),
- filesToDeleteAfterUpload: sourcemaps?.filesToDeleteAfterUpload ?? updatedFilesToDeleteAfterUpload,
- },
- bundleSizeOptimizations: {
- ...bundleSizeOptimizations,
- },
- }),
+ makeViteBuildStatePlugin(buildState),
+ sentryPlugins,
...(runtimeRelease ? [makeServerReleaseVitePlugin(runtimeRelease)] : []),
],
},
@@ -282,6 +285,26 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
};
};
+type ViteBuildState = {
+ /** The current Vite build writes the Worker of an older Cloudflare adapter to `_worker.js`. */
+ writesCloudflareWorker: boolean;
+};
+
+/**
+ * Records what the SDK needs to know about each Vite build. Its `config` hook runs before the one
+ * of the Sentry plugin, which reads `buildState` there.
+ */
+function makeViteBuildStatePlugin(buildState: ViteBuildState): VitePlugin {
+ return {
+ name: 'sentry-astro-vite-build-state',
+ apply: 'build',
+ enforce: 'post',
+ config(viteConfig) {
+ buildState.writesCloudflareWorker = /(?:^|[\\/])_worker\.js[\\/]*$/.test(viteConfig.build?.outDir ?? '');
+ },
+ };
+}
+
// Every sub-plugin of `sentryCloudflareVitePlugin()` but its orchestrion transform has this prefix,
// and some are added whatever its options are.
const CLOUDFLARE_VITE_PLUGIN_NAME_PREFIX = 'sentry-cloudflare-';
@@ -381,71 +404,3 @@ function getOutDirGlob(config: AstroConfig): string {
// fallback to default output dir
return 'dist';
}
-
-/**
- * Whether the user enabled (true, 'hidden', 'inline') or disabled (false) source maps
- */
-export type UserSourceMapSetting = 'enabled' | 'disabled' | 'unset' | undefined;
-
-/** There are 3 ways to set up source map generation (https://github.com/getsentry/sentry-javascript/issues/13993)
- *
- * 1. User explicitly disabled source maps
- * - keep this setting (emit a warning that errors won't be unminified in Sentry)
- * - We won't upload anything
- *
- * 2. Users enabled source map generation (true, 'hidden', 'inline').
- * - keep this setting (don't do anything - like deletion - besides uploading)
- *
- * 3. Users didn't set source maps generation
- * - we enable 'hidden' source maps generation
- * - configure `filesToDeleteAfterUpload` to delete all .map files (we emit a log about this)
- *
- * --> only exported for testing
- */
-export function _getUpdatedSourceMapSettings(
- astroConfig: AstroConfig,
- sentryOptions: SentryOptions | undefined,
- logger: AstroIntegrationLogger,
-): { previousUserSourceMapSetting: UserSourceMapSetting; updatedSourceMapSetting: boolean | 'inline' | 'hidden' } {
- let previousUserSourceMapSetting: UserSourceMapSetting = undefined;
-
- astroConfig.build = astroConfig.build || {};
-
- const viteSourceMap = astroConfig?.vite?.build?.sourcemap;
- let updatedSourceMapSetting = viteSourceMap;
-
- const settingKey = 'vite.build.sourcemap';
- const debug = sentryOptions?.debug;
-
- if (viteSourceMap === false) {
- previousUserSourceMapSetting = 'disabled';
- updatedSourceMapSetting = viteSourceMap;
-
- if (debug) {
- // Longer debug message with more details
- logger.warn(
- `Source map generation is currently disabled in your Astro configuration (\`${settingKey}: false\`). This setting is either a default setting or was explicitly set in your configuration. Sentry won't override this setting. Without source maps, code snippets on the Sentry Issues page will remain minified. To show unminified code, enable source maps in \`${settingKey}\` (e.g. by setting them to \`hidden\`).`,
- );
- } else {
- logger.warn('Source map generation is disabled in your Astro configuration.');
- }
- } else if (viteSourceMap && ['hidden', 'inline', true].includes(viteSourceMap)) {
- previousUserSourceMapSetting = 'enabled';
- updatedSourceMapSetting = viteSourceMap;
-
- debug &&
- logger.info(
- `We discovered \`${settingKey}\` is set to \`${viteSourceMap.toString()}\`. Sentry will keep this source map setting. This will un-minify the code snippet on the Sentry Issue page.`,
- );
- } else {
- previousUserSourceMapSetting = 'unset';
- updatedSourceMapSetting = 'hidden';
-
- debug &&
- logger.info(
- `Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`. The source maps will be deleted after they were uploaded to Sentry.`,
- );
- }
-
- return { previousUserSourceMapSetting, updatedSourceMapSetting };
-}
diff --git a/packages/astro/src/integration/middleware/index.ts b/packages/astro/src/integration/middleware/index.ts
index 76f977fa0966..238682e10434 100644
--- a/packages/astro/src/integration/middleware/index.ts
+++ b/packages/astro/src/integration/middleware/index.ts
@@ -2,7 +2,7 @@ import { handleRequest } from '../../server/middleware';
// The one `@sentry/astro` entry that resolves to server code on every runtime, so the integration's virtual module
// imports it from here.
-export { _INTERNAL_setTunnelDefaults } from '@sentry/core/server';
+export { setTunnelDefaults } from '@sentry/core/server';
type MiddlewareNext = () => Promise;
type MiddlewareHandler = (ctx: unknown, next: MiddlewareNext) => Promise | Response | Promise | void;
diff --git a/packages/astro/src/integration/sourceMaps.ts b/packages/astro/src/integration/sourceMaps.ts
new file mode 100644
index 000000000000..ff622bf5a338
--- /dev/null
+++ b/packages/astro/src/integration/sourceMaps.ts
@@ -0,0 +1,133 @@
+import { hasSourceMapUploadCredentials } from '@sentry/bundler-plugins/core';
+import { resolveSourceMapsFeatures } from '@sentry/core';
+import type { AstroConfig, AstroIntegrationLogger } from 'astro';
+import type { SentryOptions } from './types';
+
+/**
+ * Whether the user enabled (true, 'hidden', 'inline') or disabled (false) source maps
+ */
+export type UserSourceMapSetting = 'enabled' | 'disabled' | 'unset' | undefined;
+
+/** There are 3 ways to set up source map generation (https://github.com/getsentry/sentry-javascript/issues/13993)
+ *
+ * 1. User explicitly disabled source maps
+ * - keep this setting (emit a warning that errors won't be unminified in Sentry)
+ * - We won't upload anything
+ *
+ * 2. Users enabled source map generation (true, 'hidden', 'inline') or set `sourcemap` in the output options.
+ * - keep this setting (don't do anything - like deletion - besides uploading)
+ *
+ * 3. Users didn't set source maps generation
+ * - we enable 'hidden' source maps generation when Sentry can upload the maps, or when
+ * `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave it unset
+ * - we remove the maps from the build output, except in a Cloudflare `_worker.js` folder and
+ * with `sourcemaps.delete: false`
+ *
+ * --> only exported for testing
+ */
+export function _getUpdatedSourceMapSettings(
+ astroConfig: AstroConfig,
+ sentryOptions: SentryOptions | undefined,
+ logger: AstroIntegrationLogger,
+): {
+ previousUserSourceMapSetting: UserSourceMapSetting;
+ updatedSourceMapSetting: boolean | 'inline' | 'hidden' | undefined;
+} {
+ let previousUserSourceMapSetting: UserSourceMapSetting = undefined;
+
+ astroConfig.build = astroConfig.build || {};
+
+ const viteSourceMap = astroConfig?.vite?.build?.sourcemap;
+ const outputSourceMapSettings = getOutputSourceMapSettings(astroConfig?.vite?.build);
+ let updatedSourceMapSetting = viteSourceMap;
+
+ const settingKey = 'vite.build.sourcemap';
+ const debug = sentryOptions?.debug;
+
+ if (viteSourceMap === false) {
+ previousUserSourceMapSetting = 'disabled';
+ updatedSourceMapSetting = viteSourceMap;
+
+ if (debug) {
+ // Longer debug message with more details
+ logger.warn(
+ `Source map generation is currently disabled in your Astro configuration (\`${settingKey}: false\`). This setting is either a default setting or was explicitly set in your configuration. Sentry won't override this setting. Without source maps, code snippets on the Sentry Issues page will remain minified. To show unminified code, enable source maps in \`${settingKey}\` (e.g. by setting them to \`hidden\`).`,
+ );
+ } else {
+ logger.warn('Source map generation is disabled in your Astro configuration.');
+ }
+ } else if (viteSourceMap && ['hidden', 'inline', true].includes(viteSourceMap)) {
+ previousUserSourceMapSetting = 'enabled';
+ updatedSourceMapSetting = viteSourceMap;
+
+ debug &&
+ logger.info(
+ `We discovered \`${settingKey}\` is set to \`${viteSourceMap.toString()}\`. Sentry will keep this source map setting. This will un-minify the code snippet on the Sentry Issue page.`,
+ );
+ } else if (outputSourceMapSettings.length > 0) {
+ previousUserSourceMapSetting = outputSourceMapSettings.every(setting => setting === false) ? 'disabled' : 'enabled';
+ updatedSourceMapSetting = undefined;
+
+ debug &&
+ logger.info(
+ `We discovered \`sourcemap\` in the output options of \`vite.build\`, which overrides \`${settingKey}\`. Sentry will keep this source map setting.`,
+ );
+ } else {
+ previousUserSourceMapSetting = 'unset';
+ updatedSourceMapSetting = undefined;
+
+ const sourcemaps = sentryOptions?.sourcemaps;
+ const { injectDebugIds, upload, legacyDisable } = resolveSourceMapsFeatures(sourcemaps);
+
+ // Astro fixes the setting of the client build before the bundler plugin can turn source maps on.
+ // TODO(v12): Remove the `disable-upload` case along with `sourcemaps.disable`.
+ if (
+ (upload && hasSourceMapUploadCredentials(sentryOptions)) ||
+ legacyDisable === 'disable-upload' ||
+ (sourcemaps?.delete === false && injectDebugIds)
+ ) {
+ updatedSourceMapSetting = 'hidden';
+
+ debug &&
+ logger.info(
+ sourcemaps?.delete === false
+ ? `Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`. The source maps stay in the build output.`
+ : `Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`. The source maps will be deleted after they were uploaded to Sentry.`,
+ );
+ }
+ }
+
+ return { previousUserSourceMapSetting, updatedSourceMapSetting };
+}
+
+/**
+ * Whether the user set `build.sourcemap` for the given Vite environment.
+ * Astro copies the top-level setting into the `client` environment, so
+ * the bundler plugin also passes that name when the user set nothing there.
+ */
+export function hasEnvironmentSourceMapSetting(astroConfig: AstroConfig, environment: string | undefined): boolean {
+ if (environment === undefined) {
+ return false;
+ }
+ // Astro 4 types `vite` with Vite 5, which has no environments.
+ const vite = astroConfig.vite as
+ | { environments?: Record }
+ | undefined;
+ return vite?.environments?.[environment]?.build?.sourcemap !== undefined;
+}
+
+type OutputOptions = { sourcemap?: unknown };
+type BundlerOptions = { output?: OutputOptions | OutputOptions[] };
+
+/**
+ * The `sourcemap` settings of the bundler outputs, which override
+ * `vite.build.sourcemap`. Vite 8 reads both options.
+ */
+function getOutputSourceMapSettings(
+ build: { rollupOptions?: BundlerOptions; rolldownOptions?: BundlerOptions } | undefined,
+): unknown[] {
+ return [build?.rolldownOptions?.output ?? [], build?.rollupOptions?.output ?? []]
+ .flat()
+ .map(output => output.sourcemap)
+ .filter(setting => setting !== undefined);
+}
diff --git a/packages/astro/src/integration/tunnel.ts b/packages/astro/src/integration/tunnel.ts
index 33faad943393..9ec1ba864fd8 100644
--- a/packages/astro/src/integration/tunnel.ts
+++ b/packages/astro/src/integration/tunnel.ts
@@ -37,7 +37,7 @@ export function makeTunnelOptionsVitePlugin(tunnelOptions: BrowserTunnelOptions)
}
return options?.ssr
- ? `import { _INTERNAL_setTunnelDefaults } from '@sentry/astro/middleware';\n_INTERNAL_setTunnelDefaults(${stringifyForCodeInjection({ basePath: tunnelOptions.basePath })});`
+ ? `import { setTunnelDefaults } from '@sentry/astro/middleware';\nsetTunnelDefaults(${stringifyForCodeInjection({ basePath: tunnelOptions.basePath })});`
: `globalThis[${stringifyForCodeInjection(TUNNEL_OPTIONS_GLOBAL)}] = ${stringifyForCodeInjection(tunnelOptions)};`;
},
transform: (code, id) =>
diff --git a/packages/astro/src/server/middleware.ts b/packages/astro/src/server/middleware.ts
index 625ce1919e4a..4ed4c644b00b 100644
--- a/packages/astro/src/server/middleware.ts
+++ b/packages/astro/src/server/middleware.ts
@@ -28,6 +28,7 @@ import {
HTTP_SPAN_NAME_FALLBACK,
httpHeadersToSpanAttributes,
objectify,
+ SDK_VERSION,
setHttpStatus,
spanToJSON,
startSpan,
@@ -39,11 +40,7 @@ import {
filterCollectedUrlFragment,
filterCollectedUrlQuery,
} from '@sentry/core';
-import {
- flushIfServerless,
- _INTERNAL_getCacheOriginMetaTags,
- _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest,
-} from '@sentry/core/server';
+import { flushIfServerless, _INTERNAL_getCacheOriginMetaTags, handleServedTunnelRequest } from '@sentry/core/server';
import { setHttpServerSpanRouteAttribute } from '@sentry/server-utils';
import type { APIContext, MiddlewareHandler, MiddlewareNext, RoutePart } from 'astro';
@@ -77,6 +74,8 @@ function sendErrorToSentry(e: unknown): unknown {
return objectifiedErr;
}
+const SDK_NAME = 'sentry.javascript.astro';
+
type AstroLocalsWithSentry = Record & {
__sentry_wrapped__?: boolean;
};
@@ -87,7 +86,8 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareHandler =
return async (ctx, next) => {
// The middleware the integration adds runs the server init first, so this only bails without a server init, or when
// this middleware was added by hand and the request comes before any SSR page, which still runs the init.
- if (!getClient()) {
+ const client = getClient();
+ if (!client) {
return next();
}
@@ -96,6 +96,13 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareHandler =
return tunnelResponse;
}
+ // With `sentryCloudflareVitePlugin()` of `@sentry/cloudflare/vite`, `@sentry/cloudflare` inits the client.
+ const sdk = client.getOptions()._metadata?.sdk;
+ if (sdk && sdk.name !== SDK_NAME) {
+ sdk.name = SDK_NAME;
+ sdk.packages = [{ name: 'npm:@sentry/astro', version: SDK_VERSION }, ...(sdk.packages || [])];
+ }
+
// For static (prerendered) routes, we only want to inject the parametrized route meta tags
if (isPrerenderedRequest(ctx)) {
return handleStaticRoute(ctx, next);
diff --git a/packages/astro/src/tunnel.ts b/packages/astro/src/tunnel.ts
index 8658c09365e8..cdf3d872b04e 100644
--- a/packages/astro/src/tunnel.ts
+++ b/packages/astro/src/tunnel.ts
@@ -1,5 +1,5 @@
import type { BrowserTunnelOptions, Options } from '@sentry/core';
-import { _INTERNAL_applyBrowserTunnelDefaults as applyBrowserTunnelDefaults, GLOBAL_OBJ } from '@sentry/core';
+import { applyBrowserTunnelDefaults, GLOBAL_OBJ } from '@sentry/core';
/** Set by the Sentry Astro integration from the `base` and `trailingSlash` config. */
export const TUNNEL_OPTIONS_GLOBAL = '__sentry_astro_tunnel_options';
diff --git a/packages/astro/test/integration/index.files.test.ts b/packages/astro/test/integration/index.files.test.ts
index 39ca0ef66ed9..1a397f558a7b 100644
--- a/packages/astro/test/integration/index.files.test.ts
+++ b/packages/astro/test/integration/index.files.test.ts
@@ -9,7 +9,8 @@ vi.mock('fs', async requireActual => {
});
// Without a configured name, the real resolver falls back to the git revision of this checkout.
-vi.mock('@sentry/bundler-plugins/core', () => ({
+vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({
+ ...(await importOriginal>()),
resolveReleaseName: (name?: string) => name,
}));
diff --git a/packages/astro/test/integration/index.test.ts b/packages/astro/test/integration/index.test.ts
index e841abd43a97..c918b3905ade 100644
--- a/packages/astro/test/integration/index.test.ts
+++ b/packages/astro/test/integration/index.test.ts
@@ -4,16 +4,26 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { _getUpdatedSourceMapSettings, sentryAstro } from '../../src/integration';
import type { SentryOptions } from '../../src/integration/types';
-const sentryVitePluginSpy = vi.fn(() => 'sentryVitePlugin');
+type CapturedSourcemapsOptions = {
+ deleteSourcemapsAfterUpload?: boolean | ((environment?: string) => boolean | undefined);
+ sdkEnabledSourceMaps?: (environment?: string) => boolean;
+};
+
+let capturedSourcemapsOptions: CapturedSourcemapsOptions | undefined;
+
+const sentryVitePluginSpy = vi.fn((options: { sourcemaps?: CapturedSourcemapsOptions }) => {
+ capturedSourcemapsOptions = options.sourcemaps;
+ return 'sentryVitePlugin';
+});
vi.mock('@sentry/bundler-plugins/vite', () => ({
- // @ts-expect-error - just mocking around
- sentryVitePlugin: vi.fn(args => sentryVitePluginSpy(args)),
+ sentryVitePlugin: vi.fn((args: { sourcemaps?: CapturedSourcemapsOptions }) => sentryVitePluginSpy(args)),
}));
// Without a configured name, the real resolver falls back to the git revision of this checkout.
const resolveReleaseName = vi.fn((name?: string) => name);
-vi.mock('@sentry/bundler-plugins/core', () => ({
+vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({
+ ...(await importOriginal>()),
resolveReleaseName: (name?: string) => resolveReleaseName(name),
}));
@@ -89,7 +99,7 @@ describe('sentryAstro integration', () => {
expect(integration.name).toBe('@sentry/astro');
});
- it('enables "hidden" source maps, adds filesToDeleteAfterUpload and adds the sentry vite plugin if an auth token is detected', async () => {
+ it('enables "hidden" source maps, asks for their deletion and adds the sentry vite plugin if an auth token is detected', async () => {
const integration = sentryAstro({
org: 'my-org',
project: 'my-project',
@@ -107,7 +117,7 @@ describe('sentryAstro integration', () => {
build: {
sourcemap: 'hidden',
},
- plugins: ['sentryVitePlugin'],
+ plugins: [expect.objectContaining({ name: 'sentry-astro-vite-build-state' }), 'sentryVitePlugin'],
},
});
expect(updateConfig).toHaveBeenCalledWith({
@@ -127,12 +137,8 @@ describe('sentryAstro integration', () => {
bundleSizeOptimizations: {},
sourcemaps: {
assets: ['out/**/*', 'out/**/.prerender/**/*'],
- filesToDeleteAfterUpload: [
- './dist/**/client/**/*.map',
- './dist/**/server/**/*.map',
- './dist/**/_astro/**/*.map',
- './dist/**/.prerender/**/*.map',
- ],
+ deleteSourcemapsAfterUpload: expect.any(Function),
+ sdkEnabledSourceMaps: expect.any(Function),
},
_metaOptions: {
telemetry: {
@@ -163,12 +169,8 @@ describe('sentryAstro integration', () => {
bundleSizeOptimizations: {},
sourcemaps: {
assets: ['dist/**/*', 'dist/**/.prerender/**/*'],
- filesToDeleteAfterUpload: [
- './dist/**/client/**/*.map',
- './dist/**/server/**/*.map',
- './dist/**/_astro/**/*.map',
- './dist/**/.prerender/**/*.map',
- ],
+ deleteSourcemapsAfterUpload: expect.any(Function),
+ sdkEnabledSourceMaps: expect.any(Function),
},
_metaOptions: {
telemetry: {
@@ -207,12 +209,8 @@ describe('sentryAstro integration', () => {
bundleSizeOptimizations: {},
sourcemaps: {
assets: ['{.vercel,dist}/**/*', '{.vercel,dist}/**/.prerender/**/*'],
- filesToDeleteAfterUpload: [
- './dist/**/client/**/*.map',
- './dist/**/server/**/*.map',
- './dist/**/_astro/**/*.map',
- './dist/**/.prerender/**/*.map',
- ],
+ deleteSourcemapsAfterUpload: expect.any(Function),
+ sdkEnabledSourceMaps: expect.any(Function),
},
_metaOptions: {
telemetry: {
@@ -251,12 +249,8 @@ describe('sentryAstro integration', () => {
bundleSizeOptimizations: {},
sourcemaps: {
assets: ['dist/server/**/*, dist/client/**/*'],
- filesToDeleteAfterUpload: [
- './dist/**/client/**/*.map',
- './dist/**/server/**/*.map',
- './dist/**/_astro/**/*.map',
- './dist/**/.prerender/**/*.map',
- ],
+ deleteSourcemapsAfterUpload: expect.any(Function),
+ sdkEnabledSourceMaps: expect.any(Function),
},
_metaOptions: {
telemetry: {
@@ -267,7 +261,7 @@ describe('sentryAstro integration', () => {
);
});
- it('prefers user-specified filesToDeleteAfterUpload over the default values', async () => {
+ it('lets user-specified filesToDeleteAfterUpload replace the SDK deletion', async () => {
const integration = sentryAstro({
org: 'my-org',
project: 'my-project',
@@ -289,11 +283,202 @@ describe('sentryAstro integration', () => {
expect.objectContaining({
sourcemaps: expect.objectContaining({
filesToDeleteAfterUpload: ['./custom/path/**/*'],
+ deleteSourcemapsAfterUpload: undefined,
}),
}),
);
});
+ describe('deleteSourcemapsAfterUpload', () => {
+ async function runSetup(options: SentryOptions, astroConfig: Partial = {}): Promise {
+ const integration = sentryAstro({ org: 'my-org', project: 'my-project', ...options });
+ // @ts-expect-error - the hook exists, and we only need to pass what we actually use
+ await integration.hooks['astro:config:setup']({
+ ...baseConfigHookObject,
+ updateConfig,
+ injectScript,
+ config: astroConfig as AstroConfig,
+ });
+ }
+
+ function expectSourcemapsOptions({ sdkEnabledSourceMaps, ...sourcemaps }: Record): void {
+ expect(sentryVitePluginSpy).toHaveBeenCalledTimes(1);
+ expect(sentryVitePluginSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ sourcemaps: expect.objectContaining(sourcemaps) }),
+ );
+ expect(capturedSourcemapsOptions?.sdkEnabledSourceMaps?.()).toBe(sdkEnabledSourceMaps);
+ }
+
+ // The bundler plugin calls the function form in its `config` hook, after the build state
+ // plugin ran.
+ function runBuildStatePlugin(viteConfig: { build?: { outDir?: string } }): void {
+ const plugin = updateConfig.mock.calls
+ .flatMap(([astroConfigUpdate]) => astroConfigUpdate.vite?.plugins ?? [])
+ .find(plugin => plugin?.name === 'sentry-astro-vite-build-state');
+ plugin.config(viteConfig);
+ }
+
+ function expectDeleteOption(value: boolean | undefined): void {
+ expect(sentryVitePluginSpy).toHaveBeenCalledTimes(1);
+ const option = capturedSourcemapsOptions?.deleteSourcemapsAfterUpload;
+ expect(typeof option === 'function' ? option() : option).toBe(value);
+ }
+
+ it('is `true` when the SDK enabled the source maps', async () => {
+ await runSetup({});
+ runBuildStatePlugin({ build: { outDir: 'dist/' } });
+ expectDeleteOption(true);
+ });
+
+ // Older Cloudflare adapters write the Worker there, and wrangler reads its maps.
+ it.each(['dist/_worker.js/', '/path/to/project/dist/_worker.js', 'C:\\project\\dist\\_worker.js\\'])(
+ 'is not set for a build into `%s`',
+ async outDir => {
+ await runSetup({});
+ runBuildStatePlugin({ build: { outDir } });
+ expectDeleteOption(undefined);
+
+ runBuildStatePlugin({ build: { outDir: 'dist/' } });
+ expectDeleteOption(true);
+ },
+ );
+
+ it('lets a user-set `true` remove the maps of a Cloudflare `_worker.js` build', async () => {
+ await runSetup({ sourcemaps: { deleteSourcemapsAfterUpload: true } });
+ runBuildStatePlugin({ build: { outDir: 'dist/_worker.js/' } });
+ expectDeleteOption(true);
+ });
+
+ it.each(['hidden', true] as const)('is not set when the user set `vite.build.sourcemap: %s`', async sourcemap => {
+ await runSetup({}, { vite: { build: { sourcemap } } });
+ expectDeleteOption(undefined);
+ });
+
+ it.each([
+ [true, undefined],
+ [false, undefined],
+ [true, 'hidden'],
+ [false, 'hidden'],
+ ] as const)('passes a user-set `%s` through when `vite.build.sourcemap` is `%s`', async (value, sourcemap) => {
+ await runSetup({ sourcemaps: { deleteSourcemapsAfterUpload: value } }, { vite: { build: { sourcemap } } });
+ expectDeleteOption(value);
+ });
+
+ it('is not set when the user set `filesToDeleteAfterUpload`', async () => {
+ await runSetup({ sourcemaps: { filesToDeleteAfterUpload: ['./dist/**/*.map'] } });
+ expectDeleteOption(undefined);
+ });
+
+ it('lets a user-set `true` win over the user glob', async () => {
+ await runSetup({
+ sourcemaps: { deleteSourcemapsAfterUpload: true, filesToDeleteAfterUpload: ['./dist/**/*.map'] },
+ });
+ expectDeleteOption(true);
+ });
+
+ // Then the plugin removes all of these maps, also those of chunks outside the user's
+ // `assets` or `ignore`.
+ it('marks the source maps as SDK-enabled when the user narrowed the upload', async () => {
+ await runSetup({ sourcemaps: { assets: ['./dist/client/**/*'], ignore: ['**/vendor/**'] } });
+ expectSourcemapsOptions({
+ assets: ['./dist/client/**/*'],
+ ignore: ['**/vendor/**'],
+ sdkEnabledSourceMaps: true,
+ });
+ expectDeleteOption(true);
+ });
+
+ // The output setting overrides `vite.build.sourcemap`, so these maps are the user's.
+ it.each([
+ { rollupOptions: { output: { sourcemap: true } } },
+ { rollupOptions: { output: [{}, { sourcemap: 'hidden' }] } },
+ { rolldownOptions: { output: { sourcemap: false } } },
+ ] as const)('leaves the source maps to the user with the output options %j', async build => {
+ await runSetup({}, { vite: { build } } as Partial);
+ expectViteSourceMapSetting(undefined);
+ expectSourcemapsOptions({ sdkEnabledSourceMaps: false });
+ expectDeleteOption(undefined);
+ });
+
+ // Astro copies the top-level setting into the `client` environment.
+ it('marks the source maps of the `client` environment as SDK-enabled', async () => {
+ await runSetup({});
+ runBuildStatePlugin({ build: { outDir: 'dist/' } });
+ expect(capturedSourcemapsOptions?.sdkEnabledSourceMaps?.('client')).toBe(true);
+ const option = capturedSourcemapsOptions?.deleteSourcemapsAfterUpload;
+ expect(typeof option === 'function' ? option('client') : option).toBe(true);
+ });
+
+ it('does not mark the source maps of an environment the user set as SDK-enabled', async () => {
+ await runSetup({}, {
+ vite: { environments: { client: { build: { sourcemap: true } } } },
+ } as Partial);
+ runBuildStatePlugin({ build: { outDir: 'dist/' } });
+ expect(capturedSourcemapsOptions?.sdkEnabledSourceMaps?.('client')).toBe(false);
+ const option = capturedSourcemapsOptions?.deleteSourcemapsAfterUpload;
+ expect(typeof option === 'function' ? option('client') : option).toBeUndefined();
+ expectSourcemapsOptions({ sdkEnabledSourceMaps: true });
+ expectDeleteOption(true);
+ });
+
+ it.each(['hidden', true, false] as const)(
+ 'does not mark source maps as SDK-enabled when the user set `vite.build.sourcemap: %s`',
+ async sourcemap => {
+ await runSetup({}, { vite: { build: { sourcemap } } });
+ expectSourcemapsOptions({ sdkEnabledSourceMaps: false });
+ },
+ );
+
+ // The maps are removed in this mode too, after the plugin stamps the debug IDs.
+ it("is `true` with `disable: 'disable-upload'`", async () => {
+ await runSetup({ sourcemaps: { disable: 'disable-upload' } });
+ expectSourcemapsOptions({ disable: 'disable-upload', sdkEnabledSourceMaps: true });
+ expectDeleteOption(true);
+ });
+
+ function expectViteSourceMapSetting(sourcemap: 'hidden' | undefined): void {
+ const viteConfigUpdate = updateConfig.mock.calls
+ .map(([astroConfigUpdate]) => astroConfigUpdate.vite)
+ .find(vite =>
+ vite?.plugins?.some((plugin: { name?: string }) => plugin?.name === 'sentry-astro-vite-build-state'),
+ );
+ expect(viteConfigUpdate?.build?.sourcemap).toBe(sourcemap);
+ }
+
+ it.each([{ upload: false }, { injectDebugIds: false }])(
+ 'adds the plugin, turns no source maps on and asks for no deletion with %j',
+ async sourcemaps => {
+ await runSetup({ sourcemaps });
+ expectSourcemapsOptions({ ...sourcemaps, sdkEnabledSourceMaps: false });
+ expectDeleteOption(undefined);
+ expectViteSourceMapSetting(undefined);
+ },
+ );
+
+ // The bundler plugin must only see the `deleteSourcemapsAfterUpload` the user set, because it
+ // warns when both options are set.
+ it.each([
+ [{ delete: true }, 'hidden', undefined],
+ [{ delete: false }, 'hidden', undefined],
+ [{ upload: false, delete: false }, 'hidden', undefined],
+ [{ upload: false, delete: true }, undefined, undefined],
+ [{ injectDebugIds: false, delete: false }, undefined, undefined],
+ [{ delete: false, deleteSourcemapsAfterUpload: true }, 'hidden', true],
+ ] as const)('with %j it sets the source map setting to %s', async (sourcemaps, setting, deleteAfterUpload) => {
+ await runSetup({ sourcemaps });
+ expectSourcemapsOptions({ ...sourcemaps, sdkEnabledSourceMaps: setting === 'hidden' });
+ expect(capturedSourcemapsOptions?.deleteSourcemapsAfterUpload).toBe(deleteAfterUpload);
+ expectViteSourceMapSetting(setting);
+ });
+
+ it('enables hidden source maps when `upload: true` replaces `disable: true`', async () => {
+ await runSetup({ sourcemaps: { disable: true, upload: true } });
+ expectSourcemapsOptions({ sdkEnabledSourceMaps: true });
+ expectDeleteOption(true);
+ expectViteSourceMapSetting('hidden');
+ });
+ });
+
it('ignores the removed `sourceMapsUploadOptions` when computing the vite plugin options', async () => {
const integration = sentryAstro({
org: 'my-org',
@@ -872,7 +1057,7 @@ describe('_getUpdatedSourceMapSettings', () => {
beforeEach(() => {
astroConfig = { vite: { build: {} } } as Omit & { vite: { build: { sourcemap?: any } } };
- sentryOptions = {};
+ sentryOptions = { org: 'my-org', project: 'my-project' };
logger = {
info: vi.fn(),
warn: vi.fn(),
@@ -901,6 +1086,17 @@ describe('_getUpdatedSourceMapSettings', () => {
});
});
+ it.each([
+ [{ rollupOptions: { output: { sourcemap: true } } }, 'enabled'],
+ [{ rolldownOptions: { output: [{ sourcemap: 'hidden' }, { sourcemap: false }] } }, 'enabled'],
+ [{ rollupOptions: { output: { sourcemap: false } } }, 'disabled'],
+ ] as const)('keeps the output options %j as a user setting', (build, expected) => {
+ astroConfig = { vite: { build } } as unknown as typeof astroConfig;
+ const result = _getUpdatedSourceMapSettings(astroConfig, sentryOptions, logger);
+ expect(result.previousUserSourceMapSetting).toBe(expected);
+ expect(result.updatedSourceMapSetting).toBeUndefined();
+ });
+
it('should enable "hidden" source maps when unset', () => {
astroConfig.vite.build.sourcemap = undefined;
const result = _getUpdatedSourceMapSettings(astroConfig, sentryOptions, logger);
@@ -908,6 +1104,41 @@ describe('_getUpdatedSourceMapSettings', () => {
expect(result.updatedSourceMapSetting).toBe('hidden');
});
+ it.each([
+ [{ upload: false }, undefined],
+ [{ injectDebugIds: false }, undefined],
+ [{ delete: true }, 'hidden'],
+ [{ delete: false }, 'hidden'],
+ [{ upload: false, delete: false }, 'hidden'],
+ [{ upload: false, delete: true }, undefined],
+ [{ injectDebugIds: false, delete: false }, undefined],
+ [{ upload: true }, 'hidden'],
+ [{ disable: 'disable-upload' }, 'hidden'],
+ ] as const)('with unset source maps and %j it returns %s', (sourcemaps, expected) => {
+ const result = _getUpdatedSourceMapSettings(astroConfig, { ...sentryOptions, sourcemaps }, logger);
+ expect(result.previousUserSourceMapSetting).toBe('unset');
+ expect(result.updatedSourceMapSetting).toBe(expected);
+ });
+
+ it.each<[SentryOptions, 'hidden' | undefined]>([
+ [{ project: 'my-project' }, undefined],
+ [{ org: 'my-org' }, undefined],
+ [{ project: 'my-project', authToken: 'sntrys_token' }, 'hidden'],
+ [{ org: 'my-org', project: ['my-project'] }, 'hidden'],
+ [{ project: 'my-project', sourcemaps: { delete: false } }, 'hidden'],
+ [{ project: 'my-project', sourcemaps: { disable: 'disable-upload' } }, 'hidden'],
+ ])('with unset source maps and the options %j it returns %s', (options, expected) => {
+ const result = _getUpdatedSourceMapSettings(astroConfig, options, logger);
+ expect(result.updatedSourceMapSetting).toBe(expected);
+ });
+
+ it('returns undefined for unset source maps without an auth token', () => {
+ vi.stubEnv('SENTRY_AUTH_TOKEN', '');
+ const result = _getUpdatedSourceMapSettings(astroConfig, sentryOptions, logger);
+ vi.unstubAllEnvs();
+ expect(result.updatedSourceMapSetting).toBeUndefined();
+ });
+
it('should log warnings and messages when debug is enabled', () => {
sentryOptions = { debug: true };
diff --git a/packages/astro/test/server/bunSdk.test.ts b/packages/astro/test/server/bunSdk.test.ts
new file mode 100644
index 000000000000..003fd9f0d93c
--- /dev/null
+++ b/packages/astro/test/server/bunSdk.test.ts
@@ -0,0 +1,72 @@
+import type { Integration } from '@sentry/core';
+import { getMainCarrier } from '@sentry/core';
+import { afterEach, describe, expect, it } from 'vitest';
+import { init } from '../../src/index.bun';
+
+const originalVersions = Object.getOwnPropertyDescriptor(process, 'versions')!;
+
+// Without a DSN, the client does not set up its integrations, so these tests do not patch `node:http`.
+describe('Bun init()', () => {
+ afterEach(() => {
+ Object.defineProperty(process, 'versions', originalVersions);
+ getMainCarrier().__SENTRY__ = undefined;
+ });
+
+ it('reports Bun as the runtime', () => {
+ Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun: '1.4.5' } });
+
+ const client = init({});
+
+ expect(client?.getOptions().runtime).toEqual({ name: 'bun', version: '1.4.5' });
+ });
+
+ it('inits the Astro SDK', () => {
+ const client = init({});
+
+ expect(client?.getOptions()._metadata?.sdk?.name).toBe('sentry.javascript.astro');
+ });
+
+ it('replaces the undici fetch integration with the fetch and HTTP server integrations of Bun', () => {
+ const client = init({});
+
+ expect(
+ client
+ ?.getOptions()
+ .integrations.map(integration => integration.name)
+ .filter(name => ['NodeFetch', 'Fetch', 'BunHttpServer'].includes(name)),
+ ).toEqual(['Fetch', 'BunHttpServer']);
+ });
+
+ it('adds the integrations that the user passes as an array', () => {
+ const userIntegration: Integration = { name: 'UserIntegration' };
+
+ const client = init({ integrations: [userIntegration] });
+
+ expect(
+ client
+ ?.getOptions()
+ .integrations.map(integration => integration.name)
+ .filter(name => ['NodeFetch', 'Fetch', 'BunHttpServer', 'UserIntegration'].includes(name)),
+ ).toEqual(['Fetch', 'BunHttpServer', 'UserIntegration']);
+ });
+
+ it('passes the Bun integrations to an integrations function of the user', () => {
+ const client = init({
+ integrations: integrations => integrations.filter(integration => integration.name !== 'BunHttpServer'),
+ });
+
+ expect(
+ client
+ ?.getOptions()
+ .integrations.map(integration => integration.name)
+ .filter(name => ['NodeFetch', 'Fetch', 'BunHttpServer'].includes(name)),
+ ).toEqual(['Fetch']);
+ });
+
+ it('does not report the Bun runtime and integrations as set by the user', () => {
+ const client = init({ integrations: integrations => integrations });
+
+ expect(client?.getSdkMetadata()?.optionsSetByUser).toEqual(['integrations']);
+ expect(client?.getSdkMetadata()?.integrationsSetByUser).toEqual([]);
+ });
+});
diff --git a/packages/astro/test/server/denoSdk.test.ts b/packages/astro/test/server/denoSdk.test.ts
new file mode 100644
index 000000000000..45ebcb307075
--- /dev/null
+++ b/packages/astro/test/server/denoSdk.test.ts
@@ -0,0 +1,72 @@
+import type { Integration } from '@sentry/core';
+import { getMainCarrier } from '@sentry/core';
+import { afterEach, describe, expect, it } from 'vitest';
+import { init } from '../../src/index.deno';
+
+const originalVersions = Object.getOwnPropertyDescriptor(process, 'versions')!;
+
+// Without a DSN, the client does not set up its integrations, so these tests do not patch `node:http`.
+describe('Deno init()', () => {
+ afterEach(() => {
+ Object.defineProperty(process, 'versions', originalVersions);
+ getMainCarrier().__SENTRY__ = undefined;
+ });
+
+ it('reports Deno as the runtime', () => {
+ Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, deno: '2.9.0' } });
+
+ const client = init({});
+
+ expect(client?.getOptions().runtime).toEqual({ name: 'deno', version: '2.9.0' });
+ });
+
+ it('inits the Astro SDK', () => {
+ const client = init({});
+
+ expect(client?.getOptions()._metadata?.sdk?.name).toBe('sentry.javascript.astro');
+ });
+
+ it('replaces the undici fetch integration with the fetch integration of Deno', () => {
+ const client = init({});
+
+ expect(
+ client
+ ?.getOptions()
+ .integrations.map(integration => integration.name)
+ .filter(name => ['NodeFetch', 'Fetch'].includes(name)),
+ ).toEqual(['Fetch']);
+ });
+
+ it('adds the integrations that the user passes as an array', () => {
+ const userIntegration: Integration = { name: 'UserIntegration' };
+
+ const client = init({ integrations: [userIntegration] });
+
+ expect(
+ client
+ ?.getOptions()
+ .integrations.map(integration => integration.name)
+ .filter(name => ['NodeFetch', 'Fetch', 'UserIntegration'].includes(name)),
+ ).toEqual(['Fetch', 'UserIntegration']);
+ });
+
+ it('passes the Deno integrations to an integrations function of the user', () => {
+ const client = init({
+ integrations: integrations => integrations.filter(integration => integration.name !== 'Fetch'),
+ });
+
+ expect(
+ client
+ ?.getOptions()
+ .integrations.map(integration => integration.name)
+ .filter(name => ['NodeFetch', 'Fetch'].includes(name)),
+ ).toEqual([]);
+ });
+
+ it('does not report the Deno runtime and integrations as set by the user', () => {
+ const client = init({ integrations: integrations => integrations });
+
+ expect(client?.getSdkMetadata()?.optionsSetByUser).toEqual(['integrations']);
+ expect(client?.getSdkMetadata()?.integrationsSetByUser).toEqual([]);
+ });
+});
diff --git a/packages/astro/test/server/middleware.test.ts b/packages/astro/test/server/middleware.test.ts
index 082c9af75ef7..b9d50b76e7e4 100644
--- a/packages/astro/test/server/middleware.test.ts
+++ b/packages/astro/test/server/middleware.test.ts
@@ -38,7 +38,7 @@ describe('sentryMiddleware with the managed tunnel', () => {
const getClientSpy = vi.spyOn(SentryCore, 'getClient').mockReturnValue({} as Client);
const tunnelResponse = new Response('forwarded');
const matcherSpy = vi
- .spyOn(SentryCoreServer, '_INTERNAL_handleServedTunnelRequest')
+ .spyOn(SentryCoreServer, 'handleServedTunnelRequest')
.mockReturnValue(Promise.resolve(tunnelResponse));
const next = vi.fn();
const request = new Request('https://myDomain.io/abc123', { method: 'POST' });
@@ -227,6 +227,37 @@ describe('sentryMiddleware', () => {
});
});
+ it('sets the Astro SDK name on a client that another SDK inited', async () => {
+ const sdk = {
+ name: 'sentry.javascript.cloudflare',
+ packages: [{ name: 'npm:@sentry/cloudflare', version: SentryCore.SDK_VERSION }],
+ version: SentryCore.SDK_VERSION,
+ };
+ vi.spyOn(SentryCore, 'getClient').mockImplementation(
+ () =>
+ ({
+ getOptions: () => ({ _metadata: { sdk } }),
+ getDataCollectionOptions: () => DATA_COLLECTION_DEFAULTS,
+ }) as unknown as Client,
+ );
+ const middleware = handleRequest();
+ const ctx = { ...DYNAMIC_REQUEST_CONTEXT, routePattern: '/users' };
+
+ // @ts-expect-error, a partial ctx object is fine here
+ await middleware(ctx, () => Promise.resolve(new Response('ok')));
+ // @ts-expect-error, a partial ctx object is fine here
+ await middleware(ctx, () => Promise.resolve(new Response('ok')));
+
+ expect(sdk).toEqual({
+ name: 'sentry.javascript.astro',
+ packages: [
+ { name: 'npm:@sentry/astro', version: SentryCore.SDK_VERSION },
+ { name: 'npm:@sentry/cloudflare', version: SentryCore.SDK_VERSION },
+ ],
+ version: SentryCore.SDK_VERSION,
+ });
+ });
+
it("sets source route if the url couldn't be decoded correctly", async () => {
const middleware = handleRequest();
const ctx = {
diff --git a/packages/aws-serverless/package.json b/packages/aws-serverless/package.json
index 52eab180ffe1..6d2b58237e7e 100644
--- a/packages/aws-serverless/package.json
+++ b/packages/aws-serverless/package.json
@@ -66,7 +66,7 @@
"access": "public"
},
"dependencies": {
- "@sentry/conventions": "^0.35.0",
+ "@sentry/conventions": "^0.36.0",
"@sentry/core": "11.17.0",
"@sentry/node": "11.17.0",
"@sentry/server-runtime-injection": "11.17.0",
diff --git a/packages/aws-serverless/src/tunnel.ts b/packages/aws-serverless/src/tunnel.ts
index 927cc927de82..bfe4c94e2c5c 100644
--- a/packages/aws-serverless/src/tunnel.ts
+++ b/packages/aws-serverless/src/tunnel.ts
@@ -1,9 +1,5 @@
import { debug } from '@sentry/core';
-import {
- _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest,
- _INTERNAL_isServedTunnelRequest as isServedTunnelRequest,
- _INTERNAL_pickForwardedHeaders as pickForwardedHeaders,
-} from '@sentry/core/server';
+import { handleServedTunnelRequest, isServedTunnelRequest, pickForwardedHeaders } from '@sentry/core/server';
import { DEBUG_BUILD } from './debug-build';
/**
diff --git a/packages/browser-utils/.oxlintrc.json b/packages/browser-utils/.oxlintrc.json
index a0967ad5a718..a5c0bddd3943 100644
--- a/packages/browser-utils/.oxlintrc.json
+++ b/packages/browser-utils/.oxlintrc.json
@@ -1,6 +1,6 @@
{
"$schema": "../../node_modules/oxlint/configuration_schema.json",
- "extends": ["../../.oxlintrc.base.json"],
+ "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"],
"env": {
"browser": true
},
@@ -8,8 +8,7 @@
{
"files": ["src/metrics/**"],
"rules": {
- "typescript/explicit-function-return-type": "off",
- "typescript/no-non-null-assertion": "off"
+ "typescript/explicit-function-return-type": "off"
}
}
]
diff --git a/packages/browser-utils/package.json b/packages/browser-utils/package.json
index e10b60b891e8..717c06838333 100644
--- a/packages/browser-utils/package.json
+++ b/packages/browser-utils/package.json
@@ -34,7 +34,7 @@
},
"dependencies": {
"@sentry/core": "11.17.0",
- "@sentry/conventions": "^0.35.0",
+ "@sentry/conventions": "^0.36.0",
"web-vitals": "^6.2.3"
},
"devDependencies": {
diff --git a/packages/browser-utils/src/htmlTreeAsString.ts b/packages/browser-utils/src/htmlTreeAsString.ts
index 46dcc493a431..d8652ef7f5cf 100644
--- a/packages/browser-utils/src/htmlTreeAsString.ts
+++ b/packages/browser-utils/src/htmlTreeAsString.ts
@@ -15,7 +15,7 @@ type SimpleNode = {
type AccessorKey = 'parentNode' | 'tagName' | 'id' | 'className' | 'getAttribute' | 'dataset';
const accessors: Partial> = {};
-// oxlint-disable typescript/unbound-method
+// oxlint-disable typescript/unbound-method, typescript/no-non-null-assertion -- a missing descriptor throws into the catch below
try {
if (typeof Node !== 'undefined') {
accessors.parentNode = Object.getOwnPropertyDescriptor(Node.prototype, 'parentNode')!.get!;
@@ -33,7 +33,7 @@ try {
// Polyfilled or stubbed prototypes may not have the expected descriptors.
// _safeRead falls back to direct property access.
}
-// oxlint-enable typescript/unbound-method
+// oxlint-enable typescript/unbound-method, typescript/no-non-null-assertion
function _safeRead(el: unknown, prop: AccessorKey, arg?: string): T {
const fn = accessors[prop];
diff --git a/packages/browser-utils/src/web-vitals/emitSpan.ts b/packages/browser-utils/src/web-vitals/emitSpan.ts
index 90b11673e1b6..289858dca1aa 100644
--- a/packages/browser-utils/src/web-vitals/emitSpan.ts
+++ b/packages/browser-utils/src/web-vitals/emitSpan.ts
@@ -153,6 +153,6 @@ function getReplayAttributes(): SpanAttributes {
[SENTRY_REPLAY_ID]: replayId,
// Not the `SENTRY_REPLAY_IS_BUFFERING` convention: that one has no `sentry._internal.` prefix, and
// the rest of the SDK sets the prefixed key (see `logs/internal.ts`, `metrics/internal.ts`).
- 'sentry._internal.replay_is_buffering': replay!.getRecordingMode() === 'buffer' ? true : undefined,
+ 'sentry._internal.replay_is_buffering': replay?.getRecordingMode() === 'buffer' ? true : undefined,
};
}
diff --git a/packages/browser-utils/src/web-vitals/interactionCache.ts b/packages/browser-utils/src/web-vitals/interactionCache.ts
index 5a007f699c0a..bfe1bf2b026a 100644
--- a/packages/browser-utils/src/web-vitals/interactionCache.ts
+++ b/packages/browser-utils/src/web-vitals/interactionCache.ts
@@ -37,6 +37,7 @@ export function createInteractionCache({
const get = (entry: E): T | undefined => {
// The most likely match is the latest item.
for (let i = items.length - 1; i >= 0; i--) {
+ // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop
if (match(items[i]!, entry)) {
return items[i];
}
diff --git a/packages/browser/.oxlintrc.json b/packages/browser/.oxlintrc.json
index 28df8e880028..62e4d719c5d8 100644
--- a/packages/browser/.oxlintrc.json
+++ b/packages/browser/.oxlintrc.json
@@ -1,6 +1,6 @@
{
"$schema": "../../node_modules/oxlint/configuration_schema.json",
- "extends": ["../../.oxlintrc.base.json"],
+ "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"],
"env": {
"browser": true
},
diff --git a/packages/browser/package.json b/packages/browser/package.json
index b9ceef988167..69fbfc17f31f 100644
--- a/packages/browser/package.json
+++ b/packages/browser/package.json
@@ -39,7 +39,7 @@
},
"dependencies": {
"@sentry/browser-utils": "11.17.0",
- "@sentry/conventions": "^0.35.0",
+ "@sentry/conventions": "^0.36.0",
"@sentry/feedback": "11.17.0",
"@sentry/replay": "11.17.0",
"@sentry/replay-canvas": "11.17.0",
diff --git a/packages/browser/src/integrations/spotlight.ts b/packages/browser/src/integrations/spotlight.ts
index d4714ce1afbc..718803b53c6a 100644
--- a/packages/browser/src/integrations/spotlight.ts
+++ b/packages/browser/src/integrations/spotlight.ts
@@ -45,7 +45,8 @@ function setupSidecarForwarding(client: Client, sidecarUrl: string): void {
client.on('beforeEnvelope', (envelope: Envelope) => {
if (failCount > 3) {
- debug.warn('[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests:', failCount);
+ DEBUG_BUILD &&
+ debug.warn('[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests:', failCount);
return;
}
@@ -65,10 +66,11 @@ function setupSidecarForwarding(client: Client, sidecarUrl: string): void {
},
err => {
failCount++;
- debug.error(
- "Sentry SDK can't connect to Sidecar is it running? See: https://spotlightjs.com/sidecar/npx/",
- err,
- );
+ DEBUG_BUILD &&
+ debug.error(
+ "Sentry SDK can't connect to Sidecar is it running? See: https://spotlightjs.com/sidecar/npx/",
+ err,
+ );
},
);
});
diff --git a/packages/browser/src/utils/managedTunnel.ts b/packages/browser/src/utils/managedTunnel.ts
index 35b0ef9f959c..89f5f585e5f2 100644
--- a/packages/browser/src/utils/managedTunnel.ts
+++ b/packages/browser/src/utils/managedTunnel.ts
@@ -4,7 +4,7 @@ import {
getTunnelPath,
isURLObjectRelative,
makeDsn,
- _INTERNAL_normalizeTunnelBasePath as normalizeTunnelBasePath,
+ normalizeTunnelBasePath,
parseStringToURLObject,
} from '@sentry/core';
import { DEBUG_BUILD } from '../debug-build';
diff --git a/packages/bun/package.json b/packages/bun/package.json
index 1ed97e3049cf..4f7dcb8b403c 100644
--- a/packages/bun/package.json
+++ b/packages/bun/package.json
@@ -48,7 +48,7 @@
"dependencies": {
"@sentry/bundler-plugins": "11.17.0",
"@sentry/core": "11.17.0",
- "@sentry/conventions": "^0.35.0",
+ "@sentry/conventions": "^0.36.0",
"@sentry/node": "11.17.0",
"@sentry/server-runtime-injection": "11.17.0",
"@sentry/server-utils": "11.17.0"
diff --git a/packages/bun/src/tunnelServer.ts b/packages/bun/src/tunnelServer.ts
index 3df1bc78740a..12adfb4b5e06 100644
--- a/packages/bun/src/tunnelServer.ts
+++ b/packages/bun/src/tunnelServer.ts
@@ -1,11 +1,8 @@
import * as http from 'node:http';
import * as https from 'node:https';
-import { _INTERNAL_normalizeTunnelBasePath, debug } from '@sentry/core';
-import {
- _INTERNAL_getServedTunnel as getServedTunnel,
- _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest,
-} from '@sentry/core/server';
-import { _INTERNAL_instrumentTunnelServer as instrumentTunnelServer } from '@sentry/server-utils';
+import { normalizeTunnelBasePath, debug } from '@sentry/core';
+import { getServedTunnel, handleServedTunnelRequest } from '@sentry/core/server';
+import { instrumentTunnelServer } from '@sentry/server-utils';
import type { Server } from 'bun';
type BunServeOptions = Parameters[0] & { routes?: Record };
@@ -113,7 +110,7 @@ function getTunnelRoutePaths(): string[] {
return [];
}
- const basePath = _INTERNAL_normalizeTunnelBasePath(servedTunnel.basePath);
+ const basePath = normalizeTunnelBasePath(servedTunnel.basePath);
return servedTunnel.paths.flatMap(path => [`${basePath}${path}`, `${basePath}${path}/`]);
}
diff --git a/packages/bundler-plugins/src/core/build-plugin-manager.ts b/packages/bundler-plugins/src/core/build-plugin-manager.ts
index 838a9cc8e3d4..804f5398fa14 100644
--- a/packages/bundler-plugins/src/core/build-plugin-manager.ts
+++ b/packages/bundler-plugins/src/core/build-plugin-manager.ts
@@ -1,6 +1,5 @@
/* oxlint-disable max-lines */
import { closeSession, DEFAULT_ENVIRONMENT, makeSession, setMeasurement, startSpan } from '@sentry/core';
-import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
@@ -24,6 +23,7 @@ import type { SourceMapDecision, SourceMapKind } from './sourcemap-settings';
import { decideSourceMapHandling, getSourceMapFeatures } from './sourcemap-settings';
import type { UploadFilter } from './upload-filter';
import { createUploadFilter } from './upload-filter';
+import { getMissingUploadCredential, readSentryBuildPluginEnvFile } from './upload-credentials';
import { LIB_VERSION } from './version';
// Module-level guard to prevent duplicate deploy records when multiple bundler plugin
@@ -205,21 +205,13 @@ export function createSentryBuildPluginManager(
debug: userOptions.debug ?? false,
});
- try {
- const dotenvFile = fs.readFileSync(path.join(process.cwd(), '.env.sentry-build-plugin'), 'utf-8');
- // NOTE: Do not use the dotenv.config API directly to read the dotenv file! For some ungodly reason, it falls back to reading `${process.cwd()}/.env` which is absolutely not what we want.
- const dotenvResult = dotenv.parse(dotenvFile);
-
+ const dotenvResult = readSentryBuildPluginEnvFile();
+ if (dotenvResult) {
// Vite has a bug/behaviour where spreading into process.env will cause it to crash
// https://github.com/vitest-dev/vitest/issues/1870#issuecomment-1501140251
Object.assign(process.env, dotenvResult);
logger.info('Using environment variables configured in ".env.sentry-build-plugin".');
- } catch (e: unknown) {
- // Ignore "file not found" errors but throw all others
- if (typeof e === 'object' && e && 'code' in e && e.code !== 'ENOENT') {
- throw e;
- }
}
const options = normalizeUserOptions(userOptions);
@@ -1065,16 +1057,7 @@ function getSourceMapUploadBlocker(options: NormalizedOptions, isDevMode: boolea
if (isDevMode) {
return 'dev-mode';
}
- if (!options.authToken) {
- return 'no-auth-token';
- }
- if (!options.org && !options.authToken.startsWith('sntrys_')) {
- return 'no-org';
- }
- if (!getProjects(options.project)?.[0]) {
- return 'no-project';
- }
- return undefined;
+ return getMissingUploadCredential(options);
}
function canUploadSourceMaps(options: NormalizedOptions, logger: Logger, isDevMode: boolean): boolean {
diff --git a/packages/bundler-plugins/src/core/debug-id-upload.ts b/packages/bundler-plugins/src/core/debug-id-upload.ts
index 718b6c5973db..d927e292eaa2 100644
--- a/packages/bundler-plugins/src/core/debug-id-upload.ts
+++ b/packages/bundler-plugins/src/core/debug-id-upload.ts
@@ -404,6 +404,7 @@ export function defaultRewriteSourcesHook(source: string): string {
if (source.match(PROTOCOL_REGEX)) {
return source.replace(PROTOCOL_REGEX, '');
} else {
- return path.relative(process.cwd(), path.normalize(source));
+ // Source map `sources` are URLs, so Windows separators must not leak into the uploaded map.
+ return path.relative(process.cwd(), path.normalize(source)).split(path.sep).join('/');
}
}
diff --git a/packages/bundler-plugins/src/core/index.ts b/packages/bundler-plugins/src/core/index.ts
index abad714a3706..5aec05052595 100644
--- a/packages/bundler-plugins/src/core/index.ts
+++ b/packages/bundler-plugins/src/core/index.ts
@@ -121,4 +121,5 @@ export {
getSourceMapFeatures,
} from './sourcemap-settings';
export type { SourceMapDecision, SourceMapKind } from './sourcemap-settings';
+export { hasSourceMapUploadCredentials } from './upload-credentials';
export type { UploadFilter } from './upload-filter';
diff --git a/packages/bundler-plugins/src/core/options-mapping.ts b/packages/bundler-plugins/src/core/options-mapping.ts
index aaba124acd8d..29bf9bec22a6 100644
--- a/packages/bundler-plugins/src/core/options-mapping.ts
+++ b/packages/bundler-plugins/src/core/options-mapping.ts
@@ -1,4 +1,4 @@
-import { getVercelEnv } from '@sentry/core';
+import { getVercelEnv, warnOnConflictingSourceMapOptions } from '@sentry/core';
import type { Logger } from './logger';
import type {
InternalOptions as UserOptions,
@@ -9,6 +9,7 @@ import type {
ModuleMetadata,
ModuleMetadataCallback,
} from './types';
+import { parseProjectEnvVar } from './upload-credentials';
import { canAutoDetectRepository, readCommitEnvVar, resolveReleaseName } from './utils';
export type NormalizedOptions = {
@@ -99,11 +100,7 @@ export const SENTRY_SAAS_URL = 'https://sentry.io';
export function normalizeUserOptions(userOptions: UserOptions): NormalizedOptions {
const options = {
org: userOptions.org ?? process.env['SENTRY_ORG'],
- project:
- userOptions.project ??
- (process.env['SENTRY_PROJECT']?.includes(',')
- ? process.env['SENTRY_PROJECT'].split(',').map(p => p.trim())
- : process.env['SENTRY_PROJECT']),
+ project: userOptions.project ?? parseProjectEnvVar(process.env['SENTRY_PROJECT']),
authToken: userOptions.authToken ?? process.env['SENTRY_AUTH_TOKEN'],
// No sentry.io default: the CLI then uses the server an `sntrys_` org token was issued for, and
// sentry.io otherwise. A default here would send self-hosted tokens to sentry.io.
@@ -222,32 +219,7 @@ export function validateOptions(options: NormalizedOptions, logger: Logger): boo
}
}
- const sourcemaps = options.sourcemaps;
- const usesFeatureOptions = sourcemaps?.upload !== undefined || sourcemaps?.injectDebugIds !== undefined;
- if (usesFeatureOptions && sourcemaps?.disable !== undefined) {
- logger.warn(
- '`sourcemaps.disable` is ignored because `sourcemaps.upload` or `sourcemaps.injectDebugIds` is set.',
- 'Please remove `sourcemaps.disable`.',
- );
- }
- if (sourcemaps?.injectDebugIds === false && sourcemaps.upload === true) {
- logger.warn(
- '`sourcemaps.upload` is set, but `sourcemaps.injectDebugIds` is `false`.',
- 'Source maps are not uploaded, because the upload matches files by debug ID.',
- );
- }
- if (sourcemaps?.delete !== undefined && sourcemaps.deleteSourcemapsAfterUpload !== undefined) {
- logger.warn(
- '`sourcemaps.deleteSourcemapsAfterUpload` is ignored because `sourcemaps.delete` is set.',
- 'Please remove `sourcemaps.deleteSourcemapsAfterUpload`.',
- );
- }
- if (sourcemaps?.delete === false && sourcemaps.filesToDeleteAfterUpload !== undefined) {
- logger.warn(
- '`sourcemaps.filesToDeleteAfterUpload` still deletes the files it matches, although `sourcemaps.delete` is `false`.',
- 'Remove `sourcemaps.filesToDeleteAfterUpload` to keep the source maps.',
- );
- }
+ warnOnConflictingSourceMapOptions(options.sourcemaps, message => logger.warn(message));
if (options.release?.deploy && typeof options.release.deploy === 'object' && !options.release.deploy.env) {
logger.error(
diff --git a/packages/bundler-plugins/src/core/upload-credentials.ts b/packages/bundler-plugins/src/core/upload-credentials.ts
new file mode 100644
index 000000000000..e89fc7c2f53d
--- /dev/null
+++ b/packages/bundler-plugins/src/core/upload-credentials.ts
@@ -0,0 +1,66 @@
+import * as dotenv from 'dotenv';
+import * as fs from 'fs';
+import * as path from 'path';
+import { getProjects } from './utils';
+
+export type UploadCredentials = {
+ authToken?: string;
+ org?: string;
+ project?: string | string[];
+};
+
+/** The variables in `.env.sentry-build-plugin`, or `undefined` when the file does not exist. */
+export function readSentryBuildPluginEnvFile(): Record | undefined {
+ try {
+ const dotenvFile = fs.readFileSync(path.join(process.cwd(), '.env.sentry-build-plugin'), 'utf-8');
+ // NOTE: Do not use the dotenv.config API directly to read the dotenv file! For some ungodly reason, it falls back to reading `${process.cwd()}/.env` which is absolutely not what we want.
+ return dotenv.parse(dotenvFile);
+ } catch (e: unknown) {
+ // Ignore "file not found" errors but throw all others
+ if (typeof e === 'object' && e && 'code' in e && e.code !== 'ENOENT') {
+ throw e;
+ }
+ return undefined;
+ }
+}
+
+/** Reads `SENTRY_PROJECT`, which holds one project or a comma-separated list. */
+export function parseProjectEnvVar(value: string | undefined): string | string[] | undefined {
+ return value?.includes(',') ? value.split(',').map(p => p.trim()) : value;
+}
+
+/** The first credential the upload needs that is missing. */
+export function getMissingUploadCredential({
+ authToken,
+ org,
+ project,
+}: UploadCredentials): 'no-auth-token' | 'no-org' | 'no-project' | undefined {
+ if (!authToken) {
+ return 'no-auth-token';
+ }
+ if (!org && !authToken.startsWith('sntrys_')) {
+ return 'no-org';
+ }
+ if (!getProjects(project)?.[0]) {
+ return 'no-project';
+ }
+ return undefined;
+}
+
+/**
+ * Whether the plugin has the credentials to upload source maps. It reads the same environment
+ * variables and `.env.sentry-build-plugin` file as the plugin, so SDKs can call it before they
+ * create the plugin.
+ */
+export function hasSourceMapUploadCredentials(options: UploadCredentials | undefined): boolean {
+ const envFile = readSentryBuildPluginEnvFile();
+ const env = (name: string): string | undefined => envFile?.[name] ?? process.env[name];
+
+ return (
+ getMissingUploadCredential({
+ authToken: options?.authToken ?? env('SENTRY_AUTH_TOKEN'),
+ org: options?.org ?? env('SENTRY_ORG'),
+ project: options?.project ?? parseProjectEnvVar(env('SENTRY_PROJECT')),
+ }) === undefined
+ );
+}
diff --git a/packages/bundler-plugins/test/core/default-rewrite-sources-hook.test.ts b/packages/bundler-plugins/test/core/default-rewrite-sources-hook.test.ts
new file mode 100644
index 000000000000..d10b40448715
--- /dev/null
+++ b/packages/bundler-plugins/test/core/default-rewrite-sources-hook.test.ts
@@ -0,0 +1,34 @@
+import type * as Path from 'path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('path', async () => {
+ const actual = await vi.importActual('path');
+ return { ...actual.win32, default: actual.win32 };
+});
+
+import { defaultRewriteSourcesHook } from '../../src/core/debug-id-upload';
+
+describe('defaultRewriteSourcesHook on Windows', () => {
+ beforeEach(() => {
+ vi.spyOn(process, 'cwd').mockReturnValue('C:\\project\\dist\\assets');
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('returns forward-slash sources for relative inputs', () => {
+ expect(defaultRewriteSourcesHook('../../node_modules/nanoid/index.browser.js')).toBe(
+ '../../node_modules/nanoid/index.browser.js',
+ );
+ expect(defaultRewriteSourcesHook('../../src/main.js')).toBe('../../src/main.js');
+ });
+
+ it('returns forward-slash sources for absolute inputs', () => {
+ expect(defaultRewriteSourcesHook('C:\\project\\src\\main.js')).toBe('../../src/main.js');
+ });
+
+ it('strips the protocol from URL sources', () => {
+ expect(defaultRewriteSourcesHook('webpack://my-app/src/main.js')).toBe('my-app/src/main.js');
+ });
+});
diff --git a/packages/bundler-plugins/test/core/option-mappings.test.ts b/packages/bundler-plugins/test/core/option-mappings.test.ts
index 42df3d9a3317..ef56d9117d9d 100644
--- a/packages/bundler-plugins/test/core/option-mappings.test.ts
+++ b/packages/bundler-plugins/test/core/option-mappings.test.ts
@@ -448,34 +448,12 @@ describe('validateOptions', () => {
});
describe('source map options', () => {
- it.each([
- [{ upload: false, disable: true }, /`sourcemaps\.disable` is ignored/],
- [{ injectDebugIds: false, disable: 'disable-upload' }, /`sourcemaps\.disable` is ignored/],
- [{ upload: true, injectDebugIds: false }, /`sourcemaps\.injectDebugIds` is `false`/],
- [{ delete: true, deleteSourcemapsAfterUpload: false }, /`sourcemaps\.deleteSourcemapsAfterUpload` is ignored/],
- [{ delete: false, filesToDeleteAfterUpload: ['dist/**/*.map'] }, /`sourcemaps\.filesToDeleteAfterUpload` still/],
- ] as const)('warns about %j', (sourcemaps, message) => {
- const options = { sourcemaps } as Partial;
+ it('warns about conflicting options through the plugin logger', () => {
+ const options = { sourcemaps: { upload: true, injectDebugIds: false } } as Partial;
expect(validateOptions(options as unknown as NormalizedOptions, mockedLogger)).toBe(true);
expect(mockedLogger.warn).toHaveBeenCalledTimes(1);
- expect(mockedLogger.warn).toHaveBeenCalledWith(expect.stringMatching(message), expect.any(String));
- });
-
- it.each([
- { upload: false },
- { injectDebugIds: false },
- { upload: false, injectDebugIds: false },
- { delete: false },
- { disable: true, deleteSourcemapsAfterUpload: true },
- { disable: true, delete: true },
- { delete: true, filesToDeleteAfterUpload: ['extra/**'] },
- { filesToDeleteAfterUpload: ['dist/**/*.map'] },
- ] as const)('does not warn about %j', sourcemaps => {
- const options = { sourcemaps } as Partial;
-
- expect(validateOptions(options as unknown as NormalizedOptions, mockedLogger)).toBe(true);
- expect(mockedLogger.warn).not.toHaveBeenCalled();
+ expect(mockedLogger.warn).toHaveBeenCalledWith(expect.stringMatching(/`sourcemaps\.injectDebugIds` is `false`/));
});
});
diff --git a/packages/bundler-plugins/test/core/upload-credentials.test.ts b/packages/bundler-plugins/test/core/upload-credentials.test.ts
new file mode 100644
index 000000000000..71ef8723f733
--- /dev/null
+++ b/packages/bundler-plugins/test/core/upload-credentials.test.ts
@@ -0,0 +1,70 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { hasSourceMapUploadCredentials } from '../../src/core/upload-credentials';
+
+describe('hasSourceMapUploadCredentials', () => {
+ let cwd: string;
+
+ beforeEach(() => {
+ cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-upload-credentials-'));
+ vi.spyOn(process, 'cwd').mockReturnValue(cwd);
+ vi.stubEnv('SENTRY_AUTH_TOKEN', '');
+ vi.stubEnv('SENTRY_ORG', '');
+ vi.stubEnv('SENTRY_PROJECT', '');
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+ fs.rmSync(cwd, { recursive: true, force: true });
+ });
+
+ it('returns true with an auth token, org and project in the options', () => {
+ expect(hasSourceMapUploadCredentials({ authToken: 'token', org: 'org', project: 'project' })).toBe(true);
+ });
+
+ it.each([
+ ['auth token', { org: 'org', project: 'project' }],
+ ['org', { authToken: 'token', project: 'project' }],
+ ['project', { authToken: 'token', org: 'org' }],
+ ['project in the list', { authToken: 'token', org: 'org', project: [] }],
+ ])('returns false without an %s', (_, options) => {
+ expect(hasSourceMapUploadCredentials(options)).toBe(false);
+ });
+
+ it('returns false without options', () => {
+ expect(hasSourceMapUploadCredentials(undefined)).toBe(false);
+ });
+
+ it('accepts an org token without an org', () => {
+ expect(hasSourceMapUploadCredentials({ authToken: 'sntrys_token', project: 'project' })).toBe(true);
+ });
+
+ it('reads the environment variables', () => {
+ vi.stubEnv('SENTRY_AUTH_TOKEN', 'token');
+ vi.stubEnv('SENTRY_ORG', 'org');
+ vi.stubEnv('SENTRY_PROJECT', 'project1,project2');
+
+ expect(hasSourceMapUploadCredentials({})).toBe(true);
+ });
+
+ it('reads `.env.sentry-build-plugin` before the plugin loads it', () => {
+ fs.writeFileSync(
+ path.join(cwd, '.env.sentry-build-plugin'),
+ 'SENTRY_AUTH_TOKEN=token\nSENTRY_ORG=org\nSENTRY_PROJECT=project\n',
+ );
+
+ expect(hasSourceMapUploadCredentials({})).toBe(true);
+ expect(process.env.SENTRY_AUTH_TOKEN).toBe('');
+ });
+
+ it('prefers the options over the environment', () => {
+ vi.stubEnv('SENTRY_AUTH_TOKEN', 'token');
+ vi.stubEnv('SENTRY_ORG', 'org');
+ vi.stubEnv('SENTRY_PROJECT', 'project');
+
+ expect(hasSourceMapUploadCredentials({ project: [] })).toBe(false);
+ });
+});
diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json
index 84403d7a9cb8..612cffbe5a4d 100644
--- a/packages/cloudflare/package.json
+++ b/packages/cloudflare/package.json
@@ -53,7 +53,7 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
- "@sentry/conventions": "^0.35.0",
+ "@sentry/conventions": "^0.36.0",
"@sentry/core": "11.17.0",
"@sentry/opentelemetry": "11.17.0",
"@sentry/server-utils": "11.17.0",
diff --git a/packages/cloudflare/src/client.ts b/packages/cloudflare/src/client.ts
index e6935595d153..25f3e6063210 100644
--- a/packages/cloudflare/src/client.ts
+++ b/packages/cloudflare/src/client.ts
@@ -1,8 +1,8 @@
import type { CheckIn, ClientOptions, MonitorConfig, Options, Scope, TracePropagationTargets } from '@sentry/core';
import {
_INTERNAL_clearAiProviderSkips,
- _INTERNAL_flushLogsBuffer,
- _INTERNAL_flushMetricsBuffer,
+ flushLogsBuffer,
+ flushMetricsBuffer,
applySdkMetadata,
debug,
GLOBAL_OBJ,
@@ -338,8 +338,8 @@ export class CloudflareClient extends ServerRuntimeClient {
const traceId = span.spanContext().traceId;
this._eagerDrain(() => this.emit('flushTraceSpans', traceId));
});
- this.on('afterCaptureLog', () => this._eagerDrain(() => _INTERNAL_flushLogsBuffer(this)));
- this.on('afterCaptureMetric', () => this._eagerDrain(() => _INTERNAL_flushMetricsBuffer(this)));
+ this.on('afterCaptureLog', () => this._eagerDrain(() => flushLogsBuffer(this)));
+ this.on('afterCaptureMetric', () => this._eagerDrain(() => flushMetricsBuffer(this)));
}
/**
diff --git a/packages/cloudflare/src/index.ts b/packages/cloudflare/src/index.ts
index b86371145050..7d36839a6857 100644
--- a/packages/cloudflare/src/index.ts
+++ b/packages/cloudflare/src/index.ts
@@ -134,6 +134,7 @@ export { _INTERNAL_wrapRequestHandler, getDefaultIntegrations, init as _INTERNAL
export { getFinalOptions as _INTERNAL_getFinalOptions } from './options';
export { httpServerIntegration } from './integrations/httpServer';
+export { addServerTimingTraceHeader } from '@sentry/server-utils/request-handler';
export { fetchIntegration } from './integrations/fetch';
export type { FetchIntegrationOptions } from '@sentry/core';
export { spotlightIntegration } from './integrations/spotlight';
diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentEnv.ts b/packages/cloudflare/src/instrumentations/worker/instrumentEnv.ts
index a3de0f67b24b..9351c03a6e05 100644
--- a/packages/cloudflare/src/instrumentations/worker/instrumentEnv.ts
+++ b/packages/cloudflare/src/instrumentations/worker/instrumentEnv.ts
@@ -37,6 +37,8 @@ const instrumentedBindings = new WeakMap