Skip to content
Draft
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
10 changes: 8 additions & 2 deletions packages/plugins/injection/src/xpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,16 @@ export const getXpackPlugin =

// We need to prepare the injections before the build starts.
// Otherwise they'll be empty once resolved.
compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, async () => {
const setupInjections = async () => {
// Prepare the injections.
await addInjections(log, toInject, contentsToInject, context.buildRoot);
});
};

// For one-time builds (production mode)
compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, setupInjections);

// For watch mode / dev server (webpack dev mode)
compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, setupInjections);

// Handle the InjectPosition.START and InjectPosition.END.
// This is a re-implementation of the BannerPlugin,
Expand Down
24 changes: 24 additions & 0 deletions packages/plugins/rum/src/getSourceCodeContextSnippet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

import type { SourceCodeContextOptions } from './types';

export const DEFAULT_SOURCE_CODE_CONTEXT_VARIABLE = 'DD_SOURCE_CODE_CONTEXT' as const;

// The source code context snippet - single injection with function definition and call
// SSR-safe: checks window before accessing, never throws
//
// Unminified version:
// (function(c, n) {
// try {
// if (typeof window === 'undefined') return;
// var w = window,
// m = w[n] = w[n] || {},
// s = new Error().stack;
// s && (m[s] = c)
// } catch (e) {}
// })(context, variableName);
export const getSourceCodeContextSnippet = (context: SourceCodeContextOptions): string => {
return `(function(c,n){try{if(typeof window==='undefined')return;var w=window,m=w[n]=w[n]||{},s=new Error().stack;s&&(m[s]=c)}catch(e){}})(${JSON.stringify(context)},${JSON.stringify(DEFAULT_SOURCE_CODE_CONTEXT_VARIABLE)});`;
};
26 changes: 15 additions & 11 deletions packages/plugins/rum/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ describe('RUM Plugin', () => {
const injections = {
'browser-sdk': path.resolve('../plugins/rum/src/rum-browser-sdk.js'),
'sdk-init': injectionValue,
'source-code-context':
/(?=.*DD_SOURCE_CODE_CONTEXT)(?=.*"service":"checkout")(?=.*"version":"1\.2\.3")/,
};

const expectations: {
type: string;
config: RumOptions;
should: { inject: (keyof typeof injections)[]; throw?: boolean };
should: { inject: (keyof typeof injections)[] };
}[] = [
{
type: 'no sdk',
Expand All @@ -38,6 +40,16 @@ describe('RUM Plugin', () => {
config: { sdk: { applicationId: 'app-id' } },
should: { inject: ['browser-sdk', 'sdk-init'] },
},
{
type: 'source code context',
config: {
sourceCodeContext: {
service: 'checkout',
version: '1.2.3',
},
},
should: { inject: ['source-code-context'] },
},
];
describe('getPlugins', () => {
const injectMock = jest.fn();
Expand Down Expand Up @@ -79,21 +91,13 @@ describe('RUM Plugin', () => {
const mockContext = getContextMock();
const pluginConfig = { ...defaultPluginOptions, rum: config };

const expectResult = expect(() => {
getPlugins(getGetPluginsArg(pluginConfig, mockContext));
});

if (should.throw) {
expectResult.toThrow();
} else {
expectResult.not.toThrow();
}
getPlugins(getGetPluginsArg(pluginConfig, mockContext));

expect(mockContext.inject).toHaveBeenCalledTimes(should.inject.length);
for (const inject of should.inject) {
expect(mockContext.inject).toHaveBeenCalledWith(
expect.objectContaining({
value: injections[inject],
value: expect.stringMatching(injections[inject]),
}),
);
}
Expand Down
9 changes: 9 additions & 0 deletions packages/plugins/rum/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { InjectPosition } from '@dd/core/types';
import path from 'path';

import { CONFIG_KEY, PLUGIN_NAME } from './constants';
import { getSourceCodeContextSnippet } from './getSourceCodeContextSnippet';
import { getPrivacyPlugin } from './privacy';
import { getInjectionValue } from './sdk';
import type { RumOptions, RumOptionsWithSdk, RumPublicApi, RumInitConfiguration } from './types';
Expand Down Expand Up @@ -36,6 +37,14 @@ export const getPlugins: GetPlugins = ({ options, context }) => {
return plugins;
}

if (validatedOptions.sourceCodeContext) {
context.inject({
type: 'code',
position: InjectPosition.BEFORE,
value: getSourceCodeContextSnippet(validatedOptions.sourceCodeContext),
});
}

// NOTE: These files are built from "@dd/tools/rollupConfig.mjs" and available in the distributed package.
if (validatedOptions.sdk) {
// Inject the SDK from the CDN.
Expand Down
20 changes: 20 additions & 0 deletions packages/plugins/rum/src/sourceCodeContext.ts
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this file accidentally duplicated?

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

import type { Logger } from '@dd/core/types';

import type { SourceCodeContextOptions } from './types';

export const DEFAULT_SOURCE_CODE_CONTEXT_VARIABLE = 'DD_SOURCE_CODE_CONTEXT' as const;

// The source code context snippet - single injection with function definition and call
// SSR-safe: checks window before accessing, never throws
// Minified for minimal bundle size impact
export const getSourceCodeContextSnippet = (
context: SourceCodeContextOptions,
log: Logger,
): string => {
// prettier-ignore
return `(function(c,n){try{if(typeof window==='undefined')return;var w=window,m=w[n]=w[n]||{},s=new Error().stack;s&&(m[s]=c)}catch(e){}})(${JSON.stringify(context)},${JSON.stringify(DEFAULT_SOURCE_CODE_CONTEXT_VARIABLE)});`;
};
7 changes: 7 additions & 0 deletions packages/plugins/rum/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,16 @@ import type { Assign } from '@dd/core/types';

import type { PrivacyOptions, PrivacyOptionsWithDefaults } from './privacy/types';

export type SourceCodeContextOptions = {
service: string;
version?: string;
};

export type RumOptions = {
enable?: boolean;
sdk?: SDKOptions;
privacy?: PrivacyOptions;
sourceCodeContext?: SourceCodeContextOptions;
};

export type RumPublicApi = typeof datadogRum;
Expand Down Expand Up @@ -57,6 +63,7 @@ export type RumOptionsWithDefaults = {
enable?: boolean;
sdk?: SDKOptionsWithDefaults;
privacy?: PrivacyOptionsWithDefaults;
sourceCodeContext?: SourceCodeContextOptions;
};

export type RumOptionsWithSdk = Assign<RumOptionsWithDefaults, { sdk: SDKOptionsWithDefaults }>;
33 changes: 32 additions & 1 deletion packages/plugins/rum/src/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { defaultPluginOptions } from '@dd/tests/_jest/helpers/mocks';
import { createFilter } from '@rollup/pluginutils';

import { validatePrivacyOptions } from './validate';
import { validatePrivacyOptions, validateSourceCodeContextOptions } from './validate';

describe('Test privacy plugin option exclude regex', () => {
let filter: (path: string) => boolean;
Expand Down Expand Up @@ -34,3 +34,34 @@ describe('Test privacy plugin option exclude regex', () => {
expect(filter(path)).toBe(expected);
});
});

describe('sourceCodeContext validation', () => {
test('should return empty result when not configured', () => {
const pluginOptions = { ...defaultPluginOptions, rum: {} };
const result = validateSourceCodeContextOptions(pluginOptions);
expect(result.errors).toHaveLength(0);
expect(result.config).toBeUndefined();
});

test('should accept when only service is provided (version optional)', () => {
const pluginOptions = {
...defaultPluginOptions,
rum: { sourceCodeContext: { service: 'checkout' } },
};
const result = validateSourceCodeContextOptions(pluginOptions);
expect(result.errors).toHaveLength(0);
expect(result.config).toEqual(expect.objectContaining({ service: 'checkout' }));
});

test('should error when service is missing', () => {
const pluginOptions = {
...defaultPluginOptions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
rum: { sourceCodeContext: { version: '1.2.3' } as any },
};
const result = validateSourceCodeContextOptions(pluginOptions);
expect(result.errors).toEqual(
expect.arrayContaining([expect.stringContaining('"sourceCodeContext.service"')]),
);
});
});
37 changes: 36 additions & 1 deletion packages/plugins/rum/src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ import chalk from 'chalk';

import { CONFIG_KEY, PLUGIN_NAME } from './constants';
import type { PrivacyOptionsWithDefaults } from './privacy/types';
import type { RumOptions, RumOptionsWithDefaults, SDKOptionsWithDefaults } from './types';
import type {
RumOptions,
RumOptionsWithDefaults,
SDKOptionsWithDefaults,
SourceCodeContextOptions,
} from './types';

export const validateOptions = (
options: OptionsWithDefaults,
Expand All @@ -18,9 +23,11 @@ export const validateOptions = (
// Validate and add defaults sub-options.
const sdkResults = validateSDKOptions(options);
const privacyResults = validatePrivacyOptions(options);
const sourceCodeContextResults = validateSourceCodeContextOptions(options);

errors.push(...sdkResults.errors);
errors.push(...privacyResults.errors);
errors.push(...sourceCodeContextResults.errors);

// Throw if there are any errors.
if (errors.length) {
Expand All @@ -34,6 +41,7 @@ export const validateOptions = (
...options[CONFIG_KEY],
sdk: undefined,
privacy: undefined,
sourceCodeContext: undefined,
};

// Fill in the defaults.
Expand All @@ -55,6 +63,10 @@ export const validateOptions = (
);
}

if (sourceCodeContextResults.config) {
toReturn.sourceCodeContext = sourceCodeContextResults.config;
}

return toReturn;
};

Expand Down Expand Up @@ -141,3 +153,26 @@ export const validatePrivacyOptions = (options: Options): ToReturn<PrivacyOption

return toReturn;
};

export const validateSourceCodeContextOptions = (
options: OptionsWithDefaults,
): ToReturn<SourceCodeContextOptions> => {
const red = chalk.bold.red;
const validatedOptions: RumOptions = options[CONFIG_KEY] || {};
const toReturn: ToReturn<SourceCodeContextOptions> = {
errors: [],
};

if (!validatedOptions.sourceCodeContext) {
return toReturn;
}

const cfg = validatedOptions.sourceCodeContext as SourceCodeContextOptions;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would this work?
I'm not a super fan of as casting.

Suggested change
const cfg = validatedOptions.sourceCodeContext as SourceCodeContextOptions;
const cfg: SourceCodeContextOptions = validatedOptions.sourceCodeContext;


if (!cfg?.service || typeof cfg.service !== 'string') {
toReturn.errors.push(`Missing ${red('"sourceCodeContext.service"')}.`);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid any confusion from user's standpoint.

Suggested change
toReturn.errors.push(`Missing ${red('"sourceCodeContext.service"')}.`);
toReturn.errors.push(`Missing ${red('"rum.sourceCodeContext.service"')}.`);

}

toReturn.config = cfg;
return toReturn;
};
19 changes: 19 additions & 0 deletions packages/tests/src/e2e/sourceCodeContext/project/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/svg+xml" sizes="21x21" href="data:image/svg+xml," />
<title>Source Code Context Test</title>
</head>

<body>
<h1>Source Code Context Test - {{bundler}}</h1>
<p>Testing source code context injection.</p>

<button id="trigger_error" role="button">Trigger Error</button>
<button id="capture_stack" role="button">Capture Stack</button>

<script src="./dist/{{bundler}}.js"></script>
</body>
</html>
31 changes: 31 additions & 0 deletions packages/tests/src/e2e/sourceCodeContext/project/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

/* eslint-env browser */

const $ = document.querySelector.bind(document);

// Function to capture and store a stack trace
function captureStackTrace() {
const error = new Error();
const stack = error.stack;
return stack;
}

// Store stack trace globally for testing
$('#capture_stack').addEventListener('click', () => {
const stack = captureStackTrace();
window.capturedStack = stack;
console.log('Stack captured:', stack);
});

// Trigger an error for testing
$('#trigger_error').addEventListener('click', () => {
try {
throw new Error('Test error from source code context');
} catch (e) {
window.caughtError = e;
console.log('Error caught:', e);
}
});
Loading