Skip to content
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

fix(sveltekit): Fix SvelteKit Cloudflare usage #14672

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from
5 changes: 5 additions & 0 deletions packages/sveltekit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
"./package.json": "./package.json",
".": {
"types": "./build/types/index.types.d.ts",
"worker": {
"import": "./build/esm/index.worker.js",
"require": "./build/cjs/index.worker.js"
},
Copy link
Member

Choose a reason for hiding this comment

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

not directly applicable to this line but: I had to make this change to the node export to start the build:

Suggested change
},
"node": {
"require": "./build/cjs/index.server.js",
"import": "./build/esm/index.server.js"
}

However, even after this change, I get another error a bit later

Copy link
Contributor

@aloisklink aloisklink Dec 17, 2024

Choose a reason for hiding this comment

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

Sorry @Lms24 if this isn't the right place to discuss this, but is there any reason why we don't make this change in a separate PR?

I'm having an issue where trying to import import * as Sentry from '@sentry/sveltekit'; using ESM in Node.JS has all the @sentry/node imports under Sentry.default, and the above change seems to fix it.

From reading #9872 (comment), it looks like ESM used to be broken, but I think 7f2e804 might have fixed it? But a similar change for remix seems to have not worked: #12742

Copy link
Member

Choose a reason for hiding this comment

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

@aloisklink sorry for only seeing your comment now: I agree, we should make this change separately. Thing is, as far as I know, SvelteKit transpiles to CJS (at least for Node-based environments). So I'm a bit hesitant to add an ESM entry point, especially because this works even less well than it currently works in CJS, with OpenTelemetry.

Feel free to submit a PR and let's see what our tests have to see

