@servicetitan/datadog-rum 36.3.1 → 36.4.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.
Files changed (94) hide show
  1. package/dist/before-send.d.ts +11 -1
  2. package/dist/before-send.d.ts.map +1 -1
  3. package/dist/before-send.js +2 -56
  4. package/dist/before-send.js.map +1 -1
  5. package/dist/build-allowed-tracing-urls.d.ts +9 -0
  6. package/dist/build-allowed-tracing-urls.d.ts.map +1 -0
  7. package/dist/build-allowed-tracing-urls.js +54 -0
  8. package/dist/build-allowed-tracing-urls.js.map +1 -0
  9. package/dist/build-before-send.d.ts +4 -0
  10. package/dist/build-before-send.d.ts.map +1 -0
  11. package/dist/build-before-send.js +64 -0
  12. package/dist/build-before-send.js.map +1 -0
  13. package/dist/bundle-state.d.ts +10 -0
  14. package/dist/bundle-state.d.ts.map +1 -0
  15. package/dist/bundle-state.js +10 -0
  16. package/dist/bundle-state.js.map +1 -0
  17. package/dist/create-impl.d.ts +8 -0
  18. package/dist/create-impl.d.ts.map +1 -0
  19. package/dist/create-impl.js +65 -0
  20. package/dist/create-impl.js.map +1 -0
  21. package/dist/datadog-provider.d.ts +2 -5
  22. package/dist/datadog-provider.d.ts.map +1 -1
  23. package/dist/datadog-provider.js +2 -2
  24. package/dist/datadog-provider.js.map +1 -1
  25. package/dist/enrich-event.d.ts +6 -0
  26. package/dist/enrich-event.d.ts.map +1 -0
  27. package/dist/enrich-event.js +33 -0
  28. package/dist/enrich-event.js.map +1 -0
  29. package/dist/get-shared.d.ts +10 -0
  30. package/dist/get-shared.d.ts.map +1 -0
  31. package/dist/get-shared.js +16 -0
  32. package/dist/get-shared.js.map +1 -0
  33. package/dist/handle-resource.d.ts +3 -0
  34. package/dist/handle-resource.d.ts.map +1 -0
  35. package/dist/handle-resource.js +27 -0
  36. package/dist/handle-resource.js.map +1 -0
  37. package/dist/index.d.ts +3 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +3 -0
  40. package/dist/index.js.map +1 -1
  41. package/dist/init.d.ts +17 -0
  42. package/dist/init.d.ts.map +1 -0
  43. package/dist/init.js +28 -0
  44. package/dist/init.js.map +1 -0
  45. package/dist/set-user.d.ts +13 -0
  46. package/dist/set-user.d.ts.map +1 -0
  47. package/dist/set-user.js +22 -0
  48. package/dist/set-user.js.map +1 -0
  49. package/dist/shared-impl.d.ts +11 -0
  50. package/dist/shared-impl.d.ts.map +1 -0
  51. package/dist/shared-impl.js +3 -0
  52. package/dist/shared-impl.js.map +1 -0
  53. package/dist/types.d.ts +50 -0
  54. package/dist/types.d.ts.map +1 -0
  55. package/dist/types.js +3 -0
  56. package/dist/types.js.map +1 -0
  57. package/dist/use-rum-service.d.ts +12 -0
  58. package/dist/use-rum-service.d.ts.map +1 -0
  59. package/dist/use-rum-service.js +25 -0
  60. package/dist/use-rum-service.js.map +1 -0
  61. package/package.json +3 -3
  62. package/src/__mocks__/index.ts +6 -0
  63. package/src/__mocks__/init-config.ts +6 -0
  64. package/src/__mocks__/process-event.ts +20 -0
  65. package/src/__mocks__/reset-shared-impl.ts +8 -0
  66. package/src/__mocks__/tracing-urls.ts +30 -0
  67. package/src/__mocks__/types.ts +1 -0
  68. package/src/__tests__/before-send.test.ts +39 -87
  69. package/src/__tests__/build-allowed-tracing-urls.test.ts +120 -0
  70. package/src/__tests__/build-before-send.test.ts +193 -0
  71. package/src/__tests__/create-impl.test.ts +211 -0
  72. package/src/__tests__/datadog-provider.test.tsx +55 -25
  73. package/src/__tests__/enrich-event.test.ts +34 -0
  74. package/src/__tests__/get-shared.test.ts +56 -0
  75. package/src/__tests__/handle-resource.test.ts +76 -0
  76. package/src/__tests__/init.test.ts +69 -0
  77. package/src/__tests__/integration.test.ts +147 -0
  78. package/src/__tests__/set-user.test.ts +61 -0
  79. package/src/__tests__/use-rum-service.test.tsx +82 -0
  80. package/src/before-send.ts +13 -60
  81. package/src/build-allowed-tracing-urls.ts +53 -0
  82. package/src/build-before-send.ts +81 -0
  83. package/src/bundle-state.ts +9 -0
  84. package/src/create-impl.ts +71 -0
  85. package/src/datadog-provider.tsx +4 -6
  86. package/src/enrich-event.ts +38 -0
  87. package/src/get-shared.ts +24 -0
  88. package/src/handle-resource.ts +30 -0
  89. package/src/index.ts +3 -0
  90. package/src/init.ts +39 -0
  91. package/src/set-user.ts +25 -0
  92. package/src/shared-impl.ts +9 -0
  93. package/src/types.ts +61 -0
  94. package/src/use-rum-service.ts +28 -0
