-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathreactrouterv6-compat-utils.tsx
665 lines (558 loc) · 20.7 KB
/
reactrouterv6-compat-utils.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
/* eslint-disable max-lines */
// Inspired from Donnie McNeal's solution:
// https://gist.github.com/wontondon/e8c4bdf2888875e4c755712e99279536
import {
WINDOW,
browserTracingIntegration,
startBrowserTracingNavigationSpan,
startBrowserTracingPageLoadSpan,
} from '@sentry/browser';
import type { Client, Integration, Span, TransactionSource } from '@sentry/core';
import {
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
getActiveSpan,
getClient,
getCurrentScope,
getRootSpan,
logger,
spanToJSON,
} from '@sentry/core';
import * as React from 'react';
import hoistNonReactStatics from 'hoist-non-react-statics';
import { DEBUG_BUILD } from './debug-build';
import type {
Action,
AgnosticDataRouteMatch,
CreateRouterFunction,
CreateRoutesFromChildren,
Location,
MatchRoutes,
RouteMatch,
RouteObject,
Router,
RouterState,
UseEffect,
UseLocation,
UseNavigationType,
UseRoutes,
} from './types';
let _useEffect: UseEffect;
let _useLocation: UseLocation;
let _useNavigationType: UseNavigationType;
let _createRoutesFromChildren: CreateRoutesFromChildren;
let _matchRoutes: MatchRoutes;
let _stripBasename: boolean = false;
const CLIENTS_WITH_INSTRUMENT_NAVIGATION = new WeakSet<Client>();
export interface ReactRouterOptions {
useEffect: UseEffect;
useLocation: UseLocation;
useNavigationType: UseNavigationType;
createRoutesFromChildren: CreateRoutesFromChildren;
matchRoutes: MatchRoutes;
stripBasename?: boolean;
}
type V6CompatibleVersion = '6' | '7';
/**
* Creates a wrapCreateBrowserRouter function that can be used with all React Router v6 compatible versions.
*/
export function createV6CompatibleWrapCreateBrowserRouter<
TState extends RouterState = RouterState,
TRouter extends Router<TState> = Router<TState>,
>(
createRouterFunction: CreateRouterFunction<TState, TRouter>,
version: V6CompatibleVersion,
): CreateRouterFunction<TState, TRouter> {
if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) {
DEBUG_BUILD &&
logger.warn(
`reactRouterV${version}Instrumentation was unable to wrap the \`createRouter\` function because of one or more missing parameters.`,
);
return createRouterFunction;
}
return function (routes: RouteObject[], opts?: Record<string, unknown> & { basename?: string }): TRouter {
const router = createRouterFunction(routes, opts);
const basename = opts?.basename;
const activeRootSpan = getActiveRootSpan();
// The initial load ends when `createBrowserRouter` is called.
// This is the earliest convenient time to update the transaction name.
// Callbacks to `router.subscribe` are not called for the initial load.
if (router.state.historyAction === 'POP' && activeRootSpan) {
updatePageloadTransaction(activeRootSpan, router.state.location, routes, undefined, basename);
}
router.subscribe((state: RouterState) => {
const location = state.location;
if (state.historyAction === 'PUSH' || state.historyAction === 'POP') {
handleNavigation({
location,
routes,
navigationType: state.historyAction,
version,
basename,
});
}
});
return router;
};
}
/**
* Creates a wrapCreateMemoryRouter function that can be used with all React Router v6 compatible versions.
*/
export function createV6CompatibleWrapCreateMemoryRouter<
TState extends RouterState = RouterState,
TRouter extends Router<TState> = Router<TState>,
>(
createRouterFunction: CreateRouterFunction<TState, TRouter>,
version: V6CompatibleVersion,
): CreateRouterFunction<TState, TRouter> {
if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) {
DEBUG_BUILD &&
logger.warn(
`reactRouterV${version}Instrumentation was unable to wrap the \`createMemoryRouter\` function because of one or more missing parameters.`,
);
return createRouterFunction;
}
return function (
routes: RouteObject[],
opts?: Record<string, unknown> & {
basename?: string;
initialEntries?: (string | { pathname: string })[];
initialIndex?: number;
},
): TRouter {
const router = createRouterFunction(routes, opts);
const basename = opts?.basename;
const activeRootSpan = getActiveRootSpan();
let initialEntry = undefined;
const initialEntries = opts?.initialEntries;
const initialIndex = opts?.initialIndex;
const hasOnlyOneInitialEntry = initialEntries && initialEntries.length === 1;
const hasIndexedEntry = initialIndex !== undefined && initialEntries && initialEntries[initialIndex];
initialEntry = hasOnlyOneInitialEntry
? initialEntries[0]
: hasIndexedEntry
? initialEntries[initialIndex]
: undefined;
const location = initialEntry
? typeof initialEntry === 'string'
? { pathname: initialEntry }
: initialEntry
: router.state.location;
if (router.state.historyAction === 'POP' && activeRootSpan) {
updatePageloadTransaction(activeRootSpan, location, routes, undefined, basename);
}
router.subscribe((state: RouterState) => {
const location = state.location;
if (state.historyAction === 'PUSH' || state.historyAction === 'POP') {
handleNavigation({
location,
routes,
navigationType: state.historyAction,
version,
basename,
});
}
});
return router;
};
}
/**
* Creates a browser tracing integration that can be used with all React Router v6 compatible versions.
*/
export function createReactRouterV6CompatibleTracingIntegration(
options: Parameters<typeof browserTracingIntegration>[0] & ReactRouterOptions,
version: V6CompatibleVersion,
): Integration {
const integration = browserTracingIntegration({
...options,
instrumentPageLoad: false,
instrumentNavigation: false,
});
const {
useEffect,
useLocation,
useNavigationType,
createRoutesFromChildren,
matchRoutes,
stripBasename,
instrumentPageLoad = true,
instrumentNavigation = true,
} = options;
return {
...integration,
setup() {
_useEffect = useEffect;
_useLocation = useLocation;
_useNavigationType = useNavigationType;
_matchRoutes = matchRoutes;
_createRoutesFromChildren = createRoutesFromChildren;
_stripBasename = stripBasename || false;
},
afterAllSetup(client) {
integration.afterAllSetup(client);
const initPathName = WINDOW.location?.pathname;
if (instrumentPageLoad && initPathName) {
startBrowserTracingPageLoadSpan(client, {
name: initPathName,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'pageload',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: `auto.pageload.react.reactrouter_v${version}`,
},
});
}
if (instrumentNavigation) {
CLIENTS_WITH_INSTRUMENT_NAVIGATION.add(client);
}
},
};
}
export function createV6CompatibleWrapUseRoutes(origUseRoutes: UseRoutes, version: V6CompatibleVersion): UseRoutes {
if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) {
DEBUG_BUILD &&
logger.warn(
'reactRouterV6Instrumentation was unable to wrap `useRoutes` because of one or more missing parameters.',
);
return origUseRoutes;
}
const allRoutes: Set<RouteObject> = new Set();
const SentryRoutes: React.FC<{
children?: React.ReactNode;
routes: RouteObject[];
locationArg?: Partial<Location> | string;
}> = (props: { children?: React.ReactNode; routes: RouteObject[]; locationArg?: Partial<Location> | string }) => {
const isMountRenderPass = React.useRef(true);
const { routes, locationArg } = props;
const Routes = origUseRoutes(routes, locationArg);
const location = _useLocation();
const navigationType = _useNavigationType();
// A value with stable identity to either pick `locationArg` if available or `location` if not
const stableLocationParam =
typeof locationArg === 'string' || locationArg?.pathname ? (locationArg as { pathname: string }) : location;
_useEffect(() => {
const normalizedLocation =
typeof stableLocationParam === 'string' ? { pathname: stableLocationParam } : stableLocationParam;
if (isMountRenderPass.current) {
routes.forEach(route => {
const extractedChildRoutes = getChildRoutesRecursively(route);
extractedChildRoutes.forEach(r => {
allRoutes.add(r);
});
});
updatePageloadTransaction(
getActiveRootSpan(),
normalizedLocation,
routes,
undefined,
undefined,
Array.from(allRoutes),
);
isMountRenderPass.current = false;
} else {
handleNavigation({
location: normalizedLocation,
routes,
navigationType,
version,
allRoutes: Array.from(allRoutes),
});
}
}, [navigationType, stableLocationParam]);
return Routes;
};
// eslint-disable-next-line react/display-name
return (routes: RouteObject[], locationArg?: Partial<Location> | string): React.ReactElement | null => {
return <SentryRoutes routes={routes} locationArg={locationArg} />;
};
}
export function handleNavigation(opts: {
location: Location;
routes: RouteObject[];
navigationType: Action;
version: V6CompatibleVersion;
matches?: AgnosticDataRouteMatch;
basename?: string;
allRoutes?: RouteObject[];
}): void {
const { location, routes, navigationType, version, matches, basename, allRoutes } = opts;
const branches = Array.isArray(matches) ? matches : _matchRoutes(routes, location, basename);
const client = getClient();
if (!client || !CLIENTS_WITH_INSTRUMENT_NAVIGATION.has(client)) {
return;
}
if ((navigationType === 'PUSH' || navigationType === 'POP') && branches) {
let name,
source: TransactionSource = 'url';
const isInDescendantRoute = locationIsInsideDescendantRoute(location, allRoutes || routes);
if (isInDescendantRoute) {
name = prefixWithSlash(rebuildRoutePathFromAllRoutes(allRoutes || routes, location));
source = 'route';
}
if (!isInDescendantRoute || !name) {
[name, source] = getNormalizedName(routes, location, branches, basename);
}
startBrowserTracingNavigationSpan(client, {
name,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source,
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'navigation',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: `auto.navigation.react.reactrouter_v${version}`,
},
});
}
}
/**
* Strip the basename from a pathname if exists.
*
* Vendored and modified from `react-router`
* https://github.com/remix-run/react-router/blob/462bb712156a3f739d6139a0f14810b76b002df6/packages/router/utils.ts#L1038
*/
function stripBasenameFromPathname(pathname: string, basename: string): string {
if (!basename || basename === '/') {
return pathname;
}
if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
return pathname;
}
// We want to leave trailing slash behavior in the user's control, so if they
// specify a basename with a trailing slash, we should support it
const startIndex = basename.endsWith('/') ? basename.length - 1 : basename.length;
const nextChar = pathname.charAt(startIndex);
if (nextChar && nextChar !== '/') {
// pathname does not start with basename/
return pathname;
}
return pathname.slice(startIndex) || '/';
}
function sendIndexPath(pathBuilder: string, pathname: string, basename: string): [string, TransactionSource] {
const reconstructedPath = pathBuilder || _stripBasename ? stripBasenameFromPathname(pathname, basename) : pathname;
const formattedPath =
// If the path ends with a slash, remove it
reconstructedPath[reconstructedPath.length - 1] === '/'
? reconstructedPath.slice(0, -1)
: // If the path ends with a wildcard, remove it
reconstructedPath.slice(-2) === '/*'
? reconstructedPath.slice(0, -1)
: reconstructedPath;
return [formattedPath, 'route'];
}
function pathEndsWithWildcard(path: string): boolean {
return path.endsWith('*');
}
function pathIsWildcardAndHasChildren(path: string, branch: RouteMatch<string>): boolean {
return (pathEndsWithWildcard(path) && !!branch.route.children?.length) || false;
}
function routeIsDescendant(route: RouteObject): boolean {
return !!(!route.children && route.element && route.path?.endsWith('/*'));
}
function locationIsInsideDescendantRoute(location: Location, routes: RouteObject[]): boolean {
const matchedRoutes = _matchRoutes(routes, location) as RouteMatch[];
if (matchedRoutes) {
for (const match of matchedRoutes) {
if (routeIsDescendant(match.route) && pickSplat(match)) {
return true;
}
}
}
return false;
}
function getChildRoutesRecursively(route: RouteObject, allRoutes: Set<RouteObject> = new Set()): Set<RouteObject> {
if (!allRoutes.has(route)) {
allRoutes.add(route);
if (route.children && !route.index) {
route.children.forEach(child => {
const childRoutes = getChildRoutesRecursively(child, allRoutes);
childRoutes.forEach(r => allRoutes.add(r));
});
}
}
return allRoutes;
}
function pickPath(match: RouteMatch): string {
return trimWildcard(match.route.path || '');
}
function pickSplat(match: RouteMatch): string {
return match.params['*'] || '';
}
function trimWildcard(path: string): string {
return path[path.length - 1] === '*' ? path.slice(0, -1) : path;
}
function trimSlash(path: string): string {
return path[path.length - 1] === '/' ? path.slice(0, -1) : path;
}
function prefixWithSlash(path: string): string {
return path[0] === '/' ? path : `/${path}`;
}
function rebuildRoutePathFromAllRoutes(allRoutes: RouteObject[], location: Location): string {
const matchedRoutes = _matchRoutes(allRoutes, location) as RouteMatch[];
if (!matchedRoutes || matchedRoutes.length === 0) {
return '';
}
for (const match of matchedRoutes) {
if (match.route.path && match.route.path !== '*') {
const path = pickPath(match);
const strippedPath = stripBasenameFromPathname(location.pathname, prefixWithSlash(match.pathnameBase));
return trimSlash(
trimSlash(path || '') +
prefixWithSlash(
rebuildRoutePathFromAllRoutes(
allRoutes.filter(route => route !== match.route),
{
pathname: strippedPath,
},
),
),
);
}
}
return '';
}
function getNormalizedName(
routes: RouteObject[],
location: Location,
branches: RouteMatch[],
basename: string = '',
): [string, TransactionSource] {
if (!routes || routes.length === 0) {
return [_stripBasename ? stripBasenameFromPathname(location.pathname, basename) : location.pathname, 'url'];
}
let pathBuilder = '';
if (branches) {
for (const branch of branches) {
const route = branch.route;
if (route) {
// Early return if index route
if (route.index) {
return sendIndexPath(pathBuilder, branch.pathname, basename);
}
const path = route.path;
// If path is not a wildcard and has no child routes, append the path
if (path && !pathIsWildcardAndHasChildren(path, branch)) {
const newPath = path[0] === '/' || pathBuilder[pathBuilder.length - 1] === '/' ? path : `/${path}`;
pathBuilder = trimSlash(pathBuilder) + prefixWithSlash(newPath);
// If the path matches the current location, return the path
if (trimSlash(location.pathname) === trimSlash(basename + branch.pathname)) {
if (
// If the route defined on the element is something like
// <Route path="/stores/:storeId/products/:productId" element={<div>Product</div>} />
// We should check against the branch.pathname for the number of / separators
getNumberOfUrlSegments(pathBuilder) !== getNumberOfUrlSegments(branch.pathname) &&
// We should not count wildcard operators in the url segments calculation
!pathEndsWithWildcard(pathBuilder)
) {
return [(_stripBasename ? '' : basename) + newPath, 'route'];
}
// if the last character of the pathbuilder is a wildcard and there are children, remove the wildcard
if (pathIsWildcardAndHasChildren(pathBuilder, branch)) {
pathBuilder = pathBuilder.slice(0, -1);
}
return [(_stripBasename ? '' : basename) + pathBuilder, 'route'];
}
}
}
}
}
const fallbackTransactionName = _stripBasename
? stripBasenameFromPathname(location.pathname, basename)
: location.pathname || '/';
return [fallbackTransactionName, 'url'];
}
function updatePageloadTransaction(
activeRootSpan: Span | undefined,
location: Location,
routes: RouteObject[],
matches?: AgnosticDataRouteMatch,
basename?: string,
allRoutes?: RouteObject[],
): void {
const branches = Array.isArray(matches)
? matches
: (_matchRoutes(routes, location, basename) as unknown as RouteMatch[]);
if (branches) {
let name,
source: TransactionSource = 'url';
const isInDescendantRoute = locationIsInsideDescendantRoute(location, allRoutes || routes);
if (isInDescendantRoute) {
name = prefixWithSlash(rebuildRoutePathFromAllRoutes(allRoutes || routes, location));
source = 'route';
}
if (!isInDescendantRoute || !name) {
[name, source] = getNormalizedName(routes, location, branches, basename);
}
getCurrentScope().setTransactionName(name);
if (activeRootSpan) {
activeRootSpan.updateName(name);
activeRootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);
}
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function createV6CompatibleWithSentryReactRouterRouting<P extends Record<string, any>, R extends React.FC<P>>(
Routes: R,
version: V6CompatibleVersion,
): R {
if (!_useEffect || !_useLocation || !_useNavigationType || !_createRoutesFromChildren || !_matchRoutes) {
DEBUG_BUILD &&
logger.warn(`reactRouterV6Instrumentation was unable to wrap Routes because of one or more missing parameters.
useEffect: ${_useEffect}. useLocation: ${_useLocation}. useNavigationType: ${_useNavigationType}.
createRoutesFromChildren: ${_createRoutesFromChildren}. matchRoutes: ${_matchRoutes}.`);
return Routes;
}
const allRoutes: Set<RouteObject> = new Set();
const SentryRoutes: React.FC<P> = (props: P) => {
const isMountRenderPass = React.useRef(true);
const location = _useLocation();
const navigationType = _useNavigationType();
_useEffect(
() => {
const routes = _createRoutesFromChildren(props.children) as RouteObject[];
if (isMountRenderPass.current) {
routes.forEach(route => {
const extractedChildRoutes = getChildRoutesRecursively(route);
extractedChildRoutes.forEach(r => {
allRoutes.add(r);
});
});
updatePageloadTransaction(getActiveRootSpan(), location, routes, undefined, undefined, Array.from(allRoutes));
isMountRenderPass.current = false;
} else {
handleNavigation({
location,
routes,
navigationType,
version,
allRoutes: Array.from(allRoutes),
});
}
},
// `props.children` is purposely not included in the dependency array, because we do not want to re-run this effect
// when the children change. We only want to start transactions when the location or navigation type change.
[location, navigationType],
);
// @ts-expect-error Setting more specific React Component typing for `R` generic above
// will break advanced type inference done by react router params
return <Routes {...props} />;
};
hoistNonReactStatics(SentryRoutes, Routes);
// @ts-expect-error Setting more specific React Component typing for `R` generic above
// will break advanced type inference done by react router params
return SentryRoutes;
}
function getActiveRootSpan(): Span | undefined {
const span = getActiveSpan();
const rootSpan = span ? getRootSpan(span) : undefined;
if (!rootSpan) {
return undefined;
}
const op = spanToJSON(rootSpan).op;
// Only use this root span if it is a pageload or navigation span
return op === 'navigation' || op === 'pageload' ? rootSpan : undefined;
}
/**
* Returns number of URL segments of a passed string URL.
*/
export function getNumberOfUrlSegments(url: string): number {
// split at '/' or at '\/' to split regex urls correctly
return url.split(/\\?\//).filter(s => s.length > 0 && s !== ',').length;
}