@amplitude/session-replay-browser 1.47.0-sr-trc-debug-log.3 → 1.47.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 (100) hide show
  1. package/README.md +203 -0
  2. package/lib/cjs/beacon-transport.d.ts +2 -0
  3. package/lib/cjs/beacon-transport.d.ts.map +1 -1
  4. package/lib/cjs/beacon-transport.js +39 -1
  5. package/lib/cjs/beacon-transport.js.map +1 -1
  6. package/lib/cjs/config/joined-config.d.ts +1 -6
  7. package/lib/cjs/config/joined-config.d.ts.map +1 -1
  8. package/lib/cjs/config/joined-config.js +23 -64
  9. package/lib/cjs/config/joined-config.js.map +1 -1
  10. package/lib/cjs/config/local-config.d.ts +4 -6
  11. package/lib/cjs/config/local-config.d.ts.map +1 -1
  12. package/lib/cjs/config/local-config.js +3 -19
  13. package/lib/cjs/config/local-config.js.map +1 -1
  14. package/lib/cjs/config/types.d.ts +74 -19
  15. package/lib/cjs/config/types.d.ts.map +1 -1
  16. package/lib/cjs/config/types.js.map +1 -1
  17. package/lib/cjs/index.d.ts +1 -0
  18. package/lib/cjs/index.d.ts.map +1 -1
  19. package/lib/cjs/index.js.map +1 -1
  20. package/lib/cjs/plugins/url-tracking-plugin.d.ts +0 -13
  21. package/lib/cjs/plugins/url-tracking-plugin.d.ts.map +1 -1
  22. package/lib/cjs/plugins/url-tracking-plugin.js +2 -6
  23. package/lib/cjs/plugins/url-tracking-plugin.js.map +1 -1
  24. package/lib/cjs/session-replay.d.ts +0 -33
  25. package/lib/cjs/session-replay.d.ts.map +1 -1
  26. package/lib/cjs/session-replay.js +40 -335
  27. package/lib/cjs/session-replay.js.map +1 -1
  28. package/lib/cjs/targeting/targeting-manager.d.ts +1 -4
  29. package/lib/cjs/targeting/targeting-manager.d.ts.map +1 -1
  30. package/lib/cjs/targeting/targeting-manager.js +10 -56
  31. package/lib/cjs/targeting/targeting-manager.js.map +1 -1
  32. package/lib/cjs/track-destination.d.ts +5 -1
  33. package/lib/cjs/track-destination.d.ts.map +1 -1
  34. package/lib/cjs/track-destination.js +212 -55
  35. package/lib/cjs/track-destination.js.map +1 -1
  36. package/lib/cjs/version.d.ts +1 -1
  37. package/lib/cjs/version.d.ts.map +1 -1
  38. package/lib/cjs/version.js +1 -1
  39. package/lib/cjs/version.js.map +1 -1
  40. package/lib/cjs/worker/index.js +1 -1
  41. package/lib/esm/beacon-transport.d.ts +2 -0
  42. package/lib/esm/beacon-transport.d.ts.map +1 -1
  43. package/lib/esm/beacon-transport.js +39 -1
  44. package/lib/esm/beacon-transport.js.map +1 -1
  45. package/lib/esm/config/joined-config.d.ts +1 -6
  46. package/lib/esm/config/joined-config.d.ts.map +1 -1
  47. package/lib/esm/config/joined-config.js +23 -64
  48. package/lib/esm/config/joined-config.js.map +1 -1
  49. package/lib/esm/config/local-config.d.ts +4 -6
  50. package/lib/esm/config/local-config.d.ts.map +1 -1
  51. package/lib/esm/config/local-config.js +4 -20
  52. package/lib/esm/config/local-config.js.map +1 -1
  53. package/lib/esm/config/types.d.ts +74 -19
  54. package/lib/esm/config/types.d.ts.map +1 -1
  55. package/lib/esm/config/types.js.map +1 -1
  56. package/lib/esm/index.d.ts +1 -0
  57. package/lib/esm/index.d.ts.map +1 -1
  58. package/lib/esm/index.js.map +1 -1
  59. package/lib/esm/plugins/url-tracking-plugin.d.ts +0 -13
  60. package/lib/esm/plugins/url-tracking-plugin.d.ts.map +1 -1
  61. package/lib/esm/plugins/url-tracking-plugin.js +2 -6
  62. package/lib/esm/plugins/url-tracking-plugin.js.map +1 -1
  63. package/lib/esm/session-replay.d.ts +0 -33
  64. package/lib/esm/session-replay.d.ts.map +1 -1
  65. package/lib/esm/session-replay.js +40 -335
  66. package/lib/esm/session-replay.js.map +1 -1
  67. package/lib/esm/targeting/targeting-manager.d.ts +1 -4
  68. package/lib/esm/targeting/targeting-manager.d.ts.map +1 -1
  69. package/lib/esm/targeting/targeting-manager.js +10 -56
  70. package/lib/esm/targeting/targeting-manager.js.map +1 -1
  71. package/lib/esm/track-destination.d.ts +5 -1
  72. package/lib/esm/track-destination.d.ts.map +1 -1
  73. package/lib/esm/track-destination.js +212 -55
  74. package/lib/esm/track-destination.js.map +1 -1
  75. package/lib/esm/version.d.ts +1 -1
  76. package/lib/esm/version.d.ts.map +1 -1
  77. package/lib/esm/version.js +1 -1
  78. package/lib/esm/version.js.map +1 -1
  79. package/lib/esm/worker/index.js +1 -1
  80. package/lib/scripts/index-min.js +1 -1
  81. package/lib/scripts/index-min.js.gz +0 -0
  82. package/lib/scripts/index-min.js.map +1 -1
  83. package/lib/scripts/observers-min.js +1 -1
  84. package/lib/scripts/observers-min.js.gz +0 -0
  85. package/lib/scripts/session-replay-browser-min.js +1 -1
  86. package/lib/scripts/session-replay-browser-min.js.gz +0 -0
  87. package/lib/scripts/session-replay-browser-min.js.map +1 -1
  88. package/lib/scripts/targeting-min.js +1 -1
  89. package/lib/scripts/targeting-min.js.gz +0 -0
  90. package/lib/scripts/worker-min.js +1 -1
  91. package/lib/scripts/worker-min.js.gz +0 -0
  92. package/package.json +4 -4
  93. package/lib/cjs/diagnostics.d.ts +0 -50
  94. package/lib/cjs/diagnostics.d.ts.map +0 -1
  95. package/lib/cjs/diagnostics.js +0 -67
  96. package/lib/cjs/diagnostics.js.map +0 -1
  97. package/lib/esm/diagnostics.d.ts +0 -50
  98. package/lib/esm/diagnostics.d.ts.map +0 -1
  99. package/lib/esm/diagnostics.js +0 -64
  100. package/lib/esm/diagnostics.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { Config, Logger, FetchTransport, LogLevel, IDiagnosticsClient } from '@amplitude/analytics-core';
1
+ import { Config, Logger, FetchTransport, LogLevel } from '@amplitude/analytics-core';
2
2
  import { SessionReplayOptions, StoreType } from '../typings/session-replay';
3
- import { SessionReplayLocalConfig as ISessionReplayLocalConfig, CrossOriginIframesConfig, FlushIntervalConfig, InteractionConfig, PrivacyConfig, SessionReplayPerformanceConfig, SessionReplayVersion } from './types';
3
+ import { SessionReplayLocalConfig as ISessionReplayLocalConfig, CrossOriginIframesConfig, FlushIntervalConfig, InteractionConfig, PrivacyConfig, SessionReplayPerformanceConfig, SessionReplayVersion, SessionReplaySendEventsHandler, SessionReplayFetchConfigHandler } from './types';
4
4
  export declare const getDefaultConfig: () => {
5
5
  flushMaxRetries: number;
6
6
  logLevel: LogLevel;
@@ -34,10 +34,8 @@ export declare class SessionReplayLocalConfig extends Config implements ISession
34
34
  captureFullSnapshotOnFocus?: boolean;
35
35
  maxPersistedEventsSizeBytes?: number;
36
36
  maxSingleEventSizeBytes?: number;
37
- diagnosticsClient?: IDiagnosticsClient;
38
- diagnosticsEnabled?: boolean;
39
- diagnosticsSampleRate?: number;
37
+ handleSendEvents?: SessionReplaySendEventsHandler;
38
+ handleFetchConfig?: SessionReplayFetchConfigHandler;
40
39
  constructor(apiKey: string, options: SessionReplayOptions);
41
- private createStandaloneDiagnosticsClient;
42
40
  }
43
41
  //# sourceMappingURL=local-config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"local-config.d.ts","sourceRoot":"","sources":["../../../src/config/local-config.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,MAAM,EAEN,MAAM,EACN,cAAc,EACd,QAAQ,EACR,kBAAkB,EAEnB,MAAM,2BAA2B,CAAC;AAYnC,OAAO,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAC5E,OAAO,EACL,wBAAwB,IAAI,yBAAyB,EACrD,wBAAwB,EACxB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,EACb,8BAA8B,EAC9B,oBAAoB,EACrB,MAAM,SAAS,CAAC;AAIjB,eAAO,MAAM,gBAAgB;;;;;CAK3B,CAAC;AAEH,qBAAa,wBAAyB,SAAQ,MAAO,YAAW,yBAAyB;IACvF,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,iBAAiB,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,OAAO,CAAC;IACrC,2BAA2B,CAAC,EAAE,MAAM,CAAC;IACrC,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,gBAAgB,CAAC,EAAE,8BAA8B,CAAC;IAClD,iBAAiB,CAAC,EAAE,+BAA+B,CAAC;gBAExC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,oBAAoB;CAmG1D"}
@@ -17,7 +17,7 @@ var SessionReplayLocalConfig = /** @class */ (function (_super) {
17
17
  tslib_1.__extends(SessionReplayLocalConfig, _super);
18
18
  function SessionReplayLocalConfig(apiKey, options) {
19
19
  var _this = this;
20
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
20
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
21
21
  var defaultConfig = (0, exports.getDefaultConfig)();
22
22
  _this = _super.call(this, tslib_1.__assign(tslib_1.__assign({ transportProvider: defaultConfig.transportProvider, loggerProvider: new logger_1.SafeLoggerProvider(options.loggerProvider || defaultConfig.loggerProvider) }, options), { apiKey: apiKey })) || this;
23
23
  _this.flushMaxRetries =
@@ -91,26 +91,10 @@ var SessionReplayLocalConfig = /** @class */ (function (_super) {
91
91
  maxIntervalMs: constants_1.DEFAULT_FLUSH_MAX_INTERVAL_MS,
92
92
  };
93
93
  }
94
- _this.diagnosticsEnabled = options.diagnosticsEnabled;
95
- _this.diagnosticsSampleRate = options.diagnosticsSampleRate;
96
- // Single diagnostics client: in plugin mode the analytics SDK passes its own client in
97
- // (reused, not duplicated). Standalone SR has no analytics SDK, so create one here — but only
98
- // when explicitly opted in, to avoid imposing IndexedDB + flush-timer overhead on standalone
99
- // users who don't want diagnostics.
100
- _this.diagnosticsClient = (_q = options.diagnosticsClient) !== null && _q !== void 0 ? _q : _this.createStandaloneDiagnosticsClient(apiKey, options);
94
+ _this.handleSendEvents = options.handleSendEvents;
95
+ _this.handleFetchConfig = options.handleFetchConfig;
101
96
  return _this;
102
97
  }
103
- SessionReplayLocalConfig.prototype.createStandaloneDiagnosticsClient = function (apiKey, options) {
104
- var diagnosticsEnabled = options.diagnosticsEnabled, diagnosticsSampleRate = options.diagnosticsSampleRate;
105
- var optedIn = diagnosticsEnabled === true || (typeof diagnosticsSampleRate === 'number' && diagnosticsSampleRate > 0);
106
- if (!optedIn) {
107
- return undefined;
108
- }
109
- return new analytics_core_1.DiagnosticsClient(apiKey, this.loggerProvider, this.serverZone, {
110
- enabled: diagnosticsEnabled !== null && diagnosticsEnabled !== void 0 ? diagnosticsEnabled : true,
111
- sampleRate: diagnosticsSampleRate !== null && diagnosticsSampleRate !== void 0 ? diagnosticsSampleRate : 0,
112
- });
113
- };
114
98
  return SessionReplayLocalConfig;
115
99
  }(analytics_core_1.Config));
116
100
  exports.SessionReplayLocalConfig = SessionReplayLocalConfig;
