@treasuredata/web-sdk 1.0.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.
Files changed (50) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +807 -0
  4. package/dist/browser.d.ts +9 -0
  5. package/dist/checksums.txt +8 -0
  6. package/dist/core/config.d.ts +10 -0
  7. package/dist/core/config.template.d.ts +10 -0
  8. package/dist/core/configurator.d.ts +35 -0
  9. package/dist/core/sdk.d.ts +3 -0
  10. package/dist/index.d.ts +37 -0
  11. package/dist/init.d.ts +18 -0
  12. package/dist/loader.d.ts +59 -0
  13. package/dist/loader.js +1 -0
  14. package/dist/loader.min.js +1 -0
  15. package/dist/plugins/clicks.d.ts +21 -0
  16. package/dist/plugins/conversion-api.d.ts +23 -0
  17. package/dist/plugins/global-id.d.ts +17 -0
  18. package/dist/plugins/in-browser-message.d.ts +6 -0
  19. package/dist/plugins/page-personalize/bridge/constants.d.ts +9 -0
  20. package/dist/plugins/page-personalize/bridge/rpc.d.ts +15 -0
  21. package/dist/plugins/page-personalize/index.d.ts +34 -0
  22. package/dist/plugins/page-personalize/injection/inject.d.ts +17 -0
  23. package/dist/plugins/page-personalize/modes/preview.d.ts +3 -0
  24. package/dist/plugins/page-personalize/modes/spot-selection.d.ts +9 -0
  25. package/dist/plugins/page-personalize/offers.d.ts +72 -0
  26. package/dist/plugins/page-personalize/router.d.ts +17 -0
  27. package/dist/plugins/page-personalize/types.d.ts +27 -0
  28. package/dist/plugins/page-personalize/utils/selector-generator.d.ts +6 -0
  29. package/dist/plugins/personalization.d.ts +39 -0
  30. package/dist/plugins/record.d.ts +32 -0
  31. package/dist/plugins/server-cookie.d.ts +14 -0
  32. package/dist/plugins/session.d.ts +25 -0
  33. package/dist/plugins/track.d.ts +16 -0
  34. package/dist/plugins/utm.d.ts +16 -0
  35. package/dist/td-sdk.cjs +3263 -0
  36. package/dist/td-sdk.esm.js +3263 -0
  37. package/dist/td-sdk.esm.min.js +1 -0
  38. package/dist/td-sdk.js +3176 -0
  39. package/dist/td-sdk.min.cjs +1 -0
  40. package/dist/td-sdk.min.js +1 -0
  41. package/dist/treasure.d.ts +198 -0
  42. package/dist/types/index.d.ts +177 -0
  43. package/dist/utils/element.d.ts +20 -0
  44. package/dist/utils/lodash.d.ts +18 -0
  45. package/dist/utils/misc.d.ts +17 -0
  46. package/dist/utils/set-cookie.d.ts +14 -0
  47. package/dist/utils/uuid.d.ts +14 -0
  48. package/dist/utils/xhr.d.ts +58 -0
  49. package/dist/vendor/js-cookies.d.ts +19 -0
  50. package/package.json +90 -0
