@tinkerlandai/longplay-sdk 0.10.40 → 0.10.41
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 +11 -0
- package/README.md +56 -1
- package/README.zh-CN.md +5 -1
- package/dist/{ai-usage-DXwAGTxT.d.ts → ai-usage-B-qsCn-k.d.ts} +1 -1
- package/dist/{api-r6FfVQpg.d.ts → api-DpRb_Pd3.d.ts} +52 -0
- package/dist/check-response-SR3PDVGE.js +1 -0
- package/dist/chunk-24Z3THUR.js +1 -0
- package/dist/{chunk-FCDWCQYC.js → chunk-26UXCYBP.js} +1 -1
- package/dist/{chunk-7QDT6DO7.js → chunk-2LERKK7O.js} +1 -1
- package/dist/{chunk-RV6UAUK2.js → chunk-2LUVO7GM.js} +1 -1
- package/dist/{chunk-C2KT5ZFU.js → chunk-2P2YSNYU.js} +1 -1
- package/dist/{chunk-X6ONZGRY.js → chunk-2RUJXZCO.js} +1 -1
- package/dist/chunk-2XF34Q6D.js +1 -0
- package/dist/chunk-4B4RB36N.js +1 -0
- package/dist/chunk-5PNH2FPI.js +1 -0
- package/dist/{chunk-EREQZWGI.js → chunk-6EBS6MLW.js} +1 -1
- package/dist/chunk-6OVMC5BT.js +1 -0
- package/dist/{chunk-ASDJTOGM.js → chunk-6STWY5GX.js} +1 -1
- package/dist/chunk-756SIMZF.js +1 -0
- package/dist/chunk-7IVLNV5H.js +1 -0
- package/dist/chunk-ANXK3B5B.js +1 -0
- package/dist/{chunk-P6C3PNMQ.js → chunk-AQQJPP3P.js} +1 -1
- package/dist/chunk-BWRRZ2NW.js +1 -0
- package/dist/{chunk-O4KXODTJ.js → chunk-CQRSMCCG.js} +1 -1
- package/dist/{chunk-YLPQLD2A.js → chunk-DPEMW2FO.js} +1 -1
- package/dist/chunk-EECTJHI6.js +1 -0
- package/dist/{chunk-CZ4TQCUV.js → chunk-EJSDOSP5.js} +1 -1
- package/dist/{chunk-POCDWUD3.js → chunk-EON4IKWR.js} +1 -1
- package/dist/chunk-EOPKOAR5.js +1 -0
- package/dist/{chunk-QZTTKH2H.js → chunk-FTVNGN6Z.js} +1 -1
- package/dist/{chunk-WLGLQJ6M.js → chunk-G6CWZBT5.js} +1 -1
- package/dist/chunk-GXADA7OV.js +1 -0
- package/dist/{chunk-ORMQJAQE.js → chunk-H26F3IOI.js} +1 -1
- package/dist/{chunk-BYP4KVB3.js → chunk-H7AHDGVU.js} +2 -2
- package/dist/chunk-HGH2X6QM.js +1 -0
- package/dist/chunk-KINNES62.js +1 -0
- package/dist/{chunk-LSPHUA7V.js → chunk-MYDMOAKX.js} +1 -1
- package/dist/chunk-NFY7DKVJ.js +1 -0
- package/dist/{chunk-YY445FBU.js → chunk-O3HLNU6T.js} +1 -1
- package/dist/chunk-OAAS5LJY.js +1 -0
- package/dist/{chunk-2DPNSTCN.js → chunk-OEONV3JY.js} +1 -1
- package/dist/chunk-P6XQC7GG.js +1 -0
- package/dist/chunk-PYLX3WF6.js +1 -0
- package/dist/{chunk-5DZJCFNQ.js → chunk-QJMM37CB.js} +1 -1
- package/dist/{chunk-33ZVZOSC.js → chunk-RQTYIUWP.js} +1 -1
- package/dist/chunk-S4P4UUUF.js +1 -0
- package/dist/{chunk-57GPGWSK.js → chunk-SYHMHKFQ.js} +1 -1
- package/dist/{chunk-67AY54E2.js → chunk-TGPZJ5A7.js} +1 -1
- package/dist/chunk-VILB5M4X.js +1 -0
- package/dist/chunk-VJHURKRY.js +1 -0
- package/dist/{chunk-VC2HPREX.js → chunk-VWRQBQZD.js} +1 -1
- package/dist/chunk-W35FZWGG.js +1 -0
- package/dist/chunk-W3J2SIPY.js +1 -0
- package/dist/chunk-Y2HXKANG.js +1 -0
- package/dist/{configuration-sync-BHrAf-ql.d.ts → configuration-sync-7ruSsSrL.d.ts} +150 -1
- package/dist/content-XYUJFGY2.js +1 -0
- package/dist/funnel-host-purchase-BNS3242X.js +1 -0
- package/dist/{funnel-local-client-DR8OpKGU.d.ts → funnel-local-client-BMxDQWE6.d.ts} +51987 -22983
- package/dist/{funnel-node-evaluation-COxXtZEQ.d.ts → funnel-node-evaluation-COIh1hKs.d.ts} +3 -0
- package/dist/funnel-paywall-prerender-DDQI3GAZ.js +1 -0
- package/dist/{funnel-process-client-C87U4r_G.d.ts → funnel-process-client-DNR9nHs8.d.ts} +7338 -3163
- package/dist/funnel-route-prediction-BT5ZWU54.js +1 -0
- package/dist/funnel-route-source-7ZJMZRID.js +1 -0
- package/dist/funnel-runtime-host-3SSDNG24.js +1 -0
- package/dist/index.d.ts +273 -22
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-YU53UKUN.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +2 -2
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-GEIGP23I.js +1 -0
- package/dist/page.d.ts +1 -1
- package/dist/page.js +1 -1
- package/dist/paywall-YZAEI7TF.js +1 -0
- package/dist/paywall-content-QBSB5NA7.js +1 -0
- package/dist/paywall-session-MHBAZLS7.js +1 -0
- package/dist/popup.d.ts +2 -2
- package/dist/popup.js +1 -1
- package/dist/{presentation-loading-B_v5XZtM.d.ts → presentation-loading-B2OeFzRN.d.ts} +1 -0
- package/dist/react-native.d.ts +6 -6
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-SEJG7A2C.js +1 -0
- package/dist/server.d.ts +34204 -17797
- package/dist/server.js +1 -1
- package/dist/{visual-dom-5LUN4AHO.js → visual-dom-7YYJQ2ZI.js} +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/check-response-DRQCUWDW.js +0 -1
- package/dist/chunk-3NCMYTNG.js +0 -1
- package/dist/chunk-4TEZZZYK.js +0 -1
- package/dist/chunk-6PG3AS3G.js +0 -1
- package/dist/chunk-AZFWG352.js +0 -1
- package/dist/chunk-C3GYAKIU.js +0 -1
- package/dist/chunk-ESAHTG3Y.js +0 -1
- package/dist/chunk-GC6JBIRQ.js +0 -1
- package/dist/chunk-IJKAQNK6.js +0 -1
- package/dist/chunk-IOJVF52Q.js +0 -1
- package/dist/chunk-OOD2VDDP.js +0 -1
- package/dist/chunk-P23JOPR5.js +0 -1
- package/dist/chunk-PJS7M6X3.js +0 -1
- package/dist/chunk-PZOQV6MU.js +0 -1
- package/dist/chunk-RFNIGJOL.js +0 -1
- package/dist/chunk-RULQQ7WI.js +0 -1
- package/dist/chunk-U7GH4VME.js +0 -1
- package/dist/chunk-VOKEZHAH.js +0 -1
- package/dist/chunk-XDOKFAE6.js +0 -1
- package/dist/chunk-Y6HL2IY2.js +0 -1
- package/dist/content-QUEVNSXD.js +0 -1
- package/dist/funnel-host-purchase-LMVMJNUO.js +0 -1
- package/dist/funnel-paywall-prerender-LGUSHEP3.js +0 -1
- package/dist/funnel-runtime-host-H5FM67UC.js +0 -1
- package/dist/merchant-bridge-contracts-LZSQYE3O.js +0 -1
- package/dist/operation-contracts-O7TCDGV4.js +0 -1
- package/dist/paywall-UANWOKKC.js +0 -1
- package/dist/paywall-content-CHPX2P77.js +0 -1
- package/dist/paywall-session-3BNUC5ZE.js +0 -1
- package/dist/screen-renderer-FFVZ64MR.js +0 -1
- /package/dist/{chunk-RGEBK6UF.js → chunk-2ULWP26K.js} +0 -0
- /package/dist/{chunk-OJM6ORHE.js → chunk-4PGYQ2TI.js} +0 -0
- /package/dist/{chunk-CILM5XMH.js → chunk-PBBREFS5.js} +0 -0
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as pn}from"./chunk-
|
|
1
|
+
import{a as pn}from"./chunk-ANXK3B5B.js";import{a as I}from"./chunk-TGPZJ5A7.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-O3HLNU6T.js";import{a as xt}from"./chunk-756SIMZF.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-QJMM37CB.js";import"./chunk-DPEMW2FO.js";import{a as Te,b as ae,c as yt,d as It,e as wt,f as xe,g as vt,h as Me,i as dn,j as ln,k as mn}from"./chunk-P6XQC7GG.js";import{B as V,C as N,d as ft,e as ht,k as gt,l as z,m as St,p as Ct,q as Rt,r as bt,s as At,t as Ot,y as pe,z as Tt}from"./chunk-4B4RB36N.js";import{c as h}from"./chunk-EON4IKWR.js";import"./chunk-H26F3IOI.js";import{a as Et,b as _e}from"./chunk-2LERKK7O.js";import"./chunk-2RUJXZCO.js";import"./chunk-6EBS6MLW.js";import{e as at}from"./chunk-EOPKOAR5.js";import{B as pt,C as de,D as Z,E as lt,J as mt,a as et,e as q,j as Re,k as st,l as ct,q as ut,r as dt,s as be,t as Ae}from"./chunk-OAAS5LJY.js";import{b as Oe}from"./chunk-NFY7DKVJ.js";import{e as ve,i as Ze,l as it}from"./chunk-5PNH2FPI.js";import"./chunk-PYLX3WF6.js";import"./chunk-W35FZWGG.js";import"./chunk-RQTYIUWP.js";import"./chunk-7IVLNV5H.js";import{A as oe,B as tt,C as Se,D as ie,F as se,G as Ce,L as j,N as ce,O as nt,Q as Ee,R as rt,S as ot,e as Ge,f as je,i as we,q as ze,r as Ke,t as an,u as sn,x as cn,y as X,z as W}from"./chunk-VJHURKRY.js";import"./chunk-VILB5M4X.js";import"./chunk-SYHMHKFQ.js";import"./chunk-2XF34Q6D.js";import{a as Ne,b as Le}from"./chunk-26UXCYBP.js";import{o as ue}from"./chunk-KINNES62.js";import"./chunk-Y2HXKANG.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-HGH2X6QM.js";import{c as Ie}from"./chunk-MYDMOAKX.js";import{e as Xe,h as We}from"./chunk-EECTJHI6.js";import{a as c}from"./chunk-G6CWZBT5.js";import{h as Y}from"./chunk-S4P4UUUF.js";import"./chunk-3VUPVXAV.js";import"./chunk-2LUVO7GM.js";import{b as u}from"./chunk-2ULWP26K.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-CQRSMCCG.js";import"./chunk-PBBREFS5.js";import"./chunk-WOT6VMZA.js";var _t=4,Mt=[...tt,"requirement_checks","native_offers","preparations","benefit_claims","authorizations","business_results","checkout_termination"],In=u.enum(Mt),ee=(e,n)=>u.array(e).max(n).refine(t=>new Set(t).size===t.length,"Declarations must be unique"),ke=u.strictObject({...se.shape,bridgeVersion:u.literal(_t),capabilities:ee(In,Mt.length),checkKinds:ee(u.enum(["access","metered","credit"]),3),preparationActions:ee(u.enum(["purchase","subscription_change","refund"]),3),authorizationKinds:ee(u.enum(["auto_topup"]),1),nextActionTypes:ee(u.enum(["redirect","authenticate"]),2),resultEvents:ee(u.enum(["benefit.claimed","authorization.updated"]),2)}).superRefine((e,n)=>{e.capabilities.includes("catalog")!==(e.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(e.capabilities.includes("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare unique supported billing events"});let t=r=>e.capabilities.includes(r),o=(r,a)=>n.addIssue({code:"custom",path:[r],message:a});t("requirement_checks")!==e.checkKinds.length>0&&o("checkKinds","Declare the supported Check kinds"),t("preparations")!==e.preparationActions.length>0&&o("preparationActions","Declare the supported preparation actions"),t("authorizations")!==e.authorizationKinds.length>0&&o("authorizationKinds","Declare the supported authorization kinds"),t("business_results")!==e.resultEvents.length>0&&o("resultEvents","Declare the supported non-financial results");for(let[r,a,s]of[["purchases","purchase","purchase.completed"],["subscription_changes","subscription_change","subscription.change.completed"],["refunds","refund","refund.updated"]])t(r)&&(!t("operation_status")||!t("billing_records")||!t("preparations")||!e.preparationActions.includes(a)||!e.billingEvents.includes(s))&&o("capabilities",`${r} requires preparation, original lookup and its billing result`);t("purchases")&&!e.billingEvents.includes("purchase.closed")&&o("billingEvents","Purchase execution requires its terminal closure result"),t("checkout_termination")&&(!t("operation_status")||!t("billing_records")||!e.billingEvents.includes("purchase.closed"))&&o("capabilities","Checkout termination requires original lookup and purchase.closed"),t("subscription_changes")&&!e.billingEvents.includes("subscription.change.closed")&&o("billingEvents","Subscription change execution requires its terminal closure result");for(let[r,a]of[["benefit_claims","benefit.claimed"],["authorizations","authorization.updated"]])t(r)&&(!t("operation_status")||!t("business_results")||!e.resultEvents.includes(a))&&o("capabilities",`${r} requires original lookup and its non-financial result`)}),K={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":u.strictObject({}),"requirement.check":$e,"operation.prepare":ze,"benefit.claim":Ue,"operation.read":qe,"purchase.terminate":j},wn={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":ke,"requirement.check":Qe,"operation.prepare":Ke,"benefit.claim":Ve,"operation.read":He,"purchase.terminate":j.extend({outcome:u.enum(["requested","already_paid"])})},Gn=u.enum(["bridge.ping","bridge.describe","requirement.check","operation.prepare","benefit.claim","operation.read","purchase.terminate"]);function $(e,n){return u.strictObject({bridgeVersion:u.literal(_t),requestId:u.uuid(),scope:Ce,command:u.literal(e),data:n})}var kt=u.discriminatedUnion("command",[$("bridge.ping",K["bridge.ping"]),$("bridge.describe",K["bridge.describe"]),$("requirement.check",K["requirement.check"]),$("operation.prepare",K["operation.prepare"]),$("benefit.claim",K["benefit.claim"]),$("operation.read",K["operation.read"]),$("purchase.terminate",K["purchase.terminate"])]),Be=u.strictObject({code:u.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:u.string().min(1).max(500),retryable:u.boolean(),recovery:u.string().min(1).max(80),effect:u.enum(["none","unknown"])}).refine(e=>e.effect!=="unknown"||!e.retryable&&e.recovery==="recover_operation","Unknown effects require original-operation recovery");function Bt(e){let n={bridgeVersion:u.literal(4),requestId:u.uuid(),scope:Ce,command:u.literal(e)};return u.union([u.strictObject({...n,data:wn[e]}),u.strictObject({...n,error:Be})])}var Pt="X-Indiana-Bridge-Signature",Q="X-Indiana-Bridge-Key-Id";function vn(e){return new TextEncoder().encode(e)}function Dt(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),n=>n.charCodeAt(0))}function Ft(e,n,t,o){return vn(`indiana-merchant-bridge:${o}
|
|
2
2
|
${n}
|
|
3
3
|
POST
|
|
4
4
|
${W}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as a,c as b}from"./chunk-
|
|
1
|
+
import{b as a,c as b}from"./chunk-4PGYQ2TI.js";import"./chunk-J6KIN4RH.js";import"./chunk-WOT6VMZA.js";export{b as applyVisualVariation,a as safeVisualMutation};
|
package/dist/visual.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as pe,c as fe}from"./chunk-
|
|
1
|
+
import{a as pe,c as fe}from"./chunk-4PGYQ2TI.js";import{b as le}from"./chunk-J6KIN4RH.js";import{a as Ve,b as ce,c as de,d as ue}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-OEONV3JY.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-2P2YSNYU.js";import"./chunk-3VUPVXAV.js";import"./chunk-2LUVO7GM.js";import{b as o}from"./chunk-2ULWP26K.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-CQRSMCCG.js";import"./chunk-PBBREFS5.js";import"./chunk-WOT6VMZA.js";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:le(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=se(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=re(e.deviceIdCookie??"indiana_did"),T=ae(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(de(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=oe(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=ue(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=ce(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b}from"./chunk-7QDT6DO7.js";import"./chunk-Y6HL2IY2.js";import"./chunk-LSPHUA7V.js";import"./chunk-OOD2VDDP.js";import"./chunk-WLGLQJ6M.js";import"./chunk-RULQQ7WI.js";import"./chunk-RGEBK6UF.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
|
package/dist/chunk-3NCMYTNG.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function d(t){let{quote:o,operation:e,requestId:p}=t,a={type:"recover",operationId:e?.operationId??o?.operationId??null,requestId:p};if(t.destroyed||t.pending)return a;if(!e)return o?{type:"cancel",operationId:o.operationId}:a;let r=e.merchantExecution;if(r?.type==="purchase"){if(["succeeded","not_required"].includes(r.paymentStatus))return!["applied","not_applicable"].includes(r.fulfillmentStatus)||e.problem?.phase==="fulfillment"||r.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:r.recordingStatus==="accepted"&&e.status==="complete"&&!e.problem&&!r.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&!e.problem&&!r.problem&&r.checkoutUrl===e.checkoutUrl&&r.checkoutExpiresAt&&Date.parse(r.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(r.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&!e.nativePurchase&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let c=[e.problem,r?.problem],l=c.every(i=>!i||i.phase==="execution"&&i.reason!=="RESULT_UNKNOWN"),u=e.status==="cancelled"&&!c.some(Boolean)&&r?.type==="purchase"&&["pending","not_started","expired"].includes(r.paymentStatus)&&["not_started","not_applicable"].includes(r.fulfillmentStatus);return t.canReselect===!0&&l&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"||!r||r.type==="purchase"&&!["succeeded","not_required"].includes(r.paymentStatus)&&(u||r.recordingStatus==="accepted"&&r.fulfillmentStatus==="not_applicable"))?{type:"native",operationId:e.operationId}:!c.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:l&&t.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!r&&!e.quoteFinalized||r?.type==="purchase"&&["failed","expired"].includes(r.paymentStatus)&&r.fulfillmentStatus==="not_applicable"&&r.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&l&&!e.quoteFinalized&&!r&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:a}function y(t,o=!0){if(!t)return!1;let e=d({quote:t.quote??null,operation:t,requestId:null,pending:!1,destroyed:!1,canReselect:o});return e.type==="complete"||e.type==="native"}function n(t){return t.recovery??{type:"recover",operationId:t.operation?.operationId??t.quote?.operationId??null,requestId:null}}function f(t){return!!(t?.operationId&&(t.type==="checkout"||t.type==="recover"||t.type==="fulfillment"||t.type==="recording"))}async function m(t){let o=n(t);if(o.type==="recover"&&t.quote)try{await t.read(),o=n(t)}catch{return o}if(o.type!=="cancel"&&!(o.type==="recover"&&t.pendingCancellation))return o;try{await t.cancel();let e=n(t);return e.type==="cancel"?{type:"recover",operationId:o.operationId,requestId:null}:e}catch{let e=n(t);return e.type==="recover"?e:{type:"recover",operationId:o.operationId,requestId:null}}}export{d as a,y as b,n as c,f as d,m as e};
|
package/dist/chunk-4TEZZZYK.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as ue,g as se}from"./chunk-RFNIGJOL.js";import{b as on}from"./chunk-X6ONZGRY.js";import{d as tn,e as pe}from"./chunk-EREQZWGI.js";import{c as Be,d as Ke,e as J,l as nn}from"./chunk-P23JOPR5.js";import{$ as de,A as $e,E as Ye,S as Ze,X as We,Y as Xe,Z as $,_ as en,a as j,aa as U,b as qe,c as Me,d as je,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,y as Je}from"./chunk-IOJVF52Q.js";import{b as an}from"./chunk-3NCMYTNG.js";import{b as ne}from"./chunk-PZOQV6MU.js";import{a as W}from"./chunk-FCDWCQYC.js";import{$ as Qe,I as L,J as De,K as Le,Z as He,_ as le,aa as ce,g as Oe,m as Ae,q as Te,z as ae}from"./chunk-XDOKFAE6.js";import{b as D}from"./chunk-OOD2VDDP.js";import{a as f}from"./chunk-WLGLQJ6M.js";import{b as rn}from"./chunk-RV6UAUK2.js";import{b as n}from"./chunk-RGEBK6UF.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-O4KXODTJ.js";import{a as Pe,b as Ne}from"./chunk-CILM5XMH.js";function un(e){return Cn({...e,namespace:"commands",identity:[e.runToken]})}function Cn(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??rn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var sn=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Pn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Nn=n.discriminatedUnion("type",[Ye,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:q.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:We,openIn:Xe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),On={id:q,presentation:Te,outputs:n.array(q).max(250),inputs:ce,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(q,He.nullable())},An=n.strictObject({...On,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:sn,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Pn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:Qe,variables:n.record(n.string(),L),output:L.nullable(),screen:An.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([tn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Nn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),Tn=n.strictObject({scope:D,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),ln=Tn.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var cn="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function dn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var _n=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),kn=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(_n).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=kn.omit({variation:!0,description:!0,iam:!0}),Vn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),pn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(Vn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),jt=n.strictObject({iam:Q,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Dn=n.strictObject({release:Q,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Gt=n.strictObject({scope:D.extend({environmentId:n.uuid()}),release:Q,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Je.optional(),target:Dn})).max(4e3)}),Ut=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Q,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Bt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Kt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Ln=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),mn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Ln.extend({receiptId:n.uuid()})).max(100),payload:pn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(j,j),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),fn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:gn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...fn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...fn,evaluationMode:n.literal("remote")})]),qn=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ze.nullable()}))})});function Mn(e){return gn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Mn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:nn(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function er(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return qn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,jn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var Gn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),L),Un=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:en,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),ar=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:Gn,context:Ie,steps:n.array(Un).min(1).max(he)}).refine(e=>X(e)<=jn,"Segment exceeds its byte budget");var Bn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Y(e){return Array.isArray(e)?e.some(Y):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Y(u):!Bn.test(t))}function yn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Y(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Y(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Y(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Kn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Kn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let I=e.conditions[a.id];if(!I)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:I.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=h.value,o=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function hr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),zn(p,c,d))}function zn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function wr(e,t,u,r=re){return vn(Re(e,r),t,u)}function vn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(L.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(L.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function In(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>yn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),vn(I,O,{attributes:$e({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let R=s.type==="end"?s.output:s.value;if(m=R?.type==="feature"?b(s.id):{...m,port:"value",value:R?.type==="literal"?R.value:R?.type==="variable"?Ue({source:"variable",key:R.key,...R.path?{path:R.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},R&&(m.value===void 0||!je(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:o,result:m}];if(X({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let R=s.type==="coupons"?s.couponIds.map(V=>({type:"reward",id:V})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(R===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=G(s,{value:R});Ge(t.variables,s,_),Object.assign(c,_)}for(let R of m.sticky)d[`${R.next.attributeName}||${R.next.attributeValue}`]=structuredClone(R.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let T=p.get(o);return{steps:a,...!y&&T&&(!we(T)||h(T))?{boundary:{nodeId:o,visit:g}}:{}}}function hn(e,t){let u=ln.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Cr(e){return xe(e,Se)}var Jn=3,$n=2e3;function Hn(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Qn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Jn||!Hn(u))throw u;await new Promise(r=>setTimeout(r,t*$n))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Yn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Qn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Yn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Zn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Zn(e,t,u){return In(e,t,u,Se)}var wn=U.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 f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),bn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.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"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function xn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:bn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let I=await e.write(g.revision,y);if(I!==null){if(!Number.isSafeInteger(I)||I<=g.revision)throw A();t=I;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=bn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,I)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[h,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(I!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((I,h)=>{if(!I&&h!==t||I&&r(I)!==r({...a,schemaVersion:1}))throw A();if(I?.purchase&&I.purchase.generation>o.generation)return Z(I,y);if(I?.purchase&&I.purchase.generation===o.generation&&I.purchase.operationId!==o.operationId)throw A();return g?!I?.purchase||I.purchase.operationId!==o.operationId?Z(I,y):Z(I.command?{...I,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...I,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function jr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function Rn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,I=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,b="Run identity changed during the request"){if(h!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!ie(h.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of I)try{m(structuredClone(r))}catch{}}},identify(h){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(h))throw new f("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return I.add(h),()=>I.delete(h)},reset(){o||(o=!0,a(),g=void 0,r=null,I.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function $r(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Hr(e){let t=ne(e);return t.identify(e.apiKey),t}function Sn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Wn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Fn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function I(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:M(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let R=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Wn(C),V=!1;if(R&&_&&m===t.generation&&i===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});V=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw m===t.generation&&(i===s||p===s)&&_&&(!R||!(C instanceof f)||C.status===void 0||V)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),C}}function h(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return T(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(M(p))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(M(i))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=I(s);d[m]=x;let C=()=>{d[m]===x&&(d[m]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,C){let R=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=R&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==R&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?R:void 0,V=i?.requestId===_?i:p?.requestId===_?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,v=l??m.purchase,P=v?.operation,E=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,S=P?.operationId??v?.quote?.operationId??E?.operationId,F=v?.receiptId??E?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!o||w>=o.generation)){let N={receiptId:F,operationId:S,generation:w},k=an(P,v?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},N,k,_),t.assertCurrent(x),(!o||N.generation>=o.generation)&&(C===void 0||C>=t.readSequence)&&(k?o?.operationId===N.operationId&&(o=void 0):o=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(V):!1},stop(){c=!0},submit:h,settle:T,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Xn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=Rn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?un(e):void 0),a=d&&xn(d),o=Fn({journal:a,state:i,call:T,processIdentity:e.process}),g=0,y=new Map;function I(){g++,y.clear(),t=void 0}async function h(l){let v=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!v&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(v?.operation==="submit"&&v.input.type==="paywall_confirm"){let N=i.view?.paywall;Sn(u,N?.quote?.operationId===v.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=i.generation;i.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),S=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=i.signal,k,K=()=>{},En=new Promise((et,Ce)=>{K=()=>Ce(N.reason),N.addEventListener("abort",K,{once:!0}),k=setTimeout(()=>Ce(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(P),e.session.access())),En])}finally{clearTimeout(k),N.removeEventListener("abort",K)}}i.assertCurrent(P);let F={...l,...S?{customerToken:S}:{}},w=l.operation==="page_experiments"?ye.parse(F):U.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!S?{[cn]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){I(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function T(l,v){let P=t;t=void 0;let E=i.generation,S=()=>i.assertCurrent(E);a&&await o.ready,S();let F=i.view,w=hn(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(S(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let k=await o.observe(l,w,E,v);return(!i.view||w.run.revision>=i.view.revision)&&(v===void 0||v>=i.readSequence)&&(await e.onAcceptedResponse?.(w),S()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,F,v,k)),w}function O(l){let v=i.generation;I();let P=l(),E=()=>{i.generation===v&&I()};return P.then(E,E),P}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function C(l){let v=x.get(l);if(v)return v;let P=_(l);return x.set(l,P),P}let R=!1;async function _(l){let v=await l;if(v.run.instruction?.type!=="evaluate_segment")return v;if(m)return m;R=!0;let P=i.generation,E=(async()=>{for(let S=0;S<32&&v.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return v;let F=v.run;if(v.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Fe(e.configuration,F,{predict:!1});if(P!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return v;if(i.view&&(i.view.revision!==F.revision||i.view.visit!==F.visit||i.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Fe(e.configuration,F).then(({prediction:K})=>{k&&P===i.generation&&!o.closeRequested&&i.view?.id===F.id&&!i.view.stopped&&i.view.nodeId===F.nodeId&&i.view.visit===F.visit&&i.view.revision===F.revision&&(c=K)}).catch(()=>{});try{v=await s({operation:"commit_segment",requestId:dn(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...N})}finally{k=!1,c=null}}}return v})();m=E;try{return await E}finally{m===E&&(m=null)}}let V={get configuration(){return R?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(M(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(M(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return on(e,l)},async pageExperiments(l,v=[]){let P=i.generation;i.assertCurrent(P);let E=i.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let S=mn.parse(await h(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:v})));if(i.assertCurrent(P),S.runId!==E||S.scope.projectId!==i.scope?.projectId||S.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,v){let P=i.generation;l=l&&structuredClone(l),v=v&&{...v},a&&await o.ready,i.assertCurrent(P),v??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let E=JSON.stringify([i.generation,g,l??null,v??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=i.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...v?{purchase:v}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?V.settle(l):o.pending?.requestId===l?C(s(o.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(s(l))},async retry(){if(o.closeFlight)return o.closeFlight;if(o.closing)return s(o.closing);if(o.closeRequested&&o.pending)return V.settle(o.pending.requestId);if(o.inFlight)return C(o.inFlight);if(!o.pending)throw new f("INVALID_REQUEST","No command is pending");let l=o.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let v=i.generation;if(await V.settle(l.requestId),i.assertCurrent(v),!o.pending)return V.get();if(o.pending!==l||o.closeRequested)throw new f("COMMAND_PENDING","The original quote is being recovered")}return C(s(l))},identify(l){let v=i.customerToken?void 0:t;I(),i.identify(l),t=v,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return V}function vo(e,t){return Xn({...e,runToken:"",initialResponse:t})}export{dn as a,sn as b,Nn as c,me as d,Tn as e,ln as f,Dn as g,Gt as h,Ut as i,Bt as j,ye as k,mn as l,te as m,qn as n,er as o,hr as p,wr as q,hn as r,Se as s,Cr as t,Zn as u,bn as v,Z as w,un as x,Cn as y,jr as z,ie as A,Ee as B,$r as C,Hr as D,Sn as E,Xn as F,vo as G};
|
package/dist/chunk-6PG3AS3G.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as G}from"./chunk-U7GH4VME.js";import{b as Z}from"./chunk-FCDWCQYC.js";import{a as j,b as Q,c as x}from"./chunk-LSPHUA7V.js";import{d as l}from"./chunk-OOD2VDDP.js";import{a as L,b as F,c as H}from"./chunk-RULQQ7WI.js";import{b as e}from"./chunk-RGEBK6UF.js";var fe=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],K=e.enum(fe),W=e.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]);var o=e.string().min(1).max(200),c=e.iso.datetime({offset:!0}),i=e.number().int().nonnegative().max(1e8),y=e.string().regex(/^[A-Z]{3}$/),m=e.strictObject({priceId:e.uuid(),productVersionId:e.uuid(),productId:o,quantity:e.number().int().min(1).max(1e6),unitAmountMinor:i,totalMinor:i,interval:e.enum(["week","month","year","one_off"]),intervalCount:e.number().int().min(1).max(52),kind:e.enum(["fixed","prepaid","seat"]),tiers:e.strictObject({mode:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().positive().nullable(),unitAmountMinor:i,flatAmountMinor:i.optional()})).min(2).max(12)}).nullable()}),I=e.strictObject({grantId:e.uuid(),couponId:e.uuid(),amountMinor:i,applicationPolicy:G.optional(),applicableProductIds:e.array(o).min(1).max(100).optional(),terms:e.discriminatedUnion("type",[e.strictObject({type:e.literal("percent"),percentOff:e.number().gt(0).max(100)}),e.strictObject({type:e.literal("amount"),amountOffMinor:i,currency:y})]),duration:e.discriminatedUnion("type",[e.strictObject({type:e.literal("once")}),e.strictObject({type:e.literal("forever")}),e.strictObject({type:e.literal("repeating"),months:e.number().int().min(1).max(36)})])}),E={provider:e.literal("merchant"),executor:e.literal("merchant"),operationId:e.uuid(),customerId:e.uuid(),configurationRevision:e.number().int().nonnegative(),connectionRevision:e.number().int().nonnegative(),currency:y,expiresAt:c},ge=e.strictObject({...E,type:e.literal("purchase"),mode:e.enum(["payment","subscription"]),lineItems:e.array(m).min(1).max(100),catalogAmountMinor:i,nativeDiscountMinor:i.optional(),discount:I.nullable(),trialPeriodDays:e.number().int().min(1).max(730).nullable(),automaticTax:e.boolean()}).refine(t=>t.lineItems.reduce((n,r)=>n+r.totalMinor,0)===t.catalogAmountMinor&&(t.discount?.amountMinor??0)+(t.nativeDiscountMinor??0)<=t.catalogAmountMinor&&new Set(t.lineItems.map(n=>n.priceId)).size===t.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),S=e.strictObject({...E,type:e.literal("subscription_change"),subscriptionId:e.uuid(),merchantSubscriptionId:o,membershipId:e.uuid(),subscriptionAction:e.enum(["update","cancel","schedule","release"]),supersedesOperationId:e.uuid().nullable(),change:e.discriminatedUnion("type",[e.strictObject({type:e.literal("cancel")}),e.strictObject({type:e.literal("uncancel")}),e.strictObject({type:e.literal("plan"),productVersionId:e.uuid()}),e.strictObject({type:e.literal("seats"),licenseKey:o,quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("quantity"),internal_feature_id:e.uuid(),quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("billing_cycle"),billingCycleAnchor:e.union([e.literal("now"),e.number().int().positive()])})]),timing:e.enum(["immediate","renewal"]),effectiveAt:c,creditMinor:i,debitMinor:i,totalMinor:i,discountMinor:i,discount:I.nullable().optional(),taxMinor:i,proration:e.enum(["none","create_prorations","always_invoice"]),lineItems:e.array(m.extend({quantity:e.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:e.array(e.uuid()).max(100),sourceLineItems:e.array(m).min(1).max(100).optional()}),xe=e.strictObject({...E,type:e.literal("refund"),invoiceId:e.uuid(),merchantInvoiceId:o,amountMinor:i.refine(t=>t>0),mode:e.enum(["full","partial"]),entitlementAction:e.enum(["retain","revoke"]),cancelSubscriptions:e.array(o).max(100)}),Y=e.discriminatedUnion("type",[ge,S,xe]);function We(t){let n=new Set;if(t.type==="purchase")n.add(t.mode==="subscription"?"purchase.subscription":"purchase.one_time"),t.lineItems.some(r=>r.kind==="prepaid")&&n.add("purchase.prepaid"),t.lineItems.some(r=>r.kind==="seat")&&n.add("purchase.seats"),t.lineItems.some(r=>r.tiers!==null)&&n.add("purchase.tiered"),t.trialPeriodDays!==null&&n.add("purchase.trial"),t.automaticTax&&n.add("tax.automatic"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`);else if(t.type==="refund")n.add(`refund.${t.mode}`),t.entitlementAction==="revoke"&&n.add("refund.revoke");else{let r=t.change.type;r==="cancel"?n.add(`subscription.cancel.${t.timing}`):r==="uncancel"?n.add("subscription.resume"):r==="plan"?n.add(`subscription.plan.${t.timing}`):n.add(`subscription.${r}`),t.proration!=="none"&&n.add("subscription.proration"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`)}return[...n].sort()}function Xe(t){return t.type==="purchase"?t.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:t.type==="subscription_change"?["subscription.change.completed","subscription.change.closed","subscription.observed",...t.change.type==="cancel"||t.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...t.entitlementAction==="revoke"&&t.cancelSubscriptions.length?["subscription.observed"]:[]]}var ye=e.strictObject({phase:e.enum(["execution","payment","fulfillment","recording"]),code:L,reason:H.optional(),recovery:F,retryable:e.boolean()}).refine(t=>t.reason!=="RESULT_UNKNOWN"||!t.retryable&&t.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ie=e.strictObject({type:e.literal("redirect"),url:e.url().startsWith("https://"),expiresAt:c}),B={operationId:e.uuid(),customerId:e.uuid(),merchantExecutionId:o,fulfillmentStatus:e.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:e.enum(["not_ready","pending","accepted","failed"]),updatedAt:c,problem:ye.nullable(),pollAfterMs:e.number().int().min(1e3).max(6e4).nullable()},T=e.discriminatedUnion("type",[e.strictObject({...B,type:e.literal("purchase"),merchantOrderId:o.nullable(),paymentStatus:e.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:e.url().refine(t=>new URL(t).protocol==="https:").nullable(),checkoutExpiresAt:c.nullable()}).refine(t=>!t.checkoutUrl||["not_started","pending"].includes(t.paymentStatus)&&t.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),e.strictObject({...B,type:e.literal("subscription_change"),status:e.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:o,scheduledFor:c.nullable(),nextAction:Ie.optional()}).refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"A scheduled change retains its future effective time"),e.strictObject({...B,type:e.literal("refund"),status:e.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:o.nullable()}).refine(t=>t.status!=="succeeded"||t.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ee=e.discriminatedUnion("lookup",[e.strictObject({lookup:e.literal("found"),operationId:e.uuid(),customerId:e.uuid(),execution:T,readAt:c}),e.strictObject({lookup:e.literal("not_received"),operationId:e.uuid(),customerId:e.uuid(),execution:e.null(),readAt:c})]).refine(t=>!t.execution||t.execution.operationId===t.operationId&&t.execution.customerId===t.customerId,"Lookup must retain the original Customer and operation"),te=e.strictObject({merchantPriceId:o,productId:o,kind:e.enum(["fixed","prepaid"]),currency:y,unitAmountMinor:i,interval:e.enum(["one_off","day","week","month","year"]),intervalCount:e.number().int().min(1).max(100)}),X={merchantItemId:o,quantity:e.number().int().positive().max(1e6)},Se=t=>t.priceId??JSON.stringify(t.nativePrice),k=e.strictObject({merchantSubscriptionId:o,revision:e.number().int().positive(),status:e.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:c,periodEndsAt:c,cancelAtPeriodEnd:e.boolean(),hasDiscounts:e.boolean(),items:e.array(e.union([e.strictObject({...X,priceId:e.uuid()}),e.strictObject({...X,nativePrice:te})])).min(1).max(100)}).refine(t=>Date.parse(t.periodEndsAt)>Date.parse(t.periodStartsAt)&&new Set(t.items.map(Se)).size===t.items.length&&new Set(t.items.map(n=>n.merchantItemId)).size===t.items.length,"Subscription periods and Price identities must be unambiguous"),J={merchantLineId:o,quantity:e.number().int().nonnegative().max(1e6),subtotalMinor:e.number().int().min(-1e8).max(1e8),discountMinor:i,taxMinor:i,totalMinor:e.number().int().min(-1e8).max(2e8),periodStartsAt:c.nullable(),periodEndsAt:c.nullable()},R=e.strictObject({merchantInvoiceId:o,reason:e.enum(["renewal","adjustment"]).optional(),currency:y,subtotalMinor:i,discountMinor:i,taxMinor:i,totalMinor:i,paidMinor:i,periodStartsAt:c.nullable(),periodEndsAt:c.nullable(),lines:e.array(e.union([e.strictObject({...J,priceId:e.uuid()}),e.strictObject({...J,nativePrice:te})]).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&(t.subtotalMinor<0?t.discountMinor===0&&t.taxMinor===0:t.discountMinor<=t.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&t.discountMinor<=t.subtotalMinor&&t.paidMinor===t.totalMinor&&new Set(t.lines.map(n=>n.merchantLineId)).size===t.lines.length&&t.lines.reduce((n,r)=>n+r.subtotalMinor,0)===t.subtotalMinor&&t.lines.reduce((n,r)=>n+r.discountMinor,0)===t.discountMinor&&t.lines.reduce((n,r)=>n+r.taxMinor,0)===t.taxMinor&&t.lines.reduce((n,r)=>n+r.totalMinor,0)===t.totalMinor,"A paid Invoice retains the complete financial amounts"),p={eventId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:e.uuid(),occurredAt:c},Me=e.strictObject({...p,type:e.literal("purchase.completed"),operationId:e.uuid(),merchantOrderId:o,paymentStatus:e.enum(["paid","trialing","no_payment_required"]),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),_e=e.strictObject({...p,type:e.literal("purchase.closed"),operationId:e.uuid(),status:e.enum(["failed","expired","canceled"])}),Oe=e.strictObject({...p,type:e.literal("subscription.observed"),operationId:e.uuid().nullable(),subscription:k}),ve=e.strictObject({...p,type:e.literal("subscription.change.completed"),operationId:e.uuid(),status:e.enum(["scheduled","applied"]),scheduledFor:c.nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities"),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),Ae=e.strictObject({...p,type:e.literal("subscription.change.closed"),operationId:e.uuid(),merchantSubscriptionId:o,merchantInvoiceId:o.nullable(),status:e.enum(["failed","expired","canceled"])}),je=e.strictObject({...p,type:e.literal("invoice.paid"),merchantSubscriptionId:o.nullable(),invoice:R}),Pe=e.strictObject({...p,type:e.literal("refund.updated"),operationId:e.uuid().nullable(),merchantInvoiceId:o.optional(),merchantRefundId:o,status:e.enum(["pending","succeeded","failed"]),amountMinor:i.refine(t=>t>0),currency:y}),Je=[Me.refine(t=>t.paymentStatus!=="paid"||t.invoice!==null,"A paid purchase includes its Invoice"),_e,Oe.refine(t=>t.operationId===null||t.subscription.items.every(n=>"priceId"in n),"Native Price references cannot replace an operation's quoted Prices"),ve.refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),Ae,je,Pe.refine(t=>t.operationId!==null||t.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var z=e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}),rt=e.object({...z.shape,featureAllowances:e.record(e.uuid(),e.number().int().min(0).max(1e9)),creditAmounts:e.record(e.uuid(),l)}).strict(),it=e.object({id:e.uuid(),planVersionId:e.uuid(),slot:e.string(),cardRequired:e.boolean(),status:e.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),createdAt:e.iso.datetime()}).strict();var qe=e.number().int().positive().max(2e8),ne=e.number().int().min(0).max(2e8),re=t=>t.mode==="partial"==(t.amountMinor!==void 0),P=e.strictObject({mode:e.enum(["full","partial"]),amountMinor:qe.optional(),entitlementAction:e.enum(["retain","revoke"])});var a=e.string().min(1).max(200),b=e.iso.datetime({offset:!0}),f=ne,ie=f.maxValue,C=e.number().int().min(-ie).max(ie),q=e.string().regex(/^[A-Z]{3}$/),oe=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ae=e.array(a).max(100).refine(t=>new Set(t).size===t.length),Ce=e.strictObject({merchantProductId:a,merchantPriceId:a,productVersionId:e.uuid().optional(),quantity:l.refine(t=>/[1-9]/.test(t))}),w={subject:Q,operationId:e.uuid(),configurationRevision:oe,connectionRevision:oe,expiresAt:b},D=e.discriminatedUnion("action",[e.strictObject({...w,action:e.literal("purchase"),mode:e.enum(["payment","subscription"]),currency:q,items:e.array(Ce).min(1).max(100),offerRefs:ae}),e.strictObject({...w,action:e.literal("subscription_change"),currency:q,merchantSubscriptionId:a,change:S.shape.change,timing:S.shape.timing,proration:S.shape.proration,offerRefs:ae}),e.strictObject({...w,action:e.literal("refund"),currency:q,merchantInvoiceId:a,mode:P.shape.mode,amountMinor:P.shape.amountMinor,entitlementAction:P.shape.entitlementAction}).refine(re,"Only a partial refund chooses amountMinor")]),ht=e.strictObject({request:D,requestedAt:b,preparationAllowed:e.boolean()}).refine(t=>!t.preparationAllowed||Date.parse(t.requestedAt)<Date.parse(t.request.expiresAt),"Preparation authority must be within its original validity"),Be=e.strictObject({merchantLineId:a,merchantPriceId:a.nullable(),quantity:l.refine(t=>/[1-9]/.test(t)),subtotalMinor:C,discountMinor:f,taxMinor:f.nullable(),totalMinor:C.nullable()}).refine(t=>t.taxMinor===null==(t.totalMinor===null)&&(t.totalMinor===null||t.totalMinor===t.subtotalMinor-t.discountMinor+t.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),Ee=e.strictObject({items:e.array(e.strictObject({merchantPriceId:a,quantity:l.refine(t=>/[1-9]/.test(t)),interval:m.shape.interval.exclude(["one_off"]),intervalCount:m.shape.intervalCount,amountMinor:m.shape.totalMinor,amountAfterOfferMinor:m.shape.totalMinor.optional()})).min(1).max(100),trial:z.nullable(),discount:I.nullable().optional(),discountExpiresAt:b.nullable().optional(),initialAmountMinor:m.shape.totalMinor.optional()}),ce=e.strictObject({request:D,requestDigest:j,merchantQuoteId:a,quoteTermsDigest:j,termsVersion:a,sourceRevisions:e.array(e.strictObject({reference:a,revision:a})).max(100),observedAt:b,expiresAt:b,currency:q,automaticTax:e.boolean(),lines:e.array(Be).max(100),subscriptionTerms:Ee.nullable(),subtotalMinor:C,discountMinor:f,nativeDiscountMinor:f.optional(),discount:I.nullable().optional(),taxMinor:f.nullable(),totalMinor:C.nullable(),effectiveAt:b.nullable(),expectedEffects:e.array(e.strictObject({reference:a,kind:e.enum(["grant","revoke","change"]),description:e.string().min(1).max(1e3),quantity:l.nullable(),unit:a.nullable()}).refine(t=>t.quantity===null==(t.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:e.array(e.strictObject({reference:a,version:a,summary:e.string().min(1).max(1e3)})).max(20)}),U=ce.superRefine((t,n)=>{let{quoteTermsDigest:r,...u}=t,h=t.lines.every(s=>s.taxMinor!==null),A=t.request.action==="purchase"&&t.request.mode==="subscription"!=(t.subscriptionTerms!==null),be=t.subscriptionTerms!==null&&(t.request.action==="refund"||t.request.action==="subscription_change"&&t.request.change.type==="cancel");(t.requestDigest!==x(t.request)||t.quoteTermsDigest!==x(u)||t.currency!==t.request.currency||A||be||t.lines.length===0&&(t.request.action!=="subscription_change"||t.subtotalMinor!==0||t.discountMinor!==0||t.taxMinor!==0||t.totalMinor!==0)||Date.parse(t.observedAt)>=Date.parse(t.expiresAt)||Date.parse(t.expiresAt)>Date.parse(t.request.expiresAt)||new Set(t.lines.map(s=>s.merchantLineId)).size!==t.lines.length||new Set(t.sourceRevisions.map(s=>s.reference)).size!==t.sourceRevisions.length||new Set(t.requiredConsents.map(s=>s.reference)).size!==t.requiredConsents.length||t.subtotalMinor!==t.lines.reduce((s,g)=>s+g.subtotalMinor,0)||t.discountMinor!==t.lines.reduce((s,g)=>s+g.discountMinor,0)||t.taxMinor!==null!==h||!h&&!t.automaticTax||t.taxMinor===null!=(t.totalMinor===null)||h&&(t.taxMinor!==t.lines.reduce((s,g)=>s+g.taxMinor,0)||t.totalMinor!==t.subtotalMinor-t.discountMinor+t.taxMinor)||t.request.action!=="subscription_change"&&(t.subtotalMinor<0||t.totalMinor!==null&&t.totalMinor<0)||t.request.action==="refund"&&(t.taxMinor===null||t.totalMinor===null||t.totalMinor<=0||t.request.mode==="partial"&&t.totalMinor!==t.request.amountMinor))&&n.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function bt(t,n,r,u){return t.request.operationId===n&&t.request.action===r&&t.currency===u}function ft(t){return x(D.parse(t))}function gt(t){return x(ce.omit({quoteTermsDigest:!0}).parse(t))}var Te=e.strictObject({quoteTermsDigest:j,consents:e.array(e.strictObject({reference:a,version:a})).max(20)});function xt(t){return{quoteTermsDigest:t.quoteTermsDigest,consents:t.requiredConsents.map(({reference:n,version:r})=>({reference:n,version:r}))}}var ke=Te.extend({operationId:e.uuid()}).refine(t=>new Set(t.consents.map(n=>n.reference)).size===t.consents.length);function yt(t,n){let r=U.parse(t),u=ke.parse(n);return u.operationId===r.request.operationId&&u.quoteTermsDigest===r.quoteTermsDigest&&u.consents.length===r.requiredConsents.length&&r.requiredConsents.every(h=>u.consents.some(A=>A.reference===h.reference&&A.version===h.version))}var M=3,Ot="/integrations/indiana",vt="X-Indiana-Merchant-Bridge-Version",Re=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],ze=e.enum(Re),At={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},$=e.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),ue=e.string().regex(/^[A-Za-z0-9_-]{1,64}$/),we=e.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>"AEIMQUYcgkosw048".includes(t.at(-1)),"Use canonical base64url for a 32-byte key"),De=e.strictObject({keyId:ue,signingSecret:we}),Ue=e.string().max(300).superRefine((t,n)=>{try{let r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.port&&r.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(r.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(r.hostname))throw new Error("invalid origin")}catch{n.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(t=>new URL(t).origin),me=e.array(ze).max(10).refine(t=>new Set(t).size===t.length,"Capabilities must be unique"),V=e.strictObject({bridgeVersion:e.literal(M),projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),capabilities:me,catalog:e.enum(["endpoint","static","none"]),billingEvents:e.array(W).max(7),profiles:e.array(K).max(32).refine(t=>new Set(t).size===t.length,"Profiles must be unique")}).superRefine((t,n)=>{let r=u=>t.capabilities.includes(u);r("catalog")!==(t.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(r("billing_records")!==t.billingEvents.length>0||new Set(t.billingEvents).size!==t.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),de=e.strictObject({origin:Ue,requiredCapabilities:me}),$e=e.strictObject({revision:e.number().int().nonnegative(),checkedAt:e.iso.datetime(),outcome:e.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:e.strictObject({ping:e.enum(["passed","failed","not_checked"]),authentication:e.enum(["passed","failed","not_checked"]),catalog:e.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:V.nullable()}).superRefine((t,n)=>{t.outcome==="valid"!=(t.manifest!==null)&&n.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),jt=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),execution:e.enum(["indiana","record_only"]),accountId:e.string().nullable(),revision:e.number().int().nonnegative(),authentication:e.strictObject({keyId:ue}).nullable(),secretStoreConfigured:e.boolean().optional(),connection:de.nullable(),check:$e.nullable()});var se=e.strictObject({projectId:e.uuid(),environmentId:e.uuid()}),Pt=e.discriminatedUnion("action",[se.extend({action:e.literal("save"),revision:e.number().int().nonnegative(),connection:de,authentication:De.optional()}),se.extend({action:e.literal("check"),revision:e.number().int().nonnegative()})]),_=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"])});function qt(t){return e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:$,scope:_,data:t})}var le=e.strictObject({nativeUserId:e.string().min(1).max(128),session:Z.strict()}),pe=e.strictObject({nativeUserId:e.string().min(1).max(128),presentation:e.strictObject({customerId:e.uuid(),decisionId:e.uuid(),offeringVersionId:e.uuid(),paywallVersionId:e.uuid(),variant:e.string().min(1).max(128)}).nullable()}),he=e.strictObject({decisionId:e.uuid(),eventId:e.uuid()}),O=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),Ct=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:e.string().min(1).max(64),scope:_,error:e.strictObject({code:e.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:e.string().min(1).max(500),retryable:e.boolean(),recovery:e.string().min(1).max(80)})});var zt=e.strictObject({scope:_,operationId:e.uuid(),customerId:e.uuid(),confirmedAt:e.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:e.boolean(),instruction:Y,merchantTerms:U.optional()}).refine(t=>t.operationId===t.instruction.operationId&&t.customerId===t.instruction.customerId&&(!t.merchantTerms||t.merchantTerms.request.operationId===t.operationId&&t.merchantTerms.request.subject.customerId===t.customerId&&t.merchantTerms.request.action===t.instruction.type&&t.merchantTerms.currency===t.instruction.currency&&Object.entries(t.scope).every(([n,r])=>t.merchantTerms.request.subject.scope[n]===r)),"Authority must refer to the original Customer and operation"),N=T,d=e.string().min(1).max(120),Ve=e.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Ne=e.strictObject({revision:d,updatedAt:e.iso.datetime(),provider:e.literal("merchant"),items:e.array(e.strictObject({merchantProductId:d,productVersionId:e.uuid(),name:e.string().min(1).max(255),kind:e.enum(["subscription","credit_pack"]),merchantPriceId:d,currency:e.string().regex(/^[a-z]{3}$/),amountMinor:e.number().int().nonnegative().max(1e8),interval:e.enum(["one_time","month","year"]),intervalCount:e.literal(1),includedCredits:e.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:e.enum(["none","month"]),creditPolicyId:d,available:e.boolean()}).superRefine((t,n)=>{(t.kind==="credit_pack"&&(t.interval!=="one_time"||t.creditReset!=="none")||t.kind==="subscription"&&t.interval==="one_time"||t.available&&t.amountMinor===0)&&n.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Le=e.strictObject({customerId:e.uuid(),revision:e.string().min(1).max(128),observedAt:e.iso.datetime(),subscriptions:e.array(e.strictObject({merchantSubscriptionId:d,merchantProductId:d,productVersionId:e.uuid().nullable(),status:e.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:e.iso.datetime().nullable(),currentPeriodEndsAt:e.iso.datetime().nullable(),cancelAtPeriodEnd:e.boolean(),scheduledChange:e.strictObject({effectiveAt:e.iso.datetime(),merchantProductId:d}).nullable()})).max(100),purchaseHistory:e.strictObject({complete:e.boolean(),hasPaidPurchase:e.boolean(),lastPaidAt:e.iso.datetime().nullable()}),balances:e.array(e.strictObject({bucketId:d,key:d,available:Ve,expiresAt:e.iso.datetime().nullable(),nextResetAt:e.iso.datetime().nullable()})).max(100)}),v=e.strictObject({}),Fe={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":v,"session.create":v,"catalog.read":v,"customer.commerce.read":v,"presentation.resolve":v,"presentation.report":he,"purchase.execute":O,"operation.read":O,"subscription.change":O,"refund.execute":O},wt={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":V,"session.create":le,"catalog.read":Ne,"customer.commerce.read":Le,"presentation.resolve":pe,"presentation.report":e.strictObject({queued:e.literal(!0)}),"purchase.execute":N,"operation.read":ee,"subscription.change":N,"refund.execute":N},Dt=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),scope:_,command:$,data:e.unknown()}).superRefine((t,n)=>{Fe[t.command].safeParse(t.data).success||n.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});export{ge as a,S as b,xe as c,We as d,Xe as e,ye as f,T as g,ee as h,p as i,Je as j,z as k,qe as l,ne as m,re as n,P as o,ht as p,U as q,bt as r,ft as s,gt as t,Te as u,xt as v,yt as w,M as x,Ot as y,vt as z,Re as A,At as B,De as C,Ue as D,V as E,_ as F,qt as G,le as H,pe as I,he as J,O as K,Ct as L,zt as M,N,Le as O,Fe as P,wt as Q,Dt as R};
|
package/dist/chunk-AZFWG352.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{A as et,B as fe,F as tt,c as Be,d as Je,e as we,i as qe,j as He,k as $e,o as Ke,r as We}from"./chunk-4TEZZZYK.js";import{a as Xe}from"./chunk-X6ONZGRY.js";import{c as Fe,d as Ne,e as Te,f as _e,g as Le,i as De,m as Me,n as k,o as ke,q as ye,r as N,t as Ge,u as je,v as ze}from"./chunk-P23JOPR5.js";import{I as he,J as Ve,aa as D,u as Ue}from"./chunk-IOJVF52Q.js";import{a as de,b as Qe}from"./chunk-PZOQV6MU.js";import{a as ce}from"./chunk-FCDWCQYC.js";import{J as le}from"./chunk-XDOKFAE6.js";import{b as oe}from"./chunk-OOD2VDDP.js";import{a as L}from"./chunk-WLGLQJ6M.js";import{b as Ze}from"./chunk-3VUPVXAV.js";import{b as Ye}from"./chunk-RV6UAUK2.js";import{b as e}from"./chunk-RGEBK6UF.js";import{c as Ae,f as Pe}from"./chunk-O4KXODTJ.js";var G=e.literal(Ue),ft=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Ie=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),nt=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:Ie}),e.strictObject({type:e.literal("customer"),customer:he,customerData:Ve.optional()})]),ve=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),mt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:ve.omit({runId:!0,requestId:!0}).nullable()}),pt=e.union([Be,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),gt=Je.omit({authenticated:!0}).extend({identity:mt,instruction:pt.nullable()}),ht=e.discriminatedUnion("operation",[D.options[2].omit({customerToken:!0}),D.options[3].omit({customerToken:!0}),D.options[4].omit({customerToken:!0}),D.options[5].omit({customerToken:!0}),D.options[6].omit({customerToken:!0}),D.options[7].omit({customerToken:!0})]),me={contract:G,customerToken:e.string().regex(ce)},rt={contract:G,requestId:e.uuid(),runToken:ft,externalUserId:he.options[1].shape.value},ot=e.discriminatedUnion("operation",[e.strictObject({contract:G,operation:e.literal("describe")}),e.strictObject({contract:G,operation:e.literal("start"),source:nt,funnelId:D.options[0].shape.funnelId,requestId:e.uuid(),locale:D.options[0].shape.locale,parameters:D.options[0].shape.parameters}),qe.omit({operation:!0}).extend({contract:G,operation:e.literal("entry_start"),source:nt}),e.strictObject({...rt,operation:e.literal("bind_customer"),guestToken:Ie,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...rt,operation:e.literal("binding_status"),guestToken:Ie.optional()}),D.options[1].omit({operation:!0,customerToken:!0}).extend({...me,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),D.options[8].omit({operation:!0,customerToken:!0}).extend({...me,operation:e.literal("review")}),$e.omit({customerToken:!0}).extend(me),e.strictObject({...me,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:ht})]),yt=we.omit({run:!0}).extend({contract:G,run:gt,settlement:we.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Nt=He.extend({contract:G}),Tt=e.discriminatedUnion("operation",[ot.options[1].omit({contract:!0,source:!0,requestId:!0}),ot.options[2].omit({contract:!0,source:!0,requestId:!0})]),_t=yt.extend({binding:ve,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Lt=e.discriminatedUnion("state",[e.strictObject({contract:G,scope:oe,state:e.literal("not_accepted")}),e.strictObject({contract:G,scope:oe,state:e.literal("conflict")}),e.strictObject({contract:G,scope:oe,state:e.literal("bound"),binding:ve})]),Dt=e.strictObject({contract:G,scope:oe,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var it=e.string().regex(/^[a-f0-9]{64}$/),wt=Fe.omit({variations:!0,active:!0}).extend({changeId:it,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),at=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:it,experiments:e.array(wt).max(100),savedGroups:Ne}),It=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),kt=e.strictObject({events:e.array(It).min(1).max(20)}),Gt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Ht(r){let o=null,f=null,E=0,b=0,C=new Set,c=null,y=null,d=new Set,v=()=>{for(let s of d)try{s()}catch{}},l={attributes:le.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,w)=>{!C.has(s)&&o&&(!("analyticsConfig"in o)||o.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(w),structuredClone(l.attributes),o.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,w)=>o&&(!("analyticsConfig"in o)||o.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(w),structuredClone(l.attributes),o.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function p(s,w=new Set){return C.has(s)?!c||!c.features[s]||["unknownFeature","cyclicPrerequisite"].includes(c.features[s].source):w.has(s)?!1:(w.add(s),(o?.features[s]?.rules??[]).some(O=>[...O.parentConditions??[],...(O.tracks??[]).flatMap(A=>A.experiment.parentConditions??[])].some(A=>p(A.id,w))))}let x=s=>{if(r.assertUsable?.(o?.generation),!o)throw new Error("Initialize the Feature client before evaluation");if(o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return c?.expiresAt&&Date.parse(c.expiresAt)<=Date.now()&&(c=null,l.features=o.features),C.has(s)?!c||c.expiresAt&&Date.parse(c.expiresAt)<=Date.now()?S():structuredClone(c.features[s]??S()):r.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!c||p(s)?S():structuredClone(Pe(s,l))};async function U(){if(!o||!C.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=b;if(y?.revision===s)return y.loading;let w=E,O=o,A=[...C],R=(async()=>{let h=De.parse(await r.evaluateRemote({attributes:structuredClone(l.attributes),features:A}));if(!(w!==E||s!==b||O!==o)){if(r.assertUsable?.(O.generation),h.generation!==O.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(A.some(P=>!Object.hasOwn(h.features,P))||Object.keys(h.features).some(P=>!C.has(P)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!h.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=le.parse({...l.attributes,...h.merchandiseContext})}c=structuredClone(h),l.features={...O.features,...Object.fromEntries(Object.entries(c.features).map(([P,z])=>[P,{defaultValue:z.value}]))},v()}})();y={revision:s,loading:R};try{await R}finally{y?.loading===R&&(y=null)}}function T(){U().catch(s=>{try{r.onError?.(s)}catch{}})}async function M(){if(f)return f;let s=E,w=(async()=>{let O=await r.load(),A="remoteFeatures"in O?_e.parse(O):null,R=A??Te.parse(O);if(R.scope.projectId!==r.scope.projectId||R.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==E)throw new Error("Feature client was reset");if(r.assertUsable&&o?.generation===R.generation){let{evaluatedAt:P,expiresAt:z,...ie}=o,{evaluatedAt:Y,expiresAt:pe,...j}=R;if(N(ie)!==N(j))throw new Error("Immutable Feature generation changed content");return o.evaluatedAt=R.evaluatedAt,o.expiresAt=R.expiresAt,v(),(!c||c.expiresAt&&Date.parse(c.expiresAt)<=Date.now())&&T(),structuredClone(o)}let h=new Set(A?.remoteFeatures??[]);if([...h].some(P=>Object.hasOwn(R.features,P)))throw new Error("Remote Feature definitions must not be delivered locally");return o&&"analyticsConfig"in o&&"analyticsConfig"in R&&!o.analyticsConfig.experimentViewsEnabled&&A?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),o=structuredClone(R),C=h,c=null,y=null,b++,l.features=o.features,l.savedGroups=Ae(o.savedGroups),l.trackedFeatureUsage={},v(),T(),structuredClone(o)})();f=w;try{return await w}finally{f===w&&(f=null)}}return{init:M,refresh:M,refreshRemote:U,get generation(){return o?.generation??null},get expiresAt(){return o?.expiresAt??null},subscribe(s){return d.add(s),()=>{d.delete(s)}},setAttributes(s){let w=le.parse(s);(l.attributes?.merchandise||l.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=w,b++,c=null,y=null,l.features=o?.features??{},l.trackedFeatureUsage={},v(),T()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,w){let O=x(s).value;return structuredClone(O===null?w:O)},reset(){E++,b++,f=null,y=null,o=null,c=null,C.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),v()}}}var vt=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),K=2*1048576,bt=100;function St(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function st(r,o){let f=o===void 0?St():o,E=new Map,b=0,C=!1,c=!1,y,d;async function v(S){if(!f)return null;let p;try{let x=await Promise.race([Promise.resolve().then(()=>f.getItem(S)),new Promise(U=>{p=setTimeout(()=>U(null),bt)})]);return typeof x=="string"&&x.length<=K&&new TextEncoder().encode(x).byteLength<=K?x:null}catch{return null}finally{clearTimeout(p)}}function l(){if(d)return d;let S=(async()=>{try{let p=await v(`${r}:artifacts`);if(p)return vt.parse(JSON.parse(p))}catch{}return{}})();return d=S,S.finally(()=>{d===S&&(d=void 0)}),S}return{async readManifest(){return v(r)},writeManifest(S){!f||S.length>K||new TextEncoder().encode(S).byteLength>K||(y=S,!c&&(c=!0,Promise.resolve().then(async()=>{try{for(;y!==void 0;){let p=y;try{await f.setItem(r,p)}catch{}y===p&&(y=void 0)}}finally{c=!1}})))},async readArtifact(S){let p=(await l())[S],x=Date.now();return p&&x>=p.at&&x-p.at<=k.retentionMs?p.text:void 0},writeArtifact(S,p){if(!f||p.length>K)return;let x=E.get(S);if(x?.text===p||!x&&E.size>=128)return;let U=new TextEncoder().encode(p).byteLength;b-(x?.byteLength??0)+U>K||(E.set(S,{text:p,byteLength:U}),b+=U-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;E.size;){let T=new Map(E);try{let M={...await l()},s=Date.now();for(let[R,h]of T)M[R]={at:s,text:h.text};let w={},O=2,A=0;for(let[R,h]of Object.entries(M).sort(([,P],[,z])=>z.at-P.at)){if(h.at>s||s-h.at>k.retentionMs)continue;let P=new TextEncoder().encode(JSON.stringify({[R]:h})).byteLength;O+P>K||A>=128||(w[R]=h,O+=P,A++)}await f.setItem(`${r}:artifacts`,JSON.stringify(w))}catch{}finally{for(let[M,s]of T)E.get(M)===s&&(E.delete(M),b-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,o)=>new L(r,o),q=()=>performance.now(),ut=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function ln(r){let o=ke.parse(r.scope),f=new de(r.origin??Ye);if(f.username||f.password||f.search||f.hash||f.pathname!=="/"||f.protocol!=="https:"&&!(f.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(f.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let E=new Set([f.origin,...(r.assetOrigins??[]).map(n=>{let t=new de(n);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return t.origin})]),b=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${o.environmentId}`,c=`indiana:configuration:1:${f.origin}:${N(o)}`,y=st(c,r.storage),d,v=0,l=0,S=!1,p=!1,x=0,U=0,T,M,s,w,O=0,A=new Set,R=new Set,h=new Map,P=new Map,z=0,ie=!1;function Y(){for(let n of A)try{n()}catch{}}function pe(n){try{r.onError?.(n)}catch{}}let j=()=>!p&&!S&&!!d&&q()<v&&Date.now()<l;function ne(){if(!j())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function be(n,t,i){if(!h.has(n)){for(;h.size&&(h.size>=128||z+i>k.maxCacheBytes);){let a=h.entries().next().value;z-=a[1].byteLength,h.delete(a[0])}h.set(n,{text:t,byteLength:i}),z+=i}}function Se(n,t,i){return Ze(n,t,{signal:i,error:a=>u("INVALID_RESPONSE",a==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function xe(n){let t=new de(n,f);if(!E.has(t.origin)||t.username||t.password||t.hash||t.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return t.href}async function ge(n,t,i=!1){let a=await b(xe(n),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:t,headers:{}});if(a.status===429){let g=a.headers.get("retry-after")??"";O=/^\d+$/.test(g)?Number(g)*1e3:Math.max(0,Date.parse(g)-Date.now())||15e3}if(!a.ok&&a.status!==304)throw u(`CONFIGURATION_HTTP_${a.status}`,"Configuration synchronization failed");return a}function lt(n,t,i){let a=Date.parse(n.headers.get("x-indiana-config-validated-at")??""),g=Date.parse(n.headers.get("x-indiana-config-valid-until")??""),I=Date.parse(n.headers.get("date")??""),m=n.headers.get("age"),V=m!==null&&/^\d+(\.\d+)?$/.test(m)?Number(m)*1e3:NaN;if(![a,g,I,V].every(Number.isFinite)||g<=a||g-a>k.maxControlAgeMs||a>I+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let F=Math.min(g-a,i.maxControlAgeSeconds*1e3,k.maxControlAgeMs)-Math.max(V,I-a,0)-(q()-t);if(F<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return q()+F}function ae(){if(clearTimeout(s),clearTimeout(w),p||!A.size||(j()&&(w=setTimeout(()=>{j()?ae():Y()},Math.max(1,v-q())),ut(w)),typeof document<"u"&&document.visibilityState==="hidden"))return;let n=U?Math.min(15e3,1e3*2**Math.min(U-1,4)):Math.min(15e3,(d?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{Q().catch(pe)},Math.max(O,n*(.8+Math.random()*.2))),ut(s)}async function Q(){if(p)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(T)return T;let n=x,t=new AbortController;M=t;let i=(async()=>{if(!ie){ie=!0;try{let ue=await y.readManifest();if(ue&&!d){let J=ye.parse(JSON.parse(ue));N(J.scope)===N(o)&&(d=J)}}catch{}}t.signal.throwIfAborted();let m=d,V=q(),_=await ge(C,t.signal);_.status===304&&(!m||!_.headers.has("x-indiana-config-validated-at")||!_.headers.has("x-indiana-config-valid-until")||!_.headers.has("age"))&&(_=await ge(C,t.signal));let F=_.status===304?m:ye.parse(JSON.parse(await Se(_,k.maxManifestBytes,t.signal))),{generation:ee,...te}=F,B=_.headers.get("etag");if(N(F.scope)!==N(o)||Ge(te)!==ee||B!==`"${ee}"`&&B!==`W/"${ee}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(m&&(F.revision<m.revision||F.revision===m.revision&&F.generation!==m.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ue,J]of Object.entries(m?.funnels??{})){let $=F.funnels[ue];if($&&($.controlRevision<J.controlRevision||$.evaluationRevision<J.evaluationRevision||$.controlRevision===J.controlRevision&&$.state!==J.state||$.evaluationRevision===J.evaluationRevision&&$.evaluationMode!==J.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let H=lt(_,V,F.policy);if(t.signal.throwIfAborted(),n!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return d=F,v=H,l=Date.now()+Math.max(0,H-q()),S=!1,U=0,O=0,y.writeManifest(N(F)),Y(),structuredClone(F)})(),a=setTimeout(()=>t.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),k.initializationMs),g=new Promise((m,V)=>t.signal.addEventListener("abort",()=>V(t.signal.reason),{once:!0})),I=Promise.race([i,g]).catch(m=>{throw U++,(m instanceof e.ZodError||m instanceof SyntaxError||m instanceof L&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(m.code))&&(v=0,S=!0,Y()),m}).finally(()=>{clearTimeout(a),T===I&&(T=void 0),ae()});return T=I,I}async function se(n){let t=n.sha256,i=te=>Xe(te,n);xe(n.url);let a=h.get(t);if(a){if(a.byteLength!==n.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return h.delete(t),h.set(t,a),a.text}let g=P.get(t);if(g){if(g.byteLength!==n.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return g.promise}let I=new AbortController;R.add(I);let m=x,V=(async()=>{try{let H=await y.readArtifact(t);if(H&&i(H)){if(I.signal.throwIfAborted(),p||m!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return be(t,H,n.byteLength),H}}catch{}I.signal.throwIfAborted();let te=await ge(n.url,I.signal,!0),B=await Se(te,n.byteLength,I.signal);if(!i(B))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(p||m!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return be(t,B,n.byteLength),y.writeArtifact(t,B),B})(),_=setTimeout(()=>I.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),k.initializationMs),F=new Promise((te,B)=>I.signal.addEventListener("abort",()=>B(I.signal.reason),{once:!0})),ee=Promise.race([V,F]).finally(()=>{clearTimeout(_),R.delete(I),P.delete(t)});return P.set(t,{promise:ee,byteLength:n.byteLength}),ee}async function re(){return j()||await Q(),ne(),d}async function W(n){let t,i=new Promise((a,g)=>{t=setTimeout(()=>g(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),k.initializationMs)});try{return await Promise.race([n(),i])}finally{clearTimeout(t)}}function Z(n,t){if(ne(),d?.generation!==n.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(t&&d.funnels[t]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Ee(n){let t=n.gb.features;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=n.artifacts[t];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let a=Le.parse(JSON.parse(await se(i)));if(N(a.scope)!==N({projectId:o.projectId,environment:o.environment})||a.generation!==i.generation||a.remoteFeatures.some(g=>Object.hasOwn(a.features,g)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Z(n),{...a,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,v-q())).toISOString()}}async function Ce(n,t){let i=await re(),a=i.funnels[n];t&&(!a||a.evaluationMode==="local"&&!a.versions[t])&&(T&&await T,i=await Q()),Z(i,n);let g=i.funnels[n];if(g.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let I=t??g.currentVersionId,m=g.versions[I];if(!m)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[m.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[V,_]=await Promise.all([se(i.artifacts[m.artifact]).then(F=>ze(JSON.parse(F))),g.evaluationMode==="local"?Ee(i):void 0]);if(_&&N(je(V,_))!==N(m.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Z(i,n),{document:V,growth:_,versionId:I,control:structuredClone(g),manifest:structuredClone(i)}}async function Re(n,t){try{return await Ce(n,t)}catch(i){if(!(i instanceof L)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&j()))throw i;let a=d?.generation;if(T&&await T,await Q(),i.code!=="CONFIGURATION_CHANGED"&&d?.generation===a)throw i;return Ce(n,t)}}function X(){if(j()||Y(),typeof document<"u"&&document.visibilityState==="hidden"){ae();return}Q().catch(pe)}function dt(n){if(p)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return A.add(n),A.size===1&&(typeof window<"u"&&(window.addEventListener("online",X),window.addEventListener("focus",X),document.addEventListener("visibilitychange",X)),ae()),()=>{A.delete(n),A.size||(clearTimeout(s),clearTimeout(w),Oe())}}function Oe(){typeof window<"u"&&(window.removeEventListener("online",X),window.removeEventListener("focus",X),document.removeEventListener("visibilitychange",X))}return{scope:Object.freeze({...o}),refresh:Q,subscribe:dt,assertFresh:ne,assertFeatures(n){ne();let t=d.gb.features;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(n!==void 0&&d.artifacts[t].generation!==n)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return j()},get snapshot(){return d?structuredClone(d):null},get remainingMs(){return j()?Math.max(0,v-q()):0},async features(){return W(async()=>Ee(await re()))},pageExperiments:()=>W(async()=>{let n=await re(),t=n.gb.pageExperiments;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=n.artifacts[t];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let a=at.parse(JSON.parse(await se(i)));if(a.environmentId!==o.environmentId||a.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return Z(n),a}),funnel:(n,t)=>W(()=>Re(n,t)),funnelControl:n=>W(async()=>{let t=await re();return Z(t,n),structuredClone(t.funnels[n])}),paywall:(n,t)=>W(async()=>{let i=await re(),a=i.paywalls?.[n];if(!a||!t&&a.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let g=t??a.currentVersionId,I=a.versions[g],m=I&&i.artifacts[I.artifact];if(!m||m.kind!=="paywall"||m.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let V=Me.parse(JSON.parse(await se(m)));return Z(i),{document:V,versionId:g,version:I.version,control:structuredClone(a),manifest:structuredClone(i)}}),async localFunnel(n,t){let i=await W(()=>Re(n,t));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:a,remoteFeatures:g,...I}=i.growth;return Ke({scope:{projectId:o.projectId,environment:o.environment},funnelId:n,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:I})},assertFunnel(n,t,i){ne();let a=d.funnels[n];if(!a||a.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(a.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(t!==void 0&&a.controlRevision!==t)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!a.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!p){p=!0,x++,v=0,M?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(w),Oe(),Y(),A.clear();for(let n of R)n.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));h.clear(),z=0}}}}function ct(r){let o=ce.test(r.apiKey);if(typeof window<"u"&&!o)throw new L("SERVER_ONLY","Funnel starts are issued by your backend");if(!o&&!fe.test(r.apiKey))throw new L("INVALID_TOKEN","A customer credential or server API key is required");return{async start(f){let E=D.safeParse({...f,operation:"start"});if(!E.success||E.data.operation!=="start"||(o?E.data.customer!==void 0:E.data.customer===void 0))throw new L("INVALID_REQUEST","Invalid current Funnel start");let b=E.data,C=Qe({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let c=We(r,await C.request("funnels",b));if(!c.runToken)throw new L("INVALID_RESPONSE","Funnel start credentials are missing");if(c.run.source.id!==b.funnelId||c.run.locale!==(b.locale??"en")||!et(c.run.parameters,b.parameters??{})||(b.customer?!c.customerId||b.customer.type==="id"&&c.customerId!==b.customer.value:c.customerId!==void 0))throw new L("INVALID_RESPONSE","Funnel start contract changed");return{...c,runToken:c.runToken}}finally{C.dispose()}}}}async function En(r){r={...r};let o=r.configuration;if(!o)throw new L("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let f={projectId:o.scope.projectId,environment:o.scope.environment};if(r.scope&&N(f)!==N(r.scope))throw new L("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await o.funnelControl(r.funnelId)).evaluationMode!=="local")throw new L("EVALUATION_MODE","This Funnel uses Remote evaluation");let b=fe.test(r.credential);if(b?!r.customerId:r.customerId!==void 0)throw new L("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=ct({...r,scope:f,apiKey:r.credential}),c=(y,d)=>{let v=tt({...r,scope:f,runToken:y,initialResponse:d,...b?{serverKey:r.credential}:{}});return b||v.identify(r.credential),v};return{async start(y){let d=await C.start({...y,funnelId:r.funnelId,...b?{customer:{type:"id",value:r.customerId}}:{}}),v=c(d.runToken,d),l=await v.get();return{...d,...l,controller:v}},async restore(y){let d=c(y),v=await d.get();if(v.run.source.id!==r.funnelId)throw d.reset(),new L("SCOPE_MISMATCH","Run belongs to another Funnel");return{...v,runToken:y,controller:d}}}}export{ot as a,yt as b,Nt as c,Tt as d,_t as e,Lt as f,Dt as g,Ht as h,ln as i,ct as j,En as k};
|
package/dist/chunk-C3GYAKIU.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{e as P}from"./chunk-5DZJCFNQ.js";import{c as V}from"./chunk-POCDWUD3.js";import{b as j}from"./chunk-7QDT6DO7.js";import{v as L}from"./chunk-6PG3AS3G.js";import{b as x}from"./chunk-X6ONZGRY.js";import{a as K}from"./chunk-3NCMYTNG.js";import{b as U}from"./chunk-33ZVZOSC.js";import{d as H,e as W,f as B,g as F}from"./chunk-VOKEZHAH.js";import{b as J}from"./chunk-PZOQV6MU.js";import{a as M}from"./chunk-FCDWCQYC.js";import{ea as G}from"./chunk-XDOKFAE6.js";import{a as l}from"./chunk-WLGLQJ6M.js";import{a as $}from"./chunk-DSPLGTQI.js";function X(w){let r=[...new Set(w.map(({path:a})=>{let m=a.map(String).join(".");return m.startsWith("selector")?"paywallId or paywallVersionId":m||"input"}))],O=r.includes("locale")?` Pass locale, the Customer's language such as "en" or "zh-CN".`:"";return new l("INVALID_REQUEST",`createPaywallSession input is invalid: ${r.join(", ")}.${O}`)}async function de(w,r){if(!M.test(r.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");if(w.session&&w.session.peek()!==r.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let O=P.resolvePaywall.request.safeParse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,selector:r.paywallVersionId?{type:"version",versionId:r.paywallVersionId}:{type:"paywall",paywallId:r.paywallId},commerce:r.commerce,locale:r.locale,...r.requirement?{requirement:r.requirement}:{}});if(!O.success)throw X(O.error.issues);let a=O.data,m=J(w);w.session||m.identify(r.customerToken);let t=null,g=!1,_=new AbortController,c=null,u=null,v=null,h=null,R=null,d=null,f=null,N=0,C=null,k="",E=0,b=new Map,q=new Set;function S(){if(g)throw new l("IDENTITY_CHANGED","Paywall is closed")}function Q(){let e=JSON.stringify([N,f!==null]);if(!C||e!==k){k=e;let n=z(++E);C=n;let i=()=>{C===n&&(C=null)};n.then(i,i)}return C.then(n=>structuredClone(n))}async function z(e){S();let n=P.resolvePaywall,i=await V(m.request,n,{...a,selector:t?{type:"version",versionId:t.id}:a.selector});j(a,i.paywall.check,i.scope);let s=await x(w,i.paywall);if(S(),r.paywallVersionId?s.id!==r.paywallVersionId:s.paywallId!==r.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(t&&(!H(s,t)||s.paywallId!==t.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(e!==E)return structuredClone(t??s);t=s;for(let I of q)$(I,structuredClone(t));return structuredClone(t)}async function T(e){if(S(),h&&e!=="read")throw new l("COMMAND_PENDING","Wait for the original quote");if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let n=c;if(e!=="read"){if(f){if(d===e)return f;throw new l("COMMAND_PENDING","Wait for the original purchase command")}if(d&&d!==e)throw new l("COMMAND_PENDING","Read the original purchase before changing an uncertain command");d=e,N++,E++}let i=d,s=N,I=e==="read"&&f===null,p=JSON.stringify([n.operationId,s,f!==null]);if(e==="read"&&b.has(p))return b.get(p).then(o=>structuredClone(o));let A=e==="read"?P.readSubscriptionOperation:P.attach,y=(async()=>{let o=await V(m.request,A,{operationId:n.operationId,...e==="read"?{}:{intent:e},...e==="confirm"&&n.merchantTerms?{merchantConfirmation:L(n.merchantTerms)}:{}});return W(o.operation,{operationId:n.operationId,currency:a.commerce.currency},"The purchase operation changed"),S(),c?.operationId!==n.operationId?structuredClone(o.operation):(u=F(u,o.operation),(e!=="read"||I&&f===null)&&N===s&&d===i&&(d=null),structuredClone(u))})();if(e!=="read"){f=y;let o=()=>{f===y&&(f=null)};y.then(o,o)}else{b.set(p,y);let o=()=>{b.get(p)===y&&b.delete(p)};y.then(o,o)}return y.then(o=>structuredClone(o))}let D={signal:_.signal,get view(){return t?structuredClone(t):null},get quote(){return c?structuredClone(c):null},get operation(){return u?structuredClone(u):null},get webViewUrl(){return"bundled"},get locale(){return a.locale},get recovery(){return K({quote:c,operation:u,requestId:R,pending:h!==null||d!==null,destroyed:g})},get pendingCancellation(){return!g&&d==="cancel"},refresh:Q,subscribe(e){return g?()=>{}:(q.add(e),()=>q.delete(e))},async preview(e){if(S(),!t)throw new l("INVALID_REQUEST","Load the Paywall first");let n=t.document.buttons[e.actionId];if(n?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let i=U(n.product,e.selection,t.capabilities);if(!i)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let s=G(t.document.screen,i,e.selection,t.capabilities),I=P.previewAttach.request.parse({funnelId:a.funnelId,funnelVersionId:a.funnelVersionId,requestId:e.requestId,plans:[{productVersionId:i,...Object.keys(s).length?{featureQuantities:s}:{}}],provider:a.commerce.provider,currency:a.commerce.currency,...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{}}),p=JSON.stringify(I);if(v&&v!==p&&(h||d||!u||u.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(v===p){if(h)return h;if(c)return structuredClone(c)}v!==p&&(c=null,u=null),v=p,R=I.requestId;let A=(async()=>{let y=P.previewAttach,o=await V(m.request,y,I);return S(),B(o.quote,{productVersionId:i,featureQuantities:s,currency:a.commerce.currency,provider:a.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=o.quote,u=null,structuredClone(c)})();h=A;try{return await A}finally{h===A&&(h=null)}},confirm:()=>T("confirm"),cancel:()=>T("cancel"),read:()=>T("read"),destroy(){g||(g=!0,_.abort(),q.clear(),b.clear(),Y?.(),m.dispose(),t=null,c=null,u=null,v=null,R=null)}},Y=w.session?.subscribeIdentity(D.destroy);try{return await Q(),D}catch(e){throw D.destroy(),e}}export{de as a};
|
package/dist/chunk-ESAHTG3Y.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as ee,d as ne}from"./chunk-VOKEZHAH.js";import{a as Z}from"./chunk-WLGLQJ6M.js";import{a as b}from"./chunk-DSPLGTQI.js";var ue=5*6e4,pe=15e3,re=new WeakMap;function me(t){return re.get(t)}var E=t=>Array.isArray(t)?t.map(E):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(n=>[n,E(t[n])])):t,ae=(t,n)=>JSON.stringify(E(t))===JSON.stringify(E(n)),te=t=>JSON.stringify(E([t.funnelId,t.locale??null,t.parameters??{}])),fe=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","confirmOnHostedCheckout","resolveOfferId","onOpenUrl","onEvent","onAction","onComplete","onError"];function he(t,n){let V=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),y,j="",T=n.start instanceof Promise?void 0:V(n.start),O=e=>e?.parameters?.commerce,_=n.maxAgeMs??ue,J=new AbortController,d=AbortSignal.any([J.signal,n.client.identitySignal,...n.signal?[n.signal]:[]]),F=()=>r("released","aborted"),a="preparing",U,k=0,g=null,p=null,f=null,u=null,l=null,A=new Set,v=new Map,N,G=new Promise(e=>N=e),D,oe=new Promise(e=>D=e);function I(e,o){a!==e&&(a=e,U=o,b(n.onState,e))}function le(){d.removeEventListener("abort",F),R(),p?.destroy(),p=null,g?.remove(),g=null,f=null}function r(e,o){["adopted","unavailable","released","closed"].includes(a)||(I(e,o),le(),N(!1),D(null))}let q=e=>`error:${e?.code??e?.name??"unknown"}`,M=t.ownerDocument.defaultView,C=!0,W=null,h=!1,se=e=>e.storageArea===M?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),K=e=>{se(e)&&H()},ie=n.client.subscribe(()=>H());function R(){C&&(C=!1,M?.removeEventListener("storage",K),ie())}let B=()=>C&&(a==="ready"||a==="preparing");function X(e){(a==="ready"||a==="preparing")&&r("unavailable",e)}function H(){if(a==="ready"&&Date.now()-k>=_)return R();h=!0,W??=(async()=>{for(;h&&y&&B();){h=!1;try{await n.client.retained()==="pending"&&X("purchase_pending")}catch(e){d.aborted?r("released","aborted"):X(q(e))}}})().finally(()=>{W=null,h&&y&&B()&&H()})}M?.addEventListener("storage",K),d.addEventListener("abort",F,{once:!0});let $=n.client.findPurchase();$.catch(()=>{});async function P(){let e=await oe;if(!e)throw new Z("PURCHASE_PENDING","The purchase did not start; open it again");return e}let ce={get view(){return l?l.view:u},get signal(){return l?.signal??n.client.identitySignal},get quote(){return l?.quote??null},get operation(){return l?.operation??null},webViewUrl:"bundled",get canReselect(){return l?.canReselect},get recovery(){return l?.recovery},get pendingCancellation(){return l?.pendingCancellation},subscribe(e){return v.set(e,l?.subscribe?.(e)??(()=>{})),()=>{v.get(e)?.(),v.delete(e)}},refresh:async()=>l?l.refresh():structuredClone(u),preview:async e=>(await P()).preview(e),confirm:async()=>(await P()).confirm(),cancel:async()=>(await P()).cancel(),read:async()=>(await P()).read(),destroy(){l?.destroy()}},s={options:{},handoff:{}},z={loading:"host",focusAtReveal:!0,signal:n.client.identitySignal,start:async()=>ce,canInteract:()=>s.options.canInteract?s.options.canInteract():!["unavailable","released","closed"].includes(a),async beforeAction(){let e=a!=="adopted",o=u?.capabilities,i=await P();if(e&&!ae(i.view?.capabilities,o))throw new ee;await s.options.beforeAction?.()}};for(let e of fe)Object.defineProperty(z,e,{enumerable:!0,get:()=>s.options[e]});function x(){a!=="preparing"||!f||!p||!y||(I("ready"),N(!0))}let de={present(e){if(s.handoff.present)return s.handoff.present(e);a==="preparing"&&(f=e,k=Date.now(),x())},async dismiss(){if(s.handoff.dismiss)return s.handoff.dismiss();r("closed");for(let e of[...A])b(e)},quoteError(e){s.handoff.quoteError?s.handoff.quoteError(e):b(s.options.onError,e)}};(async()=>{try{let{showPaywall:e}=await import("./paywall-UANWOKKC.js");if(d.throwIfAborted(),a!=="preparing")return;let o=n.commerce??O(T),i=n.locale??T?.locale;if(!o)return r("unavailable","commerce_missing");if(!i)return r("unavailable","locale_missing");if(u=await n.client.readPaywall({paywallVersionId:n.paywallVersionId,paywallId:n.paywallId,commerce:o,locale:i}),d.throwIfAborted(),a!=="preparing")return;let m=Object.values(u.capabilities.plans);if(Object.values(u.document.buttons).some(c=>c.type==="checkout")&&m.length===0||m.some(c=>!c.available))return r("unavailable","plan_unavailable");g=t.ownerDocument.createElement("div"),t.append(g);let L=setTimeout(()=>a==="preparing"&&r("unavailable","timeout"),pe);G.then(()=>clearTimeout(L));let S=await e(g,z,de);if(!S.host||d.aborted||a!=="preparing"){S.host?.destroy(),r(d.aborted?"released":"unavailable","error");return}p=S.host,x()}catch(e){r(d.aborted?"released":"unavailable",q(e))}})(),Promise.resolve(n.start).then(async e=>{if(!e)return r("unavailable","gated");let o=V(e);if(!ae(O(o),n.commerce??O(o))||n.locale!==void 0&&o.locale!==n.locale)return r("unavailable","start_mismatch");try{let i=await $,m=i==="pending"?"purchase_pending":i==="found"?"original_purchase":i==="blocked"?"purchase_blocked":void 0;if(m)return r("unavailable",m);if(a!=="preparing")return;if(C&&(h=!1,await n.client.retained()==="pending"))return r("unavailable","purchase_pending")}catch(i){return r(d.aborted?"released":"unavailable",q(i))}a==="preparing"&&(y=o,j=te(o),x(),h&&H())},()=>r("unavailable","gated"));let Q={get state(){return a},get reason(){return U},ready:G,get start(){return y},matches:e=>!!y&&te(e)===j,open(){if(a==="preparing")return"pending";if(a!=="ready"||!f)return!1;if(Date.now()-k>=_)return r("unavailable","expired"),!1;let e=f;return f=null,R(),I("shown"),e(),"shown"},destroy(){J.abort()}};return re.set(Q,{onClose(e){return a==="closed"?(b(e),()=>{}):(A.add(e),()=>{A.delete(e)})},claim(){R()},async adopt(e,o){let i=e.paywall?.resolution,m=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(a!=="shown"||!p||!u||!i||!m||e.source.id!==y?.funnelId||!["running","waiting"].includes(e.status)||!ne(i,u))return null;let w;try{w=await o.start()}catch{return null}if(a!=="shown"||!p)return w.destroy(),null;l=w,s.options=o.options,s.handoff=o.handoff;for(let[c]of v)v.set(c,w.subscribe?.(c)??(()=>{})),w.view&&b(c,structuredClone(w.view));d.removeEventListener("abort",F),I("adopted"),D(w),A.clear();let L=p,S=g;return p=null,g=null,f=null,new Proxy(L,{get(c,Y){return Y==="destroy"?()=>{c.destroy(),S?.remove()}:Reflect.get(c,Y,c)}})},get modal(){return u?.document.presentation.type!=="inline"},get revealable(){return a==="ready"&&!!f&&Date.now()-k<_},release(){r("released")}}),Q}export{ue as a,me as b,he as c};
|
package/dist/chunk-GC6JBIRQ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as Mn,b as Un,c as un,d as dn,e as Me,f as $n,h as xn,i as Gn,j as Qn,k as Jn}from"./chunk-CZ4TQCUV.js";import{b as zn}from"./chunk-ESAHTG3Y.js";import{b as qn,c as Bn}from"./chunk-VC2HPREX.js";import{a as On}from"./chunk-W32FI2A2.js";import{c as Sn,e as _n,f as Ln,h as Hn,i as Se,j as Ze,k as Vn,l as Ke}from"./chunk-P6C3PNMQ.js";import{aa as Xe}from"./chunk-IOJVF52Q.js";import{a as Ve,d as Dn}from"./chunk-3NCMYTNG.js";import{b as Rn}from"./chunk-33ZVZOSC.js";import{b as kn,d as Tn,e as An,f as Nn,g as Fn}from"./chunk-VOKEZHAH.js";import{F as Pn,ea as En}from"./chunk-XDOKFAE6.js";import{a as y}from"./chunk-WLGLQJ6M.js";import{a as Ce}from"./chunk-DSPLGTQI.js";async function cn(t){let{session:v,load:C}=it(t);try{return await C(),v}catch(e){throw v.destroy(),e}}function it(t){let v=t.view;if(!v?.paywall)throw new y("INVALID_REQUEST","The current node is not a Paywall");let C=v.paywall.receiptId,e=v.nodeId,w=v.visit,N=v.paywall.resolution,s=v.paywall,_="document"in N?{document:N.document,offering:N.offering,capabilities:N.capabilities}:null;function d(){let i=s.resolution;return"document"in i?i:_&&{...i,document:_.document,offering:_.offering,capabilities:kn(i.capabilities,_.capabilities)}}function I(i){if(!Tn(i,N))throw new y("INVALID_RESPONSE","The pinned Paywall binding changed")}let P=!1,$=new Set,ne=null;function m(){let i=d();if(i&&!P)for(let l of $)Ce(l,structuredClone(i))}async function V(){O();let i=d();if(i)return structuredClone(i);if(!ne){let l=(async()=>{if("document"in s.resolution||!t.resolvePaywall)throw new y("INVALID_RESPONSE","Public Paywall reader is unavailable");let b=await qn(t,s.resolution);return O(),I(b),_={document:b.document,offering:b.offering,capabilities:b.capabilities},m(),d()})();ne=l;let a=()=>{ne===l&&(ne=null)};l.then(a,a)}return ne.then(l=>structuredClone(l))}let o=new AbortController,k=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===w&&i.input.type==="paywall_quote")?.requestId??v.paywall.purchaseRequestId,Y=0,J=null,Q=new Set,E=null,z=new Map;function T(i){if(i.purchase&&i.purchase.receiptId!==C)throw new y("INVALID_RESPONSE","Purchase receipt changed");let l=i.run.paywall;return i.purchase??(l?.receiptId===C?l:null)}function O(){if(P)throw new y("IDENTITY_CHANGED","Paywall presentation has closed")}function S(i,l,a){if(O(),l!==Y||a!==void 0&&s.quote?.operationId!==a)return!1;let b=s.selectionGeneration??0,c=i.run.paywall;if(c?.receiptId===C){if((c.selectionGeneration??0)<(s.selectionGeneration??0))return!1;I(c.resolution)}let u=T(i),q=c?.receiptId===C&&(c.selectionGeneration??0)>b,L=q?u?.quote??null:u?.quote??s.quote,B=u?.operation??(L?.operationId===s.quote?.operationId?s.operation:null);return L&&B&&An(B,{operationId:L.operationId},"Purchase operation changed"),(q||L?.operationId!==s.quote?.operationId)&&(Y++,c?.receiptId===C&&(k=c.purchaseRequestId)),c?.canReselect===!0&&c.purchaseRequestId===E&&!(t.pendingCommands??[t.pendingCommand]).some(M=>M?.requestId===E)&&(E=null),s={...s,...c?.receiptId===C?c:{},...a!==void 0&&!q&&u?.canReselect!==void 0?{canReselect:u.canReselect}:{},quote:L,operation:Fn(s.operation,B,!0)},m(),!0}function ce(i,l,a){return new Promise((b,c)=>{let u=!1,q=()=>{clearTimeout(Ee),o.signal.removeEventListener("abort",M)},L=Re=>{u||(u=!0,q(),b(Re))},B=Re=>{u||(u=!0,q(),c(Re))},M=()=>B(new y("IDENTITY_CHANGED","Paywall presentation has closed")),Ee=setTimeout(()=>B(new y("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,l-Date.now()));o.signal.addEventListener("abort",M,{once:!0}),o.signal.aborted&&M(),i.then(L,B)})}function Pe(i){return new Promise(l=>{let a=()=>{clearTimeout(b),o.signal.removeEventListener("abort",a),l()},b=setTimeout(a,i);o.signal.addEventListener("abort",a,{once:!0}),o.signal.aborted&&a()})}function se(i,l){O();let a=z.get(i)??t.pendingCommands?.find(u=>u.requestId===i)??t.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===e&&a.visit===w){l.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!l.predecessor&&(l={...l,predecessor:a.input.predecessor});let u=Xe.parse(a),q=Xe.parse({...a,input:l});if(u.operation!=="submit"||q.operation!=="submit"||JSON.stringify(u.input)!==JSON.stringify(q.input))throw new y("CONFLICT","A purchase request cannot change its input");return z.set(i,u),u}let b=t.view;if(!b||b.nodeId!==e||b.visit!==w||b.paywall?.receiptId!==C)throw new y("PRECONDITION_FAILED","The Paywall visit has changed");let c=Xe.parse({operation:"submit",requestId:i,nodeId:e,visit:w,revision:b.revision,input:structuredClone(l)});if(c.operation!=="submit")throw new y("INVALID_REQUEST","A purchase submission is required");return z.set(i,c),c}async function te(i,l){O();let{requestId:a,input:b}=i,c=Date.now()+3e4;Q.add(a);try{let u=await ce(t.submit(i),c,a);for(;u.run.pendingRequest?.requestId===a&&Date.now()<c&&!P&&(await Pe(Math.min(1e3,c-Date.now())),!(P||Date.now()>=c));)u=await ce(t.resume(a),c,a);if(P)throw new y("IDENTITY_CHANGED","Paywall presentation has closed");if(u.run.pendingRequest?.requestId===a)throw new y("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!S(u,l,b.type==="paywall_confirm"||b.type==="paywall_cancel"?b.operationId:void 0))throw new y("PRECONDITION_FAILED","The purchase selection has changed");E===a&&(E=null)}catch(u){if(E=a,b.type==="paywall_quote"&&t.settle&&!P&&u instanceof y&&u.status!==void 0&&![401,425].includes(u.status)&&!u.retryable&&u.recovery!=="recover_operation")try{if((await ce(t.settle(a),c,a)).settlement?.state==="settled"){let L=await ce(t.get(),c,a);S(L,l)&&L.run.paywall?.purchaseRequestId===a&&s.canReselect===!0&&z.delete(a)}}catch{}throw u instanceof y&&u.code==="COMMAND_PENDING"&&u.status===void 0&&z.delete(a),u}finally{Q.delete(a)}}async function me(i){if(!s.quote)throw new y("INVALID_REQUEST","A quoted purchase is required");let l=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...z.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(c=>c.operation==="submit"&&c.input.type===l&&"operationId"in c.input&&c.input.operationId===s.quote.operationId),b=a?.operation==="submit"&&a.input.type===l&&"operationId"in a.input&&a.input.operationId===s.quote.operationId?a.requestId:crypto.randomUUID();if(await te(se(b,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:s.quote.operationId}),Y),!s.operation)throw new y("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(s.operation)}let G={get view(){return structuredClone(d())},get quote(){return s.quote?structuredClone(s.quote):null},get operation(){return s.operation?structuredClone(s.operation):null},get webViewUrl(){return t.webViewUrl},get locale(){return t.view?.locale??v.locale},get canReselect(){return s.canReselect===!0&&E===null},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),l=t.pendingPurchase;if(l&&(l.receiptId!==C||l.operationId!==s.quote?.operationId))return{type:"recover",operationId:l.operationId,requestId:i[0]?.requestId??null};let a=Ve({quote:s.quote,operation:s.operation,requestId:i[0]?.requestId??E??k,pending:Q.size>0||i.length>0||E!==null,destroyed:P,canReselect:s.canReselect});return a.type==="recover"&&a.requestId===null&&!P&&t.hasDurableJournal===!0&&!s.quote&&!s.operation&&(s.selectionGeneration??0)===0&&!l&&!i.length&&!Q.size&&!k?{type:"native",operationId:null}:a},get pendingCancellation(){return!P&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===w&&i.input.type==="paywall_cancel"&&i.input.operationId===s.quote?.operationId)},subscribe(i){return P?()=>{}:($.add(i),()=>$.delete(i))},async refresh(){O();let i=Y,l=await t.get();if(S(l,i),l.run.paywall?.receiptId!==C)throw new y("PRECONDITION_FAILED","Paywall presentation has changed");return V()},preview(i){let l=d();if(!l)return Promise.reject(new y("PRECONDITION_FAILED","Load the Paywall presentation first"));if(k&&k!==i.requestId&&(J||s.canReselect!==!0))return Promise.reject(new y("COMMAND_PENDING","Retry the original purchase before starting another"));let a=l.document.buttons[i.actionId],b=a?.type==="checkout"?Rn(a.product,i.selection,l.capabilities):null;if(!b)return Promise.reject(new y("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let c=En(l.document.screen,b,i.selection,l.capabilities),u=k!==i.requestId&&(s.selectionGeneration??0)>0?{operationId:s.quote?.operationId??null,generation:s.selectionGeneration??0}:void 0;if(u&&s.canReselect!==!0)return Promise.reject(new y("COMMAND_PENDING","Original purchase requires authoritative termination"));let q;try{q=se(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:b,...Object.keys(c).length?{featureQuantities:c}:{},...u?{predecessor:u}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(M){return Promise.reject(M)}if(k===i.requestId&&J)return J;k!==i.requestId&&Y++;let L=Y;k=i.requestId;let B=(async()=>{if(await te(q,L),!s.quote)throw new y("INVALID_RESPONSE","The accepted quote is missing");return Nn(s.quote,{productVersionId:b,featureQuantities:c},"The selected purchase changed"),structuredClone(s.quote)})();return J=B,B.then(()=>{J===B&&(J=null)},M=>{J===B&&(J=null),k===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&M instanceof y&&M.status!==void 0&&M.status<500&&![401,425].includes(M.status)&&(k=null)}),B},confirm:()=>me("confirm"),cancel:()=>me("cancel"),async read(){if(O(),!s.quote)throw new y("INVALID_REQUEST","A quoted purchase is required");let i=s.quote.operationId,l=Y,a=t.pendingCommands?.find(L=>L.operation==="submit"&&(L.input.type==="paywall_confirm"||L.input.type==="paywall_cancel")&&L.input.operationId===i)??t.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===i&&await t.settle?.(a.requestId);let b=await t.get(void 0,{receiptId:C,operationId:i});O();let c=T(b);if(c?.quote&&c.quote.operationId!==i||c?.operation&&c.operation.operationId!==i)throw new y("INVALID_RESPONSE","Purchase operation changed");let u=S(b,l,i),q=u?s.operation:c?.operation;if(!q)throw new y("INVALID_RESPONSE","The current purchase result is missing");return u&&Q.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(E=null),structuredClone(q)},destroy(){P=!0,A(),$.clear(),o.abort(),z.clear()}},A=t.subscribe(i=>{P||i.nodeId!==e||i.visit!==w||i.paywall?.receiptId!==C||(i.paywall.selectionGeneration??0)<(s.selectionGeneration??0)||(I(i.paywall.resolution),s={...s,resolution:i.paywall.resolution},m())});return{session:G,load:V}}function jn(t){let v=new Set,C=new Set,e=null;async function w(d,I){let P=!1;for(;!t.stopped&&t.key===d&&t.client.pendingCommand?.requestId===I;){if(!t.client.settle)throw new y("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(I),P=!0,t.client.pendingCommand?.requestId===I&&await new Promise($=>setTimeout($,1500))}t.stopped||t.key!==d||(P&&await t.client.get(),!(t.stopped||t.key!==d)&&v.add(d))}function N(d,I){e=I;let P=()=>{e===I&&(e=null),C.delete(d)};return I.then(P,$=>{P(),t.busy||t.fail($)}),I}function s(d){if(t.reviewing||v.has(d)||C.has(d)||t.stopped)return;C.add(d);let I=async()=>{if(t.reviewing||t.stopped||t.key!==d||v.has(d)){C.delete(d);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{I()},250);return}let P=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==d)return;if(t.client.pendingCommand){setTimeout(()=>{I()},250);return}}let $=t.client.view,ne=t.expected(),m=ne.requestId;try{await t.client.submit({operation:"shown",...ne})}catch(V){if(!(V instanceof y)||V.code!=="CONFLICT"||V.status!==409||t.client.pendingCommand)throw V;await t.client.get();let o=t.client.view;if(t.stopped||t.reviewing||t.key!==d||!o||!$||o.id!==$.id||o.source.versionId!==$.source.versionId||o.nodeId!==ne.nodeId||o.visit!==ne.visit||o.revision<=ne.revision||o.stopped||!o.screen&&(!o.paywall||o.paywall.receiptId!==$.paywall?.receiptId)||!["running","waiting"].includes(o.status)||t.client.pendingCommand)throw V;let R=t.expected();m=R.requestId,await t.client.submit({operation:"shown",...R})}await w(d,m)})();N(d,P)};I()}function _(){if(e)return e;let d=t.client.pendingCommand;if(d?.operation!=="shown")return null;let I=t.key;return C.add(I),N(I,(async()=>{await t.client.retry(),await w(I,d.requestId)})())}return{report:s,settled:_,get inFlight(){return e}}}function Wn(t){let v={},C=new Map;async function e(w){let N=t.client.view,s=N?.screen,_=s?.customerData.nodes[w.nodeId];if(t.stopped||t.busy||!N||!s||!_)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(w.action)){let V=t.document,o=V?Pn(V,w.nodeId):null,R=o?.type==="customer_data"?o.data.outputs?.[w.action]:void 0;R&&s.outputs.includes(R)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:R,answers:t.answers,selection:w.value?{[w.nodeId]:w.value}:{}}})):await t.onIntent?.(w,N);return}let I=w.action.startsWith("sources_")?_.resources.find(V=>V.key===w.value):null;if(w.action.startsWith("sources_")&&!I)throw new y("INVALID_REQUEST","Choose a current resource");let P=`${N.visit}:${w.nodeId}:${I?.key??""}`,$=C.get(P)??[null],m=v[w.nodeId]??{page:1,after:null,filter:"all",...I?{resourceKey:I.key}:{}};if(w.action==="filter"){let V=w.value;if(!V||!(_.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(V))throw new y("INVALID_REQUEST","Unknown data filter");m={page:1,after:null,filter:V},$.splice(0,$.length,null)}else if(w.action==="next"||w.action==="sources_next"){let V=I?.sources.at(-1),o=I?V?{kind:"ledger",cursor:{at:V.detail[0],id:V.id,type:"source"}}:null:s.dataCursors[w.nodeId];if(!o||!I&&!_.hasNext)return;$[m.page]=o,m={...m,page:m.page+1,after:o}}else if(w.action==="previous"||w.action==="sources_previous"){if(m.page<=1)return;m={...m,page:m.page-1,after:$[m.page-2]??null}}C.set(P,$),v={...v,[w.nodeId]:m},await t.perform(()=>t.client.get({nodeId:N.nodeId,visit:N.visit,revision:N.revision,components:v}))}return{get queries(){return v},intent:e,reset(){v={},C.clear()}}}function Yn(t){let{doc:v,holder:C,reviewHolder:e,mountScreenPreview:w}=t,N=!1,s,_=0,d=null,I="",P,$=new Map,ne=o=>o?`${o.id}:${o.nodeId}:${o.visit}:${o.revision}:${o.paywall?.quote?.operationId??""}`:"";async function m(o){if(t.stopped||!t.client.review||N&&o===s&&P?.active)return;let R=!N||o!==s;N||(I=ne(t.client.view),$.set(I,structuredClone(t.answers))),N=!0,s=o,C.hidden=!0,t.suspend(!0),e.hidden=!1;let k=++_;R&&(P?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),P=Ze(e,t.loadingOptions,"funnel",()=>{V()}));let Y=R?P:void 0;try{if(Y?.start(!1,t.client.view?.locale),k!==_||t.stopped)return;let J=t.client.review(o),Q=await(Y?.wait(J,Se)??J);if(t.stopped||k!==_||!N)return;if(!Q.review)throw new y("INVALID_RESPONSE","Historical projection is missing");d?.destroy(),d=null,Y||e.replaceChildren();let E=v.createElement("div"),z=Y?Ke(E,e):()=>{};e.append(E);let T=Q.run.locale.startsWith("zh"),O=t.chrome;E.style.cssText=O.history;let S=v.createElement("p");S.textContent=T?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",S.style.cssText=O.historyTitle,E.append(S);let ce=v.createElement("p");ce.style.cssText=O.historyNote,ce.textContent=Q.review.pages.length?T?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":T?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",E.append(ce);let Pe=Q.review.page?.receiptId,se=v.createElement("div");se.style.cssText=O.historyPages;for(let[G,A]of Q.review.pages.entries()){let i=v.createElement("button");i.type="button",i.textContent=T?`\u7B2C ${G+1} \u9875`:`Page ${G+1}`;let l=Pe!==void 0&&A.receiptId===Pe;i.style.cssText=l?O.primary:O.secondary,l&&i.setAttribute("aria-current","page"),Me(i,()=>t.chrome.focus),i.onclick=()=>{m(A.receiptId)},se.append(i)}if(se.childElementCount&&E.append(se),Q.review.page){let G=Q.review.page,A=v.createElement("div");A.inert=!0,A.style.cssText=O.historyPage,E.append(A),d=w(A,{mode:"live",rendererUrl:t.client.webViewUrl,title:G.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{k===_&&!t.stopped&&Y?.present(z)},onError:l=>{if(k!==_||t.stopped)return;let a=new Error(l);Y?.finish("error",a),d?.destroy(),d=null,E.remove(),t.fail(a)},onEscape:()=>{V()}});let i=d;if(i.update(G.document,Q.run.locale,{serverInput:{bindings:G.inputs,answers:G.answers,values:G.values}}),await i.ready,t.stopped||k!==_||!N)return}let te=T?{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"},me=v.createElement("div");me.style.cssText=O.historyRecords;for(let G of[...Q.review.coupons.map((A,i)=>`${T?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${te[A.status]}`),...Q.review.purchases.map((A,i)=>`${T?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Jn(A.status,T)}`)]){let A=v.createElement("p");A.textContent=G,A.style.margin="0",me.append(A)}me.childElementCount&&E.append(me),Q.review.page||Y?.present(z),t.client.view&&await t.enqueue(t.client.view)}catch(J){if(k!==_||t.stopped)return;Y?.finish("error",J),d?.destroy(),d=null,e.replaceChildren(),t.fail(J)}}async function V(){if(!N||t.stopped||!t.client.review)return;let o=++_;P?.finish("dismissed");try{if(await t.client.review(),t.stopped||o!==_)return;N=!1,_++,P?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,C.hidden=!1;let R=t.client.view;ne(R)!==I?($.set(I,structuredClone(t.answers)),t.resetScreen()):($.delete(I),t.suspend(!1)),R&&await t.enqueue(R)}catch(R){if(o!==_||t.stopped)return;d?.destroy(),d=null,e.replaceChildren(),t.fail(R)}}return{get active(){return N},get receipt(){return s},open:m,exit:V,get drafts(){return new Map([...$].map(([o,R])=>[o,structuredClone(R)]))},stop(){N=!1,_++,P?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,C.hidden=!1}}}var pn=5e3;async function rt(t,v,C){let e=v,w=e.prepared&&zn(e.prepared),N=()=>{};function s(){e.prepared&&e.prepared.state!=="adopted"&&w?.release()}let _=()=>e.prepared?.state==="shown"&&!!w?.modal,d=e.client.identitySignal,I;try{I=await Promise.all([import("./screen-renderer-FFVZ64MR.js"),import("./paywall-UANWOKKC.js")]),e.signal?.throwIfAborted(),d?.throwIfAborted()}catch(n){throw s(),n}let[{mountScreenPreview:P},{showPaywall:$}]=I,ne=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&e.appManifestRelease?Bn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;ne?.start();let m=t.ownerDocument,V=Hn(m),o=m.createElement("section"),R=m.createElement("div"),k=m.createElement("div"),Y=m.createElement("div"),J=m.createElement("button");Y.hidden=!0,J.type="button";let Q=m.createElement("p"),E=m.createElement("p"),z=m.createElement("button"),T=m.createElement("button"),O=m.createElement("button"),S=m.createElement("dialog"),ce,Pe=!1;o.dataset.indianaFunnel="",o.dataset.longplayCloseOwner="sdk",o.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),E.setAttribute("role","alert"),E.hidden=!0,z.type=T.type=O.type="button",k.append(z,J,Q,E,O,T),o.append(R,Y,k),t.append(o);let se=Un,te=un(se),me="",G=(m.documentElement.lang||"").startsWith("zh"),A,i="",l;for(let n of[z,J,O,T])Me(n,()=>te.focus);function a(){let n=G?"\u5173\u95ED":"Close";T.parentElement===S?(T.textContent="\xD7",T.setAttribute("aria-label",n),Ln(T,se)):(T.textContent=n,T.removeAttribute("aria-label"),T.style.cssText=te.link+";margin-inline-start:auto")}function b(n){let r=n?.screen?.content.document.theme??se,p=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,T.parentElement===S]);if(p===me)return;me=p,se=r;let H=T.parentElement===S;te=un(se,H),o.style.cssText=te.root+";min-width:0"+(H?";display:flex;flex-direction:column;min-height:100%":""),k.style.cssText=te.bar+(H?";margin-top:auto":""),k.hidden&&(k.style.display="none"),z.style.cssText=J.style.cssText=te.secondary,O.style.cssText=te.primary,Q.style.cssText=te.status,E.style.cssText=te.alert,a(),dn(z)}function c(){k.hidden=z.hidden&&J.hidden&&O.hidden&&E.hidden&&!Q.textContent&&(T.hidden||T.parentElement!==k),k.style.display=k.hidden?"none":"flex",A?.responsive&&l!==void 0&&A.setContentHeight(l+k.getBoundingClientRect().height)}b();let u=null,q=null,L=null,B="",M="",Ee=!1,Re="",en="",Ue="",h=!1,le=0,$e=!1,fn="",nn=null,tn=Promise.resolve(),mn=!e.client.view,j=C,Te,_e,xe="",Ge,ue=!1,qe=null,he=!1,Qe=()=>e.client.pendingCommand?.operation==="close",de=null,X=null,wn=On({document:m,run:async()=>{(!q?.observing||e.client.pendingCommand)&&await on()},delay:()=>{if(!(h||!L||!["running","waiting"].includes(L.status)&&!e.client.pendingCommand)&&!(q?.observing&&!e.client.pendingCommand))return L.pendingRequest||e.client.pendingCommand?1500:pn},hiddenDelay:()=>!h&&e.client.pendingCommand?15e3:void 0}),K=null;function rn(){return X&&e.client.hasDurableJournal===!0&&K?.acknowledged===!0&&K.operationId===X.operationId&&e.client.view?.id===K.runId&&e.client.view?.status==="closed"&&e.client.view.revision===K.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?X:null}function yn(n){let r=n.run.paywall;if(K&&n.settlement?.requestId===K.requestId&&n.settlement.state==="settled"&&n.settlement.operationId===null&&n.run.id===K.runId&&n.run.status==="closed"&&!n.run.pendingRequest&&n.run.revision===K.revision+1&&n.run.nodeId===K.nodeId&&n.run.visit===K.visit&&r?.receiptId===K.receiptId&&r.selectionGeneration===K.selectionGeneration&&(r.quote?.operationId??null)===K.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===K.operationId){let p=K.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,H=Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(p||r.canReselect===!0&&H.type==="native")&&(K.acknowledged=!0)}}let De=null,Je=new Set,we={},Ae=!1,pe=(n,r=null)=>{h||(De=r,Ae=!1,E.textContent=$n(n,G),E.hidden=!1,O.hidden=e.client.pendingCommand===null,c(),Ce(e.onError,n))},gn=()=>{h||(De=null,E.textContent=Gn(G),E.hidden=!1,O.hidden=!0,c())};function ke(){let n=e.client.view;if(!n)throw new y("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision}}let F=Yn({client:e.client,doc:m,holder:R,reviewHolder:Y,mountScreenPreview:P,loadingOptions:e,get chrome(){return te},get stopped(){return h},get answers(){return we},suspend(n){q?.setSuspended(n)},resetScreen(){B="",M="",Re=""},enqueue:ye,fail:pe}),Le=jn({client:e.client,expected:ke,fail:pe,get stopped(){return h},get reviewing(){return F.active},get key(){return B},get busy(){return le},get staleRead(){return nn}}),ze=Wn({client:e.client,expected:ke,perform:Fe,onIntent:e.onCustomerDataIntent,get stopped(){return h},get busy(){return le},get document(){return u?.document},get answers(){return we}}),Be=n=>`${n.id}:${n.nodeId}:${n.visit}`,Ne=n=>n&&(n.screen||n.paywall)?Be(n):"";function ve(){let n=e.client.view;z.disabled=!F.active&&(le>0||!!e.client.pendingCommand||!n?.canBack||n.stopped||!["running","waiting"].includes(n.status)||!Ne(n)||M!==Ne(n)),z.hidden=!F.active&&!n?.canBack,dn(z);let r=!!q&&!F.active;T.hidden=r&&!j?.active||Pe&&!F.active,J.hidden=!e.client.review||!F.active&&!n?.canBack,r&&(Q.textContent=""),c()}async function hn(n){if(!n)return;let r=e.client.view;await n;let p=e.client.view;if(!r||!p||p.id!==r.id||p.nodeId!==r.nodeId||p.visit!==r.visit||p.stopped||!["running","waiting"].includes(p.status))throw new y("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Fe(n,r=!1,p){if(!((le||he||de||X)&&!r||h||F.active&&!r)){le++,o.setAttribute("aria-busy","true"),E.hidden=!0,De=null,Ae=!1,ve();try{if(r||await hn(Le.inFlight),h)return;let H=await n();h||await ye(e.client.view??H.run)}catch(H){p?.(H)&&e.client.pendingCommand===null?gn():pe(H,e.client.pendingCommand?.requestId??null)}finally{le=Math.max(0,le-1),o.setAttribute("aria-busy",String(le>0)),h||(O.hidden=e.client.pendingCommand===null,ve())}}}function He(){wn.schedule()}async function on(){if(!(h||$e||le)){if(F.active){await F.open(F.receipt);return}$e=!0;try{let n=e.client.pendingCommand;n&&e.client.settle&&await e.client.settle(n.requestId);let r=e.client.view,p=ze.queries,H=await e.client.get(r?.screen&&Object.keys(p).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:p}:void 0);Ae&&!h&&(Ae=!1,E.hidden=!0,c()),!h&&p===ze.queries&&await ye(e.client.view??H.run)}catch(n){pe(n),Ae=!h}finally{$e=!1}}}function je(n,r,p){if(j?.active){let ae=j;return ae.setDismissHandler(()=>vn(ae)),ae}let H=Ze(t,e,"funnel",()=>vn(H),Mn);return j=H,H.start(n,r,p),H}function vn(n){h||ue||(ue=!0,n.finish("dismissed"),Ie(),o.hidden=!0,e.client.view?be().finally(ie):ie())}function sn(){clearTimeout(Ge?.timeout),Ge=void 0}function Ie(){Pe=!1,sn(),Te?.abort(),Te=void 0,u?.destroy(),u=null,q?.destroy(),q=null,_e?.(),_e=void 0,S.open&&S.close(),R.replaceChildren(),R.style.cssText="",l=void 0,B="",M="",Ee=!1,Re="",Ue=""}function In(){let n=m.defaultView;A?.responsive&&n&&u?.resizeViewport?.(n.innerHeight,n.innerWidth)}function an(){A?.destroy(),A=void 0,i=""}function We(n){let r=n.screen?.presentation;if(!r||r.type==="inline"){S.open&&S.close(),an(),T.parentElement!==k&&k.append(T),o.parentElement!==t&&t.append(o);for(let ae of["flex","display","flex-direction","justify-content"])R.style.removeProperty(ae);b(n),c();return}o.parentElement!==S&&(S.append(T,o),t.append(S)),R.style.flex="1 0 auto",R.style.display="flex",R.style.flexDirection="column",R.style.justifyContent="center",b(n);let p=n.screen.content.document,H=JSON.stringify([r,me]);if(H!==i){an(),i=H;let ae={sm:420,md:640,lg:900},ge="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";S.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${se.background};color:${se.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ae[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${ge};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),A=Sn(S,{presentation:r,theme:p.theme,pages:p.pages},In),A.latch()}c(),S.setAttribute("aria-label",(ce?.screen===n.screen?.content.document.name?ce?.label:void 0)??u?.document?.name??n.screen?.content.document.name??"Funnel")}async function Xn(n){if(h||ue||he&&(Qe()||["running","waiting"].includes(n.status))||(L=n,De&&e.client.pendingCommand?.requestId!==De&&(E.hidden=!0,De=null),G=n.locale.startsWith("zh"),J.textContent=G?"\u56DE\u770B":"History",z.textContent=F.active?G?"\u8FD4\u56DE\u5F53\u524D":"Return to current":G?"\u8FD4\u56DE":"Back",a(),O.textContent=G?"\u91CD\u8BD5":"Retry",O.hidden=e.client.pendingCommand===null,Q.textContent=n.pendingRequest?G?"\u6B63\u5728\u5904\u7406":"Processing":n.instruction?.type==="wait"?G?"\u7B49\u5F85\u4E2D":"Waiting":"",ve(),fn!==`${n.revision}:${n.visit}:${n.status}:${n.stopped}`&&(fn=`${n.revision}:${n.visit}:${n.status}:${n.stopped}`,Ce(e.onState,structuredClone(n))),h||ue))return;if((!n.pendingRequest||he&&n.status==="closed")&&["closed","ineligible","failed"].includes(n.status)){ie();return}if(n.stopped&&_()){ie();return}if(n.stopped||e.client.configurationReady===!1){F.stop(),s(),Ie(),j?.finish("skipped"),o.hidden=!0,He();return}if(o.hidden=!1,F.active){He();return}let r=Ne(n),p=e.client.view;if(p&&p.revision>n.revision&&Ne(p)!==r)return;let H=!n.instruction&&!n.pendingRequest&&n.nodeType==="screen"&&["running","waiting"].includes(n.status);r!==B&&(B&&j?.finish("dismissed"),Ie(),B=r,we={...n.answers},ze.reset());let ae=Be(n);if(xe===ae){o.hidden=!0;return}if(H&&!r){o.hidden=!0;let U=e.prepared?.state==="shown"?null:je(!0,n.locale);!h&&!ue&&Ge?.key!==ae&&(sn(),Ge={key:ae,timeout:setTimeout(()=>{let g=e.client.view;if(h||!U?.active&&e.prepared?.state!=="shown"||!g||Be(g)!==ae)return;xe=ae;let W=new Error("Funnel screen preparation timed out");U?.finish("error",W),s(),Ie(),pe(W)},Se)}),He();return}sn();let Z=U=>{let g=e.client.view;return!h&&!ue&&!qe&&!U.aborted&&e.client.configurationReady!==!1&&!!g&&!g.stopped&&!["closed","ineligible","failed"].includes(g.status)&&Ne(g)===r},ge=(U,g)=>{Z(g)&&(xe=r,j?.finish("error",U),Ie(),o.hidden=!0,pe(U))};if(r||((n.instruction&&n.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(n.status))&&s(),We(n),n.instruction?.type!=="event"&&n.instruction?.type!=="open_url"&&j?.finish("skipped")),n.screen){s();let U=n.screen.content;if(!u){let x=n.screen.presentation.type!=="inline",re=je(x,n.locale);if(h||ue)return;let ee=(Te=new AbortController).signal;We(n),_e=x?Vn(S):Ke(o,t),u=P(R,{mode:"live",closeActions:Array.from(new Set([...e.closeActions??[],...U.document.actions.filter(f=>f.type==="event"&&f.close).map(f=>f.id)])),onAuthoredClose(f){Z(ee)&&(Pe=f,ve())},rendererUrl:e.client.webViewUrl,title:U.document.name,...x?{hostPresentation:()=>A?.type??n.screen.presentation.type}:{},onResize:f=>{l=f,A?.responsive&&A.setContentHeight(f+k.getBoundingClientRect().height)},onAction(f,fe={},tt={}){if(F.active||!Z(ee)||M!==r)return;we={...we,...tt};let ln=n.screen?.inputs??[],Cn=Object.fromEntries(ln.filter(({variable:Oe})=>Object.hasOwn(we,Oe)).map(({variable:Oe})=>[Oe,we[Oe]]));if(Qn(ln,Cn).length){gn();return}Fe(()=>e.client.submit({operation:"submit",...ke(),input:{type:"screen",output:f,answers:Cn,selection:fe}}),!1,Oe=>xn(Oe,ln))},onAnswers:f=>{F.active||!Z(ee)||M!==r||(we={...we,...f})},onCustomerDataIntent:f=>{F.active||!Z(ee)||M!==r||ze.intent(f).catch(pe)},onEscape:()=>{!Z(ee)||M!==r||F.active||de||X||be()},onError:f=>{let fe=new Error(f);M===r?pe(fe):ge(fe,ee)},onRendered:f=>{if(!(!Z(ee)||M===r))try{re.present(fe=>{_e?.(),_e=void 0,f&&(ce={screen:U.document.name,label:f},S.setAttribute("aria-label",f)),x&&(S.showModal(),A?.responsive&&S.focus({preventScroll:!0}),!fe&&e.loading!=="host"&&_n(S,A?.type??n.screen.presentation.type,A?.responsive)),M=r,Ee=x,ve()}),Z(ee)&&Le.report(r)}catch(fe){ge(fe,ee)}}}),In()}let g={capabilities:n.screen.capabilities,customerData:n.screen.customerData,parameters:n.parameters,serverInput:{bindings:n.screen.inputs,answers:we,values:n.screen.values}},W=JSON.stringify([U,n.locale,g.parameters,n.screen.inputs,n.screen.values]);if(W!==Re)u.update(U.document,n.locale,g),Re=W,en=JSON.stringify(g.capabilities),Ue=JSON.stringify(g.customerData);else{let x=JSON.stringify(g.capabilities);x!==en&&(u.updateCapabilities(g.capabilities),en=x),JSON.stringify(g.customerData)!==Ue&&(u.updateCustomerData(g.customerData),Ue=JSON.stringify(g.customerData))}let oe=u;if(oe)try{await(j?.wait(oe.ready)??oe.ready)}catch(x){Te&&ge(x,Te.signal)}}else if(n.paywall&&!q){let U=n.paywall.resolution,g="document"in U?U.document:null,W=w,oe=null,x=(Te=new AbortController).signal,re={loading:"host",signal:x,canInteract:()=>Z(x)&&!F.active&&!de&&!X,beforeAction:async()=>{le++;try{await hn(Le.settled()),E.hidden=!0,De=null,Ae=!1,c()}finally{le=Math.max(0,le-1)}},start:()=>cn(e.client),onObservationChange:He,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resumeCheckout:e.resumeCheckout,allowNewPurchase:e.allowNewPurchase,checkoutNavigation:e.checkoutNavigation,terminateCheckout:e.terminateCheckout,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,claimCoupon:e.claimCoupon,onEvent:e.onEvent,onOpenUrl:f=>e.onOpenUrl?e.onOpenUrl({receiptId:n.paywall.receiptId,url:f,openIn:"same_window"}):m.defaultView?.location.assign(f),onAction:async f=>{if(F.active)return;let fe=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:e.client.view?.revision??n.revision,input:{type:"screen",output:f,answers:{}}});await ye(e.client.view??fe.run)},onError:f=>{M===r?pe(f):ge(f,x)}},ee={quoteError:f=>Ce(e.onError,f),present(f){Z(x)&&(oe?.present(()=>{f(),M=r,Ee=!!R.querySelector("dialog[open]"),ve()}),Z(x)&&Le.report(r))},async dismiss(){if(!(h||x.aborted||F.active||de||X||!he&&!Z(x))){if(he=!0,(e.resumeCheckout||e.terminateCheckout)&&nt()){L=e.client.view,ie();return}await be()}}};if(W){let f=await W.adopt(n,{options:re,handoff:ee,start:()=>cn(e.client)});f&&Z(x)&&!h?(We(n),q=f,j?.active&&j.present(()=>{}),M=r,Ee=W.modal,ve(),Le.report(r),F.active&&q.setSuspended(!0)):(f?.destroy(),s())}if(h||ue)return;if(!q){if(oe=je(!0,n.locale,g),h||ue)return;We(n);let f=await $(R,re,ee).catch(fe=>(ge(fe,x),null));!Z(x)&&!(he&&!h&&!x.aborted)?f?.host?.destroy():f&&(q=f.host,q?.setSuspended(F.active))}}if(h||ue)return;ve();let D=n.instruction;if(D&&(D.type==="open_url"||D.type==="event")&&!Je.has(D.receiptId)){let U=m.createElement("button");U.type="button",U.style.cssText=te.primary,Me(U,()=>te.focus),R.style.cssText=te.stage,U.textContent=D.type==="open_url"?`${G?"\u524D\u5F80":"Continue to"} ${new URL(D.url).host}`:G?"\u7EE7\u7EED":"Continue",U.onclick=()=>{let g=ke(),W=D.type==="open_url"&&!e.onOpenUrl&&D.openIn==="new_window"?Zn(D.url):null;Fe(async()=>{let oe="success";if(D.type==="open_url")if(e.onOpenUrl)try{oe=await e.onOpenUrl({receiptId:D.receiptId,url:D.url,openIn:D.openIn})===!1?"failed":"opened"}catch(re){Ce(e.onError,re),oe="failed"}else oe=D.openIn==="new_window"&&!W?"failed":"opened";if(D.type==="event"){if(!e.onEvent)throw new y("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(D.event)}if(h||e.client.view?.nodeId!==g.nodeId||e.client.view.visit!==g.visit)throw new y("PRECONDITION_FAILED","The client action visit changed");let x=await e.client.submit({operation:"submit",...g,input:{type:"client_action",receiptId:D.receiptId,outcome:oe}});return Je.add(D.receiptId),D.type==="open_url"&&!e.onOpenUrl&&D.openIn==="same_window"&&m.defaultView?.location.assign(D.url),x})},j?.active?j.present(()=>R.replaceChildren(U)):R.replaceChildren(U)}!n.pendingRequest&&n.status==="completed"&&!Je.has(`complete:${n.id}`)&&(Je.add(`complete:${n.id}`),Ce(e.onComplete,structuredClone(n))),He()}function Zn(n){let r=m.defaultView?.open(n,"_blank")??null;return r&&(r.opener=null),r}function ye(n){return ve(),tn=tn.catch(()=>{}).then(async()=>{try{await Xn(n)}catch(r){throw j?.active&&(xe=Be(n),j.finish("error",r),Ie(),o.hidden=!0),r}}),tn}let Kn=e.client.subscribe(n=>{if(!mn){if(n.stopped&&(Ee||_())&&!he){L=n,ie();return}!he&&(n.stopped||e.client.configurationReady===!1||B&&M!==B&&(Ne(n)!==B||["closed","ineligible","failed"].includes(n.status)))&&(Ie(),j?.finish("dismissed"),o.hidden=!0),ye(n).catch(pe)}}),et=e.client.subscribeError?.(pe);function nt(){let n=e.client.view,r=n?.paywall;return!!r?.operation&&!!n&&["running","waiting"].includes(n.status)&&Dn(Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function be(n){if(qe)return qe;if(h||!n&&(de||X))return Promise.resolve();let r=!n&&Qe();return!r&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(L=e.client.view,ie(),Promise.resolve()):(qe=Fe(async()=>{let p=r?await e.client.retry():await e.client.submit({operation:"close",...n??ke()});return n&&yn(p),p},!0).then(()=>{let p=e.client.view;p?.status==="closed"&&!Qe()&&(L=p,ie())}).finally(()=>{qe=null}),qe)}function ie(){ne?.destroy(),!h&&(h=!0,N(),s(),e.signal?.removeEventListener("abort",ie),d?.removeEventListener("abort",ie),j?.finish("dismissed"),wn.destroy(),Kn(),et?.(),Ie(),an(),F.stop(),S.remove(),o.remove(),V(),Ce(e.onDismiss,L?structuredClone(L):null))}z.onclick=()=>{if(!z.disabled){if(F.active){F.exit();return}Fe(()=>e.client.submit({operation:"back",...ke()}))}},J.onclick=()=>{F.open()},T.onclick=()=>{j?.active?j.dismiss():de||be()},O.onclick=()=>{Qe()?be():Fe(()=>e.client.retry())},S.addEventListener("cancel",n=>{n.preventDefault(),j?.active?j.dismiss():de||be()}),e.signal?.addEventListener("abort",ie,{once:!0}),d?.addEventListener("abort",ie,{once:!0});let Ye=!1;w&&(N=w.onClose(()=>{h||ue||(ue=!0,j?.finish("dismissed"),Ie(),o.hidden=!0,e.client.view?be().finally(ie):Ye=!0)}));let bn={destroy:ie,refresh:on,get recovery(){let n=rn();if(n)return n;if(!h&&!le&&!he&&!de&&q){let r=q.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??X?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(de)return de;let n=rn();if(n)return Promise.resolve(n);let r=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??X?.operationId??null,p=()=>({type:"recover",operationId:r,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let D=q?.recovery;return Promise.resolve(D&&D.type!=="native"&&D.type!=="cancel"?D:p())}let H=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(D=>D.operation==="close");if(h&&!(H||X&&e.client.view?.status==="closed")||le||$e||qe||F.active||!q&&!X&&!H)return Promise.resolve(p());let ae=q,Z=(async()=>{try{if(!X&&H){let g=await e.client.retry();return await ye(e.client.view??g.run),p()}if(!X){let g=await ae.prepareFallback();if(g.type!=="native")return g;if(e.client.hasDurableJournal!==!0)return p();X=g}let D=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(D.length){let g=D.find(oe=>oe.operation==="close");if(!g||!K||g.requestId!==K.requestId)return p();let W=await e.client.retry();yn(W),await ye(e.client.view??W.run)}else{let g=e.client.view,W=g?.paywall;if(!g||!W||W.selectionGeneration===void 0||(W.quote?.operationId??null)!==X.operationId||X.operationId!==null&&W.canReselect!==!0)return p();let oe=W.selectionGeneration,x=await e.client.get();await ye(e.client.view??x.run);let re=e.client.view,ee=re?.paywall;if(!re||!ee||!["running","waiting"].includes(re.status)||re.stopped||re.id!==g.id||re.nodeId!==g.nodeId||re.visit!==g.visit||ee.receiptId!==W.receiptId||ee.selectionGeneration!==oe||(ee.quote?.operationId??null)!==X.operationId||X.operationId!==null&&ee.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return p();let f=ke();K={runId:re.id,operationId:X.operationId,revision:f.revision,requestId:f.requestId,nodeId:re.nodeId,visit:re.visit,receiptId:ee.receiptId,selectionGeneration:oe,acknowledged:!1},await be(f)}let U=rn();return U?(ie(),U):p()}catch(D){return pe(D),p()}})();de=Z;let ge=()=>{de===Z&&(de=null)};return Z.then(ge,ge),Z},review:F.open,exitReview:F.exit,get unappliedDrafts(){return F.drafts}};try{let n=e.client.view;if(n)((e.client.viewAgeMs??pn)>=pn||n.instruction?.type==="evaluate_segment")&&(nn=on().finally(()=>{nn=null})),await ye(n);else{if(o.hidden=!0,h)throw new DOMException("Presentation cancelled","AbortError");let r=Ye||e.prepared?.state==="shown"?null:je(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(h||ue&&!Ye)throw new DOMException("Presentation cancelled","AbortError");let p=e.client.get(),H=await(r?r.wait(p,Se):ot(p,Se));if(mn=!1,Ye)return h||await be().finally(ie),bn;await ye(e.client.view??H.run)}}catch(n){throw j?.finish("error",n),ie(),n}return bn}function ot(t,v){let C;return Promise.race([t,new Promise((e,w)=>{C=setTimeout(()=>w(new Error("Presentation data timed out")),v)})]).finally(()=>clearTimeout(C))}function Gt(t,v,C){return rt(t,v,C)}export{rt as a,Gt as b};
|
package/dist/chunk-IJKAQNK6.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{p as n,s as t}from"./chunk-4TEZZZYK.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
|