@@ -0,0 +1,71 @@
1
+ import { datadogRum } from '@datadog/browser-rum';
2
+ import { buildAllowedTracingUrls } from './build-allowed-tracing-urls';
3
+ import { buildBeforeSend } from './build-before-send';
4
+ import type { SharedImpl } from './shared-impl';
5
+ import type { State } from './types';
6
+
7
+ const DEFAULTS = {
8
+ sessionSampleRate: 100,
9
+ sessionReplaySampleRate: 0,
10
+ defaultPrivacyLevel: 'mask-user-input',
11
+ } as const;
12
+
13
+ /**
14
+ * Interop surface: stored on globalThis, shared across independently
15
+ * deployed bundles. First bundle to load wins. Append-only — never
16
+ * remove or change method signatures.
17
+ */
18
+ export function createImpl(): SharedImpl {
19
+ let initialized = false;
20
+ const state: State = {
21
+ services: new Map(),
22
+ };
23
+
24
+ return {
25
+ init({ service, application }) {
26
+ let initializedSdk = false;
27
+
28
+ if (application) {
29
+ if (!initialized && !datadogRum.getInitConfiguration()) {
30
+ const { beforeSend: appBeforeSend, ...sdkConfigPart } = application;
31
+ if (appBeforeSend) {
32
+ state.applicationBeforeSend = appBeforeSend;
33
+ }
34
+ datadogRum.init({
35
+ ...DEFAULTS,
36
+ ...sdkConfigPart,
37
+ service: service.name,
38
+ beforeSend: buildBeforeSend(state),
39
+ allowedTracingUrls: buildAllowedTracingUrls(state),
40
+ });
41
+ initialized = true;
42
+ initializedSdk = true;
43
+ } else if (initialized) {
44
+ // eslint-disable-next-line no-console
45
+ console.info(
46
+ '[datadog-rum] init: application config ignored; SDK already initialized.'
47
+ );
48
+ } else {
49
+ // eslint-disable-next-line no-console
50
+ console.warn(
51
+ '[datadog-rum] init: SDK was initialized outside the facade; service handlers will not fire.'
52
+ );
53
+ }
54
+ }
55
+
56
+ const { name, ...reg } = service;
57
+ const existing = state.services.get(name);
58
+ state.services.set(name, { ...reg, context: existing?.context });
59
+
60
+ return {
61
+ cleanup: () => state.services.delete(name),
62
+ initializedSdk,
63
+ };
64
+ },
65
+
66
+ setServiceContext(key, context) {
67
+ const existing = state.services.get(key);
68
+ state.services.set(key, { ...existing, context });
69
+ },
70
+ };
71
+ }
@@ -1,17 +1,15 @@
1
- import { datadogRum } from '@datadog/browser-rum';
2
1
  import { FC, Fragment, PropsWithChildren, useEffect } from 'react';
