@amplitude/analytics-core 2.39.0 → 2.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/lib/cjs/diagnostics/uncaught-sdk-errors.d.ts.map +1 -1
  2. package/lib/cjs/diagnostics/uncaught-sdk-errors.js +42 -12
  3. package/lib/cjs/diagnostics/uncaught-sdk-errors.js.map +1 -1
  4. package/lib/cjs/index.d.ts +5 -0
  5. package/lib/cjs/index.d.ts.map +1 -1
  6. package/lib/cjs/index.js +13 -1
  7. package/lib/cjs/index.js.map +1 -1
  8. package/lib/cjs/messenger/background-capture.d.ts +13 -0
  9. package/lib/cjs/messenger/background-capture.d.ts.map +1 -0
  10. package/lib/cjs/messenger/background-capture.js +64 -0
  11. package/lib/cjs/messenger/background-capture.js.map +1 -0
  12. package/lib/cjs/messenger/base-window-messenger.d.ts +100 -0
  13. package/lib/cjs/messenger/base-window-messenger.d.ts.map +1 -0
  14. package/lib/cjs/messenger/base-window-messenger.js +261 -0
  15. package/lib/cjs/messenger/base-window-messenger.js.map +1 -0
  16. package/lib/cjs/messenger/constants.d.ts +6 -0
  17. package/lib/cjs/messenger/constants.d.ts.map +1 -0
  18. package/lib/cjs/messenger/constants.js +15 -0
  19. package/lib/cjs/messenger/constants.js.map +1 -0
  20. package/lib/cjs/messenger/utils.d.ts +12 -0
  21. package/lib/cjs/messenger/utils.d.ts.map +1 -0
  22. package/lib/cjs/messenger/utils.js +48 -0
  23. package/lib/cjs/messenger/utils.js.map +1 -0
  24. package/lib/cjs/observers/network.d.ts.map +1 -1
  25. package/lib/cjs/observers/network.js +61 -42
  26. package/lib/cjs/observers/network.js.map +1 -1
  27. package/lib/cjs/types/element-interactions.d.ts +0 -1
  28. package/lib/cjs/types/element-interactions.d.ts.map +1 -1
  29. package/lib/cjs/types/element-interactions.js.map +1 -1
  30. package/lib/cjs/utils/safe-stringify.d.ts +4 -0
  31. package/lib/cjs/utils/safe-stringify.d.ts.map +1 -0
  32. package/lib/cjs/utils/safe-stringify.js +9 -0
  33. package/lib/cjs/utils/safe-stringify.js.map +1 -0
  34. package/lib/esm/diagnostics/uncaught-sdk-errors.d.ts.map +1 -1
  35. package/lib/esm/diagnostics/uncaught-sdk-errors.js +43 -13
  36. package/lib/esm/diagnostics/uncaught-sdk-errors.js.map +1 -1
  37. package/lib/esm/index.d.ts +5 -0
  38. package/lib/esm/index.d.ts.map +1 -1
  39. package/lib/esm/index.js +4 -0
  40. package/lib/esm/index.js.map +1 -1
  41. package/lib/esm/messenger/background-capture.d.ts +13 -0
  42. package/lib/esm/messenger/background-capture.d.ts.map +1 -0
  43. package/lib/esm/messenger/background-capture.js +60 -0
  44. package/lib/esm/messenger/background-capture.js.map +1 -0
  45. package/lib/esm/messenger/base-window-messenger.d.ts +100 -0
  46. package/lib/esm/messenger/base-window-messenger.d.ts.map +1 -0
  47. package/lib/esm/messenger/base-window-messenger.js +257 -0
  48. package/lib/esm/messenger/base-window-messenger.js.map +1 -0
  49. package/lib/esm/messenger/constants.d.ts +6 -0
  50. package/lib/esm/messenger/constants.d.ts.map +1 -0
  51. package/lib/esm/messenger/constants.js +12 -0
  52. package/lib/esm/messenger/constants.js.map +1 -0
  53. package/lib/esm/messenger/utils.d.ts +12 -0
  54. package/lib/esm/messenger/utils.d.ts.map +1 -0
  55. package/lib/esm/messenger/utils.js +43 -0
  56. package/lib/esm/messenger/utils.js.map +1 -0
  57. package/lib/esm/observers/network.d.ts.map +1 -1
  58. package/lib/esm/observers/network.js +59 -40
  59. package/lib/esm/observers/network.js.map +1 -1
  60. package/lib/esm/types/element-interactions.d.ts +0 -1
  61. package/lib/esm/types/element-interactions.d.ts.map +1 -1
  62. package/lib/esm/types/element-interactions.js.map +1 -1
  63. package/lib/esm/utils/safe-stringify.d.ts +4 -0
  64. package/lib/esm/utils/safe-stringify.d.ts.map +1 -0
  65. package/lib/esm/utils/safe-stringify.js +6 -0
  66. package/lib/esm/utils/safe-stringify.js.map +1 -0
  67. package/package.json +5 -1