@@ -1 +1 @@
1
- {"version":3,"file":"local-config.js","sourceRoot":"","sources":["../../../src/config/local-config.ts"],"names":[],"mappings":";;;;AAAA,4DAQmC;AACnC,0CAUsB;AAWtB,oCAA+C;AAC/C,sCAAoD;AAE7C,IAAM,gBAAgB,GAAG,cAAM,OAAA,CAAC;IACrC,eAAe,EAAE,CAAC;IAClB,QAAQ,EAAE,yBAAQ,CAAC,IAAI;IACvB,cAAc,EAAE,IAAI,uBAAM,EAAE;IAC5B,iBAAiB,EAAE,IAAI,+BAAc,EAAE;CACxC,CAAC,EALoC,CAKpC,CAAC;AALU,QAAA,gBAAgB,oBAK1B;AAEH;IAA8C,oDAAM;IA+BlD,kCAAY,MAAc,EAAE,OAA6B;QAAzD,iBAuGC;;QAtGC,IAAM,aAAa,GAAG,IAAA,wBAAgB,GAAE,CAAC;gBACzC,sDACE,iBAAiB,EAAE,aAAa,CAAC,iBAAiB,EAClD,cAAc,EAAE,IAAI,2BAAkB,CAAC,OAAO,CAAC,cAAc,IAAI,aAAa,CAAC,cAAc,CAAC,IAC3F,OAAO,KACV,MAAM,QAAA,IACN;QACF,KAAI,CAAC,eAAe;YAClB,OAA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AC,aAAa,KAAK,SAAS,IAAI,SAAS,CAAC,aAAa,KAAK,SAAS,EAAE;QAClF,IAAM,YAAY,GAAG,MAAA,SAAS,CAAC,aAAa,mCAAI,wBAAY,CAAC;QAC7D,IAAM,YAAY,GAAG,MAAA,SAAS,CAAC,aAAa,mCAAI,wBAAY,CAAC;QAC7D,IAAI,YAAY,GAAG,YAAY,EAAE;YAC/B,IAAI,SAAS,CAAC,aAAa,KAAK,SAAS,EAAE;gBACzC,cAAc,CAAC,IAAI,CACjB,6CAAsC,YAAY,kDAAwC,wBAAY,iCAA8B,CACrI,CAAC;gBACF,SAAS,CAAC,aAAa,GAAG,YAAY,CAAC;aACxC;iBAAM,IAAI,SAAS,CAAC,aAAa,KAAK,SAAS,EAAE;gBAChD,cAAc,CAAC,IAAI,CACjB,6CAAsC,YAAY,mDAAyC,wBAAY,kCAA+B,CACvI,CAAC;gBACF,SAAS,CAAC,aAAa,GAAG,YAAY,CAAC;aACxC;iBAAM;gBACL,cAAc,CAAC,IAAI,CACjB,6CAAsC,SAAS,CAAC,aAAa,2CAAiC,SAAS,CAAC,aAAa,iCAA8B,CACpJ,CAAC;gBACF,SAAS,CAAC,aAAa,GAAG,SAAS,CAAC,aAAa,CAAC;aACnD;SACF;KACF;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import {\n Config,\n ILogger,\n Logger,\n FetchTransport,\n LogLevel,\n IDiagnosticsClient,\n DiagnosticsClient,\n} from '@amplitude/analytics-core';\nimport {\n DEFAULT_FLUSH_MAX_INTERVAL_MS,\n DEFAULT_FLUSH_MIN_INTERVAL_MS,\n DEFAULT_PERFORMANCE_CONFIG,\n DEFAULT_SAMPLE_RATE,\n DEFAULT_SERVER_ZONE,\n DEFAULT_URL_CHANGE_POLLING_INTERVAL,\n MAX_INTERVAL,\n MIN_INTERVAL,\n UNMASK_TEXT_CLASS,\n} from '../constants';\nimport { SessionReplayOptions, StoreType } from '../typings/session-replay';\nimport {\n SessionReplayLocalConfig as ISessionReplayLocalConfig,\n CrossOriginIframesConfig,\n FlushIntervalConfig,\n InteractionConfig,\n PrivacyConfig,\n SessionReplayPerformanceConfig,\n SessionReplayVersion,\n} from './types';\nimport { SafeLoggerProvider } from '../logger';\nimport { validateUGCFilterRules } from '../helpers';\n\nexport const getDefaultConfig = () => ({\n flushMaxRetries: 2,\n logLevel: LogLevel.Warn,\n loggerProvider: new Logger(),\n transportProvider: new FetchTransport(),\n});\n\nexport class SessionReplayLocalConfig extends Config implements ISessionReplayLocalConfig {\n apiKey: string;\n sampleRate: number;\n privacyConfig?: PrivacyConfig;\n interactionConfig?: InteractionConfig;\n debugMode?: boolean;\n configServerUrl?: string;\n trackServerUrl?: string;\n shouldInlineStylesheet?: boolean;\n version?: SessionReplayVersion;\n storeType: StoreType;\n performanceConfig?: SessionReplayPerformanceConfig;\n useWebWorker?: boolean;\n enableTransportCompression?: boolean;\n sendTimeoutMs?: number;\n applyBackgroundColorToBlockedElements?: boolean;\n enableUrlChangePolling?: boolean;\n urlChangePollingInterval?: number;\n captureDocumentTitle?: boolean;\n captureAdoptedStyleSheets?: boolean;\n crossOriginIframes?: CrossOriginIframesConfig;\n fullSnapshotIntervalMs?: number;\n flushIntervalConfig?: FlushIntervalConfig;\n eagerFullSnapshotSend?: boolean;\n captureFullSnapshotOnFocus?: boolean;\n maxPersistedEventsSizeBytes?: number;\n maxSingleEventSizeBytes?: number;\n diagnosticsClient?: IDiagnosticsClient;\n diagnosticsEnabled?: boolean;\n diagnosticsSampleRate?: number;\n\n constructor(apiKey: string, options: SessionReplayOptions) {\n const defaultConfig = getDefaultConfig();\n super({\n transportProvider: defaultConfig.transportProvider,\n loggerProvider: new SafeLoggerProvider(options.loggerProvider || defaultConfig.loggerProvider),\n ...options,\n apiKey,\n });\n this.flushMaxRetries =\n options.flushMaxRetries !== undefined && options.flushMaxRetries <= defaultConfig.flushMaxRetries\n ? options.flushMaxRetries\n : defaultConfig.flushMaxRetries;\n\n this.apiKey = apiKey;\n this.sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE;\n this.serverZone = options.serverZone || DEFAULT_SERVER_ZONE;\n this.configServerUrl = options.configServerUrl;\n this.trackServerUrl = options.trackServerUrl;\n this.shouldInlineStylesheet = options.shouldInlineStylesheet;\n this.version = options.version;\n this.performanceConfig = options.performanceConfig || DEFAULT_PERFORMANCE_CONFIG;\n this.storeType = options.storeType ?? 'memory';\n this.applyBackgroundColorToBlockedElements = options.applyBackgroundColorToBlockedElements ?? false;\n this.enableUrlChangePolling = options.enableUrlChangePolling ?? false;\n this.urlChangePollingInterval = options.urlChangePollingInterval ?? DEFAULT_URL_CHANGE_POLLING_INTERVAL;\n this.captureDocumentTitle = options.captureDocumentTitle ?? false;\n if (options.fullSnapshotIntervalMs !== undefined) {\n this.fullSnapshotIntervalMs = options.fullSnapshotIntervalMs;\n }\n if (options.eagerFullSnapshotSend !== undefined) {\n this.eagerFullSnapshotSend = options.eagerFullSnapshotSend;\n }\n // Defaults to false per the validated amp-on-amp perf config (SR-4646): the on-focus full\n // snapshot is off unless the consumer explicitly opts in. focusListener honors this by\n // skipping the snapshot whenever the value is not true.\n this.captureFullSnapshotOnFocus = options.captureFullSnapshotOnFocus ?? false;\n if (options.maxPersistedEventsSizeBytes !== undefined) {\n this.maxPersistedEventsSizeBytes = sanitizeByteSize(\n options.maxPersistedEventsSizeBytes,\n MIN_EVENT_BYTE_SIZE,\n MAX_PERSISTED_EVENTS_SIZE_CEILING,\n 'maxPersistedEventsSizeBytes',\n this.loggerProvider,\n );\n }\n if (options.maxSingleEventSizeBytes !== undefined) {\n this.maxSingleEventSizeBytes = sanitizeByteSize(\n options.maxSingleEventSizeBytes,\n MIN_EVENT_BYTE_SIZE,\n MAX_SINGLE_EVENT_SIZE_CEILING,\n 'maxSingleEventSizeBytes',\n this.loggerProvider,\n );\n }\n\n // Auto-include .amp-unmask as a default unmaskSelector entry so it works\n // symmetrically with amp-mask/amp-block without requiring explicit config (SR-2945).\n this.privacyConfig = {\n ...(options.privacyConfig ?? {}),\n unmaskSelector: Array.from(new Set([`.${UNMASK_TEXT_CLASS}`, ...(options.privacyConfig?.unmaskSelector ?? [])])),\n };\n if (options.interactionConfig) {\n this.interactionConfig = options.interactionConfig;\n\n // validate ugcFilterRules, throw error if invalid - throw error at the beginning of the config\n if (this.interactionConfig.ugcFilterRules) {\n validateUGCFilterRules(this.interactionConfig.ugcFilterRules);\n }\n }\n if (options.debugMode) {\n this.debugMode = options.debugMode;\n }\n // Support both new useWebWorker and legacy experimental.useWebWorker for backwards\n // compatibility. Defaults to true per the validated amp-on-amp perf config (SR-4646):\n // compression runs off the main thread unless the consumer explicitly sets either flag\n // to false. The top-level option wins over the legacy experimental one when both are set.\n const legacyOptions = options as { experimental?: { useWebWorker?: boolean } };\n this.useWebWorker = options.useWebWorker ?? legacyOptions.experimental?.useWebWorker ?? true;\n this.enableTransportCompression = options.enableTransportCompression ?? true;\n // Pass through undefined so the track destination applies its SEND_TIMEOUT_MS default;\n // an explicit 0 is preserved (disables the timeout).\n this.sendTimeoutMs = options.sendTimeoutMs;\n this.captureAdoptedStyleSheets = options.captureAdoptedStyleSheets ?? true;\n if (options.crossOriginIframes) {\n this.crossOriginIframes = options.crossOriginIframes;\n }\n if (options.flushIntervalConfig) {\n this.flushIntervalConfig = sanitizeFlushIntervalConfig(options.flushIntervalConfig, this.loggerProvider);\n } else {\n // Default to the validated amp-on-amp perf config (SR-4646). The values are known-valid\n // (min <= max, both above the floor), so no sanitization is required.\n this.flushIntervalConfig = {\n minIntervalMs: DEFAULT_FLUSH_MIN_INTERVAL_MS,\n maxIntervalMs: DEFAULT_FLUSH_MAX_INTERVAL_MS,\n };\n }\n this.diagnosticsEnabled = options.diagnosticsEnabled;\n this.diagnosticsSampleRate = options.diagnosticsSampleRate;\n // Single diagnostics client: in plugin mode the analytics SDK passes its own client in\n // (reused, not duplicated). Standalone SR has no analytics SDK, so create one here — but only\n // when explicitly opted in, to avoid imposing IndexedDB + flush-timer overhead on standalone\n // users who don't want diagnostics.\n this.diagnosticsClient = options.diagnosticsClient ?? this.createStandaloneDiagnosticsClient(apiKey, options);\n }\n\n private createStandaloneDiagnosticsClient(\n apiKey: string,\n options: SessionReplayOptions,\n ): IDiagnosticsClient | undefined {\n const { diagnosticsEnabled, diagnosticsSampleRate } = options;\n const optedIn =\n diagnosticsEnabled === true || (typeof diagnosticsSampleRate === 'number' && diagnosticsSampleRate > 0);\n if (!optedIn) {\n return undefined;\n }\n return new DiagnosticsClient(apiKey, this.loggerProvider, this.serverZone, {\n enabled: diagnosticsEnabled ?? true,\n sampleRate: diagnosticsSampleRate ?? 0,\n });\n }\n}\n\n// 100ms floor avoids degenerate configs (0/negative) that would split on every event.\n// Customers wanting fewer requests should be raising the value, not lowering it; the floor\n// is just a defensive guard against typos and unsigned-int rollovers.\nconst MIN_FLUSH_INTERVAL_FLOOR_MS = 100;\n\n// Shared 1 KB floor for the byte-size overrides — small enough to exercise splitting/drops\n// while debugging, large enough to avoid a 0/negative config that splits on every event.\nconst MIN_EVENT_BYTE_SIZE = 1_000;\n// Batch cap ceiling: stay under the SR ingest service's 10 MB decompressed split threshold\n// (above which the server splits the batch itself) with headroom for the request wrapper.\nconst MAX_PERSISTED_EVENTS_SIZE_CEILING = 8_000_000;\n// Single-event ceiling: the server rejects a single event above ~10 MB, so never allow an\n// override to exceed that.\nconst MAX_SINGLE_EVENT_SIZE_CEILING = 10_000_000;\n\n// Defensive bounds for the byte-size overrides. Non-finite inputs are ignored (fall back to\n// the SDK default); out-of-range values are clamped and logged so a typo can't silently\n// disable splitting or push past the server's limits.\nfunction sanitizeByteSize(\n raw: number,\n min: number,\n max: number,\n name: string,\n loggerProvider: ILogger,\n): number | undefined {\n if (!Number.isFinite(raw)) {\n loggerProvider.warn(`${name} value is not a finite number (got ${String(raw)}); ignoring.`);\n return undefined;\n }\n if (raw < min) {\n loggerProvider.warn(`${name} ${raw} is below floor ${min}; clamping.`);\n return min;\n }\n if (raw > max) {\n loggerProvider.warn(`${name} ${raw} exceeds ceiling ${max}; clamping.`);\n return max;\n }\n return raw;\n}\n\nfunction sanitizeFlushIntervalConfig(raw: FlushIntervalConfig, loggerProvider: ILogger): FlushIntervalConfig {\n const sanitized: FlushIntervalConfig = {};\n if (raw.minIntervalMs !== undefined) {\n if (!Number.isFinite(raw.minIntervalMs) || raw.minIntervalMs < MIN_FLUSH_INTERVAL_FLOOR_MS) {\n loggerProvider.warn(\n `flushIntervalConfig.minIntervalMs ${raw.minIntervalMs} is below floor ${MIN_FLUSH_INTERVAL_FLOOR_MS}ms; clamping.`,\n );\n sanitized.minIntervalMs = MIN_FLUSH_INTERVAL_FLOOR_MS;\n } else {\n sanitized.minIntervalMs = raw.minIntervalMs;\n }\n }\n if (raw.maxIntervalMs !== undefined) {\n // Unlike min, `Infinity` is a meaningful value here: it means \"no upper bound on interval\n // growth\" (Math.min(Infinity, x) === x in BaseEventsStore.shouldSplitEventsList). Reject\n // only NaN and sub-floor values; pass Infinity through.\n if (Number.isNaN(raw.maxIntervalMs) || raw.maxIntervalMs < MIN_FLUSH_INTERVAL_FLOOR_MS) {\n loggerProvider.warn(\n `flushIntervalConfig.maxIntervalMs ${raw.maxIntervalMs} is below floor ${MIN_FLUSH_INTERVAL_FLOOR_MS}ms; clamping.`,\n );\n sanitized.maxIntervalMs = MIN_FLUSH_INTERVAL_FLOOR_MS;\n } else {\n sanitized.maxIntervalMs = raw.maxIntervalMs;\n }\n }\n // Cross-validate against the SDK's effective defaults so that a partial config (only one of\n // {minIntervalMs, maxIntervalMs}) doesn't get silently clamped by the unspecified default.\n // Concrete failure mode without this: customer sets only `minIntervalMs: 30_000`, the store's\n // `maxInterval` falls back to `MAX_INTERVAL = 10_000`, and `shouldSplitEventsList` then\n // caps the effective interval at 10s — silently negating the customer's tune-up.\n // The user-supplied value always wins; we fill in the other side to match.\n if (sanitized.minIntervalMs !== undefined || sanitized.maxIntervalMs !== undefined) {\n const effectiveMin = sanitized.minIntervalMs ?? MIN_INTERVAL;\n const effectiveMax = sanitized.maxIntervalMs ?? MAX_INTERVAL;\n if (effectiveMax < effectiveMin) {\n if (sanitized.maxIntervalMs === undefined) {\n loggerProvider.warn(\n `flushIntervalConfig.minIntervalMs (${effectiveMin}) exceeds the default maxIntervalMs (${MAX_INTERVAL}); raising max to match min.`,\n );\n sanitized.maxIntervalMs = effectiveMin;\n } else if (sanitized.minIntervalMs === undefined) {\n loggerProvider.warn(\n `flushIntervalConfig.maxIntervalMs (${effectiveMax}) is below the default minIntervalMs (${MIN_INTERVAL}); lowering min to match max.`,\n );\n sanitized.minIntervalMs = effectiveMax;\n } else {\n loggerProvider.warn(\n `flushIntervalConfig.maxIntervalMs (${sanitized.maxIntervalMs}) is less than minIntervalMs (${sanitized.minIntervalMs}); raising max to match min.`,\n );\n sanitized.maxIntervalMs = sanitized.minIntervalMs;\n }\n }\n }\n return sanitized;\n}\n"]}
1
+ {"version":3,"file":"local-config.js","sourceRoot":"","sources":["../../../src/config/local-config.ts"],"names":[],"mappings":";;;;AAAA,4DAA8F;AAC9F,0CAUsB;AAatB,oCAA+C;AAC/C,sCAAoD;AAE7C,IAAM,gBAAgB,GAAG,cAAM,OAAA,CAAC;IACrC,eAAe,EAAE,CAAC;IAClB,QAAQ,EAAE,yBAAQ,CAAC,IAAI;IACvB,cAAc,EAAE,IAAI,uBAAM,EAAE;IAC5B,iBAAiB,EAAE,IAAI,+BAAc,EAAE;CACxC,CAAC,EALoC,CAKpC,CAAC;AALU,QAAA,gBAAgB,oBAK1B;AAEH;IAA8C,oDAAM;IA8BlD,kCAAY,MAAc,EAAE,OAA6B;QAAzD,iBAkGC;;QAjGC,IAAM,aAAa,GAAG,IAAA,wBAAgB,GAAE,CAAC;gBACzC,sDACE,iBAAiB,EAAE,aAAa,CAAC,iBAAiB,EAClD,cAAc,EAAE,IAAI,2BAAkB,CAAC,OAAO,CAAC,cAAc,IAAI,aAAa,CAAC,cAAc,CAAC,IAC3F,OAAO,KACV,MAAM,QAAA,IACN;QACF,K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AAa,GAAG,SAAS,CAAC,aAAa,CAAC;aACnD;SACF;KACF;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import { Config, ILogger, Logger, FetchTransport, LogLevel } from '@amplitude/analytics-core';\nimport {\n DEFAULT_FLUSH_MAX_INTERVAL_MS,\n DEFAULT_FLUSH_MIN_INTERVAL_MS,\n DEFAULT_PERFORMANCE_CONFIG,\n DEFAULT_SAMPLE_RATE,\n DEFAULT_SERVER_ZONE,\n DEFAULT_URL_CHANGE_POLLING_INTERVAL,\n MAX_INTERVAL,\n MIN_INTERVAL,\n UNMASK_TEXT_CLASS,\n} from '../constants';\nimport { SessionReplayOptions, StoreType } from '../typings/session-replay';\nimport {\n SessionReplayLocalConfig as ISessionReplayLocalConfig,\n CrossOriginIframesConfig,\n FlushIntervalConfig,\n InteractionConfig,\n PrivacyConfig,\n SessionReplayPerformanceConfig,\n SessionReplayVersion,\n SessionReplaySendEventsHandler,\n SessionReplayFetchConfigHandler,\n} from './types';\nimport { SafeLoggerProvider } from '../logger';\nimport { validateUGCFilterRules } from '../helpers';\n\nexport const getDefaultConfig = () => ({\n flushMaxRetries: 2,\n logLevel: LogLevel.Warn,\n loggerProvider: new Logger(),\n transportProvider: new FetchTransport(),\n});\n\nexport class SessionReplayLocalConfig extends Config implements ISessionReplayLocalConfig {\n apiKey: string;\n sampleRate: number;\n privacyConfig?: PrivacyConfig;\n interactionConfig?: InteractionConfig;\n debugMode?: boolean;\n configServerUrl?: string;\n trackServerUrl?: string;\n shouldInlineStylesheet?: boolean;\n version?: SessionReplayVersion;\n storeType: StoreType;\n performanceConfig?: SessionReplayPerformanceConfig;\n useWebWorker?: boolean;\n enableTransportCompression?: boolean;\n sendTimeoutMs?: number;\n applyBackgroundColorToBlockedElements?: boolean;\n enableUrlChangePolling?: boolean;\n urlChangePollingInterval?: number;\n captureDocumentTitle?: boolean;\n captureAdoptedStyleSheets?: boolean;\n crossOriginIframes?: CrossOriginIframesConfig;\n fullSnapshotIntervalMs?: number;\n flushIntervalConfig?: FlushIntervalConfig;\n eagerFullSnapshotSend?: boolean;\n captureFullSnapshotOnFocus?: boolean;\n maxPersistedEventsSizeBytes?: number;\n maxSingleEventSizeBytes?: number;\n handleSendEvents?: SessionReplaySendEventsHandler;\n handleFetchConfig?: SessionReplayFetchConfigHandler;\n\n constructor(apiKey: string, options: SessionReplayOptions) {\n const defaultConfig = getDefaultConfig();\n super({\n transportProvider: defaultConfig.transportProvider,\n loggerProvider: new SafeLoggerProvider(options.loggerProvider || defaultConfig.loggerProvider),\n ...options,\n apiKey,\n });\n this.flushMaxRetries =\n options.flushMaxRetries !== undefined && options.flushMaxRetries <= defaultConfig.flushMaxRetries\n ? options.flushMaxRetries\n : defaultConfig.flushMaxRetries;\n\n this.apiKey = apiKey;\n this.sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE;\n this.serverZone = options.serverZone || DEFAULT_SERVER_ZONE;\n this.configServerUrl = options.configServerUrl;\n this.trackServerUrl = options.trackServerUrl;\n this.shouldInlineStylesheet = options.shouldInlineStylesheet;\n this.version = options.version;\n this.performanceConfig = options.performanceConfig || DEFAULT_PERFORMANCE_CONFIG;\n this.storeType = options.storeType ?? 'memory';\n this.applyBackgroundColorToBlockedElements = options.applyBackgroundColorToBlockedElements ?? false;\n this.enableUrlChangePolling = options.enableUrlChangePolling ?? false;\n this.urlChangePollingInterval = options.urlChangePollingInterval ?? DEFAULT_URL_CHANGE_POLLING_INTERVAL;\n this.captureDocumentTitle = options.captureDocumentTitle ?? false;\n if (options.fullSnapshotIntervalMs !== undefined) {\n this.fullSnapshotIntervalMs = options.fullSnapshotIntervalMs;\n }\n if (options.eagerFullSnapshotSend !== undefined) {\n this.eagerFullSnapshotSend = options.eagerFullSnapshotSend;\n }\n // Defaults to false per the validated amp-on-amp perf config (SR-4646): the on-focus full\n // snapshot is off unless the consumer explicitly opts in. focusListener honors this by\n // skipping the snapshot whenever the value is not true.\n this.captureFullSnapshotOnFocus = options.captureFullSnapshotOnFocus ?? false;\n if (options.maxPersistedEventsSizeBytes !== undefined) {\n this.maxPersistedEventsSizeBytes = sanitizeByteSize(\n options.maxPersistedEventsSizeBytes,\n MIN_EVENT_BYTE_SIZE,\n MAX_PERSISTED_EVENTS_SIZE_CEILING,\n 'maxPersistedEventsSizeBytes',\n this.loggerProvider,\n );\n }\n if (options.maxSingleEventSizeBytes !== undefined) {\n this.maxSingleEventSizeBytes = sanitizeByteSize(\n options.maxSingleEventSizeBytes,\n MIN_EVENT_BYTE_SIZE,\n MAX_SINGLE_EVENT_SIZE_CEILING,\n 'maxSingleEventSizeBytes',\n this.loggerProvider,\n );\n }\n\n // Auto-include .amp-unmask as a default unmaskSelector entry so it works\n // symmetrically with amp-mask/amp-block without requiring explicit config (SR-2945).\n this.privacyConfig = {\n ...(options.privacyConfig ?? {}),\n unmaskSelector: Array.from(new Set([`.${UNMASK_TEXT_CLASS}`, ...(options.privacyConfig?.unmaskSelector ?? [])])),\n };\n if (options.interactionConfig) {\n this.interactionConfig = options.interactionConfig;\n\n // validate ugcFilterRules, throw error if invalid - throw error at the beginning of the config\n if (this.interactionConfig.ugcFilterRules) {\n validateUGCFilterRules(this.interactionConfig.ugcFilterRules);\n }\n }\n if (options.debugMode) {\n this.debugMode = options.debugMode;\n }\n // Support both new useWebWorker and legacy experimental.useWebWorker for backwards\n // compatibility. Defaults to true per the validated amp-on-amp perf config (SR-4646):\n // compression runs off the main thread unless the consumer explicitly sets either flag\n // to false. The top-level option wins over the legacy experimental one when both are set.\n const legacyOptions = options as { experimental?: { useWebWorker?: boolean } };\n this.useWebWorker = options.useWebWorker ?? legacyOptions.experimental?.useWebWorker ?? true;\n this.enableTransportCompression = options.enableTransportCompression ?? true;\n // Pass through undefined so the track destination applies its SEND_TIMEOUT_MS default;\n // an explicit 0 is preserved (disables the timeout).\n this.sendTimeoutMs = options.sendTimeoutMs;\n this.captureAdoptedStyleSheets = options.captureAdoptedStyleSheets ?? true;\n if (options.crossOriginIframes) {\n this.crossOriginIframes = options.crossOriginIframes;\n }\n if (options.flushIntervalConfig) {\n this.flushIntervalConfig = sanitizeFlushIntervalConfig(options.flushIntervalConfig, this.loggerProvider);\n } else {\n // Default to the validated amp-on-amp perf config (SR-4646). The values are known-valid\n // (min <= max, both above the floor), so no sanitization is required.\n this.flushIntervalConfig = {\n minIntervalMs: DEFAULT_FLUSH_MIN_INTERVAL_MS,\n maxIntervalMs: DEFAULT_FLUSH_MAX_INTERVAL_MS,\n };\n }\n this.handleSendEvents = options.handleSendEvents;\n this.handleFetchConfig = options.handleFetchConfig;\n }\n}\n\n// 100ms floor avoids degenerate configs (0/negative) that would split on every event.\n// Customers wanting fewer requests should be raising the value, not lowering it; the floor\n// is just a defensive guard against typos and unsigned-int rollovers.\nconst MIN_FLUSH_INTERVAL_FLOOR_MS = 100;\n\n// Shared 1 KB floor for the byte-size overrides — small enough to exercise splitting/drops\n// while debugging, large enough to avoid a 0/negative config that splits on every event.\nconst MIN_EVENT_BYTE_SIZE = 1_000;\n// Batch cap ceiling: stay under the SR ingest service's 10 MB decompressed split threshold\n// (above which the server splits the batch itself) with headroom for the request wrapper.\nconst MAX_PERSISTED_EVENTS_SIZE_CEILING = 8_000_000;\n// Single-event ceiling: the server rejects a single event above ~10 MB, so never allow an\n// override to exceed that.\nconst MAX_SINGLE_EVENT_SIZE_CEILING = 10_000_000;\n\n// Defensive bounds for the byte-size overrides. Non-finite inputs are ignored (fall back to\n// the SDK default); out-of-range values are clamped and logged so a typo can't silently\n// disable splitting or push past the server's limits.\nfunction sanitizeByteSize(\n raw: number,\n min: number,\n max: number,\n name: string,\n loggerProvider: ILogger,\n): number | undefined {\n if (!Number.isFinite(raw)) {\n loggerProvider.warn(`${name} value is not a finite number (got ${String(raw)}); ignoring.`);\n return undefined;\n }\n if (raw < min) {\n loggerProvider.warn(`${name} ${raw} is below floor ${min}; clamping.`);\n return min;\n }\n if (raw > max) {\n loggerProvider.warn(`${name} ${raw} exceeds ceiling ${max}; clamping.`);\n return max;\n }\n return raw;\n}\n\nfunction sanitizeFlushIntervalConfig(raw: FlushIntervalConfig, loggerProvider: ILogger): FlushIntervalConfig {\n const sanitized: FlushIntervalConfig = {};\n if (raw.minIntervalMs !== undefined) {\n if (!Number.isFinite(raw.minIntervalMs) || raw.minIntervalMs < MIN_FLUSH_INTERVAL_FLOOR_MS) {\n loggerProvider.warn(\n `flushIntervalConfig.minIntervalMs ${raw.minIntervalMs} is below floor ${MIN_FLUSH_INTERVAL_FLOOR_MS}ms; clamping.`,\n );\n sanitized.minIntervalMs = MIN_FLUSH_INTERVAL_FLOOR_MS;\n } else {\n sanitized.minIntervalMs = raw.minIntervalMs;\n }\n }\n if (raw.maxIntervalMs !== undefined) {\n // Unlike min, `Infinity` is a meaningful value here: it means \"no upper bound on interval\n // growth\" (Math.min(Infinity, x) === x in BaseEventsStore.shouldSplitEventsList). Reject\n // only NaN and sub-floor values; pass Infinity through.\n if (Number.isNaN(raw.maxIntervalMs) || raw.maxIntervalMs < MIN_FLUSH_INTERVAL_FLOOR_MS) {\n loggerProvider.warn(\n `flushIntervalConfig.maxIntervalMs ${raw.maxIntervalMs} is below floor ${MIN_FLUSH_INTERVAL_FLOOR_MS}ms; clamping.`,\n );\n sanitized.maxIntervalMs = MIN_FLUSH_INTERVAL_FLOOR_MS;\n } else {\n sanitized.maxIntervalMs = raw.maxIntervalMs;\n }\n }\n // Cross-validate against the SDK's effective defaults so that a partial config (only one of\n // {minIntervalMs, maxIntervalMs}) doesn't get silently clamped by the unspecified default.\n // Concrete failure mode without this: customer sets only `minIntervalMs: 30_000`, the store's\n // `maxInterval` falls back to `MAX_INTERVAL = 10_000`, and `shouldSplitEventsList` then\n // caps the effective interval at 10s — silently negating the customer's tune-up.\n // The user-supplied value always wins; we fill in the other side to match.\n if (sanitized.minIntervalMs !== undefined || sanitized.maxIntervalMs !== undefined) {\n const effectiveMin = sanitized.minIntervalMs ?? MIN_INTERVAL;\n const effectiveMax = sanitized.maxIntervalMs ?? MAX_INTERVAL;\n if (effectiveMax < effectiveMin) {\n if (sanitized.maxIntervalMs === undefined) {\n loggerProvider.warn(\n `flushIntervalConfig.minIntervalMs (${effectiveMin}) exceeds the default maxIntervalMs (${MAX_INTERVAL}); raising max to match min.`,\n );\n sanitized.maxIntervalMs = effectiveMin;\n } else if (sanitized.minIntervalMs === undefined) {\n loggerProvider.warn(\n `flushIntervalConfig.maxIntervalMs (${effectiveMax}) is below the default minIntervalMs (${MIN_INTERVAL}); lowering min to match max.`,\n );\n sanitized.minIntervalMs = effectiveMax;\n } else {\n loggerProvider.warn(\n `flushIntervalConfig.maxIntervalMs (${sanitized.maxIntervalMs}) is less than minIntervalMs (${sanitized.minIntervalMs}); raising max to match min.`,\n );\n sanitized.maxIntervalMs = sanitized.minIntervalMs;\n }\n }\n }\n return sanitized;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { IConfig, LogLevel, ILogger, IDiagnosticsClient } from '@amplitude/analytics-core';
1
+ import { IConfig, LogLevel, ILogger } from '@amplitude/analytics-core';
2
2
  import { StoreType, ConsoleLogLevel } from '../typings/session-replay';
3
3
  import { TargetingFlag } from '@amplitude/targeting';
4
4
  export interface SamplingConfig {
@@ -80,6 +80,64 @@ export type UGCFilterRule = {
80
80
  */
81
81
  replacement: string;
82
82
  };
83
+ /**
84
+ * The fully-formed request the SDK hands to a custom `handleSendEvents` transport when
85
+ * uploading recorded replay events. The callback's only job is to execute this request and
86
+ * return the resulting `Response`; the SDK owns batching, retry, serialization and error
87
+ * handling around it.
88
+ */
89
+ export interface SendEventsRequest {
90
+ /** The resolved track URL (respects `trackServerUrl`) including query params. */
91
+ url: string;
92
+ method: 'POST';
93
+ /**
94
+ * SDK-supplied default headers. When the body was gzipped, this includes
95
+ * `Content-Encoding: gzip` — drop it only if you also stop forwarding the gzipped body,
96
+ * otherwise the payload will not decode server-side.
97
+ */
98
+ headers: Record<string, string>;
99
+ /**
100
+ * The serialized payload, ready to send. A gzipped `Uint8Array` when transport compression
101
+ * is active, otherwise the raw JSON string. Forward it unchanged — do not re-serialize.
102
+ *
103
+ * Typed as `string | Uint8Array` (not the broader `BodyInit`) because the body must be
104
+ * structured-cloneable to cross `postMessage` in web-worker mode; `Blob`/`FormData`/
105
+ * `ReadableStream` are not, and the SDK never produces them here.
106
+ */
107
+ body: string | Uint8Array;
108
+ /**
109
+ * Whether the built-in path would set `keepalive` on this request. `true` for page-exit
110
+ * sends (so the request survives unload) and for small in-session batches. Forward it to
111
+ * your `fetch` call — i.e. `fetch(url, { method, headers, body, keepalive })` — so exit-time
112
+ * batches are not dropped when the page is tearing down.
113
+ */
114
+ keepalive: boolean;
115
+ }
116
+ /**
117
+ * The fully-formed request the SDK hands to a custom `handleFetchConfig` transport when
118
+ * fetching remote configuration.
119
+ */
120
+ export interface FetchConfigRequest {
121
+ /** The resolved config URL (respects `configServerUrl`) including query params. */
122
+ url: string;
123
+ method: 'GET';
124
+ /** SDK-supplied default headers. */
125
+ headers: Record<string, string>;
126
+ /** Abort signal the SDK uses to enforce the remote-config fetch timeout. Honor it in your fetch. */
127
+ signal?: AbortSignal;
128
+ }
129
+ /**
130
+ * Custom transport for replay event uploads. Invoked by the SDK in place of its internal
131
+ * `fetch`. Must return a `Response` (or Response-like with `ok`, `status`, `text()`). Called
132
+ * once per logical request attempt — retry is handled by the SDK around the callback, so do
133
+ * not implement your own retry. Thrown errors / rejected promises are surfaced to the SDK's
134
+ * existing retry logic.
135
+ */
136
+ export type SessionReplaySendEventsHandler = (request: SendEventsRequest) => Promise<Response>;
137
+ /**
138
+ * Custom transport for remote-config fetches. Same contract as {@link SessionReplaySendEventsHandler}.
139
+ */
140
+ export type SessionReplayFetchConfigHandler = (request: FetchConfigRequest) => Promise<Response>;
83
141
  export interface CrossOriginIframesConfig {
84
142
  enabled: boolean;
85
143
  /**
@@ -101,24 +159,6 @@ export interface CrossOriginIframesConfig {
101
159
  export interface SessionReplayLocalConfig extends IConfig {
102
160
  apiKey: string;
103
161
  loggerProvider: ILogger;
104
- /**
105
- * Optional diagnostics client used to ship SR decision/targeting telemetry to Amplitude's
106
- * diagnostics backend (independent of whether a replay is recorded). In plugin mode this is
107
- * forwarded from the analytics SDK's already-initialized client. No-op when absent or when
108
- * diagnostics is not sampled in. See DiagnosticsClient in @amplitude/analytics-core.
109
- */
110
- diagnosticsClient?: IDiagnosticsClient;
111
- /**
112
- * Standalone SR only: when no `diagnosticsClient` is provided (i.e. SR is not running as the
113
- * analytics plugin), opt in to having SR create its own client so TRC/recording diagnostics are
114
- * still shipped. Ignored when a `diagnosticsClient` is supplied. @defaultValue false
115
- */
116
- diagnosticsEnabled?: boolean;
117
- /**
118
- * Standalone SR only: sample rate (0..1) for the diagnostics client SR creates when none is
119
- * provided. A positive value also implies opting in. @defaultValue 0
120
- */
121
- diagnosticsSampleRate?: number;
122
162
  /**
123
163
  * LogLevel.None or LogLevel.Error or LogLevel.Warn or LogLevel.Verbose or LogLevel.Debug.
124
164
  * Sets the log level.
@@ -348,6 +388,21 @@ export interface SessionReplayLocalConfig extends IConfig {
348
388
  * @defaultValue 9000000
349
389
  */
350
390
  maxSingleEventSizeBytes?: number;
391
+ /**
392
+ * Optional custom transport for replay event uploads. When provided, the SDK invokes this
393
+ * callback in place of its internal `fetch` for every event-upload attempt, passing a
394
+ * fully-formed {@link SendEventsRequest} (resolved URL, headers, serialized body). The SDK
395
+ * still owns batching, retry, serialization and error handling. Use it to attach custom
396
+ * auth (e.g. a JWT `Authorization` header) and route through an authenticated proxy.
397
+ *
398
+ * Works alongside `trackServerUrl`: the URL passed to the callback already respects it.
399
+ */
400
+ handleSendEvents?: SessionReplaySendEventsHandler;
401
+ /**
402
+ * Optional custom transport for the remote-config fetch. Same contract as `handleSendEvents`
403
+ * but for the config GET. The URL passed to the callback already respects `configServerUrl`.
404
+ */
405
+ handleFetchConfig?: SessionReplayFetchConfigHandler;
351
406
  }
352
407
  export interface FlushIntervalConfig {
353
408
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":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;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,oBAAoB,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1C;AAED,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,iBAAiB,CAAC;CACzB;AAED;;GAEG;AACH,MAAM,WAAW,8BAA8B;IAC7C;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;IACjB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;OAKG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;OAEG;IACH,WAAW,CAAC,EAAE,4BAA4B,CAAC;CAC5C;AAED;;GAEG;AACH,MAAM,WAAW,4BAA4B;IAC3C;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,MAAM,iBAAiB,GAAG,YAAY,GAAG,QAAQ,GAAG,SAAS,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/config/types.ts"],"names":[],"mappings":";;;AAwDa,QAAA,kBAAkB,GAAG,QAAQ,CAAC","sourcesContent":["import { IConfig, LogLevel, ILogger, IDiagnosticsClient } from '@amplitude/analytics-core';\nimport { StoreType, ConsoleLogLevel } from '../typings/session-replay';\nimport { TargetingFlag } from '@amplitude/targeting';\n\nexport interface SamplingConfig {\n sample_rate: number;\n capture_enabled: boolean;\n min_session_duration_ms?: number;\n}\n\nexport interface InteractionConfig {\n trackEveryNms?: number;\n enabled: boolean; // defaults to false\n batch: boolean; // defaults to false\n /**\n * UGC filter rules.\n */\n ugcFilterRules?: UGCFilterRule[];\n}\n\nexport interface LoggingConfig {\n console: {\n enabled: boolean;\n levels: ConsoleLogLevel[];\n };\n network?: {\n enabled: boolean;\n body?: {\n request?: boolean;\n response?: boolean;\n maxBodySizeBytes?: number;\n };\n };\n}\n\nexport type TargetingConfig = TargetingFlag;\n\nexport type SessionReplayRemoteConfig = {\n sr_sampling_config?: SamplingConfig;\n sr_privacy_config?: PrivacyConfig;\n sr_interaction_config?: InteractionConfig;\n sr_logging_config?: LoggingConfig;\n sr_targeting_config?: TargetingConfig;\n};\n\nexport interface SessionReplayRemoteConfigAPIResponse {\n configs: {\n sessionReplay: SessionReplayRemoteConfig;\n };\n}\n\nexport type MaskLevel =\n | 'light' // only mask a subset of inputs that's deemed sensitive - password, credit card, telephone #, email. These are information we never want to capture.\n | 'medium' // mask all form fields (inputs); page text is captured as-is\n | 'conservative'; // mask all inputs and all texts\n\nexport const DEFAULT_MASK_LEVEL = 'medium';\n\n// err on the side of excluding more\nexport type PrivacyConfig = {\n blockSelector?: string | string[]; // exclude in the UI\n defaultMaskLevel?: MaskLevel;\n maskSelector?: string[];\n unmaskSelector?: string[];\n maskAttributes?: string[]; // HTML attribute names to mask (e.g. [\"placeholder\", \"aria-label\"])\n /**\n * Per-URL overrides for `defaultMaskLevel`. Each entry contains a glob pattern (`match`)\n * and a `maskLevel` to apply when the current page URL matches that pattern.\n * Rules are evaluated in order; the first match wins. Remote rules take precedence\n * over local rules (remote entries are prepended before local entries).\n *\n * @example\n * urlMaskLevels: [\n * { match: 'https://example.com/checkout/*', maskLevel: 'conservative' },\n * { match: 'https://example.com/public/*', maskLevel: 'light' },\n * ]\n */\n urlMaskLevels?: Array<{ match: string; maskLevel: MaskLevel }>;\n};\n\n/**\n * UGC filter rule.\n */\nexport type UGCFilterRule = {\n /**\n * The selector of the UGC element.\n */\n selector: string;\n /**\n * The replacement text for the UGC element.\n */\n replacement: string;\n};\n\nexport interface CrossOriginIframesConfig {\n enabled: boolean;\n /**\n * When true (default), the parent SDK sends start/stop signals to child iframes via\n * postMessage, keeping their recording lifecycle in sync with the parent.\n *\n * **Privacy note:** The child page's rrweb instance performs its own DOM serialization,\n * so the parent's privacy config (mask levels, block selectors) does NOT automatically\n * apply inside the iframe. Privacy settings must be configured independently on the child page.\n *\n * **Third-party iframes:** Cannot capture iframes you don't control (e.g. Stripe, Google\n * Maps) — both parent and child pages must load the SDK with `crossOriginIframes.enabled: true`.\n *\n * Set to `false` to skip coordination and manage the child recording lifecycle yourself.\n * @defaultValue true\n */\n coordinateChildren?: boolean;\n}\n\nexport interface SessionReplayLocalConfig extends IConfig {\n apiKey: string;\n loggerProvider: ILogger;\n /**\n * Optional diagnostics client used to ship SR decision/targeting telemetry to Amplitude's\n * diagnostics backend (independent of whether a replay is recorded). In plugin mode this is\n * forwarded from the analytics SDK's already-initialized client. No-op when absent or when\n * diagnostics is not sampled in. See DiagnosticsClient in @amplitude/analytics-core.\n */\n diagnosticsClient?: IDiagnosticsClient;\n /**\n * Standalone SR only: when no `diagnosticsClient` is provided (i.e. SR is not running as the\n * analytics plugin), opt in to having SR create its own client so TRC/recording diagnostics are\n * still shipped. Ignored when a `diagnosticsClient` is supplied. @defaultValue false\n */\n diagnosticsEnabled?: boolean;\n /**\n * Standalone SR only: sample rate (0..1) for the diagnostics client SR creates when none is\n * provided. A positive value also implies opting in. @defaultValue 0\n */\n diagnosticsSampleRate?: number;\n /**\n * LogLevel.None or LogLevel.Error or LogLevel.Warn or LogLevel.Verbose or LogLevel.Debug.\n * Sets the log level.\n *\n * @defaultValue LogLevel.Warn\n */\n logLevel: LogLevel;\n /**\n * The maximum number of retries allowed for sending replay events.\n * Once this limit is reached, failed events will no longer be sent.\n *\n * @defaultValue 2\n */\n flushMaxRetries: number;\n /**\n * Use this option to control how many sessions to select for replay collection.\n * The number should be a decimal between 0 and 1, for example 0.4, representing\n * the fraction of sessions to have randomly selected for replay collection.\n * Over a large number of sessions, 0.4 would select 40% of those sessions.\n * Sample rates as small as six decimal places (0.000001) are supported.\n *\n * @defaultValue 0\n */\n sampleRate: number;\n privacyConfig?: PrivacyConfig;\n /**\n * Adds additional debug event property to help debug instrumentation issues\n * (such as mismatching apps). Only recommended for debugging initial setup,\n * and not recommended for production.\n */\n debugMode?: boolean;\n /**\n * Specifies the endpoint URL to fetch remote configuration.\n * If provided, it overrides the default server zone configuration.\n */\n configServerUrl?: string;\n /**\n * Specifies the endpoint URL for sending session replay data.\n * If provided, it overrides the default server zone configuration.\n */\n trackServerUrl?: string;\n /**\n * If stylesheets are inlined, the contents of the stylesheet will be stored.\n * During replay, the stored stylesheet will be used instead of attempting to fetch it remotely.\n * This prevents replays from appearing broken due to missing stylesheets.\n * Note: Inlining stylesheets may not work in all cases.\n */\n shouldInlineStylesheet?: boolean;\n version?: SessionReplayVersion;\n /**\n * Performance configuration config. If enabled, we will defer compression\n * to be done during the browser's idle periods.\n */\n performanceConfig?: SessionReplayPerformanceConfig;\n /**\n * Specifies how replay events should be stored. `idb` uses IndexedDB to persist replay events\n * when all events cannot be sent during capture. `memory` stores replay events only in memory,\n * meaning events are lost when the page is closed. If IndexedDB is unavailable, the system falls back to `memory`.\n *\n * @defaultValue 'memory' — reflects the validated amp-on-amp perf config (SR-4646). `memory`\n * drops cross-navigation persistence (unsent events do not survive a full page reload), which\n * is the intended trade-off for lower IDB overhead.\n */\n storeType: StoreType;\n\n /**\n * If true, the SDK will compress replay events using a web worker.\n * This offloads compression to a separate thread, improving performance on the main thread.\n * Set to `false` to keep compression on the main thread.\n *\n * @defaultValue true — reflects the validated amp-on-amp perf config (SR-4646). Was `false`\n * prior to that change.\n */\n useWebWorker?: boolean;\n\n /**\n * Controls transport-layer gzip compression of session replay request bodies.\n * When true (default), the SDK gzip-compresses the JSON request body via the browser's\n * `CompressionStream` API and sets `Content-Encoding: gzip` on the POST. When false,\n * the SDK sends the raw JSON body with no `Content-Encoding` header.\n *\n * Disabling is intended as a debugging / safety opt-out (e.g. for diagnosing\n * server-side decompression issues); it increases egress bytes and is not\n * recommended for production.\n *\n * Note: This is independent of `useWebWorker` / `performanceConfig`, which control\n * per-event rrweb compression that runs before events are queued.\n *\n * @defaultValue true\n */\n enableTransportCompression?: boolean;\n\n /**\n * Milliseconds to wait for a send request before aborting it. `fetch()` has no native\n * timeout, so a request stuck \"pending\" would block the serial flush loop indefinitely;\n * the SDK aborts after this many ms and routes the abort as a retryable failure.\n *\n * Set to `0` (or a negative value) to disable the timeout entirely — note this\n * reintroduces the head-of-line-blocking risk a wedged request can cause, so it is\n * intended only as a diagnostic/experiment opt-out.\n *\n * Tuning this higher is useful when large, slow-but-succeeding uploads are being aborted\n * at the default and counted as failures (which also triggers a retry, inflating request\n * volume / throttle pressure).\n *\n * @defaultValue 10000\n */\n sendTimeoutMs?: number;\n\n userProperties?: { [key: string]: any };\n\n /**\n * If true, applies a background color to blocked elements in the replay.\n * This helps visualize which elements are blocked from being captured.\n */\n applyBackgroundColorToBlockedElements?: boolean;\n /**\n * Enables URL change polling as a fallback for SPA route tracking.\n * When enabled, the SDK will periodically check for URL changes every second\n * in addition to patching the History API. This is useful for edge cases where\n * route changes might bypass the standard History API methods.\n *\n * @defaultValue false\n */\n enableUrlChangePolling?: boolean;\n /**\n * Specifies the interval in milliseconds for URL change polling when enableUrlChangePolling is true.\n * The SDK will check for URL changes at this interval as a fallback for SPA route tracking.\n *\n * @defaultValue 1000\n */\n urlChangePollingInterval?: number;\n /**\n * Whether to capture document title in URL change events.\n * When disabled, the title field will be empty in URL change events.\n *\n * @defaultValue false\n */\n captureDocumentTitle?: boolean;\n interactionConfig?: InteractionConfig;\n /**\n * When true (default), the CSS rules of any `adoptedStyleSheets` on shadow roots and\n * the document are serialized **inline** within the full snapshot. This makes the snapshot\n * self-contained so that shadow DOM styles are replayed correctly even if subsequent\n * incremental `AdoptedStyleSheet` events are dropped in transit.\n *\n * Set to `false` to revert to the legacy behavior where adopted stylesheet rules are\n * emitted as separate incremental events (which may be lost if delivery is unreliable).\n * Only consider opting out if snapshot payload size is a critical concern.\n *\n * @defaultValue true\n */\n captureAdoptedStyleSheets?: boolean;\n /**\n * Enables recording of cross-origin iframes. Both the parent page and each child iframe\n * page must load the Amplitude Session Replay SDK with this option enabled.\n *\n * When enabled, rrweb uses `postMessage` to relay child DOM events to the parent, which\n * merges them into a single unified event stream.\n */\n crossOriginIframes?: CrossOriginIframesConfig;\n /** Interval in ms at which the SDK takes a full DOM snapshot. Disabled by default — periodic snapshots are expensive. Recommended value: 300000 (5 min). */\n fullSnapshotIntervalMs?: number;\n /**\n * Controls how often the SDK splits buffered rrweb events into a sequence and dispatches\n * the resulting batch to the server. The interval starts at `minIntervalMs` and grows by\n * `minIntervalMs` after each split, capped at `maxIntervalMs`. Lowering values increases\n * replay availability latency improvements at the cost of more requests; raising them\n * reduces request volume (and 200+`X-Session-Replay-Event-Skipped` throttling responses)\n * at the cost of slightly delayed replay availability.\n *\n * Defaults to `{ minIntervalMs: 1000, maxIntervalMs: 10_000 }`, reflecting the validated\n * amp-on-amp perf config (SR-4646); the `minIntervalMs` default was `500` prior to that\n * change. Tune up if the server is back-pressuring the SDK on session start.\n */\n flushIntervalConfig?: FlushIntervalConfig;\n /**\n * When true, every rrweb full snapshot is flushed to the server immediately so replays\n * become playable as early as possible. When false (default), full-snapshot sends are\n * deferred to the normal interval/size flush cadence instead. The snapshot is still\n * compressed and buffered immediately either way (ordering and page-exit beacon coverage\n * are preserved); only the eager network send is suppressed. The default-off behavior\n * reduces request volume for pages that produce many full snapshots (e.g. focus-driven or\n * `fullSnapshotIntervalMs` checkouts), especially when many SDK instances run on the same\n * page.\n *\n * @defaultValue false — reflects the validated amp-on-amp perf config (SR-4646). Was `true`\n * prior to that change.\n */\n eagerFullSnapshotSend?: boolean;\n /**\n * When true, the window `focus` listener forces a fresh rrweb full snapshot\n * (`takeFullSnapshot`) every time the page regains focus, so the replay reflects any DOM\n * changes that happened while the tab was backgrounded. When false (default), the on-focus\n * full snapshot is skipped entirely (recording simply continues from the existing stream).\n *\n * On pages with heavy focus churn (e.g. embedded iframes, inline editors that repeatedly\n * steal and return focus) this fires constantly, and when combined with\n * `eagerFullSnapshotSend` each focus produces an immediate network send — the primary\n * driver of focus-driven request storms. The default-off behavior removes the snapshot (and\n * therefore the send) at the cost of slightly staler post-focus frames.\n *\n * @defaultValue false — reflects the validated amp-on-amp perf config (SR-4646). Was `true`\n * prior to that change.\n */\n captureFullSnapshotOnFocus?: boolean;\n /**\n * Raw (uncompressed) UTF-8 byte cap for a single buffered events list before the store\n * splits it into its own request. Larger values produce fewer, larger requests (the primary\n * steady-state lever for request volume); smaller values split sooner. Payloads are gzipped\n * on the wire, so several hundred KB of replay JSON compresses to well under 100 KB.\n *\n * Advanced/debug knob — the default already balances request volume against the server's\n * decompressed-size split threshold. Clamped to a safe range; values outside it are clamped\n * and logged. Defaults to the SDK's internal `DEFAULT_MAX_PERSISTED_EVENTS_SIZE_BYTES`.\n *\n * @defaultValue 6000000 — reflects the validated amp-on-amp perf config (SR-4646). Was\n * `MAX_EVENT_LIST_SIZE` (2000000) prior to that change.\n */\n maxPersistedEventsSizeBytes?: number;\n /**\n * Raw (uncompressed) UTF-8 byte cap for a single rrweb event. Events larger than this are\n * dropped (with a warning) both at capture time and as a pre-send backstop, because the SR\n * ingest service rejects a single event above ~10 MB. Lower this to exercise drop behavior\n * for large full snapshots while debugging.\n *\n * Advanced/debug knob. Clamped to a safe range; values outside it are clamped and logged.\n * Defaults to the SDK's internal `MAX_SINGLE_EVENT_SIZE`.\n *\n * @defaultValue 9000000\n */\n maxSingleEventSizeBytes?: number;\n}\n\nexport interface FlushIntervalConfig {\n /**\n * Lower bound on the rrweb event-split interval in milliseconds. Also the increment\n * added to the interval after each split. Must be > 0; values are clamped to a 100ms floor.\n *\n * @defaultValue 1000 — reflects the validated amp-on-amp perf config (SR-4646). Was `500`\n * prior to that change.\n */\n minIntervalMs?: number;\n /**\n * Upper bound on the rrweb event-split interval in milliseconds. Must be >= `minIntervalMs`.\n *\n * @defaultValue 10000\n */\n maxIntervalMs?: number;\n}\n\nexport interface SessionReplayJoinedConfig extends SessionReplayLocalConfig {\n captureEnabled?: boolean;\n interactionConfig?: InteractionConfig;\n loggingConfig?: LoggingConfig;\n targetingConfig?: TargetingConfig;\n minSessionDurationMs?: number;\n}\n\nexport interface SessionReplayConfigs {\n localConfig: SessionReplayLocalConfig;\n joinedConfig: SessionReplayJoinedConfig;\n remoteConfig: SessionReplayRemoteConfig | undefined;\n}\nexport interface SessionReplayJoinedConfigGenerator {\n generateJoinedConfig: () => Promise<SessionReplayConfigs>;\n}\n\nexport interface SessionReplayMetadata {\n remoteConfig: SessionReplayRemoteConfig | undefined;\n localConfig: SessionReplayLocalConfig;\n joinedConfig: SessionReplayJoinedConfig;\n framework?: {\n name: string;\n version: string;\n };\n sessionId: string | number | undefined;\n hashValue?: number;\n sampleRate: number;\n replaySDKType: string | null;\n replaySDKVersion: string | undefined;\n standaloneSDKType: string;\n standaloneSDKVersion: string | undefined;\n}\n\nexport interface SessionReplayVersion {\n version: string;\n type: SessionReplayType;\n}\n\n/**\n * Configuration options for session replay performance.\n */\nexport interface SessionReplayPerformanceConfig {\n /**\n * If enabled, event compression will be deferred to occur during the browser's idle periods.\n */\n enabled: boolean;\n /**\n * Optional timeout in milliseconds for the `requestIdleCallback` API.\n * If specified, this value will be used to set a maximum time for the browser to wait\n * before executing the deferred compression task, even if the browser is not idle.\n */\n timeout?: number;\n /**\n * If enabled, consecutive mutation events will be merged into a single event before\n * compression, reducing stored event count without changing replay semantics.\n * Defaults to true, reflecting the validated amp-on-amp perf config (SR-4646); set to\n * false to disable merging.\n */\n mergeMutations?: boolean;\n /**\n * Performance configuration for interaction tracking (clicks, scrolls).\n */\n interaction?: InteractionPerformanceConfig;\n}\n\n/**\n * Performance configuration for interaction tracking, specifically for CSS selector generation.\n */\nexport interface InteractionPerformanceConfig {\n /**\n * Maximum time in milliseconds allowed for CSS selector generation.\n * If selector generation takes longer than this, it will throw a timeout error.\n * Default: undefined (no timeout limit)\n */\n timeoutMs?: number;\n /**\n * Maximum number of attempts to optimize/simplify the CSS selector path.\n * Higher values may produce shorter selectors but take longer to compute.\n * Default: 10000\n */\n maxNumberOfTries?: number;\n /**\n * Maximum number of CSS selector combinations to test for uniqueness.\n * If more combinations would be generated, falls back to a simpler strategy.\n * Default: 1000\n */\n threshold?: number;\n}\n\nexport type SessionReplayType = 'standalone' | 'plugin' | 'segment';\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/config/types.ts"],"names":[],"mappings":";;;AAwDa,QAAA,kBAAkB,GAAG,QAAQ,CAAC","sourcesContent":["import { IConfig, LogLevel, ILogger } from '@amplitude/analytics-core';\nimport { StoreType, ConsoleLogLevel } from '../typings/session-replay';\nimport { TargetingFlag } from '@amplitude/targeting';\n\nexport interface SamplingConfig {\n sample_rate: number;\n capture_enabled: boolean;\n min_session_duration_ms?: number;\n}\n\nexport interface InteractionConfig {\n trackEveryNms?: number;\n enabled: boolean; // defaults to false\n batch: boolean; // defaults to false\n /**\n * UGC filter rules.\n */\n ugcFilterRules?: UGCFilterRule[];\n}\n\nexport interface LoggingConfig {\n console: {\n enabled: boolean;\n levels: ConsoleLogLevel[];\n };\n network?: {\n enabled: boolean;\n body?: {\n request?: boolean;\n response?: boolean;\n maxBodySizeBytes?: number;\n };\n };\n}\n\nexport type TargetingConfig = TargetingFlag;\n\nexport type SessionReplayRemoteConfig = {\n sr_sampling_config?: SamplingConfig;\n sr_privacy_config?: PrivacyConfig;\n sr_interaction_config?: InteractionConfig;\n sr_logging_config?: LoggingConfig;\n sr_targeting_config?: TargetingConfig;\n};\n\nexport interface SessionReplayRemoteConfigAPIResponse {\n configs: {\n sessionReplay: SessionReplayRemoteConfig;\n };\n}\n\nexport type MaskLevel =\n | 'light' // only mask a subset of inputs that's deemed sensitive - password, credit card, telephone #, email. These are information we never want to capture.\n | 'medium' // mask all form fields (inputs); page text is captured as-is\n | 'conservative'; // mask all inputs and all texts\n\nexport const DEFAULT_MASK_LEVEL = 'medium';\n\n// err on the side of excluding more\nexport type PrivacyConfig = {\n blockSelector?: string | string[]; // exclude in the UI\n defaultMaskLevel?: MaskLevel;\n maskSelector?: string[];\n unmaskSelector?: string[];\n maskAttributes?: string[]; // HTML attribute names to mask (e.g. [\"placeholder\", \"aria-label\"])\n /**\n * Per-URL overrides for `defaultMaskLevel`. Each entry contains a glob pattern (`match`)\n * and a `maskLevel` to apply when the current page URL matches that pattern.\n * Rules are evaluated in order; the first match wins. Remote rules take precedence\n * over local rules (remote entries are prepended before local entries).\n *\n * @example\n * urlMaskLevels: [\n * { match: 'https://example.com/checkout/*', maskLevel: 'conservative' },\n * { match: 'https://example.com/public/*', maskLevel: 'light' },\n * ]\n */\n urlMaskLevels?: Array<{ match: string; maskLevel: MaskLevel }>;\n};\n\n/**\n * UGC filter rule.\n */\nexport type UGCFilterRule = {\n /**\n * The selector of the UGC element.\n */\n selector: string;\n /**\n * The replacement text for the UGC element.\n */\n replacement: string;\n};\n\n/**\n * The fully-formed request the SDK hands to a custom `handleSendEvents` transport when\n * uploading recorded replay events. The callback's only job is to execute this request and\n * return the resulting `Response`; the SDK owns batching, retry, serialization and error\n * handling around it.\n */\nexport interface SendEventsRequest {\n /** The resolved track URL (respects `trackServerUrl`) including query params. */\n url: string;\n method: 'POST';\n /**\n * SDK-supplied default headers. When the body was gzipped, this includes\n * `Content-Encoding: gzip` — drop it only if you also stop forwarding the gzipped body,\n * otherwise the payload will not decode server-side.\n */\n headers: Record<string, string>;\n /**\n * The serialized payload, ready to send. A gzipped `Uint8Array` when transport compression\n * is active, otherwise the raw JSON string. Forward it unchanged — do not re-serialize.\n *\n * Typed as `string | Uint8Array` (not the broader `BodyInit`) because the body must be\n * structured-cloneable to cross `postMessage` in web-worker mode; `Blob`/`FormData`/\n * `ReadableStream` are not, and the SDK never produces them here.\n */\n body: string | Uint8Array;\n /**\n * Whether the built-in path would set `keepalive` on this request. `true` for page-exit\n * sends (so the request survives unload) and for small in-session batches. Forward it to\n * your `fetch` call — i.e. `fetch(url, { method, headers, body, keepalive })` — so exit-time\n * batches are not dropped when the page is tearing down.\n */\n keepalive: boolean;\n}\n\n/**\n * The fully-formed request the SDK hands to a custom `handleFetchConfig` transport when\n * fetching remote configuration.\n */\nexport interface FetchConfigRequest {\n /** The resolved config URL (respects `configServerUrl`) including query params. */\n url: string;\n method: 'GET';\n /** SDK-supplied default headers. */\n headers: Record<string, string>;\n /** Abort signal the SDK uses to enforce the remote-config fetch timeout. Honor it in your fetch. */\n signal?: AbortSignal;\n}\n\n/**\n * Custom transport for replay event uploads. Invoked by the SDK in place of its internal\n * `fetch`. Must return a `Response` (or Response-like with `ok`, `status`, `text()`). Called\n * once per logical request attempt — retry is handled by the SDK around the callback, so do\n * not implement your own retry. Thrown errors / rejected promises are surfaced to the SDK's\n * existing retry logic.\n */\nexport type SessionReplaySendEventsHandler = (request: SendEventsRequest) => Promise<Response>;\n\n/**\n * Custom transport for remote-config fetches. Same contract as {@link SessionReplaySendEventsHandler}.\n */\nexport type SessionReplayFetchConfigHandler = (request: FetchConfigRequest) => Promise<Response>;\n\nexport interface CrossOriginIframesConfig {\n enabled: boolean;\n /**\n * When true (default), the parent SDK sends start/stop signals to child iframes via\n * postMessage, keeping their recording lifecycle in sync with the parent.\n *\n * **Privacy note:** The child page's rrweb instance performs its own DOM serialization,\n * so the parent's privacy config (mask levels, block selectors) does NOT automatically\n * apply inside the iframe. Privacy settings must be configured independently on the child page.\n *\n * **Third-party iframes:** Cannot capture iframes you don't control (e.g. Stripe, Google\n * Maps) — both parent and child pages must load the SDK with `crossOriginIframes.enabled: true`.\n *\n * Set to `false` to skip coordination and manage the child recording lifecycle yourself.\n * @defaultValue true\n */\n coordinateChildren?: boolean;\n}\n\nexport interface SessionReplayLocalConfig extends IConfig {\n apiKey: string;\n loggerProvider: ILogger;\n /**\n * LogLevel.None or LogLevel.Error or LogLevel.Warn or LogLevel.Verbose or LogLevel.Debug.\n * Sets the log level.\n *\n * @defaultValue LogLevel.Warn\n */\n logLevel: LogLevel;\n /**\n * The maximum number of retries allowed for sending replay events.\n * Once this limit is reached, failed events will no longer be sent.\n *\n * @defaultValue 2\n */\n flushMaxRetries: number;\n /**\n * Use this option to control how many sessions to select for replay collection.\n * The number should be a decimal between 0 and 1, for example 0.4, representing\n * the fraction of sessions to have randomly selected for replay collection.\n * Over a large number of sessions, 0.4 would select 40% of those sessions.\n * Sample rates as small as six decimal places (0.000001) are supported.\n *\n * @defaultValue 0\n */\n sampleRate: number;\n privacyConfig?: PrivacyConfig;\n /**\n * Adds additional debug event property to help debug instrumentation issues\n * (such as mismatching apps). Only recommended for debugging initial setup,\n * and not recommended for production.\n */\n debugMode?: boolean;\n /**\n * Specifies the endpoint URL to fetch remote configuration.\n * If provided, it overrides the default server zone configuration.\n */\n configServerUrl?: string;\n /**\n * Specifies the endpoint URL for sending session replay data.\n * If provided, it overrides the default server zone configuration.\n */\n trackServerUrl?: string;\n /**\n * If stylesheets are inlined, the contents of the stylesheet will be stored.\n * During replay, the stored stylesheet will be used instead of attempting to fetch it remotely.\n * This prevents replays from appearing broken due to missing stylesheets.\n * Note: Inlining stylesheets may not work in all cases.\n */\n shouldInlineStylesheet?: boolean;\n version?: SessionReplayVersion;\n /**\n * Performance configuration config. If enabled, we will defer compression\n * to be done during the browser's idle periods.\n */\n performanceConfig?: SessionReplayPerformanceConfig;\n /**\n * Specifies how replay events should be stored. `idb` uses IndexedDB to persist replay events\n * when all events cannot be sent during capture. `memory` stores replay events only in memory,\n * meaning events are lost when the page is closed. If IndexedDB is unavailable, the system falls back to `memory`.\n *\n * @defaultValue 'memory' — reflects the validated amp-on-amp perf config (SR-4646). `memory`\n * drops cross-navigation persistence (unsent events do not survive a full page reload), which\n * is the intended trade-off for lower IDB overhead.\n */\n storeType: StoreType;\n\n /**\n * If true, the SDK will compress replay events using a web worker.\n * This offloads compression to a separate thread, improving performance on the main thread.\n * Set to `false` to keep compression on the main thread.\n *\n * @defaultValue true — reflects the validated amp-on-amp perf config (SR-4646). Was `false`\n * prior to that change.\n */\n useWebWorker?: boolean;\n\n /**\n * Controls transport-layer gzip compression of session replay request bodies.\n * When true (default), the SDK gzip-compresses the JSON request body via the browser's\n * `CompressionStream` API and sets `Content-Encoding: gzip` on the POST. When false,\n * the SDK sends the raw JSON body with no `Content-Encoding` header.\n *\n * Disabling is intended as a debugging / safety opt-out (e.g. for diagnosing\n * server-side decompression issues); it increases egress bytes and is not\n * recommended for production.\n *\n * Note: This is independent of `useWebWorker` / `performanceConfig`, which control\n * per-event rrweb compression that runs before events are queued.\n *\n * @defaultValue true\n */\n enableTransportCompression?: boolean;\n\n /**\n * Milliseconds to wait for a send request before aborting it. `fetch()` has no native\n * timeout, so a request stuck \"pending\" would block the serial flush loop indefinitely;\n * the SDK aborts after this many ms and routes the abort as a retryable failure.\n *\n * Set to `0` (or a negative value) to disable the timeout entirely — note this\n * reintroduces the head-of-line-blocking risk a wedged request can cause, so it is\n * intended only as a diagnostic/experiment opt-out.\n *\n * Tuning this higher is useful when large, slow-but-succeeding uploads are being aborted\n * at the default and counted as failures (which also triggers a retry, inflating request\n * volume / throttle pressure).\n *\n * @defaultValue 10000\n */\n sendTimeoutMs?: number;\n\n userProperties?: { [key: string]: any };\n\n /**\n * If true, applies a background color to blocked elements in the replay.\n * This helps visualize which elements are blocked from being captured.\n */\n applyBackgroundColorToBlockedElements?: boolean;\n /**\n * Enables URL change polling as a fallback for SPA route tracking.\n * When enabled, the SDK will periodically check for URL changes every second\n * in addition to patching the History API. This is useful for edge cases where\n * route changes might bypass the standard History API methods.\n *\n * @defaultValue false\n */\n enableUrlChangePolling?: boolean;\n /**\n * Specifies the interval in milliseconds for URL change polling when enableUrlChangePolling is true.\n * The SDK will check for URL changes at this interval as a fallback for SPA route tracking.\n *\n * @defaultValue 1000\n */\n urlChangePollingInterval?: number;\n /**\n * Whether to capture document title in URL change events.\n * When disabled, the title field will be empty in URL change events.\n *\n * @defaultValue false\n */\n captureDocumentTitle?: boolean;\n interactionConfig?: InteractionConfig;\n /**\n * When true (default), the CSS rules of any `adoptedStyleSheets` on shadow roots and\n * the document are serialized **inline** within the full snapshot. This makes the snapshot\n * self-contained so that shadow DOM styles are replayed correctly even if subsequent\n * incremental `AdoptedStyleSheet` events are dropped in transit.\n *\n * Set to `false` to revert to the legacy behavior where adopted stylesheet rules are\n * emitted as separate incremental events (which may be lost if delivery is unreliable).\n * Only consider opting out if snapshot payload size is a critical concern.\n *\n * @defaultValue true\n */\n captureAdoptedStyleSheets?: boolean;\n /**\n * Enables recording of cross-origin iframes. Both the parent page and each child iframe\n * page must load the Amplitude Session Replay SDK with this option enabled.\n *\n * When enabled, rrweb uses `postMessage` to relay child DOM events to the parent, which\n * merges them into a single unified event stream.\n */\n crossOriginIframes?: CrossOriginIframesConfig;\n /** Interval in ms at which the SDK takes a full DOM snapshot. Disabled by default — periodic snapshots are expensive. Recommended value: 300000 (5 min). */\n fullSnapshotIntervalMs?: number;\n /**\n * Controls how often the SDK splits buffered rrweb events into a sequence and dispatches\n * the resulting batch to the server. The interval starts at `minIntervalMs` and grows by\n * `minIntervalMs` after each split, capped at `maxIntervalMs`. Lowering values increases\n * replay availability latency improvements at the cost of more requests; raising them\n * reduces request volume (and 200+`X-Session-Replay-Event-Skipped` throttling responses)\n * at the cost of slightly delayed replay availability.\n *\n * Defaults to `{ minIntervalMs: 1000, maxIntervalMs: 10_000 }`, reflecting the validated\n * amp-on-amp perf config (SR-4646); the `minIntervalMs` default was `500` prior to that\n * change. Tune up if the server is back-pressuring the SDK on session start.\n */\n flushIntervalConfig?: FlushIntervalConfig;\n /**\n * When true, every rrweb full snapshot is flushed to the server immediately so replays\n * become playable as early as possible. When false (default), full-snapshot sends are\n * deferred to the normal interval/size flush cadence instead. The snapshot is still\n * compressed and buffered immediately either way (ordering and page-exit beacon coverage\n * are preserved); only the eager network send is suppressed. The default-off behavior\n * reduces request volume for pages that produce many full snapshots (e.g. focus-driven or\n * `fullSnapshotIntervalMs` checkouts), especially when many SDK instances run on the same\n * page.\n *\n * @defaultValue false — reflects the validated amp-on-amp perf config (SR-4646). Was `true`\n * prior to that change.\n */\n eagerFullSnapshotSend?: boolean;\n /**\n * When true, the window `focus` listener forces a fresh rrweb full snapshot\n * (`takeFullSnapshot`) every time the page regains focus, so the replay reflects any DOM\n * changes that happened while the tab was backgrounded. When false (default), the on-focus\n * full snapshot is skipped entirely (recording simply continues from the existing stream).\n *\n * On pages with heavy focus churn (e.g. embedded iframes, inline editors that repeatedly\n * steal and return focus) this fires constantly, and when combined with\n * `eagerFullSnapshotSend` each focus produces an immediate network send — the primary\n * driver of focus-driven request storms. The default-off behavior removes the snapshot (and\n * therefore the send) at the cost of slightly staler post-focus frames.\n *\n * @defaultValue false — reflects the validated amp-on-amp perf config (SR-4646). Was `true`\n * prior to that change.\n */\n captureFullSnapshotOnFocus?: boolean;\n /**\n * Raw (uncompressed) UTF-8 byte cap for a single buffered events list before the store\n * splits it into its own request. Larger values produce fewer, larger requests (the primary\n * steady-state lever for request volume); smaller values split sooner. Payloads are gzipped\n * on the wire, so several hundred KB of replay JSON compresses to well under 100 KB.\n *\n * Advanced/debug knob — the default already balances request volume against the server's\n * decompressed-size split threshold. Clamped to a safe range; values outside it are clamped\n * and logged. Defaults to the SDK's internal `DEFAULT_MAX_PERSISTED_EVENTS_SIZE_BYTES`.\n *\n * @defaultValue 6000000 — reflects the validated amp-on-amp perf config (SR-4646). Was\n * `MAX_EVENT_LIST_SIZE` (2000000) prior to that change.\n */\n maxPersistedEventsSizeBytes?: number;\n /**\n * Raw (uncompressed) UTF-8 byte cap for a single rrweb event. Events larger than this are\n * dropped (with a warning) both at capture time and as a pre-send backstop, because the SR\n * ingest service rejects a single event above ~10 MB. Lower this to exercise drop behavior\n * for large full snapshots while debugging.\n *\n * Advanced/debug knob. Clamped to a safe range; values outside it are clamped and logged.\n * Defaults to the SDK's internal `MAX_SINGLE_EVENT_SIZE`.\n *\n * @defaultValue 9000000\n */\n maxSingleEventSizeBytes?: number;\n /**\n * Optional custom transport for replay event uploads. When provided, the SDK invokes this\n * callback in place of its internal `fetch` for every event-upload attempt, passing a\n * fully-formed {@link SendEventsRequest} (resolved URL, headers, serialized body). The SDK\n * still owns batching, retry, serialization and error handling. Use it to attach custom\n * auth (e.g. a JWT `Authorization` header) and route through an authenticated proxy.\n *\n * Works alongside `trackServerUrl`: the URL passed to the callback already respects it.\n */\n handleSendEvents?: SessionReplaySendEventsHandler;\n /**\n * Optional custom transport for the remote-config fetch. Same contract as `handleSendEvents`\n * but for the config GET. The URL passed to the callback already respects `configServerUrl`.\n */\n handleFetchConfig?: SessionReplayFetchConfigHandler;\n}\n\nexport interface FlushIntervalConfig {\n /**\n * Lower bound on the rrweb event-split interval in milliseconds. Also the increment\n * added to the interval after each split. Must be > 0; values are clamped to a 100ms floor.\n *\n * @defaultValue 1000 — reflects the validated amp-on-amp perf config (SR-4646). Was `500`\n * prior to that change.\n */\n minIntervalMs?: number;\n /**\n * Upper bound on the rrweb event-split interval in milliseconds. Must be >= `minIntervalMs`.\n *\n * @defaultValue 10000\n */\n maxIntervalMs?: number;\n}\n\nexport interface SessionReplayJoinedConfig extends SessionReplayLocalConfig {\n captureEnabled?: boolean;\n interactionConfig?: InteractionConfig;\n loggingConfig?: LoggingConfig;\n targetingConfig?: TargetingConfig;\n minSessionDurationMs?: number;\n}\n\nexport interface SessionReplayConfigs {\n localConfig: SessionReplayLocalConfig;\n joinedConfig: SessionReplayJoinedConfig;\n remoteConfig: SessionReplayRemoteConfig | undefined;\n}\nexport interface SessionReplayJoinedConfigGenerator {\n generateJoinedConfig: () => Promise<SessionReplayConfigs>;\n}\n\nexport interface SessionReplayMetadata {\n remoteConfig: SessionReplayRemoteConfig | undefined;\n localConfig: SessionReplayLocalConfig;\n joinedConfig: SessionReplayJoinedConfig;\n framework?: {\n name: string;\n version: string;\n };\n sessionId: string | number | undefined;\n hashValue?: number;\n sampleRate: number;\n replaySDKType: string | null;\n replaySDKVersion: string | undefined;\n standaloneSDKType: string;\n standaloneSDKVersion: string | undefined;\n}\n\nexport interface SessionReplayVersion {\n version: string;\n type: SessionReplayType;\n}\n\n/**\n * Configuration options for session replay performance.\n */\nexport interface SessionReplayPerformanceConfig {\n /**\n * If enabled, event compression will be deferred to occur during the browser's idle periods.\n */\n enabled: boolean;\n /**\n * Optional timeout in milliseconds for the `requestIdleCallback` API.\n * If specified, this value will be used to set a maximum time for the browser to wait\n * before executing the deferred compression task, even if the browser is not idle.\n */\n timeout?: number;\n /**\n * If enabled, consecutive mutation events will be merged into a single event before\n * compression, reducing stored event count without changing replay semantics.\n * Defaults to true, reflecting the validated amp-on-amp perf config (SR-4646); set to\n * false to disable merging.\n */\n mergeMutations?: boolean;\n /**\n * Performance configuration for interaction tracking (clicks, scrolls).\n */\n interaction?: InteractionPerformanceConfig;\n}\n\n/**\n * Performance configuration for interaction tracking, specifically for CSS selector generation.\n */\nexport interface InteractionPerformanceConfig {\n /**\n * Maximum time in milliseconds allowed for CSS selector generation.\n * If selector generation takes longer than this, it will throw a timeout error.\n * Default: undefined (no timeout limit)\n */\n timeoutMs?: number;\n /**\n * Maximum number of attempts to optimize/simplify the CSS selector path.\n * Higher values may produce shorter selectors but take longer to compute.\n * Default: 10000\n */\n maxNumberOfTries?: number;\n /**\n * Maximum number of CSS selector combinations to test for uniqueness.\n * If more combinations would be generated, falls back to a simpler strategy.\n * Default: 1000\n */\n threshold?: number;\n}\n\nexport type SessionReplayType = 'standalone' | 'plugin' | 'segment';\n"]}
@@ -4,4 +4,5 @@ export declare const init: (apiKey: string, options: import("./typings/session-r
4
4
  export { SessionReplayOptions, StoreType } from './typings/session-replay';
5
5
  export { SafeLoggerProvider } from './logger';
6
6
  export { AmplitudeSessionReplay } from './typings/session-replay';
7
+ export { SendEventsRequest, FetchConfigRequest, SessionReplaySendEventsHandler, SessionReplayFetchConfigHandler, } from './config/types';
7
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,eAAO,MACL,IAAI,mJACJ,YAAY,4HACZ,YAAY,qCACZ,0BAA0B;;GAC1B,KAAK,wCACL,QAAQ,cACR,2BAA2B,wNACZ,CAAC;AAClB,OAAO,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,eAAO,MACL,IAAI,mJACJ,YAAY,4HACZ,YAAY,qCACZ,0BAA0B;;GAC1B,KAAK,wCACL,QAAQ,cACR,2BAA2B,wNACZ,CAAC;AAClB,OAAO,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,8BAA8B,EAC9B,+BAA+B,GAChC,MAAM,gBAAgB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,4FAAqD;AAEnD,QAAA,IAAI,GAOF,gCAAa,OANf,QAAA,YAAY,GAMV,gCAAa,eALf,QAAA,YAAY,GAKV,gCAAa,eAJf,QAAA,0BAA0B,GAIxB,gCAAa,6BAHf,QAAA,KAAK,GAGH,gCAAa,QAFf,QAAA,QAAQ,GAEN,gCAAa,WADf,QAAA,2BAA2B,GACzB,gCAAa,6BAAC;AAElB,mCAA8C;AAArC,4GAAA,kBAAkB,OAAA","sourcesContent":["import sessionReplay from './session-replay-factory';\nexport const {\n init,\n setSessionId,\n getSessionId,\n getSessionReplayProperties,\n flush,\n shutdown,\n evaluateTargetingAndCapture,\n} = sessionReplay;\nexport { SessionReplayOptions, StoreType } from './typings/session-replay';\nexport { SafeLoggerProvider } from './logger';\nexport { AmplitudeSessionReplay } from './typings/session-replay';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,4FAAqD;AAEnD,QAAA,IAAI,GAOF,gCAAa,OANf,QAAA,YAAY,GAMV,gCAAa,eALf,QAAA,YAAY,GAKV,gCAAa,eAJf,QAAA,0BAA0B,GAIxB,gCAAa,6BAHf,QAAA,KAAK,GAGH,gCAAa,QAFf,QAAA,QAAQ,GAEN,gCAAa,WADf,QAAA,2BAA2B,GACzB,gCAAa,6BAAC;AAElB,mCAA8C;AAArC,4GAAA,kBAAkB,OAAA","sourcesContent":["import sessionReplay from './session-replay-factory';\nexport const {\n init,\n setSessionId,\n getSessionId,\n getSessionReplayProperties,\n flush,\n shutdown,\n evaluateTargetingAndCapture,\n} = sessionReplay;\nexport { SessionReplayOptions, StoreType } from './typings/session-replay';\nexport { SafeLoggerProvider } from './logger';\nexport { AmplitudeSessionReplay } from './typings/session-replay';\nexport {\n SendEventsRequest,\n FetchConfigRequest,\n SessionReplaySendEventsHandler,\n SessionReplayFetchConfigHandler,\n} from './config/types';\n"]}
@@ -35,19 +35,6 @@ export interface SubscribeToUrlChangesOptions {
35
35
  enablePolling?: boolean;
36
36
  /** Polling interval in ms when enablePolling is true (default: 1000) */
37
37
  pollingInterval?: number;
38
- /**
39
- * Optional debug logger, called once per poll tick (only on the polling path). Lets the SDK
40
- * confirm in the browser console that the interval is actually firing — useful when verifying
41
- * that enableUrlChangePolling took effect for an SPA that bypasses the History API.
42
- */
43
- log?: (message: string) => void;
44
- /**
45
- * Optional per-tick hook (polling path only), called every interval with the current href and
46
- * whether it changed since the last tick. The SDK uses this to emit a diagnostics signal proving
47
- * the polling loop actually fired (vs only being scheduled). Kept separate from `log` so the SDK
48
- * can throttle/aggregate what it ships.
49
- */
50
- onPoll?: (href: string, changed: boolean) => void;
51
38
  }
52
39
  /**
53
40
  * Single helper for URL change detection. Supports:
@@ -1 +1 @@
1
- {"version":3,"file":"url-tracking-plugin.d.ts","sourceRoot":"","sources":["../../../src/plugins/url-tracking-plugin.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,sEAAsE;IACtE,IAAI,EAAE,MAAM,CAAC;IACb,6BAA6B;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,gCAAgC;IAChC,cAAc,EAAE,MAAM,CAAC;IACvB,+BAA+B;IAC/B,aAAa,EAAE,MAAM,CAAC;IACtB,mCAAmC;IACnC,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,kEAAkE;IAClE,cAAc,CAAC,EAAE,aAAa,EAAE,CAAC;IACjC,6EAA6E;IAC7E,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,yEAAyE;IACzE,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,8EAA8E;IAC9E,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAChC;AAED,oEAAoE;AACpE,MAAM,WAAW,4BAA4B;IAC3C,2FAA2F;IAC3F,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,wEAAwE;IACxE,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;;OAIG;IACH,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;CACnD;AAiBD;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CACnC,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,WAAW,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EACnC,OAAO,GAAE,4BAAiC,GACzC,MAAM,IAAI,CAyGZ;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,GAAE,wBAA6B,GACrC,YAAY,CAAC,wBAAwB,CAAC,CAqFxC;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB,wCAA4B,CAAC"}
1
+ {"version":3,"file":"url-tracking-plugin.d.ts","sourceRoot":"","sources":["../../../src/plugins/url-tracking-plugin.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,sEAAsE;IACtE,IAAI,EAAE,MAAM,CAAC;IACb,6BAA6B;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,gCAAgC;IAChC,cAAc,EAAE,MAAM,CAAC;IACvB,+BAA+B;IAC/B,aAAa,EAAE,MAAM,CAAC;IACtB,mCAAmC;IACnC,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,kEAAkE;IAClE,cAAc,CAAC,EAAE,aAAa,EAAE,CAAC;IACjC,6EAA6E;IAC7E,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,yEAAyE;IACzE,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,8EAA8E;IAC9E,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAChC;AAED,oEAAoE;AACpE,MAAM,WAAW,4BAA4B;IAC3C,2FAA2F;IAC3F,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,wEAAwE;IACxE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAiBD;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CACnC,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,WAAW,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EACnC,OAAO,GAAE,4BAAiC,GACzC,MAAM,IAAI,CAqGZ;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,GAAE,wBAA6B,GACrC,YAAY,CAAC,wBAAwB,CAAC,CAqFxC;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB,wCAA4B,CAAC"}
@@ -28,17 +28,13 @@ function subscribeToUrlChanges(globalScope, onUrlChange, options) {
28
28
  return;
29
29
  };
30
30
  }
31
- var _a = options.enablePolling, enablePolling = _a === void 0 ? false : _a, _b = options.pollingInterval, pollingInterval = _b === void 0 ? constants_1.DEFAULT_URL_CHANGE_POLLING_INTERVAL : _b, log = options.log, onPoll = options.onPoll;
31
+ var _a = options.enablePolling, enablePolling = _a === void 0 ? false : _a, _b = options.pollingInterval, pollingInterval = _b === void 0 ? constants_1.DEFAULT_URL_CHANGE_POLLING_INTERVAL : _b;
32
32
  if (enablePolling) {
33
33
  var getHref_1 = function () { var _a; return (_a = globalScope.location.href) !== null && _a !== void 0 ? _a : ''; };
34
34
  var lastHref_1 = getHref_1();
35
35
  var id_1 = globalScope.setInterval(function () {
36
36
  var href = getHref_1();
37
- var changed = href !== lastHref_1;
38
- // Logged every tick (not just on change) so we can confirm the polling loop is alive.
39
- log === null || log === void 0 ? void 0 : log("URL polling tick (href=".concat(href, ", changed=").concat(String(changed), ")."));
40
- onPoll === null || onPoll === void 0 ? void 0 : onPoll(href, changed);
41
- if (!changed) {
37
+ if (href === lastHref_1) {
42
38
  return;
43
39
  }
44
40
  lastHref_1 = href;
@@ -1 +1 @@
1
- {"version":3,"file":"url-tracking-plugin.js","sourceRoot":"","sources":["../../../src/plugins/url-tracking-plugin.ts"],"names":[],"mappings":";;;;AAAA,sCAAwC;AAExC,0CAAmE;AAuDnE,wDAAwD;AACxD,IAAM,YAAY,GAAG,oCAAoC,CAAC;AAW1D,wGAAwG;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getPageUrl } from '../helpers';\nimport { UGCFilterRule } from '../config/types';\nimport { DEFAULT_URL_CHANGE_POLLING_INTERVAL } from '../constants';\nimport { RecordPlugin } from '@amplitude/rrweb-types';\n\n/**\n * Event emitted when URL changes are detected by the plugin\n * Contains the current page URL, title, and viewport dimensions\n */\nexport interface URLChangeEvent {\n /** The current page URL (may be filtered if UGC rules are applied) */\n href: string;\n /** The current page title */\n title: string;\n /** Viewport height in pixels */\n viewportHeight: number;\n /** Viewport width in pixels */\n viewportWidth: number;\n /** The type of URL change event */\n type: string;\n}\n\n/**\n * Configuration options for the URL tracking plugin\n */\nexport interface URLTrackingPluginOptions {\n /** Rules for filtering sensitive URLs (User Generated Content) */\n ugcFilterRules?: UGCFilterRule[];\n /** Whether to use polling instead of history API events for URL detection */\n enablePolling?: boolean;\n /** Interval in milliseconds for polling URL changes (default: 1000ms) */\n pollingInterval?: number;\n /** Whether to capture document title in URL change events (default: false) */\n captureDocumentTitle?: boolean;\n}\n\n/** Options for subscribeToUrlChanges (polling vs history + hash) */\nexport interface SubscribeToUrlChangesOptions {\n /** Use polling instead of history/popstate/hashchange (e.g. when history is unreliable) */\n enablePolling?: boolean;\n /** Polling interval in ms when enablePolling is true (default: 1000) */\n pollingInterval?: number;\n /**\n * Optional debug logger, called once per poll tick (only on the polling path). Lets the SDK\n * confirm in the browser console that the interval is actually firing — useful when verifying\n * that enableUrlChangePolling took effect for an SPA that bypasses the History API.\n */\n log?: (message: string) => void;\n /**\n * Optional per-tick hook (polling path only), called every interval with the current href and\n * whether it changed since the last tick. The SDK uses this to emit a diagnostics signal proving\n * the polling loop actually fired (vs only being scheduled). Kept separate from `log` so the SDK\n * can throttle/aggregate what it ships.\n */\n onPoll?: (href: string, changed: boolean) => void;\n}\n\n/** Patch detection marker to prevent double-patching */\nconst PATCH_MARKER = '__amplitude_url_tracking_patched__';\n\ntype PatchableHistoryMethod<T extends (...args: any[]) => any> = T & { [PATCH_MARKER]?: boolean };\n\ninterface UrlChangeSubscriptionState {\n callbacks: Set<(href: string) => void>;\n onPopStateOrHashChange: () => void;\n notify: () => void;\n listenersAttached: boolean;\n}\n\n/** Per-globalScope subscription state; persists to avoid wrapper stacking across re-subscribe cycles */\nconst urlChangeSubscriptionsByScope = new WeakMap<Window, UrlChangeSubscriptionState>();\n\n/**\n * Single helper for URL change detection. Supports:\n * - History API (pushState/replaceState) + popstate + hashchange (shared patch per scope)\n * - Optional polling (setInterval on location.href)\n *\n * Used by session-replay targeting (re-evaluate on URL change) and the URL tracking plugin\n * (emit rrweb events). Call the returned function to unsubscribe.\n *\n * @param globalScope - window (or equivalent); no-op if undefined\n * @param onUrlChange - called when the URL changes, with the new href\n * @param options - optional polling (default: event-based only)\n * @returns cleanup function to remove this subscription\n */\nexport function subscribeToUrlChanges(\n globalScope: Window | undefined,\n onUrlChange: (href: string) => void,\n options: SubscribeToUrlChangesOptions = {},\n): () => void {\n if (!globalScope?.location) {\n return (): void => {\n return;\n };\n }\n\n const { enablePolling = false, pollingInterval = DEFAULT_URL_CHANGE_POLLING_INTERVAL, log, onPoll } = options;\n\n if (enablePolling) {\n const getHref = (): string => globalScope.location.href ?? '';\n let lastHref = getHref();\n const id = globalScope.setInterval(() => {\n const href = getHref();\n const changed = href !== lastHref;\n // Logged every tick (not just on change) so we can confirm the polling loop is alive.\n log?.(`URL polling tick (href=${href}, changed=${String(changed)}).`);\n onPoll?.(href, changed);\n if (!changed) {\n return;\n }\n lastHref = href;\n onUrlChange(href);\n }, pollingInterval);\n return (): void => {\n if (id != null) {\n globalScope.clearInterval(id);\n }\n };\n }\n\n let subscriptionState = urlChangeSubscriptionsByScope.get(globalScope);\n if (!subscriptionState) {\n let lastHref: string | undefined = undefined;\n const callbacks = new Set<(href: string) => void>();\n\n const getHref = (): string => globalScope.location.href ?? '';\n\n const notify = (): void => {\n const href = getHref();\n if (lastHref !== undefined && href === lastHref) return;\n lastHref = href;\n callbacks.forEach((c) => c(href));\n };\n\n /**\n * Creates a patched version of history methods (pushState/replaceState)\n * that calls the original method and then emits a URL change event.\n */\n const createHistoryMethodPatch = <T extends typeof history.pushState | typeof history.replaceState>(\n originalMethod: T,\n ) => {\n const patchedMethod = function (this: History, ...args: Parameters<T>) {\n const result = originalMethod.apply(this, args);\n // Read from location.href after history call so we always notify with resolved absolute URL.\n notify();\n return result;\n } as PatchableHistoryMethod<T>;\n\n patchedMethod[PATCH_MARKER] = true;\n return patchedMethod;\n };\n\n const history = globalScope.history;\n if (history?.pushState) {\n const pushState = Reflect.get(history, 'pushState') as PatchableHistoryMethod<History['pushState']>;\n if (!pushState[PATCH_MARKER]) {\n history.pushState = createHistoryMethodPatch(pushState);\n }\n }\n if (history?.replaceState) {\n const replaceState = Reflect.get(history, 'replaceState') as PatchableHistoryMethod<History['replaceState']>;\n if (!replaceState[PATCH_MARKER]) {\n history.replaceState = createHistoryMethodPatch(replaceState);\n }\n }\n\n subscriptionState = {\n callbacks,\n notify,\n onPopStateOrHashChange: () => notify(),\n listenersAttached: false,\n };\n urlChangeSubscriptionsByScope.set(globalScope, subscriptionState);\n }\n\n const state = subscriptionState;\n if (!state.listenersAttached) {\n globalScope.addEventListener('popstate', state.onPopStateOrHashChange);\n globalScope.addEventListener('hashchange', state.onPopStateOrHashChange);\n state.listenersAttached = true;\n }\n\n state.callbacks.add(onUrlChange);\n return (): void => {\n state.callbacks.delete(onUrlChange);\n if (state.callbacks.size === 0) {\n // Do not restore history methods: we are not aware of patches applied by other scripts.\n if (state.listenersAttached) {\n globalScope.removeEventListener('popstate', state.onPopStateOrHashChange);\n globalScope.removeEventListener('hashchange', state.onPopStateOrHashChange);\n state.listenersAttached = false;\n }\n }\n };\n}\n\n/**\n * Creates a URL tracking plugin for rrweb record function\n *\n * This plugin monitors URL changes in the browser and emits events when the URL changes.\n * It supports three tracking modes:\n * 1. Polling (if explicitly enabled) - periodically checks for URL changes\n * 2. History API + Hash routing (default) - patches pushState/replaceState, listens to popstate and hashchange\n * 3. Hash routing only (fallback) - listens to hashchange events when History API is unavailable\n *\n * The plugin handles edge cases gracefully:\n * - Missing or null location objects\n * - Undefined, null, or empty location.href values\n * - Temporal dead zone issues with variable declarations\n * - Consistent URL normalization across all code paths\n *\n * @param options Configuration options for URL tracking\n * @returns RecordPlugin instance that can be used with rrweb\n */\nexport function createUrlTrackingPlugin(\n options: URLTrackingPluginOptions = {},\n): RecordPlugin<URLTrackingPluginOptions> {\n return {\n name: 'amplitude/url-tracking@1',\n observer(cb, globalScope, pluginOptions?: URLTrackingPluginOptions) {\n // Merge options with plugin-level options taking precedence over constructor options\n const config = { ...options, ...pluginOptions };\n const ugcFilterRules = config.ugcFilterRules || [];\n const enablePolling = config.enablePolling ?? false;\n const pollingInterval = config.pollingInterval ?? DEFAULT_URL_CHANGE_POLLING_INTERVAL;\n const captureDocumentTitle = config.captureDocumentTitle ?? false;\n\n // Early return if no global scope is available\n if (!globalScope) {\n return () => {\n // No cleanup needed if no global scope available\n };\n }\n\n // Track the last URL to prevent duplicate events\n // Initialize to undefined to ensure first call always emits an event\n let lastTrackedUrl: string | undefined = undefined;\n\n // Helper functions\n /**\n * Gets the current URL with proper normalization\n * Handles edge cases where location.href might be undefined, null, or empty\n * Ensures consistent behavior across all code paths\n * @returns Normalized URL string (empty string if location unavailable)\n */\n const getCurrentUrl = (): string => {\n if (!globalScope.location) return '';\n return globalScope.location.href || '';\n };\n\n /**\n * Creates a URL change event with current page information\n * Applies UGC filtering if rules are configured\n * Uses getCurrentUrl() for consistent URL normalization\n * @returns URLChangeEvent with current page state\n */\n const createUrlChangeEvent = (): URLChangeEvent => {\n const { innerHeight, innerWidth, document } = globalScope;\n const currentUrl = getCurrentUrl();\n let currentTitle = '';\n if (captureDocumentTitle) {\n currentTitle = document?.title || '';\n }\n\n // Apply UGC filtering if rules are provided, otherwise use original URL\n const filteredUrl = ugcFilterRules.length > 0 ? getPageUrl(currentUrl, ugcFilterRules) : currentUrl;\n\n return {\n href: filteredUrl,\n title: currentTitle,\n viewportHeight: innerHeight,\n viewportWidth: innerWidth,\n type: 'url-change-event',\n };\n };\n\n /**\n * Emits a URL change event if the URL has actually changed\n * Always emits on first call (when lastTrackedUrl is undefined)\n */\n const emitUrlChange = (): void => {\n const currentUrl = getCurrentUrl();\n if (lastTrackedUrl === undefined || currentUrl !== lastTrackedUrl) {\n lastTrackedUrl = currentUrl;\n const event = createUrlChangeEvent();\n cb(event);\n }\n };\n\n // Single helper: history + popstate + hashchange, or polling when enabled\n const unsubscribe = subscribeToUrlChanges(\n globalScope as Window,\n () => emitUrlChange(),\n enablePolling ? { enablePolling: true, pollingInterval } : {},\n );\n emitUrlChange();\n\n return (): void => unsubscribe();\n },\n options,\n };\n}\n\n/**\n * Default URL tracking plugin instance with default options\n * Can be used directly without custom configuration\n */\nexport const urlTrackingPlugin = createUrlTrackingPlugin();\n"]}
1
+ {"version":3,"file":"url-tracking-plugin.js","sourceRoot":"","sources":["../../../src/plugins/url-tracking-plugin.ts"],"names":[],"mappings":";;;;AAAA,sCAAwC;AAExC,0CAAmE;AA0CnE,wDAAwD;AACxD,IAAM,YAAY,GAAG,oCAAoC,CAAC;AAW1D,wGAAwG;AACxG,IAAM,6BAA6B,GAAG,IAAI,OAAO,EAAsC,CAAC;AAExF;;;;;;;;;;;;GAYG;AACH,SAAgB,qBAAqB,CACnC,WAA+B,EAC/B,WAAmC,EACnC,OAA0C;IAA1C,wBAAA,EAAA,YAA0C;IAE1C,IAAI,CAAC,CAAA,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,QAAQ,CAAA,EAAE;QAC1B,OAAO;YACL,OAAO;QACT,CAAC,CAAC;KACH;IAEO,IAAA,KAAiF,OAAO,cAAnE,EAArB,aAAa,mBAAG,KAAK,KAAA,EAAE,KAA0D,OAAO,gBAAZ,EAArD,eAAe,mBAAG,+CAAmC,KAAA,CAAa;IAEjG,IAAI,aAAa,EAAE;QACjB,IAAM,SAAO,GAAG,sBAAc,OAAA,MAAA,WAAW,CAAC,QAAQ,CAAC,IAAI,mCAAI,EAAE,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BAAqB,CACvC,WAAqB,EACrB,cAAM,OAAA,aAAa,EAAE,EAAf,CAAe,EACrB,aAAa,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,IAAI,EAAE,eAAe,iBAAA,EAAE,CAAC,CAAC,CAAC,EAAE,CAC9D,CAAC;YACF,aAAa,EAAE,CAAC;YAEhB,OAAO,cAAY,OAAA,WAAW,EAAE,EAAb,CAAa,CAAC;QACnC,CAAC;QACD,OAAO,SAAA;KACR,CAAC;AACJ,CAAC;AAvFD,0DAuFC;AAED;;;GAGG;AACU,QAAA,iBAAiB,GAAG,uBAAuB,EAAE,CAAC","sourcesContent":["import { getPageUrl } from '../helpers';\nimport { UGCFilterRule } from '../config/types';\nimport { DEFAULT_URL_CHANGE_POLLING_INTERVAL } from '../constants';\nimport { RecordPlugin } from '@amplitude/rrweb-types';\n\n/**\n * Event emitted when URL changes are detected by the plugin\n * Contains the current page URL, title, and viewport dimensions\n */\nexport interface URLChangeEvent {\n /** The current page URL (may be filtered if UGC rules are applied) */\n href: string;\n /** The current page title */\n title: string;\n /** Viewport height in pixels */\n viewportHeight: number;\n /** Viewport width in pixels */\n viewportWidth: number;\n /** The type of URL change event */\n type: string;\n}\n\n/**\n * Configuration options for the URL tracking plugin\n */\nexport interface URLTrackingPluginOptions {\n /** Rules for filtering sensitive URLs (User Generated Content) */\n ugcFilterRules?: UGCFilterRule[];\n /** Whether to use polling instead of history API events for URL detection */\n enablePolling?: boolean;\n /** Interval in milliseconds for polling URL changes (default: 1000ms) */\n pollingInterval?: number;\n /** Whether to capture document title in URL change events (default: false) */\n captureDocumentTitle?: boolean;\n}\n\n/** Options for subscribeToUrlChanges (polling vs history + hash) */\nexport interface SubscribeToUrlChangesOptions {\n /** Use polling instead of history/popstate/hashchange (e.g. when history is unreliable) */\n enablePolling?: boolean;\n /** Polling interval in ms when enablePolling is true (default: 1000) */\n pollingInterval?: number;\n}\n\n/** Patch detection marker to prevent double-patching */\nconst PATCH_MARKER = '__amplitude_url_tracking_patched__';\n\ntype PatchableHistoryMethod<T extends (...args: any[]) => any> = T & { [PATCH_MARKER]?: boolean };\n\ninterface UrlChangeSubscriptionState {\n callbacks: Set<(href: string) => void>;\n onPopStateOrHashChange: () => void;\n notify: () => void;\n listenersAttached: boolean;\n}\n\n/** Per-globalScope subscription state; persists to avoid wrapper stacking across re-subscribe cycles */\nconst urlChangeSubscriptionsByScope = new WeakMap<Window, UrlChangeSubscriptionState>();\n\n/**\n * Single helper for URL change detection. Supports:\n * - History API (pushState/replaceState) + popstate + hashchange (shared patch per scope)\n * - Optional polling (setInterval on location.href)\n *\n * Used by session-replay targeting (re-evaluate on URL change) and the URL tracking plugin\n * (emit rrweb events). Call the returned function to unsubscribe.\n *\n * @param globalScope - window (or equivalent); no-op if undefined\n * @param onUrlChange - called when the URL changes, with the new href\n * @param options - optional polling (default: event-based only)\n * @returns cleanup function to remove this subscription\n */\nexport function subscribeToUrlChanges(\n globalScope: Window | undefined,\n onUrlChange: (href: string) => void,\n options: SubscribeToUrlChangesOptions = {},\n): () => void {\n if (!globalScope?.location) {\n return (): void => {\n return;\n };\n }\n\n const { enablePolling = false, pollingInterval = DEFAULT_URL_CHANGE_POLLING_INTERVAL } = options;\n\n if (enablePolling) {\n const getHref = (): string => globalScope.location.href ?? '';\n let lastHref = getHref();\n const id = globalScope.setInterval(() => {\n const href = getHref();\n if (href === lastHref) {\n return;\n }\n lastHref = href;\n onUrlChange(href);\n }, pollingInterval);\n return (): void => {\n if (id != null) {\n globalScope.clearInterval(id);\n }\n };\n }\n\n let subscriptionState = urlChangeSubscriptionsByScope.get(globalScope);\n if (!subscriptionState) {\n let lastHref: string | undefined = undefined;\n const callbacks = new Set<(href: string) => void>();\n\n const getHref = (): string => globalScope.location.href ?? '';\n\n const notify = (): void => {\n const href = getHref();\n if (lastHref !== undefined && href === lastHref) return;\n lastHref = href;\n callbacks.forEach((c) => c(href));\n };\n\n /**\n * Creates a patched version of history methods (pushState/replaceState)\n * that calls the original method and then emits a URL change event.\n */\n const createHistoryMethodPatch = <T extends typeof history.pushState | typeof history.replaceState>(\n originalMethod: T,\n ) => {\n const patchedMethod = function (this: History, ...args: Parameters<T>) {\n const result = originalMethod.apply(this, args);\n // Read from location.href after history call so we always notify with resolved absolute URL.\n notify();\n return result;\n } as PatchableHistoryMethod<T>;\n\n patchedMethod[PATCH_MARKER] = true;\n return patchedMethod;\n };\n\n const history = globalScope.history;\n if (history?.pushState) {\n const pushState = Reflect.get(history, 'pushState') as PatchableHistoryMethod<History['pushState']>;\n if (!pushState[PATCH_MARKER]) {\n history.pushState = createHistoryMethodPatch(pushState);\n }\n }\n if (history?.replaceState) {\n const replaceState = Reflect.get(history, 'replaceState') as PatchableHistoryMethod<History['replaceState']>;\n if (!replaceState[PATCH_MARKER]) {\n history.replaceState = createHistoryMethodPatch(replaceState);\n }\n }\n\n subscriptionState = {\n callbacks,\n notify,\n onPopStateOrHashChange: () => notify(),\n listenersAttached: false,\n };\n urlChangeSubscriptionsByScope.set(globalScope, subscriptionState);\n }\n\n const state = subscriptionState;\n if (!state.listenersAttached) {\n globalScope.addEventListener('popstate', state.onPopStateOrHashChange);\n globalScope.addEventListener('hashchange', state.onPopStateOrHashChange);\n state.listenersAttached = true;\n }\n\n state.callbacks.add(onUrlChange);\n return (): void => {\n state.callbacks.delete(onUrlChange);\n if (state.callbacks.size === 0) {\n // Do not restore history methods: we are not aware of patches applied by other scripts.\n if (state.listenersAttached) {\n globalScope.removeEventListener('popstate', state.onPopStateOrHashChange);\n globalScope.removeEventListener('hashchange', state.onPopStateOrHashChange);\n state.listenersAttached = false;\n }\n }\n };\n}\n\n/**\n * Creates a URL tracking plugin for rrweb record function\n *\n * This plugin monitors URL changes in the browser and emits events when the URL changes.\n * It supports three tracking modes:\n * 1. Polling (if explicitly enabled) - periodically checks for URL changes\n * 2. History API + Hash routing (default) - patches pushState/replaceState, listens to popstate and hashchange\n * 3. Hash routing only (fallback) - listens to hashchange events when History API is unavailable\n *\n * The plugin handles edge cases gracefully:\n * - Missing or null location objects\n * - Undefined, null, or empty location.href values\n * - Temporal dead zone issues with variable declarations\n * - Consistent URL normalization across all code paths\n *\n * @param options Configuration options for URL tracking\n * @returns RecordPlugin instance that can be used with rrweb\n */\nexport function createUrlTrackingPlugin(\n options: URLTrackingPluginOptions = {},\n): RecordPlugin<URLTrackingPluginOptions> {\n return {\n name: 'amplitude/url-tracking@1',\n observer(cb, globalScope, pluginOptions?: URLTrackingPluginOptions) {\n // Merge options with plugin-level options taking precedence over constructor options\n const config = { ...options, ...pluginOptions };\n const ugcFilterRules = config.ugcFilterRules || [];\n const enablePolling = config.enablePolling ?? false;\n const pollingInterval = config.pollingInterval ?? DEFAULT_URL_CHANGE_POLLING_INTERVAL;\n const captureDocumentTitle = config.captureDocumentTitle ?? false;\n\n // Early return if no global scope is available\n if (!globalScope) {\n return () => {\n // No cleanup needed if no global scope available\n };\n }\n\n // Track the last URL to prevent duplicate events\n // Initialize to undefined to ensure first call always emits an event\n let lastTrackedUrl: string | undefined = undefined;\n\n // Helper functions\n /**\n * Gets the current URL with proper normalization\n * Handles edge cases where location.href might be undefined, null, or empty\n * Ensures consistent behavior across all code paths\n * @returns Normalized URL string (empty string if location unavailable)\n */\n const getCurrentUrl = (): string => {\n if (!globalScope.location) return '';\n return globalScope.location.href || '';\n };\n\n /**\n * Creates a URL change event with current page information\n * Applies UGC filtering if rules are configured\n * Uses getCurrentUrl() for consistent URL normalization\n * @returns URLChangeEvent with current page state\n */\n const createUrlChangeEvent = (): URLChangeEvent => {\n const { innerHeight, innerWidth, document } = globalScope;\n const currentUrl = getCurrentUrl();\n let currentTitle = '';\n if (captureDocumentTitle) {\n currentTitle = document?.title || '';\n }\n\n // Apply UGC filtering if rules are provided, otherwise use original URL\n const filteredUrl = ugcFilterRules.length > 0 ? getPageUrl(currentUrl, ugcFilterRules) : currentUrl;\n\n return {\n href: filteredUrl,\n title: currentTitle,\n viewportHeight: innerHeight,\n viewportWidth: innerWidth,\n type: 'url-change-event',\n };\n };\n\n /**\n * Emits a URL change event if the URL has actually changed\n * Always emits on first call (when lastTrackedUrl is undefined)\n */\n const emitUrlChange = (): void => {\n const currentUrl = getCurrentUrl();\n if (lastTrackedUrl === undefined || currentUrl !== lastTrackedUrl) {\n lastTrackedUrl = currentUrl;\n const event = createUrlChangeEvent();\n cb(event);\n }\n };\n\n // Single helper: history + popstate + hashchange, or polling when enabled\n const unsubscribe = subscribeToUrlChanges(\n globalScope as Window,\n () => emitUrlChange(),\n enablePolling ? { enablePolling: true, pollingInterval } : {},\n );\n emitUrlChange();\n\n return (): void => unsubscribe();\n },\n options,\n };\n}\n\n/**\n * Default URL tracking plugin instance with default options\n * Can be used directly without custom configuration\n */\nexport const urlTrackingPlugin = createUrlTrackingPlugin();\n"]}