3
2
  import { HashRouting } from './hash-routing';
4
-
5
- type User = Omit<import('@datadog/browser-core').User, 'id'> & { id: string };
3
+ import { setUser, type RumUser } from './set-user';
6
4
 
7
5
  export interface Options {
8
6
  hashRouting?: boolean;
9
7
  }
10
8
 
11
- const SetUser: FC<{ user?: User }> = ({ user }) => {
9
+ const SetUser: FC<{ user?: RumUser }> = ({ user }) => {
12
10
  useEffect(() => {
13
11
  if (user) {
14
- datadogRum.setUser(user);
12
+ setUser(user);
15
13
  }
16
14
  }, [user]);
17
15
 
@@ -21,7 +19,7 @@ const SetUser: FC<{ user?: User }> = ({ user }) => {
21
19
  export const DatadogProvider: FC<
22
20
  PropsWithChildren & {
23
21
  isEnabled: boolean;
24
- user?: User;
22
+ user?: RumUser;
25
23
  options?: Options;
26
24
  }
27
25
  > = ({ children, isEnabled, user, options }) => {
@@ -0,0 +1,38 @@
1
+ import type { RumEvent, RumEventDomainContext } from '@datadog/browser-rum';
2
+
3
+ const SERVICE_REGEX =
4
+ /unpkg\.servicetitan\.com\/@servicetitan\/(?<service>[\w-]+)(?:@(?<version>\d+\.\d+\.\d+(?:-[\w.]+)?))?/;
5
+
6
+ function parseService(event: RumEvent, input: string | undefined) {
7
+ const match = input?.match(SERVICE_REGEX);
8
+
9
+ const service = match?.groups?.service;
10
+ const version = match?.groups?.version;
11
+
12
+ if (service) {
13
+ event.service = service;
14
+ event.version = version ?? 'unknown';
15
+ return true;
16
+ }
17
+
18
+ return false;
19
+ }
20
+
21
+ /**
22
+ * See https://docs.datadoghq.com/real_user_monitoring/browser/advanced_configuration/?tab=npm#micro-frontend
23
+ */
24
+ 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]) {
34
+ if (parseService(event, source)) {
35
+ break;
36
+ }
37
+ }
38
+ }
@@ -0,0 +1,24 @@
1
+ import { createImpl } from './create-impl';
2
+ import type { SharedImpl } from './shared-impl';
3
+
4
+ export const STATE_KEY = Symbol.for('@servicetitan/datadog-rum');
5
+
6
+ export interface GlobalSlot {
7
+ [STATE_KEY]?: SharedImpl;
8
+ }
9
+
10
+ function slot(): GlobalSlot {
11
+ return globalThis as unknown as GlobalSlot;
12
+ }
13
+
14
+ /** Returns the shared impl, creating it if it doesn't exist yet. Only called by `init`. */
15
+ export function getOrCreateSharedImpl(): SharedImpl {
16
+ const s = slot();
17
+ s[STATE_KEY] ??= createImpl();
18
+ return s[STATE_KEY];
19
+ }
20
+
21
+ /** Returns the shared impl if it already exists, or `undefined`. */
22
+ export function getSharedImpl(): SharedImpl | undefined {
23
+ return slot()[STATE_KEY];
24
+ }
@@ -0,0 +1,30 @@
1
+ import type { RumResourceEvent, RumResourceEventDomainContext } from '@datadog/browser-rum';
2
+
3
+ function isSameDomainRequest(url: string) {
4
+ return new URL(url).hostname === window.location.hostname;
5
+ }
6
+
7
+ export function handleResource(
8
+ event: RumResourceEvent,
9
+ context: RumResourceEventDomainContext
10
+ ): void {
11
+ if (!isSameDomainRequest(event.resource.url)) {
12
+ return;
13
+ }
14
+
15
+ let cfRay: string | undefined | null = undefined;
16
+
17
+ switch (event.resource.type) {
18
+ case 'fetch':
19
+ cfRay = context.response?.headers.get('cf-ray');
20
+ break;
21
+
22
+ case 'xhr':
23
+ cfRay = context.xhr?.getResponseHeader('cf-ray');
24
+ break;
25
+ }
26
+
27
+ if (cfRay) {
28
+ event.context = { ...event.context, cfRay };
29
+ }
30
+ }
package/src/index.ts CHANGED
@@ -1,2 +1,5 @@
1
1
  export * from './before-send';
2
2
  export * from './datadog-provider';
3
+ export * from './init';
4
+ export * from './set-user';
5
+ export * from './use-rum-service';
package/src/init.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { bundleState } from './bundle-state';
2
+ import { getOrCreateSharedImpl } from './get-shared';
3
+ import type { InitRumOptions, RumServiceRegistration } from './types';
4
+
5
+ export type {
6
+ ApplicationConfig,
7
+ Cleanup,
8
+ InitRumOptions,
9
+ RumService,
10
+ RumServiceRegistration,
11
+ ServiceConfig,
12
+ ServiceTracingUrls,
13
+ } from './types';
14
+
15
+ /**
16
+ * Registers a service and, optionally, initializes the Datadog RUM SDK.
17
+ *
18
+ * Any caller may pass `application`. The first call that includes it
19
+ * initializes the SDK; subsequent callers' `application` config is ignored
20
+ * with a warning. Callers that omit `application` register their service
21
+ * without attempting SDK init.
22
+ *
23
+ * Returns a `RumServiceRegistration` — `{ cleanup, setServiceContext }`.
24
+ * `cleanup` removes this service's `beforeSend`, `allowedTracingUrls`, and
25
+ * persistent context. `setServiceContext` attaches session-lifetime metadata
26
+ * to every event whose `event.service` matches this service's name.
27
+ */
28
+ export function init(opts: InitRumOptions): RumServiceRegistration {
29
+ const impl = getOrCreateSharedImpl();
30
+ const result = impl.init(opts);
31
+ if (result.initializedSdk) {
32
+ bundleState.isSdkInitializer = true;
33
+ }
34
+ const { name } = opts.service;
35
+ return {
36
+ cleanup: result.cleanup,
37
+ setServiceContext: context => impl.setServiceContext(name, context),
38
+ };
39
+ }
@@ -0,0 +1,25 @@
1
+ import { datadogRum } from '@datadog/browser-rum';
2
+ import { bundleState } from './bundle-state';
3
+ import { getSharedImpl } from './get-shared';
4
+ import type { RumUser } from './shared-impl';
5
+
6
+ export type { RumUser } from './shared-impl';
7
+
8
+ /**
9
+ * Sets the session user on the Datadog RUM SDK.
10
+ *
11
+ * - **SDK initialized via `init`**: only the bundle whose `init` call
12
+ * initialized the SDK may set the user; calls from any other bundle are
13
+ * silent no-ops.
14
+ * - **SDK initialized directly via `datadogRum.init`**: no gating is applied.
15
+ * - **Neither initialized**: no-op.
16
+ */
17
+ export function setUser(user: RumUser): void {
18
+ if (bundleState.isSdkInitializer) {
19
+ datadogRum.setUser(user);
20
+ return;
21
+ }
22
+ if (!getSharedImpl() && datadogRum.getInitConfiguration()) {
23
+ datadogRum.setUser(user);
24
+ }
25
+ }
@@ -0,0 +1,9 @@
1
+ import type { Context, User } from '@datadog/browser-core';
2
+ import type { Cleanup, InitRumOptions } from './types';
3
+
4
+ export type RumUser = Omit<User, 'id'> & Required<Pick<User, 'id'>>;
5
+
6
+ export interface SharedImpl {
7
+ init(opts: InitRumOptions): { cleanup: Cleanup; initializedSdk: boolean };
8
+ setServiceContext(key: string, context: Context): void;
9
+ }
package/src/types.ts ADDED
@@ -0,0 +1,61 @@
1
+ import type { Context } from '@datadog/browser-core';
2
+ import type { MatchOption, PropagatorType, RumInitConfiguration } from '@datadog/browser-rum';
3
+ import type { ApplicationBeforeSendHandler, ServiceBeforeSendHandler } from './before-send';
4
+
5
+ /**
6
+ * URL matchers grouped by the propagator type whose headers they should
7
+ * activate. A service registers its tracing URLs as e.g.
8
+ * `{ tracecontext: [/api\//, 'https://...'] }`.
9
+ */
10
+ export type ServiceTracingUrls = Partial<Record<PropagatorType, MatchOption[]>>;
11
+
12
+ /** Tears down a service registration: handlers, tracing URLs, and persistent context. */
13
+ export type Cleanup = () => void;
14
+
15
+ /**
16
+ * Service handle returned by `useRumService`. `setServiceContext` is bound to the
17
+ * service registered by the hook, so callers don't pass the service name again.
18
+ */
19
+ export interface RumService {
20
+ setServiceContext: (context: Context) => void;
21
+ }
22
+
23
+ /** Imperative service registration returned by `init`. Adds the cleanup contract. */
24
+ export interface RumServiceRegistration extends RumService {
25
+ cleanup: Cleanup;
26
+ }
27
+
28
+ export type ApplicationConfig = Omit<
29
+ RumInitConfiguration,
30
+ 'beforeSend' | 'allowedTracingUrls' | 'service'
31
+ > & {
32
+ beforeSend?: ApplicationBeforeSendHandler;
33
+ };
34
+
35
+ interface ServiceShape {
36
+ beforeSend?: ServiceBeforeSendHandler;
37
+ allowedTracingUrls?: ServiceTracingUrls;
38
+ }
39
+
40
+ export interface ServiceConfig extends ServiceShape {
41
+ name: string;
42
+ }
43
+
44
+ export interface InitRumOptions {
45
+ service: ServiceConfig;
46
+ application?: ApplicationConfig;
47
+ }
48
+
49
+ /**
50
+ * Per-service entry — `beforeSend` and `allowedTracingUrls` come from
51
+ * `init`; `context` comes from `setServiceContext`. One service = one entry.
52
+ */
53
+ export interface ServiceEntry extends ServiceShape {
54
+ context?: Context;
55
+ }
56
+
57
+ /** Registration state: application-level handler + per-service entries keyed by service name. */
58
+ export interface State {
59
+ applicationBeforeSend?: ApplicationBeforeSendHandler;
60
+ services: Map<string, ServiceEntry>;
61
+ }
@@ -0,0 +1,28 @@
1
+ import { useEffect, useMemo } from 'react';
2
+ import { getOrCreateSharedImpl } from './get-shared';
3
+ import { init, type RumService, type ServiceConfig } from './init';
4
+
5
+ /**
6
+ * Registers a service on mount and disposes it on unmount. On unmount the
7
+ * service's `beforeSend`, `allowedTracingUrls`, and any context previously set
8
+ * via `setServiceContext` are removed atomically. The config is captured on
9
+ * first render — changing it across renders does not re-register.
10
+ *
11
+ * Returns a `RumService` — `{ setServiceContext }`, bound to this service.
12
+ * The handle is identity-stable across renders.
13
+ */
14
+ export function useRumService(config: ServiceConfig): RumService {
15
+ useEffect(() => {
16
+ return init({ service: config }).cleanup;
17
+ // eslint-disable-next-line react-hooks/exhaustive-deps
18
+ }, []);
19
+
20
+ return useMemo(
21
+ () => ({
22
+ setServiceContext: context =>
23
+ getOrCreateSharedImpl().setServiceContext(config.name, context),
24
+ }),
25
+ // eslint-disable-next-line react-hooks/exhaustive-deps
26
+ []
27
+ );
28
+ }