Skip to content

chore(svelte): Detect and report SvelteKit usage #5594

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 18, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
46 changes: 44 additions & 2 deletions packages/svelte/src/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BrowserOptions, init as browserInit, SDK_VERSION } from '@sentry/browser';

import { addGlobalEventProcessor, BrowserOptions, init as browserInit, SDK_VERSION } from '@sentry/browser';
import type { EventProcessor } from '@sentry/types';
import { getDomElement } from '@sentry/utils';
/**
* Inits the Svelte SDK
*/
Expand All @@ -17,4 +18,45 @@ export function init(options: BrowserOptions): void {
};

browserInit(options);

detectAndReportSvelteKit();
}

/**
* Adds a global event processor to detect if the SDK is initialized in a SvelteKit frontend,
* in which case we add SvelteKit an event.modules entry to outgoing events.
* SvelteKit detection is performed only once, when the event processor is called for the
* first time. We cannot perform this check upfront (directly when init is called) because
* at this time, the HTML element might not yet be accessible.
*/
export function detectAndReportSvelteKit(): void {
let detectedSvelteKit: boolean | undefined = undefined;

const svelteKitProcessor: EventProcessor = event => {
if (detectedSvelteKit === undefined) {
detectedSvelteKit = isSvelteKitApp();
}
if (detectedSvelteKit) {
event.modules = {
Copy link
Contributor

Choose a reason for hiding this comment

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

Where does event.modules show up? Is it something that is indexed and we can query for?

Copy link
Member

Choose a reason for hiding this comment

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

Yup - it displays in event details page, and is indexed - we can query for it in looker.

Copy link
Contributor

Choose a reason for hiding this comment

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

@lforst, it's vaguely documented here

svelteKit: '1.0',
Copy link
Member

Choose a reason for hiding this comment

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

Hmm - feels weird to write 1.0 as that might not be the correct version. Thoughts?

Copy link
Member Author

Choose a reason for hiding this comment

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

I agree, it's weird but we have no way of knowing which SvelteKit version was actually being used (let alone that 1.0 isn't even stable yet). So my train of thought for 1.0 was to simply put there something because afaik we have to supply a version here. But happy to change it to 1.x, 0.x, 0 or whatever. Or maybe something like unknown/n/a ? Though I'm not sure which values are allowed here (for example, how they are indexed).

Copy link
Contributor

Choose a reason for hiding this comment

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

Until we are able to confidently discover correct SvelteKit version I think we can keep it at 1.0

Copy link
Member

Choose a reason for hiding this comment

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

I would maybe leave it as latest? Later on we can add in the actual version when we support SvelteKit.

Copy link
Member

Choose a reason for hiding this comment

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

My worry about leaving it as 1.0 is that we are going to pollute results when we eventually do support SvelteKit and start adding the proper version number.

Copy link
Contributor

Choose a reason for hiding this comment

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

fine with me. I was also thinking to convert it to a boolean but I don't want to abuse the module field for that

Copy link
Member Author

Choose a reason for hiding this comment

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

Sure, latest is also sounds good to me. As long as the indexer is happy with it.
Our main objective is to find out if SvelteKit is used or not, making the exact version of it lower prio IMO.

...event.modules,
};
}
return event;
};
svelteKitProcessor.id = 'svelteKitProcessor';

addGlobalEventProcessor(svelteKitProcessor);
}

/**
* To actually detect a SvelteKit frontend, we search the DOM for a special
* div that's inserted by SvelteKit when the page is rendered. It's identifyed
* by its id, 'svelte-announcer', and it's used to improve page accessibility.
* This div is not present when only using Svelte without SvelteKit.
*
* @see https://github.com/sveltejs/kit/issues/307 for more information
*/
export function isSvelteKitApp(): boolean {
return getDomElement('div#svelte-announcer') !== null;
}
62 changes: 60 additions & 2 deletions packages/svelte/test/sdk.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { init as browserInitRaw, SDK_VERSION } from '@sentry/browser';
import { addGlobalEventProcessor, init as browserInitRaw, SDK_VERSION } from '@sentry/browser';
import { EventProcessor } from '@sentry/types';

import { init as svelteInit } from '../src/sdk';
import { detectAndReportSvelteKit, init as svelteInit, isSvelteKitApp } from '../src/sdk';

const browserInit = browserInitRaw as jest.Mock;
const addGlobalEventProcessorFunction = addGlobalEventProcessor as jest.Mock;
let passedEventProcessor: EventProcessor | undefined;
addGlobalEventProcessorFunction.mockImplementation(proc => {
passedEventProcessor = proc;
});

jest.mock('@sentry/browser');