@@ -0,0 +1 @@
1
+ "use strict";function createSDK(e){if(!e||"string"!=typeof e.writeKey||!e.writeKey)throw new Error("TreasureSDK: writeKey is required");if(!e.database)throw new Error("TreasureSDK: database is required");const t={debug:(...t)=>{e.development},warn:(...e)=>{},error:(...e)=>{}},n={config:{...e},log:t},o={...n,use(e){n.log.debug(`Loading plugin: ${e.name}`);const t=e.setup(n,o);for(const n of Object.keys(t))if(n in o)throw new Error(`TreasureSDK: plugin "${e.name}" conflicts on "${n}"`);return Object.assign(o,t),o},getWriteKey:()=>n.config.writeKey,setWriteKey(e){if(!e||"string"!=typeof e)throw new Error("TreasureSDK: writeKey must be a non-empty string");n.config.writeKey=e}};return o}function isObject$1(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function isString(e){return"string"==typeof e}function isArray(e){return Array.isArray(e)}function isEmpty(e){return null==e||(isArray(e)||isString(e)?0===e.length:!!isObject$1(e)&&0===Object.keys(e).length)}function assign(e,...t){return Object.assign(e,...t)}function omit(e,...t){const n={...e};return t.forEach(e=>delete n[e]),n}function disposable(e){let t=!1;return function(){t||(t=!0,e())}}function invariant$1(e,t){if(!e)throw new Error(t)}function isLocalStorageAccessible(){const e="__td__";try{return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch{return!1}}Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const adlHeaders={"Content-Type":"application/vnd.treasuredata.v1+json",Accept:"application/vnd.treasuredata.v1+json"},globalIdAdlHeaders={"Content-Type":"application/vnd.treasuredata.v1.js+json",Accept:"application/vnd.treasuredata.v1.js+json"},CONFIG={VERSION:"1.0.0",HOST:"us01.records.in.treasuredata.com",DATABASE:"",PATHNAME:"/"};function encode(e){try{return encodeURIComponent(e)}catch(e){return null}}function decode(e){try{return decodeURIComponent(e)}catch(e){return null}}function handleSkey(e){const t=encode(e);return t?t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"):""}const cookie={getItem(e){if(!e)return null;const t=new RegExp("(?:(?:^|.*;)\\s*"+handleSkey(e)+"\\s*\\=\\s*([^;]*).*$)|^.*$");return decode(document.cookie.replace(t,"$1"))||null},setItem(e,t,n,o,r,i,s){if(!e||/^(?:expires|max\-age|path|domain|secure)$/i.test(e))return!1;let a="";n&&("number"==typeof n?a=n===1/0?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+n:"string"==typeof n?a="; expires="+n:n instanceof Date&&(a="; expires="+n.toUTCString()));let c="";s&&"NONE"===s.toUpperCase()?c="; Secure; SameSite="+s:(i&&(c+="; Secure"),s&&(c+="; SameSite="+s));const l=encode(e),u=encode(t);return!(!l||!u)&&(document.cookie=[l,"=",u,a,r?"; domain="+r:"",o?"; path="+o:"",c].join(""),!0)},removeItem(e,t,n){if(!this.hasItem(e))return!1;const o=encode(e);return!!o&&(document.cookie=[o,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT",n?"; domain="+n:"",t?"; path="+t:""].join(""),!0)},hasItem(e){if(!e)return!1;const t=encode(e);return!!t&&new RegExp("(?:^|;\\s*)"+t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")+"\\s*\\=").test(document.cookie)},keys:()=>document.cookie.replace(/((?:^|\s*;)[^=]+)(?=;|$)|^\s*|\s*(?:=[^;]*)?(?:\1|$)/g,"").split(/\s*(?:=[^;]*)?;\s*/).map(e=>decode(e)).filter(e=>null!==e)};function validateOptions(e){invariant$1(isObject$1(e),"Check out our JavaScript SDK Usage Guide: https://github.com/treasure-data/td-js-sdk#api"),invariant$1(isString(e.writeKey),"Must provide a writeKey"),invariant$1(isString(e.database),"Must provide a database"),invariant$1(e.database&&/^[a-z0-9_]{3,255}$/.test(e.database),"Database must be between 3 and 255 characters and must consist only of lower case letters, numbers, and _")}function defaultSSCCookieDomain(){if("undefined"==typeof document)return"localhost";const e=document.location.hostname.split(".");for(let t=e.length-2;t>=1;t--){const n=e.slice(t).join("."),o="_td_domain_"+n;if(cookie.setItem(o,n,3600,"/",n),cookie.getItem(o)===n)return n}return document.location.hostname}const DEFAULT_CONFIG={database:CONFIG.DATABASE,development:!1,globalIdCookie:"_td_global",host:CONFIG.HOST,logging:!0,pathname:CONFIG.PATHNAME,requestType:"fetch",jsonpTimeout:1e4,startInSignedMode:!1,useServerSideCookie:!1,sscDomain:defaultSSCCookieDomain,sscServer:function(e){return["ssc",e].join(".")},storeConsentByLocalStorage:!1};function configure(e){const t=assign({},{globals:{}},DEFAULT_CONFIG,e,{requestType:"fetch"});return validateOptions(t),t.endpoint||(t.endpoint="https://"+t.host+t.pathname),t.storage||(t.storage={name:"_td",domain:"undefined"!=typeof window&&"undefined"!=typeof document?document.location.hostname:"localhost",expires:63072e3,path:"/"}),t}function findDomains(e){const t=e.split("."),n=[];for(let e=t.length-1;e>=0;e--)n.push(t.slice(e).join("."));return n}function setCookie(e,t,n){const o={...e},r=e.domain.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/),i="localhost"===e.domain,s=e.customDomain,a=new Date;if(a.setSeconds(a.getSeconds()+o.expires),i)n?cookie.setItem(t,n,a,o.path):cookie.removeItem(t,o.path,o.domain);else if(r||s)n?cookie.setItem(t,n,a,o.path,o.domain,!0,"None"):cookie.removeItem(t,o.path,o.domain);else{const r=findDomains(e.domain),i=r.length;let s=0;if(n){if(cookie.getItem(t)===n)return;for(;s<i;s++)if(o.domain=r[s],cookie.setItem(t,n,a,o.path,o.domain,!0,"None"),cookie.getItem(t)===n){e.domain=o.domain;break}}else for(;s<i;s++)cookie.removeItem(t,e.path,r[s])}}function generateUUID$1(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}throw new Error("Secure random number generation is not available in this environment")}function isValidUUID(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}const FETCH_CREDENTIALS={"same-origin":"same-origin",include:"include",omit:"omit"};function toJSON(e){let t;try{t=JSON.parse(e)}catch{t={}}return t}function getCredentials(e={}){return FETCH_CREDENTIALS[e.credentials||"include"]||"include"}function post(e,t,n={}){const o=n.headers||{},r=getCredentials(n),i={method:"POST",headers:o,keepalive:!0,body:JSON.stringify(t)};return i.credentials=r,n.signal&&(i.signal=n.signal),fetch(e,i).then(function(e){if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.text()}).then(function(e){return toJSON(e)})}function get(e,t={}){const n=t.headers||{},o=getCredentials(t),r={method:"GET",headers:n};return r.credentials=o,t.signal&&(r.signal=t.signal),fetch(e,r).then(function(e){if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.text()}).then(function(e){return toJSON(e)})}function withTimeout(e,t,n){const o=new AbortController;let r;const i=new Promise((e,i)=>{r=setTimeout(()=>{o.abort(),i(new Error(n||"Operation Timeout"))},t)}),s=e(o.signal).finally(()=>{clearTimeout(r)});return Promise.race([s,i]).catch(e=>{if(clearTimeout(r),"AbortError"===e.name)throw new Error(n||"Operation Timeout");throw e})}function postWithTimeout(e,t,n,o={}){return withTimeout(n=>post(e,t,{...o,signal:n}),n,"Request Timeout")}function getWithTimeout(e,t,n={}){return withTimeout(t=>get(e,{...n,signal:t}),t,"Request Timeout")}function timeoutPromise(e,t,n){return withTimeout(t=>e(),t,n)}const api={post:post,get:get,postWithTimeout:postWithTimeout,getWithTimeout:getWithTimeout,withTimeout:withTimeout,timeoutPromise:timeoutPromise},SERVER_COOKIE_NAME="_td_ssc_id",COOKIE_NAME=SERVER_COOKIE_NAME;function serverCookie(){return{name:"serverCookie",setup(e,t){const n=e.config;let o,r;const i=()=>{};return{fetchServerCookie:function(e,s,a=!1){const c=e||i,l=s||i;if("function"==typeof t.inSignedMode&&!t.inSignedMode())return l("not in signed in mode");if(!n.useServerSideCookie)return l("server side cookie not enabled");if(r||(o="function"==typeof n.sscDomain?n.sscDomain():n.sscDomain||("undefined"!=typeof window?window.location.hostname:"localhost"),r="function"==typeof n.sscServer?n.sscServer(o):n.sscServer||`ssc.${o}`),!o||!r)return l("server cookie configuration not properly initialized");const u=`https://${r}/get_cookie_id?cookie_domain=${encodeURIComponent(o)}&r=${Date.now()}`,d=cookie.getItem(COOKIE_NAME);!d||a?api.getWithTimeout(u,1e4).then(e=>{c(e.td_ssc_id)}).catch(e=>{l(e)}):setTimeout(()=>{c(d)},0)}}}}}const BLOCKEVENTSCOOKIE="__td_blockEvents",SIGNEDMODECOOKIE="__td_signed";function configureStorage(e){if("none"===e)return null;const t="object"==typeof e&&null!==e?e:{};return{name:t.name||"_td",expires:t.expires??63072e3,domain:t.domain||document.location.hostname,customDomain:!!t.domain,path:t.path||"/"}}function setStorageCookie(e,t,n){try{setCookie(e,t,n||"")}catch{}}function session(){return{name:"session",setup(e,t){const n=e.config,o=n.startInSignedMode??!1,r=n.storeConsentByLocalStorage??!1,i={};function s(e,t){const n=e||"$global";return i[n]=i[n]||{},t?i[n]?.[t]??null:i[n]}const a=configureStorage(n.storage);let c;null!=n.clientId&&(c="number"==typeof n.clientId?n.clientId.toString():n.clientId),c&&"string"==typeof c||(a?.name&&"undefined"!=typeof document&&(c=cookie.getItem(a.name)??void 0),c&&"undefined"!==c||(c=generateUUID$1()));let l=c.replace(/\0/g,"");function u(){return l}function d(e,t){if(cookie.getItem(e.name)!==t)try{setCookie(e,e.name,t)}catch{}}function p(e,t){l=(t||generateUUID$1()).replace(/\0/g,"");const o=e||n.storage;if(o&&"object"==typeof o){const e=configureStorage(o);e?.expires&&g()&&d(e,l)}}function g(){if(r){if(!isLocalStorageAccessible())return o;const e=localStorage.getItem("__td_signed");return"false"!==e&&("true"===e||o)}if("undefined"==typeof document)return o;const e=cookie.getItem("__td_signed");return"false"!==e&&("true"===e||o)}function f(){if(i.$global&&delete i.$global.td_global_id,n.storage&&"object"==typeof n.storage){const e=n.globalIdCookie||"_td_global";setStorageCookie(n.storage,e,"")}if(isLocalStorageAccessible()){const e=n.globalIdCookie||"_td_global";try{localStorage.removeItem(e)}catch{}}}return a?.expires&&g()&&d(a,l),{inSignedMode:g,setSignedMode:function(){r?isLocalStorageAccessible()&&localStorage.setItem("__td_signed","true"):n.storage&&"object"==typeof n.storage&&setStorageCookie(n.storage,"__td_signed","true");const e=u();p(n.storage,e)},setAnonymousMode:function(e){r?isLocalStorageAccessible()&&localStorage.setItem("__td_signed","false"):n.storage&&"object"==typeof n.storage&&setStorageCookie(n.storage,"__td_signed","false"),e||(n.storage&&"object"==typeof n.storage&&setStorageCookie(n.storage,n.storage.name),f(),t.removeServerCookie())},blockEvents:function(){n.storage&&"object"==typeof n.storage&&setStorageCookie(n.storage,BLOCKEVENTSCOOKIE,"true")},unblockEvents:function(){n.storage&&"object"==typeof n.storage&&setStorageCookie(n.storage,BLOCKEVENTSCOOKIE,"false")},areEventsBlocked:function(){return"true"===cookie.getItem(BLOCKEVENTSCOOKIE)},getUUID:u,resetUUID:p,set:function(e,t,n){let o,r=t;"object"==typeof e&&null!==e?(r=e,o="$global"):o=e;const s=i[o]||{};i[o]=s,"object"==typeof r&&null!==r?Object.assign(s,r):"string"==typeof r&&void 0!==n&&(s[r]=n)},get:s,removeCachedGlobalID:f,removeServerCookie:function(){if(n.storage&&"object"==typeof n.storage){setStorageCookie(n.storage,SERVER_COOKIE_NAME,"");["__td_ssc","_td_ssc"].forEach(e=>{setStorageCookie(n.storage,e,"")}),n.useServerSideCookie&&n.globalIdCookie&&setStorageCookie(n.storage,n.globalIdCookie,"")}isLocalStorageAccessible()&&[SERVER_COOKIE_NAME,"__td_ssc","_td_ssc"].forEach(e=>{try{localStorage.removeItem(e)}catch{}})},isGlobalIdEnabled:function(){return"td_global_id"===s(void 0,"td_global_id")}}}}}const DEFAULT_HOST="us01.records.in.treasuredata.com",DEFAULT_PATHNAME="/";function validateRecord(e,t){invariant$1(isString(e),"Must provide a table"),invariant$1(/^[a-z0-9_]{3,255}$/.test(e),"Table must be between 3 and 255 characters and must consist only of lower case letters, numbers, and _"),invariant$1(isObject$1(t),"Must provide a record")}const _validateRecord=validateRecord;function record(){return{name:"record",setup(e,t){const n=e.config,o=n.host||DEFAULT_HOST,r=n.pathname||"/",i=n.endpoint||`https://${o}${r}`;let s=!1;if("undefined"!=typeof window&&window.addEventListener){const t=()=>{s=!0};window.addEventListener("beforeunload",t),window.addEventListener("unload",t),e._unloadHandlers=[()=>window.removeEventListener("beforeunload",t),()=>window.removeEventListener("unload",t)]}e._windowBeingUnloaded=()=>s;return{addRecord(o,r,s,a,c){validateRecord(o,r);const l=function(e,n){return Object.assign({},t.get("$global"),t.get(e),n)}(o,r),u=t.inSignedMode()?l:omitKeys(l,["td_ip","td_client_id","td_global_id"]),d={apikey:n.writeKey,record:u,time:null,url:`${i}${c?.database??n.database}/${o}`};null!=d.record.time&&(d.time=d.record.time),n.development?(e.log.debug("addRecord",d),s?.({success:!0,message:"Development mode - record not sent"})):t.areEventsBlocked()||submitRecord({...d,inSignedMode:t.inSignedMode(),isGlobalIdEnabled:t.isGlobalIdEnabled(),windowBeingUnloaded:e._windowBeingUnloaded?.()??!1,timeoutMs:n.jsonpTimeout??6e4},s,a)}}}}}function omitKeys(e,t){const n={};for(const o of Object.keys(e))if(!t.includes(o)){const t=e[o];void 0!==t&&(n[o]=t)}return n}async function submitRecord(e,t,n){const o=()=>{},r=t||o,i=n||o,s=["modified="+encodeURIComponent((new Date).getTime())];e.time&&s.push("time="+encodeURIComponent(e.time));const a=e.url+"?"+s.join("&"),c="a"===e.record.tag&&!!e.record.href,l={};l.Authorization="TD1 "+e.apikey,"undefined"!=typeof navigator&&(l["User-Agent"]=navigator.userAgent),e.inSignedMode&&e.isGlobalIdEnabled?Object.assign(l,globalIdAdlHeaders):Object.assign(l,adlHeaders);const u={events:[e.record]};try{if("undefined"!=typeof window&&(e.windowBeingUnloaded||c)){r(await api.postWithTimeout(a,u,e.timeoutMs,{headers:l,credentials:"include"}))}else{r(await api.post(a,u,{headers:l,credentials:"include"}))}}catch(e){i(e instanceof Error?{...e,name:e.name,message:e.message}:new Error("Unknown error occurred"))}}const POPUP_CONTAINER_ID="td-engage-popup-container";let inlineObserver=null,navigationCleanupInstalled=!1,accumulatedInline=[];function parseAppearance(e){if("object"==typeof e&&null!==e)return e;try{return JSON.parse(e)}catch{return{}}}function parseMessages(e){try{const t=e["td_in_browser.messages"];return t?JSON.parse(t):[]}catch{return[]}}function removeExistingPopup(){document.getElementById(POPUP_CONTAINER_ID)?.remove()}function isPopupDisplayed(){return null!==document.getElementById(POPUP_CONTAINER_ID)}function resetForNavigation(){removeExistingPopup(),inlineObserver&&(inlineObserver.disconnect(),inlineObserver=null),accumulatedInline=[]}function ensureNavigationCleanup(){if(!navigationCleanupInstalled&&"undefined"!=typeof window&&window.history){window.addEventListener("popstate",resetForNavigation),window.addEventListener("hashchange",resetForNavigation);try{const e=e=>{const t=window.history[e];window.history[e]=function(...e){const n=t.apply(this,e);return resetForNavigation(),n}};e("pushState"),e("replaceState")}catch{}navigationCleanupInstalled=!0}}function renderPopup(e){try{const t=parseAppearance(e.appearance_setting),n=window.innerWidth>620;removeExistingPopup();const o=t.position?.placement??"center",r=o.startsWith("top"),i=o.startsWith("bottom"),s=o.endsWith("left"),a=o.endsWith("right"),c=n?t.inset?.desktop??40:t.inset?.mobile??16,l=n?t.width?.desktop_max_width??600:t.width?.mobile_max_width??300,u=document.createElement("div");u.id=POPUP_CONTAINER_ID;const d=i?"end":r?"start":"center",p=s?"start":a?"end":"center";Object.assign(u.style,{position:!1===t.position?.fixed_on_scroll?"absolute":"fixed",inset:"0",display:"grid",placeItems:`${d} ${p}`,padding:`${c}px`,pointerEvents:"none",boxSizing:"border-box"}),u.style.setProperty("z-index","var(--td-popup-z-index, 2147483647)");const g=u.attachShadow({mode:"open"}),f=document.createElement("style");if(f.textContent="\n :host { --td-popup-z-index: 2147483647; --td-popup-frame-z-index: 1; --td-close-btn-cursor: pointer; --td-close-btn-line-height: 1; }\n .td-overlay { position: fixed; inset: 0; pointer-events: auto; }\n .td-frame { position: relative; width: 100%; pointer-events: auto; box-sizing: border-box; z-index: var(--td-popup-frame-z-index); }\n .td-close { position: absolute; background: transparent; border: none; cursor: var(--td-close-btn-cursor); line-height: var(--td-close-btn-line-height); padding: 0; display: flex; align-items: center; justify-content: center; z-index: 1; }\n ",g.appendChild(f),t.overlay?.enabled){const e=document.createElement("div");e.className="td-overlay",Object.assign(e.style,{background:t.overlay.color??"#000000B3"}),t.overlay.close_on_click_outside&&e.setAttribute("data-engage-popup-close",""),g.appendChild(e)}const m=document.createElement("div");m.className="td-frame";const _=t.background?.padding??0;if(Object.assign(m.style,{maxWidth:`${l}px`,background:t.background?.color??"#FFFFFF",borderRadius:`${t.background?.border_radius??8}px`,padding:`${_}px`}),!1!==t.close_button?.enabled){const e=t.close_button?.size??28,n=t.close_button?.offset_top??2,o=t.close_button?.offset_right??4,r=document.createElement("button");r.type="button",r.className="td-close",r.setAttribute("aria-label","Close"),r.setAttribute("data-engage-popup-close",""),Object.assign(r.style,{top:`${n}px`,right:`${o}px`,width:`${e}px`,height:`${e}px`,fontSize:.7*e+"px",color:t.close_button?.color??"#FFFFFF"}),r.textContent="×",m.appendChild(r)}const h=document.createElement("div");h.innerHTML=e.content_html,m.appendChild(h),g.appendChild(m),g.addEventListener("click",e=>{e.target.hasAttribute("data-engage-popup-close")&&u.remove()}),document.body.appendChild(u)}catch{}}function renderInline(e){if(e.css_selector)try{const t=document.querySelectorAll(e.css_selector);for(const n of t)n.innerHTML=e.content_html}catch{}}function compareMessages(e,t){const n=Number(t.created_at_millisecond??0)-Number(e.created_at_millisecond??0);if(0!==n)return n;const o=t._sectionName.localeCompare(e._sectionName);return 0!==o?o:t._arrayIndex-e._arrayIndex}function sortedInlineMessages(e){return e.filter(e=>"inline"===e.type&&e.css_selector).sort((e,t)=>-compareMessages(e,t))}function pickPopup(e){return e.filter(e=>"popup"===e.type).sort(compareMessages)[0]}function applyAccumulatedInline(){for(const e of accumulatedInline)renderInline(e)}function setupInlineObserver(){inlineObserver&&(inlineObserver.disconnect(),inlineObserver=null),0!==accumulatedInline.length&&(inlineObserver=new MutationObserver(()=>{inlineObserver.disconnect(),applyAccumulatedInline(),inlineObserver.observe(document.body,{childList:!0,subtree:!0})}),inlineObserver.observe(document.body,{childList:!0,subtree:!0}))}function extractMessages(e){const t=e.offers;if(!t)return[];const n=[];for(const[e,o]of Object.entries(t)){const t=o?.td_app;if(!t)continue;parseMessages(t).forEach((t,o)=>{n.push({...t,_sectionName:e,_arrayIndex:o})})}return n}function handlePersonalizationResponse(e){try{const t=extractMessages(e);if(0===t.length)return;if(ensureNavigationCleanup(),!isPopupDisplayed()){const e=pickPopup(t);e&&renderPopup(e)}const n=sortedInlineMessages(t);n.length>0&&(accumulatedInline.push(...n),applyAccumulatedInline(),setupInlineObserver())}catch{}}function configureValues(e,t){return{td_version:()=>t,td_client_id:e,td_charset:()=>(document.characterSet||document.charset||"-").toLowerCase(),td_language:()=>{const e=navigator;return(e&&(e.language||e.browserLanguage)||"-").toLowerCase()},td_color:()=>screen?screen.colorDepth+"-bit":"-",td_screen:()=>screen?`${screen.width}x${screen.height}`:"-",td_viewport:()=>{const e=document.documentElement&&document.documentElement.clientHeight,t=document.documentElement&&document.documentElement.clientWidth,n=window.innerHeight,o=window.innerWidth;return`${(t||0)<o?o:t||0}x${(e||0)<n?n:e||0}`},td_title:()=>document.title,td_description:()=>getMetaContent("description"),td_url:()=>document.location&&document.location.href&&document.location.href.split("#")[0]||"",td_user_agent:()=>[navigator.userAgent,`WEBSDK/${t}`].join(";"),td_platform:()=>navigator.platform||navigator.userAgentData?.platform||"-",td_host:()=>document.location.host,td_path:()=>document.location.pathname,td_referrer:()=>document.referrer}}function getMetaContent(e){const t=(document.head||document.getElementsByTagName("head")[0]).getElementsByTagName("meta"),n=t.length;for(let o=0;o<n;o++){const n=t[o];if(n&&n.getAttribute("name")===e)return(n.getAttribute("content")||"").substr(0,8192)}return""}function track(){return{name:"track",setup(e,t){const n=configureValues(()=>t.getUUID(),CONFIG.VERSION);function o(){const e={};for(const[t,o]of Object.entries(n))o&&(e[t]="function"==typeof o?o():o);return e}function r(n,r,i,s){const a=n||"events",c=o(),l=Object.assign(c,r),u=e.config.personalization;if(u){const n={endpoint:u.endpoint,database:u.database||e.config.database,table:a,token:u.token},i={...t.get("$global"),...t.get(a),...o(),...r};return void t.fetchPersonalization(n,i,e=>{handlePersonalizationResponse(e),"function"==typeof t.applyPersonalization&&t.applyPersonalization(e)},t=>{e.log.error("Personalization failed:",t)})}t.addRecord(a,l,i,s)}return{trackEvent:r,trackPageview:function(e,t,n,o){r(e||"pageviews",o?.payload??{},t,n)},getTrackValues:o,getPersonalizationConfig:function(){return e.config.personalization},setPersonalizationConfig:function(t){e.config.personalization=t}}}}}function getEventTarget(e){const t=e.target||e.srcElement||document;return 3===t.nodeType?t.parentNode:t}function addEventListener(e,t,n){if("addEventListener"in e)return e.addEventListener(t,o,!1),disposable(()=>{e.removeEventListener(t,o,!1)});if("attachEvent"in e)return e.attachEvent("on"+t,o),disposable(()=>{e.detachEvent("on"+t,o)});throw new Error("addEventListener not supported");function o(t){n.call(e,t||window.event)}}function htmlTreeAsString(e){const t=[];let n=0,o=0;let r,i=e;for(;i&&n++<5&&(r=htmlElementAsString(i),!("html"===r||n>1&&o+3*t.length+r.length>=80));)t.push(r),o+=r.length,i=i.parentNode;const s=t.reverse().join(" > ");return s.length>80?s.substring(0,77)+"...":s}function htmlElementAsString(e){const t=[];let n,o,r,i;if(!e||!e.tagName)return"";t.push(e.tagName.toLowerCase()),e.id&&t.push("#"+e.id);const s=e.className;if(s&&isString(s))for(n=s.split(" "),i=0;i<n.length;i++){const e=n[i];e&&e.trim()&&t.push("."+e.trim())}const a=["type","name","title","alt"];for(i=0;i<a.length;i++)o=a[i],r=e.getAttribute(o),r&&t.push("["+o+'="'+r+'"]');return t.join("")}function hasAttribute(e,t){return"function"==typeof e.hasAttribute?e.hasAttribute(t):null!==e.getAttribute(t)}const element=Object.freeze(Object.defineProperty({__proto__:null,addEventListener:addEventListener,getEventTarget:getEventTarget,hasAttribute:hasAttribute,htmlElementAsString:htmlElementAsString,htmlTreeAsString:htmlTreeAsString},Symbol.toStringTag,{value:"Module"}));function findElement(e){if(!e||!e.tagName)return null;let t=e,n=t.tagName.toLowerCase();for(;n&&"body"!==n&&t;){const e=t.getAttribute("type");if("input"===n&&"password"===e)return null;const o=t.getAttribute("role");if("button"===o||"link"===o||"a"===n||"button"===n||"input"===n)return t;t=t.parentNode,n=t&&t.tagName?t.tagName.toLowerCase():""}return null}function createTreeHasIgnoreAttribute(e){const t="data-"+e;return function n(o){return!(!o||!o.tagName||"html"===o.tagName.toLowerCase())&&(!(!hasAttribute(o,e)&&!hasAttribute(o,t))||n(o.parentNode))}}function getElementData(e){const t={tag:e.tagName.toLowerCase(),tree:htmlTreeAsString(e)};return["alt","class","href","id","name","role","title","type"].forEach(n=>{if(hasAttribute(e,n)){const o=e.getAttribute(n);o&&(t[n]=o)}}),t}function clicks(){return{name:"clicks",setup(e,t){let n=!1;return{trackClicks(e){if(n)return;const o={element:e?.element??window.document,extendClickData:e?.extendClickData??((e,t)=>t),ignoreAttribute:e?.ignoreAttribute??"td-ignore",tableName:e?.tableName??"clicks"},r=createTreeHasIgnoreAttribute(o.ignoreAttribute),i=addEventListener(o.element,"click",e=>{const n=findElement(getEventTarget(e));if(n&&!r(n)){const r=getElementData(n),i=o.extendClickData(e,r);i&&t.trackEvent(o.tableName,i)}});return n=!0,disposable(()=>{i(),n=!1})}}}}}const DEFAULT_UTM_PARAMS=["utm_id","utm_medium","utm_source_platform","utm_source","utm_campaign","utm_marketing_tactic"];function collectUTMParametersFromURL(e=DEFAULT_UTM_PARAMS){if("undefined"==typeof window||!window.location)return{};const t=window.location.search,n=new(window.URLSearchParams||URLSearchParams)(t);return e.some(e=>n.has(e))?e.reduce((e,t)=>{const o=n.get(t);return o&&(e[t]=o),e},{}):{}}function utm(e={}){return{name:"utm",setup(t,n){const o={customParameters:e.customParameters||DEFAULT_UTM_PARAMS,autoCollect:e.autoCollect??!0,table:e.table||"$global"};let r={};function i(){const e=collectUTMParametersFromURL(o.customParameters);return isObject$1(e)&&!isEmpty(e)&&("$global"===o.table?n.set(e):Object.keys(e).forEach(t=>{n.set(o.table,t,e[t])}),r={...r,...e}),e}return o.autoCollect&&i(),{getUTMParameters:function(){return{...r}},collectUTMParameters:i}}}}const DEFAULT_CDP_HOST="cdp.in.treasuredata.com";function invariant(e,t){if(!e)throw new Error(t)}function personalization(){return{name:"personalization",setup(e,t){const n=e.config.cdpHost||DEFAULT_CDP_HOST;return{fetchUserSegments:function(e,t,o){const r=()=>{},i=t||r,s=o||r,a=isObject$1(e)&&!isArray(e),c=a?e.audienceToken:e,l=a&&e.keys||{};invariant("string"==typeof c||isArray(c),`audienceToken must be a string or array; received "${String(c)}"`),invariant(isObject$1(l),`keys must be an object; received "${String(l)}"`);const u=isArray(c)?c.join(","):c,d=[];Object.keys(l).forEach(e=>{d.push(`key.${e}=${String(l[e])}`)});const p=d.join("&"),g=`https://${n}/cdp/lookup/collect/segments?version=2&token=${u}${p?"&"+p:""}`;api.getWithTimeout(g,1e4,{headers:{"Content-Type":"application/json"}}).then(i).catch(s)},fetchPersonalization:function(n,o,r,i){const s=()=>{},a=r||s,c=i||s;if(invariant(isObject$1(n),`config must be an object, received "${String(n)}"`),invariant(!!n.endpoint,"endpoint is invalid"),invariant(!!n.database,"database is invalid"),invariant(!!n.table,"table is invalid"),invariant(!!n.token,"token is invalid"),"function"==typeof t.areEventsBlocked&&t.areEventsBlocked())return;const l=`https://${n.endpoint}/public/${n.database}/${n.table}`;let u=o||{};"function"!=typeof t.inSignedMode||t.inSignedMode()||(u=omit(u,"td_ip","td_client_id","td_global_id")),api.postWithTimeout(l,u,1e4,{headers:{"Content-Type":"application/vnd.treasuredata.v1+json",Authorization:`TD1 ${e.config.writeKey}`,"WP13n-Token":n.token}}).then(a).catch(c)}}}}}const VENDOR_FUNCTION_MAPPINGS={google_ads:["getGoogle_gclid_Param","getGoogle_wbraid_Param"],google_ga:["getGoogle_ga_Cookie"],google_mp:["getGoogle_gcl_Cookies"],meta:["getFacebook_fbp_Cookie","getFacebook_fbc_Cookie","getFacebook_fbclid_Param"],instagram:["getInstagram_shbts_Cookie","getInstagram_shbid_Cookie","getInstagram_ds_user_id_Cookie","getInstagram_ig_did_Cookie"],yahoojp_ads:["getYahoo_ly_c_Param","getYahoo_ly_c_Cookie","getYahoo_ly_r_Cookie","getYahoo_ly_su_Cookie","getYahoo_yclid_Param","getYahoo_yj_r_Param","getYahoo_ycl_yjad_Cookie","getYahoo_yjr_yjad_Cookie","getYahoo_yjsu_yjad_Cookie"],line:["getLine_lt_cid_Cookie","getLine_lt_sid_Cookie","getLine_ldtag_cl_Param"],x:["getX_twclid_Param","getX_twclid_Cookie"],pinterest:["getPinterest_epik_Param","getPinterest_epik_Cookie"],snapchat:["getSnapchat_sccid_Param"],tiktok:["getTiktok_ttp_Cookie"],marketo:["getMarketo_mkto_trk_Cookie"],tealium:["getTealium_utag_main_Cookie"]};function getCookie(e){return"undefined"==typeof document?null:cookie.getItem(e)}function getCookieByNamePrefix(e){return"undefined"==typeof document?{}:cookie.keys().filter(t=>t.startsWith(e)).reduce((e,t)=>{const n=cookie.getItem(t);return null!==n&&(e[t]=n),e},{})}function getParam(e){if("undefined"==typeof window||!window.location)return null;const t=window.location.search;return new(window.URLSearchParams||URLSearchParams)(t).get(e)}function conversionAPI(){return{name:"conversionAPI",setup(e,t){const n={getGoogle_gclid_Param:()=>({gclid:getParam("gclid")}),getGoogle_wbraid_Param:()=>({wbraid:getParam("wbraid")}),getGoogle_ga_Cookie:()=>({_ga:getCookie("_ga")}),getGoogle_gcl_Cookies:(e={})=>getCookieByNamePrefix(e.gclPrefix||"_gcl"),getFacebook_fbp_Cookie:()=>({_fbp:getCookie("_fbp")}),getFacebook_fbc_Cookie:()=>({_fbc:getCookie("_fbc")}),getFacebook_fbclid_Param:()=>({fbclid:getParam("fbclid")}),getInstagram_shbts_Cookie:()=>({shbts:getCookie("shbts")}),getInstagram_shbid_Cookie:()=>({shbid:getCookie("shbid")}),getInstagram_ds_user_id_Cookie:()=>({ds_user_id:getCookie("ds_user_id")}),getInstagram_ig_did_Cookie:()=>({ig_did:getCookie("ig_did")}),getYahoo_yclid_Param:()=>({yclid:getParam("yclid")}),getYahoo_yj_r_Param:()=>({yj_r:getParam("yj_r")}),getYahoo_ycl_yjad_Cookie:()=>({_ycl_yjad:getCookie("_ycl_yjad")}),getYahoo_yjr_yjad_Cookie:()=>({_yjr_yjad:getCookie("_yjr_yjad")}),getYahoo_yjsu_yjad_Cookie:()=>({_yjsu_yjad:getCookie("_yjsu_yjad")}),getYahoo_ly_c_Param:()=>({ly_c:getParam("_ly_c")}),getYahoo_ly_c_Cookie:()=>({ly_c:getCookie("_ly_c")}),getYahoo_ly_r_Cookie:()=>({ly_r:getCookie("_ly_r")}),getYahoo_ly_su_Cookie:()=>({ly_su:getCookie("_ly_su")}),getLine_lt_cid_Cookie:()=>({__lt_cid:getCookie("__lt__cid")}),getLine_lt_sid_Cookie:()=>({__lt_sid:getCookie("__lt__sid")}),getLine_ldtag_cl_Param:()=>({ldtag_cl:getParam("ldtag_cl")}),getX_twclid_Param:()=>({twclid:getParam("twclid")}),getX_twclid_Cookie:()=>({_twclid:getCookie("_twclid")}),getPinterest_epik_Param:()=>({epik:getParam("epik")}),getPinterest_epik_Cookie:()=>({_epik:getCookie("_epik")}),getSnapchat_sccid_Param:()=>({ScCid:getParam("ScCid")}),getTiktok_ttp_Cookie:()=>({_ttp:getCookie("_ttp")}),getMarketo_mkto_trk_Cookie:()=>({_mkto_trk:getCookie("_mkto_trk")}),getTealium_utag_main_Cookie:()=>({utag_main:getCookie("utag_main")})};return{collectTags:function(e={},o={}){const r=isEmpty(e.vendors)&&isEmpty(e.cookies)&&isEmpty(e.params);let i={};isEmpty(e)||r?i=function(e={}){const t={};return Object.keys(VENDOR_FUNCTION_MAPPINGS).forEach(o=>{const r=VENDOR_FUNCTION_MAPPINGS[o];r&&r.forEach(o=>{const r=n[o](e);Object.assign(t,r)})}),Object.keys(t).reduce((e,n)=>(t[n]&&(e[n]=t[n]),e),{})}(o):(isEmpty(e.vendors)||Object.assign(i,function(e=[],t={}){return e.reduce((e,o)=>((VENDOR_FUNCTION_MAPPINGS[o]||[]).forEach(o=>{const r=n[o](t);Object.assign(e,r)}),e),{})}(e.vendors,o)),isEmpty(e.cookies)||Object.assign(i,function(e=[]){return e.reduce((e,t)=>(e[t]=getCookie(t),e),{})}(e.cookies)),isEmpty(e.params)||Object.assign(i,function(e=[]){return e.reduce((e,t)=>(e[t]=getParam(t),e),{})}(e.params))),Object.keys(i).forEach(e=>{const n=i[e];n&&t.set({[e]:n})})}}}}}const MODE_QUERY_PARAM="td-personalization-mode",INIT_MESSAGE_TYPE="td:p13n-studio:init",READY_MESSAGE_TYPE="td:p13n-studio:ready",PROD_ORIGINS=["https://console-development-next.us01.treasuredata.com","https://console-staging-next.us01.treasuredata.com","https://console-next.us01.treasuredata.com","https://console-staging-next.treasuredata.co.jp","https://console-next.treasuredata.co.jp","https://console-development-next.eu01.treasuredata.com","https://console-next.eu01.treasuredata.com","https://console-next.ap02.treasuredata.com","https://console-staging-next.ap03.treasuredata.com","https://console-next.ap03.treasuredata.com"],ALLOWED_PARENT_ORIGINS=Object.freeze([...PROD_ORIGINS]),proxyMarker=Symbol("Comlink.proxy"),createEndpoint=Symbol("Comlink.endpoint"),releaseProxy=Symbol("Comlink.releaseProxy"),finalizer=Symbol("Comlink.finalizer"),throwMarker=Symbol("Comlink.thrown"),isObject=e=>"object"==typeof e&&null!==e||"function"==typeof e,proxyTransferHandler={canHandle:e=>isObject(e)&&e[proxyMarker],serialize(e){const{port1:t,port2:n}=new MessageChannel;return expose(e,t),[n,[n]]},deserialize:e=>(e.start(),wrap(e))},throwTransferHandler={canHandle:e=>isObject(e)&&throwMarker in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler]]);function isAllowedOrigin(e,t){for(const n of e){if(t===n||"*"===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}return!1}function expose(e,t=globalThis,n=["*"]){t.addEventListener("message",function o(r){if(!r||!r.data)return;if(!isAllowedOrigin(n,r.origin))return;const{id:i,type:s,path:a}=Object.assign({path:[]},r.data),c=(r.data.argumentList||[]).map(fromWireValue);let l;try{const t=a.slice(0,-1).reduce((e,t)=>e[t],e),n=a.reduce((e,t)=>e[t],e);switch(s){case"GET":l=n;break;case"SET":t[a.slice(-1)[0]]=fromWireValue(r.data.value),l=!0;break;case"APPLY":l=n.apply(t,c);break;case"CONSTRUCT":l=proxy(new n(...c));break;case"ENDPOINT":{const{port1:t,port2:n}=new MessageChannel;expose(e,n),l=transfer(t,[t])}break;case"RELEASE":l=void 0;break;default:return}}catch(e){l={value:e,[throwMarker]:0}}Promise.resolve(l).catch(e=>({value:e,[throwMarker]:0})).then(n=>{const[r,a]=toWireValue(n);t.postMessage(Object.assign(Object.assign({},r),{id:i}),a),"RELEASE"===s&&(t.removeEventListener("message",o),closeEndPoint(t),finalizer in e&&"function"==typeof e[finalizer]&&e[finalizer]())}).catch(e=>{const[n,o]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});t.postMessage(Object.assign(Object.assign({},n),{id:i}),o)})}),t.start&&t.start()}function isMessagePort(e){return"MessagePort"===e.constructor.name}function closeEndPoint(e){isMessagePort(e)&&e.close()}function wrap(e,t){const n=new Map;return e.addEventListener("message",function(e){const{data:t}=e;if(!t||!t.id)return;const o=n.get(t.id);if(o)try{o(t)}finally{n.delete(t.id)}}),createProxy(e,n,[],t)}function throwIfProxyReleased(e){if(e)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(e){return requestResponseMessage(e,new Map,{type:"RELEASE"}).then(()=>{closeEndPoint(e)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(proxyCounter.get(e)||0)-1;proxyCounter.set(e,t),0===t&&releaseEndpoint(e)});function registerProxy(e,t){const n=(proxyCounter.get(t)||0)+1;proxyCounter.set(t,n),proxyFinalizers&&proxyFinalizers.register(e,t,e)}function unregisterProxy(e){proxyFinalizers&&proxyFinalizers.unregister(e)}function createProxy(e,t,n=[],o=function(){}){let r=!1;const i=new Proxy(o,{get(o,s){if(throwIfProxyReleased(r),s===releaseProxy)return()=>{unregisterProxy(i),releaseEndpoint(e),t.clear(),r=!0};if("then"===s){if(0===n.length)return{then:()=>i};const o=requestResponseMessage(e,t,{type:"GET",path:n.map(e=>e.toString())}).then(fromWireValue);return o.then.bind(o)}return createProxy(e,t,[...n,s])},set(o,i,s){throwIfProxyReleased(r);const[a,c]=toWireValue(s);return requestResponseMessage(e,t,{type:"SET",path:[...n,i].map(e=>e.toString()),value:a},c).then(fromWireValue)},apply(o,i,s){throwIfProxyReleased(r);const a=n[n.length-1];if(a===createEndpoint)return requestResponseMessage(e,t,{type:"ENDPOINT"}).then(fromWireValue);if("bind"===a)return createProxy(e,t,n.slice(0,-1));const[c,l]=processArguments(s);return requestResponseMessage(e,t,{type:"APPLY",path:n.map(e=>e.toString()),argumentList:c},l).then(fromWireValue)},construct(o,i){throwIfProxyReleased(r);const[s,a]=processArguments(i);return requestResponseMessage(e,t,{type:"CONSTRUCT",path:n.map(e=>e.toString()),argumentList:s},a).then(fromWireValue)}});return registerProxy(i,e),i}function myFlat(e){return Array.prototype.concat.apply([],e)}function processArguments(e){const t=e.map(toWireValue);return[t.map(e=>e[0]),myFlat(t.map(e=>e[1]))]}const transferCache=new WeakMap;function transfer(e,t){return transferCache.set(e,t),e}function proxy(e){return Object.assign(e,{[proxyMarker]:!0})}function toWireValue(e){for(const[t,n]of transferHandlers)if(n.canHandle(e)){const[o,r]=n.serialize(e);return[{type:"HANDLER",name:t,value:o},r]}return[{type:"RAW",value:e},transferCache.get(e)||[]]}function fromWireValue(e){switch(e.type){case"HANDLER":return transferHandlers.get(e.name).deserialize(e.value);case"RAW":return e.value}}function requestResponseMessage(e,t,n,o){return new Promise(r=>{const i=generateUUID();t.set(i,r),e.start&&e.start(),e.postMessage(Object.assign({id:i},n),o)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function onParentPort(e){let t=null;const n=o=>{if(!ALLOWED_PARENT_ORIGINS.includes(o.origin))return;if(o.data!==INIT_MESSAGE_TYPE)return;const r=o.ports[0];r&&(window.removeEventListener("message",n),t=r,e(r))};window.addEventListener("message",n);try{window.parent.postMessage(READY_MESSAGE_TYPE,"*")}catch{}return{dispose(){window.removeEventListener("message",n),t?.close(),t=null}}}function exposeRpc(e){return onParentPort(t=>{expose(e,t)})}function wrapParentRpc(){let e=null;const t=onParentPort(t=>{t.start(),e=wrap(t)});return{getApi:()=>e,dispose(){t.dispose?.(),e=null}}}function querySpot(e,t){try{const n=e.querySelectorAll(t);return{element:n[0]??null,matchCount:n.length}}catch{return null}}function ensureShadowRoot(e){if(e.shadowRoot)return{ok:!0,shadow:e.shadowRoot};try{return{ok:!0,shadow:e.attachShadow({mode:"open"})}}catch(e){return{ok:!1,name:e instanceof Error?e.name:""}}}function classifyShadowError(e){switch(e){case"NotSupportedError":return"unsupported_element";case"InvalidStateError":return"already_has_shadow";default:return"injection_error"}}function applySpot(e,t){const n=querySpot(e,t.selector);if(!n)return{selector:t.selector,success:!1,reason:"invalid_spot"};if(!n.element)return{selector:t.selector,success:!1,reason:"not_found",matchCount:0};const o=ensureShadowRoot(n.element);if(!o.ok)return{selector:t.selector,success:!1,reason:classifyShadowError(o.name),matchCount:n.matchCount};const r=o.shadow;try{if(r.replaceChildren(),t.css){const n=e.createElement("style");n.textContent=t.css,r.appendChild(n)}if(t.html){const n=e.createElement("div");n.innerHTML=t.html,r.appendChild(n)}return{selector:t.selector,success:!0,matchCount:n.matchCount}}catch{return{selector:t.selector,success:!1,reason:"injection_error",matchCount:n.matchCount}}}function removeSpot(e,t){let n;try{n=e.querySelector(t.selector)}catch{return}const o=n?.shadowRoot;o&&o.replaceChildren(e.createElement("slot"))}function validateSpot(e){if(!e||"object"!=typeof e)return{ok:!1,reason:`not an object (${typeof e})`};const t=e;return"string"!=typeof t.selector?{ok:!1,reason:`selector not a string (${typeof t.selector})`}:0===t.selector.length?{ok:!1,reason:"selector empty"}:void 0!==t.html&&"string"!=typeof t.html?{ok:!1,reason:`html not a string (${typeof t.html})`}:void 0!==t.css&&"string"!=typeof t.css?{ok:!1,reason:`css not a string (${typeof t.css})`}:{ok:!0,spot:e}}function isSpotRef(e){if(!e||"object"!=typeof e)return!1;const t=e.selector;return"string"==typeof t&&t.length>0}function getSelector(e){return e&&"object"==typeof e&&"selector"in e?e.selector:null}function buildRpc(e){return{applySpots:async t=>(invariant$1(Array.isArray(t),"pagePersonalize/preview: applySpots requires an array"),t.map((t,n)=>{const o=validateSpot(t);if(!o.ok)return e.warn(`pagePersonalize/preview: applySpots[${n}] invalid_spot: ${o.reason}`),{selector:getSelector(t),success:!1,reason:"invalid_spot"};const r=applySpot(document,o.spot);return r.success||e.warn(`pagePersonalize/preview: applySpot "${r.selector}" -> ${r.reason}`+(void 0!==r.matchCount?` (matchCount=${r.matchCount})`:"")),r})),async removeSpots(t){invariant$1(Array.isArray(t),"pagePersonalize/preview: removeSpots requires an array");for(let n=0;n<t.length;n++){const o=t[n];isSpotRef(o)?removeSpot(document,o):e.warn(`pagePersonalize/preview: removeSpots[${n}] skipped malformed ref`)}}}}const previewHandler={mode:"preview",activate:e=>exposeRpc(buildRpc(e.log))},UNSTABLE_ID_PATTERNS=[/^[0-9]+$/,/^:r/,/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i],UNSTABLE_DATA_VALUE_PATTERNS=[/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,/^[a-z0-9]{20,}$/i],UNSTABLE_CLASS_PATTERNS=[/^css-/,/^sc-/,/^emotion-/,/^[a-zA-Z0-9]{5,}$/],SEMANTIC_TAGS=["main","nav","header","footer","aside","article","section"],ARIA_LANDMARK_ROLES=["banner","complementary","contentinfo","form","main","navigation","region","search"];function isStableId(e){return!UNSTABLE_ID_PATTERNS.some(t=>t.test(e))}function isStableDataValue(e){return!UNSTABLE_DATA_VALUE_PATTERNS.some(t=>t.test(e))}function isStableClass(e){return!e.startsWith("p13n-sdk-")&&!UNSTABLE_CLASS_PATTERNS.some(t=>t.test(e))}function isUnique(e){return 1===document.querySelectorAll(e).length}function validate(e,t){try{return document.querySelector(e)===t}catch{return!1}}function getTagName(e){return e.localName}function tryDirectAnchor(e){if(e.id&&isStableId(e.id)){const t=`#${CSS.escape(e.id)}`;if(validate(t,e))return t}for(const t of e.attributes)if(t.name.startsWith("data-")&&t.value&&isStableDataValue(t.value)){const n=`[${CSS.escape(t.name)}="${CSS.escape(t.value)}"]`;if(isUnique(n)&&validate(n,e))return n}for(const t of e.classList)if(isStableClass(t)){const n=`.${CSS.escape(t)}`;if(isUnique(n)&&validate(n,e))return n}const t=getTagName(e);for(const n of e.classList)if(isStableClass(n)){const o=`${t}.${CSS.escape(n)}`;if(isUnique(o)&&validate(o,e))return o}const n=e.getAttribute("role");if(n&&ARIA_LANDMARK_ROLES.includes(n)){const t=`[role="${n}"]`;if(isUnique(t)&&validate(t,e))return t}return SEMANTIC_TAGS.includes(t)&&isUnique(t)&&validate(t,e)?t:null}function getNthOfTypeIndex(e){const t=getTagName(e);let n=1,o=e.previousElementSibling;for(;o;)o.localName===t&&n++,o=o.previousElementSibling;return n}function buildRelativePath(e,t){const n=[];let o=t;for(;o&&o!==e;){const e=getTagName(o),t=getNthOfTypeIndex(o);n.unshift(`${e}:nth-of-type(${t})`),o=o.parentElement}return n.join(" > ")}function tryAnchoredPath(e){let t=e.parentElement;for(;t&&t!==document.documentElement;){const n=tryDirectAnchor(t);if(n){const o=`${n} > ${buildRelativePath(t,e)}`;if(validate(o,e))return o}t=t.parentElement}return null}function buildFullPath(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=getTagName(n),o=getNthOfTypeIndex(n);t.unshift(`${e}:nth-of-type(${o})`),n=n.parentElement}const o=`html > ${t.join(" > ")}`;return validate(o,e)?o:null}function generateSelector(e){if(!e||e===document.documentElement||e===document.body)return e===document.body?"body":"html";const t=tryDirectAnchor(e);if(t)return t;const n=tryAnchoredPath(e);return n||(buildFullPath(e)??e.localName)}const SDK_ATTR="data-p13n-sdk",HIGHLIGHT_CLASS="p13n-sdk-highlight",SUPPRESSED_EVENTS=["mousedown","mouseup","pointerdown","pointerup","keydown","keyup","focusin","submit"],INJECTED_CSS=`\n .${HIGHLIGHT_CLASS} {\n outline: 2px solid blue !important;\n outline-offset: -2px !important;\n cursor: crosshair !important;\n }\n .p13n-sdk-tooltip {\n position: fixed;\n z-index: 2147483647;\n background: rgba(0, 0, 0, 0.8);\n color: #fff;\n font-family: monospace;\n font-size: 12px;\n padding: 4px 8px;\n border-radius: 4px;\n pointer-events: none;\n white-space: nowrap;\n }\n`;function isSdkElement(e){let t=e;for(;t;){if(t.hasAttribute&&t.hasAttribute(SDK_ATTR))return!0;t=t.parentElement}return!1}function getElementDimensions(e){if(0!==e.offsetWidth)return{width:e.offsetWidth,height:e.offsetHeight};const t=e.getBoundingClientRect();return{width:Math.round(t.width),height:Math.round(t.height)}}function createSelectionRuntime(e){let t=null;const n=document.createElement("style");n.setAttribute(SDK_ATTR,""),n.textContent=INJECTED_CSS,document.head.appendChild(n);const o=document.createElement("div");function r(e){let t=e.clientX+15,n=e.clientY+15;const r=o.getBoundingClientRect(),i=r.width||150,s=r.height||24;t+i>window.innerWidth&&(t=e.clientX-15-i),n+s>window.innerHeight&&(n=e.clientY-15-s),o.style.left=`${t}px`,o.style.top=`${n}px`}function i(e){const n=e.target;if(!(n instanceof HTMLElement))return;if(isSdkElement(n))return;t&&t!==n&&t.classList.remove(HIGHLIGHT_CLASS),t=n,n.classList.add(HIGHLIGHT_CLASS);const i=n.localName,{width:s,height:a}=getElementDimensions(n);o.textContent=`${i} ${s}×${a}`,o.style.display="block",r(e)}function s(e){"block"===o.style.display&&r(e)}function a(e){const n=e.target;n instanceof HTMLElement&&(isSdkElement(n)||(t===n&&(n.classList.remove(HIGHLIGHT_CLASS),t=null),o.style.display="none"))}function c(e){isSdkElement(e.target)||(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation())}function l(t){const n=t.target;if(!(n instanceof HTMLElement))return;c(t);const o=generateSelector(n);e(o)}return o.className="p13n-sdk-tooltip",o.setAttribute(SDK_ATTR,""),o.style.display="none",document.body.appendChild(o),function(){document.addEventListener("mouseover",i,!0),document.addEventListener("mousemove",s,!0),document.addEventListener("mouseout",a,!0),document.addEventListener("click",l,!0);for(const e of SUPPRESSED_EVENTS)document.addEventListener(e,c,!0)}(),{dispose(){!function(){document.removeEventListener("mouseover",i,!0),document.removeEventListener("mousemove",s,!0),document.removeEventListener("mouseout",a,!0),document.removeEventListener("click",l,!0);for(const e of SUPPRESSED_EVENTS)document.removeEventListener(e,c,!0)}(),t&&(t.classList.remove(HIGHLIGHT_CLASS),t=null),o.style.display="none",o.remove(),n.remove(),t=null}}}const spotSelectionHandler={mode:"spot-selection",activate(e){const t=wrapParentRpc(),n=createSelectionRuntime(n=>{const o=t.getApi();o?o.onSpotSelected(n):e.log.warn("pagePersonalize/spot-selection: no parent RPC connection, cannot send selector")});return{dispose(){n.dispose?.(),t.dispose?.()}}}},MODE_HANDLERS={preview:previewHandler,"spot-selection":spotSelectionHandler};function readMode(){if("undefined"==typeof window||!window.location)return null;let e;try{e=new URLSearchParams(window.location.search).get(MODE_QUERY_PARAM)}catch{return null}return e&&Object.hasOwn(MODE_HANDLERS,e)?e:null}function runRouter(e){const t=readMode();if(!t)return null;let n;try{n=MODE_HANDLERS[t].activate(e)}catch(n){return e.log.error(`pagePersonalize: activation failed for mode "${t}":`,n),null}return n?t:null}function numAttr(e,t){const n=e[t];if("string"!=typeof n||0===n.length)return null;const o=Number(n);return Number.isFinite(o)?o:null}function strAttr(e,t){const n=e[t];return"string"==typeof n&&n.length>0?n:null}function isInWindow(e,t){const n=numAttr(e,"td_personalization.campaigns_start_date");if(null!==n&&t<n)return!1;const o=numAttr(e,"td_personalization.campaigns_end_date");return!(null!==o&&t>=o)}function isLiveOffer(e,t){const n=e.attributes;return!!n&&"object"==typeof n&&isInWindow(n,t)}function toScoredOffer(e){const t=e.attributes;if(!t)return null;const n=numAttr(t,"td_personalization.audience_rank");if(null===n)return null;return{offer:e,updated:numAttr(t,"td_personalization.campaign_updated_at")??-1/0,rank:n}}function maxBy(e,t){return e.reduce((e,n)=>null===e||t(n,e)?n:e,null)}function selectWinningOffer(e,t=Date.now()/1e3){const n=e?.offers;if(!n||"object"!=typeof n)return null;const o=maxBy(Object.values(n).filter(e=>isLiveOffer(e,t)).flatMap(e=>toScoredOffer(e)??[]),(e,t)=>e.updated>t.updated||e.updated===t.updated&&e.rank<t.rank);return o?.offer??null}function parseEntries(e){if("string"!=typeof e)return null;try{const t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function toSpot(e){if(!e||"object"!=typeof e)return null;const{css_selector:t,html_value:n,css_value:o}=e;return"string"!=typeof t||0===t.length||"string"!=typeof n||"string"!=typeof o?null:{selector:t,html:n,css:o}}function decodeEntry(e,t){const n=toSpot(e);if(!n)return null;const o=e.id,r="number"==typeof o&&Number.isFinite(o)?String(o):null;return{spot:n,impression:t&&r?{campaign:t,creative:r}:null}}function decodeOffers(e,t){const n=selectWinningOffer(e,t);if(!n)return[];const o=n.attributes,r=o?strAttr(o,"td_personalization.campaign"):null,i=parseEntries(o?.["td_personalization.content"]);return i?i.flatMap(e=>decodeEntry(e,r)??[]):[]}const PERSONALIZATION_DATABASE="td_c360_personalization",PERSONALIZATION_TABLE="events",CLICKABLE_SELECTOR='a, button, [role="button"], [role="link"]',CAMPAIGN_ATTR="data-td-personalization-campaign",CREATIVE_ATTR="data-td-personalization-creative";function pagePersonalize(){return{name:"pagePersonalize",setup(e,t){const n=runRouter(e);function o(e,n){const o="function"==typeof t.getTrackValues?t.getTrackValues():{};t.addRecord("events",{...o,td_event:e,td_personalization_campaign:n.campaign,td_personalization_creative:n.creative},void 0,void 0,{database:PERSONALIZATION_DATABASE})}function r(e){const t=e.target;if(!(t instanceof Element&&t.closest(CLICKABLE_SELECTOR)))return;const n=e.currentTarget.host,r=n.getAttribute(CAMPAIGN_ATTR),i=n.getAttribute(CREATIVE_ATTR);r&&i&&o("click",{campaign:r,creative:i})}function i(e,t){const n=document.querySelector(e);n?.shadowRoot&&(n.setAttribute(CAMPAIGN_ATTR,t.campaign),n.setAttribute(CREATIVE_ATTR,t.creative),n.shadowRoot.addEventListener("click",r))}function s(e,t){if("undefined"!=typeof document&&(null===n||t?.force))for(const{spot:t,impression:n}of decodeOffers(e)){applySpot(document,t).success&&n&&(o("impression",n),i(t.selector,n))}}return{applyPersonalization:s,personalizePage:function(o,r,i,a){if(null!==n)return void e.log.debug(`pagePersonalize: personalizePage suppressed in "${n}" mode`);const c={};"undefined"!=typeof document&&document.location&&(c.td_url=document.location.href.split("#")[0],c.td_host=document.location.host,c.td_path=document.location.pathname),Object.assign(c,r),t.fetchPersonalization(o,c,e=>{const t=e;s(t),i?.(t)},a)}}}}}function globalId(){return{name:"globalId",setup(e,t){const n=e.config,o=()=>{};return{fetchGlobalID:function(e,r,i=!1,s={}){const a=e||o,c=r||o;if(!t.inSignedMode())return c("not in signed in mode");if(!t.isGlobalIdEnabled())return c("global id is not enabled");const l=n.globalIdCookie||"_td_global",u=cookie.getItem(l);if(u&&!i)return void setTimeout(()=>a(u),0);const d=s.sameSite||"None",p=`https://${n.host}`,g={Authorization:`TD1 ${n.writeKey}`,"Content-Type":globalIdAdlHeaders["Content-Type"],Accept:globalIdAdlHeaders.Accept};"undefined"!=typeof navigator&&(g["User-Agent"]=navigator.userAgent),api.get(p,{headers:g}).then(e=>{if(!e.global_id)return void a(null);const t=e.global_id,n=s.maxAge??6e3;cookie.setItem(l,t,n,s.path,s.domain,s.secure,d),a(t)}).catch(e=>{c(e)})}}}}}const LOADER_METHODS=["set","collectTags","blockEvents","unblockEvents","setSignedMode","setAnonymousMode","fetchServerCookie","fetchGlobalID","fetchUserSegments","fetchPersonalization","resetUUID","addRecord","trackEvent","trackPageview","trackClicks","ready"];function escapeForInlineScript(e){return e.replace(/[<>\u2028\u2029/]/g,e=>{switch(e){case"<":return"\\u003C";case">":return"\\u003E";case"/":return"\\u002F";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}function createLoader(e,t){return`!function(t,e){if(void 0===e[t]){e[t]=function(){e[t].clients.push(this),this._init=[Array.prototype.slice.call(arguments)]},e[t].clients=[];for(var r=function(t){return function(){return this["_"+t]=this["_"+t]||[],this["_"+t].push(Array.prototype.slice.call(arguments)),this}},s=${escapeForInlineScript(JSON.stringify(LOADER_METHODS))},c=0;c<s.length;c++){var o=s[c];e[t].prototype[o]=r(o)}var n=document.createElement("script");n.type="text/javascript",n.async=!0,n.src=("https:"===document.location.protocol?"https:":"http:")+${escapeForInlineScript(JSON.stringify(t))};var i=document.getElementsByTagName("script")[0];i.parentNode.insertBefore(n,i)}}(${escapeForInlineScript(JSON.stringify(e))},this);`}function processQueuedCalls(e,t){e._init&&e._init.length,LOADER_METHODS.forEach(n=>{const o=e["_"+n];o&&Array.isArray(o)&&o.length>0&&o.forEach(e=>{"function"==typeof t[n]&&t[n].apply(t,e)})})}function replaceLoaderStub(e,t){const n="undefined"!=typeof window?window:globalThis;if(n[e]&&n[e].clients){const o=n[e].clients;n[e]=t,o.forEach(e=>{let n;if(e._init&&e._init.length>0){const o=e._init[0];n=new t(...o||[])}else n=new t;processQueuedCalls(e,n),Object.setPrototypeOf(e,n),Object.assign(e,n)})}}class Treasure{_sdk;constructor(e){return this instanceof Treasure?(this._sdk=this.init(e),this.bindMethods(),this):new Treasure(e)}init(e){return createSDK(configure(e)).use(session()).use(record()).use(track()).use(clicks()).use(utm()).use(personalization()).use(conversionAPI()).use(serverCookie()).use(globalId()).use(pagePersonalize())}bindMethods(){const e=new Set;let t=this._sdk;for(;t&&t!==Object.prototype;)Object.getOwnPropertyNames(t).forEach(n=>{"function"==typeof t[n]&&"constructor"!==n&&e.add(n)}),t=Object.getPrototypeOf(t);e.forEach(e=>{this.hasOwnProperty(e)||"init"===e||"bindMethods"===e||(this[e]=this._sdk[e].bind(this._sdk))})}get sdk(){return this._sdk}get config(){return this._sdk.config}static version="1.0.0";get version(){return Treasure.version}addRecord=(e,t,n,o,r)=>this._sdk.addRecord(e,t,n,o,r);trackEvent=(e,t,n,o)=>this._sdk.trackEvent(e,t,n,o);trackPageview=(e,t,n,o)=>this._sdk.trackPageview(e,t,n,o);trackClicks=e=>this._sdk.trackClicks(e);fetchUserSegments(e,t,n){return this._sdk.fetchUserSegments(e,t,n)}fetchPersonalization=(e,t,n,o)=>this._sdk.fetchPersonalization(e,t,n,o);applyPersonalization=(e,t)=>{this._sdk.applyPersonalization(e,t)};personalizePage=(e,t,n,o)=>{this._sdk.personalizePage(e,t,n,o)};collectUTMParameters=()=>this._sdk.collectUTMParameters();getUTMParameters=()=>this._sdk.getUTMParameters();set=(e,t,n)=>this._sdk.set(e,t,n);get=(e,t)=>this._sdk.get(e,t);setSignedMode=()=>this._sdk.setSignedMode();setAnonymousMode=e=>this._sdk.setAnonymousMode(e);inSignedMode=()=>this._sdk.inSignedMode();blockEvents=()=>this._sdk.blockEvents();unblockEvents=()=>this._sdk.unblockEvents();areEventsBlocked=()=>this._sdk.areEventsBlocked();resetUUID=()=>this._sdk.resetUUID();getTrackValues=()=>this._sdk.getTrackValues();getPersonalizationConfig=()=>this._sdk.getPersonalizationConfig();setPersonalizationConfig=e=>this._sdk.setPersonalizationConfig(e);getWriteKey=()=>this._sdk.getWriteKey();setWriteKey=e=>this._sdk.setWriteKey(e);collectTags=e=>this._sdk.collectTags(e);fetchServerCookie=(e,t,n)=>this._sdk.fetchServerCookie(e,t,n);fetchGlobalID=(e,t,n,o)=>this._sdk.fetchGlobalID(e,t,n,o)}function initSDK(e="td"){"undefined"!=typeof window&&(replaceLoaderStub(e,Treasure),window[e]||(window[e]=Treasure))}if("undefined"!=typeof window&&replaceLoaderStub("Treasure",Treasure),"undefined"!=typeof window&&"undefined"!=typeof document){const e=document.getElementsByTagName("script"),t=e[e.length-1];if(t&&t.hasAttribute("data-auto-init")){initSDK(t.getAttribute("data-global-name")||"td")}}const version="1.0.0";exports.BLOCKEVENTSCOOKIE=BLOCKEVENTSCOOKIE,exports.DEFAULT_CONFIG=DEFAULT_CONFIG,exports.SERVER_COOKIE_NAME=SERVER_COOKIE_NAME,exports.SIGNEDMODECOOKIE="__td_signed",exports.Treasure=Treasure,exports._validateRecord=_validateRecord,exports.adlHeaders=adlHeaders,exports.clicks=clicks,exports.configure=configure,exports.conversionAPI=conversionAPI,exports.cookie=cookie,exports.createLoader=createLoader,exports.createSDK=createSDK,exports.default=Treasure,exports.elementUtils=element,exports.generateUUID=generateUUID$1,exports.globalId=globalId,exports.globalIdAdlHeaders=globalIdAdlHeaders,exports.initSDK=initSDK,exports.invariant=invariant$1,exports.isLocalStorageAccessible=isLocalStorageAccessible,exports.isValidUUID=isValidUUID,exports.pagePersonalize=pagePersonalize,exports.personalization=personalization,exports.processQueuedCalls=processQueuedCalls,exports.record=record,exports.replaceLoaderStub=replaceLoaderStub,exports.serverCookie=serverCookie,exports.session=session,exports.setCookie=setCookie,exports.track=track,exports.utm=utm,exports.version="1.0.0";
@@ -0,0 +1 @@
1
+ var Treasure=function(){"use strict";function e(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function t(e){return"string"==typeof e}function n(e){return Array.isArray(e)}function o(o){return null==o||(n(o)||t(o)?0===o.length:!!e(o)&&0===Object.keys(o).length)}function r(e){let t=!1;return function(){t||(t=!0,e())}}function i(e,t){if(!e)throw new Error(t)}function s(){const e="__td__";try{return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch{return!1}}const a={"Content-Type":"application/vnd.treasuredata.v1+json",Accept:"application/vnd.treasuredata.v1+json"},c={"Content-Type":"application/vnd.treasuredata.v1.js+json",Accept:"application/vnd.treasuredata.v1.js+json"},u="1.0.0",l="us01.records.in.treasuredata.com",d="",f="/";function p(e){try{return encodeURIComponent(e)}catch(e){return null}}function g(e){try{return decodeURIComponent(e)}catch(e){return null}}const m={getItem(e){if(!e)return null;const t=new RegExp("(?:(?:^|.*;)\\s*"+function(e){const t=p(e);return t?t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"):""}(e)+"\\s*\\=\\s*([^;]*).*$)|^.*$");return g(document.cookie.replace(t,"$1"))||null},setItem(e,t,n,o,r,i,s){if(!e||/^(?:expires|max\-age|path|domain|secure)$/i.test(e))return!1;let a="";n&&("number"==typeof n?a=n===1/0?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+n:"string"==typeof n?a="; expires="+n:n instanceof Date&&(a="; expires="+n.toUTCString()));let c="";s&&"NONE"===s.toUpperCase()?c="; Secure; SameSite="+s:(i&&(c+="; Secure"),s&&(c+="; SameSite="+s));const u=p(e),l=p(t);return!(!u||!l)&&(document.cookie=[u,"=",l,a,r?"; domain="+r:"",o?"; path="+o:"",c].join(""),!0)},removeItem(e,t,n){if(!this.hasItem(e))return!1;const o=p(e);return!!o&&(document.cookie=[o,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT",n?"; domain="+n:"",t?"; path="+t:""].join(""),!0)},hasItem(e){if(!e)return!1;const t=p(e);return!!t&&new RegExp("(?:^|;\\s*)"+t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")+"\\s*\\=").test(document.cookie)},keys:()=>document.cookie.replace(/((?:^|\s*;)[^=]+)(?=;|$)|^\s*|\s*(?:=[^;]*)?(?:\1|$)/g,"").split(/\s*(?:=[^;]*)?;\s*/).map(e=>g(e)).filter(e=>null!==e)};const h={database:d,development:!1,globalIdCookie:"_td_global",host:l,logging:!0,pathname:f,requestType:"fetch",jsonpTimeout:1e4,startInSignedMode:!1,useServerSideCookie:!1,sscDomain:function(){if("undefined"==typeof document)return"localhost";const e=document.location.hostname.split(".");for(let t=e.length-2;t>=1;t--){const n=e.slice(t).join("."),o="_td_domain_"+n;if(m.setItem(o,n,3600,"/",n),m.getItem(o)===n)return n}return document.location.hostname},sscServer:function(e){return["ssc",e].join(".")},storeConsentByLocalStorage:!1};function _(n){const o=function(e,...t){return Object.assign(e,...t)}({},{globals:{}},h,n,{requestType:"fetch"});return function(n){i(e(n),"Check out our JavaScript SDK Usage Guide: https://github.com/treasure-data/td-js-sdk#api"),i(t(n.writeKey),"Must provide a writeKey"),i(t(n.database),"Must provide a database"),i(n.database&&/^[a-z0-9_]{3,255}$/.test(n.database),"Database must be between 3 and 255 characters and must consist only of lower case letters, numbers, and _")}(o),o.endpoint||(o.endpoint="https://"+o.host+o.pathname),o.storage||(o.storage={name:"_td",domain:"undefined"!=typeof window&&"undefined"!=typeof document?document.location.hostname:"localhost",expires:63072e3,path:"/"}),o}function y(e,t,n){const o={...e},r=e.domain.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/),i="localhost"===e.domain,s=e.customDomain,a=new Date;if(a.setSeconds(a.getSeconds()+o.expires),i)n?m.setItem(t,n,a,o.path):m.removeItem(t,o.path,o.domain);else if(r||s)n?m.setItem(t,n,a,o.path,o.domain,!0,"None"):m.removeItem(t,o.path,o.domain);else{const r=function(e){const t=e.split("."),n=[];for(let e=t.length-1;e>=0;e--)n.push(t.slice(e).join("."));return n}(e.domain),i=r.length;let s=0;if(n){if(m.getItem(t)===n)return;for(;s<i;s++)if(o.domain=r[s],m.setItem(t,n,a,o.path,o.domain,!0,"None"),m.getItem(t)===n){e.domain=o.domain;break}}else for(;s<i;s++)m.removeItem(t,e.path,r[s])}}function b(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}throw new Error("Secure random number generation is not available in this environment")}const k={"same-origin":"same-origin",include:"include",omit:"omit"};function v(e){let t;try{t=JSON.parse(e)}catch{t={}}return t}function w(e={}){return k[e.credentials||"include"]||"include"}function E(e,t,n={}){const o=n.headers||{},r=w(n),i={method:"POST",headers:o,keepalive:!0,body:JSON.stringify(t)};return i.credentials=r,n.signal&&(i.signal=n.signal),fetch(e,i).then(function(e){if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.text()}).then(function(e){return v(e)})}function C(e,t={}){const n=t.headers||{},o=w(t),r={method:"GET",headers:n};return r.credentials=o,t.signal&&(r.signal=t.signal),fetch(e,r).then(function(e){if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.text()}).then(function(e){return v(e)})}function S(e,t,n){const o=new AbortController;let r;const i=new Promise((e,i)=>{r=setTimeout(()=>{o.abort(),i(new Error(n||"Operation Timeout"))},t)}),s=e(o.signal).finally(()=>{clearTimeout(r)});return Promise.race([s,i]).catch(e=>{if(clearTimeout(r),"AbortError"===e.name)throw new Error(n||"Operation Timeout");throw e})}const j={post:E,get:C,postWithTimeout:function(e,t,n,o={}){return S(n=>E(e,t,{...o,signal:n}),n,"Request Timeout")},getWithTimeout:function(e,t,n={}){return S(t=>C(e,{...n,signal:t}),t,"Request Timeout")},withTimeout:S,timeoutPromise:function(e,t,n){return S(t=>e(),t,n)}},$="_td_ssc_id",P=$;function T(){return{name:"serverCookie",setup(e,t){const n=e.config;let o,r;const i=()=>{};return{fetchServerCookie:function(e,s,a=!1){const c=e||i,u=s||i;if("function"==typeof t.inSignedMode&&!t.inSignedMode())return u("not in signed in mode");if(!n.useServerSideCookie)return u("server side cookie not enabled");if(r||(o="function"==typeof n.sscDomain?n.sscDomain():n.sscDomain||("undefined"!=typeof window?window.location.hostname:"localhost"),r="function"==typeof n.sscServer?n.sscServer(o):n.sscServer||`ssc.${o}`),!o||!r)return u("server cookie configuration not properly initialized");const l=`https://${r}/get_cookie_id?cookie_domain=${encodeURIComponent(o)}&r=${Date.now()}`,d=m.getItem(P);!d||a?j.getWithTimeout(l,1e4).then(e=>{c(e.td_ssc_id)}).catch(e=>{u(e)}):setTimeout(()=>{c(d)},0)}}}}}const x="__td_blockEvents",I="__td_signed";function z(e){if("none"===e)return null;const t="object"==typeof e&&null!==e?e:{};return{name:t.name||"_td",expires:t.expires??63072e3,domain:t.domain||document.location.hostname,customDomain:!!t.domain,path:t.path||"/"}}function A(e,t,n){try{y(e,t,n||"")}catch{}}function L(){return{name:"record",setup(n,o){const r=n.config,s=r.host||"us01.records.in.treasuredata.com",u=r.pathname||"/",l=r.endpoint||`https://${s}${u}`;let d=!1;if("undefined"!=typeof window&&window.addEventListener){const e=()=>{d=!0};window.addEventListener("beforeunload",e),window.addEventListener("unload",e),n._unloadHandlers=[()=>window.removeEventListener("beforeunload",e),()=>window.removeEventListener("unload",e)]}n._windowBeingUnloaded=()=>d;return{addRecord(s,u,d,f,p){!function(n,o){i(t(n),"Must provide a table"),i(/^[a-z0-9_]{3,255}$/.test(n),"Table must be between 3 and 255 characters and must consist only of lower case letters, numbers, and _"),i(e(o),"Must provide a record")}(s,u);const g=function(e,t){return Object.assign({},o.get("$global"),o.get(e),t)}(s,u),m=o.inSignedMode()?g:function(e,t){const n={};for(const o of Object.keys(e))if(!t.includes(o)){const t=e[o];void 0!==t&&(n[o]=t)}return n}(g,["td_ip","td_client_id","td_global_id"]),h={apikey:r.writeKey,record:m,time:null,url:`${l}${p?.database??r.database}/${s}`};null!=h.record.time&&(h.time=h.record.time),r.development?(n.log.debug("addRecord",h),d?.({success:!0,message:"Development mode - record not sent"})):o.areEventsBlocked()||async function(e,t,n){const o=()=>{},r=t||o,i=n||o,s=["modified="+encodeURIComponent((new Date).getTime())];e.time&&s.push("time="+encodeURIComponent(e.time));const u=e.url+"?"+s.join("&"),l="a"===e.record.tag&&!!e.record.href,d={};d.Authorization="TD1 "+e.apikey,"undefined"!=typeof navigator&&(d["User-Agent"]=navigator.userAgent);e.inSignedMode&&e.isGlobalIdEnabled?Object.assign(d,c):Object.assign(d,a);const f={events:[e.record]};try{if("undefined"!=typeof window&&(e.windowBeingUnloaded||l)){r(await j.postWithTimeout(u,f,e.timeoutMs,{headers:d,credentials:"include"}))}else{r(await j.post(u,f,{headers:d,credentials:"include"}))}}catch(e){i(e instanceof Error?{...e,name:e.name,message:e.message}:new Error("Unknown error occurred"))}}({...h,inSignedMode:o.inSignedMode(),isGlobalIdEnabled:o.isGlobalIdEnabled(),windowBeingUnloaded:n._windowBeingUnloaded?.()??!1,timeoutMs:r.jsonpTimeout??6e4},d,f)}}}}}const M="td-engage-popup-container";let O=null,N=!1,U=[];function D(e){try{const t=e["td_in_browser.messages"];return t?JSON.parse(t):[]}catch{return[]}}function R(){document.getElementById(M)?.remove()}function W(){R(),O&&(O.disconnect(),O=null),U=[]}function G(e){try{const t=function(e){if("object"==typeof e&&null!==e)return e;try{return JSON.parse(e)}catch{return{}}}(e.appearance_setting),n=window.innerWidth>620;R();const o=t.position?.placement??"center",r=o.startsWith("top"),i=o.startsWith("bottom"),s=o.endsWith("left"),a=o.endsWith("right"),c=n?t.inset?.desktop??40:t.inset?.mobile??16,u=n?t.width?.desktop_max_width??600:t.width?.mobile_max_width??300,l=document.createElement("div");l.id=M;const d=i?"end":r?"start":"center",f=s?"start":a?"end":"center";Object.assign(l.style,{position:!1===t.position?.fixed_on_scroll?"absolute":"fixed",inset:"0",display:"grid",placeItems:`${d} ${f}`,padding:`${c}px`,pointerEvents:"none",boxSizing:"border-box"}),l.style.setProperty("z-index","var(--td-popup-z-index, 2147483647)");const p=l.attachShadow({mode:"open"}),g=document.createElement("style");if(g.textContent="\n :host { --td-popup-z-index: 2147483647; --td-popup-frame-z-index: 1; --td-close-btn-cursor: pointer; --td-close-btn-line-height: 1; }\n .td-overlay { position: fixed; inset: 0; pointer-events: auto; }\n .td-frame { position: relative; width: 100%; pointer-events: auto; box-sizing: border-box; z-index: var(--td-popup-frame-z-index); }\n .td-close { position: absolute; background: transparent; border: none; cursor: var(--td-close-btn-cursor); line-height: var(--td-close-btn-line-height); padding: 0; display: flex; align-items: center; justify-content: center; z-index: 1; }\n ",p.appendChild(g),t.overlay?.enabled){const e=document.createElement("div");e.className="td-overlay",Object.assign(e.style,{background:t.overlay.color??"#000000B3"}),t.overlay.close_on_click_outside&&e.setAttribute("data-engage-popup-close",""),p.appendChild(e)}const m=document.createElement("div");m.className="td-frame";const h=t.background?.padding??0;if(Object.assign(m.style,{maxWidth:`${u}px`,background:t.background?.color??"#FFFFFF",borderRadius:`${t.background?.border_radius??8}px`,padding:`${h}px`}),!1!==t.close_button?.enabled){const e=t.close_button?.size??28,n=t.close_button?.offset_top??2,o=t.close_button?.offset_right??4,r=document.createElement("button");r.type="button",r.className="td-close",r.setAttribute("aria-label","Close"),r.setAttribute("data-engage-popup-close",""),Object.assign(r.style,{top:`${n}px`,right:`${o}px`,width:`${e}px`,height:`${e}px`,fontSize:.7*e+"px",color:t.close_button?.color??"#FFFFFF"}),r.textContent="×",m.appendChild(r)}const _=document.createElement("div");_.innerHTML=e.content_html,m.appendChild(_),p.appendChild(m),p.addEventListener("click",e=>{e.target.hasAttribute("data-engage-popup-close")&&l.remove()}),document.body.appendChild(l)}catch{}}function F(e){if(e.css_selector)try{const t=document.querySelectorAll(e.css_selector);for(const n of t)n.innerHTML=e.content_html}catch{}}function K(e,t){const n=Number(t.created_at_millisecond??0)-Number(e.created_at_millisecond??0);if(0!==n)return n;const o=t._sectionName.localeCompare(e._sectionName);return 0!==o?o:t._arrayIndex-e._arrayIndex}function Y(){for(const e of U)F(e)}function B(e){try{const t=function(e){const t=e.offers;if(!t)return[];const n=[];for(const[e,o]of Object.entries(t)){const t=o?.td_app;t&&D(t).forEach((t,o)=>{n.push({...t,_sectionName:e,_arrayIndex:o})})}return n}(e);if(0===t.length)return;if(function(){if(!N&&"undefined"!=typeof window&&window.history){window.addEventListener("popstate",W),window.addEventListener("hashchange",W);try{const e=e=>{const t=window.history[e];window.history[e]=function(...e){const n=t.apply(this,e);return W(),n}};e("pushState"),e("replaceState")}catch{}N=!0}}(),null===document.getElementById(M)){const e=function(e){return e.filter(e=>"popup"===e.type).sort(K)[0]}(t);e&&G(e)}const n=function(e){return e.filter(e=>"inline"===e.type&&e.css_selector).sort((e,t)=>-K(e,t))}(t);n.length>0&&(U.push(...n),Y(),O&&(O.disconnect(),O=null),0!==U.length&&(O=new MutationObserver(()=>{O.disconnect(),Y(),O.observe(document.body,{childList:!0,subtree:!0})}),O.observe(document.body,{childList:!0,subtree:!0})))}catch{}}function H(e,t){return{td_version:()=>t,td_client_id:e,td_charset:()=>(document.characterSet||document.charset||"-").toLowerCase(),td_language:()=>{const e=navigator;return(e&&(e.language||e.browserLanguage)||"-").toLowerCase()},td_color:()=>screen?screen.colorDepth+"-bit":"-",td_screen:()=>screen?`${screen.width}x${screen.height}`:"-",td_viewport:()=>{const e=document.documentElement&&document.documentElement.clientHeight,t=document.documentElement&&document.documentElement.clientWidth,n=window.innerHeight,o=window.innerWidth;return`${(t||0)<o?o:t||0}x${(e||0)<n?n:e||0}`},td_title:()=>document.title,td_description:()=>function(e){const t=(document.head||document.getElementsByTagName("head")[0]).getElementsByTagName("meta"),n=t.length;for(let o=0;o<n;o++){const n=t[o];if(n&&n.getAttribute("name")===e)return(n.getAttribute("content")||"").substr(0,8192)}return""}("description"),td_url:()=>document.location&&document.location.href&&document.location.href.split("#")[0]||"",td_user_agent:()=>[navigator.userAgent,`WEBSDK/${t}`].join(";"),td_platform:()=>navigator.platform||navigator.userAgentData?.platform||"-",td_host:()=>document.location.host,td_path:()=>document.location.pathname,td_referrer:()=>document.referrer}}function q(e){const t=[];let n=0,o=0;let r,i=e;for(;i&&n++<5&&(r=J(i),!("html"===r||n>1&&o+3*t.length+r.length>=80));)t.push(r),o+=r.length,i=i.parentNode;const s=t.reverse().join(" > ");return s.length>80?s.substring(0,77)+"...":s}function J(e){const n=[];let o,r,i,s;if(!e||!e.tagName)return"";n.push(e.tagName.toLowerCase()),e.id&&n.push("#"+e.id);const a=e.className;if(a&&t(a))for(o=a.split(" "),s=0;s<o.length;s++){const e=o[s];e&&e.trim()&&n.push("."+e.trim())}const c=["type","name","title","alt"];for(s=0;s<c.length;s++)r=c[s],i=e.getAttribute(r),i&&n.push("["+r+'="'+i+'"]');return n.join("")}function V(e,t){return"function"==typeof e.hasAttribute?e.hasAttribute(t):null!==e.getAttribute(t)}function X(){return{name:"clicks",setup(e,t){let n=!1;return{trackClicks(e){if(n)return;const o={element:e?.element??window.document,extendClickData:e?.extendClickData??((e,t)=>t),ignoreAttribute:e?.ignoreAttribute??"td-ignore",tableName:e?.tableName??"clicks"},i=function(e){const t="data-"+e;return function n(o){return!(!o||!o.tagName||"html"===o.tagName.toLowerCase())&&(!(!V(o,e)&&!V(o,t))||n(o.parentNode))}}(o.ignoreAttribute),s=function(e,t,n){if("addEventListener"in e)return e.addEventListener(t,o,!1),r(()=>{e.removeEventListener(t,o,!1)});if("attachEvent"in e)return e.attachEvent("on"+t,o),r(()=>{e.detachEvent("on"+t,o)});throw new Error("addEventListener not supported");function o(t){n.call(e,t||window.event)}}(o.element,"click",e=>{const n=function(e){const t=e.target||e.srcElement||document;return 3===t.nodeType?t.parentNode:t}(e),r=function(e){if(!e||!e.tagName)return null;let t=e,n=t.tagName.toLowerCase();for(;n&&"body"!==n&&t;){const e=t.getAttribute("type");if("input"===n&&"password"===e)return null;const o=t.getAttribute("role");if("button"===o||"link"===o||"a"===n||"button"===n||"input"===n)return t;t=t.parentNode,n=t&&t.tagName?t.tagName.toLowerCase():""}return null}(n);if(r&&!i(r)){const n=function(e){const t={tag:e.tagName.toLowerCase(),tree:q(e)};return["alt","class","href","id","name","role","title","type"].forEach(n=>{if(V(e,n)){const o=e.getAttribute(n);o&&(t[n]=o)}}),t}(r),i=o.extendClickData(e,n);i&&t.trackEvent(o.tableName,i)}});return n=!0,r(()=>{s(),n=!1})}}}}}const Z=["utm_id","utm_medium","utm_source_platform","utm_source","utm_campaign","utm_marketing_tactic"];function Q(t={}){return{name:"utm",setup(n,r){const i={customParameters:t.customParameters||Z,autoCollect:t.autoCollect??!0,table:t.table||"$global"};let s={};function a(){const t=function(e=Z){if("undefined"==typeof window||!window.location)return{};const t=window.location.search,n=new(window.URLSearchParams||URLSearchParams)(t);return e.some(e=>n.has(e))?e.reduce((e,t)=>{const o=n.get(t);return o&&(e[t]=o),e},{}):{}}(i.customParameters);return e(t)&&!o(t)&&("$global"===i.table?r.set(t):Object.keys(t).forEach(e=>{r.set(i.table,e,t[e])}),s={...s,...t}),t}return i.autoCollect&&a(),{getUTMParameters:function(){return{...s}},collectUTMParameters:a}}}}function ee(e,t){if(!e)throw new Error(t)}const te={google_ads:["getGoogle_gclid_Param","getGoogle_wbraid_Param"],google_ga:["getGoogle_ga_Cookie"],google_mp:["getGoogle_gcl_Cookies"],meta:["getFacebook_fbp_Cookie","getFacebook_fbc_Cookie","getFacebook_fbclid_Param"],instagram:["getInstagram_shbts_Cookie","getInstagram_shbid_Cookie","getInstagram_ds_user_id_Cookie","getInstagram_ig_did_Cookie"],yahoojp_ads:["getYahoo_ly_c_Param","getYahoo_ly_c_Cookie","getYahoo_ly_r_Cookie","getYahoo_ly_su_Cookie","getYahoo_yclid_Param","getYahoo_yj_r_Param","getYahoo_ycl_yjad_Cookie","getYahoo_yjr_yjad_Cookie","getYahoo_yjsu_yjad_Cookie"],line:["getLine_lt_cid_Cookie","getLine_lt_sid_Cookie","getLine_ldtag_cl_Param"],x:["getX_twclid_Param","getX_twclid_Cookie"],pinterest:["getPinterest_epik_Param","getPinterest_epik_Cookie"],snapchat:["getSnapchat_sccid_Param"],tiktok:["getTiktok_ttp_Cookie"],marketo:["getMarketo_mkto_trk_Cookie"],tealium:["getTealium_utag_main_Cookie"]};function ne(e){return"undefined"==typeof document?null:m.getItem(e)}function oe(e){if("undefined"==typeof window||!window.location)return null;const t=window.location.search;return new(window.URLSearchParams||URLSearchParams)(t).get(e)}function re(){return{name:"conversionAPI",setup(e,t){const n={getGoogle_gclid_Param:()=>({gclid:oe("gclid")}),getGoogle_wbraid_Param:()=>({wbraid:oe("wbraid")}),getGoogle_ga_Cookie:()=>({_ga:ne("_ga")}),getGoogle_gcl_Cookies:(e={})=>function(e){return"undefined"==typeof document?{}:m.keys().filter(t=>t.startsWith(e)).reduce((e,t)=>{const n=m.getItem(t);return null!==n&&(e[t]=n),e},{})}(e.gclPrefix||"_gcl"),getFacebook_fbp_Cookie:()=>({_fbp:ne("_fbp")}),getFacebook_fbc_Cookie:()=>({_fbc:ne("_fbc")}),getFacebook_fbclid_Param:()=>({fbclid:oe("fbclid")}),getInstagram_shbts_Cookie:()=>({shbts:ne("shbts")}),getInstagram_shbid_Cookie:()=>({shbid:ne("shbid")}),getInstagram_ds_user_id_Cookie:()=>({ds_user_id:ne("ds_user_id")}),getInstagram_ig_did_Cookie:()=>({ig_did:ne("ig_did")}),getYahoo_yclid_Param:()=>({yclid:oe("yclid")}),getYahoo_yj_r_Param:()=>({yj_r:oe("yj_r")}),getYahoo_ycl_yjad_Cookie:()=>({_ycl_yjad:ne("_ycl_yjad")}),getYahoo_yjr_yjad_Cookie:()=>({_yjr_yjad:ne("_yjr_yjad")}),getYahoo_yjsu_yjad_Cookie:()=>({_yjsu_yjad:ne("_yjsu_yjad")}),getYahoo_ly_c_Param:()=>({ly_c:oe("_ly_c")}),getYahoo_ly_c_Cookie:()=>({ly_c:ne("_ly_c")}),getYahoo_ly_r_Cookie:()=>({ly_r:ne("_ly_r")}),getYahoo_ly_su_Cookie:()=>({ly_su:ne("_ly_su")}),getLine_lt_cid_Cookie:()=>({__lt_cid:ne("__lt__cid")}),getLine_lt_sid_Cookie:()=>({__lt_sid:ne("__lt__sid")}),getLine_ldtag_cl_Param:()=>({ldtag_cl:oe("ldtag_cl")}),getX_twclid_Param:()=>({twclid:oe("twclid")}),getX_twclid_Cookie:()=>({_twclid:ne("_twclid")}),getPinterest_epik_Param:()=>({epik:oe("epik")}),getPinterest_epik_Cookie:()=>({_epik:ne("_epik")}),getSnapchat_sccid_Param:()=>({ScCid:oe("ScCid")}),getTiktok_ttp_Cookie:()=>({_ttp:ne("_ttp")}),getMarketo_mkto_trk_Cookie:()=>({_mkto_trk:ne("_mkto_trk")}),getTealium_utag_main_Cookie:()=>({utag_main:ne("utag_main")})};return{collectTags:function(e={},r={}){const i=o(e.vendors)&&o(e.cookies)&&o(e.params);let s={};o(e)||i?s=function(e={}){const t={};return Object.keys(te).forEach(o=>{const r=te[o];r&&r.forEach(o=>{const r=n[o](e);Object.assign(t,r)})}),Object.keys(t).reduce((e,n)=>(t[n]&&(e[n]=t[n]),e),{})}(r):(o(e.vendors)||Object.assign(s,function(e=[],t={}){return e.reduce((e,o)=>((te[o]||[]).forEach(o=>{const r=n[o](t);Object.assign(e,r)}),e),{})}(e.vendors,r)),o(e.cookies)||Object.assign(s,function(e=[]){return e.reduce((e,t)=>(e[t]=ne(t),e),{})}(e.cookies)),o(e.params)||Object.assign(s,function(e=[]){return e.reduce((e,t)=>(e[t]=oe(t),e),{})}(e.params))),Object.keys(s).forEach(e=>{const n=s[e];n&&t.set({[e]:n})})}}}}}const ie=Object.freeze(["https://console-development-next.us01.treasuredata.com","https://console-staging-next.us01.treasuredata.com","https://console-next.us01.treasuredata.com","https://console-staging-next.treasuredata.co.jp","https://console-next.treasuredata.co.jp","https://console-development-next.eu01.treasuredata.com","https://console-next.eu01.treasuredata.com","https://console-next.ap02.treasuredata.com","https://console-staging-next.ap03.treasuredata.com","https://console-next.ap03.treasuredata.com"]),se=Symbol("Comlink.proxy"),ae=Symbol("Comlink.endpoint"),ce=Symbol("Comlink.releaseProxy"),ue=Symbol("Comlink.finalizer"),le=Symbol("Comlink.thrown"),de=e=>"object"==typeof e&&null!==e||"function"==typeof e,fe=new Map([["proxy",{canHandle:e=>de(e)&&e[se],serialize(e){const{port1:t,port2:n}=new MessageChannel;return pe(e,t),[n,[n]]},deserialize:e=>(e.start(),me(e))}],["throw",{canHandle:e=>de(e)&&le in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function pe(e,t=globalThis,n=["*"]){t.addEventListener("message",function o(r){if(!r||!r.data)return;if(!function(e,t){for(const n of e){if(t===n||"*"===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}return!1}(n,r.origin))return;const{id:i,type:s,path:a}=Object.assign({path:[]},r.data),c=(r.data.argumentList||[]).map(Ce);let u;try{const t=a.slice(0,-1).reduce((e,t)=>e[t],e),n=a.reduce((e,t)=>e[t],e);switch(s){case"GET":u=n;break;case"SET":t[a.slice(-1)[0]]=Ce(r.data.value),u=!0;break;case"APPLY":u=n.apply(t,c);break;case"CONSTRUCT":u=function(e){return Object.assign(e,{[se]:!0})}(new n(...c));break;case"ENDPOINT":{const{port1:t,port2:n}=new MessageChannel;pe(e,n),u=function(e,t){return we.set(e,t),e}(t,[t])}break;case"RELEASE":u=void 0;break;default:return}}catch(e){u={value:e,[le]:0}}Promise.resolve(u).catch(e=>({value:e,[le]:0})).then(n=>{const[r,a]=Ee(n);t.postMessage(Object.assign(Object.assign({},r),{id:i}),a),"RELEASE"===s&&(t.removeEventListener("message",o),ge(t),ue in e&&"function"==typeof e[ue]&&e[ue]())}).catch(e=>{const[n,o]=Ee({value:new TypeError("Unserializable return value"),[le]:0});t.postMessage(Object.assign(Object.assign({},n),{id:i}),o)})}),t.start&&t.start()}function ge(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function me(e,t){const n=new Map;return e.addEventListener("message",function(e){const{data:t}=e;if(!t||!t.id)return;const o=n.get(t.id);if(o)try{o(t)}finally{n.delete(t.id)}}),ke(e,n,[],t)}function he(e){if(e)throw new Error("Proxy has been released and is not useable")}function _e(e){return Se(e,new Map,{type:"RELEASE"}).then(()=>{ge(e)})}const ye=new WeakMap,be="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(ye.get(e)||0)-1;ye.set(e,t),0===t&&_e(e)});function ke(e,t,n=[],o=function(){}){let r=!1;const i=new Proxy(o,{get(o,s){if(he(r),s===ce)return()=>{!function(e){be&&be.unregister(e)}(i),_e(e),t.clear(),r=!0};if("then"===s){if(0===n.length)return{then:()=>i};const o=Se(e,t,{type:"GET",path:n.map(e=>e.toString())}).then(Ce);return o.then.bind(o)}return ke(e,t,[...n,s])},set(o,i,s){he(r);const[a,c]=Ee(s);return Se(e,t,{type:"SET",path:[...n,i].map(e=>e.toString()),value:a},c).then(Ce)},apply(o,i,s){he(r);const a=n[n.length-1];if(a===ae)return Se(e,t,{type:"ENDPOINT"}).then(Ce);if("bind"===a)return ke(e,t,n.slice(0,-1));const[c,u]=ve(s);return Se(e,t,{type:"APPLY",path:n.map(e=>e.toString()),argumentList:c},u).then(Ce)},construct(o,i){he(r);const[s,a]=ve(i);return Se(e,t,{type:"CONSTRUCT",path:n.map(e=>e.toString()),argumentList:s},a).then(Ce)}});return function(e,t){const n=(ye.get(t)||0)+1;ye.set(t,n),be&&be.register(e,t,e)}(i,e),i}function ve(e){const t=e.map(Ee);return[t.map(e=>e[0]),(n=t.map(e=>e[1]),Array.prototype.concat.apply([],n))];var n}const we=new WeakMap;function Ee(e){for(const[t,n]of fe)if(n.canHandle(e)){const[o,r]=n.serialize(e);return[{type:"HANDLER",name:t,value:o},r]}return[{type:"RAW",value:e},we.get(e)||[]]}function Ce(e){switch(e.type){case"HANDLER":return fe.get(e.name).deserialize(e.value);case"RAW":return e.value}}function Se(e,t,n,o){return new Promise(r=>{const i=new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-");t.set(i,r),e.start&&e.start(),e.postMessage(Object.assign({id:i},n),o)})}function je(e){let t=null;const n=o=>{if(!ie.includes(o.origin))return;if("td:p13n-studio:init"!==o.data)return;const r=o.ports[0];r&&(window.removeEventListener("message",n),t=r,e(r))};window.addEventListener("message",n);try{window.parent.postMessage("td:p13n-studio:ready","*")}catch{}return{dispose(){window.removeEventListener("message",n),t?.close(),t=null}}}function $e(e){switch(e){case"NotSupportedError":return"unsupported_element";case"InvalidStateError":return"already_has_shadow";default:return"injection_error"}}function Pe(e,t){const n=function(e,t){try{const n=e.querySelectorAll(t);return{element:n[0]??null,matchCount:n.length}}catch{return null}}(e,t.selector);if(!n)return{selector:t.selector,success:!1,reason:"invalid_spot"};if(!n.element)return{selector:t.selector,success:!1,reason:"not_found",matchCount:0};const o=function(e){if(e.shadowRoot)return{ok:!0,shadow:e.shadowRoot};try{return{ok:!0,shadow:e.attachShadow({mode:"open"})}}catch(e){return{ok:!1,name:e instanceof Error?e.name:""}}}(n.element);if(!o.ok)return{selector:t.selector,success:!1,reason:$e(o.name),matchCount:n.matchCount};const r=o.shadow;try{if(r.replaceChildren(),t.css){const n=e.createElement("style");n.textContent=t.css,r.appendChild(n)}if(t.html){const n=e.createElement("div");n.innerHTML=t.html,r.appendChild(n)}return{selector:t.selector,success:!0,matchCount:n.matchCount}}catch{return{selector:t.selector,success:!1,reason:"injection_error",matchCount:n.matchCount}}}function Te(e,t){let n;try{n=e.querySelector(t.selector)}catch{return}const o=n?.shadowRoot;o&&o.replaceChildren(e.createElement("slot"))}function xe(e){if(!e||"object"!=typeof e)return!1;const t=e.selector;return"string"==typeof t&&t.length>0}const Ie=[/^[0-9]+$/,/^:r/,/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i],ze=[/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,/^[a-z0-9]{20,}$/i],Ae=[/^css-/,/^sc-/,/^emotion-/,/^[a-zA-Z0-9]{5,}$/],Le=["main","nav","header","footer","aside","article","section"],Me=["banner","complementary","contentinfo","form","main","navigation","region","search"];function Oe(e){return!ze.some(t=>t.test(e))}function Ne(e){return!e.startsWith("p13n-sdk-")&&!Ae.some(t=>t.test(e))}function Ue(e){return 1===document.querySelectorAll(e).length}function De(e,t){try{return document.querySelector(e)===t}catch{return!1}}function Re(e){return e.localName}function We(e){if(e.id&&(t=e.id,!Ie.some(e=>e.test(t)))){const t=`#${CSS.escape(e.id)}`;if(De(t,e))return t}var t;for(const t of e.attributes)if(t.name.startsWith("data-")&&t.value&&Oe(t.value)){const n=`[${CSS.escape(t.name)}="${CSS.escape(t.value)}"]`;if(Ue(n)&&De(n,e))return n}for(const t of e.classList)if(Ne(t)){const n=`.${CSS.escape(t)}`;if(Ue(n)&&De(n,e))return n}const n=Re(e);for(const t of e.classList)if(Ne(t)){const o=`${n}.${CSS.escape(t)}`;if(Ue(o)&&De(o,e))return o}const o=e.getAttribute("role");if(o&&Me.includes(o)){const t=`[role="${o}"]`;if(Ue(t)&&De(t,e))return t}return Le.includes(n)&&Ue(n)&&De(n,e)?n:null}function Ge(e){const t=Re(e);let n=1,o=e.previousElementSibling;for(;o;)o.localName===t&&n++,o=o.previousElementSibling;return n}function Fe(e,t){const n=[];let o=t;for(;o&&o!==e;){const e=Re(o),t=Ge(o);n.unshift(`${e}:nth-of-type(${t})`),o=o.parentElement}return n.join(" > ")}function Ke(e){if(!e||e===document.documentElement||e===document.body)return e===document.body?"body":"html";const t=We(e);if(t)return t;const n=function(e){let t=e.parentElement;for(;t&&t!==document.documentElement;){const n=We(t);if(n){const o=`${n} > ${Fe(t,e)}`;if(De(o,e))return o}t=t.parentElement}return null}(e);return n||(function(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=Re(n),o=Ge(n);t.unshift(`${e}:nth-of-type(${o})`),n=n.parentElement}const o=`html > ${t.join(" > ")}`;return De(o,e)?o:null}(e)??e.localName)}const Ye="data-p13n-sdk",Be="p13n-sdk-highlight",He=["mousedown","mouseup","pointerdown","pointerup","keydown","keyup","focusin","submit"],qe=`\n .${Be} {\n outline: 2px solid blue !important;\n outline-offset: -2px !important;\n cursor: crosshair !important;\n }\n .p13n-sdk-tooltip {\n position: fixed;\n z-index: 2147483647;\n background: rgba(0, 0, 0, 0.8);\n color: #fff;\n font-family: monospace;\n font-size: 12px;\n padding: 4px 8px;\n border-radius: 4px;\n pointer-events: none;\n white-space: nowrap;\n }\n`;function Je(e){let t=e;for(;t;){if(t.hasAttribute&&t.hasAttribute(Ye))return!0;t=t.parentElement}return!1}function Ve(e){let t=null;const n=document.createElement("style");n.setAttribute(Ye,""),n.textContent=qe,document.head.appendChild(n);const o=document.createElement("div");function r(e){let t=e.clientX+15,n=e.clientY+15;const r=o.getBoundingClientRect(),i=r.width||150,s=r.height||24;t+i>window.innerWidth&&(t=e.clientX-15-i),n+s>window.innerHeight&&(n=e.clientY-15-s),o.style.left=`${t}px`,o.style.top=`${n}px`}function i(e){const n=e.target;if(!(n instanceof HTMLElement))return;if(Je(n))return;t&&t!==n&&t.classList.remove(Be),t=n,n.classList.add(Be);const i=n.localName,{width:s,height:a}=function(e){if(0!==e.offsetWidth)return{width:e.offsetWidth,height:e.offsetHeight};const t=e.getBoundingClientRect();return{width:Math.round(t.width),height:Math.round(t.height)}}(n);o.textContent=`${i} ${s}×${a}`,o.style.display="block",r(e)}function s(e){"block"===o.style.display&&r(e)}function a(e){const n=e.target;n instanceof HTMLElement&&(Je(n)||(t===n&&(n.classList.remove(Be),t=null),o.style.display="none"))}function c(e){Je(e.target)||(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation())}function u(t){const n=t.target;if(!(n instanceof HTMLElement))return;c(t);const o=Ke(n);e(o)}return o.className="p13n-sdk-tooltip",o.setAttribute(Ye,""),o.style.display="none",document.body.appendChild(o),function(){document.addEventListener("mouseover",i,!0),document.addEventListener("mousemove",s,!0),document.addEventListener("mouseout",a,!0),document.addEventListener("click",u,!0);for(const e of He)document.addEventListener(e,c,!0)}(),{dispose(){!function(){document.removeEventListener("mouseover",i,!0),document.removeEventListener("mousemove",s,!0),document.removeEventListener("mouseout",a,!0),document.removeEventListener("click",u,!0);for(const e of He)document.removeEventListener(e,c,!0)}(),t&&(t.classList.remove(Be),t=null),o.style.display="none",o.remove(),n.remove(),t=null}}}const Xe={preview:{mode:"preview",activate(e){return n=e.log,t={applySpots:async e=>(i(Array.isArray(e),"pagePersonalize/preview: applySpots requires an array"),e.map((e,t)=>{const o=function(e){if(!e||"object"!=typeof e)return{ok:!1,reason:`not an object (${typeof e})`};const t=e;return"string"!=typeof t.selector?{ok:!1,reason:`selector not a string (${typeof t.selector})`}:0===t.selector.length?{ok:!1,reason:"selector empty"}:void 0!==t.html&&"string"!=typeof t.html?{ok:!1,reason:`html not a string (${typeof t.html})`}:void 0!==t.css&&"string"!=typeof t.css?{ok:!1,reason:`css not a string (${typeof t.css})`}:{ok:!0,spot:e}}(e);if(!o.ok)return n.warn(`pagePersonalize/preview: applySpots[${t}] invalid_spot: ${o.reason}`),{selector:(r=e,r&&"object"==typeof r&&"selector"in r?r.selector:null),success:!1,reason:"invalid_spot"};var r;const i=Pe(document,o.spot);return i.success||n.warn(`pagePersonalize/preview: applySpot "${i.selector}" -> ${i.reason}`+(void 0!==i.matchCount?` (matchCount=${i.matchCount})`:"")),i})),async removeSpots(e){i(Array.isArray(e),"pagePersonalize/preview: removeSpots requires an array");for(let t=0;t<e.length;t++){const o=e[t];xe(o)?Te(document,o):n.warn(`pagePersonalize/preview: removeSpots[${t}] skipped malformed ref`)}}},je(e=>{pe(t,e)});var t,n}},"spot-selection":{mode:"spot-selection",activate(e){const t=function(){let e=null;const t=je(t=>{t.start(),e=me(t)});return{getApi:()=>e,dispose(){t.dispose?.(),e=null}}}(),n=Ve(n=>{const o=t.getApi();o?o.onSpotSelected(n):e.log.warn("pagePersonalize/spot-selection: no parent RPC connection, cannot send selector")});return{dispose(){n.dispose?.(),t.dispose?.()}}}}};function Ze(e){const t=function(){if("undefined"==typeof window||!window.location)return null;let e;try{e=new URLSearchParams(window.location.search).get("td-personalization-mode")}catch{return null}return e&&Object.hasOwn(Xe,e)?e:null}();if(!t)return null;let n;try{n=Xe[t].activate(e)}catch(n){return e.log.error(`pagePersonalize: activation failed for mode "${t}":`,n),null}return n?t:null}function Qe(e,t){const n=e[t];if("string"!=typeof n||0===n.length)return null;const o=Number(n);return Number.isFinite(o)?o:null}function et(e,t){const n=e.attributes;return!!n&&"object"==typeof n&&function(e,t){const n=Qe(e,"td_personalization.campaigns_start_date");if(null!==n&&t<n)return!1;const o=Qe(e,"td_personalization.campaigns_end_date");return!(null!==o&&t>=o)}(n,t)}function tt(e,t=Date.now()/1e3){const n=e?.offers;if(!n||"object"!=typeof n)return null;const o=Object.values(n).filter(e=>et(e,t)).flatMap(e=>function(e){const t=e.attributes;if(!t)return null;const n=Qe(t,"td_personalization.audience_rank");return null===n?null:{offer:e,updated:Qe(t,"td_personalization.campaign_updated_at")??-1/0,rank:n}}(e)??[]),r=(i=(e,t)=>e.updated>t.updated||e.updated===t.updated&&e.rank<t.rank,o.reduce((e,t)=>null===e||i(t,e)?t:e,null));var i;return r?.offer??null}function nt(e,t){const n=tt(e,t);if(!n)return[];const o=n.attributes,r=o?function(e,t){const n=e[t];return"string"==typeof n&&n.length>0?n:null}(o,"td_personalization.campaign"):null,i=function(e){if("string"!=typeof e)return null;try{const t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}(o?.["td_personalization.content"]);return i?i.flatMap(e=>function(e,t){const n=function(e){if(!e||"object"!=typeof e)return null;const{css_selector:t,html_value:n,css_value:o}=e;return"string"!=typeof t||0===t.length||"string"!=typeof n||"string"!=typeof o?null:{selector:t,html:n,css:o}}(e);if(!n)return null;const o=e.id,r="number"==typeof o&&Number.isFinite(o)?String(o):null;return{spot:n,impression:t&&r?{campaign:t,creative:r}:null}}(e,r)??[]):[]}const ot="data-td-personalization-campaign",rt="data-td-personalization-creative";const it=["set","collectTags","blockEvents","unblockEvents","setSignedMode","setAnonymousMode","fetchServerCookie","fetchGlobalID","fetchUserSegments","fetchPersonalization","resetUUID","addRecord","trackEvent","trackPageview","trackClicks","ready"];class st{_sdk;constructor(e){return this instanceof st?(this._sdk=this.init(e),this.bindMethods(),this):new st(e)}init(t){const o=function(e){if(!e||"string"!=typeof e.writeKey||!e.writeKey)throw new Error("TreasureSDK: writeKey is required");if(!e.database)throw new Error("TreasureSDK: database is required");const t={debug:(...t)=>{e.development},warn:(...e)=>{},error:(...e)=>{}},n={config:{...e},log:t},o={...n,use(e){n.log.debug(`Loading plugin: ${e.name}`);const t=e.setup(n,o);for(const n of Object.keys(t))if(n in o)throw new Error(`TreasureSDK: plugin "${e.name}" conflicts on "${n}"`);return Object.assign(o,t),o},getWriteKey:()=>n.config.writeKey,setWriteKey(e){if(!e||"string"!=typeof e)throw new Error("TreasureSDK: writeKey must be a non-empty string");n.config.writeKey=e}};return o}(_(t)).use({name:"session",setup(e,t){const n=e.config,o=n.startInSignedMode??!1,r=n.storeConsentByLocalStorage??!1,i={};function a(e,t){const n=e||"$global";return i[n]=i[n]||{},t?i[n]?.[t]??null:i[n]}const c=z(n.storage);let u;null!=n.clientId&&(u="number"==typeof n.clientId?n.clientId.toString():n.clientId),u&&"string"==typeof u||(c?.name&&"undefined"!=typeof document&&(u=m.getItem(c.name)??void 0),u&&"undefined"!==u||(u=b()));let l=u.replace(/\0/g,"");function d(){return l}function f(e,t){if(m.getItem(e.name)!==t)try{y(e,e.name,t)}catch{}}function p(e,t){l=(t||b()).replace(/\0/g,"");const o=e||n.storage;if(o&&"object"==typeof o){const e=z(o);e?.expires&&g()&&f(e,l)}}function g(){if(r){if(!s())return o;const e=localStorage.getItem(I);return"false"!==e&&("true"===e||o)}if("undefined"==typeof document)return o;const e=m.getItem(I);return"false"!==e&&("true"===e||o)}function h(){if(i.$global&&delete i.$global.td_global_id,n.storage&&"object"==typeof n.storage){const e=n.globalIdCookie||"_td_global";A(n.storage,e,"")}if(s()){const e=n.globalIdCookie||"_td_global";try{localStorage.removeItem(e)}catch{}}}return c?.expires&&g()&&f(c,l),{inSignedMode:g,setSignedMode:function(){r?s()&&localStorage.setItem(I,"true"):n.storage&&"object"==typeof n.storage&&A(n.storage,I,"true");const e=d();p(n.storage,e)},setAnonymousMode:function(e){r?s()&&localStorage.setItem(I,"false"):n.storage&&"object"==typeof n.storage&&A(n.storage,I,"false"),e||(n.storage&&"object"==typeof n.storage&&A(n.storage,n.storage.name),h(),t.removeServerCookie())},blockEvents:function(){n.storage&&"object"==typeof n.storage&&A(n.storage,x,"true")},unblockEvents:function(){n.storage&&"object"==typeof n.storage&&A(n.storage,x,"false")},areEventsBlocked:function(){return"true"===m.getItem(x)},getUUID:d,resetUUID:p,set:function(e,t,n){let o,r=t;"object"==typeof e&&null!==e?(r=e,o="$global"):o=e;const s=i[o]||{};i[o]=s,"object"==typeof r&&null!==r?Object.assign(s,r):"string"==typeof r&&void 0!==n&&(s[r]=n)},get:a,removeCachedGlobalID:h,removeServerCookie:function(){n.storage&&"object"==typeof n.storage&&(A(n.storage,$,""),["__td_ssc","_td_ssc"].forEach(e=>{A(n.storage,e,"")}),n.useServerSideCookie&&n.globalIdCookie&&A(n.storage,n.globalIdCookie,"")),s()&&[$,"__td_ssc","_td_ssc"].forEach(e=>{try{localStorage.removeItem(e)}catch{}})},isGlobalIdEnabled:function(){return"td_global_id"===a(void 0,"td_global_id")}}}}).use(L()).use({name:"track",setup(e,t){const n=H(()=>t.getUUID(),u);function o(){const e={};for(const[t,o]of Object.entries(n))o&&(e[t]="function"==typeof o?o():o);return e}function r(n,r,i,s){const a=n||"events",c=o(),u=Object.assign(c,r),l=e.config.personalization;if(l){const n={endpoint:l.endpoint,database:l.database||e.config.database,table:a,token:l.token},i={...t.get("$global"),...t.get(a),...o(),...r};return void t.fetchPersonalization(n,i,e=>{B(e),"function"==typeof t.applyPersonalization&&t.applyPersonalization(e)},t=>{e.log.error("Personalization failed:",t)})}t.addRecord(a,u,i,s)}return{trackEvent:r,trackPageview:function(e,t,n,o){r(e||"pageviews",o?.payload??{},t,n)},getTrackValues:o,getPersonalizationConfig:function(){return e.config.personalization},setPersonalizationConfig:function(t){e.config.personalization=t}}}}).use(X()).use(Q()).use({name:"personalization",setup(t,o){const r=t.config.cdpHost||"cdp.in.treasuredata.com";return{fetchUserSegments:function(t,o,i){const s=()=>{},a=o||s,c=i||s,u=e(t)&&!n(t),l=u?t.audienceToken:t,d=u&&t.keys||{};ee("string"==typeof l||n(l),`audienceToken must be a string or array; received "${String(l)}"`),ee(e(d),`keys must be an object; received "${String(d)}"`);const f=n(l)?l.join(","):l,p=[];Object.keys(d).forEach(e=>{p.push(`key.${e}=${String(d[e])}`)});const g=p.join("&"),m=`https://${r}/cdp/lookup/collect/segments?version=2&token=${f}${g?"&"+g:""}`;j.getWithTimeout(m,1e4,{headers:{"Content-Type":"application/json"}}).then(a).catch(c)},fetchPersonalization:function(n,r,i,s){const a=()=>{},c=i||a,u=s||a;if(ee(e(n),`config must be an object, received "${String(n)}"`),ee(!!n.endpoint,"endpoint is invalid"),ee(!!n.database,"database is invalid"),ee(!!n.table,"table is invalid"),ee(!!n.token,"token is invalid"),"function"==typeof o.areEventsBlocked&&o.areEventsBlocked())return;const l=`https://${n.endpoint}/public/${n.database}/${n.table}`;let d=r||{};"function"!=typeof o.inSignedMode||o.inSignedMode()||(d=function(e){const t={...e};return["td_ip","td_client_id","td_global_id"].forEach(e=>delete t[e]),t}(d)),j.postWithTimeout(l,d,1e4,{headers:{"Content-Type":"application/vnd.treasuredata.v1+json",Authorization:`TD1 ${t.config.writeKey}`,"WP13n-Token":n.token}}).then(c).catch(u)}}}}).use(re()).use(T()).use({name:"globalId",setup(e,t){const n=e.config,o=()=>{};return{fetchGlobalID:function(e,r,i=!1,s={}){const a=e||o,u=r||o;if(!t.inSignedMode())return u("not in signed in mode");if(!t.isGlobalIdEnabled())return u("global id is not enabled");const l=n.globalIdCookie||"_td_global",d=m.getItem(l);if(d&&!i)return void setTimeout(()=>a(d),0);const f=s.sameSite||"None",p=`https://${n.host}`,g={Authorization:`TD1 ${n.writeKey}`,"Content-Type":c["Content-Type"],Accept:c.Accept};"undefined"!=typeof navigator&&(g["User-Agent"]=navigator.userAgent),j.get(p,{headers:g}).then(e=>{if(!e.global_id)return void a(null);const t=e.global_id,n=s.maxAge??6e3;m.setItem(l,t,n,s.path,s.domain,s.secure,f),a(t)}).catch(e=>{u(e)})}}}}).use({name:"pagePersonalize",setup(e,t){const n=Ze(e);function o(e,n){const o="function"==typeof t.getTrackValues?t.getTrackValues():{};t.addRecord("events",{...o,td_event:e,td_personalization_campaign:n.campaign,td_personalization_creative:n.creative},void 0,void 0,{database:"td_c360_personalization"})}function r(e){const t=e.target;if(!(t instanceof Element&&t.closest('a, button, [role="button"], [role="link"]')))return;const n=e.currentTarget.host,r=n.getAttribute(ot),i=n.getAttribute(rt);r&&i&&o("click",{campaign:r,creative:i})}function i(e,t){const n=document.querySelector(e);n?.shadowRoot&&(n.setAttribute(ot,t.campaign),n.setAttribute(rt,t.creative),n.shadowRoot.addEventListener("click",r))}function s(e,t){if("undefined"!=typeof document&&(null===n||t?.force))for(const{spot:t,impression:n}of nt(e))Pe(document,t).success&&n&&(o("impression",n),i(t.selector,n))}return{applyPersonalization:s,personalizePage:function(o,r,i,a){if(null!==n)return void e.log.debug(`pagePersonalize: personalizePage suppressed in "${n}" mode`);const c={};"undefined"!=typeof document&&document.location&&(c.td_url=document.location.href.split("#")[0],c.td_host=document.location.host,c.td_path=document.location.pathname),Object.assign(c,r),t.fetchPersonalization(o,c,e=>{const t=e;s(t),i?.(t)},a)}}}});return o}bindMethods(){const e=new Set;let t=this._sdk;for(;t&&t!==Object.prototype;)Object.getOwnPropertyNames(t).forEach(n=>{"function"==typeof t[n]&&"constructor"!==n&&e.add(n)}),t=Object.getPrototypeOf(t);e.forEach(e=>{this.hasOwnProperty(e)||"init"===e||"bindMethods"===e||(this[e]=this._sdk[e].bind(this._sdk))})}get sdk(){return this._sdk}get config(){return this._sdk.config}static version="1.0.0";get version(){return st.version}addRecord=(e,t,n,o,r)=>this._sdk.addRecord(e,t,n,o,r);trackEvent=(e,t,n,o)=>this._sdk.trackEvent(e,t,n,o);trackPageview=(e,t,n,o)=>this._sdk.trackPageview(e,t,n,o);trackClicks=e=>this._sdk.trackClicks(e);fetchUserSegments(e,t,n){return this._sdk.fetchUserSegments(e,t,n)}fetchPersonalization=(e,t,n,o)=>this._sdk.fetchPersonalization(e,t,n,o);applyPersonalization=(e,t)=>{this._sdk.applyPersonalization(e,t)};personalizePage=(e,t,n,o)=>{this._sdk.personalizePage(e,t,n,o)};collectUTMParameters=()=>this._sdk.collectUTMParameters();getUTMParameters=()=>this._sdk.getUTMParameters();set=(e,t,n)=>this._sdk.set(e,t,n);get=(e,t)=>this._sdk.get(e,t);setSignedMode=()=>this._sdk.setSignedMode();setAnonymousMode=e=>this._sdk.setAnonymousMode(e);inSignedMode=()=>this._sdk.inSignedMode();blockEvents=()=>this._sdk.blockEvents();unblockEvents=()=>this._sdk.unblockEvents();areEventsBlocked=()=>this._sdk.areEventsBlocked();resetUUID=()=>this._sdk.resetUUID();getTrackValues=()=>this._sdk.getTrackValues();getPersonalizationConfig=()=>this._sdk.getPersonalizationConfig();setPersonalizationConfig=e=>this._sdk.setPersonalizationConfig(e);getWriteKey=()=>this._sdk.getWriteKey();setWriteKey=e=>this._sdk.setWriteKey(e);collectTags=e=>this._sdk.collectTags(e);fetchServerCookie=(e,t,n)=>this._sdk.fetchServerCookie(e,t,n);fetchGlobalID=(e,t,n,o)=>this._sdk.fetchGlobalID(e,t,n,o)}return"undefined"!=typeof window&&function(e,t){const n="undefined"!=typeof window?window:globalThis;if(n[e]&&n[e].clients){const o=n[e].clients;n[e]=t,o.forEach(e=>{let n;if(e._init&&e._init.length>0){const o=e._init[0];n=new t(...o||[])}else n=new t;!function(e,t){e._init&&e._init.length,it.forEach(n=>{const o=e["_"+n];o&&Array.isArray(o)&&o.length>0&&o.forEach(e=>{"function"==typeof t[n]&&t[n].apply(t,e)})})}(e,n),Object.setPrototypeOf(e,n),Object.assign(e,n)})}}("Treasure",st),st}();
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Treasure Data Web SDK - Constructor-based API
3
+ *
4
+ * This provides the familiar constructor-based API similar to the original td-js-sdk,
5
+ * with all plugins automatically loaded and available.
6
+ */
7
+ import type { GlobalIdCookieOptions } from './plugins/global-id';
8
+ import type { TDConfig, TreasureSDK, JSONValue, PersonalizationOptions } from './types';
9
+ import type { AddRecordOptions } from './plugins/record';
10
+ import type { PersonalizationFetchConfig } from './plugins/personalization';
11
+ import type { PersonalizationPayload } from './plugins/page-personalize/offers';
12
+ import type { ApplyPersonalizationOptions } from './plugins/page-personalize';
13
+ /**
14
+ * Treasure Data SDK Constructor
15
+ *
16
+ * Creates a new Treasure Data logger instance with all plugins automatically loaded.
17
+ * If the database does not exist and you have permissions, it will be created for you.
18
+ *
19
+ * @param config - Treasure Data instance configuration parameters
20
+ * @returns Treasure logger instance object with all plugins loaded
21
+ *
22
+ * @example
23
+ * var td = new Treasure({
24
+ * database: 'my_database',
25
+ * writeKey: 'your_write_only_key'
26
+ * });
27
+ *
28
+ * // All plugin methods are immediately available:
29
+ * td.trackEvent('user_actions', { action: 'click' });
30
+ * td.trackPageview('homepage');
31
+ * td.trackClicks({ tableName: 'clicks' });
32
+ * td.fetchUserSegments('audience_token');
33
+ * td.collectUTMParameters();
34
+ */
35
+ export declare class Treasure {
36
+ private _sdk;
37
+ constructor(config: TDConfig);
38
+ /**
39
+ * Initialize the SDK with all plugins
40
+ */
41
+ private init;
42
+ /**
43
+ * Bind all SDK methods to this instance for direct access
44
+ */
45
+ private bindMethods;
46
+ /**
47
+ * Get the underlying SDK instance
48
+ */
49
+ get sdk(): TreasureSDK;
50
+ /**
51
+ * Get the configuration
52
+ */
53
+ get config(): TDConfig;
54
+ /**
55
+ * Version information
56
+ */
57
+ static version: string;
58
+ get version(): string;
59
+ /**
60
+ * Add a record to a table
61
+ */
62
+ addRecord: (table: string, record: Record<string, any>, success?: any, error?: any, options?: AddRecordOptions) => void;
63
+ /**
64
+ * Track a custom event
65
+ */
66
+ trackEvent: (table: string, data: Record<string, any>, success?: any, error?: any) => void;
67
+ /**
68
+ * Track a page view
69
+ */
70
+ trackPageview: (table?: string, success?: any, error?: any, options?: {
71
+ payload?: Record<string, JSONValue>;
72
+ }) => void;
73
+ /**
74
+ * Start tracking clicks
75
+ */
76
+ trackClicks: (options?: {
77
+ tableName?: string;
78
+ element?: string | HTMLElement;
79
+ }) => void;
80
+ /**
81
+ * Fetch user segments (overload 1: options object)
82
+ */
83
+ fetchUserSegments(options: {
84
+ audienceToken: string | string[];
85
+ keys?: Record<string, any>;
86
+ }, successCallback?: (segments: {
87
+ key: Record<string, any>;
88
+ values: string[];
89
+ attributes: Record<string, any>;
90
+ }[]) => void, errorCallback?: (error: Error) => void): void;
91
+ /**
92
+ * Fetch user segments (overload 2: audienceToken directly)
93
+ */
94
+ fetchUserSegments(audienceToken: string | string[], successCallback?: (segments: {
95
+ key: Record<string, any>;
96
+ values: string[];
97
+ attributes: Record<string, any>;
98
+ }[]) => void, errorCallback?: (error: Error) => void): void;
99
+ /**
100
+ * Fetch personalization data
101
+ */
102
+ fetchPersonalization: (config: {
103
+ endpoint: string;
104
+ database: string;
105
+ table: string;
106
+ token: string;
107
+ }, data?: Record<string, any> | null, successCallback?: (response: Record<string, any>) => void, errorCallback?: (error: Error) => void) => void;
108
+ /**
109
+ * Apply an already-fetched personalization payload to the current page
110
+ */
111
+ applyPersonalization: (payload: PersonalizationPayload, options?: ApplyPersonalizationOptions) => void;
112
+ /**
113
+ * Fetch personalization offers and apply them to the current page
114
+ */
115
+ personalizePage: (config: PersonalizationFetchConfig, data?: Record<string, JSONValue> | null, successCallback?: (payload: PersonalizationPayload) => void, errorCallback?: (error: Error) => void) => void;
116
+ /**
117
+ * Collect UTM parameters
118
+ */
119
+ collectUTMParameters: () => Record<string, JSONValue>;
120
+ /**
121
+ * Get UTM parameters
122
+ */
123
+ getUTMParameters: () => Record<string, JSONValue>;
124
+ /**
125
+ * Set global or table-specific values
126
+ */
127
+ set: (table: any, property?: any, value?: any) => void;
128
+ /**
129
+ * Get global or table-specific values
130
+ */
131
+ get: (table?: any, key?: any) => JSONValue;
132
+ /**
133
+ * Set signed mode
134
+ */
135
+ setSignedMode: () => void;
136
+ /**
137
+ * Set anonymous mode
138
+ */
139
+ setAnonymousMode: (keepIdentifier?: boolean) => void;
140
+ /**
141
+ * Check if in signed mode
142
+ */
143
+ inSignedMode: () => boolean;
144
+ /**
145
+ * Block events
146
+ */
147
+ blockEvents: () => void;
148
+ /**
149
+ * Unblock events
150
+ */
151
+ unblockEvents: () => void;
152
+ /**
153
+ * Check if events are blocked
154
+ */
155
+ areEventsBlocked: () => boolean;
156
+ /**
157
+ * Reset UUID
158
+ */
159
+ resetUUID: () => void;
160
+ /**
161
+ * Get track values
162
+ */
163
+ getTrackValues: () => Record<string, JSONValue>;
164
+ /**
165
+ * Get the personalization config
166
+ */
167
+ getPersonalizationConfig: () => PersonalizationOptions | undefined;
168
+ /**
169
+ * Set the personalization config (pass undefined to disable)
170
+ */
171
+ setPersonalizationConfig: (options?: PersonalizationOptions) => void;
172
+ /**
173
+ * Get the configured write key
174
+ */
175
+ getWriteKey: () => string;
176
+ /**
177
+ * Set the write key
178
+ */
179
+ setWriteKey: (writeKey: string) => void;
180
+ /**
181
+ * Collect conversion tracking tags
182
+ */
183
+ collectTags: (options?: {
184
+ table?: string;
185
+ success?: (response: any) => void;
186
+ error?: (error: any) => void;
187
+ }) => void;
188
+ /**
189
+ * Fetch server-side cookie ID
190
+ */
191
+ fetchServerCookie: (success?: (serverSideId: string) => void, error?: (error: string | Error) => void, forceFetch?: boolean) => void;
192
+ /**
193
+ * Fetch Global ID
194
+ */
195
+ fetchGlobalID: (success?: (globalId: string | null) => void, error?: (error: unknown) => void, forceFetch?: boolean, options?: GlobalIdCookieOptions) => void;
196
+ }
197
+ export default Treasure;
198
+ //# sourceMappingURL=treasure.d.ts.map