Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,11 +41,19 @@
"types": "./build/types/orchestrion/bundler/vite.d.ts",
"import": "./build/esm/orchestrion/bundler/vite.js"
},
"./orchestrion/rollup": {
"types": "./build/types/orchestrion/bundler/rollup.d.ts",
"import": "./build/esm/orchestrion/bundler/rollup.js"
},
"./orchestrion/webpack": {
"types": "./build/types/orchestrion/bundler/webpack.d.ts",
"import": "./build/esm/orchestrion/bundler/webpack.js",
"require": "./build/cjs/orchestrion/bundler/webpack.js"
},
"./orchestrion/esbuild": {
"types": "./build/types/orchestrion/bundler/esbuild.d.ts",
"import": "./build/esm/orchestrion/bundler/esbuild.js"
},
"./orchestrion/import-hook": {
"import": "./build/orchestrion/import-hook.mjs"
}
Expand All@@ -67,8 +75,14 @@
"orchestrion/vite": [
"build/types-ts3.8/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types-ts3.8/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types-ts3.8/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types-ts3.8/orchestrion/bundler/esbuild.d.ts"
]
},
"*": {
Expand All@@ -84,8 +98,14 @@
"orchestrion/vite": [
"build/types/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types/orchestrion/bundler/esbuild.d.ts"
]
}
},
Expand All@@ -97,8 +117,7 @@
"@apm-js-collab/code-transformer": "^0.18.0",
"@apm-js-collab/tracing-hooks": "^0.11.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.65.0",
"magic-string": "~0.30.0"
"@sentry/core": "10.65.0"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
10 changes: 6 additions & 4 deletions packages/server-utils/rollup.npm.config.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,10 +19,10 @@ export default [
...orchestrionRuntimeHooks,
...makeNPMConfigVariants(
makeBaseNPMConfig({
// `src/orchestrion/config/index.ts` and `src/orchestrion/bundler/vite.ts` are
// loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`) β€” neither is reachable from `src/index.ts`, so we
// list them as separate entrypoints to guarantee they end up in build/esm
// `src/orchestrion/config/index.ts` and the `src/orchestrion/bundler/*.ts`
// plugins are loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`, etc.) β€” none are reachable from `src/index.ts`, so
// we list them as separate entrypoints to guarantee they end up in build/esm
// and build/cjs. `src/orchestrion/index.ts` backs the `./orchestrion`
// subpath export.
entrypoints: [
Expand All@@ -34,7 +34,9 @@ export default [
// `Sentry.init()` to install the channel-injection hooks.
'src/orchestrion/runtime/register.ts',
'src/orchestrion/bundler/vite.ts',
'src/orchestrion/bundler/rollup.ts',
'src/orchestrion/bundler/webpack.ts',
'src/orchestrion/bundler/esbuild.ts',
],
packageSpecificConfig: {
output: {
Expand Down
24 changes: 24 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/esbuild.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/esbuild';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* esbuild plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with esbuild. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* esbuild does not flatten nested `plugins` arrays, so this returns a single
* plugin that strips instrumented packages from an `external` denylist before
* delegating to the upstream transform.
*
* @example
* ```ts
* // build.mjs
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/esbuild';
* await esbuild.build({ plugins: [sentryOrchestrionPlugin()] });
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
Comment thread
timfish marked this conversation as resolved.
Comment thread
timfish marked this conversation as resolved.
}
Comment thread
timfish marked this conversation as resolved.
28 changes: 28 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import type codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';

export type PluginOptions = {
/**
* Additional instrumentations to include with the default instrumentation.
*/
instrumentations?: InstrumentationConfig[];
};

/**
* The `@apm-js-collab/code-transformer-bundler-plugins` options shared by every
* orchestrion bundler plugin.
*
* `injectDiagnostics` sets `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at
* app boot so the `_experimentalSetupOrchestrion()` detector can confirm the
* bundler path ran (rather than relying on a build-time flag that wouldn't be
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): Parameters<typeof codeTransformer>[0] {
return {
instrumentations: [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])],
injectDiagnostics: () => {
return '(globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{}).bundler=true;';
Comment thread
timfish marked this conversation as resolved.
},
};
}
20 changes: 20 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/rollup.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Rollup plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with Rollup. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* @example
* ```ts
* // rollup.config.js
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
}
Comment thread
timfish marked this conversation as resolved.
70 changes: 7 additions & 63 deletions packages/server-utils/src/orchestrion/bundler/vite.ts
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,7 @@
// EXPERIMENTAL β€” Vite plugin that runs the orchestrion code transform at build
// time, injecting `diagnostics_channel.tracingChannel` calls into the libraries
// listed in `SENTRY_INSTRUMENTATIONS`.
//
// This file is published ESM-only via the `@sentry/server-utils/orchestrion/vite`
// subpath export. `@apm-js-collab/code-transformer-bundler-plugins` is
// `"type": "module"`, so consuming it from a CJS build is intentionally
// unsupported β€” vite.config.ts is almost always ESM in practice. The CJS
// rollup variant still emits this file, but `package.json` only exposes the
// ESM entry, so attempts to `require('@sentry/server-utils/orchestrion/vite')` will
// fail at resolution time rather than producing a half-broken plugin.

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type UnknownPlugin = any;

import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/vite';
import MagicString from 'magic-string';
Comment thread
timfish marked this conversation as resolved.
import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
Comment thread
sentry[bot] marked this conversation as resolved.

// `vite` types live in the package's ESM-only subpath; under Node16 module
// resolution with TS treating @sentry/server-utils as CJS, importing them produces a
// false positive. We don't need the runtime value for typing β€” `UnknownPlugin`
// is sufficient β€” so we omit the import entirely.
import { instrumentedModuleNames } from '../config';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Vite plugin that runs the orchestrion code transform on the bundled output.
Expand All@@ -29,44 +10,16 @@ import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
* pipeline, SvelteKit). For unbundled Node processes use the runtime hook
* instead (`node --import @sentry/node/orchestrion app.js`).
*
* Returns two plugins:
Comment thread
timfish marked this conversation as resolved.
* 1. `sentry-orchestrion-marker` β€” a `renderChunk` hook that prepends a
Comment thread
timfish marked this conversation as resolved.
* single-line banner to entry chunks. The banner sets
* `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at app boot, so the
* `_experimentalSetupOrchestrion()` detector can confirm the bundler path
* ran (rather than relying on a build-time flag that wouldn't be visible
* to the runtime).
* Also injects every instrumented package name into `ssr.noExternal` via
* the `config` hook, since externalized deps are `require()`d at runtime
* from `node_modules` and never pass through the transform.
* 2. The upstream `@apm-js-collab/code-transformer-bundler-plugins/vite`
* plugin, fed our central `SENTRY_INSTRUMENTATIONS` config.
*
* @example
* ```ts
* // vite.config.ts
* import { sentryOrchestrionPlugin } from '@sentry/node/orchestrion/vite';
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
Comment thread
isaacs marked this conversation as resolved.
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(): UnknownPlugin[] {
const codeTransformerPlugins = codeTransformer({ instrumentations: SENTRY_INSTRUMENTATIONS });
const codeTransformerArray: UnknownPlugin[] = Array.isArray(codeTransformerPlugins)
? codeTransformerPlugins
: [codeTransformerPlugins];
return [bundlerMarkerPlugin(), ...codeTransformerArray];
}

function bundlerMarkerPlugin(): UnknownPlugin {
const banner = [
'globalThis.__SENTRY_ORCHESTRION__ = (globalThis.__SENTRY_ORCHESTRION__ || {});',
'globalThis.__SENTRY_ORCHESTRION__.bundler = true;',
'',
].join('\n');

export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return {
name: 'sentry-orchestrion-marker',
enforce: 'pre' as const,
...codeTransformer(orchestrionTransformOptions(options)),
config(): { ssr: { noExternal: string[] } } {
// Force-bundle every instrumented package so the code transform actually
// sees its source. Vite externalizes dependencies in SSR builds by
Expand All@@ -75,16 +28,7 @@ function bundlerMarkerPlugin(): UnknownPlugin {
// diagnostics_channel calls never get injected. Vite merges array
// `noExternal` entries with the user's config, so we don't overwrite
// their additions.
return { ssr: { noExternal: INSTRUMENTED_MODULE_NAMES } };
},
renderChunk(code: string, chunk: { isEntry: boolean }): { code: string; map: unknown } | null {
if (!chunk.isEntry) return null;
// Prepend via magic-string so the entry chunk's sourcemap stays aligned β€”
// returning `map: null` here would shift every mapping by the banner's
// line count and misattribute server stack traces.
const ms = new MagicString(code);
ms.prepend(banner);
return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
return { ssr: { noExternal: instrumentedModuleNames(options.instrumentations) } };
},
};
}
28 changes: 19 additions & 9 deletions packages/server-utils/src/orchestrion/config/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,14 +74,21 @@ export const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [

/**
* The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`
* (e.g. `['mysql']`).
* merged with any caller-provided `instrumentations` (e.g. `['mysql']`).
*
* Bundler plugins MUST ensure these are actually bundled rather than
* externalized: an externalized dependency is resolved from `node_modules` at
* runtime and never passes through the code transform's `onLoad`, so its
* diagnostics_channel calls are silently never injected.
* diagnostics_channel calls are silently never injected. This includes a
* plugin's custom `instrumentations`, otherwise those extra packages can stay
* externalized and their transform never runs.
*/
export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.map(i => i.module.name));
export function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {
return uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name));
}

/** The instrumented module names from the default Sentry config, with no custom additions. */
export const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();

/**
* Returns `external` with any instrumented packages removed, so a bundler that
Expand All@@ -90,14 +97,17 @@ export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.
* (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`
* is returned unchanged.
*
* (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `INSTRUMENTED_MODULE_NAMES` directly rather than this helper.)
* Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so
* custom instrumentations are stripped too; it defaults to the Sentry config
* list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `instrumentedModuleNames` directly rather than this helper.)
*/
export function withoutInstrumentedExternals(external: readonly string[] | undefined): string[] | undefined {
export function withoutInstrumentedExternals(
external: readonly string[] | undefined,
moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,
): string[] | undefined {
if (!external) {
return undefined;
}
return external.filter(
entry => !INSTRUMENTED_MODULE_NAMES.some(name => entry === name || entry.startsWith(`${name}/`)),
);
return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));
}
2 changes: 1 addition & 1 deletion packages/server-utils/src/orchestrion/runtime/register.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -55,7 +55,7 @@ export function registerDiagnosticsChannelInjection(options?: RegisterDiagnostic
const g = (globalThis.__SENTRY_ORCHESTRION__ ??= {});

// Already injected (runtime --import hook or bundler plugin) β€” nothing to do.
if (g.runtime || g.bundler) {
if (g.runtime) {
return;
}

Expand Down
28 changes: 27 additions & 1 deletion packages/server-utils/test/orchestrion/config.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { describe, expect, it } from 'vitest';
import { INSTRUMENTED_MODULE_NAMES, withoutInstrumentedExternals } from '../../src/orchestrion/config';
import {
INSTRUMENTED_MODULE_NAMES,
instrumentedModuleNames,
withoutInstrumentedExternals,
} from '../../src/orchestrion/config';

describe('orchestrion config β€” scoped @hapi/hapi module', () => {
it('includes the scoped @hapi/hapi name in INSTRUMENTED_MODULE_NAMES', () => {
Expand All@@ -13,3 +18,24 @@ describe('orchestrion config β€” scoped @hapi/hapi module', () => {
expect(withoutInstrumentedExternals(external)).toEqual(['react']);
});
});

describe('orchestrion config β€” custom instrumentations', () => {
const customInstrumentation = { module: { name: 'my-lib' } } as InstrumentationConfig;

it('includes custom instrumentation module names alongside the defaults', () => {
const names = instrumentedModuleNames([customInstrumentation]);
expect(names).toContain('my-lib');
expect(names).toContain('@hapi/hapi');
});

it('strips custom instrumentation packages from an externals list', () => {
const external = ['react', 'my-lib', 'my-lib/sub'];
const names = instrumentedModuleNames([customInstrumentation]);
expect(withoutInstrumentedExternals(external, names)).toEqual(['react']);
});

it('leaves custom instrumentation packages externalized when only the defaults are used', () => {
const external = ['react', 'my-lib'];
expect(withoutInstrumentedExternals(external)).toEqual(['react', 'my-lib']);
});
Comment thread
timfish marked this conversation as resolved.
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,11 +41,19 @@
"types": "./build/types/orchestrion/bundler/vite.d.ts",
"import": "./build/esm/orchestrion/bundler/vite.js"
},
"./orchestrion/rollup": {
"types": "./build/types/orchestrion/bundler/rollup.d.ts",
"import": "./build/esm/orchestrion/bundler/rollup.js"
},
"./orchestrion/webpack": {
"types": "./build/types/orchestrion/bundler/webpack.d.ts",
"import": "./build/esm/orchestrion/bundler/webpack.js",
"require": "./build/cjs/orchestrion/bundler/webpack.js"
},
"./orchestrion/esbuild": {
"types": "./build/types/orchestrion/bundler/esbuild.d.ts",
"import": "./build/esm/orchestrion/bundler/esbuild.js"
},
"./orchestrion/import-hook": {
"import": "./build/orchestrion/import-hook.mjs"
}
Expand All@@ -67,8 +75,14 @@
"orchestrion/vite": [
"build/types-ts3.8/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types-ts3.8/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types-ts3.8/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types-ts3.8/orchestrion/bundler/esbuild.d.ts"
]
},
"*": {
Expand All@@ -84,8 +98,14 @@
"orchestrion/vite": [
"build/types/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types/orchestrion/bundler/esbuild.d.ts"
]
}
},
Expand All@@ -97,8 +117,7 @@
"@apm-js-collab/code-transformer": "^0.18.0",
"@apm-js-collab/tracing-hooks": "^0.11.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.65.0",
"magic-string": "~0.30.0"
"@sentry/core": "10.65.0"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
10 changes: 6 additions & 4 deletions packages/server-utils/rollup.npm.config.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,10 +19,10 @@ export default [
...orchestrionRuntimeHooks,
...makeNPMConfigVariants(
makeBaseNPMConfig({
// `src/orchestrion/config/index.ts` and `src/orchestrion/bundler/vite.ts` are
// loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`) β€” neither is reachable from `src/index.ts`, so we
// list them as separate entrypoints to guarantee they end up in build/esm
// `src/orchestrion/config/index.ts` and the `src/orchestrion/bundler/*.ts`
// plugins are loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`, etc.) β€” none are reachable from `src/index.ts`, so
// we list them as separate entrypoints to guarantee they end up in build/esm
// and build/cjs. `src/orchestrion/index.ts` backs the `./orchestrion`
// subpath export.
entrypoints: [
Expand All@@ -34,7 +34,9 @@ export default [
// `Sentry.init()` to install the channel-injection hooks.
'src/orchestrion/runtime/register.ts',
'src/orchestrion/bundler/vite.ts',
'src/orchestrion/bundler/rollup.ts',
'src/orchestrion/bundler/webpack.ts',
'src/orchestrion/bundler/esbuild.ts',
],
packageSpecificConfig: {
output: {
Expand Down
24 changes: 24 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/esbuild.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/esbuild';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* esbuild plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with esbuild. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* esbuild does not flatten nested `plugins` arrays, so this returns a single
* plugin that strips instrumented packages from an `external` denylist before
* delegating to the upstream transform.
*
* @example
* ```ts
* // build.mjs
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/esbuild';
* await esbuild.build({ plugins: [sentryOrchestrionPlugin()] });
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
Comment thread
timfish marked this conversation as resolved.
Comment thread
timfish marked this conversation as resolved.
}
Comment thread
timfish marked this conversation as resolved.
28 changes: 28 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import type codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';

export type PluginOptions = {
/**
* Additional instrumentations to include with the default instrumentation.
*/
instrumentations?: InstrumentationConfig[];
};

/**
* The `@apm-js-collab/code-transformer-bundler-plugins` options shared by every
* orchestrion bundler plugin.
*
* `injectDiagnostics` sets `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at
* app boot so the `_experimentalSetupOrchestrion()` detector can confirm the
* bundler path ran (rather than relying on a build-time flag that wouldn't be
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): Parameters<typeof codeTransformer>[0] {
return {
instrumentations: [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])],
injectDiagnostics: () => {
return '(globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{}).bundler=true;';
Comment thread
timfish marked this conversation as resolved.
},
};
}
20 changes: 20 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/rollup.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Rollup plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with Rollup. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* @example
* ```ts
* // rollup.config.js
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
}
Comment thread
timfish marked this conversation as resolved.
70 changes: 7 additions & 63 deletions packages/server-utils/src/orchestrion/bundler/vite.ts
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,7 @@
// EXPERIMENTAL β€” Vite plugin that runs the orchestrion code transform at build
// time, injecting `diagnostics_channel.tracingChannel` calls into the libraries
// listed in `SENTRY_INSTRUMENTATIONS`.
//
// This file is published ESM-only via the `@sentry/server-utils/orchestrion/vite`
// subpath export. `@apm-js-collab/code-transformer-bundler-plugins` is
// `"type": "module"`, so consuming it from a CJS build is intentionally
// unsupported β€” vite.config.ts is almost always ESM in practice. The CJS
// rollup variant still emits this file, but `package.json` only exposes the
// ESM entry, so attempts to `require('@sentry/server-utils/orchestrion/vite')` will
// fail at resolution time rather than producing a half-broken plugin.

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type UnknownPlugin = any;

import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/vite';
import MagicString from 'magic-string';
Comment thread
timfish marked this conversation as resolved.
import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
Comment thread
sentry[bot] marked this conversation as resolved.

// `vite` types live in the package's ESM-only subpath; under Node16 module
// resolution with TS treating @sentry/server-utils as CJS, importing them produces a
// false positive. We don't need the runtime value for typing β€” `UnknownPlugin`
// is sufficient β€” so we omit the import entirely.
import { instrumentedModuleNames } from '../config';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Vite plugin that runs the orchestrion code transform on the bundled output.
Expand All@@ -29,44 +10,16 @@ import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
* pipeline, SvelteKit). For unbundled Node processes use the runtime hook
* instead (`node --import @sentry/node/orchestrion app.js`).
*
* Returns two plugins:
Comment thread
timfish marked this conversation as resolved.
* 1. `sentry-orchestrion-marker` β€” a `renderChunk` hook that prepends a
Comment thread
timfish marked this conversation as resolved.
* single-line banner to entry chunks. The banner sets
* `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at app boot, so the
* `_experimentalSetupOrchestrion()` detector can confirm the bundler path
* ran (rather than relying on a build-time flag that wouldn't be visible
* to the runtime).
* Also injects every instrumented package name into `ssr.noExternal` via
* the `config` hook, since externalized deps are `require()`d at runtime
* from `node_modules` and never pass through the transform.
* 2. The upstream `@apm-js-collab/code-transformer-bundler-plugins/vite`
* plugin, fed our central `SENTRY_INSTRUMENTATIONS` config.
*
* @example
* ```ts
* // vite.config.ts
* import { sentryOrchestrionPlugin } from '@sentry/node/orchestrion/vite';
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
Comment thread
isaacs marked this conversation as resolved.
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(): UnknownPlugin[] {
const codeTransformerPlugins = codeTransformer({ instrumentations: SENTRY_INSTRUMENTATIONS });
const codeTransformerArray: UnknownPlugin[] = Array.isArray(codeTransformerPlugins)
? codeTransformerPlugins
: [codeTransformerPlugins];
return [bundlerMarkerPlugin(), ...codeTransformerArray];
}

function bundlerMarkerPlugin(): UnknownPlugin {
const banner = [
'globalThis.__SENTRY_ORCHESTRION__ = (globalThis.__SENTRY_ORCHESTRION__ || {});',
'globalThis.__SENTRY_ORCHESTRION__.bundler = true;',
'',
].join('\n');

export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return {
name: 'sentry-orchestrion-marker',
enforce: 'pre' as const,
...codeTransformer(orchestrionTransformOptions(options)),
config(): { ssr: { noExternal: string[] } } {
// Force-bundle every instrumented package so the code transform actually
// sees its source. Vite externalizes dependencies in SSR builds by
Expand All@@ -75,16 +28,7 @@ function bundlerMarkerPlugin(): UnknownPlugin {
// diagnostics_channel calls never get injected. Vite merges array
// `noExternal` entries with the user's config, so we don't overwrite
// their additions.
return { ssr: { noExternal: INSTRUMENTED_MODULE_NAMES } };
},
renderChunk(code: string, chunk: { isEntry: boolean }): { code: string; map: unknown } | null {
if (!chunk.isEntry) return null;
// Prepend via magic-string so the entry chunk's sourcemap stays aligned β€”
// returning `map: null` here would shift every mapping by the banner's
// line count and misattribute server stack traces.
const ms = new MagicString(code);
ms.prepend(banner);
return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
return { ssr: { noExternal: instrumentedModuleNames(options.instrumentations) } };
},
};
}
28 changes: 19 additions & 9 deletions packages/server-utils/src/orchestrion/config/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,14 +74,21 @@ export const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [

/**
* The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`
* (e.g. `['mysql']`).
* merged with any caller-provided `instrumentations` (e.g. `['mysql']`).
*
* Bundler plugins MUST ensure these are actually bundled rather than
* externalized: an externalized dependency is resolved from `node_modules` at
* runtime and never passes through the code transform's `onLoad`, so its
* diagnostics_channel calls are silently never injected.
* diagnostics_channel calls are silently never injected. This includes a
* plugin's custom `instrumentations`, otherwise those extra packages can stay
* externalized and their transform never runs.
*/
export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.map(i => i.module.name));
export function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {
return uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name));
}

/** The instrumented module names from the default Sentry config, with no custom additions. */
export const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();

/**
* Returns `external` with any instrumented packages removed, so a bundler that
Expand All@@ -90,14 +97,17 @@ export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.
* (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`
* is returned unchanged.
*
* (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `INSTRUMENTED_MODULE_NAMES` directly rather than this helper.)
* Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so
* custom instrumentations are stripped too; it defaults to the Sentry config
* list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `instrumentedModuleNames` directly rather than this helper.)
*/
export function withoutInstrumentedExternals(external: readonly string[] | undefined): string[] | undefined {
export function withoutInstrumentedExternals(
external: readonly string[] | undefined,
moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,
): string[] | undefined {
if (!external) {
return undefined;
}
return external.filter(
entry => !INSTRUMENTED_MODULE_NAMES.some(name => entry === name || entry.startsWith(`${name}/`)),
);
return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));
}
2 changes: 1 addition & 1 deletion packages/server-utils/src/orchestrion/runtime/register.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -55,7 +55,7 @@ export function registerDiagnosticsChannelInjection(options?: RegisterDiagnostic
const g = (globalThis.__SENTRY_ORCHESTRION__ ??= {});

// Already injected (runtime --import hook or bundler plugin) β€” nothing to do.
if (g.runtime || g.bundler) {
if (g.runtime) {
return;
}

Expand Down
28 changes: 27 additions & 1 deletion packages/server-utils/test/orchestrion/config.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { describe, expect, it } from 'vitest';
import { INSTRUMENTED_MODULE_NAMES, withoutInstrumentedExternals } from '../../src/orchestrion/config';
import {
INSTRUMENTED_MODULE_NAMES,
instrumentedModuleNames,
withoutInstrumentedExternals,
} from '../../src/orchestrion/config';

describe('orchestrion config β€” scoped @hapi/hapi module', () => {
it('includes the scoped @hapi/hapi name in INSTRUMENTED_MODULE_NAMES', () => {
Expand All@@ -13,3 +18,24 @@ describe('orchestrion config β€” scoped @hapi/hapi module', () => {
expect(withoutInstrumentedExternals(external)).toEqual(['react']);
});
});

describe('orchestrion config β€” custom instrumentations', () => {
const customInstrumentation = { module: { name: 'my-lib' } } as InstrumentationConfig;

it('includes custom instrumentation module names alongside the defaults', () => {
const names = instrumentedModuleNames([customInstrumentation]);
expect(names).toContain('my-lib');
expect(names).toContain('@hapi/hapi');
});

it('strips custom instrumentation packages from an externals list', () => {
const external = ['react', 'my-lib', 'my-lib/sub'];
const names = instrumentedModuleNames([customInstrumentation]);
expect(withoutInstrumentedExternals(external, names)).toEqual(['react']);
});

it('leaves custom instrumentation packages externalized when only the defaults are used', () => {
const external = ['react', 'my-lib'];
expect(withoutInstrumentedExternals(external)).toEqual(['react', 'my-lib']);
});
Comment thread
timfish marked this conversation as resolved.
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,11 +41,19 @@
"types": "./build/types/orchestrion/bundler/vite.d.ts",
"import": "./build/esm/orchestrion/bundler/vite.js"
},
"./orchestrion/rollup": {
"types": "./build/types/orchestrion/bundler/rollup.d.ts",
"import": "./build/esm/orchestrion/bundler/rollup.js"
},
"./orchestrion/webpack": {
"types": "./build/types/orchestrion/bundler/webpack.d.ts",
"import": "./build/esm/orchestrion/bundler/webpack.js",
"require": "./build/cjs/orchestrion/bundler/webpack.js"
},
"./orchestrion/esbuild": {
"types": "./build/types/orchestrion/bundler/esbuild.d.ts",
"import": "./build/esm/orchestrion/bundler/esbuild.js"
},
"./orchestrion/import-hook": {
"import": "./build/orchestrion/import-hook.mjs"
}
Expand All@@ -67,8 +75,14 @@
"orchestrion/vite": [
"build/types-ts3.8/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types-ts3.8/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types-ts3.8/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types-ts3.8/orchestrion/bundler/esbuild.d.ts"
]
},
"*": {
Expand All@@ -84,8 +98,14 @@
"orchestrion/vite": [
"build/types/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types/orchestrion/bundler/esbuild.d.ts"
]
}
},
Expand All@@ -97,8 +117,7 @@
"@apm-js-collab/code-transformer": "^0.18.0",
"@apm-js-collab/tracing-hooks": "^0.11.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.65.0",
"magic-string": "~0.30.0"
"@sentry/core": "10.65.0"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
10 changes: 6 additions & 4 deletions packages/server-utils/rollup.npm.config.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,10 +19,10 @@ export default [
...orchestrionRuntimeHooks,
...makeNPMConfigVariants(
makeBaseNPMConfig({
// `src/orchestrion/config/index.ts` and `src/orchestrion/bundler/vite.ts` are
// loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`) β€” neither is reachable from `src/index.ts`, so we
// list them as separate entrypoints to guarantee they end up in build/esm
// `src/orchestrion/config/index.ts` and the `src/orchestrion/bundler/*.ts`
// plugins are loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`, etc.) β€” none are reachable from `src/index.ts`, so
// we list them as separate entrypoints to guarantee they end up in build/esm
// and build/cjs. `src/orchestrion/index.ts` backs the `./orchestrion`
// subpath export.
entrypoints: [
Expand All@@ -34,7 +34,9 @@ export default [
// `Sentry.init()` to install the channel-injection hooks.
'src/orchestrion/runtime/register.ts',
'src/orchestrion/bundler/vite.ts',
'src/orchestrion/bundler/rollup.ts',
'src/orchestrion/bundler/webpack.ts',
'src/orchestrion/bundler/esbuild.ts',
],
packageSpecificConfig: {
output: {
Expand Down
24 changes: 24 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/esbuild.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/esbuild';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* esbuild plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with esbuild. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* esbuild does not flatten nested `plugins` arrays, so this returns a single
* plugin that strips instrumented packages from an `external` denylist before
* delegating to the upstream transform.
*
* @example
* ```ts
* // build.mjs
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/esbuild';
* await esbuild.build({ plugins: [sentryOrchestrionPlugin()] });
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
Comment thread
timfish marked this conversation as resolved.
Comment thread
timfish marked this conversation as resolved.
}
Comment thread
timfish marked this conversation as resolved.
28 changes: 28 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import type codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';

export type PluginOptions = {
/**
* Additional instrumentations to include with the default instrumentation.
*/
instrumentations?: InstrumentationConfig[];
};

/**
* The `@apm-js-collab/code-transformer-bundler-plugins` options shared by every
* orchestrion bundler plugin.
*
* `injectDiagnostics` sets `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at
* app boot so the `_experimentalSetupOrchestrion()` detector can confirm the
* bundler path ran (rather than relying on a build-time flag that wouldn't be
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): Parameters<typeof codeTransformer>[0] {
return {
instrumentations: [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])],
injectDiagnostics: () => {
return '(globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{}).bundler=true;';
Comment thread
timfish marked this conversation as resolved.
},
};
}
20 changes: 20 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/rollup.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Rollup plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with Rollup. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* @example
* ```ts
* // rollup.config.js
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
}
Comment thread
timfish marked this conversation as resolved.
70 changes: 7 additions & 63 deletions packages/server-utils/src/orchestrion/bundler/vite.ts
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,7 @@
// EXPERIMENTAL β€” Vite plugin that runs the orchestrion code transform at build
// time, injecting `diagnostics_channel.tracingChannel` calls into the libraries
// listed in `SENTRY_INSTRUMENTATIONS`.
//
// This file is published ESM-only via the `@sentry/server-utils/orchestrion/vite`
// subpath export. `@apm-js-collab/code-transformer-bundler-plugins` is
// `"type": "module"`, so consuming it from a CJS build is intentionally
// unsupported β€” vite.config.ts is almost always ESM in practice. The CJS
// rollup variant still emits this file, but `package.json` only exposes the
// ESM entry, so attempts to `require('@sentry/server-utils/orchestrion/vite')` will
// fail at resolution time rather than producing a half-broken plugin.

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type UnknownPlugin = any;

import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/vite';
import MagicString from 'magic-string';
Comment thread
timfish marked this conversation as resolved.
import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
Comment thread
sentry[bot] marked this conversation as resolved.

// `vite` types live in the package's ESM-only subpath; under Node16 module
// resolution with TS treating @sentry/server-utils as CJS, importing them produces a
// false positive. We don't need the runtime value for typing β€” `UnknownPlugin`
// is sufficient β€” so we omit the import entirely.
import { instrumentedModuleNames } from '../config';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Vite plugin that runs the orchestrion code transform on the bundled output.
Expand All@@ -29,44 +10,16 @@ import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
* pipeline, SvelteKit). For unbundled Node processes use the runtime hook
* instead (`node --import @sentry/node/orchestrion app.js`).
*
* Returns two plugins:
Comment thread
timfish marked this conversation as resolved.
* 1. `sentry-orchestrion-marker` β€” a `renderChunk` hook that prepends a
Comment thread
timfish marked this conversation as resolved.
* single-line banner to entry chunks. The banner sets
* `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at app boot, so the
* `_experimentalSetupOrchestrion()` detector can confirm the bundler path
* ran (rather than relying on a build-time flag that wouldn't be visible
* to the runtime).
* Also injects every instrumented package name into `ssr.noExternal` via
* the `config` hook, since externalized deps are `require()`d at runtime
* from `node_modules` and never pass through the transform.
* 2. The upstream `@apm-js-collab/code-transformer-bundler-plugins/vite`
* plugin, fed our central `SENTRY_INSTRUMENTATIONS` config.
*
* @example
* ```ts
* // vite.config.ts
* import { sentryOrchestrionPlugin } from '@sentry/node/orchestrion/vite';
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
Comment thread
isaacs marked this conversation as resolved.
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(): UnknownPlugin[] {
const codeTransformerPlugins = codeTransformer({ instrumentations: SENTRY_INSTRUMENTATIONS });
const codeTransformerArray: UnknownPlugin[] = Array.isArray(codeTransformerPlugins)
? codeTransformerPlugins
: [codeTransformerPlugins];
return [bundlerMarkerPlugin(), ...codeTransformerArray];
}

function bundlerMarkerPlugin(): UnknownPlugin {
const banner = [
'globalThis.__SENTRY_ORCHESTRION__ = (globalThis.__SENTRY_ORCHESTRION__ || {});',
'globalThis.__SENTRY_ORCHESTRION__.bundler = true;',
'',
].join('\n');

export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return {
name: 'sentry-orchestrion-marker',
enforce: 'pre' as const,
...codeTransformer(orchestrionTransformOptions(options)),
config(): { ssr: { noExternal: string[] } } {
// Force-bundle every instrumented package so the code transform actually
// sees its source. Vite externalizes dependencies in SSR builds by
Expand All@@ -75,16 +28,7 @@ function bundlerMarkerPlugin(): UnknownPlugin {
// diagnostics_channel calls never get injected. Vite merges array
// `noExternal` entries with the user's config, so we don't overwrite
// their additions.
return { ssr: { noExternal: INSTRUMENTED_MODULE_NAMES } };
},
renderChunk(code: string, chunk: { isEntry: boolean }): { code: string; map: unknown } | null {
if (!chunk.isEntry) return null;
// Prepend via magic-string so the entry chunk's sourcemap stays aligned β€”
// returning `map: null` here would shift every mapping by the banner's
// line count and misattribute server stack traces.
const ms = new MagicString(code);
ms.prepend(banner);
return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
return { ssr: { noExternal: instrumentedModuleNames(options.instrumentations) } };
},
};
}
28 changes: 19 additions & 9 deletions packages/server-utils/src/orchestrion/config/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,14 +74,21 @@ export const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [

/**
* The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`
* (e.g. `['mysql']`).
* merged with any caller-provided `instrumentations` (e.g. `['mysql']`).
*
* Bundler plugins MUST ensure these are actually bundled rather than
* externalized: an externalized dependency is resolved from `node_modules` at
* runtime and never passes through the code transform's `onLoad`, so its
* diagnostics_channel calls are silently never injected.
* diagnostics_channel calls are silently never injected. This includes a
* plugin's custom `instrumentations`, otherwise those extra packages can stay
* externalized and their transform never runs.
*/
export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.map(i => i.module.name));
export function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {
return uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name));
}

/** The instrumented module names from the default Sentry config, with no custom additions. */
export const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();

/**
* Returns `external` with any instrumented packages removed, so a bundler that
Expand All@@ -90,14 +97,17 @@ export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.
* (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`
* is returned unchanged.
*
* (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `INSTRUMENTED_MODULE_NAMES` directly rather than this helper.)
* Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so
* custom instrumentations are stripped too; it defaults to the Sentry config
* list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `instrumentedModuleNames` directly rather than this helper.)
*/
export function withoutInstrumentedExternals(external: readonly string[] | undefined): string[] | undefined {
export function withoutInstrumentedExternals(
external: readonly string[] | undefined,
moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,
): string[] | undefined {
if (!external) {
return undefined;
}
return external.filter(
entry => !INSTRUMENTED_MODULE_NAMES.some(name => entry === name || entry.startsWith(`${name}/`)),
);
return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));
}
2 changes: 1 addition & 1 deletion packages/server-utils/src/orchestrion/runtime/register.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -55,7 +55,7 @@ export function registerDiagnosticsChannelInjection(options?: RegisterDiagnostic
const g = (globalThis.__SENTRY_ORCHESTRION__ ??= {});

// Already injected (runtime --import hook or bundler plugin) β€” nothing to do.
if (g.runtime || g.bundler) {
if (g.runtime) {
return;
}

Expand Down
28 changes: 27 additions & 1 deletion packages/server-utils/test/orchestrion/config.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { describe, expect, it } from 'vitest';
import { INSTRUMENTED_MODULE_NAMES, withoutInstrumentedExternals } from '../../src/orchestrion/config';
import {
INSTRUMENTED_MODULE_NAMES,
instrumentedModuleNames,
withoutInstrumentedExternals,
} from '../../src/orchestrion/config';

describe('orchestrion config β€” scoped @hapi/hapi module', () => {
it('includes the scoped @hapi/hapi name in INSTRUMENTED_MODULE_NAMES', () => {
Expand All@@ -13,3 +18,24 @@ describe('orchestrion config β€” scoped @hapi/hapi module', () => {
expect(withoutInstrumentedExternals(external)).toEqual(['react']);
});
});

describe('orchestrion config β€” custom instrumentations', () => {
const customInstrumentation = { module: { name: 'my-lib' } } as InstrumentationConfig;

it('includes custom instrumentation module names alongside the defaults', () => {
const names = instrumentedModuleNames([customInstrumentation]);
expect(names).toContain('my-lib');
expect(names).toContain('@hapi/hapi');
});

it('strips custom instrumentation packages from an externals list', () => {
const external = ['react', 'my-lib', 'my-lib/sub'];
const names = instrumentedModuleNames([customInstrumentation]);
expect(withoutInstrumentedExternals(external, names)).toEqual(['react']);
});

it('leaves custom instrumentation packages externalized when only the defaults are used', () => {
const external = ['react', 'my-lib'];
expect(withoutInstrumentedExternals(external)).toEqual(['react', 'my-lib']);
});
Comment thread
timfish marked this conversation as resolved.
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,11 +41,19 @@
"types": "./build/types/orchestrion/bundler/vite.d.ts",
"import": "./build/esm/orchestrion/bundler/vite.js"
},
"./orchestrion/rollup": {
"types": "./build/types/orchestrion/bundler/rollup.d.ts",
"import": "./build/esm/orchestrion/bundler/rollup.js"
},
"./orchestrion/webpack": {
"types": "./build/types/orchestrion/bundler/webpack.d.ts",
"import": "./build/esm/orchestrion/bundler/webpack.js",
"require": "./build/cjs/orchestrion/bundler/webpack.js"
},
"./orchestrion/esbuild": {
"types": "./build/types/orchestrion/bundler/esbuild.d.ts",
"import": "./build/esm/orchestrion/bundler/esbuild.js"
},
"./orchestrion/import-hook": {
"import": "./build/orchestrion/import-hook.mjs"
}
Expand All@@ -67,8 +75,14 @@
"orchestrion/vite": [
"build/types-ts3.8/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types-ts3.8/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types-ts3.8/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types-ts3.8/orchestrion/bundler/esbuild.d.ts"
]
},
"*": {
Expand All@@ -84,8 +98,14 @@
"orchestrion/vite": [
"build/types/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types/orchestrion/bundler/esbuild.d.ts"
]
}
},
Expand All@@ -97,8 +117,7 @@
"@apm-js-collab/code-transformer": "^0.18.0",
"@apm-js-collab/tracing-hooks": "^0.11.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.65.0",
"magic-string": "~0.30.0"
"@sentry/core": "10.65.0"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
10 changes: 6 additions & 4 deletions packages/server-utils/rollup.npm.config.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,10 +19,10 @@ export default [
...orchestrionRuntimeHooks,
...makeNPMConfigVariants(
makeBaseNPMConfig({
// `src/orchestrion/config/index.ts` and `src/orchestrion/bundler/vite.ts` are
// loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`) β€” neither is reachable from `src/index.ts`, so we
// list them as separate entrypoints to guarantee they end up in build/esm
// `src/orchestrion/config/index.ts` and the `src/orchestrion/bundler/*.ts`
// plugins are loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`, etc.) β€” none are reachable from `src/index.ts`, so
// we list them as separate entrypoints to guarantee they end up in build/esm
// and build/cjs. `src/orchestrion/index.ts` backs the `./orchestrion`
// subpath export.
entrypoints: [
Expand All@@ -34,7 +34,9 @@ export default [
// `Sentry.init()` to install the channel-injection hooks.
'src/orchestrion/runtime/register.ts',
'src/orchestrion/bundler/vite.ts',
'src/orchestrion/bundler/rollup.ts',
'src/orchestrion/bundler/webpack.ts',
'src/orchestrion/bundler/esbuild.ts',
],
packageSpecificConfig: {
output: {
Expand Down
24 changes: 24 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/esbuild.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/esbuild';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* esbuild plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with esbuild. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* esbuild does not flatten nested `plugins` arrays, so this returns a single
* plugin that strips instrumented packages from an `external` denylist before
* delegating to the upstream transform.
*
* @example
* ```ts
* // build.mjs
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/esbuild';
* await esbuild.build({ plugins: [sentryOrchestrionPlugin()] });
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
Comment thread
timfish marked this conversation as resolved.
Comment thread
timfish marked this conversation as resolved.
}
Comment thread
timfish marked this conversation as resolved.
28 changes: 28 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import type codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';

export type PluginOptions = {
/**
* Additional instrumentations to include with the default instrumentation.
*/
instrumentations?: InstrumentationConfig[];
};

/**
* The `@apm-js-collab/code-transformer-bundler-plugins` options shared by every
* orchestrion bundler plugin.
*
* `injectDiagnostics` sets `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at
* app boot so the `_experimentalSetupOrchestrion()` detector can confirm the
* bundler path ran (rather than relying on a build-time flag that wouldn't be
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): Parameters<typeof codeTransformer>[0] {
return {
instrumentations: [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])],
injectDiagnostics: () => {
return '(globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{}).bundler=true;';
Comment thread
timfish marked this conversation as resolved.
},
};
}
20 changes: 20 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/rollup.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Rollup plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with Rollup. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* @example
* ```ts
* // rollup.config.js
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
}
Comment thread
timfish marked this conversation as resolved.
70 changes: 7 additions & 63 deletions packages/server-utils/src/orchestrion/bundler/vite.ts
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,7 @@
// EXPERIMENTAL β€” Vite plugin that runs the orchestrion code transform at build
// time, injecting `diagnostics_channel.tracingChannel` calls into the libraries
// listed in `SENTRY_INSTRUMENTATIONS`.
//
// This file is published ESM-only via the `@sentry/server-utils/orchestrion/vite`
// subpath export. `@apm-js-collab/code-transformer-bundler-plugins` is
// `"type": "module"`, so consuming it from a CJS build is intentionally
// unsupported β€” vite.config.ts is almost always ESM in practice. The CJS
// rollup variant still emits this file, but `package.json` only exposes the
// ESM entry, so attempts to `require('@sentry/server-utils/orchestrion/vite')` will
// fail at resolution time rather than producing a half-broken plugin.

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type UnknownPlugin = any;

import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/vite';
import MagicString from 'magic-string';
Comment thread
timfish marked this conversation as resolved.
import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
Comment thread
sentry[bot] marked this conversation as resolved.

// `vite` types live in the package's ESM-only subpath; under Node16 module
// resolution with TS treating @sentry/server-utils as CJS, importing them produces a
// false positive. We don't need the runtime value for typing β€” `UnknownPlugin`
// is sufficient β€” so we omit the import entirely.
import { instrumentedModuleNames } from '../config';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Vite plugin that runs the orchestrion code transform on the bundled output.
Expand All@@ -29,44 +10,16 @@ import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
* pipeline, SvelteKit). For unbundled Node processes use the runtime hook
* instead (`node --import @sentry/node/orchestrion app.js`).
*
* Returns two plugins:
Comment thread
timfish marked this conversation as resolved.
* 1. `sentry-orchestrion-marker` β€” a `renderChunk` hook that prepends a
Comment thread
timfish marked this conversation as resolved.
* single-line banner to entry chunks. The banner sets
* `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at app boot, so the
* `_experimentalSetupOrchestrion()` detector can confirm the bundler path
* ran (rather than relying on a build-time flag that wouldn't be visible
* to the runtime).
* Also injects every instrumented package name into `ssr.noExternal` via
* the `config` hook, since externalized deps are `require()`d at runtime
* from `node_modules` and never pass through the transform.
* 2. The upstream `@apm-js-collab/code-transformer-bundler-plugins/vite`
* plugin, fed our central `SENTRY_INSTRUMENTATIONS` config.
*
* @example
* ```ts
* // vite.config.ts
* import { sentryOrchestrionPlugin } from '@sentry/node/orchestrion/vite';
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
Comment thread
isaacs marked this conversation as resolved.
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(): UnknownPlugin[] {
const codeTransformerPlugins = codeTransformer({ instrumentations: SENTRY_INSTRUMENTATIONS });
const codeTransformerArray: UnknownPlugin[] = Array.isArray(codeTransformerPlugins)
? codeTransformerPlugins
: [codeTransformerPlugins];
return [bundlerMarkerPlugin(), ...codeTransformerArray];
}

function bundlerMarkerPlugin(): UnknownPlugin {
const banner = [
'globalThis.__SENTRY_ORCHESTRION__ = (globalThis.__SENTRY_ORCHESTRION__ || {});',
'globalThis.__SENTRY_ORCHESTRION__.bundler = true;',
'',
].join('\n');

export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return {
name: 'sentry-orchestrion-marker',
enforce: 'pre' as const,
...codeTransformer(orchestrionTransformOptions(options)),
config(): { ssr: { noExternal: string[] } } {
// Force-bundle every instrumented package so the code transform actually
// sees its source. Vite externalizes dependencies in SSR builds by
Expand All@@ -75,16 +28,7 @@ function bundlerMarkerPlugin(): UnknownPlugin {
// diagnostics_channel calls never get injected. Vite merges array
// `noExternal` entries with the user's config, so we don't overwrite
// their additions.
return { ssr: { noExternal: INSTRUMENTED_MODULE_NAMES } };
},
renderChunk(code: string, chunk: { isEntry: boolean }): { code: string; map: unknown } | null {
if (!chunk.isEntry) return null;
// Prepend via magic-string so the entry chunk's sourcemap stays aligned β€”
// returning `map: null` here would shift every mapping by the banner's
// line count and misattribute server stack traces.
const ms = new MagicString(code);
ms.prepend(banner);
return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
return { ssr: { noExternal: instrumentedModuleNames(options.instrumentations) } };
},
};
}
28 changes: 19 additions & 9 deletions packages/server-utils/src/orchestrion/config/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,14 +74,21 @@ export const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [

/**
* The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`
* (e.g. `['mysql']`).
* merged with any caller-provided `instrumentations` (e.g. `['mysql']`).
*
* Bundler plugins MUST ensure these are actually bundled rather than
* externalized: an externalized dependency is resolved from `node_modules` at
* runtime and never passes through the code transform's `onLoad`, so its
* diagnostics_channel calls are silently never injected.
* diagnostics_channel calls are silently never injected. This includes a
* plugin's custom `instrumentations`, otherwise those extra packages can stay
* externalized and their transform never runs.
*/
export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.map(i => i.module.name));
export function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {
return uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name));
}

/** The instrumented module names from the default Sentry config, with no custom additions. */
export const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();

/**
* Returns `external` with any instrumented packages removed, so a bundler that
Expand All@@ -90,14 +97,17 @@ export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.
* (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`
* is returned unchanged.
*
* (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `INSTRUMENTED_MODULE_NAMES` directly rather than this helper.)
* Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so
* custom instrumentations are stripped too; it defaults to the Sentry config
* list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `instrumentedModuleNames` directly rather than this helper.)
*/
export function withoutInstrumentedExternals(external: readonly string[] | undefined): string[] | undefined {
export function withoutInstrumentedExternals(
external: readonly string[] | undefined,
moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,
): string[] | undefined {
if (!external) {
return undefined;
}
return external.filter(
entry => !INSTRUMENTED_MODULE_NAMES.some(name => entry === name || entry.startsWith(`${name}/`)),
);
return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));
}
2 changes: 1 addition & 1 deletion packages/server-utils/src/orchestrion/runtime/register.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -55,7 +55,7 @@ export function registerDiagnosticsChannelInjection(options?: RegisterDiagnostic
const g = (globalThis.__SENTRY_ORCHESTRION__ ??= {});

// Already injected (runtime --import hook or bundler plugin) β€” nothing to do.
if (g.runtime || g.bundler) {
if (g.runtime) {
return;
}

Expand Down
28 changes: 27 additions & 1 deletion packages/server-utils/test/orchestrion/config.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { describe, expect, it } from 'vitest';
import { INSTRUMENTED_MODULE_NAMES, withoutInstrumentedExternals } from '../../src/orchestrion/config';
import {
INSTRUMENTED_MODULE_NAMES,
instrumentedModuleNames,
withoutInstrumentedExternals,
} from '../../src/orchestrion/config';

describe('orchestrion config β€” scoped @hapi/hapi module', () => {
it('includes the scoped @hapi/hapi name in INSTRUMENTED_MODULE_NAMES', () => {
Expand All@@ -13,3 +18,24 @@ describe('orchestrion config β€” scoped @hapi/hapi module', () => {
expect(withoutInstrumentedExternals(external)).toEqual(['react']);
});
});

describe('orchestrion config β€” custom instrumentations', () => {
const customInstrumentation = { module: { name: 'my-lib' } } as InstrumentationConfig;

it('includes custom instrumentation module names alongside the defaults', () => {
const names = instrumentedModuleNames([customInstrumentation]);
expect(names).toContain('my-lib');
expect(names).toContain('@hapi/hapi');
});

it('strips custom instrumentation packages from an externals list', () => {
const external = ['react', 'my-lib', 'my-lib/sub'];
const names = instrumentedModuleNames([customInstrumentation]);
expect(withoutInstrumentedExternals(external, names)).toEqual(['react']);
});

it('leaves custom instrumentation packages externalized when only the defaults are used', () => {
const external = ['react', 'my-lib'];
expect(withoutInstrumentedExternals(external)).toEqual(['react', 'my-lib']);
});
Comment thread
timfish marked this conversation as resolved.
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,11 +41,19 @@
"types": "./build/types/orchestrion/bundler/vite.d.ts",
"import": "./build/esm/orchestrion/bundler/vite.js"
},
"./orchestrion/rollup": {
"types": "./build/types/orchestrion/bundler/rollup.d.ts",
"import": "./build/esm/orchestrion/bundler/rollup.js"
},
"./orchestrion/webpack": {
"types": "./build/types/orchestrion/bundler/webpack.d.ts",
"import": "./build/esm/orchestrion/bundler/webpack.js",
"require": "./build/cjs/orchestrion/bundler/webpack.js"
},
"./orchestrion/esbuild": {
"types": "./build/types/orchestrion/bundler/esbuild.d.ts",
"import": "./build/esm/orchestrion/bundler/esbuild.js"
},
"./orchestrion/import-hook": {
"import": "./build/orchestrion/import-hook.mjs"
}
Expand All@@ -67,8 +75,14 @@
"orchestrion/vite": [
"build/types-ts3.8/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types-ts3.8/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types-ts3.8/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types-ts3.8/orchestrion/bundler/esbuild.d.ts"
]
},
"*": {
Expand All@@ -84,8 +98,14 @@
"orchestrion/vite": [
"build/types/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types/orchestrion/bundler/esbuild.d.ts"
]
}
},
Expand All@@ -97,8 +117,7 @@
"@apm-js-collab/code-transformer": "^0.18.0",
"@apm-js-collab/tracing-hooks": "^0.11.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.65.0",
"magic-string": "~0.30.0"
"@sentry/core": "10.65.0"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
10 changes: 6 additions & 4 deletions packages/server-utils/rollup.npm.config.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,10 +19,10 @@ export default [
...orchestrionRuntimeHooks,
...makeNPMConfigVariants(
makeBaseNPMConfig({
// `src/orchestrion/config/index.ts` and `src/orchestrion/bundler/vite.ts` are
// loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`) β€” neither is reachable from `src/index.ts`, so we
// list them as separate entrypoints to guarantee they end up in build/esm
// `src/orchestrion/config/index.ts` and the `src/orchestrion/bundler/*.ts`
// plugins are loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`, etc.) β€” none are reachable from `src/index.ts`, so
// we list them as separate entrypoints to guarantee they end up in build/esm
// and build/cjs. `src/orchestrion/index.ts` backs the `./orchestrion`
// subpath export.
entrypoints: [
Expand All@@ -34,7 +34,9 @@ export default [
// `Sentry.init()` to install the channel-injection hooks.
'src/orchestrion/runtime/register.ts',
'src/orchestrion/bundler/vite.ts',
'src/orchestrion/bundler/rollup.ts',
'src/orchestrion/bundler/webpack.ts',
'src/orchestrion/bundler/esbuild.ts',
],
packageSpecificConfig: {
output: {
Expand Down
24 changes: 24 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/esbuild.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/esbuild';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* esbuild plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with esbuild. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* esbuild does not flatten nested `plugins` arrays, so this returns a single
* plugin that strips instrumented packages from an `external` denylist before
* delegating to the upstream transform.
*
* @example
* ```ts
* // build.mjs
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/esbuild';
* await esbuild.build({ plugins: [sentryOrchestrionPlugin()] });
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
Comment thread
timfish marked this conversation as resolved.
Comment thread
timfish marked this conversation as resolved.
}
Comment thread
timfish marked this conversation as resolved.
28 changes: 28 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import type codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';

export type PluginOptions = {
/**
* Additional instrumentations to include with the default instrumentation.
*/
instrumentations?: InstrumentationConfig[];
};

/**
* The `@apm-js-collab/code-transformer-bundler-plugins` options shared by every
* orchestrion bundler plugin.
*
* `injectDiagnostics` sets `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at
* app boot so the `_experimentalSetupOrchestrion()` detector can confirm the
* bundler path ran (rather than relying on a build-time flag that wouldn't be
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): Parameters<typeof codeTransformer>[0] {
return {
instrumentations: [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])],
injectDiagnostics: () => {
return '(globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{}).bundler=true;';
Comment thread
timfish marked this conversation as resolved.
},
};
}
20 changes: 20 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/rollup.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Rollup plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with Rollup. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* @example
* ```ts
* // rollup.config.js
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
}
Comment thread
timfish marked this conversation as resolved.
70 changes: 7 additions & 63 deletions packages/server-utils/src/orchestrion/bundler/vite.ts
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,7 @@
// EXPERIMENTAL β€” Vite plugin that runs the orchestrion code transform at build
// time, injecting `diagnostics_channel.tracingChannel` calls into the libraries
// listed in `SENTRY_INSTRUMENTATIONS`.
//
// This file is published ESM-only via the `@sentry/server-utils/orchestrion/vite`
// subpath export. `@apm-js-collab/code-transformer-bundler-plugins` is
// `"type": "module"`, so consuming it from a CJS build is intentionally
// unsupported β€” vite.config.ts is almost always ESM in practice. The CJS
// rollup variant still emits this file, but `package.json` only exposes the
// ESM entry, so attempts to `require('@sentry/server-utils/orchestrion/vite')` will
// fail at resolution time rather than producing a half-broken plugin.

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type UnknownPlugin = any;

import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/vite';
import MagicString from 'magic-string';
Comment thread
timfish marked this conversation as resolved.
import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
Comment thread
sentry[bot] marked this conversation as resolved.

// `vite` types live in the package's ESM-only subpath; under Node16 module
// resolution with TS treating @sentry/server-utils as CJS, importing them produces a
// false positive. We don't need the runtime value for typing β€” `UnknownPlugin`
// is sufficient β€” so we omit the import entirely.
import { instrumentedModuleNames } from '../config';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Vite plugin that runs the orchestrion code transform on the bundled output.
Expand All@@ -29,44 +10,16 @@ import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
* pipeline, SvelteKit). For unbundled Node processes use the runtime hook
* instead (`node --import @sentry/node/orchestrion app.js`).
*
* Returns two plugins:
Comment thread
timfish marked this conversation as resolved.
* 1. `sentry-orchestrion-marker` β€” a `renderChunk` hook that prepends a
Comment thread
timfish marked this conversation as resolved.
* single-line banner to entry chunks. The banner sets
* `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at app boot, so the
* `_experimentalSetupOrchestrion()` detector can confirm the bundler path
* ran (rather than relying on a build-time flag that wouldn't be visible
* to the runtime).
* Also injects every instrumented package name into `ssr.noExternal` via
* the `config` hook, since externalized deps are `require()`d at runtime
* from `node_modules` and never pass through the transform.
* 2. The upstream `@apm-js-collab/code-transformer-bundler-plugins/vite`
* plugin, fed our central `SENTRY_INSTRUMENTATIONS` config.
*
* @example
* ```ts
* // vite.config.ts
* import { sentryOrchestrionPlugin } from '@sentry/node/orchestrion/vite';
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
Comment thread
isaacs marked this conversation as resolved.
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(): UnknownPlugin[] {
const codeTransformerPlugins = codeTransformer({ instrumentations: SENTRY_INSTRUMENTATIONS });
const codeTransformerArray: UnknownPlugin[] = Array.isArray(codeTransformerPlugins)
? codeTransformerPlugins
: [codeTransformerPlugins];
return [bundlerMarkerPlugin(), ...codeTransformerArray];
}

function bundlerMarkerPlugin(): UnknownPlugin {
const banner = [
'globalThis.__SENTRY_ORCHESTRION__ = (globalThis.__SENTRY_ORCHESTRION__ || {});',
'globalThis.__SENTRY_ORCHESTRION__.bundler = true;',
'',
].join('\n');

export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return {
name: 'sentry-orchestrion-marker',
enforce: 'pre' as const,
...codeTransformer(orchestrionTransformOptions(options)),
config(): { ssr: { noExternal: string[] } } {
// Force-bundle every instrumented package so the code transform actually
// sees its source. Vite externalizes dependencies in SSR builds by
Expand All@@ -75,16 +28,7 @@ function bundlerMarkerPlugin(): UnknownPlugin {
// diagnostics_channel calls never get injected. Vite merges array
// `noExternal` entries with the user's config, so we don't overwrite
// their additions.
return { ssr: { noExternal: INSTRUMENTED_MODULE_NAMES } };
},
renderChunk(code: string, chunk: { isEntry: boolean }): { code: string; map: unknown } | null {
if (!chunk.isEntry) return null;
// Prepend via magic-string so the entry chunk's sourcemap stays aligned β€”
// returning `map: null` here would shift every mapping by the banner's
// line count and misattribute server stack traces.
const ms = new MagicString(code);
ms.prepend(banner);
return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
return { ssr: { noExternal: instrumentedModuleNames(options.instrumentations) } };
},
};
}
28 changes: 19 additions & 9 deletions packages/server-utils/src/orchestrion/config/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,14 +74,21 @@ export const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [

/**
* The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`
* (e.g. `['mysql']`).
* merged with any caller-provided `instrumentations` (e.g. `['mysql']`).
*
* Bundler plugins MUST ensure these are actually bundled rather than
* externalized: an externalized dependency is resolved from `node_modules` at
* runtime and never passes through the code transform's `onLoad`, so its
* diagnostics_channel calls are silently never injected.
* diagnostics_channel calls are silently never injected. This includes a
* plugin's custom `instrumentations`, otherwise those extra packages can stay
* externalized and their transform never runs.
*/
export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.map(i => i.module.name));
export function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {
return uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name));
}

/** The instrumented module names from the default Sentry config, with no custom additions. */
export const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();

/**
* Returns `external` with any instrumented packages removed, so a bundler that
Expand All@@ -90,14 +97,17 @@ export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.
* (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`
* is returned unchanged.
*
* (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `INSTRUMENTED_MODULE_NAMES` directly rather than this helper.)
* Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so
* custom instrumentations are stripped too; it defaults to the Sentry config
* list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `instrumentedModuleNames` directly rather than this helper.)
*/
export function withoutInstrumentedExternals(external: readonly string[] | undefined): string[] | undefined {
export function withoutInstrumentedExternals(
external: readonly string[] | undefined,
moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,
): string[] | undefined {
if (!external) {
return undefined;
}
return external.filter(
entry => !INSTRUMENTED_MODULE_NAMES.some(name => entry === name || entry.startsWith(`${name}/`)),
);
return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));
}
2 changes: 1 addition & 1 deletion packages/server-utils/src/orchestrion/runtime/register.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -55,7 +55,7 @@ export function registerDiagnosticsChannelInjection(options?: RegisterDiagnostic
const g = (globalThis.__SENTRY_ORCHESTRION__ ??= {});

// Already injected (runtime --import hook or bundler plugin) β€” nothing to do.
if (g.runtime || g.bundler) {
if (g.runtime) {
return;
}

Expand Down
28 changes: 27 additions & 1 deletion packages/server-utils/test/orchestrion/config.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { describe, expect, it } from 'vitest';
import { INSTRUMENTED_MODULE_NAMES, withoutInstrumentedExternals } from '../../src/orchestrion/config';
import {
INSTRUMENTED_MODULE_NAMES,
instrumentedModuleNames,
withoutInstrumentedExternals,
} from '../../src/orchestrion/config';

describe('orchestrion config β€” scoped @hapi/hapi module', () => {
it('includes the scoped @hapi/hapi name in INSTRUMENTED_MODULE_NAMES', () => {
Expand All@@ -13,3 +18,24 @@ describe('orchestrion config β€” scoped @hapi/hapi module', () => {
expect(withoutInstrumentedExternals(external)).toEqual(['react']);
});
});

describe('orchestrion config β€” custom instrumentations', () => {
const customInstrumentation = { module: { name: 'my-lib' } } as InstrumentationConfig;

it('includes custom instrumentation module names alongside the defaults', () => {
const names = instrumentedModuleNames([customInstrumentation]);
expect(names).toContain('my-lib');
expect(names).toContain('@hapi/hapi');
});

it('strips custom instrumentation packages from an externals list', () => {
const external = ['react', 'my-lib', 'my-lib/sub'];
const names = instrumentedModuleNames([customInstrumentation]);
expect(withoutInstrumentedExternals(external, names)).toEqual(['react']);
});

it('leaves custom instrumentation packages externalized when only the defaults are used', () => {
const external = ['react', 'my-lib'];
expect(withoutInstrumentedExternals(external)).toEqual(['react', 'my-lib']);
});
Comment thread
timfish marked this conversation as resolved.
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,11 +41,19 @@
"types": "./build/types/orchestrion/bundler/vite.d.ts",
"import": "./build/esm/orchestrion/bundler/vite.js"
},
"./orchestrion/rollup": {
"types": "./build/types/orchestrion/bundler/rollup.d.ts",
"import": "./build/esm/orchestrion/bundler/rollup.js"
},
"./orchestrion/webpack": {
"types": "./build/types/orchestrion/bundler/webpack.d.ts",
"import": "./build/esm/orchestrion/bundler/webpack.js",
"require": "./build/cjs/orchestrion/bundler/webpack.js"
},
"./orchestrion/esbuild": {
"types": "./build/types/orchestrion/bundler/esbuild.d.ts",
"import": "./build/esm/orchestrion/bundler/esbuild.js"
},
"./orchestrion/import-hook": {
"import": "./build/orchestrion/import-hook.mjs"
}
Expand All@@ -67,8 +75,14 @@
"orchestrion/vite": [
"build/types-ts3.8/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types-ts3.8/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types-ts3.8/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types-ts3.8/orchestrion/bundler/esbuild.d.ts"
]
},
"*": {
Expand All@@ -84,8 +98,14 @@
"orchestrion/vite": [
"build/types/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types/orchestrion/bundler/esbuild.d.ts"
]
}
},
Expand All@@ -97,8 +117,7 @@
"@apm-js-collab/code-transformer": "^0.18.0",
"@apm-js-collab/tracing-hooks": "^0.11.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.65.0",
"magic-string": "~0.30.0"
"@sentry/core": "10.65.0"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
10 changes: 6 additions & 4 deletions packages/server-utils/rollup.npm.config.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,10 +19,10 @@ export default [
...orchestrionRuntimeHooks,
...makeNPMConfigVariants(
makeBaseNPMConfig({
// `src/orchestrion/config/index.ts` and `src/orchestrion/bundler/vite.ts` are
// loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`) β€” neither is reachable from `src/index.ts`, so we
// list them as separate entrypoints to guarantee they end up in build/esm
// `src/orchestrion/config/index.ts` and the `src/orchestrion/bundler/*.ts`
// plugins are loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`, etc.) β€” none are reachable from `src/index.ts`, so
// we list them as separate entrypoints to guarantee they end up in build/esm
// and build/cjs. `src/orchestrion/index.ts` backs the `./orchestrion`
// subpath export.
entrypoints: [
Expand All@@ -34,7 +34,9 @@ export default [
// `Sentry.init()` to install the channel-injection hooks.
'src/orchestrion/runtime/register.ts',
'src/orchestrion/bundler/vite.ts',
'src/orchestrion/bundler/rollup.ts',
'src/orchestrion/bundler/webpack.ts',
'src/orchestrion/bundler/esbuild.ts',
],
packageSpecificConfig: {
output: {
Expand Down
24 changes: 24 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/esbuild.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/esbuild';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* esbuild plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with esbuild. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* esbuild does not flatten nested `plugins` arrays, so this returns a single
* plugin that strips instrumented packages from an `external` denylist before
* delegating to the upstream transform.
*
* @example
* ```ts
* // build.mjs
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/esbuild';
* await esbuild.build({ plugins: [sentryOrchestrionPlugin()] });
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
Comment thread
timfish marked this conversation as resolved.
Comment thread
timfish marked this conversation as resolved.
}
Comment thread
timfish marked this conversation as resolved.
28 changes: 28 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import type codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';

export type PluginOptions = {
/**
* Additional instrumentations to include with the default instrumentation.
*/
instrumentations?: InstrumentationConfig[];
};

/**
* The `@apm-js-collab/code-transformer-bundler-plugins` options shared by every
* orchestrion bundler plugin.
*
* `injectDiagnostics` sets `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at
* app boot so the `_experimentalSetupOrchestrion()` detector can confirm the
* bundler path ran (rather than relying on a build-time flag that wouldn't be
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): Parameters<typeof codeTransformer>[0] {
return {
instrumentations: [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])],
injectDiagnostics: () => {
return '(globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{}).bundler=true;';
Comment thread
timfish marked this conversation as resolved.
},
};
}
20 changes: 20 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/rollup.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Rollup plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with Rollup. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* @example
* ```ts
* // rollup.config.js
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
}
Comment thread
timfish marked this conversation as resolved.
70 changes: 7 additions & 63 deletions packages/server-utils/src/orchestrion/bundler/vite.ts
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,7 @@
// EXPERIMENTAL β€” Vite plugin that runs the orchestrion code transform at build
// time, injecting `diagnostics_channel.tracingChannel` calls into the libraries
// listed in `SENTRY_INSTRUMENTATIONS`.
//
// This file is published ESM-only via the `@sentry/server-utils/orchestrion/vite`
// subpath export. `@apm-js-collab/code-transformer-bundler-plugins` is
// `"type": "module"`, so consuming it from a CJS build is intentionally
// unsupported β€” vite.config.ts is almost always ESM in practice. The CJS
// rollup variant still emits this file, but `package.json` only exposes the
// ESM entry, so attempts to `require('@sentry/server-utils/orchestrion/vite')` will
// fail at resolution time rather than producing a half-broken plugin.

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type UnknownPlugin = any;

import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/vite';
import MagicString from 'magic-string';
Comment thread
timfish marked this conversation as resolved.
import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
Comment thread
sentry[bot] marked this conversation as resolved.

// `vite` types live in the package's ESM-only subpath; under Node16 module
// resolution with TS treating @sentry/server-utils as CJS, importing them produces a
// false positive. We don't need the runtime value for typing β€” `UnknownPlugin`
// is sufficient β€” so we omit the import entirely.
import { instrumentedModuleNames } from '../config';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Vite plugin that runs the orchestrion code transform on the bundled output.
Expand All@@ -29,44 +10,16 @@ import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
* pipeline, SvelteKit). For unbundled Node processes use the runtime hook
* instead (`node --import @sentry/node/orchestrion app.js`).
*
* Returns two plugins:
Comment thread
timfish marked this conversation as resolved.
* 1. `sentry-orchestrion-marker` β€” a `renderChunk` hook that prepends a
Comment thread
timfish marked this conversation as resolved.
* single-line banner to entry chunks. The banner sets
* `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at app boot, so the
* `_experimentalSetupOrchestrion()` detector can confirm the bundler path
* ran (rather than relying on a build-time flag that wouldn't be visible
* to the runtime).
* Also injects every instrumented package name into `ssr.noExternal` via
* the `config` hook, since externalized deps are `require()`d at runtime
* from `node_modules` and never pass through the transform.
* 2. The upstream `@apm-js-collab/code-transformer-bundler-plugins/vite`
* plugin, fed our central `SENTRY_INSTRUMENTATIONS` config.
*
* @example
* ```ts
* // vite.config.ts
* import { sentryOrchestrionPlugin } from '@sentry/node/orchestrion/vite';
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
Comment thread
isaacs marked this conversation as resolved.
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(): UnknownPlugin[] {
const codeTransformerPlugins = codeTransformer({ instrumentations: SENTRY_INSTRUMENTATIONS });
const codeTransformerArray: UnknownPlugin[] = Array.isArray(codeTransformerPlugins)
? codeTransformerPlugins
: [codeTransformerPlugins];
return [bundlerMarkerPlugin(), ...codeTransformerArray];
}

function bundlerMarkerPlugin(): UnknownPlugin {
const banner = [
'globalThis.__SENTRY_ORCHESTRION__ = (globalThis.__SENTRY_ORCHESTRION__ || {});',
'globalThis.__SENTRY_ORCHESTRION__.bundler = true;',
'',
].join('\n');

export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return {
name: 'sentry-orchestrion-marker',
enforce: 'pre' as const,
...codeTransformer(orchestrionTransformOptions(options)),
config(): { ssr: { noExternal: string[] } } {
// Force-bundle every instrumented package so the code transform actually
// sees its source. Vite externalizes dependencies in SSR builds by
Expand All@@ -75,16 +28,7 @@ function bundlerMarkerPlugin(): UnknownPlugin {
// diagnostics_channel calls never get injected. Vite merges array
// `noExternal` entries with the user's config, so we don't overwrite
// their additions.
return { ssr: { noExternal: INSTRUMENTED_MODULE_NAMES } };
},
renderChunk(code: string, chunk: { isEntry: boolean }): { code: string; map: unknown } | null {
if (!chunk.isEntry) return null;
// Prepend via magic-string so the entry chunk's sourcemap stays aligned β€”
// returning `map: null` here would shift every mapping by the banner's
// line count and misattribute server stack traces.
const ms = new MagicString(code);
ms.prepend(banner);
return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
return { ssr: { noExternal: instrumentedModuleNames(options.instrumentations) } };
},
};
}
28 changes: 19 additions & 9 deletions packages/server-utils/src/orchestrion/config/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,14 +74,21 @@ export const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [

/**
* The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`
* (e.g. `['mysql']`).
* merged with any caller-provided `instrumentations` (e.g. `['mysql']`).
*
* Bundler plugins MUST ensure these are actually bundled rather than
* externalized: an externalized dependency is resolved from `node_modules` at
* runtime and never passes through the code transform's `onLoad`, so its
* diagnostics_channel calls are silently never injected.
* diagnostics_channel calls are silently never injected. This includes a
* plugin's custom `instrumentations`, otherwise those extra packages can stay
* externalized and their transform never runs.
*/
export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.map(i => i.module.name));
export function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {
return uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name));
}

/** The instrumented module names from the default Sentry config, with no custom additions. */
export const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();

/**
* Returns `external` with any instrumented packages removed, so a bundler that
Expand All@@ -90,14 +97,17 @@ export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.
* (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`
* is returned unchanged.
*
* (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `INSTRUMENTED_MODULE_NAMES` directly rather than this helper.)
* Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so
* custom instrumentations are stripped too; it defaults to the Sentry config
* list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `instrumentedModuleNames` directly rather than this helper.)
*/
export function withoutInstrumentedExternals(external: readonly string[] | undefined): string[] | undefined {
export function withoutInstrumentedExternals(
external: readonly string[] | undefined,
moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,
): string[] | undefined {
if (!external) {
return undefined;
}
return external.filter(
entry => !INSTRUMENTED_MODULE_NAMES.some(name => entry === name || entry.startsWith(`${name}/`)),
);
return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));
}
2 changes: 1 addition & 1 deletion packages/server-utils/src/orchestrion/runtime/register.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -55,7 +55,7 @@ export function registerDiagnosticsChannelInjection(options?: RegisterDiagnostic
const g = (globalThis.__SENTRY_ORCHESTRION__ ??= {});

// Already injected (runtime --import hook or bundler plugin) β€” nothing to do.
if (g.runtime || g.bundler) {
if (g.runtime) {
return;
}

Expand Down
28 changes: 27 additions & 1 deletion packages/server-utils/test/orchestrion/config.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { describe, expect, it } from 'vitest';
import { INSTRUMENTED_MODULE_NAMES, withoutInstrumentedExternals } from '../../src/orchestrion/config';
import {
INSTRUMENTED_MODULE_NAMES,
instrumentedModuleNames,
withoutInstrumentedExternals,
} from '../../src/orchestrion/config';

describe('orchestrion config β€” scoped @hapi/hapi module', () => {
it('includes the scoped @hapi/hapi name in INSTRUMENTED_MODULE_NAMES', () => {
Expand All@@ -13,3 +18,24 @@ describe('orchestrion config β€” scoped @hapi/hapi module', () => {
expect(withoutInstrumentedExternals(external)).toEqual(['react']);
});
});

describe('orchestrion config β€” custom instrumentations', () => {
const customInstrumentation = { module: { name: 'my-lib' } } as InstrumentationConfig;

it('includes custom instrumentation module names alongside the defaults', () => {
const names = instrumentedModuleNames([customInstrumentation]);
expect(names).toContain('my-lib');
expect(names).toContain('@hapi/hapi');
});

it('strips custom instrumentation packages from an externals list', () => {
const external = ['react', 'my-lib', 'my-lib/sub'];
const names = instrumentedModuleNames([customInstrumentation]);
expect(withoutInstrumentedExternals(external, names)).toEqual(['react']);
});

it('leaves custom instrumentation packages externalized when only the defaults are used', () => {
const external = ['react', 'my-lib'];
expect(withoutInstrumentedExternals(external)).toEqual(['react', 'my-lib']);
});
Comment thread
timfish marked this conversation as resolved.
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,11 +41,19 @@
"types": "./build/types/orchestrion/bundler/vite.d.ts",
"import": "./build/esm/orchestrion/bundler/vite.js"
},
"./orchestrion/rollup": {
"types": "./build/types/orchestrion/bundler/rollup.d.ts",
"import": "./build/esm/orchestrion/bundler/rollup.js"
},
"./orchestrion/webpack": {
"types": "./build/types/orchestrion/bundler/webpack.d.ts",
"import": "./build/esm/orchestrion/bundler/webpack.js",
"require": "./build/cjs/orchestrion/bundler/webpack.js"
},
"./orchestrion/esbuild": {
"types": "./build/types/orchestrion/bundler/esbuild.d.ts",
"import": "./build/esm/orchestrion/bundler/esbuild.js"
},
"./orchestrion/import-hook": {
"import": "./build/orchestrion/import-hook.mjs"
}
Expand All@@ -67,8 +75,14 @@
"orchestrion/vite": [
"build/types-ts3.8/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types-ts3.8/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types-ts3.8/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types-ts3.8/orchestrion/bundler/esbuild.d.ts"
]
},
"*": {
Expand All@@ -84,8 +98,14 @@
"orchestrion/vite": [
"build/types/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types/orchestrion/bundler/esbuild.d.ts"
]
}
},
Expand All@@ -97,8 +117,7 @@
"@apm-js-collab/code-transformer": "^0.18.0",
"@apm-js-collab/tracing-hooks": "^0.11.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.65.0",
"magic-string": "~0.30.0"
"@sentry/core": "10.65.0"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
10 changes: 6 additions & 4 deletions packages/server-utils/rollup.npm.config.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,10 +19,10 @@ export default [
...orchestrionRuntimeHooks,
...makeNPMConfigVariants(
makeBaseNPMConfig({
// `src/orchestrion/config/index.ts` and `src/orchestrion/bundler/vite.ts` are
// loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`) β€” neither is reachable from `src/index.ts`, so we
// list them as separate entrypoints to guarantee they end up in build/esm
// `src/orchestrion/config/index.ts` and the `src/orchestrion/bundler/*.ts`
// plugins are loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`, etc.) β€” none are reachable from `src/index.ts`, so
// we list them as separate entrypoints to guarantee they end up in build/esm
// and build/cjs. `src/orchestrion/index.ts` backs the `./orchestrion`
// subpath export.
entrypoints: [
Expand All@@ -34,7 +34,9 @@ export default [
// `Sentry.init()` to install the channel-injection hooks.
'src/orchestrion/runtime/register.ts',
'src/orchestrion/bundler/vite.ts',
'src/orchestrion/bundler/rollup.ts',
'src/orchestrion/bundler/webpack.ts',
'src/orchestrion/bundler/esbuild.ts',
],
packageSpecificConfig: {
output: {
Expand Down
24 changes: 24 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/esbuild.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/esbuild';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* esbuild plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with esbuild. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* esbuild does not flatten nested `plugins` arrays, so this returns a single
* plugin that strips instrumented packages from an `external` denylist before
* delegating to the upstream transform.
*
* @example
* ```ts
* // build.mjs
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/esbuild';
* await esbuild.build({ plugins: [sentryOrchestrionPlugin()] });
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
Comment thread
timfish marked this conversation as resolved.
Comment thread
timfish marked this conversation as resolved.
}
Comment thread
timfish marked this conversation as resolved.
28 changes: 28 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import type codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';

export type PluginOptions = {
/**
* Additional instrumentations to include with the default instrumentation.
*/
instrumentations?: InstrumentationConfig[];
};

/**
* The `@apm-js-collab/code-transformer-bundler-plugins` options shared by every
* orchestrion bundler plugin.
*
* `injectDiagnostics` sets `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at
* app boot so the `_experimentalSetupOrchestrion()` detector can confirm the
* bundler path ran (rather than relying on a build-time flag that wouldn't be
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): Parameters<typeof codeTransformer>[0] {
return {
instrumentations: [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])],
injectDiagnostics: () => {
return '(globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{}).bundler=true;';
Comment thread
timfish marked this conversation as resolved.
},
};
}
20 changes: 20 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/rollup.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Rollup plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with Rollup. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* @example
* ```ts
* // rollup.config.js
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
}
Comment thread
timfish marked this conversation as resolved.
70 changes: 7 additions & 63 deletions packages/server-utils/src/orchestrion/bundler/vite.ts
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,7 @@
// EXPERIMENTAL β€” Vite plugin that runs the orchestrion code transform at build
// time, injecting `diagnostics_channel.tracingChannel` calls into the libraries
// listed in `SENTRY_INSTRUMENTATIONS`.
//
// This file is published ESM-only via the `@sentry/server-utils/orchestrion/vite`
// subpath export. `@apm-js-collab/code-transformer-bundler-plugins` is
// `"type": "module"`, so consuming it from a CJS build is intentionally
// unsupported β€” vite.config.ts is almost always ESM in practice. The CJS
// rollup variant still emits this file, but `package.json` only exposes the
// ESM entry, so attempts to `require('@sentry/server-utils/orchestrion/vite')` will
// fail at resolution time rather than producing a half-broken plugin.

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type UnknownPlugin = any;

import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/vite';
import MagicString from 'magic-string';
Comment thread
timfish marked this conversation as resolved.
import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
Comment thread
sentry[bot] marked this conversation as resolved.

// `vite` types live in the package's ESM-only subpath; under Node16 module
// resolution with TS treating @sentry/server-utils as CJS, importing them produces a
// false positive. We don't need the runtime value for typing β€” `UnknownPlugin`
// is sufficient β€” so we omit the import entirely.
import { instrumentedModuleNames } from '../config';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Vite plugin that runs the orchestrion code transform on the bundled output.
Expand All@@ -29,44 +10,16 @@ import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
* pipeline, SvelteKit). For unbundled Node processes use the runtime hook
* instead (`node --import @sentry/node/orchestrion app.js`).
*
* Returns two plugins:
Comment thread
timfish marked this conversation as resolved.
* 1. `sentry-orchestrion-marker` β€” a `renderChunk` hook that prepends a
Comment thread
timfish marked this conversation as resolved.
* single-line banner to entry chunks. The banner sets
* `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at app boot, so the
* `_experimentalSetupOrchestrion()` detector can confirm the bundler path
* ran (rather than relying on a build-time flag that wouldn't be visible
* to the runtime).
* Also injects every instrumented package name into `ssr.noExternal` via
* the `config` hook, since externalized deps are `require()`d at runtime
* from `node_modules` and never pass through the transform.
* 2. The upstream `@apm-js-collab/code-transformer-bundler-plugins/vite`
* plugin, fed our central `SENTRY_INSTRUMENTATIONS` config.
*
* @example
* ```ts
* // vite.config.ts
* import { sentryOrchestrionPlugin } from '@sentry/node/orchestrion/vite';
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
Comment thread
isaacs marked this conversation as resolved.
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(): UnknownPlugin[] {
const codeTransformerPlugins = codeTransformer({ instrumentations: SENTRY_INSTRUMENTATIONS });
const codeTransformerArray: UnknownPlugin[] = Array.isArray(codeTransformerPlugins)
? codeTransformerPlugins
: [codeTransformerPlugins];
return [bundlerMarkerPlugin(), ...codeTransformerArray];
}

function bundlerMarkerPlugin(): UnknownPlugin {
const banner = [
'globalThis.__SENTRY_ORCHESTRION__ = (globalThis.__SENTRY_ORCHESTRION__ || {});',
'globalThis.__SENTRY_ORCHESTRION__.bundler = true;',
'',
].join('\n');

export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return {
name: 'sentry-orchestrion-marker',
enforce: 'pre' as const,
...codeTransformer(orchestrionTransformOptions(options)),
config(): { ssr: { noExternal: string[] } } {
// Force-bundle every instrumented package so the code transform actually
// sees its source. Vite externalizes dependencies in SSR builds by
Expand All@@ -75,16 +28,7 @@ function bundlerMarkerPlugin(): UnknownPlugin {
// diagnostics_channel calls never get injected. Vite merges array
// `noExternal` entries with the user's config, so we don't overwrite
// their additions.
return { ssr: { noExternal: INSTRUMENTED_MODULE_NAMES } };
},
renderChunk(code: string, chunk: { isEntry: boolean }): { code: string; map: unknown } | null {
if (!chunk.isEntry) return null;
// Prepend via magic-string so the entry chunk's sourcemap stays aligned β€”
// returning `map: null` here would shift every mapping by the banner's
// line count and misattribute server stack traces.
const ms = new MagicString(code);
ms.prepend(banner);
return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
return { ssr: { noExternal: instrumentedModuleNames(options.instrumentations) } };
},
};
}
28 changes: 19 additions & 9 deletions packages/server-utils/src/orchestrion/config/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,14 +74,21 @@ export const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [

/**
* The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`
* (e.g. `['mysql']`).
* merged with any caller-provided `instrumentations` (e.g. `['mysql']`).
*
* Bundler plugins MUST ensure these are actually bundled rather than
* externalized: an externalized dependency is resolved from `node_modules` at
* runtime and never passes through the code transform's `onLoad`, so its
* diagnostics_channel calls are silently never injected.
* diagnostics_channel calls are silently never injected. This includes a
* plugin's custom `instrumentations`, otherwise those extra packages can stay
* externalized and their transform never runs.
*/
export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.map(i => i.module.name));
export function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {
return uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name));
}

/** The instrumented module names from the default Sentry config, with no custom additions. */
export const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();

/**
* Returns `external` with any instrumented packages removed, so a bundler that
Expand All@@ -90,14 +97,17 @@ export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.
* (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`
* is returned unchanged.
*
* (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `INSTRUMENTED_MODULE_NAMES` directly rather than this helper.)
* Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so
* custom instrumentations are stripped too; it defaults to the Sentry config
* list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `instrumentedModuleNames` directly rather than this helper.)
*/
export function withoutInstrumentedExternals(external: readonly string[] | undefined): string[] | undefined {
export function withoutInstrumentedExternals(
external: readonly string[] | undefined,
moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,
): string[] | undefined {
if (!external) {
return undefined;
}
return external.filter(
entry => !INSTRUMENTED_MODULE_NAMES.some(name => entry === name || entry.startsWith(`${name}/`)),
);
return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));
}
2 changes: 1 addition & 1 deletion packages/server-utils/src/orchestrion/runtime/register.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -55,7 +55,7 @@ export function registerDiagnosticsChannelInjection(options?: RegisterDiagnostic
const g = (globalThis.__SENTRY_ORCHESTRION__ ??= {});

// Already injected (runtime --import hook or bundler plugin) β€” nothing to do.
if (g.runtime || g.bundler) {
if (g.runtime) {
return;
}

Expand Down
28 changes: 27 additions & 1 deletion packages/server-utils/test/orchestrion/config.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { describe, expect, it } from 'vitest';
import { INSTRUMENTED_MODULE_NAMES, withoutInstrumentedExternals } from '../../src/orchestrion/config';
import {
INSTRUMENTED_MODULE_NAMES,
instrumentedModuleNames,
withoutInstrumentedExternals,
} from '../../src/orchestrion/config';

describe('orchestrion config β€” scoped @hapi/hapi module', () => {
it('includes the scoped @hapi/hapi name in INSTRUMENTED_MODULE_NAMES', () => {
Expand All@@ -13,3 +18,24 @@ describe('orchestrion config β€” scoped @hapi/hapi module', () => {
expect(withoutInstrumentedExternals(external)).toEqual(['react']);
});
});

describe('orchestrion config β€” custom instrumentations', () => {
const customInstrumentation = { module: { name: 'my-lib' } } as InstrumentationConfig;

it('includes custom instrumentation module names alongside the defaults', () => {
const names = instrumentedModuleNames([customInstrumentation]);
expect(names).toContain('my-lib');
expect(names).toContain('@hapi/hapi');
});

it('strips custom instrumentation packages from an externals list', () => {
const external = ['react', 'my-lib', 'my-lib/sub'];
const names = instrumentedModuleNames([customInstrumentation]);
expect(withoutInstrumentedExternals(external, names)).toEqual(['react']);
});

it('leaves custom instrumentation packages externalized when only the defaults are used', () => {
const external = ['react', 'my-lib'];
expect(withoutInstrumentedExternals(external)).toEqual(['react', 'my-lib']);
});
Comment thread
timfish marked this conversation as resolved.
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,11 +41,19 @@
"types": "./build/types/orchestrion/bundler/vite.d.ts",
"import": "./build/esm/orchestrion/bundler/vite.js"
},
"./orchestrion/rollup": {
"types": "./build/types/orchestrion/bundler/rollup.d.ts",
"import": "./build/esm/orchestrion/bundler/rollup.js"
},
"./orchestrion/webpack": {
"types": "./build/types/orchestrion/bundler/webpack.d.ts",
"import": "./build/esm/orchestrion/bundler/webpack.js",
"require": "./build/cjs/orchestrion/bundler/webpack.js"
},
"./orchestrion/esbuild": {
"types": "./build/types/orchestrion/bundler/esbuild.d.ts",
"import": "./build/esm/orchestrion/bundler/esbuild.js"
},
"./orchestrion/import-hook": {
"import": "./build/orchestrion/import-hook.mjs"
}
Expand All@@ -67,8 +75,14 @@
"orchestrion/vite": [
"build/types-ts3.8/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types-ts3.8/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types-ts3.8/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types-ts3.8/orchestrion/bundler/esbuild.d.ts"
]
},
"*": {
Expand All@@ -84,8 +98,14 @@
"orchestrion/vite": [
"build/types/orchestrion/bundler/vite.d.ts"
],
"orchestrion/rollup": [
"build/types/orchestrion/bundler/rollup.d.ts"
],
"orchestrion/webpack": [
"build/types/orchestrion/bundler/webpack.d.ts"
],
"orchestrion/esbuild": [
"build/types/orchestrion/bundler/esbuild.d.ts"
]
}
},
Expand All@@ -97,8 +117,7 @@
"@apm-js-collab/code-transformer": "^0.18.0",
"@apm-js-collab/tracing-hooks": "^0.11.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.65.0",
"magic-string": "~0.30.0"
"@sentry/core": "10.65.0"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
10 changes: 6 additions & 4 deletions packages/server-utils/rollup.npm.config.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,10 +19,10 @@ export default [
...orchestrionRuntimeHooks,
...makeNPMConfigVariants(
makeBaseNPMConfig({
// `src/orchestrion/config/index.ts` and `src/orchestrion/bundler/vite.ts` are
// loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`) β€” neither is reachable from `src/index.ts`, so we
// list them as separate entrypoints to guarantee they end up in build/esm
// `src/orchestrion/config/index.ts` and the `src/orchestrion/bundler/*.ts`
// plugins are loaded via dedicated subpath exports (`.../orchestrion/config`,
// `.../orchestrion/vite`, etc.) β€” none are reachable from `src/index.ts`, so
// we list them as separate entrypoints to guarantee they end up in build/esm
// and build/cjs. `src/orchestrion/index.ts` backs the `./orchestrion`
// subpath export.
entrypoints: [
Expand All@@ -34,7 +34,9 @@ export default [
// `Sentry.init()` to install the channel-injection hooks.
'src/orchestrion/runtime/register.ts',
'src/orchestrion/bundler/vite.ts',
'src/orchestrion/bundler/rollup.ts',
'src/orchestrion/bundler/webpack.ts',
'src/orchestrion/bundler/esbuild.ts',
],
packageSpecificConfig: {
output: {
Expand Down
24 changes: 24 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/esbuild.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/esbuild';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* esbuild plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with esbuild. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* esbuild does not flatten nested `plugins` arrays, so this returns a single
* plugin that strips instrumented packages from an `external` denylist before
* delegating to the upstream transform.
*
* @example
* ```ts
* // build.mjs
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/esbuild';
* await esbuild.build({ plugins: [sentryOrchestrionPlugin()] });
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
Comment thread
timfish marked this conversation as resolved.
Comment thread
timfish marked this conversation as resolved.
}
Comment thread
timfish marked this conversation as resolved.
28 changes: 28 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import type codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';

export type PluginOptions = {
/**
* Additional instrumentations to include with the default instrumentation.
*/
instrumentations?: InstrumentationConfig[];
};

/**
* The `@apm-js-collab/code-transformer-bundler-plugins` options shared by every
* orchestrion bundler plugin.
*
* `injectDiagnostics` sets `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at
* app boot so the `_experimentalSetupOrchestrion()` detector can confirm the
* bundler path ran (rather than relying on a build-time flag that wouldn't be
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): Parameters<typeof codeTransformer>[0] {
return {
instrumentations: [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])],
injectDiagnostics: () => {
return '(globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{}).bundler=true;';
Comment thread
timfish marked this conversation as resolved.
},
};
}
20 changes: 20 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/rollup.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Rollup plugin that runs the orchestrion code transform on the bundled output.
*
* Use when bundling a Node app with Rollup. For unbundled Node processes use the
* runtime hook instead (`node --import @sentry/node/orchestrion app.js`).
*
* @example
* ```ts
* // rollup.config.js
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return codeTransformer(orchestrionTransformOptions(options));
}
Comment thread
timfish marked this conversation as resolved.
70 changes: 7 additions & 63 deletions packages/server-utils/src/orchestrion/bundler/vite.ts
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,7 @@
// EXPERIMENTAL β€” Vite plugin that runs the orchestrion code transform at build
// time, injecting `diagnostics_channel.tracingChannel` calls into the libraries
// listed in `SENTRY_INSTRUMENTATIONS`.
//
// This file is published ESM-only via the `@sentry/server-utils/orchestrion/vite`
// subpath export. `@apm-js-collab/code-transformer-bundler-plugins` is
// `"type": "module"`, so consuming it from a CJS build is intentionally
// unsupported β€” vite.config.ts is almost always ESM in practice. The CJS
// rollup variant still emits this file, but `package.json` only exposes the
// ESM entry, so attempts to `require('@sentry/server-utils/orchestrion/vite')` will
// fail at resolution time rather than producing a half-broken plugin.

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type UnknownPlugin = any;

import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/vite';
import MagicString from 'magic-string';
Comment thread
timfish marked this conversation as resolved.
import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
Comment thread
sentry[bot] marked this conversation as resolved.

// `vite` types live in the package's ESM-only subpath; under Node16 module
// resolution with TS treating @sentry/server-utils as CJS, importing them produces a
// false positive. We don't need the runtime value for typing β€” `UnknownPlugin`
// is sufficient β€” so we omit the import entirely.
import { instrumentedModuleNames } from '../config';
import type { PluginOptions } from './options';
import { orchestrionTransformOptions } from './options';

/**
* Vite plugin that runs the orchestrion code transform on the bundled output.
Expand All@@ -29,44 +10,16 @@ import { INSTRUMENTED_MODULE_NAMES, SENTRY_INSTRUMENTATIONS } from '../config';
* pipeline, SvelteKit). For unbundled Node processes use the runtime hook
* instead (`node --import @sentry/node/orchestrion app.js`).
*
* Returns two plugins:
Comment thread
timfish marked this conversation as resolved.
* 1. `sentry-orchestrion-marker` β€” a `renderChunk` hook that prepends a
Comment thread
timfish marked this conversation as resolved.
* single-line banner to entry chunks. The banner sets
* `globalThis.__SENTRY_ORCHESTRION__.bundler = true` at app boot, so the
* `_experimentalSetupOrchestrion()` detector can confirm the bundler path
* ran (rather than relying on a build-time flag that wouldn't be visible
* to the runtime).
* Also injects every instrumented package name into `ssr.noExternal` via
* the `config` hook, since externalized deps are `require()`d at runtime
* from `node_modules` and never pass through the transform.
* 2. The upstream `@apm-js-collab/code-transformer-bundler-plugins/vite`
* plugin, fed our central `SENTRY_INSTRUMENTATIONS` config.
*
* @example
* ```ts
* // vite.config.ts
* import { sentryOrchestrionPlugin } from '@sentry/node/orchestrion/vite';
* import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
Comment thread
isaacs marked this conversation as resolved.
* export default { plugins: [sentryOrchestrionPlugin()] };
* ```
*/
export function sentryOrchestrionPlugin(): UnknownPlugin[] {
const codeTransformerPlugins = codeTransformer({ instrumentations: SENTRY_INSTRUMENTATIONS });
const codeTransformerArray: UnknownPlugin[] = Array.isArray(codeTransformerPlugins)
? codeTransformerPlugins
: [codeTransformerPlugins];
return [bundlerMarkerPlugin(), ...codeTransformerArray];
}

function bundlerMarkerPlugin(): UnknownPlugin {
const banner = [
'globalThis.__SENTRY_ORCHESTRION__ = (globalThis.__SENTRY_ORCHESTRION__ || {});',
'globalThis.__SENTRY_ORCHESTRION__.bundler = true;',
'',
].join('\n');

export function sentryOrchestrionPlugin(options: PluginOptions = {}): ReturnType<typeof codeTransformer> {
return {
name: 'sentry-orchestrion-marker',
enforce: 'pre' as const,
...codeTransformer(orchestrionTransformOptions(options)),
config(): { ssr: { noExternal: string[] } } {
// Force-bundle every instrumented package so the code transform actually
// sees its source. Vite externalizes dependencies in SSR builds by
Expand All@@ -75,16 +28,7 @@ function bundlerMarkerPlugin(): UnknownPlugin {
// diagnostics_channel calls never get injected. Vite merges array
// `noExternal` entries with the user's config, so we don't overwrite
// their additions.
return { ssr: { noExternal: INSTRUMENTED_MODULE_NAMES } };
},
renderChunk(code: string, chunk: { isEntry: boolean }): { code: string; map: unknown } | null {
if (!chunk.isEntry) return null;
// Prepend via magic-string so the entry chunk's sourcemap stays aligned β€”
// returning `map: null` here would shift every mapping by the banner's
// line count and misattribute server stack traces.
const ms = new MagicString(code);
ms.prepend(banner);
return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
return { ssr: { noExternal: instrumentedModuleNames(options.instrumentations) } };
},
};
}
28 changes: 19 additions & 9 deletions packages/server-utils/src/orchestrion/config/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,14 +74,21 @@ export const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [

/**
* The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`
* (e.g. `['mysql']`).
* merged with any caller-provided `instrumentations` (e.g. `['mysql']`).
*
* Bundler plugins MUST ensure these are actually bundled rather than
* externalized: an externalized dependency is resolved from `node_modules` at
* runtime and never passes through the code transform's `onLoad`, so its
* diagnostics_channel calls are silently never injected.
* diagnostics_channel calls are silently never injected. This includes a
* plugin's custom `instrumentations`, otherwise those extra packages can stay
* externalized and their transform never runs.
*/
export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.map(i => i.module.name));
export function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {
return uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name));
}

/** The instrumented module names from the default Sentry config, with no custom additions. */
export const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();

/**
* Returns `external` with any instrumented packages removed, so a bundler that
Expand All@@ -90,14 +97,17 @@ export const INSTRUMENTED_MODULE_NAMES: string[] = uniq(SENTRY_INSTRUMENTATIONS.
* (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`
* is returned unchanged.
*
* (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `INSTRUMENTED_MODULE_NAMES` directly rather than this helper.)
* Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so
* custom instrumentations are stripped too; it defaults to the Sentry config
* list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes
* `instrumentedModuleNames` directly rather than this helper.)
*/
export function withoutInstrumentedExternals(external: readonly string[] | undefined): string[] | undefined {
export function withoutInstrumentedExternals(
external: readonly string[] | undefined,
moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,
): string[] | undefined {
if (!external) {
return undefined;
}
return external.filter(
entry => !INSTRUMENTED_MODULE_NAMES.some(name => entry === name || entry.startsWith(`${name}/`)),
);
return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));
}
2 changes: 1 addition & 1 deletion packages/server-utils/src/orchestrion/runtime/register.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -55,7 +55,7 @@ export function registerDiagnosticsChannelInjection(options?: RegisterDiagnostic
const g = (globalThis.__SENTRY_ORCHESTRION__ ??= {});

// Already injected (runtime --import hook or bundler plugin) β€” nothing to do.
if (g.runtime || g.bundler) {
if (g.runtime) {
return;
}

Expand Down
28 changes: 27 additions & 1 deletion packages/server-utils/test/orchestrion/config.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { describe, expect, it } from 'vitest';
import { INSTRUMENTED_MODULE_NAMES, withoutInstrumentedExternals } from '../../src/orchestrion/config';
import {
INSTRUMENTED_MODULE_NAMES,
instrumentedModuleNames,
withoutInstrumentedExternals,
} from '../../src/orchestrion/config';

describe('orchestrion config β€” scoped @hapi/hapi module', () => {
it('includes the scoped @hapi/hapi name in INSTRUMENTED_MODULE_NAMES', () => {
Expand All@@ -13,3 +18,24 @@ describe('orchestrion config β€” scoped @hapi/hapi module', () => {
expect(withoutInstrumentedExternals(external)).toEqual(['react']);
});
});

describe('orchestrion config β€” custom instrumentations', () => {
const customInstrumentation = { module: { name: 'my-lib' } } as InstrumentationConfig;

it('includes custom instrumentation module names alongside the defaults', () => {
const names = instrumentedModuleNames([customInstrumentation]);
expect(names).toContain('my-lib');
expect(names).toContain('@hapi/hapi');
});

it('strips custom instrumentation packages from an externals list', () => {
const external = ['react', 'my-lib', 'my-lib/sub'];
const names = instrumentedModuleNames([customInstrumentation]);
expect(withoutInstrumentedExternals(external, names)).toEqual(['react']);
});

it('leaves custom instrumentation packages externalized when only the defaults are used', () => {
const external = ['react', 'my-lib'];
expect(withoutInstrumentedExternals(external)).toEqual(['react', 'my-lib']);
});
Comment thread
timfish marked this conversation as resolved.
});
Loading