describe('Initialize Svelte SDk', () => {
Expand All @@ -29,3 +36,54 @@ describe('Initialize Svelte SDk', () => {
expect(browserInit).toHaveBeenCalledWith(expect.objectContaining(expectedMetadata));
});
});

describe('detectAndReportSvelteKit()', () => {
const originalHtmlBody = document.body.innerHTML;
afterEach(() => {
jest.clearAllMocks();
document.body.innerHTML = originalHtmlBody;
passedEventProcessor = undefined;
});

it('registers a global event processor', async () => {
detectAndReportSvelteKit();

expect(addGlobalEventProcessorFunction).toHaveBeenCalledTimes(1);
expect(passedEventProcessor?.id).toEqual('svelteKitProcessor');
});

it('adds "SvelteKit" as a module to the event, if SvelteKit was detected', () => {
document.body.innerHTML += '<div id="svelte-announcer">Home</div>';
detectAndReportSvelteKit();

const processedEvent = passedEventProcessor && passedEventProcessor({} as unknown as any, {});

expect(processedEvent).toBeDefined();
expect(processedEvent).toEqual({ modules: { svelteKit: '1.0' } });
});

it("doesn't add anything to the event, if SvelteKit was not detected", () => {
document.body.innerHTML = '';
detectAndReportSvelteKit();

const processedEvent = passedEventProcessor && passedEventProcessor({} as unknown as any, {});

expect(processedEvent).toBeDefined();
expect(processedEvent).toEqual({});
});

describe('isSvelteKitApp()', () => {
it('returns true if the svelte-announcer div is present', () => {
document.body.innerHTML += '<div id="svelte-announcer">Home</div>';
expect(isSvelteKitApp()).toBe(true);
});
it('returns false if the svelte-announcer div is not present (but similar elements)', () => {
document.body.innerHTML += '<div id="svelte-something">Home</div>';
expect(isSvelteKitApp()).toBe(false);
});
it('returns false if no div is present', () => {
document.body.innerHTML = '';
expect(isSvelteKitApp()).toBe(false);
});
});
});
13 changes: 3 additions & 10 deletions packages/tracing/src/browser/browsertracing.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable max-lines */
import { Hub } from '@sentry/hub';
import { EventProcessor, Integration, Transaction, TransactionContext } from '@sentry/types';
import { getGlobalObject, logger, parseBaggageSetMutability } from '@sentry/utils';
import { getDomElement, getGlobalObject, logger, parseBaggageSetMutability } from '@sentry/utils';

import { startIdleTransaction } from '../hubextensions';
import { DEFAULT_FINAL_TIMEOUT, DEFAULT_IDLE_TIMEOUT } from '../idletransaction';
Expand Down Expand Up @@ -294,13 +294,6 @@ export function extractTraceDataFromMetaTags(): Partial<TransactionContext> | un

/** Returns the value of a meta tag */
export function getMetaContent(metaName: string): string | null {
const globalObject = getGlobalObject<Window>();

// DOM/querySelector is not available in all environments
if (globalObject.document && globalObject.document.querySelector) {
const el = globalObject.document.querySelector(`meta[name=${metaName}]`);
return el ? el.getAttribute('content') : null;
} else {
return null;
}
const metaTag = getDomElement(`meta[name=${metaName}]`);
return metaTag ? metaTag.getAttribute('content') : null;
}
18 changes: 18 additions & 0 deletions packages/utils/src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,21 @@ export function getLocationHref(): string {
return '';
}
}

/**
* Gets a DOM element by using document.querySelector.
*
* This wrapper will first check for the existance of the function before
* actually calling it so that we don't have to take care of this check,
* every time we want to access the DOM.
* Reason: DOM/querySelector is not available in all environments
*
* @param selector the selector string passed on to document.querySelector
*/
export function getDomElement(selector: string): Element | null {
const global = getGlobalObject<Window>();
if (global.document && global.document.querySelector) {
return global.document.querySelector(selector);
}
return null;
}
12 changes: 11 additions & 1 deletion packages/utils/test/browser.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { JSDOM } from 'jsdom';

import { htmlTreeAsString } from '../src/browser';
import { getDomElement, htmlTreeAsString } from '../src/browser';

beforeAll(() => {
const dom = new JSDOM();
Expand Down Expand Up @@ -45,3 +45,13 @@ describe('htmlTreeAsString', () => {
);
});
});

describe('getDomElement', () => {
it('returns the element for a given query selector', () => {
document.head.innerHTML = '<div id="mydiv">Hello</div>';
const el = getDomElement('div#mydiv');
expect(el).toBeDefined();
expect(el?.tagName).toEqual('DIV');
expect(el?.id).toEqual('mydiv');
});
});