@cross-deck/web 1.6.2 → 1.6.4

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.
@@ -1,3 +1,3 @@
1
- "use strict";var Crossdeck=(()=>{var me=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var pt=(r,e)=>{for(var t in e)me(r,t,{get:e[t],enumerable:!0})},ft=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lt(e))!ut.call(r,n)&&n!==t&&me(r,n,{get:()=>e[n],enumerable:!(s=dt(e,n))||s.enumerable});return r};var ht=r=>ft(me({},"__esModule",{value:!0}),r);var Tr={};pt(Tr,{CROSSDECK_ERROR_CODES:()=>Se,Crossdeck:()=>st,CrossdeckClient:()=>G,CrossdeckContracts:()=>ot,CrossdeckError:()=>_,DEFAULT_BASE_URL:()=>Q,MemoryStorage:()=>V,SDK_NAME:()=>I,SDK_VERSION:()=>T,getErrorCode:()=>pe});var _=class r extends Error{constructor(e){super(e.message),this.name="CrossdeckError",this.type=e.type,this.code=e.code,this.requestId=e.requestId,this.status=e.status,this.retryAfterMs=e.retryAfterMs,Object.setPrototypeOf(this,r.prototype)}};async function De(r){let e=r.headers.get("x-request-id")??void 0,t=mt(r.headers.get("retry-after")),s;try{s=await r.json()}catch{s=null}let n=s?.error;return n&&typeof n.type=="string"&&typeof n.code=="string"?new _({type:n.type,code:n.code,message:n.message??`HTTP ${r.status}`,requestId:n.request_id??e,status:r.status,retryAfterMs:t}):new _({type:gt(r.status),code:`http_${r.status}`,message:`HTTP ${r.status} ${r.statusText||""}`.trim(),requestId:e,status:r.status,retryAfterMs:t})}function mt(r){if(!r)return;let e=r.trim();if(!e)return;if(/^\d+(\.\d+)?$/.test(e)){let n=Number(e);return!Number.isFinite(n)||n<0?void 0:Math.round(n*1e3)}if(!/[a-zA-Z,/:]/.test(e))return;let t=Date.parse(e);if(!Number.isFinite(t))return;let s=t-Date.now();return s>0?s:0}function gt(r){return r===401?"authentication_error":r===403?"permission_error":r===429?"rate_limit_error":r>=400&&r<500?"invalid_request_error":"internal_error"}var T="1.6.2",I="@cross-deck/web";var Q="https://api.cross-deck.com/v1",yt=15e3,X=class{constructor(e){this.config=e}async request(e,t,s={}){if(this.config.localDevMode)return bt(t);let n=this.buildUrl(t,s.query),i={Authorization:`Bearer ${this.config.publicKey}`,"Crossdeck-Sdk-Version":`${I}@${this.config.sdkVersion}`,Accept:"application/json"};s.idempotencyKey&&(i["Idempotency-Key"]=s.idempotencyKey);let c;s.body!==void 0&&(i["Content-Type"]="application/json",c=JSON.stringify(s.body));let o=s.timeoutMs??this.config.timeoutMs??yt,a=typeof AbortController<"u"&&o>0?new AbortController:null,d=null;a&&o>0&&(d=setTimeout(()=>a.abort(),o));let l;try{l=await fetch(n,{method:e,headers:i,body:c,keepalive:s.keepalive===!0,signal:a?.signal})}catch(u){let f=a?.signal?.aborted===!0;throw new _({type:"network_error",code:f?"request_timeout":"fetch_failed",message:f?`Request to ${t} aborted after ${o}ms`:u instanceof Error?u.message:"fetch failed"})}finally{d!==null&&clearTimeout(d)}if(!l.ok){let u=await De(l);if(this.config.onErrorParsed)try{this.config.onErrorParsed(u)}catch{}throw u}if(l.status!==204)try{return await l.json()}catch{throw new _({type:"internal_error",code:"invalid_json_response",message:"Server returned a 2xx with an unparseable body.",requestId:l.headers.get("x-request-id")??void 0,status:l.status})}}get isLocalDevMode(){return this.config.localDevMode===!0}buildUrl(e,t){let s=this.config.baseUrl.replace(/\/+$/,""),n=e.startsWith("/")?e:`/${e}`,i=s+n;if(t){let c=new URLSearchParams;for(let[a,d]of Object.entries(t))typeof d=="string"&&d.length>0&&c.append(a,d);let o=c.toString();o&&(i+=(i.includes("?")?"&":"?")+o)}return i}},J=null;function bt(r){return r.startsWith("/sdk/heartbeat")?{object:"heartbeat",ok:!0,projectId:"proj_local_dev",appId:"app_local_dev",platform:"web",env:"sandbox",serverTime:Date.now()}:r.startsWith("/identity/alias")?(J||(J=`cdcust_local_${typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,"").slice(0,16):Math.random().toString(36).slice(2,18)}`),{object:"alias_result",crossdeckCustomerId:J,linked:[],mergePending:!1,env:"sandbox"}):r.startsWith("/entitlements")?{object:"list",data:[],crossdeckCustomerId:J??"",env:"sandbox"}:r.startsWith("/events")?{object:"list",received:0,env:"sandbox"}:{}}var q="anon_id",K="cdcust_id",Y=class{constructor(e,t,s){this.primary=e;this.prefix=t;this.secondary=s??null;let n=e.getItem(t+q),i=e.getItem(t+K),c=this.secondary?.getItem(t+q)??null,o=this.secondary?.getItem(t+K)??null,a=n??c,d=i??o;this.state={anonymousId:a??this.mintAnonymousId(),crossdeckCustomerId:d},(!n||!c)&&this.writeBoth(t+q,this.state.anonymousId),d&&(!i||!o)&&this.writeBoth(t+K,d)}get anonymousId(){return this.state.anonymousId}get crossdeckCustomerId(){return this.state.crossdeckCustomerId}setCrossdeckCustomerId(e){this.state.crossdeckCustomerId=e,this.writeBoth(this.prefix+K,e)}reset(){this.deleteBoth(this.prefix+q),this.deleteBoth(this.prefix+K),this.state={anonymousId:this.mintAnonymousId(),crossdeckCustomerId:null},this.writeBoth(this.prefix+q,this.state.anonymousId)}mintAnonymousId(){let e=Date.now().toString(36),t=F(10);return`anon_${e}${t}`}writeBoth(e,t){try{this.primary.setItem(e,t)}catch{}if(this.secondary)try{this.secondary.setItem(e,t)}catch{}}deleteBoth(e){try{this.primary.removeItem(e)}catch{}if(this.secondary)try{this.secondary.removeItem(e)}catch{}}};function F(r){let e="0123456789abcdefghijklmnopqrstuvwxyz",t=[],s=globalThis.crypto;if(s?.getRandomValues){let n=new Uint8Array(r);s.getRandomValues(n);for(let i=0;i<r;i++)t.push(e[n[i]%e.length]??"0")}else for(let n=0;n<r;n++)t.push(e[Math.floor(Math.random()*e.length)]??"0");return t.join("")}var kt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function vt(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r);let e=[];for(let t=0;t<r.length;t++){let s=r.charCodeAt(t);if(s>=55296&&s<=56319&&t+1<r.length){let n=r.charCodeAt(t+1);n>=56320&&n<=57343&&(s=65536+(s-55296<<10)+(n-56320),t++)}s<128?e.push(s):s<2048?(e.push(192|s>>6),e.push(128|s&63)):s<65536?(e.push(224|s>>12),e.push(128|s>>6&63),e.push(128|s&63)):(e.push(240|s>>18),e.push(128|s>>12&63),e.push(128|s>>6&63),e.push(128|s&63))}return new Uint8Array(e)}function U(r){let e=vt(r),t=e.length*8,s=Math.floor((e.length+9+63)/64),n=new Uint8Array(s*64);n.set(e),n[e.length]=128;let i=Math.floor(t/4294967296),c=t>>>0,o=n.length-8;n[o+0]=i>>>24&255,n[o+1]=i>>>16&255,n[o+2]=i>>>8&255,n[o+3]=i&255,n[o+4]=c>>>24&255,n[o+5]=c>>>16&255,n[o+6]=c>>>8&255,n[o+7]=c&255;let a=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),d=new Uint32Array(64);for(let u=0;u<s;u++){let f=u*64;for(let h=0;h<16;h++)d[h]=(n[f+h*4]<<24|n[f+h*4+1]<<16|n[f+h*4+2]<<8|n[f+h*4+3])>>>0;for(let h=16;h<64;h++){let w=d[h-15],S=d[h-2],C=(w>>>7|w<<25)^(w>>>18|w<<14)^w>>>3,D=(S>>>17|S<<15)^(S>>>19|S<<13)^S>>>10;d[h]=d[h-16]+C+d[h-7]+D>>>0}let m=a[0],g=a[1],y=a[2],b=a[3],v=a[4],x=a[5],A=a[6],P=a[7];for(let h=0;h<64;h++){let w=(v>>>6|v<<26)^(v>>>11|v<<21)^(v>>>25|v<<7),S=v&x^~v&A,C=P+w+S+kt[h]+d[h]>>>0,D=(m>>>2|m<<30)^(m>>>13|m<<19)^(m>>>22|m<<10),at=m&g^m&y^g&y,ct=D+at>>>0;P=A,A=x,x=v,v=b+C>>>0,b=y,y=g,g=m,m=C+ct>>>0}a[0]=a[0]+m>>>0,a[1]=a[1]+g>>>0,a[2]=a[2]+y>>>0,a[3]=a[3]+b>>>0,a[4]=a[4]+v>>>0,a[5]=a[5]+x>>>0,a[6]=a[6]+A>>>0,a[7]=a[7]+P>>>0}let l="";for(let u=0;u<8;u++)l+=a[u].toString(16).padStart(8,"0");return l}var wt=1440*60*1e3,Z="_anon",_t="_index",R=class r{constructor(e,t="crossdeck:entitlements",s=wt){this.all=[];this.lastUpdated=0;this.lastRefreshFailedAt=0;this.listeners=new Set;this.listenerErrorCount=0;this.currentSuffix=Z;this.storage=e,this.storageKeyPrefix=t,this.staleAfterMs=s,this.hydrate()}get storageKey(){return`${this.storageKeyPrefix}:${this.currentSuffix}`}get indexKey(){return`${this.storageKeyPrefix}:${_t}`}static suffixForUserId(e){return e==null||e===""?Z:U(e)}setUserKey(e){let t=r.suffixForUserId(e);if(t===this.currentSuffix){this.all=[],this.lastUpdated=0,this.lastRefreshFailedAt=0,this.notify(),this.hydrate();return}this.currentSuffix=t,this.all=[],this.lastUpdated=0,this.lastRefreshFailedAt=0,this.hydrate(),this.notify()}isEntitled(e){let t=Date.now()/1e3;return this.all.some(s=>s.key===e&&s.isActive&&(s.validUntil==null||s.validUntil>t))}list(){return this.all.slice()}get freshness(){return this.lastUpdated}get isStale(){return this.lastRefreshFailedAt>this.lastUpdated?!0:this.lastUpdated>0&&Date.now()-this.lastUpdated>this.staleAfterMs}get refreshFailedAt(){return this.lastRefreshFailedAt}get listenerErrors(){return this.listenerErrorCount}markRefreshFailed(){this.lastRefreshFailedAt=Date.now()}setFromList(e){this.all=e.slice(),this.lastUpdated=Date.now(),this.lastRefreshFailedAt=0,this.persist(),this.recordSuffixInIndex(this.currentSuffix),this.notify()}clear(){if(this.all=[],this.lastUpdated=0,this.lastRefreshFailedAt=0,this.storage)try{this.storage.removeItem(this.storageKey)}catch{}this.removeSuffixFromIndex(this.currentSuffix),this.notify()}clearAll(){if(this.all=[],this.lastUpdated=0,this.lastRefreshFailedAt=0,this.currentSuffix=Z,this.storage){let e=this.readIndex();for(let t of e)try{this.storage.removeItem(`${this.storageKeyPrefix}:${t}`)}catch{}try{this.storage.removeItem(`${this.storageKeyPrefix}:${Z}`)}catch{}try{this.storage.removeItem(this.indexKey)}catch{}}this.notify()}subscribe(e){this.listeners.add(e);let t=!1;return()=>{t||(t=!0,this.listeners.delete(e))}}hydrate(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);t&&t.v===1&&Array.isArray(t.entitlements)&&(this.all=t.entitlements,this.lastUpdated=typeof t.lastUpdated=="number"?t.lastUpdated:0)}catch{}}persist(){if(this.storage)try{let e={v:1,entitlements:this.all,lastUpdated:this.lastUpdated};this.storage.setItem(this.storageKey,JSON.stringify(e))}catch{}}readIndex(){if(!this.storage)return[];try{let e=this.storage.getItem(this.indexKey);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}recordSuffixInIndex(e){if(!this.storage)return;let t=this.readIndex();if(!t.includes(e)){t.push(e);try{this.storage.setItem(this.indexKey,JSON.stringify(t))}catch{}}}removeSuffixFromIndex(e){if(!this.storage)return;let t=this.readIndex(),s=t.filter(n=>n!==e);if(s.length!==t.length)try{s.length===0?this.storage.removeItem(this.indexKey):this.storage.setItem(this.indexKey,JSON.stringify(s))}catch{}}notify(){if(this.listeners.size===0)return;let e=this.all.slice(),t=[...this.listeners];for(let s of t)try{s(e)}catch{this.listenerErrorCount+=1}}};function St(r){return[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.slice(20,32)].join("-")}function L(r){let e;if(r.rail==="apple"?e=r.signedTransactionInfo??"":r.rail==="google"?e=r.purchaseToken??"":e="",!e)throw new Error(`deriveIdempotencyKeyForPurchase: no stable identifier in body (rail=${r.rail}). Apple needs signedTransactionInfo; Google needs purchaseToken.`);let t=`crossdeck:purchases/sync:${r.rail}:${e}`;return St(U(t))}function Et(r,e,t={},s=Math.random){let n=t.baseMs??1e3,i=t.maxMs??6e4,c=t.factor??2,o=Math.min(r,30),d=Math.min(i,n*Math.pow(c,o))*s();if(e!==void 0){let u=Math.min(864e5,e);if(u>d)return u}return Math.max(0,Math.round(d))}var ee=class{constructor(e={}){this.options=e;this.attempts=0}get consecutiveFailures(){return this.attempts}get isWarning(){return this.attempts>=(this.options.failuresBeforeWarn??8)}nextDelay(e,t=Math.random){let s=Et(this.attempts,e,this.options,t);return this.attempts+=1,s}recordSuccess(){this.attempts=0}};var B=1e3,te=class{constructor(e){this.cfg=e;this.buffer=[];this.pendingBatch=null;this.pendingBatchId=null;this.dropped=0;this.inFlight=0;this.lastFlushAt=0;this.lastError=null;this.cancelTimer=null;this.firstFlushFired=!1;this.nextRetryAt=null;if(this.retry=new ee(e.retry??{}),this.persistent=e.persistentStore??null,this.persistent){let t=this.persistent.load();t.length>0&&(t.length>B?(this.dropped+=t.length-B,this.buffer=t.slice(t.length-B)):this.buffer=t,this.cfg.onBufferChange?.(this.buffer.length),this.scheduleIdleFlush())}}enqueue(e){if(this.buffer.push(e),this.buffer.length>B){let t=this.buffer.length-B;this.buffer.splice(0,t),this.dropped+=t,this.cfg.onDrop?.(t)}this.cfg.onBufferChange?.(this.buffer.length),this.persistAll(),this.buffer.length>=this.cfg.batchSize?this.flush():this.scheduleIdleFlush()}async flush(e={}){let t,s;if(this.pendingBatch!==null&&this.pendingBatchId!==null)t=this.pendingBatch,s=this.pendingBatchId;else{if(this.buffer.length===0)return null;t=this.buffer.splice(0),s=this.mintBatchId(),this.pendingBatch=t,this.pendingBatchId=s,this.inFlight+=t.length,this.cfg.onBufferChange?.(this.buffer.length),this.persistAll()}this.cancelTimerIfSet(),this.nextRetryAt=null;try{let n=this.cfg.envelope(),i=await this.cfg.http.request("POST","/events",{body:{appId:n.appId,environment:n.environment,sdk:n.sdk,events:t},keepalive:e.keepalive===!0,idempotencyKey:s});return this.lastFlushAt=Date.now(),this.lastError=null,this.inFlight-=t.length,this.pendingBatch=null,this.pendingBatchId=null,this.retry.recordSuccess(),this.persistAll(),this.firstFlushFired||(this.firstFlushFired=!0,this.cfg.onFirstFlushSuccess?.()),i}catch(n){let i=n instanceof Error?n.message:String(n);if(this.lastError=i,Ct(n)){let a=t.length;return this.pendingBatch=null,this.pendingBatchId=null,this.inFlight-=a,this.dropped+=a,this.persistAll(),this.cfg.onDrop?.(a),this.cfg.onPermanentFailure?.({status:n.status??0,droppedCount:a,lastError:i}),null}let c=xt(n),o=this.retry.nextDelay(c);return this.scheduleRetry(o),this.cfg.onRetryScheduled?.({delayMs:o,consecutiveFailures:this.retry.consecutiveFailures,retryAfterMs:c,lastError:i}),null}}reset(){this.cancelTimerIfSet(),this.nextRetryAt=null,this.buffer=[],this.pendingBatch=null,this.pendingBatchId=null,this.dropped=0,this.inFlight=0,this.lastError=null,this.retry.recordSuccess(),this.persistent?.clear(),this.cfg.onBufferChange?.(0)}getStats(){return{buffered:this.buffer.length,dropped:this.dropped,inFlight:this.inFlight,lastFlushAt:this.lastFlushAt,lastError:this.lastError,consecutiveFailures:this.retry.consecutiveFailures,nextRetryAt:this.nextRetryAt}}get pendingIdempotencyKey(){return this.pendingBatchId}persistAll(){if(this.persistent){if(this.pendingBatch===null){this.persistent.save(this.buffer);return}this.persistent.save([...this.pendingBatch,...this.buffer])}}scheduleIdleFlush(){this.cancelTimerIfSet();let e=this.cfg.scheduler??Fe;this.cancelTimer=e(()=>{this.flush()},this.cfg.intervalMs)}scheduleRetry(e){this.cancelTimerIfSet(),this.nextRetryAt=Date.now()+e;let t=this.cfg.scheduler??Fe;this.cancelTimer=t(()=>{this.flush()},e)}cancelTimerIfSet(){this.cancelTimer&&(this.cancelTimer(),this.cancelTimer=null)}mintBatchId(){return`batch_${Date.now().toString(36)}${F(10)}`}};function xt(r){if(r&&typeof r=="object"&&"retryAfterMs"in r){let e=r.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}}function Ct(r){if(!r||typeof r!="object")return!1;let e=r.status;return!(typeof e!="number"||!Number.isFinite(e)||e<400||e>=500||e===408||e===429)}function Fe(r,e){let t=setTimeout(r,e);if(typeof t.unref=="function")try{t.unref()}catch{}return()=>clearTimeout(t)}var re=class{constructor(e){this.options=e;this.writeScheduled=!1;this.pendingSnapshot=null;this.key=`${e.prefix}queue.v1`}load(){let e;try{e=this.options.storage.getItem(this.key)}catch{return[]}if(!e)return[];try{let t=JSON.parse(e);return!t||t.version!==1||!Array.isArray(t.events)?[]:t.events}catch{return[]}}save(e){this.pendingSnapshot=e.slice(),!this.writeScheduled&&(this.writeScheduled=!0,queueMicrotask(()=>this.flushWrite()))}saveSync(e){this.pendingSnapshot=e.slice(),this.flushWrite()}clear(){this.pendingSnapshot=null,this.writeScheduled=!1;try{this.options.storage.removeItem(this.key)}catch{}}flushWrite(){this.writeScheduled=!1;let e=this.pendingSnapshot;if(this.pendingSnapshot=null,e===null)return;if(e.length===0){try{this.options.storage.removeItem(this.key)}catch{}return}let t={version:1,events:e};try{this.options.storage.setItem(this.key,JSON.stringify(t))}catch{}}};var V=class{constructor(){this.store=new Map}getItem(e){return this.store.get(e)??null}setItem(e,t){this.store.set(e,t)}removeItem(e){this.store.delete(e)}},se=class{constructor(e){this.maxAgeSec=e?.maxAgeSec??63072e3,this.secure=e?.secure??Tt(),this.sameSite=e?.sameSite??"Lax"}getItem(e){if(!ge())return null;let t=globalThis.document,s=t.cookie?t.cookie.split(/;\s*/):[],n=encodeURIComponent(e)+"=";for(let i of s)if(i.startsWith(n))try{return decodeURIComponent(i.slice(n.length))}catch{return null}return null}setItem(e,t){if(!ge())return;let s=globalThis.document,n=[`${encodeURIComponent(e)}=${encodeURIComponent(t)}`,"Path=/",`Max-Age=${this.maxAgeSec}`,`SameSite=${this.sameSite}`];this.secure&&n.push("Secure");try{s.cookie=n.join("; ")}catch{}}removeItem(e){if(!ge())return;let t=globalThis.document,s=[`${encodeURIComponent(e)}=`,"Path=/","Max-Age=0",`SameSite=${this.sameSite}`];this.secure&&s.push("Secure");try{t.cookie=s.join("; ")}catch{}}};function Ve(){try{let r=globalThis.localStorage;if(r){let e="__crossdeck_probe__";return r.setItem(e,"1"),r.removeItem(e),r}}catch{}return new V}function Tt(){try{return globalThis.location?.protocol==="https:"}catch{return!1}}function ge(){return typeof globalThis.document<"u"}function It(){return typeof globalThis.window<"u"&&typeof globalThis.document<"u"&&typeof globalThis.navigator<"u"}function Oe(r){let e={};if(r?.appVersion&&(e.appVersion=r.appVersion),!It())return e;let t=globalThis.window,s=globalThis.navigator,n=globalThis.document;try{typeof s.language=="string"&&(e.locale=s.language)}catch{}try{e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}try{t.screen&&(e.screenWidth=t.screen.width,e.screenHeight=t.screen.height),e.viewportWidth=t.innerWidth,e.viewportHeight=t.innerHeight,e.devicePixelRatio=t.devicePixelRatio}catch{}try{let i=s.userAgent??"",c=Rt(i);Object.assign(e,c)}catch{}try{let i=s.userAgentData;if(i?.platform&&!e.os&&(e.os=i.platform),i?.brands&&!e.browser){let c=i.brands.find(o=>!/Not[ .;A]*Brand/i.test(o.brand)&&!/Chromium/i.test(o.brand));c&&(e.browser=c.brand,e.browserVersion=c.version)}}catch{}return e}function Rt(r){let e={};if(/iPad|iPhone|iPod/.test(r)){e.os="iOS";let t=r.match(/OS (\d+[._]\d+(?:[._]\d+)?)/);t?.[1]&&(e.osVersion=t[1].replace(/_/g,"."))}else if(/Android/.test(r)){e.os="Android";let t=r.match(/Android (\d+(?:\.\d+)*)/);t?.[1]&&(e.osVersion=t[1])}else if(/Windows/.test(r)){e.os="Windows";let t=r.match(/Windows NT (\d+\.\d+)/);t?.[1]&&(e.osVersion=t[1])}else if(/Mac OS X|Macintosh/.test(r)){e.os="macOS";let t=r.match(/Mac OS X (\d+[._]\d+(?:[._]\d+)?)/);t?.[1]&&(e.osVersion=t[1].replace(/_/g,"."))}else/Linux/.test(r)&&(e.os="Linux");return/Edg\/(\d+(?:\.\d+)*)/.test(r)?(e.browser="Edge",e.browserVersion=r.match(/Edg\/(\d+(?:\.\d+)*)/)?.[1]):/Firefox\/(\d+(?:\.\d+)*)/.test(r)?(e.browser="Firefox",e.browserVersion=r.match(/Firefox\/(\d+(?:\.\d+)*)/)?.[1]):/OPR\/(\d+(?:\.\d+)*)/.test(r)?(e.browser="Opera",e.browserVersion=r.match(/OPR\/(\d+(?:\.\d+)*)/)?.[1]):/Chrome\/(\d+(?:\.\d+)*)/.test(r)?(e.browser="Chrome",e.browserVersion=r.match(/Chrome\/(\d+(?:\.\d+)*)/)?.[1]):/Version\/(\d+(?:\.\d+)*).*Safari/.test(r)&&(e.browser="Safari",e.browserVersion=r.match(/Version\/(\d+(?:\.\d+)*)/)?.[1]),e}var O={sessions:!0,pageViews:!0,deviceInfo:!0,clicks:!0,webVitals:!0,errors:!0},ye=1800*1e3,At="crossdeck:session",Pt=5e3,ne={utm_source:"",utm_medium:"",utm_campaign:"",utm_content:"",utm_term:"",referrer:"",gclid:"",fbclid:"",msclkid:"",ttclid:"",li_fat_id:"",twclid:""},j=class{constructor(e,t,s){this.cfg=e;this.track=t;this.session=null;this.cleanups=[];this.lastPersistAt=0;this.pageviewId=null;this.storage=s?.storage??null,this.sessionKey=s?.storageKey??At}install(){Ne()&&(this.cfg.sessions&&this.installSessionTracking(),this.cfg.pageViews&&this.installPageViewTracking(),this.cfg.clicks&&this.installClickTracking())}uninstall(){for(;this.cleanups.length;){let e=this.cleanups.pop();try{e?.()}catch{}}this.session&&!this.session.endedSent&&this.emitSessionEnd(),this.clearStoredSession(),this.session=null}resetSession(){this.session&&!this.session.endedSent&&this.emitSessionEnd(),this.pageviewId=null,this.session=this.startNewSession(),this.persistSession(),this.emitSessionStart()}markActivity(){if(!this.session)return;let e=Date.now();if(e-this.session.lastActivityAt>=ye){this.pageviewId=null,this.session=this.startNewSession(),this.persistSession(),this.emitSessionStart();return}this.session.lastActivityAt=e,e-this.lastPersistAt>=Pt&&this.persistSession()}get currentSessionId(){return this.session?.sessionId??null}get currentPageviewId(){return this.pageviewId}get currentAcquisition(){return this.session?.acquisition??ne}installSessionTracking(){let e=Date.now(),t=this.readStoredSession();t&&e-t.lastActivityAt<ye?(this.session={sessionId:t.id,startedAt:t.startedAt,lastActivityAt:e,hiddenAt:null,endedSent:!1,acquisition:t.acquisition},this.persistSession()):(this.session=this.startNewSession(),this.persistSession(),this.emitSessionStart());let s=()=>{if(!this.session)return;let o=globalThis.document;o.visibilityState==="hidden"?(this.session.hiddenAt=Date.now(),this.persistSession()):o.visibilityState==="visible"&&(Date.now()-this.session.lastActivityAt>=ye?(this.pageviewId=null,this.session=this.startNewSession(),this.persistSession(),this.emitSessionStart()):this.session.hiddenAt=null)},n=()=>this.persistSession(),i=globalThis.window,c=globalThis.document;c.addEventListener("visibilitychange",s),i.addEventListener("pagehide",n),i.addEventListener("beforeunload",n),this.cleanups.push(()=>{c.removeEventListener("visibilitychange",s),i.removeEventListener("pagehide",n),i.removeEventListener("beforeunload",n)})}startNewSession(){let e=Date.now();return{sessionId:Ht(),startedAt:e,lastActivityAt:e,hiddenAt:null,endedSent:!1,acquisition:zt()}}readStoredSession(){if(!this.storage)return null;try{let e=this.storage.getItem(this.sessionKey);if(!e)return null;let t=JSON.parse(e);return!t||typeof t.id!="string"||typeof t.startedAt!="number"||typeof t.lastActivityAt!="number"?null:{id:t.id,startedAt:t.startedAt,lastActivityAt:t.lastActivityAt,acquisition:t.acquisition&&typeof t.acquisition=="object"?t.acquisition:ne}}catch{return null}}persistSession(){if(!(!this.storage||!this.session)){this.lastPersistAt=Date.now();try{let e={id:this.session.sessionId,startedAt:this.session.startedAt,lastActivityAt:this.session.lastActivityAt,acquisition:this.session.acquisition};this.storage.setItem(this.sessionKey,JSON.stringify(e))}catch{}}}clearStoredSession(){if(this.storage)try{this.storage.removeItem(this.sessionKey)}catch{}}emitSessionStart(){this.session&&this.track("session.started",{sessionId:this.session.sessionId})}emitSessionEnd(){if(!this.session||this.session.endedSent)return;let e=Date.now()-this.session.startedAt;this.track("session.ended",{sessionId:this.session.sessionId,durationMs:e}),this.session.endedSent=!0}installPageViewTracking(){let e=globalThis.window,t=globalThis.document,s=0,n="",i=250,c=(f=!1)=>{let m=e.location,g=m.href,y=Date.now();!f&&g===n&&y-s<i||(s=y,n=g,this.pageviewId=`pv_${Date.now().toString(36)}${F(10)}`,this.track("page.viewed",{pageviewId:this.pageviewId,path:m.pathname,url:g,search:m.search||void 0,hash:m.hash||void 0,title:t.title,referrer:t.referrer||void 0}))};c();let o=e.history.pushState,a=e.history.replaceState;function d(f,m,g){o.apply(this,[f,m,g]),queueMicrotask(c)}function l(f,m,g){a.apply(this,[f,m,g]),queueMicrotask(c)}e.history.pushState=d,e.history.replaceState=l;let u=()=>c(!0);e.addEventListener("popstate",u),this.cleanups.push(()=>{e.history.pushState===d&&(e.history.pushState=o),e.history.replaceState===l&&(e.history.replaceState=a),e.removeEventListener("popstate",u)})}installClickTracking(){let e=globalThis.window,t=globalThis.document,s=0,n=null,i=100,c=64,o=a=>{let d=a.target;if(!d||!(d instanceof Element))return;let l=Date.now();if(d===n&&l-s<i)return;s=l,n=d;let f=Dt(d)||d;if(Ft(f)||Vt(f)||Ot(f))return;let m=f.tagName.toLowerCase(),g=Bt(Kt(f),c),y=f.href||void 0,b=f.target||void 0,v=f.id||void 0,x=f.getAttribute("role")||void 0,A=f.getAttribute("aria-label")||void 0,P=jt(f),h=Wt(f),w=m==="a"&&!!y,S=f.getAttribute("data-cd-event"),C={selector:P,tag:m,text:g,elementId:v,role:x,ariaLabel:A,href:y,isLink:w,linkTarget:b,viewportX:a.clientX,viewportY:a.clientY,pageX:a.pageX,pageY:a.pageY,...h};for(let D of Object.keys(C))(C[D]===void 0||C[D]===null||C[D]==="")&&delete C[D];this.track(S||"element.clicked",C)};t.addEventListener("click",o,{capture:!0,passive:!0}),this.cleanups.push(()=>{t.removeEventListener("click",o,{capture:!0})})}};function Dt(r){return r.closest("[data-cd-event]")||r.closest("[data-cd-noTrack]")||r.closest("button, a, [role='button'], [role='link'], input[type='button'], input[type='submit']")||null}function Ft(r){if(!(r instanceof HTMLElement))return!1;let e=r.tagName.toLowerCase();if(e==="textarea"||e==="select")return!0;if(e==="input"){let t=(r.type||"").toLowerCase();return t!=="button"&&t!=="submit"&&t!=="image"&&t!=="reset"}return!1}function Vt(r){return!!r.closest("[data-cd-noTrack], [data-cd-no-track], .cd-noTrack, .cd-no-track")}function Ot(r){return!!r.closest('input[type="password"]')}var Lt=new Set(["span","b","strong","em","i","small","mark","u","label","abbr","time","bdi","cite","code","kbd","q","sub","sup"]),Nt=new Set(["svg","style","script","noscript"]),Ut="a[href], button, input, select, textarea, [role='button'], [role='link'], h1, h2, h3, h4, h5, h6",Mt="h1, h2, h3, h4, h5, h6";function Le(r){return r.replace(/\s+/g," ").trim()}function be(r){let e="",t=s=>{let n=s.childNodes;for(let i=0;i<n.length;i++){let c=n[i];if(c){if(c.nodeType===3)e+=c.textContent||"";else if(c.nodeType===1){if(Nt.has(c.tagName.toLowerCase()))continue;e+=" ",t(c),e+=" "}}}};return t(r),Le(e)}function $t(r){let e="",t=r.childNodes;for(let s=0;s<t.length;s++){let n=t[s];n&&(n.nodeType===3?e+=" "+(n.textContent||""):n.nodeType===1&&Lt.has(n.tagName.toLowerCase())&&(e+=" "+be(n)))}return Le(e)}function qt(r){if(!(r.querySelector(Ut)!==null))return be(r);let t=$t(r);if(t)return t;let s=r.querySelector(Mt);if(s){let n=be(s);if(n)return n}return""}function Kt(r){let e=d=>d.replace(/\s+/g," ").trim(),t=r.getAttribute("data-cd-track")||r.getAttribute("data-track")||r.getAttribute("data-testid");if(t){let d=e(t);if(d)return d}let s=r.getAttribute("aria-label");if(s){let d=e(s);if(d)return d}let n=r.getAttribute("aria-labelledby");if(n&&typeof r.ownerDocument?.getElementById=="function"){let d=[];for(let l of n.split(/\s+/)){let u=r.ownerDocument.getElementById(l),f=u?.textContent?e(u.textContent):"";f&&d.push(f)}if(d.length>0)return d.join(" ")}if(r instanceof HTMLInputElement&&r.value){let d=e(r.value);if(d)return d}let i=qt(r);if(i)return i;let c=r.getAttribute("title");if(c){let d=e(c);if(d)return d}let o=r.querySelector("img[alt]");if(o){let d=o.getAttribute("alt")??"",l=e(d);if(l)return l}let a=r.querySelector("svg title");if(a?.textContent){let d=e(a.textContent);if(d)return d}return""}function Bt(r,e){return r.length<=e?r:r.slice(0,e-1)+"\u2026"}function jt(r){let e=[],t=r,s=0;for(;t&&t.nodeName.toLowerCase()!=="body"&&s<5;){let n=t.nodeName.toLowerCase();if(t.id){e.unshift(`${n}#${t.id}`);break}if(t.classList.length>0){let i=Array.from(t.classList).filter(c=>!c.startsWith("cd-")).slice(0,2).join(".");i&&(n+=`.${i}`)}e.unshift(n),t=t.parentElement,s++}return e.join(" > ")}function Wt(r){let e={};if(!(r instanceof HTMLElement))return e;for(let t of r.getAttributeNames()){if(!t.startsWith("data-")||t==="data-cd-noTrack"||t==="data-cd-no-track"||t==="data-cd-event")continue;let s=r.getAttribute(t)||"",n=t.replace(/^data-cd-prop-/,"").replace(/^data-/,"");e[n]=s}return e}function Ne(){return typeof globalThis.window<"u"&&typeof globalThis.document<"u"}function Ht(){return`sess_${Date.now().toString(36)}${F(10)}`}function zt(){if(!Ne())return{...ne};let r={...ne};try{let e=globalThis.window,t=new URLSearchParams(e.location.search??"");r.utm_source=t.get("utm_source")??"",r.utm_medium=t.get("utm_medium")??"",r.utm_campaign=t.get("utm_campaign")??"",r.utm_content=t.get("utm_content")??"",r.utm_term=t.get("utm_term")??"",r.gclid=t.get("gclid")??"",r.fbclid=t.get("fbclid")??"",r.msclkid=t.get("msclkid")??"",r.ttclid=t.get("ttclid")??"",r.li_fat_id=t.get("li_fat_id")??"",r.twclid=t.get("twclid")??""}catch{}try{let e=globalThis.document;typeof e.referrer=="string"&&(r.referrer=e.referrer)}catch{}return r}var Gt=[/^email$/i,/^password$/i,/^token$/i,/^secret$/i,/^card$/i,/^phone$/i,/password/i,/credit_?card/i];function Ue(r){if(!r)return[];let e=[];for(let t of Object.keys(r))Gt.some(s=>s.test(t))&&e.push(t);return e}var ie=class{constructor(){this.enabled=!1;this.seen=new Set}emit(e,t,s){if(!this.enabled)return;if(Jt.has(e)){if(this.seen.has(e))return;this.seen.add(e)}let n=s?` ${Xt(s)}`:"";console.info(`[crossdeck:${e}] ${t}${n}`)}},Jt=new Set(["sdk.configured","sdk.first_event_sent","sdk.environment_mismatch"]);function Xt(r){try{return JSON.stringify(r)}catch{return"[unserialisable context]"}}function W(r,e={}){let t=[];if(!r)return{properties:{},warnings:t};let s=e.maxStringLength??1024,n=e.maxBatchPropertyBytes??8192,i=e.maxDepth??5,c=new Set,o=(l,u,f)=>{if(f>i)return t.push({kind:"depth_exceeded",key:u}),{keep:!0,value:"[depth-exceeded]"};if(l===null)return{keep:!0,value:null};let m=typeof l;if(m==="string"){let g=l;return g.length>s?(t.push({kind:"truncated_string",key:u}),{keep:!0,value:g.slice(0,s-1)+"\u2026"}):{keep:!0,value:g}}if(m==="number")return Number.isFinite(l)?{keep:!0,value:l}:(t.push({kind:"non_serialisable",key:u}),{keep:!0,value:null});if(m==="boolean")return{keep:!0,value:l};if(m==="bigint")return t.push({kind:"coerced_bigint",key:u}),{keep:!0,value:l.toString()};if(m==="function")return t.push({kind:"dropped_function",key:u}),{keep:!1,value:void 0};if(m==="symbol")return t.push({kind:"dropped_symbol",key:u}),{keep:!1,value:void 0};if(m==="undefined")return t.push({kind:"dropped_undefined",key:u}),{keep:!1,value:void 0};if(l instanceof Date)return t.push({kind:"coerced_date",key:u}),{keep:!0,value:Number.isFinite(l.getTime())?l.toISOString():null};if(l instanceof Error)return t.push({kind:"coerced_error",key:u}),{keep:!0,value:{name:l.name,message:l.message,stack:typeof l.stack=="string"?l.stack.slice(0,s):void 0}};if(l instanceof Map){t.push({kind:"coerced_map",key:u});let g={};for(let[y,b]of l.entries()){let v=typeof y=="string"?y:String(y),x=o(b,`${u}.${v}`,f+1);x.keep&&(g[v]=x.value)}return{keep:!0,value:g}}if(l instanceof Set){t.push({kind:"coerced_set",key:u});let g=[],y=0;for(let b of l.values()){let v=o(b,`${u}[${y}]`,f+1);v.keep&&g.push(v.value),y++}return{keep:!0,value:g}}if(Array.isArray(l)){if(c.has(l))return t.push({kind:"circular_reference",key:u}),{keep:!0,value:"[circular]"};c.add(l);let g=[];for(let y=0;y<l.length;y++){let b=o(l[y],`${u}[${y}]`,f+1);b.keep&&g.push(b.value)}return c.delete(l),{keep:!0,value:g}}if(m==="object"){let g=l;if(c.has(g))return t.push({kind:"circular_reference",key:u}),{keep:!0,value:"[circular]"};c.add(g);let y={};for(let b of Object.keys(g)){let v=o(g[b],`${u}.${b}`,f+1);v.keep&&(y[b]=v.value)}return c.delete(g),{keep:!0,value:y}}t.push({kind:"non_serialisable",key:u});try{return{keep:!0,value:String(l)}}catch{return{keep:!1,value:void 0}}},a={};for(let l of Object.keys(r)){let u=o(r[l],l,0);u.keep&&(a[l]=u.value)}let d=Me(a);if(d&&ke(d)>n){t.push({kind:"size_cap_exceeded",key:"*"});let l=Object.keys(a).map(f=>({k:f,size:ke(Me(a[f])??"")})).sort((f,m)=>m.size-f.size),u=ke(d);for(let{k:f}of l){if(u<=n)break;u-=l.find(m=>m.k===f).size,delete a[f]}a.__truncated=!0}return{properties:a,warnings:t}}function Me(r){try{return JSON.stringify(r)??null}catch{return null}}function ke(r){return typeof TextEncoder<"u"?new TextEncoder().encode(r).length:r.length*4}var oe="super_props",ve="groups",ae=class{constructor(e,t){this.storage=e;this.prefix=t;this.superProps={};this.groups={};this.superProps=$e(e,t+oe)??{},this.groups=$e(e,t+ve)??{}}register(e){for(let[t,s]of Object.entries(e))s===null?delete this.superProps[t]:s!==void 0&&(this.superProps[t]=s);return we(this.storage,this.prefix+oe,this.superProps),{...this.superProps}}unregister(e){e in this.superProps&&(delete this.superProps[e],we(this.storage,this.prefix+oe,this.superProps))}getSuperProperties(){return{...this.superProps}}setGroup(e,t,s){t===null?delete this.groups[e]:this.groups[e]=s!==void 0?{id:t,traits:s}:{id:t},we(this.storage,this.prefix+ve,this.groups)}getGroups(){return JSON.parse(JSON.stringify(this.groups))}getGroupIds(){let e={};for(let[t,s]of Object.entries(this.groups))e[t]=s.id;return e}clear(){this.superProps={},this.groups={};try{this.storage.removeItem(this.prefix+oe)}catch{}try{this.storage.removeItem(this.prefix+ve)}catch{}}};function $e(r,e){let t;try{t=r.getItem(e)}catch{return null}if(!t)return null;try{return JSON.parse(t)}catch{return null}}function we(r,e,t){try{r.setItem(e,JSON.stringify(t))}catch{}}var ce=class{constructor(e,t){this.cfg=e;this.report=t;this.observers=[];this.flushed=new Set;this.cls=0;this.clsEntries=[];this.inp=0;this.cleanups=[]}install(){if(!this.cfg.enabled||typeof PerformanceObserver>"u"||typeof globalThis>"u"||!("document"in globalThis))return;let e=globalThis.document;try{let i=new PerformanceObserver(c=>{for(let o of c.getEntries()){let a=o;a.responseStart>0&&!this.flushed.has("ttfb")&&(this.flushed.add("ttfb"),this.report("webvitals.ttfb",{valueMs:Math.round(a.responseStart-a.startTime)}))}});i.observe({type:"navigation",buffered:!0}),this.observers.push(i)}catch{}try{let i=new PerformanceObserver(c=>{for(let o of c.getEntries())o.name==="first-contentful-paint"&&!this.flushed.has("fcp")&&(this.flushed.add("fcp"),this.report("webvitals.fcp",{valueMs:Math.round(o.startTime)}))});i.observe({type:"paint",buffered:!0}),this.observers.push(i)}catch{}let t=0;try{let i=new PerformanceObserver(c=>{let o=c.getEntries(),a=o[o.length-1];a&&(t=a.startTime)});i.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(i)}catch{}try{let i=new PerformanceObserver(c=>{for(let o of c.getEntries()){let a=o;typeof a.value=="number"&&!a.hadRecentInput&&(this.cls+=a.value,this.clsEntries.push(o))}});i.observe({type:"layout-shift",buffered:!0}),this.observers.push(i)}catch{}try{let i=new PerformanceObserver(c=>{for(let o of c.getEntries()){let a=o;a.interactionId&&a.duration>this.inp&&(this.inp=a.duration)}});try{i.observe({type:"event",buffered:!0,durationThreshold:16})}catch{i.observe({type:"first-input",buffered:!0})}this.observers.push(i)}catch{}let s=()=>{t>0&&!this.flushed.has("lcp")&&(this.flushed.add("lcp"),this.report("webvitals.lcp",{valueMs:Math.round(t)})),this.cls>0&&!this.flushed.has("cls")&&(this.flushed.add("cls"),this.report("webvitals.cls",{value:Math.round(this.cls*1e3)/1e3})),this.inp>0&&!this.flushed.has("inp")&&(this.flushed.add("inp"),this.report("webvitals.inp",{valueMs:Math.round(this.inp)}))},n=()=>{e.visibilityState==="hidden"&&s()};e.addEventListener("visibilitychange",n),globalThis.window.addEventListener("pagehide",s),this.cleanups.push(()=>{e.removeEventListener("visibilitychange",n),globalThis.window.removeEventListener("pagehide",s)})}uninstall(){for(let e of this.observers)try{e.disconnect()}catch{}this.observers=[];for(let e of this.cleanups.splice(0))try{e()}catch{}}};var Qt={analytics:!0,marketing:!0,errors:!0},de=class{constructor(e){this.state={...Qt};this.dntDenied=!1;e?.respectDnt&&this.detectDnt()&&(this.dntDenied=!0,this.state={analytics:!1,marketing:!1,errors:!1})}set(e){if(this.dntDenied)return{...this.state};for(let t of Object.keys(e)){let s=e[t];typeof s=="boolean"&&(this.state[t]=s)}return{...this.state}}get(){return{...this.state}}get analytics(){return this.state.analytics}get marketing(){return this.state.marketing}get errors(){return this.state.errors}get isDntDenied(){return this.dntDenied}detectDnt(){try{let e=globalThis.navigator;return e?[e.doNotTrack,e.msDoNotTrack,globalThis.doNotTrack].some(s=>s==="1"||s==="yes"):!1}catch{return!1}}},Yt=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,Zt=/\b\d(?:[ -]?\d){12,18}\b/g,er="<email>",tr="<card>";function rr(r){return r&&r.replace(Yt,er).replace(Zt,tr)}function _e(r){let e={};for(let t of Object.keys(r))e[t]=qe(r[t]);return e}function qe(r){return typeof r=="string"?rr(r):Array.isArray(r)?r.map(qe):r&&typeof r=="object"&&r.constructor===Object?_e(r):r}var le=class{constructor(e=50){this.maxSize=e;this.items=[]}add(e){this.items.push(e),this.items.length>this.maxSize&&this.items.shift()}snapshot(){return this.items.slice()}clear(){this.items=[]}get size(){return this.items.length}};var sr="https://api.cross-deck.com/v1/events",Ke="cd_pub_live_9490e7aa029c432abf";function nr(){return!Ke.startsWith("cd_pub_RELIABILITY_PLACEHOLDER")}var ir=new Set(["contract_id","sdk_version","sdk_platform","failure_reason","run_context","run_id","test_file","test_name","device_class","verification_phase"]);function or(r){let e={};for(let[t,s]of Object.entries(r))ir.has(t)&&typeof s=="string"&&(e[t]=s);return e}function ue(r){if(!nr())return;let e=or(r);if(Object.keys(e).length===0)return;let t=JSON.stringify({events:[{name:"crossdeck.contract_failed",timestamp:Date.now(),properties:e}]}),s=globalThis.fetch;if(typeof s=="function")try{s(sr,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ke}`,"Crossdeck-Sdk-Version":`${I}@${T}`},body:t,keepalive:!0,credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"}).catch(()=>{})}catch{}}var Se=Object.freeze([{code:"invalid_public_key",type:"configuration_error",description:"The publishable key passed to Crossdeck.init() doesn't start with cd_pub_.",resolution:"Copy the key from your Crossdeck dashboard \u2192 API keys page.",retryable:!1},{code:"missing_app_id",type:"configuration_error",description:"Crossdeck.init() was called without an appId.",resolution:"Add appId to your init options \u2014 find it in the dashboard's Apps page.",retryable:!1},{code:"invalid_environment",type:"configuration_error",description:"Crossdeck.init() requires environment: 'production' | 'sandbox'.",resolution:'Pass the literal string "production" or "sandbox" \u2014 no other values are accepted.',retryable:!1},{code:"environment_mismatch",type:"configuration_error",description:"The publishable key's env prefix doesn't match the declared environment option.",resolution:"Either change `environment` to match the key prefix (cd_pub_test_ \u2194 sandbox, cd_pub_live_ \u2194 production), or swap the key for one minted in the right env.",retryable:!1},{code:"not_initialized",type:"configuration_error",description:"An SDK method was called before Crossdeck.init().",resolution:"Call Crossdeck.init({ appId, publicKey, environment }) once at app startup before any other method.",retryable:!1},{code:"missing_user_id",type:"invalid_request_error",description:"identify() was called with an empty userId.",resolution:"Pass a stable, non-empty user identifier from your auth layer \u2014 never a hardcoded placeholder.",retryable:!1},{code:"missing_event_name",type:"invalid_request_error",description:"track() was called without an event name.",resolution:"Pass a non-empty string as the first argument.",retryable:!1},{code:"missing_group_type",type:"invalid_request_error",description:"group() was called without a group type.",resolution:'Pass a non-empty type (e.g. "org", "team") as the first argument.',retryable:!1},{code:"missing_signed_transaction_info",type:"invalid_request_error",description:"syncPurchases() was called without StoreKit 2 signed transaction info.",resolution:"Pass the JWS string from Transaction.currentEntitlements / Transaction.updates.",retryable:!1},{code:"fetch_failed",type:"network_error",description:"The underlying fetch() call failed (typically a network outage or DNS issue).",resolution:"Check the user's network. The SDK will retry automatically with exponential backoff.",retryable:!0},{code:"request_timeout",type:"network_error",description:"A request was aborted after the configured timeoutMs (default 15s).",resolution:"Check the user's connection. Increase timeoutMs in init options if the user is on a known-slow network.",retryable:!0},{code:"invalid_json_response",type:"internal_error",description:"The server returned a 2xx with an unparseable body.",resolution:"Likely a transient backend bug. Retry; if it persists, contact support with the requestId.",retryable:!0},{code:"missing_api_key",type:"authentication_error",description:"No Authorization header (or Crossdeck-Api-Key header) on the request.",resolution:"Make sure Crossdeck.init({ publicKey }) was called with a cd_pub_\u2026 key before the request fired. Re-check your env-vars in CI / Docker if the key is empty at runtime.",retryable:!1},{code:"invalid_api_key",type:"authentication_error",description:"The API key is malformed, unknown, or doesn't resolve to a project.",resolution:"Copy the key from your Crossdeck dashboard \u2192 API keys. Confirm prefix is cd_pub_test_ / cd_pub_live_ for client SDKs and cd_sk_test_ / cd_sk_live_ for the Node server SDK.",retryable:!1},{code:"key_revoked",type:"authentication_error",description:"The API key was revoked in the Crossdeck dashboard.",resolution:"Mint a fresh key in the dashboard \u2192 API keys \u2192 Create new, swap it in, and redeploy. The revoked key cannot be reactivated.",retryable:!1},{code:"identity_token_invalid",type:"authentication_error",description:"The Firebase / Apple / Google ID token supplied with the request didn't verify against the dashboard's configured signers.",resolution:"Refresh the token client-side (Firebase auth.currentUser.getIdToken(true)) and retry. If the failure persists, confirm the signer is registered under dashboard \u2192 Authentication \u2192 Identity sources.",retryable:!0},{code:"origin_not_allowed",type:"permission_error",description:"The Origin header isn't in the project's Allowed origins list.",resolution:"Add the origin (e.g. https://app.example.com) under dashboard \u2192 Settings \u2192 Allowed origins. Wildcards like https://*.example.com are supported.",retryable:!1},{code:"bundle_id_not_allowed",type:"permission_error",description:"The iOS bundle ID sent via X-Crossdeck-Bundle-Id isn't registered under this app's Apple identity lock.",resolution:"Add the bundle ID under dashboard \u2192 Apps \u2192 <your app> \u2192 iOS bundle IDs.",retryable:!1},{code:"package_name_not_allowed",type:"permission_error",description:"The Android package name sent via X-Crossdeck-Package-Name isn't registered under this app's Android identity lock.",resolution:"Add the package name under dashboard \u2192 Apps \u2192 <your app> \u2192 Android package names.",retryable:!1},{code:"env_mismatch",type:"permission_error",description:"The request env (inferred from key prefix) doesn't match the resolved app's configured env.",resolution:"Use a cd_pub_live_ / cd_sk_live_ key with a production app, cd_pub_test_ / cd_sk_test_ with a sandbox app. The two cannot cross.",retryable:!1},{code:"idempotency_key_in_use",type:"invalid_request_error",description:"An Idempotency-Key was reused for a request with a different body (Stripe-grade contract).",resolution:"Generate a fresh key for a different transaction, or reuse the key only with the EXACT same body. The v1.4.0 SDKs derive keys deterministically from the body so this should never fire on SDK-managed calls.",retryable:!1},{code:"rate_limited",type:"rate_limit_error",description:"Request rate exceeded the project's per-second cap.",resolution:"Honour the Retry-After header \u2014 the SDK does this automatically on managed retries. If you're hitting it from a custom code path, throttle to <100 req/s/key.",retryable:!0},{code:"internal_error",type:"internal_error",description:"Server-side issue. Safe to retry with backoff.",resolution:"The SDK retries automatically. If your code paths through to this error, contact support with the requestId from the response envelope.",retryable:!0},{code:"google_not_supported",type:"invalid_request_error",description:"POST /purchases/sync with rail=google is gated until the Play Developer API reconciliation worker ships.",resolution:"Until v1.5+, Google Play purchases verify via Real-time Developer Notifications. The SDK auto-track path handles this transparently for Android consumers.",retryable:!1},{code:"stripe_not_supported",type:"invalid_request_error",description:"POST /purchases/sync with rail=stripe is unsupported \u2014 Stripe Checkout's redirect flow uses platform webhooks instead.",resolution:"Wire Stripe via the standard Checkout / Customer Portal flow; Crossdeck reconciles via the platform webhook automatically. No SDK call needed.",retryable:!1},{code:"missing_required_param",type:"invalid_request_error",description:"A required field is absent from the request body.",resolution:"Inspect the error.message \u2014 the missing field name is included verbatim. Refer to the SDK's TypeScript types for the canonical request shape.",retryable:!1},{code:"invalid_param_value",type:"invalid_request_error",description:"A field is present but the value failed validation (wrong shape, wrong length, wrong enum value).",resolution:"Read error.message for the specific field + reason. SDK-managed call sites should never emit this \u2014 file a bug if you do.",retryable:!1}]);function pe(r){return Se.find(e=>e.code===r)}function ze(r){return{sdkVersion:`${I}@${T}`,runId:`cd_verify_${yr(8)}`,runContext:r.runContext??"customer-app",logVerifierResults:r.logVerifierResults,disableContractAssertions:r.disableContractAssertions,console,emitTelemetry:ue}}var z=class{constructor(e){this.ctx=e;this.reentrancyDepth=0}report(e,t,s){this.ctx.disableContractAssertions||(e.ok?this.reportPass(e,t,s):this.reportFail(e,t,s))}reportPass(e,t,s){if(!this.ctx.logVerifierResults)return;let n=ar(e,s);t==="boot"?this.ctx.console.info(n):this.ctx.console.debug(n)}reportFail(e,t,s){if(this.ctx.console.warn(cr(e,s)),!(this.reentrancyDepth>0)){this.reentrancyDepth+=1;try{this.ctx.emitTelemetry({contract_id:e.contractId,sdk_version:this.ctx.sdkVersion,sdk_platform:"web",failure_reason:gr(e.failureReason,128),run_context:this.ctx.runContext,run_id:this.ctx.runId,verification_phase:t})}finally{this.reentrancyDepth-=1}}}};function ar(r,e){return`${e?`[crossdeck.${e}]`:"[crossdeck]"} \u2713 ${r.contractId} \u2014 ${r.evidence} (${r.durationMs}ms)`}function cr(r,e){return`${e?`[crossdeck.${e}]`:"[crossdeck]"} \u2717 ${r.contractId} \u2014 ${r.failureReason} (${r.durationMs}ms)`}var dr={contractId:"per-user-cache-isolation",bootTest(){let r=p();try{let e=new fe,t=new R(e,"_verifier");if(t.setUserKey("user_A"),t.setFromList([{object:"entitlement",key:"pro",isActive:!0,validUntil:null,source:{rail:"stripe",productId:"p_verifier",subscriptionId:"s_verifier"},updatedAt:Date.now()}]),t.setUserKey("user_B"),t.list().length!==0)return k("per-user-cache-isolation","in-memory snapshot still carried user_A's entitlements after rotation",p()-r);let n=R.suffixForUserId("user_A"),i=R.suffixForUserId("user_B");if(n===i)return k("per-user-cache-isolation","suffixes for user_A and user_B collided",p()-r);let c=e.getItem(`_verifier:${n}`),o=e.getItem(`_verifier:${i}`);return c?o?k("per-user-cache-isolation","user_B's storage slot already contained data before any write",p()-r):E("per-user-cache-isolation",`slot rotated A:${H(n)} \u2192 B:${H(i)} (isolated, physically separate)`,p()-r):k("per-user-cache-isolation","user_A's storage slot was wiped on rotation (expected isolation, not erasure)",p()-r)}catch(e){return k("per-user-cache-isolation",`boot test threw: ${e.message?.slice(0,80)??"unknown error"}`,p()-r)}},hooks:{onIdentify(r){let e=p(),t=R.suffixForUserId(r.priorUserId),s=R.suffixForUserId(r.nextUserId);return t!==s?r.cache.list().length!==0?k("per-user-cache-isolation","in-memory snapshot still held entitlements after slot rotation",p()-e):E("per-user-cache-isolation",`slot rotated ${H(t)} \u2192 ${H(s)}`,p()-e):E("per-user-cache-isolation",`same-id re-identify (suffix ${H(s)}); cleared + rehydrated per contract`,p()-e)}}},Ee="eyJ.jws.sig",Be="a66b1640-efaf-bb4d-1261-6650033bf111",lr={contractId:"idempotency-key-deterministic",bootTest(){let r=p();try{let e=L({rail:"apple",signedTransactionInfo:Ee});if(e!==Be)return k("idempotency-key-deterministic",`canonical apple JWS derived ${e} (expected ${Be})`,p()-r);if(L({rail:"apple",signedTransactionInfo:Ee})!==e)return k("idempotency-key-deterministic","same JWS produced different keys on two derivations",p()-r);let s=e,n=L({rail:"google",purchaseToken:Ee});return s===n?k("idempotency-key-deterministic","rail namespacing failed \u2014 apple/google identical key",p()-r):E("idempotency-key-deterministic",`apple JWS \u2192 ${e} (canonical vector + determinism + rail isolation)`,p()-r)}catch(e){return k("idempotency-key-deterministic",`boot test threw: ${e.message?.slice(0,80)??"unknown error"}`,p()-r)}},hooks:{onSyncPurchases(r){let e=p();try{return L(r.rail==="apple"?{rail:"apple",signedTransactionInfo:r.stableIdentifier}:{rail:r.rail,purchaseToken:r.stableIdentifier})!==r.derivedKey?k("idempotency-key-deterministic","derived key drifted from canonical algorithm",p()-e):E("idempotency-key-deterministic",`${r.rail} \u2192 ${r.derivedKey}`,p()-e)}catch(t){return k("idempotency-key-deterministic",`hot-path derivation threw: ${t.message?.slice(0,80)??"unknown error"}`,p()-e)}}}},ur={contractId:"error-envelope-shape",bootTest(){let r=p(),e={error:{type:"invalid_request_error",code:"missing_customer",message:"Customer identifier is required.",request_id:"req_test1234"}},t=new Set(["authentication_error","permission_error","invalid_request_error","rate_limit_error","internal_error"]),s=e.error,n=["type","code","message","request_id"].filter(i=>!(i in s)||typeof s[i]!="string");return n.length>0?k("error-envelope-shape",`envelope missing required fields: ${n.join(", ")}`,p()-r):t.has(s.type)?E("error-envelope-shape","{ type, code, message, request_id } parsed and type \u2208 ApiErrorType",p()-r):k("error-envelope-shape",`error.type "${s.type}" not in canonical ApiErrorType set`,p()-r)},hooks:{onErrorParse(r){let e=p();return new Set(["authentication_error","permission_error","invalid_request_error","rate_limit_error","internal_error"]).has(r.errorType)?!r.errorCode||r.errorCode.length===0?k("error-envelope-shape","wire error.code was empty",p()-e):E("error-envelope-shape",`${r.errorType}/${r.errorCode} on ${r.httpStatus}${r.requestId?` (${r.requestId.slice(0,12)}\u2026)`:""}`,p()-e):k("error-envelope-shape",`wire error.type "${r.errorType}" outside canonical ApiErrorType`,p()-e)}}},pr={contractId:"flush-interval-parity",bootTest(){let r=p();return 2e3!==2e3?k("flush-interval-parity","canonical default drifted from 2000ms",p()-r):E("flush-interval-parity","eventFlushIntervalMs default = 2000ms (Web/Node/RN/Swift/Android parity)",p()-r)}};function Ge(r){return{contractId:"flush-interval-parity",bootTest(){let e=p(),t=2e3;return r<100||r>6e4?k("flush-interval-parity",`configured eventFlushIntervalMs=${r} outside reasonable bounds [100, 60000]`,p()-e):r!==t?E("flush-interval-parity",`eventFlushIntervalMs = ${r}ms (override; canonical default is 2000ms)`,p()-e):E("flush-interval-parity","eventFlushIntervalMs = 2000ms (canonical default)",p()-e)}}}var fr={contractId:"super-property-merge-precedence",bootTest(){let r=p(),n={...{plan:"device_plan",os:"macos"},...{plan:"super_plan",appVersion:"1.0.0"},...{plan:"caller_plan",eventSpecific:!0}};return n.plan!=="caller_plan"?k("super-property-merge-precedence",`merged.plan = "${n.plan}" (expected "caller_plan"; caller must override super and device)`,p()-r):n.appVersion!=="1.0.0"?k("super-property-merge-precedence","super-property appVersion was clobbered by device or caller",p()-r):n.os!=="macos"?k("super-property-merge-precedence","device property os was dropped from merged result",p()-r):E("super-property-merge-precedence","caller > super > device verified (synthetic merge)",p()-r)},hooks:{onTrack(r){let e=p();for(let[t,s]of Object.entries(r.callerProperties))if(r.mergedProperties[t]!==s)return k("super-property-merge-precedence",`caller key "${t}" did not win in merged output`,p()-e);for(let[t,s]of Object.entries(r.superProperties))if(!(t in r.callerProperties)&&r.mergedProperties[t]!==s)return k("super-property-merge-precedence",`super key "${t}" did not win over device in merged output`,p()-e);return E("super-property-merge-precedence",`caller(${Object.keys(r.callerProperties).length}) > super(${Object.keys(r.superProperties).length}) > device verified`,p()-e)}}},xe=["contract_id","sdk_version","sdk_platform","failure_reason","run_context","run_id"],je=["test_file","test_name","device_class","verification_phase"],We=["anonymousId","developerUserId","crossdeckCustomerId","email","userId","ip","ipAddress","userAgent","stack","stackTrace","url","referrer","deviceId"],hr={contractId:"contract-failed-payload-schema-lock",bootTest(){let r=p(),t=Object.keys({contract_id:"synthetic",sdk_version:T,sdk_platform:"web",failure_reason:"synthetic",run_context:"customer-app",run_id:"synthetic-run-id",verification_phase:"boot"}),s=new Set([...xe,...je]),n=new Set(We);for(let i of xe)if(!t.includes(i))return k("contract-failed-payload-schema-lock",`missing required field: ${i}`,p()-r);for(let i of t)if(n.has(i))return k("contract-failed-payload-schema-lock",`forbidden field on wire: ${i}`,p()-r);for(let i of t)if(!s.has(i))return k("contract-failed-payload-schema-lock",`unrecognised field on wire: ${i} (not in required \u222A optional)`,p()-r);return E("contract-failed-payload-schema-lock",`${t.length} fields \u2286 required(${xe.length}) \u222A optional(${je.length}); ${We.length} forbidden absent`,p()-r)}},He=Object.freeze(["missing_api_key","invalid_api_key","key_revoked","identity_token_invalid","origin_not_allowed","bundle_id_not_allowed","package_name_not_allowed","env_mismatch","idempotency_key_in_use","rate_limited","internal_error","google_not_supported","stripe_not_supported","missing_required_param","invalid_param_value"]),mr={contractId:"sdk-error-codes-catalogue",bootTest(){let r=p();try{let e=[];for(let t of He){let s=pe(t);(!s||!s.description||s.description.trim().length===0||!s.resolution||s.resolution.trim().length===0)&&e.push(t)}return e.length>0?k("sdk-error-codes-catalogue",`catalogue missing description+resolution for backend code(s): ${e.join(", ")}`,p()-r):E("sdk-error-codes-catalogue",`all ${He.length} backend wire codes carry description + resolution`,p()-r)}catch(e){return k("sdk-error-codes-catalogue",`boot test threw: ${e.message?.slice(0,80)??"unknown error"}`,p()-r)}}},Je=Object.freeze([dr,lr,ur,pr,fr,hr,mr]);async function Ce(r,e,t){if(t.disableContractAssertions)return{passed:0,failed:0,totalMs:0};let s=p(),n=0,i=0;if(t.logVerifierResults){let o=r.filter(l=>l.bootTest).length,a=r.filter(l=>l.hooks).length,d=r.map(l=>l.contractId).join(", ");t.console.info(`[crossdeck] Contract self-verification \u2014 ${r.length} verifiers (${o} boot-tests, ${a} hot-path hooks): ${d}`)}for(let o of r){if(!o.bootTest)continue;let a;try{a=await o.bootTest()}catch(d){a=k(o.contractId,`bootTest threw: ${d.message?.slice(0,80)??"unknown"}`,0)}e.report(a,"boot"),a.ok?n+=1:i+=1}let c=p()-s;if(t.logVerifierResults){let o=i===0?"passed":"complete";t.console.info(`[crossdeck] Self-verification ${o} \u2014 ${n} passed, ${i} failed (${c}ms)`)}return{passed:n,failed:i,totalMs:c}}function Xe(r,e,t,s){if(!t.disableContractAssertions)for(let n of r){let i=n.hooks?.onIdentify;if(!i)continue;let c;try{c=i(s)}catch(o){c=k(n.contractId,`hook threw: ${o.message?.slice(0,80)??"unknown"}`,0)}e.report(c,"hot_path","identify")}}function Qe(r,e,t,s){if(!t.disableContractAssertions)for(let n of r){let i=n.hooks?.onTrack;if(!i)continue;let c;try{c=i(s)}catch(o){c=k(n.contractId,`hook threw: ${o.message?.slice(0,80)??"unknown"}`,0)}e.report(c,"hot_path","track")}}function Ye(r,e,t,s){if(!t.disableContractAssertions)for(let n of r){let i=n.hooks?.onSyncPurchases;if(!i)continue;let c;try{c=i(s)}catch(o){c=k(n.contractId,`hook threw: ${o.message?.slice(0,80)??"unknown"}`,0)}e.report(c,"hot_path","syncPurchases")}}function Ze(r,e,t,s){if(!t.disableContractAssertions)for(let n of r){let i=n.hooks?.onErrorParse;if(!i)continue;let c;try{c=i(s)}catch(o){c=k(n.contractId,`hook threw: ${o.message?.slice(0,80)??"unknown"}`,0)}e.report(c,"hot_path","errorParse")}}function et(){try{if(typeof process<"u"&&process.env){let e=process.env.NODE_ENV;if(typeof e=="string")return e!=="production"}}catch{}let r=globalThis.__DEV__;return typeof r=="boolean"?r:!1}function E(r,e,t){return{ok:!0,contractId:r,evidence:e,durationMs:t}}function k(r,e,t){return{ok:!1,contractId:r,failureReason:e,durationMs:t}}function p(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function gr(r,e){return r.length>e?r.slice(0,e-1)+"\u2026":r}function H(r){let e=r.startsWith("_")?r.slice(1):r;return e.length<=12?e:`${e.slice(0,4)}\u2026${e.slice(-4)}`}function yr(r){let e=new Uint8Array(Math.ceil(r/2));if(typeof globalThis<"u"&&globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else for(let s=0;s<e.length;s+=1)e[s]=Math.floor(Math.random()*256);let t="";for(let s=0;s<e.length;s+=1)t+=e[s].toString(16).padStart(2,"0");return t.slice(0,r)}var fe=class{constructor(){this.map=new Map}getItem(e){return this.map.get(e)??null}setItem(e,t){this.map.set(e,t)}removeItem(e){this.map.delete(e)}keys(){return Array.from(this.map.keys())}};fe._=U;function Ie(r){if(!r||typeof r!="string")return[];let e=r.split(`
2
- `),t=[];for(let s of e){let n=s.trim();if(!n)continue;let i=br(n);i&&t.push(i)}return t}function br(r){let e=/^at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)$/.exec(r);return e?Te({function:e[1],filename:e[2],lineno:parseInt(e[3],10),colno:parseInt(e[4],10),raw:r}):(e=/^at\s+(.+?):(\d+):(\d+)$/.exec(r),e?Te({function:"?",filename:e[1],lineno:parseInt(e[2],10),colno:parseInt(e[3],10),raw:r}):(e=/^(.*?)@(.+?):(\d+):(\d+)$/.exec(r),e?Te({function:e[1]||"?",filename:e[2],lineno:parseInt(e[3],10),colno:parseInt(e[4],10),raw:r}):/^\w*Error/.test(r)||!r.includes(":")?null:{function:"?",filename:"",lineno:0,colno:0,in_app:!0,raw:r}))}function Te(r){return{function:r.function||"?",filename:r.filename,lineno:Number.isFinite(r.lineno)?r.lineno:0,colno:Number.isFinite(r.colno)?r.colno:0,in_app:kr(r.filename),raw:r.raw}}function kr(r){return r?!(/^(?:chrome|moz|safari|webkit)-extension:\/\//.test(r)||/\bcdn\.jsdelivr\.net\b/.test(r)||/\bunpkg\.com\b/.test(r)||/\bgoogletagmanager\.com\b/.test(r)||/\bgoogle-analytics\.com\b/.test(r)||/\b@cross-deck\/web\b/.test(r)||/\/crossdeck\.umd\.min\.js$/.test(r)):!0}function M(r,e,t){let s=e.filter(i=>i.in_app).slice(0,3),n=[(r||"").slice(0,200),...s.map(i=>`${i.function}@${i.filename}:${i.lineno}`)];if(s.length===0&&t){let i=[t.errorType??"",t.filename??"",t.lineno??"",t.colno??""].join(":");i!==":::"&&n.push(i)}return vr(n.join("|"))}function vr(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)|0;return(e>>>0).toString(16).padStart(8,"0")}var tt={enabled:!0,onError:!0,onUnhandledRejection:!0,wrapFetch:!0,wrapXhr:!0,captureConsole:!1,ignoreErrors:["ResizeObserver loop limit exceeded","ResizeObserver loop completed with undelivered notifications","Non-Error promise rejection captured"],allowUrls:[],denyUrls:[/^chrome-extension:\/\//,/^moz-extension:\/\//,/^safari-extension:\/\//,/^webkit-extension:\/\//,/^safari-web-extension:\/\//],sampleRate:1,maxPerFingerprintPerMinute:5,maxPerSession:100},he=class{constructor(e){this.opts=e;this.installed=!1;this.cleanups=[];this._reporting=!1;this.sessionCount=0;this.fingerprintWindow=new Map}install(){if(this.installed||!this.opts.config.enabled||typeof globalThis>"u"||!("window"in globalThis))return;let e=globalThis.window;this.opts.config.onError&&this.installOnErrorListener(e),this.opts.config.onUnhandledRejection&&this.installRejectionListener(e),this.opts.config.wrapFetch&&this.installFetchWrap(e),this.opts.config.wrapXhr&&this.installXhrWrap(e),this.opts.config.captureConsole&&this.installConsoleWrap(),this.installed=!0}uninstall(){for(let e of this.cleanups.splice(0))try{e()}catch{}this.installed=!1}captureError(e,t){if(this.opts.isConsented())try{let s=this.buildFromUnknown(e,"error.handled",t?.level??"error");t?.context&&(s.context={...s.context,...t.context}),t?.tags&&(s.tags={...s.tags,...t.tags}),this.maybeReport(s)}catch{}}captureMessage(e,t="info"){if(this.opts.isConsented())try{let s={timestamp:Date.now(),kind:"error.message",level:t,message:e,errorType:null,frames:[],rawStack:null,filename:null,lineno:null,colno:null,fingerprint:M(e,[]),breadcrumbs:this.opts.breadcrumbs.snapshot(),context:this.opts.getContext(),tags:this.opts.getTags()};this.maybeReport(s)}catch{}}installOnErrorListener(e){let t=s=>{if(!this._reporting&&this.opts.isConsented())try{this._reporting=!0;let n=this.buildFromErrorEvent(s);this.maybeReport(n)}catch{}finally{this._reporting=!1}};e.addEventListener("error",t,!0),this.cleanups.push(()=>e.removeEventListener("error",t,!0))}installRejectionListener(e){let t=s=>{if(!this._reporting&&this.opts.isConsented())try{this._reporting=!0;let n=this.buildFromUnknown(s.reason,"error.unhandledrejection","error");this.maybeReport(n)}catch{}finally{this._reporting=!1}};e.addEventListener("unhandledrejection",t),this.cleanups.push(()=>e.removeEventListener("unhandledrejection",t))}installFetchWrap(e){let t=e.fetch?.bind(e);if(!t)return;let s=async(...n)=>{let i=n[0],c=n[1]??{},o=typeof i=="string"?i:i?.url??"",a=(c.method||"GET").toUpperCase(),d=Date.now();Ae(o,this.opts.selfHostname)||this.opts.breadcrumbs.add({timestamp:d,category:"http",message:`${a} ${o}`,data:{url:o,method:a}});try{let l=await t(...n);return l.status>=500&&this.opts.isConsented()&&(Ae(o,this.opts.selfHostname)||this.captureHttp({url:o,method:a,status:l.status,statusText:l.statusText})),l}catch(l){throw this.opts.isConsented()&&!o.includes("api.cross-deck.com")&&this.captureHttp({url:o,method:a,status:0,statusText:l instanceof Error?l.message:"network error"}),l}};e.fetch=s,this.cleanups.push(()=>{e.fetch===s&&(e.fetch=t)})}installXhrWrap(e){let s=e.XMLHttpRequest?.prototype;if(!s)return;let n=s.open,i=s.send,c=this;s.open=function(o,a,...d){return this._cdMethod=o,this._cdUrl=a,n.apply(this,[o,a,...d])},s.send=function(o){let a=this,d=()=>{try{if(a.status>=500&&c.opts.isConsented()){let l=a._cdUrl??"";Ae(l,c.opts.selfHostname)||c.captureHttp({url:l,method:(a._cdMethod??"GET").toUpperCase(),status:a.status,statusText:a.statusText})}}catch{}};return a.addEventListener("loadend",d),i.apply(this,[o??null])},this.cleanups.push(()=>{s.open=n,s.send=i})}installConsoleWrap(){let e=globalThis.console;if(!e)return;let t=e.error.bind(e);e.error=(...s)=>{try{this.opts.isConsented()&&this.captureMessage(s.map(n=>_r(n)).join(" "),"error")}catch{}return t(...s)},this.cleanups.push(()=>{e.error=t})}buildFromErrorEvent(e){let t=e.error,s=e.filename||null,n=typeof e.lineno=="number"&&e.lineno>0?e.lineno:null,i=typeof e.colno=="number"&&e.colno>0?e.colno:null;if(t==null&&!s&&n==null&&(e.message==="Script error."||e.message==="Script error"||!e.message)){let m="Cross-origin script error (browser hid details \u2014 script needs crossorigin attribute + CORS headers)";return{timestamp:Date.now(),kind:"error.unhandled",level:"error",message:m,errorType:"ScriptError",frames:[],rawStack:null,filename:null,lineno:null,colno:null,fingerprint:M(m,[]),breadcrumbs:this.opts.breadcrumbs.snapshot(),context:this.opts.getContext(),tags:{...this.opts.getTags(),cross_origin:"true"}}}let o=Pe(t),a=(o.message||e.message||"Unknown error").slice(0,1024),d=t instanceof Error?t.stack??null:null,l=Ie(d),u=o.errorType??null,f=o.extras?{...this.opts.getContext(),__error_extras:o.extras}:this.opts.getContext();return{timestamp:Date.now(),kind:"error.unhandled",level:"error",message:a,errorType:u,frames:l,rawStack:d,filename:s,lineno:n,colno:i,fingerprint:M(a,l,{filename:s,lineno:n,colno:i,errorType:u}),breadcrumbs:this.opts.breadcrumbs.snapshot(),context:f,tags:this.opts.getTags()}}buildFromUnknown(e,t,s){let n=Pe(e),i=(n.message||"Unknown error").slice(0,1024),c=e instanceof Error?e.stack??null:null,o=Ie(c),a=n.errorType??null,d=n.extras?{...this.opts.getContext(),__error_extras:n.extras}:this.opts.getContext();return{timestamp:Date.now(),kind:t,level:s,message:i,errorType:a,frames:o,rawStack:c,filename:null,lineno:null,colno:null,fingerprint:M(i,o,{errorType:a}),breadcrumbs:this.opts.breadcrumbs.snapshot(),context:d,tags:this.opts.getTags()}}captureHttp(e){try{let t=`HTTP ${e.status} ${e.method} ${e.url}`,s={timestamp:Date.now(),kind:"error.http",level:"error",message:t,errorType:"HTTPError",frames:[],rawStack:null,filename:e.url,lineno:null,colno:null,fingerprint:M(`HTTP ${e.status} ${e.method}`,[],{filename:e.url,errorType:"HTTPError"}),breadcrumbs:this.opts.breadcrumbs.snapshot(),context:this.opts.getContext(),tags:this.opts.getTags(),http:e};this.maybeReport(s)}catch{}}maybeReport(e){if(this.sessionCount>=this.opts.config.maxPerSession||this.shouldIgnore(e)||!this.passesUrlGate(e)||!this.passesSample(e)||!this.passesRateLimit(e))return;let t=e,s=this.opts.beforeSend?.();if(s){try{t=s(e)}catch{t=e}if(!t)return}this.sessionCount+=1;try{this.opts.report(t)}catch{}}shouldIgnore(e){for(let t of this.opts.config.ignoreErrors)if(typeof t=="string"&&e.message.includes(t)||t instanceof RegExp&&t.test(e.message))return!0;return!1}passesUrlGate(e){let s=(e.frames.find(n=>n.filename)??null)?.filename??e.filename??"";if(!s)return!0;for(let n of this.opts.config.denyUrls)if(typeof n=="string"&&s.includes(n)||n instanceof RegExp&&n.test(s))return!1;if(this.opts.config.allowUrls.length>0){for(let n of this.opts.config.allowUrls)if(typeof n=="string"&&s.includes(n)||n instanceof RegExp&&n.test(s))return!0;return!1}return!0}passesSample(e){return this.opts.config.sampleRate>=1?!0:this.opts.config.sampleRate<=0?!1:parseInt(e.fingerprint.slice(0,2),16)/255<this.opts.config.sampleRate}passesRateLimit(e){let s=Date.now(),n=this.opts.config.maxPerFingerprintPerMinute,c=(this.fingerprintWindow.get(e.fingerprint)??[]).filter(o=>s-o<6e4);return c.length>=n?(this.fingerprintWindow.set(e.fingerprint,c),!1):(c.push(s),this.fingerprintWindow.set(e.fingerprint,c),!0)}};function Pe(r){if(r===null)return{message:"(thrown: null)",errorType:null,extras:null};if(r===void 0)return{message:"(thrown: undefined)",errorType:null,extras:null};if(typeof r=="string")return{message:r,errorType:null,extras:null};if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return{message:String(r),errorType:typeof r,extras:null};if(typeof r=="symbol")return{message:r.toString(),errorType:"symbol",extras:null};if(typeof r=="function")return{message:`(thrown function: ${r.name||"anonymous"})`,errorType:"function",extras:null};if(r instanceof Error){let e=r.name||r.constructor?.name||"Error",t=typeof r.message=="string"&&r.message.length>0?r.message:$(r)||e,s={},n=wr(r);n.length>0&&(s.cause=n);for(let i of["code","status","statusCode","errno","response","data","detail","details"]){let c=r[i];c!==void 0&&typeof c!="function"&&(s[i]=Re(c))}for(let i of Object.keys(r)){if(i==="message"||i==="stack"||i==="name"||i==="cause"||i in s)continue;let c=r[i];typeof c!="function"&&(s[i]=Re(c))}return{message:t,errorType:e,extras:Object.keys(s).length>0?s:null}}if(typeof Response<"u"&&r instanceof Response)return{message:`HTTP ${r.status} ${r.statusText||""}${r.url?` ${r.url}`:""}`.trim(),errorType:"Response",extras:{status:r.status,statusText:r.statusText,url:r.url,type:r.type}};if(typeof r=="object"){let e=r,t=e.constructor&&typeof e.constructor=="function"&&e.constructor.name||null,s=typeof e.message=="string"&&e.message?e.message:null,n=typeof e.name=="string"&&e.name?e.name:null,i=null;try{let u=JSON.stringify(e);i=u==="{}"?null:u}catch{i=null}let c=$(e),o=s??i??(c&&c!=="[object Object]"?c:null)??(t?`(thrown ${t} with no message)`:"(thrown object with no message)"),a=n??t??null,d={},l=0;for(let u of Object.keys(e)){if(l>=20)break;if(u==="message"||u==="name")continue;let f=e[u];typeof f!="function"&&(d[u]=Re(f),l++)}return{message:o,errorType:a,extras:Object.keys(d).length>0?d:null}}return{message:$(r)||"(unstringifiable thrown value)",errorType:null,extras:null}}function wr(r){let e=[],t=r.cause,s=0;for(;t!=null&&s<5;)t instanceof Error?(e.push({name:t.name||"Error",message:t.message||""}),t=t.cause):(e.push({name:"non-Error",message:$(t)}),t=null),s++;return e}function $(r){try{let e=Object.prototype.toString.call(r);if(e!=="[object Object]")return e;let t=r?.toString;if(typeof t=="function"&&t!==Object.prototype.toString){let s=t.call(r);if(typeof s=="string")return s}return e}catch{return"(throwing toString)"}}function Re(r){if(r==null)return r;let e=typeof r;if(e==="string"||e==="number"||e==="boolean")return r;if(e==="bigint")return String(r);try{let t=JSON.stringify(r);return t===void 0?$(r):JSON.parse(t)}catch{return $(r)}}function _r(r){return Pe(r).message}function rt(r){if(!r||typeof r!="string")return null;try{return new URL(r).hostname.toLowerCase()}catch{return null}}function Ae(r,e){if(!e||!r)return!1;try{return new URL(r).hostname.toLowerCase()===e}catch{return!1}}var G=class{constructor(){this.state=null;this.verifiers=null;this.verifierReporter=null;this.verifierCtx=null}init(e){if(this.state){try{this.state.uninstallUnloadFlush?.()}catch{}try{this.state.autoTracker?.uninstall()}catch{}try{this.state.webVitals?.uninstall()}catch{}try{this.state.errors?.uninstall()}catch{}try{this.state.events.flush({keepalive:!0})}catch{}}if(!e.publicKey||!e.publicKey.startsWith("cd_pub_"))throw new _({type:"configuration_error",code:"invalid_public_key",message:"Crossdeck.init requires a publishable key starting with cd_pub_."});if(!e.appId)throw new _({type:"configuration_error",code:"missing_app_id",message:"Crossdeck.init requires an appId. Find yours in the Crossdeck dashboard."});if(e.environment!=="production"&&e.environment!=="sandbox")throw new _({type:"configuration_error",code:"invalid_environment",message:'Crossdeck.init requires environment: "production" | "sandbox".'});let t=Sr(e.publicKey);if(t&&t!==e.environment)throw new _({type:"configuration_error",code:"environment_mismatch",message:`Crossdeck.init: environment "${e.environment}" disagrees with key prefix (${t}). Reconcile the publishable key with the environment declaration.`});let s=Er(),n=e.storage??Ve(),i=e.persistIdentity??!0,c=xr(e.autoTrack),o={appId:e.appId,publicKey:e.publicKey,environment:e.environment,baseUrl:e.baseUrl??Q,persistIdentity:i,storagePrefix:e.storagePrefix??"crossdeck:",autoHeartbeat:e.autoHeartbeat??!0,eventFlushBatchSize:e.eventFlushBatchSize??20,eventFlushIntervalMs:e.eventFlushIntervalMs??2e3,sdkVersion:e.sdkVersion??T,autoTrack:c,appVersion:e.appVersion??null},a=new ie;a.enabled=e.debug===!0;let d=new X({publicKey:o.publicKey,baseUrl:o.baseUrl,sdkVersion:o.sdkVersion,localDevMode:s,onErrorParsed:h=>{this.verifiers&&this.verifierReporter&&this.verifierCtx&&Ze(this.verifiers,this.verifierReporter,this.verifierCtx,{errorType:h.type,errorCode:h.code,requestId:h.requestId??null,httpStatus:typeof h.status=="number"?h.status:0})}});s&&console.log("[crossdeck] Localhost detected \u2014 running in dev mode (no network calls). Set publicKey: 'cd_pub_test_\u2026' and deploy to a real domain to test against the Crossdeck Sandbox.");let l=i?n:new V,f=i&&!e.storage&&typeof globalThis.document<"u"?new se:void 0,m=new Y(l,o.storagePrefix,f),g=new R(l,o.storagePrefix+"entitlements"),y=i?new re({storage:l,prefix:o.storagePrefix}):null;y&&a.emit("sdk.queue_restored","Restored persisted event queue from a prior session.");let b=new te({http:d,batchSize:o.eventFlushBatchSize,intervalMs:o.eventFlushIntervalMs,envelope:()=>({appId:o.appId,environment:o.environment,sdk:{name:I,version:o.sdkVersion}}),persistentStore:y??void 0,onFirstFlushSuccess:()=>{a.emit("sdk.first_event_sent","First telemetry event received. View it in Live Events.",{appId:o.appId,environment:o.environment})},onRetryScheduled:h=>{a.emit("sdk.flush_retry_scheduled",`Event flush failed (${h.lastError}). Retrying in ${h.delayMs}ms (attempt ${h.consecutiveFailures}).`,{...h})},onPermanentFailure:h=>{let w=`[crossdeck] Event batch DROPPED (status ${h.status}): ${h.lastError}. ${h.droppedCount} event(s) lost \u2014 check your publishable key + app config.`;console.error(w),a.emit("sdk.flush_permanent_failure",w,{...h})}}),v=c.deviceInfo?Oe({appVersion:o.appVersion??void 0}):o.appVersion?{appVersion:o.appVersion}:{},x=new ae(i?l:new V,o.storagePrefix),A=new de({respectDnt:e.respectDnt===!0});A.isDntDenied&&a.emit("sdk.consent_dnt_applied","Do Not Track detected \u2014 all tracking dimensions denied at init.");let P=new le(50);if(this.state={http:d,identity:m,entitlements:g,events:b,autoTracker:null,webVitals:null,errors:null,breadcrumbs:P,errorContext:{},errorTags:{},errorBeforeSend:null,superProps:x,consent:A,scrubPii:e.scrubPii!==!1,deviceInfo:v,options:o,debug:a,developerUserId:null,uninstallUnloadFlush:null,lastServerTime:null,lastClientTime:null},a.emit("sdk.configured",`Crossdeck connected to ${o.appId} in ${o.environment} mode.`,{appId:o.appId,environment:o.environment,sdkVersion:o.sdkVersion}),c.sessions||c.pageViews){let h=new j(c,(w,S)=>this.track(w,S),{storage:l,storageKey:o.storagePrefix+"session"});this.state.autoTracker=h,h.install()}if(c.webVitals){let h=new ce({enabled:!0},(w,S)=>this.track(w,S));this.state.webVitals=h,h.install()}if(c.errors){let h=new he({config:{...tt,enabled:!0},breadcrumbs:P,report:w=>this.reportError(w),getContext:()=>({...this.state.errorContext}),getTags:()=>({...this.state.errorTags}),beforeSend:()=>this.state.errorBeforeSend,isConsented:()=>this.state.consent.errors,selfHostname:rt(o.baseUrl)});this.state.errors=h,h.install()}if(this.state.uninstallUnloadFlush=Cr(()=>{this.flush({keepalive:!0}).catch(()=>{})}),o.autoHeartbeat&&!s&&this.heartbeat().catch(()=>{}),e.disableContractAssertions!==!0){let h=et();this.verifierCtx=ze({logVerifierResults:e.logVerifierResults??h,disableContractAssertions:!1,runContext:typeof process<"u"&&process.env&&process.env.CI?"ci":"customer-app"}),this.verifierReporter=new z(this.verifierCtx);let w=Ge(o.eventFlushIntervalMs);this.verifiers=Object.freeze([...Je,w]),s?(e.verifyContractsAtBoot??h)&&this.verifierReporter&&Ce(this.verifiers,this.verifierReporter,this.verifierCtx).catch(()=>{}):this.bootstrapVerifierLayerRemote(e,h).catch(()=>{})}}async bootstrapVerifierLayerRemote(e,t){if(!this.state||!this.verifiers||!this.verifierCtx)return;let s={logVerifierResults:null,verifyContractsAtBoot:null};try{let c=await this.state.http.request("GET","/config");if(c&&c.verifierConfig){let o=c.verifierConfig;s={logVerifierResults:typeof o.logVerifierResults=="boolean"?o.logVerifierResults:null,verifyContractsAtBoot:typeof o.verifyContractsAtBoot=="boolean"?o.verifyContractsAtBoot:null}}}catch{}let n=e.logVerifierResults??s.logVerifierResults??t,i=e.verifyContractsAtBoot??s.verifyContractsAtBoot??t;n!==this.verifierCtx.logVerifierResults&&(this.verifierCtx={...this.verifierCtx,logVerifierResults:n},this.verifierReporter=new z(this.verifierCtx)),i&&this.verifierReporter&&await Ce(this.verifiers,this.verifierReporter,this.verifierCtx)}start(e){typeof console<"u"&&console.warn("[crossdeck] Crossdeck.start() is deprecated \u2014 use Crossdeck.init() instead. The signature is the same."),this.init(e)}async identify(e,t){let s=this.requireStarted();if(!e)throw new _({type:"invalid_request_error",code:"missing_user_id",message:"identify(userId) requires a non-empty userId."});if(!s.consent.analytics)return s.debug.emit("sdk.consent_denied","identify() skipped \u2014 consent denied for analytics."),{object:"alias_result",crossdeckCustomerId:s.identity.crossdeckCustomerId??"",linked:[],mergePending:!1,env:s.options.environment};let n=t?.traits!==void 0?W(t.traits):null,i=n&&Object.keys(n.properties).length>0?n.properties:void 0;if(s.debug.enabled&&n&&n.warnings.length>0)for(let d of n.warnings)s.debug.emit("sdk.property_coerced",`identify() traits key ${JSON.stringify(d.key)} was ${d.kind.replace(/_/g," ")} during validation.`,{key:d.key,kind:d.kind});let c={userId:e,anonymousId:s.identity.anonymousId};t?.email&&(c.email=t.email),i&&(c.traits=i);let o=s.developerUserId;s.entitlements.setUserKey(e),this.verifiers&&this.verifierReporter&&this.verifierCtx&&Xe(this.verifiers,this.verifierReporter,this.verifierCtx,{priorUserId:o,nextUserId:e,cache:s.entitlements});let a=await s.http.request("POST","/identity/alias",{body:c});return s.identity.setCrossdeckCustomerId(a.crossdeckCustomerId),s.developerUserId=e,a}register(e){let t=this.requireStarted(),s=W(e);return t.superProps.register(s.properties)}unregister(e){this.requireStarted().superProps.unregister(e)}getSuperProperties(){return this.state?this.state.superProps.getSuperProperties():{}}group(e,t,s){let n=this.requireStarted();if(!e)throw new _({type:"invalid_request_error",code:"missing_group_type",message:"group(type, id) requires a non-empty type."});let i=s?W(s).properties:void 0;n.superProps.setGroup(e,t,i)}getGroups(){return this.state?this.state.superProps.getGroups():{}}consent(e){let t=this.requireStarted(),s=t.consent.set(e);return t.debug.emit("sdk.consent_changed","Consent state updated.",{...s}),s}consentStatus(){return this.state?this.state.consent.get():{analytics:!0,marketing:!0,errors:!0}}captureError(e,t){this.state?.errors&&this.state.errors.captureError(e,t)}captureMessage(e,t="info"){this.state?.errors&&this.state.errors.captureMessage(e,t)}setTag(e,t){this.state&&(this.state.errorTags[e]=t)}setTags(e){this.state&&Object.assign(this.state.errorTags,e)}setContext(e,t){this.state&&(this.state.errorContext[e]=t)}addBreadcrumb(e){this.state&&this.state.breadcrumbs.add(e)}setErrorBeforeSend(e){this.state&&(this.state.errorBeforeSend=e)}reportError(e){let t={fingerprint:e.fingerprint,level:e.level,errorType:e.errorType,message:e.message,stack:e.rawStack??void 0,frames:e.frames,filename:e.filename??void 0,lineno:e.lineno??void 0,colno:e.colno??void 0,tags:e.tags,context:e.context,breadcrumbs:e.breadcrumbs,http:e.http};for(let s of Object.keys(t))t[s]===void 0&&delete t[s];this.track(e.kind,t)}async forget(){let e=this.requireStarted(),t=this.identityQueryParams();try{await e.http.request("POST","/identity/forget",{body:{...t}})}catch(s){e.debug.emit("sdk.consent_denied",`forget() server call failed (${s instanceof Error?s.message:String(s)}). Local state wiped anyway.`)}this.reset()}async getEntitlements(){let e=this.requireStarted(),t=this.identityQueryParams(),s;try{s=await e.http.request("GET","/entitlements",{query:t})}catch(n){throw e.entitlements.markRefreshFailed(),n}return s.crossdeckCustomerId&&e.identity.setCrossdeckCustomerId(s.crossdeckCustomerId),e.entitlements.setFromList(s.data),s.data}isEntitled(e){return this.requireStarted().entitlements.isEntitled(e)}listEntitlements(){return this.requireStarted().entitlements.list()}onEntitlementsChange(e){return this.requireStarted().entitlements.subscribe(e)}reportContractFailure(e){let t={contract_id:e.contractId,sdk_version:T,sdk_platform:"web",failure_reason:e.failureReason,run_context:e.runContext,run_id:e.runId};e.testRef&&(t.test_file=e.testRef.file,t.test_name=e.testRef.name),e.deviceClass&&(t.device_class=e.deviceClass),ue(t)}track(e,t){let s=this.requireStarted();if(!e)throw new _({type:"invalid_request_error",code:"missing_event_name",message:"track(name) requires a non-empty name."});let n=e.startsWith("error."),i=e.startsWith("webvitals.");if(!(n||i?s.consent.errors:s.consent.analytics)){s.debug.enabled&&s.debug.emit("sdk.consent_denied",`Dropped event "${e}" \u2014 consent denied for ${i?"errors":"analytics"}.`);return}if(s.debug.enabled&&t){let b=Ue(t);b.length>0&&s.debug.emit("sdk.sensitive_property_warning",`Event "${e}" has potentially sensitive property names: ${b.join(", ")}. Crossdeck is privacy-first \u2014 avoid sending PII unless intentional.`,{eventName:e,flagged:b})}s.debug.enabled&&!s.developerUserId&&!s.identity.crossdeckCustomerId&&s.debug.emit("sdk.no_identity","Using anonymous user until identify(userId) is called.");let o=W(t);if(s.debug.enabled&&o.warnings.length>0)for(let b of o.warnings)s.debug.emit("sdk.property_coerced",`Event "${e}" property ${JSON.stringify(b.key)} was ${b.kind.replace(/_/g," ")} during validation.`,{eventName:e,key:b.key,kind:b.kind});s.autoTracker?.markActivity();let a={...s.deviceInfo},d=s.autoTracker?.currentSessionId;d&&(a.sessionId=d);let l=s.autoTracker?.currentPageviewId;l&&(a.pageviewId=l);let u=s.autoTracker?.currentAcquisition;u&&(u.utm_source&&(a.utm_source=u.utm_source),u.utm_medium&&(a.utm_medium=u.utm_medium),u.utm_campaign&&(a.utm_campaign=u.utm_campaign),u.utm_content&&(a.utm_content=u.utm_content),u.utm_term&&(a.utm_term=u.utm_term),u.referrer&&s.consent.marketing&&(a.referrer=u.referrer),s.consent.marketing&&(u.gclid&&(a.gclid=u.gclid),u.fbclid&&(a.fbclid=u.fbclid),u.msclkid&&(a.msclkid=u.msclkid),u.ttclid&&(a.ttclid=u.ttclid),u.li_fat_id&&(a.li_fat_id=u.li_fat_id),u.twclid&&(a.twclid=u.twclid)));let f=s.superProps.getSuperProperties();for(let b of Object.keys(f))b in a||(a[b]=f[b]);let m=s.superProps.getGroupIds();Object.keys(m).length>0&&(a.$groups=m),Object.assign(a,o.properties);let g=s.scrubPii?_e(a):a,y={eventId:this.mintEventId(),name:e,timestamp:Date.now(),properties:g};if(Object.assign(y,this.identityHintForEvent()),s.events.enqueue(y),this.verifiers&&this.verifierReporter&&this.verifierCtx&&Qe(this.verifiers,this.verifierReporter,this.verifierCtx,{callerProperties:o.properties,superProperties:f,deviceProperties:s.deviceInfo,mergedProperties:a}),!n&&!i){let b=e.startsWith("page.")?"navigation":e.startsWith("element.")||e==="session.started"?"ui.click":"custom";s.breadcrumbs.add({timestamp:y.timestamp,category:b,message:e,data:t?{...t}:void 0})}}async flush(e={}){await this.requireStarted().events.flush(e)}async flushEvents(){return this.flush()}async syncPurchases(e){let t=this.requireStarted();if(!e.signedTransactionInfo)throw new _({type:"invalid_request_error",code:"missing_signed_transaction_info",message:"syncPurchases requires a signedTransactionInfo string from StoreKit 2."});let s=e.rail??"apple",n={...e,rail:s},i=L(n);if(this.verifiers&&this.verifierReporter&&this.verifierCtx){let o=s==="apple"?n.signedTransactionInfo??"":n.purchaseToken??"";Ye(this.verifiers,this.verifierReporter,this.verifierCtx,{rail:s,stableIdentifier:o,derivedKey:i})}let c=await t.http.request("POST","/purchases/sync",{body:n,idempotencyKey:i});t.identity.setCrossdeckCustomerId(c.crossdeckCustomerId),t.entitlements.setFromList(c.entitlements);try{let o=c.entitlements[0]?.source.productId,a=c.entitlements[0]?.source.subscriptionId,d={rail:s};o&&(d.productId=o),a&&(d.subscriptionId=a),c.idempotent_replay&&(d.idempotent_replay=!0),this.track("purchase.completed",d)}catch{}return t.debug.emit("sdk.purchase_evidence_sent","StoreKit transaction forwarded. Waiting for backend verification.",{rail:e.rail??"apple"}),c}async purchaseApple(e){return this.syncPurchases({rail:"apple",...e})}setDebugMode(e){let t=this.requireStarted();t.debug.enabled=e,e&&t.debug.emit("sdk.configured",`Debug mode enabled for ${t.options.appId} in ${t.options.environment} mode.`,{appId:t.options.appId,environment:t.options.environment})}async heartbeat(){let e=this.requireStarted(),t=await e.http.request("GET","/sdk/heartbeat");return typeof t?.serverTime=="number"&&Number.isFinite(t.serverTime)&&(e.lastServerTime=t.serverTime,e.lastClientTime=Date.now()),t}reset(){if(this.state){if(this.state.developerUserId)try{this.track("user.signed_out",{auto:!0})}catch{}if(this.state.autoTracker?.uninstall(),this.state.identity.reset(),this.state.entitlements.clearAll(),this.state.events.reset(),this.state.superProps.clear(),this.state.breadcrumbs.clear(),this.state.errorContext={},this.state.errorTags={},this.state.developerUserId=null,this.state.lastServerTime=null,this.state.lastClientTime=null,this.state.autoTracker){let e=new j(this.state.options.autoTrack,(t,s)=>this.track(t,s));this.state.autoTracker=e,e.install()}}}diagnostics(){if(!this.state)return{started:!1,anonymousId:null,crossdeckCustomerId:null,developerUserId:null,sdkVersion:null,baseUrl:null,clock:{lastServerTime:null,lastClientTime:null,skewMs:null},entitlements:{count:0,lastUpdated:0,stale:!1,listenerErrors:0},events:{buffered:0,dropped:0,inFlight:0,lastFlushAt:0,lastError:null,consecutiveFailures:0,nextRetryAt:null}};let e=this.state,t=e.lastServerTime!==null&&e.lastClientTime!==null?e.lastClientTime-e.lastServerTime:null;return{started:!0,anonymousId:e.identity.anonymousId,crossdeckCustomerId:e.identity.crossdeckCustomerId,developerUserId:e.developerUserId,sdkVersion:e.options.sdkVersion,baseUrl:e.options.baseUrl,clock:{lastServerTime:e.lastServerTime,lastClientTime:e.lastClientTime,skewMs:t},entitlements:{count:e.entitlements.list().length,lastUpdated:e.entitlements.freshness,stale:e.entitlements.isStale,listenerErrors:e.entitlements.listenerErrors},events:e.events.getStats()}}getCheckoutReference(){let e=this.requireStarted();return e.identity.crossdeckCustomerId??e.developerUserId??e.identity.anonymousId}requireStarted(){if(!this.state)throw new _({type:"configuration_error",code:"not_initialized",message:"Call Crossdeck.init({ appId, publicKey, environment }) before any other method."});return this.state}identityQueryParams(){let e=this.requireStarted();return e.identity.crossdeckCustomerId?{customerId:e.identity.crossdeckCustomerId}:e.developerUserId?{userId:e.developerUserId}:{anonymousId:e.identity.anonymousId}}identityHintForEvent(){let e=this.requireStarted(),t={anonymousId:e.identity.anonymousId};return e.developerUserId&&(t.developerUserId=e.developerUserId),e.identity.crossdeckCustomerId&&(t.crossdeckCustomerId=e.identity.crossdeckCustomerId),t}mintEventId(){return`evt_${Date.now().toString(36)}${F(8)}`}},st=new G;function Sr(r){return r.startsWith("cd_pub_test_")?"sandbox":r.startsWith("cd_pub_live_")?"production":null}function Er(){let r=globalThis.window;if(r?.__CROSSDECK_FORCE_LIVE__===!0)return!1;let e=r?.location?.hostname;return e?!!(e==="localhost"||e==="127.0.0.1"||e==="0.0.0.0"||e==="::1"||e==="[::1]"||/^\[?fe80::/i.test(e)||e.endsWith(".local")||/^10\./.test(e)||/^192\.168\./.test(e)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e)):!1}function xr(r){return r===!1?{sessions:!1,pageViews:!1,deviceInfo:!1,clicks:!1,webVitals:!1,errors:!1}:r===void 0||r===!0?{...O}:{sessions:r.sessions??O.sessions,pageViews:r.pageViews??O.pageViews,deviceInfo:r.deviceInfo??O.deviceInfo,clicks:r.clicks??O.clicks,webVitals:r.webVitals??O.webVitals,errors:r.errors??O.errors}}function Cr(r){let e=globalThis.window,t=globalThis.document;if(!e||!t)return()=>{};let s=()=>{t.visibilityState==="hidden"&&r()},n=()=>r();return t.addEventListener("visibilitychange",s),e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),()=>{t.removeEventListener("visibilitychange",s),e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}var nt="@cross-deck/web@1.6.2",it="1.6.2",N=Object.freeze([{id:"contract-failed-payload-schema-lock",pillar:"diagnostics",status:"enforced",claim:"The `crossdeck.contract_failed` event payload contains ONLY the named diagnostic fields and never any end-user personal data. The wire shape is fixed \u2014 adding a new field requires (1) a pull request that updates this contract's `allowedFields` set, (2) a Privacy Policy \xA76 amendment, and (3) the Customer Disclosure Template / SDK Data Collection Reference \xA7B updates. Per-SDK assertion tests enforce the field set on every release. The `verification_phase` field is a categorical bucket \u2014 values are restricted to `boot` (the SDK self-test ran on Crossdeck.start) or `hot_path` (a verifier observed a real customer-triggered operation). The categorical nature is what preserves the diagnostic-only-not-personal classification. This is the structural guarantee that backs the independent-controller lawful basis in the Privacy Policy: the payload remains diagnostic-only, not personal, so the legitimate-interest analysis stays valid as the SDK evolves.",appliesTo:["web","node","swift","android","react-native"],allowedFields:{required:["contract_id","sdk_version","sdk_platform","failure_reason","run_context","run_id"],optional:["test_file","test_name","device_class","verification_phase"],forbidden:["anonymousId","developerUserId","crossdeckCustomerId","email","ip","user_agent","message","stack","stack_trace","frames","exception_message","url","path","screen","title","label","text","ariaLabel","accessibilityLabel","contentDescription","session_id","sessionId"]},transport:"Telemetry is single-fire to the Crossdeck reliability endpoint only \u2014 NOT the customer's appId. The customer's track() pipeline never carries `crossdeck.*` events; the customer's dashboard never shows individual contract failures. Operational telemetry flows one-way to the Crossdeck operations team for SDK reliability purposes (legitimate interest, independent-controller flow per Privacy Policy \xA76). The reliability endpoint is hardcoded at SDK build time; the publishable key for the reliability project is embedded as a constant and rejects writes that don't match the schema.",codeRef:["sdks/web/src/crossdeck.ts","sdks/node/src/crossdeck-server.ts","sdks/swift/Sources/Crossdeck/Crossdeck.swift","sdks/swift/Sources/Crossdeck/_DiagnosticTelemetry.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/_DiagnosticTelemetry.kt","sdks/react-native/src/crossdeck.ts","backend/src/api/v1-sdk-diagnostic.ts","sdks/web/src/_diagnostic-telemetry.ts","sdks/node/src/_diagnostic-telemetry.ts","sdks/react-native/src/_diagnostic-telemetry.ts"],testRef:[{file:"sdks/web/tests/contract-failed-schema-lock.test.ts",name:"reportContractFailure payload conforms to schema-lock"},{file:"sdks/node/tests/contract-failed-schema-lock.test.ts",name:"reportContractFailure payload conforms to schema-lock"},{file:"sdks/swift/Tests/CrossdeckTests/ContractFailedSchemaLockTests.swift",name:"test_reportContractFailure_payloadFieldsAreInAllowList"},{file:"sdks/swift/Tests/CrossdeckTests/ContractFailedSchemaLockTests.swift",name:"test_reportContractFailure_doesNotEnterCustomerTrackPipeline"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ContractFailedSchemaLockTest.kt",name:"reportContractFailure payload conforms to schema-lock"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ContractFailedSchemaLockTest.kt",name:"reportContractFailure does not enter customer track pipeline"},{file:"sdks/react-native/tests/contract-failed-schema-lock.test.ts",name:"reportContractFailure payload conforms to schema-lock"},{file:"backend/tests/unit/v1-sdk-diagnostic.test.ts",name:"forbidden fields are enumerated in the schema-lock contract"},{file:"backend/tests/unit/v1-sdk-diagnostic.test.ts",name:"required fields are enumerated in the schema-lock contract"},{file:"backend/tests/unit/v1-sdk-diagnostic.test.ts",name:"regression guard: never returns a raw IP"},{file:"backend/tests/unit/v1-sdk-diagnostic.test.ts",name:"verification_phase is in the optional field set"}],registeredAt:"2026-05-27",firstRegisteredIn:"Diagnostic telemetry single-fire + schema-lock \u2014 independent-controller flow",privacyReferences:["legal/privacy/index.html#sdk-diagnostic","legal/customer-disclosure/index.html#flow-b","legal/security/index.html#diagnostic","legal/sdk-data/index.html#b-diagnostic"],bundledIn:"@cross-deck/web@1.6.2",runtimeVerified:!0},{id:"error-envelope-shape",pillar:"errors",status:"enforced",claim:"Every v1 REST endpoint returns errors in a Stripe-shape envelope: `{ error: { type, code, message, request_id } }` where `type` is one of authentication_error / permission_error / invalid_request_error / rate_limit_error / internal_error (the wire vocabulary in backend/src/api/v1-errors.ts ApiErrorType). HTTP status parity: invalid_request_error \u2192 400, authentication_error \u2192 401, permission_error \u2192 403, rate_limit_error \u2192 429, internal_error \u2192 500. SDK-side clients parse this shape via `crossdeckErrorFromResponse` (Web/Node/RN) / `crossdeckErrorFrom(response:)` (Swift) / `crossdeckErrorFromResponse` (Android) and surface the request_id verbatim so support traces are end-to-end joinable. Firebase callable endpoints (managed-keys / dashboard auth) use the Firebase HttpsError envelope instead \u2014 this contract applies to REST /v1/* only.",appliesTo:["web","node","react-native","swift","android","backend"],codeRef:["backend/src/api/v1-errors.ts","sdks/web/src/errors.ts","sdks/node/src/errors.ts","sdks/react-native/src/errors.ts","sdks/swift/Sources/Crossdeck/Errors.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Errors.kt"],testRef:[{file:"sdks/swift/Tests/CrossdeckTests/ErrorsTests.swift",name:"test_errorEnvelope_fallsBackOnGarbageBody"},{file:"sdks/swift/Tests/CrossdeckTests/ErrorsTests.swift",name:"test_errorEnvelope_reads_XRequestId_fallback"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ErrorTypeWireVocabTest.kt",name:"backend 500 response parses to INTERNAL_ERROR"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 8 (codifies existing contract)",bundledIn:"@cross-deck/web@1.6.2",runtimeVerified:!0},{id:"flush-interval-parity",pillar:"analytics",status:"enforced",claim:"Every Crossdeck SDK defaults its event-queue flush interval to 2000ms \u2014 the Stripe-adjacent industry norm. Pre-v1.4.0 the defaults disagreed (Web/Node 1500ms; RN/Swift/Android 5000ms), so cross-platform funnels saw events landing at different cadences. Per-instance override stays \u2014 call sites can still tune it freely.",appliesTo:["web","node","react-native","swift","android"],codeRef:["sdks/web/src/crossdeck.ts","sdks/node/src/crossdeck-server.ts","sdks/react-native/src/crossdeck.ts","sdks/swift/Sources/Crossdeck/EventQueue.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EventQueue.kt"],testRef:[{file:"sdks/swift/Sources/Crossdeck/EventQueue.swift",name:"flushIntervalMs: Int = 2_000"},{file:"sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EventQueue.kt",name:"flushIntervalMs: Long = 2_000L"},{file:"sdks/web/src/crossdeck.ts",name:"options.eventFlushIntervalMs ?? 2000"},{file:"sdks/node/src/crossdeck-server.ts",name:"options.eventFlushIntervalMs ?? 2000"},{file:"sdks/react-native/src/crossdeck.ts",name:"options.eventFlushIntervalMs ?? 2000"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 3.3",bundledIn:"@cross-deck/web@1.6.2",runtimeVerified:!0},{id:"idempotency-key-deterministic",pillar:"revenue",status:"enforced",claim:"syncPurchases() on every SDK derives a deterministic Idempotency-Key from the request body (UUID-shaped SHA-256 of `crossdeck:purchases/sync:<rail>:<jws|token>`). Same input -> same key. Backend short-circuits same-key-same-body retries by returning the cached response (status + body) with `idempotent_replay: true` flag in the body AND `Idempotent-Replayed: true` response header. Same-key-different-body returns 400 `idempotency_key_in_use`. 24-hour TTL matches Stripe. Cache only stores 2xx responses \u2014 4xx/5xx pass through so callers can fix bugs and retry. Helper returns nil/throws on missing identifier (no silent random fallback). Cross-SDK parity is CI-pinned: deriveForPurchase('apple', 'eyJ.jws.sig') MUST equal 'a66b1640-efaf-bb4d-1261-6650033bf111' on every SDK.",appliesTo:["web","node","react-native","swift","android","backend"],codeRef:["sdks/web/src/idempotency-key.ts","sdks/web/src/crossdeck.ts","sdks/react-native/src/idempotency-key.ts","sdks/react-native/src/crossdeck.ts","sdks/node/src/idempotency-key.ts","sdks/node/src/crossdeck-server.ts","sdks/swift/Sources/Crossdeck/IdempotencyKey.swift","sdks/swift/Sources/Crossdeck/Crossdeck.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/IdempotencyKey.kt","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt","backend/src/lib/idempotency-response-cache.ts","backend/src/api/v1-purchases.ts"],testRef:[{file:"sdks/web/tests/idempotency-key.test.ts",name:"cross-SDK oracle \u2014 apple JWS pins canonical vector"},{file:"sdks/web/tests/idempotency-key.test.ts",name:"is deterministic: same body twice -> identical key"},{file:"sdks/web/tests/idempotency-key.test.ts",name:"same identifier under different rails -> different keys"},{file:"sdks/web/tests/idempotency-key.test.ts",name:"never silently falls back to a random key on missing identifier"},{file:"sdks/react-native/tests/idempotency-key.test.ts",name:"is deterministic"},{file:"sdks/react-native/tests/idempotency-key.test.ts",name:"cross-SDK oracle \u2014 apple JWS pins canonical vector"},{file:"sdks/node/tests/idempotency-key.test.ts",name:"is deterministic"},{file:"sdks/node/tests/idempotency-key.test.ts",name:"rail namespacing prevents cross-rail collisions"},{file:"sdks/node/tests/idempotency-key.test.ts",name:"apple JWS produces the canonical pinned UUID across all 5 SDKs"},{file:"backend/tests/unit/idempotency-response-cache.test.ts",name:"is deterministic for the same input"},{file:"backend/tests/unit/idempotency-response-cache.test.ts",name:"injects idempotent_replay: true into a JSON object body"},{file:"backend/tests/unit/idempotency-response-cache.test.ts",name:"matches Stripe's 24-hour idempotency window"},{file:"sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",name:"test_crossSdkOracle_appleJWS"},{file:"sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",name:"test_railNamespacing_preventsCrossRailCollisions"},{file:"sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",name:"test_missingIdentifier_returnsNil"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",name:"cross-SDK oracle for apple JWS"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",name:"rail namespacing prevents cross-rail collisions"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",name:"missing identifier returns null - never silent random fallback"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 2.2.a + 2.2.b + 2.2.c",bundledIn:"@cross-deck/web@1.6.2",runtimeVerified:!0},{id:"init-reentry-drains-prior-queue",pillar:"lifecycle",status:"enforced",claim:"Web + RN init() re-entry drains the prior EventQueue's pending setTimeout BEFORE replacing this.state. Pre-v1.4.0 the teardown handled autoTracker/webVitals/errors/unloadFlush but NOT events, so the prior queue's timer would fire AFTER the state swap \u2014 sending old-init events against new-init http + identity references (cross-identity leak during HMR / config swap / multi-tenant SDK shells). The teardown CANNOT call persistent.clear() \u2014 the durable queue belongs to the SDK lifetime, not the init() lifetime, and a survived crash mid-flush re-hydrates on the next init.",appliesTo:["web","react-native"],codeRef:["sdks/web/src/crossdeck.ts","sdks/react-native/src/crossdeck.ts"],testRef:[{file:"sdks/web/tests/init-reentry.test.ts",name:"re-init drains the prior queue's pending timer before swapping state"},{file:"sdks/web/tests/init-reentry.test.ts",name:"re-init does NOT wipe the durable event store"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 5.5",bundledIn:"@cross-deck/web@1.6.2",runtimeVerified:!1},{id:"per-user-cache-isolation",pillar:"entitlements",status:"enforced",claim:"Every identify(userId) switches the entitlement cache to a physically separate per-user storage slot \u2014 `crossdeck:entitlements:<sha256(userId)>` \u2014 and unconditionally wipes the in-memory snapshot. A user-switch on a shared device CANNOT cross-read a prior user's cached entitlements, even if the in-memory clear is somehow skipped, because the storage keys are physically separate. reset() wipes every per-user slot via the persisted index.",appliesTo:["web","react-native","swift","android"],codeRef:["sdks/web/src/entitlement-cache.ts","sdks/web/src/hash.ts","sdks/web/src/crossdeck.ts","sdks/react-native/src/entitlement-cache.ts","sdks/react-native/src/hash.ts","sdks/react-native/src/crossdeck.ts","sdks/swift/Sources/Crossdeck/EntitlementCache.swift","sdks/swift/Sources/Crossdeck/IdempotencyKey.swift","sdks/swift/Sources/Crossdeck/Crossdeck.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EntitlementCache.kt","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/IdempotencyKey.kt","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt"],testRef:[{file:"sdks/web/tests/entitlement-cache-isolation.test.ts",name:"identify(B) makes A's entitlements unreachable from in-memory"},{file:"sdks/web/tests/entitlement-cache-isolation.test.ts",name:"clearAll() removes every per-user storage key plus the index"},{file:"sdks/web/tests/entitlement-cache-isolation.test.ts",name:"a second cache instance reading A's storage suffix CANNOT see B's data"},{file:"sdks/react-native/tests/entitlement-cache-isolation.test.ts",name:"identify(B) makes A's entitlements unreachable from in-memory"},{file:"sdks/react-native/tests/entitlement-cache-isolation.test.ts",name:"removes every per-user storage key plus the index"},{file:"sdks/swift/Tests/CrossdeckTests/EntitlementCacheIsolationTests.swift",name:"test_identifyB_makesAEntitlementsUnreachable"},{file:"sdks/swift/Tests/CrossdeckTests/EntitlementCacheIsolationTests.swift",name:"test_identifiedWritesLandUnderPerUserSha256Key"},{file:"sdks/swift/Tests/CrossdeckTests/EntitlementCacheIsolationTests.swift",name:"test_clearAll_removesEveryPerUserStorageKeyPlusIndex"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",name:"identified writes land under per-user sha256 key"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",name:"identify B makes A entitlements unreachable from in-memory"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",name:"clearAll removes every per-user storage key plus the index"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",name:"a fresh cache bound to A's key CANNOT read B's blob"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 1.3 (web/RN) + dogfood-gap fix (swift + android)",bundledIn:"@cross-deck/web@1.6.2",runtimeVerified:!0},{id:"sdk-error-codes-catalogue",pillar:"errors",status:"enforced",claim:"Web + Node SDK error-codes catalogues include EVERY backend-emitted ApiErrorCode with a description + resolution. Pre-v1.4.0 the catalogues documented codes the SDK threw ITSELF but ZERO backend codes \u2014 a developer hitting `invalid_api_key` / `origin_not_allowed` / `bundle_id_not_allowed` / `env_mismatch` / `idempotency_key_in_use` etc. got `undefined` from getErrorCode() and had to hunt for guidance. v1.4.0 backfills the catalogue from backend/src/api/v1-errors.ts so every wire code has a canonical 'what does this mean / what should I do' answer Stripe-style.",appliesTo:["web","node"],codeRef:["sdks/web/src/error-codes.ts","sdks/node/src/error-codes.ts","sdks/web/src/_contract-verifiers.ts","backend/src/api/v1-errors.ts"],testRef:[{file:"sdks/web/tests/contract-verifiers.test.ts",name:"sdk-error-codes-catalogue covers every backend wire code with remediation"},{file:"sdks/web/tests/error-codes-backfill.test.ts",name:"includes backend code"},{file:"sdks/web/tests/error-codes-backfill.test.ts",name:"invalid_api_key resolution points at the dashboard"},{file:"sdks/web/tests/error-codes-backfill.test.ts",name:"idempotency_key_in_use resolution mentions Stripe-grade contract"},{file:"sdks/web/tests/error-codes-backfill.test.ts",name:"identity-lock codes carry permission_error type"},{file:"sdks/web/tests/error-codes-backfill.test.ts",name:"no entry has an empty description or resolution"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 6.2",bundledIn:"@cross-deck/web@1.6.2",runtimeVerified:!0},{id:"super-property-merge-precedence",pillar:"analytics",status:"enforced",claim:"Every Crossdeck SDK merges event properties with the precedence device < super < caller (caller-supplied values win over registered super-properties, which win over auto-attached device info). Pre-v1.4.0 Swift had it INVERTED (super < device < caller \u2014 device clobbered super), so a `register('plan', 'pro')` super-property was silently overridden by auto-attached device fields whenever keys collided. Cross-SDK funnel queries on super-property keys returned different answers per platform.",appliesTo:["web","swift"],codeRef:["sdks/web/src/super-properties.ts","sdks/web/src/_contract-verifiers.ts","sdks/swift/Sources/Crossdeck/EventPropertyMerge.swift","sdks/swift/Sources/Crossdeck/Crossdeck.swift"],testRef:[{file:"sdks/web/tests/contract-verifiers.test.ts",name:"super-property-merge-precedence verifies caller > super > device"},{file:"sdks/swift/Tests/CrossdeckTests/EventPropertyMergeTests.swift",name:"test_super_overrides_device"},{file:"sdks/swift/Tests/CrossdeckTests/EventPropertyMergeTests.swift",name:"test_caller_overrides_super"},{file:"sdks/swift/Tests/CrossdeckTests/EventPropertyMergeTests.swift",name:"test_full_precedence_chain"},{file:"sdks/swift/Tests/CrossdeckTests/EventPropertyMergeTests.swift",name:"test_matchesWebNodeRNPrecedence"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 3.2",bundledIn:"@cross-deck/web@1.6.2",runtimeVerified:!0},{id:"sync-purchases-funnel-parity",pillar:"analytics",status:"enforced",claim:"Manual syncPurchases() emits a `purchase.completed` analytics event on success across ALL SDKs (Web / Node / RN / Swift / Android). Pre-v1.4.0 only Swift/Android auto-track emitted it \u2014 Web/Node/RN manual calls + Swift/Android manual calls fired ZERO analytics. Schema mirrors the auto-track event name + rail/productId/subscriptionId so cross-platform funnels reconcile on every payment path. When the backend short-circuits via the v1.4.0 idempotency cache, the event also carries `idempotent_replay: true`.",appliesTo:["web","node","react-native","swift","android"],codeRef:["sdks/web/src/crossdeck.ts","sdks/node/src/crossdeck-server.ts","sdks/react-native/src/crossdeck.ts","sdks/swift/Sources/Crossdeck/Crossdeck.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt"],testRef:[{file:"sdks/web/tests/sync-purchases-funnel.test.ts",name:"emits purchase.completed after a successful sync"},{file:"sdks/web/tests/sync-purchases-funnel.test.ts",name:"carries idempotent_replay=true when backend replied from cache"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 3.5",bundledIn:"@cross-deck/web@1.6.2",runtimeVerified:!1}]);var ot={all(){return N.filter(r=>r.status==="enforced")},allIncludingHistorical(){return N},byId(r){return N.find(e=>e.id===r)},byPillar(r){return N.filter(e=>e.pillar===r&&e.status==="enforced")},withStatus(r){return N.filter(e=>e.status===r)},sdkVersion:it,bundledIn:nt,findByTestName(r){return N.find(e=>e.testRef.some(t=>t.name===r))}};return ht(Tr);})();
1
+ "use strict";var Crossdeck=(()=>{var me=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var pt=Object.prototype.hasOwnProperty;var ht=(r,e)=>{for(var t in e)me(r,t,{get:e[t],enumerable:!0})},mt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ft(e))!pt.call(r,n)&&n!==t&&me(r,n,{get:()=>e[n],enumerable:!(s=ut(e,n))||s.enumerable});return r};var gt=r=>mt(me({},"__esModule",{value:!0}),r);var Pr={};ht(Pr,{CROSSDECK_ERROR_CODES:()=>Se,Crossdeck:()=>it,CrossdeckClient:()=>J,CrossdeckContracts:()=>ct,CrossdeckError:()=>_,DEFAULT_BASE_URL:()=>Y,MemoryStorage:()=>V,SDK_NAME:()=>T,SDK_VERSION:()=>I,getErrorCode:()=>H});var _=class r extends Error{constructor(e){super(e.message),this.name="CrossdeckError",this.type=e.type,this.code=e.code,this.requestId=e.requestId,this.status=e.status,this.retryAfterMs=e.retryAfterMs,Object.setPrototypeOf(this,r.prototype)}};async function Fe(r){let e=r.headers.get("x-request-id")??void 0,t=yt(r.headers.get("retry-after")),s;try{s=await r.json()}catch{s=null}let n=s?.error;return n&&typeof n.type=="string"&&typeof n.code=="string"?new _({type:n.type,code:n.code,message:n.message??`HTTP ${r.status}`,requestId:n.request_id??e,status:r.status,retryAfterMs:t}):new _({type:bt(r.status),code:`http_${r.status}`,message:`HTTP ${r.status} ${r.statusText||""}`.trim(),requestId:e,status:r.status,retryAfterMs:t})}function yt(r){if(!r)return;let e=r.trim();if(!e)return;if(/^\d+(\.\d+)?$/.test(e)){let n=Number(e);return!Number.isFinite(n)||n<0?void 0:Math.round(n*1e3)}if(!/[a-zA-Z,/:]/.test(e))return;let t=Date.parse(e);if(!Number.isFinite(t))return;let s=t-Date.now();return s>0?s:0}function bt(r){return r===401?"authentication_error":r===403?"permission_error":r===429?"rate_limit_error":r>=400&&r<500?"invalid_request_error":"internal_error"}var I="1.6.4",T="@cross-deck/web";var Y="https://api.cross-deck.com/v1",vt=15e3,Q=class{constructor(e){this.config=e}async request(e,t,s={}){if(this.config.localDevMode)return kt(t);let n=this.buildUrl(t,s.query),i={Authorization:`Bearer ${this.config.publicKey}`,"Crossdeck-Sdk-Version":`${T}@${this.config.sdkVersion}`,Accept:"application/json"};s.idempotencyKey&&(i["Idempotency-Key"]=s.idempotencyKey);let c;s.body!==void 0&&(i["Content-Type"]="application/json",c=JSON.stringify(s.body));let o=s.timeoutMs??this.config.timeoutMs??vt,a=typeof AbortController<"u"&&o>0?new AbortController:null,d=null;a&&o>0&&(d=setTimeout(()=>a.abort(),o));let l;try{l=await fetch(n,{method:e,headers:i,body:c,keepalive:s.keepalive===!0,signal:a?.signal})}catch(u){let p=a?.signal?.aborted===!0;throw new _({type:"network_error",code:p?"request_timeout":"fetch_failed",message:p?`Request to ${t} aborted after ${o}ms`:u instanceof Error?u.message:"fetch failed"})}finally{d!==null&&clearTimeout(d)}if(!l.ok){let u=await Fe(l);if(this.config.onErrorParsed)try{this.config.onErrorParsed(u)}catch{}throw u}if(l.status!==204)try{return await l.json()}catch{throw new _({type:"internal_error",code:"invalid_json_response",message:"Server returned a 2xx with an unparseable body.",requestId:l.headers.get("x-request-id")??void 0,status:l.status})}}get isLocalDevMode(){return this.config.localDevMode===!0}buildUrl(e,t){let s=this.config.baseUrl.replace(/\/+$/,""),n=e.startsWith("/")?e:`/${e}`,i=s+n;if(t){let c=new URLSearchParams;for(let[a,d]of Object.entries(t))typeof d=="string"&&d.length>0&&c.append(a,d);let o=c.toString();o&&(i+=(i.includes("?")?"&":"?")+o)}return i}},X=null;function kt(r){return r.startsWith("/sdk/heartbeat")?{object:"heartbeat",ok:!0,projectId:"proj_local_dev",appId:"app_local_dev",platform:"web",env:"sandbox",serverTime:Date.now()}:r.startsWith("/identity/alias")?(X||(X=`cdcust_local_${typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,"").slice(0,16):Math.random().toString(36).slice(2,18)}`),{object:"alias_result",crossdeckCustomerId:X,linked:[],mergePending:!1,env:"sandbox"}):r.startsWith("/entitlements")?{object:"list",data:[],crossdeckCustomerId:X??"",env:"sandbox"}:r.startsWith("/events")?{object:"list",received:0,env:"sandbox"}:{}}var q="anon_id",K="cdcust_id",Z=class{constructor(e,t,s){this.primary=e;this.prefix=t;this.secondary=s??null;let n=e.getItem(t+q),i=e.getItem(t+K),c=this.secondary?.getItem(t+q)??null,o=this.secondary?.getItem(t+K)??null,a=n??c,d=i??o;this.state={anonymousId:a??this.mintAnonymousId(),crossdeckCustomerId:d},(!n||!c)&&this.writeBoth(t+q,this.state.anonymousId),d&&(!i||!o)&&this.writeBoth(t+K,d)}get anonymousId(){return this.state.anonymousId}get crossdeckCustomerId(){return this.state.crossdeckCustomerId}setCrossdeckCustomerId(e){this.state.crossdeckCustomerId=e,this.writeBoth(this.prefix+K,e)}reset(){this.deleteBoth(this.prefix+q),this.deleteBoth(this.prefix+K),this.state={anonymousId:this.mintAnonymousId(),crossdeckCustomerId:null},this.writeBoth(this.prefix+q,this.state.anonymousId)}mintAnonymousId(){let e=Date.now().toString(36),t=F(10);return`anon_${e}${t}`}writeBoth(e,t){try{this.primary.setItem(e,t)}catch{}if(this.secondary)try{this.secondary.setItem(e,t)}catch{}}deleteBoth(e){try{this.primary.removeItem(e)}catch{}if(this.secondary)try{this.secondary.removeItem(e)}catch{}}};function F(r){let e="0123456789abcdefghijklmnopqrstuvwxyz",t=[],s=globalThis.crypto;if(s?.getRandomValues){let n=new Uint8Array(r);s.getRandomValues(n);for(let i=0;i<r;i++)t.push(e[n[i]%e.length]??"0")}else for(let n=0;n<r;n++)t.push(e[Math.floor(Math.random()*e.length)]??"0");return t.join("")}var wt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function _t(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r);let e=[];for(let t=0;t<r.length;t++){let s=r.charCodeAt(t);if(s>=55296&&s<=56319&&t+1<r.length){let n=r.charCodeAt(t+1);n>=56320&&n<=57343&&(s=65536+(s-55296<<10)+(n-56320),t++)}s<128?e.push(s):s<2048?(e.push(192|s>>6),e.push(128|s&63)):s<65536?(e.push(224|s>>12),e.push(128|s>>6&63),e.push(128|s&63)):(e.push(240|s>>18),e.push(128|s>>12&63),e.push(128|s>>6&63),e.push(128|s&63))}return new Uint8Array(e)}function U(r){let e=_t(r),t=e.length*8,s=Math.floor((e.length+9+63)/64),n=new Uint8Array(s*64);n.set(e),n[e.length]=128;let i=Math.floor(t/4294967296),c=t>>>0,o=n.length-8;n[o+0]=i>>>24&255,n[o+1]=i>>>16&255,n[o+2]=i>>>8&255,n[o+3]=i&255,n[o+4]=c>>>24&255,n[o+5]=c>>>16&255,n[o+6]=c>>>8&255,n[o+7]=c&255;let a=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),d=new Uint32Array(64);for(let u=0;u<s;u++){let p=u*64;for(let h=0;h<16;h++)d[h]=(n[p+h*4]<<24|n[p+h*4+1]<<16|n[p+h*4+2]<<8|n[p+h*4+3])>>>0;for(let h=16;h<64;h++){let w=d[h-15],E=d[h-2],x=(w>>>7|w<<25)^(w>>>18|w<<14)^w>>>3,D=(E>>>17|E<<15)^(E>>>19|E<<13)^E>>>10;d[h]=d[h-16]+x+d[h-7]+D>>>0}let m=a[0],g=a[1],b=a[2],v=a[3],k=a[4],C=a[5],A=a[6],P=a[7];for(let h=0;h<64;h++){let w=(k>>>6|k<<26)^(k>>>11|k<<21)^(k>>>25|k<<7),E=k&C^~k&A,x=P+w+E+wt[h]+d[h]>>>0,D=(m>>>2|m<<30)^(m>>>13|m<<19)^(m>>>22|m<<10),dt=m&g^m&b^g&b,lt=D+dt>>>0;P=A,A=C,C=k,k=v+x>>>0,v=b,b=g,g=m,m=x+lt>>>0}a[0]=a[0]+m>>>0,a[1]=a[1]+g>>>0,a[2]=a[2]+b>>>0,a[3]=a[3]+v>>>0,a[4]=a[4]+k>>>0,a[5]=a[5]+C>>>0,a[6]=a[6]+A>>>0,a[7]=a[7]+P>>>0}let l="";for(let u=0;u<8;u++)l+=a[u].toString(16).padStart(8,"0");return l}var St=1440*60*1e3,ee="_anon",Et="_index",R=class r{constructor(e,t="crossdeck:entitlements",s=St){this.all=[];this.lastUpdated=0;this.lastRefreshFailedAt=0;this.listeners=new Set;this.listenerErrorCount=0;this.currentSuffix=ee;this.storage=e,this.storageKeyPrefix=t,this.staleAfterMs=s,this.hydrate()}get storageKey(){return`${this.storageKeyPrefix}:${this.currentSuffix}`}get indexKey(){return`${this.storageKeyPrefix}:${Et}`}static suffixForUserId(e){return e==null||e===""?ee:U(e)}setUserKey(e){let t=r.suffixForUserId(e);if(t===this.currentSuffix){this.all=[],this.lastUpdated=0,this.lastRefreshFailedAt=0,this.notify(),this.hydrate();return}this.currentSuffix=t,this.all=[],this.lastUpdated=0,this.lastRefreshFailedAt=0,this.hydrate(),this.notify()}isEntitled(e){let t=Date.now()/1e3;return this.all.some(s=>s.key===e&&s.isActive&&(s.validUntil==null||s.validUntil>t))}list(){return this.all.slice()}get freshness(){return this.lastUpdated}get isStale(){return this.lastRefreshFailedAt>this.lastUpdated?!0:this.lastUpdated>0&&Date.now()-this.lastUpdated>this.staleAfterMs}get refreshFailedAt(){return this.lastRefreshFailedAt}get listenerErrors(){return this.listenerErrorCount}markRefreshFailed(){this.lastRefreshFailedAt=Date.now()}setFromList(e){this.all=e.slice(),this.lastUpdated=Date.now(),this.lastRefreshFailedAt=0,this.persist(),this.recordSuffixInIndex(this.currentSuffix),this.notify()}clear(){if(this.all=[],this.lastUpdated=0,this.lastRefreshFailedAt=0,this.storage)try{this.storage.removeItem(this.storageKey)}catch{}this.removeSuffixFromIndex(this.currentSuffix),this.notify()}clearAll(){if(this.all=[],this.lastUpdated=0,this.lastRefreshFailedAt=0,this.currentSuffix=ee,this.storage){let e=this.readIndex();for(let t of e)try{this.storage.removeItem(`${this.storageKeyPrefix}:${t}`)}catch{}try{this.storage.removeItem(`${this.storageKeyPrefix}:${ee}`)}catch{}try{this.storage.removeItem(this.indexKey)}catch{}}this.notify()}subscribe(e){this.listeners.add(e);let t=!1;return()=>{t||(t=!0,this.listeners.delete(e))}}hydrate(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);t&&t.v===1&&Array.isArray(t.entitlements)&&(this.all=t.entitlements,this.lastUpdated=typeof t.lastUpdated=="number"?t.lastUpdated:0)}catch{}}persist(){if(this.storage)try{let e={v:1,entitlements:this.all,lastUpdated:this.lastUpdated};this.storage.setItem(this.storageKey,JSON.stringify(e))}catch{}}readIndex(){if(!this.storage)return[];try{let e=this.storage.getItem(this.indexKey);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}recordSuffixInIndex(e){if(!this.storage)return;let t=this.readIndex();if(!t.includes(e)){t.push(e);try{this.storage.setItem(this.indexKey,JSON.stringify(t))}catch{}}}removeSuffixFromIndex(e){if(!this.storage)return;let t=this.readIndex(),s=t.filter(n=>n!==e);if(s.length!==t.length)try{s.length===0?this.storage.removeItem(this.indexKey):this.storage.setItem(this.indexKey,JSON.stringify(s))}catch{}}notify(){if(this.listeners.size===0)return;let e=this.all.slice(),t=[...this.listeners];for(let s of t)try{s(e)}catch{this.listenerErrorCount+=1}}};function Ct(r){return[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.slice(20,32)].join("-")}function L(r){let e;if(r.rail==="apple"?e=r.signedTransactionInfo??"":r.rail==="google"?e=r.purchaseToken??"":e="",!e)throw new Error(`deriveIdempotencyKeyForPurchase: no stable identifier in body (rail=${r.rail}). Apple needs signedTransactionInfo; Google needs purchaseToken.`);let t=`crossdeck:purchases/sync:${r.rail}:${e}`;return Ct(U(t))}function xt(r,e,t={},s=Math.random){let n=t.baseMs??1e3,i=t.maxMs??6e4,c=t.factor??2,o=Math.min(r,30),d=Math.min(i,n*Math.pow(c,o))*s();if(e!==void 0){let u=Math.min(864e5,e);if(u>d)return u}return Math.max(0,Math.round(d))}var te=class{constructor(e={}){this.options=e;this.attempts=0}get consecutiveFailures(){return this.attempts}get isWarning(){return this.attempts>=(this.options.failuresBeforeWarn??8)}nextDelay(e,t=Math.random){let s=xt(this.attempts,e,this.options,t);return this.attempts+=1,s}recordSuccess(){this.attempts=0}};var B=1e3,re=class{constructor(e){this.cfg=e;this.buffer=[];this.pendingBatch=null;this.pendingBatchId=null;this.dropped=0;this.inFlight=0;this.lastFlushAt=0;this.lastError=null;this.cancelTimer=null;this.firstFlushFired=!1;this.nextRetryAt=null;if(this.retry=new te(e.retry??{}),this.persistent=e.persistentStore??null,this.persistent){let t=this.persistent.load();t.length>0&&(t.length>B?(this.dropped+=t.length-B,this.buffer=t.slice(t.length-B)):this.buffer=t,this.cfg.onBufferChange?.(this.buffer.length),this.scheduleIdleFlush())}}enqueue(e){if(this.buffer.push(e),this.buffer.length>B){let t=this.buffer.length-B;this.buffer.splice(0,t),this.dropped+=t,this.cfg.onDrop?.(t)}this.cfg.onBufferChange?.(this.buffer.length),this.persistAll(),this.buffer.length>=this.cfg.batchSize?this.flush():this.scheduleIdleFlush()}async flush(e={}){let t,s;if(this.pendingBatch!==null&&this.pendingBatchId!==null)t=this.pendingBatch,s=this.pendingBatchId;else{if(this.buffer.length===0)return null;t=this.buffer.splice(0),s=this.mintBatchId(),this.pendingBatch=t,this.pendingBatchId=s,this.inFlight+=t.length,this.cfg.onBufferChange?.(this.buffer.length),this.persistAll()}this.cancelTimerIfSet(),this.nextRetryAt=null;try{let n=this.cfg.envelope(),i=await this.cfg.http.request("POST","/events",{body:{appId:n.appId,environment:n.environment,sdk:n.sdk,events:t},keepalive:e.keepalive===!0,idempotencyKey:s});return this.lastFlushAt=Date.now(),this.lastError=null,this.inFlight-=t.length,this.pendingBatch=null,this.pendingBatchId=null,this.retry.recordSuccess(),this.persistAll(),this.firstFlushFired||(this.firstFlushFired=!0,this.cfg.onFirstFlushSuccess?.()),i}catch(n){let i=n instanceof Error?n.message:String(n);if(this.lastError=i,Tt(n)){let a=t.length;return this.pendingBatch=null,this.pendingBatchId=null,this.inFlight-=a,this.dropped+=a,this.persistAll(),this.cfg.onDrop?.(a),this.cfg.onPermanentFailure?.({status:n.status??0,droppedCount:a,lastError:i}),null}let c=It(n),o=this.retry.nextDelay(c);return this.scheduleRetry(o),this.cfg.onRetryScheduled?.({delayMs:o,consecutiveFailures:this.retry.consecutiveFailures,retryAfterMs:c,lastError:i}),null}}reset(){this.cancelTimerIfSet(),this.nextRetryAt=null,this.buffer=[],this.pendingBatch=null,this.pendingBatchId=null,this.dropped=0,this.inFlight=0,this.lastError=null,this.retry.recordSuccess(),this.persistent?.clear(),this.cfg.onBufferChange?.(0)}getStats(){return{buffered:this.buffer.length,dropped:this.dropped,inFlight:this.inFlight,lastFlushAt:this.lastFlushAt,lastError:this.lastError,consecutiveFailures:this.retry.consecutiveFailures,nextRetryAt:this.nextRetryAt}}get pendingIdempotencyKey(){return this.pendingBatchId}persistAll(){if(this.persistent){if(this.pendingBatch===null){this.persistent.save(this.buffer);return}this.persistent.save([...this.pendingBatch,...this.buffer])}}scheduleIdleFlush(){this.cancelTimerIfSet();let e=this.cfg.scheduler??Ve;this.cancelTimer=e(()=>{this.flush()},this.cfg.intervalMs)}scheduleRetry(e){this.cancelTimerIfSet(),this.nextRetryAt=Date.now()+e;let t=this.cfg.scheduler??Ve;this.cancelTimer=t(()=>{this.flush()},e)}cancelTimerIfSet(){this.cancelTimer&&(this.cancelTimer(),this.cancelTimer=null)}mintBatchId(){return`batch_${Date.now().toString(36)}${F(10)}`}};function It(r){if(r&&typeof r=="object"&&"retryAfterMs"in r){let e=r.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}}function Tt(r){if(!r||typeof r!="object")return!1;let e=r.status;return!(typeof e!="number"||!Number.isFinite(e)||e<400||e>=500||e===408||e===429)}function Ve(r,e){let t=setTimeout(r,e);if(typeof t.unref=="function")try{t.unref()}catch{}return()=>clearTimeout(t)}var se=class{constructor(e){this.options=e;this.writeScheduled=!1;this.pendingSnapshot=null;this.key=`${e.prefix}queue.v1`}load(){let e;try{e=this.options.storage.getItem(this.key)}catch{return[]}if(!e)return[];try{let t=JSON.parse(e);return!t||t.version!==1||!Array.isArray(t.events)?[]:t.events}catch{return[]}}save(e){this.pendingSnapshot=e.slice(),!this.writeScheduled&&(this.writeScheduled=!0,queueMicrotask(()=>this.flushWrite()))}saveSync(e){this.pendingSnapshot=e.slice(),this.flushWrite()}clear(){this.pendingSnapshot=null,this.writeScheduled=!1;try{this.options.storage.removeItem(this.key)}catch{}}flushWrite(){this.writeScheduled=!1;let e=this.pendingSnapshot;if(this.pendingSnapshot=null,e===null)return;if(e.length===0){try{this.options.storage.removeItem(this.key)}catch{}return}let t={version:1,events:e};try{this.options.storage.setItem(this.key,JSON.stringify(t))}catch{}}};var V=class{constructor(){this.store=new Map}getItem(e){return this.store.get(e)??null}setItem(e,t){this.store.set(e,t)}removeItem(e){this.store.delete(e)}},ne=class{constructor(e){this.maxAgeSec=e?.maxAgeSec??63072e3,this.secure=e?.secure??Rt(),this.sameSite=e?.sameSite??"Lax"}getItem(e){if(!ge())return null;let t=globalThis.document,s=t.cookie?t.cookie.split(/;\s*/):[],n=encodeURIComponent(e)+"=";for(let i of s)if(i.startsWith(n))try{return decodeURIComponent(i.slice(n.length))}catch{return null}return null}setItem(e,t){if(!ge())return;let s=globalThis.document,n=[`${encodeURIComponent(e)}=${encodeURIComponent(t)}`,"Path=/",`Max-Age=${this.maxAgeSec}`,`SameSite=${this.sameSite}`];this.secure&&n.push("Secure");try{s.cookie=n.join("; ")}catch{}}removeItem(e){if(!ge())return;let t=globalThis.document,s=[`${encodeURIComponent(e)}=`,"Path=/","Max-Age=0",`SameSite=${this.sameSite}`];this.secure&&s.push("Secure");try{t.cookie=s.join("; ")}catch{}}};function Oe(){try{let r=globalThis.localStorage;if(r){let e="__crossdeck_probe__";return r.setItem(e,"1"),r.removeItem(e),r}}catch{}return new V}function Rt(){try{return globalThis.location?.protocol==="https:"}catch{return!1}}function ge(){return typeof globalThis.document<"u"}function At(){return typeof globalThis.window<"u"&&typeof globalThis.document<"u"&&typeof globalThis.navigator<"u"}function Le(r){let e={};if(r?.appVersion&&(e.appVersion=r.appVersion),!At())return e;let t=globalThis.window,s=globalThis.navigator,n=globalThis.document;try{typeof s.language=="string"&&(e.locale=s.language)}catch{}try{e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}try{t.screen&&(e.screenWidth=t.screen.width,e.screenHeight=t.screen.height),e.viewportWidth=t.innerWidth,e.viewportHeight=t.innerHeight,e.devicePixelRatio=t.devicePixelRatio}catch{}try{let i=s.userAgent??"",c=Pt(i);Object.assign(e,c)}catch{}try{let i=s.userAgentData;if(i?.platform&&!e.os&&(e.os=i.platform),i?.brands&&!e.browser){let c=i.brands.find(o=>!/Not[ .;A]*Brand/i.test(o.brand)&&!/Chromium/i.test(o.brand));c&&(e.browser=c.brand,e.browserVersion=c.version)}}catch{}return e}function Pt(r){let e={};if(/iPad|iPhone|iPod/.test(r)){e.os="iOS";let t=r.match(/OS (\d+[._]\d+(?:[._]\d+)?)/);t?.[1]&&(e.osVersion=t[1].replace(/_/g,"."))}else if(/Android/.test(r)){e.os="Android";let t=r.match(/Android (\d+(?:\.\d+)*)/);t?.[1]&&(e.osVersion=t[1])}else if(/Windows/.test(r)){e.os="Windows";let t=r.match(/Windows NT (\d+\.\d+)/);t?.[1]&&(e.osVersion=t[1])}else if(/Mac OS X|Macintosh/.test(r)){e.os="macOS";let t=r.match(/Mac OS X (\d+[._]\d+(?:[._]\d+)?)/);t?.[1]&&(e.osVersion=t[1].replace(/_/g,"."))}else/Linux/.test(r)&&(e.os="Linux");return/Edg\/(\d+(?:\.\d+)*)/.test(r)?(e.browser="Edge",e.browserVersion=r.match(/Edg\/(\d+(?:\.\d+)*)/)?.[1]):/Firefox\/(\d+(?:\.\d+)*)/.test(r)?(e.browser="Firefox",e.browserVersion=r.match(/Firefox\/(\d+(?:\.\d+)*)/)?.[1]):/OPR\/(\d+(?:\.\d+)*)/.test(r)?(e.browser="Opera",e.browserVersion=r.match(/OPR\/(\d+(?:\.\d+)*)/)?.[1]):/Chrome\/(\d+(?:\.\d+)*)/.test(r)?(e.browser="Chrome",e.browserVersion=r.match(/Chrome\/(\d+(?:\.\d+)*)/)?.[1]):/Version\/(\d+(?:\.\d+)*).*Safari/.test(r)&&(e.browser="Safari",e.browserVersion=r.match(/Version\/(\d+(?:\.\d+)*)/)?.[1]),e}var O={sessions:!0,pageViews:!0,deviceInfo:!0,clicks:!0,webVitals:!0,errors:!0},ye=1800*1e3,Dt="crossdeck:session",Ft=5e3,ie={utm_source:"",utm_medium:"",utm_campaign:"",utm_content:"",utm_term:"",referrer:"",gclid:"",fbclid:"",msclkid:"",ttclid:"",li_fat_id:"",twclid:""},j=class{constructor(e,t,s){this.cfg=e;this.track=t;this.session=null;this.cleanups=[];this.lastPersistAt=0;this.pageviewId=null;this.storage=s?.storage??null,this.sessionKey=s?.storageKey??Dt}install(){Ue()&&(this.cfg.sessions&&this.installSessionTracking(),this.cfg.pageViews&&this.installPageViewTracking(),this.cfg.clicks&&this.installClickTracking())}uninstall(){for(;this.cleanups.length;){let e=this.cleanups.pop();try{e?.()}catch{}}this.session&&!this.session.endedSent&&this.emitSessionEnd(),this.clearStoredSession(),this.session=null}resetSession(){this.session&&!this.session.endedSent&&this.emitSessionEnd(),this.pageviewId=null,this.session=this.startNewSession(),this.persistSession(),this.emitSessionStart()}markActivity(){if(!this.session)return;let e=Date.now();if(e-this.session.lastActivityAt>=ye){this.pageviewId=null,this.session=this.startNewSession(),this.persistSession(),this.emitSessionStart();return}this.session.lastActivityAt=e,e-this.lastPersistAt>=Ft&&this.persistSession()}get currentSessionId(){return this.session?.sessionId??null}get currentPageviewId(){return this.pageviewId}get currentAcquisition(){return this.session?.acquisition??ie}installSessionTracking(){let e=Date.now(),t=this.readStoredSession();t&&e-t.lastActivityAt<ye?(this.session={sessionId:t.id,startedAt:t.startedAt,lastActivityAt:e,hiddenAt:null,endedSent:!1,acquisition:t.acquisition},this.persistSession()):(this.session=this.startNewSession(),this.persistSession(),this.emitSessionStart());let s=()=>{if(!this.session)return;let o=globalThis.document;o.visibilityState==="hidden"?(this.session.hiddenAt=Date.now(),this.persistSession()):o.visibilityState==="visible"&&(Date.now()-this.session.lastActivityAt>=ye?(this.pageviewId=null,this.session=this.startNewSession(),this.persistSession(),this.emitSessionStart()):this.session.hiddenAt=null)},n=()=>this.persistSession(),i=globalThis.window,c=globalThis.document;c.addEventListener("visibilitychange",s),i.addEventListener("pagehide",n),i.addEventListener("beforeunload",n),this.cleanups.push(()=>{c.removeEventListener("visibilitychange",s),i.removeEventListener("pagehide",n),i.removeEventListener("beforeunload",n)})}startNewSession(){let e=Date.now();return{sessionId:Gt(),startedAt:e,lastActivityAt:e,hiddenAt:null,endedSent:!1,acquisition:Jt()}}readStoredSession(){if(!this.storage)return null;try{let e=this.storage.getItem(this.sessionKey);if(!e)return null;let t=JSON.parse(e);return!t||typeof t.id!="string"||typeof t.startedAt!="number"||typeof t.lastActivityAt!="number"?null:{id:t.id,startedAt:t.startedAt,lastActivityAt:t.lastActivityAt,acquisition:t.acquisition&&typeof t.acquisition=="object"?t.acquisition:ie}}catch{return null}}persistSession(){if(!(!this.storage||!this.session)){this.lastPersistAt=Date.now();try{let e={id:this.session.sessionId,startedAt:this.session.startedAt,lastActivityAt:this.session.lastActivityAt,acquisition:this.session.acquisition};this.storage.setItem(this.sessionKey,JSON.stringify(e))}catch{}}}clearStoredSession(){if(this.storage)try{this.storage.removeItem(this.sessionKey)}catch{}}emitSessionStart(){this.session&&this.track("session.started",{sessionId:this.session.sessionId})}emitSessionEnd(){if(!this.session||this.session.endedSent)return;let e=Date.now()-this.session.startedAt;this.track("session.ended",{sessionId:this.session.sessionId,durationMs:e}),this.session.endedSent=!0}installPageViewTracking(){let e=globalThis.window,t=globalThis.document,s=0,n="",i=250,c=(p=!1)=>{let m=e.location,g=m.href,b=Date.now();!p&&g===n&&b-s<i||(s=b,n=g,this.pageviewId=`pv_${Date.now().toString(36)}${F(10)}`,this.track("page.viewed",{pageviewId:this.pageviewId,path:m.pathname,url:g,search:m.search||void 0,hash:m.hash||void 0,title:t.title,referrer:t.referrer||void 0}))};c();let o=e.history.pushState,a=e.history.replaceState;function d(p,m,g){o.apply(this,[p,m,g]),queueMicrotask(c)}function l(p,m,g){a.apply(this,[p,m,g]),queueMicrotask(c)}e.history.pushState=d,e.history.replaceState=l;let u=()=>c(!0);e.addEventListener("popstate",u),this.cleanups.push(()=>{e.history.pushState===d&&(e.history.pushState=o),e.history.replaceState===l&&(e.history.replaceState=a),e.removeEventListener("popstate",u)})}installClickTracking(){let e=globalThis.window,t=globalThis.document,s=0,n=null,i=100,c=64,o=a=>{let d=a.target;if(!d||!(d instanceof Element))return;let l=Date.now();if(d===n&&l-s<i)return;s=l,n=d;let p=Vt(d)||d;if(Ot(p)||Lt(p)||Nt(p))return;let m=p.tagName.toLowerCase(),g=Wt(jt(p),c),b=p.href||void 0,v=p.target||void 0,k=p.id||void 0,C=p.getAttribute("role")||void 0,A=p.getAttribute("aria-label")||void 0,P=Ht(p),h=zt(p),w=m==="a"&&!!b,E=p.getAttribute("data-cd-event"),x={selector:P,tag:m,text:g,elementId:k,role:C,ariaLabel:A,href:b,isLink:w,linkTarget:v,viewportX:a.clientX,viewportY:a.clientY,pageX:a.pageX,pageY:a.pageY,...h};for(let D of Object.keys(x))(x[D]===void 0||x[D]===null||x[D]==="")&&delete x[D];this.track(E||"element.clicked",x)};t.addEventListener("click",o,{capture:!0,passive:!0}),this.cleanups.push(()=>{t.removeEventListener("click",o,{capture:!0})})}};function Vt(r){return r.closest("[data-cd-event]")||r.closest("[data-cd-noTrack]")||r.closest("button, a, [role='button'], [role='link'], input[type='button'], input[type='submit']")||null}function Ot(r){if(!(r instanceof HTMLElement))return!1;let e=r.tagName.toLowerCase();if(e==="textarea"||e==="select")return!0;if(e==="input"){let t=(r.type||"").toLowerCase();return t!=="button"&&t!=="submit"&&t!=="image"&&t!=="reset"}return!1}function Lt(r){return!!r.closest("[data-cd-noTrack], [data-cd-no-track], .cd-noTrack, .cd-no-track")}function Nt(r){return!!r.closest('input[type="password"]')}var Ut=new Set(["span","b","strong","em","i","small","mark","u","label","abbr","time","bdi","cite","code","kbd","q","sub","sup"]),Mt=new Set(["svg","style","script","noscript"]),$t="a[href], button, input, select, textarea, [role='button'], [role='link'], h1, h2, h3, h4, h5, h6",qt="h1, h2, h3, h4, h5, h6";function Ne(r){return r.replace(/\s+/g," ").trim()}function be(r){let e="",t=s=>{let n=s.childNodes;for(let i=0;i<n.length;i++){let c=n[i];if(c){if(c.nodeType===3)e+=c.textContent||"";else if(c.nodeType===1){if(Mt.has(c.tagName.toLowerCase()))continue;e+=" ",t(c),e+=" "}}}};return t(r),Ne(e)}function Kt(r){let e="",t=r.childNodes;for(let s=0;s<t.length;s++){let n=t[s];n&&(n.nodeType===3?e+=" "+(n.textContent||""):n.nodeType===1&&Ut.has(n.tagName.toLowerCase())&&(e+=" "+be(n)))}return Ne(e)}function Bt(r){if(!(r.querySelector($t)!==null))return be(r);let t=Kt(r);if(t)return t;let s=r.querySelector(qt);if(s){let n=be(s);if(n)return n}return""}function jt(r){let e=d=>d.replace(/\s+/g," ").trim(),t=r.getAttribute("data-cd-track")||r.getAttribute("data-track")||r.getAttribute("data-testid");if(t){let d=e(t);if(d)return d}let s=r.getAttribute("aria-label");if(s){let d=e(s);if(d)return d}let n=r.getAttribute("aria-labelledby");if(n&&typeof r.ownerDocument?.getElementById=="function"){let d=[];for(let l of n.split(/\s+/)){let u=r.ownerDocument.getElementById(l),p=u?.textContent?e(u.textContent):"";p&&d.push(p)}if(d.length>0)return d.join(" ")}if(r instanceof HTMLInputElement&&r.value){let d=e(r.value);if(d)return d}let i=Bt(r);if(i)return i;let c=r.getAttribute("title");if(c){let d=e(c);if(d)return d}let o=r.querySelector("img[alt]");if(o){let d=o.getAttribute("alt")??"",l=e(d);if(l)return l}let a=r.querySelector("svg title");if(a?.textContent){let d=e(a.textContent);if(d)return d}return""}function Wt(r,e){return r.length<=e?r:r.slice(0,e-1)+"\u2026"}function Ht(r){let e=[],t=r,s=0;for(;t&&t.nodeName.toLowerCase()!=="body"&&s<5;){let n=t.nodeName.toLowerCase();if(t.id){e.unshift(`${n}#${t.id}`);break}if(t.classList.length>0){let i=Array.from(t.classList).filter(c=>!c.startsWith("cd-")).slice(0,2).join(".");i&&(n+=`.${i}`)}e.unshift(n),t=t.parentElement,s++}return e.join(" > ")}function zt(r){let e={};if(!(r instanceof HTMLElement))return e;for(let t of r.getAttributeNames()){if(!t.startsWith("data-")||t==="data-cd-noTrack"||t==="data-cd-no-track"||t==="data-cd-event")continue;let s=r.getAttribute(t)||"",n=t.replace(/^data-cd-prop-/,"").replace(/^data-/,"");e[n]=s}return e}function Ue(){return typeof globalThis.window<"u"&&typeof globalThis.document<"u"}function Gt(){return`sess_${Date.now().toString(36)}${F(10)}`}function Jt(){if(!Ue())return{...ie};let r={...ie};try{let e=globalThis.window,t=new URLSearchParams(e.location.search??"");r.utm_source=t.get("utm_source")??"",r.utm_medium=t.get("utm_medium")??"",r.utm_campaign=t.get("utm_campaign")??"",r.utm_content=t.get("utm_content")??"",r.utm_term=t.get("utm_term")??"",r.gclid=t.get("gclid")??"",r.fbclid=t.get("fbclid")??"",r.msclkid=t.get("msclkid")??"",r.ttclid=t.get("ttclid")??"",r.li_fat_id=t.get("li_fat_id")??"",r.twclid=t.get("twclid")??""}catch{}try{let e=globalThis.document;typeof e.referrer=="string"&&(r.referrer=e.referrer)}catch{}return r}var Xt=[/^email$/i,/^password$/i,/^token$/i,/^secret$/i,/^card$/i,/^phone$/i,/password/i,/credit_?card/i];function Me(r){if(!r)return[];let e=[];for(let t of Object.keys(r))Xt.some(s=>s.test(t))&&e.push(t);return e}var oe=class{constructor(){this.enabled=!1;this.seen=new Set}emit(e,t,s){if(!this.enabled)return;if(Qt.has(e)){if(this.seen.has(e))return;this.seen.add(e)}let n=s?` ${Yt(s)}`:"";console.info(`[crossdeck:${e}] ${t}${n}`)}},Qt=new Set(["sdk.configured","sdk.first_event_sent","sdk.environment_mismatch"]);function Yt(r){try{return JSON.stringify(r)}catch{return"[unserialisable context]"}}function W(r,e={}){let t=[];if(!r)return{properties:{},warnings:t};let s=e.maxStringLength??1024,n=e.maxBatchPropertyBytes??8192,i=e.maxDepth??5,c=new Set,o=(l,u,p)=>{if(p>i)return t.push({kind:"depth_exceeded",key:u}),{keep:!0,value:"[depth-exceeded]"};if(l===null)return{keep:!0,value:null};let m=typeof l;if(m==="string"){let g=l;return g.length>s?(t.push({kind:"truncated_string",key:u}),{keep:!0,value:g.slice(0,s-1)+"\u2026"}):{keep:!0,value:g}}if(m==="number")return Number.isFinite(l)?{keep:!0,value:l}:(t.push({kind:"non_serialisable",key:u}),{keep:!0,value:null});if(m==="boolean")return{keep:!0,value:l};if(m==="bigint")return t.push({kind:"coerced_bigint",key:u}),{keep:!0,value:l.toString()};if(m==="function")return t.push({kind:"dropped_function",key:u}),{keep:!1,value:void 0};if(m==="symbol")return t.push({kind:"dropped_symbol",key:u}),{keep:!1,value:void 0};if(m==="undefined")return t.push({kind:"dropped_undefined",key:u}),{keep:!1,value:void 0};if(l instanceof Date)return t.push({kind:"coerced_date",key:u}),{keep:!0,value:Number.isFinite(l.getTime())?l.toISOString():null};if(l instanceof Error)return t.push({kind:"coerced_error",key:u}),{keep:!0,value:{name:l.name,message:l.message,stack:typeof l.stack=="string"?l.stack.slice(0,s):void 0}};if(l instanceof Map){t.push({kind:"coerced_map",key:u});let g={};for(let[b,v]of l.entries()){let k=typeof b=="string"?b:String(b),C=o(v,`${u}.${k}`,p+1);C.keep&&(g[k]=C.value)}return{keep:!0,value:g}}if(l instanceof Set){t.push({kind:"coerced_set",key:u});let g=[],b=0;for(let v of l.values()){let k=o(v,`${u}[${b}]`,p+1);k.keep&&g.push(k.value),b++}return{keep:!0,value:g}}if(Array.isArray(l)){if(c.has(l))return t.push({kind:"circular_reference",key:u}),{keep:!0,value:"[circular]"};c.add(l);let g=[];for(let b=0;b<l.length;b++){let v=o(l[b],`${u}[${b}]`,p+1);v.keep&&g.push(v.value)}return c.delete(l),{keep:!0,value:g}}if(m==="object"){let g=l;if(c.has(g))return t.push({kind:"circular_reference",key:u}),{keep:!0,value:"[circular]"};c.add(g);let b={};for(let v of Object.keys(g)){let k=o(g[v],`${u}.${v}`,p+1);k.keep&&(b[v]=k.value)}return c.delete(g),{keep:!0,value:b}}t.push({kind:"non_serialisable",key:u});try{return{keep:!0,value:String(l)}}catch{return{keep:!1,value:void 0}}},a={};for(let l of Object.keys(r)){let u=o(r[l],l,0);u.keep&&(a[l]=u.value)}let d=$e(a);if(d&&ve(d)>n){t.push({kind:"size_cap_exceeded",key:"*"});let l=Object.keys(a).map(p=>({k:p,size:ve($e(a[p])??"")})).sort((p,m)=>m.size-p.size),u=ve(d);for(let{k:p}of l){if(u<=n)break;u-=l.find(m=>m.k===p).size,delete a[p]}a.__truncated=!0}return{properties:a,warnings:t}}function $e(r){try{return JSON.stringify(r)??null}catch{return null}}function ve(r){return typeof TextEncoder<"u"?new TextEncoder().encode(r).length:r.length*4}var ae="super_props",ke="groups",ce=class{constructor(e,t){this.storage=e;this.prefix=t;this.superProps={};this.groups={};this.superProps=qe(e,t+ae)??{},this.groups=qe(e,t+ke)??{}}register(e){for(let[t,s]of Object.entries(e))s===null?delete this.superProps[t]:s!==void 0&&(this.superProps[t]=s);return we(this.storage,this.prefix+ae,this.superProps),{...this.superProps}}unregister(e){e in this.superProps&&(delete this.superProps[e],we(this.storage,this.prefix+ae,this.superProps))}getSuperProperties(){return{...this.superProps}}setGroup(e,t,s){t===null?delete this.groups[e]:this.groups[e]=s!==void 0?{id:t,traits:s}:{id:t},we(this.storage,this.prefix+ke,this.groups)}getGroups(){return JSON.parse(JSON.stringify(this.groups))}getGroupIds(){let e={};for(let[t,s]of Object.entries(this.groups))e[t]=s.id;return e}clear(){this.superProps={},this.groups={};try{this.storage.removeItem(this.prefix+ae)}catch{}try{this.storage.removeItem(this.prefix+ke)}catch{}}};function qe(r,e){let t;try{t=r.getItem(e)}catch{return null}if(!t)return null;try{return JSON.parse(t)}catch{return null}}function we(r,e,t){try{r.setItem(e,JSON.stringify(t))}catch{}}var de=class{constructor(e,t){this.cfg=e;this.report=t;this.observers=[];this.flushed=new Set;this.cls=0;this.clsEntries=[];this.inp=0;this.cleanups=[]}install(){if(!this.cfg.enabled||typeof PerformanceObserver>"u"||typeof globalThis>"u"||!("document"in globalThis))return;let e=globalThis.document;try{let i=new PerformanceObserver(c=>{for(let o of c.getEntries()){let a=o;a.responseStart>0&&!this.flushed.has("ttfb")&&(this.flushed.add("ttfb"),this.report("webvitals.ttfb",{valueMs:Math.round(a.responseStart-a.startTime)}))}});i.observe({type:"navigation",buffered:!0}),this.observers.push(i)}catch{}try{let i=new PerformanceObserver(c=>{for(let o of c.getEntries())o.name==="first-contentful-paint"&&!this.flushed.has("fcp")&&(this.flushed.add("fcp"),this.report("webvitals.fcp",{valueMs:Math.round(o.startTime)}))});i.observe({type:"paint",buffered:!0}),this.observers.push(i)}catch{}let t=0;try{let i=new PerformanceObserver(c=>{let o=c.getEntries(),a=o[o.length-1];a&&(t=a.startTime)});i.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(i)}catch{}try{let i=new PerformanceObserver(c=>{for(let o of c.getEntries()){let a=o;typeof a.value=="number"&&!a.hadRecentInput&&(this.cls+=a.value,this.clsEntries.push(o))}});i.observe({type:"layout-shift",buffered:!0}),this.observers.push(i)}catch{}try{let i=new PerformanceObserver(c=>{for(let o of c.getEntries()){let a=o;a.interactionId&&a.duration>this.inp&&(this.inp=a.duration)}});try{i.observe({type:"event",buffered:!0,durationThreshold:16})}catch{i.observe({type:"first-input",buffered:!0})}this.observers.push(i)}catch{}let s=()=>{t>0&&!this.flushed.has("lcp")&&(this.flushed.add("lcp"),this.report("webvitals.lcp",{valueMs:Math.round(t)})),this.cls>0&&!this.flushed.has("cls")&&(this.flushed.add("cls"),this.report("webvitals.cls",{value:Math.round(this.cls*1e3)/1e3})),this.inp>0&&!this.flushed.has("inp")&&(this.flushed.add("inp"),this.report("webvitals.inp",{valueMs:Math.round(this.inp)}))},n=()=>{e.visibilityState==="hidden"&&s()};e.addEventListener("visibilitychange",n),globalThis.window.addEventListener("pagehide",s),this.cleanups.push(()=>{e.removeEventListener("visibilitychange",n),globalThis.window.removeEventListener("pagehide",s)})}uninstall(){for(let e of this.observers)try{e.disconnect()}catch{}this.observers=[];for(let e of this.cleanups.splice(0))try{e()}catch{}}};var Zt={analytics:!0,marketing:!0,errors:!0},le=class{constructor(e){this.state={...Zt};this.dntDenied=!1;e?.respectDnt&&this.detectDnt()&&(this.dntDenied=!0,this.state={analytics:!1,marketing:!1,errors:!1})}set(e){if(this.dntDenied)return{...this.state};for(let t of Object.keys(e)){let s=e[t];typeof s=="boolean"&&(this.state[t]=s)}return{...this.state}}get(){return{...this.state}}get analytics(){return this.state.analytics}get marketing(){return this.state.marketing}get errors(){return this.state.errors}get isDntDenied(){return this.dntDenied}detectDnt(){try{let e=globalThis.navigator;return e?[e.doNotTrack,e.msDoNotTrack,globalThis.doNotTrack].some(s=>s==="1"||s==="yes"):!1}catch{return!1}}},er=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,tr=/\b\d(?:[ -]?\d){12,18}\b/g,rr="<email>",sr="<card>";function nr(r){return r&&r.replace(er,rr).replace(tr,sr)}function _e(r){let e={};for(let t of Object.keys(r))e[t]=Ke(r[t]);return e}function Ke(r){return typeof r=="string"?nr(r):Array.isArray(r)?r.map(Ke):r&&typeof r=="object"&&r.constructor===Object?_e(r):r}var ue=class{constructor(e=50){this.maxSize=e;this.items=[]}add(e){this.items.push(e),this.items.length>this.maxSize&&this.items.shift()}snapshot(){return this.items.slice()}clear(){this.items=[]}get size(){return this.items.length}};var ir="https://api.cross-deck.com/v1/events",Be="cd_pub_live_9490e7aa029c432abf";function or(){return!Be.startsWith("cd_pub_RELIABILITY_PLACEHOLDER")}var ar=new Set(["contract_id","sdk_version","sdk_platform","failure_reason","run_context","run_id","test_file","test_name","device_class","verification_phase"]);function cr(r){let e={};for(let[t,s]of Object.entries(r))ar.has(t)&&typeof s=="string"&&(e[t]=s);return e}function fe(r){if(!or())return;let e=cr(r);if(Object.keys(e).length===0)return;let t=JSON.stringify({events:[{name:"crossdeck.contract_failed",timestamp:Date.now(),properties:e}]}),s=globalThis.fetch;if(typeof s=="function")try{s(ir,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Be}`,"Crossdeck-Sdk-Version":`${T}@${I}`},body:t,keepalive:!0,credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"}).catch(()=>{})}catch{}}var Se=Object.freeze([{code:"invalid_public_key",type:"configuration_error",description:"The publishable key passed to Crossdeck.init() doesn't start with cd_pub_.",resolution:"Copy the key from your Crossdeck dashboard \u2192 API keys page.",retryable:!1},{code:"missing_app_id",type:"configuration_error",description:"Crossdeck.init() was called without an appId.",resolution:"Add appId to your init options \u2014 find it in the dashboard's Apps page.",retryable:!1},{code:"invalid_environment",type:"configuration_error",description:"Crossdeck.init() requires environment: 'production' | 'sandbox'.",resolution:'Pass the literal string "production" or "sandbox" \u2014 no other values are accepted.',retryable:!1},{code:"environment_mismatch",type:"configuration_error",description:"The publishable key's env prefix doesn't match the declared environment option.",resolution:"Either change `environment` to match the key prefix (cd_pub_test_ \u2194 sandbox, cd_pub_live_ \u2194 production), or swap the key for one minted in the right env.",retryable:!1},{code:"not_initialized",type:"configuration_error",description:"An SDK method was called before Crossdeck.init().",resolution:"Call Crossdeck.init({ appId, publicKey, environment }) once at app startup before any other method.",retryable:!1},{code:"missing_user_id",type:"invalid_request_error",description:"identify() was called with an empty userId.",resolution:"Pass a stable, non-empty user identifier from your auth layer \u2014 never a hardcoded placeholder.",retryable:!1},{code:"missing_event_name",type:"invalid_request_error",description:"track() was called without an event name.",resolution:"Pass a non-empty string as the first argument.",retryable:!1},{code:"missing_group_type",type:"invalid_request_error",description:"group() was called without a group type.",resolution:'Pass a non-empty type (e.g. "org", "team") as the first argument.',retryable:!1},{code:"missing_signed_transaction_info",type:"invalid_request_error",description:"syncPurchases() was called without StoreKit 2 signed transaction info.",resolution:"Pass the JWS string from Transaction.currentEntitlements / Transaction.updates.",retryable:!1},{code:"fetch_failed",type:"network_error",description:"The underlying fetch() call failed (typically a network outage or DNS issue).",resolution:"Check the user's network. The SDK will retry automatically with exponential backoff.",retryable:!0},{code:"request_timeout",type:"network_error",description:"A request was aborted after the configured timeoutMs (default 15s).",resolution:"Check the user's connection. Increase timeoutMs in init options if the user is on a known-slow network.",retryable:!0},{code:"invalid_json_response",type:"internal_error",description:"The server returned a 2xx with an unparseable body.",resolution:"Likely a transient backend bug. Retry; if it persists, contact support with the requestId.",retryable:!0},{code:"missing_api_key",type:"authentication_error",description:"No Authorization header (or Crossdeck-Api-Key header) on the request.",resolution:"Make sure Crossdeck.init({ publicKey }) was called with a cd_pub_\u2026 key before the request fired. Re-check your env-vars in CI / Docker if the key is empty at runtime.",retryable:!1},{code:"invalid_api_key",type:"authentication_error",description:"The API key is malformed, unknown, or doesn't resolve to a project.",resolution:"Copy the key from your Crossdeck dashboard \u2192 API keys. Confirm prefix is cd_pub_test_ / cd_pub_live_ for client SDKs and cd_sk_test_ / cd_sk_live_ for the Node server SDK.",retryable:!1},{code:"key_revoked",type:"authentication_error",description:"The API key was revoked in the Crossdeck dashboard.",resolution:"Mint a fresh key in the dashboard \u2192 API keys \u2192 Create new, swap it in, and redeploy. The revoked key cannot be reactivated.",retryable:!1},{code:"identity_token_invalid",type:"authentication_error",description:"The Firebase / Apple / Google ID token supplied with the request didn't verify against the dashboard's configured signers.",resolution:"Refresh the token client-side (Firebase auth.currentUser.getIdToken(true)) and retry. If the failure persists, confirm the signer is registered under dashboard \u2192 Authentication \u2192 Identity sources.",retryable:!0},{code:"origin_not_allowed",type:"permission_error",description:"The Origin header isn't in the project's Allowed origins list.",resolution:"Add the origin (e.g. https://app.example.com) under dashboard \u2192 Settings \u2192 Allowed origins. Wildcards like https://*.example.com are supported.",retryable:!1},{code:"bundle_id_not_allowed",type:"permission_error",description:"The iOS bundle ID sent via X-Crossdeck-Bundle-Id isn't registered under this app's Apple identity lock.",resolution:"Add the bundle ID under dashboard \u2192 Apps \u2192 <your app> \u2192 iOS bundle IDs.",retryable:!1},{code:"package_name_not_allowed",type:"permission_error",description:"The Android package name sent via X-Crossdeck-Package-Name isn't registered under this app's Android identity lock.",resolution:"Add the package name under dashboard \u2192 Apps \u2192 <your app> \u2192 Android package names.",retryable:!1},{code:"env_mismatch",type:"permission_error",description:"The request env (inferred from key prefix) doesn't match the resolved app's configured env.",resolution:"Use a cd_pub_live_ / cd_sk_live_ key with a production app, cd_pub_test_ / cd_sk_test_ with a sandbox app. The two cannot cross.",retryable:!1},{code:"idempotency_key_in_use",type:"invalid_request_error",description:"An Idempotency-Key was reused for a request with a different body (Stripe-grade contract).",resolution:"Generate a fresh key for a different transaction, or reuse the key only with the EXACT same body. The v1.4.0 SDKs derive keys deterministically from the body so this should never fire on SDK-managed calls.",retryable:!1},{code:"rate_limited",type:"rate_limit_error",description:"Request rate exceeded the project's per-second cap.",resolution:"Honour the Retry-After header \u2014 the SDK does this automatically on managed retries. If you're hitting it from a custom code path, throttle to <100 req/s/key.",retryable:!0},{code:"internal_error",type:"internal_error",description:"Server-side issue. Safe to retry with backoff.",resolution:"The SDK retries automatically. If your code paths through to this error, contact support with the requestId from the response envelope.",retryable:!0},{code:"google_not_supported",type:"invalid_request_error",description:"POST /purchases/sync with rail=google is gated until the Play Developer API reconciliation worker ships.",resolution:"Until v1.5+, Google Play purchases verify via Real-time Developer Notifications. The SDK auto-track path handles this transparently for Android consumers.",retryable:!1},{code:"stripe_not_supported",type:"invalid_request_error",description:"POST /purchases/sync with rail=stripe is unsupported \u2014 Stripe Checkout's redirect flow uses platform webhooks instead.",resolution:"Wire Stripe via the standard Checkout / Customer Portal flow; Crossdeck reconciles via the platform webhook automatically. No SDK call needed.",retryable:!1},{code:"missing_required_param",type:"invalid_request_error",description:"A required field is absent from the request body.",resolution:"Inspect the error.message \u2014 the missing field name is included verbatim. Refer to the SDK's TypeScript types for the canonical request shape.",retryable:!1},{code:"invalid_param_value",type:"invalid_request_error",description:"A field is present but the value failed validation (wrong shape, wrong length, wrong enum value).",resolution:"Read error.message for the specific field + reason. SDK-managed call sites should never emit this \u2014 file a bug if you do.",retryable:!1}]);function H(r){return Se.find(e=>e.code===r)}function ze(r){return{sdkVersion:`${T}@${I}`,runId:`cd_verify_${kr(8)}`,runContext:r.runContext??"customer-app",logVerifierResults:r.logVerifierResults,disableContractAssertions:r.disableContractAssertions,console,emitTelemetry:fe}}var G=class{constructor(e){this.ctx=e;this.reentrancyDepth=0;this.verifiers=null}attachVerifiers(e){this.verifiers=e}report(e,t,s){this.ctx.disableContractAssertions||(e.ok?this.reportPass(e,t,s):this.reportFail(e,t,s))}reportPass(e,t,s){if(!this.ctx.logVerifierResults)return;let n=dr(e,s);t==="boot"?this.ctx.console.info(n):this.ctx.console.debug(n)}reportFail(e,t,s){if(this.ctx.console.warn(lr(e,s)),!(this.reentrancyDepth>0)){this.reentrancyDepth+=1;try{let n={contract_id:e.contractId,sdk_version:this.ctx.sdkVersion,sdk_platform:"web",failure_reason:vr(e.failureReason,128),run_context:this.ctx.runContext,run_id:this.ctx.runId,verification_phase:t};this.verifiers&&br(this.verifiers,this,this.ctx,{outgoingPayload:n}),this.ctx.emitTelemetry(n)}finally{this.reentrancyDepth-=1}}}};function dr(r,e){return`${e?`[crossdeck.${e}]`:"[crossdeck]"} \u2713 ${r.contractId} \u2014 ${r.evidence} (${r.durationMs}ms)`}function lr(r,e){return`${e?`[crossdeck.${e}]`:"[crossdeck]"} \u2717 ${r.contractId} \u2014 ${r.failureReason} (${r.durationMs}ms)`}var ur={contractId:"per-user-cache-isolation",bootTest(){let r=f();try{let e=new pe,t=new R(e,"_verifier");if(t.setUserKey("user_A"),t.setFromList([{object:"entitlement",key:"pro",isActive:!0,validUntil:null,source:{rail:"stripe",productId:"p_verifier",subscriptionId:"s_verifier"},updatedAt:Date.now()}]),t.setUserKey("user_B"),t.list().length!==0)return y("per-user-cache-isolation","in-memory snapshot still carried user_A's entitlements after rotation",f()-r);let n=R.suffixForUserId("user_A"),i=R.suffixForUserId("user_B");if(n===i)return y("per-user-cache-isolation","suffixes for user_A and user_B collided",f()-r);let c=e.getItem(`_verifier:${n}`),o=e.getItem(`_verifier:${i}`);return c?o?y("per-user-cache-isolation","user_B's storage slot already contained data before any write",f()-r):S("per-user-cache-isolation",`slot rotated A:${z(n)} \u2192 B:${z(i)} (isolated, physically separate)`,f()-r):y("per-user-cache-isolation","user_A's storage slot was wiped on rotation (expected isolation, not erasure)",f()-r)}catch(e){return y("per-user-cache-isolation",`boot test threw: ${e.message?.slice(0,80)??"unknown error"}`,f()-r)}},hooks:{onIdentify(r){let e=f(),t=R.suffixForUserId(r.priorUserId),s=R.suffixForUserId(r.nextUserId);return t!==s?r.cache.list().length!==0?y("per-user-cache-isolation","in-memory snapshot still held entitlements after slot rotation",f()-e):S("per-user-cache-isolation",`slot rotated ${z(t)} \u2192 ${z(s)}`,f()-e):S("per-user-cache-isolation",`same-id re-identify (suffix ${z(s)}); cleared + rehydrated per contract`,f()-e)}}},Ee="eyJ.jws.sig",je="a66b1640-efaf-bb4d-1261-6650033bf111",fr={contractId:"idempotency-key-deterministic",bootTest(){let r=f();try{let e=L({rail:"apple",signedTransactionInfo:Ee});if(e!==je)return y("idempotency-key-deterministic",`canonical apple JWS derived ${e} (expected ${je})`,f()-r);if(L({rail:"apple",signedTransactionInfo:Ee})!==e)return y("idempotency-key-deterministic","same JWS produced different keys on two derivations",f()-r);let s=e,n=L({rail:"google",purchaseToken:Ee});return s===n?y("idempotency-key-deterministic","rail namespacing failed \u2014 apple/google identical key",f()-r):S("idempotency-key-deterministic",`apple JWS \u2192 ${e} (canonical vector + determinism + rail isolation)`,f()-r)}catch(e){return y("idempotency-key-deterministic",`boot test threw: ${e.message?.slice(0,80)??"unknown error"}`,f()-r)}},hooks:{onSyncPurchases(r){let e=f();try{return L(r.rail==="apple"?{rail:"apple",signedTransactionInfo:r.stableIdentifier}:{rail:r.rail,purchaseToken:r.stableIdentifier})!==r.derivedKey?y("idempotency-key-deterministic","derived key drifted from canonical algorithm",f()-e):S("idempotency-key-deterministic",`${r.rail} \u2192 ${r.derivedKey}`,f()-e)}catch(t){return y("idempotency-key-deterministic",`hot-path derivation threw: ${t.message?.slice(0,80)??"unknown error"}`,f()-e)}}}},pr={contractId:"error-envelope-shape",bootTest(){let r=f(),e={error:{type:"invalid_request_error",code:"missing_customer",message:"Customer identifier is required.",request_id:"req_test1234"}},t=new Set(["authentication_error","permission_error","invalid_request_error","rate_limit_error","internal_error"]),s=e.error,n=["type","code","message","request_id"].filter(i=>!(i in s)||typeof s[i]!="string");return n.length>0?y("error-envelope-shape",`envelope missing required fields: ${n.join(", ")}`,f()-r):t.has(s.type)?S("error-envelope-shape","{ type, code, message, request_id } parsed and type \u2208 ApiErrorType",f()-r):y("error-envelope-shape",`error.type "${s.type}" not in canonical ApiErrorType set`,f()-r)},hooks:{onErrorParse(r){let e=f();return new Set(["authentication_error","permission_error","invalid_request_error","rate_limit_error","internal_error"]).has(r.errorType)?!r.errorCode||r.errorCode.length===0?y("error-envelope-shape","wire error.code was empty",f()-e):S("error-envelope-shape",`${r.errorType}/${r.errorCode} on ${r.httpStatus}${r.requestId?` (${r.requestId.slice(0,12)}\u2026)`:""}`,f()-e):y("error-envelope-shape",`wire error.type "${r.errorType}" outside canonical ApiErrorType`,f()-e)}}},hr={contractId:"flush-interval-parity",bootTest(){let r=f();return 2e3!==2e3?y("flush-interval-parity","canonical default drifted from 2000ms",f()-r):S("flush-interval-parity","eventFlushIntervalMs default = 2000ms (Web/Node/RN/Swift/Android parity)",f()-r)},hooks:{onTrack(r){let e=f(),t=2e3,s=r.flushIntervalMs;return typeof s!="number"||s<100||s>6e4?y("flush-interval-parity",`live eventFlushIntervalMs=${s} outside reasonable bounds [100, 60000]`,f()-e):S("flush-interval-parity",s===t?"live eventFlushIntervalMs = 2000ms (canonical parity value)":`live eventFlushIntervalMs = ${s}ms (permitted override; canonical default 2000ms)`,f()-e)}}};function Ge(r){return{contractId:"flush-interval-parity",bootTest(){let e=f(),t=2e3;return r<100||r>6e4?y("flush-interval-parity",`configured eventFlushIntervalMs=${r} outside reasonable bounds [100, 60000]`,f()-e):r!==t?S("flush-interval-parity",`eventFlushIntervalMs = ${r}ms (override; canonical default is 2000ms)`,f()-e):S("flush-interval-parity","eventFlushIntervalMs = 2000ms (canonical default)",f()-e)}}}var mr={contractId:"super-property-merge-precedence",bootTest(){let r=f(),n={...{plan:"device_plan",os:"macos"},...{plan:"super_plan",appVersion:"1.0.0"},...{plan:"caller_plan",eventSpecific:!0}};return n.plan!=="caller_plan"?y("super-property-merge-precedence",`merged.plan = "${n.plan}" (expected "caller_plan"; caller must override super and device)`,f()-r):n.appVersion!=="1.0.0"?y("super-property-merge-precedence","super-property appVersion was clobbered by device or caller",f()-r):n.os!=="macos"?y("super-property-merge-precedence","device property os was dropped from merged result",f()-r):S("super-property-merge-precedence","caller > super > device verified (synthetic merge)",f()-r)},hooks:{onTrack(r){let e=f();for(let[t,s]of Object.entries(r.callerProperties))if(r.mergedProperties[t]!==s)return y("super-property-merge-precedence",`caller key "${t}" did not win in merged output`,f()-e);for(let[t,s]of Object.entries(r.superProperties))if(!(t in r.callerProperties)&&r.mergedProperties[t]!==s)return y("super-property-merge-precedence",`super key "${t}" did not win over device in merged output`,f()-e);return S("super-property-merge-precedence",`caller(${Object.keys(r.callerProperties).length}) > super(${Object.keys(r.superProperties).length}) > device verified`,f()-e)}}},xe=["contract_id","sdk_version","sdk_platform","failure_reason","run_context","run_id"],Je=["test_file","test_name","device_class","verification_phase"],Xe=["anonymousId","developerUserId","crossdeckCustomerId","email","userId","ip","ipAddress","userAgent","stack","stackTrace","url","referrer","deviceId"];function We(r){let e=new Set([...xe,...Je]),t=new Set(Xe);for(let s of xe)if(!r.includes(s))return`missing required field: ${s}`;for(let s of r)if(t.has(s))return`forbidden field on wire: ${s}`;for(let s of r)if(!e.has(s))return`unrecognised field on wire: ${s} (not in required \u222A optional)`;return null}var He=`fields \u2286 required(${xe.length}) \u222A optional(${Je.length}); ${Xe.length} forbidden absent`,gr={contractId:"contract-failed-payload-schema-lock",bootTest(){let r=f(),t=Object.keys({contract_id:"synthetic",sdk_version:I,sdk_platform:"web",failure_reason:"synthetic",run_context:"customer-app",run_id:"synthetic-run-id",verification_phase:"boot"}),s=We(t);return s?y("contract-failed-payload-schema-lock",s,f()-r):S("contract-failed-payload-schema-lock",`${t.length} ${He}`,f()-r)},hooks:{onReportContractFailure(r){let e=f(),t=Object.keys(r.outgoingPayload),s=We(t);return s?y("contract-failed-payload-schema-lock",s,f()-e):S("contract-failed-payload-schema-lock",`${t.length} ${He}`,f()-e)}}},Ce=Object.freeze(["missing_api_key","invalid_api_key","key_revoked","identity_token_invalid","origin_not_allowed","bundle_id_not_allowed","package_name_not_allowed","env_mismatch","idempotency_key_in_use","rate_limited","internal_error","google_not_supported","stripe_not_supported","missing_required_param","invalid_param_value"]),yr={contractId:"sdk-error-codes-catalogue",bootTest(){let r=f();try{let e=[];for(let t of Ce){let s=H(t);(!s||!s.description||s.description.trim().length===0||!s.resolution||s.resolution.trim().length===0)&&e.push(t)}return e.length>0?y("sdk-error-codes-catalogue",`catalogue missing description+resolution for backend code(s): ${e.join(", ")}`,f()-r):S("sdk-error-codes-catalogue",`all ${Ce.length} backend wire codes carry description + resolution`,f()-r)}catch(e){return y("sdk-error-codes-catalogue",`boot test threw: ${e.message?.slice(0,80)??"unknown error"}`,f()-r)}},hooks:{onErrorParse(r){let e=f(),t=r.errorCode;if(!t||!Ce.includes(t))return S("sdk-error-codes-catalogue",`wire code "${t||"(none)"}" is out of the backend-catalogue scope`,f()-e);let s=H(t);return!s||!s.description||s.description.trim().length===0||!s.resolution||s.resolution.trim().length===0?y("sdk-error-codes-catalogue",`backend wire code "${t}" hit in the field has no description+resolution in the shipped catalogue`,f()-e):S("sdk-error-codes-catalogue",`backend wire code "${t}" carries description + resolution`,f()-e)}}},Qe=Object.freeze([ur,fr,pr,hr,mr,gr,yr]);async function Ie(r,e,t){if(t.disableContractAssertions)return{passed:0,failed:0,totalMs:0};let s=f(),n=0,i=0;if(t.logVerifierResults){let o=r.filter(l=>l.bootTest).length,a=r.filter(l=>l.hooks).length,d=r.map(l=>l.contractId).join(", ");t.console.info(`[crossdeck] Contract self-verification \u2014 ${r.length} verifiers (${o} boot-tests, ${a} hot-path hooks): ${d}`)}for(let o of r){if(!o.bootTest)continue;let a;try{a=await o.bootTest()}catch(d){a=y(o.contractId,`bootTest threw: ${d.message?.slice(0,80)??"unknown"}`,0)}e.report(a,"boot"),a.ok?n+=1:i+=1}let c=f()-s;if(t.logVerifierResults){let o=i===0?"passed":"complete";t.console.info(`[crossdeck] Self-verification ${o} \u2014 ${n} passed, ${i} failed (${c}ms)`)}return{passed:n,failed:i,totalMs:c}}function Ye(r,e,t,s){if(!t.disableContractAssertions)for(let n of r){let i=n.hooks?.onIdentify;if(!i)continue;let c;try{c=i(s)}catch(o){c=y(n.contractId,`hook threw: ${o.message?.slice(0,80)??"unknown"}`,0)}e.report(c,"hot_path","identify")}}function Ze(r,e,t,s){if(!t.disableContractAssertions)for(let n of r){let i=n.hooks?.onTrack;if(!i)continue;let c;try{c=i(s)}catch(o){c=y(n.contractId,`hook threw: ${o.message?.slice(0,80)??"unknown"}`,0)}e.report(c,"hot_path","track")}}function et(r,e,t,s){if(!t.disableContractAssertions)for(let n of r){let i=n.hooks?.onSyncPurchases;if(!i)continue;let c;try{c=i(s)}catch(o){c=y(n.contractId,`hook threw: ${o.message?.slice(0,80)??"unknown"}`,0)}e.report(c,"hot_path","syncPurchases")}}function tt(r,e,t,s){if(!t.disableContractAssertions)for(let n of r){let i=n.hooks?.onErrorParse;if(!i)continue;let c;try{c=i(s)}catch(o){c=y(n.contractId,`hook threw: ${o.message?.slice(0,80)??"unknown"}`,0)}e.report(c,"hot_path","errorParse")}}function br(r,e,t,s){if(!t.disableContractAssertions)for(let n of r){let i=n.hooks?.onReportContractFailure;if(!i)continue;let c;try{c=i(s)}catch(o){c=y(n.contractId,`hook threw: ${o.message?.slice(0,80)??"unknown"}`,0)}e.report(c,"hot_path","reportContractFailure")}}function rt(){try{if(typeof process<"u"&&process.env){let e=process.env.NODE_ENV;if(typeof e=="string")return e!=="production"}}catch{}let r=globalThis.__DEV__;return typeof r=="boolean"?r:!1}function S(r,e,t){return{ok:!0,contractId:r,evidence:e,durationMs:t}}function y(r,e,t){return{ok:!1,contractId:r,failureReason:e,durationMs:t}}function f(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function vr(r,e){return r.length>e?r.slice(0,e-1)+"\u2026":r}function z(r){let e=r.startsWith("_")?r.slice(1):r;return e.length<=12?e:`${e.slice(0,4)}\u2026${e.slice(-4)}`}function kr(r){let e=new Uint8Array(Math.ceil(r/2));if(typeof globalThis<"u"&&globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else for(let s=0;s<e.length;s+=1)e[s]=Math.floor(Math.random()*256);let t="";for(let s=0;s<e.length;s+=1)t+=e[s].toString(16).padStart(2,"0");return t.slice(0,r)}var pe=class{constructor(){this.map=new Map}getItem(e){return this.map.get(e)??null}setItem(e,t){this.map.set(e,t)}removeItem(e){this.map.delete(e)}keys(){return Array.from(this.map.keys())}};pe._=U;function Re(r){if(!r||typeof r!="string")return[];let e=r.split(`
2
+ `),t=[];for(let s of e){let n=s.trim();if(!n)continue;let i=wr(n);i&&t.push(i)}return t}function wr(r){let e=/^at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)$/.exec(r);return e?Te({function:e[1],filename:e[2],lineno:parseInt(e[3],10),colno:parseInt(e[4],10),raw:r}):(e=/^at\s+(.+?):(\d+):(\d+)$/.exec(r),e?Te({function:"?",filename:e[1],lineno:parseInt(e[2],10),colno:parseInt(e[3],10),raw:r}):(e=/^(.*?)@(.+?):(\d+):(\d+)$/.exec(r),e?Te({function:e[1]||"?",filename:e[2],lineno:parseInt(e[3],10),colno:parseInt(e[4],10),raw:r}):/^\w*Error/.test(r)||!r.includes(":")?null:{function:"?",filename:"",lineno:0,colno:0,in_app:!0,raw:r}))}function Te(r){return{function:r.function||"?",filename:r.filename,lineno:Number.isFinite(r.lineno)?r.lineno:0,colno:Number.isFinite(r.colno)?r.colno:0,in_app:_r(r.filename),raw:r.raw}}function _r(r){return r?!(/^(?:chrome|moz|safari|webkit)-extension:\/\//.test(r)||/\bcdn\.jsdelivr\.net\b/.test(r)||/\bunpkg\.com\b/.test(r)||/\bgoogletagmanager\.com\b/.test(r)||/\bgoogle-analytics\.com\b/.test(r)||/\b@cross-deck\/web\b/.test(r)||/\/crossdeck\.umd\.min\.js$/.test(r)):!0}function M(r,e,t){let s=e.filter(i=>i.in_app).slice(0,3),n=[(r||"").slice(0,200),...s.map(i=>`${i.function}@${i.filename}:${i.lineno}`)];if(s.length===0&&t){let i=[t.errorType??"",t.filename??"",t.lineno??"",t.colno??""].join(":");i!==":::"&&n.push(i)}return Sr(n.join("|"))}function Sr(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)|0;return(e>>>0).toString(16).padStart(8,"0")}var st={enabled:!0,onError:!0,onUnhandledRejection:!0,wrapFetch:!0,wrapXhr:!0,captureConsole:!1,ignoreErrors:["ResizeObserver loop limit exceeded","ResizeObserver loop completed with undelivered notifications","Non-Error promise rejection captured"],allowUrls:[],denyUrls:[/^chrome-extension:\/\//,/^moz-extension:\/\//,/^safari-extension:\/\//,/^webkit-extension:\/\//,/^safari-web-extension:\/\//],sampleRate:1,maxPerFingerprintPerMinute:5,maxPerSession:100},he=class{constructor(e){this.opts=e;this.installed=!1;this.cleanups=[];this._reporting=!1;this.sessionCount=0;this.fingerprintWindow=new Map}install(){if(this.installed||!this.opts.config.enabled||typeof globalThis>"u"||!("window"in globalThis))return;let e=globalThis.window;this.opts.config.onError&&this.installOnErrorListener(e),this.opts.config.onUnhandledRejection&&this.installRejectionListener(e),this.opts.config.wrapFetch&&this.installFetchWrap(e),this.opts.config.wrapXhr&&this.installXhrWrap(e),this.opts.config.captureConsole&&this.installConsoleWrap(),this.installed=!0}uninstall(){for(let e of this.cleanups.splice(0))try{e()}catch{}this.installed=!1}captureError(e,t){if(this.opts.isConsented())try{let s=this.buildFromUnknown(e,"error.handled",t?.level??"error");t?.context&&(s.context={...s.context,...t.context}),t?.tags&&(s.tags={...s.tags,...t.tags}),this.maybeReport(s)}catch{}}captureMessage(e,t="info"){if(this.opts.isConsented())try{let s={timestamp:Date.now(),kind:"error.message",level:t,message:e,errorType:null,frames:[],rawStack:null,filename:null,lineno:null,colno:null,fingerprint:M(e,[]),breadcrumbs:this.opts.breadcrumbs.snapshot(),context:this.opts.getContext(),tags:this.opts.getTags()};this.maybeReport(s)}catch{}}installOnErrorListener(e){let t=s=>{if(!this._reporting&&this.opts.isConsented())try{this._reporting=!0;let n=this.buildFromErrorEvent(s);this.maybeReport(n)}catch{}finally{this._reporting=!1}};e.addEventListener("error",t,!0),this.cleanups.push(()=>e.removeEventListener("error",t,!0))}installRejectionListener(e){let t=s=>{if(!this._reporting&&this.opts.isConsented())try{this._reporting=!0;let n=this.buildFromUnknown(s.reason,"error.unhandledrejection","error");this.maybeReport(n)}catch{}finally{this._reporting=!1}};e.addEventListener("unhandledrejection",t),this.cleanups.push(()=>e.removeEventListener("unhandledrejection",t))}installFetchWrap(e){let t=e.fetch?.bind(e);if(!t)return;let s=async(...n)=>{let i=n[0],c=n[1]??{},o=typeof i=="string"?i:i?.url??"",a=(c.method||"GET").toUpperCase(),d=Date.now();Pe(o,this.opts.selfHostname)||this.opts.breadcrumbs.add({timestamp:d,category:"http",message:`${a} ${o}`,data:{url:o,method:a}});try{let l=await t(...n);return l.status>=500&&this.opts.isConsented()&&(Pe(o,this.opts.selfHostname)||this.captureHttp({url:o,method:a,status:l.status,statusText:l.statusText})),l}catch(l){throw this.opts.isConsented()&&!o.includes("api.cross-deck.com")&&!xr(o,l,e)&&this.captureHttp({url:o,method:a,status:0,statusText:l instanceof Error?l.message:"network error"}),l}};e.fetch=s,this.cleanups.push(()=>{e.fetch===s&&(e.fetch=t)})}installXhrWrap(e){let s=e.XMLHttpRequest?.prototype;if(!s)return;let n=s.open,i=s.send,c=this;s.open=function(o,a,...d){return this._cdMethod=o,this._cdUrl=a,n.apply(this,[o,a,...d])},s.send=function(o){let a=this,d=()=>{try{if(a.status>=500&&c.opts.isConsented()){let l=a._cdUrl??"";Pe(l,c.opts.selfHostname)||c.captureHttp({url:l,method:(a._cdMethod??"GET").toUpperCase(),status:a.status,statusText:a.statusText})}}catch{}};return a.addEventListener("loadend",d),i.apply(this,[o??null])},this.cleanups.push(()=>{s.open=n,s.send=i})}installConsoleWrap(){let e=globalThis.console;if(!e)return;let t=e.error.bind(e);e.error=(...s)=>{try{this.opts.isConsented()&&this.captureMessage(s.map(n=>Cr(n)).join(" "),"error")}catch{}return t(...s)},this.cleanups.push(()=>{e.error=t})}buildFromErrorEvent(e){let t=e.error,s=e.filename||null,n=typeof e.lineno=="number"&&e.lineno>0?e.lineno:null,i=typeof e.colno=="number"&&e.colno>0?e.colno:null;if(t==null&&!s&&n==null&&(e.message==="Script error."||e.message==="Script error"||!e.message)){let m="Cross-origin script error (browser hid details \u2014 script needs crossorigin attribute + CORS headers)";return{timestamp:Date.now(),kind:"error.unhandled",level:"error",message:m,errorType:"ScriptError",frames:[],rawStack:null,filename:null,lineno:null,colno:null,fingerprint:M(m,[]),breadcrumbs:this.opts.breadcrumbs.snapshot(),context:this.opts.getContext(),tags:{...this.opts.getTags(),cross_origin:"true"}}}let o=De(t),a=(o.message||e.message||"Unknown error").slice(0,1024),d=t instanceof Error?t.stack??null:null,l=Re(d),u=o.errorType??null,p=o.extras?{...this.opts.getContext(),__error_extras:o.extras}:this.opts.getContext();return{timestamp:Date.now(),kind:"error.unhandled",level:"error",message:a,errorType:u,frames:l,rawStack:d,filename:s,lineno:n,colno:i,fingerprint:M(a,l,{filename:s,lineno:n,colno:i,errorType:u}),breadcrumbs:this.opts.breadcrumbs.snapshot(),context:p,tags:this.opts.getTags()}}buildFromUnknown(e,t,s){let n=De(e),i=(n.message||"Unknown error").slice(0,1024),c=e instanceof Error?e.stack??null:null,o=Re(c),a=n.errorType??null,d=n.extras?{...this.opts.getContext(),__error_extras:n.extras}:this.opts.getContext();return{timestamp:Date.now(),kind:t,level:s,message:i,errorType:a,frames:o,rawStack:c,filename:null,lineno:null,colno:null,fingerprint:M(i,o,{errorType:a}),breadcrumbs:this.opts.breadcrumbs.snapshot(),context:d,tags:this.opts.getTags()}}captureHttp(e){try{let t=`HTTP ${e.status} ${e.method} ${e.url}`,s={timestamp:Date.now(),kind:"error.http",level:"error",message:t,errorType:"HTTPError",frames:[],rawStack:null,filename:e.url,lineno:null,colno:null,fingerprint:M(`HTTP ${e.status} ${e.method}`,[],{filename:e.url,errorType:"HTTPError"}),breadcrumbs:this.opts.breadcrumbs.snapshot(),context:this.opts.getContext(),tags:this.opts.getTags(),http:e};this.maybeReport(s)}catch{}}maybeReport(e){if(this.sessionCount>=this.opts.config.maxPerSession||this.shouldIgnore(e)||!this.passesUrlGate(e)||!this.passesSample(e)||!this.passesRateLimit(e))return;let t=e,s=this.opts.beforeSend?.();if(s){try{t=s(e)}catch{t=e}if(!t)return}this.sessionCount+=1;try{this.opts.report(t)}catch{}}shouldIgnore(e){for(let t of this.opts.config.ignoreErrors)if(typeof t=="string"&&e.message.includes(t)||t instanceof RegExp&&t.test(e.message))return!0;return!1}passesUrlGate(e){let s=(e.frames.find(n=>n.filename)??null)?.filename??e.filename??"";if(!s)return!0;for(let n of this.opts.config.denyUrls)if(typeof n=="string"&&s.includes(n)||n instanceof RegExp&&n.test(s))return!1;if(this.opts.config.allowUrls.length>0){for(let n of this.opts.config.allowUrls)if(typeof n=="string"&&s.includes(n)||n instanceof RegExp&&n.test(s))return!0;return!1}return!0}passesSample(e){return this.opts.config.sampleRate>=1?!0:this.opts.config.sampleRate<=0?!1:parseInt(e.fingerprint.slice(0,2),16)/255<this.opts.config.sampleRate}passesRateLimit(e){let s=Date.now(),n=this.opts.config.maxPerFingerprintPerMinute,c=(this.fingerprintWindow.get(e.fingerprint)??[]).filter(o=>s-o<6e4);return c.length>=n?(this.fingerprintWindow.set(e.fingerprint,c),!1):(c.push(s),this.fingerprintWindow.set(e.fingerprint,c),!0)}};function De(r){if(r===null)return{message:"(thrown: null)",errorType:null,extras:null};if(r===void 0)return{message:"(thrown: undefined)",errorType:null,extras:null};if(typeof r=="string")return{message:r,errorType:null,extras:null};if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return{message:String(r),errorType:typeof r,extras:null};if(typeof r=="symbol")return{message:r.toString(),errorType:"symbol",extras:null};if(typeof r=="function")return{message:`(thrown function: ${r.name||"anonymous"})`,errorType:"function",extras:null};if(r instanceof Error){let e=r.name||r.constructor?.name||"Error",t=typeof r.message=="string"&&r.message.length>0?r.message:$(r)||e,s={},n=Er(r);n.length>0&&(s.cause=n);for(let i of["code","status","statusCode","errno","response","data","detail","details"]){let c=r[i];c!==void 0&&typeof c!="function"&&(s[i]=Ae(c))}for(let i of Object.keys(r)){if(i==="message"||i==="stack"||i==="name"||i==="cause"||i in s)continue;let c=r[i];typeof c!="function"&&(s[i]=Ae(c))}return{message:t,errorType:e,extras:Object.keys(s).length>0?s:null}}if(typeof Response<"u"&&r instanceof Response)return{message:`HTTP ${r.status} ${r.statusText||""}${r.url?` ${r.url}`:""}`.trim(),errorType:"Response",extras:{status:r.status,statusText:r.statusText,url:r.url,type:r.type}};if(typeof r=="object"){let e=r,t=e.constructor&&typeof e.constructor=="function"&&e.constructor.name||null,s=typeof e.message=="string"&&e.message?e.message:null,n=typeof e.name=="string"&&e.name?e.name:null,i=null;try{let u=JSON.stringify(e);i=u==="{}"?null:u}catch{i=null}let c=$(e),o=s??i??(c&&c!=="[object Object]"?c:null)??(t?`(thrown ${t} with no message)`:"(thrown object with no message)"),a=n??t??null,d={},l=0;for(let u of Object.keys(e)){if(l>=20)break;if(u==="message"||u==="name")continue;let p=e[u];typeof p!="function"&&(d[u]=Ae(p),l++)}return{message:o,errorType:a,extras:Object.keys(d).length>0?d:null}}return{message:$(r)||"(unstringifiable thrown value)",errorType:null,extras:null}}function Er(r){let e=[],t=r.cause,s=0;for(;t!=null&&s<5;)t instanceof Error?(e.push({name:t.name||"Error",message:t.message||""}),t=t.cause):(e.push({name:"non-Error",message:$(t)}),t=null),s++;return e}function $(r){try{let e=Object.prototype.toString.call(r);if(e!=="[object Object]")return e;let t=r?.toString;if(typeof t=="function"&&t!==Object.prototype.toString){let s=t.call(r);if(typeof s=="string")return s}return e}catch{return"(throwing toString)"}}function Ae(r){if(r==null)return r;let e=typeof r;if(e==="string"||e==="number"||e==="boolean")return r;if(e==="bigint")return String(r);try{let t=JSON.stringify(r);return t===void 0?$(r):JSON.parse(t)}catch{return $(r)}}function Cr(r){return De(r).message}function nt(r){if(!r||typeof r!="string")return null;try{return new URL(r).hostname.toLowerCase()}catch{return null}}function Pe(r,e){if(!e||!r)return!1;try{return new URL(r).hostname.toLowerCase()===e}catch{return!1}}function xr(r,e,t){if(e instanceof Error&&e.name==="AbortError")return!0;let s=t.navigator;if(s&&s.onLine===!1)return!0;let n=t.location?.href,i=t.location?.origin;if(!i)return!1;try{return new URL(r,n??i).origin===i}catch{return!1}}var J=class{constructor(){this.state=null;this.verifiers=null;this.verifierReporter=null;this.verifierCtx=null;this.flushIntervalMs=2e3}init(e){if(this.state){try{this.state.uninstallUnloadFlush?.()}catch{}try{this.state.autoTracker?.uninstall()}catch{}try{this.state.webVitals?.uninstall()}catch{}try{this.state.errors?.uninstall()}catch{}try{this.state.events.flush({keepalive:!0})}catch{}}if(!e.publicKey||!e.publicKey.startsWith("cd_pub_"))throw new _({type:"configuration_error",code:"invalid_public_key",message:"Crossdeck.init requires a publishable key starting with cd_pub_."});if(!e.appId)throw new _({type:"configuration_error",code:"missing_app_id",message:"Crossdeck.init requires an appId. Find yours in the Crossdeck dashboard."});if(e.environment!=="production"&&e.environment!=="sandbox")throw new _({type:"configuration_error",code:"invalid_environment",message:'Crossdeck.init requires environment: "production" | "sandbox".'});let t=Ir(e.publicKey);if(t&&t!==e.environment)throw new _({type:"configuration_error",code:"environment_mismatch",message:`Crossdeck.init: environment "${e.environment}" disagrees with key prefix (${t}). Reconcile the publishable key with the environment declaration.`});let s=Tr(),n=e.storage??Oe(),i=e.persistIdentity??!0,c=Rr(e.autoTrack),o={appId:e.appId,publicKey:e.publicKey,environment:e.environment,baseUrl:e.baseUrl??Y,persistIdentity:i,storagePrefix:e.storagePrefix??"crossdeck:",autoHeartbeat:e.autoHeartbeat??!0,eventFlushBatchSize:e.eventFlushBatchSize??20,eventFlushIntervalMs:e.eventFlushIntervalMs??2e3,sdkVersion:e.sdkVersion??I,autoTrack:c,appVersion:e.appVersion??null},a=new oe;a.enabled=e.debug===!0;let d=new Q({publicKey:o.publicKey,baseUrl:o.baseUrl,sdkVersion:o.sdkVersion,localDevMode:s,onErrorParsed:h=>{this.verifiers&&this.verifierReporter&&this.verifierCtx&&tt(this.verifiers,this.verifierReporter,this.verifierCtx,{errorType:h.type,errorCode:h.code,requestId:h.requestId??null,httpStatus:typeof h.status=="number"?h.status:0})}});s&&console.log("[crossdeck] Localhost detected \u2014 running in dev mode (no network calls). Set publicKey: 'cd_pub_test_\u2026' and deploy to a real domain to test against the Crossdeck Sandbox.");let l=i?n:new V,p=i&&!e.storage&&typeof globalThis.document<"u"?new ne:void 0,m=new Z(l,o.storagePrefix,p),g=new R(l,o.storagePrefix+"entitlements"),b=i?new se({storage:l,prefix:o.storagePrefix}):null;b&&a.emit("sdk.queue_restored","Restored persisted event queue from a prior session.");let v=new re({http:d,batchSize:o.eventFlushBatchSize,intervalMs:o.eventFlushIntervalMs,envelope:()=>({appId:o.appId,environment:o.environment,sdk:{name:T,version:o.sdkVersion}}),persistentStore:b??void 0,onFirstFlushSuccess:()=>{a.emit("sdk.first_event_sent","First telemetry event received. View it in Live Events.",{appId:o.appId,environment:o.environment})},onRetryScheduled:h=>{a.emit("sdk.flush_retry_scheduled",`Event flush failed (${h.lastError}). Retrying in ${h.delayMs}ms (attempt ${h.consecutiveFailures}).`,{...h})},onPermanentFailure:h=>{let w=`[crossdeck] Event batch DROPPED (status ${h.status}): ${h.lastError}. ${h.droppedCount} event(s) lost \u2014 check your publishable key + app config.`;console.error(w),a.emit("sdk.flush_permanent_failure",w,{...h})}}),k=c.deviceInfo?Le({appVersion:o.appVersion??void 0}):o.appVersion?{appVersion:o.appVersion}:{},C=new ce(i?l:new V,o.storagePrefix),A=new le({respectDnt:e.respectDnt===!0});A.isDntDenied&&a.emit("sdk.consent_dnt_applied","Do Not Track detected \u2014 all tracking dimensions denied at init.");let P=new ue(50);if(this.state={http:d,identity:m,entitlements:g,events:v,autoTracker:null,webVitals:null,errors:null,breadcrumbs:P,errorContext:{},errorTags:{},errorBeforeSend:null,superProps:C,consent:A,scrubPii:e.scrubPii!==!1,deviceInfo:k,options:o,debug:a,developerUserId:null,uninstallUnloadFlush:null,lastServerTime:null,lastClientTime:null},a.emit("sdk.configured",`Crossdeck connected to ${o.appId} in ${o.environment} mode.`,{appId:o.appId,environment:o.environment,sdkVersion:o.sdkVersion}),c.sessions||c.pageViews){let h=new j(c,(w,E)=>this.track(w,E),{storage:l,storageKey:o.storagePrefix+"session"});this.state.autoTracker=h,h.install()}if(c.webVitals){let h=new de({enabled:!0},(w,E)=>this.track(w,E));this.state.webVitals=h,h.install()}if(c.errors){let h=new he({config:{...st,enabled:!0},breadcrumbs:P,report:w=>this.reportError(w),getContext:()=>({...this.state.errorContext}),getTags:()=>({...this.state.errorTags}),beforeSend:()=>this.state.errorBeforeSend,isConsented:()=>this.state.consent.errors,selfHostname:nt(o.baseUrl)});this.state.errors=h,h.install()}if(this.state.uninstallUnloadFlush=Ar(()=>{this.flush({keepalive:!0}).catch(()=>{})}),o.autoHeartbeat&&!s&&this.heartbeat().catch(()=>{}),e.disableContractAssertions!==!0){let h=rt();this.verifierCtx=ze({logVerifierResults:e.logVerifierResults??h,disableContractAssertions:!1,runContext:typeof process<"u"&&process.env&&process.env.CI?"ci":"customer-app"}),this.verifierReporter=new G(this.verifierCtx);let w=Ge(o.eventFlushIntervalMs);this.verifiers=Object.freeze([...Qe,w]),this.flushIntervalMs=o.eventFlushIntervalMs,this.verifierReporter.attachVerifiers(this.verifiers),s?(e.verifyContractsAtBoot??h)&&this.verifierReporter&&Ie(this.verifiers,this.verifierReporter,this.verifierCtx).catch(()=>{}):this.bootstrapVerifierLayerRemote(e,h).catch(()=>{})}}async bootstrapVerifierLayerRemote(e,t){if(!this.state||!this.verifiers||!this.verifierCtx)return;let s={logVerifierResults:null,verifyContractsAtBoot:null};try{let c=await this.state.http.request("GET","/config");if(c&&c.verifierConfig){let o=c.verifierConfig;s={logVerifierResults:typeof o.logVerifierResults=="boolean"?o.logVerifierResults:null,verifyContractsAtBoot:typeof o.verifyContractsAtBoot=="boolean"?o.verifyContractsAtBoot:null}}}catch{}let n=e.logVerifierResults??s.logVerifierResults??t,i=e.verifyContractsAtBoot??s.verifyContractsAtBoot??t;n!==this.verifierCtx.logVerifierResults&&(this.verifierCtx={...this.verifierCtx,logVerifierResults:n},this.verifierReporter=new G(this.verifierCtx)),i&&this.verifierReporter&&await Ie(this.verifiers,this.verifierReporter,this.verifierCtx)}start(e){typeof console<"u"&&console.warn("[crossdeck] Crossdeck.start() is deprecated \u2014 use Crossdeck.init() instead. The signature is the same."),this.init(e)}async identify(e,t){let s=this.requireStarted();if(!e)throw new _({type:"invalid_request_error",code:"missing_user_id",message:"identify(userId) requires a non-empty userId."});if(!s.consent.analytics)return s.debug.emit("sdk.consent_denied","identify() skipped \u2014 consent denied for analytics."),{object:"alias_result",crossdeckCustomerId:s.identity.crossdeckCustomerId??"",linked:[],mergePending:!1,env:s.options.environment};let n=t?.traits!==void 0?W(t.traits):null,i=n&&Object.keys(n.properties).length>0?n.properties:void 0;if(s.debug.enabled&&n&&n.warnings.length>0)for(let d of n.warnings)s.debug.emit("sdk.property_coerced",`identify() traits key ${JSON.stringify(d.key)} was ${d.kind.replace(/_/g," ")} during validation.`,{key:d.key,kind:d.kind});let c={userId:e,anonymousId:s.identity.anonymousId};t?.email&&(c.email=t.email),i&&(c.traits=i);let o=s.developerUserId;s.entitlements.setUserKey(e),this.verifiers&&this.verifierReporter&&this.verifierCtx&&Ye(this.verifiers,this.verifierReporter,this.verifierCtx,{priorUserId:o,nextUserId:e,cache:s.entitlements});let a=await s.http.request("POST","/identity/alias",{body:c});return s.identity.setCrossdeckCustomerId(a.crossdeckCustomerId),s.developerUserId=e,a}register(e){let t=this.requireStarted(),s=W(e);return t.superProps.register(s.properties)}unregister(e){this.requireStarted().superProps.unregister(e)}getSuperProperties(){return this.state?this.state.superProps.getSuperProperties():{}}group(e,t,s){let n=this.requireStarted();if(!e)throw new _({type:"invalid_request_error",code:"missing_group_type",message:"group(type, id) requires a non-empty type."});let i=s?W(s).properties:void 0;n.superProps.setGroup(e,t,i)}getGroups(){return this.state?this.state.superProps.getGroups():{}}consent(e){let t=this.requireStarted(),s=t.consent.set(e);return t.debug.emit("sdk.consent_changed","Consent state updated.",{...s}),s}consentStatus(){return this.state?this.state.consent.get():{analytics:!0,marketing:!0,errors:!0}}captureError(e,t){this.state?.errors&&this.state.errors.captureError(e,t)}captureMessage(e,t="info"){this.state?.errors&&this.state.errors.captureMessage(e,t)}setTag(e,t){this.state&&(this.state.errorTags[e]=t)}setTags(e){this.state&&Object.assign(this.state.errorTags,e)}setContext(e,t){this.state&&(this.state.errorContext[e]=t)}addBreadcrumb(e){this.state&&this.state.breadcrumbs.add(e)}setErrorBeforeSend(e){this.state&&(this.state.errorBeforeSend=e)}reportError(e){let t={fingerprint:e.fingerprint,level:e.level,errorType:e.errorType,message:e.message,stack:e.rawStack??void 0,frames:e.frames,filename:e.filename??void 0,lineno:e.lineno??void 0,colno:e.colno??void 0,tags:e.tags,context:e.context,breadcrumbs:e.breadcrumbs,http:e.http};for(let s of Object.keys(t))t[s]===void 0&&delete t[s];this.track(e.kind,t)}async forget(){let e=this.requireStarted(),t=this.identityQueryParams();try{await e.http.request("POST","/identity/forget",{body:{...t}})}catch(s){e.debug.emit("sdk.consent_denied",`forget() server call failed (${s instanceof Error?s.message:String(s)}). Local state wiped anyway.`)}this.reset()}async getEntitlements(){let e=this.requireStarted(),t=this.identityQueryParams(),s;try{s=await e.http.request("GET","/entitlements",{query:t})}catch(n){throw e.entitlements.markRefreshFailed(),n}return s.crossdeckCustomerId&&e.identity.setCrossdeckCustomerId(s.crossdeckCustomerId),e.entitlements.setFromList(s.data),s.data}isEntitled(e){return this.requireStarted().entitlements.isEntitled(e)}listEntitlements(){return this.requireStarted().entitlements.list()}onEntitlementsChange(e){return this.requireStarted().entitlements.subscribe(e)}reportContractFailure(e){let t={contract_id:e.contractId,sdk_version:I,sdk_platform:"web",failure_reason:e.failureReason,run_context:e.runContext,run_id:e.runId};e.testRef&&(t.test_file=e.testRef.file,t.test_name=e.testRef.name),e.deviceClass&&(t.device_class=e.deviceClass),fe(t)}track(e,t){let s=this.requireStarted();if(!e)throw new _({type:"invalid_request_error",code:"missing_event_name",message:"track(name) requires a non-empty name."});let n=e.startsWith("error."),i=e.startsWith("webvitals.");if(!(n||i?s.consent.errors:s.consent.analytics)){s.debug.enabled&&s.debug.emit("sdk.consent_denied",`Dropped event "${e}" \u2014 consent denied for ${i?"errors":"analytics"}.`);return}if(s.debug.enabled&&t){let v=Me(t);v.length>0&&s.debug.emit("sdk.sensitive_property_warning",`Event "${e}" has potentially sensitive property names: ${v.join(", ")}. Crossdeck is privacy-first \u2014 avoid sending PII unless intentional.`,{eventName:e,flagged:v})}s.debug.enabled&&!s.developerUserId&&!s.identity.crossdeckCustomerId&&s.debug.emit("sdk.no_identity","Using anonymous user until identify(userId) is called.");let o=W(t);if(s.debug.enabled&&o.warnings.length>0)for(let v of o.warnings)s.debug.emit("sdk.property_coerced",`Event "${e}" property ${JSON.stringify(v.key)} was ${v.kind.replace(/_/g," ")} during validation.`,{eventName:e,key:v.key,kind:v.kind});s.autoTracker?.markActivity();let a={...s.deviceInfo},d=s.autoTracker?.currentSessionId;d&&(a.sessionId=d);let l=s.autoTracker?.currentPageviewId;l&&(a.pageviewId=l);let u=s.autoTracker?.currentAcquisition;u&&(u.utm_source&&(a.utm_source=u.utm_source),u.utm_medium&&(a.utm_medium=u.utm_medium),u.utm_campaign&&(a.utm_campaign=u.utm_campaign),u.utm_content&&(a.utm_content=u.utm_content),u.utm_term&&(a.utm_term=u.utm_term),u.referrer&&s.consent.marketing&&(a.referrer=u.referrer),s.consent.marketing&&(u.gclid&&(a.gclid=u.gclid),u.fbclid&&(a.fbclid=u.fbclid),u.msclkid&&(a.msclkid=u.msclkid),u.ttclid&&(a.ttclid=u.ttclid),u.li_fat_id&&(a.li_fat_id=u.li_fat_id),u.twclid&&(a.twclid=u.twclid)));let p=s.superProps.getSuperProperties();Object.assign(a,p);let m=s.superProps.getGroupIds();Object.keys(m).length>0&&(a.$groups=m),Object.assign(a,o.properties);let g=s.scrubPii?_e(a):a,b={eventId:this.mintEventId(),name:e,timestamp:Date.now(),properties:g};if(Object.assign(b,this.identityHintForEvent()),s.events.enqueue(b),this.verifiers&&this.verifierReporter&&this.verifierCtx&&Ze(this.verifiers,this.verifierReporter,this.verifierCtx,{callerProperties:o.properties,superProperties:p,deviceProperties:s.deviceInfo,mergedProperties:a,flushIntervalMs:this.flushIntervalMs}),!n&&!i){let v=e.startsWith("page.")?"navigation":e.startsWith("element.")||e==="session.started"?"ui.click":"custom";s.breadcrumbs.add({timestamp:b.timestamp,category:v,message:e,data:t?{...t}:void 0})}}async flush(e={}){await this.requireStarted().events.flush(e)}async flushEvents(){return this.flush()}async syncPurchases(e){let t=this.requireStarted();if(!e.signedTransactionInfo)throw new _({type:"invalid_request_error",code:"missing_signed_transaction_info",message:"syncPurchases requires a signedTransactionInfo string from StoreKit 2."});let s=e.rail??"apple",n={...e,rail:s},i=L(n);if(this.verifiers&&this.verifierReporter&&this.verifierCtx){let o=s==="apple"?n.signedTransactionInfo??"":n.purchaseToken??"";et(this.verifiers,this.verifierReporter,this.verifierCtx,{rail:s,stableIdentifier:o,derivedKey:i})}let c=await t.http.request("POST","/purchases/sync",{body:n,idempotencyKey:i});t.identity.setCrossdeckCustomerId(c.crossdeckCustomerId),t.entitlements.setFromList(c.entitlements);try{let o=c.entitlements[0]?.source.productId,a=c.entitlements[0]?.source.subscriptionId,d={rail:s};o&&(d.productId=o),a&&(d.subscriptionId=a),c.idempotent_replay&&(d.idempotent_replay=!0),this.track("purchase.completed",d)}catch{}return t.debug.emit("sdk.purchase_evidence_sent","StoreKit transaction forwarded. Waiting for backend verification.",{rail:e.rail??"apple"}),c}async purchaseApple(e){return this.syncPurchases({rail:"apple",...e})}setDebugMode(e){let t=this.requireStarted();t.debug.enabled=e,e&&t.debug.emit("sdk.configured",`Debug mode enabled for ${t.options.appId} in ${t.options.environment} mode.`,{appId:t.options.appId,environment:t.options.environment})}async heartbeat(){let e=this.requireStarted(),t=await e.http.request("GET","/sdk/heartbeat");return typeof t?.serverTime=="number"&&Number.isFinite(t.serverTime)&&(e.lastServerTime=t.serverTime,e.lastClientTime=Date.now()),t}reset(){if(this.state){if(this.state.developerUserId)try{this.track("user.signed_out",{auto:!0})}catch{}if(this.state.autoTracker?.uninstall(),this.state.identity.reset(),this.state.entitlements.clearAll(),this.state.events.reset(),this.state.superProps.clear(),this.state.breadcrumbs.clear(),this.state.errorContext={},this.state.errorTags={},this.state.developerUserId=null,this.state.lastServerTime=null,this.state.lastClientTime=null,this.state.autoTracker){let e=new j(this.state.options.autoTrack,(t,s)=>this.track(t,s));this.state.autoTracker=e,e.install()}}}diagnostics(){if(!this.state)return{started:!1,anonymousId:null,crossdeckCustomerId:null,developerUserId:null,sdkVersion:null,baseUrl:null,clock:{lastServerTime:null,lastClientTime:null,skewMs:null},entitlements:{count:0,lastUpdated:0,stale:!1,listenerErrors:0},events:{buffered:0,dropped:0,inFlight:0,lastFlushAt:0,lastError:null,consecutiveFailures:0,nextRetryAt:null}};let e=this.state,t=e.lastServerTime!==null&&e.lastClientTime!==null?e.lastClientTime-e.lastServerTime:null;return{started:!0,anonymousId:e.identity.anonymousId,crossdeckCustomerId:e.identity.crossdeckCustomerId,developerUserId:e.developerUserId,sdkVersion:e.options.sdkVersion,baseUrl:e.options.baseUrl,clock:{lastServerTime:e.lastServerTime,lastClientTime:e.lastClientTime,skewMs:t},entitlements:{count:e.entitlements.list().length,lastUpdated:e.entitlements.freshness,stale:e.entitlements.isStale,listenerErrors:e.entitlements.listenerErrors},events:e.events.getStats()}}getCheckoutReference(){let e=this.requireStarted();return e.identity.crossdeckCustomerId??e.developerUserId??e.identity.anonymousId}requireStarted(){if(!this.state)throw new _({type:"configuration_error",code:"not_initialized",message:"Call Crossdeck.init({ appId, publicKey, environment }) before any other method."});return this.state}identityQueryParams(){let e=this.requireStarted();return e.identity.crossdeckCustomerId?{customerId:e.identity.crossdeckCustomerId}:e.developerUserId?{userId:e.developerUserId}:{anonymousId:e.identity.anonymousId}}identityHintForEvent(){let e=this.requireStarted(),t={anonymousId:e.identity.anonymousId};return e.developerUserId&&(t.developerUserId=e.developerUserId),e.identity.crossdeckCustomerId&&(t.crossdeckCustomerId=e.identity.crossdeckCustomerId),t}mintEventId(){return`evt_${Date.now().toString(36)}${F(8)}`}},it=new J;function Ir(r){return r.startsWith("cd_pub_test_")?"sandbox":r.startsWith("cd_pub_live_")?"production":null}function Tr(){let r=globalThis.window;if(r?.__CROSSDECK_FORCE_LIVE__===!0)return!1;let e=r?.location?.hostname;return e?!!(e==="localhost"||e==="127.0.0.1"||e==="0.0.0.0"||e==="::1"||e==="[::1]"||/^\[?fe80::/i.test(e)||e.endsWith(".local")||/^10\./.test(e)||/^192\.168\./.test(e)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e)):!1}function Rr(r){return r===!1?{sessions:!1,pageViews:!1,deviceInfo:!1,clicks:!1,webVitals:!1,errors:!1}:r===void 0||r===!0?{...O}:{sessions:r.sessions??O.sessions,pageViews:r.pageViews??O.pageViews,deviceInfo:r.deviceInfo??O.deviceInfo,clicks:r.clicks??O.clicks,webVitals:r.webVitals??O.webVitals,errors:r.errors??O.errors}}function Ar(r){let e=globalThis.window,t=globalThis.document;if(!e||!t)return()=>{};let s=()=>{t.visibilityState==="hidden"&&r()},n=()=>r();return t.addEventListener("visibilitychange",s),e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),()=>{t.removeEventListener("visibilitychange",s),e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}var ot="@cross-deck/web@1.6.4",at="1.6.4",N=Object.freeze([{id:"contract-failed-payload-schema-lock",pillar:"diagnostics",status:"enforced",claim:"The `crossdeck.contract_failed` event payload contains ONLY the named diagnostic fields and never any end-user personal data. The wire shape is fixed \u2014 adding a new field requires (1) a pull request that updates this contract's `allowedFields` set, (2) a Privacy Policy \xA76 amendment, and (3) the Customer Disclosure Template / SDK Data Collection Reference \xA7B updates. Per-SDK assertion tests enforce the field set on every release. The `verification_phase` field is a categorical bucket \u2014 values are restricted to `boot` (the SDK self-test ran on Crossdeck.start) or `hot_path` (a verifier observed a real customer-triggered operation). The categorical nature is what preserves the diagnostic-only-not-personal classification. This is the structural guarantee that backs the independent-controller lawful basis in the Privacy Policy: the payload remains diagnostic-only, not personal, so the legitimate-interest analysis stays valid as the SDK evolves.",appliesTo:["web","node","swift","android","react-native"],allowedFields:{required:["contract_id","sdk_version","sdk_platform","failure_reason","run_context","run_id"],optional:["test_file","test_name","device_class","verification_phase"],forbidden:["anonymousId","developerUserId","crossdeckCustomerId","email","ip","user_agent","message","stack","stack_trace","frames","exception_message","url","path","screen","title","label","text","ariaLabel","accessibilityLabel","contentDescription","session_id","sessionId"]},transport:"Telemetry is single-fire to the Crossdeck reliability endpoint only \u2014 NOT the customer's appId. The customer's track() pipeline never carries `crossdeck.*` events; the customer's dashboard never shows individual contract failures. Operational telemetry flows one-way to the Crossdeck operations team for SDK reliability purposes (legitimate interest, independent-controller flow per Privacy Policy \xA76). The reliability endpoint is hardcoded at SDK build time; the publishable key for the reliability project is embedded as a constant and rejects writes that don't match the schema.",codeRef:["sdks/web/src/crossdeck.ts","sdks/node/src/crossdeck-server.ts","sdks/swift/Sources/Crossdeck/Crossdeck.swift","sdks/swift/Sources/Crossdeck/_DiagnosticTelemetry.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/_DiagnosticTelemetry.kt","sdks/react-native/src/crossdeck.ts","backend/src/api/v1-sdk-diagnostic.ts","sdks/web/src/_diagnostic-telemetry.ts","sdks/node/src/_diagnostic-telemetry.ts","sdks/react-native/src/_diagnostic-telemetry.ts"],testRef:[{file:"sdks/web/tests/contract-failed-schema-lock.test.ts",name:"reportContractFailure payload conforms to schema-lock"},{file:"sdks/node/tests/contract-failed-schema-lock.test.ts",name:"reportContractFailure payload conforms to schema-lock"},{file:"sdks/swift/Tests/CrossdeckTests/ContractFailedSchemaLockTests.swift",name:"test_reportContractFailure_payloadFieldsAreInAllowList"},{file:"sdks/swift/Tests/CrossdeckTests/ContractFailedSchemaLockTests.swift",name:"test_reportContractFailure_doesNotEnterCustomerTrackPipeline"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ContractFailedSchemaLockTest.kt",name:"reportContractFailure payload conforms to schema-lock"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ContractFailedSchemaLockTest.kt",name:"reportContractFailure does not enter customer track pipeline"},{file:"sdks/react-native/tests/contract-failed-schema-lock.test.ts",name:"reportContractFailure payload conforms to schema-lock"},{file:"backend/tests/unit/v1-sdk-diagnostic.test.ts",name:"forbidden fields are enumerated in the schema-lock contract"},{file:"backend/tests/unit/v1-sdk-diagnostic.test.ts",name:"required fields are enumerated in the schema-lock contract"},{file:"backend/tests/unit/v1-sdk-diagnostic.test.ts",name:"regression guard: never returns a raw IP"},{file:"backend/tests/unit/v1-sdk-diagnostic.test.ts",name:"verification_phase is in the optional field set"}],registeredAt:"2026-05-27",firstRegisteredIn:"Diagnostic telemetry single-fire + schema-lock \u2014 independent-controller flow",privacyReferences:["legal/privacy/index.html#sdk-diagnostic","legal/customer-disclosure/index.html#flow-b","legal/security/index.html#diagnostic","legal/sdk-data/index.html#b-diagnostic"],bundledIn:"@cross-deck/web@1.6.4",runtimeVerified:!0},{id:"error-envelope-shape",pillar:"errors",status:"enforced",claim:"Every v1 REST endpoint returns errors in a Stripe-shape envelope: `{ error: { type, code, message, request_id } }` where `type` is one of authentication_error / permission_error / invalid_request_error / rate_limit_error / internal_error (the wire vocabulary in backend/src/api/v1-errors.ts ApiErrorType). HTTP status parity: invalid_request_error \u2192 400, authentication_error \u2192 401, permission_error \u2192 403, rate_limit_error \u2192 429, internal_error \u2192 500. SDK-side clients parse this shape via `crossdeckErrorFromResponse` (Web/Node/RN) / `crossdeckErrorFrom(response:)` (Swift) / `crossdeckErrorFromResponse` (Android) and surface the request_id verbatim so support traces are end-to-end joinable. Firebase callable endpoints (managed-keys / dashboard auth) use the Firebase HttpsError envelope instead \u2014 this contract applies to REST /v1/* only.",appliesTo:["web","node","react-native","swift","android","backend"],codeRef:["backend/src/api/v1-errors.ts","sdks/web/src/errors.ts","sdks/node/src/errors.ts","sdks/react-native/src/errors.ts","sdks/swift/Sources/Crossdeck/Errors.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Errors.kt"],testRef:[{file:"sdks/swift/Tests/CrossdeckTests/ErrorsTests.swift",name:"test_errorEnvelope_fallsBackOnGarbageBody"},{file:"sdks/swift/Tests/CrossdeckTests/ErrorsTests.swift",name:"test_errorEnvelope_reads_XRequestId_fallback"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ErrorTypeWireVocabTest.kt",name:"backend 500 response parses to INTERNAL_ERROR"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 8 (codifies existing contract)",bundledIn:"@cross-deck/web@1.6.4",runtimeVerified:!0},{id:"flush-interval-parity",pillar:"analytics",status:"enforced",claim:"Every Crossdeck SDK defaults its event-queue flush interval to 2000ms \u2014 the Stripe-adjacent industry norm. Pre-v1.4.0 the defaults disagreed (Web/Node 1500ms; RN/Swift/Android 5000ms), so cross-platform funnels saw events landing at different cadences. Per-instance override stays \u2014 call sites can still tune it freely.",appliesTo:["web","node","react-native","swift","android"],codeRef:["sdks/web/src/crossdeck.ts","sdks/node/src/crossdeck-server.ts","sdks/react-native/src/crossdeck.ts","sdks/swift/Sources/Crossdeck/EventQueue.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EventQueue.kt"],testRef:[{file:"sdks/swift/Sources/Crossdeck/EventQueue.swift",name:"flushIntervalMs: Int = 2_000"},{file:"sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EventQueue.kt",name:"flushIntervalMs: Long = 2_000L"},{file:"sdks/web/src/crossdeck.ts",name:"options.eventFlushIntervalMs ?? 2000"},{file:"sdks/node/src/crossdeck-server.ts",name:"options.eventFlushIntervalMs ?? 2000"},{file:"sdks/react-native/src/crossdeck.ts",name:"options.eventFlushIntervalMs ?? 2000"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 3.3",bundledIn:"@cross-deck/web@1.6.4",runtimeVerified:!0},{id:"idempotency-key-deterministic",pillar:"revenue",status:"enforced",claim:"syncPurchases() on every SDK derives a deterministic Idempotency-Key from the request body (UUID-shaped SHA-256 of `crossdeck:purchases/sync:<rail>:<jws|token>`). Same input -> same key. Backend short-circuits same-key-same-body retries by returning the cached response (status + body) with `idempotent_replay: true` flag in the body AND `Idempotent-Replayed: true` response header. Same-key-different-body returns 400 `idempotency_key_in_use`. 24-hour TTL matches Stripe. Cache only stores 2xx responses \u2014 4xx/5xx pass through so callers can fix bugs and retry. Helper returns nil/throws on missing identifier (no silent random fallback). Cross-SDK parity is CI-pinned: deriveForPurchase('apple', 'eyJ.jws.sig') MUST equal 'a66b1640-efaf-bb4d-1261-6650033bf111' on every SDK.",appliesTo:["web","node","react-native","swift","android","backend"],codeRef:["sdks/web/src/idempotency-key.ts","sdks/web/src/crossdeck.ts","sdks/react-native/src/idempotency-key.ts","sdks/react-native/src/crossdeck.ts","sdks/node/src/idempotency-key.ts","sdks/node/src/crossdeck-server.ts","sdks/swift/Sources/Crossdeck/IdempotencyKey.swift","sdks/swift/Sources/Crossdeck/Crossdeck.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/IdempotencyKey.kt","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt","backend/src/lib/idempotency-response-cache.ts","backend/src/api/v1-purchases.ts"],testRef:[{file:"sdks/web/tests/idempotency-key.test.ts",name:"cross-SDK oracle \u2014 apple JWS pins canonical vector"},{file:"sdks/web/tests/idempotency-key.test.ts",name:"is deterministic: same body twice -> identical key"},{file:"sdks/web/tests/idempotency-key.test.ts",name:"same identifier under different rails -> different keys"},{file:"sdks/web/tests/idempotency-key.test.ts",name:"never silently falls back to a random key on missing identifier"},{file:"sdks/react-native/tests/idempotency-key.test.ts",name:"is deterministic"},{file:"sdks/react-native/tests/idempotency-key.test.ts",name:"cross-SDK oracle \u2014 apple JWS pins canonical vector"},{file:"sdks/node/tests/idempotency-key.test.ts",name:"is deterministic"},{file:"sdks/node/tests/idempotency-key.test.ts",name:"rail namespacing prevents cross-rail collisions"},{file:"sdks/node/tests/idempotency-key.test.ts",name:"apple JWS produces the canonical pinned UUID across all 5 SDKs"},{file:"backend/tests/unit/idempotency-response-cache.test.ts",name:"is deterministic for the same input"},{file:"backend/tests/unit/idempotency-response-cache.test.ts",name:"injects idempotent_replay: true into a JSON object body"},{file:"backend/tests/unit/idempotency-response-cache.test.ts",name:"matches Stripe's 24-hour idempotency window"},{file:"sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",name:"test_crossSdkOracle_appleJWS"},{file:"sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",name:"test_railNamespacing_preventsCrossRailCollisions"},{file:"sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",name:"test_missingIdentifier_returnsNil"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",name:"cross-SDK oracle for apple JWS"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",name:"rail namespacing prevents cross-rail collisions"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",name:"missing identifier returns null - never silent random fallback"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 2.2.a + 2.2.b + 2.2.c",bundledIn:"@cross-deck/web@1.6.4",runtimeVerified:!0},{id:"init-reentry-drains-prior-queue",pillar:"lifecycle",status:"enforced",claim:"Web + RN init() re-entry drains the prior EventQueue's pending setTimeout BEFORE replacing this.state. Pre-v1.4.0 the teardown handled autoTracker/webVitals/errors/unloadFlush but NOT events, so the prior queue's timer would fire AFTER the state swap \u2014 sending old-init events against new-init http + identity references (cross-identity leak during HMR / config swap / multi-tenant SDK shells). The teardown CANNOT call persistent.clear() \u2014 the durable queue belongs to the SDK lifetime, not the init() lifetime, and a survived crash mid-flush re-hydrates on the next init.",appliesTo:["web","react-native"],codeRef:["sdks/web/src/crossdeck.ts","sdks/react-native/src/crossdeck.ts"],testRef:[{file:"sdks/web/tests/init-reentry.test.ts",name:"re-init drains the prior queue's pending timer before swapping state"},{file:"sdks/web/tests/init-reentry.test.ts",name:"re-init does NOT wipe the durable event store"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 5.5",bundledIn:"@cross-deck/web@1.6.4",runtimeVerified:!1},{id:"per-user-cache-isolation",pillar:"entitlements",status:"enforced",claim:"Every identify(userId) switches the entitlement cache to a physically separate per-user storage slot \u2014 `crossdeck:entitlements:<sha256(userId)>` \u2014 and unconditionally wipes the in-memory snapshot. A user-switch on a shared device CANNOT cross-read a prior user's cached entitlements, even if the in-memory clear is somehow skipped, because the storage keys are physically separate. reset() wipes every per-user slot via the persisted index.",appliesTo:["web","react-native","swift","android"],codeRef:["sdks/web/src/entitlement-cache.ts","sdks/web/src/hash.ts","sdks/web/src/crossdeck.ts","sdks/react-native/src/entitlement-cache.ts","sdks/react-native/src/hash.ts","sdks/react-native/src/crossdeck.ts","sdks/swift/Sources/Crossdeck/EntitlementCache.swift","sdks/swift/Sources/Crossdeck/IdempotencyKey.swift","sdks/swift/Sources/Crossdeck/Crossdeck.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EntitlementCache.kt","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/IdempotencyKey.kt","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt"],testRef:[{file:"sdks/web/tests/entitlement-cache-isolation.test.ts",name:"identify(B) makes A's entitlements unreachable from in-memory"},{file:"sdks/web/tests/entitlement-cache-isolation.test.ts",name:"clearAll() removes every per-user storage key plus the index"},{file:"sdks/web/tests/entitlement-cache-isolation.test.ts",name:"a second cache instance reading A's storage suffix CANNOT see B's data"},{file:"sdks/react-native/tests/entitlement-cache-isolation.test.ts",name:"identify(B) makes A's entitlements unreachable from in-memory"},{file:"sdks/react-native/tests/entitlement-cache-isolation.test.ts",name:"removes every per-user storage key plus the index"},{file:"sdks/swift/Tests/CrossdeckTests/EntitlementCacheIsolationTests.swift",name:"test_identifyB_makesAEntitlementsUnreachable"},{file:"sdks/swift/Tests/CrossdeckTests/EntitlementCacheIsolationTests.swift",name:"test_identifiedWritesLandUnderPerUserSha256Key"},{file:"sdks/swift/Tests/CrossdeckTests/EntitlementCacheIsolationTests.swift",name:"test_clearAll_removesEveryPerUserStorageKeyPlusIndex"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",name:"identified writes land under per-user sha256 key"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",name:"identify B makes A entitlements unreachable from in-memory"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",name:"clearAll removes every per-user storage key plus the index"},{file:"sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",name:"a fresh cache bound to A's key CANNOT read B's blob"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 1.3 (web/RN) + dogfood-gap fix (swift + android)",bundledIn:"@cross-deck/web@1.6.4",runtimeVerified:!0},{id:"sdk-error-codes-catalogue",pillar:"errors",status:"enforced",claim:"Web + Node SDK error-codes catalogues include EVERY backend-emitted ApiErrorCode with a description + resolution. Pre-v1.4.0 the catalogues documented codes the SDK threw ITSELF but ZERO backend codes \u2014 a developer hitting `invalid_api_key` / `origin_not_allowed` / `bundle_id_not_allowed` / `env_mismatch` / `idempotency_key_in_use` etc. got `undefined` from getErrorCode() and had to hunt for guidance. v1.4.0 backfills the catalogue from backend/src/api/v1-errors.ts so every wire code has a canonical 'what does this mean / what should I do' answer Stripe-style.",appliesTo:["web","node"],codeRef:["sdks/web/src/error-codes.ts","sdks/node/src/error-codes.ts","sdks/web/src/_contract-verifiers.ts","backend/src/api/v1-errors.ts"],testRef:[{file:"sdks/web/tests/contract-verifiers.test.ts",name:"sdk-error-codes-catalogue covers every backend wire code with remediation"},{file:"sdks/web/tests/error-codes-backfill.test.ts",name:"includes backend code"},{file:"sdks/web/tests/error-codes-backfill.test.ts",name:"invalid_api_key resolution points at the dashboard"},{file:"sdks/web/tests/error-codes-backfill.test.ts",name:"idempotency_key_in_use resolution mentions Stripe-grade contract"},{file:"sdks/web/tests/error-codes-backfill.test.ts",name:"identity-lock codes carry permission_error type"},{file:"sdks/web/tests/error-codes-backfill.test.ts",name:"no entry has an empty description or resolution"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 6.2",bundledIn:"@cross-deck/web@1.6.4",runtimeVerified:!0},{id:"super-property-merge-precedence",pillar:"analytics",status:"enforced",claim:"Every Crossdeck SDK merges event properties with the precedence device < super < caller (caller-supplied values win over registered super-properties, which win over auto-attached device info). Pre-v1.4.0 Swift had it INVERTED (super < device < caller \u2014 device clobbered super), so a `register('plan', 'pro')` super-property was silently overridden by auto-attached device fields whenever keys collided. Cross-SDK funnel queries on super-property keys returned different answers per platform.",appliesTo:["web","swift"],codeRef:["sdks/web/src/super-properties.ts","sdks/web/src/_contract-verifiers.ts","sdks/swift/Sources/Crossdeck/EventPropertyMerge.swift","sdks/swift/Sources/Crossdeck/Crossdeck.swift"],testRef:[{file:"sdks/web/tests/contract-verifiers.test.ts",name:"super-property-merge-precedence verifies caller > super > device"},{file:"sdks/swift/Tests/CrossdeckTests/EventPropertyMergeTests.swift",name:"test_super_overrides_device"},{file:"sdks/swift/Tests/CrossdeckTests/EventPropertyMergeTests.swift",name:"test_caller_overrides_super"},{file:"sdks/swift/Tests/CrossdeckTests/EventPropertyMergeTests.swift",name:"test_full_precedence_chain"},{file:"sdks/swift/Tests/CrossdeckTests/EventPropertyMergeTests.swift",name:"test_matchesWebNodeRNPrecedence"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 3.2",bundledIn:"@cross-deck/web@1.6.4",runtimeVerified:!0},{id:"sync-purchases-funnel-parity",pillar:"analytics",status:"enforced",claim:"Manual syncPurchases() emits a `purchase.completed` analytics event on success across ALL SDKs (Web / Node / RN / Swift / Android). Pre-v1.4.0 only Swift/Android auto-track emitted it \u2014 Web/Node/RN manual calls + Swift/Android manual calls fired ZERO analytics. Schema mirrors the auto-track event name + rail/productId/subscriptionId so cross-platform funnels reconcile on every payment path. When the backend short-circuits via the v1.4.0 idempotency cache, the event also carries `idempotent_replay: true`.",appliesTo:["web","node","react-native","swift","android"],codeRef:["sdks/web/src/crossdeck.ts","sdks/node/src/crossdeck-server.ts","sdks/react-native/src/crossdeck.ts","sdks/swift/Sources/Crossdeck/Crossdeck.swift","sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt"],testRef:[{file:"sdks/web/tests/sync-purchases-funnel.test.ts",name:"emits purchase.completed after a successful sync"},{file:"sdks/web/tests/sync-purchases-funnel.test.ts",name:"carries idempotent_replay=true when backend replied from cache"}],registeredAt:"2026-05-26",firstRegisteredIn:"bank-grade reconciliation v1.4.0 \u2014 phase 3.5",bundledIn:"@cross-deck/web@1.6.4",runtimeVerified:!1}]);var ct={all(){return N.filter(r=>r.status==="enforced")},allIncludingHistorical(){return N},byId(r){return N.find(e=>e.id===r)},byPillar(r){return N.filter(e=>e.pillar===r&&e.status==="enforced")},withStatus(r){return N.filter(e=>e.status===r)},sdkVersion:at,bundledIn:ot,findByTestName(r){return N.find(e=>e.testRef.some(t=>t.name===r))}};return gt(Pr);})();
3
3
  //# sourceMappingURL=crossdeck.umd.min.js.map