@tinkerlandai/indiana-sdk 0.8.3 → 0.8.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +73 -3
- package/README.zh-CN.md +40 -3
- package/dist/{ai-usage-BV-FlgWr.d.ts → ai-usage-DUlre7JC.d.ts} +1 -1
- package/dist/{api-B3FIE41b.d.ts → api-XDc4pRlN.d.ts} +63 -10
- package/dist/chunk-3KQHKRZJ.js +1 -0
- package/dist/chunk-6A5WWFNS.js +10 -0
- package/dist/{chunk-SHSNIJJM.js → chunk-A3XRIG53.js} +1 -1
- package/dist/chunk-BUDTHBFF.js +173 -0
- package/dist/{chunk-BNU6IG3F.js → chunk-FGIGKO7A.js} +1 -1
- package/dist/chunk-HEBQUICQ.js +4 -0
- package/dist/chunk-SSLZKIIU.js +1 -0
- package/dist/chunk-SUXAWRR6.js +1 -0
- package/dist/chunk-WWUUVURR.js +1 -0
- package/dist/{configuration-sync-DNvKXHk-.d.ts → configuration-sync-Ce3dShy7.d.ts} +6 -1
- package/dist/content-DDMDNRCV.js +1 -0
- package/dist/{customer-page-WUQVK_tp.d.ts → customer-page-9B97Qdt_.d.ts} +21 -1
- package/dist/{funnel-local-client-wbz-4gFx.d.ts → funnel-local-client-CUGavICI.d.ts} +43 -23
- package/dist/funnel-runtime-host-QK6WDRPS.js +1 -0
- package/dist/index.d.ts +76 -26
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +2 -2
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +1 -1
- package/dist/page.js +1 -1
- package/dist/paywall-4QT3JYD4.js +1 -0
- package/dist/popup.d.ts +14 -4
- package/dist/popup.js +1 -1
- package/dist/react-native.d.ts +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-DLXDQQKK.js +1 -0
- package/dist/server.d.ts +13 -13
- package/dist/server.js +1 -1
- package/dist/src-EG7RWDDY.js +1 -0
- package/dist/visual.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-2QPETWDX.js +0 -1
- package/dist/chunk-ANOOBDW5.js +0 -350
- package/dist/chunk-EXCPE2XH.js +0 -1
- package/dist/chunk-X747SY26.js +0 -4
- package/dist/chunk-Y32NPIYY.js +0 -1
- package/dist/chunk-ZT66RIFU.js +0 -10
- package/dist/content-J3FKZTGT.js +0 -1
- package/dist/funnel-runtime-host-C5P5JTV3.js +0 -1
- package/dist/paywall-3GIRKSHN.js +0 -1
- package/dist/screen-renderer-5FPYVSPW.js +0 -1
- package/dist/src-BMJCIMIF.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Yi as N,f as U,h as j,i as x,j as R,k,n as F}from"./chunk-6A5WWFNS.js";import{a as r}from"./chunk-SOQO2RDZ.js";import{b as H}from"./chunk-OBYJWIRB.js";var T=s=>{if(!Number.isSafeInteger(s)||s<0||s>=Number.MAX_SAFE_INTEGER)throw new r("INVALID_STATE","Installation sequence exhausted");return s+1},G=async s=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(s,p=>p.charCodeAt(0))))].map(p=>p.toString(16).padStart(2,"0")).join("");function w(s,p){return s.transaction(l=>{if(!Number.isSafeInteger(l.identitySeq)||l.identitySeq<0||!Number.isSafeInteger(l.addressSeq)||l.addressSeq<0||l.detachSeq!==null&&(!Number.isSafeInteger(l.detachSeq)||l.detachSeq<1||l.detachSeq>l.identitySeq))throw new r("INVALID_STATE","Installation journal is invalid");return p({...l})})}function K(s,p,l){let P=null,S=0,h=0,I=0,L=Promise.resolve();if(s&&(!l||H.parse(s.scope).projectId!==l.projectId||s.scope.environment!==l.environment))throw new r("SCOPE_MISMATCH","Push installation belongs to another scope");let y=()=>{if(!s)throw new r("NOT_CONFIGURED","Configure this client's native Push host first");return s},d=e=>{if(e!==S)throw new r("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(e){let t=y();if(!t.sha256&&!globalThis.crypto?.subtle)throw new r("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let n=t.sha256?await t.sha256(Uint8Array.from(e,i=>i.charCodeAt(0))):await G(e);if(!/^[a-f0-9]{64}$/.test(n))throw new r("INVALID_STATE","Push credential digest is invalid");return n}function v(e){let t=k.parse(e);if(t.installationId.toLowerCase()!==y().installationId.toLowerCase())throw new r("INVALID_RESPONSE","Push response belongs to another installation");return t}async function E(e,t){let n=y(),i={installationId:n.installationId,publicKey:n.publicKey,issuedAt:new Date().toISOString(),...t},o=await n.sign(F(e,n.scope,i));return{...i,signature:o}}async function _(){let e=y(),t=S,n=P,i=w(e,u=>u),o;if(i.detachSeq!==null){let u=i.detachSeq,O=U.parse(await E("detach",{sequence:u,platform:e.platform}));try{let a=await p.request("push/installations/detach",{...e.scope,...O},"POST",{installationDetach:!0});if(!a||typeof a!="object"||!("installation"in a))throw new r("INVALID_RESPONSE","Push detach acknowledgement is invalid");let f=v(a.installation);if(f.bound||f.identitySeq!==u)throw new r("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(a){if(a instanceof r&&a.status===404)o=a;else if(!(a instanceof r)||a.status!==412)throw a}o||w(e,a=>({...a,detachSeq:a.detachSeq===u?null:a.detachSeq}))}if(d(t),!n){if(o)throw o;return null}let c=N.bindPushInstallation,q=c.request.parse(await E("bind",{sequence:I,platform:e.platform,credentialDigest:await D(n)}));d(t);let m=c.response.parse(await p.request(c.path,q));d(t);let g=v(m.installation);if(!g.bound||g.identitySeq!==I)throw new r("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return o&&i.detachSeq!==null&&I>i.detachSeq&&w(e,u=>({...u,detachSeq:u.detachSeq===i.detachSeq?null:u.detachSeq})),g}async function C(){y();let e=S,t=P;if(!t)throw new r("NOT_IDENTIFIED","Identify before reading this installation");let n=N.readPushInstallation,i=n.request.parse(await E("read",{credentialDigest:await D(t)}));d(e);let o=n.response.parse(await p.request(n.path,i));return d(e),v(o.installation)}function A(e=_){let t=L.catch(()=>{}).then(e);return L=t,t.catch(n=>{try{s?.onError?.(n instanceof Error?n:new Error("Push synchronization failed"))}catch{}}),t}async function V(e,t,n){let i=y(),o=t.identity,c=t.observation,q=P;if(d(o),c!==h)throw new r("INVALID_STATE","Push observation changed during recovery");if(!q)throw new r("NOT_IDENTIFIED","Identify before recovering a Push address");if(!e.connectionId||!e.kind||!e.token||!["granted","provisional"].includes(e.permission))throw new r("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await A(async()=>{if(d(o),await _(),d(o),c!==h)throw new r("INVALID_STATE","Push observation changed during recovery");let m=w(i,f=>n?f:{...f,addressSeq:T(f.addressSeq)}),u=await E(n?"recovery_confirm":"recovery_request",{...e,sequence:m.addressSeq,credentialDigest:await D(q),...n?{challenge:n}:{}}),O=n?x.parse(u):j.parse(u);if(d(o),c!==h)throw new r("INVALID_STATE","Push observation changed during recovery");let a=await p.request(`push/installations/recovery/${n?"confirm":"request"}`,O);if(d(o),c!==h||w(i,f=>f).addressSeq!==m.addressSeq)throw new r("INVALID_STATE","Push observation changed during recovery");if(n){let f=N.updatePushAddress.response.parse(a),b=v(f.installation);if(!b.bound||b.identitySeq!==I||b.addressSeq!==m.addressSeq||b.connectionId!==e.connectionId||b.addressStatus!=="active")throw new r("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return b}if(!a||typeof a!="object"||!("recovery"in a))throw new r("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return R.parse(a.recovery)})}return{recoveryObserver(){y();let e={identity:S,observation:++h};return{async request(t){return R.parse(await V(t,e))},async confirm(t,n){return k.parse(await V(n,e,t))}}},identify(e){if(!s)return;I=w(s,n=>({...n,identitySeq:T(n.identitySeq)})).identitySeq,P=e,S++,h++},reset(){if(s)try{w(s,e=>{let t=T(e.identitySeq);return{...e,identitySeq:t,detachSeq:t}})}finally{P=null,S++,h++}},start(){s&&A()},async sync(){return await A()},read:C,async recover(){let e=y(),t=S,n=I;return h++,await A(async()=>{d(t);let i=await C();return d(t),I=w(e,c=>{if(c.identitySeq!==n)throw new r("IDENTITY_CHANGED","A newer installation intent exists");return{...c,identitySeq:T(Math.max(c.identitySeq,i.identitySeq)),addressSeq:Math.max(c.addressSeq,i.addressSeq)}}).identitySeq,await _()})},tokenObserver(){y();let e=++h,t=S;return async n=>{if(e!==h||t!==S)return null;let i=y(),o=P;if(!o)throw new r("NOT_IDENTIFIED","Identify before registering a Push token");if(await A(),d(t),e!==h)return null;let c=w(i,u=>({...u,addressSeq:T(u.addressSeq)})),q=N.updatePushAddress,m=q.request.parse(await E("address",{...n,sequence:c.addressSeq,credentialDigest:await D(o)}));if(d(t),e!==h)return null;let g=q.response.parse(await p.request(q.path,m));return d(t),v(g.installation)}}}}export{K as a};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as P}from"./chunk-DSPLGTQI.js";import{a as $,b as N}from"./chunk-WWUUVURR.js";import{e as C,h as O,k as D}from"./chunk-KQCTDXVD.js";function j(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let n of document.cookie.split(";"))if(n.trim().startsWith(`${e}=`))try{t=decodeURIComponent(n.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function H(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function Y(e=N){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var w=new Set,R;function B(e){let t=()=>e();if(w.add(t),!R){let n=!0,r=history.pushState,o=history.replaceState,a=()=>{if(n)for(let i of[...w])w.has(i)&&P(i)},c=function(...i){r.apply(this,i),a()},s=function(...i){o.apply(this,i),a()};history.pushState=c,history.replaceState=s,addEventListener("popstate",a),addEventListener("hashchange",a),R=()=>{n=!1,history.pushState===c&&(history.pushState=r),history.replaceState===s&&(history.replaceState=o),removeEventListener("popstate",a),removeEventListener("hashchange",a)}}return()=>{w.delete(t)&&(w.size||(R?.(),R=void 0))}}var te=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function re(e,t){let n=e,r=o=>Number.isInteger(o)&&o>=0;return!!n&&typeof n=="object"&&r(n.inserted)&&r(n.duplicates)&&r(n.skipped)&&Array.isArray(n.rejected)&&n.inserted+n.duplicates+n.skipped+n.rejected.length===t}function V(e){let t=[],n,r=(s,i)=>e.log?.(`${e.label} ${s}`,i);function o(s){n===void 0&&t.length&&(n=setTimeout(()=>{c()},s))}async function a(s){let i;try{i=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:s}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(f){return r("not sent",{error:f}),!1}if(i.status===408||i.status===429||i.status>=500)return r("not sent",{status:i.status}),!1;if(!i.ok)return r("rejected",{status:i.status,events:s.length}),!0;let p;try{p=await i.json()}catch{p=void 0}return re(p,s.length)?(p.rejected.length&&r("rejected",{rejected:p.rejected}),!0):(r("not acknowledged",{status:i.status}),!1)}function c(){clearTimeout(n),n=void 0;let s=[];for(;t.length&&s.length<20&&(!s.length||te([...s,t[0]].map(i=>i.event))<=65536);)s.push(t.shift());return s.length?a(s.map(i=>i.event)).then(i=>{if(i)return o(1e3);let p=s.filter(f=>++f.attempts<5);p.length<s.length&&r("dropped after retries",{events:s.length-p.length}),t.unshift(...p),o(5e3)}):Promise.resolve()}return{push(s){t.push({event:s,attempts:0}),t.length>=20?c():o(1e3)},flush:c}}async function q(e,t,n,r={}){let o=r.message??"Invalid SDK JSON response",a=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||a!==null&&(!/^\d+$/.test(a)||Number(a)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(o);let c=e.body.getReader(),s=[],i=0,p=!1,f=()=>{},g=new Promise((y,h)=>{f=()=>h(Error(o)),n.addEventListener("abort",f,{once:!0}),n.aborted&&f()});try{for(;;){let m=await Promise.race([c.read(),g]);if(m.done){p=!0;break}if(i+=m.value.byteLength,i>t)throw Error(o);s.push(m.value)}let y=new Uint8Array(i),h=0;for(let m of s)y.set(m,h),h+=m.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(y))}finally{n.removeEventListener("abort",f),p||c.cancel().catch(()=>{}),c.releaseLock()}}async function J(e,t){let n=e?.body;if(!n)return;let r=n.getReader(),o=0,a=!1,c,s=new Promise((f,g)=>{c=setTimeout(()=>g(Error("Exposure response timeout")),2e3)}),i=()=>{},p=new Promise((f,g)=>{i=()=>g(t?.reason),t?.addEventListener("abort",i,{once:!0}),t?.aborted&&i()});try{for(;;){let f=await Promise.race([r.read(),s,p]);if(f.done){a=!0;return}if(o+=f.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(c),t?.removeEventListener("abort",i),a||r.cancel().catch(()=>{}),r.releaseLock()}}var me=2*1024*1024,G=256*1024;async function M(e,t,n,r){let o=()=>{},a=new Promise((c,s)=>{o=()=>s(r.reason),r.addEventListener("abort",o,{once:!0}),r.aborted&&o()});try{let c=e(t,{...n,signal:r});return c.then(s=>{r.aborted&&s.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([c,a])}finally{r.removeEventListener("abort",o)}}async function he(e,t,n,r=!1){if(new TextEncoder().encode(n).byteLength>65536)throw Error("Exposure request budget");let o=new URL(t);o.searchParams.set("sdkVersion",$.version);let a=new AbortController,c=setTimeout(()=>a.abort(Error("Exposure request timeout")),5e3);try{let s=await M(e,o.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:n,credentials:"omit",keepalive:r,redirect:"error"},a.signal);await J(s,a.signal)}finally{clearTimeout(c)}}function z(e){let t,n=!1;return{async read(r,o){if(n)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let a=new AbortController;t=a;let{signal:c}=a,s=setTimeout(()=>a.abort(Error("Experiment request timeout")),5e3);try{let i=await M(e,r,{cache:"no-cache",credentials:"omit",redirect:"error"},c),p=await q(i,o,c);return c.throwIfAborted(),p}finally{clearTimeout(s),t===a&&(t=void 0)}},destroy(){n=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}/*!
|
|
2
|
+
Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
|
|
3
|
+
plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
|
|
4
|
+
*/function ne(e,t){let n,r;try{n=new URL(e),r=new URL(t)}catch{return t}return n.searchParams.forEach((o,a)=>{r.searchParams.has(a)||r.searchParams.set(a,o)}),r.toString()}function oe(e,t){let n=navigator.userAgent,r=new URLSearchParams(t.search),o={};for(let a of["source","medium","campaign","term","content"]){let c=r.get(`utm_${a}`);c!==null&&(o[`utm${a[0].toUpperCase()}${a.slice(1)}`]=c)}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(n)?"edge":/Chrome/.test(n)?"chrome":/Firefox/.test(n)?"firefox":/Safari/.test(n)?"safari":"unknown",deviceType:/Mobi/.test(n)?"mobile":"desktop",...o}}function ie(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(r=>!!r&&!["namespace","status","url","groups"].some(o=>Object.hasOwn(r,o))&&(r.hashVersion===void 0||r.hashVersion===2)&&typeof r.key=="string"&&Array.isArray(r.variations)&&r.variations.length>=2&&r.variations.every(o=>!!o&&typeof o.urlRedirect=="string")&&(r.urlPatterns===void 0||Array.isArray(r.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Pe(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=Y(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),r=z(async(u,d)=>{let l=await n(u,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),o=e.log?(u,d)=>P(e.log,u,d):void 0,a=`${t}/api/v1/page-experiments/${e.environmentId}`,c=j(e.deviceIdCookie??"indiana_did"),s=H(),i=null,p={...e.attributes??{}},f="",g=!1,y=!1,h=0,m=new Map,T=V({endpoint:`${a}/events`,fetch:n,log:o,label:"Exposure"}),S=T.flush,E={trackedExperiments:new Set,log:o,onExperimentViewed:(u,d)=>{e.trackExposures===!1||i?.trackExposures===!1||T.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:c,...s?{sessionId:s}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:u.key,variationKey:d.key})}},Q=()=>{E.url=location.href,E.attributes={...oe(c,location),...p}};function W(u){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return u.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 F(u,d){let l=e.configuration?.snapshot?.generation;f=u;let v=e.navigate??(x=>location.replace(x)),Z=e.navigateDelay??(e.navigate?0:100),ee=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(x=>setTimeout(x,ee))]),new Promise(x=>setTimeout(x,Z))]).then(()=>{!g&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&v(u)})}function b(){if(!(!i||g||e.configuration&&!e.configuration.fresh)){Q();for(let u of i.experiments){if(W(u)){o?.("Auto experiment blocked",{id:u.key});continue}let d;try{d=D(u,E)}catch(l){o?.("Skipping page experiment",{id:u.key,error:String(l)});continue}if(m.set(u.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=u.persistQueryString?ne(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,u.urlPatterns??[])?o?.("Skipping redirect because original URL matches redirect URL",{id:u.key}):l!==f&&F(l,S())}break}}}}let k="",K=()=>{location.href!==k&&(k=location.href,f="",b())},L,I;function X(){L??=B(K),addEventListener("pagehide",U)}let U=()=>{S()};async function A(){if(g)return!1;let u=++h,d;try{d=e.configuration?await e.configuration.pageExperiments():await r.read(a,G)}catch(v){if(g||u!==h)return!1;throw v}if(g||u!==h)return!1;let l=ie(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return i?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),i=l,E.savedGroups=O(l.savedGroups),!0}function _(){g||(I??=e.configuration?.subscribe(()=>{!g&&e.configuration?.fresh&&A().then(u=>{u&&b()}).catch(u=>o?.("Page configuration unavailable",{error:String(u)}))}),X(),k=location.href)}return{async start(){y||g||(y=!0,await A()&&(_(),b()))},async refresh(){await A()&&(y&&_(),f="",b())},setAttributes(u){p={...u},b()},getResults(){return new Map(m)},get generation(){return i?.generation??null},destroy(){g||(g=!0,h++,r.destroy(),I?.(),L?.(),removeEventListener("pagehide",U),i=null,m.clear(),S())}}}export{j as a,H as b,Y as c,B as d,me as e,he as f,z as g,ne as h,oe as i,ie as j,Pe as k};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var n=new WeakMap;function u(t,o){return n.set(t,o),()=>n.delete(t)}function c(t){let o=t.defaultView?.HTMLElement,e=t.activeElement;for(let r=0;r<16&&e?.shadowRoot?.activeElement;r++)e=e.shadowRoot.activeElement;let s=e?n.get(e)?.():void 0;return()=>{!e?.isConnected||!o||!(e instanceof o)||(e.focus({preventScroll:!0}),s?.())}}export{u as a,c as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as on,b as an,c as sn,d as un}from"./chunk-GRLMT5PR.js";import{a as we}from"./chunk-VVV3JNS3.js";import{a as re}from"./chunk-3KQHKRZJ.js";import{$e as Ue,Aj as Xe,Bk as rn,Je as Me,Vg as z,Yi as ee,af as qe,df as Ge,eh as Je,ej as Ye,gh as U,gk as en,hh as Be,lh as Se,lj as ge,mh as L,nh as je,oh as ze,oj as Ze,ph as He,qh as $e,th as Ke,vh as Qe,yk as nn,zj as We,zk as tn}from"./chunk-6A5WWFNS.js";import{a as p}from"./chunk-SOQO2RDZ.js";import{b as Le,h as pe}from"./chunk-OBYJWIRB.js";import{b as te}from"./chunk-WWUUVURR.js";import{b as fe}from"./chunk-RRII2DMC.js";import{h as Ve,l as ke}from"./chunk-KQCTDXVD.js";function Tn(n){let e=null,t=null,d=0,s=0,g=!1,i=new Set,o=null,r=null,a=new Set,h=()=>{for(let m of a)try{m()}catch{}},u={attributes:fe.parse(n.attributes??{}),onFeatureUsage:n.onFeatureUsage?(m,S)=>{!i.has(m)&&(!e||!("analyticsConfig"in e)||e.analyticsConfig.featureUsageEnabled)&&n.onFeatureUsage(m,structuredClone(S),structuredClone(u.attributes))}:void 0,onExperimentViewed:n.onExperimentViewed?(m,S)=>(!e||!("analyticsConfig"in e)||e.analyticsConfig.experimentViewsEnabled)&&n.onExperimentViewed(structuredClone(m),structuredClone(S),structuredClone(u.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:n.saveStickyBucketAssignmentDoc?m=>n.saveStickyBucketAssignmentDoc(structuredClone(m)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},F=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function N(m,S=new Set){return i.has(m)?!o||!o.features[m]||["unknownFeature","cyclicPrerequisite"].includes(o.features[m].source):S.has(m)?!1:(S.add(m),(e?.features[m]?.rules??[]).some(R=>[...R.parentConditions??[],...(R.tracks??[]).flatMap(C=>C.experiment.parentConditions??[])].some(C=>N(C.id,S))))}let O=m=>{if(n.assertUsable?.(e?.generation),!e)throw new Error("Initialize the Feature client before evaluation");if(e.expiresAt&&Date.parse(e.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,u.features=e.features),i.has(m)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?F():structuredClone(o.features[m]??F()):n.evaluateRemote&&(u.attributes?.merchandise||u.attributes?.merchandiseId)&&!g||N(m)?F():structuredClone(ke(m,u))};async function c(){if(!e||!i.size&&!u.attributes?.merchandise&&!u.attributes?.merchandiseId)return;if(!n.evaluateRemote){if(i.size)throw new Error("Remote Feature evaluation requires a server loader");return}let m=s;if(r?.revision===m)return r.loading;let S=d,R=e,C=[...i],P=(async()=>{let T=Ge.parse(await n.evaluateRemote({attributes:structuredClone(u.attributes),features:C}));if(!(S!==d||m!==s||R!==e)){if(n.assertUsable?.(R.generation),T.generation!==R.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(C.some(_=>!Object.hasOwn(T.features,_))||Object.keys(T.features).some(_=>!i.has(_)))throw new Error("Invalid remote Feature results");if(u.attributes?.merchandise||u.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");u.attributes=fe.parse({...u.attributes,...T.merchandiseContext}),g=!0}o=structuredClone(T),u.features={...R.features,...Object.fromEntries(Object.entries(o.features).map(([_,G])=>[_,{defaultValue:G.value}]))},h()}})();r={revision:m,loading:P};try{await P}finally{r?.loading===P&&(r=null)}}function y(){c().catch(m=>{try{n.onError?.(m)}catch{}})}async function l(){if(t)return t;let m=d,S=(async()=>{let R=await n.load(),C="remoteFeatures"in R?Ue.parse(R):null,P=C??pe.parse(R);if(P.scope.projectId!==n.scope.projectId||P.scope.environment!==n.scope.environment)throw new Error("Feature payload scope changed");if(m!==d)throw new Error("Feature client was reset");if(n.assertUsable&&e?.generation===P.generation){let{evaluatedAt:_,expiresAt:G,...J}=e,{evaluatedAt:Y,expiresAt:q,...Z}=P;if(L(J)!==L(Z))throw new Error("Immutable Feature generation changed content");return e.evaluatedAt=P.evaluatedAt,e.expiresAt=P.expiresAt,h(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&y(),structuredClone(e)}let T=new Set(C?.remoteFeatures??[]);if([...T].some(_=>Object.hasOwn(P.features,_)))throw new Error("Remote Feature definitions must not be delivered locally");return e&&"analyticsConfig"in e&&"analyticsConfig"in P&&!e.analyticsConfig.experimentViewsEnabled&&C?.analyticsConfig.experimentViewsEnabled&&u.trackedExperiments?.clear(),e=structuredClone(P),i=T,o=null,r=null,s++,u.features=e.features,u.savedGroups=Ve(e.savedGroups),u.trackedFeatureUsage={},h(),y(),structuredClone(e)})();t=S;try{return await S}finally{t===S&&(t=null)}}return{init:l,refresh:l,refreshRemote:c,get generation(){return e?.generation??null},get expiresAt(){return e?.expiresAt??null},subscribe(m){return a.add(m),()=>{a.delete(m)}},setAttributes(m){let S=fe.parse(m);(u.attributes?.merchandise||u.attributes?.merchandiseId||m.merchandise||m.merchandiseId)&&u.trackedExperiments?.clear(),u.attributes=S,s++,g=!1,o=null,r=null,u.features=e?.features??{},u.trackedFeatureUsage={},h(),y()},evalFeature:O,isOn(m){return O(m).on},isOff(m){return O(m).off},getFeatureValue(m,S){let R=O(m).value;return structuredClone(R===null?S:R)},reset(){d++,s++,t=null,r=null,e=null,o=null,i.clear(),u.features={},u.savedGroups={},u.stickyBucketAssignmentDocs={},u.attributes={},u.trackedFeatureUsage={},u.trackedExperiments?.clear(),h()}}}function ln(n){let e,t,d=()=>new p("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),s=Promise.resolve().then(async()=>{if(e=n.storage??globalThis.localStorage,t=n.locks??globalThis.navigator?.locks,!e||!t||!globalThis.crypto?.subtle)throw d();let o=new TextEncoder().encode(JSON.stringify([new URL(n.baseUrl??te).href,n.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",o));return"indiana.funnel.commands.v1."+Array.from(r,a=>a.toString(16).padStart(2,"0")).join("")});s.catch(()=>{});async function g(o){try{let r=await s;return await t.request(r,{mode:"exclusive"},()=>o(r))}catch(r){throw r instanceof p?r:d()}}function i(o){let r=e.getItem(o);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw d();let a=JSON.parse(r);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw d();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>g(i),write:(o,r)=>g(a=>{if(i(a).revision!==o)return null;if(!Number.isSafeInteger(o+1))throw d();return e.setItem(a,JSON.stringify({revision:o+1,entry:r})),o+1})}}async function ye(n,e){let{funnelRuntimeDeliverySchema:t}=await import("./src-EG7RWDDY.js"),d=t.safeParse(e);if(!d.success)throw new p("INVALID_RESPONSE","Funnel response contract changed");let s=d.data;if(n.scope&&(s.scope.projectId!==n.scope.projectId||s.scope.environment!==n.scope.environment))throw new p("SCOPE_MISMATCH","Funnel scope changed");return s}async function Pe(n,e,t){if(Number(n.headers.get("content-length"))>e)throw t.error("limit");let d=n.body?.getReader();if(!d)throw t.error("missing");let s=[],g=0;try{for(;;){t.signal?.throwIfAborted();let r=await d.read();if(r.done)break;if(g+=r.value.length,g>e)throw t.error("limit");s.push(r.value)}}finally{await d.cancel().catch(()=>{})}t.signal?.throwIfAborted();let i=new Uint8Array(g),o=0;for(let r of s)i.set(r,o),o+=r.length;return i}async function cn(n,e,t){return new TextDecoder("utf-8",{fatal:!0}).decode(await Pe(n,e,t))}function he(n,e){let t=typeof n=="string"?new TextEncoder().encode(n):n;return t.byteLength===e.byteLength&&je(t)===e.sha256}async function Ie(n,e){let t=Ke.parse(e),{artifact:d,environmentId:s}=t.content,g=new URL(n.baseUrl??te).origin,i=new URL(d.url,g);if(i.origin!==g||i.username||i.password||i.search||i.hash||i.pathname!==`/api/v1/configuration/${s}/artifacts/${d.sha256}`)throw new p("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,r=setTimeout(()=>o.abort(),U.initializationMs);try{let a=await(n.fetch??globalThis.fetch)(i,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>d.byteLength)throw new p("INVALID_RESPONSE","Public Paywall is unavailable");let h=await Pe(a,d.byteLength,{signal:o.signal,error:u=>new p("INVALID_RESPONSE",u==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!he(h,d))throw new p("INVALID_RESPONSE","Public Paywall digest or size changed");return Qe(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(h)))}finally{clearTimeout(r)}}var se=(n,e)=>new p(n,e);function $n(n){return nn(n,se)}async function Fe(n,e,{predict:t=!0}={}){let d=e.instruction;if(d?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!n)throw new p("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(n.scope.environmentId!==d.environmentId)throw new p("SCOPE_MISMATCH","Evaluation environment changed");let s=null,g;if(t)try{let i=await n.funnel(e.source.id,e.source.versionId);g=i.manifest.generation,s=bn(n,e,i)}catch{s=null}return g??=n.snapshot?.generation??(await n.refresh()).generation,{advance:{policyRevision:d.policyRevision,generation:g},prediction:s}}function bn(n,e,t){let d=e.instruction;if(d?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==d.policyRevision)return null;let{analyticsConfig:s,remoteFeatures:g,...i}=t.growth,o=We({scope:{projectId:n.scope.projectId,environment:n.scope.environment},funnelId:e.source.id,versionId:e.source.versionId,evaluationMode:"local",evaluationRevision:d.policyRevision,document:t.document,payload:pe.parse(i)}),r=Sn(o,t.document,{...e,...d}),a=r.steps.at(-1),h=r.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:e.visit+r.steps.length-1}:null);return h?{runId:e.id,from:{nodeId:e.nodeId,visit:e.visit,revision:e.revision},nodeId:h.nodeId,visit:h.visit,terminal:!r.boundary}:null}function Sn(n,e,t){return rn(n,e,t,se)}import{z as B}from"zod";var dn=z.refine(n=>!["start","get","review"].includes(n.operation)&&!("customerToken"in n),"Persist only the original mutation, without credentials").transform(n=>{if(n.operation==="start"||n.operation==="get"||n.operation==="review")throw new p("COMMAND_STORAGE_INVALID","Stored mutation required");return n}),mn=B.strictObject({schemaVersion:B.literal(1),scope:Le,runId:B.uuid(),funnelId:B.uuid(),versionId:B.uuid(),command:dn.optional(),closeCommand:dn.refine(n=>n.operation==="close").optional(),purchase:B.strictObject({receiptId:B.uuid(),operationId:B.uuid(),generation:B.number().int().nonnegative()}).optional(),closed:B.literal(!0).optional()}).refine(n=>!n.closeCommand||n.command&&n.command.operation!=="close"&&n.command.requestId!==n.closeCommand.requestId,"Close requires a separate request identity").refine(n=>n.command!==void 0||n.purchase!==void 0,"A recovery record requires an original obligation"),k=()=>new p("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ve=(n,e)=>JSON.stringify(n)===JSON.stringify(e);function fn(n){let e=0,t=null,d=r=>JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]),s=Promise.resolve();async function g(){let r=await n.read();if(!Number.isSafeInteger(r.revision)||r.revision<0)throw new p("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:r.revision,entry:r.entry===null?null:mn.parse(r.entry)}}function i(r){let a=s.then(r);return s=a.catch(()=>{}),a}async function o(r){for(let a=0;a<4;a++){let h=await g();if(h.entry&&t!==null&&d(h.entry)!==t)throw k();let u=r(h.entry,h.revision);if(ve(h.entry,u)){e=h.revision;return}let F=await n.write(h.revision,u);if(F!==null){if(!Number.isSafeInteger(F)||F<=h.revision)throw k();e=F;return}}throw k()}return{bind(r){let a=JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]);if(t!==null&&t!==a)throw k();t=a},async load(){let r=await g();return e=r.revision,t=r.entry?d(r.entry):null,r.entry},retain(r){let a=mn.parse(r),h=a.command;return!h||t!==null&&d(a)!==t?Promise.reject(k()):(t??=d(a),i(()=>o((u,F)=>{if(u&&!ve(d(u),d(a)))throw k();if(!u){if(F!==e&&h.operation!=="close")throw k();return a}if(!u.command)return{...u,command:h,...h.operation==="close"?{closed:!0}:{}};if(h.operation==="close"&&u.command.operation!=="close"){if(u.command.requestId===h.requestId||u.closeCommand&&!ve(u.closeCommand,h))throw k();return{...u,closeCommand:h,closed:!0}}if(!ve(u.command,h))throw k();return u})))},observePurchase(r,a,h){return i(()=>o((u,F)=>{if(!u&&F!==e||u&&d(u)!==d({...r,schemaVersion:1}))throw k();if(u?.purchase&&u.purchase.generation>a.generation)return u;if(u?.purchase&&u.purchase.generation===a.generation&&u.purchase.operationId!==a.operationId)throw k();return h?!u?.purchase||u.purchase.operationId!==a.operationId?u:u.command?{...u,purchase:void 0}:null:{schemaVersion:1,...r,...u,purchase:a}}))},settle(r){return i(()=>o(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===r?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===r?{...a,closeCommand:void 0}:a:null))}}}function rt(n,e){return e.type==="id"?n.customerId===e.value:n.externalUserId===e.value}function oe(n,e){if(n===e)return!0;if(Array.isArray(n)||Array.isArray(e))return Array.isArray(n)&&Array.isArray(e)&&n.length===e.length&&n.every((s,g)=>oe(s,e[g]));if(!n||!e||typeof n!="object"||typeof e!="object")return!1;let t=Object.entries(n),d=Object.entries(e);return t.length===d.length&&t.every(([s,g])=>Object.hasOwn(e,s)&&oe(g,Reflect.get(e,s)))}function pn(n){let e=null,t=0,d=!1,s,g=0,i=new Set;return{get view(){return e},get generation(){return t},get disposed(){return d},get customerToken(){return s},get readSequence(){return g},nextRead(){return++g},assertCurrent(o,r="Run identity changed during the request"){if(o!==t||d)throw new p("IDENTITY_CHANGED",r)},assertRun(o){if(e&&(o.id!==e.id||o.source.type!==e.source.type||o.source.id!==e.source.id||o.source.versionId!==e.source.versionId||o.locale!==e.locale||!oe(o.parameters,e.parameters)))throw new p("INVALID_RESPONSE","Run version changed");if(n&&o.source.id!==n)throw new p("INVALID_RESPONSE","Run belongs to another Funnel")},publish(o,r,a,h,u){if(!(o.operation==="review"&&e&&e!==a&&r.run.revision<=e.revision)&&!(e&&r.run.revision===e.revision&&h!==void 0&&h<g)&&(o.operation==="review"&&!r.run.stopped&&["running","waiting"].includes(r.run.status)&&e&&r.run.nodeId===e.nodeId&&r.run.visit===e.visit&&r.run.revision===e.revision&&(r.run.screen=e.screen,(e.paywall?.quote?.operationId===r.review?.activeOperationId||!e.paywall?.quote&&r.review?.activeOperationId===null)&&(r.run.paywall=e.paywall)),!(e?.paywall&&r.run.paywall&&e.paywall.receiptId===r.run.paywall.receiptId&&(r.run.paywall.selectionGeneration??0)<(e.paywall.selectionGeneration??0)))){if(!e||r.run.revision>=e.revision)e=r.run;else if(!u)return;if(e)for(let F of i)try{F(structuredClone(e))}catch{}}},identify(o){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(o))throw new p("INVALID_TOKEN","Customer credential required");t++,s=o},subscribe(o){return i.add(o),()=>i.delete(o)},reset(){d=!0,t++,s=void 0,e=null,i.clear()}}}function K(n){let{customerToken:e,...t}=n;return t}var Pn=n=>!(n instanceof p)||n.status===void 0||n.status>=500||[401,425].includes(n.status);function gn({options:n,journal:e,state:t,call:d}){let s=null,g=null,i=!1,o={command:null,close:null},r=!1,a,h=null,u=e?e.load().then(y=>{if(t.disposed)throw new p("IDENTITY_CHANGED","Controller was reset during command restoration");if(h=y,!y)return;if(n.scope&&(y.scope.projectId!==n.scope.projectId||y.scope.environment!==n.scope.environment))throw new p("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=y.purchase,i=y.closed===!0,!y.command)return;let l=z.parse(y.command);if(l.operation==="start"||l.operation==="get"||l.operation==="review")throw new p("COMMAND_STORAGE_INVALID","Stored mutation required");s=l,y.closeCommand&&(g=y.closeCommand,i=!0),l.operation==="close"&&(i=!0),r=!0}):Promise.resolve();u.catch(()=>{});async function F(y=s){if(e&&await u,!y)throw new p("INVALID_REQUEST","No command is pending");let l=y,m=t.generation;if(e){if(!t.view||!n.scope)throw new p("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:K(l)})}if(m!==t.generation||s!==l&&g!==l)throw new p("IDENTITY_CHANGED","Run changed before command dispatch");let S={...l,...t.customerToken?{customerToken:t.customerToken}:{}},R=r;r=!0;try{return await d(S,C=>{if(!C.settlement)throw new p("INVALID_RESPONSE","Exact command settlement is missing");if(C.settlement.requestId!==l.requestId)throw new p("INVALID_RESPONSE","Command settlement identity changed");if(m===t.generation&&(s===l||g===l)&&C.run.pendingRequest?.requestId!==l.requestId&&C.settlement.state==="settled"&&(!i||l.operation==="close"||C.settlement?.state==="settled"&&!["running","waiting"].includes(C.run.status))){let P=()=>m!==t.generation||s!==l&&g!==l?!1:(s===l&&(s=null),g===l&&(g=null),r=s!==null,h=null,!0);return e?e.settle(l.requestId).then(P):P()}return!1})}catch(C){throw m===t.generation&&s===l&&!R&&!Pn(C)&&(e&&await e.settle(l.requestId),m===t.generation&&s===l&&(s=null,r=!1,h=null)),C}}function N(y){let l=z.parse(y);if(l.operation==="start"||l.operation==="get"||l.operation==="review")throw new p("INVALID_REQUEST","Mutation required");if(i&&l.operation!=="close"){if(s?.requestId===l.requestId)return c(l.requestId);throw new p("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(l.operation==="close"&&s?.operation!=="close"){if(i=!0,g&&JSON.stringify(K(g))!==JSON.stringify(K(l)))throw new p("COMMAND_PENDING","Retry the original Close");return g??=l,o.close?o.close:O(g,"close")}if(s){if(JSON.stringify(K(s))!==JSON.stringify(K(l)))throw new p("COMMAND_PENDING","Retry the original command before sending another");if(o.command)return o.command}else s=l,r=!1;return O(s,"command")}function O(y,l){let m=F(y);o[l]=m;let S=()=>{o[l]===m&&(o[l]=null)};return m.then(S,S),m}async function c(y){let l=await d({operation:"get",settlementRequestId:y,...t.customerToken?{customerToken:t.customerToken}:{}});if(l.settlement?.requestId!==y)throw new p("INVALID_RESPONSE","Exact command settlement is missing");return l.settlement.state==="settled"&&(e&&await e.settle(y),s?.requestId===y&&(s=null,r=!1),g?.requestId===y&&(g=null)),l}return{ready:u,get pending(){return s},get closing(){return g},get closeRequested(){return i},get inFlight(){return o.command},get closeFlight(){return o.close},get purchase(){return a},assertBinding(y){if(h&&(y.run.id!==h.runId||y.run.source.id!==h.funnelId||y.run.source.versionId!==h.versionId))throw new p("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(y,l,m,S){e?.bind({scope:l.scope,runId:l.run.id,funnelId:l.run.source.id,versionId:l.run.source.versionId}),e&&!n.scope&&(n.scope=l.scope);let R=l.run.paywall,C=R??l.purchase,P=C?.operation,T=l.settlement&&(!R||R.purchaseRequestId===l.settlement.requestId)&&(!a||a.operationId===l.settlement.operationId)?l.settlement:void 0,_=P?.operationId??C?.quote?.operationId??T?.operationId,G=C?.receiptId??T?.receiptId,J=R?.selectionGeneration??a?.generation??0;if(e&&_&&G&&y.operation!=="review"&&(!t.view||l.run.revision>=t.view.revision)&&(S===void 0||S>=t.readSequence)&&(!a||J>=a.generation)){let Y={receiptId:G,operationId:_,generation:J},q=P?.status==="complete"||C?.canReselect===!0;return e.observePurchase({scope:l.scope,runId:l.run.id,funnelId:l.run.source.id,versionId:l.run.source.versionId},Y,q).then(()=>{t.assertCurrent(m),q?a?.operationId===Y.operationId&&(a=void 0):a=Y})}},stop(){i=!0},submit:N,executePending:F,settle:c,reset(){s=null,g=null,o.close=null,r=!1,o.command=null}}}function wn(n){if(n={...n},typeof n.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(n.runToken))throw new p("INVALID_TOKEN","Run credential required");if(n.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.serverKey)))throw new p("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let e=re({...n,...n.serverKey?{fetch:(c,y)=>{let l=new Headers(y?.headers),m=typeof y?.body=="string"?JSON.parse(y.body):null;return m!==null&&typeof m=="object"&&"customerToken"in m&&typeof m.customerToken=="string"&&m.customerToken.length>0||l.set(Ze,n.serverKey),(n.fetch??globalThis.fetch)(c,{...y,headers:l})}}:{},timeoutMs:n.timeoutMs??35e3});e.identify(n.runToken);let t=pn(n.funnelId),d=null,s=n.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?ln(n):void 0),g=s&&fn(s),i=gn({options:n,journal:g,state:t,call:o});async function o(c,y,l){let m=t.generation,S=()=>t.assertCurrent(m);g&&await i.ready,S();let R=t.view,C=ge.parse(await ye(n,await e.request("funnels",z.parse(c))));if(c.operation==="review"&&!C.review)throw new p("INVALID_RESPONSE","Historical projection is missing");if(S(),C.runToken&&C.runToken!==n.runToken)throw new p("INVALID_RESPONSE","Run credential changed");let P=c.operation==="get"?c.settlementRequestId:"requestId"in c&&c.operation!=="start"?c.requestId:void 0;if(P&&C.settlement?.requestId!==P)throw new p("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(C),t.assertRun(C.run);let T=i.observePurchase(c,C,m,l);if(T&&await T,!C.run.stopped&&["running","waiting"].includes(C.run.status)&&c.operation==="get"&&c.settlementRequestId)return C;let _=y?.(C),G=typeof _=="boolean"?_:_?await _:!1;return S(),["running","waiting"].includes(C.run.status)||i.stop(),t.publish(c,C,R,l,G),C}let r=i.submit,a=null,h=new WeakMap;function u(c){let y=h.get(c);if(y)return y;let l=N(c);return h.set(c,l),l}let F=!1;async function N(c){let y=await c;if(y.run.instruction?.type!=="evaluate_segment")return y;if(a)return a;F=!0;let l=t.generation,m=(async()=>{for(let S=0;S<32&&y.run.instruction?.type==="evaluate_segment";S++){if(i.pending||i.closeRequested)return y;let R=y.run;if(y.run.instruction?.type==="evaluate_segment"){let{advance:P}=await Fe(n.configuration,R,{predict:!1});if(l!==t.generation)throw new p("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return y;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return o({operation:"get",...t.customerToken?{customerToken:t.customerToken}:{}});let T=!0;Fe(n.configuration,R).then(({prediction:_})=>{T&&l===t.generation&&!i.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(d=_)}).catch(()=>{});try{y=await r({operation:"commit_segment",requestId:Ye(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...P})}finally{T=!1,d=null}}}return y})();a=m;try{return await m}finally{a===m&&(a=null)}}let O={get configuration(){return F?n.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let c=i.closing??i.pending;return c?structuredClone(K(c)):null},get pendingCommands(){return[i.pending,i.closing].filter(c=>c!==null).map(c=>structuredClone(K(c)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get prediction(){let c=t.view;return d&&c&&!c.stopped&&["running","waiting"].includes(c.status)&&c.id===d.runId&&c.nodeId===d.from.nodeId&&c.visit===d.from.visit&&c.revision===d.from.revision&&!i.closeRequested?structuredClone(d):null},settle:i.settle,get webViewUrl(){return"bundled"},resolvePaywall(c){return Ie(n,c)},review(c){return o({operation:"review",...c?{receiptId:c}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,t.nextRead())},async get(c,y){g&&await i.ready,y??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let l=t.nextRead();return u(o({operation:"get",...c?{data:c}:{},...y?{purchase:y}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,l))},resume(c=t.view?.pendingRequest?.requestId){return c?i.closeRequested?O.settle(c):i.pending?.requestId===c?u(r(i.pending)):u(r({operation:"resume",requestId:c})):Promise.reject(new p("INVALID_REQUEST","No interrupted command is available"))},submit(c){return u(r(c))},retry(){return i.closeFlight?i.closeFlight:i.closing?i.executePending(i.closing):i.closeRequested&&i.pending?O.settle(i.pending.requestId):i.inFlight?u(i.inFlight):i.pending?u(r(i.pending)):Promise.reject(new p("INVALID_REQUEST","No command is pending"))},identify(c){t.identify(c),d=null,e.identify(n.runToken)},subscribe:t.subscribe,reset(){t.reset(),i.reset(),d=null,e.reset()}};return O}async function Et(n,e){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(e.customerToken))throw new p("INVALID_TOKEN","A verified Customer credential is required");let t=re(n);t.identify(e.customerToken);let d=ee.resolvePaywall.request.parse({funnelId:e.funnelId,funnelVersionId:e.funnelVersionId,selector:e.paywallVersionId?{type:"version",versionId:e.paywallVersionId}:{type:"paywall",paywallId:e.paywallId},commerce:e.commerce,locale:e.locale,...e.requirement?{requirement:e.requirement}:{}}),s=null,g=!1,i=null,o=null,r=null,a=null;async function h(){if(g)throw new p("IDENTITY_CHANGED","Paywall is closed");let N=ee.resolvePaywall,O=await we(t.request,N,{...d,selector:s?{type:"version",versionId:s.id}:d.selector}),c={paywall:await Ie(n,O.paywall)};if(g)throw new p("IDENTITY_CHANGED","Paywall is closed");if(e.paywallVersionId?c.paywall.id!==e.paywallVersionId:c.paywall.paywallId!==e.paywallId)throw new p("INVALID_RESPONSE","The requested Paywall changed");if(s&&(!on(c.paywall,s)||c.paywall.paywallId!==s.paywallId))throw new p("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return s=c.paywall,structuredClone(s)}async function u(N){if(!i)throw new p("INVALID_REQUEST","A quoted purchase is required");let O=N==="read"?ee.readSubscriptionOperation:ee.attach,c=await we(t.request,O,{operationId:i.operationId,...N==="read"?{}:{intent:N}});return an(c.operation,{operationId:i.operationId,currency:d.commerce.currency},"The purchase operation changed"),o=un(o,c.operation),structuredClone(o)}let F={get view(){return s?structuredClone(s):null},get quote(){return i?structuredClone(i):null},get operation(){return o?structuredClone(o):null},get webViewUrl(){return"bundled"},refresh:h,async preview(N){if(!s)throw new p("INVALID_REQUEST","Load the Paywall first");let O=s.document.buttons[N.actionId];if(O?.type!=="checkout")throw new p("INVALID_REQUEST","Choose an authored purchase action");let c=Me(O.product,N.selection,s.capabilities);if(!c)throw new p("PRODUCT_UNAVAILABLE","Choose an available Product");let y=ee.previewAttach.request.parse({funnelId:d.funnelId,funnelVersionId:d.funnelVersionId,requestId:N.requestId,plans:[{productVersionId:c}],provider:d.commerce.provider,currency:d.commerce.currency,...N.offerId?{offerId:N.offerId}:{},...N.nativeOffer?{nativeOffer:N.nativeOffer}:{}}),l=JSON.stringify(y);if(r&&r!==l&&(!o||o.status==="pending"))throw new p("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(r===l){if(a)return a;if(i)return structuredClone(i)}r=l;let m=(async()=>{let S=ee.previewAttach,R=await we(t.request,S,y);return sn(R.quote,{productVersionId:c,currency:d.commerce.currency,provider:d.commerce.provider},"The purchase quote changed its selected Product or presentment"),i=R.quote,o=null,structuredClone(i)})();a=m;try{return await m}finally{a===m&&(a=null)}},confirm:()=>u("confirm"),cancel:()=>u("cancel"),read:()=>u("read"),destroy(){g=!0,t.reset(),s=null,i=null,o=null,r=null}};return await h(),F}import{z as Nn}from"zod";import{z as ue}from"zod";var Fn=ue.record(ue.string().regex(/^[a-f0-9]{64}$/),ue.strictObject({at:ue.number(),text:ue.string()})),yn=2*1048576,En=100;function An(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function hn(n,e){let t=e===void 0?An():e,d=Promise.resolve();async function s(i){if(!t)return null;let o;try{return await Promise.race([Promise.resolve().then(()=>t.getItem(i)),new Promise(r=>{o=setTimeout(()=>r(null),En)})])}catch{return null}finally{clearTimeout(o)}}async function g(){try{let i=await s(`${n}:artifacts`);if(i&&i.length<=yn)return Fn.parse(JSON.parse(i))}catch{}return{}}return{async readManifest(){return s(n)},writeManifest(i){Promise.resolve().then(()=>t?.setItem(n,i)).catch(()=>{})},async readArtifact(i){let o=(await g())[i];return o&&Date.now()>=o.at&&Date.now()-o.at<=U.retentionMs?o.text:void 0},writeArtifact(i,o){t&&(d=d.catch(()=>{}).then(async()=>{let r=await g(),a=Date.now();r[i]={at:a,text:o};let h={},u=2,F=0;for(let[N,O]of Object.entries(r).sort(([,c],[,y])=>y.at-c.at)){if(O.at>a||a-O.at>U.retentionMs)continue;let c=new TextEncoder().encode(JSON.stringify({[N]:O})).byteLength;u+c>yn||F>=128||(h[N]=O,u+=c,F++)}await t.setItem(`${n}:artifacts`,JSON.stringify(h))}).catch(()=>{}))}}}var b=(n,e)=>new p(n,e),Q=()=>performance.now(),In=n=>{typeof n=="object"&&"unref"in n&&n.unref()};function Mt(n){let e=Be.parse(n.scope),t=new URL(n.origin??te);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw b("INVALID_URL","Configuration requires a trusted HTTPS origin");let d=new Set([t.origin,...(n.assetOrigins??[]).map(w=>{let f=new URL(w);if(f.protocol!=="https:"||f.username||f.password||f.search||f.hash||f.pathname!=="/")throw b("INVALID_URL","Invalid configuration asset origin");return f.origin})]),s=n.fetch??globalThis.fetch.bind(globalThis),g=`/api/v1/configuration/${e.environmentId}`,i=`indiana:configuration:1:${t.origin}:${L(e)}`,o=hn(i,n.storage),r,a=0,h=0,u=!1,F=!1,N=0,O=0,c,y,l,m,S=0,R=new Set,C=new Set,P=new Map,T=new Map,_=0,G=!1;function J(){for(let w of R)try{w()}catch{}}function Y(w){try{n.onError?.(w)}catch{}}let q=()=>!F&&!u&&!!r&&Q()<a&&Date.now()<h;function Z(){if(!q())throw b("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ee(w,f){let I=new TextEncoder().encode(f).byteLength;if(!P.has(w)){for(;P.size&&(P.size>=128||_+I>U.maxCacheBytes);){let v=P.entries().next().value;_-=new TextEncoder().encode(v[1]).byteLength,P.delete(v[0])}P.set(w,f),_+=I}}function Ae(w,f,I){return cn(w,f,{signal:I,error:v=>b("INVALID_RESPONSE",v==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Ne(w){let f=new URL(w,t);if(!d.has(f.origin)||f.username||f.password||f.hash||f.search)throw b("INVALID_URL","Configuration artifact origin is not trusted");return f.href}async function Re(w,f,I=!1){let v=await s(Ne(w),{method:"GET",credentials:"omit",redirect:"error",cache:I?"default":"no-cache",signal:f,headers:{}});if(v.status===429){let E=v.headers.get("retry-after")??"";S=/^\d+$/.test(E)?Number(E)*1e3:Math.max(0,Date.parse(E)-Date.now())||15e3}if(!v.ok&&v.status!==304)throw b(`CONFIGURATION_HTTP_${v.status}`,"Configuration synchronization failed");return v}function Rn(w,f,I){let v=Date.parse(w.headers.get("x-indiana-config-validated-at")??""),E=Date.parse(w.headers.get("x-indiana-config-valid-until")??""),D=Date.parse(w.headers.get("date")??""),A=w.headers.get("age"),M=A!==null&&/^\d+(\.\d+)?$/.test(A)?Number(A)*1e3:NaN;if(![v,E,D,M].every(Number.isFinite)||E<=v||E-v>U.maxControlAgeMs||v>D+1e3)throw b("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(E-v,I.maxControlAgeSeconds*1e3,U.maxControlAgeMs)-Math.max(M,D-v,0)-(Q()-f);if(x<=0)throw b("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Q()+x}function Ce(){if(clearTimeout(l),clearTimeout(m),F||!R.size)return;q()&&(m=setTimeout(()=>{q()?Ce():J()},Math.max(1,a-Q())),In(m));let w=O?Math.min(15e3,1e3*2**Math.min(O-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);l=setTimeout(()=>{ne().catch(Y)},Math.max(S,w*(.8+Math.random()*.2))),In(l)}async function ne(){if(F)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(c)return c;let w=N,f=new AbortController;y=f;let I=(async()=>{if(!G){G=!0;try{let me=await o.readManifest();if(me&&!r){let j=Se.parse(JSON.parse(me));L(j.scope)===L(e)&&(r=j)}}catch{}}f.signal.throwIfAborted();let A=r,M=Q(),V=await Re(g,f.signal);V.status===304&&(!A||!V.headers.has("x-indiana-config-validated-at")||!V.headers.has("x-indiana-config-valid-until")||!V.headers.has("age"))&&(V=await Re(g,f.signal));let x=V.status===304?A:Se.parse(JSON.parse(await Ae(V,U.maxManifestBytes,f.signal))),{generation:H,...$}=x,W=V.headers.get("etag");if(L(x.scope)!==L(e)||ze($)!==H||W!==`"${H}"`&&W!==`W/"${H}"`)throw b("INVALID_RESPONSE","Configuration scope or content identity changed");if(A&&(x.revision<A.revision||x.revision===A.revision&&x.generation!==A.generation))throw b("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[me,j]of Object.entries(A?.funnels??{})){let X=x.funnels[me];if(X&&(X.controlRevision<j.controlRevision||X.evaluationRevision<j.evaluationRevision||X.controlRevision===j.controlRevision&&X.state!==j.state||X.evaluationRevision===j.evaluationRevision&&X.evaluationMode!==j.evaluationMode))throw b("INVALID_RESPONSE","Funnel control revision changed identity")}let xe=Rn(V,M,x.policy);if(f.signal.throwIfAborted(),w!==N)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return r=x,a=xe,h=Date.now()+Math.max(0,xe-Q()),u=!1,O=0,S=0,o.writeManifest(L(x)),J(),structuredClone(x)})(),v=setTimeout(()=>f.abort(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),U.initializationMs),E=new Promise((A,M)=>f.signal.addEventListener("abort",()=>M(f.signal.reason),{once:!0})),D=Promise.race([I,E]).catch(A=>{throw O++,(A instanceof Nn.ZodError||A instanceof SyntaxError||A instanceof p&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(A.code))&&(a=0,u=!0,J()),A}).finally(()=>{clearTimeout(v),c===D&&(c=void 0),Ce()});return c=D,D}async function le(w){let f=w.sha256,I=H=>he(H,w);Ne(w.url);let v=P.get(f);if(v&&I(v))return P.delete(f),P.set(f,v),v;if(T.has(f))return T.get(f);let E=new AbortController;C.add(E);let D=N,A=(async()=>{try{let W=await o.readArtifact(f);if(W&&I(W))return Ee(f,W),W}catch{}E.signal.throwIfAborted();let H=await Re(w.url,E.signal,!0),$=await Ae(H,w.byteLength,E.signal);if(!I($))throw b("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(F||D!==N)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return Ee(f,$),o.writeArtifact(f,$),$})(),M=setTimeout(()=>E.abort(b("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),U.initializationMs),V=new Promise((H,$)=>E.signal.addEventListener("abort",()=>$(E.signal.reason),{once:!0})),x=Promise.race([A,V]).finally(()=>{clearTimeout(M),C.delete(E),T.delete(f)});return T.set(f,x),x}async function ce(){return q()||await ne(),Z(),r}async function ie(w){let f,I=new Promise((v,E)=>{f=setTimeout(()=>E(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),U.initializationMs)});try{return await Promise.race([w(),I])}finally{clearTimeout(f)}}function ae(w,f){if(Z(),r?.generation!==w.generation)throw b("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(f&&r.funnels[f]?.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Oe(w){let f=w.gb.features;if(!f)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let I=w.artifacts[f];if(I.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let v=qe.parse(JSON.parse(await le(I)));if(L(v.scope)!==L({projectId:e.projectId,environment:e.environment})||v.generation!==I.generation||v.remoteFeatures.some(E=>Object.hasOwn(v.features,E)))throw b("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return ae(w),{...v,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-Q())).toISOString()}}async function Te(w,f){let I=await ce(),v=I.funnels[w];f&&(!v||v.evaluationMode==="local"&&!v.versions[f])&&(c&&await c,I=await ne()),ae(I,w);let E=I.funnels[w];if(E.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let D=f??E.currentVersionId,A=E.versions[D];if(!A)throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(I.artifacts[A.artifact].formatVersion!==3)throw b("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[M,V]=await Promise.all([le(I.artifacts[A.artifact]).then(x=>$e(JSON.parse(x))),E.evaluationMode==="local"?Oe(I):void 0]);if(V&&L(He(M,V))!==L(A.dependencies))throw b("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return ae(I,w),{document:M,growth:V,versionId:D,control:structuredClone(E),manifest:structuredClone(I)}}async function _e(w,f){try{return await Te(w,f)}catch(I){if(!(I instanceof p)||!(I.code==="CONFIGURATION_CHANGED"||I.code==="CONFIGURATION_HTTP_404"&&q()))throw I;let v=r?.generation;if(c&&await c,await ne(),I.code!=="CONFIGURATION_CHANGED"&&r?.generation===v)throw I;return Te(w,f)}}function be(){u=!0,J(),ne().catch(Y)}let de=()=>{(typeof document>"u"||document.visibilityState==="visible")&&be()};function Cn(w){if(F)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return R.add(w),R.size===1&&(typeof window<"u"&&(window.addEventListener("online",be),window.addEventListener("focus",de),document.addEventListener("visibilitychange",de)),Ce()),()=>{R.delete(w),R.size||(clearTimeout(l),clearTimeout(m),De())}}function De(){typeof window<"u"&&(window.removeEventListener("online",be),window.removeEventListener("focus",de),document.removeEventListener("visibilitychange",de))}return{scope:Object.freeze({...e}),refresh:ne,subscribe:Cn,assertFresh:Z,assertFeatures(w){Z();let f=r.gb.features;if(!f)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(w!==void 0&&r.artifacts[f].generation!==w)throw b("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return q()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return q()?Math.max(0,a-Q()):0},async features(){return ie(async()=>Oe(await ce()))},pageExperiments:()=>ie(async()=>{let w=await ce(),f=w.gb.pageExperiments;if(!f)throw b("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let I=w.artifacts[f];if(I.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let v=en.parse(JSON.parse(await le(I)));if(v.environmentId!==e.environmentId||v.generation!==I.generation)throw b("INVALID_RESPONSE","Page experiment scope or generation changed");return ae(w),v}),funnel:(w,f)=>ie(()=>_e(w,f)),paywall:(w,f)=>ie(async()=>{let I=await ce(),v=I.paywalls?.[w];if(!v||!f&&v.state!=="published")throw b("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let E=f??v.currentVersionId,D=v.versions[E],A=D&&I.artifacts[D.artifact];if(!A||A.kind!=="paywall"||A.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let M=Je.parse(JSON.parse(await le(A)));return ae(I),{document:M,versionId:E,version:D.version,control:structuredClone(v),manifest:structuredClone(I)}}),async localFunnel(w,f){let I=await ie(()=>_e(w,f));if(!I.growth)throw b("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:v,remoteFeatures:E,...D}=I.growth;return Xe({scope:{projectId:e.projectId,environment:e.environment},funnelId:w,versionId:I.versionId,evaluationMode:"local",evaluationRevision:I.control.evaluationRevision,document:I.document,payload:D})},assertFunnel(w,f,I){Z();let v=r.funnels[w];if(!v||v.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable");if(v.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel now executes at Indiana");if(f!==void 0&&v.controlRevision!==f)throw b("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(I!==void 0&&!v.versions[I])throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!F){F=!0,N++,a=0,y?.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(l),clearTimeout(m),De(),J(),R.clear();for(let w of C)w.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),_=0}}}}function Jt(n,e,t){return tn(n,e,t,se)}function vn(n){let e=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey);if(typeof window<"u"&&!e)throw new p("SERVER_ONLY","Funnel starts are issued by your backend");if(!e&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new p("INVALID_TOKEN","A customer credential or server API key is required");let t=re({...n,timeoutMs:n.timeoutMs??35e3});return t.identify(n.apiKey),{async start(d){let s=z.safeParse({...d,operation:"start"});if(!s.success||s.data.operation!=="start"||(e?s.data.customer!==void 0:s.data.customer===void 0))throw new p("INVALID_REQUEST","Invalid current Funnel start");let g=s.data,i=ge.safeParse(await ye(n,await t.request("funnels",g)));if(!i.success||!i.data.runToken)throw new p("INVALID_RESPONSE","Funnel start credentials are missing");let o=i.data;if(o.run.source.id!==g.funnelId||o.run.locale!==(g.locale??"en")||!oe(o.run.parameters,g.parameters??{})||(g.customer?!o.customerId||g.customer.type==="id"&&o.customerId!==g.customer.value:o.customerId!==void 0))throw new p("INVALID_RESPONSE","Funnel start contract changed");return{...o,runToken:o.runToken}}}}async function Xt(n){n={...n};let e=n.configuration;if(!e)throw new p("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:e.scope.projectId,environment:e.scope.environment};if(n.scope&&L(t)!==L(n.scope))throw new p("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await e.funnel(n.funnelId)).control.evaluationMode!=="local")throw new p("EVALUATION_MODE","This Funnel uses Remote evaluation");let s=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.credential);if(s?!n.customerId:n.customerId!==void 0)throw new p("INVALID_REQUEST","Only Server-Key starts name their Customer");let g=vn({...n,scope:t,apiKey:n.credential}),i=o=>{let r=wn({...n,scope:t,runToken:o,...s?{serverKey:n.credential}:{}});return s||r.identify(n.credential),r};return{async start(o){let r=await g.start({...o,funnelId:n.funnelId,...s?{customer:{type:"id",value:n.customerId}}:{}}),a=i(r.runToken),h=await a.get();return{...r,...h,controller:a}},async restore(o){let r=i(o),a=await r.get();if(a.run.source.id!==n.funnelId)throw r.reset(),new p("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:o,controller:r}}}}export{Tn as a,ye as b,se as c,$n as d,Sn as e,ln as f,rt as g,oe as h,wn as i,Et as j,Mt as k,Jt as l,vn as m,Xt as n};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var s={name:"@tinkerlandai/indiana-sdk",version:"0.8.5",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var i="https://api.tinker.cash";export{s as a,i as b};
|
|
@@ -1311,6 +1311,11 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
|
|
|
1311
1311
|
} | {
|
|
1312
1312
|
type: "plans";
|
|
1313
1313
|
planIds: string[];
|
|
1314
|
+
} | {
|
|
1315
|
+
type: "merchandise";
|
|
1316
|
+
scope: {
|
|
1317
|
+
type: "selected" | "all" | "condition";
|
|
1318
|
+
};
|
|
1314
1319
|
};
|
|
1315
1320
|
displayCopy: {
|
|
1316
1321
|
defaultLocale: string;
|
|
@@ -1571,7 +1576,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
|
|
|
1571
1576
|
entry: string;
|
|
1572
1577
|
nodes: {
|
|
1573
1578
|
id: string;
|
|
1574
|
-
type: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
1579
|
+
type: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
1575
1580
|
outputs: Record<string, string>;
|
|
1576
1581
|
writes: Record<string, string>;
|
|
1577
1582
|
resources: {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as _,j as F}from"./chunk-BUDTHBFF.js";import{b as q}from"./chunk-SSLZKIIU.js";import"./chunk-3KQHKRZJ.js";import{cd as U}from"./chunk-6A5WWFNS.js";import{a as d}from"./chunk-SOQO2RDZ.js";import{Eb as M,Mb as z,Ob as N,tb as P}from"./chunk-LMR2TM3X.js";import{a as v}from"./chunk-DSPLGTQI.js";import"./chunk-OBYJWIRB.js";import"./chunk-WWUUVURR.js";import{a as O}from"./chunk-RRII2DMC.js";import"./chunk-KQCTDXVD.js";import{z as p}from"zod";var V=new WeakMap;function Q(r){let t={string:p.string(),number:p.number().finite(),boolean:p.boolean(),strings:p.array(p.string()),json:O}[r.type];return r.nullable?t.nullable():t}async function ne(r,t){return W(r,t,!1)}async function re(r,t){return W(r,t,!0)}async function W(r,t,w){t.signal?.throwIfAborted();let T=U.parse(t.content),o=T.document;if(V.has(r))throw new d("CONFLICT","Content is already mounted in this container");let f=p.record(p.string(),O).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))z.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))Q(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 $=N.parse(t.bindings??[]),a=r.ownerDocument,L,k=o.kind==="popup",n=k?a.createElement("dialog"):null,i=a.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 c=!1,C=!1,g=!1;w&&!n&&(i.style.width=`${r.getBoundingClientRect().width||a.defaultView?.innerWidth||800}px`);let B=w?_(n??i):()=>{},H,x,A=new Promise((e,s)=>{H=e,x=s});A.catch(()=>{});let l=null,E=structuredClone(o.screen);E.actions=E.actions.map(e=>e.type==="event"?{...e,close:!1}:e);let y;function m(){c||(c=!0,t.signal?.removeEventListener("abort",m),x(new Error("Content preparation cancelled")),y?.destroy(),n?.close(),n?.remove(),i.remove(),V.delete(r),n&&L?.())}let S=()=>{g&&(m(),v(t.onDismiss))};if(n){let e=a.createElement("button");e.type="button",e.textContent="\xD7",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),e.style.cssText="position:absolute;right:8px;top:8px;width:30px;height:30px;z-index:1",e.addEventListener("click",S),n.prepend(e)}n?.addEventListener("cancel",e=>{e.preventDefault(),S()});async function D(){if(c||!g||C||!l)return;let e=l;C=!0,i.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),l=null}catch(s){v(t.onError,s)}finally{C=!1,c||i.removeAttribute("aria-busy")}}function R(){if(c)throw new d("CONFLICT","Content host has been destroyed");g||(L=q(a),B(),w&&!n&&(i.style.width="100%"),n?.showModal(),g=!0)}try{w||R(),y=F(i,{mode:"live",title:o.name,viewportHeight:o.kind==="page"?r.clientHeight||a.defaultView?.innerHeight||800:void 0,onRendered:H,onError:u=>{let I=new Error(u);x(I),v(t.onError,I)},onEscape:k?S:void 0,onAction:(u,I,J)=>{if(c||!g||C||l)return;let h=o.screen.actions.find(b=>b.id===u),j=o.contract.outputs[u];if(!(h?.type!=="event"||!j))try{let b=Q(j).parse(Object.hasOwn(h.properties,"value")?h.properties.value:h.properties);l={requestId:crypto.randomUUID(),contentVersionId:T.id,actionId:u,event:h.event,value:b,selection:I??{},answers:J??{},requestedClose:h.close},D()}catch(b){v(t.onError,b)}}});let e={destroy:m,show:R,get pendingAction(){return l?structuredClone(l):null},retryAction:D,updateCapabilities:u=>y?.updateCapabilities(u)};V.set(r,e),t.signal?.addEventListener("abort",m,{once:!0}),t.signal?.aborted&&(m(),t.signal.throwIfAborted());let s=M(E,[t.locale,...a.defaultView?.navigator.languages??[]]);if(y.update(E,s,{capabilities:t.capabilities,serverInput:{bindings:$,answers:{},values:f}}),await Promise.race([y.ready,A]),w&&await A,c)throw new Error("Content preparation cancelled");return e}catch(e){throw m(),e}}export{ne as mountContent,re as prepareContent};
|
|
@@ -311,6 +311,17 @@ declare const couponInputSchema: z.ZodObject<{
|
|
|
311
311
|
}, z.core.$strict>, z.ZodObject<{
|
|
312
312
|
type: z.ZodLiteral<"plans">;
|
|
313
313
|
planIds: z.ZodArray<z.ZodUUID>;
|
|
314
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
315
|
+
type: z.ZodLiteral<"merchandise">;
|
|
316
|
+
scope: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
317
|
+
type: z.ZodLiteral<"all">;
|
|
318
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
319
|
+
type: z.ZodLiteral<"selected">;
|
|
320
|
+
merchandiseIds: z.ZodArray<z.ZodUUID>;
|
|
321
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
322
|
+
type: z.ZodLiteral<"condition">;
|
|
323
|
+
condition: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
|
|
324
|
+
}, z.core.$strict>], "type">;
|
|
314
325
|
}, z.core.$strict>], "type">;
|
|
315
326
|
eligibility: z.ZodObject<{
|
|
316
327
|
firstPurchaseOnly: z.ZodBoolean;
|
|
@@ -397,6 +408,15 @@ declare const offerSchema: z.ZodObject<{
|
|
|
397
408
|
}, z.core.$strict>, z.ZodObject<{
|
|
398
409
|
type: z.ZodLiteral<"plans">;
|
|
399
410
|
planIds: z.ZodArray<z.ZodUUID>;
|
|
411
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
412
|
+
type: z.ZodLiteral<"merchandise">;
|
|
413
|
+
scope: z.ZodObject<{
|
|
414
|
+
type: z.ZodEnum<{
|
|
415
|
+
selected: "selected";
|
|
416
|
+
all: "all";
|
|
417
|
+
condition: "condition";
|
|
418
|
+
}>;
|
|
419
|
+
}, z.core.$strict>;
|
|
400
420
|
}, z.core.$strict>], "type">;
|
|
401
421
|
}, z.core.$strict>;
|
|
402
422
|
}, z.core.$strict>;
|
|
@@ -404,8 +424,8 @@ type Offer = z.infer<typeof offerSchema>;
|
|
|
404
424
|
/** 领取失败的原因:未生效 / 不在有效期 / 不符合标签 / 不是首购 / 已达每人上限 / 已领完。 */
|
|
405
425
|
declare const offerUnavailableReasonSchema: z.ZodEnum<{
|
|
406
426
|
unavailable: "unavailable";
|
|
407
|
-
claim_disabled: "claim_disabled";
|
|
408
427
|
inactive: "inactive";
|
|
428
|
+
claim_disabled: "claim_disabled";
|
|
409
429
|
outside_window: "outside_window";
|
|
410
430
|
not_targeted: "not_targeted";
|
|
411
431
|
not_first_purchase: "not_first_purchase";
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { I as InvoiceModeParams, b as InvoiceModeParamsInput, A as ApiInput } from './api-
|
|
1
|
+
import { I as InvoiceModeParams, b as InvoiceModeParamsInput, A as ApiInput } from './api-XDc4pRlN.js';
|
|
2
2
|
import { S as StackNode, d as ScreenSelection } from './screen-BpAejkn0.js';
|
|
3
3
|
import * as zod from 'zod';
|
|
4
4
|
import { z } from 'zod';
|
|
5
5
|
import { E as EvaluationContext, J as JsonValue, F as FeatureResult } from './growth-rules-B4YYy64R.js';
|
|
6
6
|
import { a as PushHost, S as Scope } from './errors-C8lRYZ0n.js';
|
|
7
|
-
import { C as ConfigurationSync } from './configuration-sync-
|
|
7
|
+
import { C as ConfigurationSync } from './configuration-sync-Ce3dShy7.js';
|
|
8
8
|
|
|
9
9
|
declare const currencySchema: z.ZodEnum<{
|
|
10
10
|
USD: "USD";
|
|
@@ -261,12 +261,12 @@ declare const funnelRunViewSchema: z.ZodObject<{
|
|
|
261
261
|
feature: "feature";
|
|
262
262
|
split: "split";
|
|
263
263
|
condition: "condition";
|
|
264
|
+
entry: "entry";
|
|
264
265
|
coupon: "coupon";
|
|
265
266
|
end: "end";
|
|
266
267
|
screen: "screen";
|
|
267
268
|
offering: "offering";
|
|
268
269
|
coupons: "coupons";
|
|
269
|
-
entry: "entry";
|
|
270
270
|
external_page: "external_page";
|
|
271
271
|
wait: "wait";
|
|
272
272
|
}>;
|
|
@@ -2304,12 +2304,12 @@ declare const funnelRuntimeResponseSchema: z.ZodObject<{
|
|
|
2304
2304
|
feature: "feature";
|
|
2305
2305
|
split: "split";
|
|
2306
2306
|
condition: "condition";
|
|
2307
|
+
entry: "entry";
|
|
2307
2308
|
coupon: "coupon";
|
|
2308
2309
|
end: "end";
|
|
2309
2310
|
screen: "screen";
|
|
2310
2311
|
offering: "offering";
|
|
2311
2312
|
coupons: "coupons";
|
|
2312
|
-
entry: "entry";
|
|
2313
2313
|
external_page: "external_page";
|
|
2314
2314
|
wait: "wait";
|
|
2315
2315
|
}>;
|
|
@@ -5398,12 +5398,12 @@ declare const funnelConfigurationSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
5398
5398
|
feature: "feature";
|
|
5399
5399
|
split: "split";
|
|
5400
5400
|
condition: "condition";
|
|
5401
|
+
entry: "entry";
|
|
5401
5402
|
coupon: "coupon";
|
|
5402
5403
|
end: "end";
|
|
5403
5404
|
screen: "screen";
|
|
5404
5405
|
offering: "offering";
|
|
5405
5406
|
coupons: "coupons";
|
|
5406
|
-
entry: "entry";
|
|
5407
5407
|
external_page: "external_page";
|
|
5408
5408
|
wait: "wait";
|
|
5409
5409
|
}>;
|
|
@@ -5443,12 +5443,12 @@ declare const funnelConfigurationSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
5443
5443
|
feature: "feature";
|
|
5444
5444
|
split: "split";
|
|
5445
5445
|
condition: "condition";
|
|
5446
|
+
entry: "entry";
|
|
5446
5447
|
coupon: "coupon";
|
|
5447
5448
|
end: "end";
|
|
5448
5449
|
screen: "screen";
|
|
5449
5450
|
offering: "offering";
|
|
5450
5451
|
coupons: "coupons";
|
|
5451
|
-
entry: "entry";
|
|
5452
5452
|
external_page: "external_page";
|
|
5453
5453
|
wait: "wait";
|
|
5454
5454
|
}>;
|
|
@@ -5662,12 +5662,12 @@ declare const funnelLocalConfigurationSchema: z.ZodObject<{
|
|
|
5662
5662
|
feature: "feature";
|
|
5663
5663
|
split: "split";
|
|
5664
5664
|
condition: "condition";
|
|
5665
|
+
entry: "entry";
|
|
5665
5666
|
coupon: "coupon";
|
|
5666
5667
|
end: "end";
|
|
5667
5668
|
screen: "screen";
|
|
5668
5669
|
offering: "offering";
|
|
5669
5670
|
coupons: "coupons";
|
|
5670
|
-
entry: "entry";
|
|
5671
5671
|
external_page: "external_page";
|
|
5672
5672
|
wait: "wait";
|
|
5673
5673
|
}>;
|
|
@@ -7461,6 +7461,10 @@ declare const evaluateFeaturesResultSchema: z.ZodObject<{
|
|
|
7461
7461
|
stickyBucketUsed: z.ZodOptional<z.ZodBoolean>;
|
|
7462
7462
|
}, z.core.$strict>>;
|
|
7463
7463
|
}, z.core.$strict>>;
|
|
7464
|
+
merchandiseContext: z.ZodOptional<z.ZodObject<{
|
|
7465
|
+
merchandiseId: z.ZodUUID;
|
|
7466
|
+
merchandise: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
|
|
7467
|
+
}, z.core.$strict>>;
|
|
7464
7468
|
}, z.core.$strict>;
|
|
7465
7469
|
|
|
7466
7470
|
type FunnelNodeEvaluationContext = Pick<EvaluationContext, "attributes" | "stickyBucketAssignmentDocs" | "saveStickyBucketAssignmentDoc" | "onFeatureUsage" | "onExperimentViewed">;
|
|
@@ -8567,8 +8571,14 @@ type FeatureClientOptions = {
|
|
|
8567
8571
|
attributes?: Record<string, JsonValue>;
|
|
8568
8572
|
scope: FeaturePayload["scope"];
|
|
8569
8573
|
onError?: (error: unknown) => void;
|
|
8570
|
-
onFeatureUsage?:
|
|
8571
|
-
|
|
8574
|
+
onFeatureUsage?: (...args: [
|
|
8575
|
+
...Parameters<NonNullable<EvaluationContext["onFeatureUsage"]>>,
|
|
8576
|
+
Record<string, JsonValue>
|
|
8577
|
+
]) => void;
|
|
8578
|
+
onExperimentViewed?: (...args: [
|
|
8579
|
+
...Parameters<NonNullable<EvaluationContext["onExperimentViewed"]>>,
|
|
8580
|
+
Record<string, JsonValue>
|
|
8581
|
+
]) => void;
|
|
8572
8582
|
stickyBucketAssignmentDocs?: EvaluationContext["stickyBucketAssignmentDocs"];
|
|
8573
8583
|
saveStickyBucketAssignmentDoc?: EvaluationContext["saveStickyBucketAssignmentDoc"];
|
|
8574
8584
|
};
|
|
@@ -10205,6 +10215,11 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
10205
10215
|
} | {
|
|
10206
10216
|
type: "plans";
|
|
10207
10217
|
planIds: string[];
|
|
10218
|
+
} | {
|
|
10219
|
+
type: "merchandise";
|
|
10220
|
+
scope: {
|
|
10221
|
+
type: "selected" | "all" | "condition";
|
|
10222
|
+
};
|
|
10208
10223
|
};
|
|
10209
10224
|
displayCopy: {
|
|
10210
10225
|
defaultLocale: string;
|
|
@@ -10465,7 +10480,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
10465
10480
|
entry: string;
|
|
10466
10481
|
nodes: {
|
|
10467
10482
|
id: string;
|
|
10468
|
-
type: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
10483
|
+
type: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
10469
10484
|
outputs: Record<string, string>;
|
|
10470
10485
|
writes: Record<string, string>;
|
|
10471
10486
|
resources: {
|
|
@@ -10539,7 +10554,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
10539
10554
|
revision: number;
|
|
10540
10555
|
visit: number;
|
|
10541
10556
|
nodeId: string;
|
|
10542
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
10557
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
10543
10558
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
10544
10559
|
stopped: boolean;
|
|
10545
10560
|
canBack: boolean;
|
|
@@ -11705,7 +11720,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
11705
11720
|
revision: number;
|
|
11706
11721
|
visit: number;
|
|
11707
11722
|
nodeId: string;
|
|
11708
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
11723
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
11709
11724
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
11710
11725
|
stopped: boolean;
|
|
11711
11726
|
canBack: boolean;
|
|
@@ -13386,7 +13401,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
13386
13401
|
revision: number;
|
|
13387
13402
|
visit: number;
|
|
13388
13403
|
nodeId: string;
|
|
13389
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
13404
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
13390
13405
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
13391
13406
|
stopped: boolean;
|
|
13392
13407
|
canBack: boolean;
|
|
@@ -14805,7 +14820,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
14805
14820
|
revision: number;
|
|
14806
14821
|
visit: number;
|
|
14807
14822
|
nodeId: string;
|
|
14808
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
14823
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
14809
14824
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
14810
14825
|
stopped: boolean;
|
|
14811
14826
|
canBack: boolean;
|
|
@@ -16222,7 +16237,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
16222
16237
|
revision: number;
|
|
16223
16238
|
visit: number;
|
|
16224
16239
|
nodeId: string;
|
|
16225
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
16240
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
16226
16241
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
16227
16242
|
stopped: boolean;
|
|
16228
16243
|
canBack: boolean;
|
|
@@ -17642,7 +17657,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
17642
17657
|
revision: number;
|
|
17643
17658
|
visit: number;
|
|
17644
17659
|
nodeId: string;
|
|
17645
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
17660
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
17646
17661
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
17647
17662
|
stopped: boolean;
|
|
17648
17663
|
canBack: boolean;
|
|
@@ -20310,6 +20325,11 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
20310
20325
|
} | {
|
|
20311
20326
|
type: "plans";
|
|
20312
20327
|
planIds: string[];
|
|
20328
|
+
} | {
|
|
20329
|
+
type: "merchandise";
|
|
20330
|
+
scope: {
|
|
20331
|
+
type: "selected" | "all" | "condition";
|
|
20332
|
+
};
|
|
20313
20333
|
};
|
|
20314
20334
|
displayCopy: {
|
|
20315
20335
|
defaultLocale: string;
|
|
@@ -20570,7 +20590,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
20570
20590
|
entry: string;
|
|
20571
20591
|
nodes: {
|
|
20572
20592
|
id: string;
|
|
20573
|
-
type: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
20593
|
+
type: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
20574
20594
|
outputs: Record<string, string>;
|
|
20575
20595
|
writes: Record<string, string>;
|
|
20576
20596
|
resources: {
|
|
@@ -20644,7 +20664,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
20644
20664
|
revision: number;
|
|
20645
20665
|
visit: number;
|
|
20646
20666
|
nodeId: string;
|
|
20647
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
20667
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
20648
20668
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
20649
20669
|
stopped: boolean;
|
|
20650
20670
|
canBack: boolean;
|
|
@@ -21810,7 +21830,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
21810
21830
|
revision: number;
|
|
21811
21831
|
visit: number;
|
|
21812
21832
|
nodeId: string;
|
|
21813
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
21833
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
21814
21834
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
21815
21835
|
stopped: boolean;
|
|
21816
21836
|
canBack: boolean;
|
|
@@ -23491,7 +23511,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
23491
23511
|
revision: number;
|
|
23492
23512
|
visit: number;
|
|
23493
23513
|
nodeId: string;
|
|
23494
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
23514
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
23495
23515
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
23496
23516
|
stopped: boolean;
|
|
23497
23517
|
canBack: boolean;
|
|
@@ -24910,7 +24930,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
24910
24930
|
revision: number;
|
|
24911
24931
|
visit: number;
|
|
24912
24932
|
nodeId: string;
|
|
24913
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
24933
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
24914
24934
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
24915
24935
|
stopped: boolean;
|
|
24916
24936
|
canBack: boolean;
|
|
@@ -26327,7 +26347,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
26327
26347
|
revision: number;
|
|
26328
26348
|
visit: number;
|
|
26329
26349
|
nodeId: string;
|
|
26330
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
26350
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
26331
26351
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
26332
26352
|
stopped: boolean;
|
|
26333
26353
|
canBack: boolean;
|
|
@@ -27747,7 +27767,7 @@ declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Pro
|
|
|
27747
27767
|
revision: number;
|
|
27748
27768
|
visit: number;
|
|
27749
27769
|
nodeId: string;
|
|
27750
|
-
nodeType: "output" | "action" | "feature" | "split" | "condition" | "coupon" | "end" | "screen" | "offering" | "coupons" | "
|
|
27770
|
+
nodeType: "output" | "action" | "feature" | "split" | "condition" | "entry" | "coupon" | "end" | "screen" | "offering" | "coupons" | "external_page" | "wait";
|
|
27751
27771
|
status: "failed" | "completed" | "running" | "closed" | "ineligible" | "waiting";
|
|
27752
27772
|
stopped: boolean;
|
|
27753
27773
|
canBack: boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as ce,b as pe,d as fe}from"./chunk-GRLMT5PR.js";import"./chunk-3KQHKRZJ.js";import{Je as de,Vg as ae}from"./chunk-6A5WWFNS.js";import{a as u}from"./chunk-SOQO2RDZ.js";import{Hb as ue}from"./chunk-LMR2TM3X.js";import{a as Y}from"./chunk-DSPLGTQI.js";import"./chunk-OBYJWIRB.js";import"./chunk-WWUUVURR.js";import"./chunk-RRII2DMC.js";import"./chunk-KQCTDXVD.js";function we(e){let E=e.view;if(!E?.paywall)throw new u("INVALID_REQUEST","The current node is not a Paywall");let t=E.paywall.receiptId,R=E.nodeId,h=E.visit,o=E.paywall.resolution,k=o,s="document"in o?o:null;function g(i){if(!ce(i,o))throw new u("INVALID_RESPONSE","The pinned Paywall binding changed")}let a=E.paywall.quote,D=E.paywall.operation,S=!1,q=new AbortController,l=E.paywall.purchaseRequestId,r=0,f=E.paywall.selectionGeneration??0,P=E.paywall.canReselect===!0,m=null,N=new Map,$=new Map;function G(i){if(i.purchase&&i.purchase.receiptId!==t)throw new u("INVALID_RESPONSE","Purchase receipt changed");let c=i.run.paywall;return i.purchase??(c?.receiptId===t?c:null)}function F(){if(S)throw new u("IDENTITY_CHANGED","Paywall presentation has closed")}function O(i,c,y){if(F(),c!==r||y!==void 0&&a?.operationId!==y)return!1;let v=f,p=i.run.paywall;if(p?.receiptId===t){if((p.selectionGeneration??0)<f)return!1;f=p.selectionGeneration??0,P=p.canReselect===!0,g(p.resolution)}let w=G(i),d=f>v,L=d?w?.quote??null:w?.quote??a,A=w?.operation??(L?.operationId===a?.operationId?D:null);return L&&A&&pe(A,{operationId:L.operationId},"Purchase operation changed"),p?.receiptId===t&&(k=p.resolution,s="document"in k?k:s?{...k,document:s.document,offering:s.offering}:null),(d||L?.operationId!==a?.operationId)&&(r++,p?.receiptId===t&&(l=p.purchaseRequestId)),a=L,D=fe(D,A,!0),!0}function T(i,c,y){return new Promise((v,p)=>{let w=!1,d=()=>{clearTimeout(j),q.signal.removeEventListener("abort",Q)},L=b=>{w||(w=!0,d(),v(b))},A=b=>{w||(w=!0,d(),p(b))},Q=()=>A(new u("IDENTITY_CHANGED","Paywall presentation has closed")),j=setTimeout(()=>A(new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,y)),Math.max(0,c-Date.now()));q.signal.addEventListener("abort",Q,{once:!0}),q.signal.aborted&&Q(),i.then(L,A)})}function X(i){return new Promise(c=>{let y=()=>{clearTimeout(v),q.signal.removeEventListener("abort",y),c()},v=setTimeout(y,i);q.signal.addEventListener("abort",y,{once:!0}),q.signal.aborted&&y()})}async function J(i,c,y){F();let v=N.get(i);if(!v){let d=e.pendingCommands?.find(L=>L.requestId===i)??e.pendingCommand;if(d?.operation==="submit"&&d.requestId===i&&d.nodeId===R&&d.visit===h){c.type==="paywall_quote"&&d.input.type==="paywall_quote"&&d.input.predecessor&&!c.predecessor&&(c={...c,predecessor:d.input.predecessor});let L=ae.parse(d),A=ae.parse({...d,input:c});if(A.operation!=="submit"||L.operation!=="submit"||JSON.stringify(A.input)!==JSON.stringify(L.input))throw new u("CONFLICT","A restored purchase request cannot change its input");c=A.input,v=L,N.set(i,v)}}if(v){if(JSON.stringify(v.input)!==JSON.stringify(c))throw new u("CONFLICT","A purchase request cannot change its input")}else{let d=e.view;if(!d||d.nodeId!==R||d.visit!==h||d.paywall?.receiptId!==t)throw new u("PRECONDITION_FAILED","The Paywall visit has changed");v={operation:"submit",requestId:i,nodeId:R,visit:h,revision:d.revision,input:c},N.set(i,v)}let p=Date.now()+3e4,w=await T(e.submit(v),p,i);for(;w.run.pendingRequest?.requestId===i&&Date.now()<p&&!S&&(await X(Math.min(1e3,p-Date.now())),!(S||Date.now()>=p));)w=await T(e.resume(i),p,i);if(S)throw new u("IDENTITY_CHANGED","Paywall presentation has closed");if(w.run.pendingRequest?.requestId===i)throw new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,i);if(!O(w,y,c.type==="paywall_confirm"||c.type==="paywall_cancel"?c.operationId:void 0))throw new u("PRECONDITION_FAILED","The purchase selection has changed")}async function _(i){if(!a)throw new u("INVALID_REQUEST","A quoted purchase is required");let c=`${i}:${a.operationId}`,y=$.get(c);if(!y){let v=i==="confirm"?"paywall_confirm":"paywall_cancel",p=e.pendingCommands?.find(w=>w.operation==="submit"&&w.input.type===v&&"operationId"in w.input&&w.input.operationId===a.operationId)??e.pendingCommand;y=p?.operation==="submit"&&p.input.type===v&&"operationId"in p.input&&p.input.operationId===a.operationId?p.requestId:crypto.randomUUID(),$.set(c,y)}if(await J(y,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:a.operationId},r),!D)throw new u("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(D)}return{get view(){return structuredClone(s)},get quote(){return a?structuredClone(a):null},get operation(){return D?structuredClone(D):null},get webViewUrl(){return e.webViewUrl},get canReselect(){return P},async refresh(){F();let i=r,c=await e.get();if(O(c,i),c.run.paywall?.receiptId!==t)throw new u("PRECONDITION_FAILED","Paywall presentation has changed");if(!s){if("document"in k||!e.resolvePaywall)throw new u("INVALID_RESPONSE","Public Paywall reader is unavailable");let y=await e.resolvePaywall(k);F(),g(y),s={...k,document:y.document,offering:y.offering}}return structuredClone(s)},preview(i){if(!s)return Promise.reject(new u("PRECONDITION_FAILED","Load the Paywall presentation first"));if(l&&l!==i.requestId&&(m||!P))return Promise.reject(new u("COMMAND_PENDING","Retry the original purchase before starting another"));if(l===i.requestId&&m)return m;let c=s.document.buttons[i.actionId],y=c?.type==="checkout"?de(c.product,i.selection,s.capabilities):null;if(!y)return Promise.reject(new u("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let v=l!==i.requestId&&f>0?{operationId:a?.operationId??null,generation:f}:void 0;if(v&&(!P||f<=0))return Promise.reject(new u("COMMAND_PENDING","Original purchase requires authoritative termination"));l!==i.requestId&&r++;let p=r;l=i.requestId;let w=(async()=>{if(await J(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:y,...v?{predecessor:v}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}},p),!a)throw new u("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(a)})();return m=w,w.then(()=>{m===w&&(m=null)},d=>{m===w&&(m=null),l===i.requestId&&e.pendingCommand?.requestId!==i.requestId&&d instanceof u&&d.status!==void 0&&d.status<500&&![401,425].includes(d.status)&&(l=null)}),w},confirm:()=>_("confirm"),cancel:()=>_("cancel"),async read(){if(F(),!a)throw new u("INVALID_REQUEST","A quoted purchase is required");let i=a.operationId,c=r,y=e.pendingCommands?.find(d=>d.operation==="submit"&&(d.input.type==="paywall_confirm"||d.input.type==="paywall_cancel")&&d.input.operationId===i)??e.pendingCommand;y?.operation==="submit"&&(y.input.type==="paywall_confirm"||y.input.type==="paywall_cancel")&&y.input.operationId===i&&await e.settle?.(y.requestId);let v=await e.get(void 0,{receiptId:t,operationId:i});F();let p=G(v);if(p?.quote&&p.quote.operationId!==i||p?.operation&&p.operation.operationId!==i)throw new u("INVALID_RESPONSE","Purchase operation changed");let w=O(v,c,i)?D:p?.operation;if(!w)throw new u("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(w)},destroy(){S=!0,q.abort(),N.clear(),$.clear()}}}function me(e){let E=new Set,t=new Set,R=null;function h(o){if(e.reviewing||E.has(o)||t.has(o)||e.stopped)return;t.add(o);let k=async()=>{if(e.reviewing||e.stopped||e.key!==o){t.delete(o);return}if(e.busy||e.client.pendingCommand){setTimeout(()=>{k()},250);return}let s=(async()=>{let a=e.client.view,D=e.expected(),S=D.requestId,q=!1;try{await e.client.submit({operation:"shown",...D})}catch(l){if(!(l instanceof u)||l.code!=="CONFLICT"||l.status!==409||e.client.pendingCommand)throw l;await e.client.get();let r=e.client.view;if(e.stopped||e.reviewing||e.key!==o||!r||!a||r.id!==a.id||r.source.versionId!==a.source.versionId||r.nodeId!==D.nodeId||r.visit!==D.visit||r.revision<=D.revision||r.stopped||!r.screen||!["running","waiting"].includes(r.status)||e.client.pendingCommand)throw l;let f=e.expected();S=f.requestId,await e.client.submit({operation:"shown",...f})}for(;!e.stopped&&e.key===o&&e.client.pendingCommand?.requestId===S;){if(!e.client.settle)throw new u("COMMAND_PENDING","The original display acknowledgement is still pending");await e.client.settle(S),q=!0,e.client.pendingCommand?.requestId===S&&await new Promise(l=>setTimeout(l,1500))}e.stopped||e.key!==o||(q&&await e.client.get(),!(e.stopped||e.key!==o)&&E.add(o))})();R=s;let g=()=>{R===s&&(R=null),t.delete(o)};s.then(g,a=>{g(),e.busy||e.fail(a)})};k()}return{report:h,get inFlight(){return R}}}function ye(e){let E={},t=new Map;async function R(h){let o=e.client.view,k=o?.screen,s=k?.customerData.nodes[h.nodeId];if(e.stopped||e.busy||!o||!k||!s)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(h.action)){let r=e.document,f=r?ue(r,h.nodeId):null,P=f?.type==="customer_data"?f.data.outputs?.[h.action]:void 0;P&&k.outputs.includes(P)?await e.perform(()=>e.client.submit({operation:"submit",...e.expected(),input:{type:"screen",output:P,answers:e.answers,selection:h.value?{[h.nodeId]:h.value}:{}}})):await e.onIntent?.(h,o);return}let a=h.action.startsWith("sources_")?s.resources.find(r=>r.key===h.value):null;if(h.action.startsWith("sources_")&&!a)throw new u("INVALID_REQUEST","Choose a current resource");let D=`${o.visit}:${h.nodeId}:${a?.key??""}`,S=t.get(D)??[null],l=E[h.nodeId]??{page:1,after:null,filter:"all",...a?{resourceKey:a.key}:{}};if(h.action==="filter"){let r=h.value;if(!r||!(s.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(r))throw new u("INVALID_REQUEST","Unknown data filter");l={page:1,after:null,filter:r},S.splice(0,S.length,null)}else if(h.action==="next"||h.action==="sources_next"){let r=a?.sources.at(-1),f=a?r?{kind:"ledger",cursor:{at:r.detail[0],id:r.id,type:"source"}}:null:k.dataCursors[h.nodeId];if(!f||!a&&!s.hasNext)return;S[l.page]=f,l={...l,page:l.page+1,after:f}}else if(h.action==="previous"||h.action==="sources_previous"){if(l.page<=1)return;l={...l,page:l.page-1,after:S[l.page-2]??null}}t.set(D,S),E={...E,[h.nodeId]:l},await e.perform(()=>e.client.get({nodeId:o.nodeId,visit:o.visit,revision:o.revision,components:E}))}return{get queries(){return E},intent:R,reset(){E={},t.clear()}}}function he(e){let{doc:E,holder:t,reviewHolder:R,mountScreenPreview:h}=e,o=!1,k,s=0,g=null,a="",D=new Map,S=r=>r?`${r.id}:${r.nodeId}:${r.visit}:${r.revision}:${r.paywall?.quote?.operationId??""}`:"";async function q(r){if(e.stopped||!e.client.review)return;o||(a=S(e.client.view),D.set(a,structuredClone(e.answers))),o=!0,k=r,t.hidden=!0,e.suspend(!0),R.hidden=!1;let f=++s;try{let P=await e.client.review(r);if(e.stopped||f!==s||!o)return;if(!P.review)throw new u("INVALID_RESPONSE","Historical projection is missing");g?.destroy(),g=null,R.replaceChildren();let m=P.run.locale.startsWith("zh"),N=E.createElement("p");N.textContent=m?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",R.append(N);for(let[F,O]of P.review.pages.entries()){let T=E.createElement("button");T.type="button",T.textContent=m?`\u7B2C ${F+1} \u9875`:`Page ${F+1}`,T.onclick=()=>{q(O.receiptId)},R.append(T)}if(P.review.page){let F=P.review.page,O=E.createElement("div");if(O.inert=!0,R.append(O),g=h(O,{mode:"live",rendererUrl:e.client.webViewUrl,title:F.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{l()}}),g.update(F.document,P.run.locale,{serverInput:{bindings:F.inputs,answers:F.answers,values:F.values}}),await g.ready,e.stopped||f!==s||!o)return}let $=m?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},G=m?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let F of[...P.review.coupons.map((O,T)=>`${m?"\u4F18\u60E0\u5238":"Coupon"} ${T+1}: ${$[O.status]}`),...P.review.purchases.map((O,T)=>`${m?"\u8D2D\u4E70":"Purchase"} ${T+1}: ${G[O.status]}`)]){let O=E.createElement("p");O.textContent=F,R.append(O)}e.client.view&&await e.enqueue(e.client.view)}catch(P){if(f!==s||e.stopped)return;g?.destroy(),g=null,R.replaceChildren(),e.fail(P)}}async function l(){if(!o||e.stopped||!e.client.review)return;let r=++s;try{if(await e.client.review(),e.stopped||r!==s)return;o=!1,s++,g?.destroy(),g=null,R.replaceChildren(),R.hidden=!0,t.hidden=!1;let f=e.client.view;S(f)!==a?(D.set(a,structuredClone(e.answers)),e.resetScreen()):(D.delete(a),e.suspend(!1)),f&&await e.enqueue(f)}catch(f){if(r!==s||e.stopped)return;g?.destroy(),g=null,R.replaceChildren(),e.fail(f)}}return{get active(){return o},get receipt(){return k},open:q,exit:l,get drafts(){return new Map([...D].map(([r,f])=>[r,structuredClone(f)]))},stop(){o=!1,s++,g?.destroy(),g=null,R.replaceChildren(),R.hidden=!0,t.hidden=!1}}}async function Me(e,E){let t=E,{mountScreenPreview:R}=await import("./screen-renderer-DLXDQQKK.js"),{showPaywall:h}=await import("./paywall-4QT3JYD4.js"),o=e.ownerDocument,k=o.activeElement,s=o.createElement("section"),g=o.createElement("div"),a=o.createElement("div"),D=o.createElement("div"),S=o.createElement("button");D.hidden=!0,S.type="button";let q=o.createElement("p"),l=o.createElement("p"),r=o.createElement("button"),f=o.createElement("button"),P=o.createElement("button"),m=o.createElement("dialog");s.dataset.indianaFunnel="",s.setAttribute("aria-busy","false"),s.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",a.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",q.setAttribute("role","status"),l.setAttribute("role","alert"),l.hidden=!0,r.type=f.type=P.type="button",a.append(r,q,l,P,S,f),s.append(g,D,a),e.append(s);let N=null,$=null,G=null,F="",O="",T="",X="",J="",_=!1,i=0,c=!1,y="",v=null,p=Promise.resolve(),w=null,d=null,L=new Set,A={},Q=(n,I=null)=>{_||(d=I,l.textContent=n instanceof Error?n.message:"Request failed",l.hidden=!1,P.hidden=t.client.pendingCommand===null,Y(t.onError,n))};function j(){let n=t.client.view;if(!n)throw new u("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision}}let b=he({client:t.client,doc:o,holder:g,reviewHolder:D,mountScreenPreview:R,get stopped(){return _},get answers(){return A},suspend(n){$?.setSuspended(n)},resetScreen(){F="",O="",T=""},enqueue:B,fail:Q}),x=me({client:t.client,expected:j,fail:Q,get stopped(){return _},get reviewing(){return b.active},get key(){return F},get busy(){return i}}),K=ye({client:t.client,expected:j,perform:z,onIntent:t.onCustomerDataIntent,get stopped(){return _},get busy(){return i},get document(){return N?.document},get answers(){return A}}),re=n=>n&&(n.screen||n.paywall)?`${n.id}:${n.nodeId}:${n.visit}`:"";function Z(){let n=t.client.view;r.disabled=!b.active&&(i>0||!!t.client.pendingCommand||!n?.canBack||n.stopped||!["running","waiting"].includes(n.status)||!re(n)||O!==re(n))}async function z(n,I=!1){if(!(i&&!I||_||b.active&&!I)){i++,s.setAttribute("aria-busy","true"),Z(),l.hidden=!0,d=null;try{if(!I&&x.inFlight){let C=t.client.view;await x.inFlight;let V=t.client.view;if(!C||!V||V.id!==C.id||V.nodeId!==C.nodeId||V.visit!==C.visit||V.stopped||!["running","waiting"].includes(V.status))throw new u("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(_)return;let H=await n();_||await B(t.client.view??H.run)}catch(H){Q(H,t.client.pendingCommand?.requestId??null)}finally{i=Math.max(0,i-1),s.setAttribute("aria-busy",String(i>0)),_||(P.hidden=t.client.pendingCommand===null,Z())}}}function ee(){v&&clearTimeout(v),!(_||!G||!["running","waiting"].includes(G.status)&&!t.client.pendingCommand)&&(v=setTimeout(()=>{v=null,le().finally(ee)},G.pendingRequest||t.client.pendingCommand?1500:5e3))}async function le(){if(!(_||c||i)){if(b.active){await b.open(b.receipt);return}c=!0;try{let n=t.client.pendingCommand;n&&t.client.settle&&await t.client.settle(n.requestId);let I=t.client.view,H=K.queries,C=await t.client.get(I?.screen&&Object.keys(H).length?{nodeId:I.nodeId,visit:I.visit,revision:I.revision,components:H}:void 0);!_&&H===K.queries&&await B(t.client.view??C.run)}catch(n){Q(n)}finally{c=!1}}}function ve(n){let I=n.screen?.presentation;if(!I||I.type==="inline"){m.open&&m.close(),s.parentElement!==e&&e.append(s);return}s.parentElement!==m&&(m.append(s),e.append(m));let H={sm:420,md:640,lg:900};m.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in I?H[I.size]+"px":"100vw"}`,m.setAttribute("aria-label",N?.document?.name??n.screen?.content.document.name??"Funnel"),m.open||m.showModal()}async function ge(n){if(_)return;G=n,d&&t.client.pendingCommand?.requestId!==d&&(l.hidden=!0,d=null);let I=n.locale.startsWith("zh");if(S.textContent=I?"\u56DE\u770B":"History",S.hidden=!t.client.review,r.textContent=b.active?I?"\u8FD4\u56DE\u5F53\u524D":"Return to current":I?"\u8FD4\u56DE":"Back",f.textContent=I?"\u5173\u95ED":"Close",P.textContent=I?"\u91CD\u8BD5":"Retry",Z(),P.hidden=t.client.pendingCommand===null,q.textContent=n.pendingRequest?I?"\u6B63\u5728\u5904\u7406":"Processing":n.instruction?.type==="wait"?I?"\u7B49\u5F85\u4E2D":"Waiting":"",y!==`${n.revision}:${n.visit}:${n.status}:${n.stopped}`&&(y=`${n.revision}:${n.visit}:${n.status}:${n.stopped}`,Y(t.onState,structuredClone(n))),n.stopped||t.client.configurationReady===!1){b.stop(),N?.destroy(),N=null,$?.destroy(),$=null,g.replaceChildren(),F="",O="",T="",J="",m.open&&m.close(),s.hidden=!0,ee();return}if(s.hidden=!1,b.active){ee();return}let H=re(n);if(H!==F&&(O="",N?.destroy(),N=null,$?.destroy(),$=null,g.replaceChildren(),F=H,T="",J="",A={...n.answers},K.reset()),ve(n),n.screen){let V=n.screen.content;N||(N=R(g,{mode:"live",rendererUrl:t.client.webViewUrl,title:V.document.name,onAction(M,oe={},se={}){if(b.active)return;A={...A,...se};let Ee=Object.fromEntries((n.screen?.inputs??[]).filter(({variable:ie})=>Object.hasOwn(A,ie)).map(({variable:ie})=>[ie,A[ie]]));z(()=>t.client.submit({operation:"submit",...j(),input:{type:"screen",output:M,answers:Ee,selection:oe}}))},onAnswers:M=>{b.active||(A={...A,...M})},onCustomerDataIntent:M=>{b.active||K.intent(M).catch(Q)},onEscape:()=>{b.active||ne()},onError:M=>Q(new Error(M)),onRendered:()=>x.report(H)}));let U={capabilities:n.screen.capabilities,customerData:n.screen.customerData,parameters:n.parameters,serverInput:{bindings:n.screen.inputs,answers:A,values:n.screen.values}},W=JSON.stringify([V,n.locale,U.parameters,n.screen.inputs,n.screen.values]);if(W!==T)N.update(V.document,n.locale,U),T=W,X=JSON.stringify(U.capabilities),J=JSON.stringify(U.customerData);else{let M=JSON.stringify(U.capabilities);M!==X&&(N.updateCapabilities(U.capabilities),X=M),JSON.stringify(U.customerData)!==J&&(N.updateCustomerData(U.customerData),J=JSON.stringify(U.customerData))}await N.ready}else if(n.paywall&&!$){let V=await h(g,{canInteract:()=>!b.active&&!_,start:async()=>we(t.client),onPurchase:t.onPurchase,onCheckoutUrl:t.onCheckoutUrl,resolveOfferId:t.resolveOfferId,onEvent:t.onEvent,onOpenUrl:U=>t.onOpenUrl?t.onOpenUrl({receiptId:n.paywall.receiptId,url:U,openIn:"same_window"}):o.defaultView?.location.assign(U),onAction:async U=>{if(b.active)return;let W=await t.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision,input:{type:"screen",output:U,answers:{}}});await B(t.client.view??W.run)},onError:Q,onDismiss:()=>{!b.active&&!_&&t.client.view?.visit===n.visit&&ne()}});_?V.host?.destroy():($=V.host,$?.setSuspended(b.active)),x.report(H)}if(_)return;O=H,Z();let C=n.instruction;if(C&&(C.type==="open_url"||C.type==="event")&&!L.has(C.receiptId)){let V=o.createElement("button");V.type="button",V.textContent=C.type==="open_url"?`${I?"\u524D\u5F80":"Continue to"} ${new URL(C.url).host}`:I?"\u7EE7\u7EED":"Continue",V.onclick=()=>{let U=j(),W=C.type==="open_url"&&!t.onOpenUrl&&C.openIn==="new_window"?Ie(C.url):null;z(async()=>{let M="success";if(C.type==="open_url")if(t.onOpenUrl)try{M=await t.onOpenUrl({receiptId:C.receiptId,url:C.url,openIn:C.openIn})===!1?"failed":"opened"}catch(se){Y(t.onError,se),M="failed"}else M=C.openIn==="new_window"&&!W?"failed":"opened";if(C.type==="event"){if(!t.onEvent)throw new u("EVENT_HANDLER_REQUIRED","Provide the event handler");await t.onEvent(C.event)}if(_||t.client.view?.nodeId!==U.nodeId||t.client.view.visit!==U.visit)throw new u("PRECONDITION_FAILED","The client action visit changed");let oe=await t.client.submit({operation:"submit",...U,input:{type:"client_action",receiptId:C.receiptId,outcome:M}});return L.add(C.receiptId),C.type==="open_url"&&!t.onOpenUrl&&C.openIn==="same_window"&&o.defaultView?.location.assign(C.url),oe})},g.replaceChildren(V)}!n.pendingRequest&&n.status==="completed"&&!L.has(`complete:${n.id}`)&&(L.add(`complete:${n.id}`),Y(t.onComplete,structuredClone(n))),ee()}function Ie(n){let I=o.defaultView?.open(n,"_blank")??null;return I&&(I.opener=null),I}function B(n){return Z(),p=p.catch(()=>{}).then(()=>ge(n)),p}let be=t.client.subscribe(n=>{t.client.configurationReady===!1&&(s.hidden=!0,N?.destroy(),N=null,$?.destroy(),$=null,g.replaceChildren(),F="",O="",T="",J="",m.open&&m.close()),B(n).catch(Q)}),Ce=t.client.subscribeError?.(Q);function ne(){return w||(_?Promise.resolve():t.client.view&&!["running","waiting"].includes(t.client.view.status)?(te(),Promise.resolve()):(w=z(()=>t.client.submit({operation:"close",...j()}),!0).then(()=>{t.client.view?.status==="closed"&&te()}).finally(()=>{w=null}),w))}function te(){_||(_=!0,v&&clearTimeout(v),be(),Ce?.(),N?.destroy(),b.stop(),$?.destroy(),m.close(),m.remove(),s.remove(),k instanceof HTMLElement&&k.isConnected&&k.focus(),Y(t.onDismiss,G?structuredClone(G):null))}r.onclick=()=>{if(!r.disabled){if(b.active){b.exit();return}z(()=>t.client.submit({operation:"back",...j()}))}},S.onclick=()=>{b.open()},f.onclick=()=>{ne()},P.onclick=()=>{z(()=>t.client.retry())},m.addEventListener("cancel",n=>{n.preventDefault(),ne()});try{let n=await t.client.get();await B(t.client.view??n.run)}catch(n){throw te(),n}return{destroy:te,refresh:le,review:b.open,exitReview:b.exit,get unappliedDrafts(){return b.drafts}}}export{Me as showFunnelRun};
|