@servicetitan/datadog-rum 40.0.0 → 40.2.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.
@@ -1,12 +1,20 @@
1
+ /* eslint-disable @typescript-eslint/naming-convention -- RUM event fields are snake_case */
1
2
  import type { RumEvent, RumEventDomainContext } from '@datadog/browser-rum';
2
3
  import { type Mutable, rumEvents, type RumEventType } from '../__mocks__';
4
+ import { type ElementService, elementServiceRecorder } from '../element-service-recorder';
3
5
  import { enrichEvent } from '../enrich-event';
4
6
 
7
+ jest.mock('../element-service-recorder');
8
+
5
9
  describe(`[datadog-rum] ${enrichEvent.name}`, () => {
6
10
  let event: Mutable<RumEventType>;
7
11
  let context: RumEventDomainContext;
12
+ let elementService: ElementService | undefined;
8
13
 
9
14
  beforeEach(() => {
15
+ jest.clearAllMocks();
16
+ elementService = undefined;
17
+ jest.mocked(elementServiceRecorder.serviceFor).mockImplementation(() => elementService);
10
18
  event = { type: 'action' };
11
19
  context = {};
12
20
  });
@@ -19,16 +27,113 @@ describe(`[datadog-rum] ${enrichEvent.name}`, () => {
19
27
  context = rumEvent.context ?? {};
20
28
  });
21
29
 
22
- test('assigns the expected service', () => {
30
+ test('attributes the expected service and version', () => {
31
+ subject();
32
+
33
+ expect({ service: event.service, version: event.version }).toEqual({
34
+ service: rumEvent.service,
35
+ version: rumEvent.version,
36
+ });
37
+ });
38
+ });
39
+
40
+ describe('with a long animation frame', () => {
41
+ const unpkgUrl = (name: string) =>
42
+ `https://unpkg.servicetitan.com/@servicetitan/${name}@1.0.0/dist/main.js`;
43
+ const hostUrl = 'https://go.servicetitan.com/scripts/build/desktop/main.js';
44
+
45
+ const loafEvent = (scripts: { duration: number; source_url: string }[]) =>
46
+ ({
47
+ type: 'long_task',
48
+ long_task: { entry_type: 'long-animation-frame', scripts },
49
+ }) as Mutable<RumEventType>;
50
+
51
+ beforeEach(() => {
52
+ event = loafEvent([
53
+ { duration: 10, source_url: unpkgUrl('task-hub') },
54
+ { duration: 30, source_url: hostUrl },
55
+ { duration: 20, source_url: unpkgUrl('other-mfe') },
56
+ { duration: 5, source_url: unpkgUrl('task-hub') },
57
+ ]);
58
+ });
59
+
60
+ test('lists every MFE that ran a script, in run order', () => {
61
+ subject();
62
+
63
+ expect(event.context?.loafServices).toEqual(['task-hub', 'other-mfe']);
64
+ });
65
+
66
+ describe('with only host scripts', () => {
67
+ beforeEach(() => (event = loafEvent([{ duration: 60, source_url: hostUrl }])));
68
+
69
+ test('adds no list', () => {
70
+ subject();
71
+
72
+ expect(event.context?.loafServices).toBeUndefined();
73
+ });
74
+ });
75
+ });
76
+
77
+ describe('with a click action', () => {
78
+ const pointerUpEvent = new MouseEvent('pointerup');
79
+ const taskHubService = { service: 'task-hub', version: '1.4.0' };
80
+ const hostService = { service: 'desktop', version: '1.0.0' };
81
+
82
+ beforeEach(() => {
83
+ event = { type: 'action', action: { type: 'click' }, ...hostService };
84
+ context = { events: [pointerUpEvent] };
85
+ elementService = taskHubService;
86
+ });
87
+
88
+ test('reads the service from the DOM event', () => {
23
89
  subject();
24
90
 
25
- expect(event.service).toEqual(rumEvent.service);
91
+ expect(elementServiceRecorder.serviceFor).toHaveBeenCalledWith(pointerUpEvent);
26
92
  });
27
93
 
28
- test('assigns the expected version', () => {
94
+ test('assigns the element service and version', () => {
29
95
  subject();
30
96
 
31
- expect(event.version).toEqual(rumEvent.version);
97
+ expect({ service: event.service, version: event.version }).toEqual(taskHubService);
98
+ });
99
+
100
+ describe('with an MFE handling stack', () => {
101
+ beforeEach(() => {
102
+ context = {
103
+ events: [pointerUpEvent],
104
+ handlingStack:
105
+ 'at f @ https://unpkg.servicetitan.com/@servicetitan/other-mfe@2.0.0/dist/main.js:1:1',
106
+ };
107
+ });
108
+
109
+ test('assigns the service and version from the handling stack', () => {
110
+ subject();
111
+
112
+ expect({ service: event.service, version: event.version }).toEqual({
113
+ service: 'other-mfe',
114
+ version: '2.0.0',
115
+ });
116
+ });
117
+ });
118
+
119
+ describe('without an MFE element on the path', () => {
120
+ beforeEach(() => (elementService = undefined));
121
+
122
+ test('keeps the application service', () => {
123
+ subject();
124
+
125
+ expect({ service: event.service, version: event.version }).toEqual(hostService);
126
+ });
127
+ });
128
+
129
+ describe('without DOM events', () => {
130
+ beforeEach(() => (context = {}));
131
+
132
+ test('keeps the application service', () => {
133
+ subject();
134
+
135
+ expect({ service: event.service, version: event.version }).toEqual(hostService);
136
+ });
32
137
  });
33
138
  });
34
139
  });
@@ -0,0 +1,130 @@
1
+ import { mfeHost } from '../__mocks__';
2
+ import { resolvePathService } from '../resolve-path-service';
3
+
4
+ describe(`[datadog-rum] ${resolvePathService.name}`, () => {
5
+ const outerName = 'servicetitan-dispatch-pro-console';
6
+ const innerName = 'servicetitan-task-hub';
7
+ const outerVersion = '1.2.3';
8
+ const innerVersion = '0.0.0-master.8e05d88';
9
+
10
+ const mfePortal = (name: string, owner?: HTMLElement) => {
11
+ const portal = document.body.appendChild(document.createElement('div'));
12
+ portal.setAttribute('data-mfe-portal-name', name);
13
+ const shadowRoot = portal.attachShadow({ mode: 'open' });
14
+ if (owner) {
15
+ Object.assign(owner, { portal: shadowRoot });
16
+ }
17
+ return portal;
18
+ };
19
+
20
+ let outerHost: HTMLElement;
21
+ let innerHost: HTMLElement;
22
+ let target: HTMLElement;
23
+ let path: EventTarget[];
24
+
25
+ beforeEach(() => {
26
+ outerHost = document.body.appendChild(mfeHost(outerName, outerVersion));
27
+ innerHost = outerHost.shadowRoot!.appendChild(mfeHost(innerName, innerVersion));
28
+ target = innerHost.shadowRoot!.appendChild(document.createElement('button'));
29
+ path = [target, innerHost.shadowRoot!, innerHost, outerHost.shadowRoot!, outerHost];
30
+ });
31
+
32
+ afterEach(() => {
33
+ document.body.innerHTML = '';
34
+ });
35
+
36
+ const subject = () => resolvePathService(path);
37
+
38
+ test('returns the innermost MFE on the path', () => {
39
+ expect(subject()).toEqual({ service: 'task-hub', version: innerVersion });
40
+ });
41
+
42
+ describe('with no MFE element on the path', () => {
43
+ beforeEach(() => (path = [document.body, window]));
44
+
45
+ test('returns undefined', () => {
46
+ expect(subject()).toBeUndefined();
47
+ });
48
+ });
49
+
50
+ describe('with a host that has no version', () => {
51
+ beforeEach(() => innerHost.removeAttribute('data-mfe-version'));
52
+
53
+ test('returns an unknown version', () => {
54
+ expect(subject()?.version).toBe('unknown');
55
+ });
56
+ });
57
+
58
+ describe('with a target in a portal', () => {
59
+ let portal: HTMLElement;
60
+
61
+ beforeEach(() => {
62
+ portal = mfePortal(innerName, innerHost);
63
+ path = [portal];
64
+ });
65
+
66
+ test('reads the version from the owning host', () => {
67
+ expect(subject()).toEqual({ service: 'task-hub', version: innerVersion });
68
+ });
69
+
70
+ describe('with a version on the portal', () => {
71
+ const portalVersion = '9.9.9';
72
+
73
+ beforeEach(() => portal.setAttribute('data-mfe-version', portalVersion));
74
+
75
+ test('reads the version from the portal', () => {
76
+ expect(subject()).toEqual({ service: 'task-hub', version: portalVersion });
77
+ });
78
+ });
79
+
80
+ describe('with two mounted builds of the same MFE', () => {
81
+ const secondVersion = '2.0.0';
82
+
83
+ beforeEach(() => {
84
+ const secondHost = document.body.appendChild(mfeHost(innerName, secondVersion));
85
+ portal = mfePortal(innerName, secondHost);
86
+ path = [portal];
87
+ });
88
+
89
+ test('reads the version from the build that owns the portal', () => {
90
+ expect(subject()).toEqual({ service: 'task-hub', version: secondVersion });
91
+ });
92
+ });
93
+
94
+ describe('with a host that does not keep its portal', () => {
95
+ beforeEach(() => {
96
+ portal = mfePortal(outerName);
97
+ path = [portal];
98
+ });
99
+
100
+ test('reads the version from a host with the same name', () => {
101
+ expect(subject()).toEqual({
102
+ service: 'dispatch-pro-console',
103
+ version: outerVersion,
104
+ });
105
+ });
106
+ });
107
+
108
+ describe('without a matching host', () => {
109
+ beforeEach(() => {
110
+ portal = mfePortal('servicetitan-missing');
111
+ path = [portal];
112
+ });
113
+
114
+ test('returns an unknown version', () => {
115
+ expect(subject()).toEqual({ service: 'missing', version: 'unknown' });
116
+ });
117
+ });
118
+
119
+ describe('when the portal was resolved before', () => {
120
+ beforeEach(() => {
121
+ subject();
122
+ innerHost.setAttribute('data-mfe-version', '3.0.0');
123
+ });
124
+
125
+ test('keeps the version it first resolved', () => {
126
+ expect(subject()).toEqual({ service: 'task-hub', version: innerVersion });
127
+ });
128
+ });
129
+ });
130
+ });
@@ -2,6 +2,7 @@ import { datadogRum } from '@datadog/browser-rum';
2
2
  import { buildAllowedTracingUrls } from './build-allowed-tracing-urls';
3
3
  import { buildBeforeSend } from './build-before-send';
4
4
  import { installDdRumGuard } from './dd-rum-guard';
5
+ import { elementServiceRecorder } from './element-service-recorder';
5
6
  import { DATADOG_RUM_FOR_DEV, installDevConsole, isForceEnabled } from './runtime-override';
6
7
  import type { SharedImpl } from './shared-impl';
7
8
  import type { ApplicationConfig, PendingApplication, ServiceConfig, State } from './types';
@@ -58,6 +59,7 @@ export function createImpl(): SharedImpl {
58
59
  datadogRum.setGlobalContextProperty(DATADOG_RUM_FOR_DEV, true);
59
60
  }
60
61
  installDdRumGuard(datadogRum);
62
+ elementServiceRecorder.install();
61
63
  if (initializedBy) {
62
64
  datadogRum.setGlobalContextProperty('initializedBy', { service: initializedBy });
63
65
  }
@@ -0,0 +1,45 @@
1
+ import { type ElementService, resolvePathService } from './resolve-path-service';
2
+
3
+ export type { ElementService } from './resolve-path-service';
4
+
5
+ /** The SDK passes each click's `pointerup` as `context.events` (`@datadog/browser-rum` 6.19.0 to 7.15.0); re-check on an SDK upgrade. */
6
+ const RECORDED_EVENT = 'pointerup';
7
+
8
+ function ancestors(target: EventTarget | null): Element[] {
9
+ const path: Element[] = [];
10
+ for (let node = target instanceof Element ? target : null; node; node = node.parentElement) {
11
+ path.push(node);
12
+ }
13
+ return path;
14
+ }
15
+
16
+ /**
17
+ * Resolves the MFE of each click at dispatch time. The browser empties `composedPath()`
18
+ * once dispatch ends, and the MFE can unmount before the RUM SDK runs `beforeSend`.
19
+ */
20
+ export function createElementServiceRecorder() {
21
+ const recorded = new WeakMap<Event, ElementService | null>();
22
+ let installed = false;
23
+ const record = (event: Event) =>
24
+ recorded.set(event, resolvePathService(event.composedPath()) ?? null);
25
+
26
+ return {
27
+ install(): void {
28
+ if (installed) {
29
+ return;
30
+ }
31
+ installed = true;
32
+ window.addEventListener(RECORDED_EVENT, record, { capture: true, passive: true });
33
+ },
34
+
35
+ /** Falls back to the retargeted target when the event was not recorded. */
36
+ serviceFor(event: Event): ElementService | undefined {
37
+ const hit = recorded.get(event);
38
+ return hit !== undefined
39
+ ? (hit ?? undefined)
40
+ : resolvePathService(ancestors(event.target));
41
+ },
42
+ };
43
+ }
44
+
45
+ export const elementServiceRecorder = createElementServiceRecorder();
@@ -1,38 +1,86 @@
1
- import type { RumEvent, RumEventDomainContext } from '@datadog/browser-rum';
1
+ import type { RumEvent, RumEventDomainContext, RumLongTaskEvent } from '@datadog/browser-rum';
2
+ import { elementServiceRecorder } from './element-service-recorder';
2
3
 
3
4
  const SERVICE_REGEX =
4
- /unpkg\.servicetitan\.com\/@servicetitan\/(?<service>[\w-]+)(?:@(?<version>\d+\.\d+\.\d+(?:-[\w.]+)?))?/;
5
+ /unpkg\.servicetitan\.com\/@servicetitan\/(?<service>[\w-]+)(?:@(?<version>\d+\.\d+\.\d+(?:-[\w.-]+)?))?/;
6
+
7
+ function matchService(input: string | undefined): { service: string; version: string } | undefined {
8
+ const groups = input ? SERVICE_REGEX.exec(input)?.groups : undefined;
9
+ return groups?.service
10
+ ? { service: groups.service, version: groups.version ?? 'unknown' }
11
+ : undefined;
12
+ }
5
13
 
6
14
  function parseService(event: RumEvent, input: string | undefined) {
7
- const match = input?.match(SERVICE_REGEX);
15
+ const match = matchService(input);
16
+ if (match) {
17
+ event.service = match.service;
18
+ event.version = match.version;
19
+ }
20
+ return !!match;
21
+ }
8
22
 
9
- const service = match?.groups?.service;
10
- const version = match?.groups?.version;
23
+ function attributionSources(
24
+ event: RumEvent,
25
+ context: RumEventDomainContext
26
+ ): (string | undefined)[] {
27
+ const handlingStack = context && 'handlingStack' in context ? context.handlingStack : undefined;
11
28
 
12
- if (service) {
13
- event.service = service;
14
- event.version = version ?? 'unknown';
15
- return true;
29
+ switch (event.type) {
30
+ case 'error':
31
+ return event.error.stack
32
+ ? [event.error.stack, event.error.message]
33
+ : [handlingStack, event.error.message];
34
+ case 'resource':
35
+ return [handlingStack, event.resource.url];
36
+ default:
37
+ return [handlingStack];
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Writes every MFE that ran a script to `context.loafServices`, and returns the source URL of the
43
+ * longest script, which names the frame's service. Legacy long tasks have no `scripts`.
44
+ */
45
+ function tagLoafServices(event: RumLongTaskEvent): string | undefined {
46
+ const services = new Set<string>();
47
+ let longest: NonNullable<RumLongTaskEvent['long_task']['scripts']>[number] | undefined;
48
+ for (const script of event.long_task.scripts ?? []) {
49
+ const match = matchService(script.source_url);
50
+ if (match) {
51
+ services.add(match.service);
52
+ }
53
+ if (!longest || (script.duration ?? 0) > (longest.duration ?? 0)) {
54
+ longest = script;
55
+ }
56
+ }
57
+ if (services.size) {
58
+ event.context = { ...event.context, loafServices: [...services] };
16
59
  }
60
+ return longest?.source_url;
61
+ }
17
62
 
18
- return false;
63
+ function applyElementService(event: RumEvent, context: RumEventDomainContext): void {
64
+ const domEvent = context && 'events' in context ? context.events?.[0] : undefined;
65
+ const result = domEvent && elementServiceRecorder.serviceFor(domEvent);
66
+ if (result) {
67
+ event.service = result.service;
68
+ event.version = result.version;
69
+ }
19
70
  }
20
71
 
21
72
  /**
22
73
  * See https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/?tab=npm#micro-frontend
23
74
  */
24
75
  export function enrichEvent(event: RumEvent, context: RumEventDomainContext): void {
25
- const stack =
26
- (context && 'handlingStack' in context ? context.handlingStack : undefined) ??
27
- (event.type === 'error' ? event.error?.stack : undefined);
28
-
29
- const message = event.type === 'error' ? event.error?.message : undefined;
30
-
31
- const url = event.type === 'resource' ? event.resource?.url : undefined;
32
-
33
- for (const source of [stack, message, url]) {
76
+ const sources =
77
+ event.type === 'long_task' ? [tagLoafServices(event)] : attributionSources(event, context);
78
+ for (const source of sources) {
34
79
  if (parseService(event, source)) {
35
- break;
80
+ return;
36
81
  }
37
82
  }
83
+ if (event.type === 'action') {
84
+ applyElementService(event, context);
85
+ }
38
86
  }
@@ -0,0 +1,83 @@
1
+ const NAME_ATTRIBUTE = 'data-mfe-name';
2
+ const PORTAL_NAME_ATTRIBUTE = 'data-mfe-portal-name';
3
+ const VERSION_ATTRIBUTE = 'data-mfe-version';
4
+ const ELEMENT_NAME_PREFIX = /^servicetitan-/;
5
+ const UNKNOWN_VERSION = 'unknown';
6
+
7
+ export interface ElementService {
8
+ service: string;
9
+ version: string;
10
+ }
11
+
12
+ /** The `portal` field that `@servicetitan/web-components` keeps on each MFE element. */
13
+ interface MfeHostElement extends Element {
14
+ portal?: ShadowRoot;
15
+ }
16
+
17
+ const portalServices = new WeakMap<Element, ElementService>();
18
+
19
+ function toService(name: string, version: string | null | undefined): ElementService {
20
+ return { service: name.replace(ELEMENT_NAME_PREFIX, ''), version: version ?? UNKNOWN_VERSION };
21
+ }
22
+
23
+ /**
24
+ * Finds the host that owns `portal`. Builds of one MFE share a name, so the `portal` field
25
+ * identifies the owner; the name is a fallback for builds that do not keep that field.
26
+ */
27
+ function findHost(portal: Element, name: string): Element | undefined {
28
+ let byName: Element | undefined;
29
+ const roots: (Document | ShadowRoot)[] = [document];
30
+ for (const root of roots) {
31
+ for (const element of root.querySelectorAll('*')) {
32
+ if (portal.shadowRoot && (element as MfeHostElement).portal === portal.shadowRoot) {
33
+ return element;
34
+ }
35
+ if (!byName && element.getAttribute(NAME_ATTRIBUTE) === name) {
36
+ byName = element;
37
+ }
38
+ if (element.shadowRoot) {
39
+ roots.push(element.shadowRoot);
40
+ }
41
+ }
42
+ }
43
+ return byName;
44
+ }
45
+
46
+ /** Caches a portal's service. */
47
+ function toPortalService(portal: Element, name: string): ElementService {
48
+ const cached = portalServices.get(portal);
49
+ if (cached) {
50
+ return cached;
51
+ }
52
+ const ownVersion = portal.getAttribute(VERSION_ATTRIBUTE);
53
+ const host = ownVersion ? undefined : findHost(portal, name);
54
+ const result = toService(name, ownVersion ?? host?.getAttribute(VERSION_ATTRIBUTE));
55
+ portalServices.set(portal, result);
56
+ return result;
57
+ }
58
+
59
+ function toElementService(element: Element): ElementService | undefined {
60
+ const hostName = element.getAttribute(NAME_ATTRIBUTE);
61
+ if (hostName) {
62
+ return toService(hostName, element.getAttribute(VERSION_ATTRIBUTE));
63
+ }
64
+ const portalName = element.getAttribute(PORTAL_NAME_ATTRIBUTE);
65
+ return portalName ? toPortalService(element, portalName) : undefined;
66
+ }
67
+
68
+ /**
69
+ * Returns the service of the innermost MFE element on `path`.
70
+ * `data-mfe-name` holds the element name (`servicetitan-task-hub`); the service is the
71
+ * unscoped package name (`task-hub`), the same value parsed from unpkg URLs.
72
+ */
73
+ export function resolvePathService(path: EventTarget[]): ElementService | undefined {
74
+ for (const target of path) {
75
+ if (target instanceof Element) {
76
+ const result = toElementService(target);
77
+ if (result) {
78
+ return result;
79
+ }
80
+ }
81
+ }
82
+ return undefined;
83
+ }