Skip to content
Open
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
3 changes: 2 additions & 1 deletion .oxlintrc.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@
"files": ["**/src/**/*.ts", "**/src/**/*.tsx", "**/addon/**/*.ts"],
"rules": {
"sdk/no-unguarded-span-apis": "error",
"sdk/no-unguarded-debug-logs": "error"
"sdk/no-unguarded-debug-logs": "error",
"sdk/require-define-integration": "error"
}
},
{
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin-sdk/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ module.exports = {
'no-unfiltered-url-attributes': require('./rules/no-unfiltered-url-attributes'),
'no-unguarded-span-apis': require('./rules/no-unguarded-span-apis'),
'no-unsafe-html-writes': require('./rules/no-unsafe-html-writes'),
'require-define-integration': require('./rules/require-define-integration'),
},
};
189 changes: 189 additions & 0 deletions packages/eslint-plugin-sdk/src/rules/require-define-integration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
'use strict';

/**
* @fileoverview Rule to require that integrations are created with `defineIntegration`.
*
* `defineIntegration` records the options an integration was created with on `_options`. An
* integration that returns its object directly works, but its options are never recorded.
*
* Oxlint offers no type information to JS plugins, so the rule looks for the shape of an integration
* instead: an object literal with a `name` and at least one integration hook. Such an object is fine
* when the function that builds it reaches `defineIntegration` within the same file, either because
* it is passed to it or because a function that is passed to it uses it.
*/

const { splitPackagePath } = require('../utils/browser-facing');

const INTEGRATION_HOOKS = new Set([
'setupOnce',
'beforeSetup',
'setup',
'afterAllSetup',
'preprocessEvent',
'processEvent',
'processSpan',
'processSegmentSpan',
]);

/**
* Bundler and framework plugins are also `{ name, setup }` objects, so the files that define them are
* skipped. Paths are relative to `packages/`.
*/
const PLUGIN_PATHS = [
/^bundler-plugins\//,
/^server-runtime-injection\//,
/^bun\/src\/plugin\.ts$/,
/^nitro\/src\/(?:module|orchestrion)\.ts$/,
/^node\/src\/bundler-plugin\//,
/^nuxt\/src\/runtime\/plugins\//,
/^server-utils\/src\/orchestrion\/bundler\//,
/^tanstackstart-react\/src\/vite\//,
];

const TRANSPARENT_WRAPPERS = new Set([
'TSSatisfiesExpression',
'TSAsExpression',
'TSNonNullExpression',
'ParenthesizedExpression',
]);

const FUNCTIONS = new Set(['ArrowFunctionExpression', 'FunctionExpression', 'FunctionDeclaration']);

function isPluginFile(filename) {
const location = splitPackagePath(filename);
if (!location) {
return false;
}

const path = `${location.pkg}/${location.path}`;

return PLUGIN_PATHS.some(pattern => pattern.test(path));
}

function isDefineIntegrationCall(node) {
if (node.type !== 'CallExpression') {
return false;
}

const callee = node.callee;

return (
(callee.type === 'Identifier' && callee.name === 'defineIntegration') ||
(callee.type === 'MemberExpression' && !callee.computed && callee.property.name === 'defineIntegration')
);
}

function getPropertyName(property) {
if (property.type !== 'Property' || property.computed) {
return undefined;
}

return property.key.type === 'Identifier' ? property.key.name : property.key.value;
}

/** The name a function can be referred to by: its own, or the variable it is assigned to. */
function getFunctionName(node) {
if (node.id) {
return node.id.name;
}

let parent = node.parent;
while (parent && TRANSPARENT_WRAPPERS.has(parent.type)) {
parent = parent.parent;
}

return parent?.type === 'VariableDeclarator' && parent.id.type === 'Identifier' ? parent.id.name : undefined;
}

