diff --git a/dev-packages/deno-integration-tests/node-suites/excludes.ts b/dev-packages/deno-integration-tests/node-suites/excludes.ts index bf60cdeed3eb..dc1e75c9e5ad 100644 --- a/dev-packages/deno-integration-tests/node-suites/excludes.ts +++ b/dev-packages/deno-integration-tests/node-suites/excludes.ts @@ -37,7 +37,6 @@ const NO_SENTRY_DENO_EXPORT = [ 'suites/cron/node-cron/base/test.ts', 'suites/cron/node-cron/isolateTrace/test.ts', 'suites/cron/node-schedule/test.ts', - 'suites/esm/modules-integration/test.ts', 'suites/express/multiple-init/test.ts', 'suites/express/with-http/maxIncomingRequestBodySize/test.ts', 'suites/fs-instrumentation/test.ts', @@ -65,12 +64,11 @@ const NO_CLIENT_TRACER = ['suites/tracing/tracer-start-active-span-error/test.ts const NO_NODE_LOGGER_PARAMETERS = ['suites/public-api/logs/test.ts']; // The test expects data that a default integration of `@sentry/node` adds and `@sentry/deno` does -// not have: process sessions, child process breadcrumbs, the `modules` of the event, the -// `node_system_error` context, and the context attributes of `nodeContextIntegration` on spans. +// not have: process sessions, child process breadcrumbs, the `node_system_error` context, and the +// context attributes of `nodeContextIntegration` on spans. const NO_NODE_DEFAULT_INTEGRATION = [ 'suites/child-process/test.ts', 'suites/context/test.ts', - 'suites/modules/test.ts', 'suites/public-api/startSpan/basic-usage/with-children/test.ts', 'suites/sessions/process-session/test.ts', 'suites/sessions/server-without-process-session/test.ts', diff --git a/dev-packages/node-integration-tests/suites/modules/test.ts b/dev-packages/node-integration-tests/suites/modules/test.ts index cee120ea4f03..50ba6c86b26c 100644 --- a/dev-packages/node-integration-tests/suites/modules/test.ts +++ b/dev-packages/node-integration-tests/suites/modules/test.ts @@ -2,6 +2,7 @@ import { SDK_VERSION } from '@sentry/core'; import { copyFileSync, cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs'; import { dirname, join } from 'path'; import { afterAll, describe, expect, test } from 'vitest'; +import { supports } from '../../utils'; 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 @@ -10,12 +11,16 @@ function makeTempDir(): string { return mkdtempSync(join(__dirname, 'tmp-')); } +// The Deno integration cannot see packages that were loaded but not declared in `package.json`, because it does not +// read the CommonJS module cache. +const READS_LOADED_MODULES = supports({ runtimes: ['node', 'bun'] }); + describe('modulesIntegration', () => { afterAll(() => { cleanupChildProcesses(); }); - test('CJS', async () => { + test.runIf(READS_LOADED_MODULES)('CJS', async () => { await createRunner(__dirname, 'scenario.js') .expect({ event: { @@ -33,7 +38,7 @@ describe('modulesIntegration', () => { .completed(); }); - test('CJS with the isolated layouts of pnpm and Bun', async () => { + test.runIf(READS_LOADED_MODULES)('CJS with the isolated layouts of pnpm and Bun', async () => { const tempDir = makeTempDir(); copyFileSync(join(__dirname, 'scenario-isolated.js'), join(tempDir, 'scenario-isolated.js')); const nodeModulesDir = join(tempDir, 'node_modules'); @@ -90,7 +95,7 @@ describe('modulesIntegration', () => { .completed(); }); - test('ESM app in a subfolder with its own package.json', async () => { + test.runIf(READS_LOADED_MODULES)('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 }); diff --git a/packages/deno/src/index.ts b/packages/deno/src/index.ts index e76ae70e0ed1..31b4bbc66a7e 100644 --- a/packages/deno/src/index.ts +++ b/packages/deno/src/index.ts @@ -150,6 +150,7 @@ export type { DenoServeIntegrationOptions } from './integrations/deno-serve'; export { fetchIntegration } from './integrations/fetch'; export type { FetchIntegrationOptions } from '@sentry/core'; export { denoHttpIntegration } from './integrations/http'; +export { modulesIntegration } from './integrations/modules'; export type { DenoHttpIntegrationOptions } from './integrations/http'; // The orchestrion channel integrations, re-exported from `@sentry/server-utils`. diff --git a/packages/deno/src/integrations/modules.ts b/packages/deno/src/integrations/modules.ts new file mode 100644 index 000000000000..158cdf5bee15 --- /dev/null +++ b/packages/deno/src/integrations/modules.ts @@ -0,0 +1,67 @@ +import { fileURLToPath } from 'node:url'; +import type { IntegrationFn } from '@sentry/core'; +import { defineIntegration, dirname, join } from '@sentry/core'; +import { collectInstalledModules } from '@sentry/server-utils'; + +/** Reads only with granted permission, so it never prompts. */ +function readFile(path?: string): string | undefined { + try { + if (Deno.permissions.querySync({ name: 'read', path }).state === 'granted') { + return path ? Deno.readTextFileSync(path) : Deno.cwd(); + } + } catch { + // not readable + } + return undefined; +} + +/** Exact versions of the `jsr:` and `npm:` specifiers in the nearest `deno.lock` (versions 3 to 5). */ +function getDenoLockModules(startDir: string): Record { + const modules: Record = {}; + for (let dir = startDir, prev = ''; dir !== prev && dir !== '.'; prev = dir, dir = dirname(dir)) { + const content = readFile(join(dir, 'deno.lock')); + if (content) { + try { + const lock = JSON.parse(content) as { specifiers?: object; packages?: { specifiers?: object } }; + for (const [specifier, resolved] of Object.entries(lock.specifiers || lock.packages?.specifiers || {})) { + const name = /^(?:npm|jsr):(@?[^@]+)@/.exec(specifier)?.[1]; + // v3 stores `npm:express@4.21.2`, later versions `4.21.2`; npm versions can end in `_`. + const version = typeof resolved === 'string' && resolved.replace(/^(?:npm|jsr):@?[^@]+@/, '').split('_')[0]; + if (name && version) { + modules[name] = version; + } + } + } catch { + // invalid lockfile + } + break; + } + } + return modules; +} + +function collectModules(): Record { + const entryPath = Deno.mainModule.startsWith('file:') ? fileURLToPath(Deno.mainModule) : undefined; + const cwd = readFile(); + const modules = collectInstalledModules({ readFile, entryPath, cwd }); + const startDir = (entryPath ? dirname(entryPath.replace(/\\/g, '/')) : cwd?.replace(/\\/g, '/')) || '.'; + // Without `node_modules`, `modules` only has declared ranges, so the exact versions from `deno.lock` win. + return { ...modules, ...getDenoLockModules(startDir) }; +} + +const _modulesIntegration = (() => { + let modules: Record | undefined; + return { + name: 'Modules' as const, + processEvent(event) { + modules = modules || collectModules(); + event.modules = { ...event.modules, ...modules }; + return event; + }, + }; +}) satisfies IntegrationFn; + +/** + * Adds the app's packages and versions to events, from `deno.lock` and from `package.json` and `node_modules`. + */ +export const modulesIntegration = defineIntegration(_modulesIntegration); diff --git a/packages/deno/src/sdk.ts b/packages/deno/src/sdk.ts index 6cf358c9db7c..1550863d14f2 100644 --- a/packages/deno/src/sdk.ts +++ b/packages/deno/src/sdk.ts @@ -30,6 +30,7 @@ import { denoServeIntegration } from './integrations/deno-serve'; import { fetchIntegration } from './integrations/fetch'; import { denoHttpIntegration } from './integrations/http'; import { globalHandlersIntegration } from './integrations/globalhandlers'; +import { modulesIntegration } from './integrations/modules'; import { normalizePathsIntegration } from './integrations/normalizepaths'; import { setupOpenTelemetryTracer } from './opentelemetry/tracer'; import { makeFetchTransport } from './transports'; @@ -54,6 +55,7 @@ export function getDefaultIntegrationsWithoutPerformance(): Integration[] { fetchIntegration(), denoHttpIntegration(), contextLinesIntegration(), + modulesIntegration(), normalizePathsIntegration(), globalHandlersIntegration(), // server-utils integrations diff --git a/packages/deno/test/__snapshots__/mod.test.ts.snap b/packages/deno/test/__snapshots__/mod.test.ts.snap index a38158657b59..fca4d16bd8f0 100644 --- a/packages/deno/test/__snapshots__/mod.test.ts.snap +++ b/packages/deno/test/__snapshots__/mod.test.ts.snap @@ -44,6 +44,9 @@ snapshot[`captureMessage 1`] = ` event_id: "{{id}}", level: "info", message: "Some error message", + modules: { + "{{modules}}": "{{version}}", + }, platform: "javascript", sdk: { integrations: [ @@ -114,6 +117,9 @@ snapshot[`captureMessage twice 1`] = ` event_id: "{{id}}", level: "info", message: "Some error message", + modules: { + "{{modules}}": "{{version}}", + }, platform: "javascript", sdk: { integrations: [ @@ -191,6 +197,9 @@ snapshot[`captureMessage twice 2`] = ` event_id: "{{id}}", level: "info", message: "Another error message", + modules: { + "{{modules}}": "{{version}}", + }, platform: "javascript", sdk: { integrations: [ diff --git a/packages/deno/test/exports.test.ts b/packages/deno/test/exports.test.ts index 771873d5377e..baab4f229e0d 100644 --- a/packages/deno/test/exports.test.ts +++ b/packages/deno/test/exports.test.ts @@ -37,6 +37,7 @@ const EXPECTED_FUNCTION_EXPORTS = [ // ./sdk 'initWithoutDefaultIntegrations', 'getDefaultIntegrationsWithoutPerformance', + 'modulesIntegration', ]; for (const name of EXPECTED_FUNCTION_EXPORTS) { diff --git a/packages/deno/test/fixtures/modules/deno.lock b/packages/deno/test/fixtures/modules/deno.lock new file mode 100644 index 000000000000..54aabb729fe2 --- /dev/null +++ b/packages/deno/test/fixtures/modules/deno.lock @@ -0,0 +1,8 @@ +{ + "version": "5", + "specifiers": { + "jsr:@std/assert@^1.0.0": "1.0.13", + "npm:@types/react-dom@18": "18.3.0_@types+react@18.3.1", + "npm:express@^4.18.2": "4.21.2" + } +} diff --git a/packages/deno/test/fixtures/modules/main.ts b/packages/deno/test/fixtures/modules/main.ts new file mode 100644 index 000000000000..ad02f94d6bcd --- /dev/null +++ b/packages/deno/test/fixtures/modules/main.ts @@ -0,0 +1,15 @@ +import * as Sentry from '../../../build/esm/index.js'; + +Sentry.init({ + dsn: 'https://username@domain/123', + defaultIntegrations: false, + integrations: [Sentry.modulesIntegration()], + beforeSend(event) { + // oxlint-disable-next-line no-console + console.log(JSON.stringify(event.modules)); + return null; + }, +}); + +Sentry.captureException(new Error('test')); +await Sentry.flush(); diff --git a/packages/deno/test/fixtures/modules/package.json b/packages/deno/test/fixtures/modules/package.json new file mode 100644 index 000000000000..6d7664335910 --- /dev/null +++ b/packages/deno/test/fixtures/modules/package.json @@ -0,0 +1,7 @@ +{ + "name": "deno-modules-fixture", + "private": true, + "dependencies": { + "left-pad": "^1.3.0" + } +} diff --git a/packages/deno/test/modules.test.ts b/packages/deno/test/modules.test.ts new file mode 100644 index 000000000000..2a60d3b880fd --- /dev/null +++ b/packages/deno/test/modules.test.ts @@ -0,0 +1,27 @@ +import { assertEquals } from 'https://deno.land/std@0.212.0/assert/assert_equals.ts'; + +const fixtureDir = new URL('./fixtures/modules/', import.meta.url); + +async function runFixture(permissions: string[]): Promise { + const { stdout, stderr, success } = await new Deno.Command(Deno.execPath(), { + // `--no-lock` keeps Deno from rewriting the fixture lockfile. + args: ['run', '--no-prompt', '--no-lock', ...permissions, new URL('main.ts', fixtureDir).pathname], + cwd: fixtureDir.pathname, + stdin: 'null', + }).output(); + assertEquals(success, true, new TextDecoder().decode(stderr)); + return JSON.parse(new TextDecoder().decode(stdout).trim()); +} + +Deno.test('modulesIntegration reads deno.lock and package.json', async () => { + assertEquals(await runFixture([`--allow-read=${fixtureDir.pathname}`]), { + 'left-pad': '^1.3.0', + '@std/assert': '1.0.13', + '@types/react-dom': '18.3.0', + express: '4.21.2', + }); +}); + +Deno.test('modulesIntegration reads nothing without read permission', async () => { + assertEquals(await runFixture([]), {}); +}); diff --git a/packages/deno/test/normalize.ts b/packages/deno/test/normalize.ts index 15af97f30b7b..0ef199b4fbaa 100644 --- a/packages/deno/test/normalize.ts +++ b/packages/deno/test/normalize.ts @@ -85,6 +85,11 @@ function normalizeEvent(event: Event): Event { event.sdk.integrations = ['{{integrations}}']; } + // Installed packages depend on the checkout, so collapse them to a placeholder. + if (event.modules) { + event.modules = { '{{modules}}': '{{version}}' }; + } + if (event.contexts?.app?.app_start_time) { event.contexts.app.app_start_time = '{{time}}'; }