@rudderstack/analytics-js 3.23.2 → 3.24.0-beta.pr.2494.29b4d0c
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/CHANGELOG.md +18 -0
- package/dist/npm/index.d.cts +48 -8
- package/dist/npm/index.d.mts +48 -8
- package/dist/npm/legacy/bundled/cjs/index.cjs +84 -35
- package/dist/npm/legacy/bundled/esm/index.mjs +84 -35
- package/dist/npm/legacy/bundled/umd/index.js +84 -35
- package/dist/npm/legacy/cjs/index.cjs +84 -35
- package/dist/npm/legacy/content-script/cjs/index.cjs +84 -35
- package/dist/npm/legacy/content-script/esm/index.mjs +84 -35
- package/dist/npm/legacy/content-script/umd/index.js +84 -35
- package/dist/npm/legacy/esm/index.mjs +84 -35
- package/dist/npm/legacy/umd/index.js +84 -35
- package/dist/npm/modern/bundled/cjs/index.cjs +61 -25
- package/dist/npm/modern/bundled/esm/index.mjs +61 -25
- package/dist/npm/modern/bundled/umd/index.js +61 -25
- package/dist/npm/modern/cjs/index.cjs +64 -25
- package/dist/npm/modern/content-script/cjs/index.cjs +61 -25
- package/dist/npm/modern/content-script/esm/index.mjs +61 -25
- package/dist/npm/modern/content-script/umd/index.js +61 -25
- package/dist/npm/modern/esm/index.mjs +64 -25
- package/dist/npm/modern/umd/index.js +64 -25
- package/package.json +1 -1
@@ -342,7 +342,7 @@ mergeDeepRight(mergedArray[index],value):value;});return mergedArray;};/**
|
|
342
342
|
* @returns Returns the input value if it is a boolean, otherwise returns the default value
|
343
343
|
* @example
|
344
344
|
* getNormalizedBooleanValue(true, false) // returns true
|
345
|
-
*/const getNormalizedBooleanValue=(val,defVal)=>typeof val==='boolean'?val:defVal;
|
345
|
+
*/const getNormalizedBooleanValue=(val,defVal)=>typeof val==='boolean'?val:defVal;const deepFreeze=obj=>{Object.getOwnPropertyNames(obj).forEach(function(prop){if(obj[prop]&&typeof obj[prop]==='object'){deepFreeze(obj[prop]);}});return Object.freeze(obj);};
|
346
346
|
|
347
347
|
const trim=value=>value.replace(/^\s+|\s+$/gm,'');const removeLeadingPeriod=value=>value.replace(/^\.+/,'');/**
|
348
348
|
* A function to convert values to string
|
@@ -429,6 +429,11 @@ const hasCrypto$1=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalTh
|
|
429
429
|
|
430
430
|
const generateUUID=()=>{if(hasCrypto$1()){return v4$1();}return v4();};
|
431
431
|
|
432
|
+
/**
|
433
|
+
* Determines if the SDK is running inside a chrome extension
|
434
|
+
* @returns boolean
|
435
|
+
*/const isSDKRunningInChromeExtension=()=>!!window.chrome?.runtime?.id;const isIE11=()=>isString(globalThis.navigator.userAgent)&&/Trident.*rv:11\./.test(globalThis.navigator.userAgent);
|
436
|
+
|
432
437
|
const onPageLeave=callback=>{// To ensure the callback is only called once even if more than one events
|
433
438
|
// are fired at once.
|
434
439
|
let pageLeft=false;let isAccessible=false;function handleOnLeave(){if(pageLeft){return;}pageLeft=true;callback(isAccessible);// Reset pageLeft on the next tick
|
@@ -438,8 +443,12 @@ setTimeout(()=>{pageLeft=false;},0);}// Catches the unloading of the page (e.g.,
|
|
438
443
|
// Includes user actions like clicking a link, entering a new URL,
|
439
444
|
// refreshing the page, or closing the browser tab
|
440
445
|
// Note that 'pagehide' is not supported in IE.
|
441
|
-
//
|
442
|
-
|
446
|
+
// Registering this event conditionally for IE11 also because
|
447
|
+
// it affects bfcache optimization on modern browsers otherwise.
|
448
|
+
if(isIE11()){globalThis.addEventListener('beforeunload',()=>{isAccessible=false;handleOnLeave();});}// This is important for iOS Safari browser as it does not
|
449
|
+
// fire the regular pagehide and visibilitychange events
|
450
|
+
// when user goes to tablist view and closes the tab.
|
451
|
+
globalThis.addEventListener('blur',()=>{isAccessible=true;handleOnLeave();});globalThis.addEventListener('focus',()=>{pageLeft=false;});// Catches the page being hidden, including scenarios like closing the tab.
|
443
452
|
document.addEventListener('pagehide',()=>{isAccessible=document.visibilityState==='hidden';handleOnLeave();});// Catches visibility changes, such as switching tabs or minimizing the browser.
|
444
453
|
document.addEventListener('visibilitychange',()=>{isAccessible=true;if(document.visibilityState==='hidden'){handleOnLeave();}else {pageLeft=false;}});};
|
445
454
|
|
@@ -499,7 +508,7 @@ error.stack=`${stack}\n${MANUAL_ERROR_IDENTIFIER}`;break;case stacktrace:// esli
|
|
499
508
|
error.stacktrace=`${stacktrace}\n${MANUAL_ERROR_IDENTIFIER}`;break;case operaSourceloc:default:// eslint-disable-next-line no-param-reassign
|
500
509
|
error['opera#sourceloc']=`${operaSourceloc}\n${MANUAL_ERROR_IDENTIFIER}`;break;}}}globalThis.dispatchEvent(new ErrorEvent('error',{error,bubbles:true,cancelable:true,composed:true}));};
|
501
510
|
|
502
|
-
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.
|
511
|
+
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.24.0-beta.pr.2494.29b4d0c';const APP_NAMESPACE='com.rudderlabs.javascript';const MODULE_TYPE='npm';const ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';const ADBLOCK_PAGE_NAME='ad-block page request';const ADBLOCK_PAGE_PATH='/ad-blocked';const GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';const CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
503
512
|
|
504
513
|
const QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';const QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';const QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';const QUERY_PARAM_USER_ID_KEY='ajs_uid';const QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
|
505
514
|
|
@@ -637,9 +646,10 @@ const BUILD_TYPE='modern';const SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';co
|
|
637
646
|
|
638
647
|
const DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';const DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';const ConsentManagersToPluginNameMap={iubenda:'IubendaConsentManager',oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};const StorageEncryptionVersionsToPluginNameMap={[DEFAULT_STORAGE_ENCRYPTION_VERSION]:'StorageEncryption',legacy:'StorageEncryptionLegacy'};const DataPlaneEventsTransportToPluginNameMap={[DEFAULT_DATA_PLANE_EVENTS_TRANSPORT]:'XhrQueue',beacon:'BeaconQueue'};const DEFAULT_DATA_SERVICE_ENDPOINT='rsaRequest';const METRICS_SERVICE_ENDPOINT='rsaMetrics';const CUSTOM_DEVICE_MODE_DESTINATION_DISPLAY_NAME='Custom Device Mode';
|
639
648
|
|
640
|
-
const defaultLoadOptions={configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS,cutOff:{enabled:false}},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:
|
649
|
+
const defaultLoadOptions={configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS,cutOff:{enabled:false}},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,lockPluginsVersion:false,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true,cookie:{}},sendAdblockPage:false,sameDomainCookiesOnly:false,secureCookie:false,sendAdblockPageOptions:{},useServerSideCookies:false};const loadOptionsState=d$1(clone(defaultLoadOptions));
|
641
650
|
|
642
|
-
const DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};const
|
651
|
+
const DEFAULT_USER_SESSION_VALUES=deepFreeze({userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null});const DEFAULT_RESET_OPTIONS=deepFreeze({entries:{userId:true,userTraits:true,groupId:true,groupTraits:true,sessionInfo:true,authToken:true,// These are not reset by default
|
652
|
+
anonymousId:false,initialReferrer:false,initialReferringDomain:false}});const SERVER_SIDE_COOKIES_DEBOUNCE_TIME=10;// milliseconds
|
643
653
|
|
644
654
|
const sessionState={userId:d$1(DEFAULT_USER_SESSION_VALUES.userId),userTraits:d$1(DEFAULT_USER_SESSION_VALUES.userTraits),anonymousId:d$1(DEFAULT_USER_SESSION_VALUES.anonymousId),groupId:d$1(DEFAULT_USER_SESSION_VALUES.groupId),groupTraits:d$1(DEFAULT_USER_SESSION_VALUES.groupTraits),initialReferrer:d$1(DEFAULT_USER_SESSION_VALUES.initialReferrer),initialReferringDomain:d$1(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),sessionInfo:d$1(DEFAULT_USER_SESSION_VALUES.sessionInfo),authToken:d$1(DEFAULT_USER_SESSION_VALUES.authToken)};
|
645
655
|
|
@@ -773,8 +783,8 @@ throw err;}};
|
|
773
783
|
const getErrInstance=(err,errorType)=>{switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{const{error}=err;return error||err;}case ErrorType.UNHANDLEDREJECTION:{return err.reason;}case ErrorType.HANDLEDEXCEPTION:default:return err;}};const createNewBreadcrumb=message=>({type:'manual',name:message,timestamp:new Date(),metaData:{}});/**
|
774
784
|
* A function to get the Bugsnag release stage for the current environment
|
775
785
|
* @param getHostName Optional function to get the hostname (primarily for testing)
|
776
|
-
* @returns 'development' if the host is empty (for file:// protocol etc.) or a dev host (localhost, 127.0.0.1, etc.), otherwise ''
|
777
|
-
*/const getReleaseStage=(getHostName=()=>window.location.hostname)=>{const host=getHostName();return !host||host&&DEV_HOSTS.includes(host)?'development':'
|
786
|
+
* @returns 'development' if the host is empty (for file:// protocol etc.) or a dev host (localhost, 127.0.0.1, etc.), otherwise ''beta'' (it'll be replaced with the actual release stage during the build)
|
787
|
+
*/const getReleaseStage=(getHostName=()=>window.location.hostname)=>{const host=getHostName();return !host||host&&DEV_HOSTS.includes(host)?'development':'beta';};const getAppStateForMetadata=state=>{const stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};const getURLWithoutQueryString=()=>{const url=globalThis.location.href.split('?');return url[0];};const getUserDetails=(source,session,lifecycle,autoTrack)=>({id:`${source.value?.id??lifecycle.writeKey.value}..${session.sessionInfo.value.id??'NA'}..${autoTrack.pageLifecycle.pageViewId.value??'NA'}`,name:source.value?.name??'NA'});const getDeviceDetails=(locale,userAgent)=>({locale:locale.value??'NA',userAgent:userAgent.value??'NA',time:new Date()});const getBugsnagErrorEvent=(exception,errorState,state,groupingHash)=>{const{context,lifecycle,session,source,reporting,autoTrack}=state;const{app,locale,userAgent,timezone,screen,library}=context;return {payloadVersion:'5',notifier:{name:NOTIFIER_NAME,version:app.value.version,url:SDK_GITHUB_URL},events:[{exceptions:[clone(exception)],severity:errorState.severity,unhandled:errorState.unhandled,severityReason:errorState.severityReason,app:{version:app.value.version,releaseStage:getReleaseStage(),type:app.value.installType},device:getDeviceDetails(locale,userAgent),request:{url:getURLWithoutQueryString(),clientIp:'[NOT COLLECTED]'},breadcrumbs:clone(reporting.breadcrumbs.value),context:exception.message,groupingHash,metaData:{app:{snippetVersion:library.value.snippetVersion},device:{...screen.value,timezone:timezone.value},// Add rest of the state groups as metadata
|
778
788
|
// so that they show up as separate tabs in the dashboard
|
779
789
|
...getAppStateForMetadata(state)},user:getUserDetails(source,session,lifecycle,autoTrack)}]};};/**
|
780
790
|
* A function to check if adblockers are active. The promise's resolve function
|
@@ -2671,7 +2681,8 @@ const pluginName='XhrQueue';const XhrQueue=()=>({name:pluginName,deps:[],initial
|
|
2671
2681
|
`${QUEUE_NAME}_${writeKey}`,finalQOpts,(itemData,done,qItemProcessInfo)=>{const{data,url,headers}=getRequestInfo(itemData,state,qItemProcessInfo,logger);httpClient.getAsyncData({url,options:{method:'POST',headers,data:data,sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS,callback:(result,details)=>{// If there is no error, we can consider the item as delivered
|
2672
2682
|
if(isUndefined(details?.error)){// null means item will not be processed further and will be removed from the queue (even from the storage)
|
2673
2683
|
done(null);return;}const isRetryable=isErrRetryable(details?.xhr?.status??0);logMessageOnFailure(details,isRetryable,qItemProcessInfo,logger);if(isRetryable){let retryReason=DEFAULT_RETRY_REASON;if(details?.timedOut){retryReason=RETRY_REASON_CLIENT_TIMEOUT;}else if(isDefined(details?.xhr?.status)){retryReason=`server-${details.xhr.status}`;}done(details,{retryReason});}else {// null means item will not be processed further and will be removed from the queue (even from the storage)
|
2674
|
-
done(null);}}});},storeManager
|
2684
|
+
done(null);}}});},storeManager,// If local storage is available, use it, else use memory storage
|
2685
|
+
state.capabilities.storage.isLocalStorageAvailable.value?LOCAL_STORAGE:MEMORY_STORAGE,logger,itemData=>{const currentTime=getCurrentTimeFormatted();const events=itemData.map(queueItemData=>queueItemData.event);// type casting to string as we know that the event has already been validated prior to enqueue
|
2675
2686
|
return getBatchDeliveryPayload(events,currentTime,logger)?.length;});return eventsQueue;},/**
|
2676
2687
|
* Add event to the queue for delivery
|
2677
2688
|
* @param state Application state
|
@@ -2757,10 +2768,13 @@ for(let i=parts.length-2;i>=0;i-=1){levels.push(parts.slice(i).join('.'));}retur
|
|
2757
2768
|
* The method returns an empty string when the hostname is an ip.
|
2758
2769
|
*/const domain=url=>{const levels=levelsFunc(url);// Lookup the real top level one.
|
2759
2770
|
// eslint-disable-next-line unicorn/no-for-loop
|
2760
|
-
for(let i=0;i<levels.length;i+=1){const domain=levels[i];const cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;const opts={domain:`${domain.indexOf('localhost')!==-1?'':'.'}${domain}`}
|
2771
|
+
for(let i=0;i<levels.length;i+=1){const domain=levels[i];const cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;const opts={domain:`${domain.indexOf('localhost')!==-1?'':'.'}${domain}`};try{// Set cookie on domain
|
2761
2772
|
cookie(cname,1,opts);// If successful
|
2762
2773
|
if(cookie(cname)){// Remove cookie from domain
|
2763
|
-
cookie(cname,null,opts);return domain;}}
|
2774
|
+
cookie(cname,null,opts);return domain;}}catch{// Silently continue to next domain level if cookie access is restricted or setting fails
|
2775
|
+
// Best-effort cleanup to avoid leaking the test cookie
|
2776
|
+
try{cookie(cname,null,opts);}catch{// Ignore if we are unable to delete the cookie
|
2777
|
+
}}}return '';};
|
2764
2778
|
|
2765
2779
|
const getDefaultCookieOptions=()=>{const topDomain=`.${domain(globalThis.location.href)}`;return {maxage:DEFAULT_COOKIE_MAX_AGE_MS,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:'Lax',enabled:true};};const getDefaultLocalStorageOptions=()=>({enabled:true});const getDefaultSessionStorageOptions=()=>({enabled:true});const getDefaultInMemoryStorageOptions=()=>({enabled:true});
|
2766
2780
|
|
@@ -2781,7 +2795,7 @@ var storeExports = requireStore();
|
|
2781
2795
|
const store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
|
2782
2796
|
|
2783
2797
|
const hasCrypto=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);// eslint-disable-next-line compat/compat -- We are checking for the existence of navigator.userAgentData
|
2784
|
-
const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);
|
2798
|
+
const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);
|
2785
2799
|
|
2786
2800
|
const getUserAgentClientHint=(callback,level='none')=>{if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){navigator.userAgentData?.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(ua=>{callback(ua);}).catch(()=>{callback();});}};
|
2787
2801
|
|
@@ -2925,11 +2939,6 @@ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(err
|
|
2925
2939
|
*/const getUrlWithoutHash=url=>{let urlWithoutHash=url;try{const urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
|
2926
2940
|
}return urlWithoutHash;};
|
2927
2941
|
|
2928
|
-
/**
|
2929
|
-
* Determines if the SDK is running inside a chrome extension
|
2930
|
-
* @returns boolean
|
2931
|
-
*/const isSDKRunningInChromeExtension=()=>!!window.chrome?.runtime?.id;
|
2932
|
-
|
2933
2942
|
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
|
2934
2943
|
|
2935
2944
|
const isErrorReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.errors?.enabled===true;const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
@@ -3153,7 +3162,9 @@ timeout,autoTrack:true,...(cutOff&&{cutOff})};};/**
|
|
3153
3162
|
*/const generateManualTrackingSession=(id,logger)=>{const sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};const isStorageTypeValidForStoringData=storageType=>Boolean(storageType===COOKIE_STORAGE||storageType===LOCAL_STORAGE||storageType===SESSION_STORAGE||storageType===MEMORY_STORAGE);/**
|
3154
3163
|
* Generate a new anonymousId
|
3155
3164
|
* @returns string anonymousID
|
3156
|
-
*/const generateAnonymousId=()=>generateUUID();
|
3165
|
+
*/const generateAnonymousId=()=>generateUUID();const getFinalResetOptions=options=>{// Legacy behavior: toggle only anonymousId without mutating defaults
|
3166
|
+
if(isBoolean(options)){const{entries,...rest}=DEFAULT_RESET_OPTIONS;return {...rest,entries:{...entries,anonymousId:options}};}// Override any defaults with the user provided options
|
3167
|
+
if(isObjectLiteralAndNotNull(options)&&isObjectLiteralAndNotNull(options.entries)){return mergeDeepRight(DEFAULT_RESET_OPTIONS,options);}return {...DEFAULT_RESET_OPTIONS};};
|
3157
3168
|
|
3158
3169
|
/**
|
3159
3170
|
* To get the page properties for context object
|
@@ -3362,13 +3373,11 @@ this.migrateStorageIfNeeded([store],[sessionKey]);const storageKey=entries[sessi
|
|
3362
3373
|
if(sessionInfo.sessionStart===undefined){sessionInfo={...sessionInfo,sessionStart:true};}else if(sessionInfo.sessionStart){sessionInfo={...sessionInfo,sessionStart:false};}}// Always write to state (in-turn to storage) to keep the session info up to date.
|
3363
3374
|
state.session.sessionInfo.value=sessionInfo;if(state.lifecycle.status.value!=='readyExecuted'){// Force update the storage as the 'effect' blocks are not getting triggered
|
3364
3375
|
// when processing preload buffered requests
|
3365
|
-
this.syncValueToStorage('sessionInfo',sessionInfo);}}/**
|
3376
|
+
this.syncValueToStorage('sessionInfo',sessionInfo);}}resetAndStartNewSession(){const session=state.session;const{manualTrack,autoTrack,timeout,cutOff}=session.sessionInfo.value;if(autoTrack){const sessionInfo={...DEFAULT_USER_SESSION_VALUES.sessionInfo,timeout};if(cutOff){sessionInfo.cutOff={enabled:cutOff.enabled,duration:cutOff.duration};}session.sessionInfo.value=sessionInfo;this.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){this.startManualTrackingInternal();}}/**
|
3366
3377
|
* Reset state values
|
3367
|
-
* @param
|
3368
|
-
* @param noNewSessionStart
|
3378
|
+
* @param options options for reset
|
3369
3379
|
* @returns
|
3370
|
-
*/reset(
|
3371
|
-
this.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){const sessionInfo={...DEFAULT_USER_SESSION_VALUES.sessionInfo,timeout};if(cutOff){sessionInfo.cutOff={enabled:cutOff.enabled,duration:cutOff.duration};}session.sessionInfo.value=sessionInfo;this.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){this.startManualTrackingInternal();}});}/**
|
3380
|
+
*/reset(options){const{session}=state;const opts=getFinalResetOptions(options);r(()=>{Object.keys(DEFAULT_USER_SESSION_VALUES).forEach(key=>{const userSessionKey=key;if(opts.entries[userSessionKey]!==true){return;}switch(key){case 'anonymousId':this.setAnonymousId();break;case 'sessionInfo':this.resetAndStartNewSession();break;default:session[userSessionKey].value=DEFAULT_USER_SESSION_VALUES[userSessionKey];break;}});});}/**
|
3372
3381
|
* Set user Id
|
3373
3382
|
* @param userId
|
3374
3383
|
*/setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
|
@@ -3531,7 +3540,7 @@ if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_
|
|
3531
3540
|
// in v3 implementation
|
3532
3541
|
path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}track(payload,isBufferedInvocation=false){const type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event - ${payload.name}`);state.metrics.triggered.value+=1;this.eventManager?.addEvent({type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}identify(payload,isBufferedInvocation=false){const type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;const shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
|
3533
3542
|
if(!isNull(payload.userId)){this.userSessionManager?.setUserId(payload.userId);}this.userSessionManager?.setUserTraits(payload.traits);this.eventManager?.addEvent({type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}alias(payload,isBufferedInvocation=false){const type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;const previousId=payload.from??(this.getUserId()||this.userSessionManager?.getAnonymousId());this.eventManager?.addEvent({type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}group(payload,isBufferedInvocation=false){const type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
|
3534
|
-
if(!isNull(payload.groupId)){this.userSessionManager?.setGroupId(payload.groupId);}this.userSessionManager?.setGroupTraits(payload.traits);this.eventManager?.addEvent({type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}reset(
|
3543
|
+
if(!isNull(payload.groupId)){this.userSessionManager?.setGroupId(payload.groupId);}this.userSessionManager?.setGroupTraits(payload.traits);this.eventManager?.addEvent({type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}reset(options,isBufferedInvocation=false){const type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,options]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.userSessionManager?.reset(options);}getAnonymousId(options){return this.userSessionManager?.getAnonymousId(options);}setAnonymousId(anonymousId,rudderAmpLinkerParam,isBufferedInvocation=false){const type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
|
3535
3544
|
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,anonymousId,rudderAmpLinkerParam]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.userSessionManager?.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
|
3536
3545
|
getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
|
3537
3546
|
getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
@@ -3633,6 +3642,33 @@ identify(userId,traits,options,callback){try{this.getAnalyticsInstance()?.identi
|
|
3633
3642
|
alias(to,from,options,callback){try{this.getAnalyticsInstance()?.alias(aliasArgumentsToCallOptions(getSanitizedValue(to),getSanitizedValue(from),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
3634
3643
|
* Process group arguments and forward to page call
|
3635
3644
|
*/// These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
3636
|
-
group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}
|
3645
|
+
group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
3646
|
+
* Reset the analytics instance
|
3647
|
+
* @param options Reset options. Except for anonymousId, initialReferrer, and initialReferringDomain
|
3648
|
+
* all other values will be reset by default.
|
3649
|
+
* @example
|
3650
|
+
* ```ts
|
3651
|
+
* reset({
|
3652
|
+
* entries: {
|
3653
|
+
* anonymousId: true,
|
3654
|
+
* }
|
3655
|
+
* });
|
3656
|
+
* ```
|
3657
|
+
* @example
|
3658
|
+
* ```ts
|
3659
|
+
* reset({
|
3660
|
+
* entries: {
|
3661
|
+
* userId: false,
|
3662
|
+
* sessionInfo: false,
|
3663
|
+
* }
|
3664
|
+
* });
|
3665
|
+
* ```
|
3666
|
+
* @returns none
|
3667
|
+
*//**
|
3668
|
+
* Reset the analytics instance
|
3669
|
+
* @param resetAnonymousId Reset anonymous ID
|
3670
|
+
* @returns none
|
3671
|
+
* @deprecated Use reset(options) instead
|
3672
|
+
*/reset(options){try{this.getAnalyticsInstance()?.reset(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}getAnonymousId(options){try{return this.getAnalyticsInstance()?.getAnonymousId(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);return undefined;}}setAnonymousId(anonymousId,rudderAmpLinkerParam){try{this.getAnalyticsInstance()?.setAnonymousId(getSanitizedValue(anonymousId),getSanitizedValue(rudderAmpLinkerParam));}catch(error){dispatchErrorEvent(error);}}getUserId(){try{return this.getAnalyticsInstance()?.getUserId();}catch(error){dispatchErrorEvent(error);return undefined;}}getUserTraits(){try{return this.getAnalyticsInstance()?.getUserTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupId(){try{return this.getAnalyticsInstance()?.getGroupId();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupTraits(){try{return this.getAnalyticsInstance()?.getGroupTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}startSession(sessionId){try{this.getAnalyticsInstance()?.startSession(getSanitizedValue(sessionId));}catch(error){dispatchErrorEvent(error);}}endSession(){try{this.getAnalyticsInstance()?.endSession();}catch(error){dispatchErrorEvent(error);}}getSessionId(){try{return this.getAnalyticsInstance()?.getSessionId();}catch(error){dispatchErrorEvent(error);return undefined;}}setAuthToken(token){try{this.getAnalyticsInstance()?.setAuthToken(getSanitizedValue(token));}catch(error){dispatchErrorEvent(error);}}consent(options){try{this.getAnalyticsInstance()?.consent(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}addCustomIntegration(destinationId,integration){try{this.getAnalyticsInstance()?.addCustomIntegration(getSanitizedValue(destinationId),getSanitizedValue(integration));}catch(error){dispatchErrorEvent(error);}}}
|
3637
3673
|
|
3638
3674
|
export { RudderAnalytics };
|
@@ -348,7 +348,7 @@
|
|
348
348
|
* @returns Returns the input value if it is a boolean, otherwise returns the default value
|
349
349
|
* @example
|
350
350
|
* getNormalizedBooleanValue(true, false) // returns true
|
351
|
-
*/const getNormalizedBooleanValue=(val,defVal)=>typeof val==='boolean'?val:defVal;
|
351
|
+
*/const getNormalizedBooleanValue=(val,defVal)=>typeof val==='boolean'?val:defVal;const deepFreeze=obj=>{Object.getOwnPropertyNames(obj).forEach(function(prop){if(obj[prop]&&typeof obj[prop]==='object'){deepFreeze(obj[prop]);}});return Object.freeze(obj);};
|
352
352
|
|
353
353
|
const trim=value=>value.replace(/^\s+|\s+$/gm,'');const removeLeadingPeriod=value=>value.replace(/^\.+/,'');/**
|
354
354
|
* A function to convert values to string
|
@@ -435,6 +435,11 @@
|
|
435
435
|
|
436
436
|
const generateUUID=()=>{if(hasCrypto$1()){return v4$1();}return v4();};
|
437
437
|
|
438
|
+
/**
|
439
|
+
* Determines if the SDK is running inside a chrome extension
|
440
|
+
* @returns boolean
|
441
|
+
*/const isSDKRunningInChromeExtension=()=>!!window.chrome?.runtime?.id;const isIE11=()=>isString(globalThis.navigator.userAgent)&&/Trident.*rv:11\./.test(globalThis.navigator.userAgent);
|
442
|
+
|
438
443
|
const onPageLeave=callback=>{// To ensure the callback is only called once even if more than one events
|
439
444
|
// are fired at once.
|
440
445
|
let pageLeft=false;let isAccessible=false;function handleOnLeave(){if(pageLeft){return;}pageLeft=true;callback(isAccessible);// Reset pageLeft on the next tick
|
@@ -444,8 +449,12 @@
|
|
444
449
|
// Includes user actions like clicking a link, entering a new URL,
|
445
450
|
// refreshing the page, or closing the browser tab
|
446
451
|
// Note that 'pagehide' is not supported in IE.
|
447
|
-
//
|
448
|
-
|
452
|
+
// Registering this event conditionally for IE11 also because
|
453
|
+
// it affects bfcache optimization on modern browsers otherwise.
|
454
|
+
if(isIE11()){globalThis.addEventListener('beforeunload',()=>{isAccessible=false;handleOnLeave();});}// This is important for iOS Safari browser as it does not
|
455
|
+
// fire the regular pagehide and visibilitychange events
|
456
|
+
// when user goes to tablist view and closes the tab.
|
457
|
+
globalThis.addEventListener('blur',()=>{isAccessible=true;handleOnLeave();});globalThis.addEventListener('focus',()=>{pageLeft=false;});// Catches the page being hidden, including scenarios like closing the tab.
|
449
458
|
document.addEventListener('pagehide',()=>{isAccessible=document.visibilityState==='hidden';handleOnLeave();});// Catches visibility changes, such as switching tabs or minimizing the browser.
|
450
459
|
document.addEventListener('visibilitychange',()=>{isAccessible=true;if(document.visibilityState==='hidden'){handleOnLeave();}else {pageLeft=false;}});};
|
451
460
|
|
@@ -505,7 +514,7 @@
|
|
505
514
|
error.stacktrace=`${stacktrace}\n${MANUAL_ERROR_IDENTIFIER}`;break;case operaSourceloc:default:// eslint-disable-next-line no-param-reassign
|
506
515
|
error['opera#sourceloc']=`${operaSourceloc}\n${MANUAL_ERROR_IDENTIFIER}`;break;}}}globalThis.dispatchEvent(new ErrorEvent('error',{error,bubbles:true,cancelable:true,composed:true}));};
|
507
516
|
|
508
|
-
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.
|
517
|
+
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.24.0-beta.pr.2494.29b4d0c';const APP_NAMESPACE='com.rudderlabs.javascript';const MODULE_TYPE='npm';const ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';const ADBLOCK_PAGE_NAME='ad-block page request';const ADBLOCK_PAGE_PATH='/ad-blocked';const GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';const CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
509
518
|
|
510
519
|
const QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';const QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';const QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';const QUERY_PARAM_USER_ID_KEY='ajs_uid';const QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
|
511
520
|
|
@@ -643,9 +652,10 @@
|
|
643
652
|
|
644
653
|
const DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';const DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';const ConsentManagersToPluginNameMap={iubenda:'IubendaConsentManager',oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};const StorageEncryptionVersionsToPluginNameMap={[DEFAULT_STORAGE_ENCRYPTION_VERSION]:'StorageEncryption',legacy:'StorageEncryptionLegacy'};const DataPlaneEventsTransportToPluginNameMap={[DEFAULT_DATA_PLANE_EVENTS_TRANSPORT]:'XhrQueue',beacon:'BeaconQueue'};const DEFAULT_DATA_SERVICE_ENDPOINT='rsaRequest';const METRICS_SERVICE_ENDPOINT='rsaMetrics';const CUSTOM_DEVICE_MODE_DESTINATION_DISPLAY_NAME='Custom Device Mode';
|
645
654
|
|
646
|
-
const defaultLoadOptions={configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS,cutOff:{enabled:false}},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:
|
655
|
+
const defaultLoadOptions={configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS,cutOff:{enabled:false}},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,lockPluginsVersion:false,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true,cookie:{}},sendAdblockPage:false,sameDomainCookiesOnly:false,secureCookie:false,sendAdblockPageOptions:{},useServerSideCookies:false};const loadOptionsState=d$1(clone(defaultLoadOptions));
|
647
656
|
|
648
|
-
const DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};const
|
657
|
+
const DEFAULT_USER_SESSION_VALUES=deepFreeze({userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null});const DEFAULT_RESET_OPTIONS=deepFreeze({entries:{userId:true,userTraits:true,groupId:true,groupTraits:true,sessionInfo:true,authToken:true,// These are not reset by default
|
658
|
+
anonymousId:false,initialReferrer:false,initialReferringDomain:false}});const SERVER_SIDE_COOKIES_DEBOUNCE_TIME=10;// milliseconds
|
649
659
|
|
650
660
|
const sessionState={userId:d$1(DEFAULT_USER_SESSION_VALUES.userId),userTraits:d$1(DEFAULT_USER_SESSION_VALUES.userTraits),anonymousId:d$1(DEFAULT_USER_SESSION_VALUES.anonymousId),groupId:d$1(DEFAULT_USER_SESSION_VALUES.groupId),groupTraits:d$1(DEFAULT_USER_SESSION_VALUES.groupTraits),initialReferrer:d$1(DEFAULT_USER_SESSION_VALUES.initialReferrer),initialReferringDomain:d$1(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),sessionInfo:d$1(DEFAULT_USER_SESSION_VALUES.sessionInfo),authToken:d$1(DEFAULT_USER_SESSION_VALUES.authToken)};
|
651
661
|
|
@@ -779,8 +789,8 @@
|
|
779
789
|
const getErrInstance=(err,errorType)=>{switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{const{error}=err;return error||err;}case ErrorType.UNHANDLEDREJECTION:{return err.reason;}case ErrorType.HANDLEDEXCEPTION:default:return err;}};const createNewBreadcrumb=message=>({type:'manual',name:message,timestamp:new Date(),metaData:{}});/**
|
780
790
|
* A function to get the Bugsnag release stage for the current environment
|
781
791
|
* @param getHostName Optional function to get the hostname (primarily for testing)
|
782
|
-
* @returns 'development' if the host is empty (for file:// protocol etc.) or a dev host (localhost, 127.0.0.1, etc.), otherwise ''
|
783
|
-
*/const getReleaseStage=(getHostName=()=>window.location.hostname)=>{const host=getHostName();return !host||host&&DEV_HOSTS.includes(host)?'development':'
|
792
|
+
* @returns 'development' if the host is empty (for file:// protocol etc.) or a dev host (localhost, 127.0.0.1, etc.), otherwise ''beta'' (it'll be replaced with the actual release stage during the build)
|
793
|
+
*/const getReleaseStage=(getHostName=()=>window.location.hostname)=>{const host=getHostName();return !host||host&&DEV_HOSTS.includes(host)?'development':'beta';};const getAppStateForMetadata=state=>{const stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};const getURLWithoutQueryString=()=>{const url=globalThis.location.href.split('?');return url[0];};const getUserDetails=(source,session,lifecycle,autoTrack)=>({id:`${source.value?.id??lifecycle.writeKey.value}..${session.sessionInfo.value.id??'NA'}..${autoTrack.pageLifecycle.pageViewId.value??'NA'}`,name:source.value?.name??'NA'});const getDeviceDetails=(locale,userAgent)=>({locale:locale.value??'NA',userAgent:userAgent.value??'NA',time:new Date()});const getBugsnagErrorEvent=(exception,errorState,state,groupingHash)=>{const{context,lifecycle,session,source,reporting,autoTrack}=state;const{app,locale,userAgent,timezone,screen,library}=context;return {payloadVersion:'5',notifier:{name:NOTIFIER_NAME,version:app.value.version,url:SDK_GITHUB_URL},events:[{exceptions:[clone(exception)],severity:errorState.severity,unhandled:errorState.unhandled,severityReason:errorState.severityReason,app:{version:app.value.version,releaseStage:getReleaseStage(),type:app.value.installType},device:getDeviceDetails(locale,userAgent),request:{url:getURLWithoutQueryString(),clientIp:'[NOT COLLECTED]'},breadcrumbs:clone(reporting.breadcrumbs.value),context:exception.message,groupingHash,metaData:{app:{snippetVersion:library.value.snippetVersion},device:{...screen.value,timezone:timezone.value},// Add rest of the state groups as metadata
|
784
794
|
// so that they show up as separate tabs in the dashboard
|
785
795
|
...getAppStateForMetadata(state)},user:getUserDetails(source,session,lifecycle,autoTrack)}]};};/**
|
786
796
|
* A function to check if adblockers are active. The promise's resolve function
|
@@ -2677,7 +2687,8 @@
|
|
2677
2687
|
`${QUEUE_NAME}_${writeKey}` ,finalQOpts,(itemData,done,qItemProcessInfo)=>{const{data,url,headers}=getRequestInfo(itemData,state,qItemProcessInfo,logger);httpClient.getAsyncData({url,options:{method:'POST',headers,data:data,sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS,callback:(result,details)=>{// If there is no error, we can consider the item as delivered
|
2678
2688
|
if(isUndefined(details?.error)){// null means item will not be processed further and will be removed from the queue (even from the storage)
|
2679
2689
|
done(null);return;}const isRetryable=isErrRetryable(details?.xhr?.status??0);logMessageOnFailure(details,isRetryable,qItemProcessInfo,logger);if(isRetryable){let retryReason=DEFAULT_RETRY_REASON;if(details?.timedOut){retryReason=RETRY_REASON_CLIENT_TIMEOUT;}else if(isDefined(details?.xhr?.status)){retryReason=`server-${details.xhr.status}`;}done(details,{retryReason});}else {// null means item will not be processed further and will be removed from the queue (even from the storage)
|
2680
|
-
done(null);}}});},storeManager
|
2690
|
+
done(null);}}});},storeManager,// If local storage is available, use it, else use memory storage
|
2691
|
+
state.capabilities.storage.isLocalStorageAvailable.value?LOCAL_STORAGE:MEMORY_STORAGE,logger,itemData=>{const currentTime=getCurrentTimeFormatted();const events=itemData.map(queueItemData=>queueItemData.event);// type casting to string as we know that the event has already been validated prior to enqueue
|
2681
2692
|
return getBatchDeliveryPayload(events,currentTime,logger)?.length;});return eventsQueue;},/**
|
2682
2693
|
* Add event to the queue for delivery
|
2683
2694
|
* @param state Application state
|
@@ -2763,10 +2774,13 @@
|
|
2763
2774
|
* The method returns an empty string when the hostname is an ip.
|
2764
2775
|
*/const domain=url=>{const levels=levelsFunc(url);// Lookup the real top level one.
|
2765
2776
|
// eslint-disable-next-line unicorn/no-for-loop
|
2766
|
-
for(let i=0;i<levels.length;i+=1){const domain=levels[i];const cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;const opts={domain:`${domain.indexOf('localhost')!==-1?'':'.'}${domain}`}
|
2777
|
+
for(let i=0;i<levels.length;i+=1){const domain=levels[i];const cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;const opts={domain:`${domain.indexOf('localhost')!==-1?'':'.'}${domain}`};try{// Set cookie on domain
|
2767
2778
|
cookie(cname,1,opts);// If successful
|
2768
2779
|
if(cookie(cname)){// Remove cookie from domain
|
2769
|
-
cookie(cname,null,opts);return domain;}}
|
2780
|
+
cookie(cname,null,opts);return domain;}}catch{// Silently continue to next domain level if cookie access is restricted or setting fails
|
2781
|
+
// Best-effort cleanup to avoid leaking the test cookie
|
2782
|
+
try{cookie(cname,null,opts);}catch{// Ignore if we are unable to delete the cookie
|
2783
|
+
}}}return '';};
|
2770
2784
|
|
2771
2785
|
const getDefaultCookieOptions=()=>{const topDomain=`.${domain(globalThis.location.href)}`;return {maxage:DEFAULT_COOKIE_MAX_AGE_MS,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:'Lax',enabled:true};};const getDefaultLocalStorageOptions=()=>({enabled:true});const getDefaultSessionStorageOptions=()=>({enabled:true});const getDefaultInMemoryStorageOptions=()=>({enabled:true});
|
2772
2786
|
|
@@ -2787,7 +2801,7 @@
|
|
2787
2801
|
const store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
|
2788
2802
|
|
2789
2803
|
const hasCrypto=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);// eslint-disable-next-line compat/compat -- We are checking for the existence of navigator.userAgentData
|
2790
|
-
const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);
|
2804
|
+
const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);
|
2791
2805
|
|
2792
2806
|
const getUserAgentClientHint=(callback,level='none')=>{if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){navigator.userAgentData?.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(ua=>{callback(ua);}).catch(()=>{callback();});}};
|
2793
2807
|
|
@@ -2931,11 +2945,6 @@
|
|
2931
2945
|
*/const getUrlWithoutHash=url=>{let urlWithoutHash=url;try{const urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
|
2932
2946
|
}return urlWithoutHash;};
|
2933
2947
|
|
2934
|
-
/**
|
2935
|
-
* Determines if the SDK is running inside a chrome extension
|
2936
|
-
* @returns boolean
|
2937
|
-
*/const isSDKRunningInChromeExtension=()=>!!window.chrome?.runtime?.id;
|
2938
|
-
|
2939
2948
|
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
|
2940
2949
|
|
2941
2950
|
const isErrorReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.errors?.enabled===true;const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
@@ -3159,7 +3168,9 @@
|
|
3159
3168
|
*/const generateManualTrackingSession=(id,logger)=>{const sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};const isStorageTypeValidForStoringData=storageType=>Boolean(storageType===COOKIE_STORAGE||storageType===LOCAL_STORAGE||storageType===SESSION_STORAGE||storageType===MEMORY_STORAGE);/**
|
3160
3169
|
* Generate a new anonymousId
|
3161
3170
|
* @returns string anonymousID
|
3162
|
-
*/const generateAnonymousId=()=>generateUUID();
|
3171
|
+
*/const generateAnonymousId=()=>generateUUID();const getFinalResetOptions=options=>{// Legacy behavior: toggle only anonymousId without mutating defaults
|
3172
|
+
if(isBoolean(options)){const{entries,...rest}=DEFAULT_RESET_OPTIONS;return {...rest,entries:{...entries,anonymousId:options}};}// Override any defaults with the user provided options
|
3173
|
+
if(isObjectLiteralAndNotNull(options)&&isObjectLiteralAndNotNull(options.entries)){return mergeDeepRight(DEFAULT_RESET_OPTIONS,options);}return {...DEFAULT_RESET_OPTIONS};};
|
3163
3174
|
|
3164
3175
|
/**
|
3165
3176
|
* To get the page properties for context object
|
@@ -3368,13 +3379,11 @@
|
|
3368
3379
|
if(sessionInfo.sessionStart===undefined){sessionInfo={...sessionInfo,sessionStart:true};}else if(sessionInfo.sessionStart){sessionInfo={...sessionInfo,sessionStart:false};}}// Always write to state (in-turn to storage) to keep the session info up to date.
|
3369
3380
|
state.session.sessionInfo.value=sessionInfo;if(state.lifecycle.status.value!=='readyExecuted'){// Force update the storage as the 'effect' blocks are not getting triggered
|
3370
3381
|
// when processing preload buffered requests
|
3371
|
-
this.syncValueToStorage('sessionInfo',sessionInfo);}}/**
|
3382
|
+
this.syncValueToStorage('sessionInfo',sessionInfo);}}resetAndStartNewSession(){const session=state.session;const{manualTrack,autoTrack,timeout,cutOff}=session.sessionInfo.value;if(autoTrack){const sessionInfo={...DEFAULT_USER_SESSION_VALUES.sessionInfo,timeout};if(cutOff){sessionInfo.cutOff={enabled:cutOff.enabled,duration:cutOff.duration};}session.sessionInfo.value=sessionInfo;this.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){this.startManualTrackingInternal();}}/**
|
3372
3383
|
* Reset state values
|
3373
|
-
* @param
|
3374
|
-
* @param noNewSessionStart
|
3384
|
+
* @param options options for reset
|
3375
3385
|
* @returns
|
3376
|
-
*/reset(
|
3377
|
-
this.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){const sessionInfo={...DEFAULT_USER_SESSION_VALUES.sessionInfo,timeout};if(cutOff){sessionInfo.cutOff={enabled:cutOff.enabled,duration:cutOff.duration};}session.sessionInfo.value=sessionInfo;this.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){this.startManualTrackingInternal();}});}/**
|
3386
|
+
*/reset(options){const{session}=state;const opts=getFinalResetOptions(options);r(()=>{Object.keys(DEFAULT_USER_SESSION_VALUES).forEach(key=>{const userSessionKey=key;if(opts.entries[userSessionKey]!==true){return;}switch(key){case 'anonymousId':this.setAnonymousId();break;case 'sessionInfo':this.resetAndStartNewSession();break;default:session[userSessionKey].value=DEFAULT_USER_SESSION_VALUES[userSessionKey];break;}});});}/**
|
3378
3387
|
* Set user Id
|
3379
3388
|
* @param userId
|
3380
3389
|
*/setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
|
@@ -3537,7 +3546,7 @@
|
|
3537
3546
|
// in v3 implementation
|
3538
3547
|
path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}track(payload,isBufferedInvocation=false){const type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event - ${payload.name}`);state.metrics.triggered.value+=1;this.eventManager?.addEvent({type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}identify(payload,isBufferedInvocation=false){const type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;const shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
|
3539
3548
|
if(!isNull(payload.userId)){this.userSessionManager?.setUserId(payload.userId);}this.userSessionManager?.setUserTraits(payload.traits);this.eventManager?.addEvent({type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}alias(payload,isBufferedInvocation=false){const type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;const previousId=payload.from??(this.getUserId()||this.userSessionManager?.getAnonymousId());this.eventManager?.addEvent({type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}group(payload,isBufferedInvocation=false){const type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
|
3540
|
-
if(!isNull(payload.groupId)){this.userSessionManager?.setGroupId(payload.groupId);}this.userSessionManager?.setGroupTraits(payload.traits);this.eventManager?.addEvent({type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}reset(
|
3549
|
+
if(!isNull(payload.groupId)){this.userSessionManager?.setGroupId(payload.groupId);}this.userSessionManager?.setGroupTraits(payload.traits);this.eventManager?.addEvent({type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}reset(options,isBufferedInvocation=false){const type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,options]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.userSessionManager?.reset(options);}getAnonymousId(options){return this.userSessionManager?.getAnonymousId(options);}setAnonymousId(anonymousId,rudderAmpLinkerParam,isBufferedInvocation=false){const type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
|
3541
3550
|
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,anonymousId,rudderAmpLinkerParam]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.userSessionManager?.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
|
3542
3551
|
getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
|
3543
3552
|
getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
@@ -3639,7 +3648,34 @@
|
|
3639
3648
|
alias(to,from,options,callback){try{this.getAnalyticsInstance()?.alias(aliasArgumentsToCallOptions(getSanitizedValue(to),getSanitizedValue(from),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
3640
3649
|
* Process group arguments and forward to page call
|
3641
3650
|
*/// These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
3642
|
-
group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}
|
3651
|
+
group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
3652
|
+
* Reset the analytics instance
|
3653
|
+
* @param options Reset options. Except for anonymousId, initialReferrer, and initialReferringDomain
|
3654
|
+
* all other values will be reset by default.
|
3655
|
+
* @example
|
3656
|
+
* ```ts
|
3657
|
+
* reset({
|
3658
|
+
* entries: {
|
3659
|
+
* anonymousId: true,
|
3660
|
+
* }
|
3661
|
+
* });
|
3662
|
+
* ```
|
3663
|
+
* @example
|
3664
|
+
* ```ts
|
3665
|
+
* reset({
|
3666
|
+
* entries: {
|
3667
|
+
* userId: false,
|
3668
|
+
* sessionInfo: false,
|
3669
|
+
* }
|
3670
|
+
* });
|
3671
|
+
* ```
|
3672
|
+
* @returns none
|
3673
|
+
*//**
|
3674
|
+
* Reset the analytics instance
|
3675
|
+
* @param resetAnonymousId Reset anonymous ID
|
3676
|
+
* @returns none
|
3677
|
+
* @deprecated Use reset(options) instead
|
3678
|
+
*/reset(options){try{this.getAnalyticsInstance()?.reset(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}getAnonymousId(options){try{return this.getAnalyticsInstance()?.getAnonymousId(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);return undefined;}}setAnonymousId(anonymousId,rudderAmpLinkerParam){try{this.getAnalyticsInstance()?.setAnonymousId(getSanitizedValue(anonymousId),getSanitizedValue(rudderAmpLinkerParam));}catch(error){dispatchErrorEvent(error);}}getUserId(){try{return this.getAnalyticsInstance()?.getUserId();}catch(error){dispatchErrorEvent(error);return undefined;}}getUserTraits(){try{return this.getAnalyticsInstance()?.getUserTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupId(){try{return this.getAnalyticsInstance()?.getGroupId();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupTraits(){try{return this.getAnalyticsInstance()?.getGroupTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}startSession(sessionId){try{this.getAnalyticsInstance()?.startSession(getSanitizedValue(sessionId));}catch(error){dispatchErrorEvent(error);}}endSession(){try{this.getAnalyticsInstance()?.endSession();}catch(error){dispatchErrorEvent(error);}}getSessionId(){try{return this.getAnalyticsInstance()?.getSessionId();}catch(error){dispatchErrorEvent(error);return undefined;}}setAuthToken(token){try{this.getAnalyticsInstance()?.setAuthToken(getSanitizedValue(token));}catch(error){dispatchErrorEvent(error);}}consent(options){try{this.getAnalyticsInstance()?.consent(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}addCustomIntegration(destinationId,integration){try{this.getAnalyticsInstance()?.addCustomIntegration(getSanitizedValue(destinationId),getSanitizedValue(integration));}catch(error){dispatchErrorEvent(error);}}}
|
3643
3679
|
|
3644
3680
|
exports.RudderAnalytics = RudderAnalytics;
|
3645
3681
|
|