@servicetitan/datadog-rum 31.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ import type { RumInitConfiguration } from '@datadog/browser-rum';
2
+ export declare function beforeSend(handler?: RumInitConfiguration['beforeSend']): NonNullable<RumInitConfiguration['beforeSend']>;
3
+ //# sourceMappingURL=before-send.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"before-send.d.ts","sourceRoot":"","sources":["../src/before-send.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAMR,oBAAoB,EACvB,MAAM,sBAAsB,CAAC;AAiE9B,wBAAgB,UAAU,CACtB,OAAO,CAAC,EAAE,oBAAoB,CAAC,YAAY,CAAC,GAC7C,WAAW,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAC,CAcjD"}
@@ -0,0 +1,70 @@
1
+ const SERVICE_REGEX = /unpkg\.servicetitan\.com\/@servicetitan\/(?<service>[\w-]+)(?:@(?<version>\d+\.\d+\.\d+(?:-[\w.]+)?))?/;
2
+ function isSameDomainRequest(url) {
3
+ return new URL(url).hostname === window.location.hostname;
4
+ }
5
+ function parseService(event, input) {
6
+ var _match_groups, _match_groups1;
7
+ const match = input === null || input === void 0 ? void 0 : input.match(SERVICE_REGEX);
8
+ const service = match === null || match === void 0 ? void 0 : (_match_groups = match.groups) === null || _match_groups === void 0 ? void 0 : _match_groups.service;
9
+ const version = match === null || match === void 0 ? void 0 : (_match_groups1 = match.groups) === null || _match_groups1 === void 0 ? void 0 : _match_groups1.version;
10
+ if (service) {
11
+ event.service = service;
12
+ event.version = version !== null && version !== void 0 ? version : 'unknown';
13
+ return true;
14
+ }
15
+ return false;
16
+ }
17
+ /**
18
+ * See https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/?tab=npm#micro-frontend
19
+ */ function enrichEvent(event, context) {
20
+ var _event_error, _event_error1, _event_resource;
21
+ var _ref;
22
+ const stack = (_ref = context && 'handlingStack' in context ? context.handlingStack : undefined) !== null && _ref !== void 0 ? _ref : event.type === 'error' ? (_event_error = event.error) === null || _event_error === void 0 ? void 0 : _event_error.stack : undefined;
23
+ const message = event.type === 'error' ? (_event_error1 = event.error) === null || _event_error1 === void 0 ? void 0 : _event_error1.message : undefined;
24
+ const url = event.type === 'resource' ? (_event_resource = event.resource) === null || _event_resource === void 0 ? void 0 : _event_resource.url : undefined;
25
+ for (const source of [
26
+ stack,
27
+ message,
28
+ url
29
+ ]){
30
+ if (parseService(event, source)) {
31
+ break;
32
+ }
33
+ }
34
+ }
35
+ function handleResource(event, context) {
36
+ if (!isSameDomainRequest(event.resource.url)) {
37
+ return;
38
+ }
39
+ let cfRay = undefined;
40
+ switch(event.resource.type){
41
+ case 'fetch':
42
+ var _context_response;
43
+ cfRay = (_context_response = context.response) === null || _context_response === void 0 ? void 0 : _context_response.headers.get('cf-ray');
44
+ break;
45
+ case 'xhr':
46
+ cfRay = context.xhr.getResponseHeader('cf-ray');
47
+ break;
48
+ }
49
+ if (cfRay) {
50
+ event.context = {
51
+ ...event.context,
52
+ cfRay
53
+ };
54
+ }
55
+ }
56
+ export function beforeSend(handler) {
57
+ return function(event, context) {
58
+ try {
59
+ if (event.type === 'resource') {
60
+ handleResource(event, context);
61
+ }
62
+ enrichEvent(event, context);
63
+ var _handler;
64
+ return (_handler = handler === null || handler === void 0 ? void 0 : handler(event, context)) !== null && _handler !== void 0 ? _handler : true;
65
+ } catch (e) {} // eslint-disable-line no-empty
66
+ return true;
67
+ };
68
+ }
69
+
70
+ //# sourceMappingURL=before-send.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/before-send.ts"],"sourcesContent":["import type {\n RumEvent,\n RumEventDomainContext,\n RumFetchResourceEventDomainContext,\n RumResourceEvent,\n RumXhrResourceEventDomainContext,\n RumInitConfiguration,\n} from '@datadog/browser-rum';\n\nconst SERVICE_REGEX =\n /unpkg\\.servicetitan\\.com\\/@servicetitan\\/(?<service>[\\w-]+)(?:@(?<version>\\d+\\.\\d+\\.\\d+(?:-[\\w.]+)?))?/;\n\nfunction isSameDomainRequest(url: string) {\n return new URL(url).hostname === window.location.hostname;\n}\n\nfunction parseService(event: RumEvent, input: string | undefined) {\n const match = input?.match(SERVICE_REGEX);\n\n const service = match?.groups?.service;\n const version = match?.groups?.version;\n\n if (service) {\n event.service = service;\n event.version = version ?? 'unknown';\n return true;\n }\n\n return false;\n}\n\n/**\n * See https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/?tab=npm#micro-frontend\n */\nfunction enrichEvent(event: RumEvent, context: RumEventDomainContext): void {\n const stack =\n (context && 'handlingStack' in context ? context.handlingStack : undefined) ??\n (event.type === 'error' ? event.error?.stack : undefined);\n\n const message = event.type === 'error' ? event.error?.message : undefined;\n\n const url = event.type === 'resource' ? event.resource?.url : undefined;\n\n for (const source of [stack, message, url]) {\n if (parseService(event, source)) {\n break;\n }\n }\n}\n\nfunction handleResource(event: RumResourceEvent, context: RumEventDomainContext): void {\n if (!isSameDomainRequest(event.resource.url)) {\n return;\n }\n\n let cfRay: string | undefined | null = undefined;\n\n switch (event.resource.type) {\n case 'fetch':\n cfRay = (context as RumFetchResourceEventDomainContext).response?.headers.get('cf-ray');\n break;\n\n case 'xhr':\n cfRay = (context as RumXhrResourceEventDomainContext).xhr.getResponseHeader('cf-ray');\n break;\n }\n\n if (cfRay) {\n event.context = { ...event.context, cfRay };\n }\n}\n\nexport function beforeSend(\n handler?: RumInitConfiguration['beforeSend']\n): NonNullable<RumInitConfiguration['beforeSend']> {\n return function (event: RumEvent, context: RumEventDomainContext) {\n try {\n if (event.type === 'resource') {\n handleResource(event, context);\n }\n\n enrichEvent(event, context);\n\n return handler?.(event, context) ?? true;\n } catch {} // eslint-disable-line no-empty\n\n return true;\n };\n}\n"],"names":["SERVICE_REGEX","isSameDomainRequest","url","URL","hostname","window","location","parseService","event","input","match","service","groups","version","enrichEvent","context","stack","handlingStack","undefined","type","error","message","resource","source","handleResource","cfRay","response","headers","get","xhr","getResponseHeader","beforeSend","handler"],"mappings":"AASA,MAAMA,gBACF;AAEJ,SAASC,oBAAoBC,GAAW;IACpC,OAAO,IAAIC,IAAID,KAAKE,QAAQ,KAAKC,OAAOC,QAAQ,CAACF,QAAQ;AAC7D;AAEA,SAASG,aAAaC,KAAe,EAAEC,KAAyB;QAG5CC,eACAA;IAHhB,MAAMA,QAAQD,kBAAAA,4BAAAA,MAAOC,KAAK,CAACV;IAE3B,MAAMW,UAAUD,kBAAAA,6BAAAA,gBAAAA,MAAOE,MAAM,cAAbF,oCAAAA,cAAeC,OAAO;IACtC,MAAME,UAAUH,kBAAAA,6BAAAA,iBAAAA,MAAOE,MAAM,cAAbF,qCAAAA,eAAeG,OAAO;IAEtC,IAAIF,SAAS;QACTH,MAAMG,OAAO,GAAGA;QAChBH,MAAMK,OAAO,GAAGA,oBAAAA,qBAAAA,UAAW;QAC3B,OAAO;IACX;IAEA,OAAO;AACX;AAEA;;CAEC,GACD,SAASC,YAAYN,KAAe,EAAEO,OAA8B;QAGlCP,cAEWA,eAEDA;QALnCO;IADL,MAAMC,QACF,CAACD,OAAAA,WAAW,mBAAmBA,UAAUA,QAAQE,aAAa,GAAGC,uBAAhEH,kBAAAA,OACAP,MAAMW,IAAI,KAAK,WAAUX,eAAAA,MAAMY,KAAK,cAAXZ,mCAAAA,aAAaQ,KAAK,GAAGE;IAEnD,MAAMG,UAAUb,MAAMW,IAAI,KAAK,WAAUX,gBAAAA,MAAMY,KAAK,cAAXZ,oCAAAA,cAAaa,OAAO,GAAGH;IAEhE,MAAMhB,MAAMM,MAAMW,IAAI,KAAK,cAAaX,kBAAAA,MAAMc,QAAQ,cAAdd,sCAAAA,gBAAgBN,GAAG,GAAGgB;IAE9D,KAAK,MAAMK,UAAU;QAACP;QAAOK;QAASnB;KAAI,CAAE;QACxC,IAAIK,aAAaC,OAAOe,SAAS;YAC7B;QACJ;IACJ;AACJ;AAEA,SAASC,eAAehB,KAAuB,EAAEO,OAA8B;IAC3E,IAAI,CAACd,oBAAoBO,MAAMc,QAAQ,CAACpB,GAAG,GAAG;QAC1C;IACJ;IAEA,IAAIuB,QAAmCP;IAEvC,OAAQV,MAAMc,QAAQ,CAACH,IAAI;QACvB,KAAK;gBACO;YAARM,SAAQ,oBAAA,AAACV,QAA+CW,QAAQ,cAAxD,wCAAA,kBAA0DC,OAAO,CAACC,GAAG,CAAC;YAC9E;QAEJ,KAAK;YACDH,QAAQ,AAACV,QAA6Cc,GAAG,CAACC,iBAAiB,CAAC;YAC5E;IACR;IAEA,IAAIL,OAAO;QACPjB,MAAMO,OAAO,GAAG;YAAE,GAAGP,MAAMO,OAAO;YAAEU;QAAM;IAC9C;AACJ;AAEA,OAAO,SAASM,WACZC,OAA4C;IAE5C,OAAO,SAAUxB,KAAe,EAAEO,OAA8B;QAC5D,IAAI;YACA,IAAIP,MAAMW,IAAI,KAAK,YAAY;gBAC3BK,eAAehB,OAAOO;YAC1B;YAEAD,YAAYN,OAAOO;gBAEZiB;YAAP,OAAOA,CAAAA,WAAAA,oBAAAA,8BAAAA,QAAUxB,OAAOO,sBAAjBiB,sBAAAA,WAA6B;QACxC,EAAE,UAAM,CAAC,EAAE,+BAA+B;QAE1C,OAAO;IACX;AACJ"}
@@ -0,0 +1,14 @@
1
+ import { FC, PropsWithChildren } from 'react';
2
+ type User = Omit<import('@datadog/browser-core').User, 'id'> & {
3
+ id: string;
4
+ };
5
+ export interface Options {
6
+ hashRouting?: boolean;
7
+ }
8
+ export declare const DatadogProvider: FC<PropsWithChildren & {
9
+ isEnabled: boolean;
10
+ user?: User;
11
+ options?: Options;
12
+ }>;
13
+ export {};
14
+ //# sourceMappingURL=datadog-provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"datadog-provider.d.ts","sourceRoot":"","sources":["../src/datadog-provider.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,EAAY,iBAAiB,EAAa,MAAM,OAAO,CAAC;AAGnE,KAAK,IAAI,GAAG,IAAI,CAAC,OAAO,uBAAuB,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAE9E,MAAM,WAAW,OAAO;IACpB,WAAW,CAAC,EAAE,OAAO,CAAC;CACzB;AAYD,eAAO,MAAM,eAAe,EAAE,EAAE,CAC5B,iBAAiB,GAAG;IAChB,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,OAAO,CAAC;CACrB,CAYJ,CAAC"}
@@ -0,0 +1,30 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { datadogRum } from '@datadog/browser-rum';
3
+ import { Fragment, useEffect } from 'react';
4
+ import { HashRouting } from './hash-routing';
5
+ const SetUser = ({ user })=>{
6
+ useEffect(()=>{
7
+ if (user) {
8
+ datadogRum.setUser(user);
9
+ }
10
+ }, [
11
+ user
12
+ ]);
13
+ return null;
14
+ };
15
+ export const DatadogProvider = ({ children, isEnabled, user, options })=>{
16
+ if (isEnabled) {
17
+ return /*#__PURE__*/ _jsxs(Fragment, {
18
+ children: [
19
+ /*#__PURE__*/ _jsx(SetUser, {
20
+ user: user
21
+ }),
22
+ (options === null || options === void 0 ? void 0 : options.hashRouting) && /*#__PURE__*/ _jsx(HashRouting, {}),
23
+ children
24
+ ]
25
+ });
26
+ }
27
+ return children;
28
+ };
29
+
30
+ //# sourceMappingURL=datadog-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/datadog-provider.tsx"],"sourcesContent":["import { datadogRum } from '@datadog/browser-rum';\nimport { FC, Fragment, PropsWithChildren, useEffect } from 'react';\nimport { HashRouting } from './hash-routing';\n\ntype User = Omit<import('@datadog/browser-core').User, 'id'> & { id: string };\n\nexport interface Options {\n hashRouting?: boolean;\n}\n\nconst SetUser: FC<{ user?: User }> = ({ user }) => {\n useEffect(() => {\n if (user) {\n datadogRum.setUser(user);\n }\n }, [user]);\n\n return null;\n};\n\nexport const DatadogProvider: FC<\n PropsWithChildren & {\n isEnabled: boolean;\n user?: User;\n options?: Options;\n }\n> = ({ children, isEnabled, user, options }) => {\n if (isEnabled) {\n return (\n <Fragment>\n <SetUser user={user} />\n {options?.hashRouting && <HashRouting />}\n {children}\n </Fragment>\n );\n }\n return children;\n};\n"],"names":["datadogRum","Fragment","useEffect","HashRouting","SetUser","user","setUser","DatadogProvider","children","isEnabled","options","hashRouting"],"mappings":";AAAA,SAASA,UAAU,QAAQ,uBAAuB;AAClD,SAAaC,QAAQ,EAAqBC,SAAS,QAAQ,QAAQ;AACnE,SAASC,WAAW,QAAQ,iBAAiB;AAQ7C,MAAMC,UAA+B,CAAC,EAAEC,IAAI,EAAE;IAC1CH,UAAU;QACN,IAAIG,MAAM;YACNL,WAAWM,OAAO,CAACD;QACvB;IACJ,GAAG;QAACA;KAAK;IAET,OAAO;AACX;AAEA,OAAO,MAAME,kBAMT,CAAC,EAAEC,QAAQ,EAAEC,SAAS,EAAEJ,IAAI,EAAEK,OAAO,EAAE;IACvC,IAAID,WAAW;QACX,qBACI,MAACR;;8BACG,KAACG;oBAAQC,MAAMA;;gBACdK,CAAAA,oBAAAA,8BAAAA,QAASC,WAAW,mBAAI,KAACR;gBACzBK;;;IAGb;IACA,OAAOA;AACX,EAAE"}
@@ -0,0 +1,3 @@
1
+ import { FC } from 'react';
2
+ export declare const HashRouting: FC;
3
+ //# sourceMappingURL=hash-routing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash-routing.d.ts","sourceRoot":"","sources":["../src/hash-routing.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,EAAqB,MAAM,OAAO,CAAC;AAgB9C,eAAO,MAAM,WAAW,EAAE,EAGzB,CAAC"}
@@ -0,0 +1,22 @@
1
+ import { datadogRum } from '@datadog/browser-rum';
2
+ import { useEffect, useRef } from 'react';
3
+ import { useLocation } from 'react-router-dom';
4
+ import { sanitizeViewName } from './sanitize-view-name';
5
+ const useHashRouting = ()=>{
6
+ const pathname = sanitizeViewName(useLocation().pathname);
7
+ const lastPathname = useRef(undefined);
8
+ useEffect(()=>{
9
+ if (lastPathname.current !== pathname) {
10
+ datadogRum.startView(pathname);
11
+ lastPathname.current = pathname;
12
+ }
13
+ }, [
14
+ pathname
15
+ ]);
16
+ };
17
+ export const HashRouting = ()=>{
18
+ useHashRouting();
19
+ return null;
20
+ };
21
+
22
+ //# sourceMappingURL=hash-routing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hash-routing.tsx"],"sourcesContent":["import { datadogRum } from '@datadog/browser-rum';\nimport { FC, useEffect, useRef } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport { sanitizeViewName } from './sanitize-view-name';\n\nconst useHashRouting = () => {\n const pathname = sanitizeViewName(useLocation().pathname);\n const lastPathname = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n if (lastPathname.current !== pathname) {\n datadogRum.startView(pathname);\n lastPathname.current = pathname;\n }\n }, [pathname]);\n};\n\nexport const HashRouting: FC = () => {\n useHashRouting();\n return null;\n};\n"],"names":["datadogRum","useEffect","useRef","useLocation","sanitizeViewName","useHashRouting","pathname","lastPathname","undefined","current","startView","HashRouting"],"mappings":"AAAA,SAASA,UAAU,QAAQ,uBAAuB;AAClD,SAAaC,SAAS,EAAEC,MAAM,QAAQ,QAAQ;AAC9C,SAASC,WAAW,QAAQ,mBAAmB;AAC/C,SAASC,gBAAgB,QAAQ,uBAAuB;AAExD,MAAMC,iBAAiB;IACnB,MAAMC,WAAWF,iBAAiBD,cAAcG,QAAQ;IACxD,MAAMC,eAAeL,OAA2BM;IAEhDP,UAAU;QACN,IAAIM,aAAaE,OAAO,KAAKH,UAAU;YACnCN,WAAWU,SAAS,CAACJ;YACrBC,aAAaE,OAAO,GAAGH;QAC3B;IACJ,GAAG;QAACA;KAAS;AACjB;AAEA,OAAO,MAAMK,cAAkB;IAC3BN;IACA,OAAO;AACX,EAAE"}
@@ -0,0 +1,3 @@
1
+ export * from './before-send';
2
+ export * from './datadog-provider';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,oBAAoB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './before-send';
2
+ export * from './datadog-provider';
3
+
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './before-send';\nexport * from './datadog-provider';\n"],"names":[],"mappings":"AAAA,cAAc,gBAAgB;AAC9B,cAAc,qBAAqB"}
@@ -0,0 +1,2 @@
1
+ export declare function sanitizeViewName(viewName: string): string;
2
+ //# sourceMappingURL=sanitize-view-name.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sanitize-view-name.d.ts","sourceRoot":"","sources":["../src/sanitize-view-name.tsx"],"names":[],"mappings":"AAAA,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,UAoBhD"}
@@ -0,0 +1,21 @@
1
+ export function sanitizeViewName(viewName) {
2
+ try {
3
+ const replaceIds = viewName.toLowerCase().replace(/\/(\d+[^/]*)(?=\/|$)/g, '/{id}') // turn numbers to {id} placeholder
4
+ .replace(/\/(null|undefined)(?=\/|$)/g, '/{id}') // turn null and undefined to {id} placeholder
5
+ .replace(/\/([^/]*\.[a-z]+)(?=\/|$)/g, '/{id}') // turn file names to {id} placeholder
6
+ .replace(/\/([^/]*[=%+][^/]*)(?=\/|$)/g, '/{id}') // turn dates, phone numbers and query parameters to {id} placeholder
7
+ .replace(/(.+?)(\/+)$/, '$1') // remove '/' from the end of the line
8
+ .replace(/(\/)(\/+)/g, '/') // remove duplicate '/'
9
+ .replace('#', '');
10
+ if (replaceIds.startsWith('/proxy')) {
11
+ return replaceIds.replace(/^\/proxy/, '/').replace(/\/[^/]*$/, '');
12
+ }
13
+ return replaceIds;
14
+ } catch (e) {
15
+ // eslint-disable-next-line no-console
16
+ console.error(e);
17
+ return viewName;
18
+ }
19
+ }
20
+
21
+ //# sourceMappingURL=sanitize-view-name.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sanitize-view-name.tsx"],"sourcesContent":["export function sanitizeViewName(viewName: string) {\n try {\n const replaceIds = viewName\n .toLowerCase()\n .replace(/\\/(\\d+[^/]*)(?=\\/|$)/g, '/{id}') // turn numbers to {id} placeholder\n .replace(/\\/(null|undefined)(?=\\/|$)/g, '/{id}') // turn null and undefined to {id} placeholder\n .replace(/\\/([^/]*\\.[a-z]+)(?=\\/|$)/g, '/{id}') // turn file names to {id} placeholder\n .replace(/\\/([^/]*[=%+][^/]*)(?=\\/|$)/g, '/{id}') // turn dates, phone numbers and query parameters to {id} placeholder\n .replace(/(.+?)(\\/+)$/, '$1') // remove '/' from the end of the line\n .replace(/(\\/)(\\/+)/g, '/') // remove duplicate '/'\n .replace('#', '');\n if (replaceIds.startsWith('/proxy')) {\n return replaceIds.replace(/^\\/proxy/, '/').replace(/\\/[^/]*$/, '');\n }\n return replaceIds;\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n return viewName;\n }\n}\n"],"names":["sanitizeViewName","viewName","replaceIds","toLowerCase","replace","startsWith","e","console","error"],"mappings":"AAAA,OAAO,SAASA,iBAAiBC,QAAgB;IAC7C,IAAI;QACA,MAAMC,aAAaD,SACdE,WAAW,GACXC,OAAO,CAAC,yBAAyB,SAAS,mCAAmC;SAC7EA,OAAO,CAAC,+BAA+B,SAAS,8CAA8C;SAC9FA,OAAO,CAAC,8BAA8B,SAAS,sCAAsC;SACrFA,OAAO,CAAC,gCAAgC,SAAS,qEAAqE;SACtHA,OAAO,CAAC,eAAe,MAAM,sCAAsC;SACnEA,OAAO,CAAC,cAAc,KAAK,uBAAuB;SAClDA,OAAO,CAAC,KAAK;QAClB,IAAIF,WAAWG,UAAU,CAAC,WAAW;YACjC,OAAOH,WAAWE,OAAO,CAAC,YAAY,KAAKA,OAAO,CAAC,YAAY;QACnE;QACA,OAAOF;IACX,EAAE,OAAOI,GAAG;QACR,sCAAsC;QACtCC,QAAQC,KAAK,CAACF;QACd,OAAOL;IACX;AACJ"}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@servicetitan/datadog-rum",
3
+ "version": "31.6.0",
4
+ "description": "",
5
+ "homepage": "https://docs.st.dev/docs/frontend/datadog-rum",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/servicetitan/uikit.git",
9
+ "directory": "packages/datadog-rum"
10
+ },
11
+ "sideEffects": false,
12
+ "exports": {
13
+ ".": {
14
+ "default": "./dist/index.js",
15
+ "types": "./dist/index.d.ts"
16
+ }
17
+ },
18
+ "main": "./dist/index.js",
19
+ "typings": "./dist/index.d.ts",
20
+ "files": [
21
+ "dist",
22
+ "src"
23
+ ],
24
+ "devDependencies": {
25
+ "@datadog/browser-rum": "^6.19.0",
26
+ "@testing-library/dom": "^10.4.1",
27
+ "@testing-library/jest-dom": "^6.8.0",
28
+ "@testing-library/react": "^16.3.0",
29
+ "react": "~18.3.1",
30
+ "react-router-dom": "~5.3.0"
31
+ },
32
+ "peerDependencies": {
33
+ "@datadog/browser-rum": "^6.19.0",
34
+ "react": ">=17.0.2",
35
+ "react-router-dom": ">=5.3.0"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "cli": {
41
+ "webpack": false
42
+ },
43
+ "gitHead": "533bcbd267e11c88700b29f539ca1cb5de6440ae"
44
+ }
@@ -0,0 +1,177 @@
1
+ // These are real error messages that are used to verify service and version attribution.
2
+
3
+ import { RumEvent, RumEventDomainContext } from '@datadog/browser-rum';
4
+
5
+ const hostErrorAxiosError400 = {
6
+ error: {
7
+ message: 'Request failed with status code 400',
8
+ stack: `
9
+ AxiosError: Request failed with status code 400
10
+ at settle @ https://go.servicetitan.com/scripts/build/desktop/log.55e5bb93faab978eaf35.bundle.js?3d68802447462b52b684:2:102209
11
+ at XMLHttpRequest.onloadend @ https://go.servicetitan.com/scripts/build/desktop/log.55e5bb93faab978eaf35.bundle.js?3d68802447462b52b684:2:71196
12
+ `,
13
+ },
14
+ context: {},
15
+ };
16
+
17
+ const hostErrorFailedToFetchMetadata = {
18
+ error: {
19
+ message:
20
+ 'Failed to fetch: "https://unpkg.servicetitan.com/@servicetitan/global-search-bar/dist/metadata.json".',
21
+ },
22
+ context: {
23
+ handlingStack: `
24
+ Error:
25
+ at Li @ https://go.servicetitan.com/scripts/build/desktop/main.f692da9da087afdc5a8e.bundle.js?5813f5881d1fcbafd9db:2:17756142
26
+ at Qi.ye.componentDidCatch.de.callback @ https://go.servicetitan.com/scripts/build/desktop/main.f692da9da087afdc5a8e.bundle.js?5813f5881d1fcbafd9db:2:17756694
27
+ at sh @ https://go.servicetitan.com/scripts/build/desktop/main.f692da9da087afdc5a8e.bundle.js?5813f5881d1fcbafd9db:2:17742258
28
+ at kk @ https://go.servicetitan.com/scripts/build/desktop/main.f692da9da087afdc5a8e.bundle.js?5813f5881d1fcbafd9db:2:17791244
29
+ at ik @ https://go.servicetitan.com/scripts/build/desktop/main.f692da9da087afdc5a8e.bundle.js?5813f5881d1fcbafd9db:2:17790779
30
+ at hk @ https://go.servicetitan.com/scripts/build/desktop/main.f692da9da087afdc5a8e.bundle.js?5813f5881d1fcbafd9db:2:17790255
31
+ at Wk @ https://go.servicetitan.com/scripts/build/desktop/main.f692da9da087afdc5a8e.bundle.js?5813f5881d1fcbafd9db:2:17801154
32
+ at Pk @ https://go.servicetitan.com/scripts/build/desktop/main.f692da9da087afdc5a8e.bundle.js?5813f5881d1fcbafd9db:2:17800452
33
+ `,
34
+ },
35
+ };
36
+
37
+ const mfeErrorComponentDidCatch = {
38
+ error: {
39
+ message: `
40
+ Request failed with status code 502
41
+ URL: https://coolairmechanicalllc-71757.eh.go.servicetitan.com/api/global-search/search
42
+ `,
43
+ },
44
+ context: {
45
+ handlingStack: `
46
+ Error:
47
+ at console.e [as error] @ https://edge.fullstory.com/s/fs.js:4:32090
48
+ at Li @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.5f317fc/dist/bundle/light/common.4930800d528fa1ae167c.bundle.js:2:259070
49
+ at Qi.f.componentDidCatch.c.callback @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.5f317fc/dist/bundle/light/common.4930800d528fa1ae167c.bundle.js:2:259583
50
+ at sh @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.5f317fc/dist/bundle/light/common.4930800d528fa1ae167c.bundle.js:2:246367
51
+ at kk @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.5f317fc/dist/bundle/light/common.4930800d528fa1ae167c.bundle.js:2:291027
52
+ at ik @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.5f317fc/dist/bundle/light/common.4930800d528fa1ae167c.bundle.js:2:290595
53
+ at ik @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.5f317fc/dist/bundle/light/common.4930800d528fa1ae167c.bundle.js:2:290492
54
+ at ik @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.5f317fc/dist/bundle/light/common.4930800d528fa1ae167c.bundle.js:2:290492
55
+ `,
56
+ },
57
+ };
58
+
59
+ const hostResourceXhrRequest = {
60
+ resource: {
61
+ url: 'https://go.servicetitan.com/CoreSettings/GetPermissions?_=1757708219745',
62
+ },
63
+ context: {
64
+ handlingStack: `
65
+ Error:
66
+ at Object.send @ https://go.servicetitan.com/scripts/build/desktop-legacy/core.a7e0b207b2ca2251a254.bundle.js:2:214394
67
+ at ajax @ https://go.servicetitan.com/scripts/build/desktop-legacy/core.a7e0b207b2ca2251a254.bundle.js:2:206941
68
+ at jQuery.aroundAjax [as ajax] @ https://go.servicetitan.com/scripts/build/desktop-legacy/app.730fca0be346d7ecd92e.bundle.js:2:4543920
69
+ at jQuery.each.jQuery.<computed> [as get] @ https://go.servicetitan.com/scripts/build/desktop-legacy/core.a7e0b207b2ca2251a254.bundle.js:2:208902
70
+ at activateSettingsBoard @ https://go.servicetitan.com/scripts/build/desktop-legacy/app.730fca0be346d7ecd92e.bundle.js:2:8233677
71
+ at context_prototype.<anonymous> @ https://go.servicetitan.com/scripts/build/desktop-legacy/app.730fca0be346d7ecd92e.bundle.js:2:8242958
72
+ at nextRoute @ https://go.servicetitan.com/scripts/build/desktop-legacy/core.a7e0b207b2ca2251a254.bundle.js:2:587350
73
+ at wrapped_route @ https://go.servicetitan.com/scripts/build/desktop-legacy/core.a7e0b207b2ca2251a254.bundle.js:2:587499
74
+ `,
75
+ },
76
+ };
77
+
78
+ const hostResourceUnpkgRequest = {
79
+ resource: {
80
+ url: 'https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.c8fa2a6/dist/bundle/light/main.a7d8d964f5d244d802a4.bundle.js',
81
+ },
82
+ context: {},
83
+ };
84
+
85
+ const mfeResourceXhrRequest = {
86
+ resource: { url: 'https://go.servicetitan.com/app/api/data/user' },
87
+ context: {
88
+ handlingStack: `
89
+ Error:
90
+ at dispatchXhrRequest @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.c8fa2a6/dist/bundle/light/common.5bf0a9999ba3a2165cca.bundle.js:2:157541
91
+ at new Promise @ <anonymous>
92
+ at xhr @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.c8fa2a6/dist/bundle/light/common.5bf0a9999ba3a2165cca.bundle.js:2:153971
93
+ at Axios.dispatchRequest @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.c8fa2a6/dist/bundle/light/common.5bf0a9999ba3a2165cca.bundle.js:2:166313
94
+ at Axios._request @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.c8fa2a6/dist/bundle/light/common.5bf0a9999ba3a2165cca.bundle.js:2:171799
95
+ at Axios.request @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.c8fa2a6/dist/bundle/light/common.5bf0a9999ba3a2165cca.bundle.js:2:168810
96
+ at wrap [as request] @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.c8fa2a6/dist/bundle/light/common.5bf0a9999ba3a2165cca.bundle.js:2:118354
97
+ at UserApi.get @ https://unpkg.servicetitan.com/@servicetitan/global-search-bar@0.0.0-HEAD.c8fa2a6/dist/bundle/light/main.a7d8d964f5d244d802a4.bundle.js:2:582407
98
+ `,
99
+ },
100
+ };
101
+
102
+ type DeepPartial<T> = T extends object
103
+ ? {
104
+ [P in keyof T]?: DeepPartial<T[P]>;
105
+ }
106
+ : T;
107
+
108
+ export type RumEventType = DeepPartial<RumEvent>;
109
+
110
+ export const rumEvents: {
111
+ event: RumEventType;
112
+ context?: RumEventDomainContext;
113
+ title: string;
114
+ service?: string;
115
+ version?: string;
116
+ }[] = [
117
+ {
118
+ event: {
119
+ type: 'error',
120
+ error: hostErrorAxiosError400.error,
121
+ },
122
+ context: hostErrorAxiosError400.context,
123
+ title: 'host request failed with status code 400',
124
+ service: undefined,
125
+ version: undefined,
126
+ },
127
+ {
128
+ event: {
129
+ type: 'error',
130
+ error: hostErrorFailedToFetchMetadata.error,
131
+ },
132
+ context: hostErrorFailedToFetchMetadata.context,
133
+ title: 'host failed to fetch metadata.json',
134
+ service: 'global-search-bar',
135
+ version: 'unknown',
136
+ },
137
+ {
138
+ event: {
139
+ type: 'error',
140
+ error: mfeErrorComponentDidCatch.error,
141
+ },
142
+ context: mfeErrorComponentDidCatch.context,
143
+ title: 'MFE request failed with status code 502',
144
+ service: 'global-search-bar',
145
+ version: '0.0.0-HEAD.5f317fc',
146
+ },
147
+ {
148
+ event: {
149
+ type: 'resource',
150
+ resource: hostResourceXhrRequest.resource,
151
+ },
152
+ context: hostResourceXhrRequest.context,
153
+ title: 'host sends XHR request',
154
+ service: undefined,
155
+ version: undefined,
156
+ },
157
+ {
158
+ event: {
159
+ type: 'resource',
160
+ resource: hostResourceUnpkgRequest.resource,
161
+ },
162
+ context: hostResourceUnpkgRequest.context,
163
+ title: 'host sends request to unpkg',
164
+ service: 'global-search-bar',
165
+ version: '0.0.0-HEAD.c8fa2a6',
166
+ },
167
+ {
168
+ event: {
169
+ type: 'resource',
170
+ resource: mfeResourceXhrRequest.resource,
171
+ },
172
+ context: mfeResourceXhrRequest.context,
173
+ title: 'mfe sends XHR request',
174
+ service: 'global-search-bar',
175
+ version: '0.0.0-HEAD.c8fa2a6',
176
+ },
177
+ ];
@@ -0,0 +1,112 @@
1
+ import type { RumEvent, RumEventDomainContext } from '@datadog/browser-rum';
2
+
3
+ import { beforeSend } from '../before-send';
4
+ import { rumEvents, RumEventType } from '../__mocks__/before-send-data';
5
+
6
+ type Mutable<T> = { -readonly [P in keyof T]: T[P] };
7
+
8
+ describe(`[datadog-rum] ${beforeSend.name}`, () => {
9
+ let customHandler: (() => boolean) | undefined;
10
+
11
+ let event: Mutable<RumEventType>;
12
+ let context: RumEventDomainContext;
13
+
14
+ beforeEach(() => {
15
+ context = {};
16
+ customHandler = undefined;
17
+ });
18
+
19
+ const subject = () => {
20
+ const beforeSendHandler = beforeSend(customHandler);
21
+ return beforeSendHandler(event as RumEvent, context);
22
+ };
23
+
24
+ describe('with an "error" event', () => {
25
+ beforeEach(() => (event = { type: 'error' }));
26
+
27
+ function itReturns(value: boolean) {
28
+ test(`returns ${value}`, () => expect(subject()).toBe(value));
29
+ }
30
+
31
+ itReturns(true);
32
+
33
+ describe('with custom handler', () => {
34
+ beforeEach(() => {
35
+ customHandler = jest.fn(() => true);
36
+ });
37
+
38
+ itReturns(true);
39
+
40
+ test('custom handler is called', () => {
41
+ subject();
42
+
43
+ expect(customHandler).toHaveBeenCalled();
44
+ });
45
+
46
+ describe('when the handler returns false', () => {
47
+ beforeEach(() => {
48
+ customHandler = jest.fn(() => false);
49
+ });
50
+
51
+ itReturns(false);
52
+ });
53
+ });
54
+ });
55
+
56
+ describe('with a "resource" event', () => {
57
+ const cfRay = 'foo: bar';
58
+ const headers = new Map([['cf-ray', cfRay]]);
59
+
60
+ beforeEach(() => (event = { type: 'resource' }));
61
+
62
+ function itAddsCfRayToEventContext() {
63
+ test('adds "cfRay" header to event context', () => {
64
+ subject();
65
+
66
+ expect(event.context!.cfRay).toEqual(cfRay);
67
+ });
68
+
69
+ describe('when location is different', () => {
70
+ beforeEach(() => ((event.resource as any).url = 'https://example.com'));
71
+
72
+ test('does not add "cfRay" header', () => {
73
+ subject();
74
+
75
+ expect(event.context?.cfRay).toBeUndefined();
76
+ });
77
+ });
78
+ }
79
+
80
+ describe('with "fetch" resource type', () => {
81
+ beforeEach(() => {
82
+ event.resource = { type: 'fetch', url: window.location.toString() };
83
+ context = { response: { headers } };
84
+ });
85
+
86
+ itAddsCfRayToEventContext();
87
+ });
88
+
89
+ describe('with "xhr" resource type', () => {
90
+ beforeEach(() => {
91
+ event.resource = { type: 'xhr', url: window.location.toString() };
92
+ context = { xhr: { getResponseHeader: (key: string) => headers.get(key) } };
93
+ });
94
+
95
+ itAddsCfRayToEventContext();
96
+ });
97
+ });
98
+
99
+ describe.each(rumEvents)('when event.type=$event.type and $title', rumEvent => {
100
+ beforeEach(() => {
101
+ event = rumEvent.event;
102
+ context = rumEvent.context ?? {};
103
+ });
104
+
105
+ test('assigns expected service and version', () => {
106
+ subject();
107
+
108
+ expect(event.service).toEqual(rumEvent.service);
109
+ expect(event.version).toEqual(rumEvent.version);
110
+ });
111
+ });
112
+ });
@@ -0,0 +1,102 @@
1
+ import { FC, Fragment, useState } from 'react';
2
+ import { act, render, waitFor, screen } from '@testing-library/react';
3
+ import { datadogRum } from '@datadog/browser-rum';
4
+ import '@testing-library/jest-dom';
5
+
6
+ import { DatadogProvider, Options } from '../datadog-provider';
7
+
8
+ jest.mock('@datadog/browser-rum');
9
+ jest.mock('../hash-routing', () => mockComponent('HashRouting'));
10
+
11
+ function mockComponent(name: string) {
12
+ return {
13
+ [name]: ({ children }: any) => (
14
+ <Fragment>
15
+ <div>{`<${name} />`}</div>
16
+ {children}
17
+ </Fragment>
18
+ ),
19
+ };
20
+ }
21
+
22
+ type User = Omit<import('@datadog/browser-core').User, 'id'> & { id: string };
23
+
24
+ describe(`[datadog-rum] ${DatadogProvider.name}`, () => {
25
+ let setUser: (user?: User) => void;
26
+ let isEnabled: boolean;
27
+ let options: Options;
28
+
29
+ const subject = () => {
30
+ const Component: FC = () => {
31
+ const [user, setUserInner] = useState<User | undefined>({ id: '1' });
32
+ setUser = setUserInner;
33
+ return <DatadogProvider isEnabled={isEnabled} user={user} options={options} />;
34
+ };
35
+ return render(<Component />);
36
+ };
37
+
38
+ beforeEach(() => {
39
+ isEnabled = true;
40
+ options = {};
41
+ jest.clearAllMocks();
42
+ });
43
+ test('initializes user', () => {
44
+ subject();
45
+ expect(datadogRum.setUser).toHaveBeenCalledWith({ id: '1' });
46
+ });
47
+
48
+ describe('when user is changed', () => {
49
+ beforeEach(() => {
50
+ subject();
51
+ act(() => {
52
+ setUser({ id: '2' });
53
+ });
54
+ });
55
+
56
+ test('updates user', () => {
57
+ expect(datadogRum.setUser).toHaveBeenCalledWith({ id: '2' });
58
+ });
59
+
60
+ describe('to undefined', () => {
61
+ beforeEach(() => {
62
+ jest.clearAllMocks();
63
+ act(() => {
64
+ setUser(undefined);
65
+ });
66
+ });
67
+ test("doesn't update user", () => {
68
+ expect(datadogRum.setUser).not.toHaveBeenCalled();
69
+ });
70
+ });
71
+ });
72
+
73
+ describe('with isEnabled=false', () => {
74
+ beforeEach(() => {
75
+ isEnabled = false;
76
+ });
77
+
78
+ test("doesn't initialize user", () => {
79
+ subject();
80
+
81
+ expect(datadogRum.setUser).not.toHaveBeenCalled();
82
+ });
83
+ });
84
+
85
+ test("doesn't render <HashRouting />", async () => {
86
+ subject();
87
+
88
+ await waitFor(() => expect(screen.queryByText('<HashRouting />')).not.toBeInTheDocument());
89
+ });
90
+
91
+ describe('when options.hashRouting=true', () => {
92
+ beforeEach(() => {
93
+ options = { hashRouting: true };
94
+ });
95
+
96
+ test('renders <HashRouting />', async () => {
97
+ subject();
98
+
99
+ await waitFor(() => expect(screen.queryByText('<HashRouting />')).toBeInTheDocument());
100
+ });
101
+ });
102
+ });
@@ -0,0 +1,71 @@
1
+ import { FC } from 'react';
2
+ import { act, render } from '@testing-library/react';
3
+ import { BrowserRouter, useHistory } from 'react-router-dom';
4
+ import { datadogRum } from '@datadog/browser-rum';
5
+
6
+ import { HashRouting } from '../hash-routing';
7
+
8
+ jest.mock('@datadog/browser-rum');
9
+
10
+ function mockLocation(newLocation: { origin?: string; pathname?: string } | string) {
11
+ const { origin = window.location.origin, pathname = window.location.pathname } =
12
+ typeof newLocation === 'string' ? { pathname: newLocation } : newLocation;
13
+ (window.location as any) = Object.assign(new URL(`${origin}${pathname}`), {
14
+ assign: jest.fn(),
15
+ reload: jest.fn(),
16
+ });
17
+ }
18
+
19
+ describe(`[datadog-rum] ${HashRouting.name}`, () => {
20
+ let history: ReturnType<typeof useHistory>;
21
+ const subject = () => {
22
+ const History: FC = () => {
23
+ history = useHistory();
24
+ return null;
25
+ };
26
+ return render(
27
+ <BrowserRouter>
28
+ <History />
29
+ <HashRouting />
30
+ </BrowserRouter>
31
+ );
32
+ };
33
+
34
+ beforeEach(() => {
35
+ jest.clearAllMocks();
36
+ mockLocation({ origin: 'https://go.servicetitan.com' });
37
+ });
38
+
39
+ describe('when location changes', () => {
40
+ const location = '/billing/1';
41
+ const setup = (locations: string[] = []) => {
42
+ const subjectResult = subject();
43
+ jest.mocked(datadogRum.startView).mockClear();
44
+ locations.forEach(currentLocation => act(() => history.push(currentLocation)));
45
+ return subjectResult;
46
+ };
47
+
48
+ test('notifies DataDog', () => {
49
+ setup([location]);
50
+ expect(datadogRum.startView).toHaveBeenCalledTimes(1);
51
+ expect(datadogRum.startView).toHaveBeenCalledWith('/billing/{id}');
52
+ });
53
+
54
+ test('sends single notification for duplicate locations', () => {
55
+ setup([location, location]);
56
+ expect(datadogRum.startView).toHaveBeenCalledTimes(1);
57
+ });
58
+
59
+ test('sends single notification for similar locations', () => {
60
+ setup([location, '/billing/2']);
61
+ expect(datadogRum.startView).toHaveBeenCalledTimes(1);
62
+ });
63
+
64
+ test('sends no notification after unmount', () => {
65
+ const { unmount } = setup();
66
+ unmount();
67
+ history.push(location);
68
+ expect(datadogRum.startView).not.toHaveBeenCalled();
69
+ });
70
+ });
71
+ });
@@ -0,0 +1,92 @@
1
+ import { sanitizeViewName } from '../sanitize-view-name';
2
+
3
+ describe(`[datadog-rum] ${sanitizeViewName.name}`, () => {
4
+ const subject = (viewName: string) => {
5
+ return sanitizeViewName(viewName);
6
+ };
7
+
8
+ describe('when view name contains IDs', () => {
9
+ test.each([
10
+ ['/new/reports/123', '/new/reports/{id}'],
11
+ ['/new/reports/123/summary', '/new/reports/{id}/summary'],
12
+ ['/new/reports/123/summary/321', '/new/reports/{id}/summary/{id}'],
13
+ ['/new/reports/123ab/summary/32100--r', '/new/reports/{id}/summary/{id}'],
14
+ ['/new/reports/10-10-2022/summary/321', '/new/reports/{id}/summary/{id}'],
15
+ ['/new/reports/null/summary/undefined', '/new/reports/{id}/summary/{id}'],
16
+ [
17
+ '/new/inventory/download-import-errors/Temp%2FDataExportResults%2Fb8ef44acd-d4ed-4d1a-9f9f-a6c21e80ce9e.xlsx/1',
18
+ '/new/inventory/download-import-errors/{id}/{id}',
19
+ ],
20
+ [
21
+ '/new/inventory/download-import-errors/Temp%2FDataExportResults%2Fb8ef44acd-d4ed-4d1a-9f9f-a6c21e80ce9e.txt.xlsx/1',
22
+ '/new/inventory/download-import-errors/{id}/{id}',
23
+ ],
24
+ [
25
+ '/new/inventory/download-import-errors/hello.txt',
26
+ '/new/inventory/download-import-errors/{id}',
27
+ ],
28
+ ['/AbandonedScorecard/1/2/%20Abandoned', '/abandonedscorecard/{id}/{id}/{id}'],
29
+ ['/Calls/Caller/%2019104715121', '/calls/caller/{id}'],
30
+ [
31
+ '/dispatch/routes/coordinates=33.5365013%2C-111.944217&name=Richard+Nearhood&address=6767+North+63rd+Place%2C+Paradise+Valley%2C+AZ+85253+USA',
32
+ '/dispatch/routes/{id}',
33
+ ],
34
+ [
35
+ '/new/marketing/re/reputationmanagement/id=4716512/hello',
36
+ '/new/marketing/re/reputationmanagement/{id}/hello',
37
+ ],
38
+ ['/KpiMatrix/Office%20Performance', '/kpimatrix/{id}'],
39
+ ['/ChatCenter/+16193895593+1619-389-5593', '/chatcenter/{id}'],
40
+ ])('replaces IDs with placeholders (%s -> %s)', (viewName, expected) => {
41
+ expect(subject(viewName)).toBe(expected);
42
+ });
43
+ });
44
+
45
+ describe('when view name contain IDs lookalikes', () => {
46
+ test.each([
47
+ ['/new/reports/summary/uundefined', '/new/reports/summary/uundefined'],
48
+ ['/new/reports/nulll/summary', '/new/reports/nulll/summary'],
49
+ ['/new/reports/feature2.0/summary', '/new/reports/feature2.0/summary'],
50
+ ])('does nothing (%s -> %s)', (viewName, expected) => {
51
+ expect(subject(viewName)).toBe(expected);
52
+ });
53
+ });
54
+
55
+ describe('when view name contains "#"', () => {
56
+ test('removes "#"', () => {
57
+ expect(subject('#/new/reports')).toBe('/new/reports');
58
+ });
59
+ });
60
+
61
+ describe('when view name contains IDs and/or /proxy prefix', () => {
62
+ test.each([
63
+ ['/proxyCalls/tenantName', '/calls'],
64
+ ['/proxyCalls/chat/123/321/tenantName', '/calls/chat/{id}/{id}'],
65
+ ])(
66
+ 'replaces IDs with placeholders and removes /proxy and /tenantName (%s -> %s)',
67
+ (viewName, expected) => {
68
+ expect(subject(viewName)).toBe(expected);
69
+ }
70
+ );
71
+ });
72
+
73
+ describe('when view name contains empty segments', () => {
74
+ test.each([
75
+ ['/new/reports/123/', '/new/reports/{id}'],
76
+ ['/new/reports/123//', '/new/reports/{id}'],
77
+ ['/', '/'],
78
+ ['///', '/'],
79
+ ['//new///reports//123//', '/new/reports/{id}'],
80
+ ])('removes duplicate "/" (%s -> %s)', (viewName, expected) => {
81
+ expect(subject(viewName)).toBe(expected);
82
+ });
83
+ });
84
+
85
+ describe('when view name is invalid', () => {
86
+ test("doesn't throw an error", () => {
87
+ jest.spyOn(console, 'error').mockImplementation(jest.fn()); // suppress error output
88
+ // @ts-expect-error because number is not a valid argument
89
+ expect(subject(1)).toBe(1);
90
+ });
91
+ });
92
+ });
@@ -0,0 +1,89 @@
1
+ import type {
2
+ RumEvent,
3
+ RumEventDomainContext,
4
+ RumFetchResourceEventDomainContext,
5
+ RumResourceEvent,
6
+ RumXhrResourceEventDomainContext,
7
+ RumInitConfiguration,
8
+ } from '@datadog/browser-rum';
9
+
10
+ const SERVICE_REGEX =
11
+ /unpkg\.servicetitan\.com\/@servicetitan\/(?<service>[\w-]+)(?:@(?<version>\d+\.\d+\.\d+(?:-[\w.]+)?))?/;
12
+
13
+ function isSameDomainRequest(url: string) {
14
+ return new URL(url).hostname === window.location.hostname;
15
+ }
16
+
17
+ function parseService(event: RumEvent, input: string | undefined) {
18
+ const match = input?.match(SERVICE_REGEX);
19
+
20
+ const service = match?.groups?.service;
21
+ const version = match?.groups?.version;
22
+
23
+ if (service) {
24
+ event.service = service;
25
+ event.version = version ?? 'unknown';
26
+ return true;
27
+ }
28
+
29
+ return false;
30
+ }
31
+
32
+ /**
33
+ * See https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/?tab=npm#micro-frontend
34
+ */
35
+ function enrichEvent(event: RumEvent, context: RumEventDomainContext): void {
36
+ const stack =
37
+ (context && 'handlingStack' in context ? context.handlingStack : undefined) ??
38
+ (event.type === 'error' ? event.error?.stack : undefined);
39
+
40
+ const message = event.type === 'error' ? event.error?.message : undefined;
41
+
42
+ const url = event.type === 'resource' ? event.resource?.url : undefined;
43
+
44
+ for (const source of [stack, message, url]) {
45
+ if (parseService(event, source)) {
46
+ break;
47
+ }
48
+ }
49
+ }
50
+
51
+ function handleResource(event: RumResourceEvent, context: RumEventDomainContext): void {
52
+ if (!isSameDomainRequest(event.resource.url)) {
53
+ return;
54
+ }
55
+
56
+ let cfRay: string | undefined | null = undefined;
57
+
58
+ switch (event.resource.type) {
59
+ case 'fetch':
60
+ cfRay = (context as RumFetchResourceEventDomainContext).response?.headers.get('cf-ray');
61
+ break;
62
+
63
+ case 'xhr':
64
+ cfRay = (context as RumXhrResourceEventDomainContext).xhr.getResponseHeader('cf-ray');
65
+ break;
66
+ }
67
+
68
+ if (cfRay) {
69
+ event.context = { ...event.context, cfRay };
70
+ }
71
+ }
72
+
73
+ export function beforeSend(
74
+ handler?: RumInitConfiguration['beforeSend']
75
+ ): NonNullable<RumInitConfiguration['beforeSend']> {
76
+ return function (event: RumEvent, context: RumEventDomainContext) {
77
+ try {
78
+ if (event.type === 'resource') {
79
+ handleResource(event, context);
80
+ }
81
+
82
+ enrichEvent(event, context);
83
+
84
+ return handler?.(event, context) ?? true;
85
+ } catch {} // eslint-disable-line no-empty
86
+
87
+ return true;
88
+ };
89
+ }
@@ -0,0 +1,38 @@
1
+ import { datadogRum } from '@datadog/browser-rum';
2
+ import { FC, Fragment, PropsWithChildren, useEffect } from 'react';
3
+ import { HashRouting } from './hash-routing';
4
+
5
+ type User = Omit<import('@datadog/browser-core').User, 'id'> & { id: string };
6
+
7
+ export interface Options {
8
+ hashRouting?: boolean;
9
+ }
10
+
11
+ const SetUser: FC<{ user?: User }> = ({ user }) => {
12
+ useEffect(() => {
13
+ if (user) {
14
+ datadogRum.setUser(user);
15
+ }
16
+ }, [user]);
17
+
18
+ return null;
19
+ };
20
+
21
+ export const DatadogProvider: FC<
22
+ PropsWithChildren & {
23
+ isEnabled: boolean;
24
+ user?: User;
25
+ options?: Options;
26
+ }
27
+ > = ({ children, isEnabled, user, options }) => {
28
+ if (isEnabled) {
29
+ return (
30
+ <Fragment>
31
+ <SetUser user={user} />
32
+ {options?.hashRouting && <HashRouting />}
33
+ {children}
34
+ </Fragment>
35
+ );
36
+ }
37
+ return children;
38
+ };
@@ -0,0 +1,21 @@
1
+ import { datadogRum } from '@datadog/browser-rum';
2
+ import { FC, useEffect, useRef } from 'react';
3
+ import { useLocation } from 'react-router-dom';
4
+ import { sanitizeViewName } from './sanitize-view-name';
5
+
6
+ const useHashRouting = () => {
7
+ const pathname = sanitizeViewName(useLocation().pathname);
8
+ const lastPathname = useRef<string | undefined>(undefined);
9
+
10
+ useEffect(() => {
11
+ if (lastPathname.current !== pathname) {
12
+ datadogRum.startView(pathname);
13
+ lastPathname.current = pathname;
14
+ }
15
+ }, [pathname]);
16
+ };
17
+
18
+ export const HashRouting: FC = () => {
19
+ useHashRouting();
20
+ return null;
21
+ };
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './before-send';
2
+ export * from './datadog-provider';
@@ -0,0 +1,21 @@
1
+ export function sanitizeViewName(viewName: string) {
2
+ try {
3
+ const replaceIds = viewName
4
+ .toLowerCase()
5
+ .replace(/\/(\d+[^/]*)(?=\/|$)/g, '/{id}') // turn numbers to {id} placeholder
6
+ .replace(/\/(null|undefined)(?=\/|$)/g, '/{id}') // turn null and undefined to {id} placeholder
7
+ .replace(/\/([^/]*\.[a-z]+)(?=\/|$)/g, '/{id}') // turn file names to {id} placeholder
8
+ .replace(/\/([^/]*[=%+][^/]*)(?=\/|$)/g, '/{id}') // turn dates, phone numbers and query parameters to {id} placeholder
9
+ .replace(/(.+?)(\/+)$/, '$1') // remove '/' from the end of the line
10
+ .replace(/(\/)(\/+)/g, '/') // remove duplicate '/'
11
+ .replace('#', '');
12
+ if (replaceIds.startsWith('/proxy')) {
13
+ return replaceIds.replace(/^\/proxy/, '/').replace(/\/[^/]*$/, '');
14
+ }
15
+ return replaceIds;
16
+ } catch (e) {
17
+ // eslint-disable-next-line no-console
18
+ console.error(e);
19
+ return viewName;
20
+ }
21
+ }