"browser": {
"import": "./build/esm/index.client.js",
"require": "./build/cjs/index.client.js"
Expand All @@ -40,6 +44,7 @@
}
},
"dependencies": {
"@sentry/cloudflare": "8.44.0",
"@sentry/core": "8.44.0",
"@sentry/node": "8.44.0",
"@sentry/opentelemetry": "8.44.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/sveltekit/rollup.npm.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollu

export default makeNPMConfigVariants(
makeBaseNPMConfig({
entrypoints: ['src/index.server.ts', 'src/index.client.ts', 'src/client/index.ts', 'src/server/index.ts'],
entrypoints: ['src/index.server.ts', 'src/index.client.ts', 'src/index.worker.ts', 'src/client/index.ts', 'src/server/index.ts', 'src/worker/index.ts'],
packageSpecificConfig: {
external: ['$app/stores'],
output: {
Expand Down
4 changes: 4 additions & 0 deletions packages/sveltekit/src/index.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
export * from './client';
export * from './vite';
export * from './server';
export * from './worker';

// Use the ./server version of some functions that are also exported from ./worker
export { wrapServerLoadWithSentry, wrapServerRouteWithSentry, sentryHandle } from './server';

import type { Client, Integration, Options, StackParser } from '@sentry/core';
import type { HandleClientError, HandleServerError } from '@sveltejs/kit';
Expand Down
2 changes: 2 additions & 0 deletions packages/sveltekit/src/index.worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './worker';
// export * from './vite';
181 changes: 181 additions & 0 deletions packages/sveltekit/src/server-common/handle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import type { continueTrace, Span } from '@sentry/core';
import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
getActiveSpan,
getCurrentScope,
getDefaultIsolationScope,
getIsolationScope,
getTraceMetaTags,
logger,
setHttpStatus,
startSpan,
winterCGRequestToRequestData,
withIsolationScope,
} from '@sentry/core';
import type { Handle, ResolveOptions } from '@sveltejs/kit';

import { DEBUG_BUILD } from '../common/debug-build';
import { flushIfServerless, getTracePropagationData, sendErrorToSentry } from './utils';

export type SentryHandleOptions = {
/**
* Controls whether the SDK should capture errors and traces in requests that don't belong to a
* route defined in your SvelteKit application.
*
* By default, this option is set to `false` to reduce noise (e.g. bots sending random requests to your server).
*
* Set this option to `true` if you want to monitor requests events without a route. This might be useful in certain
* scenarios, for instance if you registered other handlers that handle these requests.
* If you set this option, you might want adjust the the transaction name in the `beforeSendTransaction`
* callback of your server-side `Sentry.init` options. You can also use `beforeSendTransaction` to filter out
* transactions that you still don't want to be sent to Sentry.
*
* @default false
*/
handleUnknownRoutes?: boolean;

/**
* Controls if `sentryHandle` should inject a script tag into the page that enables instrumentation
* of `fetch` calls in `load` functions.
*
* @default true
*/
injectFetchProxyScript?: boolean;

/**
* If this option is set, the `sentryHandle` handler will add a nonce attribute to the script
* tag it injects into the page. This script is used to enable instrumentation of `fetch` calls
* in `load` functions.
*
* Use this if your CSP policy blocks the fetch proxy script injected by `sentryHandle`.
*/
fetchProxyScriptNonce?: string;
};

export const FETCH_PROXY_SCRIPT = `
const f = window.fetch;
if(f){
window._sentryFetchProxy = function(...a){return f(...a)}
window.fetch = function(...a){return window._sentryFetchProxy(...a)}
}
`;

/**
* Adds Sentry tracing <meta> tags to the returned html page.
* Adds Sentry fetch proxy script to the returned html page if enabled in options.
* Also adds a nonce attribute to the script tag if users specified one for CSP.
*/
export function addSentryCodeToPage(options: SentryHandleOptions): NonNullable<ResolveOptions['transformPageChunk']> {
const { fetchProxyScriptNonce, injectFetchProxyScript } = options;
// if injectFetchProxyScript is not set, we default to true
const shouldInjectScript = injectFetchProxyScript !== false;
const nonce = fetchProxyScriptNonce ? `nonce="${fetchProxyScriptNonce}"` : '';

return ({ html }) => {
const metaTags = getTraceMetaTags();
const headWithMetaTags = metaTags ? `<head>\n${metaTags}` : '<head>';

const headWithFetchScript = shouldInjectScript ? `\n<script ${nonce}>${FETCH_PROXY_SCRIPT}</script>` : '';

const modifiedHead = `${headWithMetaTags}${headWithFetchScript}`;

return html.replace('<head>', modifiedHead);
};
}

export async function instrumentHandle(
{ event, resolve }: Parameters<Handle>[0],
options: SentryHandleOptions,
): Promise<Response> {
if (!event.route?.id && !options.handleUnknownRoutes) {
return resolve(event);
}

const routeName = `${event.request.method} ${event.route?.id || event.url.pathname}`;

if (getIsolationScope() !== getDefaultIsolationScope()) {
getIsolationScope().setTransactionName(routeName);
} else {
DEBUG_BUILD && logger.warn('Isolation scope is default isolation scope - skipping setting transactionName');
}

try {
const resolveResult = await startSpan(
{
op: 'http.server',
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.sveltekit',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: event.route?.id ? 'route' : 'url',
'http.method': event.request.method,
},
name: routeName,
},
async (span?: Span) => {
getCurrentScope().setSDKProcessingMetadata({
normalizedRequest: winterCGRequestToRequestData(event.request.clone()),
});
const res = await resolve(event, {
transformPageChunk: addSentryCodeToPage(options),
});
if (span) {
setHttpStatus(span, res.status);
}
return res;
},
);
return resolveResult;
} catch (e: unknown) {
sendErrorToSentry(e, 'handle');
throw e;
} finally {
await flushIfServerless();
}
}

/**
* A SvelteKit handle function that wraps the request for Sentry error and
* performance monitoring.
*
* Some environments require a different continueTrace function. E.g. Node can use
* the Opentelemetry SDK, whereas Cloudflare cannot.
*/
export function sentryHandleGeneric(
continueTraceFunction: typeof continueTrace,
handlerOptions?: SentryHandleOptions,
): Handle {
const options = {
handleUnknownRoutes: false,
injectFetchProxyScript: true,
...handlerOptions,
};

const sentryRequestHandler: Handle = input => {
// event.isSubRequest was added in SvelteKit 1.21.0 and we can use it to check
// if we should create a new execution context or not.
// In case of a same-origin `fetch` call within a server`load` function,
// SvelteKit will actually just re-enter the `handle` function and set `isSubRequest`
// to `true` so that no additional network call is made.
// We want the `http.server` span of that nested call to be a child span of the
// currently active span instead of a new root span to correctly reflect this
// behavior.
// As a fallback for Kit < 1.21.0, we check if there is an active span only if there's none,
// we create a new execution context.
const isSubRequest = typeof input.event.isSubRequest === 'boolean' ? input.event.isSubRequest : !!getActiveSpan();

if (isSubRequest) {
return instrumentHandle(input, options);
}

return withIsolationScope(isolationScope => {
// We only call continueTrace in the initial top level request to avoid
// creating a new root span for the sub request.
isolationScope.setSDKProcessingMetadata({
normalizedRequest: winterCGRequestToRequestData(input.event.request.clone()),
});
return continueTraceFunction(getTracePropagationData(input.event), () => instrumentHandle(input, options));
});
};

return sentryRequestHandler;
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { consoleSandbox } from '@sentry/core';
import { captureException } from '@sentry/node';
import { captureException, consoleSandbox } from '@sentry/core';
import type { HandleServerError } from '@sveltejs/kit';

import { flushIfServerless } from './utils';
import { flushIfServerless } from '../server-common/utils';

// The SvelteKit default error handler just logs the error's stack trace to the console
// see: https://github.com/sveltejs/kit/blob/369e7d6851f543a40c947e033bfc4a9506fdc0a8/packages/kit/src/runtime/server/index.js#L43
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { addNonEnumerableProperty } from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, startSpan } from '@sentry/node';
import {
addNonEnumerableProperty,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
startSpan,
} from '@sentry/core';
import type { LoadEvent, ServerLoadEvent } from '@sveltejs/kit';

import type { SentryWrappedFlag } from '../common/utils';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
join,
rewriteFramesIntegration as originalRewriteFramesIntegration,
} from '@sentry/core';
import { WRAPPED_MODULE_SUFFIX } from '../vite/autoInstrument';
import { WRAPPED_MODULE_SUFFIX } from '../vite/constants';
import type { GlobalWithSentryValues } from '../vite/injectGlobalValues';

type StackFrameIteratee = (frame: StackFrame) => StackFrame;
Expand Down Expand Up @@ -53,8 +53,8 @@ export function rewriteFramesIteratee(frame: StackFrame): StackFrame {
if (isWindowsFrame || startsWithSlash) {
const filename = isWindowsFrame
? frame.filename
.replace(/^[a-zA-Z]:/, '') // remove Windows-style prefix
.replace(/\\/g, '/') // replace all `\\` instances with `/`
.replace(/^[a-zA-Z]:/, '') // remove Windows-style prefix
.replace(/\\/g, '/') // replace all `\\` instances with `/`
: frame.filename;

let strippedFilename;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { addNonEnumerableProperty } from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, startSpan } from '@sentry/node';
import {
addNonEnumerableProperty,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
startSpan,
} from '@sentry/core';
import type { RequestEvent } from '@sveltejs/kit';
import { flushIfServerless, sendErrorToSentry } from './utils';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { logger, objectify } from '@sentry/core';
import { captureException, flush } from '@sentry/node';
import { captureException, flush, logger, objectify } from '@sentry/core';
import type { RequestEvent } from '@sveltejs/kit';

import { DEBUG_BUILD } from '../common/debug-build';
Expand Down
Loading
Loading