@tinkerlandai/longplay-sdk 0.10.21-rc.1 → 0.10.21-rc.2

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 CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## 0.10.21 — 2026-11-07
4
4
 
5
+ - Reopen a Funnel on the first click after its Paywall closes. The Paywall dialog stays open until the Run confirms Close, then the host removes it, restores focus and calls `onDismiss` in the same handoff, so an entry, including the SDK IAM button, no longer ignores a click made while the old Run was still closing. If Close cannot be confirmed, the same dialog retries the original Close with its `requestId`, and repeated Close clicks are merged. A purchase left on the closed Run remains recoverable by its original `operationId`.
5
6
  - Show a placeholder until the first screen has rendered. A Paywall, a Funnel screen and a Page, Popup or Banner display a local skeleton from the moment they open, and keep it through the frame handshake until the screen reports that it has rendered. Pass `loading: "host"` to keep your own placeholder and follow `onPresentationState`: `loading` carries `dismiss()`, then `ready`, `dismissed`, `skipped` or `error` ends it. Pass `signal` to cancel while data is pending; a reply that arrives after a Close, timeout, Customer change or node change no longer reopens the old view.
6
7
  - Funnels reach their first screen sooner. `showFunnelRun` renders the Run the start reply already carries instead of reading it again, and `createFunnelRunController` accepts an optional `initialResponse` so a merchant backend can forward its start reply. With the current runtime a Local Funnel enters in one request.
7
8
  - Fewer repeated reads. A Funnel Paywall reuses the presentation delivered with the Run and refreshes only its personal capabilities, identical concurrent reads share one request, and idle presentation and public configuration polls pause while the page is hidden. A pending purchase keeps a slower bounded read.
package/README.md CHANGED
@@ -184,6 +184,8 @@ In a browser, use `createFunnelRunController` and `showFunnelRun`. The controlle
184
184
 
185
185
  `showFunnelRun` renders a Run its controller already holds straight away, and with none it reads the Run first. `createFunnelClient().start()` and `createLocalFunnelClient().start()` return a controller holding the Run, so the first screen needs no read. After a start on your backend, forward its reply and pass it as `initialResponse` to `createFunnelRunController` to get the same result. Pass only the reply your backend just received. Leave it out after a reload, so the controller reads the current Run.
186
186
 
187
+ When a customer dismisses a Funnel Paywall, the Web host keeps the dialog open until the Run closes. If Close cannot be confirmed, the same dialog offers a retry of the original pending Close. The host removes the dialog, restores focus, and calls `onDismiss` in the same handoff; an entry can open a new Run on the next click. An unresolved purchase remains recoverable on the original Run with its original operation ID.
188
+
187
189
  Each Funnel chooses local or remote evaluation. `createFunnelDecisionClient` supports `configuration()`, `features()`, submission, and result reads. `createFeatureClient` identifies configuration by `generation`. Downloaded local rules are visible to clients; use remote evaluation and verified business facts for sensitive decisions.
188
190
 
189
191
  ### Guest entry and same-Run login
package/README.zh-CN.md CHANGED
@@ -196,6 +196,8 @@ Web 宿主可以用独立的第一方安装 cookie 保留信号。清除 cookie
196
196
 
197
197
  `showFunnelRun` 在控制器已有 Run 时立即渲染,没有时先读取。`createFunnelClient().start()` 和 `createLocalFunnelClient().start()` 返回的控制器已经带着 Run,首屏不用再读一次。如果 Funnel 由你的后端启动,把启动响应转给浏览器,作为 `initialResponse` 传给 `createFunnelRunController`,效果相同。只传后端刚收到的响应。页面重新加载后不要传,让控制器读取当前 Run。
198
198
 
199
+ 顾客关闭 Funnel Paywall 时,Web 宿主会保留原弹窗,直到 Run 确认关闭。关闭结果未确认时,可在原弹窗内重试同一条待确认的 Close。宿主在同一次交接中移除弹窗、归还焦点并调用 `onDismiss`,下一次点击入口即可打开新 Run。未结算的购买仍可在原 Run 上按原操作 ID 恢复。
200
+
199
201
  Local/Remote 求值策略由每个 Funnel 决定。`createFunnelDecisionClient` 支持当前 `configuration()`、`features()`、提交和结果读取;`createFeatureClient` 以 `generation` 标识配置。Local 下载的规则对客户端可见;敏感决策应使用 Remote 和可信业务事实。
200
202
 
201
203
  ### 独立消费方的分桶身份
