@servicetitan/datadog-rum 39.2.0 → 40.0.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 +1 @@
1
- {"version":3,"file":"create-impl.d.ts","sourceRoot":"","sources":["../src/create-impl.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAShD;;;;GAIG;AACH,wBAAgB,UAAU,IAAI,UAAU,CA2EvC"}
1
+ {"version":3,"file":"create-impl.d.ts","sourceRoot":"","sources":["../src/create-impl.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAShD;;;;GAIG;AACH,wBAAgB,UAAU,IAAI,UAAU,CAgHvC"}
@@ -1,6 +1,7 @@
1
1
  import { datadogRum } from '@datadog/browser-rum';
2
2
  import { buildAllowedTracingUrls } from './build-allowed-tracing-urls';
3
3
  import { buildBeforeSend } from './build-before-send';
4
+ import { installDdRumGuard } from './dd-rum-guard';
4
5
  import { DATADOG_RUM_FOR_DEV, installDevConsole, isForceEnabled } from './runtime-override';
5
6
  const DEFAULTS = {
6
7
  sessionSampleRate: 100,
@@ -13,15 +14,11 @@ const DEFAULTS = {
13
14
  * remove or change method signatures.
14
15
  */ export function createImpl() {
15
16
  let initialized = false;
17
+ let offer;
16
18
  const state = {
17
19
  services: new Map()
18
20
  };
19
- function initializeSdk(service, application, enabled) {
20
- if (initialized) {
21
- // eslint-disable-next-line no-console
22
- console.info('[datadog-rum] init: application config ignored; SDK already initialized.');
23
- return false;
24
- }
21
+ function initializeSdk({ service, application, enabled, initializedBy }) {
25
22
  if (datadogRum.getInitConfiguration()) {
26
23
  // eslint-disable-next-line no-console
27
24
  console.warn('[datadog-rum] init: SDK was initialized outside the facade; service handlers will not fire.');
@@ -41,6 +38,12 @@ const DEFAULTS = {
41
38
  if (!enabled) {
42
39
  datadogRum.setGlobalContextProperty(DATADOG_RUM_FOR_DEV, true);
43
40
  }
41
+ installDdRumGuard(datadogRum);
42
+ if (initializedBy) {
43
+ datadogRum.setGlobalContextProperty('initializedBy', {
44
+ service: initializedBy
45
+ });
46
+ }
44
47
  initialized = true;
45
48
  return true;
46
49
  }
@@ -51,17 +54,41 @@ const DEFAULTS = {
51
54
  context: existing === null || existing === void 0 ? void 0 : existing.context
52
55
  });
53
56
  }
54
- return {
55
- init ({ service, application, enabled = true }) {
56
- let initializedSdk = false;
57
+ function startSdk(service, application, enabled) {
58
+ if (application && !enabled) {
59
+ installDevConsole();
60
+ }
61
+ if (initialized) {
57
62
  if (application) {
58
- if (!enabled) {
59
- installDevConsole();
60
- }
61
- if (enabled || isForceEnabled()) {
62
- initializedSdk = initializeSdk(service, application, enabled);
63
- }
63
+ // eslint-disable-next-line no-console
64
+ console.info(`[datadog-rum] init: application config from '${service.name}' ignored; the SDK is already started.`);
64
65
  }
66
+ return false;
67
+ }
68
+ if (application) {
69
+ offer !== null && offer !== void 0 ? offer : offer = {
70
+ service,
71
+ application
72
+ };
73
+ }
74
+ if (!offer || !enabled && !isForceEnabled()) {
75
+ return false;
76
+ }
77
+ const startedByOfferer = offer.service.name === service.name;
78
+ if (application && !startedByOfferer) {
79
+ // eslint-disable-next-line no-console
80
+ console.info(`[datadog-rum] init: application config from '${service.name}' ignored; started the application offered by '${offer.service.name}'.`);
81
+ }
82
+ return initializeSdk({
83
+ service: offer.service,
84
+ application: offer.application,
85
+ enabled,
86
+ initializedBy: startedByOfferer ? undefined : service.name
87
+ });
88
+ }
89
+ return {
90
+ init ({ service, application, enabled = true }) {
91
+ const initializedSdk = startSdk(service, application, enabled);
65
92
  registerService(service);
66
93
  return {
67
94
  cleanup: ()=>state.services.delete(service.name),
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/create-impl.ts"],"sourcesContent":["import { datadogRum } from '@datadog/browser-rum';\nimport { buildAllowedTracingUrls } from './build-allowed-tracing-urls';\nimport { buildBeforeSend } from './build-before-send';\nimport { DATADOG_RUM_FOR_DEV, installDevConsole, isForceEnabled } from './runtime-override';\nimport type { SharedImpl } from './shared-impl';\nimport type { ApplicationConfig, ServiceConfig, State } from './types';\n\nconst DEFAULTS = {\n sessionSampleRate: 100,\n sessionReplaySampleRate: 0,\n defaultPrivacyLevel: 'mask-user-input',\n} as const;\n\n/**\n * Interop surface: stored on globalThis, shared across independently\n * deployed bundles. First bundle to load wins. Append-only — never\n * remove or change method signatures.\n */\nexport function createImpl(): SharedImpl {\n let initialized = false;\n const state: State = {\n services: new Map(),\n };\n\n function initializeSdk(\n service: ServiceConfig,\n application: ApplicationConfig,\n enabled: boolean\n ): boolean {\n if (initialized) {\n // eslint-disable-next-line no-console\n console.info(\n '[datadog-rum] init: application config ignored; SDK already initialized.'\n );\n return false;\n }\n if (datadogRum.getInitConfiguration()) {\n // eslint-disable-next-line no-console\n console.warn(\n '[datadog-rum] init: SDK was initialized outside the facade; service handlers will not fire.'\n );\n return false;\n }\n\n const { beforeSend: appBeforeSend, ...sdkConfigPart } = application;\n if (appBeforeSend) {\n state.applicationBeforeSend = appBeforeSend;\n }\n datadogRum.init({\n ...DEFAULTS,\n ...sdkConfigPart,\n service: service.name,\n beforeSend: buildBeforeSend(state),\n allowedTracingUrls: buildAllowedTracingUrls(state),\n });\n if (!enabled) {\n datadogRum.setGlobalContextProperty(DATADOG_RUM_FOR_DEV, true);\n }\n initialized = true;\n return true;\n }\n\n function registerService({ name, ...reg }: ServiceConfig): void {\n const existing = state.services.get(name);\n state.services.set(name, { ...reg, context: existing?.context });\n }\n\n return {\n init({ service, application, enabled = true }) {\n let initializedSdk = false;\n\n if (application) {\n if (!enabled) {\n installDevConsole();\n }\n if (enabled || isForceEnabled()) {\n initializedSdk = initializeSdk(service, application, enabled);\n }\n }\n\n registerService(service);\n\n return {\n cleanup: () => state.services.delete(service.name),\n initializedSdk,\n };\n },\n\n setServiceContext(key, context) {\n const existing = state.services.get(key);\n state.services.set(key, { ...existing, context });\n },\n };\n}\n"],"names":["datadogRum","buildAllowedTracingUrls","buildBeforeSend","DATADOG_RUM_FOR_DEV","installDevConsole","isForceEnabled","DEFAULTS","sessionSampleRate","sessionReplaySampleRate","defaultPrivacyLevel","createImpl","initialized","state","services","Map","initializeSdk","service","application","enabled","console","info","getInitConfiguration","warn","beforeSend","appBeforeSend","sdkConfigPart","applicationBeforeSend","init","name","allowedTracingUrls","setGlobalContextProperty","registerService","reg","existing","get","set","context","initializedSdk","cleanup","delete","setServiceContext","key"],"mappings":"AAAA,SAASA,UAAU,QAAQ,uBAAuB;AAClD,SAASC,uBAAuB,QAAQ,+BAA+B;AACvE,SAASC,eAAe,QAAQ,sBAAsB;AACtD,SAASC,mBAAmB,EAAEC,iBAAiB,EAAEC,cAAc,QAAQ,qBAAqB;AAI5F,MAAMC,WAAW;IACbC,mBAAmB;IACnBC,yBAAyB;IACzBC,qBAAqB;AACzB;AAEA;;;;CAIC,GACD,OAAO,SAASC;IACZ,IAAIC,cAAc;IAClB,MAAMC,QAAe;QACjBC,UAAU,IAAIC;IAClB;IAEA,SAASC,cACLC,OAAsB,EACtBC,WAA8B,EAC9BC,OAAgB;QAEhB,IAAIP,aAAa;YACb,sCAAsC;YACtCQ,QAAQC,IAAI,CACR;YAEJ,OAAO;QACX;QACA,IAAIpB,WAAWqB,oBAAoB,IAAI;YACnC,sCAAsC;YACtCF,QAAQG,IAAI,CACR;YAEJ,OAAO;QACX;QAEA,MAAM,EAAEC,YAAYC,aAAa,EAAE,GAAGC,eAAe,GAAGR;QACxD,IAAIO,eAAe;YACfZ,MAAMc,qBAAqB,GAAGF;QAClC;QACAxB,WAAW2B,IAAI,CAAC;YACZ,GAAGrB,QAAQ;YACX,GAAGmB,aAAa;YAChBT,SAASA,QAAQY,IAAI;YACrBL,YAAYrB,gBAAgBU;YAC5BiB,oBAAoB5B,wBAAwBW;QAChD;QACA,IAAI,CAACM,SAAS;YACVlB,WAAW8B,wBAAwB,CAAC3B,qBAAqB;QAC7D;QACAQ,cAAc;QACd,OAAO;IACX;IAEA,SAASoB,gBAAgB,EAAEH,IAAI,EAAE,GAAGI,KAAoB;QACpD,MAAMC,WAAWrB,MAAMC,QAAQ,CAACqB,GAAG,CAACN;QACpChB,MAAMC,QAAQ,CAACsB,GAAG,CAACP,MAAM;YAAE,GAAGI,GAAG;YAAEI,OAAO,EAAEH,qBAAAA,+BAAAA,SAAUG,OAAO;QAAC;IAClE;IAEA,OAAO;QACHT,MAAK,EAAEX,OAAO,EAAEC,WAAW,EAAEC,UAAU,IAAI,EAAE;YACzC,IAAImB,iBAAiB;YAErB,IAAIpB,aAAa;gBACb,IAAI,CAACC,SAAS;oBACVd;gBACJ;gBACA,IAAIc,WAAWb,kBAAkB;oBAC7BgC,iBAAiBtB,cAAcC,SAASC,aAAaC;gBACzD;YACJ;YAEAa,gBAAgBf;YAEhB,OAAO;gBACHsB,SAAS,IAAM1B,MAAMC,QAAQ,CAAC0B,MAAM,CAACvB,QAAQY,IAAI;gBACjDS;YACJ;QACJ;QAEAG,mBAAkBC,GAAG,EAAEL,OAAO;YAC1B,MAAMH,WAAWrB,MAAMC,QAAQ,CAACqB,GAAG,CAACO;YACpC7B,MAAMC,QAAQ,CAACsB,GAAG,CAACM,KAAK;gBAAE,GAAGR,QAAQ;gBAAEG;YAAQ;QACnD;IACJ;AACJ"}
1
+ {"version":3,"sources":["../src/create-impl.ts"],"sourcesContent":["import { datadogRum } from '@datadog/browser-rum';\nimport { buildAllowedTracingUrls } from './build-allowed-tracing-urls';\nimport { buildBeforeSend } from './build-before-send';\nimport { installDdRumGuard } from './dd-rum-guard';\nimport { DATADOG_RUM_FOR_DEV, installDevConsole, isForceEnabled } from './runtime-override';\nimport type { SharedImpl } from './shared-impl';\nimport type { ApplicationConfig, PendingApplication, ServiceConfig, State } from './types';\n\nconst DEFAULTS = {\n sessionSampleRate: 100,\n sessionReplaySampleRate: 0,\n defaultPrivacyLevel: 'mask-user-input',\n} as const;\n\n/**\n * Interop surface: stored on globalThis, shared across independently\n * deployed bundles. First bundle to load wins. Append-only — never\n * remove or change method signatures.\n */\nexport function createImpl(): SharedImpl {\n let initialized = false;\n let offer: PendingApplication | undefined;\n const state: State = {\n services: new Map(),\n };\n\n function initializeSdk({\n service,\n application,\n enabled,\n initializedBy,\n }: {\n service: ServiceConfig;\n application: ApplicationConfig;\n enabled: boolean;\n initializedBy?: string;\n }): boolean {\n if (datadogRum.getInitConfiguration()) {\n // eslint-disable-next-line no-console\n console.warn(\n '[datadog-rum] init: SDK was initialized outside the facade; service handlers will not fire.'\n );\n return false;\n }\n\n const { beforeSend: appBeforeSend, ...sdkConfigPart } = application;\n if (appBeforeSend) {\n state.applicationBeforeSend = appBeforeSend;\n }\n datadogRum.init({\n ...DEFAULTS,\n ...sdkConfigPart,\n service: service.name,\n beforeSend: buildBeforeSend(state),\n allowedTracingUrls: buildAllowedTracingUrls(state),\n });\n if (!enabled) {\n datadogRum.setGlobalContextProperty(DATADOG_RUM_FOR_DEV, true);\n }\n installDdRumGuard(datadogRum);\n if (initializedBy) {\n datadogRum.setGlobalContextProperty('initializedBy', { service: initializedBy });\n }\n initialized = true;\n return true;\n }\n\n function registerService({ name, ...reg }: ServiceConfig): void {\n const existing = state.services.get(name);\n state.services.set(name, { ...reg, context: existing?.context });\n }\n\n function startSdk(\n service: ServiceConfig,\n application: ApplicationConfig | undefined,\n enabled: boolean\n ): boolean {\n if (application && !enabled) {\n installDevConsole();\n }\n\n if (initialized) {\n if (application) {\n // eslint-disable-next-line no-console\n console.info(\n `[datadog-rum] init: application config from '${service.name}' ignored; the SDK is already started.`\n );\n }\n return false;\n }\n\n if (application) {\n offer ??= { service, application };\n }\n\n if (!offer || (!enabled && !isForceEnabled())) {\n return false;\n }\n\n const startedByOfferer = offer.service.name === service.name;\n if (application && !startedByOfferer) {\n // eslint-disable-next-line no-console\n console.info(\n `[datadog-rum] init: application config from '${service.name}' ignored; started the application offered by '${offer.service.name}'.`\n );\n }\n\n return initializeSdk({\n service: offer.service,\n application: offer.application,\n enabled,\n initializedBy: startedByOfferer ? undefined : service.name,\n });\n }\n\n return {\n init({ service, application, enabled = true }) {\n const initializedSdk = startSdk(service, application, enabled);\n registerService(service);\n\n return {\n cleanup: () => state.services.delete(service.name),\n initializedSdk,\n };\n },\n\n setServiceContext(key, context) {\n const existing = state.services.get(key);\n state.services.set(key, { ...existing, context });\n },\n };\n}\n"],"names":["datadogRum","buildAllowedTracingUrls","buildBeforeSend","installDdRumGuard","DATADOG_RUM_FOR_DEV","installDevConsole","isForceEnabled","DEFAULTS","sessionSampleRate","sessionReplaySampleRate","defaultPrivacyLevel","createImpl","initialized","offer","state","services","Map","initializeSdk","service","application","enabled","initializedBy","getInitConfiguration","console","warn","beforeSend","appBeforeSend","sdkConfigPart","applicationBeforeSend","init","name","allowedTracingUrls","setGlobalContextProperty","registerService","reg","existing","get","set","context","startSdk","info","startedByOfferer","undefined","initializedSdk","cleanup","delete","setServiceContext","key"],"mappings":"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"}
@@ -0,0 +1,3 @@
1
+ import type { DatadogRum } from '@datadog/browser-rum';
2
+ export declare function installDdRumGuard(instance: DatadogRum): void;
3
+ //# sourceMappingURL=dd-rum-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dd-rum-guard.d.ts","sourceRoot":"","sources":["../src/dd-rum-guard.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,UAAU,GAAG,IAAI,CAY5D"}
@@ -0,0 +1,15 @@
1
+ export function installDdRumGuard(instance) {
2
+ try {
3
+ Object.defineProperty(window, 'DD_RUM', {
4
+ configurable: true,
5
+ enumerable: true,
6
+ get: ()=>instance,
7
+ set: ()=>{}
8
+ });
9
+ } catch (error) {
10
+ // eslint-disable-next-line no-console
11
+ console.error('[datadog-rum] failed to install the window.DD_RUM guard', error);
12
+ }
13
+ }
14
+
15
+ //# sourceMappingURL=dd-rum-guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/dd-rum-guard.ts"],"sourcesContent":["import type { DatadogRum } from '@datadog/browser-rum';\n\nexport function installDdRumGuard(instance: DatadogRum): void {\n try {\n Object.defineProperty(window, 'DD_RUM', {\n configurable: true,\n enumerable: true,\n get: () => instance,\n set: () => {},\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[datadog-rum] failed to install the window.DD_RUM guard', error);\n }\n}\n"],"names":["installDdRumGuard","instance","Object","defineProperty","window","configurable","enumerable","get","set","error","console"],"mappings":"AAEA,OAAO,SAASA,kBAAkBC,QAAoB;IAClD,IAAI;QACAC,OAAOC,cAAc,CAACC,QAAQ,UAAU;YACpCC,cAAc;YACdC,YAAY;YACZC,KAAK,IAAMN;YACXO,KAAK,KAAO;QAChB;IACJ,EAAE,OAAOC,OAAO;QACZ,sCAAsC;QACtCC,QAAQD,KAAK,CAAC,2DAA2DA;IAC7E;AACJ"}
package/dist/init.d.ts CHANGED
@@ -3,10 +3,11 @@ export type { ApplicationConfig, Cleanup, InitRumOptions, RumService, RumService
3
3
  /**
4
4
  * Registers a service and, optionally, initializes the Datadog RUM SDK.
5
5
  *
6
- * Any caller may pass `application`. The first call that includes it
7
- * initializes the SDK; subsequent callers' `application` config is ignored
8
- * with a warning. Callers that omit `application` register their service
9
- * without attempting SDK init.
6
+ * Any caller may pass `application`. The first `application` passed wins,
7
+ * and a later caller's `application` config is ignored. The SDK starts on
8
+ * the first call that asks for a session, which is not always the call that
9
+ * supplied the winning `application`. Callers that omit `application`
10
+ * register their service without attempting SDK init.
10
11
  *
11
12
  * Returns a `RumServiceRegistration` — `{ cleanup, setServiceContext }`.
12
13
  * `cleanup` removes this service's `beforeSend`, `allowedTracingUrls`, and
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAEtE,YAAY,EACR,iBAAiB,EACjB,OAAO,EACP,cAAc,EACd,UAAU,EACV,sBAAsB,EACtB,aAAa,EACb,kBAAkB,GACrB,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;GAYG;AACH,wBAAgB,IAAI,CAAC,IAAI,EAAE,cAAc,GAAG,sBAAsB,CAWjE"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAEtE,YAAY,EACR,iBAAiB,EACjB,OAAO,EACP,cAAc,EACd,UAAU,EACV,sBAAsB,EACtB,aAAa,EACb,kBAAkB,GACrB,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;GAaG;AACH,wBAAgB,IAAI,CAAC,IAAI,EAAE,cAAc,GAAG,sBAAsB,CAWjE"}
package/dist/init.js CHANGED
@@ -3,10 +3,11 @@ import { getOrCreateSharedImpl } from './get-shared';
3
3
  /**
4
4
  * Registers a service and, optionally, initializes the Datadog RUM SDK.
5
5
  *
6
- * Any caller may pass `application`. The first call that includes it
7
- * initializes the SDK; subsequent callers' `application` config is ignored
8
- * with a warning. Callers that omit `application` register their service
9
- * without attempting SDK init.
6
+ * Any caller may pass `application`. The first `application` passed wins,
7
+ * and a later caller's `application` config is ignored. The SDK starts on
8
+ * the first call that asks for a session, which is not always the call that
9
+ * supplied the winning `application`. Callers that omit `application`
10
+ * register their service without attempting SDK init.
10
11
  *
11
12
  * Returns a `RumServiceRegistration` — `{ cleanup, setServiceContext }`.
12
13
  * `cleanup` removes this service's `beforeSend`, `allowedTracingUrls`, and
package/dist/init.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/init.ts"],"sourcesContent":["import { bundleState } from './bundle-state';\nimport { getOrCreateSharedImpl } from './get-shared';\nimport type { InitRumOptions, RumServiceRegistration } from './types';\n\nexport type {\n ApplicationConfig,\n Cleanup,\n InitRumOptions,\n RumService,\n RumServiceRegistration,\n ServiceConfig,\n ServiceTracingUrls,\n} from './types';\n\n/**\n * Registers a service and, optionally, initializes the Datadog RUM SDK.\n *\n * Any caller may pass `application`. The first call that includes it\n * initializes the SDK; subsequent callers' `application` config is ignored\n * with a warning. Callers that omit `application` register their service\n * without attempting SDK init.\n *\n * Returns a `RumServiceRegistration` — `{ cleanup, setServiceContext }`.\n * `cleanup` removes this service's `beforeSend`, `allowedTracingUrls`, and\n * persistent context. `setServiceContext` attaches session-lifetime metadata\n * to every event whose `event.service` matches this service's name.\n */\nexport function init(opts: InitRumOptions): RumServiceRegistration {\n const impl = getOrCreateSharedImpl();\n const result = impl.init(opts);\n if (result.initializedSdk) {\n bundleState.isSdkInitializer = true;\n }\n const { name } = opts.service;\n return {\n cleanup: result.cleanup,\n setServiceContext: context => impl.setServiceContext(name, context),\n };\n}\n"],"names":["bundleState","getOrCreateSharedImpl","init","opts","impl","result","initializedSdk","isSdkInitializer","name","service","cleanup","setServiceContext","context"],"mappings":"AAAA,SAASA,WAAW,QAAQ,iBAAiB;AAC7C,SAASC,qBAAqB,QAAQ,eAAe;AAarD;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,KAAKC,IAAoB;IACrC,MAAMC,OAAOH;IACb,MAAMI,SAASD,KAAKF,IAAI,CAACC;IACzB,IAAIE,OAAOC,cAAc,EAAE;QACvBN,YAAYO,gBAAgB,GAAG;IACnC;IACA,MAAM,EAAEC,IAAI,EAAE,GAAGL,KAAKM,OAAO;IAC7B,OAAO;QACHC,SAASL,OAAOK,OAAO;QACvBC,mBAAmBC,CAAAA,UAAWR,KAAKO,iBAAiB,CAACH,MAAMI;IAC/D;AACJ"}
1
+ {"version":3,"sources":["../src/init.ts"],"sourcesContent":["import { bundleState } from './bundle-state';\nimport { getOrCreateSharedImpl } from './get-shared';\nimport type { InitRumOptions, RumServiceRegistration } from './types';\n\nexport type {\n ApplicationConfig,\n Cleanup,\n InitRumOptions,\n RumService,\n RumServiceRegistration,\n ServiceConfig,\n ServiceTracingUrls,\n} from './types';\n\n/**\n * Registers a service and, optionally, initializes the Datadog RUM SDK.\n *\n * Any caller may pass `application`. The first `application` passed wins,\n * and a later caller's `application` config is ignored. The SDK starts on\n * the first call that asks for a session, which is not always the call that\n * supplied the winning `application`. Callers that omit `application`\n * register their service without attempting SDK init.\n *\n * Returns a `RumServiceRegistration` — `{ cleanup, setServiceContext }`.\n * `cleanup` removes this service's `beforeSend`, `allowedTracingUrls`, and\n * persistent context. `setServiceContext` attaches session-lifetime metadata\n * to every event whose `event.service` matches this service's name.\n */\nexport function init(opts: InitRumOptions): RumServiceRegistration {\n const impl = getOrCreateSharedImpl();\n const result = impl.init(opts);\n if (result.initializedSdk) {\n bundleState.isSdkInitializer = true;\n }\n const { name } = opts.service;\n return {\n cleanup: result.cleanup,\n setServiceContext: context => impl.setServiceContext(name, context),\n };\n}\n"],"names":["bundleState","getOrCreateSharedImpl","init","opts","impl","result","initializedSdk","isSdkInitializer","name","service","cleanup","setServiceContext","context"],"mappings":"AAAA,SAASA,WAAW,QAAQ,iBAAiB;AAC7C,SAASC,qBAAqB,QAAQ,eAAe;AAarD;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,KAAKC,IAAoB;IACrC,MAAMC,OAAOH;IACb,MAAMI,SAASD,KAAKF,IAAI,CAACC;IACzB,IAAIE,OAAOC,cAAc,EAAE;QACvBN,YAAYO,gBAAgB,GAAG;IACnC;IACA,MAAM,EAAEC,IAAI,EAAE,GAAGL,KAAKM,OAAO;IAC7B,OAAO;QACHC,SAASL,OAAOK,OAAO;QACvBC,mBAAmBC,CAAAA,UAAWR,KAAKO,iBAAiB,CAACH,MAAMI;IAC/D;AACJ"}
package/dist/types.d.ts CHANGED
@@ -42,6 +42,10 @@ export interface InitRumOptions {
42
42
  export interface ServiceEntry extends ServiceShape {
43
43
  context?: Context;
44
44
  }
45
+ export interface PendingApplication {
46
+ service: ServiceConfig;
47
+ application: ApplicationConfig;
48
+ }
45
49
  /** Registration state: application-level handler + per-service entries keyed by service name. */
46
50
  export interface State {
47
51
  applicationBeforeSend?: ApplicationBeforeSendHandler;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,KAAK,EAAE,4BAA4B,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAE5F;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC;AAEhF,yFAAyF;AACzF,MAAM,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC;AAEjC;;;GAGG;AACH,MAAM,WAAW,UAAU;IACvB,iBAAiB,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;CACjD;AAED,qFAAqF;AACrF,MAAM,WAAW,sBAAuB,SAAQ,UAAU;IACtD,OAAO,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAChC,oBAAoB,EACpB,YAAY,GAAG,oBAAoB,GAAG,SAAS,CAClD,GAAG;IACA,UAAU,CAAC,EAAE,4BAA4B,CAAC;CAC7C,CAAC;AAEF,UAAU,YAAY;IAClB,UAAU,CAAC,EAAE,wBAAwB,CAAC;IACtC,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;CAC3C;AAED,MAAM,WAAW,aAAc,SAAQ,YAAY;IAC/C,IAAI,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,cAAc;IAC3B,OAAO,EAAE,aAAa,CAAC;IACvB,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAChC,OAAO,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;GAGG;AACH,MAAM,WAAW,YAAa,SAAQ,YAAY;IAC9C,OAAO,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,iGAAiG;AACjG,MAAM,WAAW,KAAK;IAClB,qBAAqB,CAAC,EAAE,4BAA4B,CAAC;IACrD,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;CACvC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,KAAK,EAAE,4BAA4B,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAE5F;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC;AAEhF,yFAAyF;AACzF,MAAM,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC;AAEjC;;;GAGG;AACH,MAAM,WAAW,UAAU;IACvB,iBAAiB,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;CACjD;AAED,qFAAqF;AACrF,MAAM,WAAW,sBAAuB,SAAQ,UAAU;IACtD,OAAO,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAChC,oBAAoB,EACpB,YAAY,GAAG,oBAAoB,GAAG,SAAS,CAClD,GAAG;IACA,UAAU,CAAC,EAAE,4BAA4B,CAAC;CAC7C,CAAC;AAEF,UAAU,YAAY;IAClB,UAAU,CAAC,EAAE,wBAAwB,CAAC;IACtC,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;CAC3C;AAED,MAAM,WAAW,aAAc,SAAQ,YAAY;IAC/C,IAAI,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,cAAc;IAC3B,OAAO,EAAE,aAAa,CAAC;IACvB,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAChC,OAAO,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;GAGG;AACH,MAAM,WAAW,YAAa,SAAQ,YAAY;IAC9C,OAAO,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,kBAAkB;IAC/B,OAAO,EAAE,aAAa,CAAC;IACvB,WAAW,EAAE,iBAAiB,CAAC;CAClC;AAED,iGAAiG;AACjG,MAAM,WAAW,KAAK;IAClB,qBAAqB,CAAC,EAAE,4BAA4B,CAAC;IACrD,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;CACvC"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { Context } from '@datadog/browser-core';\nimport type { MatchOption, PropagatorType, RumInitConfiguration } from '@datadog/browser-rum';\nimport type { ApplicationBeforeSendHandler, ServiceBeforeSendHandler } from './before-send';\n\n/**\n * URL matchers grouped by the propagator type whose headers they should\n * activate. A service registers its tracing URLs as e.g.\n * `{ tracecontext: [/api\\//, 'https://...'] }`.\n */\nexport type ServiceTracingUrls = Partial<Record<PropagatorType, MatchOption[]>>;\n\n/** Tears down a service registration: handlers, tracing URLs, and persistent context. */\nexport type Cleanup = () => void;\n\n/**\n * Service handle returned by `useRumService`. `setServiceContext` is bound to the\n * service registered by the hook, so callers don't pass the service name again.\n */\nexport interface RumService {\n setServiceContext: (context: Context) => void;\n}\n\n/** Imperative service registration returned by `init`. Adds the cleanup contract. */\nexport interface RumServiceRegistration extends RumService {\n cleanup: Cleanup;\n}\n\nexport type ApplicationConfig = Omit<\n RumInitConfiguration,\n 'beforeSend' | 'allowedTracingUrls' | 'service'\n> & {\n beforeSend?: ApplicationBeforeSendHandler;\n};\n\ninterface ServiceShape {\n beforeSend?: ServiceBeforeSendHandler;\n allowedTracingUrls?: ServiceTracingUrls;\n}\n\nexport interface ServiceConfig extends ServiceShape {\n name: string;\n}\n\nexport interface InitRumOptions {\n service: ServiceConfig;\n application?: ApplicationConfig;\n enabled?: boolean;\n}\n\n/**\n * Per-service entry — `beforeSend` and `allowedTracingUrls` come from\n * `init`; `context` comes from `setServiceContext`. One service = one entry.\n */\nexport interface ServiceEntry extends ServiceShape {\n context?: Context;\n}\n\n/** Registration state: application-level handler + per-service entries keyed by service name. */\nexport interface State {\n applicationBeforeSend?: ApplicationBeforeSendHandler;\n services: Map<string, ServiceEntry>;\n}\n"],"names":[],"mappings":"AAyDA,+FAA+F,GAC/F,WAGC"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { Context } from '@datadog/browser-core';\nimport type { MatchOption, PropagatorType, RumInitConfiguration } from '@datadog/browser-rum';\nimport type { ApplicationBeforeSendHandler, ServiceBeforeSendHandler } from './before-send';\n\n/**\n * URL matchers grouped by the propagator type whose headers they should\n * activate. A service registers its tracing URLs as e.g.\n * `{ tracecontext: [/api\\//, 'https://...'] }`.\n */\nexport type ServiceTracingUrls = Partial<Record<PropagatorType, MatchOption[]>>;\n\n/** Tears down a service registration: handlers, tracing URLs, and persistent context. */\nexport type Cleanup = () => void;\n\n/**\n * Service handle returned by `useRumService`. `setServiceContext` is bound to the\n * service registered by the hook, so callers don't pass the service name again.\n */\nexport interface RumService {\n setServiceContext: (context: Context) => void;\n}\n\n/** Imperative service registration returned by `init`. Adds the cleanup contract. */\nexport interface RumServiceRegistration extends RumService {\n cleanup: Cleanup;\n}\n\nexport type ApplicationConfig = Omit<\n RumInitConfiguration,\n 'beforeSend' | 'allowedTracingUrls' | 'service'\n> & {\n beforeSend?: ApplicationBeforeSendHandler;\n};\n\ninterface ServiceShape {\n beforeSend?: ServiceBeforeSendHandler;\n allowedTracingUrls?: ServiceTracingUrls;\n}\n\nexport interface ServiceConfig extends ServiceShape {\n name: string;\n}\n\nexport interface InitRumOptions {\n service: ServiceConfig;\n application?: ApplicationConfig;\n enabled?: boolean;\n}\n\n/**\n * Per-service entry — `beforeSend` and `allowedTracingUrls` come from\n * `init`; `context` comes from `setServiceContext`. One service = one entry.\n */\nexport interface ServiceEntry extends ServiceShape {\n context?: Context;\n}\n\nexport interface PendingApplication {\n service: ServiceConfig;\n application: ApplicationConfig;\n}\n\n/** Registration state: application-level handler + per-service entries keyed by service name. */\nexport interface State {\n applicationBeforeSend?: ApplicationBeforeSendHandler;\n services: Map<string, ServiceEntry>;\n}\n"],"names":[],"mappings":"AA8DA,+FAA+F,GAC/F,WAGC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@servicetitan/datadog-rum",
3
- "version": "39.2.0",
3
+ "version": "40.0.0",
4
4
  "description": "DataDog RUM JS SDK configuration for standalone applications",
5
5
  "homepage": "https://docs.st.dev/docs/frontend/uikit/datadog-rum",
6
6
  "repository": {
@@ -22,8 +22,8 @@
22
22
  "src"
23
23
  ],
24
24
  "devDependencies": {
25
- "@datadog/browser-rum": "^7.9.0",
26
- "@testing-library/dom": "^10.4.1",
25
+ "@datadog/browser-rum": "^7.13.0",
26
+ "@testing-library/dom": "^10.4.2",
27
27
  "@testing-library/jest-dom": "^7.0.1",
28
28
  "@testing-library/react": "^16.3.3",
29
29
  "react": "~18.3.1",
@@ -3,13 +3,15 @@ import { minimalApplication } from '../__mocks__';
3
3
  import { buildAllowedTracingUrls } from '../build-allowed-tracing-urls';
4
4
  import { buildBeforeSend } from '../build-before-send';
5
5
  import { createImpl } from '../create-impl';
6
+ import { installDdRumGuard } from '../dd-rum-guard';
6
7
  import { DATADOG_RUM_FOR_DEV, installDevConsole, isForceEnabled } from '../runtime-override';
7
8
  import type { SharedImpl } from '../shared-impl';
8
- import type { InitRumOptions, State } from '../types';
9
+ import type { ApplicationConfig, InitRumOptions, State } from '../types';
9
10
 
10
11
  jest.mock('@datadog/browser-rum');
11
12
  jest.mock('../build-before-send');
12
13
  jest.mock('../build-allowed-tracing-urls');
14
+ jest.mock('../dd-rum-guard');
13
15
  jest.mock('../runtime-override', () => ({
14
16
  ...jest.requireActual('../runtime-override'),
15
17
  isForceEnabled: jest.fn(),
@@ -159,6 +161,12 @@ describe(`[datadog-rum] ${createImpl.name}`, () => {
159
161
  });
160
162
  }
161
163
 
164
+ test('installs the window.DD_RUM guard', () => {
165
+ subject();
166
+
167
+ expect(installDdRumGuard).toHaveBeenCalledWith(datadogRum);
168
+ });
169
+
162
170
  describe('when already called', () => {
163
171
  beforeEach(() => {
164
172
  subject();
@@ -174,11 +182,32 @@ describe(`[datadog-rum] ${createImpl.name}`, () => {
174
182
  subject();
175
183
 
176
184
  expect(infoSpy).toHaveBeenCalledWith(
177
- expect.stringContaining('application config ignored')
185
+ expect.stringContaining('the SDK is already started')
178
186
  );
179
187
  });
180
188
  });
181
189
 
190
+ describe('when a session is already started', () => {
191
+ beforeEach(() => subject());
192
+
193
+ describe('when an application is offered', () => {
194
+ beforeEach(() => (options.enabled = false));
195
+
196
+ test('does not initialize a second time', () => {
197
+ subject();
198
+
199
+ expect(datadogRum.init).toHaveBeenCalledTimes(1);
200
+ });
201
+
202
+ test('does not start the late offer afterwards', () => {
203
+ subject();
204
+ impl.init({ service: { name: 'task-hub-my-tasks' } });
205
+
206
+ expect(datadogRum.init).toHaveBeenCalledTimes(1);
207
+ });
208
+ });
209
+ });
210
+
182
211
  describe('when datadogRum.init was already called directly', () => {
183
212
  beforeEach(() => {
184
213
  jest.spyOn(console, 'warn').mockImplementation(() => {});
@@ -251,6 +280,103 @@ describe(`[datadog-rum] ${createImpl.name}`, () => {
251
280
 
252
281
  itDoesNotInstallDevConsole();
253
282
  });
283
+
284
+ describe('when the application is offered', () => {
285
+ const host = 'desktop';
286
+ const guest = 'task-hub-my-tasks';
287
+ const askForSession = (application?: ApplicationConfig) =>
288
+ impl.init({ service: { name: guest }, application });
289
+
290
+ const expectOfferedApplication = () =>
291
+ expect(datadogRum.init).toHaveBeenCalledWith(
292
+ expect.objectContaining({
293
+ applicationId: minimalApplication.applicationId,
294
+ service: host,
295
+ })
296
+ );
297
+
298
+ beforeEach(() => {
299
+ jest.spyOn(console, 'info').mockImplementation(() => {});
300
+ subject();
301
+ });
302
+
303
+ describe('when a later caller asks for a session', () => {
304
+ const guestApplication = {
305
+ ...minimalApplication,
306
+ applicationId: 'guest-app-id',
307
+ };
308
+
309
+ beforeEach(() => askForSession(guestApplication));
310
+
311
+ test('initializes with the offered application', expectOfferedApplication);
312
+
313
+ test("does not initialize with the later caller's application", () => {
314
+ expect(datadogRum.init).not.toHaveBeenCalledWith(
315
+ expect.objectContaining({ applicationId: 'guest-app-id' })
316
+ );
317
+ });
318
+
319
+ test('records the service that started the session', () => {
320
+ expect(datadogRum.setGlobalContextProperty).toHaveBeenCalledWith(
321
+ 'initializedBy',
322
+ { service: guest }
323
+ );
324
+ });
325
+
326
+ test('does not tag the session as a dev override', () => {
327
+ expect(datadogRum.setGlobalContextProperty).not.toHaveBeenCalledWith(
328
+ DATADOG_RUM_FOR_DEV,
329
+ true
330
+ );
331
+ });
332
+
333
+ test("registers the later caller's service", () => {
334
+ expect(capturedState().services.has(guest)).toBe(true);
335
+ });
336
+
337
+ test('logs which application started', () => {
338
+ expect(jest.spyOn(console, 'info')).toHaveBeenCalledWith(
339
+ expect.stringContaining(`'${guest}' ignored`)
340
+ );
341
+ });
342
+ });
343
+
344
+ describe('when a later caller asks with no application', () => {
345
+ beforeEach(() => askForSession());
346
+
347
+ test('initializes with the offered application', expectOfferedApplication);
348
+
349
+ test('records the service that started the session', () => {
350
+ expect(datadogRum.setGlobalContextProperty).toHaveBeenCalledWith(
351
+ 'initializedBy',
352
+ { service: guest }
353
+ );
354
+ });
355
+
356
+ test('does not report an ignored application', () => {
357
+ expect(jest.spyOn(console, 'info')).not.toHaveBeenCalled();
358
+ });
359
+ });
360
+
361
+ describe('when a later caller offers another application', () => {
362
+ beforeEach(() => {
363
+ impl.init({
364
+ service: { name: 'enterprise-hub' },
365
+ application: { ...minimalApplication, applicationId: 'later-app-id' },
366
+ enabled: false,
367
+ });
368
+ askForSession();
369
+ });
370
+
371
+ test('keeps the first offer', expectOfferedApplication);
372
+
373
+ test('does not initialize with the later offer', () => {
374
+ expect(datadogRum.init).not.toHaveBeenCalledWith(
375
+ expect.objectContaining({ applicationId: 'later-app-id' })
376
+ );
377
+ });
378
+ });
379
+ });
254
380
  });
255
381
 
256
382
  describe('cleanup', () => {
@@ -0,0 +1,73 @@
1
+ import type { DatadogRum } from '@datadog/browser-rum';
2
+ import { installDdRumGuard } from '../dd-rum-guard';
3
+
4
+ describe(`[datadog-rum] ${installDdRumGuard.name}`, () => {
5
+ const slot = window as unknown as Record<string, unknown>;
6
+
7
+ let instance: DatadogRum;
8
+ let errorSpy: jest.SpyInstance;
9
+
10
+ beforeEach(() => {
11
+ jest.clearAllMocks();
12
+ errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
13
+ instance = { addAction: jest.fn() } as unknown as DatadogRum;
14
+ delete slot.DD_RUM;
15
+ });
16
+
17
+ afterEach(() => {
18
+ delete slot.DD_RUM;
19
+ });
20
+
21
+ const subject = () => installDdRumGuard(instance);
22
+
23
+ test('exposes the initialized instance', () => {
24
+ subject();
25
+
26
+ expect(slot.DD_RUM).toBe(instance);
27
+ });
28
+
29
+ describe('when other code reassigns the handle', () => {
30
+ beforeEach(() => {
31
+ subject();
32
+ slot.DD_RUM = { impostor: true };
33
+ });
34
+
35
+ test('keeps the initialized instance', () => {
36
+ expect(slot.DD_RUM).toBe(instance);
37
+ });
38
+
39
+ test('reports nothing', () => {
40
+ expect(instance.addAction).not.toHaveBeenCalled();
41
+ });
42
+
43
+ describe('when the handle is reassigned multiple times', () => {
44
+ beforeEach(() => {
45
+ slot.DD_RUM = { impostor: 'again' };
46
+ slot.DD_RUM = { impostor: 'and again' };
47
+ });
48
+
49
+ test('still keeps the initialized instance', () => {
50
+ expect(slot.DD_RUM).toBe(instance);
51
+ });
52
+ });
53
+ });
54
+
55
+ describe('when the handle cannot be defined', () => {
56
+ const error = new Error('Nope!');
57
+
58
+ beforeEach(() => {
59
+ jest.spyOn(Object, 'defineProperty').mockImplementationOnce(() => {
60
+ throw error;
61
+ });
62
+ });
63
+
64
+ test('reports the failure rather than throwing', () => {
65
+ subject();
66
+
67
+ expect(errorSpy).toHaveBeenCalledWith(
68
+ expect.stringContaining('failed to install the window.DD_RUM guard'),
69
+ error
70
+ );
71
+ });
72
+ });
73
+ });
@@ -1,9 +1,10 @@
1
1
  import { datadogRum } from '@datadog/browser-rum';
2
2
  import { buildAllowedTracingUrls } from './build-allowed-tracing-urls';
3
3
  import { buildBeforeSend } from './build-before-send';
4
+ import { installDdRumGuard } from './dd-rum-guard';
4
5
  import { DATADOG_RUM_FOR_DEV, installDevConsole, isForceEnabled } from './runtime-override';
5
6
  import type { SharedImpl } from './shared-impl';
6
- import type { ApplicationConfig, ServiceConfig, State } from './types';
7
+ import type { ApplicationConfig, PendingApplication, ServiceConfig, State } from './types';
7
8
 
8
9
  const DEFAULTS = {
9
10
  sessionSampleRate: 100,
@@ -18,22 +19,22 @@ const DEFAULTS = {
18
19
  */
19
20
  export function createImpl(): SharedImpl {
20
21
  let initialized = false;
22
+ let offer: PendingApplication | undefined;
21
23
  const state: State = {
22
24
  services: new Map(),
23
25
  };
24
26
 
25
- function initializeSdk(
26
- service: ServiceConfig,
27
- application: ApplicationConfig,
28
- enabled: boolean
29
- ): boolean {
30
- if (initialized) {
31
- // eslint-disable-next-line no-console
32
- console.info(
33
- '[datadog-rum] init: application config ignored; SDK already initialized.'
34
- );
35
- return false;
36
- }
27
+ function initializeSdk({
28
+ service,
29
+ application,
30
+ enabled,
31
+ initializedBy,
32
+ }: {
33
+ service: ServiceConfig;
34
+ application: ApplicationConfig;
35
+ enabled: boolean;
36
+ initializedBy?: string;
37
+ }): boolean {
37
38
  if (datadogRum.getInitConfiguration()) {
38
39
  // eslint-disable-next-line no-console
39
40
  console.warn(
@@ -56,6 +57,10 @@ export function createImpl(): SharedImpl {
56
57
  if (!enabled) {
57
58
  datadogRum.setGlobalContextProperty(DATADOG_RUM_FOR_DEV, true);
58
59
  }
60
+ installDdRumGuard(datadogRum);
61
+ if (initializedBy) {
62
+ datadogRum.setGlobalContextProperty('initializedBy', { service: initializedBy });
63
+ }
59
64
  initialized = true;
60
65
  return true;
61
66
  }
@@ -65,19 +70,52 @@ export function createImpl(): SharedImpl {
65
70
  state.services.set(name, { ...reg, context: existing?.context });
66
71
  }
67
72
 
68
- return {
69
- init({ service, application, enabled = true }) {
70
- let initializedSdk = false;
73
+ function startSdk(
74
+ service: ServiceConfig,
75
+ application: ApplicationConfig | undefined,
76
+ enabled: boolean
77
+ ): boolean {
78
+ if (application && !enabled) {
79
+ installDevConsole();
80
+ }
71
81
 
82
+ if (initialized) {
72
83
  if (application) {
73
- if (!enabled) {
74
- installDevConsole();
75
- }
76
- if (enabled || isForceEnabled()) {
77
- initializedSdk = initializeSdk(service, application, enabled);
78
- }
84
+ // eslint-disable-next-line no-console
85
+ console.info(
86
+ `[datadog-rum] init: application config from '${service.name}' ignored; the SDK is already started.`
87
+ );
79
88
  }
89
+ return false;
90
+ }
80
91
 
92
+ if (application) {
93
+ offer ??= { service, application };
94
+ }
95
+
96
+ if (!offer || (!enabled && !isForceEnabled())) {
97
+ return false;
98
+ }
99
+
100
+ const startedByOfferer = offer.service.name === service.name;
101
+ if (application && !startedByOfferer) {
102
+ // eslint-disable-next-line no-console
103
+ console.info(
104
+ `[datadog-rum] init: application config from '${service.name}' ignored; started the application offered by '${offer.service.name}'.`
105
+ );
106
+ }
107
+
108
+ return initializeSdk({
109
+ service: offer.service,
110
+ application: offer.application,
111
+ enabled,
112
+ initializedBy: startedByOfferer ? undefined : service.name,
113
+ });
114
+ }
115
+
116
+ return {
117
+ init({ service, application, enabled = true }) {
118
+ const initializedSdk = startSdk(service, application, enabled);
81
119
  registerService(service);
82
120
 
83
121
  return {
@@ -0,0 +1,15 @@
1
+ import type { DatadogRum } from '@datadog/browser-rum';
2
+
3
+ export function installDdRumGuard(instance: DatadogRum): void {
4
+ try {
5
+ Object.defineProperty(window, 'DD_RUM', {
6
+ configurable: true,
7
+ enumerable: true,
8
+ get: () => instance,
9
+ set: () => {},
10
+ });
11
+ } catch (error) {
12
+ // eslint-disable-next-line no-console
13
+ console.error('[datadog-rum] failed to install the window.DD_RUM guard', error);
14
+ }
15
+ }
package/src/init.ts CHANGED
@@ -15,10 +15,11 @@ export type {
15
15
  /**
16
16
  * Registers a service and, optionally, initializes the Datadog RUM SDK.
17
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.
18
+ * Any caller may pass `application`. The first `application` passed wins,
19
+ * and a later caller's `application` config is ignored. The SDK starts on
20
+ * the first call that asks for a session, which is not always the call that
21
+ * supplied the winning `application`. Callers that omit `application`
22
+ * register their service without attempting SDK init.
22
23
  *
23
24
  * Returns a `RumServiceRegistration` — `{ cleanup, setServiceContext }`.
24
25
  * `cleanup` removes this service's `beforeSend`, `allowedTracingUrls`, and
package/src/types.ts CHANGED
@@ -55,6 +55,11 @@ export interface ServiceEntry extends ServiceShape {
55
55
  context?: Context;
56
56
  }
57
57
 
58
+ export interface PendingApplication {
59
+ service: ServiceConfig;
60
+ application: ApplicationConfig;
61
+ }
62
+
58
63
  /** Registration state: application-level handler + per-service entries keyed by service name. */
59
64
  export interface State {
60
65
  applicationBeforeSend?: ApplicationBeforeSendHandler;