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
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ const router = createRouter({
path: '/users/:id',
component: () => import('../views/UserIdView.vue'),
},
{
path: '/route-provider/:id',
component: () => import('../views/RouteProviderView.vue'),
},
{
path: '/users-error/:id',
component: () => import('../views/UserIdErrorView.vue'),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<script setup lang="ts">
import * as Sentry from '@sentry/vue';
import { onMounted, ref } from 'vue';

const route = ref<string>();

onMounted(() => {
route.value = Sentry.resolveCurrentRoute() ?? 'unresolved';
});
</script>

<template>
<div id="resolved-route">{{ route }}</div>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { expect, test } from '@playwright/test';

// The route provider reads the router off the app passed to `Sentry.init`, so this fails if it can't
// find it there.
test('resolves the parameterized route through the route provider', async ({ page }) => {
await page.goto('/route-provider/123');

await expect(page.locator('#resolved-route')).toHaveText('/route-provider/:id');
});
1 change: 1 addition & 0 deletions packages/vue/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ export { browserTracingIntegration } from './browserTracingIntegration';
export { attachErrorHandler } from './errorhandler';
export { createTracingMixins } from './tracing';
export { vueIntegration } from './integration';
export { createVueRouteProvider as _INTERNAL_createVueRouteProvider } from './routeProvider';
export type { VueIntegrationOptions } from './integration';
export { createSentryPiniaPlugin } from './pinia';
9 changes: 9 additions & 0 deletions packages/vue/src/integration.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { getRouteProvider, setRouteProvider } from '@sentry/browser';
import { consoleSandbox, defineIntegration, GLOBAL_OBJ, hasSpansEnabled } from '@sentry/core';
import { DEFAULT_HOOKS, DEFAULT_ROOT_SPAN_TIMEOUT } from './constants';
import { DEBUG_BUILD } from './debug-build';
import { attachErrorHandler } from './errorhandler';
import { instrumentAppMountWithoutMixin } from './rootInstrumentation';
import { captureRouterFromVue, createVueRouteProvider, getRouterFromApp } from './routeProvider';
import { createTracingMixins } from './tracing';
import type { Options, TracingOptions, Vue, VueOptions } from './types';

Expand Down Expand Up @@ -38,6 +40,13 @@ export const vueIntegration = defineIntegration((integrationOptions: Partial<Vue
return;
}

// The router is looked up lazily because it may be installed after `init`. A user's `routeProvider` wins.
if (!getRouteProvider(client)) {
const { app, Vue } = options;
const getRouter = app ? () => getRouterFromApp(app) : captureRouterFromVue(Vue!);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Non-null assertion lacks required comment

Low Severity

A new non-null assertion on Vue has no comment explaining why a safer type is not possible. The earlier app/Vue guard makes the assertion valid, but the project rule still requires that comment on new ! uses in SDK source. Flagged because this was mentioned in the review rules file.

Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

Reviewed by Cursor Bugbot for commit 89d893e. Configure here.

setRouteProvider(createVueRouteProvider(getRouter), client);
}

if (options.app) {
const apps = Array.isArray(options.app) ? options.app : [options.app];
apps.forEach(app => vueInit(app, options));
Expand Down
89 changes: 89 additions & 0 deletions packages/vue/src/routeProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import type { RouteProvider } from '@sentry/browser';
import { createUrlRouteProvider } from '@sentry/browser';
import type { Route } from './router';
import type { Vue } from './types';

// Vue Router 3 resolves to `{ route }`, Vue Router 4+ returns the route itself.
type ResolvedLocation = Route | { route: Route };

type RouteUrl = Parameters<RouteProvider['resolveRoute']>[0];

interface InstalledRouter {
resolve?: (to: string) => ResolvedLocation;
/** Vue Router 4+ */
options?: { history?: { base?: string } };
/** Vue Router 3 */
mode?: string;
history?: { base?: string };
}

interface AppWithRouter {
config?: { globalProperties?: { $router?: InstalledRouter } };
}

/**
* Builds a route provider from a `vue-router` instance, however the SDK got hold of one.
*
* The router is looked up per call rather than captured once, because `app.use(router)` may run
* either side of `Sentry.init()` and only the app itself is guaranteed to exist by then.
*/
export function createVueRouteProvider(getRouter: () => InstalledRouter | undefined): RouteProvider {
return createUrlRouteProvider(url => {
const router = getRouter();
const resolved = router?.resolve?.(getRouterLocation(router, url));
if (!resolved) {
return undefined;
}

const route = 'matched' in resolved ? resolved : resolved.route;

// Always the matched path, never `route.name`. Callers set `url.template` from this, and a route
// name is an identifier rather than a template.
return route.matched[route.matched.length - 1]?.path;
Comment thread
cursor[bot] marked this conversation as resolved.
});
}

/**
* Reads the router `vue-router` installed onto a Vue app.
*/
export function getRouterFromApp(app: Vue | Vue[] | undefined): InstalledRouter | undefined {
const firstApp = (Array.isArray(app) ? app[0] : app) as AppWithRouter | undefined;

return firstApp?.config?.globalProperties?.$router;
}

/**
* Vue 2 only exposes the router on instances, not on the constructor passed to `init`, so this picks it
* up from the root instance (`new Vue({ router })`) as it is created.
*/
export function captureRouterFromVue(Vue: Vue): () => InstalledRouter | undefined {
let router: InstalledRouter | undefined;
Vue.mixin({
beforeCreate(this: { $options: { router?: InstalledRouter } }) {
router = router || this.$options.router;
},
});

return () => router;
}

/**
* `resolve` matches the router's own location rather than the browser's: the hash in hash mode, and
* the path without the router's base otherwise. Mirrors vue-router's `createCurrentLocation`.
*/
function getRouterLocation(router: InstalledRouter, { pathname, search, hash }: RouteUrl): string {
const base = router.options?.history?.base ?? router.history?.base ?? '';
const hashPos = base.indexOf('#');

if (hashPos > -1 || router.mode === 'hash') {
const hashBase = hashPos > -1 ? base.slice(hashPos) : '#';
const path = hash.slice(hash.startsWith(hashBase) ? hashBase.length : 1);

return path.startsWith('/') ? path : `/${path}`;
}

const path =
base && pathname.toLowerCase().startsWith(base.toLowerCase()) ? pathname.slice(base.length) || '/' : pathname;

return `${path}${search}${hash}`;
}
3 changes: 2 additions & 1 deletion packages/vue/test/integration/mixinRegistration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,8 @@ describe('tracing mixin registration', () => {
it('registers the tracing mixin on the constructor passed as `Vue` (Vue 2 setup)', ({ app, initSentry }) => {
initSentry({ sdk: { app: undefined, Vue: app } });

expect(getRegisteredMixins(app)).toHaveLength(1);
// The tracing mixin, plus the one that picks up the router for the route provider.
expect(getRegisteredMixins(app)).toHaveLength(2);
});
});

Expand Down
113 changes: 113 additions & 0 deletions packages/vue/test/routeProvider.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { describe, expect, it } from 'vitest';
import { createVueRouteProvider, getRouterFromApp } from '../src/routeProvider';
import type { Route } from '../src/router';
import type { Vue } from '../src/types';

function makeRoute(overrides: Partial<Route> = {}): Route {
return { path: '/users/42', query: {}, params: {}, matched: [{ path: '/users/:id' }], ...overrides };
}

/** Vue Router 4+ returns the route itself. Only `/users/42` matches, so a wrong location resolves to nothing. */
const v4Router = (route: Route | undefined, base = '') => ({
options: { history: { base } },
resolve: (to: string) => (to.split('?')[0] === '/users/42' ? route : makeRoute({ matched: [] })) as Route,
});
/** Vue Router 3 wraps it in `{ route }`. */
const v3Router = (route: Route, mode = 'history', base = '') => ({
mode,
history: { base },
resolve: (to: string) => ({ route: to.split('?')[0] === '/users/42' ? route : makeRoute({ matched: [] }) }),
});

/** A Vue 3 app with `vue-router` installed, which sets `config.globalProperties.$router`. */
const appWithRouter = (router: unknown) => ({ config: { globalProperties: { $router: router } } }) as unknown as Vue;

describe('getRouterFromApp', () => {
it('reads the router vue-router installed on the app', () => {
const router = v4Router(makeRoute());

expect(getRouterFromApp(appWithRouter(router))).toBe(router);
});

it('reads from the first app when several were passed', () => {
const router = v4Router(makeRoute());

expect(getRouterFromApp([appWithRouter(router), appWithRouter(undefined)])).toBe(router);
});

it('returns undefined when no router is installed yet', () => {
expect(getRouterFromApp(appWithRouter(undefined))).toBeUndefined();
expect(getRouterFromApp(undefined)).toBeUndefined();
});
});

describe('createVueRouteProvider', () => {
it('resolves the matched path for Vue Router 4+', () => {
const provider = createVueRouteProvider(() => v4Router(makeRoute()));

expect(provider.resolveRoute(new URL('https://example.com/users/42?tab=1'))).toBe('/users/:id');
});

it('unwraps the `{ route }` shape Vue Router 3 resolves to', () => {
const provider = createVueRouteProvider(() => v3Router(makeRoute()));

expect(provider.resolveRoute(new URL('https://example.com/users/42'))).toBe('/users/:id');
});

it('returns the matched path even for a named route, since a name is not a template', () => {
const provider = createVueRouteProvider(() => v4Router(makeRoute({ name: 'UserProfile' })));

expect(provider.resolveRoute(new URL('https://example.com/users/42'))).toBe('/users/:id');
});

it('picks the router up late, since `app.use(router)` may run after `Sentry.init`', () => {
let router: ReturnType<typeof v4Router> | undefined;
const provider = createVueRouteProvider(() => router);

expect(provider.resolveRoute(new URL('https://example.com/users/42'))).toBeUndefined();

router = v4Router(makeRoute());
expect(provider.resolveRoute(new URL('https://example.com/users/42'))).toBe('/users/:id');
});

it('returns undefined when nothing matched', () => {
const provider = createVueRouteProvider(() => v4Router(makeRoute()));

expect(provider.resolveRoute(new URL('https://example.com/nope'))).toBeUndefined();
});

describe('Vue Router 4+ history base', () => {
it('strips a non-root base', () => {
const provider = createVueRouteProvider(() => v4Router(makeRoute(), '/app'));

expect(provider.resolveRoute(new URL('https://example.com/app/users/42'))).toBe('/users/:id');
});

it('resolves from the hash with hash history', () => {
const provider = createVueRouteProvider(() => v4Router(makeRoute(), '/#'));

expect(provider.resolveRoute(new URL('https://example.com/#/users/42?tab=1'))).toBe('/users/:id');
expect(provider.resolveRoute(new URL('https://example.com/'))).toBeUndefined();
});

it('resolves from the hash with hash history under a base', () => {
const provider = createVueRouteProvider(() => v4Router(makeRoute(), '/app/#'));

expect(provider.resolveRoute(new URL('https://example.com/app/#/users/42'))).toBe('/users/:id');
});
});

describe('Vue Router 3 mode', () => {
it('strips a non-root base in history mode', () => {
const provider = createVueRouteProvider(() => v3Router(makeRoute(), 'history', '/app'));

expect(provider.resolveRoute(new URL('https://example.com/app/users/42'))).toBe('/users/:id');
});

it('resolves from the hash in hash mode', () => {
const provider = createVueRouteProvider(() => v3Router(makeRoute(), 'hash'));

expect(provider.resolveRoute(new URL('https://example.com/#/users/42'))).toBe('/users/:id');
});
});
});
Comment thread
cursor[bot] marked this conversation as resolved.
63 changes: 63 additions & 0 deletions packages/vue/test/sdk.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { getRouteProvider, resolveRoute } from '@sentry/browser';
import { getMainCarrier } from '@sentry/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { vueIntegration } from '../src/integration';
import { init } from '../src/sdk';
import type { Vue } from '../src/types';

const DSN = 'https://public@dsn.ingest.sentry.io/1337';

const router = { resolve: () => ({ matched: [{ path: '/users/:id' }] }) };

const app = {
config: { globalProperties: { $router: router } },
mixin: vi.fn(),
} as unknown as Vue;

describe('route provider registration', () => {
afterEach(() => {
vi.clearAllMocks();
getMainCarrier().__SENTRY__ = undefined;
});

it('registers a route provider that reads the router off the app passed to `init`', () => {
const client = init({ dsn: DSN, app, defaultIntegrations: false, integrations: [vueIntegration()] });

expect(resolveRoute('https://example.com/users/42', client)).toBe('/users/:id');
});

it('registers a route provider when the app is passed to `vueIntegration`', () => {
const client = init({ dsn: DSN, defaultIntegrations: false, integrations: [vueIntegration({ app })] });

expect(resolveRoute('https://example.com/users/42', client)).toBe('/users/:id');
});

it('registers a route provider that picks the router up from the Vue 2 root instance', () => {
let beforeCreate: (this: unknown) => void = () => {};
const Vue2 = {
config: {},
mixin: (mixin: { beforeCreate: typeof beforeCreate }) => {
beforeCreate = mixin.beforeCreate;
},
} as unknown as Vue;
const client = init({ dsn: DSN, Vue: Vue2, defaultIntegrations: false, integrations: [vueIntegration()] });

expect(resolveRoute('https://example.com/users/42', client)).toBeUndefined();

beforeCreate.call({ $options: { router } });
expect(resolveRoute('https://example.com/users/42', client)).toBe('/users/:id');
});

it('does not register a route provider without an app to read the router from', () => {
const client = init({ dsn: DSN, defaultIntegrations: false, integrations: [vueIntegration()] });

expect(getRouteProvider(client)).toBeUndefined();
});

it('keeps a route provider passed by the user', () => {
const routeProvider = { resolveRoute: () => '/custom', resolveCurrentRoute: () => '/custom' };
const client = init({ dsn: DSN, app, routeProvider, defaultIntegrations: false, integrations: [vueIntegration()] });

expect(getRouteProvider(client)).toBe(routeProvider);
});
});
Loading