@amplitude/session-replay-browser 1.52.0-codexsemantic-review-integration.0 → 1.52.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.
- package/lib/cjs/config/joined-config.d.ts +1 -0
- package/lib/cjs/config/joined-config.d.ts.map +1 -1
- package/lib/cjs/config/joined-config.js +10 -1
- package/lib/cjs/config/joined-config.js.map +1 -1
- package/lib/cjs/config/local-config.d.ts +3 -3
- package/lib/cjs/config/local-config.d.ts.map +1 -1
- package/lib/cjs/config/local-config.js +5 -3
- package/lib/cjs/config/local-config.js.map +1 -1
- package/lib/cjs/config/types.d.ts +17 -9
- package/lib/cjs/config/types.d.ts.map +1 -1
- package/lib/cjs/config/types.js.map +1 -1
- package/lib/cjs/helpers.d.ts.map +1 -1
- package/lib/cjs/helpers.js +7 -4
- package/lib/cjs/helpers.js.map +1 -1
- package/lib/cjs/hooks/click.d.ts +2 -8
- package/lib/cjs/hooks/click.d.ts.map +1 -1
- package/lib/cjs/hooks/click.js +3 -42
- package/lib/cjs/hooks/click.js.map +1 -1
- package/lib/cjs/index.d.ts +1 -0
- package/lib/cjs/index.d.ts.map +1 -1
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/plugins/url-tracking-plugin.d.ts +0 -3
- package/lib/cjs/plugins/url-tracking-plugin.d.ts.map +1 -1
- package/lib/cjs/plugins/url-tracking-plugin.js +9 -16
- package/lib/cjs/plugins/url-tracking-plugin.js.map +1 -1
- package/lib/cjs/semantic-identity.d.ts +1 -1
- package/lib/cjs/semantic-identity.d.ts.map +1 -1
- package/lib/cjs/semantic-identity.js +4 -3
- package/lib/cjs/semantic-identity.js.map +1 -1
- package/lib/cjs/semantic-types.d.ts +45 -0
- package/lib/cjs/semantic-types.d.ts.map +1 -0
- package/lib/cjs/semantic-types.js +3 -0
- package/lib/cjs/semantic-types.js.map +1 -0
- package/lib/cjs/semantic.d.ts +9 -12
- package/lib/cjs/semantic.d.ts.map +1 -1
- package/lib/cjs/semantic.js +17 -90
- package/lib/cjs/semantic.js.map +1 -1
- package/lib/cjs/session-replay.d.ts +39 -2
- package/lib/cjs/session-replay.d.ts.map +1 -1
- package/lib/cjs/session-replay.js +267 -132
- package/lib/cjs/session-replay.js.map +1 -1
- package/lib/cjs/utils/rrweb.d.ts +0 -3
- package/lib/cjs/utils/rrweb.d.ts.map +1 -1
- package/lib/cjs/utils/rrweb.js.map +1 -1
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.d.ts.map +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/cjs/version.js.map +1 -1
- package/lib/cjs/window-focus.d.ts +40 -0
- package/lib/cjs/window-focus.d.ts.map +1 -0
- package/lib/cjs/window-focus.js +182 -0
- package/lib/cjs/window-focus.js.map +1 -0
- package/lib/esm/config/joined-config.d.ts +1 -0
- package/lib/esm/config/joined-config.d.ts.map +1 -1
- package/lib/esm/config/joined-config.js +10 -1
- package/lib/esm/config/joined-config.js.map +1 -1
- package/lib/esm/config/local-config.d.ts +3 -3
- package/lib/esm/config/local-config.d.ts.map +1 -1
- package/lib/esm/config/local-config.js +5 -3
- package/lib/esm/config/local-config.js.map +1 -1
- package/lib/esm/config/types.d.ts +17 -9
- package/lib/esm/config/types.d.ts.map +1 -1
- package/lib/esm/config/types.js.map +1 -1
- package/lib/esm/helpers.d.ts.map +1 -1
- package/lib/esm/helpers.js +8 -5
- package/lib/esm/helpers.js.map +1 -1
- package/lib/esm/hooks/click.d.ts +2 -8
- package/lib/esm/hooks/click.d.ts.map +1 -1
- package/lib/esm/hooks/click.js +3 -42
- package/lib/esm/hooks/click.js.map +1 -1
- package/lib/esm/index.d.ts +1 -0
- package/lib/esm/index.d.ts.map +1 -1
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/plugins/url-tracking-plugin.d.ts +0 -3
- package/lib/esm/plugins/url-tracking-plugin.d.ts.map +1 -1
- package/lib/esm/plugins/url-tracking-plugin.js +9 -16
- package/lib/esm/plugins/url-tracking-plugin.js.map +1 -1
- package/lib/esm/semantic-identity.d.ts +1 -1
- package/lib/esm/semantic-identity.d.ts.map +1 -1
- package/lib/esm/semantic-identity.js +4 -3
- package/lib/esm/semantic-identity.js.map +1 -1
- package/lib/esm/semantic-types.d.ts +45 -0
- package/lib/esm/semantic-types.d.ts.map +1 -0
- package/lib/esm/semantic-types.js +2 -0
- package/lib/esm/semantic-types.js.map +1 -0
- package/lib/esm/semantic.d.ts +9 -12
- package/lib/esm/semantic.d.ts.map +1 -1
- package/lib/esm/semantic.js +17 -90
- package/lib/esm/semantic.js.map +1 -1
- package/lib/esm/session-replay.d.ts +39 -2
- package/lib/esm/session-replay.d.ts.map +1 -1
- package/lib/esm/session-replay.js +267 -132
- package/lib/esm/session-replay.js.map +1 -1
- package/lib/esm/utils/rrweb.d.ts +0 -3
- package/lib/esm/utils/rrweb.d.ts.map +1 -1
- package/lib/esm/utils/rrweb.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.d.ts.map +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/esm/version.js.map +1 -1
- package/lib/esm/window-focus.d.ts +40 -0
- package/lib/esm/window-focus.d.ts.map +1 -0
- package/lib/esm/window-focus.js +179 -0
- package/lib/esm/window-focus.js.map +1 -0
- package/lib/scripts/index-min.js +1 -1
- package/lib/scripts/index-min.js.gz +0 -0
- package/lib/scripts/index-min.js.map +1 -1
- package/lib/scripts/session-replay-browser-min.js +1 -1
- package/lib/scripts/session-replay-browser-min.js.gz +0 -0
- package/lib/scripts/session-replay-browser-min.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/config/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { AnalyticsContext, SemanticCaptureConfig } from '@amplitude/amp-semantic';\nimport type { PrivacyConfig } from '@amplitude/session-replay-dom-privacy';\nexport type { PrivacyConfig, MaskLevel } from '@amplitude/session-replay-dom-privacy';\nimport { IConfig, LogLevel, ILogger } from '@amplitude/analytics-core';\nimport { StoreType, ConsoleLogLevel } from '../typings/session-replay';\nimport { TargetingFlag } from '@amplitude/targeting';\nimport type { BodyCaptureRuleConfig } from '../network-body-capture';\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?: BodyCaptureRuleConfig;\n response?: BodyCaptureRuleConfig;\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 sr_semantic_config?: Partial<SemanticCaptureConfig>;\n};\n\nexport interface SessionReplayRemoteConfigAPIResponse {\n configs: {\n sessionReplay: SessionReplayRemoteConfig;\n };\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 /** Optional semantic events in the replay stream. Disabled by default. */\n semanticCapture?: SemanticCaptureConfig;\n /** @internal Supplied by the analytics plugin host. */\n semanticAnalyticsContext?: AnalyticsContext;\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 /**\n * When true, image sources are inlined as data URLs in the rrweb snapshot so replays do not\n * depend on fetching remote image assets at playback time. Increases snapshot payload size.\n * Passed through to rrweb's `inlineImages` record option; when unset, rrweb defaults to false.\n */\n inlineImages?: 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"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/config/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { SemanticAnalyticsContext, SemanticCaptureConfig, SemanticCaptureOptions } from '../semantic-types';\nimport type { PrivacyConfig } from '@amplitude/session-replay-dom-privacy';\nexport type { PrivacyConfig, MaskLevel } from '@amplitude/session-replay-dom-privacy';\nimport { IConfig, LogLevel, ILogger } from '@amplitude/analytics-core';\nimport { StoreType, ConsoleLogLevel } from '../typings/session-replay';\nimport { TargetingFlag } from '@amplitude/targeting';\nimport type { BodyCaptureRuleConfig } from '../network-body-capture';\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?: BodyCaptureRuleConfig;\n response?: BodyCaptureRuleConfig;\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 sr_semantic_config?: Partial<SemanticCaptureConfig>;\n};\n\nexport interface SessionReplayRemoteConfigAPIResponse {\n configs: {\n sessionReplay: SessionReplayRemoteConfig;\n };\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 /** Optional semantic events in the replay stream. Disabled by default. */\n semanticCapture?: SemanticCaptureOptions;\n /** @internal Supplied by the analytics plugin host. */\n semanticAnalyticsContext?: SemanticAnalyticsContext;\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 /**\n * When true, image sources are inlined as data URLs in the rrweb snapshot so replays do not\n * depend on fetching remote image assets at playback time. Increases snapshot payload size.\n * Passed through to rrweb's `inlineImages` record option; when unset, rrweb defaults to false.\n */\n inlineImages?: 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. 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.\n *\n * Switching browser tabs does not depend on this flag. Hiding the document flushes\n * mutations still waiting on the idle queue, and showing it takes one checkout snapshot\n * so playback is not left on an older snapshot from this tab or from another tab that\n * shares the session. `visibilitychange` fires once per tab switch, so that path stays\n * on when focus snapshots are off.\n *\n * Two windows that both stay visible never hide, so focus arriving from outside this\n * window still takes one checkout. Focus that only moved into an iframe in this page\n * does not. Leaving that iframe for another window does not blur the parent again;\n * the return still takes one checkout.\n *\n * @defaultValue false. Was `true` before the on-focus snapshot default changed.\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"]}
|
package/lib/esm/helpers.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE1E,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAQlD,eAAO,MAAM,aAAa,cAGzB,CAAC;AAEF,eAAO,MAAM,uBAAuB,cAAe,MAAM,GAAG,MAAM,YAAY,MAAM,KAAG,MAEtF,CAAC;AASF,eAAO,MAAM,sBAAsB,mBAAoB,aAAa,EAAE,SAUrE,CAAC;AAEF,eAAO,MAAM,UAAU,YAAa,MAAM,kBAAkB,aAAa,EAAE,WAW1E,CAAC;AAEF,eAAO,MAAM,cAAc,QAAa,QAAQ,WAAW,CAa1D,CAAC;AAEF,eAAO,MAAM,cAAc,WAAY,yBAAyB,KAAG,
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE1E,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAQlD,eAAO,MAAM,aAAa,cAGzB,CAAC;AAEF,eAAO,MAAM,uBAAuB,cAAe,MAAM,GAAG,MAAM,YAAY,MAAM,KAAG,MAEtF,CAAC;AASF,eAAO,MAAM,sBAAsB,mBAAoB,aAAa,EAAE,SAUrE,CAAC;AAEF,eAAO,MAAM,UAAU,YAAa,MAAM,kBAAkB,aAAa,EAAE,WAW1E,CAAC;AAEF,eAAO,MAAM,cAAc,QAAa,QAAQ,WAAW,CAa1D,CAAC;AAEF,eAAO,MAAM,cAAc,WAAY,yBAAyB,KAAG,yBAWlE,CAAC"}
|
package/lib/esm/helpers.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { __assign, __awaiter, __generator, __values } from "tslib";
|
|
1
|
+
import { __assign, __awaiter, __generator, __rest, __values } from "tslib";
|
|
2
2
|
import { getGlobalScope } from '@amplitude/analytics-core';
|
|
3
3
|
import { KB_SIZE } from './constants';
|
|
4
4
|
import { globToRegex } from '@amplitude/session-replay-dom-privacy';
|
|
@@ -72,9 +72,12 @@ export var getStorageSize = function () { return __awaiter(void 0, void 0, void
|
|
|
72
72
|
});
|
|
73
73
|
}); };
|
|
74
74
|
export var getDebugConfig = function (config) {
|
|
75
|
-
|
|
76
|
-
var
|
|
77
|
-
debugConfig
|
|
78
|
-
|
|
75
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
76
|
+
var loggerProvider = config.loggerProvider, rest = __rest(config, ["loggerProvider"]);
|
|
77
|
+
var debugConfig = __assign(__assign({}, rest), { apiKey: "****".concat(config.apiKey.substring(config.apiKey.length - 4)) });
|
|
78
|
+
// Debug config is attached to custom rrweb events, which a cross-origin iframe child
|
|
79
|
+
// forwards to its parent via postMessage. Round-trip through JSON so runtime values
|
|
80
|
+
// (logger, transport/handler functions, class instances) can't break structured clone.
|
|
81
|
+
return JSON.parse(JSON.stringify(debugConfig));
|
|
79
82
|
};
|
|
80
83
|
//# sourceMappingURL=helpers.js.map
|
package/lib/esm/helpers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/helpers.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEtC,OAAO,EAAE,WAAW,EAAE,MAAM,uCAAuC,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAQlD,MAAM,CAAC,IAAM,aAAa,GAAG;IAC3B,IAAM,WAAW,GAAG,cAAc,EAAE,CAAC;IACrC,OAAO,CAAA,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,QAAQ,EAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;AAChE,CAAC,CAAC;AAEF,MAAM,CAAC,IAAM,uBAAuB,GAAG,UAAC,SAA0B,EAAE,QAAgB;IAClF,OAAO,UAAG,QAAQ,cAAI,SAAS,CAAE,CAAC;A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cAAc,GAAc,MAAM,eAApB,EAAK,IAAI,UAAK,MAAM,EAApC,kBAA2B,CAAF,CAAY;IAC3C,IAAM,WAAW,yBACZ,IAAI,KACP,MAAM,EAAE,cAAO,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAE,GACnE,CAAC;IACF,qFAAqF;IACrF,oFAAoF;IACpF,uFAAuF;IACvF,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAA8B,CAAC;AAC9E,CAAC,CAAC","sourcesContent":["import { getGlobalScope } from '@amplitude/analytics-core';\nimport { SessionReplayJoinedConfig, UGCFilterRule } from './config/types';\nimport { KB_SIZE } from './constants';\nimport { StorageData } from './typings/session-replay';\nimport { globToRegex } from '@amplitude/session-replay-dom-privacy';\nexport { getServerUrl } from './utils/server-url';\n\ntype ChromeStorageEstimate = {\n quota?: number;\n usage?: number;\n usageDetails?: { [key: string]: number };\n};\n\nexport const getCurrentUrl = () => {\n const globalScope = getGlobalScope();\n return globalScope?.location ? globalScope.location.href : '';\n};\n\nexport const generateSessionReplayId = (sessionId: string | number, deviceId: string): string => {\n return `${deviceId}/${sessionId}`;\n};\n\nconst isValidGlobUrl = (globUrl: string): boolean => {\n if (typeof globUrl !== 'string' || globUrl.trim() === '') return false;\n const urlPattern = /^\\/|^https?:\\/\\/[^\\s]+$/;\n if (!urlPattern.test(globUrl)) return false;\n return true;\n};\n\nexport const validateUGCFilterRules = (ugcFilterRules: UGCFilterRule[]) => {\n // validate ugcFilterRules\n if (!ugcFilterRules.every((rule) => typeof rule.selector === 'string' && typeof rule.replacement === 'string')) {\n throw new Error('ugcFilterRules must be an array of objects with selector and replacement properties');\n }\n\n // validate ugcFilterRules are valid globs\n if (!ugcFilterRules.every((rule) => isValidGlobUrl(rule.selector))) {\n throw new Error('ugcFilterRules must be an array of objects with valid globs');\n }\n};\n\nexport const getPageUrl = (pageUrl: string, ugcFilterRules: UGCFilterRule[]) => {\n // apply ugcFilterRules, order is important, first rule wins\n for (const rule of ugcFilterRules) {\n const regex = globToRegex(rule.selector);\n\n if (regex.test(pageUrl)) {\n return pageUrl.replace(regex, rule.replacement);\n }\n }\n\n return pageUrl;\n};\n\nexport const getStorageSize = async (): Promise<StorageData> => {\n try {\n const globalScope = getGlobalScope();\n if (globalScope) {\n const { usage, quota, usageDetails }: ChromeStorageEstimate = await globalScope.navigator.storage.estimate();\n const totalStorageSize = usage ? Math.round(usage / KB_SIZE) : 0;\n const percentOfQuota = usage && quota ? Math.round((usage / quota + Number.EPSILON) * 1000) / 1000 : 0;\n return { totalStorageSize, percentOfQuota, usageDetails: JSON.stringify(usageDetails) };\n }\n } catch (e) {\n // swallow\n }\n return { totalStorageSize: 0, percentOfQuota: 0, usageDetails: '' };\n};\n\nexport const getDebugConfig = (config: SessionReplayJoinedConfig): SessionReplayJoinedConfig => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { loggerProvider, ...rest } = config;\n const debugConfig = {\n ...rest,\n apiKey: `****${config.apiKey.substring(config.apiKey.length - 4)}`,\n };\n // Debug config is attached to custom rrweb events, which a cross-origin iframe child\n // forwards to its parent via postMessage. Round-trip through JSON so runtime values\n // (logger, transport/handler functions, class instances) can't break structured clone.\n return JSON.parse(JSON.stringify(debugConfig)) as SessionReplayJoinedConfig;\n};\n"]}
|
package/lib/esm/hooks/click.d.ts
CHANGED
|
@@ -2,7 +2,6 @@ import type { mouseInteractionCallBack } from '@amplitude/rrweb-types';
|
|
|
2
2
|
import { Mirror } from '../utils/rrweb';
|
|
3
3
|
import { SessionReplayEventsManager as AmplitudeSessionReplayEventsManager } from '../typings/session-replay';
|
|
4
4
|
import { PayloadBatcher } from '../track-destination';
|
|
5
|
-
import { Options as FinderOptions } from '../libs/finder';
|
|
6
5
|
import { ILogger } from '@amplitude/analytics-core';
|
|
7
6
|
import { UGCFilterRule, InteractionPerformanceConfig } from '../config/types';
|
|
8
7
|
import { ScrollWatcher } from './scroll';
|
|
@@ -31,13 +30,8 @@ export declare const clickNonBatcher: PayloadBatcher;
|
|
|
31
30
|
export declare const clickBatcher: PayloadBatcher;
|
|
32
31
|
export declare class ClickHandler {
|
|
33
32
|
private readonly logger;
|
|
34
|
-
private readonly scrollWatcher
|
|
35
|
-
|
|
36
|
-
constructor(logger: ILogger, scrollWatcher?: ScrollWatcher);
|
|
37
|
-
/** Resolve once per native click when heatmaps and semantics use the same node. */
|
|
38
|
-
getSelector(element: Element, options?: Partial<FinderOptions>): string | null;
|
|
39
|
-
/** Both consumers run before heatmap batching; the native event stays in memory only. */
|
|
40
|
-
createSharedHook(heatmapHook?: mouseInteractionCallBack, semanticClick?: (event: MouseEvent) => void): (data: Parameters<mouseInteractionCallBack>[0], nativeEvent?: MouseEvent | TouchEvent) => void;
|
|
33
|
+
private readonly scrollWatcher;
|
|
34
|
+
constructor(logger: ILogger, scrollWatcher: ScrollWatcher);
|
|
41
35
|
createHook: (context: Context) => mouseInteractionCallBack;
|
|
42
36
|
}
|
|
43
37
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"click.d.ts","sourceRoot":"","sources":["../../../src/hooks/click.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAEvE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,0BAA0B,IAAI,mCAAmC,EAAE,MAAM,2BAA2B,CAAC;AAC9G,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"click.d.ts","sourceRoot":"","sources":["../../../src/hooks/click.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAEvE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,0BAA0B,IAAI,mCAAm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H"}
|
package/lib/esm/hooks/click.js
CHANGED
|
@@ -46,7 +46,6 @@ var ClickHandler = /** @class */ (function () {
|
|
|
46
46
|
this.createHook = function (_a) {
|
|
47
47
|
var eventsManager = _a.eventsManager, sessionId = _a.sessionId, deviceIdFn = _a.deviceIdFn, mirror = _a.mirror, ugcFilterRules = _a.ugcFilterRules, performanceOptions = _a.performanceOptions;
|
|
48
48
|
return function (e) {
|
|
49
|
-
var _a, _b, _c, _d, _e;
|
|
50
49
|
if (e.type !== MouseInteractions.Click) {
|
|
51
50
|
return;
|
|
52
51
|
}
|
|
@@ -67,7 +66,7 @@ var ClickHandler = /** @class */ (function () {
|
|
|
67
66
|
var selector;
|
|
68
67
|
if (node) {
|
|
69
68
|
try {
|
|
70
|
-
selector = (
|
|
69
|
+
selector = finder(node, performanceOptions);
|
|
71
70
|
}
|
|
72
71
|
catch (err) {
|
|
73
72
|
_this.logger.debug('error resolving selector from finder');
|
|
@@ -75,8 +74,8 @@ var ClickHandler = /** @class */ (function () {
|
|
|
75
74
|
}
|
|
76
75
|
var pageUrl = getPageUrl(location.href, ugcFilterRules);
|
|
77
76
|
var event = {
|
|
78
|
-
x: x +
|
|
79
|
-
y: y +
|
|
77
|
+
x: x + _this.scrollWatcher.currentScrollX,
|
|
78
|
+
y: y + _this.scrollWatcher.currentScrollY,
|
|
80
79
|
selector: selector,
|
|
81
80
|
viewportHeight: innerHeight,
|
|
82
81
|
viewportWidth: innerWidth,
|
|
@@ -93,44 +92,6 @@ var ClickHandler = /** @class */ (function () {
|
|
|
93
92
|
this.logger = logger;
|
|
94
93
|
this.scrollWatcher = scrollWatcher;
|
|
95
94
|
}
|
|
96
|
-
/** Resolve once per native click when heatmaps and semantics use the same node. */
|
|
97
|
-
ClickHandler.prototype.getSelector = function (element, options) {
|
|
98
|
-
var _a, _b, _c;
|
|
99
|
-
if ((_a = this.clickSelectors) === null || _a === void 0 ? void 0 : _a.has(element))
|
|
100
|
-
return (_b = this.clickSelectors.get(element)) !== null && _b !== void 0 ? _b : null;
|
|
101
|
-
var selector = finder(element, options);
|
|
102
|
-
(_c = this.clickSelectors) === null || _c === void 0 ? void 0 : _c.set(element, selector);
|
|
103
|
-
return selector;
|
|
104
|
-
};
|
|
105
|
-
/** Both consumers run before heatmap batching; the native event stays in memory only. */
|
|
106
|
-
ClickHandler.prototype.createSharedHook = function (heatmapHook, semanticClick) {
|
|
107
|
-
var _this = this;
|
|
108
|
-
return function (data, nativeEvent) {
|
|
109
|
-
if (data.type !== MouseInteractions.Click)
|
|
110
|
-
return;
|
|
111
|
-
var previous = _this.clickSelectors;
|
|
112
|
-
_this.clickSelectors = new Map();
|
|
113
|
-
try {
|
|
114
|
-
try {
|
|
115
|
-
heatmapHook === null || heatmapHook === void 0 ? void 0 : heatmapHook(data);
|
|
116
|
-
}
|
|
117
|
-
catch (error) {
|
|
118
|
-
_this.logger.debug('Heatmap click hook failed', error);
|
|
119
|
-
}
|
|
120
|
-
if ((nativeEvent === null || nativeEvent === void 0 ? void 0 : nativeEvent.type) === 'click') {
|
|
121
|
-
try {
|
|
122
|
-
semanticClick === null || semanticClick === void 0 ? void 0 : semanticClick(nativeEvent);
|
|
123
|
-
}
|
|
124
|
-
catch (error) {
|
|
125
|
-
_this.logger.debug('Semantic click hook failed', error);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
finally {
|
|
130
|
-
_this.clickSelectors = previous;
|
|
131
|
-
}
|
|
132
|
-
};
|
|
133
|
-
};
|
|
134
95
|
return ClickHandler;
|
|
135
96
|
}());
|
|
136
97
|
export { ClickHandler };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"click.js","sourceRoot":"","sources":["../../../src/hooks/click.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAI3D,OAAO,EAAE,MAAM,EAA4B,MAAM,gBAAgB,CAAC;AAClE,OAAO,EAAE,cAAc,EAAW,MAAM,2BAA2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,CAAC,cAAc,GAAG,QAAQ,CAAC;aAChC;QACH,CAAC,CAAC;IACJ,CAAC;IA4DH,mBAAC;AAAD,CAAC,AAxGD,IAwGC","sourcesContent":["import type { mouseInteractionCallBack } from '@amplitude/rrweb-types';\nimport { MouseInteractions } from '@amplitude/rrweb-types';\nimport { Mirror } from '../utils/rrweb';\nimport { SessionReplayEventsManager as AmplitudeSessionReplayEventsManager } from '../typings/session-replay';\nimport { PayloadBatcher } from '../track-destination';\nimport { finder, Options as FinderOptions } from '../libs/finder';\nimport { getGlobalScope, ILogger } from '@amplitude/analytics-core';\nimport { UGCFilterRule, InteractionPerformanceConfig } from '../config/types';\nimport { getPageUrl } from '../helpers';\nimport { ScrollWatcher } from './scroll';\n\n// exported for testing\nexport type ClickEvent = {\n timestamp: number;\n x: number;\n y: number;\n viewportWidth: number;\n viewportHeight: number;\n pageUrl: string;\n selector?: string;\n type: 'click';\n};\n\n// exported for testing\nexport type ClickEventWithCount = ClickEvent & { count: number };\n\ntype Context = {\n sessionId: string | number;\n deviceIdFn: () => string | undefined;\n eventsManager: AmplitudeSessionReplayEventsManager<'interaction', string>;\n mirror: Mirror;\n ugcFilterRules: UGCFilterRule[];\n performanceOptions?: InteractionPerformanceConfig;\n};\n\nconst HOUR_IN_MILLISECONDS = 3_600_000;\n\nexport const clickNonBatcher: PayloadBatcher = ({ version, events }) => {\n const clickEvents: ClickEvent[] = [];\n events.forEach((evt: string) => {\n const record = JSON.parse(evt) as Record<string, unknown>;\n record.count = 1;\n if (record.type === 'click') {\n clickEvents.push(record as ClickEvent);\n }\n });\n return { version, events: clickEvents };\n};\n\nexport const clickBatcher: PayloadBatcher = ({ version, events }) => {\n const clickEvents: ClickEvent[] = [];\n events.forEach((evt: string) => {\n const record = JSON.parse(evt) as Record<string, unknown>;\n if (record.type === 'click') {\n clickEvents.push(record as ClickEvent);\n }\n });\n\n const reduced = clickEvents.reduce<Record<string, ClickEventWithCount>>((prev, curr) => {\n const { x, y, selector, timestamp } = curr;\n\n // round down to nearest hour.\n const hour = timestamp - (timestamp % HOUR_IN_MILLISECONDS);\n\n const k = `${x}:${y}:${selector ?? ''}:${hour}`;\n if (!prev[k]) {\n prev[k] = { ...curr, timestamp: hour, count: 1 };\n } else {\n prev[k].count += 1;\n }\n return prev;\n }, {});\n\n return { version, events: Object.values(reduced) };\n};\n\nexport class ClickHandler {\n private readonly logger: ILogger;\n private readonly scrollWatcher?: ScrollWatcher;\n private clickSelectors?: Map<Element, string | null>;\n\n constructor(logger: ILogger, scrollWatcher?: ScrollWatcher) {\n this.logger = logger;\n this.scrollWatcher = scrollWatcher;\n }\n\n /** Resolve once per native click when heatmaps and semantics use the same node. */\n getSelector(element: Element, options?: Partial<FinderOptions>): string | null {\n if (this.clickSelectors?.has(element)) return this.clickSelectors.get(element) ?? null;\n const selector = finder(element, options);\n this.clickSelectors?.set(element, selector);\n return selector;\n }\n\n /** Both consumers run before heatmap batching; the native event stays in memory only. */\n createSharedHook(\n heatmapHook?: mouseInteractionCallBack,\n semanticClick?: (event: MouseEvent) => void,\n ): (data: Parameters<mouseInteractionCallBack>[0], nativeEvent?: MouseEvent | TouchEvent) => void {\n return (data, nativeEvent) => {\n if (data.type !== MouseInteractions.Click) return;\n const previous = this.clickSelectors;\n this.clickSelectors = new Map();\n try {\n try {\n heatmapHook?.(data);\n } catch (error) {\n this.logger.debug('Heatmap click hook failed', error);\n }\n if (nativeEvent?.type === 'click') {\n try {\n semanticClick?.(nativeEvent as MouseEvent);\n } catch (error) {\n this.logger.debug('Semantic click hook failed', error);\n }\n }\n } finally {\n this.clickSelectors = previous;\n }\n };\n }\n\n createHook: (context: Context) => mouseInteractionCallBack = ({\n eventsManager,\n sessionId,\n deviceIdFn,\n mirror,\n ugcFilterRules,\n performanceOptions,\n }) => {\n return (e) => {\n if (e.type !== MouseInteractions.Click) {\n return;\n }\n\n const globalScope = getGlobalScope();\n if (!globalScope) {\n return;\n }\n\n const { location, innerHeight, innerWidth } = globalScope;\n // it only makes sense to send events if a pageUrl exists\n if (!location) {\n return;\n }\n\n const { x, y } = e;\n if (x === undefined || y === undefined) {\n return;\n }\n\n const node = mirror.getNode(e.id);\n let selector;\n if (node) {\n try {\n selector = this.getSelector(node as Element, performanceOptions) ?? undefined;\n } catch (err) {\n this.logger.debug('error resolving selector from finder');\n }\n }\n\n const pageUrl = getPageUrl(location.href, ugcFilterRules);\n\n const event: ClickEvent = {\n x: x + (this.scrollWatcher?.currentScrollX ?? 0),\n y: y + (this.scrollWatcher?.currentScrollY ?? 0),\n selector,\n\n viewportHeight: innerHeight,\n viewportWidth: innerWidth,\n pageUrl,\n timestamp: Date.now(),\n type: 'click',\n };\n const deviceId = deviceIdFn();\n if (deviceId) {\n eventsManager.addEvent({ sessionId, event: { type: 'interaction', data: JSON.stringify(event) }, deviceId });\n }\n };\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"click.js","sourceRoot":"","sources":["../../../src/hooks/click.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAI3D,OAAO,EAAE,MAAM,EAA4B,MAAM,gBAAgB,CAAC;AAClE,OAAO,EAAE,cAAc,EAAW,MAAM,2BAA2B,CAAC;AAEpE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AA2BxC,IAAM,oBAAoB,GAAG,OAAS,CAAC;AAEvC,MAAM,CAAC,IAAM,eAAe,GAAmB,UAAC,EAAmB;QAAjB,OAAO,aAAA,EAAE,MAAM,YAAA;IAC/D,IAAM,WAAW,GAAiB,EAAE,CAAC;IACrC,MAAM,CAAC,OAAO,CAAC,UAAC,GAAW;QACzB,IAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAA4B,CAAC;QAC1D,MAAM,CAAC,KAAK,GAAG,CAAC,CAAC;QACjB,IAAI,MAAM,CAAC,IAAI,KAAK,OAAO,EAAE;YAC3B,WAAW,CAAC,IAAI,CAAC,MAAoB,CAAC,CAAC;SACxC;IACH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CAAC,GAAG,KAAI,CAAC,aAAa,CAAC,cAAc;oBACxC,CAAC,EAAE,CAAC,GAAG,KAAI,CAAC,aAAa,CAAC,cAAc;oBACxC,QAAQ,UAAA;oBAER,cAAc,EAAE,WAAW;oBAC3B,aAAa,EAAE,UAAU;oBACzB,OAAO,SAAA;oBACP,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;oBACrB,IAAI,EAAE,OAAO;iBACd,CAAC;gBACF,IAAM,QAAQ,GAAG,UAAU,EAAE,CAAC;gBAC9B,IAAI,QAAQ,EAAE;oBACZ,aAAa,CAAC,QAAQ,CAAC,EAAE,SAAS,WAAA,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,EAAE,QAAQ,UAAA,EAAE,CAAC,CAAC;iBAC9G;YACH,CAAC,CAAC;QACJ,CAAC,CAAC;QAhEA,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;IA+DH,mBAAC;AAAD,CAAC,AAtED,IAsEC","sourcesContent":["import type { mouseInteractionCallBack } from '@amplitude/rrweb-types';\nimport { MouseInteractions } from '@amplitude/rrweb-types';\nimport { Mirror } from '../utils/rrweb';\nimport { SessionReplayEventsManager as AmplitudeSessionReplayEventsManager } from '../typings/session-replay';\nimport { PayloadBatcher } from '../track-destination';\nimport { finder, Options as FinderOptions } from '../libs/finder';\nimport { getGlobalScope, ILogger } from '@amplitude/analytics-core';\nimport { UGCFilterRule, InteractionPerformanceConfig } from '../config/types';\nimport { getPageUrl } from '../helpers';\nimport { ScrollWatcher } from './scroll';\n\n// exported for testing\nexport type ClickEvent = {\n timestamp: number;\n x: number;\n y: number;\n viewportWidth: number;\n viewportHeight: number;\n pageUrl: string;\n selector?: string;\n type: 'click';\n};\n\n// exported for testing\nexport type ClickEventWithCount = ClickEvent & { count: number };\n\ntype Context = {\n sessionId: string | number;\n deviceIdFn: () => string | undefined;\n eventsManager: AmplitudeSessionReplayEventsManager<'interaction', string>;\n mirror: Mirror;\n ugcFilterRules: UGCFilterRule[];\n performanceOptions?: InteractionPerformanceConfig;\n};\n\nconst HOUR_IN_MILLISECONDS = 3_600_000;\n\nexport const clickNonBatcher: PayloadBatcher = ({ version, events }) => {\n const clickEvents: ClickEvent[] = [];\n events.forEach((evt: string) => {\n const record = JSON.parse(evt) as Record<string, unknown>;\n record.count = 1;\n if (record.type === 'click') {\n clickEvents.push(record as ClickEvent);\n }\n });\n return { version, events: clickEvents };\n};\n\nexport const clickBatcher: PayloadBatcher = ({ version, events }) => {\n const clickEvents: ClickEvent[] = [];\n events.forEach((evt: string) => {\n const record = JSON.parse(evt) as Record<string, unknown>;\n if (record.type === 'click') {\n clickEvents.push(record as ClickEvent);\n }\n });\n\n const reduced = clickEvents.reduce<Record<string, ClickEventWithCount>>((prev, curr) => {\n const { x, y, selector, timestamp } = curr;\n\n // round down to nearest hour.\n const hour = timestamp - (timestamp % HOUR_IN_MILLISECONDS);\n\n const k = `${x}:${y}:${selector ?? ''}:${hour}`;\n if (!prev[k]) {\n prev[k] = { ...curr, timestamp: hour, count: 1 };\n } else {\n prev[k].count += 1;\n }\n return prev;\n }, {});\n\n return { version, events: Object.values(reduced) };\n};\n\nexport class ClickHandler {\n private readonly logger: ILogger;\n private readonly scrollWatcher: ScrollWatcher;\n\n constructor(logger: ILogger, scrollWatcher: ScrollWatcher) {\n this.logger = logger;\n this.scrollWatcher = scrollWatcher;\n }\n\n createHook: (context: Context) => mouseInteractionCallBack = ({\n eventsManager,\n sessionId,\n deviceIdFn,\n mirror,\n ugcFilterRules,\n performanceOptions,\n }) => {\n return (e) => {\n if (e.type !== MouseInteractions.Click) {\n return;\n }\n\n const globalScope = getGlobalScope();\n if (!globalScope) {\n return;\n }\n\n const { location, innerHeight, innerWidth } = globalScope;\n // it only makes sense to send events if a pageUrl exists\n if (!location) {\n return;\n }\n\n const { x, y } = e;\n if (x === undefined || y === undefined) {\n return;\n }\n\n const node = mirror.getNode(e.id);\n let selector;\n if (node) {\n try {\n selector = finder(\n node as Element,\n performanceOptions as Pick<FinderOptions, 'timeoutMs' | 'maxNumberOfTries' | 'threshold'>,\n );\n } catch (err) {\n this.logger.debug('error resolving selector from finder');\n }\n }\n\n const pageUrl = getPageUrl(location.href, ugcFilterRules);\n\n const event: ClickEvent = {\n x: x + this.scrollWatcher.currentScrollX,\n y: y + this.scrollWatcher.currentScrollY,\n selector,\n\n viewportHeight: innerHeight,\n viewportWidth: innerWidth,\n pageUrl,\n timestamp: Date.now(),\n type: 'click',\n };\n const deviceId = deviceIdFn();\n if (deviceId) {\n eventsManager.addEvent({ sessionId, event: { type: 'interaction', data: JSON.stringify(event) }, deviceId });\n }\n };\n };\n}\n"]}
|
package/lib/esm/index.d.ts
CHANGED
|
@@ -5,4 +5,5 @@ export { SessionReplayOptions, StoreType } from './typings/session-replay';
|
|
|
5
5
|
export { SafeLoggerProvider } from './logger';
|
|
6
6
|
export { AmplitudeSessionReplay } from './typings/session-replay';
|
|
7
7
|
export { SendEventsRequest, FetchConfigRequest, SessionReplaySendEventsHandler, SessionReplayFetchConfigHandler, } from './config/types';
|
|
8
|
+
export type { SemanticCaptureConfig, SemanticCaptureOptions, SemanticCaptureFactory, SemanticCaptureHost, SemanticCaptureController, } from './semantic-types';
|
|
8
9
|
//# sourceMappingURL=index.d.ts.map
|
package/lib/esm/index.d.ts.map
CHANGED
|
@@ -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,KAAK,mEACL,IAAI,cACJ,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
|
+
{"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,KAAK,mEACL,IAAI,cACJ,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;AAExB,YAAY,EACV,qBAAqB,EACrB,sBAAsB,EACtB,sBAAsB,EACtB,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,kBAAkB,CAAC"}
|
package/lib/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,aAAa,MAAM,0BAA0B,CAAC;AACrD,MAAM,CACJ,IAAA,IAAI,GASF,aAAa,KATX,EACJ,YAAY,GAQV,aAAa,aARH,EACZ,YAAY,GAOV,aAAa,aAPH,EACZ,0BAA0B,GAMxB,aAAa,2BANW,EAC1B,KAAK,GAKH,aAAa,MALV,EACL,KAAK,GAIH,aAAa,MAJV,EACL,IAAI,GAGF,aAAa,KAHX,EACJ,QAAQ,GAEN,aAAa,SAFP,EACR,2BAA2B,GACzB,aAAa,4BADY,CACX;AAElB,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC","sourcesContent":["import sessionReplay from './session-replay-factory';\nexport const {\n init,\n setSessionId,\n getSessionId,\n getSessionReplayProperties,\n flush,\n start,\n stop,\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"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,aAAa,MAAM,0BAA0B,CAAC;AACrD,MAAM,CACJ,IAAA,IAAI,GASF,aAAa,KATX,EACJ,YAAY,GAQV,aAAa,aARH,EACZ,YAAY,GAOV,aAAa,aAPH,EACZ,0BAA0B,GAMxB,aAAa,2BANW,EAC1B,KAAK,GAKH,aAAa,MALV,EACL,KAAK,GAIH,aAAa,MAJV,EACL,IAAI,GAGF,aAAa,KAHX,EACJ,QAAQ,GAEN,aAAa,SAFP,EACR,2BAA2B,GACzB,aAAa,4BADY,CACX;AAElB,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC","sourcesContent":["import sessionReplay from './session-replay-factory';\nexport const {\n init,\n setSessionId,\n getSessionId,\n getSessionReplayProperties,\n flush,\n start,\n stop,\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\nexport type {\n SemanticCaptureConfig,\n SemanticCaptureOptions,\n SemanticCaptureFactory,\n SemanticCaptureHost,\n SemanticCaptureController,\n} from './semantic-types';\n"]}
|
|
@@ -31,14 +31,11 @@ export interface URLTrackingPluginOptions {
|
|
|
31
31
|
}
|
|
32
32
|
/** Options for subscribeToUrlChanges (polling vs history + hash) */
|
|
33
33
|
export interface SubscribeToUrlChangesOptions {
|
|
34
|
-
/** Optional navigation metadata for semantic capture; existing callbacks remain unchanged. */
|
|
35
|
-
onNavigation?: (reason: URLChangeReason) => void;
|
|
36
34
|
/** Use polling instead of history/popstate/hashchange (e.g. when history is unreliable) */
|
|
37
35
|
enablePolling?: boolean;
|
|
38
36
|
/** Polling interval in ms when enablePolling is true (default: 1000) */
|
|
39
37
|
pollingInterval?: number;
|
|
40
38
|
}
|
|
41
|
-
export type URLChangeReason = 'push' | 'replace' | 'pop' | 'hash';
|
|
42
39
|
/**
|
|
43
40
|
* Single helper for URL change detection. Supports:
|
|
44
41
|
* - History API (pushState/replaceState) + popstate + hashchange (shared patch per scope)
|
|
@@ -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,
|
|
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"}
|
|
@@ -30,14 +30,12 @@ export function subscribeToUrlChanges(globalScope, onUrlChange, options) {
|
|
|
30
30
|
var getHref_1 = function () { var _a; return (_a = globalScope.location.href) !== null && _a !== void 0 ? _a : ''; };
|
|
31
31
|
var lastHref_1 = getHref_1();
|
|
32
32
|
var id_1 = globalScope.setInterval(function () {
|
|
33
|
-
var _a;
|
|
34
33
|
var href = getHref_1();
|
|
35
34
|
if (href === lastHref_1) {
|
|
36
35
|
return;
|
|
37
36
|
}
|
|
38
37
|
lastHref_1 = href;
|
|
39
38
|
onUrlChange(href);
|
|
40
|
-
(_a = options.onNavigation) === null || _a === void 0 ? void 0 : _a.call(options, 'replace');
|
|
41
39
|
}, pollingInterval);
|
|
42
40
|
return function () {
|
|
43
41
|
if (id_1 != null) {
|
|
@@ -50,18 +48,18 @@ export function subscribeToUrlChanges(globalScope, onUrlChange, options) {
|
|
|
50
48
|
var lastHref_2 = undefined;
|
|
51
49
|
var callbacks_1 = new Set();
|
|
52
50
|
var getHref_2 = function () { var _a; return (_a = globalScope.location.href) !== null && _a !== void 0 ? _a : ''; };
|
|
53
|
-
var notify_1 = function (
|
|
51
|
+
var notify_1 = function () {
|
|
54
52
|
var href = getHref_2();
|
|
55
53
|
if (lastHref_2 !== undefined && href === lastHref_2)
|
|
56
54
|
return;
|
|
57
55
|
lastHref_2 = href;
|
|
58
|
-
callbacks_1.forEach(function (c) { return c(href
|
|
56
|
+
callbacks_1.forEach(function (c) { return c(href); });
|
|
59
57
|
};
|
|
60
58
|
/**
|
|
61
59
|
* Creates a patched version of history methods (pushState/replaceState)
|
|
62
60
|
* that calls the original method and then emits a URL change event.
|
|
63
61
|
*/
|
|
64
|
-
var createHistoryMethodPatch = function (originalMethod
|
|
62
|
+
var createHistoryMethodPatch = function (originalMethod) {
|
|
65
63
|
var patchedMethod = function () {
|
|
66
64
|
var args = [];
|
|
67
65
|
for (var _i = 0; _i < arguments.length; _i++) {
|
|
@@ -69,7 +67,7 @@ export function subscribeToUrlChanges(globalScope, onUrlChange, options) {
|
|
|
69
67
|
}
|
|
70
68
|
var result = originalMethod.apply(this, args);
|
|
71
69
|
// Read from location.href after history call so we always notify with resolved absolute URL.
|
|
72
|
-
notify_1(
|
|
70
|
+
notify_1();
|
|
73
71
|
return result;
|
|
74
72
|
};
|
|
75
73
|
patchedMethod[PATCH_MARKER] = true;
|
|
@@ -79,19 +77,19 @@ export function subscribeToUrlChanges(globalScope, onUrlChange, options) {
|
|
|
79
77
|
if (history_1 === null || history_1 === void 0 ? void 0 : history_1.pushState) {
|
|
80
78
|
var pushState = Reflect.get(history_1, 'pushState');
|
|
81
79
|
if (!pushState[PATCH_MARKER]) {
|
|
82
|
-
history_1.pushState = createHistoryMethodPatch(pushState
|
|
80
|
+
history_1.pushState = createHistoryMethodPatch(pushState);
|
|
83
81
|
}
|
|
84
82
|
}
|
|
85
83
|
if (history_1 === null || history_1 === void 0 ? void 0 : history_1.replaceState) {
|
|
86
84
|
var replaceState = Reflect.get(history_1, 'replaceState');
|
|
87
85
|
if (!replaceState[PATCH_MARKER]) {
|
|
88
|
-
history_1.replaceState = createHistoryMethodPatch(replaceState
|
|
86
|
+
history_1.replaceState = createHistoryMethodPatch(replaceState);
|
|
89
87
|
}
|
|
90
88
|
}
|
|
91
89
|
subscriptionState = {
|
|
92
90
|
callbacks: callbacks_1,
|
|
93
91
|
notify: notify_1,
|
|
94
|
-
onPopStateOrHashChange: function (
|
|
92
|
+
onPopStateOrHashChange: function () { return notify_1(); },
|
|
95
93
|
listenersAttached: false,
|
|
96
94
|
};
|
|
97
95
|
urlChangeSubscriptionsByScope.set(globalScope, subscriptionState);
|
|
@@ -102,14 +100,9 @@ export function subscribeToUrlChanges(globalScope, onUrlChange, options) {
|
|
|
102
100
|
globalScope.addEventListener('hashchange', state.onPopStateOrHashChange);
|
|
103
101
|
state.listenersAttached = true;
|
|
104
102
|
}
|
|
105
|
-
|
|
106
|
-
var _a;
|
|
107
|
-
onUrlChange(href);
|
|
108
|
-
(_a = options.onNavigation) === null || _a === void 0 ? void 0 : _a.call(options, reason);
|
|
109
|
-
};
|
|
110
|
-
state.callbacks.add(callback);
|
|
103
|
+
state.callbacks.add(onUrlChange);
|
|
111
104
|
return function () {
|
|
112
|
-
state.callbacks.delete(
|
|
105
|
+
state.callbacks.delete(onUrlChange);
|
|
113
106
|
if (state.callbacks.size === 0) {
|
|
114
107
|
// Do not restore history methods: we are not aware of patches applied by other scripts.
|
|
115
108
|
if (state.listenersAttached) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"url-tracking-plugin.js","sourceRoot":"","sources":["../../../src/plugins/url-tracking-plugin.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,OAAO,EAAE,mCAAmC,EAAE,MAAM,cAAc,CAAC;AA4CnE,wDAAwD;AACxD,IAAM,YAAY,GAAG,oCAAoC,CAAC;AAa1D,wGAAwG;AACxG,IAAM,6BAA6B,GAAG,IAAI,OAAO,EAAsC,CAAC;AAExF;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,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,mCAAmC,KAAA,CAAa;IAEjG,IAAI,aAAa,EAAE;QACjB,IAAM,SAAO,GAAG,sBAAc,OAAA,MAAA,W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KAAK,EAAE,YAAY;oBACnB,cAAc,EAAE,WAAW;oBAC3B,aAAa,EAAE,UAAU;oBACzB,IAAI,EAAE,kBAAkB;iBACzB,CAAC;YACJ,CAAC,CAAC;YAEF;;;eAGG;YACH,IAAM,aAAa,GAAG;gBACpB,IAAM,UAAU,GAAG,aAAa,EAAE,CAAC;gBACnC,IAAI,cAAc,KAAK,SAAS,IAAI,UAAU,KAAK,cAAc,EAAE;oBACjE,cAAc,GAAG,UAAU,CAAC;oBAC5B,IAAM,OAAK,GAAG,oBAAoB,EAAE,CAAC;oBACrC,EAAE,CAAC,OAAK,CAAC,CAAC;iBACX;YACH,CAAC,CAAC;YAEF,0EAA0E;YAC1E,IAAM,WAAW,GAAG,qBAAqB,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;AAED;;;GAGG;AACH,MAAM,CAAC,IAAM,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 /** Optional navigation metadata for semantic capture; existing callbacks remain unchanged. */\n onNavigation?: (reason: URLChangeReason) => void;\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\nexport type URLChangeReason = 'push' | 'replace' | 'pop' | 'hash';\n\ntype PatchableHistoryMethod<T extends (...args: any[]) => any> = T & { [PATCH_MARKER]?: boolean };\n\ninterface UrlChangeSubscriptionState {\n callbacks: Set<(href: string, reason: URLChangeReason) => void>;\n onPopStateOrHashChange: (event: Event) => void;\n notify: (reason: URLChangeReason) => 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 options.onNavigation?.('replace');\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, reason: URLChangeReason) => void>();\n\n const getHref = (): string => globalScope.location.href ?? '';\n\n const notify = (reason: URLChangeReason): void => {\n const href = getHref();\n if (lastHref !== undefined && href === lastHref) return;\n lastHref = href;\n callbacks.forEach((c) => c(href, reason));\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 reason: URLChangeReason,\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(reason);\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, 'push');\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, 'replace');\n }\n }\n\n subscriptionState = {\n callbacks,\n notify,\n onPopStateOrHashChange: (event) => notify(event?.type === 'hashchange' ? 'hash' : 'pop'),\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 const callback = (href: string, reason: URLChangeReason) => {\n onUrlChange(href);\n options.onNavigation?.(reason);\n };\n state.callbacks.add(callback);\n return (): void => {\n state.callbacks.delete(callback);\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"]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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"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SemanticIdentity } from '
|
|
1
|
+
import type { SemanticIdentity } from './semantic-types';
|
|
2
2
|
export declare const SEMANTIC_TAB_STORAGE_KEY = "AMP_semantic_tab_v1";
|
|
3
3
|
/** Called only when semantic capture accepts an event. Shared by SDK instances in this document. */
|
|
4
4
|
export declare function getSemanticIdentity(scope: Window): SemanticIdentity;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"semantic-identity.d.ts","sourceRoot":"","sources":["../../src/semantic-identity.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"semantic-identity.d.ts","sourceRoot":"","sources":["../../src/semantic-identity.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,eAAO,MAAM,wBAAwB,wBAAwB,CAAC;AAK9D,oGAAoG;AACpG,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,gBAAgB,CAkDnE"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { __assign } from "tslib";
|
|
2
|
-
import {
|
|
2
|
+
import { UUID } from '@amplitude/analytics-core';
|
|
3
3
|
export var SEMANTIC_TAB_STORAGE_KEY = 'AMP_semantic_tab_v1';
|
|
4
4
|
var identities = new WeakMap();
|
|
5
5
|
var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
@@ -9,7 +9,8 @@ export function getSemanticIdentity(scope) {
|
|
|
9
9
|
var existing = identities.get(document);
|
|
10
10
|
if (existing)
|
|
11
11
|
return existing;
|
|
12
|
-
var
|
|
12
|
+
var fallback = Object.freeze({ tab_id: UUID(), document_id: UUID() });
|
|
13
|
+
var identity = fallback;
|
|
13
14
|
// Child frames share their parent's sessionStorage. Do not claim its tab record.
|
|
14
15
|
if (scope.top === scope) {
|
|
15
16
|
try {
|
|
@@ -54,7 +55,7 @@ export function getSemanticIdentity(scope) {
|
|
|
54
55
|
}
|
|
55
56
|
catch (_a) {
|
|
56
57
|
// No storage access: identity lasts for this document only.
|
|
57
|
-
identity =
|
|
58
|
+
identity = fallback;
|
|
58
59
|
}
|
|
59
60
|
}
|
|
60
61
|
identities.set(document, identity);
|