@tinkerlandai/longplay-sdk 0.10.13 → 0.10.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/{ai-usage-C-OZBxgW.d.ts → ai-usage-C3dCagmQ.d.ts} +1 -1
  3. package/dist/{api-Bf_aRlXs.d.ts → api-Cefn6AaL.d.ts} +17 -2
  4. package/dist/{chunk-RK6UEQF2.js → chunk-2ODPDLTX.js} +1 -1
  5. package/dist/{chunk-3JDJD4NY.js → chunk-3WVMD3FK.js} +1 -1
  6. package/dist/{chunk-OBZSDWLC.js → chunk-D5D75HM6.js} +1 -1
  7. package/dist/{chunk-RGWFBLW4.js → chunk-J42MHRU7.js} +1 -1
  8. package/dist/{chunk-KQ4MS4LR.js → chunk-KOGWARWA.js} +2 -2
  9. package/dist/{chunk-AY3DAC2V.js → chunk-NR2M6SNG.js} +1 -1
  10. package/dist/chunk-OEQ2QTPD.js +1 -0
  11. package/dist/{chunk-VQBQAKJD.js → chunk-PNIWWTLM.js} +1 -1
  12. package/dist/{chunk-ADSQZ7T3.js → chunk-WVQM23J4.js} +1 -1
  13. package/dist/{chunk-AHDMDMHB.js → chunk-ZQUUDOHV.js} +1 -1
  14. package/dist/{content-6JUK2IAJ.js → content-M6BANOTZ.js} +1 -1
  15. package/dist/{funnel-local-client-DJq2K7an.d.ts → funnel-local-client-9U-_hkEE.d.ts} +1 -1
  16. package/dist/{funnel-node-evaluation-CJSkUkbv.d.ts → funnel-node-evaluation-DSSSmXHX.d.ts} +2 -0
  17. package/dist/{funnel-process-client-C_UhTH8g.d.ts → funnel-process-client-BaHMeArI.d.ts} +2 -2
  18. package/dist/funnel-runtime-host-HPHUWGIF.js +1 -0
  19. package/dist/index.d.ts +7 -7
  20. package/dist/index.js +1 -1
  21. package/dist/native-shell.js +1 -1
  22. package/dist/openrouter.d.ts +2 -2
  23. package/dist/openrouter.js +1 -1
  24. package/dist/page.js +1 -1
  25. package/dist/{paywall-KSTKKKEA.js → paywall-D3QFOE5C.js} +1 -1
  26. package/dist/react-native.d.ts +5 -5
  27. package/dist/react-native.js +1 -1
  28. package/dist/server.d.ts +6 -6
  29. package/dist/server.js +1 -1
  30. package/dist/visual.js +1 -1
  31. package/package.json +1 -1
  32. package/dist/chunk-YT7TSF3I.js +0 -1
  33. package/dist/funnel-runtime-host-X5AMUCP2.js +0 -1
@@ -1,4 +1,4 @@
1
- import{a as $,b as N,c as J,d as q}from"./chunk-RGWFBLW4.js";import{a as _}from"./chunk-DSPLGTQI.js";import{a as P}from"./chunk-RK6UEQF2.js";import{bb as D}from"./chunk-KQ4MS4LR.js";import{s as C,v as O,x as j}from"./chunk-VSJOHWDL.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
1
+ import{a as $,b as N,c as J,d as q}from"./chunk-J42MHRU7.js";import{a as _}from"./chunk-DSPLGTQI.js";import{a as P}from"./chunk-2ODPDLTX.js";import{bb as D}from"./chunk-KOGWARWA.js";import{s as C,v as O,x as j}from"./chunk-VSJOHWDL.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
2
2
  Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
3
  plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
4
  */function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
