1(function(w,S){typeof exports=="object"&&typeof module<"u"?S(exports):typeof define=="function"&&define.amd?define(["exports"],S):(w=typeof globalThis<"u"?globalThis:w||self,S(w.XGenSdkCore={}))})(this,function(w){"use strict";var oe=Object.defineProperty,ae=(w2,S2,b2)=>S2 in w2?oe(w2,S2,{enumerable:!0,configurable:!0,writable:!0,value:b2}):w2[S2]=b2,l=(w2,S2,b2)=>ae(w2,typeof S2!="symbol"?S2+"":S2,b2);function S(){var a;return typeof process<"u"&&!!((a=process==null?void 0:process.versions)!=null&&a.node)}function b(){return typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u"}function M(){var a,t;if(!S())return null;const e=(a=process==null?void 0:process.versions)==null?void 0:a.node,s=(t=e?.split("."))==null?void 0:t.map(n=>Number.parseInt(n,10));return s?.length===3&&s!=null&&s.every(n=>!Number.isNaN(n))?{major:s?.[0],minor:s?.[1],patch:s?.[2]}:null}function N(a,t,e){if(!b())return;let s=`${encodeURIComponent(a)}=${encodeURIComponent(t)}`;if(e!=null&&e.expires){const n=typeof e.expires=="number"?new Date(Date.now()+e.expires*864e5).toUTCString():e.expires.toUTCString();s+=`; expires=${n}`}s+=`; path=${e?.path||"/"}`,e!=null&&e.domain&&(s+=`; domain=${e.domain}`),e!=null&&e.secure&&(s+="; secure"),document.cookie=s}function F(a){if(!b())return;const t=document.cookie?document.cookie.split("; "):[];for(let e=0;e<t.length;e++){const[s,...n]=t[e].split("=");if(decodeURIComponent(s)===a)return decodeURIComponent(n.join("="))}}function L(a,t){b()&&N(a,"",{...t,expires:new Date(0)})}const O=/^[\t\u0020-\u007e\u0080-\u00ff]+$/;function D(a,t){const e={};if(typeof a!="string")return e;const s=Object.assign({},{}).decode||z;let n=0;for(;n<a.length;){const r=a.indexOf("=",n);if(r===-1)break;let i=a.indexOf(";",n);if(i===-1)i=a.length;else if(i<r){n=a.lastIndexOf(";",r-1)+1;continue}const o=a.slice(n,r).trim();if(e[o]===void 0){let c=a.slice(r+1,i).trim();c.charCodeAt(0)===34&&(c=c.slice(1,-1));try{e[o]=s(c)}catch{e[o]=c}}n=i+1}return e}function K(a,t,e){const s=Object.assign({},e||{}),n=s.encode||Q;
1if(!O.test(a))throw new TypeError("argument name is invalid");const r=n(t);if(r&&!O.test(r))throw new TypeError("argument val is invalid");let i=`${a}=${r}`;if(s.maxAge!=null){const o=s.maxAge-0;if(Number.isNaN(o)||!Number.isFinite(o))throw new TypeError("option maxAge is invalid");i+=`; Max-Age=${Math.floor(o)}`}if(s.domain){if(!O.test(s.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${s.domain}`}if(s.path){if(!O.test(s.path))throw new TypeError("option path is invalid");i+=`; Path=${s.path}`}if(s.expires){if(!H(s.expires)||Number.isNaN(s.expires.valueOf()))throw new TypeError("option expires is invalid");i+=`; Expires=${s.expires.toUTCString()}`}if(s.httpOnly&&(i+="; HttpOnly"),s.secure&&(i+="; Secure"),s.priority)switch(typeof s.priority=="string"?s.priority.toLowerCase():s.priority){case"low":i+="; Priority=Low";break;case"medium":i+="; Priority=Medium";break;case"high":i+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(s.sameSite)switch(typeof s.sameSite=="string"?s.sameSite.toLowerCase():s.sameSite){case!0:i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"strict":i+="; SameSite=Strict";break;case"none":i+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return i}function z(a){return a.indexOf("%")!==-1?decodeURIComponent(a):a}function Q(a){return encodeURIComponent(a)}function H(a){return Object.prototype.toString.call(a)==="[object Date]"||a instanceof Date}const m=[];for(let a=0;a<256;++a)m.push((a+256).toString(16).slice(1));function Y(a,t=0){return(m[a[t+0]]+m[a[t+1]]+m[a[t+2]]+m[a[t+3]]+"-"+m[a[t+4]]+m[a[t+5]]+"-"+m[a[t+6]]+m[a[t+7]]+"-"+m[a[t+8]]+m[a[t+9]]+"-"+m[a[t+10]]+m[a[t+11]]+m[a[t+12]]+m[a[t+13]]+m[a[t+14]]+m[a[t+15]]).toLowerCase()}let R;const X=new Uint8Array(16);function W(){if(!R){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");R=crypto.getRandomValues.bind(crypto)}return R(X)}const V={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function P(a,t,e){var n;if(V.randomUUID&&!a)return V.randomUUID();a=a||{};const s=a.random??((n=a.rng)==null?void 0:n.call(a))??W();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Y(s)}class Z{constructor(t){l(this,"client"),this.client=t}}class A extends Z{getUser(){var s;const t=this.client.authStore.addAlternateUserId(),e=(s=this.client.authStore.user)==null?void 0:s.alternateUserId;return t&&this.client.authStore.user&&e!==t&&this.client.authStore.save({userRecord:{...this.client.authStore.user,alternateUserId:t}}),this.client.authStore.user}setUser(){const t={userId:this.client.authStore.generateUserId(),userType:"new_user",exp:this.client.authStore.getUserExpiration()},e=this.client.authStore.addAlternateUserId();return e&&(t.alternateUserId=e),this.client.authStore.save({userRecord:t,sessionRecord:{sessionId:P(),exp:this.client.authStore.getSessionExpiration()}}),t}getOrCreateUser(){let t=this.getUser();return t||(t=this.setUser()),t}}class I extends Error{constructor(e){var s;super("XGenClientResponseError"),l(this,"url",""),l(this,"status",0),l(this,"response",{}),l(this,"isAbort",!1),l(this,"originalError",null),Object.setPrototypeOf(this,I.prototype),e!==null&&typeof e=="object"&&(this.url=typeof e.url=="string"?e.url:"",this.status=typeof e.status=="number"?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,e.response!==null&&typeof e.response=="object"?this.response=e.response:e.data!==null&&typeof e.data=="object"?this.response=e.data:this.response={}),!this.originalError&&!(e instanceof I)&&(this.originalError=e),typeof DOMException<"u"&&e instanceof DOMException&&(this.isAbort=!0),this.name=`XGenClientResponseError ${this.status}`,this.message=(s=this.response)==null?void 0:s.message,this.message||(this.message="Something went wrong while processing your request.")}toJSON(){return{...this}}}class ee extends A{async getResultsById({elementId:t,containerId:e,options:s,queryId:n}){var C,k,E;const r=(C=this.getOrCreateUser())==null?void 0:C.userId,{context:i,pathname:o,locale:c,productC
1ode:u,targetProductCode:d,exclude:y,recentlyViewed:g,...v}=s||{};if(t&&e)throw new Error("Please only pass either elementId or containerId. You cannot pass both");if(!t&&!e)throw new Error("You must provide either elementId or containerId");if(u&&d)throw new Error("Please only pass `productCode` or `targetProductCode`. You cannot pass both.");const h={context:{...v,...i}},p=e?"v3":"v2";t&&(h.element_ids=[t]),e&&(h.container_ids=[e]),h.context.pathname=o??c??(b()?window.location.pathname:"")??"",u&&(h.context.pdpCode=u),d&&(h.context.pdpCode=d,h.context.skip_fv_creation=!0),y&&(h.context.exclude=y.join("|")),g&&(h.context.recentlyViewed=g.join("|"));const f=(E=(k=this.client.authStore)==null?void 0:k.user)==null?void 0:E.alternateUserId;f&&(h.alternate_user_id=f);const x=`${this.getBaseUrl()}/${p}/render/customers/${this.client.clientId}/users/${r}`,_=await this.client.send({url:x,options:{body:JSON.stringify(h)},queryId:n});if(_!=null&&_.code&&!String(_.code).startsWith("2"))throw new I({url:x,status:_.code,data:_});return p==="v3"?this.formatGetResultsByIdV3(_):this.formatGetResultsById(_)}async getResults({elementIds:t,containerIds:e,options:s,queryId:n}){var E,T,U;const r=(E=this.getOrCreateUser())==null?void 0:E.userId,{context:i,pathname:o,locale:c,productCode:u,targetProductCode:d,exclude:y,recentlyViewed:g,...v}=s||{},h=Array.isArray(e)&&e.length>0,p=Array.isArray(t)&&t.length>0;if(h&&p)throw new Error("Please only pass either elementIds or containerIds. You cannot pass both.");if(!h&&!p)throw new Error("You must provide either elementIds or containerIds");if(u&&d)throw new Error("Please only pass `productCode` or `targetProductCode`. You cannot pass both.");const f={context:{...v,...i}},x=h?"v3":"v2";p&&(f.element_ids=t),h&&(f.container_ids=e),f.context.pathname=o??c??(b()?window.location.pathname:"")??"",u&&(f.context.pdpCode=u),d&&(f.context.pdpCode=d,f.context.skip_fv_creation=!0),y&&(f.context.exclude=y.join("|")),g&&(f.context.recentlyViewed=g.join("|"));const _=(U=(T=this.client.authStore)==null?void 0:T.user)==null?void 0:U.alternateUserId;_&&(f.alternate_user_id=_);const C=`${this.getBaseUrl()}/${x}/render/customers/${this.client.clientId}/users/${r}`,k=await this.client.send({url:C,options:{body:JSON.stringify(f)},queryId:n});if(k!=null&&k.code&&!String(k.code).startsWith("2"))throw new I({url:C,status:k.code,data:k});return x==="v3"?this.formatGetResultsV3(k):this.formatGetResults(k)}formatGetResults(t){const{render_data:e}=t||{};return e?.reduce((s,n)=>(s[n.element.id]={items:n.prediction,title:n.element.title,ruleEngine:n.rule_engine_v,ruleset:n.element.ruleset},s),{})}formatGetResultsById(t){const{render_data:e}=t||{};return{items:e?.[0].prediction,title:e?.[0].element.title,ruleEngine:e?.[0].rule_engine_v,ruleset:e?.[0].element.ruleset}}formatGetResultsV3(t){const{containers:e}=t||{};return e?.reduce((s,n)=>(s[n.id]={items:n.prediction,title:n.title},s),{})}formatGetResultsByIdV3(t){const{containers:e}=t||{};return{items:e?.[0].prediction,title:e?.[0].title}}getBaseUrl(){var e,s,n,r;let t="prod";return typeof((e=this.client)==null?void 0:e.getRecommendationEnv)=="function"?t=this.client.getRecommendationEnv():typeof((s=this.client)==null?void 0:s.getRecommendationEnv)=="string"?t=this.client.getRecommendationEnv:typeof((n=this.client)==null?void 0:n.getEnv)=="function"?t=this.client.getEnv():typeof((r=this.client)==null?void 0:r.getEnv)=="string"&&(t=this.client.getEnv),t==="dev"?"https://prediction-dev.xgen.dev":t==="stage"?"https://prediction-stage.xgen.dev":"https://prediction.xgen.dev"}}class te extends A{async getResults({query:t,options:e,queryId:s,autoTrack:n=!0}){var T,U,q,G;const r=P(),{deploymentId:i,pageSize:o=60,forceDeepSearch:c,sortBy:u,sortOrder:d,facets:y,context:g={},locale:v,url:h,referrer:p,...f}=e,x={query:t,deployment_id:i,use_opensearch_neural_as_primary:c,field_sort:u,field_sort_order:d,context:g,...f};if(y){let $="perform_new_faceting";y==="v1"&&($="perform_faceting"),x[$]=!0}const _=(U=(T=this.client.authStore)==null?void 0:T.user)==null?void 0:U.alternateUserId;_&&(x.alternate_user_id=_);const C=(q=this.getOrCreateUser())==null?void 0:q.userId,k=this.client.track.createBatch();n&&k.searchQuery({query:t,queryId:r,deploymentId:e.deploymentId});const E=await this.client.send({url:`${this.getBaseUrl()}/customers/${this.client.clientId}/users/${C}?page_size=${o}`,options:{body:JSON.stringify(x)},queryId:s});return n&&(k.searchResult({query:t,queryId:r,deploymentId:e.deploymentId,items:(G=E?.products_list)==null?void 0:G.map($=>$.prod_code)}),k.send({locale:v,url:h,referrer:p})),E.queryId=r,this.formatGetResults(E)}async getResultValues({productId:t,collection:e,queryId:s}){var o;const n=(o=this.getOrCreateUser())==null?void 0:o.userId,r={collection:e};return t&&(r.prod_code=t),await this.client.send({url:`${this.getBaseUrl()}/customers/${this.client.clientId}/users/${n}/product-values`,options:{body:JSON.stringify(r)},queryId:s})}async getCategoryPage({category:t,collection:e,page:s,queryId:n}){var c;const r=(c=this.getOrCreateUser())==null?void 0:c.userId,i={category:t,collection:e};
1s&&(i.page=s);const o=await this.client.send({url:`${this.getBaseUrl()}/customers/${this.client.clientId}/users/${r}/categories`,options:{body:JSON.stringify(i)},queryId:n});return this.formatGetResults(o)}async getTrendingSearches({collection:t,version:e,queryId:s}){var i;const n=(i=this.getOrCreateUser())==null?void 0:i.userId;return await this.client.send({url:`${this.getBaseUrl()}/${e||"v1"}/customers/${this.client.clientId}/users/${n}/collections/${t}/trending`,options:{method:"GET"},queryId:s})}async getSearchSuggestions({collection:t,query:e,options:s,queryId:n}){var u;if(e.length<3)return[];const r=(u=this.getOrCreateUser())==null?void 0:u.userId,{version:i="v1",devMode:o=!1}=s||{};return await this.client.send({url:`${this.getBaseUrl()}/${i}/customers/${this.client.clientId}/users/${r}/collections/${t}/suggestions?query=${e}${o?"&dev_mode=true":""}`,options:{method:"GET"},queryId:n})}formatGetResults(t){return{items:t.products_list||[],page:t.page,totalResults:t.total_result,facets:t.facet_list??t.facet,sortedBy:t.sorted_by,isQueryTranslated:t.query_translated,isFromCache:t.is_from_cache,keyword:t.keyword,isUrlRedirect:t.is_url_redirect,urlRedirect:t.url_redirect,isCachedFilterApplied:t.is_cached_filter_applied,isKeywordConfigApplied:t.is_keyword_config_applied,searchTermMatches:t.search_term_matches,behaviorId:t.behavior_id,responseEngine:t.response_engine,variantMapping:t.product_code_variant_mapping,filter:t.filter,queryId:t.queryId}}getBaseUrl(){var e,s,n,r;let t="prod";return typeof((e=this.client)==null?void 0:e.getSearchEnv)=="function"?t=this.client.getSearchEnv():typeof((s=this.client)==null?void 0:s.getSearchEnv)=="string"?t=this.client.getSearchEnv:typeof((n=this.client)==null?void 0:n.getEnv)=="function"?t=this.client.getEnv():typeof((r=this.client)==null?void 0:r.getEnv)=="string"&&(t=this.client.getEnv),t==="dev"?"https://prompt-dev.xgen.dev":t==="stage"?"https://prompt-stage.xgen.dev":"https://prompt.xgen.dev"}}class se extends A{constructor(){super(...arguments),l(this,"locale"),l(this,"group"),l(this,"baseTracking",new ie)}setLocale(e){this.locale=e}setGroup(e){this.group=e}async pageView({context:e,locale:s,url:n,referrer:r,group:i}={}){const o=this.baseTracking.createPageViewPayload({context:e});return await this.trackEvents({events:[o],locale:s,url:n,referrer:r,group:i})}async itemView({item:e,context:s,locale:n,url:r,referrer:i,group:o}){const c=this.baseTracking.createItemViewPayload({item:e,context:s});return await this.trackEvents({events:[c],locale:n,url:r,referrer:i,group:o})}async categoryView({category:e,items:s,context:n,locale:r,url:i,referrer:o,group:c}){const u=this.baseTracking.createCategoryViewPayload({category:e,items:s,context:n});return await this.trackEvents({events:[u],locale:r,url:i,referrer:o,group:c})}async addToCart({item:e,context:s,locale:n,url:r,referrer:i,group:o}){const c=this.baseTracking.createAddToCartPayload({item:e,context:s});return await this.trackEvents({events:[c],locale:n,url:r,referrer:i,group:o})}async purchaseOrder({items:e,orderId:s,tax:n,discount:r,context:i,locale:o,url:c,referrer:u,group:d}){const y=this.baseTracking.createPurchaseOrderPayloads({items:e,orderId:s,tax:n,discount:r,context:i});return await this.trackEvents({events:y,locale:o,url:c,referrer:u,group:d})}async elementView({element:e,context:s,locale:n,url:r,referrer:i,group:o,isCompetitor:c}){const u=this.baseTracking.createElementViewPayload({element:e,context:s,isCompetitor:c});return await this.trackEvents({events:[u],locale:n,url:r,referrer:i,group:o})}async elementRender({element:e,context:s,locale:n,url:r,referrer:i,group:o,isCompetitor:c}){const u=this.baseTracking.createElementRenderPayload({element:e,context:s,isCompetitor:c});return await this.trackEvents({events:[u],locale:n,url:r,referrer:i,group:o})}async elementClick({element:e,item:s,context:n,locale:r,url:i,referrer:o,group:c,isCompetitor:u}){const d=this.baseTracking.createElementClickPayload({element:e,item:s,context:n,isCompetitor:u});return await this.trackEvents({events:[d],locale:r,url:i,referrer:o,group:c})}async searchQuery({query:e,queryId:s,deploymentId:n,isTypeToSearch:r,page:i,filtersContext:o,context:c,locale:u,url:d,referrer:y,group:g,isCompetitor:v}){const h=this.baseTracking.createSearchQueryPayload({query:e,queryId:s,deploymentId:n,isTypeToSearch:r,page:i,filtersContext:o,context:c,isCompetitor:v});return await this.trackEvents({events:[h],locale:u,url:d,referrer:y,group:g})}async searchResult({query:e,queryId:s,deploymentId:n,items:r,isTypeToSearch:i,page:o,filtersContext:c,context:u,locale:d,url:y,referrer:g,group:v,isCompetitor:h}){const p=this.baseTracking.createSearchResultPayload({query:e,queryId:s,deploymentId:n,items:r,isTypeToSearch:i,page:o,filtersContext:c,context:u,isCompetitor:h});return await this.trackEvents({events:[p],locale:d,url:y,referrer:g,group:v})}async searchClick({query:e,queryId:s,deploymentId:n,page:r,item:i,items:o,context:c,locale:u,url:d,referrer:y,group:g,isCompetitor:v}){const h=this.baseTracking.createSearchClickPayload({query:e,queryId:s,deploymentId:n,page:r,item:i,items:o,context:c,isCompetitor:v});return await this.trackEvents({events:[h],locale:u,url:d,referrer:y,group:g})}async groupAssignment({group:e,previousGroup:s,locale:n,url:r,referrer:i}){const o=this.baseTracking.createGroupAssignmentPayload({group:e,previousGroup:s});return await this.trackEvents({events:[o],locale:n,url:r,referrer:i,group:e})}async customEvent({category:e,action:s,name:n,value:r,context:i,locale:o,url:c,referrer:u,group:d}){const y=this.baseTracking.createCustomEventPayload({category:e,action:s,name:n,value:r,context:i});return await this.trackEvents({events:[y],locale:o,url:c,referrer:u,group:d})}async trackEvents({events:e,queryId:s,locale:n,url:r,referrer:i,group:o}){var v,h,p;const c=new Headers({cstid:this.client.clientId}),u=(v=this.getOrCreateUser())==null?void 0:v.userId,d=(p=(h=this.client.authStore)==null?void 0:h.user)==null?void 0:p.alternateUserId,y=await this.getDefaultParams({locale:n,url:r,referrer:i,group:o}),g=e?.map(f=>({...y,...f,...d?{alternate_user_id:d}:{}}));return await this.client.send({url:`${this.getBaseUrl()}/customers/${this.client.clientId}/users/${u}/batch`,options:{headers:c,body:JSON.stringify(g)},queryId:s}),{message:"Event(s) tracked successfully",success:!0}}async getDefaultParams({locale:e,url:s="",referrer:n="",group:r}){var u;
1const i={customer_id:this.client.clientId,user_type:(u=this.client.authStore.user)==null?void 0:u.userType,session_id:this.client.authStore.sessionId},o=r??this.group??(typeof this.client.group=="function"?await this.client.group():this.client.group)??null;o!=null&&o.name&&(i.testing_group_name=o.name),o!=null&&o.id&&(i.ab_test_id=o.id);const c=e??this.locale??(typeof this.client.locale=="function"?await this.client.locale():this.client.locale)??"";return{rec:"1",idsite:this.client.trackerId,url:s||(b()?document?.URL:"")||"",urlref:n||(b()?document?.referrer:"")||"",locale:c,uid:JSON.stringify(i)}}createBatch(){return new ne(this,this.baseTracking)}getBaseUrl(){var s,n,r,i;let e="prod";return typeof((s=this.client)==null?void 0:s.getTrackerEnv)=="function"?e=this.client.getTrackerEnv():typeof((n=this.client)==null?void 0:n.getTrackerEnv)=="string"?e=this.client.getTrackerEnv:typeof((r=this.client)==null?void 0:r.getEnv)=="function"?e=this.client.getEnv():typeof((i=this.client)==null?void 0:i.getEnv)=="string"&&(e=this.client.getEnv),e==="dev"||e==="stage"?"https://tracker-eu-stage.xgen.dev":"https://tracker.xgen.dev"}}class ne{constructor(t,e){l(this,"items",[]),l(this,"trackService"),l(this,"baseTracking"),this.trackService=t,this.baseTracking=e}pageView(t){const{context:e}=t||{},s=this.baseTracking.createPageViewPayload({context:e});this.items.push(s)}itemView(t){const{item:e,context:s}=t||{},n=this.baseTracking.createItemViewPayload({item:e,context:s});this.items.push(n)}categoryView(t){const{category:e,items:s,context:n}=t||{},r=this.baseTracking.createCategoryViewPayload({category:e,items:s,context:n});this.items.push(r)}addToCart(t){const{item:e,context:s}=t||{},n=this.baseTracking.createAddToCartPayload({item:e,context:s});this.items.push(n)}purchaseOrder(t){const{items:e,orderId:s,tax:n,discount:r,context:i}=t||{},o=this.baseTracking.createPurchaseOrderPayloads({items:e,orderId:s,tax:n,discount:r,context:i});this.items.push(...o)}elementView(t){const{element:e,context:s}=t||{},n=this.baseTracking.createElementViewPayload({element:e,context:s});this.items.push(n)}elementRender(t){const{element:e,context:s}=t||{},n=this.baseTracking.createElementRenderPayload({element:e,context:s});this.items.push(n)}elementClick(t){const{element:e,item:s,context:n}=t||{},r=this.baseTracking.createElementClickPayload({element:e,item:s,context:n});this.items.push(r)}searchQuery(t){const{query:e,queryId:s,deploymentId:n,isTypeToSearch:r,page:i,filtersContext:o,context:c}=t||{},u=this.baseTracking.createSearchQueryPayload({query:e,queryId:s,deploymentId:n,isTypeToSearch:r,page:i,filtersContext:o,context:c});this.items.push(u)}searchResult(t){const{query:e,queryId:s,deploymentId:n,items:r,isTypeToSearch:i,page:o,filtersContext:c,context:u}=t||{},d=this.baseTracking.createSearchResultPayload({query:e,queryId:s,deploymentId:n,items:r,isTypeToSearch:i,page:o,filtersContext:c,context:u});this.items.push(d)}searchClick(t){const{query:e,queryId:s,deploymentId:n,page:r,item:i,items:o,context:c}=t||{},u=this.baseTracking.createSearchClickPayload({query:e,queryId:s,deploymentId:n,page:r,item:i,items:o,context:c});this.items.push(u)}groupAssignment(t){const{group:e,previousGroup:s}=t||{},n=this.baseTracking.createGroupAssignmentPayload({group:e,previousGroup:s});this.items.push(n)}customEvent(t){const{category:e,action:s,name:n,value:r}=t||{},i=this.baseTracking.createCustomEventPayload({category:e,action:s,name:n,value:r});this.items.push(i)}async send({locale:t,url:e,referrer:s,group:n}={}){if(this.items.length===0)return{data:{message:"No events to track",success:!0},error:null};const r=await this.trackService.trackEvents({events:this.items,locale:t,url:e,referrer:s,group:n});return this.clear(),r}clear(){this.items=[]}}class ie{createPageViewPayload({context:t}={}){const e={action_detail:"page_view",action_name:"page_view",action_type:"ecomm"};return t&&(e.context=t),e}createItemViewPayload({item:t,context:e}){const s={cvar:JSON.stringify({2:["_pkp",t.price],3:["_pks",t.id],4:["_pkn",t.name],5:["_pkc",JSON.stringify({currency_code:t.currency})]}
1),action_name:"product_view",action_detail:"product_view",action_type:"ecomm"};return e&&(s.context=e),s}createAddToCartPayload({item:t,context:e}){const s=[t.id,t.name,JSON.stringify({currency_code:t.currency}),t.price,t.quantity],n={ec_items:JSON.stringify([s]),revenue:t.price*t.quantity,action_name:"product_add",action_detail:"product_add",action_type:"ecomm"};return e&&(n.context=e),n}createPurchaseOrderPayloads({items:t,orderId:e,tax:s,discount:n,context:r}){const i=t?.map(d=>[d.id,d.name,JSON.stringify({currency_code:d.currency}),d.price,d.quantity||1]),o=i?.map(d=>({ec_items:JSON.stringify([d]),ec_id:e,action_name:"product_purchase",action_detail:"product_purchase",action_type:"ecomm",version:"2",context:r})),c=t?.reduce((d,y)=>d+y.price*y.quantity,0),u={ec_items:JSON.stringify(i),revenue:c,ec_id:e,ec_st:c,ec_tx:s||0,ec_dt:String(n||0),idgoal:"0",action_name:"purchase_order",action_detail:"purchase_order",action_type:"ecomm",version:"2",context:r};return[...o,u]}createCategoryViewPayload({category:t,items:e,context:s}){const n={cvar:JSON.stringify({5:["_pkc",t]}),action_name:"category_view",action_detail:"category_view",action_type:"ecomm",context:{plpProducts:e}};return s&&(n.context={...n.context,...s}),n}createElementViewPayload({element:t,context:e,isCompetitor:s}){const n={c_n:s?`competitor-${t.id}`:t.id,c_t:t?.items.join(","),c_i:"elementViewed",action_name:"content_tracking",action_detail:"element_view",action_type:"smart_element"};return e&&(n.context=e),n}createElementRenderPayload({element:t,context:e,isCompetitor:s}){const n={c_n:s?`competitor-${t.id}`:t.id,c_t:t?.items.join(","),action_name:"content_tracking",action_detail:"element_impression",action_type:"smart_element"};return e&&(n.context=e),n}createElementClickPayload({element:t,item:e,context:s,isCompetitor:n}){var i;const r={c_n:n?`competitor-${t.id}`:t.id,c_p:e,c_t:((i=t?.items)==null?void 0:i.join(","))||"",c_i:"elementClicked",action_name:"content_tracking",action_detail:"element_click",action_type:"smart_element"};return s&&(r.context=s),r}createSearchQueryPayload({query:t,queryId:e,deploymentId:s,isTypeToSearch:n,page:r,filtersContext:i,context:o,isCompetitor:c}){return{query_id:e,action_name:"search",action_detail:"search",action_type:"search_service",context:{...o,query:t,deployment_id:c?`competitor-${s}`:s,is_type_to_search:n||!1,page:r||0,filters_context:i}}}createSearchResultPayload({query:t,queryId:e,deploymentId:s,items:n,isTypeToSearch:r,page:i,filtersContext:o,context:c,isCompetitor:u}){return{c_n:u?`competitor-${s}`:s,c_t:n?.join(",")||"",c_i:"searchResult",query_id:e,action_name:"content_tracking",action_detail:"search_result",action_type:"search_service",context:{...c,query:t,deployment_id:u?`competitor-${s}`:s,is_type_to_search:r||!1,page:i||0,filters_context:o}}}createSearchClickPayload({query:t,queryId:e,deploymentId:s,page:n,item:r,items:i,context:o,isCompetitor:c}){return{c_n:c?`competitor-${s}`:s,c_p:r,c_t:i?.join(",")||"",c_i:"searchClicked",query_id:e,action_name:"content_tracking",action_detail:"search_click",action_type:"search_service",context:{...o,query:t,deployment_id:c?`competitor-${s}`:s,page:n||0}}}createGroupAssignmentPayload({group:t,previousGroup:e,context:s}){const n={action_name:"group_assignment",action_detail:"group_assignment",action_type:"ecomm",context:{...s,new_value:t.name}};return e!=null&&e.name&&n.context&&(n.context.prev_value=e?.name),n}createCustomEventPayload({category:t,action:e,name:s,value:n,context:r}){return{e_c:t,e_a:e,e_n:s,e_v:n,action_name:"event_tracking",action_detail:e,action_type:t,context:r}}}class B{constructor({keyPrefix:t="xgen_",tokenSuffix:e="token",userSuffix:s="user",sessionSuffix:n="session",generateUserId:r=()=>Math.random().toString(36).substring(2)+new Date().getTime().toString(36),addAlternateUserId:i=()=>{},getUserExpiration:o=()=>Date.now()+395*24*60*60*1e3,getSessionExpiration:c=()=>Date.now()+1800*1e3}={}){l(this,"baseToken",null),l(this,"baseSession",null),l(this,"baseUser",null),l(this,"tokenKey"),l(this,"userKey"),l(this,"sessionKey"),l(this,"getUserExpiration"),l(this,"getSessionExpiration"),l(this,"generateUserId"),l(this,"addAlternateUserId"),this.tokenKey=`${t}${e}`,this.userKey=`${t}${s}`,this.sessionKey=`${t}${n}
1`,this.getUserExpiration=o,this.getSessionExpiration=c,this.generateUserId=r,this.addAlternateUserId=i}get token(){var t;return this.isExpired(this.baseToken)?(this.baseToken=null,""):((t=this.baseToken)==null?void 0:t.token)||""}get user(){return this.isExpired(this.baseUser)?(this.baseUser=null,this.baseUser):this.baseUser}get sessionId(){var t;return this.isExpired(this.baseSession)?(this.baseSession=null,""):((t=this.baseSession)==null?void 0:t.sessionId)||""}isExpired(t){return t?t!=null&&t.exp?Date.now()>t.exp:!1:!0}get cookieInfo(){return[{dataKey:"baseToken",cookieKey:this.tokenKey},{dataKey:"baseUser",cookieKey:this.userKey},{dataKey:"baseSession",cookieKey:this.sessionKey}]}save({tokenRecord:t,userRecord:e,sessionRecord:s}){t&&(this.baseToken=t),e&&(this.baseUser=e),s&&(this.baseSession=s)}clear(){this.baseToken=null,this.baseUser=null,this.baseSession=null}loadFromCookie(t){let e={};for(const{dataKey:s,cookieKey:n}of this.cookieInfo){const r=D(t)[n]||"";try{e[s]=JSON.parse(r),(e===null||typeof e!="object"||Array.isArray(e))&&(e={})}catch{}}this.save({tokenRecord:e?.baseToken||null,userRecord:e?.baseUser||null,sessionRecord:e?.baseSession||null})}exportToCookie(t){const e={secure:!0,sameSite:!0,httpOnly:!0,path:"/"};let s=[];for(const{cookieKey:n,dataKey:r}of this.cookieInfo){const i=this[r];i!=null&&i.exp?e.expires=new Date(i.exp):e.expires=new Date("1970-01-01");const o=Object.assign({},e,t),c=K(n,JSON.stringify(i),o);typeof Blob<"u"?new Blob([c]).size:c.length,s.push(K(n,JSON.stringify(i),o))}return s}}class j extends B{constructor({params:e,cookieOptions:s}={}){super(e),l(this,"storageFallback",{}),l(this,"cookieOptions"),this.cookieOptions=s;const n=this.user;n&&this.save({userRecord:{...n,exp:this.getUserExpiration()}})}get token(){const e=this._storageGet(this.tokenKey);return this.isExpired(e)?(this._storageRemove(this.tokenKey),""):e?.token||""}get user(){const e=this._storageGet(this.userKey);return this.isExpired(e)?(this.clear(),null):e}get sessionId(){const e=this._storageGet(this.sessionKey);return this.isExpired(e)?(this._storageRemove(this.sessionKey),""):e?.sessionId||""}save({tokenRecord:e,userRecord:s,sessionRecord:n}){e&&this._storageSet(this.tokenKey,e),s&&this._storageSet(this.userKey,s),n&&this._storageSet(this.sessionKey,n),super.save({tokenRecord:e,userRecord:s,sessionRecord:n})}clear(){this._storageRemove(this.tokenKey),this._storageRemove(this.userKey),this._storageRemove(this.sessionKey),super.clear()}_storageGet(e){if(this.isBrowserAndCookiesAvailable()){const s=F(e)||"";try{return JSON.parse(s)}catch{return s}}return this.storageFallback[e]}_storageSet(e,s){if(this.isBrowserAndCookiesAvailable()){const n=JSON.stringify(s);N(e,n,{expires:new Date(s.exp),...this.cookieOptions})}this.storageFallback[e]=s}_storageRemove(e){this.isBrowserAndCookiesAvailable()&&L(e),delete this.storageFallback[e]}isBrowserAndCookiesAvailable(){var e;return typeof window<"u"&&typeof((e=window?.document)==null?void 0:e.cookie)=="string"}}class re{constructor({key:t,secret:e,clientId:s,trackerId:n,getEnv:r=()=>"prod",getTrackerEnv:i,getRecommendationEnv:o,getSearchEnv:c,locale:u,group:d,fetchFunc:y}){if(l(this,"key"),l(this,"secret"),l(this,"trackerId"),l(this,"clientId"),l(this,"locale"),l(this,"group"),l(this,"getEnv"),l(this,"getTrackerEnv"),l(this,"getRecommendationEnv"),l(this,"getSearchEnv"),l(this,"fetchFunc"),l(this,"_search",null),l(this,"_recommend",null),l(this,"_track",null),l(this,"_authStore",null),l(this,"beforeSend"),l(this,"afterSend"),l(this,"cancelControllers",new Map),!t||!e||!s||!n)throw new Error("key, secret, clientId, trackerId, and getLocale are required");if(S()){const g=M();g!=null&&g.major&&g?.major<21&&console.warn("The XGen SDK works best with Node.js version 21 or higher. If you must use a lower version, please pass in a custom fetch function. We recommend using node-fetch. See <docs> for more info.")}this.key=t,this.secret=e,this.clientId=s,this.trackerId=n,this.locale=u,this.group=d,this.getEnv=r,this.getTrackerEnv=i,this.getRecommendationEnv=o,this.getSearchEnv=c,this.fetchFunc=y}get search(){if(!this._search)throw new Error("Search service not initialized");return this._search}get recommend(){if(!this._recommend)throw new Error("Recommend service not initialized");return this._recommend}get track(){if(!this._track)throw new Error("Track service not initialized");return this._track}get authStore(){if(!this._authStore)throw new Error("Auth store not initialized");return this._authStore}registerServices(t,e,s,n){this._search=t,this._recommend=e,this._track=s,this._authStore=n}cancelAll(){for(const t of this.cancelControllers.values())t.abort();this.cancelControllers.clear()}cancel(t){var e;(e=this.cancelControllers.get(t))==null||e.abort(),this.cancelControllers.delete(t)}async send({url:t,options:e,queryId:s}){const n=s||P();try{const r=new AbortController;this.cancelControllers.set(n,r);const i=new Headers({"Content-Type":"application/json"}),o=this.authStore.token;o?i.append("access_token",o):(i.append("x-api-key",this.key),i.append("x-api-secret",this.secret));const c=this.authStore.user;
1if(this.authStore.sessionId||(c?.userType==="new_user"&&(c.userType="return_user",this.authStore.save({userRecord:c})),this.authStore.save({sessionRecord:{sessionId:P(),exp:this.authStore.getSessionExpiration()}})),this.beforeSend){const h=await this.beforeSend({url:t,options:e});(typeof h.url<"u"||typeof h.options<"u")&&(t=h.url||t,e=h.options||e)}const{headers:d,method:y,...g}=e||{},v=this.fetchFunc||fetch;if(d)for(const[h,p]of Object.entries(d))i.append(h,p);return v(t,{...g,method:y||"POST",headers:i,keepalive:!0,signal:r.signal}).then(async h=>{var f,x,_;let p={};try{p=await h.json()}catch{}if((f=p?.user_data)!=null&&f.access_token&&(x=p?.user_data)!=null&&x.expiration_date&&this.authStore.save({tokenRecord:{token:p.user_data.access_token,exp:Math.floor(new Date(`${(_=p?.user_data)==null?void 0:_.expiration_date}Z`).getTime())}}),this.afterSend){const C=await this.afterSend({response:h,data:p});typeof C<"u"&&(p=C)}if(!h.ok)throw new I({url:t,status:h?.status,data:p});return p}).catch(h=>{throw h instanceof I||h instanceof Error&&h.name==="AbortError"?h:new I(h)}).finally(()=>{this.cancelControllers.delete(n)})}catch(r){throw this.cancelControllers.delete(n),r}}}class J{constructor(t){l(this,"serviceClient"),l(this,"authStore"),l(this,"cancelAll"),l(this,"cancel"),l(this,"search"),l(this,"recommend"),l(this,"track"),this.serviceClient=new re(t),this.cancelAll=this.serviceClient.cancelAll.bind(this.serviceClient),this.cancel=this.serviceClient.cancel.bind(this.serviceClient),this.search=new te(this.serviceClient),this.recommend=new ee(this.serviceClient),this.track=new se(this.serviceClient),this.authStore=t.authStore||new j,this.serviceClient.registerServices(this.search,this.recommend,this.track,this.authStore)}get beforeSend(){return this.serviceClient.beforeSend}set beforeSend(t){this.serviceClient.beforeSend=t}get afterSend(){return this.serviceClient.afterSend}set afterSend(t){this.serviceClient.afterSend=t}}w.BaseAuthStore=B,w.LocalCookieAuthStore=j,w.XGenClient=J,w.default=J,Object.defineProperties(w,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); 2//# sourceMappingURL=/cdn/shop/t/811/assets/xgen-sdk.js.map?v=78314093207208265601789977862
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.