@@ -1 +1 @@
1
- import{lb as d}from"./chunk-ZDLY6GPF.js";import{a as u}from"./chunk-DSPLGTQI.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.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 y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){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 o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
1
+ import{lb as d}from"./chunk-ZC6PDVLR.js";import{a as u}from"./chunk-DSPLGTQI.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.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 y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){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 o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
@@ -1 +1 @@
1
- import{b as mn,c as pn,d as gn,e as yn,f as wn}from"./chunk-YAVWELIV.js";import{a as ae,b as ee}from"./chunk-SZJDNCKU.js";import{a as l}from"./chunk-QVGTHPWT.js";import{a as dn,b as fn,c as Pe}from"./chunk-7P7KRVLI.js";import{$ as Se,Da as ie,Ea as nn,Ha as tn,Ia as rn,Na as Te,Oa as on,Z as je,aa as Je,ab as an,ba as He,bb as sn,ca as ze,eb as un,fb as ln,ib as cn,lb as ye,ma as X,na as Qe,o as ke,oa as Y,pa as Ye,q as ge,qa as Oe,ra as j,ta as $e,ua as We,va as Ze,wa as Xe,xa as en}from"./chunk-ZDLY6GPF.js";import{a as hn}from"./chunk-DSPLGTQI.js";import{C as Ue,J as Ge,M as Be,Na as Ke,P as be,a as qe}from"./chunk-HDVLCRC6.js";function zn(e){let n=null,a=null,t=0,f=0,p=new Set,m=null,c=null,r=new Set,o=()=>{for(let i of r)try{i()}catch{}},s={attributes:be.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(i,y)=>{!p.has(i)&&n&&(!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(i,structuredClone(y),structuredClone(s.attributes),n.generation)}:void 0,onExperimentViewed:e.onExperimentViewed?(i,y)=>n&&(!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(i),structuredClone(y),structuredClone(s.attributes),n.generation):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?i=>e.saveStickyBucketAssignmentDoc(structuredClone(i)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},I=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function g(i,y=new Set){return p.has(i)?!m||!m.features[i]||["unknownFeature","cyclicPrerequisite"].includes(m.features[i].source):y.has(i)?!1:(y.add(i),(n?.features[i]?.rules??[]).some(P=>[...P.parentConditions??[],...(P.tracks??[]).flatMap(N=>N.experiment.parentConditions??[])].some(N=>g(N.id,y))))}let d=i=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return m?.expiresAt&&Date.parse(m.expiresAt)<=Date.now()&&(m=null,s.features=n.features),p.has(i)?!m||m.expiresAt&&Date.parse(m.expiresAt)<=Date.now()?I():structuredClone(m.features[i]??I()):e.evaluateRemote&&(s.attributes?.merchandise||s.attributes?.merchandiseId)&&!m||g(i)?I():structuredClone(Be(i,s))};async function S(){if(!n||!p.size&&!s.attributes?.merchandise&&!s.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(p.size)throw new Error("Remote Feature evaluation requires a server loader");return}let i=f;if(c?.revision===i)return c.loading;let y=t,P=n,N=[...p],D=(async()=>{let T=ze.parse(await e.evaluateRemote({attributes:structuredClone(s.attributes),features:N}));if(!(y!==t||i!==f||P!==n)){if(e.assertUsable?.(P.generation),T.generation!==P.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(N.some(u=>!Object.hasOwn(T.features,u))||Object.keys(T.features).some(u=>!p.has(u)))throw new Error("Invalid remote Feature results");if(s.attributes?.merchandise||s.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");s.attributes=be.parse({...s.attributes,...T.merchandiseContext})}m=structuredClone(T),s.features={...P.features,...Object.fromEntries(Object.entries(m.features).map(([u,b])=>[u,{defaultValue:b.value}]))},o()}})();c={revision:i,loading:D};try{await D}finally{c?.loading===D&&(c=null)}}function _(){S().catch(i=>{try{e.onError?.(i)}catch{}})}async function q(){if(a)return a;let i=t,y=(async()=>{let P=await e.load(),N="remoteFeatures"in P?Je.parse(P):null,D=N??Se.parse(P);if(D.scope.projectId!==e.scope.projectId||D.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(i!==t)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===D.generation){let{evaluatedAt:u,expiresAt:b,...L}=n,{evaluatedAt:v,expiresAt:O,...E}=D;if(j(L)!==j(E))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=D.evaluatedAt,n.expiresAt=D.expiresAt,o(),(!m||m.expiresAt&&Date.parse(m.expiresAt)<=Date.now())&&_(),structuredClone(n)}let T=new Set(N?.remoteFeatures??[]);if([...T].some(u=>Object.hasOwn(D.features,u)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in D&&!n.analyticsConfig.experimentViewsEnabled&&N?.analyticsConfig.experimentViewsEnabled&&s.trackedExperiments?.clear(),n=structuredClone(D),p=T,m=null,c=null,f++,s.features=n.features,s.savedGroups=Ge(n.savedGroups),s.trackedFeatureUsage={},o(),_(),structuredClone(n)})();a=y;try{return await y}finally{a===y&&(a=null)}}return{init:q,refresh:q,refreshRemote:S,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(i){return r.add(i),()=>{r.delete(i)}},setAttributes(i){let y=be.parse(i);(s.attributes?.merchandise||s.attributes?.merchandiseId||i.merchandise||i.merchandiseId)&&s.trackedExperiments?.clear(),s.attributes=y,f++,m=null,c=null,s.features=n?.features??{},s.trackedFeatureUsage={},o(),_()},evalFeature:d,isOn(i){return d(i).on},isOff(i){return d(i).off},getFeatureValue(i,y){let P=d(i).value;return structuredClone(P===null?y:P)},reset(){t++,f++,a=null,c=null,n=null,m=null,p.clear(),s.features={},s.savedGroups={},s.stickyBucketAssignmentDocs={},s.attributes={},s.trackedFeatureUsage={},s.trackedExperiments?.clear(),o()}}}function In(e){let n,a,t=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),f=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,a=e.locks??globalThis.navigator?.locks,!n||!a||!globalThis.crypto?.subtle)throw t();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ye).href,e.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return"indiana.funnel.commands.v1."+Array.from(r,o=>o.toString(16).padStart(2,"0")).join("")});f.catch(()=>{});async function p(c){try{let r=await f;return await a.request(r,{mode:"exclusive"},()=>c(r))}catch(r){throw r instanceof l?r:t()}}function m(c){let r=n.getItem(c);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw t();let o=JSON.parse(r);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw t();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(m),write:(c,r)=>p(o=>{if(m(o).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw t();return n.setItem(o,JSON.stringify({revision:c+1,entry:r})),c+1})}}function Ee(e,n){let a=tn.safeParse(n);if(!a.success)throw new l("INVALID_RESPONSE","Funnel response contract changed");let t=a.data;if(e.scope&&(t.scope.projectId!==e.scope.projectId||t.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Funnel scope changed");return t}async function Ae(e,n){let a=Xe.parse(n),{artifact:t,environmentId:f}=a.content,p=new ae(e.baseUrl??ye).origin,m=new ae(t.url,p);if(m.origin!==p||m.username||m.password||m.search||m.hash||m.pathname!==`/api/v1/configuration/${f}/artifacts/${t.sha256}`)throw new l("INVALID_RESPONSE","Public Paywall locator is not trusted");let c=new AbortController,r,o=new Promise((I,g)=>{r=setTimeout(()=>{let d=new l("TIMEOUT","Public Paywall read timed out");c.abort(d),g(d)},Y.initializationMs)}),s=(async()=>{let I=await(e.fetch??globalThis.fetch)(m,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:c.signal});if(c.signal.aborted&&(I.body?.cancel().catch(()=>{}),c.signal.throwIfAborted()),!I.ok||!I.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(I.headers.get("content-length"))>t.byteLength)throw I.body?.cancel().catch(()=>{}),new l("INVALID_RESPONSE","Public Paywall is unavailable");let g=await dn(I,t.byteLength,{signal:c.signal,error:d=>new l("INVALID_RESPONSE",d==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Pe(g,t))throw new l("INVALID_RESPONSE","Public Paywall digest or size changed");return en(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(g)))})();try{return await Promise.race([s,o])}finally{clearTimeout(r)}}var _e=(e,n)=>new l(e,n);function ut(e){return ln(e,_e)}var _n=3,Dn=2e3;function Ln(e){return e instanceof TypeError||e instanceof l&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function xn(e){for(let n=1;;n++)try{return await e.refresh()}catch(a){if(n===_n||!Ln(a))throw a;await new Promise(t=>setTimeout(t,n*Dn))}}async function De(e,n,{predict:a=!0}={}){let t=n.instruction;if(t?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==t.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let f=null,p;if(a)try{let m=await e.funnel(n.source.id,n.source.versionId);p=m.manifest.generation,f=Mn(e,n,m)}catch{f=null}return p??=e.snapshot?.generation??(await xn(e)).generation,{advance:{policyRevision:t.policyRevision,generation:p},prediction:f}}function Mn(e,n,a){let t=n.instruction;if(t?.type!=="evaluate_segment"||!a.growth||a.control.evaluationMode!=="local"||a.control.evaluationRevision!==t.policyRevision)return null;let{analyticsConfig:f,remoteFeatures:p,...m}=a.growth,c=an({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:t.policyRevision,document:a.document,payload:Se.parse(m)}),r=Vn(c,a.document,{...n,...t}),o=r.steps.at(-1),s=r.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:n.visit+r.steps.length-1}:null);return s?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:s.nodeId,visit:s.visit,terminal:!r.boundary}:null}function Vn(e,n,a){return cn(e,n,a,_e)}import{z as $}from"zod";var vn=X.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Rn=$.strictObject({schemaVersion:$.literal(1),scope:qe,runId:$.uuid(),funnelId:$.uuid(),versionId:$.uuid(),processBindingIds:$.record($.uuid(),$.uuid().nullable()).optional(),command:vn.optional(),closeCommand:vn.refine(e=>e.operation==="close").optional(),purchase:$.strictObject({receiptId:$.uuid(),operationId:$.uuid(),generation:$.number().int().nonnegative()}).optional(),closed:$.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),z=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Fe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function Cn(e){let n=0,a=null,t=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),f=Promise.resolve();async function p(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:Rn.parse(o.entry)}}function m(o){let s=f.then(o);return f=s.catch(()=>{}),s}async function c(o){for(let s=0;s<4;s++){let I=await p();if(I.entry&&a!==null&&t(I.entry)!==a)throw z();let g=o(I.entry,I.revision);if(Fe(I.entry,g)){n=I.revision;return}let d=await e.write(I.revision,g);if(d!==null){if(!Number.isSafeInteger(d)||d<=I.revision)throw z();n=d;return}}throw z()}function r(o,s){if(!o||!s)return o;if(o.processBindingIds&&Object.hasOwn(o.processBindingIds,s)){let I={...o.processBindingIds};delete I[s],o={...o,processBindingIds:I}}return o.command?.requestId===s?o.closeCommand?{...o,command:o.closeCommand,closeCommand:void 0}:o.purchase?{...o,command:void 0}:null:o.closeCommand?.requestId===s?{...o,closeCommand:void 0}:o}return{bind(o){let s=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(a!==null&&a!==s)throw z();a=s},async load(){let o=await p();return n=o.revision,a=o.entry?t(o.entry):null,o.entry},retain(o){let s=Rn.parse(o),I=s.command;return!I||a!==null&&t(s)!==a?Promise.reject(z()):(a??=t(s),m(()=>c((g,d)=>{if(g&&!Fe(t(g),t(s)))throw z();if(g&&s.processBindingIds){for(let[S,_]of Object.entries(s.processBindingIds))if(g.processBindingIds&&Object.hasOwn(g.processBindingIds,S)&&g.processBindingIds[S]!==_)throw z();g={...g,processBindingIds:{...g.processBindingIds,...s.processBindingIds}}}if(!g){if(d!==n&&I.operation!=="close")throw z();return s}if(!g.command)return{...g,command:I,...I.operation==="close"?{closed:!0}:{}};if(I.operation==="close"&&g.command.operation!=="close"){if(g.command.requestId===I.requestId||g.closeCommand&&!Fe(g.closeCommand,I))throw z();return{...g,closeCommand:I,closed:!0}}if(!Fe(g.command,I))throw z();return g})))},observePurchase(o,s,I,g){return m(()=>c((d,S)=>{if(!d&&S!==n||d&&t(d)!==t({...o,schemaVersion:1}))throw z();if(d?.purchase&&d.purchase.generation>s.generation)return r(d,g);if(d?.purchase&&d.purchase.generation===s.generation&&d.purchase.operationId!==s.operationId)throw z();return I?!d?.purchase||d.purchase.operationId!==s.operationId?r(d,g):r(d.command?{...d,purchase:void 0}:null,g):r({schemaVersion:1,...o,...d,purchase:s},g)}))},settle(o){return m(()=>c(s=>r(s,o)))}}}function ht(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function we(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((f,p)=>we(f,n[p]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let a=Object.entries(e),t=Object.entries(n);return a.length===t.length&&a.every(([f,p])=>Object.hasOwn(n,f)&&we(p,Reflect.get(n,f)))}function bn(e,n){let a=n&&{...n},t=null,f=0,p=-1,m=0,c=new AbortController;function r(){m++,c.abort(new l("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let o=!1,s,I=0,g=new Set;return{get scope(){return a},bindScope(d){if(a&&(a.projectId!==d.projectId||a.environment!==d.environment))throw new l("SCOPE_MISMATCH","Run scope changed");a??={...d}},get view(){return t},get currentView(){return p===m?t:null},get viewAgeMs(){return t&&p===m?performance.now()-f:void 0},get generation(){return m},get signal(){return c.signal},get disposed(){return o},get customerToken(){return s},get readSequence(){return I},nextRead(){return++I},assertCurrent(d,S="Run identity changed during the request"){if(d!==m||o)throw new l("IDENTITY_CHANGED",S)},assertRun(d){if(t&&(d.id!==t.id||d.source.type!==t.source.type||d.source.id!==t.source.id||d.source.versionId!==t.source.versionId||d.locale!==t.locale||!we(d.parameters,t.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e&&d.source.id!==e)throw new l("INVALID_RESPONSE","Run belongs to another Funnel")},publish(d,S,_,q,i){if(!(d.operation==="review"&&t&&t!==_&&S.run.revision<=t.revision)&&!(t&&S.run.revision===t.revision&&q!==void 0&&q<I)&&(d.operation==="review"&&!S.run.stopped&&["running","waiting"].includes(S.run.status)&&t&&p===m&&S.run.nodeId===t.nodeId&&S.run.visit===t.visit&&S.run.revision===t.revision&&(S.run.screen=t.screen,(t.paywall?.quote?.operationId===S.review?.activeOperationId||!t.paywall?.quote&&S.review?.activeOperationId===null)&&(S.run.paywall=t.paywall)),!(t?.paywall&&S.run.paywall&&t.paywall.receiptId===S.run.paywall.receiptId&&(S.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||S.run.revision>=t.revision)t=S.run,f=performance.now(),p=m;else if(!i)return;if(t&&p===m)for(let y of g)try{y(structuredClone(t))}catch{}}},identify(d){if(o)throw new l("IDENTITY_CHANGED","Controller was reset");if(!ge.test(d))throw new l("INVALID_TOKEN","Customer credential required");r(),s=d},subscribe(d){return g.add(d),()=>g.delete(d)},reset(){o||(o=!0,r(),s=void 0,t=null,g.clear())}}}var se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Pt(e,n,a="A server API key is required"){if(typeof window<"u")throw new l("SERVER_ONLY",n);if(!se.test(e))throw new l("INVALID_TOKEN",a)}function Et(e){let n=ee(e);return n.identify(e.apiKey),n}function ne(e){let{customerToken:n,...a}=e;return a}var qn=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Sn({journal:e,state:n,call:a,processIdentity:t}){let f=null,p=null,m=!1,c={command:null,close:null},r=new Set,o,s=null,I=e?e.load().then(i=>{if(n.disposed)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(s=i,!i)return;if(t){if([i.command,i.closeCommand].some(P=>P&&!Object.hasOwn(i.processBindingIds??{},P.requestId)))throw new l("COMMAND_STORAGE_INVALID","The original process identity is missing");t.restore(i.processBindingIds??{})}if(n.scope&&(i.scope.projectId!==n.scope.projectId||i.scope.environment!==n.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=i.purchase,m=i.closed===!0,!i.command)return;let y=i.command;f=y.operation==="close"?null:y,p=y.operation==="close"?y:i.closeCommand?.operation==="close"?i.closeCommand:null,p&&(m=!0);for(let P of[f,p])P&&r.add(P.requestId)}):Promise.resolve();I.catch(()=>{});async function g(i){e&&await I;let y=n.generation;if(e){if(!n.view||!n.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:ne(i),...t?{processBindingIds:{[i.requestId]:t.binding(i.requestId)}}:{}})}if(y!==n.generation||f!==i&&p!==i)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let P=r.has(i.requestId);r.add(i.requestId);try{return await a(i)}catch(N){throw y===n.generation&&(f===i||p===i)&&!P&&!qn(N)&&(e&&await e.settle(i.requestId),y===n.generation&&q(i)),N}}function d(i){let y=X.parse(i);if(y.operation==="start"||y.operation==="get"||y.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(m&&y.operation!=="close"){if(f?.requestId===y.requestId)return _(y.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(y.operation==="close"){if(f?.requestId===y.requestId)throw new l("INVALID_REQUEST","Close requires its own request identity");if(m=!0,p&&JSON.stringify(ne(p))!==JSON.stringify(ne(y)))throw new l("COMMAND_PENDING","Retry the original Close");return p??=y,c.close?c.close:S(p,"close")}if(f){if(JSON.stringify(ne(f))!==JSON.stringify(ne(y)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else f=y;return S(f,"command")}function S(i,y){let P=g(i);c[y]=P;let N=()=>{c[y]===P&&(c[y]=null)};return P.then(N,N),P}function _(i){return a({operation:"get",settlementRequestId:i})}function q(i){return!i||f!==i&&p!==i?!1:(f===i&&(f=null),p===i&&(p=null),r.delete(i.requestId),!f&&!p&&(s=null),!0)}return{ready:I,get pending(){return f},get closing(){return p},get closeRequested(){return m},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return o},assertBinding(i){if(s&&(i.run.id!==s.runId||i.run.source.id!==s.funnelId||i.run.source.versionId!==s.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(i,y,P,N){let D=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0,T=D&&y.settlement?.state==="settled"&&y.run.pendingRequest?.requestId!==D&&(i.operation==="get"||!m||i.operation==="close"||!["running","waiting"].includes(y.run.status))?D:void 0,u=f?.requestId===T?f:p?.requestId===T?p:void 0;e?.bind({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId});let b=y.run.paywall,L=b??y.purchase,v=L?.operation,O=y.settlement&&(!b||b.purchaseRequestId===y.settlement.requestId)&&(!o||o.operationId===y.settlement.operationId)?y.settlement:void 0,E=v?.operationId??L?.quote?.operationId??O?.operationId,A=L?.receiptId??O?.receiptId,U=b?.selectionGeneration??o?.generation??0;if(e&&E&&A&&i.operation!=="review"&&(!n.view||y.run.revision>=n.view.revision)&&(N===void 0||N>=n.readSequence)&&(!o||U>=o.generation)){let x={receiptId:A,operationId:E,generation:U},H=v?.status==="complete"||L?.canReselect===!0;await e.observePurchase({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId},x,H,T),n.assertCurrent(P),(!o||x.generation>=o.generation)&&(N===void 0||N>=n.readSequence)&&(H?o?.operationId===x.operationId&&(o=void 0):o=x)}else e&&T&&await e.settle(T);return n.assertCurrent(P),T?q(u):!1},stop(){m=!0},submit:d,settle:_,reset(){m=!0,f=null,p=null,o=void 0,s=null,c.close=null,r.clear(),c.command=null}}}function Pn(e){e={...e};let n=e.initialResponse;if(delete e.initialResponse,typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!se.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new l("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let a=ee({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=bn(e.funnelId,e.scope??e.configuration?.scope),f=e.session?.subscribeIdentity(d),p=null,m=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?In(e):void 0),c=m&&Cn(m),r=Sn({journal:c,state:t,call:S,processIdentity:e.process}),o=0,s=new Map;function I(){o++,s.clear(),n=void 0}async function g(u){if(e.process)return e.process.request(u);let b=t.generation;t.assertCurrent(b);let L=performance.now()+(e.timeoutMs??35e3),v=t.customerToken??("customerToken"in u?u.customerToken:void 0);if(e.session){let A=t.signal,U,x=()=>{},H=new Promise((K,G)=>{x=()=>G(A.reason),A.addEventListener("abort",x,{once:!0}),U=setTimeout(()=>G(new l("TIMEOUT","Longplay request timed out")),Math.max(1,L-performance.now()))});try{v=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(b),e.session.access())),H])}finally{clearTimeout(U),A.removeEventListener("abort",x)}}t.assertCurrent(b);let O={...u,...v?{customerToken:v}:{}},E=u.operation==="page_experiments"?Te.parse(O):X.parse(O);return a.requestWithCredential("funnels",E,e.runToken,{headers:e.serverKey&&!v?{[rn]:e.serverKey}:void 0,timeoutMs:Math.max(1,L-performance.now())})}function d(){I(),f?.(),t.reset(),r.reset(),p=null,a.dispose()}async function S(u,b){let L=n;n=void 0;let v=t.generation,O=()=>t.assertCurrent(v);c&&await r.ready,O();let E=t.view,A=Ee(e,L!==void 0&&u.operation==="get"&&!u.data&&!u.purchase&&!u.settlementRequestId?L:await g(u));if(u.operation==="review"&&!A.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(O(),A.runToken&&A.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let U=u.operation==="get"?u.settlementRequestId:"requestId"in u&&u.operation!=="start"?u.requestId:void 0;if(U&&A.settlement?.requestId!==U)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(A),t.assertRun(A.run),t.bindScope(A.scope);let x=await r.observe(u,A,v,b);return!A.run.stopped&&["running","waiting"].includes(A.run.status)&&u.operation==="get"&&u.settlementRequestId||(O(),["running","waiting"].includes(A.run.status)||r.stop(),t.publish(u,A,E,b,x)),A}function _(u){let b=t.generation;I();let L=u(),v=()=>{t.generation===b&&I()};return L.then(v,v),L}let q=u=>_(()=>r.submit(u)),i=null,y=new WeakMap;function P(u){let b=y.get(u);if(b)return b;let L=D(u);return y.set(u,L),L}let N=!1;async function D(u){let b=await u;if(b.run.instruction?.type!=="evaluate_segment")return b;if(i)return i;N=!0;let L=t.generation,v=(async()=>{for(let O=0;O<32&&b.run.instruction?.type==="evaluate_segment";O++){if(r.pending||r.closeRequested)return b;let E=b.run;if(b.run.instruction?.type==="evaluate_segment"){let{advance:U}=await De(e.configuration,E,{predict:!1});if(L!==t.generation)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return b;if(t.view&&(t.view.revision!==E.revision||t.view.visit!==E.visit||t.view.nodeId!==E.nodeId))return S({operation:"get"});let x=!0;De(e.configuration,E).then(({prediction:H})=>{x&&L===t.generation&&!r.closeRequested&&t.view?.id===E.id&&!t.view.stopped&&t.view.nodeId===E.nodeId&&t.view.visit===E.visit&&t.view.revision===E.revision&&(p=H)}).catch(()=>{});try{b=await q({operation:"commit_segment",requestId:nn(E.id,E.visit,`segment:${E.revision}`),nodeId:E.nodeId,visit:E.visit,revision:E.revision,...U})}finally{x=!1,p=null}}}return b})();i=v;try{return await v}finally{i===v&&(i=null)}}let T={get configuration(){return N?e.configuration:void 0},get configurationReady(){return!0},get view(){let u=t.currentView;return u?structuredClone(u):null},get viewAgeMs(){return t.viewAgeMs},get pendingCommand(){let u=r.closing??r.pending;return u?structuredClone(ne(u)):null},get pendingCommands(){return[r.pending,r.closing].filter(u=>u!==null).map(u=>structuredClone(ne(u)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get hasDurableJournal(){return c!==void 0},get prediction(){let u=t.view;return p&&u&&!u.stopped&&["running","waiting"].includes(u.status)&&u.id===p.runId&&u.nodeId===p.from.nodeId&&u.visit===p.from.visit&&u.revision===p.from.revision&&!r.closeRequested?structuredClone(p):null},settle:(...u)=>_(()=>r.settle(...u)),get webViewUrl(){return"bundled"},resolvePaywall(u){return Ae(e,u)},async pageExperiments(u,b=[]){let L=t.generation;t.assertCurrent(L);let v=t.view?.id;if(!v)throw new l("INVALID_REQUEST","Read the Run before its page experiments");let O=on.parse(await g(Te.parse({operation:"page_experiments",release:u,usedReceiptIds:b})));if(t.assertCurrent(L),O.runId!==v||O.scope.projectId!==t.scope?.projectId||O.scope.environment!==t.scope?.environment)throw new l("SCOPE_MISMATCH","Page experiment Run changed");return O},review(u){return S({operation:"review",...u?{receiptId:u}:{}},t.nextRead())},async get(u,b){let L=t.generation;u=u&&structuredClone(u),b=b&&{...b},c&&await r.ready,t.assertCurrent(L),b??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let v=JSON.stringify([t.generation,o,u??null,b??null]),O=s.get(v);if(O)return O.then(x=>structuredClone(x));let E=t.nextRead(),A=P(S({operation:"get",...u?{data:u}:{},...b?{purchase:b}:{}},E));s.set(v,A);let U=()=>{s.get(v)===A&&s.delete(v)};return A.then(U,U),A.then(x=>structuredClone(x))},resume(u=t.view?.pendingRequest?.requestId){return u?r.closeRequested?T.settle(u):r.pending?.requestId===u?P(q(r.pending)):P(q({operation:"resume",requestId:u})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(u){return P(q(u))},retry(){return r.closeFlight?r.closeFlight:r.closing?q(r.closing):r.closeRequested&&r.pending?T.settle(r.pending.requestId):r.inFlight?P(r.inFlight):r.pending?P(q(r.pending)):Promise.reject(new l("INVALID_REQUEST","No command is pending"))},identify(u){let b=t.customerToken?void 0:n;I(),t.identify(u),n=b,p=null,a.reset()},get identitySignal(){return t.signal},subscribe:t.subscribe,reset:d};return T}function kn(e,n,a,t){if(!Ue(e,n)||a!==void 0&&n.observation&&n.observation.subject.customerId!==a||t!==void 0&&n.observation!==void 0&&(n.observation.subject.scope.projectId!==t.projectId||n.observation.subject.scope.environment!==t.environment))throw new l("INVALID_RESPONSE","The access requirement or Customer changed");return n}function En(e,n,a){if(e.requirement){if(!n)throw new l("INVALID_RESPONSE","The requested access check is missing");kn(e.requirement,n,e.customerId,a)}}import{ZodError as Un}from"zod";function An(e,n,a,t){try{return e.parse(n)}catch(f){throw t&&f instanceof Un?new l(a,t):f}}async function Ne(e,n,a,t={},f){let p=typeof t=="function"?{}:t,m=An(n.request,a,"INVALID_REQUEST",p.request);try{let c=await e(n.path,m,n.method,f),r=typeof t=="function"?t:t.parseResponse;return r?r(n.response,c):An(n.response,c,"INVALID_RESPONSE",p.response)}catch(c){throw c instanceof l&&m!==null&&typeof m=="object"&&"requestId"in m&&typeof m.requestId=="string"&&(c.commandRequestId??=m.requestId),c}}async function or(e,n){if(!ge.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let a=ie.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),t=ee(e);e.session||t.identify(n.customerToken);let f=null,p=!1,m=new AbortController,c=null,r=null,o=null,s=null,I=null,g=null,d=null,S=0,_=null,q="",i=0,y=new Map,P=new Set;function N(){if(p)throw new l("IDENTITY_CHANGED","Paywall is closed")}function D(){let v=JSON.stringify([S,d!==null]);if(!_||v!==q){q=v;let O=T(++i);_=O;let E=()=>{_===O&&(_=null)};O.then(E,E)}return _.then(O=>structuredClone(O))}async function T(v){N();let O=ie.resolvePaywall,E=await Ne(t.request,O,{...a,selector:f?{type:"version",versionId:f.id}:a.selector});En(a,E.paywall.check,E.scope);let A=await Ae(e,E.paywall);if(N(),n.paywallVersionId?A.id!==n.paywallVersionId:A.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(f&&(!mn(A,f)||A.paywallId!==f.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(v!==i)return structuredClone(f??A);f=A;for(let U of P)hn(U,structuredClone(f));return structuredClone(f)}async function u(v){if(N(),s&&v!=="read")throw new l("COMMAND_PENDING","Wait for the original quote");if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let O=c;if(v!=="read"){if(d){if(g===v)return d;throw new l("COMMAND_PENDING","Wait for the original purchase command")}if(g&&g!==v)throw new l("COMMAND_PENDING","Read the original purchase before changing an uncertain command");g=v,S++,i++}let E=g,A=S,U=v==="read"&&d===null,x=JSON.stringify([O.operationId,A,d!==null]);if(v==="read"&&y.has(x))return y.get(x).then(G=>structuredClone(G));let H=v==="read"?ie.readSubscriptionOperation:ie.attach,K=(async()=>{let G=await Ne(t.request,H,{operationId:O.operationId,...v==="read"?{}:{intent:v},...v==="confirm"&&O.merchantTerms?{merchantConfirmation:ke(O.merchantTerms)}:{}});return pn(G.operation,{operationId:O.operationId,currency:a.commerce.currency},"The purchase operation changed"),N(),c?.operationId!==O.operationId?structuredClone(G.operation):(r=yn(r,G.operation),(v!=="read"||U&&d===null)&&S===A&&g===E&&(g=null),structuredClone(r))})();if(v!=="read"){d=K;let G=()=>{d===K&&(d=null)};K.then(G,G)}else{y.set(x,K);let G=()=>{y.get(x)===K&&y.delete(x)};K.then(G,G)}return K.then(G=>structuredClone(G))}let b={signal:m.signal,get view(){return f?structuredClone(f):null},get quote(){return c?structuredClone(c):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return"bundled"},get recovery(){return wn({quote:c,operation:r,requestId:I,pending:s!==null||g!==null,destroyed:p})},get pendingCancellation(){return!p&&g==="cancel"},refresh:D,subscribe(v){return p?()=>{}:(P.add(v),()=>P.delete(v))},async preview(v){if(N(),!f)throw new l("INVALID_REQUEST","Load the Paywall first");let O=f.document.buttons[v.actionId];if(O?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let E=je(O.product,v.selection,f.capabilities);if(!E)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let A=Ke(f.document.screen,E,v.selection,f.capabilities),U=ie.previewAttach.request.parse({funnelId:a.funnelId,funnelVersionId:a.funnelVersionId,requestId:v.requestId,plans:[{productVersionId:E,...Object.keys(A).length?{featureQuantities:A}:{}}],provider:a.commerce.provider,currency:a.commerce.currency,...v.offerId?{offerId:v.offerId}:{},...v.nativeOffer?{nativeOffer:v.nativeOffer}:{}}),x=JSON.stringify(U);if(o&&o!==x&&(s||g||!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===x){if(s)return s;if(c)return structuredClone(c)}o!==x&&(c=null,r=null),o=x,I=U.requestId;let H=(async()=>{let K=ie.previewAttach,G=await Ne(t.request,K,U);return N(),gn(G.quote,{productVersionId:E,featureQuantities:A,currency:a.commerce.currency,provider:a.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=G.quote,r=null,structuredClone(c)})();s=H;try{return await H}finally{s===H&&(s=null)}},confirm:()=>u("confirm"),cancel:()=>u("cancel"),read:()=>u("read"),destroy(){p||(p=!0,m.abort(),P.clear(),y.clear(),L?.(),t.dispose(),f=null,c=null,r=null,o=null,I=null)}},L=e.session?.subscribeIdentity(b.destroy);try{return await D(),b}catch(v){throw b.destroy(),v}}import{z as Jn}from"zod";import{z as Ie}from"zod";var Gn=Ie.record(Ie.string().regex(/^[a-f0-9]{64}$/),Ie.strictObject({at:Ie.number(),text:Ie.string()})),ue=2*1048576,Bn=100;function jn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Fn(e,n){let a=n===void 0?jn():n,t=new Map,f=0,p=!1,m=!1,c,r;async function o(I){if(!a)return null;let g;try{let d=await Promise.race([Promise.resolve().then(()=>a.getItem(I)),new Promise(S=>{g=setTimeout(()=>S(null),Bn)})]);return typeof d=="string"&&d.length<=ue&&new TextEncoder().encode(d).byteLength<=ue?d:null}catch{return null}finally{clearTimeout(g)}}function s(){if(r)return r;let I=(async()=>{try{let g=await o(`${e}:artifacts`);if(g)return Gn.parse(JSON.parse(g))}catch{}return{}})();return r=I,I.finally(()=>{r===I&&(r=void 0)}),I}return{async readManifest(){return o(e)},writeManifest(I){!a||I.length>ue||new TextEncoder().encode(I).byteLength>ue||(c=I,!m&&(m=!0,Promise.resolve().then(async()=>{try{for(;c!==void 0;){let g=c;try{await a.setItem(e,g)}catch{}c===g&&(c=void 0)}}finally{m=!1}})))},async readArtifact(I){let g=(await s())[I],d=Date.now();return g&&d>=g.at&&d-g.at<=Y.retentionMs?g.text:void 0},writeArtifact(I,g){if(!a||g.length>ue)return;let d=t.get(I);if(d?.text===g||!d&&t.size>=128)return;let S=new TextEncoder().encode(g).byteLength;f-(d?.byteLength??0)+S>ue||(t.set(I,{text:g,byteLength:S}),f+=S-(d?.byteLength??0),!p&&(p=!0,Promise.resolve().then(async()=>{try{for(;t.size;){let _=new Map(t);try{let q={...await s()},i=Date.now();for(let[D,T]of _)q[D]={at:i,text:T.text};let y={},P=2,N=0;for(let[D,T]of Object.entries(q).sort(([,u],[,b])=>b.at-u.at)){if(T.at>i||i-T.at>Y.retentionMs)continue;let u=new TextEncoder().encode(JSON.stringify({[D]:T})).byteLength;P+u>ue||N>=128||(y[D]=T,P+=u,N++)}await a.setItem(`${e}:artifacts`,JSON.stringify(y))}catch{}finally{for(let[q,i]of _)t.get(q)===i&&(t.delete(q),f-=i.byteLength)}}}finally{p=!1}})))}}}var F=(e,n)=>new l(e,n),te=()=>performance.now(),Nn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function yr(e){let n=Ye.parse(e.scope),a=new ae(e.origin??ye);if(a.username||a.password||a.search||a.hash||a.pathname!=="/"||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))throw F("INVALID_URL","Configuration requires a trusted HTTPS origin");let t=new Set([a.origin,...(e.assetOrigins??[]).map(h=>{let w=new ae(h);if(w.protocol!=="https:"||w.username||w.password||w.search||w.hash||w.pathname!=="/")throw F("INVALID_URL","Invalid configuration asset origin");return w.origin})]),f=e.fetch??globalThis.fetch.bind(globalThis),p=`/api/v1/configuration/${n.environmentId}`,m=`indiana:configuration:1:${a.origin}:${j(n)}`,c=Fn(m,e.storage),r,o=0,s=0,I=!1,g=!1,d=0,S=0,_,q,i,y,P=0,N=new Set,D=new Set,T=new Map,u=new Map,b=0,L=!1;function v(){for(let h of N)try{h()}catch{}}function O(h){try{e.onError?.(h)}catch{}}let E=()=>!g&&!I&&!!r&&te()<o&&Date.now()<s;function A(){if(!E())throw F("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function U(h,w,R){if(!T.has(h)){for(;T.size&&(T.size>=128||b+R>Y.maxCacheBytes);){let C=T.entries().next().value;b-=C[1].byteLength,T.delete(C[0])}T.set(h,{text:w,byteLength:R}),b+=R}}function x(h,w,R){return fn(h,w,{signal:R,error:C=>F("INVALID_RESPONSE",C==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function H(h){let w=new ae(h,a);if(!t.has(w.origin)||w.username||w.password||w.hash||w.search)throw F("INVALID_URL","Configuration artifact origin is not trusted");return w.href}async function K(h,w,R=!1){let C=await f(H(h),{method:"GET",credentials:"omit",redirect:"error",cache:R?"default":"no-cache",signal:w,headers:{}});if(C.status===429){let V=C.headers.get("retry-after")??"";P=/^\d+$/.test(V)?Number(V)*1e3:Math.max(0,Date.parse(V)-Date.now())||15e3}if(!C.ok&&C.status!==304)throw F(`CONFIGURATION_HTTP_${C.status}`,"Configuration synchronization failed");return C}function G(h,w,R){let C=Date.parse(h.headers.get("x-indiana-config-validated-at")??""),V=Date.parse(h.headers.get("x-indiana-config-valid-until")??""),k=Date.parse(h.headers.get("date")??""),M=h.headers.get("age"),Q=M!==null&&/^\d+(\.\d+)?$/.test(M)?Number(M)*1e3:NaN;if(![C,V,k,Q].every(Number.isFinite)||V<=C||V-C>Y.maxControlAgeMs||C>k+1e3)throw F("INVALID_RESPONSE","Configuration freshness evidence is invalid");let B=Math.min(V-C,R.maxControlAgeSeconds*1e3,Y.maxControlAgeMs)-Math.max(Q,k-C,0)-(te()-w);if(B<=0)throw F("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return te()+B}function ve(){if(clearTimeout(i),clearTimeout(y),g||!N.size||(E()&&(y=setTimeout(()=>{E()?ve():v()},Math.max(1,o-te())),Nn(y)),typeof document<"u"&&document.visibilityState==="hidden"))return;let h=S?Math.min(15e3,1e3*2**Math.min(S-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);i=setTimeout(()=>{le().catch(O)},Math.max(P,h*(.8+Math.random()*.2))),Nn(i)}async function le(){if(g)throw F("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(_)return _;let h=d,w=new AbortController;q=w;let R=(async()=>{if(!L){L=!0;try{let Ce=await c.readManifest();if(Ce&&!r){let Z=Oe.parse(JSON.parse(Ce));j(Z.scope)===j(n)&&(r=Z)}}catch{}}w.signal.throwIfAborted();let M=r,Q=te(),J=await K(p,w.signal);J.status===304&&(!M||!J.headers.has("x-indiana-config-validated-at")||!J.headers.has("x-indiana-config-valid-until")||!J.headers.has("age"))&&(J=await K(p,w.signal));let B=J.status===304?M:Oe.parse(JSON.parse(await x(J,Y.maxManifestBytes,w.signal))),{generation:me,...pe}=B,W=J.headers.get("etag");if(j(B.scope)!==j(n)||$e(pe)!==me||W!==`"${me}"`&&W!==`W/"${me}"`)throw F("INVALID_RESPONSE","Configuration scope or content identity changed");if(M&&(B.revision<M.revision||B.revision===M.revision&&B.generation!==M.generation))throw F("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Ce,Z]of Object.entries(M?.funnels??{})){let oe=B.funnels[Ce];if(oe&&(oe.controlRevision<Z.controlRevision||oe.evaluationRevision<Z.evaluationRevision||oe.controlRevision===Z.controlRevision&&oe.state!==Z.state||oe.evaluationRevision===Z.evaluationRevision&&oe.evaluationMode!==Z.evaluationMode))throw F("INVALID_RESPONSE","Funnel control revision changed identity")}let re=G(J,Q,B.policy);if(w.signal.throwIfAborted(),h!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return r=B,o=re,s=Date.now()+Math.max(0,re-te()),I=!1,S=0,P=0,c.writeManifest(j(B)),v(),structuredClone(B)})(),C=setTimeout(()=>w.abort(F("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Y.initializationMs),V=new Promise((M,Q)=>w.signal.addEventListener("abort",()=>Q(w.signal.reason),{once:!0})),k=Promise.race([R,V]).catch(M=>{throw S++,(M instanceof Jn.ZodError||M instanceof SyntaxError||M instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(M.code))&&(o=0,I=!0,v()),M}).finally(()=>{clearTimeout(C),_===k&&(_=void 0),ve()});return _=k,k}async function Re(h){let w=h.sha256,R=pe=>Pe(pe,h);H(h.url);let C=T.get(w);if(C){if(C.byteLength!==h.byteLength)throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return T.delete(w),T.set(w,C),C.text}let V=u.get(w);if(V){if(V.byteLength!==h.byteLength)throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return V.promise}let k=new AbortController;D.add(k);let M=d,Q=(async()=>{try{let re=await c.readArtifact(w);if(re&&R(re)){if(k.signal.throwIfAborted(),g||M!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return U(w,re,h.byteLength),re}}catch{}k.signal.throwIfAborted();let pe=await K(h.url,k.signal,!0),W=await x(pe,h.byteLength,k.signal);if(!R(W))throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(g||M!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return U(w,W,h.byteLength),c.writeArtifact(w,W),W})(),J=setTimeout(()=>k.abort(F("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Y.initializationMs),B=new Promise((pe,W)=>k.signal.addEventListener("abort",()=>W(k.signal.reason),{once:!0})),me=Promise.race([Q,B]).finally(()=>{clearTimeout(J),D.delete(k),u.delete(w)});return u.set(w,{promise:me,byteLength:h.byteLength}),me}async function he(){return E()||await le(),A(),r}async function ce(h){let w,R=new Promise((C,V)=>{w=setTimeout(()=>V(F("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Y.initializationMs)});try{return await Promise.race([h(),R])}finally{clearTimeout(w)}}function de(h,w){if(A(),r?.generation!==h.generation)throw F("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(w&&r.funnels[w]?.state!=="active")throw F("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Le(h){let w=h.gb.features;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let R=h.artifacts[w];if(R.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let C=He.parse(JSON.parse(await Re(R)));if(j(C.scope)!==j({projectId:n.projectId,environment:n.environment})||C.generation!==R.generation||C.remoteFeatures.some(V=>Object.hasOwn(C.features,V)))throw F("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return de(h),{...C,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,o-te())).toISOString()}}async function xe(h,w){let R=await he(),C=R.funnels[h];w&&(!C||C.evaluationMode==="local"&&!C.versions[w])&&(_&&await _,R=await le()),de(R,h);let V=R.funnels[h];if(V.evaluationMode!=="local")throw F("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let k=w??V.currentVersionId,M=V.versions[k];if(!M)throw F("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(R.artifacts[M.artifact].formatVersion!==3)throw F("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Q,J]=await Promise.all([Re(R.artifacts[M.artifact]).then(B=>Ze(JSON.parse(B))),V.evaluationMode==="local"?Le(R):void 0]);if(J&&j(We(Q,J))!==j(M.dependencies))throw F("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return de(R,h),{document:Q,growth:J,versionId:k,control:structuredClone(V),manifest:structuredClone(R)}}async function Me(h,w){try{return await xe(h,w)}catch(R){if(!(R instanceof l)||!(R.code==="CONFIGURATION_CHANGED"||R.code==="CONFIGURATION_HTTP_404"&&E()))throw R;let C=r?.generation;if(_&&await _,await le(),R.code!=="CONFIGURATION_CHANGED"&&r?.generation===C)throw R;return xe(h,w)}}function fe(){if(E()||v(),typeof document<"u"&&document.visibilityState==="hidden"){ve();return}le().catch(O)}function Tn(h){if(g)throw F("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return N.add(h),N.size===1&&(typeof window<"u"&&(window.addEventListener("online",fe),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),ve()),()=>{N.delete(h),N.size||(clearTimeout(i),clearTimeout(y),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",fe),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:le,subscribe:Tn,assertFresh:A,assertFeatures(h){A();let w=r.gb.features;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(h!==void 0&&r.artifacts[w].generation!==h)throw F("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return E()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return E()?Math.max(0,o-te()):0},async features(){return ce(async()=>Le(await he()))},pageExperiments:()=>ce(async()=>{let h=await he(),w=h.gb.pageExperiments;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let R=h.artifacts[w];if(R.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let C=un.parse(JSON.parse(await Re(R)));if(C.environmentId!==n.environmentId||C.generation!==R.generation)throw F("INVALID_RESPONSE","Page experiment scope or generation changed");return de(h),C}),funnel:(h,w)=>ce(()=>Me(h,w)),funnelControl:h=>ce(async()=>{let w=await he();return de(w,h),structuredClone(w.funnels[h])}),paywall:(h,w)=>ce(async()=>{let R=await he(),C=R.paywalls?.[h];if(!C||!w&&C.state!=="published")throw F("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let V=w??C.currentVersionId,k=C.versions[V],M=k&&R.artifacts[k.artifact];if(!M||M.kind!=="paywall"||M.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Q=Qe.parse(JSON.parse(await Re(M)));return de(R),{document:Q,versionId:V,version:k.version,control:structuredClone(C),manifest:structuredClone(R)}}),async localFunnel(h,w){let R=await ce(()=>Me(h,w));if(!R.growth)throw F("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:C,remoteFeatures:V,...k}=R.growth;return sn({scope:{projectId:n.projectId,environment:n.environment},funnelId:h,versionId:R.versionId,evaluationMode:"local",evaluationRevision:R.control.evaluationRevision,document:R.document,payload:k})},assertFunnel(h,w,R){A();let C=r.funnels[h];if(!C||C.state!=="active")throw F("FUNNEL_STOPPED","Funnel is paused or unavailable");if(C.evaluationMode!=="local")throw F("EVALUATION_MODE","This Funnel now executes at Longplay");if(w!==void 0&&C.controlRevision!==w)throw F("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(R!==void 0&&!C.versions[R])throw F("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!g){g=!0,d++,o=0,q?.abort(F("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(i),clearTimeout(y),Ve(),v(),N.clear();for(let h of D)h.abort(F("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));T.clear(),b=0}}}}function On(e){let n=ge.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!se.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");return{async start(a){let t=X.safeParse({...a,operation:"start"});if(!t.success||t.data.operation!=="start"||(n?t.data.customer!==void 0:t.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let f=t.data,p=ee({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||p.identify(e.apiKey);let m=Ee(e,await p.request("funnels",f));if(!m.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");if(m.run.source.id!==f.funnelId||m.run.locale!==(f.locale??"en")||!we(m.run.parameters,f.parameters??{})||(f.customer?!m.customerId||f.customer.type==="id"&&m.customerId!==f.customer.value:m.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...m,runToken:m.runToken}}finally{p.dispose()}}}}async function Nr(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let a={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&j(a)!==j(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnelControl(e.funnelId)).evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let f=se.test(e.credential);if(f?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let p=On({...e,scope:a,apiKey:e.credential}),m=(c,r)=>{let o=Pn({...e,scope:a,runToken:c,initialResponse:r,...f?{serverKey:e.credential}:{}});return f||o.identify(e.credential),o};return{async start(c){let r=await p.start({...c,funnelId:e.funnelId,...f?{customer:{type:"id",value:e.customerId}}:{}}),o=m(r.runToken,r),s=await o.get();return{...r,...s,controller:o}},async restore(c){let r=m(c),o=await r.get();if(o.run.source.id!==e.funnelId)throw r.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...o,runToken:c,controller:r}}}}export{Ne as a,kn as b,En as c,zn as d,Ee as e,_e as f,ut as g,Vn as h,In as i,ht as j,we as k,Pt as l,Et as m,Pn as n,or as o,yr as p,On as q,Nr as r};
1
+ import{b as mn,c as pn,d as gn,e as yn,f as wn}from"./chunk-YAVWELIV.js";import{a as ae,b as ee}from"./chunk-H6PIJ4WG.js";import{a as l}from"./chunk-QVGTHPWT.js";import{a as dn,b as fn,c as Pe}from"./chunk-KOFZECHE.js";import{$ as Se,Da as ie,Ea as nn,Ha as tn,Ia as rn,Na as Te,Oa as on,Z as je,aa as Je,ab as an,ba as He,bb as sn,ca as ze,eb as un,fb as ln,ib as cn,lb as ye,ma as X,na as Qe,o as ke,oa as Y,pa as Ye,q as ge,qa as Oe,ra as j,ta as $e,ua as We,va as Ze,wa as Xe,xa as en}from"./chunk-ZC6PDVLR.js";import{a as hn}from"./chunk-DSPLGTQI.js";import{C as Ue,J as Ge,M as Be,Na as Ke,P as be,a as qe}from"./chunk-HDVLCRC6.js";function zn(e){let n=null,a=null,t=0,f=0,p=new Set,m=null,c=null,r=new Set,o=()=>{for(let i of r)try{i()}catch{}},s={attributes:be.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(i,y)=>{!p.has(i)&&n&&(!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(i,structuredClone(y),structuredClone(s.attributes),n.generation)}:void 0,onExperimentViewed:e.onExperimentViewed?(i,y)=>n&&(!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(i),structuredClone(y),structuredClone(s.attributes),n.generation):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?i=>e.saveStickyBucketAssignmentDoc(structuredClone(i)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},I=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function g(i,y=new Set){return p.has(i)?!m||!m.features[i]||["unknownFeature","cyclicPrerequisite"].includes(m.features[i].source):y.has(i)?!1:(y.add(i),(n?.features[i]?.rules??[]).some(P=>[...P.parentConditions??[],...(P.tracks??[]).flatMap(N=>N.experiment.parentConditions??[])].some(N=>g(N.id,y))))}let d=i=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return m?.expiresAt&&Date.parse(m.expiresAt)<=Date.now()&&(m=null,s.features=n.features),p.has(i)?!m||m.expiresAt&&Date.parse(m.expiresAt)<=Date.now()?I():structuredClone(m.features[i]??I()):e.evaluateRemote&&(s.attributes?.merchandise||s.attributes?.merchandiseId)&&!m||g(i)?I():structuredClone(Be(i,s))};async function S(){if(!n||!p.size&&!s.attributes?.merchandise&&!s.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(p.size)throw new Error("Remote Feature evaluation requires a server loader");return}let i=f;if(c?.revision===i)return c.loading;let y=t,P=n,N=[...p],D=(async()=>{let T=ze.parse(await e.evaluateRemote({attributes:structuredClone(s.attributes),features:N}));if(!(y!==t||i!==f||P!==n)){if(e.assertUsable?.(P.generation),T.generation!==P.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(N.some(u=>!Object.hasOwn(T.features,u))||Object.keys(T.features).some(u=>!p.has(u)))throw new Error("Invalid remote Feature results");if(s.attributes?.merchandise||s.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");s.attributes=be.parse({...s.attributes,...T.merchandiseContext})}m=structuredClone(T),s.features={...P.features,...Object.fromEntries(Object.entries(m.features).map(([u,b])=>[u,{defaultValue:b.value}]))},o()}})();c={revision:i,loading:D};try{await D}finally{c?.loading===D&&(c=null)}}function _(){S().catch(i=>{try{e.onError?.(i)}catch{}})}async function q(){if(a)return a;let i=t,y=(async()=>{let P=await e.load(),N="remoteFeatures"in P?Je.parse(P):null,D=N??Se.parse(P);if(D.scope.projectId!==e.scope.projectId||D.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(i!==t)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===D.generation){let{evaluatedAt:u,expiresAt:b,...L}=n,{evaluatedAt:v,expiresAt:O,...E}=D;if(j(L)!==j(E))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=D.evaluatedAt,n.expiresAt=D.expiresAt,o(),(!m||m.expiresAt&&Date.parse(m.expiresAt)<=Date.now())&&_(),structuredClone(n)}let T=new Set(N?.remoteFeatures??[]);if([...T].some(u=>Object.hasOwn(D.features,u)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in D&&!n.analyticsConfig.experimentViewsEnabled&&N?.analyticsConfig.experimentViewsEnabled&&s.trackedExperiments?.clear(),n=structuredClone(D),p=T,m=null,c=null,f++,s.features=n.features,s.savedGroups=Ge(n.savedGroups),s.trackedFeatureUsage={},o(),_(),structuredClone(n)})();a=y;try{return await y}finally{a===y&&(a=null)}}return{init:q,refresh:q,refreshRemote:S,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(i){return r.add(i),()=>{r.delete(i)}},setAttributes(i){let y=be.parse(i);(s.attributes?.merchandise||s.attributes?.merchandiseId||i.merchandise||i.merchandiseId)&&s.trackedExperiments?.clear(),s.attributes=y,f++,m=null,c=null,s.features=n?.features??{},s.trackedFeatureUsage={},o(),_()},evalFeature:d,isOn(i){return d(i).on},isOff(i){return d(i).off},getFeatureValue(i,y){let P=d(i).value;return structuredClone(P===null?y:P)},reset(){t++,f++,a=null,c=null,n=null,m=null,p.clear(),s.features={},s.savedGroups={},s.stickyBucketAssignmentDocs={},s.attributes={},s.trackedFeatureUsage={},s.trackedExperiments?.clear(),o()}}}function In(e){let n,a,t=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),f=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,a=e.locks??globalThis.navigator?.locks,!n||!a||!globalThis.crypto?.subtle)throw t();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ye).href,e.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return"indiana.funnel.commands.v1."+Array.from(r,o=>o.toString(16).padStart(2,"0")).join("")});f.catch(()=>{});async function p(c){try{let r=await f;return await a.request(r,{mode:"exclusive"},()=>c(r))}catch(r){throw r instanceof l?r:t()}}function m(c){let r=n.getItem(c);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw t();let o=JSON.parse(r);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw t();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(m),write:(c,r)=>p(o=>{if(m(o).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw t();return n.setItem(o,JSON.stringify({revision:c+1,entry:r})),c+1})}}function Ee(e,n){let a=tn.safeParse(n);if(!a.success)throw new l("INVALID_RESPONSE","Funnel response contract changed");let t=a.data;if(e.scope&&(t.scope.projectId!==e.scope.projectId||t.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Funnel scope changed");return t}async function Ae(e,n){let a=Xe.parse(n),{artifact:t,environmentId:f}=a.content,p=new ae(e.baseUrl??ye).origin,m=new ae(t.url,p);if(m.origin!==p||m.username||m.password||m.search||m.hash||m.pathname!==`/api/v1/configuration/${f}/artifacts/${t.sha256}`)throw new l("INVALID_RESPONSE","Public Paywall locator is not trusted");let c=new AbortController,r,o=new Promise((I,g)=>{r=setTimeout(()=>{let d=new l("TIMEOUT","Public Paywall read timed out");c.abort(d),g(d)},Y.initializationMs)}),s=(async()=>{let I=await(e.fetch??globalThis.fetch)(m,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:c.signal});if(c.signal.aborted&&(I.body?.cancel().catch(()=>{}),c.signal.throwIfAborted()),!I.ok||!I.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(I.headers.get("content-length"))>t.byteLength)throw I.body?.cancel().catch(()=>{}),new l("INVALID_RESPONSE","Public Paywall is unavailable");let g=await dn(I,t.byteLength,{signal:c.signal,error:d=>new l("INVALID_RESPONSE",d==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Pe(g,t))throw new l("INVALID_RESPONSE","Public Paywall digest or size changed");return en(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(g)))})();try{return await Promise.race([s,o])}finally{clearTimeout(r)}}var _e=(e,n)=>new l(e,n);function ut(e){return ln(e,_e)}var _n=3,Dn=2e3;function Ln(e){return e instanceof TypeError||e instanceof l&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function xn(e){for(let n=1;;n++)try{return await e.refresh()}catch(a){if(n===_n||!Ln(a))throw a;await new Promise(t=>setTimeout(t,n*Dn))}}async function De(e,n,{predict:a=!0}={}){let t=n.instruction;if(t?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==t.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let f=null,p;if(a)try{let m=await e.funnel(n.source.id,n.source.versionId);p=m.manifest.generation,f=Mn(e,n,m)}catch{f=null}return p??=e.snapshot?.generation??(await xn(e)).generation,{advance:{policyRevision:t.policyRevision,generation:p},prediction:f}}function Mn(e,n,a){let t=n.instruction;if(t?.type!=="evaluate_segment"||!a.growth||a.control.evaluationMode!=="local"||a.control.evaluationRevision!==t.policyRevision)return null;let{analyticsConfig:f,remoteFeatures:p,...m}=a.growth,c=an({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:t.policyRevision,document:a.document,payload:Se.parse(m)}),r=Vn(c,a.document,{...n,...t}),o=r.steps.at(-1),s=r.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:n.visit+r.steps.length-1}:null);return s?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:s.nodeId,visit:s.visit,terminal:!r.boundary}:null}function Vn(e,n,a){return cn(e,n,a,_e)}import{z as $}from"zod";var vn=X.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Rn=$.strictObject({schemaVersion:$.literal(1),scope:qe,runId:$.uuid(),funnelId:$.uuid(),versionId:$.uuid(),processBindingIds:$.record($.uuid(),$.uuid().nullable()).optional(),command:vn.optional(),closeCommand:vn.refine(e=>e.operation==="close").optional(),purchase:$.strictObject({receiptId:$.uuid(),operationId:$.uuid(),generation:$.number().int().nonnegative()}).optional(),closed:$.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),z=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Fe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function Cn(e){let n=0,a=null,t=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),f=Promise.resolve();async function p(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:Rn.parse(o.entry)}}function m(o){let s=f.then(o);return f=s.catch(()=>{}),s}async function c(o){for(let s=0;s<4;s++){let I=await p();if(I.entry&&a!==null&&t(I.entry)!==a)throw z();let g=o(I.entry,I.revision);if(Fe(I.entry,g)){n=I.revision;return}let d=await e.write(I.revision,g);if(d!==null){if(!Number.isSafeInteger(d)||d<=I.revision)throw z();n=d;return}}throw z()}function r(o,s){if(!o||!s)return o;if(o.processBindingIds&&Object.hasOwn(o.processBindingIds,s)){let I={...o.processBindingIds};delete I[s],o={...o,processBindingIds:I}}return o.command?.requestId===s?o.closeCommand?{...o,command:o.closeCommand,closeCommand:void 0}:o.purchase?{...o,command:void 0}:null:o.closeCommand?.requestId===s?{...o,closeCommand:void 0}:o}return{bind(o){let s=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(a!==null&&a!==s)throw z();a=s},async load(){let o=await p();return n=o.revision,a=o.entry?t(o.entry):null,o.entry},retain(o){let s=Rn.parse(o),I=s.command;return!I||a!==null&&t(s)!==a?Promise.reject(z()):(a??=t(s),m(()=>c((g,d)=>{if(g&&!Fe(t(g),t(s)))throw z();if(g&&s.processBindingIds){for(let[S,_]of Object.entries(s.processBindingIds))if(g.processBindingIds&&Object.hasOwn(g.processBindingIds,S)&&g.processBindingIds[S]!==_)throw z();g={...g,processBindingIds:{...g.processBindingIds,...s.processBindingIds}}}if(!g){if(d!==n&&I.operation!=="close")throw z();return s}if(!g.command)return{...g,command:I,...I.operation==="close"?{closed:!0}:{}};if(I.operation==="close"&&g.command.operation!=="close"){if(g.command.requestId===I.requestId||g.closeCommand&&!Fe(g.closeCommand,I))throw z();return{...g,closeCommand:I,closed:!0}}if(!Fe(g.command,I))throw z();return g})))},observePurchase(o,s,I,g){return m(()=>c((d,S)=>{if(!d&&S!==n||d&&t(d)!==t({...o,schemaVersion:1}))throw z();if(d?.purchase&&d.purchase.generation>s.generation)return r(d,g);if(d?.purchase&&d.purchase.generation===s.generation&&d.purchase.operationId!==s.operationId)throw z();return I?!d?.purchase||d.purchase.operationId!==s.operationId?r(d,g):r(d.command?{...d,purchase:void 0}:null,g):r({schemaVersion:1,...o,...d,purchase:s},g)}))},settle(o){return m(()=>c(s=>r(s,o)))}}}function ht(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function we(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((f,p)=>we(f,n[p]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let a=Object.entries(e),t=Object.entries(n);return a.length===t.length&&a.every(([f,p])=>Object.hasOwn(n,f)&&we(p,Reflect.get(n,f)))}function bn(e,n){let a=n&&{...n},t=null,f=0,p=-1,m=0,c=new AbortController;function r(){m++,c.abort(new l("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let o=!1,s,I=0,g=new Set;return{get scope(){return a},bindScope(d){if(a&&(a.projectId!==d.projectId||a.environment!==d.environment))throw new l("SCOPE_MISMATCH","Run scope changed");a??={...d}},get view(){return t},get currentView(){return p===m?t:null},get viewAgeMs(){return t&&p===m?performance.now()-f:void 0},get generation(){return m},get signal(){return c.signal},get disposed(){return o},get customerToken(){return s},get readSequence(){return I},nextRead(){return++I},assertCurrent(d,S="Run identity changed during the request"){if(d!==m||o)throw new l("IDENTITY_CHANGED",S)},assertRun(d){if(t&&(d.id!==t.id||d.source.type!==t.source.type||d.source.id!==t.source.id||d.source.versionId!==t.source.versionId||d.locale!==t.locale||!we(d.parameters,t.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e&&d.source.id!==e)throw new l("INVALID_RESPONSE","Run belongs to another Funnel")},publish(d,S,_,q,i){if(!(d.operation==="review"&&t&&t!==_&&S.run.revision<=t.revision)&&!(t&&S.run.revision===t.revision&&q!==void 0&&q<I)&&(d.operation==="review"&&!S.run.stopped&&["running","waiting"].includes(S.run.status)&&t&&p===m&&S.run.nodeId===t.nodeId&&S.run.visit===t.visit&&S.run.revision===t.revision&&(S.run.screen=t.screen,(t.paywall?.quote?.operationId===S.review?.activeOperationId||!t.paywall?.quote&&S.review?.activeOperationId===null)&&(S.run.paywall=t.paywall)),!(t?.paywall&&S.run.paywall&&t.paywall.receiptId===S.run.paywall.receiptId&&(S.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||S.run.revision>=t.revision)t=S.run,f=performance.now(),p=m;else if(!i)return;if(t&&p===m)for(let y of g)try{y(structuredClone(t))}catch{}}},identify(d){if(o)throw new l("IDENTITY_CHANGED","Controller was reset");if(!ge.test(d))throw new l("INVALID_TOKEN","Customer credential required");r(),s=d},subscribe(d){return g.add(d),()=>g.delete(d)},reset(){o||(o=!0,r(),s=void 0,t=null,g.clear())}}}var se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Pt(e,n,a="A server API key is required"){if(typeof window<"u")throw new l("SERVER_ONLY",n);if(!se.test(e))throw new l("INVALID_TOKEN",a)}function Et(e){let n=ee(e);return n.identify(e.apiKey),n}function ne(e){let{customerToken:n,...a}=e;return a}var qn=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Sn({journal:e,state:n,call:a,processIdentity:t}){let f=null,p=null,m=!1,c={command:null,close:null},r=new Set,o,s=null,I=e?e.load().then(i=>{if(n.disposed)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(s=i,!i)return;if(t){if([i.command,i.closeCommand].some(P=>P&&!Object.hasOwn(i.processBindingIds??{},P.requestId)))throw new l("COMMAND_STORAGE_INVALID","The original process identity is missing");t.restore(i.processBindingIds??{})}if(n.scope&&(i.scope.projectId!==n.scope.projectId||i.scope.environment!==n.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=i.purchase,m=i.closed===!0,!i.command)return;let y=i.command;f=y.operation==="close"?null:y,p=y.operation==="close"?y:i.closeCommand?.operation==="close"?i.closeCommand:null,p&&(m=!0);for(let P of[f,p])P&&r.add(P.requestId)}):Promise.resolve();I.catch(()=>{});async function g(i){e&&await I;let y=n.generation;if(e){if(!n.view||!n.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:ne(i),...t?{processBindingIds:{[i.requestId]:t.binding(i.requestId)}}:{}})}if(y!==n.generation||f!==i&&p!==i)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let P=r.has(i.requestId);r.add(i.requestId);try{return await a(i)}catch(N){throw y===n.generation&&(f===i||p===i)&&!P&&!qn(N)&&(e&&await e.settle(i.requestId),y===n.generation&&q(i)),N}}function d(i){let y=X.parse(i);if(y.operation==="start"||y.operation==="get"||y.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(m&&y.operation!=="close"){if(f?.requestId===y.requestId)return _(y.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(y.operation==="close"){if(f?.requestId===y.requestId)throw new l("INVALID_REQUEST","Close requires its own request identity");if(m=!0,p&&JSON.stringify(ne(p))!==JSON.stringify(ne(y)))throw new l("COMMAND_PENDING","Retry the original Close");return p??=y,c.close?c.close:S(p,"close")}if(f){if(JSON.stringify(ne(f))!==JSON.stringify(ne(y)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else f=y;return S(f,"command")}function S(i,y){let P=g(i);c[y]=P;let N=()=>{c[y]===P&&(c[y]=null)};return P.then(N,N),P}function _(i){return a({operation:"get",settlementRequestId:i})}function q(i){return!i||f!==i&&p!==i?!1:(f===i&&(f=null),p===i&&(p=null),r.delete(i.requestId),!f&&!p&&(s=null),!0)}return{ready:I,get pending(){return f},get closing(){return p},get closeRequested(){return m},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return o},assertBinding(i){if(s&&(i.run.id!==s.runId||i.run.source.id!==s.funnelId||i.run.source.versionId!==s.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(i,y,P,N){let D=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0,T=D&&y.settlement?.state==="settled"&&y.run.pendingRequest?.requestId!==D&&(i.operation==="get"||!m||i.operation==="close"||!["running","waiting"].includes(y.run.status))?D:void 0,u=f?.requestId===T?f:p?.requestId===T?p:void 0;e?.bind({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId});let b=y.run.paywall,L=b??y.purchase,v=L?.operation,O=y.settlement&&(!b||b.purchaseRequestId===y.settlement.requestId)&&(!o||o.operationId===y.settlement.operationId)?y.settlement:void 0,E=v?.operationId??L?.quote?.operationId??O?.operationId,A=L?.receiptId??O?.receiptId,U=b?.selectionGeneration??o?.generation??0;if(e&&E&&A&&i.operation!=="review"&&(!n.view||y.run.revision>=n.view.revision)&&(N===void 0||N>=n.readSequence)&&(!o||U>=o.generation)){let x={receiptId:A,operationId:E,generation:U},H=v?.status==="complete"||L?.canReselect===!0;await e.observePurchase({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId},x,H,T),n.assertCurrent(P),(!o||x.generation>=o.generation)&&(N===void 0||N>=n.readSequence)&&(H?o?.operationId===x.operationId&&(o=void 0):o=x)}else e&&T&&await e.settle(T);return n.assertCurrent(P),T?q(u):!1},stop(){m=!0},submit:d,settle:_,reset(){m=!0,f=null,p=null,o=void 0,s=null,c.close=null,r.clear(),c.command=null}}}function Pn(e){e={...e};let n=e.initialResponse;if(delete e.initialResponse,typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!se.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new l("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let a=ee({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=bn(e.funnelId,e.scope??e.configuration?.scope),f=e.session?.subscribeIdentity(d),p=null,m=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?In(e):void 0),c=m&&Cn(m),r=Sn({journal:c,state:t,call:S,processIdentity:e.process}),o=0,s=new Map;function I(){o++,s.clear(),n=void 0}async function g(u){if(e.process)return e.process.request(u);let b=t.generation;t.assertCurrent(b);let L=performance.now()+(e.timeoutMs??35e3),v=t.customerToken??("customerToken"in u?u.customerToken:void 0);if(e.session){let A=t.signal,U,x=()=>{},H=new Promise((K,G)=>{x=()=>G(A.reason),A.addEventListener("abort",x,{once:!0}),U=setTimeout(()=>G(new l("TIMEOUT","Longplay request timed out")),Math.max(1,L-performance.now()))});try{v=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(b),e.session.access())),H])}finally{clearTimeout(U),A.removeEventListener("abort",x)}}t.assertCurrent(b);let O={...u,...v?{customerToken:v}:{}},E=u.operation==="page_experiments"?Te.parse(O):X.parse(O);return a.requestWithCredential("funnels",E,e.runToken,{headers:e.serverKey&&!v?{[rn]:e.serverKey}:void 0,timeoutMs:Math.max(1,L-performance.now())})}function d(){I(),f?.(),t.reset(),r.reset(),p=null,a.dispose()}async function S(u,b){let L=n;n=void 0;let v=t.generation,O=()=>t.assertCurrent(v);c&&await r.ready,O();let E=t.view,A=Ee(e,L!==void 0&&u.operation==="get"&&!u.data&&!u.purchase&&!u.settlementRequestId?L:await g(u));if(u.operation==="review"&&!A.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(O(),A.runToken&&A.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let U=u.operation==="get"?u.settlementRequestId:"requestId"in u&&u.operation!=="start"?u.requestId:void 0;if(U&&A.settlement?.requestId!==U)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(A),t.assertRun(A.run),t.bindScope(A.scope);let x=await r.observe(u,A,v,b);return!A.run.stopped&&["running","waiting"].includes(A.run.status)&&u.operation==="get"&&u.settlementRequestId||(O(),["running","waiting"].includes(A.run.status)||r.stop(),t.publish(u,A,E,b,x)),A}function _(u){let b=t.generation;I();let L=u(),v=()=>{t.generation===b&&I()};return L.then(v,v),L}let q=u=>_(()=>r.submit(u)),i=null,y=new WeakMap;function P(u){let b=y.get(u);if(b)return b;let L=D(u);return y.set(u,L),L}let N=!1;async function D(u){let b=await u;if(b.run.instruction?.type!=="evaluate_segment")return b;if(i)return i;N=!0;let L=t.generation,v=(async()=>{for(let O=0;O<32&&b.run.instruction?.type==="evaluate_segment";O++){if(r.pending||r.closeRequested)return b;let E=b.run;if(b.run.instruction?.type==="evaluate_segment"){let{advance:U}=await De(e.configuration,E,{predict:!1});if(L!==t.generation)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return b;if(t.view&&(t.view.revision!==E.revision||t.view.visit!==E.visit||t.view.nodeId!==E.nodeId))return S({operation:"get"});let x=!0;De(e.configuration,E).then(({prediction:H})=>{x&&L===t.generation&&!r.closeRequested&&t.view?.id===E.id&&!t.view.stopped&&t.view.nodeId===E.nodeId&&t.view.visit===E.visit&&t.view.revision===E.revision&&(p=H)}).catch(()=>{});try{b=await q({operation:"commit_segment",requestId:nn(E.id,E.visit,`segment:${E.revision}`),nodeId:E.nodeId,visit:E.visit,revision:E.revision,...U})}finally{x=!1,p=null}}}return b})();i=v;try{return await v}finally{i===v&&(i=null)}}let T={get configuration(){return N?e.configuration:void 0},get configurationReady(){return!0},get view(){let u=t.currentView;return u?structuredClone(u):null},get viewAgeMs(){return t.viewAgeMs},get pendingCommand(){let u=r.closing??r.pending;return u?structuredClone(ne(u)):null},get pendingCommands(){return[r.pending,r.closing].filter(u=>u!==null).map(u=>structuredClone(ne(u)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get hasDurableJournal(){return c!==void 0},get prediction(){let u=t.view;return p&&u&&!u.stopped&&["running","waiting"].includes(u.status)&&u.id===p.runId&&u.nodeId===p.from.nodeId&&u.visit===p.from.visit&&u.revision===p.from.revision&&!r.closeRequested?structuredClone(p):null},settle:(...u)=>_(()=>r.settle(...u)),get webViewUrl(){return"bundled"},resolvePaywall(u){return Ae(e,u)},async pageExperiments(u,b=[]){let L=t.generation;t.assertCurrent(L);let v=t.view?.id;if(!v)throw new l("INVALID_REQUEST","Read the Run before its page experiments");let O=on.parse(await g(Te.parse({operation:"page_experiments",release:u,usedReceiptIds:b})));if(t.assertCurrent(L),O.runId!==v||O.scope.projectId!==t.scope?.projectId||O.scope.environment!==t.scope?.environment)throw new l("SCOPE_MISMATCH","Page experiment Run changed");return O},review(u){return S({operation:"review",...u?{receiptId:u}:{}},t.nextRead())},async get(u,b){let L=t.generation;u=u&&structuredClone(u),b=b&&{...b},c&&await r.ready,t.assertCurrent(L),b??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let v=JSON.stringify([t.generation,o,u??null,b??null]),O=s.get(v);if(O)return O.then(x=>structuredClone(x));let E=t.nextRead(),A=P(S({operation:"get",...u?{data:u}:{},...b?{purchase:b}:{}},E));s.set(v,A);let U=()=>{s.get(v)===A&&s.delete(v)};return A.then(U,U),A.then(x=>structuredClone(x))},resume(u=t.view?.pendingRequest?.requestId){return u?r.closeRequested?T.settle(u):r.pending?.requestId===u?P(q(r.pending)):P(q({operation:"resume",requestId:u})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(u){return P(q(u))},retry(){return r.closeFlight?r.closeFlight:r.closing?q(r.closing):r.closeRequested&&r.pending?T.settle(r.pending.requestId):r.inFlight?P(r.inFlight):r.pending?P(q(r.pending)):Promise.reject(new l("INVALID_REQUEST","No command is pending"))},identify(u){let b=t.customerToken?void 0:n;I(),t.identify(u),n=b,p=null,a.reset()},get identitySignal(){return t.signal},subscribe:t.subscribe,reset:d};return T}function kn(e,n,a,t){if(!Ue(e,n)||a!==void 0&&n.observation&&n.observation.subject.customerId!==a||t!==void 0&&n.observation!==void 0&&(n.observation.subject.scope.projectId!==t.projectId||n.observation.subject.scope.environment!==t.environment))throw new l("INVALID_RESPONSE","The access requirement or Customer changed");return n}function En(e,n,a){if(e.requirement){if(!n)throw new l("INVALID_RESPONSE","The requested access check is missing");kn(e.requirement,n,e.customerId,a)}}import{ZodError as Un}from"zod";function An(e,n,a,t){try{return e.parse(n)}catch(f){throw t&&f instanceof Un?new l(a,t):f}}async function Ne(e,n,a,t={},f){let p=typeof t=="function"?{}:t,m=An(n.request,a,"INVALID_REQUEST",p.request);try{let c=await e(n.path,m,n.method,f),r=typeof t=="function"?t:t.parseResponse;return r?r(n.response,c):An(n.response,c,"INVALID_RESPONSE",p.response)}catch(c){throw c instanceof l&&m!==null&&typeof m=="object"&&"requestId"in m&&typeof m.requestId=="string"&&(c.commandRequestId??=m.requestId),c}}async function or(e,n){if(!ge.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let a=ie.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),t=ee(e);e.session||t.identify(n.customerToken);let f=null,p=!1,m=new AbortController,c=null,r=null,o=null,s=null,I=null,g=null,d=null,S=0,_=null,q="",i=0,y=new Map,P=new Set;function N(){if(p)throw new l("IDENTITY_CHANGED","Paywall is closed")}function D(){let v=JSON.stringify([S,d!==null]);if(!_||v!==q){q=v;let O=T(++i);_=O;let E=()=>{_===O&&(_=null)};O.then(E,E)}return _.then(O=>structuredClone(O))}async function T(v){N();let O=ie.resolvePaywall,E=await Ne(t.request,O,{...a,selector:f?{type:"version",versionId:f.id}:a.selector});En(a,E.paywall.check,E.scope);let A=await Ae(e,E.paywall);if(N(),n.paywallVersionId?A.id!==n.paywallVersionId:A.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(f&&(!mn(A,f)||A.paywallId!==f.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(v!==i)return structuredClone(f??A);f=A;for(let U of P)hn(U,structuredClone(f));return structuredClone(f)}async function u(v){if(N(),s&&v!=="read")throw new l("COMMAND_PENDING","Wait for the original quote");if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let O=c;if(v!=="read"){if(d){if(g===v)return d;throw new l("COMMAND_PENDING","Wait for the original purchase command")}if(g&&g!==v)throw new l("COMMAND_PENDING","Read the original purchase before changing an uncertain command");g=v,S++,i++}let E=g,A=S,U=v==="read"&&d===null,x=JSON.stringify([O.operationId,A,d!==null]);if(v==="read"&&y.has(x))return y.get(x).then(G=>structuredClone(G));let H=v==="read"?ie.readSubscriptionOperation:ie.attach,K=(async()=>{let G=await Ne(t.request,H,{operationId:O.operationId,...v==="read"?{}:{intent:v},...v==="confirm"&&O.merchantTerms?{merchantConfirmation:ke(O.merchantTerms)}:{}});return pn(G.operation,{operationId:O.operationId,currency:a.commerce.currency},"The purchase operation changed"),N(),c?.operationId!==O.operationId?structuredClone(G.operation):(r=yn(r,G.operation),(v!=="read"||U&&d===null)&&S===A&&g===E&&(g=null),structuredClone(r))})();if(v!=="read"){d=K;let G=()=>{d===K&&(d=null)};K.then(G,G)}else{y.set(x,K);let G=()=>{y.get(x)===K&&y.delete(x)};K.then(G,G)}return K.then(G=>structuredClone(G))}let b={signal:m.signal,get view(){return f?structuredClone(f):null},get quote(){return c?structuredClone(c):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return"bundled"},get recovery(){return wn({quote:c,operation:r,requestId:I,pending:s!==null||g!==null,destroyed:p})},get pendingCancellation(){return!p&&g==="cancel"},refresh:D,subscribe(v){return p?()=>{}:(P.add(v),()=>P.delete(v))},async preview(v){if(N(),!f)throw new l("INVALID_REQUEST","Load the Paywall first");let O=f.document.buttons[v.actionId];if(O?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let E=je(O.product,v.selection,f.capabilities);if(!E)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let A=Ke(f.document.screen,E,v.selection,f.capabilities),U=ie.previewAttach.request.parse({funnelId:a.funnelId,funnelVersionId:a.funnelVersionId,requestId:v.requestId,plans:[{productVersionId:E,...Object.keys(A).length?{featureQuantities:A}:{}}],provider:a.commerce.provider,currency:a.commerce.currency,...v.offerId?{offerId:v.offerId}:{},...v.nativeOffer?{nativeOffer:v.nativeOffer}:{}}),x=JSON.stringify(U);if(o&&o!==x&&(s||g||!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===x){if(s)return s;if(c)return structuredClone(c)}o!==x&&(c=null,r=null),o=x,I=U.requestId;let H=(async()=>{let K=ie.previewAttach,G=await Ne(t.request,K,U);return N(),gn(G.quote,{productVersionId:E,featureQuantities:A,currency:a.commerce.currency,provider:a.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=G.quote,r=null,structuredClone(c)})();s=H;try{return await H}finally{s===H&&(s=null)}},confirm:()=>u("confirm"),cancel:()=>u("cancel"),read:()=>u("read"),destroy(){p||(p=!0,m.abort(),P.clear(),y.clear(),L?.(),t.dispose(),f=null,c=null,r=null,o=null,I=null)}},L=e.session?.subscribeIdentity(b.destroy);try{return await D(),b}catch(v){throw b.destroy(),v}}import{z as Jn}from"zod";import{z as Ie}from"zod";var Gn=Ie.record(Ie.string().regex(/^[a-f0-9]{64}$/),Ie.strictObject({at:Ie.number(),text:Ie.string()})),ue=2*1048576,Bn=100;function jn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Fn(e,n){let a=n===void 0?jn():n,t=new Map,f=0,p=!1,m=!1,c,r;async function o(I){if(!a)return null;let g;try{let d=await Promise.race([Promise.resolve().then(()=>a.getItem(I)),new Promise(S=>{g=setTimeout(()=>S(null),Bn)})]);return typeof d=="string"&&d.length<=ue&&new TextEncoder().encode(d).byteLength<=ue?d:null}catch{return null}finally{clearTimeout(g)}}function s(){if(r)return r;let I=(async()=>{try{let g=await o(`${e}:artifacts`);if(g)return Gn.parse(JSON.parse(g))}catch{}return{}})();return r=I,I.finally(()=>{r===I&&(r=void 0)}),I}return{async readManifest(){return o(e)},writeManifest(I){!a||I.length>ue||new TextEncoder().encode(I).byteLength>ue||(c=I,!m&&(m=!0,Promise.resolve().then(async()=>{try{for(;c!==void 0;){let g=c;try{await a.setItem(e,g)}catch{}c===g&&(c=void 0)}}finally{m=!1}})))},async readArtifact(I){let g=(await s())[I],d=Date.now();return g&&d>=g.at&&d-g.at<=Y.retentionMs?g.text:void 0},writeArtifact(I,g){if(!a||g.length>ue)return;let d=t.get(I);if(d?.text===g||!d&&t.size>=128)return;let S=new TextEncoder().encode(g).byteLength;f-(d?.byteLength??0)+S>ue||(t.set(I,{text:g,byteLength:S}),f+=S-(d?.byteLength??0),!p&&(p=!0,Promise.resolve().then(async()=>{try{for(;t.size;){let _=new Map(t);try{let q={...await s()},i=Date.now();for(let[D,T]of _)q[D]={at:i,text:T.text};let y={},P=2,N=0;for(let[D,T]of Object.entries(q).sort(([,u],[,b])=>b.at-u.at)){if(T.at>i||i-T.at>Y.retentionMs)continue;let u=new TextEncoder().encode(JSON.stringify({[D]:T})).byteLength;P+u>ue||N>=128||(y[D]=T,P+=u,N++)}await a.setItem(`${e}:artifacts`,JSON.stringify(y))}catch{}finally{for(let[q,i]of _)t.get(q)===i&&(t.delete(q),f-=i.byteLength)}}}finally{p=!1}})))}}}var F=(e,n)=>new l(e,n),te=()=>performance.now(),Nn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function yr(e){let n=Ye.parse(e.scope),a=new ae(e.origin??ye);if(a.username||a.password||a.search||a.hash||a.pathname!=="/"||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))throw F("INVALID_URL","Configuration requires a trusted HTTPS origin");let t=new Set([a.origin,...(e.assetOrigins??[]).map(h=>{let w=new ae(h);if(w.protocol!=="https:"||w.username||w.password||w.search||w.hash||w.pathname!=="/")throw F("INVALID_URL","Invalid configuration asset origin");return w.origin})]),f=e.fetch??globalThis.fetch.bind(globalThis),p=`/api/v1/configuration/${n.environmentId}`,m=`indiana:configuration:1:${a.origin}:${j(n)}`,c=Fn(m,e.storage),r,o=0,s=0,I=!1,g=!1,d=0,S=0,_,q,i,y,P=0,N=new Set,D=new Set,T=new Map,u=new Map,b=0,L=!1;function v(){for(let h of N)try{h()}catch{}}function O(h){try{e.onError?.(h)}catch{}}let E=()=>!g&&!I&&!!r&&te()<o&&Date.now()<s;function A(){if(!E())throw F("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function U(h,w,R){if(!T.has(h)){for(;T.size&&(T.size>=128||b+R>Y.maxCacheBytes);){let C=T.entries().next().value;b-=C[1].byteLength,T.delete(C[0])}T.set(h,{text:w,byteLength:R}),b+=R}}function x(h,w,R){return fn(h,w,{signal:R,error:C=>F("INVALID_RESPONSE",C==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function H(h){let w=new ae(h,a);if(!t.has(w.origin)||w.username||w.password||w.hash||w.search)throw F("INVALID_URL","Configuration artifact origin is not trusted");return w.href}async function K(h,w,R=!1){let C=await f(H(h),{method:"GET",credentials:"omit",redirect:"error",cache:R?"default":"no-cache",signal:w,headers:{}});if(C.status===429){let V=C.headers.get("retry-after")??"";P=/^\d+$/.test(V)?Number(V)*1e3:Math.max(0,Date.parse(V)-Date.now())||15e3}if(!C.ok&&C.status!==304)throw F(`CONFIGURATION_HTTP_${C.status}`,"Configuration synchronization failed");return C}function G(h,w,R){let C=Date.parse(h.headers.get("x-indiana-config-validated-at")??""),V=Date.parse(h.headers.get("x-indiana-config-valid-until")??""),k=Date.parse(h.headers.get("date")??""),M=h.headers.get("age"),Q=M!==null&&/^\d+(\.\d+)?$/.test(M)?Number(M)*1e3:NaN;if(![C,V,k,Q].every(Number.isFinite)||V<=C||V-C>Y.maxControlAgeMs||C>k+1e3)throw F("INVALID_RESPONSE","Configuration freshness evidence is invalid");let B=Math.min(V-C,R.maxControlAgeSeconds*1e3,Y.maxControlAgeMs)-Math.max(Q,k-C,0)-(te()-w);if(B<=0)throw F("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return te()+B}function ve(){if(clearTimeout(i),clearTimeout(y),g||!N.size||(E()&&(y=setTimeout(()=>{E()?ve():v()},Math.max(1,o-te())),Nn(y)),typeof document<"u"&&document.visibilityState==="hidden"))return;let h=S?Math.min(15e3,1e3*2**Math.min(S-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);i=setTimeout(()=>{le().catch(O)},Math.max(P,h*(.8+Math.random()*.2))),Nn(i)}async function le(){if(g)throw F("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(_)return _;let h=d,w=new AbortController;q=w;let R=(async()=>{if(!L){L=!0;try{let Ce=await c.readManifest();if(Ce&&!r){let Z=Oe.parse(JSON.parse(Ce));j(Z.scope)===j(n)&&(r=Z)}}catch{}}w.signal.throwIfAborted();let M=r,Q=te(),J=await K(p,w.signal);J.status===304&&(!M||!J.headers.has("x-indiana-config-validated-at")||!J.headers.has("x-indiana-config-valid-until")||!J.headers.has("age"))&&(J=await K(p,w.signal));let B=J.status===304?M:Oe.parse(JSON.parse(await x(J,Y.maxManifestBytes,w.signal))),{generation:me,...pe}=B,W=J.headers.get("etag");if(j(B.scope)!==j(n)||$e(pe)!==me||W!==`"${me}"`&&W!==`W/"${me}"`)throw F("INVALID_RESPONSE","Configuration scope or content identity changed");if(M&&(B.revision<M.revision||B.revision===M.revision&&B.generation!==M.generation))throw F("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Ce,Z]of Object.entries(M?.funnels??{})){let oe=B.funnels[Ce];if(oe&&(oe.controlRevision<Z.controlRevision||oe.evaluationRevision<Z.evaluationRevision||oe.controlRevision===Z.controlRevision&&oe.state!==Z.state||oe.evaluationRevision===Z.evaluationRevision&&oe.evaluationMode!==Z.evaluationMode))throw F("INVALID_RESPONSE","Funnel control revision changed identity")}let re=G(J,Q,B.policy);if(w.signal.throwIfAborted(),h!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return r=B,o=re,s=Date.now()+Math.max(0,re-te()),I=!1,S=0,P=0,c.writeManifest(j(B)),v(),structuredClone(B)})(),C=setTimeout(()=>w.abort(F("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Y.initializationMs),V=new Promise((M,Q)=>w.signal.addEventListener("abort",()=>Q(w.signal.reason),{once:!0})),k=Promise.race([R,V]).catch(M=>{throw S++,(M instanceof Jn.ZodError||M instanceof SyntaxError||M instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(M.code))&&(o=0,I=!0,v()),M}).finally(()=>{clearTimeout(C),_===k&&(_=void 0),ve()});return _=k,k}async function Re(h){let w=h.sha256,R=pe=>Pe(pe,h);H(h.url);let C=T.get(w);if(C){if(C.byteLength!==h.byteLength)throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return T.delete(w),T.set(w,C),C.text}let V=u.get(w);if(V){if(V.byteLength!==h.byteLength)throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return V.promise}let k=new AbortController;D.add(k);let M=d,Q=(async()=>{try{let re=await c.readArtifact(w);if(re&&R(re)){if(k.signal.throwIfAborted(),g||M!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return U(w,re,h.byteLength),re}}catch{}k.signal.throwIfAborted();let pe=await K(h.url,k.signal,!0),W=await x(pe,h.byteLength,k.signal);if(!R(W))throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(g||M!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return U(w,W,h.byteLength),c.writeArtifact(w,W),W})(),J=setTimeout(()=>k.abort(F("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Y.initializationMs),B=new Promise((pe,W)=>k.signal.addEventListener("abort",()=>W(k.signal.reason),{once:!0})),me=Promise.race([Q,B]).finally(()=>{clearTimeout(J),D.delete(k),u.delete(w)});return u.set(w,{promise:me,byteLength:h.byteLength}),me}async function he(){return E()||await le(),A(),r}async function ce(h){let w,R=new Promise((C,V)=>{w=setTimeout(()=>V(F("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Y.initializationMs)});try{return await Promise.race([h(),R])}finally{clearTimeout(w)}}function de(h,w){if(A(),r?.generation!==h.generation)throw F("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(w&&r.funnels[w]?.state!=="active")throw F("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Le(h){let w=h.gb.features;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let R=h.artifacts[w];if(R.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let C=He.parse(JSON.parse(await Re(R)));if(j(C.scope)!==j({projectId:n.projectId,environment:n.environment})||C.generation!==R.generation||C.remoteFeatures.some(V=>Object.hasOwn(C.features,V)))throw F("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return de(h),{...C,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,o-te())).toISOString()}}async function xe(h,w){let R=await he(),C=R.funnels[h];w&&(!C||C.evaluationMode==="local"&&!C.versions[w])&&(_&&await _,R=await le()),de(R,h);let V=R.funnels[h];if(V.evaluationMode!=="local")throw F("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let k=w??V.currentVersionId,M=V.versions[k];if(!M)throw F("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(R.artifacts[M.artifact].formatVersion!==3)throw F("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Q,J]=await Promise.all([Re(R.artifacts[M.artifact]).then(B=>Ze(JSON.parse(B))),V.evaluationMode==="local"?Le(R):void 0]);if(J&&j(We(Q,J))!==j(M.dependencies))throw F("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return de(R,h),{document:Q,growth:J,versionId:k,control:structuredClone(V),manifest:structuredClone(R)}}async function Me(h,w){try{return await xe(h,w)}catch(R){if(!(R instanceof l)||!(R.code==="CONFIGURATION_CHANGED"||R.code==="CONFIGURATION_HTTP_404"&&E()))throw R;let C=r?.generation;if(_&&await _,await le(),R.code!=="CONFIGURATION_CHANGED"&&r?.generation===C)throw R;return xe(h,w)}}function fe(){if(E()||v(),typeof document<"u"&&document.visibilityState==="hidden"){ve();return}le().catch(O)}function Tn(h){if(g)throw F("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return N.add(h),N.size===1&&(typeof window<"u"&&(window.addEventListener("online",fe),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),ve()),()=>{N.delete(h),N.size||(clearTimeout(i),clearTimeout(y),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",fe),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:le,subscribe:Tn,assertFresh:A,assertFeatures(h){A();let w=r.gb.features;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(h!==void 0&&r.artifacts[w].generation!==h)throw F("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return E()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return E()?Math.max(0,o-te()):0},async features(){return ce(async()=>Le(await he()))},pageExperiments:()=>ce(async()=>{let h=await he(),w=h.gb.pageExperiments;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let R=h.artifacts[w];if(R.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let C=un.parse(JSON.parse(await Re(R)));if(C.environmentId!==n.environmentId||C.generation!==R.generation)throw F("INVALID_RESPONSE","Page experiment scope or generation changed");return de(h),C}),funnel:(h,w)=>ce(()=>Me(h,w)),funnelControl:h=>ce(async()=>{let w=await he();return de(w,h),structuredClone(w.funnels[h])}),paywall:(h,w)=>ce(async()=>{let R=await he(),C=R.paywalls?.[h];if(!C||!w&&C.state!=="published")throw F("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let V=w??C.currentVersionId,k=C.versions[V],M=k&&R.artifacts[k.artifact];if(!M||M.kind!=="paywall"||M.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Q=Qe.parse(JSON.parse(await Re(M)));return de(R),{document:Q,versionId:V,version:k.version,control:structuredClone(C),manifest:structuredClone(R)}}),async localFunnel(h,w){let R=await ce(()=>Me(h,w));if(!R.growth)throw F("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:C,remoteFeatures:V,...k}=R.growth;return sn({scope:{projectId:n.projectId,environment:n.environment},funnelId:h,versionId:R.versionId,evaluationMode:"local",evaluationRevision:R.control.evaluationRevision,document:R.document,payload:k})},assertFunnel(h,w,R){A();let C=r.funnels[h];if(!C||C.state!=="active")throw F("FUNNEL_STOPPED","Funnel is paused or unavailable");if(C.evaluationMode!=="local")throw F("EVALUATION_MODE","This Funnel now executes at Longplay");if(w!==void 0&&C.controlRevision!==w)throw F("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(R!==void 0&&!C.versions[R])throw F("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!g){g=!0,d++,o=0,q?.abort(F("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(i),clearTimeout(y),Ve(),v(),N.clear();for(let h of D)h.abort(F("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));T.clear(),b=0}}}}function On(e){let n=ge.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!se.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");return{async start(a){let t=X.safeParse({...a,operation:"start"});if(!t.success||t.data.operation!=="start"||(n?t.data.customer!==void 0:t.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let f=t.data,p=ee({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||p.identify(e.apiKey);let m=Ee(e,await p.request("funnels",f));if(!m.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");if(m.run.source.id!==f.funnelId||m.run.locale!==(f.locale??"en")||!we(m.run.parameters,f.parameters??{})||(f.customer?!m.customerId||f.customer.type==="id"&&m.customerId!==f.customer.value:m.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...m,runToken:m.runToken}}finally{p.dispose()}}}}async function Nr(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let a={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&j(a)!==j(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnelControl(e.funnelId)).evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let f=se.test(e.credential);if(f?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let p=On({...e,scope:a,apiKey:e.credential}),m=(c,r)=>{let o=Pn({...e,scope:a,runToken:c,initialResponse:r,...f?{serverKey:e.credential}:{}});return f||o.identify(e.credential),o};return{async start(c){let r=await p.start({...c,funnelId:e.funnelId,...f?{customer:{type:"id",value:e.customerId}}:{}}),o=m(r.runToken,r),s=await o.get();return{...r,...s,controller:o}},async restore(c){let r=m(c),o=await r.get();if(o.run.source.id!==e.funnelId)throw r.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...o,runToken:c,controller:r}}}}export{Ne as a,kn as b,En as c,zn as d,Ee as e,_e as f,ut as g,Vn as h,In as i,ht as j,we as k,Pt as l,Et as m,Pn as n,or as o,yr as p,On as q,Nr as r};
@@ -1,4 +1,4 @@
1
- import{a as $,b as N,c as J,d as q}from"./chunk-KPVVGOOU.js";import{a as P}from"./chunk-7P7KRVLI.js";import{kb as D}from"./chunk-ZDLY6GPF.js";import{a as _}from"./chunk-DSPLGTQI.js";import{I as C,J as O,L as j}from"./chunk-HDVLCRC6.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
1
+ import{a as $,b as N,c as J,d as q}from"./chunk-2QSCQD6Q.js";import{a as P}from"./chunk-KOFZECHE.js";import{kb as D}from"./chunk-ZC6PDVLR.js";import{a as _}from"./chunk-DSPLGTQI.js";import{I as C,J as O,L as j}from"./chunk-HDVLCRC6.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
2
2
  Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
3
  plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
4
  */function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
@@ -1 +1 @@
1
- import{a as u}from"./chunk-QVGTHPWT.js";import{Aa as j,Ba as O,Ca as T,ya as E,za as M}from"./chunk-ZDLY6GPF.js";import{q as w}from"./chunk-HDVLCRC6.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
1
+ import{a as u}from"./chunk-QVGTHPWT.js";import{Aa as j,Ba as O,Ca as T,ya as E,za as M}from"./chunk-ZC6PDVLR.js";import{q as w}from"./chunk-HDVLCRC6.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
@@ -0,0 +1 @@
1
+ import{a as Ve,c as sn}from"./chunk-JGG4R75K.js";import{d as tn,f as qe,g as _e,h as rn,i as Le,k as on}from"./chunk-6DTGBDYG.js";import{a as Ke,b as Xe,c as Ze,d as en,e as nn,f as Te}from"./chunk-YAVWELIV.js";import{a as b}from"./chunk-QVGTHPWT.js";import{b as an,e as un}from"./chunk-SLUA7ABW.js";import{d as ln}from"./chunk-2QSCQD6Q.js";import{Z as xe,ma as Ae}from"./chunk-ZC6PDVLR.js";import{a as le}from"./chunk-DSPLGTQI.js";import{Da as We,I as Be,Na as Ye}from"./chunk-HDVLCRC6.js";async function dn(n){let{session:E,load:e}=bn(n);try{return await e(),E}catch(I){throw E.destroy(),I}}function bn(n){let E=n.view;if(!E?.paywall)throw new b("INVALID_REQUEST","The current node is not a Paywall");let e=E.paywall.receiptId,I=E.nodeId,w=E.visit,P=E.paywall.resolution,o=E.paywall,m="document"in P?{document:P.document,offering:P.offering,capabilities:P.capabilities}:null;function p(){let i=o.resolution;return"document"in i?i:m&&{...i,document:m.document,offering:m.offering,capabilities:Ke(i.capabilities,m.capabilities)}}function r(i){if(!Xe(i,P))throw new b("INVALID_RESPONSE","The pinned Paywall binding changed")}let v=!1,S=new Set,A=null;function F(){let i=p();if(i&&!v)for(let c of S)le(c,structuredClone(i))}async function q(){L();let i=p();if(i)return structuredClone(i);if(!A){let c=(async()=>{if("document"in o.resolution||!n.resolvePaywall)throw new b("INVALID_RESPONSE","Public Paywall reader is unavailable");let d=await n.resolvePaywall(o.resolution);return L(),r(d),m={document:d.document,offering:d.offering,capabilities:d.capabilities},F(),p()})();A=c;let a=()=>{A===c&&(A=null)};c.then(a,a)}return A.then(c=>structuredClone(c))}let u=new AbortController,O=(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===I&&i.visit===w&&i.input.type==="paywall_quote")?.requestId??E.paywall.purchaseRequestId,T=0,D=null,z=new Set,N=null,f=new Map;function M(i){if(i.purchase&&i.purchase.receiptId!==e)throw new b("INVALID_RESPONSE","Purchase receipt changed");let c=i.run.paywall;return i.purchase??(c?.receiptId===e?c:null)}function L(){if(v)throw new b("IDENTITY_CHANGED","Paywall presentation has closed")}function x(i,c,a){if(L(),c!==T||a!==void 0&&o.quote?.operationId!==a)return!1;let d=o.selectionGeneration??0,y=i.run.paywall;if(y?.receiptId===e){if((y.selectionGeneration??0)<(o.selectionGeneration??0))return!1;r(y.resolution)}let h=M(i),B=y?.receiptId===e&&(y.selectionGeneration??0)>d,Q=B?h?.quote??null:h?.quote??o.quote,$=h?.operation??(Q?.operationId===o.quote?.operationId?o.operation:null);return Q&&$&&Ze($,{operationId:Q.operationId},"Purchase operation changed"),(B||Q?.operationId!==o.quote?.operationId)&&(T++,y?.receiptId===e&&(O=y.purchaseRequestId)),o={...o,...y?.receiptId===e?y:{},quote:Q,operation:nn(o.operation,$,!0)},F(),!0}function U(i,c,a){return new Promise((d,y)=>{let h=!1,B=()=>{clearTimeout(ce),u.signal.removeEventListener("abort",Z)},Q=ye=>{h||(h=!0,B(),d(ye))},$=ye=>{h||(h=!0,B(),y(ye))},Z=()=>$(new b("IDENTITY_CHANGED","Paywall presentation has closed")),ce=setTimeout(()=>$(new b("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,c-Date.now()));u.signal.addEventListener("abort",Z,{once:!0}),u.signal.aborted&&Z(),i.then(Q,$)})}function Y(i){return new Promise(c=>{let a=()=>{clearTimeout(d),u.signal.removeEventListener("abort",a),c()},d=setTimeout(a,i);u.signal.addEventListener("abort",a,{once:!0}),u.signal.aborted&&a()})}function _(i,c){L();let a=f.get(i)??n.pendingCommands?.find(h=>h.requestId===i)??n.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===I&&a.visit===w){c.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!c.predecessor&&(c={...c,predecessor:a.input.predecessor});let h=Ae.parse(a),B=Ae.parse({...a,input:c});if(h.operation!=="submit"||B.operation!=="submit"||JSON.stringify(h.input)!==JSON.stringify(B.input))throw new b("CONFLICT","A purchase request cannot change its input");return f.set(i,h),h}let d=n.view;if(!d||d.nodeId!==I||d.visit!==w||d.paywall?.receiptId!==e)throw new b("PRECONDITION_FAILED","The Paywall visit has changed");let y=Ae.parse({operation:"submit",requestId:i,nodeId:I,visit:w,revision:d.revision,input:structuredClone(c)});if(y.operation!=="submit")throw new b("INVALID_REQUEST","A purchase submission is required");return f.set(i,y),y}async function C(i,c){L();let{requestId:a,input:d}=i,y=Date.now()+3e4;z.add(a);try{let h=await U(n.submit(i),y,a);for(;h.run.pendingRequest?.requestId===a&&Date.now()<y&&!v&&(await Y(Math.min(1e3,y-Date.now())),!(v||Date.now()>=y));)h=await U(n.resume(a),y,a);if(v)throw new b("IDENTITY_CHANGED","Paywall presentation has closed");if(h.run.pendingRequest?.requestId===a)throw new b("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!x(h,c,d.type==="paywall_confirm"||d.type==="paywall_cancel"?d.operationId:void 0))throw new b("PRECONDITION_FAILED","The purchase selection has changed");N===a&&(N=null)}catch(h){throw N=a,h instanceof b&&h.code==="COMMAND_PENDING"&&h.status===void 0&&f.delete(a),h}finally{z.delete(a)}}async function G(i){if(!o.quote)throw new b("INVALID_REQUEST","A quoted purchase is required");let c=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...f.values(),...n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])].find(y=>y.operation==="submit"&&y.input.type===c&&"operationId"in y.input&&y.input.operationId===o.quote.operationId),d=a?.operation==="submit"&&a.input.type===c&&"operationId"in a.input&&a.input.operationId===o.quote.operationId?a.requestId:crypto.randomUUID();if(await C(_(d,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId}),T),!o.operation)throw new b("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let j={get view(){return structuredClone(p())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return n.webViewUrl},get canReselect(){return o.canReselect===!0},get recovery(){let i=n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[]),c=n.pendingPurchase;if(c&&(c.receiptId!==e||c.operationId!==o.quote?.operationId))return{type:"recover",operationId:c.operationId,requestId:i[0]?.requestId??null};let a=Te({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??N??O,pending:z.size>0||i.length>0||N!==null,destroyed:v,canReselect:o.canReselect});return a.type==="recover"&&a.requestId===null&&!v&&n.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!c&&!i.length&&!z.size&&!O?{type:"native",operationId:null}:a},get pendingCancellation(){return!v&&(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===I&&i.visit===w&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return v?()=>{}:(S.add(i),()=>S.delete(i))},async refresh(){L();let i=T,c=await n.get();if(x(c,i),c.run.paywall?.receiptId!==e)throw new b("PRECONDITION_FAILED","Paywall presentation has changed");return q()},preview(i){let c=p();if(!c)return Promise.reject(new b("PRECONDITION_FAILED","Load the Paywall presentation first"));if(O&&O!==i.requestId&&(D||o.canReselect!==!0))return Promise.reject(new b("COMMAND_PENDING","Retry the original purchase before starting another"));let a=c.document.buttons[i.actionId],d=a?.type==="checkout"?xe(a.product,i.selection,c.capabilities):null;if(!d)return Promise.reject(new b("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let y=Ye(c.document.screen,d,i.selection,c.capabilities),h=O!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0;if(h&&o.canReselect!==!0)return Promise.reject(new b("COMMAND_PENDING","Original purchase requires authoritative termination"));let B;try{B=_(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:d,...Object.keys(y).length?{featureQuantities:y}:{},...h?{predecessor:h}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(Z){return Promise.reject(Z)}if(O===i.requestId&&D)return D;O!==i.requestId&&T++;let Q=T;O=i.requestId;let $=(async()=>{if(await C(B,Q),!o.quote)throw new b("INVALID_RESPONSE","The accepted quote is missing");return en(o.quote,{productVersionId:d,featureQuantities:y},"The selected purchase changed"),structuredClone(o.quote)})();return D=$,$.then(()=>{D===$&&(D=null)},Z=>{D===$&&(D=null),O===i.requestId&&n.pendingCommand?.requestId!==i.requestId&&Z instanceof b&&Z.status!==void 0&&Z.status<500&&![401,425].includes(Z.status)&&(O=null)}),$},confirm:()=>G("confirm"),cancel:()=>G("cancel"),async read(){if(L(),!o.quote)throw new b("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,c=T,a=n.pendingCommands?.find(Q=>Q.operation==="submit"&&(Q.input.type==="paywall_confirm"||Q.input.type==="paywall_cancel")&&Q.input.operationId===i)??n.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===i&&await n.settle?.(a.requestId);let d=await n.get(void 0,{receiptId:e,operationId:i});L();let y=M(d);if(y?.quote&&y.quote.operationId!==i||y?.operation&&y.operation.operationId!==i)throw new b("INVALID_RESPONSE","Purchase operation changed");let h=x(d,c,i),B=h?o.operation:y?.operation;if(!B)throw new b("INVALID_RESPONSE","The current purchase result is missing");return h&&z.size===0&&!(n.pendingCommands?.length??(n.pendingCommand?1:0))&&(N=null),structuredClone(B)},destroy(){v=!0,ie(),S.clear(),u.abort(),f.clear()}},ie=n.subscribe(i=>{v||i.nodeId!==I||i.visit!==w||i.paywall?.receiptId!==e||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(r(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},F())});return{session:j,load:q}}function cn(n){let E=new Set,e=new Set,I=null;async function w(p,r){let v=!1;for(;!n.stopped&&n.key===p&&n.client.pendingCommand?.requestId===r;){if(!n.client.settle)throw new b("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(r),v=!0,n.client.pendingCommand?.requestId===r&&await new Promise(S=>setTimeout(S,1500))}n.stopped||n.key!==p||(v&&await n.client.get(),!(n.stopped||n.key!==p)&&E.add(p))}function P(p,r){I=r;let v=()=>{I===r&&(I=null),e.delete(p)};return r.then(v,S=>{v(),n.busy||n.fail(S)}),r}function o(p){if(n.reviewing||E.has(p)||e.has(p)||n.stopped)return;e.add(p);let r=async()=>{if(n.reviewing||n.stopped||n.key!==p||E.has(p)){e.delete(p);return}if(n.busy||n.client.pendingCommand){setTimeout(()=>{r()},250);return}let v=(async()=>{if(n.staleRead){if(await n.staleRead,n.stopped||n.key!==p)return;if(n.client.pendingCommand){setTimeout(()=>{r()},250);return}}let S=n.client.view,A=n.expected(),F=A.requestId;try{await n.client.submit({operation:"shown",...A})}catch(q){if(!(q instanceof b)||q.code!=="CONFLICT"||q.status!==409||n.client.pendingCommand)throw q;await n.client.get();let u=n.client.view;if(n.stopped||n.reviewing||n.key!==p||!u||!S||u.id!==S.id||u.source.versionId!==S.source.versionId||u.nodeId!==A.nodeId||u.visit!==A.visit||u.revision<=A.revision||u.stopped||!u.screen&&(!u.paywall||u.paywall.receiptId!==S.paywall?.receiptId)||!["running","waiting"].includes(u.status)||n.client.pendingCommand)throw q;let k=n.expected();F=k.requestId,await n.client.submit({operation:"shown",...k})}await w(p,F)})();P(p,v)};r()}function m(){if(I)return I;let p=n.client.pendingCommand;if(p?.operation!=="shown")return null;let r=n.key;return e.add(r),P(r,(async()=>{await n.client.retry(),await w(r,p.requestId)})())}return{report:o,settled:m,get inFlight(){return I}}}function pn(n){let E={},e=new Map;async function I(w){let P=n.client.view,o=P?.screen,m=o?.customerData.nodes[w.nodeId];if(n.stopped||n.busy||!P||!o||!m)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(w.action)){let q=n.document,u=q?We(q,w.nodeId):null,k=u?.type==="customer_data"?u.data.outputs?.[w.action]:void 0;k&&o.outputs.includes(k)?await n.perform(()=>n.client.submit({operation:"submit",...n.expected(),input:{type:"screen",output:k,answers:n.answers,selection:w.value?{[w.nodeId]:w.value}:{}}})):await n.onIntent?.(w,P);return}let r=w.action.startsWith("sources_")?m.resources.find(q=>q.key===w.value):null;if(w.action.startsWith("sources_")&&!r)throw new b("INVALID_REQUEST","Choose a current resource");let v=`${P.visit}:${w.nodeId}:${r?.key??""}`,S=e.get(v)??[null],F=E[w.nodeId]??{page:1,after:null,filter:"all",...r?{resourceKey:r.key}:{}};if(w.action==="filter"){let q=w.value;if(!q||!(m.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(q))throw new b("INVALID_REQUEST","Unknown data filter");F={page:1,after:null,filter:q},S.splice(0,S.length,null)}else if(w.action==="next"||w.action==="sources_next"){let q=r?.sources.at(-1),u=r?q?{kind:"ledger",cursor:{at:q.detail[0],id:q.id,type:"source"}}:null:o.dataCursors[w.nodeId];if(!u||!r&&!m.hasNext)return;S[F.page]=u,F={...F,page:F.page+1,after:u}}else if(w.action==="previous"||w.action==="sources_previous"){if(F.page<=1)return;F={...F,page:F.page-1,after:S[F.page-2]??null}}e.set(v,S),E={...E,[w.nodeId]:F},await n.perform(()=>n.client.get({nodeId:P.nodeId,visit:P.visit,revision:P.revision,components:E}))}return{get queries(){return E},intent:I,reset(){E={},e.clear()}}}function fn(n){let{doc:E,holder:e,reviewHolder:I,mountScreenPreview:w}=n,P=!1,o,m=0,p=null,r="",v,S=new Map,A=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function F(u){if(n.stopped||!n.client.review||P&&u===o&&v?.active)return;let k=!P||u!==o;P||(r=A(n.client.view),S.set(r,structuredClone(n.answers))),P=!0,o=u,e.hidden=!0,n.suspend(!0),I.hidden=!1;let O=++m;k&&(v?.finish("dismissed"),p?.destroy(),p=null,I.replaceChildren(),v=_e(I,n.loadingOptions,"funnel",()=>{q()}));let T=k?v:void 0;try{if(T?.start(!1,n.client.view?.locale),O!==m||n.stopped)return;let D=n.client.review(u),z=await(T?.wait(D,qe)??D);if(n.stopped||O!==m||!P)return;if(!z.review)throw new b("INVALID_RESPONSE","Historical projection is missing");p?.destroy(),p=null,T||I.replaceChildren();let N=E.createElement("div"),f=T?Le(N,I):()=>{};I.append(N);let M=z.run.locale.startsWith("zh"),L=E.createElement("p");L.textContent=M?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",N.append(L);for(let[U,Y]of z.review.pages.entries()){let _=E.createElement("button");_.type="button",_.textContent=M?`\u7B2C ${U+1} \u9875`:`Page ${U+1}`,_.onclick=()=>{F(Y.receiptId)},N.append(_)}if(z.review.page){let U=z.review.page,Y=E.createElement("div");Y.inert=!0,N.append(Y),p=w(Y,{mode:"live",rendererUrl:n.client.webViewUrl,title:U.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{O===m&&!n.stopped&&T?.present(f)},onError:C=>{if(O!==m||n.stopped)return;let G=new Error(C);T?.finish("error",G),p?.destroy(),p=null,N.remove(),n.fail(G)},onEscape:()=>{q()}});let _=p;if(_.update(U.document,z.run.locale,{serverInput:{bindings:U.inputs,answers:U.answers,values:U.values}}),await _.ready,n.stopped||O!==m||!P)return}let x=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"};for(let U of[...z.review.coupons.map((Y,_)=>`${M?"\u4F18\u60E0\u5238":"Coupon"} ${_+1}: ${x[Y.status]}`),...z.review.purchases.map((Y,_)=>`${M?"\u8D2D\u4E70":"Purchase"} ${_+1}: ${sn(Y.status,M)}`)]){let Y=E.createElement("p");Y.textContent=U,N.append(Y)}z.review.page||T?.present(f),n.client.view&&await n.enqueue(n.client.view)}catch(D){if(O!==m||n.stopped)return;T?.finish("error",D),p?.destroy(),p=null,I.replaceChildren(),n.fail(D)}}async function q(){if(!P||n.stopped||!n.client.review)return;let u=++m;v?.finish("dismissed");try{if(await n.client.review(),n.stopped||u!==m)return;P=!1,m++,v?.finish("dismissed"),p?.destroy(),p=null,I.replaceChildren(),I.hidden=!0,e.hidden=!1;let k=n.client.view;A(k)!==r?(S.set(r,structuredClone(n.answers)),n.resetScreen()):(S.delete(r),n.suspend(!1)),k&&await n.enqueue(k)}catch(k){if(u!==m||n.stopped)return;p?.destroy(),p=null,I.replaceChildren(),n.fail(k)}}return{get active(){return P},get receipt(){return o},open:F,exit:q,get drafts(){return new Map([...S].map(([u,k])=>[u,structuredClone(k)]))},stop(){P=!1,m++,v?.finish("dismissed"),p?.destroy(),p=null,I.replaceChildren(),I.hidden=!0,e.hidden=!1}}}function mn(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let E=n.client.pageExperiments.bind(n.client),e=!1,I=!1,w=0,P=!1,o=!1,m="",p=()=>{let f=n.client.view;return JSON.stringify([f?.id,f?.source.versionId,f?.visit,f?.revision,f?.status,f?.stopped])},r=new Map,v=new Set,S={},A=new Map,F=an(n.appManifestRelease),q=()=>{for(let f of r.values())f.effect.revert();r.clear()},u=()=>{q();for(let f of A.values())f();A.clear()};function k(f){if(e||v.has(f))return;v.add(f);let M=w;E(n.appManifestRelease,[f]).catch(L=>{v.delete(f),!e&&M===w&&le(n.onError,L)})}async function O(){if(e)return;m=p();let f=n.client.view;if(!f||f.stopped||!["running","waiting"].includes(f.status)){w++,u();return}if(document.visibilityState==="hidden")return;if(P){o=!0;return}P=!0;let M=++w,L=`${f.id}:${f.visit}:${f.revision}`,x=location.href;try{let[U,{applyVisualVariation:Y}]=await Promise.all([E(n.appManifestRelease),import("./visual-dom-7IF7ITAK.js")]),_=n.client.view;if(e||M!==w||!_||_.stopped||!["running","waiting"].includes(_.status)||`${_.id}:${_.visit}:${_.revision}`!==L||location.href!==x)return;let C=new Set,G=new Set;for(let j of U.assignments){let ie=`${U.payload.environmentId}:${j.experimentKey}`;if(G.add(ie),A.has(ie)||A.set(ie,un(ie,S)),!!j.inExperiment)for(let i of U.payload.experiments){if(i.key!==j.experimentKey||!Be(location.href,i.urlPatterns??[]))continue;let c=i.meta?.findIndex(Q=>Q.key===j.variationKey)??-1,a=i.variations[c];if(!a?.renderGuard)continue;let d=j.receiptId+":"+i.changeId,y=JSON.stringify([j.variationKey,a]);C.add(d);let h=r.get(d);if(h?.signature===y){h.effect.applied&&k(j.receiptId);continue}r.get(d)?.effect.revert(),r.delete(d);let B=Y(a,{requireUniqueTargets:!0,boundVariations:i.variations,allowJs:!1,onApplied:()=>k(j.receiptId),onError:Q=>le(n.onError,Q)});r.set(d,{signature:y,effect:B}),B.applied&&k(j.receiptId)}}for(let[j,ie]of r)C.has(j)||(ie.effect.revert(),r.delete(j));for(let[j,ie]of A)G.has(j)||(ie(),A.delete(j))}catch(U){M===w&&u(),!e&&M===w&&le(n.onError,U)}finally{P=!1,o&&!e&&(o=!1,O())}}let T=n.client.subscribe(()=>{if(p()===m)return;m=p(),w++;let f=n.client.view;(!f||f.stopped||!["running","waiting"].includes(f.status))&&u(),I&&O()}),D=ln(()=>{w++,u(),I&&O()}),z=()=>{w++,q()};document.addEventListener("visibilitychange",z);let N=Ve({document,run:async()=>{I&&await O()},delay:()=>I&&!e?15e3:void 0});return{async start(){I||e||(I=!0,await N.refresh())},refresh:O,destroy(){e=!0,w++,N.destroy(),document.removeEventListener("visibilitychange",z),T(),D(),u(),F.destroy()}}}var Qe=5e3;async function rt(n,E){let e=E,[{mountScreenPreview:I},{showPaywall:w}]=await Promise.all([import("./screen-renderer-TEVGVUT5.js"),import("./paywall-YBC5XAB7.js")]),P=e.client.identitySignal;e.signal?.throwIfAborted(),P?.throwIfAborted();let o=e.appManifestRelease?mn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;o?.start();let m=n.ownerDocument,p=on(m),r=m.createElement("section"),v=m.createElement("div"),S=m.createElement("div"),A=m.createElement("div"),F=m.createElement("button");A.hidden=!0,F.type="button";let q=m.createElement("p"),u=m.createElement("p"),k=m.createElement("button"),O=m.createElement("button"),T=m.createElement("button"),D=m.createElement("dialog"),z;r.dataset.indianaFunnel="",r.setAttribute("aria-busy","false"),r.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",S.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",q.setAttribute("role","status"),u.setAttribute("role","alert"),u.hidden=!0,k.type=O.type=T.type="button",S.append(k,q,u,T,F,O),r.append(v,A,S),n.append(r);let N=null,f=null,M=null,L="",x="",U="",Y="",_="",C=!1,G=0,j=!1,ie="",i=null,c=Promise.resolve(),a=!e.client.view,d,y,h,B="",Q,$=!1,Z=null,ce=!1,ye=()=>e.client.pendingCommand?.operation==="close",re=null,K=null,Je=Ve({document:m,run:async()=>{(!f?.observing||e.client.pendingCommand)&&await Ue()},delay:()=>{if(!(C||!M||!["running","waiting"].includes(M.status)&&!e.client.pendingCommand)&&!(f?.observing&&!e.client.pendingCommand))return M.pendingRequest||e.client.pendingCommand?1500:Qe},hiddenDelay:()=>!C&&e.client.pendingCommand?15e3:void 0}),X=null;function Me(){return K&&e.client.hasDurableJournal===!0&&X?.acknowledged===!0&&X.operationId===K.operationId&&e.client.view?.id===X.runId&&e.client.view?.status==="closed"&&e.client.view.revision===X.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?K:null}function ze(t){let s=t.run.paywall;if(X&&t.settlement?.requestId===X.requestId&&t.settlement.state==="settled"&&t.settlement.operationId===null&&t.run.id===X.runId&&t.run.status==="closed"&&!t.run.pendingRequest&&t.run.revision===X.revision+1&&t.run.nodeId===X.nodeId&&t.run.visit===X.visit&&s?.receiptId===X.receiptId&&s.selectionGeneration===X.selectionGeneration&&(s.quote?.operationId??null)===X.operationId&&(s.operation?.operationId??s.quote?.operationId??null)===X.operationId){let l=X.operationId===null&&s.selectionGeneration===0&&!s.quote&&!s.operation&&!s.purchaseRequestId,ue=Te({quote:s.quote,operation:s.operation,requestId:s.purchaseRequestId,pending:!1,destroyed:!1,canReselect:s.canReselect});(l||s.canReselect===!0&&ue.type==="native")&&(X.acknowledged=!0)}}let Ce=null,De=new Set,pe={},oe=(t,s=null)=>{C||(Ce=s,u.textContent=t instanceof Error?t.message:"Request failed",u.hidden=!1,T.hidden=e.client.pendingCommand===null,le(e.onError,t))};function he(){let t=e.client.view;if(!t)throw new b("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let V=fn({client:e.client,doc:m,holder:v,reviewHolder:A,mountScreenPreview:I,loadingOptions:e,get stopped(){return C},get answers(){return pe},suspend(t){f?.setSuspended(t)},resetScreen(){L="",x="",U=""},enqueue:fe,fail:oe}),Se=cn({client:e.client,expected:he,fail:oe,get stopped(){return C},get reviewing(){return V.active},get key(){return L},get busy(){return G},get staleRead(){return i}}),Fe=pn({client:e.client,expected:he,perform:Re,onIntent:e.onCustomerDataIntent,get stopped(){return C},get busy(){return G},get document(){return N?.document},get answers(){return pe}}),ke=t=>`${t.id}:${t.nodeId}:${t.visit}`,Pe=t=>t&&(t.screen||t.paywall)?ke(t):"";function Ie(){let t=e.client.view;k.disabled=!V.active&&(G>0||!!e.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!Pe(t)||x!==Pe(t))}async function je(t){if(!t)return;let s=e.client.view;await t;let l=e.client.view;if(!s||!l||l.id!==s.id||l.nodeId!==s.nodeId||l.visit!==s.visit||l.stopped||!["running","waiting"].includes(l.status))throw new b("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Re(t,s=!1){if(!((G||ce||re||K)&&!s||C||V.active&&!s)){G++,r.setAttribute("aria-busy","true"),Ie(),u.hidden=!0,Ce=null;try{if(s||await je(Se.inFlight),C)return;let l=await t();C||await fe(e.client.view??l.run)}catch(l){oe(l,e.client.pendingCommand?.requestId??null)}finally{G=Math.max(0,G-1),r.setAttribute("aria-busy",String(G>0)),C||(T.hidden=e.client.pendingCommand===null,Ie())}}}function Ee(){Je.schedule()}async function Ue(){if(!(C||j||G)){if(V.active){await V.open(V.receipt);return}j=!0;try{let t=e.client.pendingCommand;t&&e.client.settle&&await e.client.settle(t.requestId);let s=e.client.view,l=Fe.queries,ue=await e.client.get(s?.screen&&Object.keys(l).length?{nodeId:s.nodeId,visit:s.visit,revision:s.revision,components:l}:void 0);!C&&l===Fe.queries&&await fe(e.client.view??ue.run)}catch(t){oe(t)}finally{j=!1}}}function Oe(t,s){if(d?.active)return d;let l=_e(n,e,"funnel",()=>{C||$||($=!0,l.finish("dismissed"),ge(),r.hidden=!0,e.client.view?be().finally(se):se())});return d=l,l.start(t,s),l}function $e(){clearTimeout(Q?.timeout),Q=void 0}function ge(){$e(),y?.abort(),y=void 0,N?.destroy(),N=null,f?.destroy(),f=null,h?.(),h=void 0,D.open&&D.close(),v.replaceChildren(),L="",x="",U="",_=""}function He(t){let s=t.screen?.presentation;if(!s||s.type==="inline"){D.open&&D.close(),r.parentElement!==n&&n.append(r);return}r.parentElement!==D&&(D.append(r),n.append(D));let l={sm:420,md:640,lg:900};D.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in s?l[s.size]+"px":"100vw"}`,D.setAttribute("aria-label",(z?.screen===t.screen?.content.document.name?z?.label:void 0)??N?.document?.name??t.screen?.content.document.name??"Funnel")}async function wn(t){if(C||$||ce&&(ye()||["running","waiting"].includes(t.status)))return;M=t,Ce&&e.client.pendingCommand?.requestId!==Ce&&(u.hidden=!0,Ce=null);let s=t.locale.startsWith("zh");if(F.textContent=s?"\u56DE\u770B":"History",F.hidden=!e.client.review,k.textContent=V.active?s?"\u8FD4\u56DE\u5F53\u524D":"Return to current":s?"\u8FD4\u56DE":"Back",O.textContent=s?"\u5173\u95ED":"Close",T.textContent=s?"\u91CD\u8BD5":"Retry",Ie(),T.hidden=e.client.pendingCommand===null,q.textContent=t.pendingRequest?s?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?s?"\u7B49\u5F85\u4E2D":"Waiting":"",ie!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(ie=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,le(e.onState,structuredClone(t))),C||$)return;if((!t.pendingRequest||ce&&t.status==="closed")&&["closed","ineligible","failed"].includes(t.status)){se();return}if(t.stopped||e.client.configurationReady===!1){V.stop(),ge(),d?.finish("skipped"),r.hidden=!0,Ee();return}if(r.hidden=!1,V.active){Ee();return}let l=Pe(t),ue=e.client.view;if(ue&&ue.revision>t.revision&&Pe(ue)!==l)return;let Ge=!t.instruction&&!t.pendingRequest&&t.nodeType==="screen"&&["running","waiting"].includes(t.status);l!==L&&(L&&d?.finish("dismissed"),ge(),L=l,pe={...t.answers},Fe.reset());let me=ke(t);if(B===me){r.hidden=!0;return}if(Ge&&!l){r.hidden=!0;let R=Oe(!0,t.locale);!C&&!$&&Q?.key!==me&&($e(),Q={key:me,timeout:setTimeout(()=>{let g=e.client.view;if(!R.active||!g||ke(g)!==me)return;B=me;let ne=new Error("Funnel screen preparation timed out");R.finish("error",ne),ge(),oe(ne)},qe)}),Ee();return}$e();let te=R=>{let g=e.client.view;return!C&&!$&&!Z&&!R.aborted&&e.client.configurationReady!==!1&&!!g&&!g.stopped&&!["closed","ineligible","failed"].includes(g.status)&&Pe(g)===l},ee=(R,g)=>{te(g)&&(B=l,d?.finish("error",R),ge(),r.hidden=!0,oe(R))};if(l||(He(t),t.instruction?.type!=="event"&&t.instruction?.type!=="open_url"&&d?.finish("skipped")),t.screen){let R=t.screen.content;if(!N){let J=t.screen.presentation.type!=="inline",we=Oe(J,t.locale);if(C||$)return;let ae=(y=new AbortController).signal;He(t),h=J?rn(D):Le(r,n),N=I(v,{mode:"live",rendererUrl:e.client.webViewUrl,title:R.document.name,onAction(de,ve={},hn={}){if(V.active||!te(ae)||x!==l)return;pe={...pe,...hn};let In=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:Ne})=>Object.hasOwn(pe,Ne)).map(({variable:Ne})=>[Ne,pe[Ne]]));Re(()=>e.client.submit({operation:"submit",...he(),input:{type:"screen",output:de,answers:In,selection:ve}}))},onAnswers:de=>{V.active||!te(ae)||x!==l||(pe={...pe,...de})},onCustomerDataIntent:de=>{V.active||!te(ae)||x!==l||Fe.intent(de).catch(oe)},onEscape:()=>{!te(ae)||x!==l||V.active||re||K||be()},onError:de=>{let ve=new Error(de);x===l?oe(ve):ee(ve,ae)},onRendered:de=>{if(!(!te(ae)||x===l))try{we.present(ve=>{h?.(),h=void 0,de&&(z={screen:R.document.name,label:de},D.setAttribute("aria-label",de)),J&&(D.showModal(),!ve&&e.loading!=="host"&&tn(D,t.screen.presentation.type)),x=l,Ie()}),te(ae)&&Se.report(l)}catch(ve){ee(ve,ae)}}})}let g={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:pe,values:t.screen.values}},ne=JSON.stringify([R,t.locale,g.parameters,t.screen.inputs,t.screen.values]);if(ne!==U)N.update(R.document,t.locale,g),U=ne,Y=JSON.stringify(g.capabilities),_=JSON.stringify(g.customerData);else{let J=JSON.stringify(g.capabilities);J!==Y&&(N.updateCapabilities(g.capabilities),Y=J),JSON.stringify(g.customerData)!==_&&(N.updateCustomerData(g.customerData),_=JSON.stringify(g.customerData))}let W=N;if(W)try{await(d?.wait(W.ready)??W.ready)}catch(J){y&&ee(J,y.signal)}}else if(t.paywall&&!f){let R=Oe(!0,t.locale);if(C||$)return;let g=(y=new AbortController).signal;He(t);let ne=await w(v,{loading:"host",signal:g,canInteract:()=>te(g)&&!V.active&&!re&&!K,beforeAction:async()=>{G++;try{await je(Se.settled()),u.hidden=!0,Ce=null}finally{G=Math.max(0,G-1)}},start:()=>dn(e.client),onObservationChange:Ee,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:W=>e.onOpenUrl?e.onOpenUrl({receiptId:t.paywall.receiptId,url:W,openIn:"same_window"}):m.defaultView?.location.assign(W),onAction:async W=>{if(V.active)return;let J=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:e.client.view?.revision??t.revision,input:{type:"screen",output:W,answers:{}}});await fe(e.client.view??J.run)},onError:W=>{x===l?oe(W):ee(W,g)}},{present(W){te(g)&&(R.present(()=>{W(),x=l,Ie()}),te(g)&&Se.report(l))},async dismiss(){C||g.aborted||V.active||re||K||!ce&&!te(g)||(ce=!0,await be())}}).catch(W=>(ee(W,g),null));!te(g)&&!(ce&&!C&&!g.aborted)?ne?.host?.destroy():ne&&(f=ne.host,f?.setSuspended(V.active))}if(C||$)return;Ie();let H=t.instruction;if(H&&(H.type==="open_url"||H.type==="event")&&!De.has(H.receiptId)){let R=m.createElement("button");R.type="button",R.textContent=H.type==="open_url"?`${s?"\u524D\u5F80":"Continue to"} ${new URL(H.url).host}`:s?"\u7EE7\u7EED":"Continue",R.onclick=()=>{let g=he(),ne=H.type==="open_url"&&!e.onOpenUrl&&H.openIn==="new_window"?yn(H.url):null;Re(async()=>{let W="success";if(H.type==="open_url")if(e.onOpenUrl)try{W=await e.onOpenUrl({receiptId:H.receiptId,url:H.url,openIn:H.openIn})===!1?"failed":"opened"}catch(we){le(e.onError,we),W="failed"}else W=H.openIn==="new_window"&&!ne?"failed":"opened";if(H.type==="event"){if(!e.onEvent)throw new b("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(H.event)}if(C||e.client.view?.nodeId!==g.nodeId||e.client.view.visit!==g.visit)throw new b("PRECONDITION_FAILED","The client action visit changed");let J=await e.client.submit({operation:"submit",...g,input:{type:"client_action",receiptId:H.receiptId,outcome:W}});return De.add(H.receiptId),H.type==="open_url"&&!e.onOpenUrl&&H.openIn==="same_window"&&m.defaultView?.location.assign(H.url),J})},d?.active?d.present(()=>v.replaceChildren(R)):v.replaceChildren(R)}!t.pendingRequest&&t.status==="completed"&&!De.has(`complete:${t.id}`)&&(De.add(`complete:${t.id}`),le(e.onComplete,structuredClone(t))),Ee()}function yn(t){let s=m.defaultView?.open(t,"_blank")??null;return s&&(s.opener=null),s}function fe(t){return Ie(),c=c.catch(()=>{}).then(async()=>{try{await wn(t)}catch(s){throw d?.active&&(B=ke(t),d.finish("error",s),ge(),r.hidden=!0),s}}),c}let gn=e.client.subscribe(t=>{a||(!ce&&(t.stopped||e.client.configurationReady===!1||L&&x!==L&&(Pe(t)!==L||["closed","ineligible","failed"].includes(t.status)))&&(ge(),d?.finish("dismissed"),r.hidden=!0),fe(t).catch(oe))}),vn=e.client.subscribeError?.(oe);function be(t){if(Z)return Z;if(C||!t&&(re||K))return Promise.resolve();let s=!t&&ye();return!s&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(M=e.client.view,se(),Promise.resolve()):(Z=Re(async()=>{let l=s?await e.client.retry():await e.client.submit({operation:"close",...t??he()});return t&&ze(l),l},!0).then(()=>{let l=e.client.view;l?.status==="closed"&&!ye()&&(M=l,se())}).finally(()=>{Z=null}),Z)}function se(){o?.destroy(),!C&&(C=!0,e.signal?.removeEventListener("abort",se),P?.removeEventListener("abort",se),d?.finish("dismissed"),Je.destroy(),gn(),vn?.(),ge(),V.stop(),D.remove(),r.remove(),p(),le(e.onDismiss,M?structuredClone(M):null))}k.onclick=()=>{if(!k.disabled){if(V.active){V.exit();return}Re(()=>e.client.submit({operation:"back",...he()}))}},F.onclick=()=>{V.open()},O.onclick=()=>{d?.active?d.dismiss():re||be()},T.onclick=()=>{ye()?be():Re(()=>e.client.retry())},D.addEventListener("cancel",t=>{t.preventDefault(),d?.active?d.dismiss():re||be()}),e.signal?.addEventListener("abort",se,{once:!0}),P?.addEventListener("abort",se,{once:!0});try{let t=e.client.view;if(t)((e.client.viewAgeMs??Qe)>=Qe||t.instruction?.type==="evaluate_segment")&&(i=Ue().finally(()=>{i=null})),await fe(t);else{r.hidden=!0;let s=Oe(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(C||$)throw new DOMException("Presentation cancelled","AbortError");let l=await s.wait(e.client.get(),qe);a=!1,await fe(e.client.view??l.run)}}catch(t){throw d?.finish("error",t),se(),t}return{destroy:se,refresh:Ue,get recovery(){let t=Me();if(t)return t;if(!C&&!G&&!ce&&!re&&f){let s=f.recovery;if(s.type!=="native")return s}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(re)return re;let t=Me();if(t)return Promise.resolve(t);let s=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,l=()=>({type:"recover",operationId:s,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let ee=f?.recovery;return Promise.resolve(ee&&ee.type!=="native"&&ee.type!=="cancel"?ee:l())}let ue=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(ee=>ee.operation==="close");if(C&&!(ue||K&&e.client.view?.status==="closed")||G||j||Z||V.active||!f&&!K&&!ue)return Promise.resolve(l());let Ge=f,me=(async()=>{try{if(!K&&ue){let R=await e.client.retry();return await fe(e.client.view??R.run),l()}if(!K){let R=await Ge.prepareFallback();if(R.type!=="native")return R;if(e.client.hasDurableJournal!==!0)return l();K=R}let ee=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(ee.length){let R=ee.find(ne=>ne.operation==="close");if(!R||!X||R.requestId!==X.requestId)return l();let g=await e.client.retry();ze(g),await fe(e.client.view??g.run)}else{let R=e.client.view,g=R?.paywall;if(!R||!g||g.selectionGeneration===void 0||(g.quote?.operationId??null)!==K.operationId||K.operationId!==null&&g.canReselect!==!0)return l();let ne=g.selectionGeneration,W=await e.client.get();await fe(e.client.view??W.run);let J=e.client.view,we=J?.paywall;if(!J||!we||!["running","waiting"].includes(J.status)||J.stopped||J.id!==R.id||J.nodeId!==R.nodeId||J.visit!==R.visit||we.receiptId!==g.receiptId||we.selectionGeneration!==ne||(we.quote?.operationId??null)!==K.operationId||K.operationId!==null&&we.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return l();let ae=he();X={runId:J.id,operationId:K.operationId,revision:ae.revision,requestId:ae.requestId,nodeId:J.nodeId,visit:J.visit,receiptId:we.receiptId,selectionGeneration:ne,acknowledged:!1},await be(ae)}let H=Me();return H?(se(),H):l()}catch(ee){return oe(ee),l()}})();re=me;let te=()=>{re===me&&(re=null)};return me.then(te,te),me},review:V.open,exitReview:V.exit,get unappliedDrafts(){return V.drafts}}}export{mn as a,rt as b};