@thg-agentic/hyper-personalisation-web 0.0.0-stage → 3.18.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/LICENSE +21 -0
- package/README.md +860 -2
- package/dist/hp.min.js +3 -0
- package/dist/snippet.min.js +1 -0
- package/package.json +83 -3
- package/src/assignment.js +75 -0
- package/src/auto/attributes.js +16 -0
- package/src/auto/exposures.js +45 -0
- package/src/auto/lists.js +136 -0
- package/src/auto/promotions.js +104 -0
- package/src/auto/rails.js +217 -0
- package/src/auto/viewability.js +150 -0
- package/src/auto.js +13 -0
- package/src/bootstrap.js +504 -0
- package/src/carry.js +74 -0
- package/src/conformance.js +530 -0
- package/src/consent-gate.js +324 -0
- package/src/consent.js +604 -0
- package/src/context.js +439 -0
- package/src/datalayer.js +411 -0
- package/src/debug.js +45 -0
- package/src/decisions.js +90 -0
- package/src/device-storage.js +213 -0
- package/src/experiments.js +220 -0
- package/src/ga4.js +124 -0
- package/src/hash.js +138 -0
- package/src/hp.js +135 -0
- package/src/index.js +840 -0
- package/src/preview.js +44 -0
- package/src/recommendation-context.js +101 -0
- package/src/sampling.js +19 -0
- package/src/segment.js +388 -0
- package/src/session/category.js +40 -0
- package/src/session/record.js +176 -0
- package/src/session/rules.js +195 -0
- package/src/session/signals.js +150 -0
- package/src/session-id.js +62 -0
- package/src/session.js +28 -0
- package/src/settings.js +230 -0
- package/src/shape.js +120 -0
- package/src/social-proof.js +139 -0
- package/src/spec-version.js +4 -0
- package/src/storage-scope.js +164 -0
- package/src/transport.js +451 -0
- package/src/version.js +2 -0
- package/types/auto.d.ts +51 -0
- package/types/bootstrap.d.ts +165 -0
- package/types/consent.d.ts +126 -0
- package/types/datalayer.d.ts +76 -0
- package/types/events.d.ts +713 -0
- package/types/hp.d.ts +64 -0
- package/types/index.d.ts +617 -0
- package/types/segment.d.ts +68 -0
package/dist/hp.min.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
(()=>{var Pt=e=>{throw TypeError(e)};var ir=(e,t,n)=>t.has(e)||Pt("Cannot "+n);var Lt=(e,t,n)=>t.has(e)?Pt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n);var N=(e,t,n)=>(ir(e,t,"access private method"),n);var ge=[];for(let e=2;ge.length<64;e++)ge.every(t=>e%t!==0)&&ge.push(e);var Ot=e=>(e-Math.floor(e))*2**32>>>0,ar=ge.slice(0,8).map(e=>Ot(Math.sqrt(e))),cr=ge.map(e=>Ot(Math.cbrt(e))),z=(e,t)=>e>>>t|e<<32-t;function Nt(e){let t=new TextEncoder().encode(String(e)),n=new Uint32Array((t.length+8>>6)*16+16);t.forEach((s,i)=>{n[i>>2]|=s<<24-i%4*8}),n[t.length>>2]|=128<<24-t.length%4*8,n[n.length-2]=Math.floor(t.length/2**29),n[n.length-1]=t.length*8;let r=Uint32Array.from(ar),o=new Uint32Array(64);for(let s=0;s<n.length;s+=16){for(let g=0;g<64;g++){if(g<16){o[g]=n[s+g];continue}let _=o[g-15],x=o[g-2],v=z(_,7)^z(_,18)^_>>>3,h=z(x,17)^z(x,19)^x>>>10;o[g]=o[g-16]+v+o[g-7]+h}let[i,a,u,d,p,f,m,b]=r;for(let g=0;g<64;g++){let _=z(p,6)^z(p,11)^z(p,25),x=b+_+(p&f^~p&m)+cr[g]+o[g]|0,h=(z(i,2)^z(i,13)^z(i,22))+(i&a^i&u^a&u)|0;[b,m,f,p,d,u,a,i]=[m,f,p,d+x|0,u,a,i,x+h|0]}[i,a,u,d,p,f,m,b].forEach((g,_)=>{r[_]+=g})}return Array.from(r,s=>s.toString(16).padStart(8,"0")).join("")}var He=(e,t)=>e<<t|e>>>32-t;function Tt(e){let t=new Uint32Array((e.length+8>>6)*16+16);e.forEach((s,i)=>{t[i>>2]|=s<<24-i%4*8}),t[e.length>>2]|=128<<24-e.length%4*8,t[t.length-2]=Math.floor(e.length/2**29),t[t.length-1]=e.length*8;let n=Uint32Array.of(1732584193,4023233417,2562383102,271733878,3285377520),r=new Uint32Array(80);for(let s=0;s<t.length;s+=16){for(let f=0;f<80;f++)r[f]=f<16?t[s+f]:He(r[f-3]^r[f-8]^r[f-14]^r[f-16],1);let[i,a,u,d,p]=n;for(let f=0;f<80;f++){let m,b;f<20?(m=a&u|~a&d,b=1518500249):f<40?(m=a^u^d,b=1859775393):f<60?(m=a&u|a&d|u&d,b=2400959708):(m=a^u^d,b=3395469782);let g=He(i,5)+m+p+b+r[f]|0;[p,d,u,a,i]=[d,u,He(a,30),i,g]}[i,a,u,d,p].forEach((f,m)=>{n[m]+=f})}let o=new Uint8Array(20);return n.forEach((s,i)=>{o[i*4]=s>>>24,o[i*4+1]=s>>>16,o[i*4+2]=s>>>8,o[i*4+3]=s}),o}var ur="e28e8ada-5b76-4209-bba9-79b823a0af75",lr=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");function Rt(e,t){let n=Uint8Array.from(e.replace(/-/g,"").match(/../g),a=>Number.parseInt(a,16)),r=new TextEncoder().encode(t),o=new Uint8Array(16+r.length);o.set(n),o.set(r,16);let s=Tt(o).slice(0,16);s[6]=s[6]&15|80,s[8]=s[8]&63|128;let i=lr(s);return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}var ee=(e,t)=>typeof e=="string"&&e!==""&&e.length<=t?e:null;function be(e,t){return ee(e,64)??ee(t,256)}function Dt({sessionId:e,slot:t,arm:n}={}){let r=ee(e,256);return!r||!ee(t,256)||!ee(n,256)?null:Rt(ur,`${r}:${t}:${n}`)}var dr="4b1f2c7e-9a3d-4e58-b6c1-2d7f0a9e8c53";function Mt({sessionId:e,surface:t}={}){let n=ee(e,256);return!n||!ee(t,64)?null:Rt(dr,`${n}:${t}`)}var fr=Array.from({length:11},(e,t)=>t/10);function pr(e,t){if(!e.isIntersecting)return!1;let{intersectionRect:n,boundingClientRect:r,rootBounds:o}=e;if(!n||!r)return!0;let s=n.width*n.height,i=r.width*r.height,a=o?Math.min(i,o.width*o.height):i;return a>0&&s/a>=t}function Y(e){let{selector:t,onViewable:n,visibleRatio:r=.5,dwellMs:o=1e3,root:s=document}=e,i=new Map,a=new WeakSet,u=new Set,d=h=>{i.has(h)||i.set(h,setTimeout(()=>{i.delete(h),n(h)&&(f?.unobserve(h),u.delete(h))},o))},p=h=>{clearTimeout(i.get(h)),i.delete(h)},f=typeof IntersectionObserver>"u"?null:new IntersectionObserver(h=>{for(let E of h){let S=E.target;if(!pr(E,r)){u.delete(S),p(S);continue}u.add(S),m()&&d(S)}},{threshold:fr}),m=()=>typeof document>"u"||document.visibilityState!=="hidden",b=()=>{if(m())for(let h of u)d(h);else for(let h of u)p(h)};document.addEventListener("visibilitychange",b);let g=()=>{for(let h of s.querySelectorAll(t))a.has(h)||(a.add(h),f?.observe(h))},_=typeof MutationObserver>"u"?null:new MutationObserver(()=>g()),x=()=>{g(),_?.observe(s===document?document.body:s,{childList:!0,subtree:!0})},v=s===document&&!document.body;return v?document.addEventListener("DOMContentLoaded",x,{once:!0}):x(),()=>{v&&document.removeEventListener("DOMContentLoaded",x),document.removeEventListener("visibilitychange",b),f?.disconnect(),_?.disconnect();for(let h of i.values())clearTimeout(h);i.clear(),u.clear()}}function Ke(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-exposure]",visibleRatio:r=.5,dwellMs:o=1e3,root:s=document}=t;return Y({selector:n,root:s,visibleRatio:r,dwellMs:o,onViewable(i){let a=i.dataset?.hpExposure?.trim();return a&&e.surfaceViewed({surface:a}),!0}})}var Ut=e=>{try{return new URL(e,document.baseURI).toString()}catch{return e}};function Ge(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-list]",tileSelector:r="[data-hp-product]",visibleRatio:o=.5,dwellMs:s=1e3,root:i=document}=t,a=new Set,u=g=>g.closest?.(n)??null,d=g=>{let _=g.dataset.hpList?.trim();return _?{list_id:_,category:g.dataset.hpListCategory?.trim()||null}:null},p=g=>Array.from(g.querySelectorAll(r)).filter(_=>u(_)===g),f=(g,_)=>{try{let x=JSON.parse(g.dataset.hpProduct??"");return!x||typeof x!="object"||!x.product_id?null:{...x,position:x.position??_+1,...x.url?{url:Ut(x.url)}:{},...x.image_url?{image_url:Ut(x.image_url)}:{}}}catch{return null}},m=Y({selector:`${n} ${r}`,root:i,visibleRatio:o,dwellMs:s,onViewable(g){let _=u(g);if(!_||_.dataset.hpListView==="manual")return!0;let x=d(_);if(!x||a.has(x.list_id))return!0;let v=new Set,h=p(_).map(f).filter(E=>!E||v.has(E.product_id)?!1:(v.add(E.product_id),!0));return h.length===0||(a.add(x.list_id),e.productListViewed({...x,products:h})),!0}}),b=g=>{let x=g.target?.closest?.("a[href]")?.closest(r);if(!x)return;let v=u(x),h=f(x,v?p(v).indexOf(x):0);h&&e.productClicked({list_id:v?d(v)?.list_id??null:null,products:[h]})};return document.addEventListener("click",b,!0),()=>{document.removeEventListener("click",b,!0),m()}}function T(e,...t){let n=e.dataset??{};for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim()!=="")return o.trim()}return null}function xe(e,...t){let n=T(e,...t);if(n===null)return null;let r=Number(n);return Number.isFinite(r)?Math.trunc(r):null}function mr(e,t){let n=T(e,"hpPromotion");return n?{promotion_id:n,name:T(e,"hpPromotionName"),creative:T(e,"hpPromotionCreative"),position:T(e,"hpPromotionSlot")??String(t+1)}:null}function We(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-promotion]",resolve:r=mr,visibleRatio:o=.5,dwellMs:s=1e3,root:i=document}=t,a=new Set,u=f=>{let m=Array.from(i.querySelectorAll(n)),b=m.indexOf(f);try{return r(f,b<0?m.length:b)}catch{return null}},d=Y({selector:n,root:i,visibleRatio:o,dwellMs:s,onViewable(f){let m=u(f);return!m||a.has(m.promotion_id)?!1:(a.add(m.promotion_id),e.promotionViewed(m),!0)}}),p=f=>{let m=f.target;if(!m||typeof m.closest!="function")return;let b=m.closest(n),g=m.closest("a[href]");if(!b||!g||!b.contains(g)&&!g.contains(b))return;let _=u(b);_&&e.promotionClicked({..._,href:g.getAttribute("href")})};return document.addEventListener("click",p,!0),()=>{document.removeEventListener("click",p,!0),d()}}function hr(e){let t=T(e,"hpRecoRequest"),n=T(e,"hpRecoPlacement"),r=T(e,"hpRecoStrategy");if(!t||!n||!r)return null;let o=T(e,"hpRecoHoldout");return{recommendation_request_id:t,placement:n,strategy:r,recipe:T(e,"hpRecoRecipe"),algorithm_version:T(e,"hpRecoAlgorithmVersion"),experiment:T(e,"hpRecoExperiment"),variant:T(e,"hpRecoVariant"),holdout:o===null?null:o==="true",assignment_bucket:xe(e,"hpRecoBucket"),assignment_unit_kind:T(e,"hpRecoUnitKind"),candidate_set_fingerprint:T(e,"hpRecoFingerprint"),candidate_set_size:xe(e,"hpRecoCandidates"),ranked_by:T(e,"hpRecoRankedBy"),served_at:T(e,"hpRecoServedAt")}}function gr(e,t){let n=T(e,"hpRecoProduct");if(!n)return null;let r=T(e,"hpRecoPrice");return{product_id:n,sku:T(e,"hpRecoSku"),name:T(e,"hpRecoName"),brand:T(e,"hpRecoBrand"),price:r===null||Number.isNaN(Number(r))?null:Number(r),position:xe(e,"hpRecoPosition")??t+1}}function ze(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-reco-request]",tileSelector:r="[data-hp-reco-product]",resolveRail:o=hr,resolveTile:s=gr,visibleRatio:i=.5,dwellMs:a=1e3,root:u=document}=t,d=new Set,p=new Map,f=new Map,m=(h,...E)=>{try{return h(...E)}catch{return null}},b=h=>typeof h.closest=="function"?h.closest(n):null,g=h=>Array.from(h.querySelectorAll(r)),_=(h,E)=>{if(f.delete(E.recommendation_request_id),d.has(E.recommendation_request_id))return;let S=g(h).map((w,L)=>m(s,w,L)).filter(w=>w?.product_id);if(S.length===0)return;d.add(E.recommendation_request_id);let y=[...p.get(E.recommendation_request_id)?.values()??[]].sort((w,L)=>w.position-L.position);e.recommendationsViewed({...E,products:S,viewable:y})},x=Y({selector:`${n} ${r}`,root:u,visibleRatio:i,dwellMs:a,onViewable(h){let E=b(h);if(!E)return!0;let S=m(o,E);if(!S)return!0;let y=S.recommendation_request_id,w=m(s,h,g(E).indexOf(h));if(w?.product_id){p.has(y)||p.set(y,new Map);let L=p.get(y);L.has(w.position)||L.set(w.position,{position:w.position,product_id:w.product_id,viewable_at:new Date().toISOString()})}return!d.has(y)&&!f.has(y)&&f.set(y,setTimeout(()=>_(E,S),0)),!0}}),v=h=>{let E=h.target;if(!E||typeof E.closest!="function")return;let S=E.closest(r);if(!S)return;let y=E.closest("[data-hp-reco-interaction]"),w=E.closest("a[href]"),L=w&&(S.contains(w)||w.contains(S));if(!(y&&S.contains(y))&&!L)return;let D=b(S);if(!D)return;let H=m(o,D);if(!H)return;let K=m(s,S,g(D).indexOf(S));if(!K?.product_id)return;let F=H.recommendation_request_id;d.has(F)||(clearTimeout(f.get(F)),_(D,H)),e.productClicked({recommendation_request_id:H.recommendation_request_id,interaction:T(y??S,"hpRecoInteraction")??"navigate",products:[K]})};return document.addEventListener("click",v,!0),()=>{document.removeEventListener("click",v,!0);for(let h of f.values())clearTimeout(h);f.clear(),x()}}var ae=new Set(["home","list","product","search","basket","checkout","order_confirmation","login","register","account","info","blog","other"]),yr=new Set(["products"]),$t=e=>e==null;function Je(e,t=new WeakSet){if(e instanceof Date)return e.toJSON();if(e===null||typeof e!="object"||t.has(e))return e;t.add(e);let n=Array.isArray(e)?e.map(r=>Je(r,t)):Object.fromEntries(Object.entries(e).filter(([,r])=>!$t(r)).map(([r,o])=>[r,Je(o,t)]));return t.delete(e),n}function Xe(e){if(!e)return e;let t=Je(e);for(let n of yr)n in e&&$t(e[n])&&(t[n]=e[n]);return t}function Vt(){try{let e=performance.getEntriesByType("navigation")[0];return e?["navigate","reload","back_forward","prerender"].includes(e.type)?e.type:"navigate":null}catch{return null}}var Sr=new Set(["","unknown","undefined","null","none","nil","nan","anonymous","guest","0","-1"]);function B(e){if(e==null)return null;let t=String(e).trim();return Sr.has(t.toLowerCase())?null:t}function Z(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var jt="1.10";function U(e){if(typeof document>"u")return null;try{let t=document.cookie.split(";").map(n=>n.trim()).find(n=>n.startsWith(`${e}=`));return t&&decodeURIComponent(t.slice(e.length+1))||null}catch{return null}}var wr={gclid:"gclid",fbclid:"fbclid",ttclid:"ttclid"},_r=/[a-z0-9._%+-]+@[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}/i,br=/\d(?:[ -]?\d){12,}/,xr=new Set(["gclid","fbclid","ttclid","msclkid"]);function qt(e,t=""){if(typeof e!="string"||e==="")return!1;let n=[e];try{let o=decodeURIComponent(e.replace(/\+/g," "));o!==e&&n.push(o)}catch{}let r=!xr.has(String(t).toLowerCase());return n.some(o=>_r.test(o)||r&&br.test(o))}function Ir(e){if(!e)return null;let t=new URLSearchParams(e),n={},r={utm_source:"source",utm_medium:"medium",utm_campaign:"name",utm_term:"term",utm_content:"content"};for(let[o,s]of[...Object.entries(r),...Object.entries(wr)]){let i=t.get(o);i&&!qt(i,o)&&(n[s]=i)}return Object.keys(n).length?n:null}var Ar=["email","e-mail","password","pass","pwd","token","auth","code","uid","customer_id","postcode","zip","phone","applyCode"],kr=["email","password","passwd","pwd","token","secret","auth","session","phone","postcode","zip","address","birth","card","cvv","iban","ssn","customerid","userid"],vr=["tel","uid","dob"],Er=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","gclid","fbclid","ttclid","msclkid"],Cr=new Set(Ar.map(e=>e.toLowerCase()));function Pr(e){let t=String(e).toLowerCase();if(Cr.has(t))return!0;let n=t.replace(/[-_.]/g,"");return kr.some(o=>n.includes(o))?!0:String(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).some(o=>vr.includes(o))}function Ye(e){return(e??[]).map(t=>{try{return new RegExp(`^${t}$`,"i")}catch{return{test:n=>n.toLowerCase()===String(t).toLowerCase()}}})}function Ft(e,t={}){if(!e)return null;try{let n=new URLSearchParams(e),r=t.queryParamAllowlist?Ye([...t.queryParamAllowlist,...Er]):null,o=Ye(t.queryParamBlocklist),s=Ye(t.sensitiveParamAllowlist);for(let a of new Set(n.keys()))(Pr(a)&&!s.some(d=>d.test(a))||n.getAll(a).some(d=>qt(d,a))||(r?!r.some(d=>d.test(a)):o.some(d=>d.test(a))))&&n.delete(a);let i=n.toString();return i?`?${i}`:""}catch{return""}}function Lr(e,t,n={}){if(!e)return null;try{let r=new URL(e);return t&&r.origin===t?r.origin+r.pathname+(Ft(r.search,n)??""):r.origin+r.pathname}catch{return null}}function Ze(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();return/^[A-Z]{3}$/.test(t)?t:null}function Bt(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();return/^[A-Z]{2}$/.test(t)?t:null}function Or(e){if(typeof e!="string")return null;let t=e.trim().replace(/_/g,"-");if(!/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(t))return null;try{return Intl.getCanonicalLocales(t)[0]}catch{return null}}function M(e,t){if(typeof e=="function")try{let n=e();if(n!=null)return n}catch{}return t}function Nr(e){return{property_id:String(e.propertyId),channel:e.channel??null,market:e.market??null,environment:e.environment??null}}function Tr(e){let t=typeof window<"u"?window.location:null,n=t?Ft(t.search,e):null;return{url:t?t.origin+t.pathname+(n??""):e.pageUrl??null,path:t?t.pathname:e.pagePath??null,search:n??null,referrer:typeof document<"u"?Lr(document.referrer,t?.origin,e):null,title:typeof document<"u"&&document.title||null,type:e.pageType??null}}function Ht(e,t={}){let n=typeof window<"u"?window.location:null,r={library:{name:e.libraryName,version:e.libraryVersion},spec:{version:jt},source:Nr(e),session_id:M(e.getSessionId,null),render_id:M(e.getRenderId,null),identity_trust:B(M(e.getAnonymousId,null))?"device":"none",page:Tr(e),campaign:n?Ir(n.search):null,device:{user_agent:typeof navigator<"u"?navigator.userAgent:null,type:null,viewport_width:typeof window<"u"?window.innerWidth:null,viewport_height:typeof window<"u"?window.innerHeight:null},currency:Ze(M(e.getCurrency,e.currency)),locale:Or(M(e.getLocale,e.locale)),timezone:(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}})(),country:Bt(e.country),ship_to_country:Bt(M(e.getShipToCountry,e.shipToCountry)),ip:null,bot:null,consent:e.getConsent?.()??null,experiments:M(e.getExperiments,null),audiences:M(e.getAudiences,null),decisions:M(e.getDecisions,null),recommendations:M(e.getRecommendations,null),extensions:M(e.getExtensions,null)};return Kt(r,t)}function Kt(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t))o&&typeof o=="object"&&!Array.isArray(o)&&e[r]&&typeof e[r]=="object"&&!Array.isArray(e[r])?n[r]=Kt(e[r],o):o!==void 0&&(n[r]=o);return n}var re=Object.freeze({consent:"thg_hp_consent",retry:"thg_hp_retry",sessionSignals:"thg_hp_session_signals",identified:"thg_hp_identified",previousPage:"thg_hp_prev_page",decisions:"thg_hp_decisions",settings:"thg_hp_settings",held:"thg_hp_held",carried:"thg_hp_carried",recommendationContext:"thg_hp_recommendation_context",anonymousId:"thg_hp_anonymous_id",session:"thg_hp_session",preview:"thg_hp_preview",debug:"thg_hp_debug"}),Rr={retry:"cdp.retry",sessionSignals:"cdp_session_signals",identified:"cdp_identified",previousPage:"cdp_prev_page_message_id"},Qe={...re},Gt=!1;function Ie(e){let t={...re};for(let[n,r]of Object.entries(e??{})){if(!(n in re))throw new Error(`storageNames: unknown kind "${n}"`);if(typeof r!="string"||!/^[\w.-]+$/.test(r))throw new Error(`storageNames.${n} must be a non-empty cookie-safe name`);t[n]=r}Qe=t}function O(e){return Qe[e]}var Dr="_",Wt=e=>e==null||e===""?Dr:String(e);function q(e,t,n){let r=`${e}:${Wt(t)}`;return n==null||n===""?r:`${r}:${n}`}function zt(e,t){return`${e}:${Wt(t)}:`}function Ae(){if(!Gt){Gt=!0;for(let e of[()=>localStorage,()=>sessionStorage]){let t;try{if(t=e(),!t)continue;for(let n of Object.keys(t))for(let[r,o]of Object.entries(Rr)){if(n!==o&&!n.startsWith(`${o}:`))continue;let s=Qe[r]+n.slice(o.length);t.getItem(s)===null&&t.setItem(s,t.getItem(n)),t.removeItem(n)}}catch{}}}}var tt=1800*1e3,ke=()=>{try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}},et=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}};function Jt(e,t=()=>Date.now()){return{read(){try{let n=ke()?.getItem(e),r=n?JSON.parse(n):null;return!r||t()-r.savedAt>tt?(r&&ke()?.removeItem(e),{items:[],anonymousId:null}):{items:Array.isArray(r.items)?r.items:[],anonymousId:typeof r.anonymousId=="string"?r.anonymousId:null}}catch{return{items:[],anonymousId:null}}},write(n,r=null){try{n.length===0?ke()?.removeItem(e):ke()?.setItem(e,JSON.stringify({savedAt:t(),items:n,anonymousId:r}))}catch{}}}}var Mr=400*24*60*60;function Q(e,t,n,r){if(typeof document>"u")return!1;try{let o=typeof location<"u"&&location.protocol==="https:"?"; Secure":"",s=r?`; Domain=${r}`:"",i=n===null?"":`; Max-Age=${n}`;return document.cookie=`${e}=${encodeURIComponent(t)}; Path=/${i}; SameSite=Lax`+s+o,!0}catch{return!1}}function Ur({name:e,domain:t=null,legacyKey:n,read:r,mint:o,mayStore:s,carried:i=null}){let a=null;try{a=et()?.getItem(n)||null}catch{a=null}let u=r(e)??a??i,d=!1,p=()=>{if(!(d||u===null||!s())&&(d=Q(e,u,Mr,t),!(!d||a===null)))try{et()?.removeItem(n),a=null}catch{}};return{get(){return u??(u=o()),p(),u},peek:()=>u,persist:p,forget(){Q(e,"",0,t),u=null,d=!1;try{et()?.removeItem(n)}catch{}a=null}}}function Xt(e,{carried:t=null,mayStore:n,orOwn:r=!1}){let o=e.anonymousIdSource,s=()=>Ur({name:O("anonymousId"),domain:e.consentCookieDomain??null,legacyKey:q(O("anonymousId"),e.propertyId),read:U,mint:Z,mayStore:n,carried:t});if(o?.source==="hp_cookie"){let u=s();return e.getAnonymousId=()=>u.get(),u}if(o?.source==="site_cookie"&&o.cookie){let u=o.cookie;e.getAnonymousId=()=>U(u)}if(!r)return null;let i=e.getAnonymousId,a=s();return e.getAnonymousId=()=>B(M(i,null))??a.get(),a}var $r=200;function Yt(e,t,n=()=>Date.now()){let r=()=>q(O("carried"),e),o=!1;function s(){try{let i=JSON.parse(sessionStorage.getItem(r())??"null");return!i||!(n()-i.savedAt<=tt)?[]:Array.isArray(i.calls)?i.calls:[]}catch{return[]}}return{take(){let i=s();try{sessionStorage.removeItem(r())}catch{}return i},save(i){try{return o||!t()?!1:(sessionStorage.setItem(r(),JSON.stringify({savedAt:n(),calls:[...s(),...i].slice(-$r)})),!0)}catch{return!1}},close(){o=!0}}}var Fs=re.consent,ve=Object.freeze({visitor:"visitor",host:"host"}),Zt=()=>({basis:ve.host}),Vr="hp-consent",oe=["analytics","marketing","personalisation","ad_user_data","ad_personalization"],Qt={analytics:"a",marketing:"m",personalisation:"p",ad_user_data:"aud",ad_personalization:"adp"},X=()=>typeof window<"u",en=()=>X()&&typeof window.cookieStore?.addEventListener=="function",jr=e=>e===!0?!0:e===!1?!1:null;function ce(e){if(!e||typeof e!="object")return null;let t={};for(let n of oe)t[n]=jr(e[n]);return t}function rt(e,t){return!e||!t?e===t:oe.every(n=>e[n]===t[n])}function ot(e){if(!e)return"";let t=[];for(let n of oe){let r=e[n];(r===!0||r===!1)&&t.push(`${Qt[n]}=${r?1:0}`)}return t.join("&")}function tn(e){return{[Vr]:ot(ce(e))}}function ye(e){let t=ce({});if(e==null)return t;let n=String(e).trim();if(n.length>=2&&n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1)),n.includes("%"))try{n=decodeURIComponent(n.replace(/\+/g," "))}catch{return t}let r=Object.fromEntries(Object.entries(Qt).map(([s,i])=>[i,s])),o=new Set;for(let s of n.split("&")){let i=s.indexOf("=");if(i<=0)continue;let a=r[s.slice(0,i).trim()],u={1:!0,0:!1}[s.slice(i+1).trim()]??null;!a||u===null||o.has(a)||(t[a]===null?t[a]=u:t[a]!==u&&(t[a]=null,o.add(a)))}return t}function st(e,t){if(!t)return e;let n=r=>{if(!r)return r;let o={...r};for(let s of oe)s!=="analytics"&&t[s]!==!0&&(o[s]=null);return o};return{name:e.name,basis:e.basis,read:()=>n(e.read()),subscribe:r=>e.subscribe(o=>r(n(o))),get observesChanges(){return e.observesChanges}}}function it(e,t={}){return{...e,ad_user_data:t.ad_user_data??e.marketing,ad_personalization:t.ad_personalization??e.marketing}}function Ee(e,t){let n=!0;return{notify:()=>{if(n)try{let o=e();o&&t(o)}catch{}},stop:()=>n=!1}}var Br={analytics:["analytics","measure_content_performance","audience_measurement"],marketing:["marketing","targeting","advertising","select_personalized_ads","create_ads_profile"],personalisation:["personalisation","personalization","select_personalized_content","create_content_profile"]};function qr(e,t){if(!t?.length)return null;let n=!1;for(let[r,o]of Object.entries(e)){let s=String(o?.id??r).toLowerCase();if(t.some(a=>{let u=String(a).toLowerCase();return s===u||s.startsWith(`${u}-`)})&&(n=!0,o?.enabled===!0))return!0}return n?!1:null}function nn(e={}){let t={...Br,...e.purposes};function n(){let r=X()?window.Didomi:void 0;if(!r?.getCurrentUserStatus||r.shouldUserStatusBeCollected?.()!==!1||r.isUserStatusPartial?.()===!0)return null;let o=r.getCurrentUserStatus()?.purposes;if(!o||typeof o!="object")return null;let s=i=>qr(o,t[i]);return it({analytics:s("analytics"),marketing:s("marketing"),personalisation:s("personalisation")},{ad_user_data:s("ad_user_data"),ad_personalization:s("ad_personalization")})}return{name:"didomi",read:n,observesChanges:!0,subscribe(r){if(!X())return()=>{};let o=Ee(n,r),s={event:"consent.changed",listener:o.notify};return window.didomiEventListeners=window.didomiEventListeners||[],window.didomiEventListeners.push(s),window.didomiOnReady=window.didomiOnReady||[],window.didomiOnReady.push(i=>{o.notify(),(i??window.Didomi)?.on?.("consent.changed",o.notify)}),window.Didomi?.on?.("consent.changed",o.notify),o.stop}}}function nt(e){let t={};if(!e)return t;for(let n of String(e).split("&")){let r=n.indexOf("=");if(r<=0)continue;let o=n.slice(r+1).replace(/\+/g," ");try{o=decodeURIComponent(o)}catch{}t[n.slice(0,r)]=o}return t}function rn(e={}){let t={analytics:"C0002",personalisation:"C0003",marketing:"C0004",...e.groups},n=e.impliedConsent===!0;function r(){let i=X()?window.OnetrustActiveGroups:void 0;if(typeof i=="string"&&i.length){let d=new Set(i.split(",").map(p=>p.trim()).filter(Boolean));return p=>d.has(p)}let a=nt(U("OptanonConsent"));if(!a.groups)return null;let u={};for(let d of a.groups.split(",")){let[p,f]=d.split(":");p?.trim()&&(u[p.trim()]=f==="1"?!0:f==="0"?!1:null)}return d=>u[d]??null}function o(){if(U("OptanonAlertBoxClosed"))return!0;try{if(X()&&window.OneTrust?.IsAlertBoxClosed?.()===!0)return!0}catch{}return Number.parseInt(nt(U("OptanonConsent")).interactionCount,10)>0?!0:n&&X()&&(!!window.OneTrust||typeof window.OnetrustActiveGroups=="string")}function s(){if(!o())return null;let i=r();if(!i)return null;let a=f=>t[f]?i(t[f]):null,u=it({analytics:a("analytics"),marketing:a("marketing"),personalisation:a("personalisation")},{ad_user_data:a("ad_user_data"),ad_personalization:a("ad_personalization")}),d=nt(U("OptanonConsent"));return(typeof navigator<"u"&&navigator.globalPrivacyControl===!0||d.isGpcEnabled==="1")&&(u.marketing=!1,u.ad_user_data=!1,u.ad_personalization=!1),u}return{name:"onetrust",read:s,observesChanges:!0,subscribe(i){if(!X())return()=>{};let a=Ee(s,i),u=!1,d=()=>{u||!window.OneTrust?.OnConsentChanged||(u=!0,window.OneTrust.OnConsentChanged(a.notify))};window.addEventListener("OneTrustGroupsUpdated",a.notify);let p=window.OptanonWrapper;return window.OptanonWrapper=function(...m){try{typeof p=="function"&&p.apply(this,m)}finally{d(),a.notify()}},d(),()=>{a.stop(),window.removeEventListener("OneTrustGroupsUpdated",a.notify)}}}}function Fr(e){let t=String(e).split(",").map(n=>n.trim()).filter(Boolean);return t.length?new Set(t):null}function on(e){let{name:t,categories:n,parse:r=Fr,refusedValue:o,source:s="native",changeEvent:i="thg_hp_consent_change"}=e??{};if(typeof t!="string"||t==="")throw new Error("cookieConsent: `name` (the cookie your banner writes) is required");if(!n||typeof n.analytics!="string")throw new Error("cookieConsent: `categories.analytics` (the category id that grants analytics) is required");function a(){let u=U(t);if(u==null)return null;let d;if(o!==void 0&&u===o)d=new Set;else try{d=r(u)}catch{d=null}if(!(d instanceof Set))return null;let p=f=>n[f]?d.has(n[f]):null;return it({analytics:p("analytics"),marketing:p("marketing"),personalisation:p("personalisation")},{ad_user_data:p("ad_user_data"),ad_personalization:p("ad_personalization")})}return{name:s,read:a,get observesChanges(){return en()},subscribe(u){if(!X())return()=>{};let d=Ee(a,u),p=f=>{[...f.changed??[],...f.deleted??[]].some(b=>b?.name===t)&&d.notify()};return window.addEventListener(i,d.notify),window.cookieStore?.addEventListener?.("change",p),()=>{d.stop(),window.removeEventListener(i,d.notify),window.cookieStore?.removeEventListener?.("change",p)}}}}function sn(e={}){let t=e.name??O("consent"),n=()=>{let r=U(t);if(r==null)return null;let o=ye(r);return o.analytics==null?null:o};return{name:"forwarded",read:n,get observesChanges(){return en()},subscribe(r){if(!X())return()=>{};let o=Ee(n,r),s=i=>{[...i.changed??[],...i.deleted??[]].some(u=>u?.name===t)&&o.notify()};return window.cookieStore?.addEventListener?.("change",s),()=>{o.stop(),window.cookieStore?.removeEventListener?.("change",s)}}}}function an(e){let t=ce(e);return{name:"static",basis:ve.host,read:()=>t?{...t}:null,observesChanges:!0,subscribe:()=>()=>{}}}function cn(e){if(e==null)return null;let t=String(e).split("/").map(n=>n.trim()).filter(Boolean).join("/");return t===""?null:t}function Hr(e){let t=e.item_category;if(t!=null&&String(t).includes("/"))return cn(t);let n=[t,e.item_category2,e.item_category3,e.item_category4,e.item_category5].map(r=>r==null?"":String(r).trim()).filter(Boolean);return cn(n.join("/"))}var Kr=e=>{if(e==null||typeof e=="object")return null;let t=String(e).trim();return t===""?null:t};function Gr(...e){for(let t of e){if(typeof t=="number"&&Number.isFinite(t))return String(t);if(typeof t=="string"&&t.trim()!=="")return t.trim()}return null}var Ce=e=>Gr(e.item_group_id,e.item_id);function Wr(e,t=Ce){if(!e)return null;let n=a=>a==null||a===""||Number.isNaN(Number(a))?null:Number(a),r=a=>{let u=n(a);return u==null?null:Math.round(u*1e6)/1e6},o=a=>{let u=r(a);return u!=null&&u>=0?u:null},s=a=>{let u=n(a);return Number.isInteger(u)&&u>=0?u:null},i=Kr;return{product_id:i(t(e)),sku:i(e.item_id),name:i(e.item_name),brand:i(e.item_brand),variant:i(e.item_variant)??i(e.variant),category:Hr(e),price:r(e.price),discount:o(e.discount),quantity:s(e.quantity),coupon:i(e.coupon),position:s(e.index)!=null?s(e.index)+1:null,url:i(e.url)??i(e.item_url)??null,image_url:i(e.image_url)??i(e.image_link)??null,displayed_sku:i(e.displayed_sku)??i(e.displayed_variant_sku)}}function at(e,t=Ce){return(e??[]).map(n=>Wr(n,t)).filter(n=>n?.product_id)}var zr=1e3,Jr={shipping:2,payment:3},Xr=new Set(["password","google","apple","facebook","magic_link","sso","passkey","other"]),$=e=>{if(e==null||typeof e=="object")return null;let t=String(e).trim();return t===""?null:t},Yr=e=>{if(e==null||e===""||typeof e=="object")return null;let t=Number(e);return Number.isFinite(t)&&t>=0?t:null},Pe=e=>e!==null&&typeof e=="object";function Zr(e){return Array.isArray(e.items)?e.items.filter(Pe):null}function un(e){let t=$(e)?.toLowerCase().replace(/[\s-]+/g,"_");return t?Xr.has(t)?t:t==="email"||t==="email_password"?"password":"other":null}function Qr({ecommerce:e,items:t}){let n=s=>({promotion_id:$(s.promotion_id),name:$(s.promotion_name),creative:$(s.creative_name),position:$(s.creative_slot)}),r=new Set,o=[];for(let s of[n(e),...t.map(n)])!s.promotion_id||r.has(s.promotion_id)||(r.add(s.promotion_id),o.push(s));return o}var ln=({ecommerce:e,items:t})=>$(e.item_list_id)??$(e.item_list_name)??$(t[0]?.item_list_id)??$(t[0]?.item_list_name),se=(e,t)=>t.products?.length?{event:e,properties:t}:null,eo=new Set(["product","products","item","items"]);function to({ecommerce:e}){let t=$(e.item_id),n=$(e.content_type)?.toLowerCase();return!t||n&&!eo.has(n)?null:{event:"Product Shared",properties:{share_via:$(e.method),products:[{product_id:t}]}}}function no(e){let t=o=>se("Product List Viewed",{list_id:ln(o),products:o.products}),n=o=>{let s=$(o.ecommerce.search_term);return s?{event:"Products Searched",properties:{query:s,...o.products.length?{products:o.products}:{}}}:null},r=o=>s=>s.promotions.map(i=>({event:o,properties:i}));return{view_item:o=>se("Product Viewed",{currency:o.currency,value:o.value,products:o.products.slice(0,1)}),view_item_list:t,view_search_results:o=>n(o)??t(o),search:n,select_item:o=>se("Product Clicked",{list_id:ln(o),products:o.products.slice(0,1)}),add_to_cart:o=>se("Product Added",{cart_id:$(o.ecommerce.cart_id),products:o.products}),remove_from_cart:o=>se("Product Removed",{cart_id:$(o.ecommerce.cart_id),products:o.products}),view_cart:o=>({event:"Cart Viewed",properties:{cart_id:$(o.ecommerce.cart_id),value:o.value,currency:o.currency,coupon:$(o.ecommerce.coupon),...o.itemsListed?{products:o.products}:{}}}),begin_checkout:o=>se("Checkout Started",{value:o.value,currency:o.currency,coupon:$(o.ecommerce.coupon),products:o.products}),add_shipping_info:o=>({event:"Checkout Step Completed",properties:{step:e.shipping,step_name:"shipping",shipping_method:$(o.ecommerce.shipping_tier)}}),add_payment_info:o=>({event:"Payment Info Entered",properties:{step:e.payment,step_name:"payment",payment_method:$(o.ecommerce.payment_type)}}),view_promotion:r("Promotion Viewed"),select_promotion:r("Promotion Clicked"),add_to_wishlist:o=>se("Product Added to Wishlist",{products:o.products}),share:to,login:o=>({event:"Signed In",properties:{method:un(o.ecommerce.method)}}),sign_up:o=>({event:"Signed Up",properties:{method:un(o.ecommerce.method)}})}}var ro=e=>e.event;function oo(e,t){if(!Pe(e))return null;if(typeof e.length=="number"&&e[0]==="event"&&typeof e[1]=="string"){let r=Pe(e[2])?e[2]:{};return{name:e[1],entry:r,ecommerce:r}}let n=$(t(e));return n?{name:n,entry:e,ecommerce:Pe(e.ecommerce)?e.ecommerce:e}:null}function ct(e){return Array.isArray(e)?`[${e.map(ct).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ct(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function dn(e,t={}){if(!e||typeof e.track!="function")throw new Error("connectDataLayer: analytics must have a track(event, properties, options) method");let n=t.dataLayer??(typeof window<"u"?window.dataLayer=window.dataLayer||[]:null);if(!Array.isArray(n))return()=>{};let r=no({...Jr,...t.steps}),o=t.map??{},s=t.eventName??ro,i=t.productId??Ce,a=new Set(["purchase","refund",...t.ignore??[]]),u=t.dedupeMs??zr,d=new Map,p=!0;function f(S,y,w){if(u<=0)return!1;let L=`${S}|${w??""}|${ct(y)}`,D=Date.now();for(let[H,K]of d)D-K>u&&d.delete(H);return d.has(L)?!0:(d.set(L,D),!1)}let m=null,b=new Set;function g(S,y){if(S!=="Product Viewed")return!1;let w=typeof location>"u"?"":location.pathname;w!==m&&(m=w,b.clear());let L=y.products?.[0]?.product_id;return L?b.has(L)?!0:(b.add(L),!1):!1}function _({event:S,properties:y={}},w){if(!S||f(S,y,w)||g(S,y))return;let L=w?{context:{currency:w}}:void 0;if(S==="Signed Out"&&typeof e.signedOut=="function"){e.signedOut(L);return}e.track(S,y,L)}function x(S){let y=t.transform?t.transform(S):S,w=oo(y,s);if(!w||a.has(w.name))return;let L=Object.hasOwn(o,w.name),D=L?o[w.name]:r[w.name];if(typeof D!="function")return;let H=Zr(w.ecommerce),K=H??[],F={...w,items:K,itemsListed:H!==null,products:at(K,i),currency:Ze(w.ecommerce.currency),value:Yr(w.ecommerce.value)};F.promotions=Qr(F);let I=L?D(y,{...F,toProducts:G=>at(G,i)}):D(F);for(let G of[I].flat())G&&_(G,F.currency)}function v(S){if(p)try{x(S)}catch(y){try{t.onError?.(y,S)}catch{}}}for(let S of n.slice())v(S);let h=n.push;function E(...S){let y=h.apply(this,S);for(let w of S)v(w);return y}return n.push=E,()=>{p=!1,n.push===E&&(n.push=h)}}var so="hp_debug",io=256;function ao(){try{return new URLSearchParams(location.search).get(so)}catch{return null}}function fn(e,t){if(typeof location>"u")return!1;try{let n=ao();if(n!==null){let o=n.trim();o===""||o.length>io?sessionStorage.removeItem(t):sessionStorage.setItem(t,o)}let r=sessionStorage.getItem(t);return!!(e&&r&&Nt(r)===e)}catch{return!1}}var co=4320*60*60,uo=100,lo=1e3,fo=2e3,pn=500,Le=e=>(e?.unref?.(),e);function po(e,t){if(t?.analytics===!0&&e.analytics===!1)return"withdrawn";let n=oe.map(r=>e[r]).filter(r=>r!==null);return n.length&&n.every(Boolean)?"accept_all":n.length&&n.every(r=>!r)?"reject_all":"custom"}function mo(e,t,n=O("consent")){if(!(typeof document>"u"))try{let r=typeof location<"u"&&location.protocol==="https:"?"; Secure":"",o=t?`; Domain=${t}`:"";document.cookie=`${n}=${ot(e)}; Path=/; Max-Age=${co}; SameSite=Lax`+o+r}catch{}}function ho(e){let t=ye(U(e));return oe.some(n=>t[n]!==null)?t:null}function mn(e){let{adapter:t,timeoutMs:n=5e3,cookieDomain:r=null,cookieName:o=O("consent"),release:s,announce:i}=e,a=e.discard??(()=>{}),u="pending",d=null,p=null,f=null,m=null,b=!1,g=null,_=[],x=R=>{u=R,e.onStatus?.(R)};function v(){try{return ce(t.read())}catch{return null}}function h(){p&&clearInterval(p),f&&clearTimeout(f),p=null,f=null}let E=()=>typeof window<"u"&&typeof document<"u",S=()=>{try{return typeof t.subscribe=="function"&&t.observesChanges===!0}catch{return!1}};function y(){m&&clearInterval(m),m=null}function w(){b||m||d===null||S()||E()&&document.visibilityState==="hidden"||(m=Le(setInterval(()=>F(v()),fo)))}let L=()=>u==="pending"||u==="unknown",D=e.store??null,H=()=>{let R=_.splice(0);D?.write([]);for(let j of R)s(j)},K=()=>{let R=_.splice(0);D?.write([]);for(let j of R)a(j)};function F(R){let j=ce(R);if(!j||j.analytics===null)return;let c=d===null,l=c?ho(o):d;if(!c&&rt(l,j))return;h(),d=j,w(),mo(j,r,o);let k=!rt(l,j);if(j.analytics){x("granted"),H(),k&&i({action:po(j,l),state:j,withdrawal:!1});return}K(),l?.analytics===!0&&i({action:"withdrawn",state:j,withdrawal:!0}),x("denied")}function I(){f=null,u==="pending"&&(x("unknown"),p&&clearInterval(p),p=Le(setInterval(()=>F(v()),lo)))}function G(R){L()&&(D||R?.type!=="visibilitychange"&&!R?.persisted&&K())}let we=R=>{document.visibilityState==="hidden"?(y(),G(R)):w()},me=R=>{y(),G(R)},he=()=>w();return{get status(){return u},get state(){return d?{...d}:null},stamp(){return d?{...d,source:t.name??null,basis:t.basis??ve.visitor}:null},admits(){return u==="granted"},hold(R){return!L()||_.length>=pn?(a(R),!1):(_.push(R),D?.write(_),!0)},onHidden:G,start(){b=!1;try{g=t.subscribe?.(R=>F(R))??null}catch(R){e.debug&&console.warn("[hp] consent adapter subscribe failed",R)}E()&&(window.addEventListener("pagehide",me),window.addEventListener("pageshow",he),document.addEventListener("visibilitychange",we)),D&&_.length===0&&_.push(...D.read().slice(-pn)),F(v()),!d&&(p=Le(setInterval(()=>F(v()),uo)),f=Le(setTimeout(I,n)))},stop(){b=!0,h(),y(),typeof g=="function"&&g(),E()&&(window.removeEventListener("pagehide",me),window.removeEventListener("pageshow",he),document.removeEventListener("visibilitychange",we))}}}var go=["recommendation","search_rank","banner","offer","layout","copy","price","other"],Oe=e=>typeof e=="string"&&e!=="";function hn(e){return(Array.isArray(e?.decisions)?e.decisions:[]).filter(t=>Oe(t?.slot)&&Oe(t.decision_id)&&t.holdout!==!0).map(({decision_id:t,slot:n,arm:r,kind:o})=>({decision_id:t,slot:n,...Oe(r)&&{arm:r},...go.includes(o)&&{kind:o}}))}function gn({key:e,mayStore:t}){let n,r=()=>{if(n)return n;try{let s=JSON.parse(sessionStorage.getItem(e));n=Array.isArray(s)?s.filter(i=>Oe(i?.slot)):[]}catch{n=[]}return n},o=()=>{try{n?.length&&t()&&sessionStorage.setItem(e,JSON.stringify(n))}catch{}};return{persist:o,current:()=>r().length?n.map(s=>({...s})):null,remember(s){if(!s.length)return;let i=new Set(s.map(a=>a.slot));n=[...r().filter(a=>!i.has(a.slot)),...s],o()},forget(){n=[];try{sessionStorage.removeItem(e)}catch{}}}}function yo(e){let t=2166136261,n=String(e);for(let r=0;r<n.length;r+=1)t^=n.charCodeAt(r),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t^=t>>>16,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t>>>0}function Ne(e,t,n=1e4){return yo(`${t}\0${e}`)%n}function ut(e){let t=o=>Math.min(Math.max(Number(o)||0,0),1),n=t(e.share),r=1-n;return{holdout_share:n,personalised_share:e.ramp==null?r:Math.min(t(e.ramp),r)}}function lt(e,t){if(!e||typeof e.salt!="string")return{holdout:!1,bucket:null,group:"personalised"};let n=e.ramp!=null;if(t==null||t==="")return{holdout:!1,bucket:null,group:n?"excluded":"personalised"};let{holdout_share:r,personalised_share:o}=ut(e),s=Ne(t,e.salt),i=u=>Math.round(u*1e4),a=r>0&&s<i(r)?"holdout":!n||s<i(r+o)?"personalised":"excluded";return{holdout:a==="holdout",bucket:s,group:a}}function yn(e,t){return typeof e!="string"||e===""||t==null||t===""?null:Ne(t,`bandit-vs-default:${e}`)<1e4/2?"default":"bandit"}var So="hp_preview",wo=256;function Sn(e,t=null){if(typeof location>"u")return U(e);let n=null;try{n=new URLSearchParams(location.search).get(So)}catch{n=null}if(n===null)return U(e);let r=n.trim();return r===""||r.length>wo?(Q(e,"",0,t),null):(Q(e,r,null,t),r)}var _o=40,bo=128,xo=5,Io=60,_n=e=>typeof e=="string"&&e!==""&&e.length<=bo&&!e.includes(","),wn=e=>Array.isArray(e)?e.filter(_n).slice(0,_o):[],Ao=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.replaceAll(","," ").trim()).filter(t=>t!=="").slice(0,xo):[],ko=e=>Object.entries(e&&typeof e=="object"?e:{}).filter(([t,n])=>_n(t)&&Number.isFinite(n)&&n>=1).sort(([,t],[,n])=>n-t).slice(0,Io).map(([t,n])=>`${t}:${Math.floor(n)}`);function dt(e){let t={},n={viewed:wn(e?.recentProducts),basket:wn(e?.basketProducts),q:Ao(e?.recentSearches),impressed:ko(e?.impressions)};for(let[r,o]of Object.entries(n))o.length>0&&(t[r]=o.join(","));return t}var vo=1800*1e3;function bn(e,t=Date.now()){try{localStorage.setItem(O("recommendationContext"),JSON.stringify({context:e,until:t+vo}))}catch{}}function xn(){try{localStorage.removeItem(O("recommendationContext"))}catch{}}var Eo="hp_sample",In=1e4;function An(e,t){return!(typeof t=="number"&&t<1)||e==null||e===""?!0:Ne(e,Eo,In)<Math.round(t*In)}function ft(e){return e.trim().toLowerCase().replace(/\s*\/\s*/g,"/").replace(/^\/+|\/+$/g,"")}var Co=2,Po=12;function Lo(e,t=Co){return e.split("/").slice(0,t).join("/")}function ue(e,t){if(typeof t!="string"||!t.trim())return null;let n=Lo(ft(t));return n?(e.unshift(n),e.length=Math.min(e.length,Po),n):null}var ie=()=>O("sessionSignals"),le=null,pt=()=>le??ie();function kn(){try{return le?localStorage:sessionStorage}catch{return}}function vn(e,t){let n=t==null?null:String(t),r=e?q(ie(),n,e):null;if(r===le)return;let o=le===null?Oo():null;if(le=r,!!le)try{let s=pt(),i=zt(ie(),n);for(let a of Object.keys(localStorage))a.startsWith(i)&&a!==s&&localStorage.removeItem(a);o&&!localStorage.getItem(s)&&(localStorage.setItem(s,JSON.stringify(o)),sessionStorage.removeItem(ie()))}catch{}}function Oo(){try{let e=sessionStorage.getItem(ie());if(!e)return null;let t=JSON.parse(e);return t&&(t.productViews>0||t.listViews>0||t.basketValue!=null||t.recentProducts?.length||t.recentBrowse?.length)?t:null}catch{return null}}function Te(){return{productViews:0,listViews:0,cartAdds:0,searches:0,recentProducts:[],recentCategories:[],recentBrowse:[],basketProducts:[],basketValue:null,recentSearches:[],impressions:{},browsingCategory:null,startedAt:0}}function mt(){let e=kn();if(!e)return Te();try{let t=e.getItem(pt());return t?{...Te(),...JSON.parse(t)}:{...Te(),startedAt:Date.now()}}catch{return{...Te(),startedAt:Date.now()}}}function ht(e){let t=kn();if(t)try{t.setItem(pt(),JSON.stringify(e))}catch{}}function En(){return mt()}function Cn(){for(let e of[()=>sessionStorage,()=>localStorage])try{let t=e();t.removeItem(ie());for(let n of Object.keys(t))n.startsWith(`${ie()}:`)&&t.removeItem(n)}catch{}}var Pn=20,Ln=200,No=new Set(["Product Viewed","Product Clicked","Product Added","Product Added to Wishlist"]),To=new Set(["Product Clicked","Product Added to Wishlist"]);function On(e,t){let n=mt();n.startedAt||(n.startedAt=Date.now());let r=Array.isArray(t?.products)?t.products:[];switch(e){case"Product Viewed":n.productViews+=1,ue(n.recentBrowse,n.browsingCategory);break;case"Product List Viewed":n.listViews+=1;{let i=t?.list_id;typeof i=="string"&&i.includes("/")&&!i.startsWith("cdp-")&&(n.browsingCategory=ue(n.recentBrowse,i)??n.browsingCategory)}break;case"Product List Filtered":{let i=t?.change,a=typeof t?.list_id=="string"?t.list_id:"",u=typeof i?.value=="string"?i.value:"";u&&i?.action!=="removed"&&(n.browsingCategory=ue(n.recentBrowse,`${a}/${u}`)??n.browsingCategory);break}case"Product Added":{n.cartAdds+=1,ue(n.recentBrowse,n.browsingCategory);for(let i of r){let a=i.product_id;typeof a!="string"||!a||(n.basketProducts=[a,...n.basketProducts.filter(u=>u!==a)].slice(0,Pn))}break}case"Product Removed":{for(let i of r){let a=i.product_id;typeof a=="string"&&a&&(n.basketProducts=n.basketProducts.filter(u=>u!==a))}break}case"Products Searched":{n.searches+=1;let i=t?.query;if(typeof i=="string"&&i.trim()){let a=i.trim().toLowerCase().slice(0,64);n.recentSearches=[a,...n.recentSearches.filter(u=>u!==a)].slice(0,5)}break}case"Product Clicked":case"Product Added to Wishlist":break;case"Cart Updated":{let i=t?.value;return n.basketValue=typeof i=="number"&&Number.isFinite(i)&&i>=0?i:null,ht(n),n}default:return n}let o=No.has(e);if(o)for(let i of r)typeof i.product_id=="string"&&i.product_id&&delete n.impressions[i.product_id];else{for(let a of r){let u=a.product_id;typeof u!="string"||!u||(n.impressions[u]=(n.impressions[u]??0)+1)}let i=Object.keys(n.impressions);if(i.length>Ln){let a={};for(let u of i.sort((d,p)=>n.impressions[p]-n.impressions[d]).slice(0,Ln))a[u]=n.impressions[u];n.impressions=a}}let s=new Set;for(let i of r){let a=i.product_id;if(o&&typeof a=="string"&&a&&(n.recentProducts=[a,...n.recentProducts.filter(u=>u!==a)].slice(0,Pn)),!To.has(e)&&typeof i.category=="string"&&i.category){let u=ft(i.category);u&&!s.has(u)&&(s.add(u),ue(n.recentCategories,u))}}return ht(n),n}var Nn=1800*1e3;function Tn({name:e,domain:t=null,mayStore:n,now:r=()=>Date.now(),mint:o=Z}){let s=null,i=0,a=()=>{s!==null&&n()&&Q(e,s,Nn/1e3,t)};return{get(){let u=r(),d=U(e);return d?s=d:(s===null||u-i>=Nn)&&(s=o()),i=u,a(),s},persist:a,forget(){Q(e,"",0,t),s=null}}}var J=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Rn=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),yt=Object.freeze({enabled:!1});function Dn(e,t){let n=e?.track;return J(n)?(Object.hasOwn(n,t)?n[t]:n.__default)?.enabled!==!1:!0}function Ro(e,t){return`${de(e)}/v1/projects/${encodeURIComponent(t)}/settings`}var Do="https://hp.thgingenuity.com";function de(e){return e==null||e===""?Do:Mn(e)}function Mn(e){if(typeof e!="string")return null;let t=e.trim().replace(/\/+$/,"");return/^https?:\/\/[^/\s]+$/i.test(t)?t:/^[a-z0-9.-]+(:\d+)?$/i.test(t)?`https://${t}`:null}function Mo(e){if(!J(e))return null;let t=Object.fromEntries(Object.entries(e).filter(([,n])=>typeof n=="boolean"));return Object.keys(t).length?t:null}var gt=e=>typeof e=="number"&&e>=0&&e<=1,Uo=/^[0-9a-f]{64}$/;function $o(e){return J(e)?{enabled:e.enabled===!0,tokenSha256:typeof e.tokenSha256=="string"&&Uo.test(e.tokenSha256)?e.tokenSha256:null}:{enabled:!1,tokenSha256:null}}function Vo(e){if(!J(e))return null;let t=Object.fromEntries(Object.entries(e).filter(([,n])=>J(n)&>(n.share)&&(n.ramp==null||gt(n.ramp))&&typeof n.salt=="string"&&n.salt!=="").map(([n,r])=>[n,{share:r.share,ramp:r.ramp??null,salt:r.salt,...Rn(r.readoutSlots)&&r.readoutSlots.length>0&&{readoutSlots:r.readoutSlots}}]));return Object.keys(t).length?t:null}var jo=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;function Bo(e){return J(e)?e.source==="hp_cookie"?{source:"hp_cookie"}:e.source!=="site_cookie"?null:e.cookie==null?{source:"site_cookie",cookie:null}:typeof e.cookie=="string"&&jo.test(e.cookie)?{source:"site_cookie",cookie:e.cookie}:null:null}function St(e){let t=J(e)?e.hp:null;return!J(t)||t.enabled!==!0?yt:{enabled:!0,propertyId:typeof t.propertyId=="string"&&t.propertyId!==""?t.propertyId:null,environment:typeof t.environment=="string"?t.environment:null,consentPurposes:Mo(t.consent?.purposes),queryParamAllowlist:Rn(t.queryParamAllowlist)?t.queryParamAllowlist:null,anonymousId:Bo(t.anonymousId),apiHost:Mn(t.apiHost),holdouts:Vo(t.holdouts),sampleRate:gt(t.sampleRate)?t.sampleRate:1,debug:$o(t.debug),plan:J(e.plan)&&J(e.plan.track)?{track:e.plan.track}:null}}async function Un(e,t,n=globalThis.fetch){try{let r=await n(Ro(e,t),{credentials:"omit",headers:{accept:"application/json"}});return r.ok?St(await r.json()):null}catch{return null}}var Re=e=>q(O("settings"),e);function $n(e){try{let t=localStorage.getItem(Re(e));if(!t)return null;let n=JSON.parse(t);return n?.enabled===!0?n:null}catch{return null}}function Vn(e,t){try{t?.enabled===!0?localStorage.setItem(Re(e),JSON.stringify(t)):localStorage.removeItem(Re(e))}catch{}}function wt(e){try{localStorage.removeItem(Re(e))}catch{}}var qo={flushAt:20,flushIntervalMs:1e4,maxQueue:500,maxRetryAgeMs:1440*60*1e3,maxRetries:5,maxPersistedBatches:20,maxPersistedBytes:1024*1024,storageKey:re.retry,beaconSafeBytes:56*1024,maxBatchEvents:100,maxBatchBytes:500*1024},_t=()=>Date.now(),fe=e=>typeof TextEncoder<"u"?new TextEncoder().encode(e).length:Buffer.byteLength(e),bt=()=>typeof window<"u"&&typeof document<"u";function Fo(){try{return!bt()||!window.localStorage?null:(window.localStorage.getItem("thg_hp_probe"),window.localStorage)}catch{return null}}var A,xt,jn,De,It,At,Bn,Se,kt,Me,qn,vt,Fn,Ue,$e=class{constructor(t){Lt(this,A);this.o={...qo,...t},this.queue=[],this.timer=null,this.storage=Fo(),this.inflight=null,this.sending=new Set,this.replayAllowed=!this.o.deferReplay,this.draining=null,bt()&&(window.addEventListener("pagehide",()=>this.flush({beacon:!0})),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flush()}),N(this,A,Ue).call(this))}replayPersisted(){return this.replayAllowed=!0,N(this,A,Ue).call(this)}clearPersisted(){if(this.replayAllowed=!1,!!this.storage)try{this.storage.removeItem(this.o.storageKey)}catch{}}enqueue(t){let n;try{n=JSON.parse(JSON.stringify(t))}catch(r){this.o.onError?.(`event ${t?.messageId??""} cannot be serialised; dropped`,r);return}this.queue.push(n),this.queue.length>this.o.maxQueue&&this.queue.splice(0,this.queue.length-this.o.maxQueue),this.queue.length>=this.o.flushAt?this.flush():N(this,A,xt).call(this)}flush(t={}){if(N(this,A,jn).call(this),this.queue.length===0)return Promise.resolve();if(t.beacon&&bt()&&typeof navigator<"u"&&navigator.sendBeacon)return N(this,A,Bn).call(this),Promise.resolve();if(this.inflight)return this.inflight;let n=N(this,A,At).call(this,this.queue,this.o.maxBatchEvents,this.o.maxBatchBytes).map(r=>{let o=N(this,A,vt).call(this,r);return o&&this.sending.add(o),{batch:r,id:o}});return this.queue=[],this.inflight=(async()=>{for(let{batch:r,id:o}of n)await N(this,A,Se).call(this,r,0,o)})().finally(()=>{this.inflight=null,this.queue.length>=this.o.flushAt?this.flush():this.queue.length&&N(this,A,xt).call(this)}),this.inflight}};A=new WeakSet,xt=function(){this.timer||(this.timer=setTimeout(()=>this.flush(),this.o.flushIntervalMs),this.timer?.unref?.())},jn=function(){this.timer&&(clearTimeout(this.timer),this.timer=null)},De=function(t){return JSON.stringify({batch:t,writeKey:this.o.writeKey,sentAt:new Date().toISOString()})},It=function(){return`${this.o.apiHost.replace(/\/$/,"")}/v1/batch`},At=function(t,n,r){let o=fe(N(this,A,De).call(this,[])),s=[],i=[],a=o;for(let u of t){let d=fe(JSON.stringify(u))+1;i.length&&(i.length>=n||a+d>r)&&(s.push(i),i=[],a=o),i.push(u),a+=d}return i.length&&s.push(i),s},Bn=function(){let t=this.queue;this.queue=[];let n=N(this,A,It).call(this);for(let r of N(this,A,At).call(this,t,this.o.maxBatchEvents,this.o.beaconSafeBytes)){let o=N(this,A,De).call(this,r);if(fe(o)<=this.o.beaconSafeBytes){let s=!1;try{s=navigator.sendBeacon(n,new Blob([o],{type:"text/plain"}))}catch{s=!1}if(s)continue}N(this,A,Se).call(this,r,0,N(this,A,vt).call(this,r))}},Se=async function(t,n,r=null){r&&this.sending.add(r);let o=N(this,A,De).call(this,t);try{let s=await fetch(N(this,A,It).call(this),{method:"POST",headers:{"Content-Type":"text/plain"},body:o,keepalive:fe(o)<=this.o.beaconSafeBytes});if(s.ok)return N(this,A,kt).call(this,r),N(this,A,Ue).call(this),!0;if(!(s.status===429||s.status>=500))return N(this,A,kt).call(this,r),this.o.onError?.(`CDP ingest rejected batch (${s.status}); dropping ${t.length} events`),!0;throw new Error(`retryable ${s.status}`)}catch(s){if(n>=this.o.maxRetries){r&&this.sending.delete(r);let a=r?"kept for the next page":"dropped";return this.o.onError?.(`CDP ingest unreachable after ${n} attempts; ${a}: ${t.length} events`,s),!1}let i=Math.min(1e3*2**n,3e4)*(.5+Math.random());return await new Promise(a=>setTimeout(a,i)),N(this,A,Se).call(this,t,n+1,r)}},kt=function(t){t&&(this.sending.delete(t),N(this,A,Fn).call(this,t))},Me=function(){let t=JSON.parse(this.storage.getItem(this.o.storageKey)||"[]");return Array.isArray(t)?t:[]},qn=function(t,n){let r=i=>fe(JSON.stringify(i))+1,o=[...t,n].slice(-this.o.maxPersistedBatches),s=o.reduce((i,a)=>i+r(a),2);for(;o.length>1&&s>this.o.maxPersistedBytes;)s-=r(o[0]),o=o.slice(1);for(;o.length;)try{return this.storage.setItem(this.o.storageKey,JSON.stringify(o)),!0}catch{o=o.slice(1)}return!1},vt=function(t){if(!this.storage||this.o.mayPersist&&!this.o.mayPersist())return null;try{let n={at:_t(),id:`${_t()}-${Math.random().toString(36).slice(2)}`,batch:t};return fe(JSON.stringify(n))+3>this.o.maxPersistedBytes?null:N(this,A,qn).call(this,N(this,A,Me).call(this),n)?n.id:null}catch{return null}},Fn=function(t){if(!(!t||!this.storage))try{let n=N(this,A,Me).call(this).filter(r=>r.id!==t);n.length?this.storage.setItem(this.o.storageKey,JSON.stringify(n)):this.storage.removeItem(this.o.storageKey)}catch{}},Ue=function(){if(!this.storage||!this.replayAllowed)return this.draining??Promise.resolve();if(this.draining)return this.draining;let t;try{let r=N(this,A,Me).call(this);t=r.filter(o=>Array.isArray(o?.batch)&&_t()-o.at<this.o.maxRetryAgeMs).map(o=>o.id?o:{...o,id:`${o.at}-${Math.random().toString(36).slice(2)}`}),(t.length!==r.length||t.some((o,s)=>o!==r[s]))&&(t.length?this.storage.setItem(this.o.storageKey,JSON.stringify(t)):this.storage.removeItem(this.o.storageKey))}catch{return Promise.resolve()}let n=t.filter(r=>!this.sending.has(r.id));return n.length?(this.draining=(async()=>{for(let r of n)if(!this.replayAllowed||!await N(this,A,Se).call(this,r.batch,0,r.id))return})().finally(()=>{this.draining=null}),this.draining):Promise.resolve()};var Hn="3.18.0",Kn="@thg-agentic/hyper-personalisation-web";var Ho=new Set(["audiences","decisions","recommendations"]);var Ko=Symbol.for("@thg-agentic/hyper-personalisation-web.replay"),Ve=class extends Error{};function Go(e){let t={...e??{}},n=Array.isArray(t.products)?t.products:null;if(t.item_count==null&&n){let r=n.map(o=>o?.quantity);r.every(Number.isInteger)&&(t.item_count=r.reduce((o,s)=>o+s,0))}return t}var Wo="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";function zo(e){if(/^[0-9a-fA-F]{64}$/.test(e))return e.toLowerCase();if(!/^[A-Za-z0-9+/_-]{43}=?$/.test(e))return null;try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(44,"="));return t.length!==32?null:Array.from(t,n=>n.charCodeAt(0).toString(16).padStart(2,"0")).join("")}catch{return null}}function je(e){if(typeof e!="string")return null;let t=zo(e.trim());return t===Wo?null:t}var Gn=!1;function Jo(e){!e||Gn||(Gn=!0,console.warn("[hp] mintAnonymousId is ignored since 3.6: where device ids come from is set per source in the console (the site\u2019s own cookie, or Hyper-Personalisation\u2019s)."))}function Wn(e){return e&&typeof e.context=="object"&&e.context!==null?e.context:e}function zn(e){let t=de(e?.apiHost);if(!t)throw new Error("createAnalytics: apiHost, when given, must be a host or an http(s) origin");if(!e?.propertyId)throw new Error("createAnalytics: propertyId is required");let n={libraryName:Kn,libraryVersion:Hn,writeKey:"web",queryParamBlocklist:[],debug:!1,validate:null,consentTimeoutMs:5e3,...e,apiHost:t};Ie(n.storageNames),Ae();let r=!!n.consent,o=null;n.getConsent=()=>o?o.stamp():Zt();let s=()=>!r||o?.status==="granted",i=r&&n.holdAcrossPages?Jt(q(O("held"),n.propertyId)):null,a=i?.read()??{items:[],anonymousId:null};n.mintAnonymousId!==void 0&&Jo(n.debug);let u=Xt(n,{carried:a.anonymousId,mayStore:s,orOwn:!0}),d=Tn({name:O("session"),domain:n.consentCookieDomain??null,mayStore:s}),p=n.getSessionId;n.getSessionId=()=>B(M(p,null))??d.get();let f=Sn(O("preview"),n.consentCookieDomain??null),m=n.transport??new $e({apiHost:n.apiHost,writeKey:n.writeKey,storageKey:q(O("retry"),n.propertyId),mayPersist:r?()=>o?.status==="granted":void 0,deferReplay:r,onError:(c,l)=>n.debug&&console.warn("[hp]",c,l??"")}),b=q(O("previousPage"),n.propertyId),g=null,_=()=>{if(g)return g;try{return sessionStorage.getItem(b)||null}catch{return null}},x=c=>{if(g=c||null,!(r&&o.status!=="granted"))try{sessionStorage.setItem(b,c)}catch{}},v=gn({key:q(O("decisions"),n.propertyId),mayStore:s});n.getDecisions??(n.getDecisions=v.current);let h=B(M(n.getUserId,null)),E=null;function S(c,l,k=!1){try{return y(c,l,k)}catch(P){if(P instanceof Ve)throw P;return console.warn("[hp] the event was not sent",P),null}}function y(c,l,k){let P=E;E=null;let C={messageId:P?.messageId??Z(),timestamp:P?.timestamp??new Date().toISOString(),anonymousId:B(M(n.getAnonymousId,null)),userId:h??null,...c,context:Ht(n,Wn(l))};if(C.properties&&(C.properties=Xe(C.properties)),!k&&!An(C.anonymousId,n.sampleRate))return n.debug&&console.debug("[hp] not sent: outside the sample",C),null;if(n.beforeSend){let W;try{W=n.beforeSend(C)}catch(sr){return console.warn("[hp] beforeSend failed; the event was not sent",sr),null}if(!W)return null;let{type:_e,event:Ct,messageId:rr,timestamp:or}=C;C={...W,type:_e,messageId:rr,timestamp:or,...Ct?{event:Ct}:{}}}if(n.validate){let W=n.validate(C,{producer:"web"});if(!W.valid){let _e=`[hp] invalid ${C.event??C.type}:
|
|
2
|
+
${W.errors.join(`
|
|
3
|
+
`)}`;if(n.throwOnInvalid)throw new Ve(_e);console.error(_e)}}return n.debug&&console.debug("[hp]",C.event??C.type,C),F(C,k),C}function w(c){if(c.type==="track"&&K(c),n.onEvent)try{n.onEvent(c)}catch(l){console.warn("[hp] onEvent observer failed",l)}}let L=()=>r&&o?.state?.personalisation===!0,D=()=>vn(M(n.getSessionId,null),n.propertyId),H=!1;function K(c){try{L()?(D(),bn(dt(On(c.event,c.properties))),H=!0):(xn(),H&&Cn(),H=!1)}catch(l){n.debug&&console.warn("[hp] the visit was not recorded",l)}}function F(c,l){!r||l||o.admits()?(w(c),m.enqueue(c)):o.hold(c)}let I=(c,l,k)=>Dn(n.plan,c)?S({type:"track",event:c,properties:l??{}},k):null,G=new Set,we=(c,l,k)=>c==="audiences"?{audiences:l?null:k.audiences??[]}:c==="decisions"?{decisions:(k.decisions??[]).map(P=>({slot:P.slot,decision_id:P.decision_id??null,arm:P.arm??null,...P.variant&&{variant:P.variant}}))}:{recommendation_request_id:k.recommendation_request_id??null};r&&(o=mn({adapter:n.consent,timeoutMs:n.consentTimeoutMs,cookieDomain:n.consentCookieDomain,debug:n.debug,store:i&&{read:()=>a.items,write:c=>i.write(c,u?.peek()??null)},release(c){c.context&&(c.context.consent=o.stamp()),w(c),m.enqueue(c)},onStatus(c){if(c==="granted"&&(u?.persist(),d.persist(),g&&x(g),v.persist(),m.replayPersisted?.()),c==="denied"){m.clearPersisted?.(),u?.forget(),d.forget();try{sessionStorage.removeItem(b)}catch{}v.forget()}try{n.onConsentStatus?.(c)}catch(l){console.warn("[hp] onConsentStatus observer failed",l)}},announce({action:c,state:l,withdrawal:k}){S({type:"track",event:"Consent Updated",properties:{action:c,state:l}},void 0,k),k&&m.flush()}}),o.start());let me=()=>n.holdout?ut(n.holdout):null,he=()=>lt(n.holdout,B(M(n.getAnonymousId,null))).group;function R(c,l){if(!Array.isArray(c?.decisions))return c;let k=n.holdout?.readoutSlots??[],P=B(M(n.getAnonymousId,null));return{...c,decisions:c.decisions.map(C=>{let W=C?.variant==="bandit"||C?.variant==="default"?C.variant:!l&&C?.holdout!==!0&&k.includes(C?.slot)?yn(C.slot,P):null;return W?W==="default"?{...C,variant:W,decision_id:null}:{...C,variant:W}:C})}}function j(c,l){if(f)return null;let k=c?.exposure,P=k?.holdout===!0,C=R(c,P);return v.remember(hn(C)),!k?.token||G.has(k.token)?null:(G.add(k.token),I("Personalisation Exposed",{exposure_token:k.token,surface:k.surface,holdout:P,holdout_share:k.holdout_share??me()?.holdout_share??null,personalised_share:k.personalised_share??me()?.personalised_share??null,...we(k.surface,P,C)},l))}return{track:I,page(c={},l){let k=n.pageType??null;c.type&&(ae.has(c.type)?(k=c.type,n.pageType=c.type):n.debug&&console.warn(`[hp] ignoring unknown page.type "${c.type}". Allowed: ${[...ae].join(", ")}`));let P=S({type:"page",properties:{name:c.name??null,navigation_trigger:c.navigation_trigger??Vt(),previous_message_id:_()}},{page:{type:k},...Wn(l)??{}});return P&&x(P.messageId),P},identify(c,l){let{userId:k,...P}=c&&typeof c=="object"?c:{};if(k!==void 0&&(h=B(k)),typeof P.email_sha256=="string"){let C=je(P.email_sha256);C?P.email_sha256=C:delete P.email_sha256}return S({type:"identify",traits:P},l)},reset(){h=null,x("")},productViewed:(c,l)=>I("Product Viewed",c,l),productListViewed:(c,l)=>I("Product List Viewed",c,l),recommendationsViewed:(c,l)=>I("Recommendations Viewed",c,l),personalisationExposed:(c,l)=>I("Personalisation Exposed",c,l),recordExposure:j,surfaceViewed({surface:c}={},l){if(!Ho.has(c)||!n.holdout||c!=="decisions"&&!L())return null;let k=B(M(n.getAnonymousId,null)),P=lt(n.holdout,k).group;if(P==="excluded")return null;let C=Mt({sessionId:be(M(n.getSessionId,null),k),surface:c});return C?j({exposure:{token:C,surface:c,holdout:P==="holdout"}},l):null},inHoldout:()=>he()!=="personalised",personalisationGroup:he,productClicked:(c,l)=>I("Product Clicked",c,l),productListFiltered:(c,l)=>I("Product List Filtered",c,l),productsSearched:(c,l)=>I("Products Searched",c,l),productAdded:(c,l)=>I("Product Added",c,l),productRemoved:(c,l)=>I("Product Removed",c,l),cartUpdated:(c,l)=>I("Cart Updated",Go(c),l),identityLinked:(c,l)=>I("Identity Linked",c,l),slotEngaged:(c,l)=>f?null:I("Slot Engaged",c,l),productVariantSelected:(c,l)=>I("Product Variant Selected",c,l),cartViewed:(c,l)=>I("Cart Viewed",c,l),productAddedToWishlist:(c,l)=>I("Product Added to Wishlist",c,l),productRemovedFromWishlist:(c,l)=>I("Product Removed from Wishlist",c,l),wishlistProductAddedToCart:(c,l)=>I("Wishlist Product Added to Cart",c,l),productShared:(c,l)=>I("Product Shared",c,l),cartShared:(c,l)=>I("Cart Shared",c,l),couponEntered:(c,l)=>I("Coupon Entered",c,l),couponApplied:(c,l)=>I("Coupon Applied",c,l),couponDenied:(c,l)=>I("Coupon Denied",c,l),couponRemoved:(c,l)=>I("Coupon Removed",c,l),checkoutStarted:(c,l)=>I("Checkout Started",c,l),promotionViewed:(c,l)=>I("Promotion Viewed",c,l),promotionClicked:(c,l)=>I("Promotion Clicked",c,l),checkoutStepViewed:(c,l)=>I("Checkout Step Viewed",c,l),checkoutStepCompleted:(c,l)=>I("Checkout Step Completed",c,l),paymentInfoEntered:(c,l)=>I("Payment Info Entered",c,l),checkoutFailed:(c,l)=>I("Checkout Failed",c,l),signedIn:(c,l)=>I("Signed In",c,l),signedUp:(c,l)=>I("Signed Up",c,l),signedOut(c){let l=I("Signed Out",{},c);return h=null,l},newsletterSubscribed:(c,l)=>I("Newsletter Subscribed",c,l),newsletterUnsubscribed:(c,l)=>I("Newsletter Unsubscribed",c,l),backInStockSubscribed:(c,l)=>I("Back In Stock Subscribed",c,l),productReviewed:(c,l)=>I("Product Reviewed",c,l),consentUpdated:(c,l)=>I("Consent Updated",c,l),flush:c=>m.flush(c),recommendationContext(){if(!L())return{};try{return D(),dt(En())}catch{return{}}},get consent(){return o?o.state:null},servingHeaders:()=>tn(o?.state??null),get lastPageMessageId(){return _()},get anonymousId(){return B(M(n.getAnonymousId,null))},[Ko](c,l,k){if(typeof this[c]=="function"){E=typeof k?.messageId=="string"&&typeof k?.timestamp=="string"?{messageId:k.messageId,timestamp:k.timestamp}:null;try{this[c](...Array.isArray(l)?l:[])}finally{E=null}}}}}var Et=Symbol.for("@thg-agentic/hyper-personalisation-web.bootstrap"),Xo=Symbol.for("@thg-agentic/hyper-personalisation-web.drain"),Yo=Symbol.for("@thg-agentic/hyper-personalisation-web.carry"),Jn=Symbol.for("@thg-agentic/hyper-personalisation-web.replay"),Zo=Symbol.for("@thg-agentic/hyper-personalisation-web.assignment"),Qo=Symbol.for("@thg-agentic/hyper-personalisation-web.recommendation-context"),Fe=e=>e?()=>U(e):()=>null,Zn={didomi:e=>nn({purposes:e.purposes}),onetrust:e=>rn({groups:e.groups,impliedConsent:e.impliedConsent}),cookie:e=>on({name:e.name,categories:e.categories,refusedValue:e.refusedValue,source:e.source,changeEvent:e.changeEvent}),forwarded:e=>sn({name:e.name}),static:e=>{if(!e.state||typeof e.state!="object")throw new Error('consent.state is required for provider "static"');return an(e.state)}},Xn=Object.keys(Zn),pe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Be=e=>typeof e=="string"&&e!=="",es=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Qn=e=>pe(e)&&typeof e.read=="function";function ts(e,t={}){let n=[];if(!pe(e))return["config must be { writeKey, apiHost? }"];Be(e.writeKey)||n.push("writeKey is required"),de(e.apiHost)||n.push("apiHost, when given, must be a host or an http(s) origin"),t.propertyId!==void 0&&!Be(t.propertyId)&&n.push("propertyId must be a string");let{consent:r}=t;if(!Qn(r)&&!(pe(r)&&Xn.includes(r.provider))&&n.push(`consent must be a consent adapter or { provider: ${Xn.join(" | ")} }`),t.autocapture!==void 0&&t.autocapture!==!1&&!pe(t.autocapture)&&n.push("autocapture must be false or { promotions, productLists, recommendations }"),t.beforeSend!==void 0&&typeof t.beforeSend!="function"&&n.push("beforeSend must be a function"),t.identityCookies!==void 0)if(!pe(t.identityCookies))n.push("identityCookies must be an object");else for(let o of["anonymousId","sessionId"]){let s=t.identityCookies[o];s!==void 0&&!Be(s)&&n.push(`identityCookies.${o} must be a cookie name`)}for(let o of["getCurrency","getShipToCountry","getLocale"])t[o]!==void 0&&typeof t[o]!="function"&&n.push(`${o} must be a function`);return t.dataLayer!==void 0&&(pe(t.dataLayer)?(t.dataLayer.name!==void 0&&!Be(t.dataLayer.name)&&n.push("dataLayer.name must be a string"),t.dataLayer.ignore!==void 0&&!es(t.dataLayer.ignore)&&n.push("dataLayer.ignore must be an array of strings")):n.push("dataLayer must be an object")),n}function ns(e,t,n){if(Qn(e))return st(e,t.consentPurposes);let{provider:r,...o}=e,s=n?.consent?.[r]??Zn[r];return st(s(o),t.consentPurposes)}var er=(e,t)=>`${e??""}|${t??""}`;function rs(e,t){let n=B(t?.userId),r=je(t?.emailSha256);if(!n&&!r)return null;try{let o=q(O("identified"),e);if(sessionStorage.getItem(o)===er(n,r))return null}catch{}return{...n?{userId:n}:{},...r?{email_sha256:r}:{}}}async function os({writeKey:e,apiHost:t},n){if(n.settings!==void 0)return{settings:St(n.settings),revalidated:null};let r=Un(t,e),o=$n(e);if(o)return{settings:o,revalidated:r};let s=await r,i=s??yt;return{settings:i,revalidated:Promise.resolve(i),unreachable:s===null}}function tr(e,t={}){let n=typeof window<"u"?window:null;if(n?.[Et])return n[Et];let r=Yt(e?.writeKey,()=>{let{analytics:s}=ye(U(O("consent")));return s===!0||s===null&&t.holdAcrossPages===!0}),o=is(e,t,r);if(n){let s=t.extend?.getSessionId??Fe(t.identityCookies?.sessionId),i=Fe(t.identityCookies?.anonymousId);n[Zo]=({slot:a,arm:u}={})=>Dt({sessionId:be(s(),i()),slot:a,arm:u}),n[Et]=o,n[Yo]=r,n[Xo]?.(o)}return o}function ss(){let e=globalThis.performance?.now?.();return new Date(Date.now()-(Number.isFinite(e)?e:0)).toISOString()}function Yn(e,t){if(t===!1)return()=>{};let n={promotions:!0,productLists:!0,recommendations:!0,exposures:!0,...t},r=s=>s&&typeof s=="object"?s:{},o=[];try{n.promotions&&o.push(We(e,r(n.promotions))),n.productLists&&o.push(Ge(e,r(n.productLists))),n.recommendations&&o.push(ze(e,r(n.recommendations))),n.exposures&&o.push(Ke(e,r(n.exposures)))}catch(s){console.warn("[hp] autocapture not started:",s?.message??s)}return()=>{for(let s of o)s()}}function qe(e){return e.close(),null}async function is(e,t,n){try{let r=ts(e,t);if(r.length)return console.warn(`[hp] not started, the configuration is invalid: ${r.join("; ")}`),qe(n);Ie(t.storageNames),Ae();let{writeKey:o}=e,[{settings:s,revalidated:i,unreachable:a},u]=await Promise.all([os(e,t),Promise.resolve(t.identity).catch(()=>null)]),d=i?s:null,p=!1,f=()=>p&&d&&Vn(o,d);if(i?.then(y=>{y&&(d=y,y.enabled?f():wt(o))}),a)return null;if(!s.enabled)return t.debug&&console.info("[hp] off: the settings for this write key do not enable it"),qe(n);let m=s.propertyId??t.propertyId;if(!m)return console.warn("[hp] not started: this write key covers several properties, so propertyId is required"),qe(n);let{preset:b}=t,g=rs(m,u),_=t.debug===!0||s.debug?.enabled===!0||fn(s.debug?.tokenSha256??null,O("debug")),x=B(u?.userId),v=zn({apiHost:s.apiHost??de(e.apiHost),writeKey:o,propertyId:m,pageType:ae.has(t.pageType)?t.pageType:void 0,environment:s.environment,queryParamAllowlist:s.queryParamAllowlist??void 0,plan:s.plan,sampleRate:s.sampleRate??1,holdout:s.holdouts?.[m],getCurrency:t.getCurrency,getShipToCountry:t.getShipToCountry,getLocale:t.getLocale,consent:ns(t.consent,s,b),consentCookieDomain:t.consentCookieDomain,storageNames:t.storageNames,holdAcrossPages:t.holdAcrossPages===!0,mintAnonymousId:t.mintAnonymousId,debug:_,anonymousIdSource:s.anonymousId??void 0,getAnonymousId:Fe(t.identityCookies?.anonymousId),getSessionId:t.identityCookies?.sessionId?Fe(t.identityCookies.sessionId):void 0,getUserId:()=>x,beforeSend:t.beforeSend,...t.extend,onConsentStatus(y){if(y==="granted"&&(p=!0,f()),y==="denied"){wt(o);try{sessionStorage.removeItem(q(O("identified"),m))}catch{}}t.extend?.onConsentStatus?.(y)},onEvent(y){if(y.type==="identify"){let w=er(B(y.userId),je(y.traits?.email_sha256));try{sessionStorage.setItem(q(O("identified"),m),w)}catch{}}t.extend?.onEvent?.(y)}});typeof window<"u"&&(window[Qo]=()=>v.recommendationContext());for(let[y,w,L]of n.take())try{v[Jn](y,w,L)}catch(D){console.warn(`[hp] carried ${y} failed`,D)}v[Jn]("page",[t.pageType?{type:t.pageType}:{}],{messageId:Z(),timestamp:ss()});let h=Yn(v,t.autocapture),E=v.page;v.page=(...y)=>{let w=E(...y);return h(),h=Yn(v,t.autocapture),w};let S=typeof window<"u"?window:null;if(t.dataLayer&&S){let y=t.dataLayer.name??"dataLayer";S[y]=S[y]||[],dn(v,{...b,dataLayer:S[y],ignore:[...b?.ignore??[],...t.dataLayer.ignore??[]],onError:w=>_&&console.warn("[hp] dataLayer mapping failed",w)})}return g&&v.identify(g),v}catch(r){return console.warn("[hp] not started:",r?.message??r),qe(n)}}function nr(e){e.initialized=!0,tr(e._config,e._options).then(t=>{let n=e.splice(0);if(!t){for(let r of e.methods??[])e[r]=()=>e;return}e.client=t;for(let[r,o]of Object.entries(t))typeof o=="function"&&(e[r]=o);for(let[r,...o]of n)try{t[r]?.(...o)}catch(s){console.warn(`[hp] queued ${r} failed`,s)}})}var V=window.hp=window.hp||[];V.servingHeaders??(V.servingHeaders=()=>({}));V.inHoldout??(V.inHoldout=()=>!0);V.personalisationGroup??(V.personalisationGroup=()=>"excluded");V.recommendationContext??(V.recommendationContext=()=>({}));V.initialized||(V._config?nr(V):V.load=(e,t)=>{V._config=e,V._options=t??{},nr(V)});})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{(()=>{let e=window.hp=window.hp||[];if(!(e.initialized||e.invoked)){e.invoked=!0,e.methods=["track","page","identify","reset","flush","productViewed","productListViewed","recommendationsViewed","personalisationExposed","recordExposure","surfaceViewed","productClicked","productListFiltered","productsSearched","productAdded","productRemoved","cartUpdated","identityLinked","slotEngaged","productVariantSelected","cartViewed","productAddedToWishlist","productRemovedFromWishlist","wishlistProductAddedToCart","productShared","cartShared","couponEntered","couponApplied","couponDenied","couponRemoved","checkoutStarted","promotionViewed","promotionClicked","checkoutStepViewed","checkoutStepCompleted","paymentInfoEntered","checkoutFailed","signedIn","signedUp","signedOut","newsletterSubscribed","newsletterUnsubscribed","backInStockSubscribed","productReviewed","consentUpdated"],e.factory=t=>(...o)=>(e.push([t,...o]),e);for(let t of e.methods)e[t]=e.factory(t);e.servingHeaders=()=>({}),e.inHoldout=()=>!0,e.personalisationGroup=()=>"excluded",e.recommendationContext=()=>({}),e.load=(t,o,r)=>{e._config=t,e._options=o||{};let d=document.createElement("script");d.async=!0,d.src=r;let i=document.getElementsByTagName("script")[0];i.parentNode.insertBefore(d,i)},e.SNIPPET_VERSION="1",e.load({writeKey:"hp_pk_live_REPLACE_ME",apiHost:"https://api.example.com"},{consent:{provider:"onetrust"},identityCookies:{sessionId:"session_id"}},"https://cdn.jsdelivr.net/npm/@thg-agentic/hyper-personalisation-web@3/dist/hp.min.js")}})();})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,86 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@thg-agentic/hyper-personalisation-web",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "3.18.0",
|
|
4
|
+
"description": "Browser SDK for the THG Hyper-Personalisation event specification: event tracking from a write key and remote settings, strict CMP-agnostic consent, a GA4 dataLayer bridge and in-session audience evaluation. Dependency-free ESM on the Segment wire protocol, a CDN script (dist/hp.min.js), and an optional @segment/analytics-next plugin path.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"types": "./types/index.d.ts",
|
|
8
|
+
"unpkg": "./dist/hp.min.js",
|
|
9
|
+
"jsdelivr": "./dist/hp.min.js",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./types/index.d.ts",
|
|
13
|
+
"default": "./src/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./consent": {
|
|
16
|
+
"types": "./types/consent.d.ts",
|
|
17
|
+
"default": "./src/consent.js"
|
|
18
|
+
},
|
|
19
|
+
"./datalayer": {
|
|
20
|
+
"types": "./types/datalayer.d.ts",
|
|
21
|
+
"default": "./src/datalayer.js"
|
|
22
|
+
},
|
|
23
|
+
"./segment": {
|
|
24
|
+
"types": "./types/segment.d.ts",
|
|
25
|
+
"default": "./src/segment.js"
|
|
26
|
+
},
|
|
27
|
+
"./bootstrap": {
|
|
28
|
+
"types": "./types/bootstrap.d.ts",
|
|
29
|
+
"default": "./src/bootstrap.js"
|
|
30
|
+
},
|
|
31
|
+
"./hp": {
|
|
32
|
+
"types": "./types/hp.d.ts",
|
|
33
|
+
"default": "./src/hp.js"
|
|
34
|
+
},
|
|
35
|
+
"./auto": {
|
|
36
|
+
"types": "./types/auto.d.ts",
|
|
37
|
+
"default": "./src/auto.js"
|
|
38
|
+
},
|
|
39
|
+
"./session": "./src/session.js",
|
|
40
|
+
"./experiments": "./src/experiments.js",
|
|
41
|
+
"./conformance": "./src/conformance.js"
|
|
42
|
+
},
|
|
43
|
+
"files": [
|
|
44
|
+
"src/",
|
|
45
|
+
"types/**/*.d.ts",
|
|
46
|
+
"dist/hp.min.js",
|
|
47
|
+
"dist/snippet.min.js"
|
|
48
|
+
],
|
|
49
|
+
"sideEffects": false,
|
|
50
|
+
"license": "MIT",
|
|
51
|
+
"repository": {
|
|
52
|
+
"type": "git",
|
|
53
|
+
"url": "git+https://github.com/THG-Commerce/hyper-personalisation.git",
|
|
54
|
+
"directory": "sdks/web"
|
|
55
|
+
},
|
|
56
|
+
"publishConfig": {
|
|
57
|
+
"access": "public"
|
|
58
|
+
},
|
|
59
|
+
"//peerDependencies": [
|
|
60
|
+
"OPTIONAL PEER, NOT A DEPENDENCY. The default delivery path is src/transport.js, which imports",
|
|
61
|
+
"nothing. Only the opt-in ./segment entry point runs inside analytics-next, and it never imports",
|
|
62
|
+
"it: the host passes cdpPlugins() to its own AnalyticsBrowser, so there is exactly one copy."
|
|
63
|
+
],
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"@segment/analytics-next": "^1.84.1"
|
|
66
|
+
},
|
|
67
|
+
"peerDependenciesMeta": {
|
|
68
|
+
"@segment/analytics-next": {
|
|
69
|
+
"optional": true
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
"devDependencies": {
|
|
73
|
+
"@segment/analytics-next": "1.84.3",
|
|
74
|
+
"esbuild": "^0.28.2",
|
|
75
|
+
"jsdom": "^30.1.1",
|
|
76
|
+
"typescript": "^7.0.2",
|
|
77
|
+
"@thg-agentic/hyper-personalisation-spec": "1.10.0"
|
|
78
|
+
},
|
|
79
|
+
"scripts": {
|
|
80
|
+
"test": "node --test tests/*.test.mjs",
|
|
81
|
+
"build": "node scripts/build-cdn.mjs",
|
|
82
|
+
"build:types": "node scripts/build-types.mjs",
|
|
83
|
+
"pack": "pnpm pack --pack-destination dist",
|
|
84
|
+
"check:types": "tsc -p types/tsconfig.json"
|
|
85
|
+
}
|
|
6
86
|
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `decision_id` of a server-side assignment (`POST /v1/assignments`), derived rather than
|
|
3
|
+
* minted, so a page cached per arm, not per visitor, can still name the decision it showed.
|
|
4
|
+
*
|
|
5
|
+
* decision_id = UUIDv5(ASSIGNMENT_DECISION_NAMESPACE, `${session_id}:${slot}:${arm}`)
|
|
6
|
+
*
|
|
7
|
+
* `session_id` is the session HP assigned under: the renderer's session id, or, with none, the
|
|
8
|
+
* visitor id. HP logs the assignment's `Decision Made` under this id, and the page reports
|
|
9
|
+
* `Slot Engaged` with the same one, so the reward joins on `decision_id` as for any decision.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { sha1 } from './hash.js';
|
|
13
|
+
|
|
14
|
+
/** HP's fixed namespace for assignment decision ids. Never changes: every id ever logged uses it. */
|
|
15
|
+
export const ASSIGNMENT_DECISION_NAMESPACE =
|
|
16
|
+
'e28e8ada-5b76-4209-bba9-79b823a0af75';
|
|
17
|
+
|
|
18
|
+
const hex = (bytes) =>
|
|
19
|
+
Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
20
|
+
|
|
21
|
+
/** A name-based UUID, version 5 (RFC 9562 §5.5). */
|
|
22
|
+
export function uuidV5(namespace, name) {
|
|
23
|
+
const space = Uint8Array.from(
|
|
24
|
+
namespace.replace(/-/g, '').match(/../g),
|
|
25
|
+
(pair) => Number.parseInt(pair, 16),
|
|
26
|
+
);
|
|
27
|
+
const text = new TextEncoder().encode(name);
|
|
28
|
+
const input = new Uint8Array(16 + text.length);
|
|
29
|
+
input.set(space);
|
|
30
|
+
input.set(text, 16);
|
|
31
|
+
const bytes = sha1(input).slice(0, 16);
|
|
32
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x50;
|
|
33
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
34
|
+
const h = hex(bytes);
|
|
35
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A value HP takes as given: a non-empty string within its length limit. */
|
|
39
|
+
const given = (value, max) =>
|
|
40
|
+
typeof value === 'string' && value !== '' && value.length <= max
|
|
41
|
+
? value
|
|
42
|
+
: null;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The session HP assigns under, from what the renderer forwarded: the session id (at most 64
|
|
46
|
+
* characters), else the visitor id (at most 256). Null with neither: HP assigns nothing then.
|
|
47
|
+
*/
|
|
48
|
+
export function assignmentSession(sessionId, visitorId) {
|
|
49
|
+
return given(sessionId, 64) ?? given(visitorId, 256);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The `decision_id` HP logged for assigning `arm` to `slot` in `sessionId`. Null when any of the
|
|
54
|
+
* three is missing or empty.
|
|
55
|
+
*/
|
|
56
|
+
export function assignmentDecisionId({ sessionId, slot, arm } = {}) {
|
|
57
|
+
const session = given(sessionId, 256);
|
|
58
|
+
if (!session || !given(slot, 256) || !given(arm, 256)) return null;
|
|
59
|
+
return uuidV5(ASSIGNMENT_DECISION_NAMESPACE, `${session}:${slot}:${arm}`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** HP's fixed namespace for the exposure tokens a page derives itself. Never changes. */
|
|
63
|
+
export const SURFACE_EXPOSURE_NAMESPACE =
|
|
64
|
+
'4b1f2c7e-9a3d-4e58-b6c1-2d7f0a9e8c53';
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The token of the property holdout's exposure for `surface` in `sessionId`, for a surface the
|
|
68
|
+
* page saw rendered without its serving answer (a product rail the site's server fetched): one per session
|
|
69
|
+
* per surface, which is the grain the readout counts. Null without a session or a surface.
|
|
70
|
+
*/
|
|
71
|
+
export function surfaceExposureToken({ sessionId, surface } = {}) {
|
|
72
|
+
const session = given(sessionId, 256);
|
|
73
|
+
if (!session || !given(surface, 64)) return null;
|
|
74
|
+
return uuidV5(SURFACE_EXPOSURE_NAMESPACE, `${session}:${surface}`);
|
|
75
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Read the first non-empty dataset value among several candidate keys. */
|
|
2
|
+
export function firstAttr(el, ...keys) {
|
|
3
|
+
const data = el.dataset ?? {};
|
|
4
|
+
for (const key of keys) {
|
|
5
|
+
const value = data[key];
|
|
6
|
+
if (typeof value === 'string' && value.trim() !== '') return value.trim();
|
|
7
|
+
}
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function intAttr(el, ...keys) {
|
|
12
|
+
const raw = firstAttr(el, ...keys);
|
|
13
|
+
if (raw === null) return null;
|
|
14
|
+
const n = Number(raw);
|
|
15
|
+
return Number.isFinite(n) ? Math.trunc(n) : null;
|
|
16
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_DWELL_MS,
|
|
3
|
+
DEFAULT_VISIBLE_RATIO,
|
|
4
|
+
watchViewability,
|
|
5
|
+
} from './viewability.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Personalised surfaces described in markup: an element `data-hp-exposure="<surface>"`
|
|
9
|
+
* (`recommendations`, `decisions` or `audiences`) records the property holdout's exposure for that
|
|
10
|
+
* surface once it is viewable, through `surfaceViewed`. Mark the container the site renders for
|
|
11
|
+
* both groups, HP's content for a treated visitor and the default for a held-out one, so the two
|
|
12
|
+
* are counted on the same trigger. `surfaceViewed` decides the group and records one exposure per
|
|
13
|
+
* session per surface, so marking several elements, or the same one on every page, counts once.
|
|
14
|
+
*
|
|
15
|
+
* @param {{ surfaceViewed(fields: { surface: string }): unknown }} analytics
|
|
16
|
+
* @param {object} [options]
|
|
17
|
+
* @param {string} [options.selector]
|
|
18
|
+
* @param {number} [options.visibleRatio]
|
|
19
|
+
* @param {number} [options.dwellMs]
|
|
20
|
+
* @param {Document|Element} [options.root]
|
|
21
|
+
* @returns {() => void} Teardown, for a SPA route change.
|
|
22
|
+
*/
|
|
23
|
+
export function trackExposures(analytics, options = {}) {
|
|
24
|
+
if (typeof window === 'undefined' || typeof document === 'undefined')
|
|
25
|
+
return () => {};
|
|
26
|
+
|
|
27
|
+
const {
|
|
28
|
+
selector = '[data-hp-exposure]',
|
|
29
|
+
visibleRatio = DEFAULT_VISIBLE_RATIO,
|
|
30
|
+
dwellMs = DEFAULT_DWELL_MS,
|
|
31
|
+
root = document,
|
|
32
|
+
} = options;
|
|
33
|
+
|
|
34
|
+
return watchViewability({
|
|
35
|
+
selector,
|
|
36
|
+
root,
|
|
37
|
+
visibleRatio,
|
|
38
|
+
dwellMs,
|
|
39
|
+
onViewable(el) {
|
|
40
|
+
const surface = el.dataset?.hpExposure?.trim();
|
|
41
|
+
if (surface) analytics.surfaceViewed({ surface });
|
|
42
|
+
return true;
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_DWELL_MS,
|
|
3
|
+
DEFAULT_VISIBLE_RATIO,
|
|
4
|
+
watchViewability,
|
|
5
|
+
} from './viewability.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Product lists described in markup: a container `data-hp-list="<list id>"`, optionally
|
|
9
|
+
* `data-hp-list-category`, whose tiles carry `data-hp-product`, the spec product as JSON.
|
|
10
|
+
*
|
|
11
|
+
* - Product List Viewed, once per list id per page, when one of its tiles meets the viewability
|
|
12
|
+
* standard, carrying every tile in the list.
|
|
13
|
+
* - Product Clicked, for a click on a link inside a tile. A button inside one (quick buy, a
|
|
14
|
+
* wishlist heart, a colour swatch) is not a product click.
|
|
15
|
+
*
|
|
16
|
+
* A list the page reports itself, because only the page knows its pagination and filters, is
|
|
17
|
+
* marked `data-hp-list-view="manual"`: its clicks are still captured, its views are not.
|
|
18
|
+
*
|
|
19
|
+
* @param {object} analytics An SDK instance from createAnalytics.
|
|
20
|
+
* @param {object} [options]
|
|
21
|
+
* @param {string} [options.selector] Which elements are lists.
|
|
22
|
+
* @param {string} [options.tileSelector] Which elements inside a list are product tiles.
|
|
23
|
+
* @param {number} [options.visibleRatio]
|
|
24
|
+
* @param {number} [options.dwellMs]
|
|
25
|
+
* @param {Document|Element} [options.root]
|
|
26
|
+
* @returns {() => void} Teardown.
|
|
27
|
+
*/
|
|
28
|
+
const absolute = (value) => {
|
|
29
|
+
try {
|
|
30
|
+
return new URL(value, document.baseURI).toString();
|
|
31
|
+
} catch {
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export function trackProductLists(analytics, options = {}) {
|
|
37
|
+
if (typeof window === 'undefined' || typeof document === 'undefined')
|
|
38
|
+
return () => {};
|
|
39
|
+
|
|
40
|
+
const {
|
|
41
|
+
selector = '[data-hp-list]',
|
|
42
|
+
tileSelector = '[data-hp-product]',
|
|
43
|
+
visibleRatio = DEFAULT_VISIBLE_RATIO,
|
|
44
|
+
dwellMs = DEFAULT_DWELL_MS,
|
|
45
|
+
root = document,
|
|
46
|
+
} = options;
|
|
47
|
+
|
|
48
|
+
/** List ids already reported: a re-rendered carousel replaces nodes, not the list. */
|
|
49
|
+
const reported = new Set();
|
|
50
|
+
|
|
51
|
+
const listOf = (el) => el.closest?.(selector) ?? null;
|
|
52
|
+
|
|
53
|
+
const listFields = (list) => {
|
|
54
|
+
const id = list.dataset.hpList?.trim();
|
|
55
|
+
if (!id) return null;
|
|
56
|
+
return {
|
|
57
|
+
list_id: id,
|
|
58
|
+
category: list.dataset.hpListCategory?.trim() || null,
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// A tile's own list only: a carousel nested in a list does not lend it its tiles.
|
|
63
|
+
const tilesOf = (list) =>
|
|
64
|
+
Array.from(list.querySelectorAll(tileSelector)).filter(
|
|
65
|
+
(tile) => listOf(tile) === list,
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
const productOf = (tile, index) => {
|
|
69
|
+
try {
|
|
70
|
+
const product = JSON.parse(tile.dataset.hpProduct ?? '');
|
|
71
|
+
if (!product || typeof product !== 'object' || !product.product_id)
|
|
72
|
+
return null;
|
|
73
|
+
return {
|
|
74
|
+
...product,
|
|
75
|
+
position: product.position ?? index + 1,
|
|
76
|
+
// Markup rendered on a server may not know its own origin; the page does.
|
|
77
|
+
...(product.url ? { url: absolute(product.url) } : {}),
|
|
78
|
+
...(product.image_url
|
|
79
|
+
? { image_url: absolute(product.image_url) }
|
|
80
|
+
: {}),
|
|
81
|
+
};
|
|
82
|
+
} catch {
|
|
83
|
+
// One malformed tile must not stop the rest of the list reporting.
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const stopWatching = watchViewability({
|
|
89
|
+
selector: `${selector} ${tileSelector}`,
|
|
90
|
+
root,
|
|
91
|
+
visibleRatio,
|
|
92
|
+
dwellMs,
|
|
93
|
+
onViewable(tile) {
|
|
94
|
+
const list = listOf(tile);
|
|
95
|
+
if (!list || list.dataset.hpListView === 'manual') return true;
|
|
96
|
+
const fields = listFields(list);
|
|
97
|
+
if (!fields || reported.has(fields.list_id)) return true;
|
|
98
|
+
// A responsive page often renders a list twice, one layout hidden: a product is listed once.
|
|
99
|
+
const seen = new Set();
|
|
100
|
+
const products = tilesOf(list)
|
|
101
|
+
.map(productOf)
|
|
102
|
+
.filter((product) => {
|
|
103
|
+
if (!product || seen.has(product.product_id)) return false;
|
|
104
|
+
seen.add(product.product_id);
|
|
105
|
+
return true;
|
|
106
|
+
});
|
|
107
|
+
// An empty list would fail validation at the ingest.
|
|
108
|
+
if (products.length === 0) return true;
|
|
109
|
+
reported.add(fields.list_id);
|
|
110
|
+
analytics.productListViewed({ ...fields, products });
|
|
111
|
+
return true;
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
// Capture phase: tile components often stopPropagation, which would hide them from a bubble
|
|
116
|
+
// listener.
|
|
117
|
+
const onClick = (event) => {
|
|
118
|
+
const link = event.target?.closest?.('a[href]');
|
|
119
|
+
const tile = link?.closest(tileSelector);
|
|
120
|
+
if (!tile) return;
|
|
121
|
+
const list = listOf(tile);
|
|
122
|
+
const product = productOf(tile, list ? tilesOf(list).indexOf(tile) : 0);
|
|
123
|
+
if (!product) return;
|
|
124
|
+
analytics.productClicked({
|
|
125
|
+
list_id: list ? (listFields(list)?.list_id ?? null) : null,
|
|
126
|
+
products: [product],
|
|
127
|
+
});
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
document.addEventListener('click', onClick, true);
|
|
131
|
+
|
|
132
|
+
return () => {
|
|
133
|
+
document.removeEventListener('click', onClick, true);
|
|
134
|
+
stopWatching();
|
|
135
|
+
};
|
|
136
|
+
}
|