@@ -0,0 +1 @@
1
+ import{d as t}from"./chunk-PNIWWTLM.js";import{Za as n}from"./chunk-KOGWARWA.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
@@ -1 +1 @@
1
- import{b as dn,c as fn,d as mn,e as pn}from"./chunk-VSMITXQD.js";import{a as te,b as Y}from"./chunk-OBZSDWLC.js";import{a as m}from"./chunk-OZZMZH7X.js";import{a as ln,b as cn,c as Ce}from"./chunk-RK6UEQF2.js";import{$a as un,Ea as Te,Fa as tn,R as Ge,T as Re,Ta as rn,U as Be,Ua as on,V as je,W as Je,Xa as an,Ya as sn,a as Ue,cb as le,da as Q,ea as ze,fa as B,ga as Ke,ha as Oe,ia as L,ka as Qe,la as Ye,ma as $e,n as ue,na as We,oa as Ze,ua as ne,va as Xe,ya as en,za as nn}from"./chunk-KQ4MS4LR.js";import{B as ve,Ca as He,v as qe,y as ke}from"./chunk-VSJOHWDL.js";function Mn(e){let n=null,r=null,s=0,l=0,y=new Set,f=null,i=null,p=new Set,a=()=>{for(let o of p)try{o()}catch{}},u={attributes:ve.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(o,t)=>{!y.has(o)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(o,structuredClone(t),structuredClone(u.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(o,t)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(o),structuredClone(t),structuredClone(u.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?o=>e.saveStickyBucketAssignmentDoc(structuredClone(o)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},c=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function d(o,t=new Set){return y.has(o)?!f||!f.features[o]||["unknownFeature","cyclicPrerequisite"].includes(f.features[o].source):t.has(o)?!1:(t.add(o),(n?.features[o]?.rules??[]).some(I=>[...I.parentConditions??[],...(I.tracks??[]).flatMap(b=>b.experiment.parentConditions??[])].some(b=>d(b.id,t))))}let h=o=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return f?.expiresAt&&Date.parse(f.expiresAt)<=Date.now()&&(f=null,u.features=n.features),y.has(o)?!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now()?c():structuredClone(f.features[o]??c()):e.evaluateRemote&&(u.attributes?.merchandise||u.attributes?.merchandiseId)&&!f||d(o)?c():structuredClone(ke(o,u))};async function A(){if(!n||!y.size&&!u.attributes?.merchandise&&!u.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(y.size)throw new Error("Remote Feature evaluation requires a server loader");return}let o=l;if(i?.revision===o)return i.loading;let t=s,I=n,b=[...y],S=(async()=>{let P=Je.parse(await e.evaluateRemote({attributes:structuredClone(u.attributes),features:b}));if(!(t!==s||o!==l||I!==n)){if(e.assertUsable?.(I.generation),P.generation!==I.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(b.some(v=>!Object.hasOwn(P.features,v))||Object.keys(P.features).some(v=>!y.has(v)))throw new Error("Invalid remote Feature results");if(u.attributes?.merchandise||u.attributes?.merchandiseId){if(!P.merchandiseContext)throw new Error("Server did not resolve merchandise context");u.attributes=ve.parse({...u.attributes,...P.merchandiseContext})}f=structuredClone(P),u.features={...I.features,...Object.fromEntries(Object.entries(f.features).map(([v,D])=>[v,{defaultValue:D.value}]))},a()}})();i={revision:o,loading:S};try{await S}finally{i?.loading===S&&(i=null)}}function F(){A().catch(o=>{try{e.onError?.(o)}catch{}})}async function T(){if(r)return r;let o=s,t=(async()=>{let I=await e.load(),b="remoteFeatures"in I?Be.parse(I):null,S=b??Re.parse(I);if(S.scope.projectId!==e.scope.projectId||S.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(o!==s)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===S.generation){let{evaluatedAt:v,expiresAt:D,...V}=n,{evaluatedAt:M,expiresAt:H,...k}=S;if(L(V)!==L(k))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=S.evaluatedAt,n.expiresAt=S.expiresAt,a(),(!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now())&&F(),structuredClone(n)}let P=new Set(b?.remoteFeatures??[]);if([...P].some(v=>Object.hasOwn(S.features,v)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in S&&!n.analyticsConfig.experimentViewsEnabled&&b?.analyticsConfig.experimentViewsEnabled&&u.trackedExperiments?.clear(),n=structuredClone(S),y=P,f=null,i=null,l++,u.features=n.features,u.savedGroups=qe(n.savedGroups),u.trackedFeatureUsage={},a(),F(),structuredClone(n)})();r=t;try{return await t}finally{r===t&&(r=null)}}return{init:T,refresh:T,refreshRemote:A,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(o){return p.add(o),()=>{p.delete(o)}},setAttributes(o){let t=ve.parse(o);(u.attributes?.merchandise||u.attributes?.merchandiseId||o.merchandise||o.merchandiseId)&&u.trackedExperiments?.clear(),u.attributes=t,l++,f=null,i=null,u.features=n?.features??{},u.trackedFeatureUsage={},a(),F()},evalFeature:h,isOn(o){return h(o).on},isOff(o){return h(o).off},getFeatureValue(o,t){let I=h(o).value;return structuredClone(I===null?t:I)},reset(){s++,l++,r=null,i=null,n=null,f=null,y.clear(),u.features={},u.savedGroups={},u.stickyBucketAssignmentDocs={},u.attributes={},u.trackedFeatureUsage={},u.trackedExperiments?.clear(),a()}}}function gn(e){let n,r,s=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),l=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,r=e.locks??globalThis.navigator?.locks,!n||!r||!globalThis.crypto?.subtle)throw s();let i=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??le).href,e.runToken])),p=new Uint8Array(await crypto.subtle.digest("SHA-256",i));return"indiana.funnel.commands.v1."+Array.from(p,a=>a.toString(16).padStart(2,"0")).join("")});l.catch(()=>{});async function y(i){try{let p=await l;return await r.request(p,{mode:"exclusive"},()=>i(p))}catch(p){throw p instanceof m?p:s()}}function f(i){let p=n.getItem(i);if(p===null)return{revision:0,entry:null};if(p.length>1048576)throw s();let a=JSON.parse(p);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw s();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>y(f),write:(i,p)=>y(a=>{if(f(a).revision!==i)return null;if(!Number.isSafeInteger(i+1))throw s();return n.setItem(a,JSON.stringify({revision:i+1,entry:p})),i+1})}}function be(e,n){let r=en.safeParse(n);if(!r.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let s=r.data;if(e.scope&&(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return s}async function Pe(e,n){let r=We.parse(n),{artifact:s,environmentId:l}=r.content,y=new te(e.baseUrl??le).origin,f=new te(s.url,y);if(f.origin!==y||f.username||f.password||f.search||f.hash||f.pathname!==`/api/v1/configuration/${l}/artifacts/${s.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let i=new AbortController,p,a=new Promise((c,d)=>{p=setTimeout(()=>{let h=new m("TIMEOUT","Public Paywall read timed out");i.abort(h),d(h)},B.initializationMs)}),u=(async()=>{let c=await(e.fetch??globalThis.fetch)(f,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:i.signal});if(i.signal.aborted&&(c.body?.cancel().catch(()=>{}),i.signal.throwIfAborted()),!c.ok||!c.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(c.headers.get("content-length"))>s.byteLength)throw c.body?.cancel().catch(()=>{}),new m("INVALID_RESPONSE","Public Paywall is unavailable");let d=await ln(c,s.byteLength,{signal:i.signal,error:h=>new m("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ce(d,s))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return Ze(r,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)))})();try{return await Promise.race([u,a])}finally{clearTimeout(p)}}var _e=(e,n)=>new m(e,n);function Xn(e){return sn(e,_e)}async function De(e,n,{predict:r=!0}={}){let s=n.instruction;if(s?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==s.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let l=null,y;if(r)try{let f=await e.funnel(n.source.id,n.source.versionId);y=f.manifest.generation,l=An(e,n,f)}catch{l=null}return y??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:s.policyRevision,generation:y},prediction:l}}function An(e,n,r){let s=n.instruction;if(s?.type!=="evaluate_segment"||!r.growth||r.control.evaluationMode!=="local"||r.control.evaluationRevision!==s.policyRevision)return null;let{analyticsConfig:l,remoteFeatures:y,...f}=r.growth,i=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:s.policyRevision,document:r.document,payload:Re.parse(f)}),p=Nn(i,r.document,{...n,...s}),a=p.steps.at(-1),u=p.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+p.steps.length-1}:null);return u?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:u.nodeId,visit:u.visit,terminal:!p.boundary}:null}function Nn(e,n,r){return un(e,n,r,_e)}import{z as j}from"zod";var yn=Q.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=j.strictObject({schemaVersion:j.literal(1),scope:Ue,runId:j.uuid(),funnelId:j.uuid(),versionId:j.uuid(),processBindingIds:j.record(j.uuid(),j.uuid().nullable()).optional(),command:yn.optional(),closeCommand:yn.refine(e=>e.operation==="close").optional(),purchase:j.strictObject({receiptId:j.uuid(),operationId:j.uuid(),generation:j.number().int().nonnegative()}).optional(),closed:j.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),q=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Se=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function In(e){let n=0,r=null,s=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),l=Promise.resolve();async function y(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function f(a){let u=l.then(a);return l=u.catch(()=>{}),u}async function i(a){for(let u=0;u<4;u++){let c=await y();if(c.entry&&r!==null&&s(c.entry)!==r)throw q();let d=a(c.entry,c.revision);if(Se(c.entry,d)){n=c.revision;return}let h=await e.write(c.revision,d);if(h!==null){if(!Number.isSafeInteger(h)||h<=c.revision)throw q();n=h;return}}throw q()}function p(a,u){if(!a||!u)return a;if(a.processBindingIds&&Object.hasOwn(a.processBindingIds,u)){let c={...a.processBindingIds};delete c[u],a={...a,processBindingIds:c}}return a.command?.requestId===u?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand?.requestId===u?{...a,closeCommand:void 0}:a}return{bind(a){let u=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(r!==null&&r!==u)throw q();r=u},async load(){let a=await y();return n=a.revision,r=a.entry?s(a.entry):null,a.entry},retain(a){let u=wn.parse(a),c=u.command;return!c||r!==null&&s(u)!==r?Promise.reject(q()):(r??=s(u),f(()=>i((d,h)=>{if(d&&!Se(s(d),s(u)))throw q();if(d&&u.processBindingIds){for(let[A,F]of Object.entries(u.processBindingIds))if(d.processBindingIds&&Object.hasOwn(d.processBindingIds,A)&&d.processBindingIds[A]!==F)throw q();d={...d,processBindingIds:{...d.processBindingIds,...u.processBindingIds}}}if(!d){if(h!==n&&c.operation!=="close")throw q();return u}if(!d.command)return{...d,command:c,...c.operation==="close"?{closed:!0}:{}};if(c.operation==="close"&&d.command.operation!=="close"){if(d.command.requestId===c.requestId||d.closeCommand&&!Se(d.closeCommand,c))throw q();return{...d,closeCommand:c,closed:!0}}if(!Se(d.command,c))throw q();return d})))},observePurchase(a,u,c,d){return f(()=>i((h,A)=>{if(!h&&A!==n||h&&s(h)!==s({...a,schemaVersion:1}))throw q();if(h?.purchase&&h.purchase.generation>u.generation)return p(h,d);if(h?.purchase&&h.purchase.generation===u.generation&&h.purchase.operationId!==u.operationId)throw q();return c?!h?.purchase||h.purchase.operationId!==u.operationId?p(h,d):p(h.command?{...h,purchase:void 0}:null,d):p({schemaVersion:1,...a,...h,purchase:u},d)}))},settle(a){return f(()=>i(u=>p(u,a)))}}}function lt(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ce(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((l,y)=>ce(l,n[y]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let r=Object.entries(e),s=Object.entries(n);return r.length===s.length&&r.every(([l,y])=>Object.hasOwn(n,l)&&ce(y,Reflect.get(n,l)))}function hn(e,n){let r=n&&{...n},s=null,l=0,y=new AbortController;function f(){l++,y.abort(new m("IDENTITY_CHANGED","Run identity changed")),y=new AbortController}let i=!1,p,a=0,u=new Set;return{get scope(){return r},bindScope(c){if(r&&(r.projectId!==c.projectId||r.environment!==c.environment))throw new m("SCOPE_MISMATCH","Run scope changed");r??={...c}},get view(){return s},get generation(){return l},get signal(){return y.signal},get disposed(){return i},get customerToken(){return p},get readSequence(){return a},nextRead(){return++a},assertCurrent(c,d="Run identity changed during the request"){if(c!==l||i)throw new m("IDENTITY_CHANGED",d)},assertRun(c){if(s&&(c.id!==s.id||c.source.type!==s.source.type||c.source.id!==s.source.id||c.source.versionId!==s.source.versionId||c.locale!==s.locale||!ce(c.parameters,s.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&c.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(c,d,h,A,F){if(!(c.operation==="review"&&s&&s!==h&&d.run.revision<=s.revision)&&!(s&&d.run.revision===s.revision&&A!==void 0&&A<a)&&(c.operation==="review"&&!d.run.stopped&&["running","waiting"].includes(d.run.status)&&s&&d.run.nodeId===s.nodeId&&d.run.visit===s.visit&&d.run.revision===s.revision&&(d.run.screen=s.screen,(s.paywall?.quote?.operationId===d.review?.activeOperationId||!s.paywall?.quote&&d.review?.activeOperationId===null)&&(d.run.paywall=s.paywall)),!(s?.paywall&&d.run.paywall&&s.paywall.receiptId===d.run.paywall.receiptId&&(d.run.paywall.selectionGeneration??0)<(s.paywall.selectionGeneration??0)))){if(!s||d.run.revision>=s.revision)s=d.run;else if(!F)return;if(s)for(let T of u)try{T(structuredClone(s))}catch{}}},identify(c){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!ue.test(c))throw new m("INVALID_TOKEN","Customer credential required");f(),p=c},subscribe(c){return u.add(c),()=>u.delete(c)},reset(){i||(i=!0,f(),p=void 0,s=null,u.clear())}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function yt(e,n,r="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!re.test(e))throw new m("INVALID_TOKEN",r)}function wt(e){let n=Y(e);return n.identify(e.apiKey),n}function $(e){let{customerToken:n,...r}=e;return r}var On=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function vn({journal:e,state:n,call:r,processIdentity:s}){let l=null,y=null,f=!1,i={command:null,close:null},p=new Set,a,u=null,c=e?e.load().then(o=>{if(n.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(u=o,!o)return;if(s){if([o.command,o.closeCommand].some(I=>I&&!Object.hasOwn(o.processBindingIds??{},I.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");s.restore(o.processBindingIds??{})}if(n.scope&&(o.scope.projectId!==n.scope.projectId||o.scope.environment!==n.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=o.purchase,f=o.closed===!0,!o.command)return;let t=o.command;l=t.operation==="close"?null:t,y=t.operation==="close"?t:o.closeCommand?.operation==="close"?o.closeCommand:null,y&&(f=!0);for(let I of[l,y])I&&p.add(I.requestId)}):Promise.resolve();c.catch(()=>{});async function d(o){e&&await c;let t=n.generation;if(e){if(!n.view||!n.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:$(o),...s?{processBindingIds:{[o.requestId]:s.binding(o.requestId)}}:{}})}if(t!==n.generation||l!==o&&y!==o)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let I=p.has(o.requestId);p.add(o.requestId);try{return await r(o)}catch(b){throw t===n.generation&&(l===o||y===o)&&!I&&!On(b)&&(e&&await e.settle(o.requestId),t===n.generation&&T(o)),b}}function h(o){let t=Q.parse(o);if(t.operation==="start"||t.operation==="get"||t.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(f&&t.operation!=="close"){if(l?.requestId===t.requestId)return F(t.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(t.operation==="close"){if(l?.requestId===t.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(f=!0,y&&JSON.stringify($(y))!==JSON.stringify($(t)))throw new m("COMMAND_PENDING","Retry the original Close");return y??=t,i.close?i.close:A(y,"close")}if(l){if(JSON.stringify($(l))!==JSON.stringify($(t)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(i.command)return i.command}else l=t;return A(l,"command")}function A(o,t){let I=d(o);i[t]=I;let b=()=>{i[t]===I&&(i[t]=null)};return I.then(b,b),I}function F(o){return r({operation:"get",settlementRequestId:o})}function T(o){return!o||l!==o&&y!==o?!1:(l===o&&(l=null),y===o&&(y=null),p.delete(o.requestId),!l&&!y&&(u=null),!0)}return{ready:c,get pending(){return l},get closing(){return y},get closeRequested(){return f},get inFlight(){return i.command},get closeFlight(){return i.close},get purchase(){return a},assertBinding(o){if(u&&(o.run.id!==u.runId||o.run.source.id!==u.funnelId||o.run.source.versionId!==u.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(o,t,I,b){let S=o.operation==="get"?o.settlementRequestId:"requestId"in o&&o.operation!=="start"?o.requestId:void 0,P=S&&t.settlement?.state==="settled"&&t.run.pendingRequest?.requestId!==S&&(o.operation==="get"||!f||o.operation==="close"||!["running","waiting"].includes(t.run.status))?S:void 0,v=l?.requestId===P?l:y?.requestId===P?y:void 0;e?.bind({scope:t.scope,runId:t.run.id,funnelId:t.run.source.id,versionId:t.run.source.versionId});let D=t.run.paywall,V=D??t.purchase,M=V?.operation,H=t.settlement&&(!D||D.purchaseRequestId===t.settlement.requestId)&&(!a||a.operationId===t.settlement.operationId)?t.settlement:void 0,k=M?.operationId??V?.quote?.operationId??H?.operationId,J=V?.receiptId??H?.receiptId,de=D?.selectionGeneration??a?.generation??0;if(e&&k&&J&&o.operation!=="review"&&(!n.view||t.run.revision>=n.view.revision)&&(b===void 0||b>=n.readSequence)&&(!a||de>=a.generation)){let Z={receiptId:J,operationId:k,generation:de},fe=M?.status==="complete"||V?.canReselect===!0;await e.observePurchase({scope:t.scope,runId:t.run.id,funnelId:t.run.source.id,versionId:t.run.source.versionId},Z,fe,P),n.assertCurrent(I),(!a||Z.generation>=a.generation)&&(b===void 0||b>=n.readSequence)&&(fe?a?.operationId===Z.operationId&&(a=void 0):a=Z)}else e&&P&&await e.settle(P);return n.assertCurrent(I),P?T(v):!1},stop(){f=!0},submit:h,settle:F,reset(){f=!0,l=null,y=null,a=void 0,u=null,i.close=null,p.clear(),i.command=null}}}function Rn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Y({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),r=hn(e.funnelId,e.scope??e.configuration?.scope),s=e.session?.subscribeIdentity(a),l=null,y=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?gn(e):void 0),f=y&&In(y),i=vn({journal:f,state:r,call:u,processIdentity:e.process});async function p(t){if(e.process)return e.process.request(t);let I=r.generation;r.assertCurrent(I);let b=performance.now()+(e.timeoutMs??35e3),S=r.customerToken??("customerToken"in t?t.customerToken:void 0);if(e.session){let D=r.signal,V,M=()=>{},H=new Promise((k,J)=>{M=()=>J(D.reason),D.addEventListener("abort",M,{once:!0}),V=setTimeout(()=>J(new m("TIMEOUT","Longplay request timed out")),Math.max(1,b-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(r.assertCurrent(I),e.session.access())),H])}finally{clearTimeout(V),D.removeEventListener("abort",M)}}r.assertCurrent(I);let P={...t,...S?{customerToken:S}:{}},v=t.operation==="page_experiments"?Te.parse(P):Q.parse(P);return n.requestWithCredential("funnels",v,e.runToken,{headers:e.serverKey&&!S?{[nn]:e.serverKey}:void 0,timeoutMs:Math.max(1,b-performance.now())})}function a(){s?.(),r.reset(),i.reset(),l=null,n.dispose()}async function u(t,I){let b=r.generation,S=()=>r.assertCurrent(b);f&&await i.ready,S();let P=r.view,v=be(e,await p(t));if(t.operation==="review"&&!v.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(S(),v.runToken&&v.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let D=t.operation==="get"?t.settlementRequestId:"requestId"in t&&t.operation!=="start"?t.requestId:void 0;if(D&&v.settlement?.requestId!==D)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(v),r.assertRun(v.run),r.bindScope(v.scope);let V=await i.observe(t,v,b,I);return!v.run.stopped&&["running","waiting"].includes(v.run.status)&&t.operation==="get"&&t.settlementRequestId||(S(),["running","waiting"].includes(v.run.status)||i.stop(),r.publish(t,v,P,I,V)),v}let c=i.submit,d=null,h=new WeakMap;function A(t){let I=h.get(t);if(I)return I;let b=T(t);return h.set(t,b),b}let F=!1;async function T(t){let I=await t;if(I.run.instruction?.type!=="evaluate_segment")return I;if(d)return d;F=!0;let b=r.generation,S=(async()=>{for(let P=0;P<32&&I.run.instruction?.type==="evaluate_segment";P++){if(i.pending||i.closeRequested)return I;let v=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:V}=await De(e.configuration,v,{predict:!1});if(b!==r.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(r.view&&(r.view.revision!==v.revision||r.view.visit!==v.visit||r.view.nodeId!==v.nodeId))return u({operation:"get"});let M=!0;De(e.configuration,v).then(({prediction:H})=>{M&&b===r.generation&&!i.closeRequested&&r.view?.id===v.id&&!r.view.stopped&&r.view.nodeId===v.nodeId&&r.view.visit===v.visit&&r.view.revision===v.revision&&(l=H)}).catch(()=>{});try{I=await c({operation:"commit_segment",requestId:Xe(v.id,v.visit,`segment:${v.revision}`),nodeId:v.nodeId,visit:v.visit,revision:v.revision,...V})}finally{M=!1,l=null}}}return I})();d=S;try{return await S}finally{d===S&&(d=null)}}let o={get configuration(){return F?e.configuration:void 0},get configurationReady(){return!0},get view(){return r.view?structuredClone(r.view):null},get pendingCommand(){let t=i.closing??i.pending;return t?structuredClone($(t)):null},get pendingCommands(){return[i.pending,i.closing].filter(t=>t!==null).map(t=>structuredClone($(t)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get prediction(){let t=r.view;return l&&t&&!t.stopped&&["running","waiting"].includes(t.status)&&t.id===l.runId&&t.nodeId===l.from.nodeId&&t.visit===l.from.visit&&t.revision===l.from.revision&&!i.closeRequested?structuredClone(l):null},settle:i.settle,get webViewUrl(){return"bundled"},resolvePaywall(t){return Pe(e,t)},async pageExperiments(t,I=[]){let b=r.generation;r.assertCurrent(b);let S=r.view?.id;if(!S)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let P=tn.parse(await p(Te.parse({operation:"page_experiments",release:t,usedReceiptIds:I})));if(r.assertCurrent(b),P.runId!==S||P.scope.projectId!==r.scope?.projectId||P.scope.environment!==r.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return P},review(t){return u({operation:"review",...t?{receiptId:t}:{}},r.nextRead())},async get(t,I){f&&await i.ready,I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let b=r.nextRead();return A(u({operation:"get",...t?{data:t}:{},...I?{purchase:I}:{}},b))},resume(t=r.view?.pendingRequest?.requestId){return t?i.closeRequested?o.settle(t):i.pending?.requestId===t?A(c(i.pending)):A(c({operation:"resume",requestId:t})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(t){return A(c(t))},retry(){return i.closeFlight?i.closeFlight:i.closing?c(i.closing):i.closeRequested&&i.pending?o.settle(i.pending.requestId):i.inFlight?A(i.inFlight):i.pending?A(c(i.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(t){r.identify(t),l=null,n.reset()},subscribe:r.subscribe,reset:a};return o}import{ZodError as Tn}from"zod";function Cn(e,n,r,s){try{return e.parse(n)}catch(l){throw s&&l instanceof Tn?new m(r,s):l}}async function Ee(e,n,r,s={},l){let y=typeof s=="function"?{}:s,f=Cn(n.request,r,"INVALID_REQUEST",y.request);try{let i=await e(n.path,f,n.method,l),p=typeof s=="function"?s:s.parseResponse;return p?p(n.response,i):Cn(n.response,i,"INVALID_RESPONSE",y.response)}catch(i){throw i instanceof m&&f!==null&&typeof f=="object"&&"requestId"in f&&typeof f.requestId=="string"&&(i.commandRequestId??=f.requestId),i}}async function jt(e,n){if(!ue.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),s=Y(e);e.session||s.identify(n.customerToken);let l=null,y=!1,f=null,i=null,p=null,a=null;function u(){if(y)throw new m("IDENTITY_CHANGED","Paywall is closed")}async function c(){u();let F=ne.resolvePaywall,T=await Ee(s.request,F,{...r,selector:l?{type:"version",versionId:l.id}:r.selector}),o=await Pe(e,T.paywall);if(u(),n.paywallVersionId?o.id!==n.paywallVersionId:o.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(l&&(!dn(o,l)||o.paywallId!==l.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return l=o,structuredClone(l)}async function d(F){if(u(),a&&F!=="read")throw new m("COMMAND_PENDING","Wait for the original quote");if(!f)throw new m("INVALID_REQUEST","A quoted purchase is required");let T=f,o=F==="read"?ne.readSubscriptionOperation:ne.attach,t=await Ee(s.request,o,{operationId:T.operationId,...F==="read"?{}:{intent:F}});return fn(t.operation,{operationId:T.operationId,currency:r.commerce.currency},"The purchase operation changed"),u(),f?.operationId!==T.operationId?structuredClone(t.operation):(i=pn(i,t.operation),structuredClone(i))}let h={get view(){return l?structuredClone(l):null},get quote(){return f?structuredClone(f):null},get operation(){return i?structuredClone(i):null},get webViewUrl(){return"bundled"},refresh:c,async preview(F){if(u(),!l)throw new m("INVALID_REQUEST","Load the Paywall first");let T=l.document.buttons[F.actionId];if(T?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let o=Ge(T.product,F.selection,l.capabilities);if(!o)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let t=He(l.document.screen,o,F.selection,l.capabilities),I=ne.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:F.requestId,plans:[{productVersionId:o,...Object.keys(t).length?{featureQuantities:t}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...F.offerId?{offerId:F.offerId}:{},...F.nativeOffer?{nativeOffer:F.nativeOffer}:{}}),b=JSON.stringify(I);if(p&&p!==b&&(a||!i||i.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(p===b){if(a)return a;if(f)return structuredClone(f)}p!==b&&(f=null,i=null),p=b;let S=(async()=>{let P=ne.previewAttach,v=await Ee(s.request,P,I);return u(),mn(v.quote,{productVersionId:o,featureQuantities:t,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),f=v.quote,i=null,structuredClone(f)})();a=S;try{return await S}finally{a===S&&(a=null)}},confirm:()=>d("confirm"),cancel:()=>d("cancel"),read:()=>d("read"),destroy(){y||(y=!0,A?.(),s.dispose(),l=null,f=null,i=null,p=null)}},A=e.session?.subscribeIdentity(h.destroy);try{return await c(),h}catch(F){throw h.destroy(),F}}import{z as Ln}from"zod";import{z as ge}from"zod";var _n=ge.record(ge.string().regex(/^[a-f0-9]{64}$/),ge.strictObject({at:ge.number(),text:ge.string()})),oe=2*1048576,Dn=100;function xn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function bn(e,n){let r=n===void 0?xn():n,s=new Map,l=0,y=!1,f=!1,i,p;async function a(c){if(!r)return null;let d;try{let h=await Promise.race([Promise.resolve().then(()=>r.getItem(c)),new Promise(A=>{d=setTimeout(()=>A(null),Dn)})]);return typeof h=="string"&&h.length<=oe&&new TextEncoder().encode(h).byteLength<=oe?h:null}catch{return null}finally{clearTimeout(d)}}function u(){if(p)return p;let c=(async()=>{try{let d=await a(`${e}:artifacts`);if(d)return _n.parse(JSON.parse(d))}catch{}return{}})();return p=c,c.finally(()=>{p===c&&(p=void 0)}),c}return{async readManifest(){return a(e)},writeManifest(c){!r||c.length>oe||new TextEncoder().encode(c).byteLength>oe||(i=c,!f&&(f=!0,Promise.resolve().then(async()=>{try{for(;i!==void 0;){let d=i;try{await r.setItem(e,d)}catch{}i===d&&(i=void 0)}}finally{f=!1}})))},async readArtifact(c){let d=(await u())[c],h=Date.now();return d&&h>=d.at&&h-d.at<=B.retentionMs?d.text:void 0},writeArtifact(c,d){if(!r||d.length>oe)return;let h=s.get(c);if(h?.text===d||!h&&s.size>=128)return;let A=new TextEncoder().encode(d).byteLength;l-(h?.byteLength??0)+A>oe||(s.set(c,{text:d,byteLength:A}),l+=A-(h?.byteLength??0),!y&&(y=!0,Promise.resolve().then(async()=>{try{for(;s.size;){let F=new Map(s);try{let T={...await u()},o=Date.now();for(let[S,P]of F)T[S]={at:o,text:P.text};let t={},I=2,b=0;for(let[S,P]of Object.entries(T).sort(([,v],[,D])=>D.at-v.at)){if(P.at>o||o-P.at>B.retentionMs)continue;let v=new TextEncoder().encode(JSON.stringify({[S]:P})).byteLength;I+v>oe||b>=128||(t[S]=P,I+=v,b++)}await r.setItem(`${e}:artifacts`,JSON.stringify(t))}catch{}finally{for(let[T,o]of F)s.get(T)===o&&(s.delete(T),l-=o.byteLength)}}}finally{y=!1}})))}}}var E=(e,n)=>new m(e,n),W=()=>performance.now(),Pn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function nr(e){let n=Ke.parse(e.scope),r=new te(e.origin??le);if(r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.protocol!=="https:"&&!(r.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let s=new Set([r.origin,...(e.assetOrigins??[]).map(w=>{let g=new te(w);if(g.protocol!=="https:"||g.username||g.password||g.search||g.hash||g.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return g.origin})]),l=e.fetch??globalThis.fetch.bind(globalThis),y=`/api/v1/configuration/${n.environmentId}`,f=`indiana:configuration:1:${r.origin}:${L(n)}`,i=bn(f,e.storage),p,a=0,u=0,c=!1,d=!1,h=0,A=0,F,T,o,t,I=0,b=new Set,S=new Set,P=new Map,v=new Map,D=0,V=!1;function M(){for(let w of b)try{w()}catch{}}function H(w){try{e.onError?.(w)}catch{}}let k=()=>!d&&!c&&!!p&&W()<a&&Date.now()<u;function J(){if(!k())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function de(w,g,R){if(!P.has(w)){for(;P.size&&(P.size>=128||D+R>B.maxCacheBytes);){let C=P.entries().next().value;D-=C[1].byteLength,P.delete(C[0])}P.set(w,{text:g,byteLength:R}),D+=R}}function Z(w,g,R){return cn(w,g,{signal:R,error:C=>E("INVALID_RESPONSE",C==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function fe(w){let g=new te(w,r);if(!s.has(g.origin)||g.username||g.password||g.hash||g.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return g.href}async function Fe(w,g,R=!1){let C=await l(fe(w),{method:"GET",credentials:"omit",redirect:"error",cache:R?"default":"no-cache",signal:g,headers:{}});if(C.status===429){let O=C.headers.get("retry-after")??"";I=/^\d+$/.test(O)?Number(O)*1e3:Math.max(0,Date.parse(O)-Date.now())||15e3}if(!C.ok&&C.status!==304)throw E(`CONFIGURATION_HTTP_${C.status}`,"Configuration synchronization failed");return C}function En(w,g,R){let C=Date.parse(w.headers.get("x-indiana-config-validated-at")??""),O=Date.parse(w.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(w.headers.get("date")??""),N=w.headers.get("age"),G=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![C,O,_,G].every(Number.isFinite)||O<=C||O-C>B.maxControlAgeMs||C>_+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(O-C,R.maxControlAgeSeconds*1e3,B.maxControlAgeMs)-Math.max(G,_-C,0)-(W()-g);if(x<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return W()+x}function Ae(){if(clearTimeout(o),clearTimeout(t),d||!b.size)return;k()&&(t=setTimeout(()=>{k()?Ae():M()},Math.max(1,a-W())),Pn(t));let w=A?Math.min(15e3,1e3*2**Math.min(A-1,4)):Math.min(15e3,(p?.policy.refreshIntervalSeconds??15)*1e3);o=setTimeout(()=>{ie().catch(H)},Math.max(I,w*(.8+Math.random()*.2))),Pn(o)}async function ie(){if(d)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(F)return F;let w=h,g=new AbortController;T=g;let R=(async()=>{if(!V){V=!0;try{let he=await i.readManifest();if(he&&!p){let K=Oe.parse(JSON.parse(he));L(K.scope)===L(n)&&(p=K)}}catch{}}g.signal.throwIfAborted();let N=p,G=W(),U=await Fe(y,g.signal);U.status===304&&(!N||!U.headers.has("x-indiana-config-validated-at")||!U.headers.has("x-indiana-config-valid-until")||!U.headers.has("age"))&&(U=await Fe(y,g.signal));let x=U.status===304?N:Oe.parse(JSON.parse(await Z(U,B.maxManifestBytes,g.signal))),{generation:ae,...se}=x,z=U.headers.get("etag");if(L(x.scope)!==L(n)||Qe(se)!==ae||z!==`"${ae}"`&&z!==`W/"${ae}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(x.revision<N.revision||x.revision===N.revision&&x.generation!==N.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[he,K]of Object.entries(N?.funnels??{})){let ee=x.funnels[he];if(ee&&(ee.controlRevision<K.controlRevision||ee.evaluationRevision<K.evaluationRevision||ee.controlRevision===K.controlRevision&&ee.state!==K.state||ee.evaluationRevision===K.evaluationRevision&&ee.evaluationMode!==K.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let X=En(U,G,x.policy);if(g.signal.throwIfAborted(),w!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return p=x,a=X,u=Date.now()+Math.max(0,X-W()),c=!1,A=0,I=0,i.writeManifest(L(x)),M(),structuredClone(x)})(),C=setTimeout(()=>g.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),B.initializationMs),O=new Promise((N,G)=>g.signal.addEventListener("abort",()=>G(g.signal.reason),{once:!0})),_=Promise.race([R,O]).catch(N=>{throw A++,(N instanceof Ln.ZodError||N instanceof SyntaxError||N instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,c=!0,M()),N}).finally(()=>{clearTimeout(C),F===_&&(F=void 0),Ae()});return F=_,_}async function ye(w){let g=w.sha256,R=se=>Ce(se,w);fe(w.url);let C=P.get(g);if(C){if(C.byteLength!==w.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return P.delete(g),P.set(g,C),C.text}let O=v.get(g);if(O){if(O.byteLength!==w.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return O.promise}let _=new AbortController;S.add(_);let N=h,G=(async()=>{try{let X=await i.readArtifact(g);if(X&&R(X)){if(_.signal.throwIfAborted(),d||N!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(g,X,w.byteLength),X}}catch{}_.signal.throwIfAborted();let se=await Fe(w.url,_.signal,!0),z=await Z(se,w.byteLength,_.signal);if(!R(z))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(d||N!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(g,z,w.byteLength),i.writeArtifact(g,z),z})(),U=setTimeout(()=>_.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),B.initializationMs),x=new Promise((se,z)=>_.signal.addEventListener("abort",()=>z(_.signal.reason),{once:!0})),ae=Promise.race([G,x]).finally(()=>{clearTimeout(U),S.delete(_),v.delete(g)});return v.set(g,{promise:ae,byteLength:w.byteLength}),ae}async function we(){return k()||await ie(),J(),p}async function me(w){let g,R=new Promise((C,O)=>{g=setTimeout(()=>O(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),B.initializationMs)});try{return await Promise.race([w(),R])}finally{clearTimeout(g)}}function pe(w,g){if(J(),p?.generation!==w.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(g&&p.funnels[g]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function xe(w){let g=w.gb.features;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let R=w.artifacts[g];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let C=je.parse(JSON.parse(await ye(R)));if(L(C.scope)!==L({projectId:n.projectId,environment:n.environment})||C.generation!==R.generation||C.remoteFeatures.some(O=>Object.hasOwn(C.features,O)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return pe(w),{...C,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-W())).toISOString()}}async function Le(w,g){let R=await we(),C=R.funnels[w];g&&(!C||C.evaluationMode==="local"&&!C.versions[g])&&(F&&await F,R=await ie()),pe(R,w);let O=R.funnels[w];if(O.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let _=g??O.currentVersionId,N=O.versions[_];if(!N)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(R.artifacts[N.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[G,U]=await Promise.all([ye(R.artifacts[N.artifact]).then(x=>$e(JSON.parse(x))),O.evaluationMode==="local"?xe(R):void 0]);if(U&&L(Ye(G,U))!==L(N.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return pe(R,w),{document:G,growth:U,versionId:_,control:structuredClone(O),manifest:structuredClone(R)}}async function Ve(w,g){try{return await Le(w,g)}catch(R){if(!(R instanceof m)||!(R.code==="CONFIGURATION_CHANGED"||R.code==="CONFIGURATION_HTTP_404"&&k()))throw R;let C=p?.generation;if(F&&await F,await ie(),R.code!=="CONFIGURATION_CHANGED"&&p?.generation===C)throw R;return Le(w,g)}}function Ne(){c=!0,M(),ie().catch(H)}let Ie=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ne()};function Fn(w){if(d)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return b.add(w),b.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ie)),Ae()),()=>{b.delete(w),b.size||(clearTimeout(o),clearTimeout(t),Me())}}function Me(){typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ie))}return{scope:Object.freeze({...n}),refresh:ie,subscribe:Fn,assertFresh:J,assertFeatures(w){J();let g=p.gb.features;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(w!==void 0&&p.artifacts[g].generation!==w)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return k()},get snapshot(){return p?structuredClone(p):null},get remainingMs(){return k()?Math.max(0,a-W()):0},async features(){return me(async()=>xe(await we()))},pageExperiments:()=>me(async()=>{let w=await we(),g=w.gb.pageExperiments;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let R=w.artifacts[g];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let C=an.parse(JSON.parse(await ye(R)));if(C.environmentId!==n.environmentId||C.generation!==R.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return pe(w),C}),funnel:(w,g)=>me(()=>Ve(w,g)),paywall:(w,g)=>me(async()=>{let R=await we(),C=R.paywalls?.[w];if(!C||!g&&C.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let O=g??C.currentVersionId,_=C.versions[O],N=_&&R.artifacts[_.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let G=ze.parse(JSON.parse(await ye(N)));return pe(R),{document:G,versionId:O,version:_.version,control:structuredClone(C),manifest:structuredClone(R)}}),async localFunnel(w,g){let R=await me(()=>Ve(w,g));if(!R.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:C,remoteFeatures:O,..._}=R.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:w,versionId:R.versionId,evaluationMode:"local",evaluationRevision:R.control.evaluationRevision,document:R.document,payload:_})},assertFunnel(w,g,R){J();let C=p.funnels[w];if(!C||C.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(C.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Longplay");if(g!==void 0&&C.controlRevision!==g)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(R!==void 0&&!C.versions[R])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!d){d=!0,h++,a=0,T?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(o),clearTimeout(t),Me(),M(),b.clear();for(let w of S)w.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),D=0}}}}function Sn(e){let n=ue.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");return{async start(r){let s=Q.safeParse({...r,operation:"start"});if(!s.success||s.data.operation!=="start"||(n?s.data.customer!==void 0:s.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let l=s.data,y=Y({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||y.identify(e.apiKey);let f=be(e,await y.request("funnels",l));if(!f.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");if(f.run.source.id!==l.funnelId||f.run.locale!==(l.locale??"en")||!ce(f.run.parameters,l.parameters??{})||(l.customer?!f.customerId||l.customer.type==="id"&&f.customerId!==l.customer.value:f.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...f,runToken:f.runToken}}finally{y.dispose()}}}}async function pr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let r={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(r)!==L(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let l=re.test(e.credential);if(l?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let y=Sn({...e,scope:r,apiKey:e.credential}),f=i=>{let p=Rn({...e,scope:r,runToken:i,...l?{serverKey:e.credential}:{}});return l||p.identify(e.credential),p};return{async start(i){let p=await y.start({...i,funnelId:e.funnelId,...l?{customer:{type:"id",value:e.customerId}}:{}}),a=f(p.runToken),u=await a.get();return{...p,...u,controller:a}},async restore(i){let p=f(i),a=await p.get();if(a.run.source.id!==e.funnelId)throw p.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:i,controller:p}}}}export{Ee as a,Mn as b,be as c,_e as d,Xn as e,Nn as f,gn as g,lt as h,ce as i,yt as j,wt as k,Rn as l,jt as m,nr as n,Sn as o,pr as p};
1
+ import{b as dn,c as fn,d as mn,e as pn}from"./chunk-VSMITXQD.js";import{a as te,b as Y}from"./chunk-D5D75HM6.js";import{a as m}from"./chunk-OZZMZH7X.js";import{a as ln,b as cn,c as Ce}from"./chunk-2ODPDLTX.js";import{$a as un,Ea as Te,Fa as tn,R as Ge,T as Re,Ta as rn,U as Be,Ua as on,V as je,W as Je,Xa as an,Ya as sn,a as Ue,cb as le,da as Q,ea as ze,fa as B,ga as Ke,ha as Oe,ia as L,ka as Qe,la as Ye,ma as $e,n as ue,na as We,oa as Ze,ua as ne,va as Xe,ya as en,za as nn}from"./chunk-KOGWARWA.js";import{B as ve,Ca as He,v as qe,y as ke}from"./chunk-VSJOHWDL.js";function Mn(e){let n=null,r=null,s=0,l=0,y=new Set,f=null,i=null,p=new Set,a=()=>{for(let o of p)try{o()}catch{}},u={attributes:ve.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(o,t)=>{!y.has(o)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(o,structuredClone(t),structuredClone(u.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(o,t)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(o),structuredClone(t),structuredClone(u.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?o=>e.saveStickyBucketAssignmentDoc(structuredClone(o)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},c=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function d(o,t=new Set){return y.has(o)?!f||!f.features[o]||["unknownFeature","cyclicPrerequisite"].includes(f.features[o].source):t.has(o)?!1:(t.add(o),(n?.features[o]?.rules??[]).some(I=>[...I.parentConditions??[],...(I.tracks??[]).flatMap(b=>b.experiment.parentConditions??[])].some(b=>d(b.id,t))))}let h=o=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return f?.expiresAt&&Date.parse(f.expiresAt)<=Date.now()&&(f=null,u.features=n.features),y.has(o)?!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now()?c():structuredClone(f.features[o]??c()):e.evaluateRemote&&(u.attributes?.merchandise||u.attributes?.merchandiseId)&&!f||d(o)?c():structuredClone(ke(o,u))};async function A(){if(!n||!y.size&&!u.attributes?.merchandise&&!u.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(y.size)throw new Error("Remote Feature evaluation requires a server loader");return}let o=l;if(i?.revision===o)return i.loading;let t=s,I=n,b=[...y],S=(async()=>{let P=Je.parse(await e.evaluateRemote({attributes:structuredClone(u.attributes),features:b}));if(!(t!==s||o!==l||I!==n)){if(e.assertUsable?.(I.generation),P.generation!==I.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(b.some(v=>!Object.hasOwn(P.features,v))||Object.keys(P.features).some(v=>!y.has(v)))throw new Error("Invalid remote Feature results");if(u.attributes?.merchandise||u.attributes?.merchandiseId){if(!P.merchandiseContext)throw new Error("Server did not resolve merchandise context");u.attributes=ve.parse({...u.attributes,...P.merchandiseContext})}f=structuredClone(P),u.features={...I.features,...Object.fromEntries(Object.entries(f.features).map(([v,D])=>[v,{defaultValue:D.value}]))},a()}})();i={revision:o,loading:S};try{await S}finally{i?.loading===S&&(i=null)}}function F(){A().catch(o=>{try{e.onError?.(o)}catch{}})}async function T(){if(r)return r;let o=s,t=(async()=>{let I=await e.load(),b="remoteFeatures"in I?Be.parse(I):null,S=b??Re.parse(I);if(S.scope.projectId!==e.scope.projectId||S.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(o!==s)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===S.generation){let{evaluatedAt:v,expiresAt:D,...V}=n,{evaluatedAt:M,expiresAt:H,...k}=S;if(L(V)!==L(k))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=S.evaluatedAt,n.expiresAt=S.expiresAt,a(),(!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now())&&F(),structuredClone(n)}let P=new Set(b?.remoteFeatures??[]);if([...P].some(v=>Object.hasOwn(S.features,v)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in S&&!n.analyticsConfig.experimentViewsEnabled&&b?.analyticsConfig.experimentViewsEnabled&&u.trackedExperiments?.clear(),n=structuredClone(S),y=P,f=null,i=null,l++,u.features=n.features,u.savedGroups=qe(n.savedGroups),u.trackedFeatureUsage={},a(),F(),structuredClone(n)})();r=t;try{return await t}finally{r===t&&(r=null)}}return{init:T,refresh:T,refreshRemote:A,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(o){return p.add(o),()=>{p.delete(o)}},setAttributes(o){let t=ve.parse(o);(u.attributes?.merchandise||u.attributes?.merchandiseId||o.merchandise||o.merchandiseId)&&u.trackedExperiments?.clear(),u.attributes=t,l++,f=null,i=null,u.features=n?.features??{},u.trackedFeatureUsage={},a(),F()},evalFeature:h,isOn(o){return h(o).on},isOff(o){return h(o).off},getFeatureValue(o,t){let I=h(o).value;return structuredClone(I===null?t:I)},reset(){s++,l++,r=null,i=null,n=null,f=null,y.clear(),u.features={},u.savedGroups={},u.stickyBucketAssignmentDocs={},u.attributes={},u.trackedFeatureUsage={},u.trackedExperiments?.clear(),a()}}}function gn(e){let n,r,s=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),l=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,r=e.locks??globalThis.navigator?.locks,!n||!r||!globalThis.crypto?.subtle)throw s();let i=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??le).href,e.runToken])),p=new Uint8Array(await crypto.subtle.digest("SHA-256",i));return"indiana.funnel.commands.v1."+Array.from(p,a=>a.toString(16).padStart(2,"0")).join("")});l.catch(()=>{});async function y(i){try{let p=await l;return await r.request(p,{mode:"exclusive"},()=>i(p))}catch(p){throw p instanceof m?p:s()}}function f(i){let p=n.getItem(i);if(p===null)return{revision:0,entry:null};if(p.length>1048576)throw s();let a=JSON.parse(p);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw s();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>y(f),write:(i,p)=>y(a=>{if(f(a).revision!==i)return null;if(!Number.isSafeInteger(i+1))throw s();return n.setItem(a,JSON.stringify({revision:i+1,entry:p})),i+1})}}function be(e,n){let r=en.safeParse(n);if(!r.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let s=r.data;if(e.scope&&(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return s}async function Pe(e,n){let r=We.parse(n),{artifact:s,environmentId:l}=r.content,y=new te(e.baseUrl??le).origin,f=new te(s.url,y);if(f.origin!==y||f.username||f.password||f.search||f.hash||f.pathname!==`/api/v1/configuration/${l}/artifacts/${s.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let i=new AbortController,p,a=new Promise((c,d)=>{p=setTimeout(()=>{let h=new m("TIMEOUT","Public Paywall read timed out");i.abort(h),d(h)},B.initializationMs)}),u=(async()=>{let c=await(e.fetch??globalThis.fetch)(f,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:i.signal});if(i.signal.aborted&&(c.body?.cancel().catch(()=>{}),i.signal.throwIfAborted()),!c.ok||!c.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(c.headers.get("content-length"))>s.byteLength)throw c.body?.cancel().catch(()=>{}),new m("INVALID_RESPONSE","Public Paywall is unavailable");let d=await ln(c,s.byteLength,{signal:i.signal,error:h=>new m("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ce(d,s))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return Ze(r,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)))})();try{return await Promise.race([u,a])}finally{clearTimeout(p)}}var _e=(e,n)=>new m(e,n);function Xn(e){return sn(e,_e)}async function De(e,n,{predict:r=!0}={}){let s=n.instruction;if(s?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==s.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let l=null,y;if(r)try{let f=await e.funnel(n.source.id,n.source.versionId);y=f.manifest.generation,l=An(e,n,f)}catch{l=null}return y??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:s.policyRevision,generation:y},prediction:l}}function An(e,n,r){let s=n.instruction;if(s?.type!=="evaluate_segment"||!r.growth||r.control.evaluationMode!=="local"||r.control.evaluationRevision!==s.policyRevision)return null;let{analyticsConfig:l,remoteFeatures:y,...f}=r.growth,i=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:s.policyRevision,document:r.document,payload:Re.parse(f)}),p=Nn(i,r.document,{...n,...s}),a=p.steps.at(-1),u=p.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+p.steps.length-1}:null);return u?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:u.nodeId,visit:u.visit,terminal:!p.boundary}:null}function Nn(e,n,r){return un(e,n,r,_e)}import{z as j}from"zod";var yn=Q.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=j.strictObject({schemaVersion:j.literal(1),scope:Ue,runId:j.uuid(),funnelId:j.uuid(),versionId:j.uuid(),processBindingIds:j.record(j.uuid(),j.uuid().nullable()).optional(),command:yn.optional(),closeCommand:yn.refine(e=>e.operation==="close").optional(),purchase:j.strictObject({receiptId:j.uuid(),operationId:j.uuid(),generation:j.number().int().nonnegative()}).optional(),closed:j.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),q=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Se=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function In(e){let n=0,r=null,s=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),l=Promise.resolve();async function y(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function f(a){let u=l.then(a);return l=u.catch(()=>{}),u}async function i(a){for(let u=0;u<4;u++){let c=await y();if(c.entry&&r!==null&&s(c.entry)!==r)throw q();let d=a(c.entry,c.revision);if(Se(c.entry,d)){n=c.revision;return}let h=await e.write(c.revision,d);if(h!==null){if(!Number.isSafeInteger(h)||h<=c.revision)throw q();n=h;return}}throw q()}function p(a,u){if(!a||!u)return a;if(a.processBindingIds&&Object.hasOwn(a.processBindingIds,u)){let c={...a.processBindingIds};delete c[u],a={...a,processBindingIds:c}}return a.command?.requestId===u?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand?.requestId===u?{...a,closeCommand:void 0}:a}return{bind(a){let u=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(r!==null&&r!==u)throw q();r=u},async load(){let a=await y();return n=a.revision,r=a.entry?s(a.entry):null,a.entry},retain(a){let u=wn.parse(a),c=u.command;return!c||r!==null&&s(u)!==r?Promise.reject(q()):(r??=s(u),f(()=>i((d,h)=>{if(d&&!Se(s(d),s(u)))throw q();if(d&&u.processBindingIds){for(let[A,F]of Object.entries(u.processBindingIds))if(d.processBindingIds&&Object.hasOwn(d.processBindingIds,A)&&d.processBindingIds[A]!==F)throw q();d={...d,processBindingIds:{...d.processBindingIds,...u.processBindingIds}}}if(!d){if(h!==n&&c.operation!=="close")throw q();return u}if(!d.command)return{...d,command:c,...c.operation==="close"?{closed:!0}:{}};if(c.operation==="close"&&d.command.operation!=="close"){if(d.command.requestId===c.requestId||d.closeCommand&&!Se(d.closeCommand,c))throw q();return{...d,closeCommand:c,closed:!0}}if(!Se(d.command,c))throw q();return d})))},observePurchase(a,u,c,d){return f(()=>i((h,A)=>{if(!h&&A!==n||h&&s(h)!==s({...a,schemaVersion:1}))throw q();if(h?.purchase&&h.purchase.generation>u.generation)return p(h,d);if(h?.purchase&&h.purchase.generation===u.generation&&h.purchase.operationId!==u.operationId)throw q();return c?!h?.purchase||h.purchase.operationId!==u.operationId?p(h,d):p(h.command?{...h,purchase:void 0}:null,d):p({schemaVersion:1,...a,...h,purchase:u},d)}))},settle(a){return f(()=>i(u=>p(u,a)))}}}function lt(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ce(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((l,y)=>ce(l,n[y]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let r=Object.entries(e),s=Object.entries(n);return r.length===s.length&&r.every(([l,y])=>Object.hasOwn(n,l)&&ce(y,Reflect.get(n,l)))}function hn(e,n){let r=n&&{...n},s=null,l=0,y=new AbortController;function f(){l++,y.abort(new m("IDENTITY_CHANGED","Run identity changed")),y=new AbortController}let i=!1,p,a=0,u=new Set;return{get scope(){return r},bindScope(c){if(r&&(r.projectId!==c.projectId||r.environment!==c.environment))throw new m("SCOPE_MISMATCH","Run scope changed");r??={...c}},get view(){return s},get generation(){return l},get signal(){return y.signal},get disposed(){return i},get customerToken(){return p},get readSequence(){return a},nextRead(){return++a},assertCurrent(c,d="Run identity changed during the request"){if(c!==l||i)throw new m("IDENTITY_CHANGED",d)},assertRun(c){if(s&&(c.id!==s.id||c.source.type!==s.source.type||c.source.id!==s.source.id||c.source.versionId!==s.source.versionId||c.locale!==s.locale||!ce(c.parameters,s.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&c.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(c,d,h,A,F){if(!(c.operation==="review"&&s&&s!==h&&d.run.revision<=s.revision)&&!(s&&d.run.revision===s.revision&&A!==void 0&&A<a)&&(c.operation==="review"&&!d.run.stopped&&["running","waiting"].includes(d.run.status)&&s&&d.run.nodeId===s.nodeId&&d.run.visit===s.visit&&d.run.revision===s.revision&&(d.run.screen=s.screen,(s.paywall?.quote?.operationId===d.review?.activeOperationId||!s.paywall?.quote&&d.review?.activeOperationId===null)&&(d.run.paywall=s.paywall)),!(s?.paywall&&d.run.paywall&&s.paywall.receiptId===d.run.paywall.receiptId&&(d.run.paywall.selectionGeneration??0)<(s.paywall.selectionGeneration??0)))){if(!s||d.run.revision>=s.revision)s=d.run;else if(!F)return;if(s)for(let T of u)try{T(structuredClone(s))}catch{}}},identify(c){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!ue.test(c))throw new m("INVALID_TOKEN","Customer credential required");f(),p=c},subscribe(c){return u.add(c),()=>u.delete(c)},reset(){i||(i=!0,f(),p=void 0,s=null,u.clear())}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function yt(e,n,r="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!re.test(e))throw new m("INVALID_TOKEN",r)}function wt(e){let n=Y(e);return n.identify(e.apiKey),n}function $(e){let{customerToken:n,...r}=e;return r}var On=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function vn({journal:e,state:n,call:r,processIdentity:s}){let l=null,y=null,f=!1,i={command:null,close:null},p=new Set,a,u=null,c=e?e.load().then(o=>{if(n.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(u=o,!o)return;if(s){if([o.command,o.closeCommand].some(I=>I&&!Object.hasOwn(o.processBindingIds??{},I.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");s.restore(o.processBindingIds??{})}if(n.scope&&(o.scope.projectId!==n.scope.projectId||o.scope.environment!==n.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=o.purchase,f=o.closed===!0,!o.command)return;let t=o.command;l=t.operation==="close"?null:t,y=t.operation==="close"?t:o.closeCommand?.operation==="close"?o.closeCommand:null,y&&(f=!0);for(let I of[l,y])I&&p.add(I.requestId)}):Promise.resolve();c.catch(()=>{});async function d(o){e&&await c;let t=n.generation;if(e){if(!n.view||!n.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:$(o),...s?{processBindingIds:{[o.requestId]:s.binding(o.requestId)}}:{}})}if(t!==n.generation||l!==o&&y!==o)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let I=p.has(o.requestId);p.add(o.requestId);try{return await r(o)}catch(b){throw t===n.generation&&(l===o||y===o)&&!I&&!On(b)&&(e&&await e.settle(o.requestId),t===n.generation&&T(o)),b}}function h(o){let t=Q.parse(o);if(t.operation==="start"||t.operation==="get"||t.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(f&&t.operation!=="close"){if(l?.requestId===t.requestId)return F(t.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(t.operation==="close"){if(l?.requestId===t.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(f=!0,y&&JSON.stringify($(y))!==JSON.stringify($(t)))throw new m("COMMAND_PENDING","Retry the original Close");return y??=t,i.close?i.close:A(y,"close")}if(l){if(JSON.stringify($(l))!==JSON.stringify($(t)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(i.command)return i.command}else l=t;return A(l,"command")}function A(o,t){let I=d(o);i[t]=I;let b=()=>{i[t]===I&&(i[t]=null)};return I.then(b,b),I}function F(o){return r({operation:"get",settlementRequestId:o})}function T(o){return!o||l!==o&&y!==o?!1:(l===o&&(l=null),y===o&&(y=null),p.delete(o.requestId),!l&&!y&&(u=null),!0)}return{ready:c,get pending(){return l},get closing(){return y},get closeRequested(){return f},get inFlight(){return i.command},get closeFlight(){return i.close},get purchase(){return a},assertBinding(o){if(u&&(o.run.id!==u.runId||o.run.source.id!==u.funnelId||o.run.source.versionId!==u.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(o,t,I,b){let S=o.operation==="get"?o.settlementRequestId:"requestId"in o&&o.operation!=="start"?o.requestId:void 0,P=S&&t.settlement?.state==="settled"&&t.run.pendingRequest?.requestId!==S&&(o.operation==="get"||!f||o.operation==="close"||!["running","waiting"].includes(t.run.status))?S:void 0,v=l?.requestId===P?l:y?.requestId===P?y:void 0;e?.bind({scope:t.scope,runId:t.run.id,funnelId:t.run.source.id,versionId:t.run.source.versionId});let D=t.run.paywall,V=D??t.purchase,M=V?.operation,H=t.settlement&&(!D||D.purchaseRequestId===t.settlement.requestId)&&(!a||a.operationId===t.settlement.operationId)?t.settlement:void 0,k=M?.operationId??V?.quote?.operationId??H?.operationId,J=V?.receiptId??H?.receiptId,de=D?.selectionGeneration??a?.generation??0;if(e&&k&&J&&o.operation!=="review"&&(!n.view||t.run.revision>=n.view.revision)&&(b===void 0||b>=n.readSequence)&&(!a||de>=a.generation)){let Z={receiptId:J,operationId:k,generation:de},fe=M?.status==="complete"||V?.canReselect===!0;await e.observePurchase({scope:t.scope,runId:t.run.id,funnelId:t.run.source.id,versionId:t.run.source.versionId},Z,fe,P),n.assertCurrent(I),(!a||Z.generation>=a.generation)&&(b===void 0||b>=n.readSequence)&&(fe?a?.operationId===Z.operationId&&(a=void 0):a=Z)}else e&&P&&await e.settle(P);return n.assertCurrent(I),P?T(v):!1},stop(){f=!0},submit:h,settle:F,reset(){f=!0,l=null,y=null,a=void 0,u=null,i.close=null,p.clear(),i.command=null}}}function Rn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Y({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),r=hn(e.funnelId,e.scope??e.configuration?.scope),s=e.session?.subscribeIdentity(a),l=null,y=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?gn(e):void 0),f=y&&In(y),i=vn({journal:f,state:r,call:u,processIdentity:e.process});async function p(t){if(e.process)return e.process.request(t);let I=r.generation;r.assertCurrent(I);let b=performance.now()+(e.timeoutMs??35e3),S=r.customerToken??("customerToken"in t?t.customerToken:void 0);if(e.session){let D=r.signal,V,M=()=>{},H=new Promise((k,J)=>{M=()=>J(D.reason),D.addEventListener("abort",M,{once:!0}),V=setTimeout(()=>J(new m("TIMEOUT","Longplay request timed out")),Math.max(1,b-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(r.assertCurrent(I),e.session.access())),H])}finally{clearTimeout(V),D.removeEventListener("abort",M)}}r.assertCurrent(I);let P={...t,...S?{customerToken:S}:{}},v=t.operation==="page_experiments"?Te.parse(P):Q.parse(P);return n.requestWithCredential("funnels",v,e.runToken,{headers:e.serverKey&&!S?{[nn]:e.serverKey}:void 0,timeoutMs:Math.max(1,b-performance.now())})}function a(){s?.(),r.reset(),i.reset(),l=null,n.dispose()}async function u(t,I){let b=r.generation,S=()=>r.assertCurrent(b);f&&await i.ready,S();let P=r.view,v=be(e,await p(t));if(t.operation==="review"&&!v.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(S(),v.runToken&&v.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let D=t.operation==="get"?t.settlementRequestId:"requestId"in t&&t.operation!=="start"?t.requestId:void 0;if(D&&v.settlement?.requestId!==D)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(v),r.assertRun(v.run),r.bindScope(v.scope);let V=await i.observe(t,v,b,I);return!v.run.stopped&&["running","waiting"].includes(v.run.status)&&t.operation==="get"&&t.settlementRequestId||(S(),["running","waiting"].includes(v.run.status)||i.stop(),r.publish(t,v,P,I,V)),v}let c=i.submit,d=null,h=new WeakMap;function A(t){let I=h.get(t);if(I)return I;let b=T(t);return h.set(t,b),b}let F=!1;async function T(t){let I=await t;if(I.run.instruction?.type!=="evaluate_segment")return I;if(d)return d;F=!0;let b=r.generation,S=(async()=>{for(let P=0;P<32&&I.run.instruction?.type==="evaluate_segment";P++){if(i.pending||i.closeRequested)return I;let v=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:V}=await De(e.configuration,v,{predict:!1});if(b!==r.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(r.view&&(r.view.revision!==v.revision||r.view.visit!==v.visit||r.view.nodeId!==v.nodeId))return u({operation:"get"});let M=!0;De(e.configuration,v).then(({prediction:H})=>{M&&b===r.generation&&!i.closeRequested&&r.view?.id===v.id&&!r.view.stopped&&r.view.nodeId===v.nodeId&&r.view.visit===v.visit&&r.view.revision===v.revision&&(l=H)}).catch(()=>{});try{I=await c({operation:"commit_segment",requestId:Xe(v.id,v.visit,`segment:${v.revision}`),nodeId:v.nodeId,visit:v.visit,revision:v.revision,...V})}finally{M=!1,l=null}}}return I})();d=S;try{return await S}finally{d===S&&(d=null)}}let o={get configuration(){return F?e.configuration:void 0},get configurationReady(){return!0},get view(){return r.view?structuredClone(r.view):null},get pendingCommand(){let t=i.closing??i.pending;return t?structuredClone($(t)):null},get pendingCommands(){return[i.pending,i.closing].filter(t=>t!==null).map(t=>structuredClone($(t)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get prediction(){let t=r.view;return l&&t&&!t.stopped&&["running","waiting"].includes(t.status)&&t.id===l.runId&&t.nodeId===l.from.nodeId&&t.visit===l.from.visit&&t.revision===l.from.revision&&!i.closeRequested?structuredClone(l):null},settle:i.settle,get webViewUrl(){return"bundled"},resolvePaywall(t){return Pe(e,t)},async pageExperiments(t,I=[]){let b=r.generation;r.assertCurrent(b);let S=r.view?.id;if(!S)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let P=tn.parse(await p(Te.parse({operation:"page_experiments",release:t,usedReceiptIds:I})));if(r.assertCurrent(b),P.runId!==S||P.scope.projectId!==r.scope?.projectId||P.scope.environment!==r.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return P},review(t){return u({operation:"review",...t?{receiptId:t}:{}},r.nextRead())},async get(t,I){f&&await i.ready,I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let b=r.nextRead();return A(u({operation:"get",...t?{data:t}:{},...I?{purchase:I}:{}},b))},resume(t=r.view?.pendingRequest?.requestId){return t?i.closeRequested?o.settle(t):i.pending?.requestId===t?A(c(i.pending)):A(c({operation:"resume",requestId:t})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(t){return A(c(t))},retry(){return i.closeFlight?i.closeFlight:i.closing?c(i.closing):i.closeRequested&&i.pending?o.settle(i.pending.requestId):i.inFlight?A(i.inFlight):i.pending?A(c(i.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(t){r.identify(t),l=null,n.reset()},subscribe:r.subscribe,reset:a};return o}import{ZodError as Tn}from"zod";function Cn(e,n,r,s){try{return e.parse(n)}catch(l){throw s&&l instanceof Tn?new m(r,s):l}}async function Ee(e,n,r,s={},l){let y=typeof s=="function"?{}:s,f=Cn(n.request,r,"INVALID_REQUEST",y.request);try{let i=await e(n.path,f,n.method,l),p=typeof s=="function"?s:s.parseResponse;return p?p(n.response,i):Cn(n.response,i,"INVALID_RESPONSE",y.response)}catch(i){throw i instanceof m&&f!==null&&typeof f=="object"&&"requestId"in f&&typeof f.requestId=="string"&&(i.commandRequestId??=f.requestId),i}}async function jt(e,n){if(!ue.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),s=Y(e);e.session||s.identify(n.customerToken);let l=null,y=!1,f=null,i=null,p=null,a=null;function u(){if(y)throw new m("IDENTITY_CHANGED","Paywall is closed")}async function c(){u();let F=ne.resolvePaywall,T=await Ee(s.request,F,{...r,selector:l?{type:"version",versionId:l.id}:r.selector}),o=await Pe(e,T.paywall);if(u(),n.paywallVersionId?o.id!==n.paywallVersionId:o.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(l&&(!dn(o,l)||o.paywallId!==l.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return l=o,structuredClone(l)}async function d(F){if(u(),a&&F!=="read")throw new m("COMMAND_PENDING","Wait for the original quote");if(!f)throw new m("INVALID_REQUEST","A quoted purchase is required");let T=f,o=F==="read"?ne.readSubscriptionOperation:ne.attach,t=await Ee(s.request,o,{operationId:T.operationId,...F==="read"?{}:{intent:F}});return fn(t.operation,{operationId:T.operationId,currency:r.commerce.currency},"The purchase operation changed"),u(),f?.operationId!==T.operationId?structuredClone(t.operation):(i=pn(i,t.operation),structuredClone(i))}let h={get view(){return l?structuredClone(l):null},get quote(){return f?structuredClone(f):null},get operation(){return i?structuredClone(i):null},get webViewUrl(){return"bundled"},refresh:c,async preview(F){if(u(),!l)throw new m("INVALID_REQUEST","Load the Paywall first");let T=l.document.buttons[F.actionId];if(T?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let o=Ge(T.product,F.selection,l.capabilities);if(!o)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let t=He(l.document.screen,o,F.selection,l.capabilities),I=ne.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:F.requestId,plans:[{productVersionId:o,...Object.keys(t).length?{featureQuantities:t}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...F.offerId?{offerId:F.offerId}:{},...F.nativeOffer?{nativeOffer:F.nativeOffer}:{}}),b=JSON.stringify(I);if(p&&p!==b&&(a||!i||i.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(p===b){if(a)return a;if(f)return structuredClone(f)}p!==b&&(f=null,i=null),p=b;let S=(async()=>{let P=ne.previewAttach,v=await Ee(s.request,P,I);return u(),mn(v.quote,{productVersionId:o,featureQuantities:t,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),f=v.quote,i=null,structuredClone(f)})();a=S;try{return await S}finally{a===S&&(a=null)}},confirm:()=>d("confirm"),cancel:()=>d("cancel"),read:()=>d("read"),destroy(){y||(y=!0,A?.(),s.dispose(),l=null,f=null,i=null,p=null)}},A=e.session?.subscribeIdentity(h.destroy);try{return await c(),h}catch(F){throw h.destroy(),F}}import{z as Ln}from"zod";import{z as ge}from"zod";var _n=ge.record(ge.string().regex(/^[a-f0-9]{64}$/),ge.strictObject({at:ge.number(),text:ge.string()})),oe=2*1048576,Dn=100;function xn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function bn(e,n){let r=n===void 0?xn():n,s=new Map,l=0,y=!1,f=!1,i,p;async function a(c){if(!r)return null;let d;try{let h=await Promise.race([Promise.resolve().then(()=>r.getItem(c)),new Promise(A=>{d=setTimeout(()=>A(null),Dn)})]);return typeof h=="string"&&h.length<=oe&&new TextEncoder().encode(h).byteLength<=oe?h:null}catch{return null}finally{clearTimeout(d)}}function u(){if(p)return p;let c=(async()=>{try{let d=await a(`${e}:artifacts`);if(d)return _n.parse(JSON.parse(d))}catch{}return{}})();return p=c,c.finally(()=>{p===c&&(p=void 0)}),c}return{async readManifest(){return a(e)},writeManifest(c){!r||c.length>oe||new TextEncoder().encode(c).byteLength>oe||(i=c,!f&&(f=!0,Promise.resolve().then(async()=>{try{for(;i!==void 0;){let d=i;try{await r.setItem(e,d)}catch{}i===d&&(i=void 0)}}finally{f=!1}})))},async readArtifact(c){let d=(await u())[c],h=Date.now();return d&&h>=d.at&&h-d.at<=B.retentionMs?d.text:void 0},writeArtifact(c,d){if(!r||d.length>oe)return;let h=s.get(c);if(h?.text===d||!h&&s.size>=128)return;let A=new TextEncoder().encode(d).byteLength;l-(h?.byteLength??0)+A>oe||(s.set(c,{text:d,byteLength:A}),l+=A-(h?.byteLength??0),!y&&(y=!0,Promise.resolve().then(async()=>{try{for(;s.size;){let F=new Map(s);try{let T={...await u()},o=Date.now();for(let[S,P]of F)T[S]={at:o,text:P.text};let t={},I=2,b=0;for(let[S,P]of Object.entries(T).sort(([,v],[,D])=>D.at-v.at)){if(P.at>o||o-P.at>B.retentionMs)continue;let v=new TextEncoder().encode(JSON.stringify({[S]:P})).byteLength;I+v>oe||b>=128||(t[S]=P,I+=v,b++)}await r.setItem(`${e}:artifacts`,JSON.stringify(t))}catch{}finally{for(let[T,o]of F)s.get(T)===o&&(s.delete(T),l-=o.byteLength)}}}finally{y=!1}})))}}}var E=(e,n)=>new m(e,n),W=()=>performance.now(),Pn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function nr(e){let n=Ke.parse(e.scope),r=new te(e.origin??le);if(r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.protocol!=="https:"&&!(r.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let s=new Set([r.origin,...(e.assetOrigins??[]).map(w=>{let g=new te(w);if(g.protocol!=="https:"||g.username||g.password||g.search||g.hash||g.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return g.origin})]),l=e.fetch??globalThis.fetch.bind(globalThis),y=`/api/v1/configuration/${n.environmentId}`,f=`indiana:configuration:1:${r.origin}:${L(n)}`,i=bn(f,e.storage),p,a=0,u=0,c=!1,d=!1,h=0,A=0,F,T,o,t,I=0,b=new Set,S=new Set,P=new Map,v=new Map,D=0,V=!1;function M(){for(let w of b)try{w()}catch{}}function H(w){try{e.onError?.(w)}catch{}}let k=()=>!d&&!c&&!!p&&W()<a&&Date.now()<u;function J(){if(!k())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function de(w,g,R){if(!P.has(w)){for(;P.size&&(P.size>=128||D+R>B.maxCacheBytes);){let C=P.entries().next().value;D-=C[1].byteLength,P.delete(C[0])}P.set(w,{text:g,byteLength:R}),D+=R}}function Z(w,g,R){return cn(w,g,{signal:R,error:C=>E("INVALID_RESPONSE",C==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function fe(w){let g=new te(w,r);if(!s.has(g.origin)||g.username||g.password||g.hash||g.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return g.href}async function Fe(w,g,R=!1){let C=await l(fe(w),{method:"GET",credentials:"omit",redirect:"error",cache:R?"default":"no-cache",signal:g,headers:{}});if(C.status===429){let O=C.headers.get("retry-after")??"";I=/^\d+$/.test(O)?Number(O)*1e3:Math.max(0,Date.parse(O)-Date.now())||15e3}if(!C.ok&&C.status!==304)throw E(`CONFIGURATION_HTTP_${C.status}`,"Configuration synchronization failed");return C}function En(w,g,R){let C=Date.parse(w.headers.get("x-indiana-config-validated-at")??""),O=Date.parse(w.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(w.headers.get("date")??""),N=w.headers.get("age"),G=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![C,O,_,G].every(Number.isFinite)||O<=C||O-C>B.maxControlAgeMs||C>_+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(O-C,R.maxControlAgeSeconds*1e3,B.maxControlAgeMs)-Math.max(G,_-C,0)-(W()-g);if(x<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return W()+x}function Ae(){if(clearTimeout(o),clearTimeout(t),d||!b.size)return;k()&&(t=setTimeout(()=>{k()?Ae():M()},Math.max(1,a-W())),Pn(t));let w=A?Math.min(15e3,1e3*2**Math.min(A-1,4)):Math.min(15e3,(p?.policy.refreshIntervalSeconds??15)*1e3);o=setTimeout(()=>{ie().catch(H)},Math.max(I,w*(.8+Math.random()*.2))),Pn(o)}async function ie(){if(d)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(F)return F;let w=h,g=new AbortController;T=g;let R=(async()=>{if(!V){V=!0;try{let he=await i.readManifest();if(he&&!p){let K=Oe.parse(JSON.parse(he));L(K.scope)===L(n)&&(p=K)}}catch{}}g.signal.throwIfAborted();let N=p,G=W(),U=await Fe(y,g.signal);U.status===304&&(!N||!U.headers.has("x-indiana-config-validated-at")||!U.headers.has("x-indiana-config-valid-until")||!U.headers.has("age"))&&(U=await Fe(y,g.signal));let x=U.status===304?N:Oe.parse(JSON.parse(await Z(U,B.maxManifestBytes,g.signal))),{generation:ae,...se}=x,z=U.headers.get("etag");if(L(x.scope)!==L(n)||Qe(se)!==ae||z!==`"${ae}"`&&z!==`W/"${ae}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(x.revision<N.revision||x.revision===N.revision&&x.generation!==N.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[he,K]of Object.entries(N?.funnels??{})){let ee=x.funnels[he];if(ee&&(ee.controlRevision<K.controlRevision||ee.evaluationRevision<K.evaluationRevision||ee.controlRevision===K.controlRevision&&ee.state!==K.state||ee.evaluationRevision===K.evaluationRevision&&ee.evaluationMode!==K.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let X=En(U,G,x.policy);if(g.signal.throwIfAborted(),w!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return p=x,a=X,u=Date.now()+Math.max(0,X-W()),c=!1,A=0,I=0,i.writeManifest(L(x)),M(),structuredClone(x)})(),C=setTimeout(()=>g.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),B.initializationMs),O=new Promise((N,G)=>g.signal.addEventListener("abort",()=>G(g.signal.reason),{once:!0})),_=Promise.race([R,O]).catch(N=>{throw A++,(N instanceof Ln.ZodError||N instanceof SyntaxError||N instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,c=!0,M()),N}).finally(()=>{clearTimeout(C),F===_&&(F=void 0),Ae()});return F=_,_}async function ye(w){let g=w.sha256,R=se=>Ce(se,w);fe(w.url);let C=P.get(g);if(C){if(C.byteLength!==w.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return P.delete(g),P.set(g,C),C.text}let O=v.get(g);if(O){if(O.byteLength!==w.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return O.promise}let _=new AbortController;S.add(_);let N=h,G=(async()=>{try{let X=await i.readArtifact(g);if(X&&R(X)){if(_.signal.throwIfAborted(),d||N!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(g,X,w.byteLength),X}}catch{}_.signal.throwIfAborted();let se=await Fe(w.url,_.signal,!0),z=await Z(se,w.byteLength,_.signal);if(!R(z))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(d||N!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(g,z,w.byteLength),i.writeArtifact(g,z),z})(),U=setTimeout(()=>_.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),B.initializationMs),x=new Promise((se,z)=>_.signal.addEventListener("abort",()=>z(_.signal.reason),{once:!0})),ae=Promise.race([G,x]).finally(()=>{clearTimeout(U),S.delete(_),v.delete(g)});return v.set(g,{promise:ae,byteLength:w.byteLength}),ae}async function we(){return k()||await ie(),J(),p}async function me(w){let g,R=new Promise((C,O)=>{g=setTimeout(()=>O(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),B.initializationMs)});try{return await Promise.race([w(),R])}finally{clearTimeout(g)}}function pe(w,g){if(J(),p?.generation!==w.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(g&&p.funnels[g]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function xe(w){let g=w.gb.features;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let R=w.artifacts[g];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let C=je.parse(JSON.parse(await ye(R)));if(L(C.scope)!==L({projectId:n.projectId,environment:n.environment})||C.generation!==R.generation||C.remoteFeatures.some(O=>Object.hasOwn(C.features,O)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return pe(w),{...C,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-W())).toISOString()}}async function Le(w,g){let R=await we(),C=R.funnels[w];g&&(!C||C.evaluationMode==="local"&&!C.versions[g])&&(F&&await F,R=await ie()),pe(R,w);let O=R.funnels[w];if(O.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let _=g??O.currentVersionId,N=O.versions[_];if(!N)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(R.artifacts[N.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[G,U]=await Promise.all([ye(R.artifacts[N.artifact]).then(x=>$e(JSON.parse(x))),O.evaluationMode==="local"?xe(R):void 0]);if(U&&L(Ye(G,U))!==L(N.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return pe(R,w),{document:G,growth:U,versionId:_,control:structuredClone(O),manifest:structuredClone(R)}}async function Ve(w,g){try{return await Le(w,g)}catch(R){if(!(R instanceof m)||!(R.code==="CONFIGURATION_CHANGED"||R.code==="CONFIGURATION_HTTP_404"&&k()))throw R;let C=p?.generation;if(F&&await F,await ie(),R.code!=="CONFIGURATION_CHANGED"&&p?.generation===C)throw R;return Le(w,g)}}function Ne(){c=!0,M(),ie().catch(H)}let Ie=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ne()};function Fn(w){if(d)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return b.add(w),b.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ie)),Ae()),()=>{b.delete(w),b.size||(clearTimeout(o),clearTimeout(t),Me())}}function Me(){typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ie))}return{scope:Object.freeze({...n}),refresh:ie,subscribe:Fn,assertFresh:J,assertFeatures(w){J();let g=p.gb.features;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(w!==void 0&&p.artifacts[g].generation!==w)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return k()},get snapshot(){return p?structuredClone(p):null},get remainingMs(){return k()?Math.max(0,a-W()):0},async features(){return me(async()=>xe(await we()))},pageExperiments:()=>me(async()=>{let w=await we(),g=w.gb.pageExperiments;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let R=w.artifacts[g];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let C=an.parse(JSON.parse(await ye(R)));if(C.environmentId!==n.environmentId||C.generation!==R.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return pe(w),C}),funnel:(w,g)=>me(()=>Ve(w,g)),paywall:(w,g)=>me(async()=>{let R=await we(),C=R.paywalls?.[w];if(!C||!g&&C.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let O=g??C.currentVersionId,_=C.versions[O],N=_&&R.artifacts[_.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let G=ze.parse(JSON.parse(await ye(N)));return pe(R),{document:G,versionId:O,version:_.version,control:structuredClone(C),manifest:structuredClone(R)}}),async localFunnel(w,g){let R=await me(()=>Ve(w,g));if(!R.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:C,remoteFeatures:O,..._}=R.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:w,versionId:R.versionId,evaluationMode:"local",evaluationRevision:R.control.evaluationRevision,document:R.document,payload:_})},assertFunnel(w,g,R){J();let C=p.funnels[w];if(!C||C.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(C.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Longplay");if(g!==void 0&&C.controlRevision!==g)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(R!==void 0&&!C.versions[R])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!d){d=!0,h++,a=0,T?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(o),clearTimeout(t),Me(),M(),b.clear();for(let w of S)w.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),D=0}}}}function Sn(e){let n=ue.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");return{async start(r){let s=Q.safeParse({...r,operation:"start"});if(!s.success||s.data.operation!=="start"||(n?s.data.customer!==void 0:s.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let l=s.data,y=Y({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||y.identify(e.apiKey);let f=be(e,await y.request("funnels",l));if(!f.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");if(f.run.source.id!==l.funnelId||f.run.locale!==(l.locale??"en")||!ce(f.run.parameters,l.parameters??{})||(l.customer?!f.customerId||l.customer.type==="id"&&f.customerId!==l.customer.value:f.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...f,runToken:f.runToken}}finally{y.dispose()}}}}async function pr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let r={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(r)!==L(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let l=re.test(e.credential);if(l?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let y=Sn({...e,scope:r,apiKey:e.credential}),f=i=>{let p=Rn({...e,scope:r,runToken:i,...l?{serverKey:e.credential}:{}});return l||p.identify(e.credential),p};return{async start(i){let p=await y.start({...i,funnelId:e.funnelId,...l?{customer:{type:"id",value:e.customerId}}:{}}),a=f(p.runToken),u=await a.get();return{...p,...u,controller:a}},async restore(i){let p=f(i),a=await p.get();if(a.run.source.id!==e.funnelId)throw p.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:i,controller:p}}}}export{Ee as a,Mn as b,be as c,_e as d,Xn as e,Nn as f,gn as g,lt as h,ce as i,yt as j,wt as k,Rn as l,jt as m,nr as n,Sn as o,pr as p};
@@ -1 +1 @@
1
- import{a as d,b as ee,l as B,o as te}from"./chunk-VQBQAKJD.js";import{b as Z}from"./chunk-OBZSDWLC.js";import{a as s}from"./chunk-OZZMZH7X.js";import{a as G}from"./chunk-DSPLGTQI.js";import{Ha as $,S as X,a as z,b as Y,c as K,d as Q,e as j,f as M,g as W,n as L,ua as a,wa as H}from"./chunk-KQ4MS4LR.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},he=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ne(t,e,n){let i=null,c=0,o=0,l=0,y=Promise.resolve(),P=!1;if(t&&(!n||z.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let g=()=>{if(P)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},b=r=>{if(r!==c)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(r){let u=g();if(!u.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let p=u.sha256?await u.sha256(Uint8Array.from(r,I=>I.charCodeAt(0))):await he(r);if(!/^[a-f0-9]{64}$/.test(p))throw new s("INVALID_STATE","Push credential digest is invalid");return p}function m(r){let u=M.parse(r);if(u.installationId.toLowerCase()!==g().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return u}async function C(r,u){let p=g(),I={installationId:p.installationId,publicKey:p.publicKey,issuedAt:new Date().toISOString(),...u},S=await p.sign(W(r,p.scope,I));return{...I,signature:S}}let f=(r,u,p)=>e.requestWithCredential?e.requestWithCredential(r,u,p):e.request(r,u);async function w(){let r=g(),u=c,p=i?await(e.session?.access()??i):null,I=_(r,v=>v),S;if(I.detachSeq!==null){let v=I.detachSeq,V=Y.parse(await C("detach",{sequence:v,platform:r.platform}));try{let N=await e.request("push/installations/detach",{...r.scope,...V},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let F=m(N.installation);if(F.bound||F.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof s&&N.status===404)S=N;else if(!(N instanceof s)||N.status!==412)throw N}S||_(r,N=>({...N,detachSeq:N.detachSeq===v?null:N.detachSeq}))}if(b(u),!p){if(S)throw S;return null}let q=a.bindPushInstallation,k=q.request.parse(await C("bind",{sequence:l,platform:r.platform,credentialDigest:await D(p)}));b(u);let R=q.response.parse(await f(q.path,k,p));b(u);let T=m(R.installation);if(!T.bound||T.identitySeq!==l)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return S&&I.detachSeq!==null&&l>I.detachSeq&&_(r,v=>({...v,detachSeq:v.detachSeq===I.detachSeq?null:v.detachSeq})),T}async function E(){g();let r=c,u=i?await(e.session?.access()??i):null;if(!u)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let p=a.readPushInstallation,I=p.request.parse(await C("read",{credentialDigest:await D(u)}));b(r);let S=p.response.parse(await f(p.path,I,u));return b(r),m(S.installation)}function h(r=w){let u=y.catch(()=>{}).then(r);return y=u,u.catch(p=>{try{t?.onError?.(p instanceof Error?p:new Error("Push synchronization failed"))}catch{}}),u}async function O(r,u,p){let I=g(),S=u.identity,q=u.observation,k=i?await(e.session?.access()??i):null;if(b(S),q!==o)throw new s("INVALID_STATE","Push observation changed during recovery");if(!k)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!r.connectionId||!r.kind||!r.token||!["granted","provisional"].includes(r.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await h(async()=>{if(b(S),await w(),b(S),q!==o)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(I,F=>p?F:{...F,addressSeq:U(F.addressSeq)}),v=await C(p?"recovery_confirm":"recovery_request",{...r,sequence:R.addressSeq,credentialDigest:await D(k),...p?{challenge:p}:{}}),V=p?Q.parse(v):K.parse(v);if(b(S),q!==o)throw new s("INVALID_STATE","Push observation changed during recovery");let N=await f(`push/installations/recovery/${p?"confirm":"request"}`,V,k);if(b(S),q!==o||_(I,F=>F).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(p){let F=a.updatePushAddress.response.parse(N),x=m(F.installation);if(!x.bound||x.identitySeq!==l||x.addressSeq!==R.addressSeq||x.connectionId!==r.connectionId||x.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return x}if(!N||typeof N!="object"||!("recovery"in N))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return j.parse(N.recovery)})}return{recoveryObserver(){g();let r={identity:c,observation:++o};return{async request(u){return j.parse(await O(u,r))},async confirm(u,p){return M.parse(await O(p,r,u))}}},identify(r){if(!t)return;l=_(t,p=>({...p,identitySeq:U(p.identitySeq)})).identitySeq,i=r,c++,o++},reset(){if(t)try{_(t,r=>{let u=U(r.identitySeq);return{...r,identitySeq:u,detachSeq:u}})}finally{i=null,c++,o++}},start(){t&&!P&&h()},destroy(){P=!0,i=null,c++,o++},async sync(){return await h()},read:E,async recover(){let r=g(),u=c,p=l;return o++,await h(async()=>{b(u);let I=await E();return b(u),l=_(r,q=>{if(q.identitySeq!==p)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...q,identitySeq:U(Math.max(q.identitySeq,I.identitySeq)),addressSeq:Math.max(q.addressSeq,I.addressSeq)}}).identitySeq,await w()})},tokenObserver(){g();let r=++o,u=c;return async p=>{if(r!==o||u!==c)return null;let I=g(),S=i?await(e.session?.access()??i):null;if(!S)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await h(),b(u),r!==o)return null;let q=_(I,v=>({...v,addressSeq:U(v.addressSeq)})),k=a.updatePushAddress,R=k.request.parse(await C("address",{...p,sequence:q.addressSeq,credentialDigest:await D(S)}));if(b(u),r!==o)return null;let T=await f(k.path,R,S);return b(u),r!==o||_(I,v=>v).addressSeq!==q.addressSeq?null:m(k.response.parse(T).installation)}}}}function re(t,e){let n={async preference(i){let c=a.readMessagingPreference;return(await d(t,c,{channel:i})).preference},async setPreference(i){let c=a.setMessagingPreference;return(await d(t,c,i)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(i){return n.setPreference({...i,channel:"push"})}}}}function ie(t,e,n={}){let i=!1;function c(){if(i)throw new s("CLOSED","SDK client was destroyed")}let o=new Set,l=P=>{for(let g of o)try{g(P)}catch{}},y=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:c,isIdentified:()=>!i&&!!t.session.peek(),methods:{subscribeIdentity(P){return c(),o.add(P),()=>{o.delete(P)}},identify(P){c();let g=typeof P=="string"?P:P.accessToken;if(!L.test(g))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(g),t.identify(P)},reset(){if(!i)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!i){i=!0,y(),o.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function A(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new s("INVALID_REQUEST","Customer requests use the verified session identity")}var ge={...a.readHoldings,request:a.readHoldings.request.omit({customerId:!0})};function se(t){return{async checkEntitlement(e){A(e);let n=a.checkEntitlement;return d(t,n,e)},async readHoldings(e={}){return d(t,ge,e)}}}function oe(t){return{async readLedger(e){let n=a.readLedger;return d(t,n,{query:e})},async readCreditStatement(e){A(e);let n=a.readCreditStatement;return d(t,n,e)},async quoteBalance(e){A(e);let n=a.quoteBalance;return d(t,n,{command:e})}}}function ae(t){return{async setupPayment(e){A(e);let n=a.setupPayment;return d(t,n,e)},async readPaymentSetup(e){A(e);let n=a.readPaymentSetup;return d(t,n,e)},async readBillingInvoice(e){A(e);let n=a.readBillingInvoice;return d(t,n,e)},async readBillingControls(e={}){A(e);let n=a.readBillingControls;return d(t,n,e)},async prepareBillingAuthorization(e){A(e);let n=a.prepareBillingAuthorization;return d(t,n,e)},async confirmBillingAuthorization(e){A(e);let n=a.confirmBillingAuthorization;return d(t,n,e)},async setBillingCoupons(e){A(e);let n=a.setBillingCoupons;return d(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){A(e);let n=a.revokeBillingAuthorization;return d(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){A(e);let n=a.listBillingInvoices;return d(t,n,e)},async confirmBillingAdjustment(e){A(e);let n=a.confirmBillingAdjustment;return d(t,n,e)}}}function ce(t){return{async previewUpdate(e){A(e);let n=a.previewUpdate;return d(t,n,e)},async update(e){A(e);let n=a.update;return d(t,n,e)},async readSubscriptionUpdate(e){A(e);let n=a.readSubscriptionUpdate;return d(t,n,e)},async restoreNativePurchase(e){A(e);let n=a.restoreNativePurchase;return d(t,n,e)},async previewAttach(e){A(e);let n=a.previewAttach;return d(t,n,e)},async attach(e){A(e);let n=a.attach;return d(t,n,e)},async readSubscriptionOperation(e){A(e);let n=a.readSubscriptionOperation;return d(t,n,e)}}}function ue(t){return{async redeemReward(e){return A(e),(await d(t,a.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return A(e),(await d(t,a.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return A(e),(await d(t,a.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let i=await d(t,a.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:i.offer,reason:i.reason}},async claimCoupon(e,n=crypto.randomUUID()){let i=await d(t,a.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:i.offer,reason:i.reason}},async listOffers(){return(await d(t,a.listOffers,{},{response:"Invalid offers response"})).offers}}}function de(t){return{...se(t),...oe(t),...ae(t),...ce(t),...ue(t)}}function pe(t){return{async resolveContent(e){A(e);let n=a.resolveContent;return d(t,n,e)},async resolvePaywall(e){A(e);let n=a.resolvePaywall;return d(t,n,e)},async resolveOffering(e){A(e);let n=a.resolveOffering;return d(t,n,e)}}}var J=t=>new TextEncoder().encode(JSON.stringify(t)).length,le=16384;function fe(t,e){let n=0,i,c=f=>{i={config:structuredClone(f),until:Date.now()+3e4}},o=[],l=null,y;function P(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function g(){y||!o.length||(y=setTimeout(()=>{y=void 0,D().catch(()=>{}).finally(g)},5e3),typeof y=="object"&&"unref"in y&&y.unref())}function b(f,w={},E={}){if(P(),i&&Date.now()<i.until&&!X(i.config,f))return;C();let h=a.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:f,properties:w,...E}]}).events[0];if(J({events:[h]})>le)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(o.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");o.push(structuredClone(h)),g()}async function D(f=!1){if(P(),l)return l;let w=n,E=(async()=>{let h={inserted:0,duplicates:0,rejected:0,skipped:0},O=o.length;for(;O&&w===n;){let r=[],u=J({events:[]});for(let S of o.slice(0,Math.min(O,100))){let q=J(S)+(r.length?1:0);if(r.length&&u+q>le)break;r.push(S),u+=q}let p=a.trackEvents,I=await d(t,p,{events:r},void 0,{keepalive:f});if(w!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(I.inserted+I.duplicates+I.rejected+I.skipped!==r.length)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement");c(I.analyticsConfig),o.splice(0,r.length),O-=r.length,h.inserted+=I.inserted,h.duplicates+=I.duplicates,h.rejected+=I.rejected,h.skipped+=I.skipped}return h})();l=E;try{return await E}finally{l===E&&(l=null)}}let m;function C(){if(m||typeof document>"u")return;let f=()=>{document.visibilityState==="hidden"&&e()&&o.length&&D(!0).catch(()=>{})};document.addEventListener("visibilitychange",f),m=()=>document.removeEventListener("visibilitychange",f)}return{rememberConfiguration:c,track:b,flush:D,reset(){n++,i=void 0,clearTimeout(y),y=void 0,o=[],l=null},detachVisibility(){m?.(),m=void 0}}}function me(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function we(t){let e=me(t),{merchandiseId:n,merchandise:i,...c}=t;return{...c,...e?{merchandise:e}:{}}}function ye(t,e,n,i,c){if(c&&i&&(c.scope.projectId!==i.projectId||c.scope.environment!==i.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=0,l=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function P(g={}){c||y();let b=o,D=!1,m=async()=>{if(D||b!==o)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=a.getFeatures,T=c?{scope:{projectId:c.scope.projectId,environment:c.scope.environment},payload:await c.features()}:await d(t,R,{});if(b!==o)throw new s("IDENTITY_CHANGED","Feature identity changed");if(i&&(T.scope.projectId!==i.projectId||T.scope.environment!==i.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(T.payload.analyticsConfig),T},C=await m(),f=!0,w,E=R=>{try{g.onError?.(R)}catch{}},h=(R,T,v)=>{try{let V=me(v);n.track(R,T,V?{merchandise:V}:{})}catch(V){E(V)}},O=ee({assertUsable:c?.assertFeatures,scope:C.scope,attributes:g.attributes,onError:g.onError,load:async()=>f?(f=!1,C.payload):(await m()).payload,evaluateRemote:async R=>{if(b!==o)throw new s("IDENTITY_CHANGED","Feature identity changed");let T=a.evaluateFeatures,v=await d(t,T,{...R,attributes:we(R.attributes)});if(v.scope.projectId!==C.scope.projectId||v.scope.environment!==C.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,T,v)=>h("Experiment Viewed",{experimentId:R.key,variationId:T.key},v),onFeatureUsage:(R,T,v)=>h("Feature Evaluated",{feature:R,value:T.value,source:T.source,ruleId:T.ruleId,...T.experimentResult?{variationId:T.experimentResult.key}:{}},v)}),r=O.refresh;function u(){clearTimeout(w),!c&&(D||b!==o||!O.expiresAt||(w=setTimeout(()=>{p().catch(E)},Math.min(2147483647,Math.max(1e3,Date.parse(O.expiresAt)-Date.now()))),typeof w=="object"&&"unref"in w&&w.unref()))}async function p(){try{return await r()}finally{u()}}let I=()=>{D||p().catch(E)},S=O.subscribe(u),q=c?.subscribe(()=>{!D&&c.fresh&&p().catch(E)});function k(){D||(D=!0,clearTimeout(w),typeof window<"u"&&window.removeEventListener("focus",I),S(),q?.(),O.reset(),l.delete(k))}l.add(k);try{await O.init(),(g.attributes?.merchandise||g.attributes?.merchandiseId)&&await O.refreshRemote()}catch(R){throw k(),R}return u(),!c&&typeof window<"u"&&window.addEventListener("focus",I),Object.assign(O,{refresh:p,destroy:k})}return{features:P,reset(g){o++,g();for(let b of l)b()}}}import{z as ve}from"zod";function Ie(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,i=ve.object({funnelId:H.shape.id,funnelVersionId:H.shape.versionId.optional()}).safeParse(n);if(!i.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let c=Object.freeze(i.data);function o(l){if("customerId"in l)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==c.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==c.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...c}}return{async claimCoupon(l,y=crypto.randomUUID()){let P=a.grantOffer,g=await d(t,P,o({couponId:l,requestId:y}));return{offer:g.offer,reason:g.reason}},async resolveOffering(l){let y=a.resolveOffering;return d(t,y,o(l))},async resolvePaywall(l){let y=a.resolvePaywall;return d(t,y,o(l))},async previewAttach(l){let y=a.previewAttach;return d(t,y,o(l))}}}function Dt(t){return Ae(t)}function Ae(t){let e=Z(t),n=e.request,i;try{i=ne(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let c=ie(e,()=>{l.reset(o.reset),o.detachVisibility()},{beforeIdentify:i.identify,beforeReset:i.reset,afterChange:i.start,beforeDestroy:i.destroy}),o=fe(n,c.isIdentified),l=ye(n,c.isIdentified,o,t.scope,t.configuration);return{session:e.session,...re(n,i),...de(n),...pe(n),forFunnel(y){return c.assertActive(),Ie(n,y)},async features(y={}){return c.assertActive(),l.features(y)},track(y,P,g={}){return o.track(y,P,g)},flush(){return o.flush()},...c.methods}}function Ut(t){if(!L.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=te({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let i=await e.start(n),c=B({...t,runToken:i.runToken});c.identify(t.customerToken);let o=i.run.instruction?.type==="evaluate_segment"?await c.get():i;return{...i,...o,controller:c}}}}function Gt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,i=0,c=new Set,o=new Map,l=new Map;async function y(m){let C,f=new Promise((w,E)=>{C=setTimeout(()=>E(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),f])}finally{clearTimeout(C)}}function P(m){throw m instanceof s&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(i++,n?.reset(),n=void 0,e=null,o.clear(),l.clear()),m}function g(m,C){if(C!==i)throw new s("IDENTITY_CHANGED","Process was detached during a request");let f=$.parse(m);if(f.scope.projectId!==t.scope.projectId||f.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==f.run.id||e.run.source.versionId!==f.run.source.versionId||e.run.source.id!==f.run.source.id||e.run.runExpiresAt!==f.run.runExpiresAt||e.run.identity.startedAs!==f.run.identity.startedAs||e.run.identity.participantId!==f.run.identity.participantId||e.run.identity.binding&&f.run.identity.binding&&e.run.identity.binding.id!==f.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||f.run.revision>=e.run.revision){if(e?.run.identity.binding&&!f.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=f;for(let I of c)G(I,f.run);f.run.instruction?.type==="authentication_required"&&G(t.onAuthenticationRequired,f.run)}f.settlement?.accepted!==void 0&&l.set(f.settlement.requestId,f.settlement.accepted);let{identity:w,instruction:E,...h}=f.run,{contract:O,settlement:r,...u}=f,p=r&&(({accepted:I,...S})=>S)(r);return{...u,run:{...h,authenticated:w.binding!==null,instruction:E?.type==="authentication_required"?null:E},...p?{settlement:p}:{}}}let b=m=>(o.has(m)||o.set(m,e?.run.identity.binding?.id??null),o.get(m));async function D(m){let C=i,f=e?.run.identity.binding?.id??null,w=h=>{if(f!==(e?.run.identity.binding?.id??null))throw h;return P(h)};if(m.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(w)}let E;if(m.operation==="get"){let{operation:h,customerToken:O,...r}=m;E=await y(()=>t.adapter.get({...r,...r.settlementRequestId?{settlementBindingId:b(r.settlementRequestId)}:{}})).catch(w)}else if(m.operation==="review")E=await y(()=>t.adapter.review(m.receiptId)).catch(w);else{if(m.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:h,...O}=m;E=await y(()=>t.adapter.command(O,b(O.requestId))).catch(w)}}return g(E,C)}return{get view(){return e?.run??null},get controller(){return n},async open(m){let C=i,f=await y(()=>t.adapter.open(m)).catch(P);if(g(f,C),!n){n=B({...t,runToken:f.runToken,process:{request:D,binding:b,restore(h){for(let[O,r]of Object.entries(h))o.set(O,r)}}});let w=n,E=w.submit;w.submit=async h=>{try{return await E(h)}catch(O){if(!(O instanceof s)||O.reason!=="IDENTITY_CONTEXT_CHANGED"||h.operation!=="submit"||h.input.type!=="screen"||o.get(h.requestId)!==null)throw O;await w.settle?.(h.requestId),await w.get();let r=w.view;if(l.get(h.requestId)!==!1||!r||r.id!==e?.run.id||r.nodeId!==h.nodeId||r.visit!==h.visit||!e?.run.identity.binding)throw O;return E({...h,requestId:crypto.randomUUID(),revision:r.revision})}}}await n.get();for(let w of n.pendingCommands??[])o.has(w.requestId)&&o.get(w.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(w.requestId);return{run:e.run,controller:n}},async syncIdentity(){let m=i;g(await y(()=>t.adapter.syncIdentity()).catch(P),m),await n?.get();for(let C of n?.pendingCommands??[])o.has(C.requestId)&&o.get(C.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(C.requestId);return e.run},async detach(){i++,n?.reset(),n=void 0,e=null,o.clear(),l.clear(),await y(()=>t.adapter.detach())},forProcess(m){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:m}},subscribe(m){return c.add(m),()=>{c.delete(m)}},destroy(){i++,n?.reset(),n=void 0,e=null,o.clear(),l.clear(),c.clear()}}}export{Dt as a,Ae as b,Ut as c,Gt as d};
1
+ import{a as d,b as ee,l as B,o as te}from"./chunk-PNIWWTLM.js";import{b as Z}from"./chunk-D5D75HM6.js";import{a as s}from"./chunk-OZZMZH7X.js";import{a as G}from"./chunk-DSPLGTQI.js";import{Ha as $,S as X,a as z,b as Y,c as K,d as Q,e as j,f as M,g as W,n as L,ua as a,wa as H}from"./chunk-KOGWARWA.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},he=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ne(t,e,n){let i=null,c=0,o=0,l=0,y=Promise.resolve(),P=!1;if(t&&(!n||z.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let g=()=>{if(P)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},b=r=>{if(r!==c)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(r){let u=g();if(!u.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let p=u.sha256?await u.sha256(Uint8Array.from(r,I=>I.charCodeAt(0))):await he(r);if(!/^[a-f0-9]{64}$/.test(p))throw new s("INVALID_STATE","Push credential digest is invalid");return p}function m(r){let u=M.parse(r);if(u.installationId.toLowerCase()!==g().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return u}async function C(r,u){let p=g(),I={installationId:p.installationId,publicKey:p.publicKey,issuedAt:new Date().toISOString(),...u},S=await p.sign(W(r,p.scope,I));return{...I,signature:S}}let f=(r,u,p)=>e.requestWithCredential?e.requestWithCredential(r,u,p):e.request(r,u);async function w(){let r=g(),u=c,p=i?await(e.session?.access()??i):null,I=_(r,v=>v),S;if(I.detachSeq!==null){let v=I.detachSeq,V=Y.parse(await C("detach",{sequence:v,platform:r.platform}));try{let N=await e.request("push/installations/detach",{...r.scope,...V},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let F=m(N.installation);if(F.bound||F.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof s&&N.status===404)S=N;else if(!(N instanceof s)||N.status!==412)throw N}S||_(r,N=>({...N,detachSeq:N.detachSeq===v?null:N.detachSeq}))}if(b(u),!p){if(S)throw S;return null}let q=a.bindPushInstallation,k=q.request.parse(await C("bind",{sequence:l,platform:r.platform,credentialDigest:await D(p)}));b(u);let R=q.response.parse(await f(q.path,k,p));b(u);let T=m(R.installation);if(!T.bound||T.identitySeq!==l)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return S&&I.detachSeq!==null&&l>I.detachSeq&&_(r,v=>({...v,detachSeq:v.detachSeq===I.detachSeq?null:v.detachSeq})),T}async function E(){g();let r=c,u=i?await(e.session?.access()??i):null;if(!u)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let p=a.readPushInstallation,I=p.request.parse(await C("read",{credentialDigest:await D(u)}));b(r);let S=p.response.parse(await f(p.path,I,u));return b(r),m(S.installation)}function h(r=w){let u=y.catch(()=>{}).then(r);return y=u,u.catch(p=>{try{t?.onError?.(p instanceof Error?p:new Error("Push synchronization failed"))}catch{}}),u}async function O(r,u,p){let I=g(),S=u.identity,q=u.observation,k=i?await(e.session?.access()??i):null;if(b(S),q!==o)throw new s("INVALID_STATE","Push observation changed during recovery");if(!k)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!r.connectionId||!r.kind||!r.token||!["granted","provisional"].includes(r.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await h(async()=>{if(b(S),await w(),b(S),q!==o)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(I,F=>p?F:{...F,addressSeq:U(F.addressSeq)}),v=await C(p?"recovery_confirm":"recovery_request",{...r,sequence:R.addressSeq,credentialDigest:await D(k),...p?{challenge:p}:{}}),V=p?Q.parse(v):K.parse(v);if(b(S),q!==o)throw new s("INVALID_STATE","Push observation changed during recovery");let N=await f(`push/installations/recovery/${p?"confirm":"request"}`,V,k);if(b(S),q!==o||_(I,F=>F).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(p){let F=a.updatePushAddress.response.parse(N),x=m(F.installation);if(!x.bound||x.identitySeq!==l||x.addressSeq!==R.addressSeq||x.connectionId!==r.connectionId||x.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return x}if(!N||typeof N!="object"||!("recovery"in N))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return j.parse(N.recovery)})}return{recoveryObserver(){g();let r={identity:c,observation:++o};return{async request(u){return j.parse(await O(u,r))},async confirm(u,p){return M.parse(await O(p,r,u))}}},identify(r){if(!t)return;l=_(t,p=>({...p,identitySeq:U(p.identitySeq)})).identitySeq,i=r,c++,o++},reset(){if(t)try{_(t,r=>{let u=U(r.identitySeq);return{...r,identitySeq:u,detachSeq:u}})}finally{i=null,c++,o++}},start(){t&&!P&&h()},destroy(){P=!0,i=null,c++,o++},async sync(){return await h()},read:E,async recover(){let r=g(),u=c,p=l;return o++,await h(async()=>{b(u);let I=await E();return b(u),l=_(r,q=>{if(q.identitySeq!==p)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...q,identitySeq:U(Math.max(q.identitySeq,I.identitySeq)),addressSeq:Math.max(q.addressSeq,I.addressSeq)}}).identitySeq,await w()})},tokenObserver(){g();let r=++o,u=c;return async p=>{if(r!==o||u!==c)return null;let I=g(),S=i?await(e.session?.access()??i):null;if(!S)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await h(),b(u),r!==o)return null;let q=_(I,v=>({...v,addressSeq:U(v.addressSeq)})),k=a.updatePushAddress,R=k.request.parse(await C("address",{...p,sequence:q.addressSeq,credentialDigest:await D(S)}));if(b(u),r!==o)return null;let T=await f(k.path,R,S);return b(u),r!==o||_(I,v=>v).addressSeq!==q.addressSeq?null:m(k.response.parse(T).installation)}}}}function re(t,e){let n={async preference(i){let c=a.readMessagingPreference;return(await d(t,c,{channel:i})).preference},async setPreference(i){let c=a.setMessagingPreference;return(await d(t,c,i)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(i){return n.setPreference({...i,channel:"push"})}}}}function ie(t,e,n={}){let i=!1;function c(){if(i)throw new s("CLOSED","SDK client was destroyed")}let o=new Set,l=P=>{for(let g of o)try{g(P)}catch{}},y=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:c,isIdentified:()=>!i&&!!t.session.peek(),methods:{subscribeIdentity(P){return c(),o.add(P),()=>{o.delete(P)}},identify(P){c();let g=typeof P=="string"?P:P.accessToken;if(!L.test(g))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(g),t.identify(P)},reset(){if(!i)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!i){i=!0,y(),o.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function A(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new s("INVALID_REQUEST","Customer requests use the verified session identity")}var ge={...a.readHoldings,request:a.readHoldings.request.omit({customerId:!0})};function se(t){return{async checkEntitlement(e){A(e);let n=a.checkEntitlement;return d(t,n,e)},async readHoldings(e={}){return d(t,ge,e)}}}function oe(t){return{async readLedger(e){let n=a.readLedger;return d(t,n,{query:e})},async readCreditStatement(e){A(e);let n=a.readCreditStatement;return d(t,n,e)},async quoteBalance(e){A(e);let n=a.quoteBalance;return d(t,n,{command:e})}}}function ae(t){return{async setupPayment(e){A(e);let n=a.setupPayment;return d(t,n,e)},async readPaymentSetup(e){A(e);let n=a.readPaymentSetup;return d(t,n,e)},async readBillingInvoice(e){A(e);let n=a.readBillingInvoice;return d(t,n,e)},async readBillingControls(e={}){A(e);let n=a.readBillingControls;return d(t,n,e)},async prepareBillingAuthorization(e){A(e);let n=a.prepareBillingAuthorization;return d(t,n,e)},async confirmBillingAuthorization(e){A(e);let n=a.confirmBillingAuthorization;return d(t,n,e)},async setBillingCoupons(e){A(e);let n=a.setBillingCoupons;return d(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){A(e);let n=a.revokeBillingAuthorization;return d(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){A(e);let n=a.listBillingInvoices;return d(t,n,e)},async confirmBillingAdjustment(e){A(e);let n=a.confirmBillingAdjustment;return d(t,n,e)}}}function ce(t){return{async previewUpdate(e){A(e);let n=a.previewUpdate;return d(t,n,e)},async update(e){A(e);let n=a.update;return d(t,n,e)},async readSubscriptionUpdate(e){A(e);let n=a.readSubscriptionUpdate;return d(t,n,e)},async restoreNativePurchase(e){A(e);let n=a.restoreNativePurchase;return d(t,n,e)},async previewAttach(e){A(e);let n=a.previewAttach;return d(t,n,e)},async attach(e){A(e);let n=a.attach;return d(t,n,e)},async readSubscriptionOperation(e){A(e);let n=a.readSubscriptionOperation;return d(t,n,e)}}}function ue(t){return{async redeemReward(e){return A(e),(await d(t,a.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return A(e),(await d(t,a.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return A(e),(await d(t,a.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let i=await d(t,a.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:i.offer,reason:i.reason}},async claimCoupon(e,n=crypto.randomUUID()){let i=await d(t,a.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:i.offer,reason:i.reason}},async listOffers(){return(await d(t,a.listOffers,{},{response:"Invalid offers response"})).offers}}}function de(t){return{...se(t),...oe(t),...ae(t),...ce(t),...ue(t)}}function pe(t){return{async resolveContent(e){A(e);let n=a.resolveContent;return d(t,n,e)},async resolvePaywall(e){A(e);let n=a.resolvePaywall;return d(t,n,e)},async resolveOffering(e){A(e);let n=a.resolveOffering;return d(t,n,e)}}}var J=t=>new TextEncoder().encode(JSON.stringify(t)).length,le=16384;function fe(t,e){let n=0,i,c=f=>{i={config:structuredClone(f),until:Date.now()+3e4}},o=[],l=null,y;function P(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function g(){y||!o.length||(y=setTimeout(()=>{y=void 0,D().catch(()=>{}).finally(g)},5e3),typeof y=="object"&&"unref"in y&&y.unref())}function b(f,w={},E={}){if(P(),i&&Date.now()<i.until&&!X(i.config,f))return;C();let h=a.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:f,properties:w,...E}]}).events[0];if(J({events:[h]})>le)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(o.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");o.push(structuredClone(h)),g()}async function D(f=!1){if(P(),l)return l;let w=n,E=(async()=>{let h={inserted:0,duplicates:0,rejected:0,skipped:0},O=o.length;for(;O&&w===n;){let r=[],u=J({events:[]});for(let S of o.slice(0,Math.min(O,100))){let q=J(S)+(r.length?1:0);if(r.length&&u+q>le)break;r.push(S),u+=q}let p=a.trackEvents,I=await d(t,p,{events:r},void 0,{keepalive:f});if(w!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(I.inserted+I.duplicates+I.rejected+I.skipped!==r.length)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement");c(I.analyticsConfig),o.splice(0,r.length),O-=r.length,h.inserted+=I.inserted,h.duplicates+=I.duplicates,h.rejected+=I.rejected,h.skipped+=I.skipped}return h})();l=E;try{return await E}finally{l===E&&(l=null)}}let m;function C(){if(m||typeof document>"u")return;let f=()=>{document.visibilityState==="hidden"&&e()&&o.length&&D(!0).catch(()=>{})};document.addEventListener("visibilitychange",f),m=()=>document.removeEventListener("visibilitychange",f)}return{rememberConfiguration:c,track:b,flush:D,reset(){n++,i=void 0,clearTimeout(y),y=void 0,o=[],l=null},detachVisibility(){m?.(),m=void 0}}}function me(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function we(t){let e=me(t),{merchandiseId:n,merchandise:i,...c}=t;return{...c,...e?{merchandise:e}:{}}}function ye(t,e,n,i,c){if(c&&i&&(c.scope.projectId!==i.projectId||c.scope.environment!==i.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=0,l=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function P(g={}){c||y();let b=o,D=!1,m=async()=>{if(D||b!==o)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=a.getFeatures,T=c?{scope:{projectId:c.scope.projectId,environment:c.scope.environment},payload:await c.features()}:await d(t,R,{});if(b!==o)throw new s("IDENTITY_CHANGED","Feature identity changed");if(i&&(T.scope.projectId!==i.projectId||T.scope.environment!==i.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(T.payload.analyticsConfig),T},C=await m(),f=!0,w,E=R=>{try{g.onError?.(R)}catch{}},h=(R,T,v)=>{try{let V=me(v);n.track(R,T,V?{merchandise:V}:{})}catch(V){E(V)}},O=ee({assertUsable:c?.assertFeatures,scope:C.scope,attributes:g.attributes,onError:g.onError,load:async()=>f?(f=!1,C.payload):(await m()).payload,evaluateRemote:async R=>{if(b!==o)throw new s("IDENTITY_CHANGED","Feature identity changed");let T=a.evaluateFeatures,v=await d(t,T,{...R,attributes:we(R.attributes)});if(v.scope.projectId!==C.scope.projectId||v.scope.environment!==C.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,T,v)=>h("Experiment Viewed",{experimentId:R.key,variationId:T.key},v),onFeatureUsage:(R,T,v)=>h("Feature Evaluated",{feature:R,value:T.value,source:T.source,ruleId:T.ruleId,...T.experimentResult?{variationId:T.experimentResult.key}:{}},v)}),r=O.refresh;function u(){clearTimeout(w),!c&&(D||b!==o||!O.expiresAt||(w=setTimeout(()=>{p().catch(E)},Math.min(2147483647,Math.max(1e3,Date.parse(O.expiresAt)-Date.now()))),typeof w=="object"&&"unref"in w&&w.unref()))}async function p(){try{return await r()}finally{u()}}let I=()=>{D||p().catch(E)},S=O.subscribe(u),q=c?.subscribe(()=>{!D&&c.fresh&&p().catch(E)});function k(){D||(D=!0,clearTimeout(w),typeof window<"u"&&window.removeEventListener("focus",I),S(),q?.(),O.reset(),l.delete(k))}l.add(k);try{await O.init(),(g.attributes?.merchandise||g.attributes?.merchandiseId)&&await O.refreshRemote()}catch(R){throw k(),R}return u(),!c&&typeof window<"u"&&window.addEventListener("focus",I),Object.assign(O,{refresh:p,destroy:k})}return{features:P,reset(g){o++,g();for(let b of l)b()}}}import{z as ve}from"zod";function Ie(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,i=ve.object({funnelId:H.shape.id,funnelVersionId:H.shape.versionId.optional()}).safeParse(n);if(!i.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let c=Object.freeze(i.data);function o(l){if("customerId"in l)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==c.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==c.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...c}}return{async claimCoupon(l,y=crypto.randomUUID()){let P=a.grantOffer,g=await d(t,P,o({couponId:l,requestId:y}));return{offer:g.offer,reason:g.reason}},async resolveOffering(l){let y=a.resolveOffering;return d(t,y,o(l))},async resolvePaywall(l){let y=a.resolvePaywall;return d(t,y,o(l))},async previewAttach(l){let y=a.previewAttach;return d(t,y,o(l))}}}function Dt(t){return Ae(t)}function Ae(t){let e=Z(t),n=e.request,i;try{i=ne(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let c=ie(e,()=>{l.reset(o.reset),o.detachVisibility()},{beforeIdentify:i.identify,beforeReset:i.reset,afterChange:i.start,beforeDestroy:i.destroy}),o=fe(n,c.isIdentified),l=ye(n,c.isIdentified,o,t.scope,t.configuration);return{session:e.session,...re(n,i),...de(n),...pe(n),forFunnel(y){return c.assertActive(),Ie(n,y)},async features(y={}){return c.assertActive(),l.features(y)},track(y,P,g={}){return o.track(y,P,g)},flush(){return o.flush()},...c.methods}}function Ut(t){if(!L.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=te({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let i=await e.start(n),c=B({...t,runToken:i.runToken});c.identify(t.customerToken);let o=i.run.instruction?.type==="evaluate_segment"?await c.get():i;return{...i,...o,controller:c}}}}function Gt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,i=0,c=new Set,o=new Map,l=new Map;async function y(m){let C,f=new Promise((w,E)=>{C=setTimeout(()=>E(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),f])}finally{clearTimeout(C)}}function P(m){throw m instanceof s&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(i++,n?.reset(),n=void 0,e=null,o.clear(),l.clear()),m}function g(m,C){if(C!==i)throw new s("IDENTITY_CHANGED","Process was detached during a request");let f=$.parse(m);if(f.scope.projectId!==t.scope.projectId||f.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==f.run.id||e.run.source.versionId!==f.run.source.versionId||e.run.source.id!==f.run.source.id||e.run.runExpiresAt!==f.run.runExpiresAt||e.run.identity.startedAs!==f.run.identity.startedAs||e.run.identity.participantId!==f.run.identity.participantId||e.run.identity.binding&&f.run.identity.binding&&e.run.identity.binding.id!==f.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||f.run.revision>=e.run.revision){if(e?.run.identity.binding&&!f.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=f;for(let I of c)G(I,f.run);f.run.instruction?.type==="authentication_required"&&G(t.onAuthenticationRequired,f.run)}f.settlement?.accepted!==void 0&&l.set(f.settlement.requestId,f.settlement.accepted);let{identity:w,instruction:E,...h}=f.run,{contract:O,settlement:r,...u}=f,p=r&&(({accepted:I,...S})=>S)(r);return{...u,run:{...h,authenticated:w.binding!==null,instruction:E?.type==="authentication_required"?null:E},...p?{settlement:p}:{}}}let b=m=>(o.has(m)||o.set(m,e?.run.identity.binding?.id??null),o.get(m));async function D(m){let C=i,f=e?.run.identity.binding?.id??null,w=h=>{if(f!==(e?.run.identity.binding?.id??null))throw h;return P(h)};if(m.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(w)}let E;if(m.operation==="get"){let{operation:h,customerToken:O,...r}=m;E=await y(()=>t.adapter.get({...r,...r.settlementRequestId?{settlementBindingId:b(r.settlementRequestId)}:{}})).catch(w)}else if(m.operation==="review")E=await y(()=>t.adapter.review(m.receiptId)).catch(w);else{if(m.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:h,...O}=m;E=await y(()=>t.adapter.command(O,b(O.requestId))).catch(w)}}return g(E,C)}return{get view(){return e?.run??null},get controller(){return n},async open(m){let C=i,f=await y(()=>t.adapter.open(m)).catch(P);if(g(f,C),!n){n=B({...t,runToken:f.runToken,process:{request:D,binding:b,restore(h){for(let[O,r]of Object.entries(h))o.set(O,r)}}});let w=n,E=w.submit;w.submit=async h=>{try{return await E(h)}catch(O){if(!(O instanceof s)||O.reason!=="IDENTITY_CONTEXT_CHANGED"||h.operation!=="submit"||h.input.type!=="screen"||o.get(h.requestId)!==null)throw O;await w.settle?.(h.requestId),await w.get();let r=w.view;if(l.get(h.requestId)!==!1||!r||r.id!==e?.run.id||r.nodeId!==h.nodeId||r.visit!==h.visit||!e?.run.identity.binding)throw O;return E({...h,requestId:crypto.randomUUID(),revision:r.revision})}}}await n.get();for(let w of n.pendingCommands??[])o.has(w.requestId)&&o.get(w.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(w.requestId);return{run:e.run,controller:n}},async syncIdentity(){let m=i;g(await y(()=>t.adapter.syncIdentity()).catch(P),m),await n?.get();for(let C of n?.pendingCommands??[])o.has(C.requestId)&&o.get(C.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(C.requestId);return e.run},async detach(){i++,n?.reset(),n=void 0,e=null,o.clear(),l.clear(),await y(()=>t.adapter.detach())},forProcess(m){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:m}},subscribe(m){return c.add(m),()=>{c.delete(m)}},destroy(){i++,n?.reset(),n=void 0,e=null,o.clear(),l.clear(),c.clear()}}}export{Dt as a,Ae as b,Ut as c,Gt as d};
@@ -1 +1 @@
1
- import{a as u}from"./chunk-OZZMZH7X.js";import{pa as E,qa as M,ra as j,sa as O,ta as T}from"./chunk-KQ4MS4LR.js";import{k as w}from"./chunk-VSJOHWDL.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
1
+ import{a as u}from"./chunk-OZZMZH7X.js";import{pa as E,qa as M,ra as j,sa as O,ta as T}from"./chunk-KOGWARWA.js";import{k as w}from"./chunk-VSJOHWDL.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
@@ -1 +1 @@
1
- import{f as F,j as Q}from"./chunk-33FQUT3Z.js";import{b as B}from"./chunk-SSLZKIIU.js";import{a as z,b as _}from"./chunk-MOWYD2TV.js";import"./chunk-OBZSDWLC.js";import{a as d}from"./chunk-OZZMZH7X.js";import{a as v}from"./chunk-DSPLGTQI.js";import{Q as M}from"./chunk-KQ4MS4LR.js";import{A as V,ka as P,qa as U,xa as N,ya as q}from"./chunk-VSJOHWDL.js";import{z as p}from"zod";var x=new WeakMap;function W(r){let t={string:p.string(),number:p.number().finite(),boolean:p.boolean(),strings:p.array(p.string()),json:V}[r.type];return r.nullable?t.nullable():t}async function ie(r,t){return $(r,t,!1)}async function se(r,t){return $(r,t,!0)}async function $(r,t,w){t.signal?.throwIfAborted();let L=M.parse(t.content),o=L.document;if(x.has(r))throw new d("CONFLICT","Content is already mounted in this container");let f=p.record(p.string(),V).parse(t.inputs??{});if(Object.keys(f).length>40)throw new d("INVALID_REQUEST","Too many content inputs");for(let[e,s]of Object.entries(f))N.parse({[e]:s});if(Object.keys(f).some(e=>!Object.hasOwn(o.contract.inputs,e)))throw new d("INVALID_REQUEST","Undeclared content input");for(let[e,s]of Object.entries(o.contract.inputs))if(Object.hasOwn(f,e))W(s).parse(f[e]);else if(s.required)throw new d("INVALID_REQUEST",`Missing content input ${e}`);for(let e of Object.keys(o.contract.outputs))if(typeof t.actions[e]!="function")throw new d("INVALID_REQUEST",`Missing host handler for ${e}`);let J=q.parse(t.bindings??[]),c=r.ownerDocument,T,k=o.kind==="popup",n=k?c.createElement("dialog"):null,i=c.createElement("div");if(i.dataset.indianaContent=o.kind,i.setAttribute("aria-label",o.name),i.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",o.name);let e=o.screen.presentation;n.style.cssText="box-sizing:border-box;padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto",e.type==="modal"||e.type==="sheet"?(n.style.width=`${P[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",n.append(i),r.append(n)}else r.append(i);let l=!1,C=!1,g=!1;w&&!n&&(i.style.width=`${r.getBoundingClientRect().width||c.defaultView?.innerWidth||800}px`);let G=w?F(n??i):()=>{},D,A,S=new Promise((e,s)=>{D=e,A=s});S.catch(()=>{});let u=null,E=structuredClone(o.screen);E.actions=E.actions.map(e=>e.type==="event"?{...e,close:!1}:e);let y;function m(){l||(l=!0,t.signal?.removeEventListener("abort",m),A(new Error("Content preparation cancelled")),y?.destroy(),n?.close(),n?.remove(),i.remove(),x.delete(r),n&&T?.())}let O=()=>{g&&(m(),v(t.onDismiss))};if(n){let e=c.createElement("button");e.type="button",e.textContent="\xD7",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),_(e,o.screen.theme),e.addEventListener("click",O),n.prepend(e)}n?.addEventListener("cancel",e=>{e.preventDefault(),O()});async function H(){if(l||!g||C||!u)return;let e=u;C=!0,i.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),u=null}catch(s){v(t.onError,s)}finally{C=!1,l||i.removeAttribute("aria-busy")}}function R(){if(l)throw new d("CONFLICT","Content host has been destroyed");g||(T=B(c),G(),w&&!n&&(i.style.width="100%"),n&&(n.showModal(),z(n,o.screen.presentation.type)),g=!0)}try{w||R(),y=Q(i,{mode:"live",rendererUrl:t.rendererUrl,title:o.name,viewportHeight:o.kind==="page"?r.clientHeight||c.defaultView?.innerHeight||800:void 0,onRendered:a=>{a&&n?.setAttribute("aria-label",a),D()},onError:a=>{let I=new Error(a);A(I),v(t.onError,I)},onEscape:k?O:void 0,onAction:(a,I,K)=>{if(l||!g||C||u)return;let h=o.screen.actions.find(b=>b.id===a),j=o.contract.outputs[a];if(!(h?.type!=="event"||!j))try{let b=W(j).parse(Object.hasOwn(h.properties,"value")?h.properties.value:h.properties);u={requestId:crypto.randomUUID(),contentVersionId:L.id,actionId:a,event:h.event,value:b,selection:I??{},answers:K??{},requestedClose:h.close},H()}catch(b){v(t.onError,b)}}});let e={destroy:m,show:R,get pendingAction(){return u?structuredClone(u):null},retryAction:H,updateCapabilities:a=>y?.updateCapabilities(a)};x.set(r,e),t.signal?.addEventListener("abort",m,{once:!0}),t.signal?.aborted&&(m(),t.signal.throwIfAborted());let s=U(E,[t.locale,...c.defaultView?.navigator.languages??[]]);if(y.update(E,s,{capabilities:t.capabilities,serverInput:{bindings:J,answers:{},values:f}}),await Promise.race([y.ready,S]),w&&await S,l)throw new Error("Content preparation cancelled");return e}catch(e){throw m(),e}}export{ie as mountContent,se as prepareContent};
1
+ import{f as F,j as Q}from"./chunk-33FQUT3Z.js";import{b as B}from"./chunk-SSLZKIIU.js";import{a as z,b as _}from"./chunk-MOWYD2TV.js";import"./chunk-D5D75HM6.js";import{a as d}from"./chunk-OZZMZH7X.js";import{a as v}from"./chunk-DSPLGTQI.js";import{Q as M}from"./chunk-KOGWARWA.js";import{A as V,ka as P,qa as U,xa as N,ya as q}from"./chunk-VSJOHWDL.js";import{z as p}from"zod";var x=new WeakMap;function W(r){let t={string:p.string(),number:p.number().finite(),boolean:p.boolean(),strings:p.array(p.string()),json:V}[r.type];return r.nullable?t.nullable():t}async function ie(r,t){return $(r,t,!1)}async function se(r,t){return $(r,t,!0)}async function $(r,t,w){t.signal?.throwIfAborted();let L=M.parse(t.content),o=L.document;if(x.has(r))throw new d("CONFLICT","Content is already mounted in this container");let f=p.record(p.string(),V).parse(t.inputs??{});if(Object.keys(f).length>40)throw new d("INVALID_REQUEST","Too many content inputs");for(let[e,s]of Object.entries(f))N.parse({[e]:s});if(Object.keys(f).some(e=>!Object.hasOwn(o.contract.inputs,e)))throw new d("INVALID_REQUEST","Undeclared content input");for(let[e,s]of Object.entries(o.contract.inputs))if(Object.hasOwn(f,e))W(s).parse(f[e]);else if(s.required)throw new d("INVALID_REQUEST",`Missing content input ${e}`);for(let e of Object.keys(o.contract.outputs))if(typeof t.actions[e]!="function")throw new d("INVALID_REQUEST",`Missing host handler for ${e}`);let J=q.parse(t.bindings??[]),c=r.ownerDocument,T,k=o.kind==="popup",n=k?c.createElement("dialog"):null,i=c.createElement("div");if(i.dataset.indianaContent=o.kind,i.setAttribute("aria-label",o.name),i.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",o.name);let e=o.screen.presentation;n.style.cssText="box-sizing:border-box;padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto",e.type==="modal"||e.type==="sheet"?(n.style.width=`${P[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",n.append(i),r.append(n)}else r.append(i);let l=!1,C=!1,g=!1;w&&!n&&(i.style.width=`${r.getBoundingClientRect().width||c.defaultView?.innerWidth||800}px`);let G=w?F(n??i):()=>{},D,A,S=new Promise((e,s)=>{D=e,A=s});S.catch(()=>{});let u=null,E=structuredClone(o.screen);E.actions=E.actions.map(e=>e.type==="event"?{...e,close:!1}:e);let y;function m(){l||(l=!0,t.signal?.removeEventListener("abort",m),A(new Error("Content preparation cancelled")),y?.destroy(),n?.close(),n?.remove(),i.remove(),x.delete(r),n&&T?.())}let O=()=>{g&&(m(),v(t.onDismiss))};if(n){let e=c.createElement("button");e.type="button",e.textContent="\xD7",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),_(e,o.screen.theme),e.addEventListener("click",O),n.prepend(e)}n?.addEventListener("cancel",e=>{e.preventDefault(),O()});async function H(){if(l||!g||C||!u)return;let e=u;C=!0,i.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),u=null}catch(s){v(t.onError,s)}finally{C=!1,l||i.removeAttribute("aria-busy")}}function R(){if(l)throw new d("CONFLICT","Content host has been destroyed");g||(T=B(c),G(),w&&!n&&(i.style.width="100%"),n&&(n.showModal(),z(n,o.screen.presentation.type)),g=!0)}try{w||R(),y=Q(i,{mode:"live",rendererUrl:t.rendererUrl,title:o.name,viewportHeight:o.kind==="page"?r.clientHeight||c.defaultView?.innerHeight||800:void 0,onRendered:a=>{a&&n?.setAttribute("aria-label",a),D()},onError:a=>{let I=new Error(a);A(I),v(t.onError,I)},onEscape:k?O:void 0,onAction:(a,I,K)=>{if(l||!g||C||u)return;let h=o.screen.actions.find(b=>b.id===a),j=o.contract.outputs[a];if(!(h?.type!=="event"||!j))try{let b=W(j).parse(Object.hasOwn(h.properties,"value")?h.properties.value:h.properties);u={requestId:crypto.randomUUID(),contentVersionId:L.id,actionId:a,event:h.event,value:b,selection:I??{},answers:K??{},requestedClose:h.close},H()}catch(b){v(t.onError,b)}}});let e={destroy:m,show:R,get pendingAction(){return u?structuredClone(u):null},retryAction:H,updateCapabilities:a=>y?.updateCapabilities(a)};x.set(r,e),t.signal?.addEventListener("abort",m,{once:!0}),t.signal?.aborted&&(m(),t.signal.throwIfAborted());let s=U(E,[t.locale,...c.defaultView?.navigator.languages??[]]);if(y.update(E,s,{capabilities:t.capabilities,serverInput:{bindings:J,answers:{},values:f}}),await Promise.race([y.ready,S]),w&&await S,l)throw new Error("Content preparation cancelled");return e}catch(e){throw m(),e}}export{ie as mountContent,se as prepareContent};
@@ -1,6 +1,6 @@
1
1
  import * as zod from 'zod';
2
2
  import { z } from 'zod';
3
- import { I as InvoiceModeParams, a as InvoiceModeParamsInput, A as ApiInput } from './api-Bf_aRlXs.js';
3
+ import { I as InvoiceModeParams, a as InvoiceModeParamsInput, A as ApiInput } from './api-Cefn6AaL.js';
4
4
  import { S as StackNode, a as ScreenSelection } from './screen-D81zCpfi.js';
5
5
  import { J as JsonValue, E as EvaluationContext, F as FeatureResult } from './growth-rules-B4YYy64R.js';
6
6
  import { a as ConfigurationSync } from './configuration-sync-D2n_gGj6.js';
@@ -47,6 +47,7 @@ declare const merchantBridgeManifestSchema: z.ZodObject<{
47
47
  "invoice.paid": "invoice.paid";
48
48
  "subscription.change.completed": "subscription.change.completed";
49
49
  "refund.updated": "refund.updated";
50
+ "dispute.updated": "dispute.updated";
50
51
  }>>;
51
52
  profiles: z.ZodArray<z.ZodEnum<{
52
53
  "purchase.subscription": "purchase.subscription";
@@ -339,6 +340,7 @@ declare const merchantBridgeCommandOutputs: {
339
340
  "invoice.paid": "invoice.paid";
340
341
  "subscription.change.completed": "subscription.change.completed";
341
342
  "refund.updated": "refund.updated";
343
+ "dispute.updated": "dispute.updated";
342
344
  }>>;
343
345
  profiles: z.ZodArray<z.ZodEnum<{
344
346
  "purchase.subscription": "purchase.subscription";
@@ -1,8 +1,8 @@
1
1
  import * as zod from 'zod';
2
2
  import { z } from 'zod';
3
- import { g as FunnelRuntimeResponse, F as FunnelRunView, h as FunnelMutation, m as FunnelPurchaseRecovery, d as FunnelSegmentPrediction, e as PaywallDelivery, y as PaywallResolution, f as FunnelDataQueries, I as IndianaOptions, z as FunnelCommand, k as FeatureClientOptions, A as FunnelProcessOpenInput, B as FunnelProcessResponse, D as FunnelProcessMutation, i as FunnelProcessRunView } from './funnel-local-client-DJq2K7an.js';
3
+ import { g as FunnelRuntimeResponse, F as FunnelRunView, h as FunnelMutation, m as FunnelPurchaseRecovery, d as FunnelSegmentPrediction, e as PaywallDelivery, y as PaywallResolution, f as FunnelDataQueries, I as IndianaOptions, z as FunnelCommand, k as FeatureClientOptions, A as FunnelProcessOpenInput, B as FunnelProcessResponse, D as FunnelProcessMutation, i as FunnelProcessRunView } from './funnel-local-client-9U-_hkEE.js';
4
4
  import { S as StackNode } from './screen-D81zCpfi.js';
5
- import { I as InvoiceModeParams } from './api-Bf_aRlXs.js';
5
+ import { I as InvoiceModeParams } from './api-Cefn6AaL.js';
6
6
  import { a as ConfigurationSync } from './configuration-sync-D2n_gGj6.js';
7
7
 
8
8
  /** The store supplies the intent hint. Only verified provider facts prove ownership. */
@@ -0,0 +1 @@
1
+ import{b as a}from"./chunk-3WVMD3FK.js";import"./chunk-MOWYD2TV.js";import"./chunk-VSMITXQD.js";import"./chunk-D5D75HM6.js";import"./chunk-OZZMZH7X.js";import"./chunk-SLUA7ABW.js";import"./chunk-J42MHRU7.js";import"./chunk-DSPLGTQI.js";import"./chunk-KOGWARWA.js";import"./chunk-VSJOHWDL.js";export{a as showFunnelRun};
package/dist/index.d.ts CHANGED
@@ -3,15 +3,15 @@ import { z } from 'zod';
3
3
  import { S as ScreenAnswers, s as screenInputBindingsSchema, a as SurfaceData, C as CustomerDataIntent } from './customer-page-km5f1PJZ.js';
4
4
  import { J as JsonValue, F as FeatureResult } from './growth-rules-B4YYy64R.js';
5
5
  import { S as StackNode, a as ScreenSelection } from './screen-D81zCpfi.js';
6
- import { P as PaywallSession, S as SubscriptionOperation, F as FunnelRunView, I as IndianaOptions, C as CustomerSession, R as RemoteFeatureResult, a as PushAddressObservation, b as FunnelCommandStorage, c as FunnelStartInput, d as FunnelSegmentPrediction, e as PaywallDelivery, f as FunnelDataQueries, g as FunnelRuntimeResponse, h as FunnelMutation, i as FunnelProcessRunView } from './funnel-local-client-DJq2K7an.js';
7
- export { j as FeatureClient, k as FeatureClientOptions, l as FunnelPendingEntry, m as FunnelPurchaseRecovery, L as LocalFunnelClient, n as LocalFunnelClientOptions, o as LongplayError, p as PaywallPurchaseInput, q as PaywallStartInput, r as PushHost, s as PushJournal, t as SessionCredentials, u as createFeatureClient, v as createLocalFunnelClient, w as createPaywallSession } from './funnel-local-client-DJq2K7an.js';
8
- import { F as FunnelRunController, a as FunnelResourceSource, I as IndianaFeatureOptions, N as NativeRestoreCommand, b as IamFunnelEntryDelivery, c as createFunnelProcess } from './funnel-process-client-C_UhTH8g.js';
9
- export { d as FunnelControllerResponse, e as FunnelProcessAdapter, f as FunnelProcessOptions, g as createFunnelRunController } from './funnel-process-client-C_UhTH8g.js';
6
+ import { P as PaywallSession, S as SubscriptionOperation, F as FunnelRunView, I as IndianaOptions, C as CustomerSession, R as RemoteFeatureResult, a as PushAddressObservation, b as FunnelCommandStorage, c as FunnelStartInput, d as FunnelSegmentPrediction, e as PaywallDelivery, f as FunnelDataQueries, g as FunnelRuntimeResponse, h as FunnelMutation, i as FunnelProcessRunView } from './funnel-local-client-9U-_hkEE.js';
7
+ export { j as FeatureClient, k as FeatureClientOptions, l as FunnelPendingEntry, m as FunnelPurchaseRecovery, L as LocalFunnelClient, n as LocalFunnelClientOptions, o as LongplayError, p as PaywallPurchaseInput, q as PaywallStartInput, r as PushHost, s as PushJournal, t as SessionCredentials, u as createFeatureClient, v as createLocalFunnelClient, w as createPaywallSession } from './funnel-local-client-9U-_hkEE.js';
8
+ import { F as FunnelRunController, a as FunnelResourceSource, I as IndianaFeatureOptions, N as NativeRestoreCommand, b as IamFunnelEntryDelivery, c as createFunnelProcess } from './funnel-process-client-BaHMeArI.js';
9
+ export { d as FunnelControllerResponse, e as FunnelProcessAdapter, f as FunnelProcessOptions, g as createFunnelRunController } from './funnel-process-client-BaHMeArI.js';
10
10
  import { C as CouponInput, O as Offer } from './coupon-fA1QujHt.js';
11
11
  export { a as OfferUnavailableReason } from './coupon-fA1QujHt.js';
12
- import { M as MerchantBridgeManifest } from './funnel-node-evaluation-CJSkUkbv.js';
13
- export { F as FunnelNodeEvaluationContext, e as evaluateFunnelNode } from './funnel-node-evaluation-CJSkUkbv.js';
14
- import { A as ApiInput, O as OfferingItem, I as InvoiceModeParams } from './api-Bf_aRlXs.js';
12
+ import { M as MerchantBridgeManifest } from './funnel-node-evaluation-DSSSmXHX.js';
13
+ export { F as FunnelNodeEvaluationContext, e as evaluateFunnelNode } from './funnel-node-evaluation-DSSSmXHX.js';
14
+ import { A as ApiInput, O as OfferingItem, I as InvoiceModeParams } from './api-Cefn6AaL.js';
15
15
  export { C as ConfigurationStorage, a as ConfigurationSync, b as ConfigurationSyncOptions, c as createConfigurationSync } from './configuration-sync-D2n_gGj6.js';
16
16
  import 'zod/v4';
17
17