posthog-js 1.90.2 → 1.91.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/dist/array.full.js +1 -1
- package/dist/array.full.js.map +1 -1
- package/dist/array.js +1 -1
- package/dist/array.js.map +1 -1
- package/dist/es.js +1 -1
- package/dist/es.js.map +1 -1
- package/dist/exception-autocapture.js +1 -1
- package/dist/exception-autocapture.js.map +1 -1
- package/dist/module.d.ts +3 -4
- package/dist/module.js +1 -1
- package/dist/module.js.map +1 -1
- package/dist/recorder-v2.js +1 -1
- package/dist/recorder-v2.js.map +1 -1
- package/dist/recorder.js +1 -1
- package/dist/recorder.js.map +1 -1
- package/dist/surveys.js +1 -1
- package/dist/surveys.js.map +1 -1
- package/lib/package.json +1 -1
- package/lib/src/autocapture-utils.js +2 -1
- package/lib/src/autocapture-utils.js.map +1 -1
- package/lib/src/autocapture.js +11 -4
- package/lib/src/autocapture.js.map +1 -1
- package/lib/src/decide.js +2 -1
- package/lib/src/decide.js.map +1 -1
- package/lib/src/extensions/exception-autocapture/index.js +6 -3
- package/lib/src/extensions/exception-autocapture/index.js.map +1 -1
- package/lib/src/extensions/replay/sessionrecording.js +8 -8
- package/lib/src/extensions/replay/sessionrecording.js.map +1 -1
- package/lib/src/extensions/replay/web-performance.js +1 -0
- package/lib/src/extensions/replay/web-performance.js.map +1 -1
- package/lib/src/extensions/surveys.js +10 -2
- package/lib/src/extensions/surveys.js.map +1 -1
- package/lib/src/extensions/toolbar.d.ts +2 -2
- package/lib/src/extensions/toolbar.js +16 -13
- package/lib/src/extensions/toolbar.js.map +1 -1
- package/lib/src/gdpr-utils.js +2 -2
- package/lib/src/gdpr-utils.js.map +1 -1
- package/lib/src/loader-exception-autocapture.js +4 -3
- package/lib/src/loader-exception-autocapture.js.map +1 -1
- package/lib/src/loader-recorder-v2.js +7 -4
- package/lib/src/loader-recorder-v2.js.map +1 -1
- package/lib/src/loader-recorder.js +6 -6
- package/lib/src/loader-recorder.js.map +1 -1
- package/lib/src/loader-surveys.js +5 -3
- package/lib/src/loader-surveys.js.map +1 -1
- package/lib/src/page-view.js +14 -11
- package/lib/src/page-view.js.map +1 -1
- package/lib/src/posthog-core.js +21 -22
- package/lib/src/posthog-core.js.map +1 -1
- package/lib/src/posthog-surveys.js +7 -4
- package/lib/src/posthog-surveys.js.map +1 -1
- package/lib/src/retry-queue.js +2 -1
- package/lib/src/retry-queue.js.map +1 -1
- package/lib/src/session-props.d.ts +1 -2
- package/lib/src/session-props.js +2 -2
- package/lib/src/session-props.js.map +1 -1
- package/lib/src/sessionid.js +1 -1
- package/lib/src/sessionid.js.map +1 -1
- package/lib/src/storage.d.ts +1 -1
- package/lib/src/storage.js +18 -8
- package/lib/src/storage.js.map +1 -1
- package/lib/src/utils/event-utils.js +16 -10
- package/lib/src/utils/event-utils.js.map +1 -1
- package/lib/src/utils/globals.d.ts +5 -4
- package/lib/src/utils/globals.js +7 -5
- package/lib/src/utils/globals.js.map +1 -1
- package/lib/src/utils/index.js +7 -4
- package/lib/src/utils/index.js.map +1 -1
- package/lib/src/utils/logger.js +5 -2
- package/lib/src/utils/logger.js.map +1 -1
- package/lib/src/uuidv7.js +1 -1
- package/lib/src/uuidv7.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { SURVEYS } from './constants';
|
|
2
2
|
import { _isUrlMatchingRegex } from './utils/request-utils';
|
|
3
|
+
import { window, document } from './utils/globals';
|
|
3
4
|
export var surveyUrlValidationMap = {
|
|
4
|
-
icontains: function (conditionsUrl) {
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
icontains: function (conditionsUrl) {
|
|
6
|
+
return !!window && window.location.href.toLowerCase().indexOf(conditionsUrl.toLowerCase()) > -1;
|
|
7
|
+
},
|
|
8
|
+
regex: function (conditionsUrl) { return !!window && _isUrlMatchingRegex(window.location.href, conditionsUrl); },
|
|
9
|
+
exact: function (conditionsUrl) { return (window === null || window === void 0 ? void 0 : window.location.href) === conditionsUrl; },
|
|
7
10
|
};
|
|
8
11
|
var PostHogSurveys = /** @class */ (function () {
|
|
9
12
|
function PostHogSurveys(instance) {
|
|
@@ -43,7 +46,7 @@ var PostHogSurveys = /** @class */ (function () {
|
|
|
43
46
|
? surveyUrlValidationMap[(_c = (_b = survey.conditions) === null || _b === void 0 ? void 0 : _b.urlMatchType) !== null && _c !== void 0 ? _c : 'icontains'](survey.conditions.url)
|
|
44
47
|
: true;
|
|
45
48
|
var selectorCheck = ((_d = survey.conditions) === null || _d === void 0 ? void 0 : _d.selector)
|
|
46
|
-
? document.querySelector(survey.conditions.selector)
|
|
49
|
+
? document === null || document === void 0 ? void 0 : document.querySelector(survey.conditions.selector)
|
|
47
50
|
: true;
|
|
48
51
|
return urlCheck && selectorCheck;
|
|
49
52
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog-surveys.js","sourceRoot":"","sources":["../../src/posthog-surveys.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAErC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA;
|
|
1
|
+
{"version":3,"file":"posthog-surveys.js","sourceRoot":"","sources":["../../src/posthog-surveys.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAErC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA;AAC3D,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAA;AAElD,MAAM,CAAC,IAAM,sBAAsB,GAAmE;IAClG,SAAS,EAAE,UAAC,aAAa;QACrB,OAAA,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,aAAa,CAAC,WAAW,EAAE,CAAC,GAAG,CAAC,CAAC;IAAxF,CAAwF;IAC5F,KAAK,EAAE,UAAC,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AAC,KAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,gBAAgB,CAAC,MAAM,CAAC,kBAAkB,CAAC;oBACxE,CAAC,CAAC,IAAI,CAAA;gBACV,OAAO,eAAe,IAAI,kBAAkB,CAAA;YAChD,CAAC,CAAC,CAAA;YAEF,OAAO,QAAQ,CAAC,uBAAuB,CAAC,CAAA;QAC5C,CAAC,EAAE,WAAW,CAAC,CAAA;IACnB,CAAC;IACL,qBAAC;AAAD,CAAC,AA5DD,IA4DC","sourcesContent":["import { PostHog } from './posthog-core'\nimport { SURVEYS } from './constants'\nimport { SurveyCallback, SurveyUrlMatchType } from './posthog-surveys-types'\nimport { _isUrlMatchingRegex } from './utils/request-utils'\nimport { window, document } from './utils/globals'\n\nexport const surveyUrlValidationMap: Record<SurveyUrlMatchType, (conditionsUrl: string) => boolean> = {\n icontains: (conditionsUrl) =>\n !!window && window.location.href.toLowerCase().indexOf(conditionsUrl.toLowerCase()) > -1,\n regex: (conditionsUrl) => !!window && _isUrlMatchingRegex(window.location.href, conditionsUrl),\n exact: (conditionsUrl) => window?.location.href === conditionsUrl,\n}\n\nexport class PostHogSurveys {\n instance: PostHog\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n getSurveys(callback: SurveyCallback, forceReload = false) {\n const existingSurveys = this.instance.get_property(SURVEYS)\n if (!existingSurveys || forceReload) {\n this.instance._send_request(\n `${this.instance.config.api_host}/api/surveys/?token=${this.instance.config.token}`,\n {},\n { method: 'GET' },\n (response) => {\n const surveys = response.surveys || []\n this.instance.persistence?.register({ [SURVEYS]: surveys })\n return callback(surveys)\n }\n )\n } else {\n return callback(existingSurveys)\n }\n }\n\n getActiveMatchingSurveys(callback: SurveyCallback, forceReload = false) {\n this.getSurveys((surveys) => {\n const activeSurveys = surveys.filter((survey) => {\n return !!(survey.start_date && !survey.end_date)\n })\n const conditionMatchedSurveys = activeSurveys.filter((survey) => {\n if (!survey.conditions) {\n return true\n }\n\n // use urlMatchType to validate url condition, fallback to contains for backwards compatibility\n const urlCheck = survey.conditions?.url\n ? surveyUrlValidationMap[survey.conditions?.urlMatchType ?? 'icontains'](survey.conditions.url)\n : true\n const selectorCheck = survey.conditions?.selector\n ? document?.querySelector(survey.conditions.selector)\n : true\n return urlCheck && selectorCheck\n })\n const targetingMatchedSurveys = conditionMatchedSurveys.filter((survey) => {\n if (!survey.linked_flag_key && !survey.targeting_flag_key) {\n return true\n }\n const linkedFlagCheck = survey.linked_flag_key\n ? this.instance.featureFlags.isFeatureEnabled(survey.linked_flag_key)\n : true\n const targetingFlagCheck = survey.targeting_flag_key\n ? this.instance.featureFlags.isFeatureEnabled(survey.targeting_flag_key)\n : true\n return linkedFlagCheck && targetingFlagCheck\n })\n\n return callback(targetingMatchedSurveys)\n }, forceReload)\n }\n}\n"]}
|
package/lib/src/retry-queue.js
CHANGED
|
@@ -39,6 +39,7 @@ import { RequestQueueScaffold } from './base-request-queue';
|
|
|
39
39
|
import { encodePostData, xhr } from './send-request';
|
|
40
40
|
import { _isUndefined } from './utils/type-utils';
|
|
41
41
|
import { logger } from './utils/logger';
|
|
42
|
+
import { window } from './utils/globals';
|
|
42
43
|
var thirtyMinutes = 30 * 60 * 1000;
|
|
43
44
|
/**
|
|
44
45
|
* Generates a jitter-ed exponential backoff delay in milliseconds
|
|
@@ -151,7 +152,7 @@ var RetryQueue = /** @class */ (function (_super) {
|
|
|
151
152
|
try {
|
|
152
153
|
// we've had send beacon in place for at least 2 years
|
|
153
154
|
// eslint-disable-next-line compat/compat
|
|
154
|
-
window.navigator.sendBeacon(url, encodePostData(data, __assign(__assign({}, options), { sendBeacon: true })));
|
|
155
|
+
window === null || window === void 0 ? void 0 : window.navigator.sendBeacon(url, encodePostData(data, __assign(__assign({}, options), { sendBeacon: true })));
|
|
155
156
|
}
|
|
156
157
|
catch (e) {
|
|
157
158
|
// Note sendBeacon automatically retries, and after the first retry it will lose reference to contextual `this`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry-queue.js","sourceRoot":"","sources":["../../src/retry-queue.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAA;AAC3D,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAA;AAIpD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;
|
|
1
|
+
{"version":3,"file":"retry-queue.js","sourceRoot":"","sources":["../../src/retry-queue.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAA;AAC3D,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAA;AAIpD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAExC,IAAM,aAAa,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA;AAEpC;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAAC,qBAA6B;IAC5D,IAAM,cAAc,GAAG,IAAI,GAAG,SAAA,CAAC,EAAI,qBAAqB,CAAA,CAAA;IACxD,IAAM,UAAU,GAAG,cAAc,GAAG,CAAC,CAAA;IACrC,IAAM,iBAAiB,GAAG,IAAI,CAAC,GAAG,CAAC,aAAa,EAAE,cAAc,CAAC,CAAA;IACjE,IAAM,cAAc,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,CAAA,CAAC,uCAAuC;IAClF,IAAM,MAAM,GAAG,cAAc,GAAG,CAAC,iBAAiB,GAAG,UAAU,CAAC,CAAA;IAChE,OAAO,IAAI,CAAC,IAAI,CAAC,iBAAiB,G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B,OAAO,EAAE,OAAO,IAAI,EAAE;YACtB,qBAAqB,EAAE,qBAAqB,IAAI,CAAC;YACjD,QAAQ,UAAA;YACR,UAAU,EAAE,IAAI;YAChB,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,gBAAgB;SAChD,CAAC,CAAA;IACN,CAAC;IAED,0CAAqB,GAArB;QACI,IAAI,CAAC,WAAW,GAAG,IAAI,CAAA;QACvB,IAAI,CAAC,KAAK,EAAE,CAAA;IAChB,CAAC;IACL,iBAAC;AAAD,CAAC,AAvHD,CAAgC,oBAAoB,GAuHnD","sourcesContent":["import { RequestQueueScaffold } from './base-request-queue'\nimport { encodePostData, xhr } from './send-request'\nimport { QueuedRequestData, RetryQueueElement } from './types'\nimport { RateLimiter } from './rate-limiter'\n\nimport { _isUndefined } from './utils/type-utils'\nimport { logger } from './utils/logger'\nimport { window } from './utils/globals'\n\nconst thirtyMinutes = 30 * 60 * 1000\n\n/**\n * Generates a jitter-ed exponential backoff delay in milliseconds\n *\n * The base value is 6 seconds, which is doubled with each retry\n * up to the maximum of 30 minutes\n *\n * Each value then has +/- 50% jitter\n *\n * Giving a range of 6 seconds up to 45 minutes\n */\nexport function pickNextRetryDelay(retriesPerformedSoFar: number): number {\n const rawBackoffTime = 3000 * 2 ** retriesPerformedSoFar\n const minBackoff = rawBackoffTime / 2\n const cappedBackoffTime = Math.min(thirtyMinutes, rawBackoffTime)\n const jitterFraction = Math.random() - 0.5 // A random number between -0.5 and 0.5\n const jitter = jitterFraction * (cappedBackoffTime - minBackoff)\n return Math.ceil(cappedBackoffTime + jitter)\n}\n\nexport class RetryQueue extends RequestQueueScaffold {\n queue: RetryQueueElement[]\n isPolling: boolean\n areWeOnline: boolean\n onXHRError: (failedRequest: XMLHttpRequest) => void\n rateLimiter: RateLimiter\n\n constructor(onXHRError: (failedRequest: XMLHttpRequest) => void, rateLimiter: RateLimiter) {\n super()\n this.isPolling = false\n this.queue = []\n this.areWeOnline = true\n this.onXHRError = onXHRError\n this.rateLimiter = rateLimiter\n\n if (!_isUndefined(window) && 'onLine' in window.navigator) {\n this.areWeOnline = window.navigator.onLine\n window.addEventListener('online', () => {\n this._handleWeAreNowOnline()\n })\n window.addEventListener('offline', () => {\n this.areWeOnline = false\n })\n }\n }\n\n enqueue(requestData: QueuedRequestData): void {\n const retriesPerformedSoFar = requestData.retriesPerformedSoFar || 0\n if (retriesPerformedSoFar >= 10) {\n return\n }\n const msToNextRetry = pickNextRetryDelay(retriesPerformedSoFar)\n const retryAt = new Date(Date.now() + msToNextRetry)\n\n this.queue.push({ retryAt, requestData })\n\n let logMessage = `Enqueued failed request for retry in ${msToNextRetry}`\n if (!navigator.onLine) {\n logMessage += ' (Browser is offline)'\n }\n logger.warn(logMessage)\n\n if (!this.isPolling) {\n this.isPolling = true\n this.poll()\n }\n }\n\n poll(): void {\n this._poller && clearTimeout(this._poller)\n this._poller = setTimeout(() => {\n if (this.areWeOnline && this.queue.length > 0) {\n this.flush()\n }\n this.poll()\n }, this._pollInterval) as any as number\n }\n\n flush(): void {\n // using Date.now to make tests easier, as recommended here https://codewithhugo.com/mocking-the-current-date-in-jest-tests/\n const now = new Date(Date.now())\n const toFlush = this.queue.filter(({ retryAt }) => retryAt < now)\n if (toFlush.length > 0) {\n this.queue = this.queue.filter(({ retryAt }) => retryAt >= now)\n for (const { requestData } of toFlush) {\n this._executeXhrRequest(requestData)\n }\n }\n }\n\n unload(): void {\n if (this._poller) {\n clearTimeout(this._poller)\n this._poller = undefined\n }\n\n for (const { requestData } of this.queue) {\n const { url, data, options } = requestData\n\n if (this.rateLimiter.isRateLimited(options._batchKey)) {\n logger.warn('[RetryQueue] is quota limited. Dropping request.')\n continue\n }\n\n try {\n // we've had send beacon in place for at least 2 years\n // eslint-disable-next-line compat/compat\n window?.navigator.sendBeacon(url, encodePostData(data, { ...options, sendBeacon: true }))\n } catch (e) {\n // Note sendBeacon automatically retries, and after the first retry it will lose reference to contextual `this`.\n // This means in some cases `this.getConfig` will be undefined.\n logger.error(e)\n }\n }\n this.queue = []\n }\n\n _executeXhrRequest({ url, data, options, headers, callback, retriesPerformedSoFar }: QueuedRequestData): void {\n if (this.rateLimiter.isRateLimited(options._batchKey)) {\n return\n }\n\n xhr({\n url,\n data: data || {},\n options: options || {},\n headers: headers || {},\n retriesPerformedSoFar: retriesPerformedSoFar || 0,\n callback,\n retryQueue: this,\n onXHRError: this.onXHRError,\n onResponse: this.rateLimiter.checkForLimiting,\n })\n }\n\n _handleWeAreNowOnline(): void {\n this.areWeOnline = true\n this.flush()\n }\n}\n"]}
|
|
@@ -13,12 +13,11 @@ interface StoredSessionSourceProps {
|
|
|
13
13
|
sessionId: string;
|
|
14
14
|
props: SessionSourceProps;
|
|
15
15
|
}
|
|
16
|
-
export declare const generateSessionSourceParams: () => SessionSourceProps;
|
|
17
16
|
export declare class SessionPropsManager {
|
|
18
17
|
private readonly _sessionIdManager;
|
|
19
18
|
private readonly _persistence;
|
|
20
19
|
private readonly _sessionSourceParamGenerator;
|
|
21
|
-
constructor(sessionIdManager: SessionIdManager, persistence: PostHogPersistence, sessionSourceParamGenerator?:
|
|
20
|
+
constructor(sessionIdManager: SessionIdManager, persistence: PostHogPersistence, sessionSourceParamGenerator?: () => SessionSourceProps);
|
|
22
21
|
_getStoredProps(): StoredSessionSourceProps | undefined;
|
|
23
22
|
_onSessionIdCallback: (sessionId: string) => void;
|
|
24
23
|
getSessionProps(): {
|
package/lib/src/session-props.js
CHANGED
|
@@ -20,8 +20,8 @@ var __assign = (this && this.__assign) || function () {
|
|
|
20
20
|
import { window } from './utils/globals';
|
|
21
21
|
import { _info } from './utils/event-utils';
|
|
22
22
|
import { CLIENT_SESSION_PROPS } from './constants';
|
|
23
|
-
|
|
24
|
-
return __assign({ initialPathName: window.location.pathname, referringDomain: _info.referringDomain() }, _info.campaignParams());
|
|
23
|
+
var generateSessionSourceParams = function () {
|
|
24
|
+
return __assign({ initialPathName: (window === null || window === void 0 ? void 0 : window.location.pathname) || '', referringDomain: _info.referringDomain() }, _info.campaignParams());
|
|
25
25
|
};
|
|
26
26
|
var SessionPropsManager = /** @class */ (function () {
|
|
27
27
|
function SessionPropsManager(sessionIdManager, persistence, sessionSourceParamGenerator) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-props.js","sourceRoot":"","sources":["../../src/session-props.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACxC,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AAG3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAiBlD,
|
|
1
|
+
{"version":3,"file":"session-props.js","sourceRoot":"","sources":["../../src/session-props.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACxC,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AAG3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAiBlD,IAAM,2BAA2B,GAAG;IAChC,kBACI,eAAe,EAAE,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,QAAQ,CAAC,QAAQ,KAAI,EAAE,EAChD,eAAe,EAAE,KAAK,CAAC,eAAe,EAAE,IACrC,KAAK,CAAC,cAAc,EAAE,EAC5B;AACL,CAAC,CAAA;AAED;IAKI,6BACI,gBAAkC,EAClC,WAA+B,EAC/B,2BAAsD;QAH1D,iBAUC;QAMD,yBAAoB,GAAG,UAAC,SAAiB;;YACrC,IAAM,MAAM,GAAG,KAAI,CAAC,eAAe,EAAE,CAAA;YACrC,IAAI,MAAM,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,EAAE;gBAC1C,OAAM;aACT;YAED,IAAM,QAAQ,GAA6B;gBACvC,SAAS,WAAA;gBACT,KAAK,EAAE,KAAI,CAAC,4BAA4B,EAAE;aAC7C,CAAA;YACD,KAAI,CAAC,YAAY,CAAC,QAAQ,WAAG,GAAC,oBAAoB,IAAG,QAAQ,MAAG,CAAA;QACpE,CAAC,CAAA;QAtBG,IAAI,CAAC,iBAAiB,GAAG,gBAAgB,CAAA;QACzC,IAAI,CAAC,YAAY,GAAG,WAAW,CAAA;QAC/B,IAAI,CAAC,4BAA4B,GAAG,2BAA2B,IAAI,2BAA2B,CAAA;QAE9F,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAA;IACjE,CAAC;IAED,6CAAe,GAAf;QACI,OAAO,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,oBAAoB,CAAC,CAAA;IACxD,CAAC;IAeD,6CAAe,GAAf;;QACI,IAAM,CAAC,GAAG,MAAA,IAAI,CAAC,eAAe,EAAE,0CAAE,KAAK,CAAA;QACvC,IAAI,CAAC,CAAC,EAAE;YACJ,OAAO,EAAE,CAAA;SACZ;QAED,OAAO;YACH,sCAAsC,EAAE,CAAC,CAAC,eAAe;YACzD,gCAAgC,EAAE,CAAC,CAAC,eAAe;YACnD,kCAAkC,EAAE,CAAC,CAAC,UAAU;YAChD,oCAAoC,EAAE,CAAC,CAAC,YAAY;YACpD,kCAAkC,EAAE,CAAC,CAAC,UAAU;YAChD,mCAAmC,EAAE,CAAC,CAAC,WAAW;YAClD,gCAAgC,EAAE,CAAC,CAAC,QAAQ;SAC/C,CAAA;IACL,CAAC;IACL,0BAAC;AAAD,CAAC,AAlDD,IAkDC","sourcesContent":["/* Client-side session parameters. These are primarily used by web analytics,\n * which relies on these for session analytics without the plugin server being\n * available for the person level set-once properties. Obviously not consistent\n * between client-side events and server-side events but this is acceptable\n * as web analytics only uses client-side.\n *\n * These have the same lifespan as a session_id\n */\nimport { window } from './utils/globals'\nimport { _info } from './utils/event-utils'\nimport { SessionIdManager } from './sessionid'\nimport { PostHogPersistence } from './posthog-persistence'\nimport { CLIENT_SESSION_PROPS } from './constants'\n\ninterface SessionSourceProps {\n initialPathName: string\n referringDomain: string // Is actually host, but named domain for internal consistency. Should contain a port if there is one.\n utm_medium?: string\n utm_source?: string\n utm_campaign?: string\n utm_content?: string\n utm_term?: string\n}\n\ninterface StoredSessionSourceProps {\n sessionId: string\n props: SessionSourceProps\n}\n\nconst generateSessionSourceParams = (): SessionSourceProps => {\n return {\n initialPathName: window?.location.pathname || '',\n referringDomain: _info.referringDomain(),\n ..._info.campaignParams(),\n }\n}\n\nexport class SessionPropsManager {\n private readonly _sessionIdManager: SessionIdManager\n private readonly _persistence: PostHogPersistence\n private readonly _sessionSourceParamGenerator: () => SessionSourceProps\n\n constructor(\n sessionIdManager: SessionIdManager,\n persistence: PostHogPersistence,\n sessionSourceParamGenerator?: () => SessionSourceProps\n ) {\n this._sessionIdManager = sessionIdManager\n this._persistence = persistence\n this._sessionSourceParamGenerator = sessionSourceParamGenerator || generateSessionSourceParams\n\n this._sessionIdManager.onSessionId(this._onSessionIdCallback)\n }\n\n _getStoredProps(): StoredSessionSourceProps | undefined {\n return this._persistence.props[CLIENT_SESSION_PROPS]\n }\n\n _onSessionIdCallback = (sessionId: string) => {\n const stored = this._getStoredProps()\n if (stored && stored.sessionId === sessionId) {\n return\n }\n\n const newProps: StoredSessionSourceProps = {\n sessionId,\n props: this._sessionSourceParamGenerator(),\n }\n this._persistence.register({ [CLIENT_SESSION_PROPS]: newProps })\n }\n\n getSessionProps() {\n const p = this._getStoredProps()?.props\n if (!p) {\n return {}\n }\n\n return {\n $client_session_initial_referring_host: p.referringDomain,\n $client_session_initial_pathname: p.initialPathName,\n $client_session_initial_utm_source: p.utm_source,\n $client_session_initial_utm_campaign: p.utm_campaign,\n $client_session_initial_utm_medium: p.utm_medium,\n $client_session_initial_utm_content: p.utm_content,\n $client_session_initial_utm_term: p.utm_term,\n }\n }\n}\n"]}
|
package/lib/src/sessionid.js
CHANGED
|
@@ -148,7 +148,7 @@ var SessionIdManager = /** @class */ (function () {
|
|
|
148
148
|
*/
|
|
149
149
|
SessionIdManager.prototype._listenToReloadWindow = function () {
|
|
150
150
|
var _this = this;
|
|
151
|
-
window.addEventListener('beforeunload', function () {
|
|
151
|
+
window === null || window === void 0 ? void 0 : window.addEventListener('beforeunload', function () {
|
|
152
152
|
if (_this._canUseSessionStorage()) {
|
|
153
153
|
sessionStore.remove(_this._primary_window_exists_storage_key);
|
|
154
154
|
}
|
package/lib/src/sessionid.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionid.js","sourceRoot":"","sources":["../../src/sessionid.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AACA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAExC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAExC,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAEvC,IAAM,wBAAwB,GAAG,EAAE,GAAG,EAAE,CAAA,CAAC,aAAa;AACtD,IAAM,wBAAwB,GAAG,EAAE,CAAA,CAAC,WAAW;AAC/C,IAAM,oBAAoB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAA,CAAC,WAAW;AAEzD;IAeI,0BACI,MAA8B,EAC9B,WAA+B,EAC/B,kBAAiC,EACjC,iBAAgC;QAN5B,8BAAyB,GAA+B,EAAE,CAAA;QAQ9D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;QAC9B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;QAC1B,IAAI,CAAC,UAAU,GAAG,SAAS,CAAA;QAC3B,IAAI,CAAC,sBAAsB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,IAAI,IAAI,CAAC,GAAG,CAAC,SAAS,GAAG,aAAa,CAAC,GAAG,IAAI,CAAC,iBAAiB,CAAA;QACjG,IAAI,WAAW,IAAI,eAAe,IAAI,wBAAwB,EAAE;YAC5D,SAAS,GAAG,IAAI,CAAC,mBAAmB,EAAE,CAAA;YACtC,QAAQ,GAAG,IAAI,CAAC,kBAAkB,EAAE,CAAA;YACpC,cAAc,GAAG,SAAS,CAAA;YAC1B,aAAa,GAAG,IAAI,CAAA;SACvB;aAAM,IAAI,CAAC,QAAQ,EAAE;YAClB,QAAQ,GAAG,IAAI,CAAC,kBAAkB,EAAE,CAAA;YACpC,aAAa,GAAG,IAAI,CAAA;SACvB;QAED,IAAM,YAAY,GAAG,aAAa,KAAK,CAAC,IAAI,CAAC,QAAQ,IAAI,wBAAwB,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa,CAAA;QAC7G,IAAM,qBAAqB,GAAG,cAAc,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,cAAc,CAAA;QAE1F,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAA;QAC3B,IAAI,CAAC,aAAa,CAAC,SAAS,EAAE,YAAY,EAAE,qBAAqB,CAAC,CAAA;QAElE,IAAI,aAAa,EAAE;YACf,IAAI,CAAC,yBAAyB,CAAC,OAAO,CAAC,UAAC,OAAO,IAAK,OAAA,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC,EAA5B,CAA4B,CAAC,CAAA;SACpF;QAED,OAAO;YACH,SAAS,WAAA;YACT,QAAQ,UAAA;YACR,qBAAqB,uBAAA;SACxB,CAAA;IACL,CAAC;IACL,uBAAC;AAAD,CAAC,AA/ND,IA+NC","sourcesContent":["import { PostHogPersistence } from './posthog-persistence'\nimport { SESSION_ID } from './constants'\nimport { sessionStore } from './storage'\nimport { PostHogConfig, SessionIdChangedCallback } from './types'\nimport { uuidv7 } from './uuidv7'\nimport { window } from './utils/globals'\n\nimport { _isArray, _isNumber, _isUndefined } from './utils/type-utils'\nimport { logger } from './utils/logger'\n\nconst MAX_SESSION_IDLE_TIMEOUT = 30 * 60 // 30 minutes\nconst MIN_SESSION_IDLE_TIMEOUT = 60 // 1 minute\nconst SESSION_LENGTH_LIMIT = 24 * 3600 * 1000 // 24 hours\n\nexport class SessionIdManager {\n private readonly _sessionIdGenerator: () => string\n private readonly _windowIdGenerator: () => string\n private config: Partial<PostHogConfig>\n private persistence: PostHogPersistence\n private _windowId: string | null | undefined\n private _sessionId: string | null | undefined\n private readonly _window_id_storage_key: string\n private readonly _primary_window_exists_storage_key: string\n private _sessionStartTimestamp: number | null\n\n private _sessionActivityTimestamp: number | null\n private readonly _sessionTimeoutMs: number\n private _sessionIdChangedHandlers: SessionIdChangedCallback[] = []\n\n constructor(\n config: Partial<PostHogConfig>,\n persistence: PostHogPersistence,\n sessionIdGenerator?: () => string,\n windowIdGenerator?: () => string\n ) {\n this.config = config\n this.persistence = persistence\n this._windowId = undefined\n this._sessionId = undefined\n this._sessionStartTimestamp = null\n this._sessionActivityTimestamp = null\n this._sessionIdGenerator = sessionIdGenerator || uuidv7\n this._windowIdGenerator = windowIdGenerator || uuidv7\n\n const persistenceName = config['persistence_name'] || config['token']\n let desiredTimeout = config['session_idle_timeout_seconds'] || MAX_SESSION_IDLE_TIMEOUT\n\n if (!_isNumber(desiredTimeout)) {\n logger.warn('session_idle_timeout_seconds must be a number. Defaulting to 30 minutes.')\n desiredTimeout = MAX_SESSION_IDLE_TIMEOUT\n } else if (desiredTimeout > MAX_SESSION_IDLE_TIMEOUT) {\n logger.warn('session_idle_timeout_seconds cannot be greater than 30 minutes. Using 30 minutes instead.')\n } else if (desiredTimeout < MIN_SESSION_IDLE_TIMEOUT) {\n logger.warn('session_idle_timeout_seconds cannot be less than 60 seconds. Using 60 seconds instead.')\n }\n\n this._sessionTimeoutMs =\n Math.min(Math.max(desiredTimeout, MIN_SESSION_IDLE_TIMEOUT), MAX_SESSION_IDLE_TIMEOUT) * 1000\n this._window_id_storage_key = 'ph_' + persistenceName + '_window_id'\n this._primary_window_exists_storage_key = 'ph_' + persistenceName + '_primary_window_exists'\n\n // primary_window_exists is set when the DOM has been loaded and is cleared on unload\n // if it exists here it means there was no unload which suggests this window is opened as a tab duplication, window.open, etc.\n if (this._canUseSessionStorage()) {\n const lastWindowId = sessionStore.parse(this._window_id_storage_key)\n\n const primaryWindowExists = sessionStore.parse(this._primary_window_exists_storage_key)\n if (lastWindowId && !primaryWindowExists) {\n // Persist window from previous storage state\n this._windowId = lastWindowId\n } else {\n // Wipe any reference to previous window id\n sessionStore.remove(this._window_id_storage_key)\n }\n // Flag this session as having a primary window\n sessionStore.set(this._primary_window_exists_storage_key, true)\n }\n\n this._listenToReloadWindow()\n }\n\n onSessionId(callback: SessionIdChangedCallback): () => void {\n // KLUDGE: when running in tests the handlers array was always undefined\n // it's yucky but safe to set it here so that it's always definitely available\n if (_isUndefined(this._sessionIdChangedHandlers)) {\n this._sessionIdChangedHandlers = []\n }\n\n this._sessionIdChangedHandlers.push(callback)\n if (this._sessionId) {\n callback(this._sessionId, this._windowId)\n }\n return () => {\n this._sessionIdChangedHandlers = this._sessionIdChangedHandlers.filter((h) => h !== callback)\n }\n }\n\n private _canUseSessionStorage(): boolean {\n // We only want to use sessionStorage if persistence is enabled and not memory storage\n return this.config.persistence !== 'memory' && !this.persistence.disabled && sessionStore.is_supported()\n }\n\n // Note: this tries to store the windowId in sessionStorage. SessionStorage is unique to the current window/tab,\n // and persists page loads/reloads. So it's uniquely suited for storing the windowId. This function also respects\n // when persistence is disabled (by user config) and when sessionStorage is not supported (it *should* be supported on all browsers),\n // and in that case, it falls back to memory (which sadly, won't persist page loads)\n private _setWindowId(windowId: string): void {\n if (windowId !== this._windowId) {\n this._windowId = windowId\n if (this._canUseSessionStorage()) {\n sessionStore.set(this._window_id_storage_key, windowId)\n }\n }\n }\n\n private _getWindowId(): string | null {\n if (this._windowId) {\n return this._windowId\n }\n if (this._canUseSessionStorage()) {\n return sessionStore.parse(this._window_id_storage_key)\n }\n // New window id will be generated\n return null\n }\n\n // Note: 'this.persistence.register' can be disabled in the config.\n // In that case, this works by storing sessionId and the timestamp in memory.\n private _setSessionId(\n sessionId: string | null,\n sessionActivityTimestamp: number | null,\n sessionStartTimestamp: number | null\n ): void {\n if (\n sessionId !== this._sessionId ||\n sessionActivityTimestamp !== this._sessionActivityTimestamp ||\n sessionStartTimestamp !== this._sessionStartTimestamp\n ) {\n this._sessionStartTimestamp = sessionStartTimestamp\n this._sessionActivityTimestamp = sessionActivityTimestamp\n this._sessionId = sessionId\n\n this.persistence.register({\n [SESSION_ID]: [sessionActivityTimestamp, sessionId, sessionStartTimestamp],\n })\n }\n }\n\n private _getSessionId(): [number, string, number] {\n if (this._sessionId && this._sessionActivityTimestamp && this._sessionStartTimestamp) {\n return [this._sessionActivityTimestamp, this._sessionId, this._sessionStartTimestamp]\n }\n const sessionId = this.persistence.props[SESSION_ID]\n\n if (_isArray(sessionId) && sessionId.length === 2) {\n // Storage does not yet have a session start time. Add the last activity timestamp as the start time\n sessionId.push(sessionId[0])\n }\n\n return sessionId || [0, null, 0]\n }\n\n // Resets the session id by setting it to null. On the subsequent call to checkAndGetSessionAndWindowId,\n // new ids will be generated.\n resetSessionId(): void {\n this._setSessionId(null, null, null)\n }\n\n /*\n * Listens to window unloads and removes the primaryWindowExists key from sessionStorage.\n * Reloaded or fresh tabs created after a DOM unloads (reloading the same tab) WILL NOT have this primaryWindowExists flag in session storage.\n * Cloned sessions (new tab, tab duplication, window.open(), ...) WILL have this primaryWindowExists flag in their copied session storage.\n * We conditionally check the primaryWindowExists value in the constructor to decide if the window id in the last session storage should be carried over.\n */\n private _listenToReloadWindow(): void {\n window.addEventListener('beforeunload', () => {\n if (this._canUseSessionStorage()) {\n sessionStore.remove(this._primary_window_exists_storage_key)\n }\n })\n }\n\n /*\n * This function returns the current sessionId and windowId. It should be used to\n * access these values over directly calling `._sessionId` or `._windowId`.\n * In addition to returning the sessionId and windowId, this function also manages cycling the\n * sessionId and windowId when appropriate by doing the following:\n *\n * 1. If the sessionId or windowId is not set, it will generate a new one and store it.\n * 2. If the readOnly param is set to false, it will:\n * a. Check if it has been > SESSION_CHANGE_THRESHOLD since the last call with this flag set.\n * If so, it will generate a new sessionId and store it.\n * b. Update the timestamp stored with the sessionId to ensure the current session is extended\n * for the appropriate amount of time.\n *\n * @param {boolean} readOnly (optional) Defaults to False. Should be set to True when the call to the function should not extend or cycle the session (e.g. being called for non-user generated events)\n * @param {Number} timestamp (optional) Defaults to the current time. The timestamp to be stored with the sessionId (used when determining if a new sessionId should be generated)\n */\n checkAndGetSessionAndWindowId(readOnly = false, _timestamp: number | null = null) {\n const timestamp = _timestamp || new Date().getTime()\n\n // eslint-disable-next-line prefer-const\n let [lastTimestamp, sessionId, startTimestamp] = this._getSessionId()\n let windowId = this._getWindowId()\n\n const sessionPastMaximumLength =\n startTimestamp && startTimestamp > 0 && Math.abs(timestamp - startTimestamp) > SESSION_LENGTH_LIMIT\n\n let valuesChanged = false\n const noSessionId = !sessionId\n const activityTimeout = !readOnly && Math.abs(timestamp - lastTimestamp) > this._sessionTimeoutMs\n if (noSessionId || activityTimeout || sessionPastMaximumLength) {\n sessionId = this._sessionIdGenerator()\n windowId = this._windowIdGenerator()\n startTimestamp = timestamp\n valuesChanged = true\n } else if (!windowId) {\n windowId = this._windowIdGenerator()\n valuesChanged = true\n }\n\n const newTimestamp = lastTimestamp === 0 || !readOnly || sessionPastMaximumLength ? timestamp : lastTimestamp\n const sessionStartTimestamp = startTimestamp === 0 ? new Date().getTime() : startTimestamp\n\n this._setWindowId(windowId)\n this._setSessionId(sessionId, newTimestamp, sessionStartTimestamp)\n\n if (valuesChanged) {\n this._sessionIdChangedHandlers.forEach((handler) => handler(sessionId, windowId))\n }\n\n return {\n sessionId,\n windowId,\n sessionStartTimestamp,\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"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I,CAAC,QAAQ,EAAE;YAClB,QAAQ,GAAG,IAAI,CAAC,kBAAkB,EAAE,CAAA;YACpC,aAAa,GAAG,IAAI,CAAA;SACvB;QAED,IAAM,YAAY,GAAG,aAAa,KAAK,CAAC,IAAI,CAAC,QAAQ,IAAI,wBAAwB,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa,CAAA;QAC7G,IAAM,qBAAqB,GAAG,cAAc,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,cAAc,CAAA;QAE1F,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAA;QAC3B,IAAI,CAAC,aAAa,CAAC,SAAS,EAAE,YAAY,EAAE,qBAAqB,CAAC,CAAA;QAElE,IAAI,aAAa,EAAE;YACf,IAAI,CAAC,yBAAyB,CAAC,OAAO,CAAC,UAAC,OAAO,IAAK,OAAA,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC,EAA5B,CAA4B,CAAC,CAAA;SACpF;QAED,OAAO;YACH,SAAS,WAAA;YACT,QAAQ,UAAA;YACR,qBAAqB,uBAAA;SACxB,CAAA;IACL,CAAC;IACL,uBAAC;AAAD,CAAC,AA/ND,IA+NC","sourcesContent":["import { PostHogPersistence } from './posthog-persistence'\nimport { SESSION_ID } from './constants'\nimport { sessionStore } from './storage'\nimport { PostHogConfig, SessionIdChangedCallback } from './types'\nimport { uuidv7 } from './uuidv7'\nimport { window } from './utils/globals'\n\nimport { _isArray, _isNumber, _isUndefined } from './utils/type-utils'\nimport { logger } from './utils/logger'\n\nconst MAX_SESSION_IDLE_TIMEOUT = 30 * 60 // 30 minutes\nconst MIN_SESSION_IDLE_TIMEOUT = 60 // 1 minute\nconst SESSION_LENGTH_LIMIT = 24 * 3600 * 1000 // 24 hours\n\nexport class SessionIdManager {\n private readonly _sessionIdGenerator: () => string\n private readonly _windowIdGenerator: () => string\n private config: Partial<PostHogConfig>\n private persistence: PostHogPersistence\n private _windowId: string | null | undefined\n private _sessionId: string | null | undefined\n private readonly _window_id_storage_key: string\n private readonly _primary_window_exists_storage_key: string\n private _sessionStartTimestamp: number | null\n\n private _sessionActivityTimestamp: number | null\n private readonly _sessionTimeoutMs: number\n private _sessionIdChangedHandlers: SessionIdChangedCallback[] = []\n\n constructor(\n config: Partial<PostHogConfig>,\n persistence: PostHogPersistence,\n sessionIdGenerator?: () => string,\n windowIdGenerator?: () => string\n ) {\n this.config = config\n this.persistence = persistence\n this._windowId = undefined\n this._sessionId = undefined\n this._sessionStartTimestamp = null\n this._sessionActivityTimestamp = null\n this._sessionIdGenerator = sessionIdGenerator || uuidv7\n this._windowIdGenerator = windowIdGenerator || uuidv7\n\n const persistenceName = config['persistence_name'] || config['token']\n let desiredTimeout = config['session_idle_timeout_seconds'] || MAX_SESSION_IDLE_TIMEOUT\n\n if (!_isNumber(desiredTimeout)) {\n logger.warn('session_idle_timeout_seconds must be a number. Defaulting to 30 minutes.')\n desiredTimeout = MAX_SESSION_IDLE_TIMEOUT\n } else if (desiredTimeout > MAX_SESSION_IDLE_TIMEOUT) {\n logger.warn('session_idle_timeout_seconds cannot be greater than 30 minutes. Using 30 minutes instead.')\n } else if (desiredTimeout < MIN_SESSION_IDLE_TIMEOUT) {\n logger.warn('session_idle_timeout_seconds cannot be less than 60 seconds. Using 60 seconds instead.')\n }\n\n this._sessionTimeoutMs =\n Math.min(Math.max(desiredTimeout, MIN_SESSION_IDLE_TIMEOUT), MAX_SESSION_IDLE_TIMEOUT) * 1000\n this._window_id_storage_key = 'ph_' + persistenceName + '_window_id'\n this._primary_window_exists_storage_key = 'ph_' + persistenceName + '_primary_window_exists'\n\n // primary_window_exists is set when the DOM has been loaded and is cleared on unload\n // if it exists here it means there was no unload which suggests this window is opened as a tab duplication, window.open, etc.\n if (this._canUseSessionStorage()) {\n const lastWindowId = sessionStore.parse(this._window_id_storage_key)\n\n const primaryWindowExists = sessionStore.parse(this._primary_window_exists_storage_key)\n if (lastWindowId && !primaryWindowExists) {\n // Persist window from previous storage state\n this._windowId = lastWindowId\n } else {\n // Wipe any reference to previous window id\n sessionStore.remove(this._window_id_storage_key)\n }\n // Flag this session as having a primary window\n sessionStore.set(this._primary_window_exists_storage_key, true)\n }\n\n this._listenToReloadWindow()\n }\n\n onSessionId(callback: SessionIdChangedCallback): () => void {\n // KLUDGE: when running in tests the handlers array was always undefined\n // it's yucky but safe to set it here so that it's always definitely available\n if (_isUndefined(this._sessionIdChangedHandlers)) {\n this._sessionIdChangedHandlers = []\n }\n\n this._sessionIdChangedHandlers.push(callback)\n if (this._sessionId) {\n callback(this._sessionId, this._windowId)\n }\n return () => {\n this._sessionIdChangedHandlers = this._sessionIdChangedHandlers.filter((h) => h !== callback)\n }\n }\n\n private _canUseSessionStorage(): boolean {\n // We only want to use sessionStorage if persistence is enabled and not memory storage\n return this.config.persistence !== 'memory' && !this.persistence.disabled && sessionStore.is_supported()\n }\n\n // Note: this tries to store the windowId in sessionStorage. SessionStorage is unique to the current window/tab,\n // and persists page loads/reloads. So it's uniquely suited for storing the windowId. This function also respects\n // when persistence is disabled (by user config) and when sessionStorage is not supported (it *should* be supported on all browsers),\n // and in that case, it falls back to memory (which sadly, won't persist page loads)\n private _setWindowId(windowId: string): void {\n if (windowId !== this._windowId) {\n this._windowId = windowId\n if (this._canUseSessionStorage()) {\n sessionStore.set(this._window_id_storage_key, windowId)\n }\n }\n }\n\n private _getWindowId(): string | null {\n if (this._windowId) {\n return this._windowId\n }\n if (this._canUseSessionStorage()) {\n return sessionStore.parse(this._window_id_storage_key)\n }\n // New window id will be generated\n return null\n }\n\n // Note: 'this.persistence.register' can be disabled in the config.\n // In that case, this works by storing sessionId and the timestamp in memory.\n private _setSessionId(\n sessionId: string | null,\n sessionActivityTimestamp: number | null,\n sessionStartTimestamp: number | null\n ): void {\n if (\n sessionId !== this._sessionId ||\n sessionActivityTimestamp !== this._sessionActivityTimestamp ||\n sessionStartTimestamp !== this._sessionStartTimestamp\n ) {\n this._sessionStartTimestamp = sessionStartTimestamp\n this._sessionActivityTimestamp = sessionActivityTimestamp\n this._sessionId = sessionId\n\n this.persistence.register({\n [SESSION_ID]: [sessionActivityTimestamp, sessionId, sessionStartTimestamp],\n })\n }\n }\n\n private _getSessionId(): [number, string, number] {\n if (this._sessionId && this._sessionActivityTimestamp && this._sessionStartTimestamp) {\n return [this._sessionActivityTimestamp, this._sessionId, this._sessionStartTimestamp]\n }\n const sessionId = this.persistence.props[SESSION_ID]\n\n if (_isArray(sessionId) && sessionId.length === 2) {\n // Storage does not yet have a session start time. Add the last activity timestamp as the start time\n sessionId.push(sessionId[0])\n }\n\n return sessionId || [0, null, 0]\n }\n\n // Resets the session id by setting it to null. On the subsequent call to checkAndGetSessionAndWindowId,\n // new ids will be generated.\n resetSessionId(): void {\n this._setSessionId(null, null, null)\n }\n\n /*\n * Listens to window unloads and removes the primaryWindowExists key from sessionStorage.\n * Reloaded or fresh tabs created after a DOM unloads (reloading the same tab) WILL NOT have this primaryWindowExists flag in session storage.\n * Cloned sessions (new tab, tab duplication, window.open(), ...) WILL have this primaryWindowExists flag in their copied session storage.\n * We conditionally check the primaryWindowExists value in the constructor to decide if the window id in the last session storage should be carried over.\n */\n private _listenToReloadWindow(): void {\n window?.addEventListener('beforeunload', () => {\n if (this._canUseSessionStorage()) {\n sessionStore.remove(this._primary_window_exists_storage_key)\n }\n })\n }\n\n /*\n * This function returns the current sessionId and windowId. It should be used to\n * access these values over directly calling `._sessionId` or `._windowId`.\n * In addition to returning the sessionId and windowId, this function also manages cycling the\n * sessionId and windowId when appropriate by doing the following:\n *\n * 1. If the sessionId or windowId is not set, it will generate a new one and store it.\n * 2. If the readOnly param is set to false, it will:\n * a. Check if it has been > SESSION_CHANGE_THRESHOLD since the last call with this flag set.\n * If so, it will generate a new sessionId and store it.\n * b. Update the timestamp stored with the sessionId to ensure the current session is extended\n * for the appropriate amount of time.\n *\n * @param {boolean} readOnly (optional) Defaults to False. Should be set to True when the call to the function should not extend or cycle the session (e.g. being called for non-user generated events)\n * @param {Number} timestamp (optional) Defaults to the current time. The timestamp to be stored with the sessionId (used when determining if a new sessionId should be generated)\n */\n checkAndGetSessionAndWindowId(readOnly = false, _timestamp: number | null = null) {\n const timestamp = _timestamp || new Date().getTime()\n\n // eslint-disable-next-line prefer-const\n let [lastTimestamp, sessionId, startTimestamp] = this._getSessionId()\n let windowId = this._getWindowId()\n\n const sessionPastMaximumLength =\n startTimestamp && startTimestamp > 0 && Math.abs(timestamp - startTimestamp) > SESSION_LENGTH_LIMIT\n\n let valuesChanged = false\n const noSessionId = !sessionId\n const activityTimeout = !readOnly && Math.abs(timestamp - lastTimestamp) > this._sessionTimeoutMs\n if (noSessionId || activityTimeout || sessionPastMaximumLength) {\n sessionId = this._sessionIdGenerator()\n windowId = this._windowIdGenerator()\n startTimestamp = timestamp\n valuesChanged = true\n } else if (!windowId) {\n windowId = this._windowIdGenerator()\n valuesChanged = true\n }\n\n const newTimestamp = lastTimestamp === 0 || !readOnly || sessionPastMaximumLength ? timestamp : lastTimestamp\n const sessionStartTimestamp = startTimestamp === 0 ? new Date().getTime() : startTimestamp\n\n this._setWindowId(windowId)\n this._setSessionId(sessionId, newTimestamp, sessionStartTimestamp)\n\n if (valuesChanged) {\n this._sessionIdChangedHandlers.forEach((handler) => handler(sessionId, windowId))\n }\n\n return {\n sessionId,\n windowId,\n sessionStartTimestamp,\n }\n }\n}\n"]}
|
package/lib/src/storage.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { PersistentStore } from './types';
|
|
|
12
12
|
*
|
|
13
13
|
* inspired by https://github.com/AngusFu/browser-root-domain
|
|
14
14
|
*/
|
|
15
|
-
export declare function seekFirstNonPublicSubDomain(hostname: string, cookieJar?: Document): string;
|
|
15
|
+
export declare function seekFirstNonPublicSubDomain(hostname: string, cookieJar?: Document | undefined): string;
|
|
16
16
|
export declare function chooseCookieDomain(hostname: string, cross_subdomain: boolean | undefined): string;
|
|
17
17
|
export declare const cookieStore: PersistentStore;
|
|
18
18
|
export declare const localStore: PersistentStore;
|
package/lib/src/storage.js
CHANGED
|
@@ -13,6 +13,7 @@ import { _extend } from './utils';
|
|
|
13
13
|
import { DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED } from './constants';
|
|
14
14
|
import { _isNull, _isUndefined } from './utils/type-utils';
|
|
15
15
|
import { logger } from './utils/logger';
|
|
16
|
+
import { window, document } from './utils/globals';
|
|
16
17
|
import { uuidv7 } from './uuidv7';
|
|
17
18
|
var Y1970 = 'Thu, 01 Jan 1970 00:00:00 GMT';
|
|
18
19
|
/**
|
|
@@ -30,6 +31,9 @@ var Y1970 = 'Thu, 01 Jan 1970 00:00:00 GMT';
|
|
|
30
31
|
*/
|
|
31
32
|
export function seekFirstNonPublicSubDomain(hostname, cookieJar) {
|
|
32
33
|
if (cookieJar === void 0) { cookieJar = document; }
|
|
34
|
+
if (!cookieJar) {
|
|
35
|
+
return '';
|
|
36
|
+
}
|
|
33
37
|
if (['localhost', '127.0.0.1'].includes(hostname))
|
|
34
38
|
return '';
|
|
35
39
|
var list = hostname.split('.');
|
|
@@ -71,11 +75,14 @@ export function chooseCookieDomain(hostname, cross_subdomain) {
|
|
|
71
75
|
}
|
|
72
76
|
// Methods partially borrowed from quirksmode.org/js/cookies.html
|
|
73
77
|
export var cookieStore = {
|
|
74
|
-
is_supported: function () { return
|
|
78
|
+
is_supported: function () { return !!document; },
|
|
75
79
|
error: function (msg) {
|
|
76
80
|
logger.error('cookieStore error: ' + msg);
|
|
77
81
|
},
|
|
78
82
|
get: function (name) {
|
|
83
|
+
if (!document) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
79
86
|
try {
|
|
80
87
|
var nameEQ = name + '=';
|
|
81
88
|
var ca = document.cookie.split(';').filter(function (x) { return x.length; });
|
|
@@ -103,6 +110,9 @@ export var cookieStore = {
|
|
|
103
110
|
return cookie;
|
|
104
111
|
},
|
|
105
112
|
set: function (name, value, days, cross_subdomain, is_secure) {
|
|
113
|
+
if (!document) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
106
116
|
try {
|
|
107
117
|
var expires = '', secure = '';
|
|
108
118
|
var cdomain = chooseCookieDomain(document.location.hostname, cross_subdomain);
|
|
@@ -171,7 +181,7 @@ export var localStore = {
|
|
|
171
181
|
},
|
|
172
182
|
get: function (name) {
|
|
173
183
|
try {
|
|
174
|
-
return window.localStorage.getItem(name);
|
|
184
|
+
return window === null || window === void 0 ? void 0 : window.localStorage.getItem(name);
|
|
175
185
|
}
|
|
176
186
|
catch (err) {
|
|
177
187
|
localStore.error(err);
|
|
@@ -189,7 +199,7 @@ export var localStore = {
|
|
|
189
199
|
},
|
|
190
200
|
set: function (name, value) {
|
|
191
201
|
try {
|
|
192
|
-
window.localStorage.setItem(name, JSON.stringify(value));
|
|
202
|
+
window === null || window === void 0 ? void 0 : window.localStorage.setItem(name, JSON.stringify(value));
|
|
193
203
|
}
|
|
194
204
|
catch (err) {
|
|
195
205
|
localStore.error(err);
|
|
@@ -197,7 +207,7 @@ export var localStore = {
|
|
|
197
207
|
},
|
|
198
208
|
remove: function (name) {
|
|
199
209
|
try {
|
|
200
|
-
window.localStorage.removeItem(name);
|
|
210
|
+
window === null || window === void 0 ? void 0 : window.localStorage.removeItem(name);
|
|
201
211
|
}
|
|
202
212
|
catch (err) {
|
|
203
213
|
localStore.error(err);
|
|
@@ -242,7 +252,7 @@ export var localPlusCookieStore = __assign(__assign({}, localStore), { parse: fu
|
|
|
242
252
|
}
|
|
243
253
|
}, remove: function (name, cross_subdomain) {
|
|
244
254
|
try {
|
|
245
|
-
window.localStorage.removeItem(name);
|
|
255
|
+
window === null || window === void 0 ? void 0 : window.localStorage.removeItem(name);
|
|
246
256
|
cookieStore.remove(name, cross_subdomain);
|
|
247
257
|
}
|
|
248
258
|
catch (err) {
|
|
@@ -305,7 +315,7 @@ export var sessionStore = {
|
|
|
305
315
|
},
|
|
306
316
|
get: function (name) {
|
|
307
317
|
try {
|
|
308
|
-
return window.sessionStorage.getItem(name);
|
|
318
|
+
return window === null || window === void 0 ? void 0 : window.sessionStorage.getItem(name);
|
|
309
319
|
}
|
|
310
320
|
catch (err) {
|
|
311
321
|
sessionStore.error(err);
|
|
@@ -323,7 +333,7 @@ export var sessionStore = {
|
|
|
323
333
|
},
|
|
324
334
|
set: function (name, value) {
|
|
325
335
|
try {
|
|
326
|
-
window.sessionStorage.setItem(name, JSON.stringify(value));
|
|
336
|
+
window === null || window === void 0 ? void 0 : window.sessionStorage.setItem(name, JSON.stringify(value));
|
|
327
337
|
}
|
|
328
338
|
catch (err) {
|
|
329
339
|
sessionStore.error(err);
|
|
@@ -331,7 +341,7 @@ export var sessionStore = {
|
|
|
331
341
|
},
|
|
332
342
|
remove: function (name) {
|
|
333
343
|
try {
|
|
334
|
-
window.sessionStorage.removeItem(name);
|
|
344
|
+
window === null || window === void 0 ? void 0 : window.sessionStorage.removeItem(name);
|
|
335
345
|
}
|
|
336
346
|
catch (err) {
|
|
337
347
|
sessionStore.error(err);
|
package/lib/src/storage.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/storage.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAEjC,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,4BAA4B,EAAE,MAAM,aAAa,CAAA;AAEnF,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAEjC,IAAM,KAAK,GAAG,+BAA+B,CAAA;AAE7C;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,2BAA2B,CAAC,QAAgB,EAAE,SAAoB;IAApB,0BAAA,EAAA,oBAAoB;IAC9E,IAAI,CAAC,WAAW,EAAE,WA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AA;aAC3B;YAAC,OAAO,GAAG,EAAE;gBACV,uBAAuB,GAAG,KAAK,CAAA;aAClC;SACJ;aAAM;YACH,uBAAuB,GAAG,KAAK,CAAA;SAClC;QACD,OAAO,uBAAuB,CAAA;IAClC,CAAC;IAED,KAAK,EAAE,UAAU,GAAG;QAChB,MAAM,CAAC,KAAK,CAAC,wBAAwB,EAAE,GAAG,CAAC,CAAA;IAC/C,CAAC;IAED,GAAG,EAAE,UAAU,IAAI;QACf,IAAI;YACA,OAAO,MAAM,CAAC,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;SAC7C;QAAC,OAAO,GAAG,EAAE;YACV,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;QACD,OAAO,IAAI,CAAA;IACf,CAAC;IAED,KAAK,EAAE,UAAU,IAAI;QACjB,IAAI;YACA,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAA;SACpD;QAAC,OAAO,GAAG,EAAE;YACV,OAAO;SACV;QACD,OAAO,IAAI,CAAA;IACf,CAAC;IAED,GAAG,EAAE,UAAU,IAAI,EAAE,KAAK;QACtB,IAAI;YACA,MAAM,CAAC,cAAc,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAA;SAC7D;QAAC,OAAO,GAAG,EAAE;YACV,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;IACL,CAAC;IAED,MAAM,EAAE,UAAU,IAAI;QAClB,IAAI;YACA,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;SACzC;QAAC,OAAO,GAAG,EAAE;YACV,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;IACL,CAAC;CACJ,CAAA","sourcesContent":["import { _extend } from './utils'\nimport { PersistentStore, Properties } from './types'\nimport { DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED } from './constants'\n\nimport { _isNull, _isUndefined } from './utils/type-utils'\nimport { logger } from './utils/logger'\nimport { uuidv7 } from './uuidv7'\n\nconst Y1970 = 'Thu, 01 Jan 1970 00:00:00 GMT'\n\n/**\n * Browsers don't offer a way to check if something is a public suffix\n * e.g. `.com.au`, `.io`, `.org.uk`\n *\n * But they do reject cookies set on public suffixes\n * Setting a cookie on `.co.uk` would mean it was sent for every `.co.uk` site visited\n *\n * So, we can use this to check if a domain is a public suffix\n * by trying to set a cookie on a subdomain of the provided hostname\n * until the browser accepts it\n *\n * inspired by https://github.com/AngusFu/browser-root-domain\n */\nexport function seekFirstNonPublicSubDomain(hostname: string, cookieJar = document): string {\n if (['localhost', '127.0.0.1'].includes(hostname)) return ''\n\n const list = hostname.split('.')\n let len = list.length\n const key = 'dmn_chk_' + uuidv7()\n const R = new RegExp('(^|;)\\\\s*' + key + '=1')\n\n while (len--) {\n const candidate = list.slice(len).join('.')\n const candidateCookieValue = key + '=1;domain=.' + candidate\n\n // try to set cookie\n cookieJar.cookie = candidateCookieValue\n\n if (R.test(cookieJar.cookie)) {\n // the cookie was accepted by the browser, remove the test cookie\n cookieJar.cookie = candidateCookieValue + ';expires=' + Y1970\n return candidate\n }\n }\n return ''\n}\n\nconst DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\\.[a-z]{2,}$/i\nconst originalCookieDomainFn = (hostname: string): string => {\n const matches = hostname.match(DOMAIN_MATCH_REGEX)\n return matches ? matches[0] : ''\n}\n\nexport function chooseCookieDomain(hostname: string, cross_subdomain: boolean | undefined): string {\n if (cross_subdomain) {\n // NOTE: Could we use this for cross domain tracking?\n let matchedSubDomain = seekFirstNonPublicSubDomain(hostname)\n\n if (!matchedSubDomain) {\n const originalMatch = originalCookieDomainFn(hostname)\n if (originalMatch !== matchedSubDomain) {\n logger.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain)\n }\n matchedSubDomain = originalMatch\n }\n\n return matchedSubDomain ? '; domain=.' + matchedSubDomain : ''\n }\n return ''\n}\n\n// Methods partially borrowed from quirksmode.org/js/cookies.html\nexport const cookieStore: PersistentStore = {\n is_supported: () => true,\n\n error: function (msg) {\n logger.error('cookieStore error: ' + msg)\n },\n\n get: function (name) {\n try {\n const nameEQ = name + '='\n const ca = document.cookie.split(';').filter((x) => x.length)\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i]\n while (c.charAt(0) == ' ') {\n c = c.substring(1, c.length)\n }\n if (c.indexOf(nameEQ) === 0) {\n return decodeURIComponent(c.substring(nameEQ.length, c.length))\n }\n }\n } catch (err) {}\n return null\n },\n\n parse: function (name) {\n let cookie\n try {\n cookie = JSON.parse(cookieStore.get(name)) || {}\n } catch (err) {\n // noop\n }\n return cookie\n },\n\n set: function (name, value, days, cross_subdomain, is_secure) {\n try {\n let expires = '',\n secure = ''\n\n const cdomain = chooseCookieDomain(document.location.hostname, cross_subdomain)\n\n if (days) {\n const date = new Date()\n date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)\n expires = '; expires=' + date.toUTCString()\n }\n\n if (is_secure) {\n secure = '; secure'\n }\n\n const new_cookie_val =\n name +\n '=' +\n encodeURIComponent(JSON.stringify(value)) +\n expires +\n '; SameSite=Lax; path=/' +\n cdomain +\n secure\n document.cookie = new_cookie_val\n return new_cookie_val\n } catch (err) {\n return\n }\n },\n\n remove: function (name, cross_subdomain) {\n try {\n cookieStore.set(name, '', -1, cross_subdomain)\n } catch (err) {\n return\n }\n },\n}\n\nlet _localStorage_supported: boolean | null = null\n\nexport const localStore: PersistentStore = {\n is_supported: function () {\n if (!_isNull(_localStorage_supported)) {\n return _localStorage_supported\n }\n\n let supported = true\n if (!_isUndefined(window)) {\n try {\n const key = '__mplssupport__',\n val = 'xyz'\n localStore.set(key, val)\n if (localStore.get(key) !== '\"xyz\"') {\n supported = false\n }\n localStore.remove(key)\n } catch (err) {\n supported = false\n }\n } else {\n supported = false\n }\n if (!supported) {\n logger.error('localStorage unsupported; falling back to cookie store')\n }\n\n _localStorage_supported = supported\n return supported\n },\n\n error: function (msg) {\n logger.error('localStorage error: ' + msg)\n },\n\n get: function (name) {\n try {\n return window.localStorage.getItem(name)\n } catch (err) {\n localStore.error(err)\n }\n return null\n },\n\n parse: function (name) {\n try {\n return JSON.parse(localStore.get(name)) || {}\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value) {\n try {\n window.localStorage.setItem(name, JSON.stringify(value))\n } catch (err) {\n localStore.error(err)\n }\n },\n\n remove: function (name) {\n try {\n window.localStorage.removeItem(name)\n } catch (err) {\n localStore.error(err)\n }\n },\n}\n\n// Use localstorage for most data but still use cookie for COOKIE_PERSISTED_PROPERTIES\n// This solves issues with cookies having too much data in them causing headers too large\n// Also makes sure we don't have to send a ton of data to the server\nconst COOKIE_PERSISTED_PROPERTIES = [DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED]\n\nexport const localPlusCookieStore: PersistentStore = {\n ...localStore,\n parse: function (name) {\n try {\n let extend: Properties = {}\n try {\n // See if there's a cookie stored with data.\n extend = cookieStore.parse(name) || {}\n } catch (err) {}\n const value = _extend(extend, JSON.parse(localStore.get(name) || '{}'))\n localStore.set(name, value)\n return value\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value, days, cross_subdomain, is_secure) {\n try {\n localStore.set(name, value)\n const cookiePersistedProperties: Record<string, any> = {}\n COOKIE_PERSISTED_PROPERTIES.forEach((key) => {\n if (value[key]) {\n cookiePersistedProperties[key] = value[key]\n }\n })\n\n if (Object.keys(cookiePersistedProperties).length) {\n cookieStore.set(name, cookiePersistedProperties, days, cross_subdomain, is_secure)\n }\n } catch (err) {\n localStore.error(err)\n }\n },\n\n remove: function (name, cross_subdomain) {\n try {\n window.localStorage.removeItem(name)\n cookieStore.remove(name, cross_subdomain)\n } catch (err) {\n localStore.error(err)\n }\n },\n}\n\nconst memoryStorage: Properties = {}\n\n// Storage that only lasts the length of the pageview if we don't want to use cookies\nexport const memoryStore: PersistentStore = {\n is_supported: function () {\n return true\n },\n\n error: function (msg) {\n logger.error('memoryStorage error: ' + msg)\n },\n\n get: function (name) {\n return memoryStorage[name] || null\n },\n\n parse: function (name) {\n return memoryStorage[name] || null\n },\n\n set: function (name, value) {\n memoryStorage[name] = value\n },\n\n remove: function (name) {\n delete memoryStorage[name]\n },\n}\n\nlet sessionStorageSupported: boolean | null = null\nexport const resetSessionStorageSupported = () => {\n sessionStorageSupported = null\n}\n// Storage that only lasts the length of a tab/window. Survives page refreshes\nexport const sessionStore: PersistentStore = {\n is_supported: function () {\n if (!_isNull(sessionStorageSupported)) {\n return sessionStorageSupported\n }\n sessionStorageSupported = true\n if (!_isUndefined(window)) {\n try {\n const key = '__support__',\n val = 'xyz'\n sessionStore.set(key, val)\n if (sessionStore.get(key) !== '\"xyz\"') {\n sessionStorageSupported = false\n }\n sessionStore.remove(key)\n } catch (err) {\n sessionStorageSupported = false\n }\n } else {\n sessionStorageSupported = false\n }\n return sessionStorageSupported\n },\n\n error: function (msg) {\n logger.error('sessionStorage error: ', msg)\n },\n\n get: function (name) {\n try {\n return window.sessionStorage.getItem(name)\n } catch (err) {\n sessionStore.error(err)\n }\n return null\n },\n\n parse: function (name) {\n try {\n return JSON.parse(sessionStore.get(name)) || null\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value) {\n try {\n window.sessionStorage.setItem(name, JSON.stringify(value))\n } catch (err) {\n sessionStore.error(err)\n }\n },\n\n remove: function (name) {\n try {\n window.sessionStorage.removeItem(name)\n } catch (err) {\n sessionStore.error(err)\n }\n },\n}\n"]}
|
|
1
|
+
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/storage.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAEjC,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,4BAA4B,EAAE,MAAM,aAAa,CAAA;AAEnF,OAAO,EAAE,OA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,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAA;SACpD;QAAC,OAAO,GAAG,EAAE;YACV,OAAO;SACV;QACD,OAAO,IAAI,CAAA;IACf,CAAC;IAED,GAAG,EAAE,UAAU,IAAI,EAAE,KAAK;QACtB,IAAI;YACA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,cAAc,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAA;SAC9D;QAAC,OAAO,GAAG,EAAE;YACV,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;IACL,CAAC;IAED,MAAM,EAAE,UAAU,IAAI;QAClB,IAAI;YACA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,cAAc,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;SAC1C;QAAC,OAAO,GAAG,EAAE;YACV,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;IACL,CAAC;CACJ,CAAA","sourcesContent":["import { _extend } from './utils'\nimport { PersistentStore, Properties } from './types'\nimport { DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED } from './constants'\n\nimport { _isNull, _isUndefined } from './utils/type-utils'\nimport { logger } from './utils/logger'\nimport { window, document } from './utils/globals'\nimport { uuidv7 } from './uuidv7'\n\nconst Y1970 = 'Thu, 01 Jan 1970 00:00:00 GMT'\n\n/**\n * Browsers don't offer a way to check if something is a public suffix\n * e.g. `.com.au`, `.io`, `.org.uk`\n *\n * But they do reject cookies set on public suffixes\n * Setting a cookie on `.co.uk` would mean it was sent for every `.co.uk` site visited\n *\n * So, we can use this to check if a domain is a public suffix\n * by trying to set a cookie on a subdomain of the provided hostname\n * until the browser accepts it\n *\n * inspired by https://github.com/AngusFu/browser-root-domain\n */\nexport function seekFirstNonPublicSubDomain(hostname: string, cookieJar = document): string {\n if (!cookieJar) {\n return ''\n }\n if (['localhost', '127.0.0.1'].includes(hostname)) return ''\n\n const list = hostname.split('.')\n let len = list.length\n const key = 'dmn_chk_' + uuidv7()\n const R = new RegExp('(^|;)\\\\s*' + key + '=1')\n\n while (len--) {\n const candidate = list.slice(len).join('.')\n const candidateCookieValue = key + '=1;domain=.' + candidate\n\n // try to set cookie\n cookieJar.cookie = candidateCookieValue\n\n if (R.test(cookieJar.cookie)) {\n // the cookie was accepted by the browser, remove the test cookie\n cookieJar.cookie = candidateCookieValue + ';expires=' + Y1970\n return candidate\n }\n }\n return ''\n}\n\nconst DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\\.[a-z]{2,}$/i\nconst originalCookieDomainFn = (hostname: string): string => {\n const matches = hostname.match(DOMAIN_MATCH_REGEX)\n return matches ? matches[0] : ''\n}\n\nexport function chooseCookieDomain(hostname: string, cross_subdomain: boolean | undefined): string {\n if (cross_subdomain) {\n // NOTE: Could we use this for cross domain tracking?\n let matchedSubDomain = seekFirstNonPublicSubDomain(hostname)\n\n if (!matchedSubDomain) {\n const originalMatch = originalCookieDomainFn(hostname)\n if (originalMatch !== matchedSubDomain) {\n logger.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain)\n }\n matchedSubDomain = originalMatch\n }\n\n return matchedSubDomain ? '; domain=.' + matchedSubDomain : ''\n }\n return ''\n}\n\n// Methods partially borrowed from quirksmode.org/js/cookies.html\nexport const cookieStore: PersistentStore = {\n is_supported: () => !!document,\n\n error: function (msg) {\n logger.error('cookieStore error: ' + msg)\n },\n\n get: function (name) {\n if (!document) {\n return\n }\n\n try {\n const nameEQ = name + '='\n const ca = document.cookie.split(';').filter((x) => x.length)\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i]\n while (c.charAt(0) == ' ') {\n c = c.substring(1, c.length)\n }\n if (c.indexOf(nameEQ) === 0) {\n return decodeURIComponent(c.substring(nameEQ.length, c.length))\n }\n }\n } catch (err) {}\n return null\n },\n\n parse: function (name) {\n let cookie\n try {\n cookie = JSON.parse(cookieStore.get(name)) || {}\n } catch (err) {\n // noop\n }\n return cookie\n },\n\n set: function (name, value, days, cross_subdomain, is_secure) {\n if (!document) {\n return\n }\n try {\n let expires = '',\n secure = ''\n\n const cdomain = chooseCookieDomain(document.location.hostname, cross_subdomain)\n\n if (days) {\n const date = new Date()\n date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)\n expires = '; expires=' + date.toUTCString()\n }\n\n if (is_secure) {\n secure = '; secure'\n }\n\n const new_cookie_val =\n name +\n '=' +\n encodeURIComponent(JSON.stringify(value)) +\n expires +\n '; SameSite=Lax; path=/' +\n cdomain +\n secure\n document.cookie = new_cookie_val\n return new_cookie_val\n } catch (err) {\n return\n }\n },\n\n remove: function (name, cross_subdomain) {\n try {\n cookieStore.set(name, '', -1, cross_subdomain)\n } catch (err) {\n return\n }\n },\n}\n\nlet _localStorage_supported: boolean | null = null\n\nexport const localStore: PersistentStore = {\n is_supported: function () {\n if (!_isNull(_localStorage_supported)) {\n return _localStorage_supported\n }\n\n let supported = true\n if (!_isUndefined(window)) {\n try {\n const key = '__mplssupport__',\n val = 'xyz'\n localStore.set(key, val)\n if (localStore.get(key) !== '\"xyz\"') {\n supported = false\n }\n localStore.remove(key)\n } catch (err) {\n supported = false\n }\n } else {\n supported = false\n }\n if (!supported) {\n logger.error('localStorage unsupported; falling back to cookie store')\n }\n\n _localStorage_supported = supported\n return supported\n },\n\n error: function (msg) {\n logger.error('localStorage error: ' + msg)\n },\n\n get: function (name) {\n try {\n return window?.localStorage.getItem(name)\n } catch (err) {\n localStore.error(err)\n }\n return null\n },\n\n parse: function (name) {\n try {\n return JSON.parse(localStore.get(name)) || {}\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value) {\n try {\n window?.localStorage.setItem(name, JSON.stringify(value))\n } catch (err) {\n localStore.error(err)\n }\n },\n\n remove: function (name) {\n try {\n window?.localStorage.removeItem(name)\n } catch (err) {\n localStore.error(err)\n }\n },\n}\n\n// Use localstorage for most data but still use cookie for COOKIE_PERSISTED_PROPERTIES\n// This solves issues with cookies having too much data in them causing headers too large\n// Also makes sure we don't have to send a ton of data to the server\nconst COOKIE_PERSISTED_PROPERTIES = [DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED]\n\nexport const localPlusCookieStore: PersistentStore = {\n ...localStore,\n parse: function (name) {\n try {\n let extend: Properties = {}\n try {\n // See if there's a cookie stored with data.\n extend = cookieStore.parse(name) || {}\n } catch (err) {}\n const value = _extend(extend, JSON.parse(localStore.get(name) || '{}'))\n localStore.set(name, value)\n return value\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value, days, cross_subdomain, is_secure) {\n try {\n localStore.set(name, value)\n const cookiePersistedProperties: Record<string, any> = {}\n COOKIE_PERSISTED_PROPERTIES.forEach((key) => {\n if (value[key]) {\n cookiePersistedProperties[key] = value[key]\n }\n })\n\n if (Object.keys(cookiePersistedProperties).length) {\n cookieStore.set(name, cookiePersistedProperties, days, cross_subdomain, is_secure)\n }\n } catch (err) {\n localStore.error(err)\n }\n },\n\n remove: function (name, cross_subdomain) {\n try {\n window?.localStorage.removeItem(name)\n cookieStore.remove(name, cross_subdomain)\n } catch (err) {\n localStore.error(err)\n }\n },\n}\n\nconst memoryStorage: Properties = {}\n\n// Storage that only lasts the length of the pageview if we don't want to use cookies\nexport const memoryStore: PersistentStore = {\n is_supported: function () {\n return true\n },\n\n error: function (msg) {\n logger.error('memoryStorage error: ' + msg)\n },\n\n get: function (name) {\n return memoryStorage[name] || null\n },\n\n parse: function (name) {\n return memoryStorage[name] || null\n },\n\n set: function (name, value) {\n memoryStorage[name] = value\n },\n\n remove: function (name) {\n delete memoryStorage[name]\n },\n}\n\nlet sessionStorageSupported: boolean | null = null\nexport const resetSessionStorageSupported = () => {\n sessionStorageSupported = null\n}\n// Storage that only lasts the length of a tab/window. Survives page refreshes\nexport const sessionStore: PersistentStore = {\n is_supported: function () {\n if (!_isNull(sessionStorageSupported)) {\n return sessionStorageSupported\n }\n sessionStorageSupported = true\n if (!_isUndefined(window)) {\n try {\n const key = '__support__',\n val = 'xyz'\n sessionStore.set(key, val)\n if (sessionStore.get(key) !== '\"xyz\"') {\n sessionStorageSupported = false\n }\n sessionStore.remove(key)\n } catch (err) {\n sessionStorageSupported = false\n }\n } else {\n sessionStorageSupported = false\n }\n return sessionStorageSupported\n },\n\n error: function (msg) {\n logger.error('sessionStorage error: ', msg)\n },\n\n get: function (name) {\n try {\n return window?.sessionStorage.getItem(name)\n } catch (err) {\n sessionStore.error(err)\n }\n return null\n },\n\n parse: function (name) {\n try {\n return JSON.parse(sessionStore.get(name)) || null\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value) {\n try {\n window?.sessionStorage.setItem(name, JSON.stringify(value))\n } catch (err) {\n sessionStore.error(err)\n }\n },\n\n remove: function (name) {\n try {\n window?.sessionStorage.removeItem(name)\n } catch (err) {\n sessionStore.error(err)\n }\n },\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import { _getQueryParam } from './request-utils';
|
|
|
2
2
|
import { _isNull, _isUndefined } from './type-utils';
|
|
3
3
|
import Config from '../config';
|
|
4
4
|
import { _each, _extend, _includes, _strip_empty_properties, _timestamp } from './index';
|
|
5
|
-
import { document, userAgent } from './globals';
|
|
5
|
+
import { document, window, userAgent, assignableWindow } from './globals';
|
|
6
6
|
/**
|
|
7
7
|
* Safari detection turns out to be complicted. For e.g. https://stackoverflow.com/a/29696509
|
|
8
8
|
* We can be slightly loose because some options have been ruled out (e.g. firefox on iOS)
|
|
@@ -25,7 +25,7 @@ export var _info = {
|
|
|
25
25
|
].concat(customParams || []);
|
|
26
26
|
var params = {};
|
|
27
27
|
_each(campaign_keywords, function (kwkey) {
|
|
28
|
-
var kw = _getQueryParam(document.URL, kwkey);
|
|
28
|
+
var kw = document ? _getQueryParam(document.URL, kwkey) : '';
|
|
29
29
|
if (kw.length) {
|
|
30
30
|
params[kwkey] = kw;
|
|
31
31
|
}
|
|
@@ -33,7 +33,7 @@ export var _info = {
|
|
|
33
33
|
return params;
|
|
34
34
|
},
|
|
35
35
|
searchEngine: function () {
|
|
36
|
-
var referrer = document.referrer;
|
|
36
|
+
var referrer = document === null || document === void 0 ? void 0 : document.referrer;
|
|
37
37
|
if (!referrer) {
|
|
38
38
|
return null;
|
|
39
39
|
}
|
|
@@ -57,7 +57,7 @@ export var _info = {
|
|
|
57
57
|
var search = _info.searchEngine(), param = search != 'yahoo' ? 'q' : 'p', ret = {};
|
|
58
58
|
if (!_isNull(search)) {
|
|
59
59
|
ret['$search_engine'] = search;
|
|
60
|
-
var keyword = _getQueryParam(document.referrer, param);
|
|
60
|
+
var keyword = document ? _getQueryParam(document.referrer, param) : '';
|
|
61
61
|
if (keyword.length) {
|
|
62
62
|
ret['ph_keyword'] = keyword;
|
|
63
63
|
}
|
|
@@ -265,10 +265,10 @@ export var _info = {
|
|
|
265
265
|
}
|
|
266
266
|
},
|
|
267
267
|
referrer: function () {
|
|
268
|
-
return document.referrer || '$direct';
|
|
268
|
+
return (document === null || document === void 0 ? void 0 : document.referrer) || '$direct';
|
|
269
269
|
},
|
|
270
270
|
referringDomain: function () {
|
|
271
|
-
if (!document.referrer) {
|
|
271
|
+
if (!(document === null || document === void 0 ? void 0 : document.referrer)) {
|
|
272
272
|
return '$direct';
|
|
273
273
|
}
|
|
274
274
|
var parser = document.createElement('a'); // Unfortunately we cannot use new URL due to IE11
|
|
@@ -276,11 +276,14 @@ export var _info = {
|
|
|
276
276
|
return parser.host;
|
|
277
277
|
},
|
|
278
278
|
properties: function () {
|
|
279
|
+
if (!userAgent) {
|
|
280
|
+
return {};
|
|
281
|
+
}
|
|
279
282
|
var _a = _info.os(userAgent), os_name = _a.os_name, os_version = _a.os_version;
|
|
280
283
|
return _extend(_strip_empty_properties({
|
|
281
284
|
$os: os_name,
|
|
282
285
|
$os_version: os_version,
|
|
283
|
-
$browser: _info.browser(userAgent, navigator.vendor,
|
|
286
|
+
$browser: _info.browser(userAgent, navigator.vendor, assignableWindow.opera),
|
|
284
287
|
$device: _info.device(userAgent),
|
|
285
288
|
$device_type: _info.deviceType(userAgent),
|
|
286
289
|
}), {
|
|
@@ -288,7 +291,7 @@ export var _info = {
|
|
|
288
291
|
$host: window === null || window === void 0 ? void 0 : window.location.host,
|
|
289
292
|
$pathname: window === null || window === void 0 ? void 0 : window.location.pathname,
|
|
290
293
|
$raw_user_agent: userAgent.length > 1000 ? userAgent.substring(0, 997) + '...' : userAgent,
|
|
291
|
-
$browser_version: _info.browserVersion(userAgent, navigator.vendor,
|
|
294
|
+
$browser_version: _info.browserVersion(userAgent, navigator.vendor, assignableWindow.opera),
|
|
292
295
|
$browser_language: _info.browserLanguage(),
|
|
293
296
|
$screen_height: window === null || window === void 0 ? void 0 : window.screen.height,
|
|
294
297
|
$screen_width: window === null || window === void 0 ? void 0 : window.screen.width,
|
|
@@ -301,13 +304,16 @@ export var _info = {
|
|
|
301
304
|
});
|
|
302
305
|
},
|
|
303
306
|
people_properties: function () {
|
|
307
|
+
if (!userAgent) {
|
|
308
|
+
return {};
|
|
309
|
+
}
|
|
304
310
|
var _a = _info.os(userAgent), os_name = _a.os_name, os_version = _a.os_version;
|
|
305
311
|
return _extend(_strip_empty_properties({
|
|
306
312
|
$os: os_name,
|
|
307
313
|
$os_version: os_version,
|
|
308
|
-
$browser: _info.browser(userAgent, navigator.vendor,
|
|
314
|
+
$browser: _info.browser(userAgent, navigator.vendor, assignableWindow.opera),
|
|
309
315
|
}), {
|
|
310
|
-
$browser_version: _info.browserVersion(userAgent, navigator.vendor,
|
|
316
|
+
$browser_version: _info.browserVersion(userAgent, navigator.vendor, assignableWindow.opera),
|
|
311
317
|
});
|
|
312
318
|
},
|
|
313
319
|
};
|