module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Require integrations to be created with `defineIntegration`',
category: 'Possible Errors',
recommended: true,
},
fixable: null,
schema: [],
messages: {
requireDefineIntegration:
'Integrations must be created with `defineIntegration`. Without it, the options the integration was created with are not recorded.',
},
},
create: function (context) {
if (isPluginFile(context.getFilename())) {
return {};
}

/** Names used inside a `defineIntegration(...)` call. */
const defined = new Set();
/** Names used inside each named function, to follow helpers that build the object. */
const usedByFunction = new Map();
const candidates = [];

/** Names of the functions around `node`, or `undefined` when it is inside `defineIntegration(...)`. */
function getEnclosingFunctionNames(node) {
const names = [];
for (let parent = node.parent; parent; parent = parent.parent) {
if (isDefineIntegrationCall(parent)) {
return undefined;
}

const name = FUNCTIONS.has(parent.type) ? getFunctionName(parent) : undefined;
if (name) {
names.push(name);
}
}

return names;
}

return {
Identifier(node) {
const functionNames = getEnclosingFunctionNames(node);
if (!functionNames) {
defined.add(node.name);

return;
}

for (const functionName of functionNames) {
if (!usedByFunction.has(functionName)) {
usedByFunction.set(functionName, new Set());
}
usedByFunction.get(functionName).add(node.name);
}
},

ObjectExpression(node) {
const names = node.properties.map(getPropertyName);
if (!names.includes('name') || !names.some(name => INTEGRATION_HOOKS.has(name))) {
return;
}

const functionNames = getEnclosingFunctionNames(node);
if (functionNames) {
candidates.push({ node, functionNames });
}
},

'Program:exit'() {
const pending = [...defined];
while (pending.length) {
for (const name of usedByFunction.get(pending.pop()) || []) {
if (!defined.has(name)) {
defined.add(name);
pending.push(name);
}
}
}

for (const { node, functionNames } of candidates) {
if (!functionNames.some(name => defined.has(name))) {
context.report({ node, messageId: 'requireDefineIntegration' });
}
}
},
};
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { RuleTester } from 'eslint';
import { describe, test } from 'vitest';
// @ts-expect-error untyped module
import rule from '../../../src/rules/require-define-integration';

const errors = [{ messageId: 'requireDefineIntegration', type: 'ObjectExpression' }];

describe('require-define-integration', () => {
test('ruleTester', () => {
const ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
},
});

ruleTester.run('require-define-integration', rule, {
valid: [
{
code: "export const fooIntegration = defineIntegration(() => ({ name: 'Foo', setup() {} }));",
},
{
code: "export const fooIntegration = core.defineIntegration(() => ({ name: 'Foo', setup() {} }));",
},
{
code: `
const _fooIntegration = () => {
return { name: 'Foo', setupOnce() {} };
};
export const fooIntegration = defineIntegration(_fooIntegration);
`,
},
// The object is built by a helper of the function that is passed to `defineIntegration`.
{
code: `
function buildFoo(options) {
return { name: 'Foo', processEvent: event => event };
}
const _fooIntegration = options => buildFoo(options);
export const fooIntegration = defineIntegration(_fooIntegration);
`,
},
{
code: `
function buildFoo(options) {
return { name: 'Foo', setup() {} };
}
export const fooIntegration = defineIntegration(options => buildFoo(options));
`,
},
// A factory that wraps the integration itself.
{
code: `
export function createFooIntegration(name) {
return defineIntegration(() => ({ name, setup() {} }));
}
`,
},
// No hook, so not an integration.
{
code: "export const foo = () => ({ name: 'Foo', handler() {} });",
},
// No name, so not an integration.
{
code: 'export const foo = () => ({ setup() {} });',
},
// Bundler plugins share the `{ name, setup }` shape.
{
filename: '/repo/packages/bundler-plugins/src/esbuild/index.ts',
code: "export const plugin = () => ({ name: 'sentry-esbuild-plugin', setup(build) {} });",
},
],
invalid: [
{
code: "export const fooIntegration = () => ({ name: 'Foo', setup() {} });",
errors,
},
{
code: `
export function fooIntegration() {
return { name: 'Foo', setupOnce() {} };
}
`,
errors,
},
// The function is never passed to `defineIntegration`.
{
code: `
const _fooIntegration = () => {
return { name: 'Foo', processSpan() {} };
};
export const fooIntegration = _fooIntegration;
`,
errors,
},
// `defineIntegration` wraps another integration of the file, not this one.
{
code: `
const _fooIntegration = () => ({ name: 'Foo', setup() {} });
const _barIntegration = () => ({ name: 'Bar', setup() {} });
export const fooIntegration = defineIntegration(_fooIntegration);
export const barIntegration = _barIntegration;
`,
errors,
},
{
filename: '/repo/packages/node/src/integrations/foo.ts',
code: "export const fooIntegration = () => ({ name: 'Foo', afterAllSetup() {} });",
errors,
},
],
});
});
});
8 changes: 6 additions & 2 deletions packages/feedback/src/modal/integration.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/core';
import { getClient, getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';
import { defineIntegration, getClient, getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';
import { h, render } from 'preact';
import * as hooks from 'preact/hooks';
import { DOCUMENT } from '../constants';
Expand All @@ -19,7 +19,7 @@ function getUser(): User | undefined {
return globalUser;
}

export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
const _feedbackModalIntegration = ((): FeedbackModalIntegration => {
return {
name: 'FeedbackModal' as const,
setupOnce() {},
Expand Down Expand Up @@ -131,3 +131,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => {
},
};
}) satisfies IntegrationFn;

export const feedbackModalIntegration = defineIntegration(
_feedbackModalIntegration,
) as typeof _feedbackModalIntegration;
7 changes: 6 additions & 1 deletion packages/feedback/src/screenshot/integration.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import type { Attachment, FeedbackScreenshotIntegration, IntegrationFn } from '@sentry/core';
import { defineIntegration } from '@sentry/core';
import type { h as hType } from 'preact';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT } from '../constants';
import { ScreenshotEditorFactory } from './components/ScreenshotEditor';

export const feedbackScreenshotIntegration = ((): FeedbackScreenshotIntegration => {
const _feedbackScreenshotIntegration = ((): FeedbackScreenshotIntegration => {
return {
name: 'FeedbackScreenshot' as const,
setupOnce() {},
Expand Down Expand Up @@ -40,3 +41,7 @@ export const feedbackScreenshotIntegration = ((): FeedbackScreenshotIntegration
},
};
}) satisfies IntegrationFn;

export const feedbackScreenshotIntegration = defineIntegration(
_feedbackScreenshotIntegration,
) as typeof _feedbackScreenshotIntegration;
6 changes: 3 additions & 3 deletions packages/nextjs/src/cloudflare/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import type { Context, TextMapGetter } from '@opentelemetry/api';
import { context, propagation, trace } from '@opentelemetry/api';
import type { CloudflareOptions } from '@sentry/cloudflare';
import { withSentry as withSentryCloudflare } from '@sentry/cloudflare';
import type { Integration } from '@sentry/core';
import {
_INTERNAL_captureOptionsSetByUser,
applySdkMetadata,
defineIntegration,
extractTraceparentData,
getRootSpan,
GLOBAL_OBJ,
Expand Down Expand Up @@ -52,7 +52,7 @@ class NextjsCloudflarePropagator extends NextSentryPropagator {
}
}

const nextjsIntegration = (): Integration => ({
const nextjsIntegration = defineIntegration(() => ({
name: 'Nextjs',
setup: client => {
if ((client.getOptions() as CloudflareOptions).enableOpenTelemetrySetup) {
Expand All @@ -72,7 +72,7 @@ const nextjsIntegration = (): Integration => ({
}
});
},
});
}));

/**
* `withSentry` of `@sentry/cloudflare` for the Worker entry of a Next.js app, e.g. `.open-next/worker.js`. It adds the
Expand Down
Loading
Loading