@@ -1 +1 @@
1
- {"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/observers/network.ts"],"names":[],"mappings":";;;;AAAA,wBAAoC;AACpC,sCAAqC;AAErC,kEAUkC;AAalC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,KAAK,IAAI,IAAI,KAAK,IAAI,WAAW,IAAI,QAAQ,IAAI,WAAW,CAAC;AACpH,CAAC;AAID;IACE,8BAA4B,QAA8C,EAAkB,EAAmB;QAAnB,mBAAA,EAAA,SAAa,WAAI,GAAE;QAAnF,aAAQ,GAAR,QAAQ,CAAsC;QAAkB,OAAE,GAAF,EAAE,CAAiB;IAAG,CAAC;IACrH,2BAAC;AAAD,CAAC,AAFD,IAEC;AAFY,oDAAoB;AAuBjC;IAME,yBAAY,MAAgB;QALpB,mBAAc,GAAsC,IAAI,GAAG,EAAE,CAAC;QAI9D,gBAAW,GAAG,KAAK,CAAC;QAE1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAM,WAAW,GAAG,IAAA,kBAAc,GAAE,CAAC;QACrC,IAAI,CAAC,eAAe,CAAC,WAAW,EAAE,EAAE;YAClC,0BAA0B;YAC1B,OAAO;SACR;QACD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAEM,2BAAW,GAAlB;QACE,IAAM,WAAW,GAAG,IAAA,kBAAc,GAAE,CAAC;QACrC,OAAO,CAAC,CAAC,WAAW,IAAI,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC;IAC9C,CAAC;IAED,mCAAS,GAAT,UAAU,aAAmC,EAAE,MAAgB;;QAC7D,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;YAChB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;SACtB;QACD,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,EAAE,aAAa,CA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id';\nimport { ILogger } from '../logger';\nimport {\n IRequestWrapper,\n NetworkRequestEvent,\n RequestWrapperFetch,\n ResponseWrapperFetch,\n RequestWrapperXhr,\n ResponseWrapperXhr,\n IResponseWrapper,\n RequestInitSafe,\n XMLHttpRequestBodyInitSafe,\n} from '../network-request-event';\n\n// object that is added to each XHR instance so\n// that info can be set in xhr.open and retrieved in xhr.send\ntype AmplitudeAnalyticsEvent = {\n method: string;\n url: string | URL;\n startTime: number;\n durationStart: number;\n status?: number;\n headers: Record<string, string>;\n};\n\n/**\n * Typeguard function checks if an input is a Request object.\n */\nfunction isRequest(requestInfo: any): requestInfo is Request {\n return typeof requestInfo === 'object' && requestInfo !== null && 'url' in requestInfo && 'method' in requestInfo;\n}\n\nexport type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;\n\nexport class NetworkEventCallback {\n constructor(public readonly callback: (event: NetworkRequestEvent) => void, public readonly id: string = UUID()) {}\n}\n\ntype RequestUrlAndMethod = {\n url: string | URL | undefined;\n method: string | undefined;\n};\n\n// A narrowed down [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) type\n// that only includes the properties we need to access and adds the $$AmplitudeAnalyticsEvent property\n// Use great care when modifying this type, make sure you only use read-only properties and only add\n// what you need to access, nothing more.\ntype AmplitudeXMLHttpRequestSafe = {\n $$AmplitudeAnalyticsEvent: AmplitudeAnalyticsEvent;\n status: number;\n responseText: string;\n responseType: XMLHttpRequestResponseType;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nexport class NetworkObserver {\n private eventCallbacks: Map<string, NetworkEventCallback> = new Map();\n // eslint-disable-next-line no-restricted-globals\n private globalScope?: typeof globalThis;\n private logger?: ILogger;\n private isObserving = false;\n constructor(logger?: ILogger) {\n this.logger = logger;\n const globalScope = getGlobalScope();\n if (!NetworkObserver.isSupported()) {\n /* istanbul ignore next */\n return;\n }\n this.globalScope = globalScope;\n }\n\n static isSupported(): boolean {\n const globalScope = getGlobalScope();\n return !!globalScope && !!globalScope.fetch;\n }\n\n subscribe(eventCallback: NetworkEventCallback, logger?: ILogger) {\n if (!this.logger) {\n this.logger = logger;\n }\n this.eventCallbacks.set(eventCallback.id, eventCallback);\n if (!this.isObserving) {\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrOpen = this.globalScope?.XMLHttpRequest?.prototype?.open;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSend = this.globalScope?.XMLHttpRequest?.prototype?.send;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\n }\n\n /* istanbul ignore next */\n const originalFetch = this.globalScope?.fetch;\n /* istanbul ignore next */\n if (originalFetch) {\n this.observeFetch(originalFetch);\n }\n\n /* istanbul ignore next */\n this.isObserving = true;\n }\n }\n\n unsubscribe(eventCallback: NetworkEventCallback) {\n this.eventCallbacks.delete(eventCallback.id);\n }\n\n protected triggerEventCallbacks(event: NetworkRequestEvent) {\n this.eventCallbacks.forEach((callback) => {\n try {\n callback.callback(event);\n } catch (err) {\n // if the callback throws an error, we should catch it\n // to avoid breaking the fetch promise chain\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n }\n });\n }\n\n handleNetworkRequestEvent(\n requestType: 'fetch' | 'xhr',\n requestInfo: RequestInfo | URL | RequestUrlAndMethod | undefined,\n requestWrapper: IRequestWrapper | undefined,\n responseWrapper: IResponseWrapper | undefined,\n typedError: Error | undefined,\n startTime?: number,\n durationStart?: number,\n ) {\n /* istanbul ignore next */\n if (startTime === undefined || durationStart === undefined) {\n // if we reach this point, it means that the performance API is not supported\n // so we can't construct a NetworkRequestEvent\n return;\n }\n\n // parse the URL and Method\n let url: string | undefined;\n let method = 'GET';\n if (isRequest(requestInfo)) {\n url = requestInfo['url'];\n method = requestInfo['method'];\n } else {\n url = requestInfo?.toString?.();\n }\n\n // strip basic auth from the URL\n if (url) {\n try {\n const parsedUrl = new URL(url);\n // reconstruct the URL without the basic auth\n url = `${parsedUrl.protocol}//${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;\n // eslint-disable-next-line no-empty\n } catch (err) {}\n }\n method = requestWrapper?.method || method;\n\n let status, error;\n if (responseWrapper) {\n status = responseWrapper.status;\n }\n\n if (typedError) {\n error = {\n name: typedError.name || 'UnknownError',\n message: typedError.message || 'An unknown error occurred',\n };\n status = 0;\n }\n\n const duration = Math.floor(performance.now() - durationStart);\n const endTime = Math.floor(startTime + duration);\n\n const requestEvent = new NetworkRequestEvent(\n requestType,\n method,\n startTime, // timestamp and startTime are aliases\n startTime,\n url,\n requestWrapper,\n status,\n duration,\n responseWrapper,\n error,\n endTime,\n );\n\n this.triggerEventCallbacks(requestEvent);\n }\n\n private getTimestamps() {\n /* istanbul ignore next */\n return {\n startTime: Date.now?.(),\n durationStart: performance?.now?.(),\n };\n }\n\n private observeFetch(\n originalFetch: (requestInfo: RequestInfo | URL, requestInit?: RequestInit) => Promise<Response>,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalFetch) {\n return;\n }\n /**\n * IMPORTANT: This overrides window.fetch in browsers.\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of fetch\n * and make sure another developer who is an expert reviews this change throughly\n */\n this.globalScope.fetch = async (requestInfo?: RequestInfo | URL, requestInit?: RequestInit) => {\n // 1: capture the start time and duration start time before the fetch call\n let timestamps;\n try {\n timestamps = this.getTimestamps();\n } catch (error) {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while retrieving timestamps', error);\n }\n\n // 2. make the call to the original fetch and preserve the response or error\n let originalResponse, originalError;\n try {\n originalResponse = await originalFetch(requestInfo as RequestInfo | URL, requestInit);\n } catch (err) {\n // Capture error information\n originalError = err;\n }\n\n // 3. call the handler after the fetch call is done\n try {\n this.handleNetworkRequestEvent(\n 'fetch',\n requestInfo,\n requestInit ? new RequestWrapperFetch(requestInit as RequestInitSafe) : undefined,\n originalResponse ? new ResponseWrapperFetch(originalResponse) : undefined,\n originalError as Error,\n /* istanbul ignore next */\n timestamps?.startTime,\n /* istanbul ignore next */\n timestamps?.durationStart,\n );\n } catch (err) {\n // this catch shouldn't be reachable, but keep it here for safety\n // because we're overriding the fetch function and better to be safe than sorry\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while handling fetch', err);\n }\n\n // 4. return the original response or throw the original error\n if (originalResponse) {\n // if the response is not undefined, return it\n return originalResponse;\n } else {\n throw originalError;\n }\n };\n }\n\n /**\n * Creates a function that parses the response of an XMLHttpRequest as JSON.\n *\n * Returns function instead of JSON object to avoid unnecessary parsing if the\n * body is not being captured.\n *\n * @param xhrSafe - The XMLHttpRequest object.\n * @param context - The NetworkObserver instance.\n * @returns A function that parses the response of an XMLHttpRequest as JSON.\n */\n static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver) {\n return () => {\n try {\n if (xhrUnsafe.responseType === 'json') {\n // if response is a JS object, clone it so that subscribers can't mutate it\n if (context.globalScope?.structuredClone) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return context.globalScope.structuredClone(xhrUnsafe.response);\n }\n } else if (['text', ''].includes(xhrUnsafe.responseType)) {\n // if response is a string, parse it as JSON\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return JSON.parse(xhrUnsafe.responseText);\n }\n } catch (err) {\n /* istanbul ignore if */\n if (err instanceof Error && err.name === 'InvalidStateError') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions\n // if we reach here, it means we don't handle responseType correctly\n context.logger?.error(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\n );\n }\n // the other possible error is Json Parse error which we fail silently\n return null;\n }\n return null;\n };\n }\n\n private observeXhr(\n originalXhrOpen:\n | ((\n method: string,\n url: string | URL,\n async?: boolean,\n username?: string | null,\n password?: string | null,\n ) => void)\n | undefined,\n originalXhrSend: ((body?: Document | XMLHttpRequestBodyInit | null) => void) | undefined,\n originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {\n return;\n }\n\n const xhrProto = this.globalScope.XMLHttpRequest.prototype;\n\n const networkObserverContext = this as NetworkObserver;\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.open\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.open\n * and make sure another developer who is an expert reviews this change throughly\n */\n xhrProto.open = function (...args: any[]) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const [method, url] = args as [string, string | URL];\n try {\n /* istanbul ignore next */\n xhrSafe.$$AmplitudeAnalyticsEvent = {\n method,\n url: url?.toString?.(),\n headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr open', err);\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return originalXhrOpen.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.send\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.send\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.send = function (...args: any[]) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhrUnsafe = this;\n const xhrSafe = xhrUnsafe as unknown as AmplitudeXMLHttpRequestSafe;\n const getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n getJson,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\n requestEvent.status = xhrSafe.status;\n networkObserverContext.handleNetworkRequestEvent(\n 'xhr',\n { url: requestEvent.url, method: requestEvent.method },\n requestWrapper,\n responseWrapper,\n undefined,\n requestEvent.startTime,\n requestEvent.durationStart,\n );\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while handling xhr send', err);\n }\n });\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.setRequestHeader\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr setRequestHeader', err);\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
1
+ {"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/observers/network.ts"],"names":[],"mappings":";;;;AAAA,gDAAiD;AACjD,sCAAqC;AAErC,kEAUkC;AAalC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,KAAK,IAAI,IAAI,KAAK,IAAI,WAAW,IAAI,QAAQ,IAAI,WAAW,CAAC;AACpH,CAAC;AAID;IACE,8BAA4B,QAA8C,EAAkB,EAAmB;QAAnB,mBAAA,EAAA,SAAa,WAAI,GAAE;QAAnF,aAAQ,GAAR,QAAQ,CAAsC;QAAkB,OAAE,GAAF,EAAE,CAAiB;IAAG,CAAC;IACrH,2BAAC;AAAD,CAAC,AAFD,IAEC;AAFY,oDAAoB;AAuBjC,SAAS,UAAU,CAAC,EAAc;IAChC,IAAI;QACF,EAAE,EAAE,CAAC;KACN;IAAC,OAAO,GAAG,EAAE;QACZ,oBAAoB;KACrB;AACH,CAAC;AAED;IAME,yBAAY,MAAgB;QALpB,mBAAc,GAAsC,IAAI,GAAG,EAAE,CAAC;QAI9D,gBAAW,GAAG,KAAK,CAAC;QAE1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAM,WAAW,GAAG,IAAA,6BAAc,GAAE,CAAC;QACrC,IAAI,CAAC,eAAe,CAAC,WAAW,EAAE,EAAE;YAClC,0BAA0B;YAC1B,OAAO;SACR;QACD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAEM,2BAAW,GAAlB;QACE,IAAM,WAAW,GAAG,IAAA,6BAAc,GAAE,CAAC;QACrC,OAAO,CAAC,CAAC,WAAW,IAAI,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC;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AAO,GAAG,IAA8C,CAAC;YAC/D,IAAI;gBACF,IAAM,cAAc,GAAG,OAAO,CAAC,yBAAyB,CAAC;gBACzD,IAAI,cAAc,EAAE;oBAClB,sEAAsE;oBACtE,cAAc,CAAC,OAAO,CAAC,UAAoB,CAAC,GAAG,WAAqB,CAAC;iBACtE;aACF;YAAC,OAAO,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,UAAU,CAAC,sBACT,OAAA,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAA,EAAA,CAC7G,CAAC;aACH;YACD,oEAAoE;YACpE,2BAA2B,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;QACxE,CAAC,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AAhYD,IAgYC;AAhYY,0CAAe;AAkY5B,wCAAwC;AAC3B,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from '../global-scope';\nimport { UUID } from '../utils/uuid';\nimport { ILogger } from '../logger';\nimport {\n IRequestWrapper,\n NetworkRequestEvent,\n RequestWrapperFetch,\n ResponseWrapperFetch,\n RequestWrapperXhr,\n ResponseWrapperXhr,\n IResponseWrapper,\n RequestInitSafe,\n XMLHttpRequestBodyInitSafe,\n} from '../network-request-event';\n\n// object that is added to each XHR instance so\n// that info can be set in xhr.open and retrieved in xhr.send\ntype AmplitudeAnalyticsEvent = {\n method: string;\n url: string | URL;\n startTime: number;\n durationStart: number;\n status?: number;\n headers: Record<string, string>;\n};\n\n/**\n * Typeguard function checks if an input is a Request object.\n */\nfunction isRequest(requestInfo: any): requestInfo is Request {\n return typeof requestInfo === 'object' && requestInfo !== null && 'url' in requestInfo && 'method' in requestInfo;\n}\n\nexport type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;\n\nexport class NetworkEventCallback {\n constructor(public readonly callback: (event: NetworkRequestEvent) => void, public readonly id: string = UUID()) {}\n}\n\ntype RequestUrlAndMethod = {\n url: string | URL | undefined;\n method: string | undefined;\n};\n\n// A narrowed down [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) type\n// that only includes the properties we need to access and adds the $$AmplitudeAnalyticsEvent property\n// Use great care when modifying this type, make sure you only use read-only properties and only add\n// what you need to access, nothing more.\ntype AmplitudeXMLHttpRequestSafe = {\n $$AmplitudeAnalyticsEvent: AmplitudeAnalyticsEvent;\n status: number;\n responseText: string;\n responseType: XMLHttpRequestResponseType;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nfunction safeInvoke(fn: () => void) {\n try {\n fn();\n } catch (err) {\n // swallow the error\n }\n}\n\nexport class NetworkObserver {\n private eventCallbacks: Map<string, NetworkEventCallback> = new Map();\n // eslint-disable-next-line no-restricted-globals\n private globalScope?: typeof globalThis;\n private logger?: ILogger;\n private isObserving = false;\n constructor(logger?: ILogger) {\n this.logger = logger;\n const globalScope = getGlobalScope();\n if (!NetworkObserver.isSupported()) {\n /* istanbul ignore next */\n return;\n }\n this.globalScope = globalScope;\n }\n\n static isSupported(): boolean {\n const globalScope = getGlobalScope();\n return !!globalScope && !!globalScope.fetch;\n }\n\n subscribe(eventCallback: NetworkEventCallback, logger?: ILogger) {\n if (!this.logger) {\n this.logger = logger;\n }\n this.eventCallbacks.set(eventCallback.id, eventCallback);\n if (!this.isObserving) {\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrOpen = this.globalScope?.XMLHttpRequest?.prototype?.open;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSend = this.globalScope?.XMLHttpRequest?.prototype?.send;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\n }\n\n /* istanbul ignore next */\n const originalFetch = this.globalScope?.fetch;\n /* istanbul ignore next */\n if (originalFetch) {\n this.observeFetch(originalFetch);\n }\n\n /* istanbul ignore next */\n this.isObserving = true;\n }\n }\n\n unsubscribe(eventCallback: NetworkEventCallback) {\n this.eventCallbacks.delete(eventCallback.id);\n }\n\n protected triggerEventCallbacks(event: NetworkRequestEvent) {\n this.eventCallbacks.forEach((callback) => {\n try {\n callback.callback(event);\n } catch (err) {\n // if the callback throws an error, we should catch it\n // to avoid breaking the fetch promise chain\n safeInvoke(() => {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n });\n }\n });\n }\n\n handleNetworkRequestEvent(\n requestType: 'fetch' | 'xhr',\n requestInfo: RequestInfo | URL | RequestUrlAndMethod | undefined,\n requestWrapper: IRequestWrapper | undefined,\n responseWrapper: IResponseWrapper | undefined,\n typedError: Error | undefined,\n startTime?: number,\n durationStart?: number,\n ) {\n /* istanbul ignore next */\n if (startTime === undefined || durationStart === undefined) {\n // if we reach this point, it means that the performance API is not supported\n // so we can't construct a NetworkRequestEvent\n return;\n }\n\n // parse the URL and Method\n let url: string | undefined;\n let method = 'GET';\n if (isRequest(requestInfo)) {\n url = requestInfo['url'];\n method = requestInfo['method'];\n } else {\n url = requestInfo?.toString?.();\n }\n\n // strip basic auth from the URL\n if (url) {\n try {\n const parsedUrl = new URL(url);\n // reconstruct the URL without the basic auth\n url = `${parsedUrl.protocol}//${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;\n // eslint-disable-next-line no-empty\n } catch (err) {}\n }\n method = requestWrapper?.method || method;\n\n let status, error;\n if (responseWrapper) {\n status = responseWrapper.status;\n }\n\n if (typedError) {\n error = {\n name: typedError.name || 'UnknownError',\n message: typedError.message || 'An unknown error occurred',\n };\n status = 0;\n }\n\n const duration = Math.floor(performance.now() - durationStart);\n const endTime = Math.floor(startTime + duration);\n\n const requestEvent = new NetworkRequestEvent(\n requestType,\n method,\n startTime, // timestamp and startTime are aliases\n startTime,\n url,\n requestWrapper,\n status,\n duration,\n responseWrapper,\n error,\n endTime,\n );\n\n this.triggerEventCallbacks(requestEvent);\n }\n\n private getTimestamps() {\n /* istanbul ignore next */\n return {\n startTime: Date.now?.(),\n durationStart: performance?.now?.(),\n };\n }\n\n private observeFetch(\n originalFetch: (requestInfo: RequestInfo | URL, requestInit?: RequestInit) => Promise<Response>,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalFetch) {\n return;\n }\n /**\n * IMPORTANT: This overrides window.fetch in browsers.\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of fetch\n * and make sure another developer who is an expert reviews this change throughly\n */\n this.globalScope.fetch = async (requestInfo?: RequestInfo | URL, requestInit?: RequestInit) => {\n // 1: capture the start time and duration start time before the fetch call\n let timestamps;\n try {\n timestamps = this.getTimestamps();\n } catch (error) {\n /* istanbul ignore next */\n safeInvoke(() => this.logger?.debug('an unexpected error occurred while retrieving timestamps', error));\n }\n\n // 2. make the call to the original fetch and preserve the response or error\n let originalResponse, originalError;\n try {\n originalResponse = await originalFetch(requestInfo as RequestInfo | URL, requestInit);\n } catch (err) {\n // Capture error information\n originalError = err;\n }\n\n // 3. call the handler after the fetch call is done\n try {\n this.handleNetworkRequestEvent(\n 'fetch',\n requestInfo,\n requestInit ? new RequestWrapperFetch(requestInit as RequestInitSafe) : undefined,\n originalResponse ? new ResponseWrapperFetch(originalResponse) : undefined,\n originalError as Error,\n /* istanbul ignore next */\n timestamps?.startTime,\n /* istanbul ignore next */\n timestamps?.durationStart,\n );\n } catch (err) {\n // this catch shouldn't be reachable, but keep it here for safety\n // because we're overriding the fetch function and better to be safe than sorry\n /* istanbul ignore next */\n safeInvoke(() => this.logger?.debug('an unexpected error occurred while handling fetch', err));\n }\n\n // 4. return the original response or throw the original error\n if (originalResponse) {\n // if the response is not undefined, return it\n return originalResponse;\n } else {\n throw originalError;\n }\n };\n }\n\n /**\n * Creates a function that parses the response of an XMLHttpRequest as JSON.\n *\n * Returns function instead of JSON object to avoid unnecessary parsing if the\n * body is not being captured.\n *\n * @param xhrSafe - The XMLHttpRequest object.\n * @param context - The NetworkObserver instance.\n * @returns A function that parses the response of an XMLHttpRequest as JSON.\n */\n static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver) {\n return () => {\n try {\n if (xhrUnsafe.responseType === 'json') {\n // if response is a JS object, clone it so that subscribers can't mutate it\n if (context.globalScope?.structuredClone) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return context.globalScope.structuredClone(xhrUnsafe.response);\n }\n } else if (['text', ''].includes(xhrUnsafe.responseType)) {\n // if response is a string, parse it as JSON\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return JSON.parse(xhrUnsafe.responseText);\n }\n } catch (err) {\n /* istanbul ignore if */\n if (err instanceof Error && err.name === 'InvalidStateError') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions\n // if we reach here, it means we don't handle responseType correctly\n safeInvoke(() =>\n context.logger?.debug(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\n ),\n );\n }\n // the other possible error is Json Parse error which we fail silently\n return null;\n }\n return null;\n };\n }\n\n private observeXhr(\n originalXhrOpen:\n | ((\n method: string,\n url: string | URL,\n async?: boolean,\n username?: string | null,\n password?: string | null,\n ) => void)\n | undefined,\n originalXhrSend: ((body?: Document | XMLHttpRequestBodyInit | null) => void) | undefined,\n originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {\n return;\n }\n\n const xhrProto = this.globalScope.XMLHttpRequest.prototype;\n\n const networkObserverContext = this as NetworkObserver;\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.open\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.open\n * and make sure another developer who is an expert reviews this change throughly\n */\n xhrProto.open = function (...args: any[]) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const [method, url] = args as [string, string | URL];\n try {\n /* istanbul ignore next */\n xhrSafe.$$AmplitudeAnalyticsEvent = {\n method,\n url: url?.toString?.(),\n headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr open', err),\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return originalXhrOpen.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.send\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.send\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.send = function (...args: any[]) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhrUnsafe = this;\n const xhrSafe = xhrUnsafe as unknown as AmplitudeXMLHttpRequestSafe;\n const getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n // if xhrSafe.$$AmplitudeAnalyticsEvent is not set, it means that\n // the xhr.open method was called before we monkey-patched XHR and\n // the event is missed\n if (xhrSafe.$$AmplitudeAnalyticsEvent) {\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n getJson,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\n requestEvent.status = xhrSafe.status;\n networkObserverContext.handleNetworkRequestEvent(\n 'xhr',\n { url: requestEvent.url, method: requestEvent.method },\n requestWrapper,\n responseWrapper,\n undefined,\n requestEvent.startTime,\n requestEvent.durationStart,\n );\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while handling xhr send', err),\n );\n }\n });\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.setRequestHeader\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n const analyticsEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n if (analyticsEvent) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n analyticsEvent.headers[headerName as string] = headerValue as string;\n }\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr setRequestHeader', err),\n );\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
@@ -59,7 +59,6 @@ export interface ElementInteractionsOptions {
59
59
  */
60
60
  visualTaggingOptions?: {
61
61
  enabled?: boolean;
62
- messenger?: Messenger;
63
62
  };
64
63
  /**
65
64
  * This has been deprecated in favor of rage clicks tracking
@@ -1 +1 @@
1
- {"version":3,"file":"element-interactions.d.ts","sourceRoot":"","sources":["../../../src/types/element-interactions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,QAAQ,CAAC;AAE5C;;;;;;;;GAQG;AACH,eAAO,MAAM,8BAA8B,UAY1C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,6BAA6B,oBAAoB,CAAC;AAE/D;;GAEG;AACH,eAAO,MAAM,8BAA8B,UAAsD,CAAC;AAElG,MAAM,WAAW,0BAA0B;IACzC;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAEhC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAEvC;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,GAAG;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,EAAE,CAAC;IAE/D;;;;;;;OAOG;IACH,wBAAwB,CAAC,EAAE,CAAC,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,KAAK,OAAO,CAAC;IAEpF;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,oBAAoB,CAAC,EAAE;QACrB,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,SAAS,CAAC,EAAE,SAAS,CAAC;KACvB,CAAC;IAEF;;;;;;;OAOG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;OAEG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAEhC;;OAEG;IACH,WAAW,CAAC,EAAE;QACZ,QAAQ,EAAE,OAAO,EAAE,CAAC;QACpB,aAA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ACzC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,GACD;IACE,UAAU,EAAE,cAAc,CAAC;IAC3B,YAAY,EAAE,MAAM,CAAC;CACtB,CACJ,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,0BAA0B,GAAG,+BAA+B,CAAC;AAE3F,MAAM,MAAM,MAAM,GAAG;IACnB,WAAW,EAAE,eAAe,CAAC;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,EAAE,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE;QACV,UAAU,EAAE,6BAA6B,GAAG,6BAA6B,CAAC;QAC1E,OAAO,EAAE,MAAM,EAAE,CAAC;KACnB,EAAE,CAAC;CACL,CAAC;AAEF,MAAM,WAAW,SAAS;IACxB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAKD,KAAK,UAAU,GAAG,OAAO,UAAU,SAAS;IAC1C,OAAO,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,CAAC;CACxC,GACG,CAAC,GACD,KAAK,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"element-interactions.js","sourceRoot":"","sources":["../../../src/types/element-interactions.ts"],"names":[],"mappings":";;;AAIA;;;;;;;;GAQG;AACU,QAAA,8BAA8B,GAAG;IAC5C,GAAG;IACH,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,UAAU;IACV,OAAO;IACP,OAAO;IACP,OAAO;IACP,4BAA4B;IAC5B,0BAA0B;IAC1B,oBAAoB;CACrB,CAAC;AAEF;;GAEG;AACU,QAAA,6BAA6B,GAAG,iBAAiB,CAAC;AAE/D;;GAEG;AACU,QAAA,8BAA8B,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC","sourcesContent":["import { ILogger } from '../logger';\n\nexport type ActionType = 'click' | 'change';\n\n/**\n * Default CSS selectors to define which elements on the page to track.\n * Extend this list to include additional elements to track. For example:\n * ```\n * autocapturePlugin({\n * cssSelectorAllowlist: [...DEFAULT_CSS_SELECTOR_ALLOWLIST, \".my-class\"],\n * })\n * ```\n */\nexport const DEFAULT_CSS_SELECTOR_ALLOWLIST = [\n 'a',\n 'button',\n 'input',\n 'select',\n 'textarea',\n 'label',\n 'video',\n 'audio',\n '[contenteditable=\"true\" i]',\n '[data-amp-default-track]',\n '.amp-default-track',\n];\n\n/**\n * Default prefix to allow the plugin to capture data attributes as an event property.\n */\nexport const DEFAULT_DATA_ATTRIBUTE_PREFIX = 'data-amp-track-';\n\n/**\n * Default list of elements on the page should be tracked when the page changes.\n */\nexport const DEFAULT_ACTION_CLICK_ALLOWLIST = ['div', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];\n\nexport interface ElementInteractionsOptions {\n /**\n * List of CSS selectors to allow auto tracking on.\n * When provided, allow elements matching any selector to be tracked.\n * Default is ['a', 'button', 'input', 'select', 'textarea', 'label', '[data-amp-default-track]', '.amp-default-track'].\n */\n cssSelectorAllowlist?: string[];\n\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * List of page URLs to exclude from auto tracking.\n * When provided, tracking will be blocked on these URLs.\n * Both full URLs and regex are supported.\n * This takes precedence over pageUrlAllowlist.\n */\n pageUrlExcludelist?: (RegExp | string | { pattern: string })[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Options for integrating visual tagging selector.\n */\n visualTaggingOptions?: {\n enabled?: boolean;\n messenger?: Messenger;\n };\n\n /**\n * This has been deprecated in favor of rage clicks tracking\n * via frustrationInteractions.\n *\n * Setting this will have no effect.\n *\n * @deprecated\n */\n debounceTime?: number;\n\n /**\n * CSS selector allowlist for tracking clicks that result in a DOM change/navigation on elements not already allowed by the cssSelectorAllowlist\n */\n actionClickAllowlist?: string[];\n\n /**\n * Remote config for page actions\n */\n pageActions?: {\n triggers: Trigger[];\n labeledEvents: Record<string, LabeledEvent>;\n };\n\n /**\n * RegExp pattern list to allow custom patterns for text masking\n */\n maskTextRegex?: (RegExp | { pattern: string; description: string })[];\n}\n\ntype MatchingCondition = {\n type: 'LABELED_EVENT';\n match: {\n eventId: string;\n };\n};\n\nexport type Trigger = {\n id: string;\n name: string; // Human friendly name for the trigger\n conditions: MatchingCondition[]; // Configures when the actions should be executed; AND\n actions: Array<PageAction | string>; // Actions to execute if conditions are met\n};\n\nexport type PageAction = {\n id: string;\n actionType: 'ATTACH_EVENT_PROPERTY';\n dataSource: DataSource; // Defines where and how to get the data\n destinationKey: string; // Property key name for the data (e.g. event property name, data layer key, user property name)\n};\n\nexport type DataSource = {\n sourceType: 'DOM_ELEMENT' | 'PAGE_CONTEXT'; // | 'URL' ;\n} & (\n | {\n sourceType: 'DOM_ELEMENT';\n selector?: string; // For DOM_ELEMENT: CSS selector for the target element\n elementExtractType: 'TEXT' | 'ATTRIBUTE';\n attribute?: string; // For DOM_ELEMENT: Attribute name to extract (null/empty for text content)\n scope?: string; // CSS selector for the scope of the element, document by default\n }\n | {\n sourceType: 'PAGE_CONTEXT';\n propertyPath: string; // For PAGE_CONTEXT: e.g., 'document.title'\n }\n);\n\nexport type EventSubpropKey = '[Amplitude] Element Text' | '[Amplitude] Element Hierarchy';\n\nexport type Filter = {\n subprop_key: EventSubpropKey;\n subprop_op: string; // exact, autotrack css match\n subprop_value: string[];\n};\n\nexport type LabeledEvent = {\n id: string;\n definition: {\n event_type: '[Amplitude] Element Clicked' | '[Amplitude] Element Changed';\n filters: Filter[];\n }[];\n};\n\nexport interface Messenger {\n logger?: ILogger;\n setup: () => void;\n}\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
1
+ {"version":3,"file":"element-interactions.js","sourceRoot":"","sources":["../../../src/types/element-interactions.ts"],"names":[],"mappings":";;;AAIA;;;;;;;;GAQG;AACU,QAAA,8BAA8B,GAAG;IAC5C,GAAG;IACH,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,UAAU;IACV,OAAO;IACP,OAAO;IACP,OAAO;IACP,4BAA4B;IAC5B,0BAA0B;IAC1B,oBAAoB;CACrB,CAAC;AAEF;;GAEG;AACU,QAAA,6BAA6B,GAAG,iBAAiB,CAAC;AAE/D;;GAEG;AACU,QAAA,8BAA8B,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC","sourcesContent":["import { ILogger } from '../logger';\n\nexport type ActionType = 'click' | 'change';\n\n/**\n * Default CSS selectors to define which elements on the page to track.\n * Extend this list to include additional elements to track. For example:\n * ```\n * autocapturePlugin({\n * cssSelectorAllowlist: [...DEFAULT_CSS_SELECTOR_ALLOWLIST, \".my-class\"],\n * })\n * ```\n */\nexport const DEFAULT_CSS_SELECTOR_ALLOWLIST = [\n 'a',\n 'button',\n 'input',\n 'select',\n 'textarea',\n 'label',\n 'video',\n 'audio',\n '[contenteditable=\"true\" i]',\n '[data-amp-default-track]',\n '.amp-default-track',\n];\n\n/**\n * Default prefix to allow the plugin to capture data attributes as an event property.\n */\nexport const DEFAULT_DATA_ATTRIBUTE_PREFIX = 'data-amp-track-';\n\n/**\n * Default list of elements on the page should be tracked when the page changes.\n */\nexport const DEFAULT_ACTION_CLICK_ALLOWLIST = ['div', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];\n\nexport interface ElementInteractionsOptions {\n /**\n * List of CSS selectors to allow auto tracking on.\n * When provided, allow elements matching any selector to be tracked.\n * Default is ['a', 'button', 'input', 'select', 'textarea', 'label', '[data-amp-default-track]', '.amp-default-track'].\n */\n cssSelectorAllowlist?: string[];\n\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * List of page URLs to exclude from auto tracking.\n * When provided, tracking will be blocked on these URLs.\n * Both full URLs and regex are supported.\n * This takes precedence over pageUrlAllowlist.\n */\n pageUrlExcludelist?: (RegExp | string | { pattern: string })[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Options for integrating visual tagging selector.\n */\n visualTaggingOptions?: {\n enabled?: boolean;\n };\n\n /**\n * This has been deprecated in favor of rage clicks tracking\n * via frustrationInteractions.\n *\n * Setting this will have no effect.\n *\n * @deprecated\n */\n debounceTime?: number;\n\n /**\n * CSS selector allowlist for tracking clicks that result in a DOM change/navigation on elements not already allowed by the cssSelectorAllowlist\n */\n actionClickAllowlist?: string[];\n\n /**\n * Remote config for page actions\n */\n pageActions?: {\n triggers: Trigger[];\n labeledEvents: Record<string, LabeledEvent>;\n };\n\n /**\n * RegExp pattern list to allow custom patterns for text masking\n */\n maskTextRegex?: (RegExp | { pattern: string; description: string })[];\n}\n\ntype MatchingCondition = {\n type: 'LABELED_EVENT';\n match: {\n eventId: string;\n };\n};\n\nexport type Trigger = {\n id: string;\n name: string; // Human friendly name for the trigger\n conditions: MatchingCondition[]; // Configures when the actions should be executed; AND\n actions: Array<PageAction | string>; // Actions to execute if conditions are met\n};\n\nexport type PageAction = {\n id: string;\n actionType: 'ATTACH_EVENT_PROPERTY';\n dataSource: DataSource; // Defines where and how to get the data\n destinationKey: string; // Property key name for the data (e.g. event property name, data layer key, user property name)\n};\n\nexport type DataSource = {\n sourceType: 'DOM_ELEMENT' | 'PAGE_CONTEXT'; // | 'URL' ;\n} & (\n | {\n sourceType: 'DOM_ELEMENT';\n selector?: string; // For DOM_ELEMENT: CSS selector for the target element\n elementExtractType: 'TEXT' | 'ATTRIBUTE';\n attribute?: string; // For DOM_ELEMENT: Attribute name to extract (null/empty for text content)\n scope?: string; // CSS selector for the scope of the element, document by default\n }\n | {\n sourceType: 'PAGE_CONTEXT';\n propertyPath: string; // For PAGE_CONTEXT: e.g., 'document.title'\n }\n);\n\nexport type EventSubpropKey = '[Amplitude] Element Text' | '[Amplitude] Element Hierarchy';\n\nexport type Filter = {\n subprop_key: EventSubpropKey;\n subprop_op: string; // exact, autotrack css match\n subprop_value: string[];\n};\n\nexport type LabeledEvent = {\n id: string;\n definition: {\n event_type: '[Amplitude] Element Clicked' | '[Amplitude] Element Changed';\n filters: Filter[];\n }[];\n};\n\nexport interface Messenger {\n logger?: ILogger;\n setup: () => void;\n}\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
@@ -0,0 +1,4 @@
1
+ type SafeJsonStringifyFn = (data: object, replacer?: any, space?: string | number) => string;
2
+ declare const safeJsonStringify: SafeJsonStringifyFn;
3
+ export { safeJsonStringify };
4
+ //# sourceMappingURL=safe-stringify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"safe-stringify.d.ts","sourceRoot":"","sources":["../../../src/utils/safe-stringify.ts"],"names":[],"mappings":"AAKA,KAAK,mBAAmB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,KAAK,MAAM,CAAC;AAC7F,QAAA,MAAM,iBAAiB,EAAE,mBACqD,CAAC;AAE/E,OAAO,EAAE,iBAAiB,EAAE,CAAC"}
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.safeJsonStringify = void 0;
4
+ /* eslint-disable @typescript-eslint/no-unsafe-assignment */
5
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
6
+ var safeJsonStringifyModule = require("safe-json-stringify");
7
+ var safeJsonStringify = safeJsonStringifyModule.default || safeJsonStringifyModule;
8
+ exports.safeJsonStringify = safeJsonStringify;
9
+ //# sourceMappingURL=safe-stringify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"safe-stringify.js","sourceRoot":"","sources":["../../../src/utils/safe-stringify.ts"],"names":[],"mappings":";;;AAAA,4DAA4D;AAC5D,+DAA+D;AAC/D,6DAA+D;AAI/D,IAAM,iBAAiB,GACpB,uBAA+B,CAAC,OAAO,IAAK,uBAA+B,CAAC;AAEtE,8CAAiB","sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport * as safeJsonStringifyModule from 'safe-json-stringify';\n\n// do a simple, typed re-export of \"safe-json-stringify\"\ntype SafeJsonStringifyFn = (data: object, replacer?: any, space?: string | number) => string;\nconst safeJsonStringify: SafeJsonStringifyFn =\n (safeJsonStringifyModule as any).default || (safeJsonStringifyModule as any);\n\nexport { safeJsonStringify };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"uncaught-sdk-errors.d.ts","sourceRoot":"","sources":["../../../src/diagnostics/uncaught-sdk-errors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAa1D,eAAO,MAAM,UAAU,6BAA6B,CAAC;AACrD,eAAO,MAAM,yBAAyB,uBAAuB,CAAC;AAe9D,eAAO,MAAM,yBAAyB,aAAc;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,SAOzE,CAAC;AAEF,eAAO,MAAM,uBAAuB,WAAY,kBAAkB,SAmEjE,CAAC"}
1
+ {"version":3,"file":"uncaught-sdk-errors.d.ts","sourceRoot":"","sources":["../../../src/diagnostics/uncaught-sdk-errors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAa1D,eAAO,MAAM,UAAU,6BAA6B,CAAC;AACrD,eAAO,MAAM,yBAAyB,uBAAuB,CAAC;AAgC9D,eAAO,MAAM,yBAAyB,aAAc;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,SAOzE,CAAC;AAEF,eAAO,MAAM,uBAAuB,WAAY,kBAAkB,SAmEjE,CAAC"}
@@ -1,23 +1,40 @@
1
- import { __assign } from "tslib";
1
+ import { __assign, __values } from "tslib";
2
2
  import { getGlobalScope } from '../global-scope';
3
3
  export var GLOBAL_KEY = '__AMPLITUDE_SCRIPT_URL__';
4
4
  export var EVENT_NAME_ERROR_UNCAUGHT = 'sdk.error.uncaught';
5
- var getNormalizedScriptUrl = function () {
5
+ var getNormalizedScriptUrls = function () {
6
6
  var scope = getGlobalScope();
7
7
  /* istanbul ignore next */
8
- return scope === null || scope === void 0 ? void 0 : scope[GLOBAL_KEY];
8
+ if (!scope) {
9
+ return [];
10
+ }
11
+ var value = scope[GLOBAL_KEY];
12
+ if (Array.isArray(value)) {
13
+ return value;
14
+ }
15
+ /* istanbul ignore next - legacy single URL stored as string */
16
+ if (typeof value === 'string') {
17
+ return [value];
18
+ }
19
+ return [];
9
20
  };
10
- var setNormalizedScriptUrl = function (url) {
21
+ var addNormalizedScriptUrl = function (url) {
11
22
  var scope = getGlobalScope();
12
- if (scope) {
13
- scope[GLOBAL_KEY] = url;
23
+ /* istanbul ignore next */
24
+ if (!scope) {
25
+ return;
26
+ }
27
+ var urls = getNormalizedScriptUrls();
28
+ if (!urls.includes(url)) {
29
+ urls.push(url);
30
+ scope[GLOBAL_KEY] = urls;
14
31
  }
15
32
  };
16
33
  export var registerSdkLoaderMetadata = function (metadata) {
17
34
  if (metadata.scriptUrl) {
18
35
  var normalized = normalizeUrl(metadata.scriptUrl);
19
36
  if (normalized) {
20
- setNormalizedScriptUrl(normalized);
37
+ addNormalizedScriptUrl(normalized);
21
38
  }
22
39
  }
23
40
  };
@@ -76,15 +93,28 @@ export var enableSdkErrorListeners = function (client) {
76
93
  scope.addEventListener('unhandledrejection', handleRejection, true);
77
94
  };
78
95
  var detectSdkOrigin = function (payload) {
79
- var normalizedScriptUrl = getNormalizedScriptUrl();
80
- if (!normalizedScriptUrl) {
96
+ var e_1, _a;
97
+ var normalizedScriptUrls = getNormalizedScriptUrls();
98
+ if (normalizedScriptUrls.length === 0) {
81
99
  return undefined;
82
100
  }
83
- if (payload.filename && payload.filename.includes(normalizedScriptUrl)) {
84
- return 'filename';
101
+ try {
102
+ for (var normalizedScriptUrls_1 = __values(normalizedScriptUrls), normalizedScriptUrls_1_1 = normalizedScriptUrls_1.next(); !normalizedScriptUrls_1_1.done; normalizedScriptUrls_1_1 = normalizedScriptUrls_1.next()) {
103
+ var normalizedScriptUrl = normalizedScriptUrls_1_1.value;
104
+ if (payload.filename && payload.filename.includes(normalizedScriptUrl)) {
105
+ return 'filename';
106
+ }
107
+ if (payload.stack && payload.stack.includes(normalizedScriptUrl)) {
108
+ return 'stack';
109
+ }
110
+ }
85
111
  }
86
- if (payload.stack && payload.stack.includes(normalizedScriptUrl)) {
87
- return 'stack';
112
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
113
+ finally {
114
+ try {
115
+ if (normalizedScriptUrls_1_1 && !normalizedScriptUrls_1_1.done && (_a = normalizedScriptUrls_1.return)) _a.call(normalizedScriptUrls_1);
116
+ }
117
+ finally { if (e_1) throw e_1.error; }
88
118
  }
89
119
  return undefined;
90
120
  };
@@ -1 +1 @@
1
- {"version":3,"file":"uncaught-sdk-errors.js","sourceRoot":"","sources":["../../../src/diagnostics/uncaught-sdk-errors.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAcjD,MAAM,CAAC,IAAM,UAAU,GAAG,0BAA0B,CAAC;AACrD,MAAM,CAAC,IAAM,yBAAyB,GAAG,oBAAoB,CAAC;AAE9D,IAAM,sBAAsB,GAAG;IAC7B,IAAM,KAAK,GAAG,cAAc,EAAoC,CAAC;IACjE,0BAA0B;IAC1B,OAAO,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAG,UAAU,CAAuB,CAAC;AACnD,CAAC,CAAC;AAEF,IAAM,sBAAsB,GAAG,UAAC,GAAW;IACzC,IAAM,KAAK,GAAG,cAAc,EAAoC,CAAC;IACjE,IAAI,KAAK,EAAE;QACT,KAAK,CAAC,UAAU,CAAC,GAAG,GAAG,CAAC;KACzB;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,IAAM,yBAAyB,GAAG,UAAC,QAAgC;IACxE,IAAI,QAAQ,CAAC,SAAS,EAAE;QACtB,IAAM,UAAU,GAAG,YAAY,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;QACpD,IAAI,UAAU,EAAE;YACd,sBAAsB,CAAC,UAAU,CAAC,CAAC;SACpC;KACF;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,IAAM,uBAAuB,GAAG,UAAC,MAA0B;IAChE,IAAM,KAA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;KACnB;IAED,IAAI,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,mBAAmB,CAAC,EAAE;QAChE,OAAO,OAAO,CAAC;KAChB;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAEF,IAAM,YAAY,GAAG,UAAC,KAAa;;IACjC,IAAI;QACF,0BAA0B;QAC1B,IAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,EAAE,MAAA,MAAA,cAAc,EAAE,0CAAE,QAAQ,0CAAE,MAAM,CAAC,CAAC;QAC/D,OAAO,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,QAAQ,CAAC;KAClC;IAAC,WAAM;QACN,OAAO,SAAS,CAAC;KAClB;AACH,CAAC,CAAC;AAEF,IAAM,wBAAwB,GAAG,UAAC,KAAc;IAC9C,IAAI,CAAC,KAAK,EAAE;QACV,OAAO,SAAS,CAAC;KAClB;IAED,IAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAC1D,0BAA0B;IAC1B,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACtC,CAAC,CAAC;AAEF,0BAA0B;AAC1B,IAAM,eAAe,GAAG,UAAC,MAAe;IACtC,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QAC9B,OAAO,MAAM,CAAC;KACf;IAED,IAAI;QACF,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;KAC/B;IAAC,WAAM;QACN,OAAO,iBAAiB,CAAC;KAC1B;AACH,CAAC,CAAC","sourcesContent":["import { getGlobalScope } from '../global-scope';\nimport { IDiagnosticsClient } from './diagnostics-client';\n\ntype ErrorEventType = 'error' | 'unhandledrejection';\n\ninterface CapturedErrorContext {\n readonly type: ErrorEventType;\n readonly message: string;\n readonly stack?: string;\n readonly filename?: string;\n readonly errorName?: string;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport const GLOBAL_KEY = '__AMPLITUDE_SCRIPT_URL__';\nexport const EVENT_NAME_ERROR_UNCAUGHT = 'sdk.error.uncaught';\n\nconst getNormalizedScriptUrl = (): string | undefined => {\n const scope = getGlobalScope() as Record<string, unknown> | null;\n /* istanbul ignore next */\n return scope?.[GLOBAL_KEY] as string | undefined;\n};\n\nconst setNormalizedScriptUrl = (url: string) => {\n const scope = getGlobalScope() as Record<string, unknown> | null;\n if (scope) {\n scope[GLOBAL_KEY] = url;\n }\n};\n\nexport const registerSdkLoaderMetadata = (metadata: { scriptUrl?: string }) => {\n if (metadata.scriptUrl) {\n const normalized = normalizeUrl(metadata.scriptUrl);\n if (normalized) {\n setNormalizedScriptUrl(normalized);\n }\n }\n};\n\nexport const enableSdkErrorListeners = (client: IDiagnosticsClient) => {\n const scope = getGlobalScope();\n\n if (!scope || typeof scope.addEventListener !== 'function') {\n return;\n }\n\n const handleError = (event: ErrorEvent) => {\n const error = event.error instanceof Error ? event.error : undefined;\n const stack = error?.stack;\n const match = detectSdkOrigin({ filename: event.filename, stack });\n if (!match) {\n return;\n }\n\n capture({\n type: 'error',\n message: event.message,\n stack,\n filename: event.filename,\n errorName: error?.name,\n metadata: {\n colno: event.colno,\n lineno: event.lineno,\n isTrusted: event.isTrusted,\n matchReason: match,\n },\n });\n };\n\n const handleRejection = (event: PromiseRejectionEvent) => {\n const error = event.reason instanceof Error ? event.reason : undefined;\n const stack = error?.stack;\n const filename = extractFilenameFromStack(stack);\n const match = detectSdkOrigin({ filename, stack });\n\n if (!match) {\n return;\n }\n\n /* istanbul ignore next */\n capture({\n type: 'unhandledrejection',\n message: error?.message ?? stringifyReason(event.reason),\n stack,\n filename,\n errorName: error?.name,\n metadata: {\n isTrusted: event.isTrusted,\n matchReason: match,\n },\n });\n };\n\n const capture = (context: CapturedErrorContext) => {\n client.recordEvent(EVENT_NAME_ERROR_UNCAUGHT, {\n type: context.type,\n message: context.message,\n filename: context.filename,\n error_name: context.errorName,\n stack: context.stack,\n ...context.metadata,\n });\n };\n\n scope.addEventListener('error', handleError, true);\n scope.addEventListener('unhandledrejection', handleRejection, true);\n};\n\nconst detectSdkOrigin = (payload: { filename?: string; stack?: string }): 'filename' | 'stack' | undefined => {\n const normalizedScriptUrl = getNormalizedScriptUrl();\n if (!normalizedScriptUrl) {\n return undefined;\n }\n\n if (payload.filename && payload.filename.includes(normalizedScriptUrl)) {\n return 'filename';\n }\n\n if (payload.stack && payload.stack.includes(normalizedScriptUrl)) {\n return 'stack';\n }\n\n return undefined;\n};\n\nconst normalizeUrl = (value: string) => {\n try {\n /* istanbul ignore next */\n const url = new URL(value, getGlobalScope()?.location?.origin);\n return url.origin + url.pathname;\n } catch {\n return undefined;\n }\n};\n\nconst extractFilenameFromStack = (stack?: string) => {\n if (!stack) {\n return undefined;\n }\n\n const match = stack.match(/(https?:\\/\\/\\S+?)(?=[)\\s]|$)/);\n /* istanbul ignore next */\n return match ? match[1] : undefined;\n};\n\n/* istanbul ignore next */\nconst stringifyReason = (reason: unknown) => {\n if (typeof reason === 'string') {\n return reason;\n }\n\n try {\n return JSON.stringify(reason);\n } catch {\n return '[object Object]';\n }\n};\n"]}
1
+ {"version":3,"file":"uncaught-sdk-errors.js","sourceRoot":"","sources":["../../../src/diagnostics/uncaught-sdk-errors.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAcjD,MAAM,CAAC,IAAM,UAAU,GAAG,0BAA0B,CAAC;AACrD,MAAM,CAAC,IAAM,yBAAyB,GAAG,oBAAoB,CAAC;AAE9D,IAAM,uBAAuB,GAAG;IAC9B,IAAM,KAAK,GAAG,cAAc,EAAoC,CAAC;IACjE,0BAA0B;IAC1B,IAAI,CAAC,KAAK,EAAE;QACV,OAAO,EAAE,CAAC;KACX;IACD,IAAM,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC;IAChC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC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AAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,EAAE,MAAA,MAAA,cAAc,EAAE,0CAAE,QAAQ,0CAAE,MAAM,CAAC,CAAC;QAC/D,OAAO,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,QAAQ,CAAC;KAClC;IAAC,WAAM;QACN,OAAO,SAAS,CAAC;KAClB;AACH,CAAC,CAAC;AAEF,IAAM,wBAAwB,GAAG,UAAC,KAAc;IAC9C,IAAI,CAAC,KAAK,EAAE;QACV,OAAO,SAAS,CAAC;KAClB;IAED,IAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAC1D,0BAA0B;IAC1B,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACtC,CAAC,CAAC;AAEF,0BAA0B;AAC1B,IAAM,eAAe,GAAG,UAAC,MAAe;IACtC,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QAC9B,OAAO,MAAM,CAAC;KACf;IAED,IAAI;QACF,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;KAC/B;IAAC,WAAM;QACN,OAAO,iBAAiB,CAAC;KAC1B;AACH,CAAC,CAAC","sourcesContent":["import { getGlobalScope } from '../global-scope';\nimport { IDiagnosticsClient } from './diagnostics-client';\n\ntype ErrorEventType = 'error' | 'unhandledrejection';\n\ninterface CapturedErrorContext {\n readonly type: ErrorEventType;\n readonly message: string;\n readonly stack?: string;\n readonly filename?: string;\n readonly errorName?: string;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport const GLOBAL_KEY = '__AMPLITUDE_SCRIPT_URL__';\nexport const EVENT_NAME_ERROR_UNCAUGHT = 'sdk.error.uncaught';\n\nconst getNormalizedScriptUrls = (): string[] => {\n const scope = getGlobalScope() as Record<string, unknown> | null;\n /* istanbul ignore next */\n if (!scope) {\n return [];\n }\n const value = scope[GLOBAL_KEY];\n if (Array.isArray(value)) {\n return value as string[];\n }\n /* istanbul ignore next - legacy single URL stored as string */\n if (typeof value === 'string') {\n return [value];\n }\n return [];\n};\n\nconst addNormalizedScriptUrl = (url: string) => {\n const scope = getGlobalScope() as Record<string, unknown> | null;\n /* istanbul ignore next */\n if (!scope) {\n return;\n }\n const urls = getNormalizedScriptUrls();\n if (!urls.includes(url)) {\n urls.push(url);\n scope[GLOBAL_KEY] = urls;\n }\n};\n\nexport const registerSdkLoaderMetadata = (metadata: { scriptUrl?: string }) => {\n if (metadata.scriptUrl) {\n const normalized = normalizeUrl(metadata.scriptUrl);\n if (normalized) {\n addNormalizedScriptUrl(normalized);\n }\n }\n};\n\nexport const enableSdkErrorListeners = (client: IDiagnosticsClient) => {\n const scope = getGlobalScope();\n\n if (!scope || typeof scope.addEventListener !== 'function') {\n return;\n }\n\n const handleError = (event: ErrorEvent) => {\n const error = event.error instanceof Error ? event.error : undefined;\n const stack = error?.stack;\n const match = detectSdkOrigin({ filename: event.filename, stack });\n if (!match) {\n return;\n }\n\n capture({\n type: 'error',\n message: event.message,\n stack,\n filename: event.filename,\n errorName: error?.name,\n metadata: {\n colno: event.colno,\n lineno: event.lineno,\n isTrusted: event.isTrusted,\n matchReason: match,\n },\n });\n };\n\n const handleRejection = (event: PromiseRejectionEvent) => {\n const error = event.reason instanceof Error ? event.reason : undefined;\n const stack = error?.stack;\n const filename = extractFilenameFromStack(stack);\n const match = detectSdkOrigin({ filename, stack });\n\n if (!match) {\n return;\n }\n\n /* istanbul ignore next */\n capture({\n type: 'unhandledrejection',\n message: error?.message ?? stringifyReason(event.reason),\n stack,\n filename,\n errorName: error?.name,\n metadata: {\n isTrusted: event.isTrusted,\n matchReason: match,\n },\n });\n };\n\n const capture = (context: CapturedErrorContext) => {\n client.recordEvent(EVENT_NAME_ERROR_UNCAUGHT, {\n type: context.type,\n message: context.message,\n filename: context.filename,\n error_name: context.errorName,\n stack: context.stack,\n ...context.metadata,\n });\n };\n\n scope.addEventListener('error', handleError, true);\n scope.addEventListener('unhandledrejection', handleRejection, true);\n};\n\nconst detectSdkOrigin = (payload: { filename?: string; stack?: string }): 'filename' | 'stack' | undefined => {\n const normalizedScriptUrls = getNormalizedScriptUrls();\n if (normalizedScriptUrls.length === 0) {\n return undefined;\n }\n\n for (const normalizedScriptUrl of normalizedScriptUrls) {\n if (payload.filename && payload.filename.includes(normalizedScriptUrl)) {\n return 'filename';\n }\n if (payload.stack && payload.stack.includes(normalizedScriptUrl)) {\n return 'stack';\n }\n }\n\n return undefined;\n};\n\nconst normalizeUrl = (value: string) => {\n try {\n /* istanbul ignore next */\n const url = new URL(value, getGlobalScope()?.location?.origin);\n return url.origin + url.pathname;\n } catch {\n return undefined;\n }\n};\n\nconst extractFilenameFromStack = (stack?: string) => {\n if (!stack) {\n return undefined;\n }\n\n const match = stack.match(/(https?:\\/\\/\\S+?)(?=[)\\s]|$)/);\n /* istanbul ignore next */\n return match ? match[1] : undefined;\n};\n\n/* istanbul ignore next */\nconst stringifyReason = (reason: unknown) => {\n if (typeof reason === 'string') {\n return reason;\n }\n\n try {\n return JSON.stringify(reason);\n } catch {\n return '[object Object]';\n }\n};\n"]}
@@ -68,4 +68,9 @@ export { ReactNativeConfig, ReactNativeTrackingOptions, ReactNativeOptions, Reac
68
68
  export { ReactNativeClient } from './types/client/react-native-client';
69
69
  export { Observable, asyncMap, merge, multicast, Unsubscribable } from './utils/observable';
70
70
  export { InstanceProxy } from './types/proxy';
71
+ export { safeJsonStringify } from './utils/safe-stringify';
72
+ export type { BaseWindowMessenger, ActionHandler } from './messenger/base-window-messenger';
73
+ export { getOrCreateWindowMessenger } from './messenger/base-window-messenger';
74
+ export { enableBackgroundCapture } from './messenger/background-capture';
75
+ export { AMPLITUDE_ORIGIN, AMPLITUDE_ORIGIN_EU, AMPLITUDE_ORIGIN_STAGING, AMPLITUDE_ORIGINS_MAP, AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL, } from './messenger/constants';
71
76
  //# sourceMappingURL=index.d.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M,mCAAmC,CAAC;AAC5F,OAAO,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;AAC/E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,wBAAwB,EACxB,qBAAqB,EACrB,uCAAuC,GACxC,MAAM,uBAAuB,CAAC"}
package/lib/esm/index.js CHANGED
@@ -42,4 +42,8 @@ export { EMPTY_VALUE, BASE_CAMPAIGN, MKTG } from './types/constants';
42
42
  export { CampaignParser } from './campaign/campaign-parser';
43
43
  export { getPageTitle, TEXT_MASK_ATTRIBUTE, MASKED_TEXT_VALUE, replaceSensitiveString, CC_REGEX, SSN_REGEX, EMAIL_REGEX, } from './plugins/helpers';
44
44
  export { Observable, asyncMap, merge, multicast } from './utils/observable';
45
+ export { safeJsonStringify } from './utils/safe-stringify';
46
+ export { getOrCreateWindowMessenger } from './messenger/base-window-messenger';
47
+ export { enableBackgroundCapture } from './messenger/background-capture';
48
+ export { AMPLITUDE_ORIGIN, AMPLITUDE_ORIGIN_EU, AMPLITUDE_ORIGIN_STAGING, AMPLITUDE_ORIGINS_MAP, AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL, } from './messenger/constants';
45
49
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAI9C,OAAO,EAAE,QAAQ,EAAgC,MAAM,YAAY,CAAC;AACpE,OAAO,EAAE,OAAO,EAAY,eAAe,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAEnD,OAAO,EAAE,MAAM,E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AAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAErE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAEL,iBAAiB,EACjB,gBAAgB,GAIjB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EAAkB,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAelD,OAAO,EAIL,8BAA8B,EAC9B,6BAA6B,EAC7B,8BAA8B,GAI/B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAEL,4BAA4B,EAC5B,4BAA4B,EAC5B,6BAA6B,EAC7B,4BAA4B,EAC5B,4BAA4B,EAC5B,0CAA0C,EAC1C,4BAA4B,GAC7B,MAAM,kCAAkC,CAAC;AAG1C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,mBAAmB,EAAqD,MAAM,yBAAyB,CAAC;AAEjH,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAMpE,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EACL,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,sBAAsB,EACtB,QAAQ,EACR,SAAS,EACT,WAAW,GACZ,MAAM,mBAAmB,CAAC;AA4B3B,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,SAAS,EAAkB,MAAM,oBAAoB,CAAC","sourcesContent":["export { AmplitudeCore } from './core-client';\nexport { CoreClient, PluginHost } from './types/client/core-client';\nexport { AnalyticsClient } from './types/client/analytics-client';\nexport { AmplitudeContext } from './types/amplitude-context';\nexport { Identify, IIdentify, ValidPropertyType } from './identify';\nexport { Revenue, IRevenue, RevenueProperty } from './revenue';\nexport { Destination } from './plugins/destination';\nexport { IdentityEventSender } from './plugins/identity';\nexport { Config, RequestMetadata } from './config';\nexport { IConfig } from './types/config/core-config';\nexport { Logger, ILogger, LogConfig } from './logger';\nexport { getGlobalScope } from './global-scope';\nexport { getAnalyticsConnector, setConnectorDeviceId, setConnectorUserId } from './analytics-connector';\nexport { isNewSession } from './session';\nexport { getCookieName, getOldCookieName } from './cookie-name';\nexport { getLanguage } from './language';\nexport { getQueryParams } from './query-params';\n\nexport { returnWrapper, AmplitudeReturn } from './utils/return-wrapper';\nexport { debugWrapper, getClientLogConfig, getClientStates } from './utils/debug';\nexport { UUID } from './utils/uuid';\nexport { createIdentifyEvent } from './utils/event-builder';\nexport { isUrlMatchAllowlist, getDecodeURI } from './utils/url-utils';\nexport { generateHashCode, isTimestampInSample } from './utils/sampling';\n\nexport { MemoryStorage } from './storage/memory';\nexport { CookieStorage, isDomainEqual, decodeCookieValue } from './storage/cookie';\nexport { getStorageKey } from './storage/helpers';\n\nexport { BrowserStorage } from './storage/browser-storage';\n\nexport { DiagnosticsClient, IDiagnosticsClient } from './diagnostics/diagnostics-client';\nexport { registerSdkLoaderMetadata } from './diagnostics/uncaught-sdk-errors';\n\nexport { BaseTransport } from './transports/base';\nexport { FetchTransport } from './transports/fetch';\n\nexport { RemoteConfigClient, IRemoteConfigClient, RemoteConfig, Source } from './remote-config/remote-config';\n\nexport { LogLevel } from './types/loglevel';\nexport { AMPLITUDE_PREFIX, STORAGE_PREFIX } from './types/constants';\nexport { Storage, IdentityStorageType, CookieStorageConfig } from './types/storage';\nexport { consoleObserver } from './observers/console';\nexport {\n Event,\n IdentifyOperation,\n SpecialEventType,\n IdentifyEvent,\n GroupIdentifyEvent,\n IdentifyUserProperties,\n} from './types/event/event';\nexport { EventOptions, BaseEvent } from './types/event/base-event';\nexport { IngestionMetadata } from './types/event/ingestion-metadata';\nexport { ServerZoneType, ServerZone } from './types/server-zone';\nexport { OfflineDisabled } from './types/offline';\nexport { Plan } from './types/event/plan';\nexport { TransportType, Transport, TransportOptions, TransportTypeOrOptions } from './types/transport';\nexport { Payload } from './types/payload';\nexport { Response } from './types/response';\nexport { UserSession } from './types/user-session';\nexport {\n Plugin,\n BeforePlugin,\n DestinationPlugin,\n EnrichmentPlugin,\n PluginType,\n AnalyticsIdentity,\n} from './types/plugin';\nexport { Result } from './types/result';\nexport {\n ElementInteractionsOptions,\n Messenger,\n ActionType,\n DEFAULT_CSS_SELECTOR_ALLOWLIST,\n DEFAULT_DATA_ATTRIBUTE_PREFIX,\n DEFAULT_ACTION_CLICK_ALLOWLIST,\n LabeledEvent,\n Trigger,\n DataSource,\n} from './types/element-interactions';\n\nexport {\n FrustrationInteractionsOptions,\n DEFAULT_DEAD_CLICK_ALLOWLIST,\n DEFAULT_RAGE_CLICK_ALLOWLIST,\n DEFAULT_ERROR_CLICK_ALLOWLIST,\n DEFAULT_RAGE_CLICK_THRESHOLD,\n DEFAULT_RAGE_CLICK_WINDOW_MS,\n DEFAULT_RAGE_CLICK_OUT_OF_BOUNDS_THRESHOLD,\n DEFAULT_DEAD_CLICK_WINDOW_MS,\n} from './types/frustration-interactions';\nexport { PageTrackingOptions, PageTrackingTrackOn, PageTrackingHistoryChanges } from './types/page-view-tracking';\nexport { FormInteractionsOptions } from './types/form-interactions';\nexport { Status } from './types/status';\n\nexport { NetworkEventCallback, networkObserver } from './observers/network';\nexport { NetworkRequestEvent, IRequestWrapper, JsonObject, JsonValue, JsonArray } from './network-request-event';\nexport { NetworkTrackingOptions, NetworkCaptureRule } from './types/network-tracking';\nexport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './types/constants';\n\nexport { PageUrlEnrichmentOptions } from './types/page-url-enrichment';\n\n// Campaign\nexport { Campaign, UTMParameters, ReferrerParameters, ClickIdParameters, ICampaignParser } from './types/campaign';\nexport { EMPTY_VALUE, BASE_CAMPAIGN, MKTG } from './types/constants';\nexport { CampaignParser } from './campaign/campaign-parser';\nexport {\n getPageTitle,\n TEXT_MASK_ATTRIBUTE,\n MASKED_TEXT_VALUE,\n replaceSensitiveString,\n CC_REGEX,\n SSN_REGEX,\n EMAIL_REGEX,\n} from './plugins/helpers';\n\n// Browser\nexport {\n BrowserConfig,\n BrowserOptions,\n DefaultTrackingOptions,\n TrackingOptions,\n AutocaptureOptions,\n CookieOptions,\n AttributionOptions,\n RemoteConfigOptions,\n} from './types/config/browser-config';\nexport { BrowserClient } from './types/client/browser-client';\n\n// Node\nexport { NodeClient } from './types/client/node-client';\nexport { NodeConfig, NodeOptions } from './types/config/node-config';\n\n// React Native\nexport {\n ReactNativeConfig,\n ReactNativeTrackingOptions,\n ReactNativeOptions,\n ReactNativeAttributionOptions,\n} from './types/config/react-native-config';\nexport { ReactNativeClient } from './types/client/react-native-client';\n\nexport { Observable, asyncMap, merge, multicast, Unsubscribable } from './utils/observable';\n\nexport { InstanceProxy } from './types/proxy';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAI9C,OAAO,EAAE,QAAQ,EAAgC,MAAM,YAAY,CAAC;AACpE,OAAO,EAAE,OAAO,EAAY,eAAe,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAEnD,OAAO,EAAE,MAAM,EAAsB,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,C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EACrB,uCAAuC,GACxC,MAAM,uBAAuB,CAAC","sourcesContent":["export { AmplitudeCore } from './core-client';\nexport { CoreClient, PluginHost } from './types/client/core-client';\nexport { AnalyticsClient } from './types/client/analytics-client';\nexport { AmplitudeContext } from './types/amplitude-context';\nexport { Identify, IIdentify, ValidPropertyType } from './identify';\nexport { Revenue, IRevenue, RevenueProperty } from './revenue';\nexport { Destination } from './plugins/destination';\nexport { IdentityEventSender } from './plugins/identity';\nexport { Config, RequestMetadata } from './config';\nexport { IConfig } from './types/config/core-config';\nexport { Logger, ILogger, LogConfig } from './logger';\nexport { getGlobalScope } from './global-scope';\nexport { getAnalyticsConnector, setConnectorDeviceId, setConnectorUserId } from './analytics-connector';\nexport { isNewSession } from './session';\nexport { getCookieName, getOldCookieName } from './cookie-name';\nexport { getLanguage } from './language';\nexport { getQueryParams } from './query-params';\n\nexport { returnWrapper, AmplitudeReturn } from './utils/return-wrapper';\nexport { debugWrapper, getClientLogConfig, getClientStates } from './utils/debug';\nexport { UUID } from './utils/uuid';\nexport { createIdentifyEvent } from './utils/event-builder';\nexport { isUrlMatchAllowlist, getDecodeURI } from './utils/url-utils';\nexport { generateHashCode, isTimestampInSample } from './utils/sampling';\n\nexport { MemoryStorage } from './storage/memory';\nexport { CookieStorage, isDomainEqual, decodeCookieValue } from './storage/cookie';\nexport { getStorageKey } from './storage/helpers';\n\nexport { BrowserStorage } from './storage/browser-storage';\n\nexport { DiagnosticsClient, IDiagnosticsClient } from './diagnostics/diagnostics-client';\nexport { registerSdkLoaderMetadata } from './diagnostics/uncaught-sdk-errors';\n\nexport { BaseTransport } from './transports/base';\nexport { FetchTransport } from './transports/fetch';\n\nexport { RemoteConfigClient, IRemoteConfigClient, RemoteConfig, Source } from './remote-config/remote-config';\n\nexport { LogLevel } from './types/loglevel';\nexport { AMPLITUDE_PREFIX, STORAGE_PREFIX } from './types/constants';\nexport { Storage, IdentityStorageType, CookieStorageConfig } from './types/storage';\nexport { consoleObserver } from './observers/console';\nexport {\n Event,\n IdentifyOperation,\n SpecialEventType,\n IdentifyEvent,\n GroupIdentifyEvent,\n IdentifyUserProperties,\n} from './types/event/event';\nexport { EventOptions, BaseEvent } from './types/event/base-event';\nexport { IngestionMetadata } from './types/event/ingestion-metadata';\nexport { ServerZoneType, ServerZone } from './types/server-zone';\nexport { OfflineDisabled } from './types/offline';\nexport { Plan } from './types/event/plan';\nexport { TransportType, Transport, TransportOptions, TransportTypeOrOptions } from './types/transport';\nexport { Payload } from './types/payload';\nexport { Response } from './types/response';\nexport { UserSession } from './types/user-session';\nexport {\n Plugin,\n BeforePlugin,\n DestinationPlugin,\n EnrichmentPlugin,\n PluginType,\n AnalyticsIdentity,\n} from './types/plugin';\nexport { Result } from './types/result';\nexport {\n ElementInteractionsOptions,\n Messenger,\n ActionType,\n DEFAULT_CSS_SELECTOR_ALLOWLIST,\n DEFAULT_DATA_ATTRIBUTE_PREFIX,\n DEFAULT_ACTION_CLICK_ALLOWLIST,\n LabeledEvent,\n Trigger,\n DataSource,\n} from './types/element-interactions';\n\nexport {\n FrustrationInteractionsOptions,\n DEFAULT_DEAD_CLICK_ALLOWLIST,\n DEFAULT_RAGE_CLICK_ALLOWLIST,\n DEFAULT_ERROR_CLICK_ALLOWLIST,\n DEFAULT_RAGE_CLICK_THRESHOLD,\n DEFAULT_RAGE_CLICK_WINDOW_MS,\n DEFAULT_RAGE_CLICK_OUT_OF_BOUNDS_THRESHOLD,\n DEFAULT_DEAD_CLICK_WINDOW_MS,\n} from './types/frustration-interactions';\nexport { PageTrackingOptions, PageTrackingTrackOn, PageTrackingHistoryChanges } from './types/page-view-tracking';\nexport { FormInteractionsOptions } from './types/form-interactions';\nexport { Status } from './types/status';\n\nexport { NetworkEventCallback, networkObserver } from './observers/network';\nexport { NetworkRequestEvent, IRequestWrapper, JsonObject, JsonValue, JsonArray } from './network-request-event';\nexport { NetworkTrackingOptions, NetworkCaptureRule } from './types/network-tracking';\nexport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './types/constants';\n\nexport { PageUrlEnrichmentOptions } from './types/page-url-enrichment';\n\n// Campaign\nexport { Campaign, UTMParameters, ReferrerParameters, ClickIdParameters, ICampaignParser } from './types/campaign';\nexport { EMPTY_VALUE, BASE_CAMPAIGN, MKTG } from './types/constants';\nexport { CampaignParser } from './campaign/campaign-parser';\nexport {\n getPageTitle,\n TEXT_MASK_ATTRIBUTE,\n MASKED_TEXT_VALUE,\n replaceSensitiveString,\n CC_REGEX,\n SSN_REGEX,\n EMAIL_REGEX,\n} from './plugins/helpers';\n\n// Browser\nexport {\n BrowserConfig,\n BrowserOptions,\n DefaultTrackingOptions,\n TrackingOptions,\n AutocaptureOptions,\n CookieOptions,\n AttributionOptions,\n RemoteConfigOptions,\n} from './types/config/browser-config';\nexport { BrowserClient } from './types/client/browser-client';\n\n// Node\nexport { NodeClient } from './types/client/node-client';\nexport { NodeConfig, NodeOptions } from './types/config/node-config';\n\n// React Native\nexport {\n ReactNativeConfig,\n ReactNativeTrackingOptions,\n ReactNativeOptions,\n ReactNativeAttributionOptions,\n} from './types/config/react-native-config';\nexport { ReactNativeClient } from './types/client/react-native-client';\n\nexport { Observable, asyncMap, merge, multicast, Unsubscribable } from './utils/observable';\n\nexport { InstanceProxy } from './types/proxy';\nexport { safeJsonStringify } from './utils/safe-stringify';\n\n// Messenger (cross-window communication)\nexport type { BaseWindowMessenger, ActionHandler } from './messenger/base-window-messenger';\nexport { getOrCreateWindowMessenger } from './messenger/base-window-messenger';\nexport { enableBackgroundCapture } from './messenger/background-capture';\nexport {\n AMPLITUDE_ORIGIN,\n AMPLITUDE_ORIGIN_EU,\n AMPLITUDE_ORIGIN_STAGING,\n AMPLITUDE_ORIGINS_MAP,\n AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL,\n} from './messenger/constants';\n"]}
@@ -0,0 +1,13 @@
1
+ import type { BaseWindowMessenger } from './base-window-messenger';
2
+ /**
3
+ * Enable background capture on a messenger instance.
4
+ * Plugins can call this on a shared messenger instance.
5
+ * The first call registers the handlers; subsequent calls are no-ops.
6
+ *
7
+ * @param messenger - The messenger to enable background capture on
8
+ * @param options.scriptUrl - Override the background capture script URL (optional)
9
+ */
10
+ export declare function enableBackgroundCapture(messenger: BaseWindowMessenger, options?: {
11
+ scriptUrl?: string;
12
+ }): void;
13
+ //# sourceMappingURL=background-capture.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"background-capture.d.ts","sourceRoot":"","sources":["../../../src/messenger/background-capture.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AASnE;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,mBAAmB,EAAE,OAAO,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CA6C9G"}
@@ -0,0 +1,60 @@
1
+ import { AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL } from './constants';
2
+ /**
3
+ * Brand key set on the messenger instance to track whether background capture
4
+ * has been enabled.
5
+ */
6
+ var BG_CAPTURE_BRAND = '__AMPLITUDE_BACKGROUND_CAPTURE__';
7
+ /**
8
+ * Enable background capture on a messenger instance.
9
+ * Plugins can call this on a shared messenger instance.
10
+ * The first call registers the handlers; subsequent calls are no-ops.
11
+ *
12
+ * @param messenger - The messenger to enable background capture on
13
+ * @param options.scriptUrl - Override the background capture script URL (optional)
14
+ */
15
+ export function enableBackgroundCapture(messenger, options) {
16
+ var _a;
17
+ // Check the brand on the messenger object itself — works across bundle boundaries
18
+ var branded = messenger;
19
+ if (branded[BG_CAPTURE_BRAND] === true) {
20
+ return;
21
+ }
22
+ branded[BG_CAPTURE_BRAND] = true;
23
+ var scriptUrl = (_a = options === null || options === void 0 ? void 0 : options.scriptUrl) !== null && _a !== void 0 ? _a : AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL;
24
+ var backgroundCaptureInstance = null;
25
+ var onBackgroundCapture = function (type, backgroundCaptureData) {
26
+ var _a, _b;
27
+ if (type === 'background-capture-complete') {
28
+ (_b = (_a = messenger.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, 'Background capture complete');
29
+ messenger.notify({ action: 'background-capture-complete', data: backgroundCaptureData });
30
+ }
31
+ };
32
+ messenger.registerActionHandler('initialize-background-capture', function () {
33
+ var _a, _b;
34
+ (_b = (_a = messenger.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, 'Initializing background capture (external script)');
35
+ var resolvedUrl = new URL(scriptUrl, messenger.endpoint).toString();
36
+ messenger
37
+ .loadScriptOnce(resolvedUrl)
38
+ .then(function () {
39
+ var _a, _b, _c;
40
+ (_b = (_a = messenger.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, 'Background capture script loaded (external)');
41
+ // eslint-disable-next-line
42
+ backgroundCaptureInstance = /* istanbul ignore next -- window is always defined in browser */ (_c = window === null || window === void 0 ? void 0 : window.amplitudeBackgroundCapture) === null || _c === void 0 ? void 0 : _c.call(window, {
43
+ messenger: messenger,
44
+ onBackgroundCapture: onBackgroundCapture,
45
+ });
46
+ messenger.notify({ action: 'background-capture-loaded' });
47
+ })
48
+ .catch(function () {
49
+ var _a;
50
+ (_a = messenger.logger) === null || _a === void 0 ? void 0 : _a.warn('Failed to initialize background capture');
51
+ });
52
+ });
53
+ messenger.registerActionHandler('close-background-capture', function () {
54
+ var _a;
55
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
56
+ (_a = backgroundCaptureInstance === null || backgroundCaptureInstance === void 0 ? void 0 : backgroundCaptureInstance.close) === null || _a === void 0 ? void 0 : _a.call(backgroundCaptureInstance);
57
+ backgroundCaptureInstance = null;
58
+ });
59
+ }
60
+ //# sourceMappingURL=background-capture.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"background-capture.js","sourceRo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GAAG,iEAAiE,CAAC,MAC5F,MACD,aADC,MAAM,uBAAN,MAAM,CACL,0BAA0B,uDAAG;gBAC9B,SAAS,WAAA;gBACT,mBAAmB,qBAAA;aACpB,CAAC,CAAC;YACH,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,2BAA2B,EAAE,CAAC,CAAC;QAC5D,CAAC,CAAC;aACD,KAAK,CAAC;;YACL,MAAA,SAAS,CAAC,MAAM,0CAAE,IAAI,CAAC,yCAAyC,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,SAAS,CAAC,qBAAqB,CAAC,0BAA0B,EAAE;;QAC1D,yGAAyG;QACzG,MAAA,yBAAyB,aAAzB,yBAAyB,uBAAzB,yBAAyB,CAAE,KAAK,yEAAI,CAAC;QACrC,yBAAyB,GAAG,IAAI,CAAC;IACnC,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable no-restricted-globals */\nimport type { BaseWindowMessenger } from './base-window-messenger';\nimport { AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL } from './constants';\n\n/**\n * Brand key set on the messenger instance to track whether background capture\n * has been enabled.\n */\nconst BG_CAPTURE_BRAND = '__AMPLITUDE_BACKGROUND_CAPTURE__' as const;\n\n/**\n * Enable background capture on a messenger instance.\n * Plugins can call this on a shared messenger instance.\n * The first call registers the handlers; subsequent calls are no-ops.\n *\n * @param messenger - The messenger to enable background capture on\n * @param options.scriptUrl - Override the background capture script URL (optional)\n */\nexport function enableBackgroundCapture(messenger: BaseWindowMessenger, options?: { scriptUrl?: string }): void {\n // Check the brand on the messenger object itself — works across bundle boundaries\n const branded = messenger as unknown as Record<string, unknown>;\n if (branded[BG_CAPTURE_BRAND] === true) {\n return;\n }\n branded[BG_CAPTURE_BRAND] = true;\n\n const scriptUrl = options?.scriptUrl ?? AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL;\n let backgroundCaptureInstance: any = null;\n\n const onBackgroundCapture = (type: string, backgroundCaptureData: { [key: string]: string | number | null }) => {\n if (type === 'background-capture-complete') {\n messenger.logger?.debug?.('Background capture complete');\n messenger.notify({ action: 'background-capture-complete', data: backgroundCaptureData });\n }\n };\n\n messenger.registerActionHandler('initialize-background-capture', () => {\n messenger.logger?.debug?.('Initializing background capture (external script)');\n const resolvedUrl = new URL(scriptUrl, messenger.endpoint).toString();\n\n messenger\n .loadScriptOnce(resolvedUrl)\n .then(() => {\n messenger.logger?.debug?.('Background capture script loaded (external)');\n // eslint-disable-next-line\n backgroundCaptureInstance = /* istanbul ignore next -- window is always defined in browser */ (\n window as any\n )?.amplitudeBackgroundCapture?.({\n messenger,\n onBackgroundCapture,\n });\n messenger.notify({ action: 'background-capture-loaded' });\n })\n .catch(() => {\n messenger.logger?.warn('Failed to initialize background capture');\n });\n });\n\n messenger.registerActionHandler('close-background-capture', () => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n backgroundCaptureInstance?.close?.();\n backgroundCaptureInstance = null;\n });\n}\n"]}