@tinkerlandai/longplay-sdk 0.10.78 → 0.10.79
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 +4 -0
- package/dist/check-response-XGOTG3KL.js +1 -0
- package/dist/{chunk-IB6BBGLM.js → chunk-2OBXRQMW.js} +1 -1
- package/dist/{chunk-HOX2FQQE.js → chunk-2WXUJGGZ.js} +1 -1
- package/dist/{chunk-DLLC7CRI.js → chunk-3532HSBP.js} +1 -1
- package/dist/{chunk-L6XCRIR2.js → chunk-3WCIX4VH.js} +1 -1
- package/dist/{chunk-6NDL2ELB.js → chunk-5BPZUW6B.js} +1 -1
- package/dist/{chunk-CW7MTKXP.js → chunk-67WFVDTV.js} +1 -1
- package/dist/{chunk-HEPQNLR2.js → chunk-6VVQWTHV.js} +1 -1
- package/dist/{chunk-LZYQA3Q4.js → chunk-6XRQR43F.js} +1 -1
- package/dist/{chunk-4CJUGCMG.js → chunk-72UVQYXH.js} +1 -1
- package/dist/{chunk-XLOCTL2Y.js → chunk-7CZEXBQY.js} +1 -1
- package/dist/{chunk-CAOUMQZ6.js → chunk-7KW3LCWQ.js} +1 -1
- package/dist/{chunk-45PGU2HW.js → chunk-7ZAM4YRK.js} +1 -1
- package/dist/{chunk-TJRXWGKB.js → chunk-A5WUQLAO.js} +1 -1
- package/dist/{chunk-HXXUZ6RR.js → chunk-BLXI5I3S.js} +2 -2
- package/dist/{chunk-LWIBARE4.js → chunk-BOT6ZDLK.js} +1 -1
- package/dist/{chunk-VEGGHQTQ.js → chunk-CHRNCOXJ.js} +1 -1
- package/dist/{chunk-FWM3577O.js → chunk-CO6HDNOC.js} +1 -1
- package/dist/{chunk-T44KC4GO.js → chunk-DUS5V65Z.js} +1 -1
- package/dist/{chunk-SQMA5YYI.js → chunk-EQBJNU6R.js} +1 -1
- package/dist/{chunk-BSPJMJDI.js → chunk-EQUVI5QU.js} +1 -1
- package/dist/{chunk-D7SPHHSF.js → chunk-F4AIEI5N.js} +1 -1
- package/dist/{chunk-5MPALDJL.js → chunk-FFEJS4K3.js} +1 -1
- package/dist/{chunk-VPT5MFDG.js → chunk-FYMVNLQN.js} +2 -2
- package/dist/{chunk-2HIWXIJE.js → chunk-FYUMVOCV.js} +1 -1
- package/dist/{chunk-JXVZK3RZ.js → chunk-GADT6JMW.js} +1 -1
- package/dist/{chunk-ABLGIN4X.js → chunk-GB74QWAG.js} +1 -1
- package/dist/{chunk-7RBU7UEU.js → chunk-GJPOVI7F.js} +1 -1
- package/dist/{chunk-6FWT2BXF.js → chunk-I5ZXIKOT.js} +1 -1
- package/dist/{chunk-LUYWRWJ2.js → chunk-KCUE2VFJ.js} +1 -1
- package/dist/{chunk-VZMLPENL.js → chunk-KX67ZM7H.js} +1 -1
- package/dist/{chunk-XX5O7H6R.js → chunk-LFR2LWYC.js} +1 -1
- package/dist/{chunk-FVYB2P6Y.js → chunk-LQV7EC5H.js} +1 -1
- package/dist/{chunk-BN6UIKEV.js → chunk-MOIVJERE.js} +1 -1
- package/dist/{chunk-CDFRRXSQ.js → chunk-NS4YGWQP.js} +1 -1
- package/dist/{chunk-ZBV6DOEY.js → chunk-ORR47GDS.js} +1 -1
- package/dist/{chunk-IHAMRL3F.js → chunk-PG5Q3B7Z.js} +1 -1
- package/dist/chunk-PGKKIL6M.js +1 -0
- package/dist/{chunk-N6RBDJ5Y.js → chunk-PGNIOWKY.js} +1 -1
- package/dist/{chunk-OZ32ZMZZ.js → chunk-PUDTOCQF.js} +1 -1
- package/dist/{chunk-HXWWH644.js → chunk-SX7U2ONB.js} +1 -1
- package/dist/chunk-SYFRWKJP.js +1 -0
- package/dist/{chunk-5X7PTCI4.js → chunk-UGATOG2T.js} +1 -1
- package/dist/{chunk-IXDARDPI.js → chunk-VXNN3RV3.js} +1 -1
- package/dist/{chunk-ZP5XCBBK.js → chunk-WU6HDOZM.js} +1 -1
- package/dist/{chunk-CZ33YJWK.js → chunk-XH6VXXCX.js} +1 -1
- package/dist/{chunk-EDZJ2IGA.js → chunk-Y3W5G4BF.js} +1 -1
- package/dist/{chunk-R4ETTZ2H.js → chunk-Y6KA56V2.js} +1 -1
- package/dist/{chunk-IEKRWGRV.js → chunk-YQ2PQWHZ.js} +1 -1
- package/dist/{chunk-YXD5B3UB.js → chunk-Z5JTYDD5.js} +1 -1
- package/dist/{chunk-NJNENW5L.js → chunk-ZHVVJBT6.js} +1 -1
- package/dist/{content-AD7CZRT4.js → content-6MJOU3SX.js} +1 -1
- package/dist/{funnel-host-purchase-45TUH4H2.js → funnel-host-purchase-526HVMXY.js} +1 -1
- package/dist/funnel-host-recovery-paywall-GRX7CLGF.js +1 -0
- package/dist/{funnel-paywall-copies-BPHMFJ2K.js → funnel-paywall-copies-SKNQNABD.js} +1 -1
- package/dist/funnel-paywall-prerender-GVHYSFWI.js +1 -0
- package/dist/funnel-route-prediction-Q4HMRAVQ.js +1 -0
- package/dist/funnel-route-source-HYWJWEM3.js +1 -0
- package/dist/funnel-runtime-host-4KBMPKBE.js +1 -0
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-OIYML3DE.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-3JEVPMO2.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-22EYVJAK.js +1 -0
- package/dist/paywall-content-XH344BMX.js +1 -0
- package/dist/paywall-session-TJ3X7NZA.js +1 -0
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-HJOKBOZH.js +1 -0
- package/dist/server.js +1 -1
- package/dist/{visual-dom-5LUN4AHO.js → visual-dom-KUABNJV6.js} +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/check-response-DO2R3PE6.js +0 -1
- package/dist/chunk-E773KSFH.js +0 -1
- package/dist/chunk-PX7APKZR.js +0 -1
- package/dist/funnel-host-recovery-paywall-JQWNXDLS.js +0 -1
- package/dist/funnel-paywall-prerender-RSXERNQ3.js +0 -1
- package/dist/funnel-route-prediction-G4OKIQGD.js +0 -1
- package/dist/funnel-route-source-W4R62B7H.js +0 -1
- package/dist/funnel-runtime-host-TQAFDG3X.js +0 -1
- package/dist/merchant-bridge-contracts-ADLTLAJJ.js +0 -1
- package/dist/operation-contracts-WLKY7HAO.js +0 -1
- package/dist/paywall-3P5YKZRE.js +0 -1
- package/dist/paywall-content-JJCSFM6J.js +0 -1
- package/dist/paywall-session-AWH5GSKC.js +0 -1
- package/dist/screen-renderer-TZIU775B.js +0 -1
- /package/dist/{chunk-HXXUZ6RR.js.LEGAL.txt → chunk-BLXI5I3S.js.LEGAL.txt} +0 -0
- /package/dist/{chunk-CILM5XMH.js → chunk-FRK6322O.js} +0 -0
- /package/dist/{chunk-VPT5MFDG.js.LEGAL.txt → chunk-FYMVNLQN.js.LEGAL.txt} +0 -0
- /package/dist/{chunk-OJM6ORHE.js → chunk-KV5MZ4NI.js} +0 -0
- /package/dist/{chunk-J6MYX7WY.js → chunk-W22ESUYY.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as tn}from"./chunk-D7SPHHSF.js";import{b as rn}from"./chunk-SQMA5YYI.js";import{b as nn}from"./chunk-YXD5B3UB.js";import{d as We,e as ce}from"./chunk-JXVZK3RZ.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-6NDL2ELB.js";import{A as Je,F as He,G as Qe,H as z,I as Ye,J as le,K as G,a as Me,c as Y,g as Z,h as Ge,i as Ue,m as $e}from"./chunk-6FWT2BXF.js";import{A as ie,B as ae,z as oe}from"./chunk-DLLC7CRI.js";import{a as de,b as Xe}from"./chunk-VZMLPENL.js";import{a as j,b as _e,c as ke,e as De,h as Ve,i as Le,l as Be}from"./chunk-HEPQNLR2.js";import{b as W}from"./chunk-L6XCRIR2.js";import{a as Q}from"./chunk-LUYWRWJ2.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-EDZJ2IGA.js";import{g as Ee,m as Ce,w as re}from"./chunk-2HIWXIJE.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-TJRXWGKB.js";import{a as m}from"./chunk-5X7PTCI4.js";import{h as V}from"./chunk-XX5O7H6R.js";import{a as en}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-J6MYX7WY.js";import{a as on}from"./chunk-DSPLGTQI.js";import{c as Ne,f as Oe}from"./chunk-VPT5MFDG.js";function an(e){return Fn({...e,namespace:"commands",identity:[e.runToken]})}function Fn(e){let t,u,r=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),o=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??en).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,i=>i.toString(16).padStart(2,"0")).join("")});o.catch(()=>{});async function p(c){try{let a=await o;return await u.request(a,{mode:"exclusive"},()=>c(a))}catch(a){throw a instanceof m?a:r()}}function d(c){let a=t.getItem(c);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let i=JSON.parse(a);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw r();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>p(d),write:(c,a)=>p(i=>{if(d(i).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw r();let y=JSON.stringify({revision:c+1,entry:a});if(y.length>1048576)throw r();return t.setItem(i,y),c+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var M=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),En=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Cn=n.discriminatedUnion("type",[$e,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:M.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:He,openIn:Qe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:M})]),Pn={id:M,presentation:Pe,outputs:n.array(M).max(250),nextPaywalls:n.record(M,n.strictObject({paywallVersionId:n.uuid()})).optional(),inputs:se,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Ee,customerData:Ce,dataCursors:n.record(M,Ke.nullable())},Nn=n.strictObject({...Pn,content:n.strictObject({type:n.literal("document"),document:re})}),pe=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:M,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:En,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:ue,parameters:ze,variables:n.record(n.string(),L),output:L.nullable(),screen:Nn.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([We,ce]),quote:oe.nullable(),operation:ie.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Cn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),On=n.strictObject({scope:V,run:pe,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:oe.nullable(),operation:ie.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative(),document:re,answers:ue,inputs:se,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()}),sn=On.extend({run:pe.extend({paywall:pe.shape.paywall.unwrap().extend({resolution:ce}).nullable()})});var ln="X-Indiana-Server-Key";var An=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()}),Tn=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(An).max(200).default([]),iam:Ge.optional(),renderGuard:Z.optional()}),me=Tn.omit({variation:!0,description:!0,iam:!0}),_n=qe.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([me,me]).rest(me).refine(e=>e.length<=20)}),cn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(_n).max(100),savedGroups:je});var $=n.string().regex(/^[a-f0-9]{64}$/),Tt=n.strictObject({iam:$,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),kn=n.strictObject({release:$,render:Z,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),_t=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:$,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:Ue.optional(),target:kn})).max(4e3)}),kt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:$,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Dt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Vt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=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)}),fe=n.strictObject({operation:n.literal("page_experiments"),release:$,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(Q).optional()}),dn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:cn});var U=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),mn=n.strictObject({entry:U,nodes:n.array(n.strictObject({id:U,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),U),writes:n.record(j,j),resources:n.strictObject({screenId:U.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)}),pn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:mn},X=n.discriminatedUnion("evaluationMode",[n.strictObject({...pn,evaluationMode:n.literal("local"),growth:K,conditions:n.record(U,n.array(n.strictObject({condition:Te,port:n.string()})))}),n.strictObject({...pn,evaluationMode:n.literal("remote")})]),Vn=X.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,ke),outputSchema:_e,terminals:n.record(U,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Je.nullable()}))})});function Ln(e){return mn.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(d=>d.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,d)=>{u[`case:${d}`]=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 o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.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 ge(e){let t=le.parse(e.document),u=e.evaluationMode==="local"?K.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:Ln(t)};return X.parse(e.evaluationMode==="remote"?r:{...r,growth:Ze(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((p,d)=>({condition:p.condition,port:`case:${d}`}))]))})}function $t(e){let t=ge(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=le.parse(e.document);return Vn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}var Ie=32,Mn=522240;function ve(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 qn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),ye=n.record(n.string(),L),jn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:z.shape.schemaVersion,kind:z.shape.kind,selector:z.shape.selector,contract:z.shape.contract}),context:ye,removed:n.array(n.string()).max(100),attributes:ye,removedAttributes:n.array(n.string()).max(100),result:Ye,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()})}),Wt=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:ye,steps:n.array(jn).min(1).max(Ie)}).refine(e=>Y(e)<=Mn,"Segment exceeds its byte budget");var Gn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function J(e){return Array.isArray(e)?e.some(J):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&J(u):!Gn.test(t))}function fn(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(c=>c.id===t.screenId&&c.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(c=>J(c.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(c=>c.id===t.screenId):null]);for(let[c,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${c}`)||p.includes(JSON.stringify(c))))return"customer_required";if(t.type==="split"){let c=u.experiments?.[t.experimentId];if((c?.hashAttribute??"id")!=="funnelParticipantId"||J(c?.condition)||c?.parentConditions?.length)return"customer_experiment_required"}let d=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return d&&u.features?.[d]?.rules?.some(c=>(c.hashAttribute??"id")!=="funnelParticipantId"||J(c.condition)||c.parentConditions?.length)?"customer_experiment_required":null}var he=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},ee=(e,t)=>new he(e,t),Un=e=>({experiments:e.experiments,features:e.features});function we(e,t=ee){let u=new Map(e.topology.nodes.map(d=>[d.id,d])),r=Ne(e.growth.savedGroups),o=Un(e.growth);function p(d,c){if(!Object.hasOwn(e.growth.features,d))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Oe(d,c).value}return{nodes:u,savedGroups:r,features:o.features,feature:p,evaluate(d,c){let a=u.get(d);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let i,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");i=de({id:a.id,name:a.id,type:"condition",cases:v.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},c,o.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,c),i="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=de({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},c,o.experiments);g=h.value,i=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,c),i=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[i]??(i==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:i,target:y,...g===void 0?{}:{value:g}}}}}function dr(e,t,u,r=ee){return be(e,r)(t,u)}function be(e,t){let u=X.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,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let p=we(u,t);return(d,c)=>(o(),Bn(p,d,c))}function Bn(e,t,u){let r=Ae.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:p,onExperimentViewed:d}=u,c={attributes:r,...o?{saveStickyBucketAssignmentDoc:a=>o(structuredClone(a))}:{},...p?{onFeatureUsage:(a,i)=>p(a,structuredClone(i))}:{},...d?{onExperimentViewed:(a,i)=>d(structuredClone(a),structuredClone(i))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function pr(e,t,u,r=ee){return gn(be(e,r),t,u)}function gn(e,t,u){let r=[],o=[],p=[],d=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(c){let a=r.findIndex(y=>y.next.attributeName===c.attributeName&&y.next.attributeValue===c.attributeValue),i=c.attributeName+"||"+c.attributeValue,g={expected:u.sticky[i]??null,next:c};a<0?r.push(g):r[a]=g},onExperimentViewed(c,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&o.push(L.parse({key:c.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(c,a){p.push(L.parse({feature:c,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:d.port,...d.value===void 0?{}:{value:d.value},sticky:r,exposures:o,features:p}}function yn(e,t,u,r=ee){let o=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),d=structuredClone(u.variables),c=structuredClone(o.sticky),a=[],i=u.nodeId,g=u.visit,y=!1,v,h=O=>fn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),R=O=>(v??=be(e,r),gn(v,O,{attributes:Be({declarations:t.variables,attributes:o.attributes,parameters:u.parameters,answers:u.answers,results:d,savedGroups:{}}),sticky:c}));for(let O=0;O<Ie;O++){let s=p.get(i);if(!s||!ve(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 f,w;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")f=R(s.id),s.type==="offering"&&(f.value={type:"offering_version",id:String(f.value)}),s.type==="condition"?w=f.port==="default"?s.default:s.cases[Number(f.port.slice(5))]?.target:s.type==="split"?w=f.port==="notParticipating"?s.notParticipating:s.routes[f.port]:(s.type==="feature"||s.type==="offering")&&(w=s.next);else if(f={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(w=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(f.value={type:"offering_version",id:s.configuration.versionId},w=s.next),s.type==="end"||s.type==="output"){let x=s.type==="end"?s.output:s.value;if(f=x?.type==="feature"?R(s.id):{...f,port:"value",value:x?.type==="literal"?x.value:x?.type==="variable"?Me({source:"variable",key:x.key,...x.path?{path:x.path}:{}},{declarations:t.variables,answers:u.answers,results:d,parameters:u.parameters,attributes:o.attributes,savedGroups:{}}):null},x&&(f.value===void 0||!De(t.outputSchema,f.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:i,result:f}];if(Y({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:i,result:f}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let x=s.type==="coupons"?s.couponIds.map(D=>({type:"reward",id:D})):s.type==="coupon"?{type:"reward",id:s.couponId}:f.value;if(x===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=Ve(s,{value:x});Le(t.variables,s,_),Object.assign(d,_)}for(let x of f.sticky)c[`${x.next.attributeName}||${x.next.attributeValue}`]=structuredClone(x.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!w)throw r("INVALID_RESPONSE","Local pure exit is unavailable");i=w,g++}let T=p.get(i);return{steps:a,...!y&&T&&(!ve(T)||h(T))?{boundary:{nodeId:i,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new m("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 m("SCOPE_MISMATCH","Funnel scope changed");return r}var xe=(e,t)=>new m(e,t);function hr(e){return we(e,xe)}var Kn=3,zn=2e3;function $n(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Jn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Kn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*zn))}}async function Re(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 m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let o=null,p;if(u)try{let d=await e.funnel(t.source.id,t.source.versionId);p=d.manifest.generation,o=Hn(e,t,d)}catch{o=null}return p??=e.snapshot?.generation??(await Jn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:o}}function Hn(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:o,remoteFeatures:p,...d}=u.growth,c=ge({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:K.parse(d)}),a=Qn(c,u.document,{...t,...r}),i=a.steps.at(-1),g=a.boundary??(i?.result.port==="value"?{nodeId:i.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 Qn(e,t,u){return yn(e,t,u,xe)}var vn=G.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:vn.optional(),closeCommand:vn.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 m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ne=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function H(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 wn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),o=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:hn.parse(a.entry)}}function d(a){let i=o.then(a);return o=i.catch(()=>{}),i}async function c(a){for(let i=0;i<4;i++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(ne(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let i=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==i)throw A();u=i},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let i=hn.parse(a),g=i.command;return!g||u!==null&&r(i)!==u?Promise.reject(A()):(u??=r(i),d(()=>c((y,v)=>{if(y&&!ne(r(y),r(i)))throw A();if(y&&i.processBindingIds){for(let[h,R]of Object.entries(i.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==R)throw A();y={...y,processBindingIds:{...y.processBindingIds,...i.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return i}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&&!ne(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!ne(y.command,g))throw A();return y})))},observePurchase(a,i,g,y){return d(()=>c((v,h)=>{if(!v&&h!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>i.generation)return H(v,y);if(v?.purchase&&v.purchase.generation===i.generation&&v.purchase.operationId!==i.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==i.operationId?H(v,y):H(v.command?{...v,purchase:void 0}:null,y):H({schemaVersion:1,...a,...v,purchase:i},y)}))},settle(a){return d(()=>c(i=>H(i,a)))}}}function Tr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function te(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((o,p)=>te(o,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(([o,p])=>Object.hasOwn(t,o)&&te(p,Reflect.get(t,o)))}function bn(e,t){let u=t&&{...t},r=null,o=0,p=-1,d=0,c=new AbortController;function a(){d++,c.abort(new m("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let i=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new m("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===d?r:null},get viewAgeMs(){return r&&p===d?performance.now()-o:void 0},get generation(){return d},get signal(){return c.signal},get disposed(){return i},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,R="Run identity changed during the request"){if(h!==d||i)throw new m("IDENTITY_CHANGED",R)},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||!te(h.parameters,r.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,R,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&R.run.revision<=r.revision)&&!(r&&R.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r&&p===d&&R.run.nodeId===r.nodeId&&R.run.visit===r.visit&&R.run.revision===r.revision&&(R.run.screen=r.screen,(r.paywall?.quote?.operationId===R.review?.activeOperationId||!r.paywall?.quote&&R.review?.activeOperationId===null)&&(R.run.paywall=r.paywall)),!(r?.paywall&&R.run.paywall&&r.paywall.receiptId===R.run.paywall.receiptId&&(R.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||R.run.revision>=r.revision)r=R.run,o=performance.now(),p=d;else if(!s)return;if(r&&p===d)for(let f of v)try{f(structuredClone(r))}catch{}}},identify(h){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!Q.test(h))throw new m("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return v.add(h),()=>v.delete(h)},reset(){i||(i=!0,a(),g=void 0,r=null,v.clear())}}}var Se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function qr(e,t,u="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",t);if(!Se.test(e))throw new m("INVALID_TOKEN",u)}function jr(e){let t=W(e);return t.identify(e.apiKey),t}function xn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&!ae(t)&&["apple","google"].includes(t.provider)?"native":t&&!ae(t)&&t.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new m("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function q(e){let{customerToken:t,...u}=e;return u}var Yn=e=>!(e instanceof m&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Rn({journal:e,state:t,call:u,processIdentity:r}){let o=null,p=null,d=!1,c={command:null,close:null},a=new Set,i,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(w=>w&&!Object.hasOwn(s.processBindingIds??{},w.requestId)))throw new m("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 m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,d=s.closed===!0,!s.command)return;let f=s.command;o=f.operation==="close"?null:f,p=f.operation==="close"?f:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(d=!0);for(let w of[o,p])w&&a.add(w.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s,f){e&&await y;let w=t.generation;if(e){if(!t.view||!t.scope)throw new m("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:q(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(w!==t.generation||o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");if(e&&on(f),t.assertCurrent(w),o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let N=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(x){let _=s.operation==="submit"&&s.input.type==="paywall_quote",D=!N&&!Yn(x),l=!1;if(_&&D&&w===t.generation&&o===s&&x instanceof m&&x.status!==void 0){let I=await T(s.requestId).catch(()=>{});l=I?.settlement?.state==="unknown"&&I.settlement.operationId===null}throw w===t.generation&&(o===s||p===s)&&D&&(!_||!(x instanceof m)||x.status===void 0||l)&&(e&&await e.settle(s.requestId),w===t.generation&&O(s)),x}}function h(s,f){let w=G.parse(s);if(w.operation==="start"||w.operation==="get"||w.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(d&&w.operation!=="close"){if(o?.requestId===w.requestId)return T(w.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(w.operation==="close"){if(o?.requestId===w.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(d=!0,p&&JSON.stringify(q(p))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original Close");return p??=w,c.close?c.close:R(p,"close",f)}if(o){if(JSON.stringify(q(o))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else o=w;return R(o,"command",f)}function R(s,f,w){let N=v(s,w);c[f]=N;let x=()=>{c[f]===N&&(c[f]=null)};return N.then(x,x),N}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||o!==s&&p!==s?!1:(o===s&&(o=null),p===s&&(p=null),a.delete(s.requestId),!o&&!p&&(g=null),!0)}return{ready:y,get pending(){return o},get closing(){return p},get closeRequested(){return d},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return i},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,f,w,N){let x=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=x&&f.settlement?.state==="settled"&&f.run.pendingRequest?.requestId!==x&&(s.operation==="get"||!d||s.operation==="close"||!["running","waiting"].includes(f.run.status))?x:void 0,D=o?.requestId===_?o:p?.requestId===_?p:void 0;e?.bind({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId});let l=f.run.paywall,I=l??f.purchase,C=I?.operation,E=f.settlement&&(!l||l.purchaseRequestId===f.settlement.requestId)&&(!i||i.operationId===f.settlement.operationId)?f.settlement:void 0,S=C?.operationId??I?.quote?.operationId??E?.operationId,F=I?.receiptId??E?.receiptId,b=l?.selectionGeneration??i?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||f.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!i||b>=i.generation)){let P={receiptId:F,operationId:S,generation:b},k=rn(C,I?.canReselect===!0);await e.observePurchase({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId},P,k,_),t.assertCurrent(w),(!i||P.generation>=i.generation)&&(N===void 0||N>=t.readSequence)&&(k?i?.operationId===P.operationId&&(i=void 0):i=P)}else e&&_&&await e.settle(_);return t.assertCurrent(w),_?O(D):!1},stop(){d=!0},submit:h,settle:T,reset(){d=!0,o=null,p=null,i=void 0,g=null,c.close=null,a.clear(),c.command=null}}}function Zn(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 m("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new m("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Se.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=W({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),o=bn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(R),d=null,c=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=c&&wn(c),i=Rn({journal:a,state:o,call:T,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function h(l){let I=l.operation==="resume"?i.pending?.operation==="resume"?null:i.pending:l;if(u&&l.operation==="resume"&&!I&&l.requestId!==e.customerRun?.startRequestId)throw new m("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let P=o.view?.paywall;xn(u,P?.quote?.operationId===I.input.operationId?P.quote:void 0)}if(e.process)return e.process.request(l);let C=o.generation;o.assertCurrent(C);let E=performance.now()+(e.timeoutMs??35e3),S=o.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let P=o.signal,k,B=()=>{},Sn=new Promise((Wn,Fe)=>{B=()=>Fe(P.reason),P.addEventListener("abort",B,{once:!0}),k=setTimeout(()=>Fe(new m("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(o.assertCurrent(C),e.session.access())),Sn])}finally{clearTimeout(k),P.removeEventListener("abort",B)}}o.assertCurrent(C);let F={...l,...S?{customerToken:S}:{}},b=l.operation==="page_experiments"?fe.parse(F):G.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new m("IDENTITY_CHANGED","Original recovery Customer changed");let P={...b};return"customerToken"in P&&delete P.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:P},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",b,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function R(){v(),p?.(),o.reset(),i.reset(),d=null,r.dispose()}async function T(l,I){let C=t;t=void 0;let E=o.generation,S=()=>o.assertCurrent(E);a&&await i.ready,S();let F=o.view,b=In(e,C!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?C:await h(l));if(l.operation==="review"&&!b.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&b.run.id!==e.customerRun.runId)throw new m("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&b.purchase&&(b.purchase.receiptId!==l.purchase.receiptId||(b.purchase.operation?.operationId??b.purchase.quote?.operationId)!==l.purchase.operationId))throw new m("INVALID_RESPONSE","The requested original purchase changed");if(S(),b.runToken&&b.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let P=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(P&&b.settlement?.requestId!==P)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(b),o.assertRun(b.run),o.bindScope(b.scope);let k=await i.observe(l,b,E,I);return(!o.view||b.run.revision>=o.view.revision)&&(I===void 0||I>=o.readSequence)&&(await e.onAcceptedResponse?.(b),S()),!b.run.stopped&&["running","waiting"].includes(b.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(b.run.status)||i.stop(),o.publish(l,b,F,I,k)),b}function O(l){let I=o.generation;v();let C=l(),E=()=>{o.generation===I&&v()};return C.then(E,E),C}let s=(l,I)=>O(()=>i.submit(l,I)),f=null,w=new WeakMap;function N(l){let I=w.get(l);if(I)return I;let C=_(l);return w.set(l,C),C}let x=!1;async function _(l){let I=await l;if(I.run.instruction?.type!=="evaluate_segment")return I;if(f)return f;x=!0;let C=o.generation,E=(async()=>{for(let S=0;S<32&&I.run.instruction?.type==="evaluate_segment";S++){if(i.pending||i.closeRequested)return I;let F=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:P}=await Re(e.configuration,F,{predict:!1});if(C!==o.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(o.view&&(o.view.revision!==F.revision||o.view.visit!==F.visit||o.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Re(e.configuration,F).then(({prediction:B})=>{k&&C===o.generation&&!i.closeRequested&&o.view?.id===F.id&&!o.view.stopped&&o.view.nodeId===F.nodeId&&o.view.visit===F.visit&&o.view.revision===F.revision&&(d=B)}).catch(()=>{});try{I=await s({operation:"commit_segment",requestId:Xe(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...P})}finally{k=!1,d=null}}}return I})();f=E;try{return await E}finally{f===E&&(f=null)}}let D={get configuration(){return x?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=o.currentView;return l?structuredClone(l):null},get viewAgeMs(){return o.viewAgeMs},get pendingCommand(){let l=i.closing??i.pending;return l?structuredClone(q(l)):null},get pendingCommands(){return[i.pending,i.closing].filter(l=>l!==null).map(l=>structuredClone(q(l)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=o.view;return d&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===d.runId&&l.nodeId===d.from.nodeId&&l.visit===d.from.visit&&l.revision===d.from.revision&&!i.closeRequested?structuredClone(d):null},settle:(...l)=>O(()=>i.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return nn(e,l)},async pageExperiments(l,I=[]){let C=o.generation;o.assertCurrent(C);let E=o.view?.id;if(!E)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=dn.parse(await h(fe.parse({operation:"page_experiments",release:l,usedReceiptIds:I})));if(o.assertCurrent(C),S.runId!==E||S.scope.projectId!==o.scope?.projectId||S.scope.environment!==o.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},o.nextRead())},async get(l,I){let C=o.generation;l=l&&structuredClone(l),I=I&&{...I},a&&await i.ready,o.assertCurrent(C),I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let E=JSON.stringify([o.generation,g,l??null,I??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=o.nextRead(),b=N(T({operation:"get",...l?{data:l}:{},...I?{purchase:I}:{}},F));y.set(E,b);let P=()=>{y.get(E)===b&&y.delete(E)};return b.then(P,P),b.then(k=>structuredClone(k))},resume(l=o.view?.pendingRequest?.requestId){return l?i.closeRequested?D.settle(l):i.pending?.requestId===l?N(s(i.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},async retry(){if(i.closeFlight)return i.closeFlight;if(i.closing)return s(i.closing);if(i.closeRequested&&i.pending)return D.settle(i.pending.requestId);if(i.inFlight)return N(i.inFlight);if(!i.pending)throw new m("INVALID_REQUEST","No command is pending");let l=i.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let I=o.generation;if(await D.settle(l.requestId),o.assertCurrent(I),!i.pending)return D.get();if(i.pending!==l||i.closeRequested)throw new m("COMMAND_PENDING","The original quote is being recovered")}return N(s(l))},identify(l){let I=o.customerToken?void 0:t;v(),o.identify(l),t=I,d=null,r.reset()},get identitySignal(){return o.signal},subscribe:o.subscribe,reset:R};return tn(D,(l,I)=>N(s(l,I))),D}function po(e,t){return Zn({...e,runToken:"",initialResponse:t})}export{un as a,Cn as b,pe as c,On as d,sn as e,kn as f,_t as g,kt as h,Dt as i,fe as j,dn as k,X as l,Vn as m,$t as n,dr as o,pr as p,In as q,xe as r,hr as s,Qn as t,hn as u,H as v,an as w,Fn as x,Tr as y,te as z,Se as A,qr as B,jr as C,xn as D,Zn as E,po as F};
|
|
1
|
+
import{a as tn}from"./chunk-F4AIEI5N.js";import{b as rn}from"./chunk-EQBJNU6R.js";import{b as nn}from"./chunk-Z5JTYDD5.js";import{d as We,e as ce}from"./chunk-GADT6JMW.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-5BPZUW6B.js";import{A as Je,F as He,G as Qe,H as z,I as Ye,J as le,K as G,a as Me,c as Y,g as Z,h as Ge,i as Ue,m as $e}from"./chunk-I5ZXIKOT.js";import{A as ie,B as ae,z as oe}from"./chunk-3532HSBP.js";import{a as de,b as Xe}from"./chunk-KX67ZM7H.js";import{a as j,b as _e,c as ke,e as De,h as Ve,i as Le,l as Be}from"./chunk-6VVQWTHV.js";import{b as W}from"./chunk-3WCIX4VH.js";import{a as Q}from"./chunk-KCUE2VFJ.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-Y3W5G4BF.js";import{g as Ee,m as Ce,w as re}from"./chunk-FYUMVOCV.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-A5WUQLAO.js";import{a as m}from"./chunk-UGATOG2T.js";import{h as V}from"./chunk-LFR2LWYC.js";import{a as en}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-W22ESUYY.js";import{a as on}from"./chunk-DSPLGTQI.js";import{c as Ne,f as Oe}from"./chunk-FYMVNLQN.js";function an(e){return Fn({...e,namespace:"commands",identity:[e.runToken]})}function Fn(e){let t,u,r=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),o=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??en).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,i=>i.toString(16).padStart(2,"0")).join("")});o.catch(()=>{});async function p(c){try{let a=await o;return await u.request(a,{mode:"exclusive"},()=>c(a))}catch(a){throw a instanceof m?a:r()}}function d(c){let a=t.getItem(c);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let i=JSON.parse(a);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw r();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>p(d),write:(c,a)=>p(i=>{if(d(i).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw r();let y=JSON.stringify({revision:c+1,entry:a});if(y.length>1048576)throw r();return t.setItem(i,y),c+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var M=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),En=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Cn=n.discriminatedUnion("type",[$e,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:M.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:He,openIn:Qe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:M})]),Pn={id:M,presentation:Pe,outputs:n.array(M).max(250),nextPaywalls:n.record(M,n.strictObject({paywallVersionId:n.uuid()})).optional(),inputs:se,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Ee,customerData:Ce,dataCursors:n.record(M,Ke.nullable())},Nn=n.strictObject({...Pn,content:n.strictObject({type:n.literal("document"),document:re})}),pe=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:M,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:En,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:ue,parameters:ze,variables:n.record(n.string(),L),output:L.nullable(),screen:Nn.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([We,ce]),quote:oe.nullable(),operation:ie.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Cn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),On=n.strictObject({scope:V,run:pe,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:oe.nullable(),operation:ie.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative(),document:re,answers:ue,inputs:se,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()}),sn=On.extend({run:pe.extend({paywall:pe.shape.paywall.unwrap().extend({resolution:ce}).nullable()})});var ln="X-Indiana-Server-Key";var An=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()}),Tn=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(An).max(200).default([]),iam:Ge.optional(),renderGuard:Z.optional()}),me=Tn.omit({variation:!0,description:!0,iam:!0}),_n=qe.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([me,me]).rest(me).refine(e=>e.length<=20)}),cn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(_n).max(100),savedGroups:je});var $=n.string().regex(/^[a-f0-9]{64}$/),Tt=n.strictObject({iam:$,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),kn=n.strictObject({release:$,render:Z,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),_t=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:$,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:Ue.optional(),target:kn})).max(4e3)}),kt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:$,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Dt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Vt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=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)}),fe=n.strictObject({operation:n.literal("page_experiments"),release:$,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(Q).optional()}),dn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:cn});var U=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),mn=n.strictObject({entry:U,nodes:n.array(n.strictObject({id:U,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),U),writes:n.record(j,j),resources:n.strictObject({screenId:U.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)}),pn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:mn},X=n.discriminatedUnion("evaluationMode",[n.strictObject({...pn,evaluationMode:n.literal("local"),growth:K,conditions:n.record(U,n.array(n.strictObject({condition:Te,port:n.string()})))}),n.strictObject({...pn,evaluationMode:n.literal("remote")})]),Vn=X.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,ke),outputSchema:_e,terminals:n.record(U,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Je.nullable()}))})});function Ln(e){return mn.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(d=>d.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,d)=>{u[`case:${d}`]=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 o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.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 ge(e){let t=le.parse(e.document),u=e.evaluationMode==="local"?K.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:Ln(t)};return X.parse(e.evaluationMode==="remote"?r:{...r,growth:Ze(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((p,d)=>({condition:p.condition,port:`case:${d}`}))]))})}function $t(e){let t=ge(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=le.parse(e.document);return Vn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}var Ie=32,Mn=522240;function ve(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 qn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),ye=n.record(n.string(),L),jn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:z.shape.schemaVersion,kind:z.shape.kind,selector:z.shape.selector,contract:z.shape.contract}),context:ye,removed:n.array(n.string()).max(100),attributes:ye,removedAttributes:n.array(n.string()).max(100),result:Ye,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()})}),Wt=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:ye,steps:n.array(jn).min(1).max(Ie)}).refine(e=>Y(e)<=Mn,"Segment exceeds its byte budget");var Gn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function J(e){return Array.isArray(e)?e.some(J):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&J(u):!Gn.test(t))}function fn(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(c=>c.id===t.screenId&&c.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(c=>J(c.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(c=>c.id===t.screenId):null]);for(let[c,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${c}`)||p.includes(JSON.stringify(c))))return"customer_required";if(t.type==="split"){let c=u.experiments?.[t.experimentId];if((c?.hashAttribute??"id")!=="funnelParticipantId"||J(c?.condition)||c?.parentConditions?.length)return"customer_experiment_required"}let d=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return d&&u.features?.[d]?.rules?.some(c=>(c.hashAttribute??"id")!=="funnelParticipantId"||J(c.condition)||c.parentConditions?.length)?"customer_experiment_required":null}var he=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},ee=(e,t)=>new he(e,t),Un=e=>({experiments:e.experiments,features:e.features});function we(e,t=ee){let u=new Map(e.topology.nodes.map(d=>[d.id,d])),r=Ne(e.growth.savedGroups),o=Un(e.growth);function p(d,c){if(!Object.hasOwn(e.growth.features,d))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Oe(d,c).value}return{nodes:u,savedGroups:r,features:o.features,feature:p,evaluate(d,c){let a=u.get(d);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let i,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");i=de({id:a.id,name:a.id,type:"condition",cases:v.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},c,o.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,c),i="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=de({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},c,o.experiments);g=h.value,i=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,c),i=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[i]??(i==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:i,target:y,...g===void 0?{}:{value:g}}}}}function dr(e,t,u,r=ee){return be(e,r)(t,u)}function be(e,t){let u=X.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,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let p=we(u,t);return(d,c)=>(o(),Bn(p,d,c))}function Bn(e,t,u){let r=Ae.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:p,onExperimentViewed:d}=u,c={attributes:r,...o?{saveStickyBucketAssignmentDoc:a=>o(structuredClone(a))}:{},...p?{onFeatureUsage:(a,i)=>p(a,structuredClone(i))}:{},...d?{onExperimentViewed:(a,i)=>d(structuredClone(a),structuredClone(i))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function pr(e,t,u,r=ee){return gn(be(e,r),t,u)}function gn(e,t,u){let r=[],o=[],p=[],d=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(c){let a=r.findIndex(y=>y.next.attributeName===c.attributeName&&y.next.attributeValue===c.attributeValue),i=c.attributeName+"||"+c.attributeValue,g={expected:u.sticky[i]??null,next:c};a<0?r.push(g):r[a]=g},onExperimentViewed(c,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&o.push(L.parse({key:c.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(c,a){p.push(L.parse({feature:c,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:d.port,...d.value===void 0?{}:{value:d.value},sticky:r,exposures:o,features:p}}function yn(e,t,u,r=ee){let o=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),d=structuredClone(u.variables),c=structuredClone(o.sticky),a=[],i=u.nodeId,g=u.visit,y=!1,v,h=O=>fn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),R=O=>(v??=be(e,r),gn(v,O,{attributes:Be({declarations:t.variables,attributes:o.attributes,parameters:u.parameters,answers:u.answers,results:d,savedGroups:{}}),sticky:c}));for(let O=0;O<Ie;O++){let s=p.get(i);if(!s||!ve(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 f,w;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")f=R(s.id),s.type==="offering"&&(f.value={type:"offering_version",id:String(f.value)}),s.type==="condition"?w=f.port==="default"?s.default:s.cases[Number(f.port.slice(5))]?.target:s.type==="split"?w=f.port==="notParticipating"?s.notParticipating:s.routes[f.port]:(s.type==="feature"||s.type==="offering")&&(w=s.next);else if(f={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(w=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(f.value={type:"offering_version",id:s.configuration.versionId},w=s.next),s.type==="end"||s.type==="output"){let x=s.type==="end"?s.output:s.value;if(f=x?.type==="feature"?R(s.id):{...f,port:"value",value:x?.type==="literal"?x.value:x?.type==="variable"?Me({source:"variable",key:x.key,...x.path?{path:x.path}:{}},{declarations:t.variables,answers:u.answers,results:d,parameters:u.parameters,attributes:o.attributes,savedGroups:{}}):null},x&&(f.value===void 0||!De(t.outputSchema,f.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:i,result:f}];if(Y({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:i,result:f}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let x=s.type==="coupons"?s.couponIds.map(D=>({type:"reward",id:D})):s.type==="coupon"?{type:"reward",id:s.couponId}:f.value;if(x===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=Ve(s,{value:x});Le(t.variables,s,_),Object.assign(d,_)}for(let x of f.sticky)c[`${x.next.attributeName}||${x.next.attributeValue}`]=structuredClone(x.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!w)throw r("INVALID_RESPONSE","Local pure exit is unavailable");i=w,g++}let T=p.get(i);return{steps:a,...!y&&T&&(!ve(T)||h(T))?{boundary:{nodeId:i,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new m("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 m("SCOPE_MISMATCH","Funnel scope changed");return r}var xe=(e,t)=>new m(e,t);function hr(e){return we(e,xe)}var Kn=3,zn=2e3;function $n(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Jn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Kn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*zn))}}async function Re(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 m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let o=null,p;if(u)try{let d=await e.funnel(t.source.id,t.source.versionId);p=d.manifest.generation,o=Hn(e,t,d)}catch{o=null}return p??=e.snapshot?.generation??(await Jn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:o}}function Hn(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:o,remoteFeatures:p,...d}=u.growth,c=ge({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:K.parse(d)}),a=Qn(c,u.document,{...t,...r}),i=a.steps.at(-1),g=a.boundary??(i?.result.port==="value"?{nodeId:i.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 Qn(e,t,u){return yn(e,t,u,xe)}var vn=G.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:vn.optional(),closeCommand:vn.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 m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ne=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function H(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 wn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),o=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:hn.parse(a.entry)}}function d(a){let i=o.then(a);return o=i.catch(()=>{}),i}async function c(a){for(let i=0;i<4;i++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(ne(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let i=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==i)throw A();u=i},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let i=hn.parse(a),g=i.command;return!g||u!==null&&r(i)!==u?Promise.reject(A()):(u??=r(i),d(()=>c((y,v)=>{if(y&&!ne(r(y),r(i)))throw A();if(y&&i.processBindingIds){for(let[h,R]of Object.entries(i.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==R)throw A();y={...y,processBindingIds:{...y.processBindingIds,...i.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return i}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&&!ne(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!ne(y.command,g))throw A();return y})))},observePurchase(a,i,g,y){return d(()=>c((v,h)=>{if(!v&&h!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>i.generation)return H(v,y);if(v?.purchase&&v.purchase.generation===i.generation&&v.purchase.operationId!==i.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==i.operationId?H(v,y):H(v.command?{...v,purchase:void 0}:null,y):H({schemaVersion:1,...a,...v,purchase:i},y)}))},settle(a){return d(()=>c(i=>H(i,a)))}}}function Tr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function te(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((o,p)=>te(o,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(([o,p])=>Object.hasOwn(t,o)&&te(p,Reflect.get(t,o)))}function bn(e,t){let u=t&&{...t},r=null,o=0,p=-1,d=0,c=new AbortController;function a(){d++,c.abort(new m("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let i=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new m("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===d?r:null},get viewAgeMs(){return r&&p===d?performance.now()-o:void 0},get generation(){return d},get signal(){return c.signal},get disposed(){return i},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,R="Run identity changed during the request"){if(h!==d||i)throw new m("IDENTITY_CHANGED",R)},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||!te(h.parameters,r.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,R,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&R.run.revision<=r.revision)&&!(r&&R.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r&&p===d&&R.run.nodeId===r.nodeId&&R.run.visit===r.visit&&R.run.revision===r.revision&&(R.run.screen=r.screen,(r.paywall?.quote?.operationId===R.review?.activeOperationId||!r.paywall?.quote&&R.review?.activeOperationId===null)&&(R.run.paywall=r.paywall)),!(r?.paywall&&R.run.paywall&&r.paywall.receiptId===R.run.paywall.receiptId&&(R.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||R.run.revision>=r.revision)r=R.run,o=performance.now(),p=d;else if(!s)return;if(r&&p===d)for(let f of v)try{f(structuredClone(r))}catch{}}},identify(h){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!Q.test(h))throw new m("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return v.add(h),()=>v.delete(h)},reset(){i||(i=!0,a(),g=void 0,r=null,v.clear())}}}var Se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function qr(e,t,u="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",t);if(!Se.test(e))throw new m("INVALID_TOKEN",u)}function jr(e){let t=W(e);return t.identify(e.apiKey),t}function xn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&!ae(t)&&["apple","google"].includes(t.provider)?"native":t&&!ae(t)&&t.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new m("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function q(e){let{customerToken:t,...u}=e;return u}var Yn=e=>!(e instanceof m&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Rn({journal:e,state:t,call:u,processIdentity:r}){let o=null,p=null,d=!1,c={command:null,close:null},a=new Set,i,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(w=>w&&!Object.hasOwn(s.processBindingIds??{},w.requestId)))throw new m("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 m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,d=s.closed===!0,!s.command)return;let f=s.command;o=f.operation==="close"?null:f,p=f.operation==="close"?f:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(d=!0);for(let w of[o,p])w&&a.add(w.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s,f){e&&await y;let w=t.generation;if(e){if(!t.view||!t.scope)throw new m("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:q(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(w!==t.generation||o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");if(e&&on(f),t.assertCurrent(w),o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let N=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(x){let _=s.operation==="submit"&&s.input.type==="paywall_quote",D=!N&&!Yn(x),l=!1;if(_&&D&&w===t.generation&&o===s&&x instanceof m&&x.status!==void 0){let I=await T(s.requestId).catch(()=>{});l=I?.settlement?.state==="unknown"&&I.settlement.operationId===null}throw w===t.generation&&(o===s||p===s)&&D&&(!_||!(x instanceof m)||x.status===void 0||l)&&(e&&await e.settle(s.requestId),w===t.generation&&O(s)),x}}function h(s,f){let w=G.parse(s);if(w.operation==="start"||w.operation==="get"||w.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(d&&w.operation!=="close"){if(o?.requestId===w.requestId)return T(w.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(w.operation==="close"){if(o?.requestId===w.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(d=!0,p&&JSON.stringify(q(p))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original Close");return p??=w,c.close?c.close:R(p,"close",f)}if(o){if(JSON.stringify(q(o))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else o=w;return R(o,"command",f)}function R(s,f,w){let N=v(s,w);c[f]=N;let x=()=>{c[f]===N&&(c[f]=null)};return N.then(x,x),N}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||o!==s&&p!==s?!1:(o===s&&(o=null),p===s&&(p=null),a.delete(s.requestId),!o&&!p&&(g=null),!0)}return{ready:y,get pending(){return o},get closing(){return p},get closeRequested(){return d},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return i},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,f,w,N){let x=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=x&&f.settlement?.state==="settled"&&f.run.pendingRequest?.requestId!==x&&(s.operation==="get"||!d||s.operation==="close"||!["running","waiting"].includes(f.run.status))?x:void 0,D=o?.requestId===_?o:p?.requestId===_?p:void 0;e?.bind({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId});let l=f.run.paywall,I=l??f.purchase,C=I?.operation,E=f.settlement&&(!l||l.purchaseRequestId===f.settlement.requestId)&&(!i||i.operationId===f.settlement.operationId)?f.settlement:void 0,S=C?.operationId??I?.quote?.operationId??E?.operationId,F=I?.receiptId??E?.receiptId,b=l?.selectionGeneration??i?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||f.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!i||b>=i.generation)){let P={receiptId:F,operationId:S,generation:b},k=rn(C,I?.canReselect===!0);await e.observePurchase({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId},P,k,_),t.assertCurrent(w),(!i||P.generation>=i.generation)&&(N===void 0||N>=t.readSequence)&&(k?i?.operationId===P.operationId&&(i=void 0):i=P)}else e&&_&&await e.settle(_);return t.assertCurrent(w),_?O(D):!1},stop(){d=!0},submit:h,settle:T,reset(){d=!0,o=null,p=null,i=void 0,g=null,c.close=null,a.clear(),c.command=null}}}function Zn(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 m("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new m("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Se.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=W({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),o=bn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(R),d=null,c=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=c&&wn(c),i=Rn({journal:a,state:o,call:T,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function h(l){let I=l.operation==="resume"?i.pending?.operation==="resume"?null:i.pending:l;if(u&&l.operation==="resume"&&!I&&l.requestId!==e.customerRun?.startRequestId)throw new m("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let P=o.view?.paywall;xn(u,P?.quote?.operationId===I.input.operationId?P.quote:void 0)}if(e.process)return e.process.request(l);let C=o.generation;o.assertCurrent(C);let E=performance.now()+(e.timeoutMs??35e3),S=o.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let P=o.signal,k,B=()=>{},Sn=new Promise((Wn,Fe)=>{B=()=>Fe(P.reason),P.addEventListener("abort",B,{once:!0}),k=setTimeout(()=>Fe(new m("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(o.assertCurrent(C),e.session.access())),Sn])}finally{clearTimeout(k),P.removeEventListener("abort",B)}}o.assertCurrent(C);let F={...l,...S?{customerToken:S}:{}},b=l.operation==="page_experiments"?fe.parse(F):G.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new m("IDENTITY_CHANGED","Original recovery Customer changed");let P={...b};return"customerToken"in P&&delete P.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:P},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",b,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function R(){v(),p?.(),o.reset(),i.reset(),d=null,r.dispose()}async function T(l,I){let C=t;t=void 0;let E=o.generation,S=()=>o.assertCurrent(E);a&&await i.ready,S();let F=o.view,b=In(e,C!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?C:await h(l));if(l.operation==="review"&&!b.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&b.run.id!==e.customerRun.runId)throw new m("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&b.purchase&&(b.purchase.receiptId!==l.purchase.receiptId||(b.purchase.operation?.operationId??b.purchase.quote?.operationId)!==l.purchase.operationId))throw new m("INVALID_RESPONSE","The requested original purchase changed");if(S(),b.runToken&&b.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let P=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(P&&b.settlement?.requestId!==P)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(b),o.assertRun(b.run),o.bindScope(b.scope);let k=await i.observe(l,b,E,I);return(!o.view||b.run.revision>=o.view.revision)&&(I===void 0||I>=o.readSequence)&&(await e.onAcceptedResponse?.(b),S()),!b.run.stopped&&["running","waiting"].includes(b.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(b.run.status)||i.stop(),o.publish(l,b,F,I,k)),b}function O(l){let I=o.generation;v();let C=l(),E=()=>{o.generation===I&&v()};return C.then(E,E),C}let s=(l,I)=>O(()=>i.submit(l,I)),f=null,w=new WeakMap;function N(l){let I=w.get(l);if(I)return I;let C=_(l);return w.set(l,C),C}let x=!1;async function _(l){let I=await l;if(I.run.instruction?.type!=="evaluate_segment")return I;if(f)return f;x=!0;let C=o.generation,E=(async()=>{for(let S=0;S<32&&I.run.instruction?.type==="evaluate_segment";S++){if(i.pending||i.closeRequested)return I;let F=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:P}=await Re(e.configuration,F,{predict:!1});if(C!==o.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(o.view&&(o.view.revision!==F.revision||o.view.visit!==F.visit||o.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Re(e.configuration,F).then(({prediction:B})=>{k&&C===o.generation&&!i.closeRequested&&o.view?.id===F.id&&!o.view.stopped&&o.view.nodeId===F.nodeId&&o.view.visit===F.visit&&o.view.revision===F.revision&&(d=B)}).catch(()=>{});try{I=await s({operation:"commit_segment",requestId:Xe(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...P})}finally{k=!1,d=null}}}return I})();f=E;try{return await E}finally{f===E&&(f=null)}}let D={get configuration(){return x?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=o.currentView;return l?structuredClone(l):null},get viewAgeMs(){return o.viewAgeMs},get pendingCommand(){let l=i.closing??i.pending;return l?structuredClone(q(l)):null},get pendingCommands(){return[i.pending,i.closing].filter(l=>l!==null).map(l=>structuredClone(q(l)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=o.view;return d&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===d.runId&&l.nodeId===d.from.nodeId&&l.visit===d.from.visit&&l.revision===d.from.revision&&!i.closeRequested?structuredClone(d):null},settle:(...l)=>O(()=>i.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return nn(e,l)},async pageExperiments(l,I=[]){let C=o.generation;o.assertCurrent(C);let E=o.view?.id;if(!E)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=dn.parse(await h(fe.parse({operation:"page_experiments",release:l,usedReceiptIds:I})));if(o.assertCurrent(C),S.runId!==E||S.scope.projectId!==o.scope?.projectId||S.scope.environment!==o.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},o.nextRead())},async get(l,I){let C=o.generation;l=l&&structuredClone(l),I=I&&{...I},a&&await i.ready,o.assertCurrent(C),I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let E=JSON.stringify([o.generation,g,l??null,I??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=o.nextRead(),b=N(T({operation:"get",...l?{data:l}:{},...I?{purchase:I}:{}},F));y.set(E,b);let P=()=>{y.get(E)===b&&y.delete(E)};return b.then(P,P),b.then(k=>structuredClone(k))},resume(l=o.view?.pendingRequest?.requestId){return l?i.closeRequested?D.settle(l):i.pending?.requestId===l?N(s(i.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},async retry(){if(i.closeFlight)return i.closeFlight;if(i.closing)return s(i.closing);if(i.closeRequested&&i.pending)return D.settle(i.pending.requestId);if(i.inFlight)return N(i.inFlight);if(!i.pending)throw new m("INVALID_REQUEST","No command is pending");let l=i.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let I=o.generation;if(await D.settle(l.requestId),o.assertCurrent(I),!i.pending)return D.get();if(i.pending!==l||i.closeRequested)throw new m("COMMAND_PENDING","The original quote is being recovered")}return N(s(l))},identify(l){let I=o.customerToken?void 0:t;v(),o.identify(l),t=I,d=null,r.reset()},get identitySignal(){return o.signal},subscribe:o.subscribe,reset:R};return tn(D,(l,I)=>N(s(l,I))),D}function po(e,t){return Zn({...e,runToken:"",initialResponse:t})}export{un as a,Cn as b,pe as c,On as d,sn as e,kn as f,_t as g,kt as h,Dt as i,fe as j,dn as k,X as l,Vn as m,$t as n,dr as o,pr as p,In as q,xe as r,hr as s,Qn as t,hn as u,H as v,an as w,Fn as x,Tr as y,te as z,Se as A,qr as B,jr as C,xn as D,Zn as E,po as F};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as w,f as b}from"./chunk-
|
|
1
|
+
import{e as w,f as b}from"./chunk-GADT6JMW.js";import{n as h,s as u}from"./chunk-5BPZUW6B.js";import{a as y}from"./chunk-3WCIX4VH.js";import{a as n}from"./chunk-UGATOG2T.js";import{a as g}from"./chunk-3VUPVXAV.js";import{a as f}from"./chunk-5MRSFLQA.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.
|
|
1
|
+
var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.79",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md","native-funnel-host.NOTICES.txt"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};export{s as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as ie}from"./chunk-
|
|
1
|
+
import{i as ie}from"./chunk-LQV7EC5H.js";import{a as N,b as Z,d as ee,f as te,g as ne,j as M,l as re,m as oe,n as se}from"./chunk-CO6HDNOC.js";import{b as K}from"./chunk-PGNIOWKY.js";import{r as V}from"./chunk-5BPZUW6B.js";import"./chunk-I5ZXIKOT.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-3WCIX4VH.js";import"./chunk-KCUE2VFJ.js";import{o as X,p as Y}from"./chunk-Y3W5G4BF.js";import{A as G}from"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import{d as R}from"./chunk-A5WUQLAO.js";import{a as p}from"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-ZHVVJBT6.js";import"./chunk-5MRSFLQA.js";import{b as u}from"./chunk-W22ESUYY.js";import{a as h}from"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";var z=new WeakMap;function ce(o){let t={string:u.string(),number:u.number().finite(),boolean:u.boolean(),strings:u.array(u.string()),json:R}[o.type];return o.nullable?t.nullable():t}function ae(o,t){let f=u.record(u.string(),R).parse(o);if(Object.keys(f).length>40)throw new p("INVALID_REQUEST","Too many content inputs");for(let[m,n]of Object.entries(f))X.parse({[m]:n});if(Object.keys(f).some(m=>!Object.hasOwn(t.inputs,m)))throw new p("INVALID_REQUEST","Undeclared content input");for(let[m,n]of Object.entries(t.inputs))if(Object.hasOwn(f,m))ce(n).parse(f[m]);else if(n.required)throw new p("INVALID_REQUEST",`Missing content input ${m}`);return f}async function Ve(o,t){return le(o,t,!1)}async function Ae(o,t){return le(o,t,!0)}async function le(o,t,f){t.signal?.throwIfAborted();let m=K.parse(t.content),n=m.document;if(t.closeControl==="content"&&!n.screen.actions.some(e=>e.type==="event"&&e.close))throw new p("INVALID_REQUEST","An authored Close control requires a declared Close action");if(z.has(o))throw new p("CONFLICT","Content is already mounted in this container");let g=ae(t.inputs??{},n.contract),T=new Set(u.array(u.string()).max(40).parse(t.mutableInputs??[]));if(T.size!==(t.mutableInputs?.length??0)||[...T].some(e=>!Object.hasOwn(n.contract.inputs,e)))throw new p("INVALID_REQUEST","Mutable content inputs must name unique declared inputs");for(let e of Object.keys(n.contract.outputs))if(typeof t.actions[e]!="function")throw new p("INVALID_REQUEST",`Missing host handler for ${e}`);let q=Y.parse(t.bindings??[]),d=o.ownerDocument,ue=o.clientHeight||d.defaultView?.innerHeight||800,P,w,a,_,H=n.kind==="popup",r=H?d.createElement("dialog"):null,c=d.createElement("div");if(c.dataset.indianaContent=n.kind,c.setAttribute("aria-label",n.name),c.style.cssText="width:100%;min-width:0",r){r.setAttribute("aria-label",n.name);let e=n.screen.presentation;r.style.cssText=e.type==="inline"?N("content",{type:"fullscreen"},n.screen.theme):N("content",e,n.screen.theme),a=ee(r,n.screen,()=>{w?.resizeViewport(d.defaultView?.innerHeight||800,d.defaultView?.innerWidth||1024)}),r.append(c),o.append(r)}else o.append(c);let i=!1,A=!1,C=!1,D=!1,de=r?oe(r):se(c,o),S=re(o,t,n.kind,()=>{k()&&(v(),h(t.onDismiss))}),F,j,L=new Promise((e,s)=>{F=e,j=s});L.catch(()=>{});let y=null,E=structuredClone(n.screen),J=G(E,[t.locale,...d.defaultView?.navigator.languages??[]]),x=t.capabilities;E.actions=E.actions.map(e=>e.type==="event"?{...e,close:!1}:e);function v(){i||(i=!0,t.signal?.removeEventListener("abort",v),S.finish("dismissed"),j(new Error("Content preparation cancelled")),a?.destroy(),_?.(),w?.destroy(),r?.close(),r?.remove(),c.remove(),z.delete(o),r&&P?.())}let I=()=>{!C||!k()||(v(),h(t.onDismiss))};function k(){try{return t.canDismiss?.()!==!1}catch(e){return h(t.onError,e),!1}}if(r&&t.closeControl!=="content"){let e=d.createElement("button");e.type="button",e.textContent="×",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"关闭":"Close"),ne(e,n.screen.theme),e.addEventListener("click",I),r.prepend(e)}r&&a?.responsive&&(_=Z(r,I,k,t.locale?.startsWith("zh")?"关闭":"Close")),r?.addEventListener("cancel",e=>{e.preventDefault(),I()}),r?.addEventListener("keydown",e=>{e.key==="Escape"&&(e.preventDefault(),I())});async function Q(){if(i||!C||A||!y)return;let e=y;A=!0,c.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),y=null}catch(s){i||h(t.onError,s)}finally{A=!1,i||c.removeAttribute("aria-busy")}}function W(){if(i)throw new p("CONFLICT","Content host has been destroyed");C||!D||(P??=M(d),S.present(e=>{de(),r&&(a?.latch(),r.showModal(),a?.responsive&&r.focus({preventScroll:!0}),!e&&t.loading!=="host"&&te(r,a?.type??n.screen.presentation.type,a?.responsive)),C=!0}))}function U(e){S.finish("error",e),j(e instanceof Error?e:new Error(String(e))),v()}let B={destroy:v,show:W,get pendingAction(){return y?structuredClone(y):null},retryAction:Q,updateInputs(e){if(i)throw new p("CONFLICT","Content host has been destroyed");let s=u.record(u.string(),R).parse(e),b=ae({...g,...s},n.contract);for(let l of Object.keys(s))if(!T.has(l)&&(!Object.hasOwn(g,l)||V(g[l])!==V(b[l])))throw new p("PRECONDITION_FAILED","This content input is frozen; prepare a new presentation");V(g)!==V(b)&&(w?.update(E,J,{capabilities:x,serverInput:{bindings:q,answers:{},values:b}}),g=b)},updateCapabilities(e){if(i)return;let s=structuredClone(e);w?.updateCapabilities(s),x=s}};z.set(o,B),t.signal?.addEventListener("abort",v,{once:!0});try{if(t.signal?.throwIfAborted(),f||(P=M(d),S.start(H,t.locale??n.screen.strings.defaultLocale),i&&await L),w=ie(c,{mode:"live",rendererUrl:t.rendererUrl,title:n.name,viewportHeight:n.kind==="page"?ue:a?.responsive?d.defaultView?.innerHeight||800:void 0,...a?.responsive?{viewportWidth:d.defaultView?.innerWidth||1024,hostPresentation:()=>a.type}:{},onResize:e=>{i||a?.responsive&&(c.style.height=`${e}px`,c.style.overflow="clip",a.setContentHeight(e))},onRendered:e=>{if(!i&&(e&&r?.setAttribute("aria-label",e),!D))try{D=!0,f||W(),F()}catch(s){U(s),h(t.onError,s)}},onError:e=>{if(i)return;let s=new Error(e);D||U(s),h(t.onError,s)},onEscape:H?I:void 0,onAction:(e,s,b)=>{if(i||!C||A||y)return;let l=n.screen.actions.find(O=>O.id===e),$=n.contract.outputs[e];if(!(l?.type!=="event"||!$)&&!(l.close&&!k()))try{let O=ce($).parse(Object.hasOwn(l.properties,"value")?l.properties.value:l.properties);y=structuredClone({requestId:crypto.randomUUID(),contentVersionId:m.id,actionId:e,event:l.event,value:O,selection:s??{},answers:b??{},requestedClose:l.close}),Q()}catch(O){h(t.onError,O)}}}),w.update(E,J,{capabilities:x,serverInput:{bindings:q,answers:{},values:g}}),await Promise.race([w.ready,L]),f&&await L,i)throw new Error("Content preparation cancelled");return B}catch(e){throw U(e),e}}export{Ve as mountContent,Ae as prepareContent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as ce}from"./chunk-ZP5XCBBK.js";import{b as W,d as oe}from"./chunk-HOX2FQQE.js";import{b as ue}from"./chunk-ABLGIN4X.js";import{a as se}from"./chunk-PX7APKZR.js";import"./chunk-4CJUGCMG.js";import{a as X}from"./chunk-VEGGHQTQ.js";import"./chunk-XLOCTL2Y.js";import"./chunk-IXDARDPI.js";import{b as ie}from"./chunk-CZ33YJWK.js";import"./chunk-45PGU2HW.js";import"./chunk-AEQUKR4O.js";import"./chunk-W32FI2A2.js";import{k as H,l as Y}from"./chunk-FWM3577O.js";import"./chunk-ZBV6DOEY.js";import"./chunk-BSPJMJDI.js";import"./chunk-IEKRWGRV.js";import"./chunk-D7SPHHSF.js";import"./chunk-5MPALDJL.js";import"./chunk-SQMA5YYI.js";import"./chunk-BN6UIKEV.js";import"./chunk-YXD5B3UB.js";import"./chunk-JXVZK3RZ.js";import"./chunk-6NDL2ELB.js";import"./chunk-6FWT2BXF.js";import"./chunk-LZYQA3Q4.js";import"./chunk-DLLC7CRI.js";import"./chunk-CW7MTKXP.js";import"./chunk-VZMLPENL.js";import"./chunk-HEPQNLR2.js";import"./chunk-VILB5M4X.js";import"./chunk-L6XCRIR2.js";import"./chunk-LUYWRWJ2.js";import"./chunk-EDZJ2IGA.js";import"./chunk-2HIWXIJE.js";import"./chunk-T44KC4GO.js";import"./chunk-LWIBARE4.js";import"./chunk-TJRXWGKB.js";import{a as g}from"./chunk-5X7PTCI4.js";import"./chunk-XX5O7H6R.js";import"./chunk-SLUA7ABW.js";import"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-NJNENW5L.js";import"./chunk-5MRSFLQA.js";import"./chunk-J6MYX7WY.js";import{a as h}from"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";var D=new WeakMap,V=new WeakMap,Z=new WeakSet;function be(R,e){let w=e.hostPaywallTarget?void 0:e.prepared,$=()=>{e.prepared&&!Z.has(e.prepared)&&W(e.prepared)?.release()},ee=D.get(e.client);if(ee)return $(),ee;let te=n=>({...n,requestId:n.requestId??crypto.randomUUID()}),N=e.allowNewPurchase!==!1&&e.start instanceof Promise?e.start:void 0,m=e.allowNewPurchase===!1||!e.start||e.start instanceof Promise?void 0:te(e.start);m&&w?.state==="ready"&&w.matches(m)&&w.open();let f=w&&(m&&(w.state==="preparing"||["shown","closed"].includes(w.state)&&w.matches(m))||N&&["preparing","ready"].includes(w.state)||w.state==="shown"&&W(w)?.recovering)?w:void 0;f?Z.add(f):$();let P=f&&W(f);P?.claim();let z=()=>!!P?.recovering&&f?.state==="shown",T=Promise.resolve().then(async()=>{let n=!1,c,b=!1,j,C=0,S,I,U=!1,E=()=>{},re=()=>{},_,B=!1,J=!1,O,ne=!1,a=e.signal?AbortSignal.any([e.signal,e.client.identitySignal]):e.client.identitySignal,v=()=>{D.get(e.client)===T&&D.delete(e.client),a.removeEventListener("abort",F),E(),re(),f&&Z.delete(f),P?.release()};function ae(){if(O)return O;let t=new Promise(o=>O=o);return V.set(e.client,t),t.then(()=>{V.get(e.client)===t&&V.delete(e.client)}),D.get(e.client)===T&&D.delete(e.client),O}let l=Y(R,e,"funnel",()=>k(),X);function F(){k()}function k(t=!1){if(!n){if(n=!0,l.finish("dismissed"),c){c.destroy();return}if(t&&_){let o=ae();ne=!0,_.then(async s=>{s.mode==="run"&&s.status!=="blocked"&&e.client.controller&&e.client.attempt?.requestId===m?.requestId&&await e.client.close()}).catch(()=>{}).finally(()=>{o(),h(e.onDismiss,null)}),v();return}v(),h(e.onDismiss,null)}}let q={destroy:()=>k(),refresh:()=>S??(b?Q():c?.refresh())??Promise.resolve(),get recovery(){return c?.recovery??{type:"recover",operationId:null,requestId:null}},prepareFallback:()=>c?.prepareFallback()??Promise.resolve({type:"recover",operationId:null,requestId:null}),review:(...t)=>c?.review(...t)??Promise.resolve(),exitReview:(...t)=>c?.exitReview(...t)??Promise.resolve(),get unappliedDrafts(){return c?.unappliedDrafts??new Map}};a.addEventListener("abort",F,{once:!0}),P&&(re=P.onClose(()=>{B?n||ae():k(!0)}));try{a.throwIfAborted();let t=e.client.controller?.view?.paywall?.resolution,o=t&&"document"in t?t.document:e.loadingDocument;l.start(!0,m?.locale??e.client.attempt?.locale??o?.screen.strings.defaultLocale,o??null);let s=N?l.wait(N.then(r=>r?te(r):null,()=>null),H):Promise.resolve(m??null);s.catch(()=>{}),f?.state==="shown"?(J=!0,l.present(()=>{})):f&&["preparing","ready"].includes(f.state)&&Promise.all([f.ready,s.catch(()=>null)]).then(([r,i])=>{if(r){if(n||!l.active||!i||!f.matches(i)||!P?.revealable)return P?.release();l.present(()=>{f.open()==="shown"?J=!0:P.release()})}});let d=V.get(e.client);if(d&&await l.wait(d),n)return null;if(a.throwIfAborted(),N){let r=await s;if(n)return null;if(a.throwIfAborted(),!r&&!z())return l.finish("skipped"),v(),null;m=r??void 0}_=m?e.client.start(m):e.client.refresh({reuseRecentRead:!0});let u=await l.wait(_,H);return n?null:(a.throwIfAborted(),await le(u,l))}catch(t){if(ne||O?.(),n)return null;throw l.finish("error",t),v(),h(e.onError,t),t}function K(t=!1){C++;let o=c;c=void 0,E(),E=()=>{};let s=t?o?.retainPurchaseDialog?.():void 0;return o?.destroy(),a.addEventListener("abort",F,{once:!0}),s}function x(t){b=!0;let o=e.client.attempt?.locale??m?.locale,s=o?.startsWith("zh"),d=t?s?"正在查询原订单…":"Checking your purchase…":s?"暂时无法确认原订单,请重试。":"Could not check your original purchase. Try again.",u=t?void 0:()=>{Q()};c?.setPurchaseRecovery?.(d,u)||(c&&K(),l.active||(l=Y(R,e,"funnel",()=>k(),X),l.start(!0,o,e.loadingDocument??null)),l.setPurchaseRecovery(d,u))}function Q(){if(S)return S;if(n||a.aborted)return Promise.resolve();j??=c?.recoveryPaywall,a.addEventListener("abort",F,{once:!0}),x(!0);let t=Promise.resolve().then(async()=>{try{let s=await l.wait(e.client.refresh(),H);!n&&!a.aborted&&await le(s,l)}catch(s){!n&&!a.aborted&&(h(e.onError,s),x(!1))}});S=t;let o=()=>{S===t&&(S=void 0)};return t.then(o,o),t}async function le(t,o){let s=e.client.controller;if(t.mode==="run"&&t.status!=="blocked"&&s)return b&&c&&K(),b=!1,j=void 0,de(s,o?.active?o:void 0);if(t.mode==="operation"&&t.purchases.length){z()||x(!0);let d=await l.wait(e.client.recoverPurchasePaywall(j).then(u=>((n||a.aborted)&&u?.destroy(),u)),H).catch(u=>(!n&&!a.aborted&&h(e.onError,u),null));if(n||a.aborted)return null;if(d){if(n||a.aborted)return d.destroy(),null;let u=K(!0)??P?.retainPurchaseDialog?.()??l.retainPurchaseDialog();P?.release();let r=m,i=ue({client:e.client,session:d,start:e.allowNewPurchase===!1||!r?void 0:async()=>{let{requestId:p,...G}=r;return G},signal:a}),y=()=>{!n&&!a.aborted&&!U&&I&&e.client.recovery.status==="complete"&&(U=!0,h(e.onComplete,structuredClone(I)))},A=await se(R,{signal:a,loading:"host",start:async()=>i.session,checkoutNavigation:"after_confirmation",allowNewPurchase:!1,resumeCheckout:p=>e.client.continueCheckout(L,p),...i.prepare&&{prepareUpgradeReplacement:i.prepare,terminateCheckout:p=>e.client.terminateCheckout(p),beforeCheckoutReplacement:e.beforeCheckoutReplacement,purchaseConfirmation:e.purchaseConfirmation,confirmOnHostedCheckout:e.confirmOnHostedCheckout,claimCoupon:e.claimCoupon,prepareSubscriptionChange:e.prepareSubscriptionChange,resolveSubscriptionChange:e.resolveSubscriptionChange,onPurchase:e.onPurchase,onCheckoutUrl:L,async resolveOfferId(p){let G=e.client.attempt;if(!G)throw new g("PURCHASE_PENDING","Read the new Start before selecting an offer");return e.resolveOfferId?.(p,G)},onComplete(){I=structuredClone(e.client.controller?.view)??I,E(),E=e.client.subscribe(y),y()}},onError:e.onError,onDismiss:()=>{n||k()}},{retainedDialog:u,present(p){l.active?l.present(p):p(!!u)},async dismiss(){k()}});if(!A.host||n||a.aborted)return A.host?.destroy(),u?.release(),v(),null;let M=A.host;return b=!1,c={destroy(){M.destroy(),v(),h(e.onDismiss,null)},refresh:async()=>{await M.refresh()},get recovery(){return M.recovery},prepareFallback:()=>M.prepareFallback(),review:async()=>{},exitReview:async()=>{},unappliedDrafts:new Map},q}}return t.purchases.length||b?(z()&&P?.release(),x(!1),q):(l.finish("skipped"),v(),(J||B)&&(n=!0,h(e.onDismiss,null)),null)}function L(t){if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");return e.onCheckoutUrl?e.onCheckoutUrl(t):R.ownerDocument.defaultView?.location.assign(t)}async function de(t,o){a.removeEventListener("abort",F),B=!0;function s(){!n&&!a.aborted&&!b&&!U&&I&&e.client.recovery.status==="complete"&&(U=!0,h(e.onComplete,structuredClone(I)))}E(),E=e.client.subscribe(s);let d=++C,u=await ce(R,{...e,prepared:f,client:t,signal:a,prepareNextPaywall:({run:r,paywallVersionId:i})=>oe(R,{client:e.client,run:r,paywallVersionId:i,signal:a}),checkoutNavigation:"after_confirmation",resumeCheckout:r=>e.client.continueCheckout(L,r),terminateCheckout:e.allowNewPurchase===!1?void 0:r=>e.client.terminateCheckout(r),async onCheckoutUrl(r){if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");let i=e.client.recovery;if((!i.actions.includes("continue_checkout")||!i.purchases.some(y=>y.type==="checkout"&&y.checkoutUrl===r))&&(i=await e.client.refresh(),a.throwIfAborted(),n))throw new DOMException("Presentation dismissed","AbortError");if(ie(i)!==r)throw new g("PURCHASE_PENDING","Checkout differs from the original recovery proof");return L(r)},async resolveOfferId(r){if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");let i=e.client.attempt;if(!i)throw new g("PURCHASE_PENDING","Read the original Start before selecting an offer");let y=await e.resolveOfferId?.(r,i);if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");if(e.client.attempt?.requestId!==i.requestId)throw new g("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting an offer");return y},async resolveSubscriptionChange(r,...i){a.throwIfAborted();let y=e.client.attempt;if(n||!y)throw new g("PURCHASE_PENDING","Read the original Start before selecting a membership");let A=e.resolveSubscriptionChange?await e.resolveSubscriptionChange(r,...i):await i[0]?.();if(a.throwIfAborted(),n||e.client.attempt?.requestId!==y.requestId)throw new g("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting a membership");return A},onPresentationState(r){d===C&&h(e.onPresentationState,r)},onComplete(r){d===C&&(I=r,s())},onError(r){d===C&&(h(e.onError,r),r instanceof g&&(r.status===401||r.status===409&&r.reason==="STATE_CHANGED"&&r.recovery==="recover_operation")&&!a.aborted&&Q().catch(i=>h(e.onError,i)))},onDismiss(r){d===C&&(n=!0,v(),O?.(),h(e.onDismiss,r))}},o);return d!==C||n||a.aborted?(u.destroy(),n||a.aborted?null:q):(c=u,q)}});return D.set(e.client,T),T}export{be as showFunnelPurchase};
|
|
1
|
+
import{b as ce}from"./chunk-WU6HDOZM.js";import{b as W,d as oe}from"./chunk-2WXUJGGZ.js";import{b as ue}from"./chunk-GB74QWAG.js";import{a as se}from"./chunk-PGKKIL6M.js";import"./chunk-72UVQYXH.js";import{a as X}from"./chunk-CHRNCOXJ.js";import"./chunk-7CZEXBQY.js";import"./chunk-VXNN3RV3.js";import{b as ie}from"./chunk-XH6VXXCX.js";import"./chunk-7ZAM4YRK.js";import"./chunk-AEQUKR4O.js";import"./chunk-W32FI2A2.js";import{k as H,l as Y}from"./chunk-CO6HDNOC.js";import"./chunk-ORR47GDS.js";import"./chunk-EQUVI5QU.js";import"./chunk-YQ2PQWHZ.js";import"./chunk-F4AIEI5N.js";import"./chunk-FFEJS4K3.js";import"./chunk-EQBJNU6R.js";import"./chunk-MOIVJERE.js";import"./chunk-Z5JTYDD5.js";import"./chunk-GADT6JMW.js";import"./chunk-5BPZUW6B.js";import"./chunk-I5ZXIKOT.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-KX67ZM7H.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-3WCIX4VH.js";import"./chunk-KCUE2VFJ.js";import"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import{a as g}from"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-SLUA7ABW.js";import"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-ZHVVJBT6.js";import"./chunk-5MRSFLQA.js";import"./chunk-W22ESUYY.js";import{a as h}from"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";var D=new WeakMap,V=new WeakMap,Z=new WeakSet;function be(R,e){let w=e.hostPaywallTarget?void 0:e.prepared,$=()=>{e.prepared&&!Z.has(e.prepared)&&W(e.prepared)?.release()},ee=D.get(e.client);if(ee)return $(),ee;let te=n=>({...n,requestId:n.requestId??crypto.randomUUID()}),N=e.allowNewPurchase!==!1&&e.start instanceof Promise?e.start:void 0,m=e.allowNewPurchase===!1||!e.start||e.start instanceof Promise?void 0:te(e.start);m&&w?.state==="ready"&&w.matches(m)&&w.open();let f=w&&(m&&(w.state==="preparing"||["shown","closed"].includes(w.state)&&w.matches(m))||N&&["preparing","ready"].includes(w.state)||w.state==="shown"&&W(w)?.recovering)?w:void 0;f?Z.add(f):$();let P=f&&W(f);P?.claim();let z=()=>!!P?.recovering&&f?.state==="shown",T=Promise.resolve().then(async()=>{let n=!1,c,b=!1,j,C=0,S,I,U=!1,E=()=>{},re=()=>{},_,B=!1,J=!1,O,ne=!1,a=e.signal?AbortSignal.any([e.signal,e.client.identitySignal]):e.client.identitySignal,v=()=>{D.get(e.client)===T&&D.delete(e.client),a.removeEventListener("abort",F),E(),re(),f&&Z.delete(f),P?.release()};function ae(){if(O)return O;let t=new Promise(o=>O=o);return V.set(e.client,t),t.then(()=>{V.get(e.client)===t&&V.delete(e.client)}),D.get(e.client)===T&&D.delete(e.client),O}let l=Y(R,e,"funnel",()=>k(),X);function F(){k()}function k(t=!1){if(!n){if(n=!0,l.finish("dismissed"),c){c.destroy();return}if(t&&_){let o=ae();ne=!0,_.then(async s=>{s.mode==="run"&&s.status!=="blocked"&&e.client.controller&&e.client.attempt?.requestId===m?.requestId&&await e.client.close()}).catch(()=>{}).finally(()=>{o(),h(e.onDismiss,null)}),v();return}v(),h(e.onDismiss,null)}}let q={destroy:()=>k(),refresh:()=>S??(b?Q():c?.refresh())??Promise.resolve(),get recovery(){return c?.recovery??{type:"recover",operationId:null,requestId:null}},prepareFallback:()=>c?.prepareFallback()??Promise.resolve({type:"recover",operationId:null,requestId:null}),review:(...t)=>c?.review(...t)??Promise.resolve(),exitReview:(...t)=>c?.exitReview(...t)??Promise.resolve(),get unappliedDrafts(){return c?.unappliedDrafts??new Map}};a.addEventListener("abort",F,{once:!0}),P&&(re=P.onClose(()=>{B?n||ae():k(!0)}));try{a.throwIfAborted();let t=e.client.controller?.view?.paywall?.resolution,o=t&&"document"in t?t.document:e.loadingDocument;l.start(!0,m?.locale??e.client.attempt?.locale??o?.screen.strings.defaultLocale,o??null);let s=N?l.wait(N.then(r=>r?te(r):null,()=>null),H):Promise.resolve(m??null);s.catch(()=>{}),f?.state==="shown"?(J=!0,l.present(()=>{})):f&&["preparing","ready"].includes(f.state)&&Promise.all([f.ready,s.catch(()=>null)]).then(([r,i])=>{if(r){if(n||!l.active||!i||!f.matches(i)||!P?.revealable)return P?.release();l.present(()=>{f.open()==="shown"?J=!0:P.release()})}});let d=V.get(e.client);if(d&&await l.wait(d),n)return null;if(a.throwIfAborted(),N){let r=await s;if(n)return null;if(a.throwIfAborted(),!r&&!z())return l.finish("skipped"),v(),null;m=r??void 0}_=m?e.client.start(m):e.client.refresh({reuseRecentRead:!0});let u=await l.wait(_,H);return n?null:(a.throwIfAborted(),await le(u,l))}catch(t){if(ne||O?.(),n)return null;throw l.finish("error",t),v(),h(e.onError,t),t}function K(t=!1){C++;let o=c;c=void 0,E(),E=()=>{};let s=t?o?.retainPurchaseDialog?.():void 0;return o?.destroy(),a.addEventListener("abort",F,{once:!0}),s}function x(t){b=!0;let o=e.client.attempt?.locale??m?.locale,s=o?.startsWith("zh"),d=t?s?"正在查询原订单…":"Checking your purchase…":s?"暂时无法确认原订单,请重试。":"Could not check your original purchase. Try again.",u=t?void 0:()=>{Q()};c?.setPurchaseRecovery?.(d,u)||(c&&K(),l.active||(l=Y(R,e,"funnel",()=>k(),X),l.start(!0,o,e.loadingDocument??null)),l.setPurchaseRecovery(d,u))}function Q(){if(S)return S;if(n||a.aborted)return Promise.resolve();j??=c?.recoveryPaywall,a.addEventListener("abort",F,{once:!0}),x(!0);let t=Promise.resolve().then(async()=>{try{let s=await l.wait(e.client.refresh(),H);!n&&!a.aborted&&await le(s,l)}catch(s){!n&&!a.aborted&&(h(e.onError,s),x(!1))}});S=t;let o=()=>{S===t&&(S=void 0)};return t.then(o,o),t}async function le(t,o){let s=e.client.controller;if(t.mode==="run"&&t.status!=="blocked"&&s)return b&&c&&K(),b=!1,j=void 0,de(s,o?.active?o:void 0);if(t.mode==="operation"&&t.purchases.length){z()||x(!0);let d=await l.wait(e.client.recoverPurchasePaywall(j).then(u=>((n||a.aborted)&&u?.destroy(),u)),H).catch(u=>(!n&&!a.aborted&&h(e.onError,u),null));if(n||a.aborted)return null;if(d){if(n||a.aborted)return d.destroy(),null;let u=K(!0)??P?.retainPurchaseDialog?.()??l.retainPurchaseDialog();P?.release();let r=m,i=ue({client:e.client,session:d,start:e.allowNewPurchase===!1||!r?void 0:async()=>{let{requestId:p,...G}=r;return G},signal:a}),y=()=>{!n&&!a.aborted&&!U&&I&&e.client.recovery.status==="complete"&&(U=!0,h(e.onComplete,structuredClone(I)))},A=await se(R,{signal:a,loading:"host",start:async()=>i.session,checkoutNavigation:"after_confirmation",allowNewPurchase:!1,resumeCheckout:p=>e.client.continueCheckout(L,p),...i.prepare&&{prepareUpgradeReplacement:i.prepare,terminateCheckout:p=>e.client.terminateCheckout(p),beforeCheckoutReplacement:e.beforeCheckoutReplacement,purchaseConfirmation:e.purchaseConfirmation,confirmOnHostedCheckout:e.confirmOnHostedCheckout,claimCoupon:e.claimCoupon,prepareSubscriptionChange:e.prepareSubscriptionChange,resolveSubscriptionChange:e.resolveSubscriptionChange,onPurchase:e.onPurchase,onCheckoutUrl:L,async resolveOfferId(p){let G=e.client.attempt;if(!G)throw new g("PURCHASE_PENDING","Read the new Start before selecting an offer");return e.resolveOfferId?.(p,G)},onComplete(){I=structuredClone(e.client.controller?.view)??I,E(),E=e.client.subscribe(y),y()}},onError:e.onError,onDismiss:()=>{n||k()}},{retainedDialog:u,present(p){l.active?l.present(p):p(!!u)},async dismiss(){k()}});if(!A.host||n||a.aborted)return A.host?.destroy(),u?.release(),v(),null;let M=A.host;return b=!1,c={destroy(){M.destroy(),v(),h(e.onDismiss,null)},refresh:async()=>{await M.refresh()},get recovery(){return M.recovery},prepareFallback:()=>M.prepareFallback(),review:async()=>{},exitReview:async()=>{},unappliedDrafts:new Map},q}}return t.purchases.length||b?(z()&&P?.release(),x(!1),q):(l.finish("skipped"),v(),(J||B)&&(n=!0,h(e.onDismiss,null)),null)}function L(t){if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");return e.onCheckoutUrl?e.onCheckoutUrl(t):R.ownerDocument.defaultView?.location.assign(t)}async function de(t,o){a.removeEventListener("abort",F),B=!0;function s(){!n&&!a.aborted&&!b&&!U&&I&&e.client.recovery.status==="complete"&&(U=!0,h(e.onComplete,structuredClone(I)))}E(),E=e.client.subscribe(s);let d=++C,u=await ce(R,{...e,prepared:f,client:t,signal:a,prepareNextPaywall:({run:r,paywallVersionId:i})=>oe(R,{client:e.client,run:r,paywallVersionId:i,signal:a}),checkoutNavigation:"after_confirmation",resumeCheckout:r=>e.client.continueCheckout(L,r),terminateCheckout:e.allowNewPurchase===!1?void 0:r=>e.client.terminateCheckout(r),async onCheckoutUrl(r){if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");let i=e.client.recovery;if((!i.actions.includes("continue_checkout")||!i.purchases.some(y=>y.type==="checkout"&&y.checkoutUrl===r))&&(i=await e.client.refresh(),a.throwIfAborted(),n))throw new DOMException("Presentation dismissed","AbortError");if(ie(i)!==r)throw new g("PURCHASE_PENDING","Checkout differs from the original recovery proof");return L(r)},async resolveOfferId(r){if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");let i=e.client.attempt;if(!i)throw new g("PURCHASE_PENDING","Read the original Start before selecting an offer");let y=await e.resolveOfferId?.(r,i);if(a.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");if(e.client.attempt?.requestId!==i.requestId)throw new g("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting an offer");return y},async resolveSubscriptionChange(r,...i){a.throwIfAborted();let y=e.client.attempt;if(n||!y)throw new g("PURCHASE_PENDING","Read the original Start before selecting a membership");let A=e.resolveSubscriptionChange?await e.resolveSubscriptionChange(r,...i):await i[0]?.();if(a.throwIfAborted(),n||e.client.attempt?.requestId!==y.requestId)throw new g("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting a membership");return A},onPresentationState(r){d===C&&h(e.onPresentationState,r)},onComplete(r){d===C&&(I=r,s())},onError(r){d===C&&(h(e.onError,r),r instanceof g&&(r.status===401||r.status===409&&r.reason==="STATE_CHANGED"&&r.recovery==="recover_operation")&&!a.aborted&&Q().catch(i=>h(e.onError,i)))},onDismiss(r){d===C&&(n=!0,v(),O?.(),h(e.onDismiss,r))}},o);return d!==C||n||a.aborted?(u.destroy(),n||a.aborted?null:q):(c=u,q)}});return D.set(e.client,T),T}export{be as showFunnelPurchase};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b}from"./chunk-GB74QWAG.js";import"./chunk-PGKKIL6M.js";import"./chunk-72UVQYXH.js";import"./chunk-CHRNCOXJ.js";import"./chunk-AEQUKR4O.js";import"./chunk-W32FI2A2.js";import"./chunk-CO6HDNOC.js";import"./chunk-EQBJNU6R.js";import"./chunk-MOIVJERE.js";import"./chunk-I5ZXIKOT.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-3WCIX4VH.js";import"./chunk-KCUE2VFJ.js";import"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-ZHVVJBT6.js";import"./chunk-5MRSFLQA.js";import"./chunk-W22ESUYY.js";import"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{a as mountFunnelRecoveryPaywall,b as replaceableOriginalSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as p}from"./chunk-
|
|
1
|
+
import{d as p}from"./chunk-GADT6JMW.js";import"./chunk-5BPZUW6B.js";import"./chunk-I5ZXIKOT.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-KCUE2VFJ.js";import"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import"./chunk-LFR2LWYC.js";import{a as g}from"./chunk-5MRSFLQA.js";import{b as t}from"./chunk-W22ESUYY.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";var m=1440*6e4,f=8,y=512*1024,h=t.strictObject({savedAt:t.number().int().nonnegative(),funnelId:t.string().min(1),context:t.strictObject({commerce:t.strictObject({provider:t.string(),currency:t.string(),intent:t.literal("subscription_change").optional()}),locale:t.string()}),resolution:p}),w=t.strictObject({savedAt:t.number().int().nonnegative(),funnelId:t.string().min(1),presented:t.literal("nothing")}),d=t.union([h,w]),S=t.strictObject({copies:t.record(t.string(),t.unknown())});function v(c){let u=(async()=>{let n=c.storage??globalThis.localStorage;if(!n||!globalThis.crypto?.subtle)return null;let s=new TextEncoder().encode(JSON.stringify([new URL(c.baseUrl??g).href,c.scope.projectId,c.scope.environment,c.customerId])),e=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return{storage:n,key:"indiana.funnel.paywalls.v1."+Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}})().catch(()=>null);async function l(){let n=await u;if(!n)return null;try{let s=n.storage.getItem(n.key),e=s&&s.length<=y?S.safeParse(JSON.parse(s)):null;return{...n,copies:e?.success?e.data.copies:{}}}catch{return{...n,copies:{}}}}return{async read(n){let s=await l(),e=d.safeParse(s?.copies[n]);if(!e.success)return null;if("presented"in e.data)return e.data;let o=Date.now()-e.data.savedAt;return o>=0&&o<m?e.data:null},async write(n,s){let e=await l();if(!e)return;let o={...e.copies};delete o[n];let i=[...s?[[n,s]]:[],...Object.entries(o).map(([r,a])=>[r,d.safeParse(a)]).flatMap(([r,a])=>a.success?[[r,a.data]]:[]).sort(([,r],[,a])=>a.savedAt-r.savedAt)].slice(0,f);try{for(;i.length;){let r=JSON.stringify({copies:Object.fromEntries(i)});if(r.length<=y){e.storage.setItem(e.key,r);return}i.pop()}e.storage.removeItem(e.key)}catch{}}}}export{m as PAYWALL_COPY_MAX_AGE_MS,v as createPaywallCopies};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d}from"./chunk-2WXUJGGZ.js";import"./chunk-7CZEXBQY.js";import"./chunk-VXNN3RV3.js";import"./chunk-MOIVJERE.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-KX67ZM7H.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-KCUE2VFJ.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-W22ESUYY.js";import"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{a as PRERENDER_MAX_AGE_MS,b as preparedInternals,c as prerenderFunnelPurchase,d as prerenderRunPaywall};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-7CZEXBQY.js";import"./chunk-VXNN3RV3.js";import"./chunk-KX67ZM7H.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-A5WUQLAO.js";import"./chunk-W22ESUYY.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{a as predictFunnelStart,c as predictedPaywallLoadingDocument,b as predictionRefusal};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,b as o,c as n}from"./chunk-VXNN3RV3.js";import"./chunk-KX67ZM7H.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-A5WUQLAO.js";import"./chunk-W22ESUYY.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{e as FUNNEL_ROUTE_LIMITS,o as funnelRouteSchema,n as projectFunnelRoute};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b}from"./chunk-WU6HDOZM.js";import"./chunk-2WXUJGGZ.js";import"./chunk-72UVQYXH.js";import"./chunk-CHRNCOXJ.js";import"./chunk-7CZEXBQY.js";import"./chunk-VXNN3RV3.js";import"./chunk-7ZAM4YRK.js";import"./chunk-AEQUKR4O.js";import"./chunk-W32FI2A2.js";import"./chunk-CO6HDNOC.js";import"./chunk-F4AIEI5N.js";import"./chunk-EQBJNU6R.js";import"./chunk-MOIVJERE.js";import"./chunk-I5ZXIKOT.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-KX67ZM7H.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-3WCIX4VH.js";import"./chunk-KCUE2VFJ.js";import"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-SLUA7ABW.js";import"./chunk-MB2U2GWJ.js";import"./chunk-ZHVVJBT6.js";import"./chunk-5MRSFLQA.js";import"./chunk-W22ESUYY.js";import"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{a as showFunnelRun,b as showObservedFunnelRun};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as En,c as bn}from"./chunk-CZ33YJWK.js";import{a as Rn}from"./chunk-45PGU2HW.js";import{a as We}from"./chunk-AEQUKR4O.js";import{a as Ie}from"./chunk-W32FI2A2.js";import{a as pn,c as wn,d as Sn}from"./chunk-IHAMRL3F.js";import"./chunk-ZBV6DOEY.js";import{a as In}from"./chunk-E773KSFH.js";import"./chunk-BSPJMJDI.js";import{h as mn,i as vn,k as Pn}from"./chunk-CDFRRXSQ.js";import{E as Ae,d as Xe,f as Qe,g as ge,h as ve,i as Ye,w as yn}from"./chunk-IEKRWGRV.js";import"./chunk-D7SPHHSF.js";import{a as ze}from"./chunk-5MPALDJL.js";import{c as hn,e as gn}from"./chunk-SQMA5YYI.js";import"./chunk-BN6UIKEV.js";import"./chunk-IB6BBGLM.js";import"./chunk-OZ32ZMZZ.js";import"./chunk-YXD5B3UB.js";import"./chunk-JXVZK3RZ.js";import"./chunk-6NDL2ELB.js";import{K as Ke}from"./chunk-6FWT2BXF.js";import"./chunk-LZYQA3Q4.js";import{B as dn,C as ln,D as un,E as fn,c as an,d as sn,e as cn}from"./chunk-DLLC7CRI.js";import{A as Le,B as Be,D as He,F as qe,G as Ue,I as Ve,J as je,K as Ge,L as Je,M as Te,N as $e,z as _e}from"./chunk-CW7MTKXP.js";import"./chunk-VZMLPENL.js";import"./chunk-HEPQNLR2.js";import"./chunk-VILB5M4X.js";import{b as Ce}from"./chunk-L6XCRIR2.js";import"./chunk-LUYWRWJ2.js";import"./chunk-EDZJ2IGA.js";import"./chunk-2HIWXIJE.js";import"./chunk-T44KC4GO.js";import"./chunk-LWIBARE4.js";import"./chunk-TJRXWGKB.js";import{a as G}from"./chunk-5X7PTCI4.js";import"./chunk-XX5O7H6R.js";import{a as be,c as de}from"./chunk-J6KIN4RH.js";import"./chunk-SLUA7ABW.js";import{c as we,d as Ee}from"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-NJNENW5L.js";import"./chunk-5MRSFLQA.js";import{b as U}from"./chunk-J6MYX7WY.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";var I=class extends Error{constructor(f,b=0,w=!1,h="fix_request"){super(f);this.code=f;this.status=b;this.retryable=w;this.recovery=h;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function _n(n,d){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let f=n.body?.getReader();if(!f)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let b=()=>{f.cancel().catch(()=>{})};d.addEventListener("abort",b,{once:!0});let w=0,h="",t=new TextDecoder("utf-8",{fatal:!0});try{for(d.throwIfAborted();;){let i=await f.read();if(d.throwIfAborted(),i.done)break;if(w+=i.value.byteLength,w>262144)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");h+=t.decode(i.value,{stream:!0})}return h+=t.decode(),JSON.parse(h)}catch(i){throw d.throwIfAborted(),i instanceof I?i:new I("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{d.removeEventListener("abort",b),await f.cancel().catch(()=>{}),f.releaseLock()}}function Tn(n){let d=qe.parse(n.origin),f=Ue.parse(n.manifest),b={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let m of["projectId","environmentId","environment"])if(f[m]!==n.scope[m])throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");let w=n.customerId===void 0?null:U.uuid().parse(n.customerId),h=0,t=null,i=null,u=new AbortController,y=n.fetch??globalThis.fetch;async function P(m,s,E,_,O){if(!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=He[m];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(S.authority))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);let l=h,o=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],..._?[_]:[]]);o.throwIfAborted();let T=new Headers(await n.headers?.());if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(T.get("authorization")??"")||T.has("X-Indiana-Bridge-Signature")||T.has("X-Indiana-Bridge-Key-Id"))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);T.set(Be,String(_e)),T.set("Accept","application/json");let g=crypto.randomUUID();T.set("X-Request-Id",g),T.set("Content-Type","application/json");let M=await y(d+Le,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:T,signal:o,body:JSON.stringify({bridgeVersion:_e,requestId:g,command:S.command,scope:b,data:O??(E===void 0?{}:{operationId:E})})}),J=await _n(M,o);if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(!M.ok){let F=$e.safeParse(J);throw!F.success||F.data.scope.projectId!==n.scope.projectId||F.data.scope.environment!==n.scope.environment||F.data.scope.environmentId!==n.scope.environmentId||F.data.requestId!==g||F.data.command!==S.command?new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status):new I(F.data.error.code,M.status,F.data.error.retryable,F.data.error.recovery)}let c=Ve(U.unknown()).safeParse(J);if(!c.success||c.data.scope.projectId!==n.scope.projectId||c.data.scope.environment!==n.scope.environment||c.data.scope.environmentId!==n.scope.environmentId||c.data.requestId!==g||c.data.command!==S.command)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);let $=s.safeParse(c.data.data);if(!$.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);return $.data}function R(){if(!w)throw new I("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return w}async function B(m,s,E,_){let O=R();if(_!==void 0&&Te.parse({operationId:_,customerId:O}),!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=h,l=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...s?[s]:[]]);l.throwIfAborted();let o,T=new Promise((g,M)=>{o=()=>M(l.reason),l.addEventListener("abort",o,{once:!0})});try{let M=E(async()=>{let c=await import("./merchant-bridge-contracts-ADLTLAJJ.js");if(l.throwIfAborted(),S!==h||w!==O)throw new DOMException("Merchant identity changed","AbortError");return c},l),J=await Promise.race([M,T]);return l.throwIfAborted(),J}finally{l.removeEventListener("abort",o)}}async function z(m,s,E,_){let O=R(),S=Te.parse({operationId:E,customerId:O}),l=await P(m,s,S.operationId,_,S);if(l.customerId!==O||l.operationId!==S.operationId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return l}return{async readPresentation(m){let s=await P("presentation",Ge,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(s.presentation&&w!==null&&s.presentation.customerId!==w)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i=s.nativeUserId,t=s.presentation,s},async createSession(m){let s=await P("session",je,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(w!==null&&w!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(t&&t.customerId!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return w=s.session.customerId,i=s.nativeUserId,s.session},async reportPresentation(m,s){let E=R(),_=Je.parse(m);if(!t||t.customerId!==E||t.decisionId!==_.decisionId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return P("presentation_events",U.strictObject({queued:U.literal(!0)}),void 0,s,_)},async readCustomerCommerce(m){let s=R(),E=await B("customer_commerce",m,async(_,O)=>{let[S,l]=await Promise.all([_(),P("customer_commerce",U.unknown(),void 0,O)]),o=S.merchantBridgeCommerceSchema.safeParse(l);if(!o.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return o.data});if(E.customerId!==s)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return E},async executePurchase(m,s){let E=await B("purchases",s,async(_,O)=>z("purchases",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="purchase")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},readOperation:(m,s)=>B("operation_status",s,async(E,_)=>z("operation_status",(await E()).merchantOperationLookupSchema,m,_),m),async executeSubscriptionChange(m,s){let E=await B("subscription_changes",s,async(_,O)=>z("subscription_changes",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="subscription_change")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},reset(){h++,u.abort(),u=new AbortController,w=null,t=null,i=null}}}var en=U.strictObject({command:ve,target:Qe,runId:U.uuid().optional(),expiresAt:U.iso.datetime({offset:!0}).optional(),deliveryLimit:U.number().int().min(1).max(100).optional()}).refine(n=>n.command.release===n.target.release),Ze=U.strictObject({schemaVersion:U.literal(1),entries:U.array(en).max(4e3)});function nn(n){let d=!1,f=()=>{d||n.unavailable(),d=!0};function b(){return n.storage===!1?void 0:n.storage??globalThis.sessionStorage}function w(t){let i=b()?.getItem(t);if(!i)return[];if(i.length>1048576)throw Error("Entry recovery is too large");return Ze.parse(JSON.parse(i)).entries}function h(t,i){let u=b();if(!u)return;if(!i.length)return u.removeItem(t);let y=JSON.stringify(Ze.parse({schemaVersion:1,entries:i}));if(y.length>1048576)throw Error("Entry recovery is too large");u.setItem(t,y)}return{load(){try{let t=n.binding();if(!t||n.storage===!1)return;let i="indiana.funnel.entries.v1."+JSON.stringify(t);return{key:i,entries:w(i)}}catch{f();return}},retain(t,i){if(t)try{let u=en.parse(i);h(t,[...w(t).filter(y=>y.command.funnelId!==u.command.funnelId),u])}catch{f()}},forget(t,i){if(t)try{h(t,w(t).filter(u=>u.command.requestId!==i))}catch{f()}}}}var tn=U.strictObject({version:U.literal(1),runs:U.array(U.uuid()).max(100)}),De=new WeakMap,Oe=new WeakMap;function Se(n){let d=!1;function f(){d||n.unavailable(),d=!0}function b(t){let i=t.storage.getItem(t.key);if(!i)return[];if(i.length>8192)throw Error("Invalid entry delivery record");return tn.parse(JSON.parse(i)).runs}function w(t){let i=De.get(t.storage);i||De.set(t.storage,i=new Map);let u=i.get(t.key);return u||i.set(t.key,u=new Set),u}function h(t){if(!t)return;let i=De.get(t.storage),u=i?.get(t.key);u?.delete(t.requestId),u?.size===0&&i?.delete(t.key)}return{claim(t,i,u,y,P=!1){if(u!==void 0)try{let R=n.binding();if(!R)throw Error("Entry delivery identity is unavailable");let B={storage:n.storage??globalThis.sessionStorage,key:"indiana.funnel.delivery.v1."+JSON.stringify([...R,i,t]),requestId:y},z=b(B);if(Oe.get(B.storage)?.has(B.key))throw Error("Entry delivery storage is unavailable");B.storage.setItem(B.key,JSON.stringify({version:1,runs:z}));let m=w(B);return!P&&!m.has(y)&&z.length+m.size>=u?!1:(m.add(y),B)}catch{return f(),!1}},accept(t,i){if(t)try{let u=b(t);u.includes(i)||t.storage.setItem(t.key,JSON.stringify(tn.parse({version:1,runs:[...u,i].slice(-100)})))}catch{let u=Oe.get(t.storage);u||Oe.set(t.storage,u=new Set),u.add(t.key),f()}finally{h(t)}},release:h}}function Pe(){let n,d,f=()=>{clearTimeout(n),n=void 0;let b=d;d=void 0,b?.cancelled()};return{get active(){return d!==void 0},start(b,w,h,t){if(d)return;if(b===0){w()?h():t();return}let i={valid:w,cancelled:t};d=i,n=setTimeout(()=>{d===i&&(d=void 0,n=void 0,w()?h():t())},b*1e3)},recheck(){d&&!d.valid()&&f()},cancel:f}}var Re=n=>["running","waiting"].includes(n.status)&&!n.pendingRequest&&(n.stopped||!n.screen&&!n.paywall&&n.instruction?.type==="wait"&&n.instruction.kind!=="operation");function Cn(n){let d=we(n.baseUrl),f=n.scope,b=Ce(n),w=n.fetch??globalThis.fetch.bind(globalThis),h,t=!1,i=!1,u=0,y=0,P="",R=0,B=0,z=0,m=!1,s,E=!0,_,O,S,l,o,T=-1,g,M=e=>{g===e&&(F.release(e.deliveryTicket),g=void 0,x())},J=new Set,c=(e,a)=>Z(n.onStatus,e,a),$=Pe(),F=Se({storage:n.deliveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,"customer",e]:void 0},unavailable:()=>c("delivery_unavailable")}),ee=new Set,te=nn({storage:n.recoveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,n.appManifestRelease,e]:void 0},unavailable:()=>c("recovery_unavailable")}),Y=e=>te.forget(e.storageKey,e.command.requestId);function Q(e,a){a&&(e.runId=a.id,e.expiresAt=a.runExpiresAt),te.retain(e.storageKey,{command:e.command,target:e.target,...e.runId&&{runId:e.runId},...e.expiresAt&&{expiresAt:e.expiresAt},...e.deliveryLimit!==void 0&&{deliveryLimit:e.deliveryLimit}})}function re(){let e=o;o=void 0,e?.host.destroy(),e?.slot.remove(),e?.client.reset(),x()}let le=()=>$.active||g!==void 0||o!==void 0&&!o.background;function me(e,a){if(o?.client!==e)return;Q(o.recovery,a);let p=Re(a);o.slot.hidden=p,p!==o.background&&(o.background=p,p?c("run_background",o.entryId):T=y,x())}function pe(e,a,p){let v=e.client.view;if(!a||e.background||!v?.screen||v.paywall||v.pendingRequest||v.stopped||v.status!=="waiting")return;let K=Ke.parse({operation:"close",requestId:crypto.randomUUID(),nodeId:v.nodeId,visit:v.visit,revision:v.revision,customerToken:a}),j=Ce({...n,session:void 0});j.requestWithCredential("funnels",K,e.runToken,{keepalive:p}).then(()=>Y(e.recovery)).catch(()=>{}).finally(()=>j.dispose())}let ae=()=>{o&&pe(o,n.session.peek(),!0)},r=()=>Date.now()<B&&performance.now()<z;function C(e){if(e.target.release!==n.appManifestRelease||!r())return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return c("incompatible",e.id),!1}}function H(e){if(t||e.epoch!==R||e.visit!==y||document.visibilityState==="hidden")return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function W(e){if(le()){c("in_progress",e.id);return}let a=R,p=y;$.start(e.delivery?.delaySeconds??0,()=>!t&&a===R&&p===y&&document.visibilityState!=="hidden"&&C(e)&&h?.entries.some(v=>v.id===e.id&&v.funnelId===e.funnelId&&v.versionId===e.versionId&&v.event===e.event&&JSON.stringify(v.target)===JSON.stringify(e.target)&&JSON.stringify(v.delivery)===JSON.stringify(e.delivery))===!0,()=>{V(e)},()=>{J.delete(`${e.funnelId}:${e.id}`)})}async function V(e){if(le()){c("in_progress",e.id);return}if(!n.session.peek()){c("identity_required",e.id);return}let a=te.load(),p=a?.entries.find(A=>A.command.funnelId===e.funnelId&&(!A.expiresAt||Date.parse(A.expiresAt)>Date.now()));if(p){if(!X(p)){c("recovery_pending",e.id);return}let A={...p,storageKey:a.key,epoch:R,visit:y};ee.add(A.command.requestId),g=A,await N(A);return}let v=crypto.randomUUID(),K=F.claim(e.id,e.funnelId,e.delivery?.maxPerSession,v);if(K===!1){c("frequency",e.id),x();return}let j={freshStart:!0,deliveryLimit:e.delivery?.maxPerSession,deliveryTicket:K,command:ve.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:v,locale:document.documentElement.lang||"en"}),epoch:R,visit:y,target:e.target,storageKey:a?.key};ee.add(j.command.requestId),g=j,await N(j)}async function N(e){if(e.dispatching)return;e.dispatching=!0;let a=e.freshStart===!0;e.freshStart=!1;let p,v=!1,K=!1;async function j(A){if(e.epoch!==R)return;let D=A.view;if(!(e.storageKey&&D&&(Re(D)||D.paywall||D.pendingRequest))&&D&&["running","waiting"].includes(D.status))try{await A.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:D.nodeId,visit:D.visit,revision:D.revision}),Y(e)}catch(k){if(!(k instanceof G&&k.code==="FORBIDDEN"))throw k}}try{if(!e.deliveryTicket&&e.deliveryLimit!==void 0){let q=F.claim(e.command.entryId,e.command.funnelId,e.deliveryLimit,e.command.requestId,!0);q!==!1&&(e.deliveryTicket=q)}Q(e),c("starting",e.command.entryId);let A=await b.request("funnels",e.command),D=Ye.safeParse(A);if(D.success){if(D.data.scope.projectId!==f.projectId||D.data.scope.environment!==f.environment)throw new G("SCOPE_MISMATCH","Entry scope changed");e.epoch===R&&c(D.data.reason,e.command.entryId),Y(e),M(e);return}let k=Xe.parse(A);if(!k.runToken||k.scope.projectId!==f.projectId||k.scope.environment!==f.environment||k.run.source.type!=="funnel"||k.run.source.id!==e.command.funnelId||k.run.source.versionId!==e.command.versionId||e.runId!==void 0&&k.run.id!==e.runId)throw new G("INVALID_RESPONSE","Invalid entry Run");if(F.accept(e.deliveryTicket,k.run.id),e.epoch!==R){M(e),c("identity_changed",e.command.entryId);return}Q(e,k.run);let L=Ae({...n,runToken:k.runToken,funnelId:e.command.funnelId,initialResponse:a?A:void 0});p=L,K=!0,await L.get(),K=!1;let ne=L.view;if(!ne||ne.id!==k.run.id||ne.source.type!=="funnel"||ne.source.id!==e.command.funnelId||ne.source.versionId!==e.command.versionId)throw new G("INVALID_RESPONSE","Entry Run version changed");if(!["running","waiting"].includes(ne.status)){Y(e),M(e),c("run_ended",e.command.entryId);return}let{showFunnelRun:fe}=await import("./funnel-runtime-host-TQAFDG3X.js");if(!H(e)){await j(L),c("left_screen",e.command.entryId),M(e);return}let Ne=!1,xe=!1;if(o&&!o.background){await j(L),c("in_progress",e.command.entryId),M(e);return}o&&re();let ie=document.createElement("div");ie.hidden=Re(ne),n.container.append(ie);let ke=await fe(ie,{...n.host,client:L,appManifestRelease:n.appManifestRelease,onState(q){me(L,q),Z(n.host?.onState,q)},onDismiss(q){Ne=!0,ie.remove(),q&&!["running","waiting"].includes(q.status)&&Y(e),o?.client===L&&(o=void 0,L.reset(),x(),q&&q.status!=="completed"&&c("run_ended",e.command.entryId)),Z(n.host?.onDismiss,q)},onComplete(q){xe=!0,Y(e),o?.client===L&&re(),Z(n.host?.onComplete,q)},onError(q){Z(n.host?.onError,q),o?.client===L&&q instanceof G&&q.code==="FORBIDDEN"&&(Y(e),re(),c("run_ended",e.command.entryId))}}).catch(q=>{throw ie.remove(),q});if(!H(e)||Ne||xe){ke.destroy(),ie.remove(),H(e)||await j(L),M(e);return}let he=Re(L.view??ne);ie.hidden=he,o={host:ke,client:L,slot:ie,entryId:e.command.entryId,background:he,runToken:k.runToken,owner:n.session.peek(),recovery:e},he||(T=e.visit),v=!0,M(e),c("started",e.command.entryId),he&&c("run_background",e.command.entryId)}catch(A){A instanceof G&&(!p||K&&A.code==="FORBIDDEN")&&A.status!==void 0&&A.status>=400&&A.status<500&&!A.retryable&&(Y(e),M(e)),e.epoch===R&&!t&&(c("start_failed",e.command.entryId),Z(n.host?.onError,A))}finally{v||p?.reset(),e.dispatching=!1}}function X(e){if(e.command.release!==n.appManifestRelease||e.target.release!==n.appManifestRelease)return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function ye(){if(le())return!1;let e=te.load();for(let a of e?.entries??[]){if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now()){te.forget(e.key,a.command.requestId);continue}if(a.command.requestId===o?.recovery.command.requestId||ee.has(a.command.requestId)||!X(a))continue;ee.add(a.command.requestId);let p={...a,storageKey:e.key,epoch:R,visit:y};return g=p,N(p),!0}return!1}function ue(){if(m=!1,$.recheck(),t||!i||document.visibilityState==="hidden")return;se();let e=o!==void 0&&!o.background;if(e&&(T=y),!ye()){if(!r()){E=!0;return}E=!1;for(let a of h?.entries??[]){let p=`${a.funnelId}:${a.id}`;if(!(a.event!=="screen_enter"||J.has(p)||!C(a))){if(!n.session.peek()){c("identity_required",a.id);continue}if(T===y){J.add(p),e&&c("in_progress",a.id);continue}if(g||$.active){c("in_progress",a.id);return}J.add(p),W(a);break}}}}let x=()=>{!m&&!t&&(m=!0,queueMicrotask(ue))};function se(){let e=location.origin+location.pathname;return e===P?!1:(P=e,y++,$.cancel(),E=!0,J.clear(),ee.clear(),!0)}function oe(){se()&&x()}function ce(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let a=e.target;if(!(a instanceof Element)||a.closest("[data-indiana-funnel]"))return;let p=a.closest("button,a,input");if(!(!p||p.matches(":disabled,[aria-disabled='true']")||p.closest("[hidden],[inert],[aria-hidden='true']")))for(let v of h?.entries??[]){let K=v.target.button;if(!(v.event!=="button_click"||!K||!C(v))){try{let j=be(document);if(!p.matches(K.selector)||j(K.selector,p)!==1)continue}catch{c("incompatible",v.id);continue}W(v);break}}}async function Me(){if(t)return;if(s)return s;let e=++u,a=new AbortController;_=a;let p,v=new Promise((A,D)=>{p=()=>D(new G("TIMEOUT","Funnel entry configuration read cancelled or timed out")),a.signal.addEventListener("abort",p,{once:!0})}),K=setTimeout(()=>a.abort(),n.timeoutMs??5e3),j=(async()=>{let A=async()=>{let fe=await w(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:a.signal});if(!fe.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",fe.status);return ge.parse(await fe.json())},D=await Promise.race([A(),v]),k=Date.parse(D.validatedAt),L=Date.parse(D.validUntil);if(D.scope.projectId!==f.projectId||D.scope.environment!==f.environment||D.scope.environmentId!==n.environmentId||D.release!==n.appManifestRelease||L<=Date.now()||k>Date.now()+5e3||L-k>6e4||L<=k)throw new G("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(t||e!==u)return;let ne=h===void 0;h=D,B=L,z=performance.now()+Math.min(L-Date.now(),6e4),$.recheck(),(ne||E)&&x()})();s=j;try{await j}finally{clearTimeout(K),a.signal.removeEventListener("abort",p),s===j&&(s=void 0)}}async function on(){if(!(!i||t)){try{await Me()}catch{t||c("configuration_unavailable")}x()}}let Fe=Ie({document,run:on,delay:()=>i&&!t?15e3:void 0});return{async start(){i||t||(i=!0,P=location.origin+location.pathname,O=Ee(oe),S=n.session.subscribeIdentity(()=>{R++,$.cancel(),F.release(g?.deliveryTicket),E=!0,g=void 0,J.clear(),T=-1,ee.clear(),o&&pe(o,o.owner,!1),re(),x()}),l=new MutationObserver(x),l.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",ce,!0),document.addEventListener("visibilitychange",x),addEventListener("pagehide",ae),await Fe.refresh())},refresh:Me,async retry(){g&&!t&&g.epoch===R&&await N(g)},destroy(){t=!0,u++,$.cancel(),F.release(g?.deliveryTicket),Fe.destroy(),_?.abort(),l?.disconnect(),O?.(),S?.(),document.removeEventListener("click",ce,!0),document.removeEventListener("visibilitychange",x),removeEventListener("pagehide",ae),ae(),re(),b.dispose(),h=void 0}}}function An(n){let d=we(n.baseUrl),f=n.fetch??globalThis.fetch.bind(globalThis),b,w=0,h=0,t=!1,i=!1,u=!1,y=0,P=0,R=-1,B=!1,z="",m,s,E,_,O=new Set,S,l,o,T=(r,C)=>Z(n.onStatus,r,C),g=Pe(),M=()=>{try{return n.deliveryIdentity?.()}catch{return}},J=()=>JSON.stringify(M()),c=Se({storage:n.deliveryStorage,binding:()=>{let r=M();return r?.id?[d,n.scope.projectId,n.scope.environment,n.environmentId,r.type,r.id]:void 0},unavailable:()=>T("delivery_unavailable")}),$=()=>Date.now()<w&&performance.now()<h;function F(r){try{return $()&&r.target.release===n.appManifestRelease&&de(r.target.render,document,location.pathname,()=>{})}catch{return T("incompatible",r.id),!1}}function ee(){let r=o;o=void 0,r?.host.destroy(),r?.slot.remove()}async function te(r){if(r.dispatching)return;r.dispatching=!0;let C=y;try{let H=await r.process.open({operation:"entry_start",funnelId:r.entry.funnelId,versionId:r.entry.versionId,entryId:r.entry.id,release:n.appManifestRelease,locale:n.locale??"en"});c.accept(r.deliveryTicket,H.run.id);let{showFunnelRun:W}=await import("./funnel-runtime-host-TQAFDG3X.js");if(t||C!==y||l!==r)return;let V=document.createElement("div");n.container.append(V),R=P;let N=await W(V,{...n.host,client:H.controller,appManifestRelease:n.appManifestRelease,onDismiss(X){o?.process===r.process&&(o=void 0,V.remove()),Z(n.host?.onDismiss,X)}});if(t||C!==y||l!==r){N.destroy(),V.remove();return}o={entry:r.entry,process:r.process,host:N,slot:V,deliveryTicket:r.deliveryTicket},l=void 0,T("run_presented",r.entry.id)}catch(H){if(t||C!==y||l!==r)return;H instanceof G&&"result"in H?(c.release(r.deliveryTicket),l=void 0,r.process.destroy(),T("suppressed",r.entry.id),Q()):T("entry_unavailable",r.entry.id)}finally{r.dispatching=!1}}function Y(r){if(t||i||l||o||S||g.active||R===P||!F(r))return;let C=`${P}:${r.id}`;if(O.has(C))return;O.add(C);let H=P,W=y,V=J();g.start(r.delivery?.delaySeconds??0,()=>!t&&y===W&&P===H&&J()===V&&document.visibilityState!=="hidden"&&F(r)&&b?.entries.some(N=>N.id===r.id&&N.funnelId===r.funnelId&&N.versionId===r.versionId&&N.event===r.event&&JSON.stringify(N.target)===JSON.stringify(r.target)&&JSON.stringify(N.delivery)===JSON.stringify(r.delivery))===!0,()=>{let N=c.claim(r.id,r.funnelId,r.delivery?.maxPerSession,crypto.randomUUID());if(N===!1){T("frequency",r.id),Q();return}try{let X={entry:r,process:n.createProcess(r),visit:P,deliveryTicket:N};l=X,te(X)}catch(X){c.release(N),T("entry_unavailable",r.id),Z(n.host?.onError,X)}},()=>{O.delete(C)})}function Q(){B||t||(B=!0,queueMicrotask(()=>{if(B=!1,g.recheck(),!(t||i||document.visibilityState==="hidden"||!$()||l||o||S||g.active||R===P)){for(let r of b?.entries??[])if(r.event==="screen_enter"&&!O.has(`${P}:${r.id}`)&&F(r)){Y(r);break}}}))}function re(r){if(!r.isTrusted||r.defaultPrevented||!(r.target instanceof Element)||l||o||S||R===P)return;let C=be(document,()=>{});for(let H of b?.entries??[]){let W=H.target.button;if(H.event!=="button_click"||!W||!F(H))continue;let V=r.target.closest(W.selector);if(!(!V||V.tagName.toLowerCase()!==W.tag||C(W.selector)!==1||V.matches(":disabled")||V.closest('[inert],[hidden],[aria-hidden="true"]'))){Y(H);break}}}let le=()=>{let r=location.origin+location.pathname;r!==z&&(z=r,P++,g.cancel(),O.clear(),Q())};async function me(){if(t)return;if(s)return s;let r=y,C=new AbortController;m=C;let H,W=new Promise((ye,ue)=>{H=ue}),V=()=>H(new G("TIMEOUT","Funnel entry read cancelled"));C.signal.addEventListener("abort",V,{once:!0});let N=setTimeout(()=>C.abort(),n.timeoutMs??5e3),X=(async()=>{let ye=encodeURIComponent(JSON.stringify(["funnel-process/1"])),ue=async()=>{let ce=await f(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}&executionContracts=${ye}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:C.signal});if(!ce.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",ce.status);return ge.parse(await ce.json())},x=await Promise.race([ue(),W]),se=Date.parse(x.validatedAt),oe=Date.parse(x.validUntil);if(x.scope.projectId!==n.scope.projectId||x.scope.environment!==n.scope.environment||x.scope.environmentId!==n.environmentId||x.release!==n.appManifestRelease||oe<=Date.now()||se>Date.now()+5e3||oe<=se||oe-se>6e4)throw new G("INVALID_RESPONSE","Entry scope or deadline changed");t||r!==y||(b=x,w=oe,h=performance.now()+Math.min(oe-Date.now(),6e4),g.recheck(),Q())})();s=X;try{await X}finally{clearTimeout(N),C.signal.removeEventListener("abort",V),s===X&&(s=void 0)}}async function pe(){if(!(!u||t))try{await me()}catch{t||T("configuration_unavailable")}}let ae=Ie({document,run:pe,delay:()=>u&&!t?15e3:void 0});return{async start(){u||t||(u=!0,z=location.origin+location.pathname,E=Ee(le),_=new MutationObserver(Q),_.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",re,!0),document.addEventListener("visibilitychange",Q),await ae.refresh())},refresh:me,async retry(){l&&!t&&await te(l)},async syncIdentity(){g.cancel();let r=o??l??S;if(!r){i=!1,Q();return}try{let C=await r.process.syncIdentity();return i=!1,S===r&&(l={...r,visit:P},S=void 0,await te(l)),C}catch(C){throw r.process.view||(S={...r,visit:P},l=void 0,ee()),C}},async detach(){i=!0,y++,g.cancel(),m?.abort();let r=o??l??S;r&&(S={...r,visit:P}),l=void 0,ee(),r&&await r.process.detach()},destroy(){t=!0,y++,g.cancel(),ae.destroy(),m?.abort(),_?.disconnect(),E?.(),document.removeEventListener("click",re,!0),document.removeEventListener("visibilitychange",Q);let r=o??l??S;c.release(r?.deliveryTicket),l=void 0,S=void 0,ee(),r?.process.destroy(),b=void 0}}}async function Dn(n,d){return(await import("./paywall-3P5YKZRE.js")).showPaywall(n,d)}async function dt(){return await Promise.all([import("./paywall-3P5YKZRE.js"),import("./screen-renderer-TZIU775B.js")]),Dn}async function lt(...n){return n[1]=ze(n[1]),(await import("./paywall-session-AWH5GSKC.js")).createPaywallSession(...n)}async function ut(...n){let d=n[1].signal?.aborted?void 0:We(n[1].client);try{return import("./screen-renderer-TZIU775B.js").catch(()=>{}),import("./paywall-3P5YKZRE.js").catch(()=>{}),await(await rn(()=>import("./funnel-runtime-host-TQAFDG3X.js"),n[1].prepared)).showFunnelRun(...n)}finally{d?.()}}async function rn(n,d){try{return await n()}catch(f){throw d&&d.state!=="adopted"&&await import("./funnel-paywall-prerender-RSXERNQ3.js").then(b=>b.preparedInternals(d)?.release(),()=>{}),f}}async function ft(...n){return import("./screen-renderer-TZIU775B.js").catch(()=>{}),import("./paywall-3P5YKZRE.js").catch(()=>{}),(await rn(()=>import("./funnel-host-purchase-45TUH4H2.js"),n[1].prepared)).showFunnelPurchase(...n)}async function mt(...n){return import("./funnel-host-purchase-45TUH4H2.js").catch(()=>{}),import("./screen-renderer-TZIU775B.js").catch(()=>{}),(await import("./funnel-paywall-prerender-RSXERNQ3.js")).prerenderFunnelPurchase(...n)}async function pt(){await Promise.all([import("./funnel-paywall-prerender-RSXERNQ3.js"),import("./funnel-host-purchase-45TUH4H2.js"),import("./paywall-3P5YKZRE.js"),import("./screen-renderer-TZIU775B.js"),import("./paywall-content-JJCSFM6J.js"),import("./check-response-DO2R3PE6.js"),import("./operation-contracts-WLKY7HAO.js")])}async function yt(...n){return(await import("./funnel-route-prediction-G4OKIQGD.js")).predictFunnelStart(...n)}async function ht(...n){return(await import("./funnel-route-prediction-G4OKIQGD.js")).predictedPaywallLoadingDocument(...n)}async function gt(...n){return(await import("./funnel-host-recovery-paywall-JQWNXDLS.js")).mountFunnelRecoveryPaywall(...n)}async function vt(...n){return(await import("./content-AD7CZRT4.js")).mountContent(...n)}async function It(...n){return(await import("./content-AD7CZRT4.js")).prepareContent(...n)}export{G as LongplayError,I as MerchantBridgeError,yn as createBrowserFunnelCommandStorage,En as createBrowserFunnelPurchaseStorage,vn as createConfigurationSync,mn as createFeatureClient,wn as createFunnelClient,Rn as createFunnelPageExperiments,Sn as createFunnelProcess,bn as createFunnelPurchaseClient,Ae as createFunnelRunController,Cn as createIamFunnelEntries,An as createIamFunnelProcessEntries,Pn as createLocalFunnelClient,pn as createLongplay,Tn as createMerchantBridge,lt as createPaywallSession,In as evaluateFunnelNode,sn as formatCouponDiscount,an as formatCouponMoney,cn as formatCouponTerms,hn as getPaywallRecovery,un as isPaywallOperationComplete,fn as isPaywallOperationPending,ln as isPaywallUpdateOperation,dn as isPaywallUpdateQuote,vt as mountContent,gt as mountFunnelRecoveryPaywall,yt as predictFunnelStart,ht as predictedPaywallLoadingDocument,pt as preloadFunnelPurchase,dt as preloadPaywall,It as prepareContent,gn as preparePaywallFallback,mt as prerenderFunnelPurchase,ft as showFunnelPurchase,ut as showFunnelRun,Dn as showPaywall};
|
|
1
|
+
import{a as En,c as bn}from"./chunk-XH6VXXCX.js";import{a as Rn}from"./chunk-7ZAM4YRK.js";import{a as We}from"./chunk-AEQUKR4O.js";import{a as Ie}from"./chunk-W32FI2A2.js";import{a as pn,c as wn,d as Sn}from"./chunk-PG5Q3B7Z.js";import"./chunk-ORR47GDS.js";import{a as In}from"./chunk-SYFRWKJP.js";import"./chunk-EQUVI5QU.js";import{h as mn,i as vn,k as Pn}from"./chunk-NS4YGWQP.js";import{E as Ae,d as Xe,f as Qe,g as ge,h as ve,i as Ye,w as yn}from"./chunk-YQ2PQWHZ.js";import"./chunk-F4AIEI5N.js";import{a as ze}from"./chunk-FFEJS4K3.js";import{c as hn,e as gn}from"./chunk-EQBJNU6R.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import"./chunk-PUDTOCQF.js";import"./chunk-Z5JTYDD5.js";import"./chunk-GADT6JMW.js";import"./chunk-5BPZUW6B.js";import{K as Ke}from"./chunk-I5ZXIKOT.js";import"./chunk-6XRQR43F.js";import{B as dn,C as ln,D as un,E as fn,c as an,d as sn,e as cn}from"./chunk-3532HSBP.js";import{A as Le,B as Be,D as He,F as qe,G as Ue,I as Ve,J as je,K as Ge,L as Je,M as Te,N as $e,z as _e}from"./chunk-67WFVDTV.js";import"./chunk-KX67ZM7H.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import{b as Ce}from"./chunk-3WCIX4VH.js";import"./chunk-KCUE2VFJ.js";import"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import{a as G}from"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import{a as be,c as de}from"./chunk-J6KIN4RH.js";import"./chunk-SLUA7ABW.js";import{c as we,d as Ee}from"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-ZHVVJBT6.js";import"./chunk-5MRSFLQA.js";import{b as U}from"./chunk-W22ESUYY.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";var I=class extends Error{constructor(f,b=0,w=!1,h="fix_request"){super(f);this.code=f;this.status=b;this.retryable=w;this.recovery=h;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function _n(n,d){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let f=n.body?.getReader();if(!f)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let b=()=>{f.cancel().catch(()=>{})};d.addEventListener("abort",b,{once:!0});let w=0,h="",t=new TextDecoder("utf-8",{fatal:!0});try{for(d.throwIfAborted();;){let i=await f.read();if(d.throwIfAborted(),i.done)break;if(w+=i.value.byteLength,w>262144)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");h+=t.decode(i.value,{stream:!0})}return h+=t.decode(),JSON.parse(h)}catch(i){throw d.throwIfAborted(),i instanceof I?i:new I("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{d.removeEventListener("abort",b),await f.cancel().catch(()=>{}),f.releaseLock()}}function Tn(n){let d=qe.parse(n.origin),f=Ue.parse(n.manifest),b={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let m of["projectId","environmentId","environment"])if(f[m]!==n.scope[m])throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");let w=n.customerId===void 0?null:U.uuid().parse(n.customerId),h=0,t=null,i=null,u=new AbortController,y=n.fetch??globalThis.fetch;async function P(m,s,E,_,O){if(!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=He[m];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(S.authority))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);let l=h,o=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],..._?[_]:[]]);o.throwIfAborted();let T=new Headers(await n.headers?.());if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(T.get("authorization")??"")||T.has("X-Indiana-Bridge-Signature")||T.has("X-Indiana-Bridge-Key-Id"))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);T.set(Be,String(_e)),T.set("Accept","application/json");let g=crypto.randomUUID();T.set("X-Request-Id",g),T.set("Content-Type","application/json");let M=await y(d+Le,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:T,signal:o,body:JSON.stringify({bridgeVersion:_e,requestId:g,command:S.command,scope:b,data:O??(E===void 0?{}:{operationId:E})})}),J=await _n(M,o);if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(!M.ok){let F=$e.safeParse(J);throw!F.success||F.data.scope.projectId!==n.scope.projectId||F.data.scope.environment!==n.scope.environment||F.data.scope.environmentId!==n.scope.environmentId||F.data.requestId!==g||F.data.command!==S.command?new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status):new I(F.data.error.code,M.status,F.data.error.retryable,F.data.error.recovery)}let c=Ve(U.unknown()).safeParse(J);if(!c.success||c.data.scope.projectId!==n.scope.projectId||c.data.scope.environment!==n.scope.environment||c.data.scope.environmentId!==n.scope.environmentId||c.data.requestId!==g||c.data.command!==S.command)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);let $=s.safeParse(c.data.data);if(!$.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);return $.data}function R(){if(!w)throw new I("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return w}async function B(m,s,E,_){let O=R();if(_!==void 0&&Te.parse({operationId:_,customerId:O}),!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=h,l=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...s?[s]:[]]);l.throwIfAborted();let o,T=new Promise((g,M)=>{o=()=>M(l.reason),l.addEventListener("abort",o,{once:!0})});try{let M=E(async()=>{let c=await import("./merchant-bridge-contracts-OIYML3DE.js");if(l.throwIfAborted(),S!==h||w!==O)throw new DOMException("Merchant identity changed","AbortError");return c},l),J=await Promise.race([M,T]);return l.throwIfAborted(),J}finally{l.removeEventListener("abort",o)}}async function z(m,s,E,_){let O=R(),S=Te.parse({operationId:E,customerId:O}),l=await P(m,s,S.operationId,_,S);if(l.customerId!==O||l.operationId!==S.operationId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return l}return{async readPresentation(m){let s=await P("presentation",Ge,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(s.presentation&&w!==null&&s.presentation.customerId!==w)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i=s.nativeUserId,t=s.presentation,s},async createSession(m){let s=await P("session",je,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(w!==null&&w!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(t&&t.customerId!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return w=s.session.customerId,i=s.nativeUserId,s.session},async reportPresentation(m,s){let E=R(),_=Je.parse(m);if(!t||t.customerId!==E||t.decisionId!==_.decisionId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return P("presentation_events",U.strictObject({queued:U.literal(!0)}),void 0,s,_)},async readCustomerCommerce(m){let s=R(),E=await B("customer_commerce",m,async(_,O)=>{let[S,l]=await Promise.all([_(),P("customer_commerce",U.unknown(),void 0,O)]),o=S.merchantBridgeCommerceSchema.safeParse(l);if(!o.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return o.data});if(E.customerId!==s)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return E},async executePurchase(m,s){let E=await B("purchases",s,async(_,O)=>z("purchases",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="purchase")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},readOperation:(m,s)=>B("operation_status",s,async(E,_)=>z("operation_status",(await E()).merchantOperationLookupSchema,m,_),m),async executeSubscriptionChange(m,s){let E=await B("subscription_changes",s,async(_,O)=>z("subscription_changes",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="subscription_change")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},reset(){h++,u.abort(),u=new AbortController,w=null,t=null,i=null}}}var en=U.strictObject({command:ve,target:Qe,runId:U.uuid().optional(),expiresAt:U.iso.datetime({offset:!0}).optional(),deliveryLimit:U.number().int().min(1).max(100).optional()}).refine(n=>n.command.release===n.target.release),Ze=U.strictObject({schemaVersion:U.literal(1),entries:U.array(en).max(4e3)});function nn(n){let d=!1,f=()=>{d||n.unavailable(),d=!0};function b(){return n.storage===!1?void 0:n.storage??globalThis.sessionStorage}function w(t){let i=b()?.getItem(t);if(!i)return[];if(i.length>1048576)throw Error("Entry recovery is too large");return Ze.parse(JSON.parse(i)).entries}function h(t,i){let u=b();if(!u)return;if(!i.length)return u.removeItem(t);let y=JSON.stringify(Ze.parse({schemaVersion:1,entries:i}));if(y.length>1048576)throw Error("Entry recovery is too large");u.setItem(t,y)}return{load(){try{let t=n.binding();if(!t||n.storage===!1)return;let i="indiana.funnel.entries.v1."+JSON.stringify(t);return{key:i,entries:w(i)}}catch{f();return}},retain(t,i){if(t)try{let u=en.parse(i);h(t,[...w(t).filter(y=>y.command.funnelId!==u.command.funnelId),u])}catch{f()}},forget(t,i){if(t)try{h(t,w(t).filter(u=>u.command.requestId!==i))}catch{f()}}}}var tn=U.strictObject({version:U.literal(1),runs:U.array(U.uuid()).max(100)}),De=new WeakMap,Oe=new WeakMap;function Se(n){let d=!1;function f(){d||n.unavailable(),d=!0}function b(t){let i=t.storage.getItem(t.key);if(!i)return[];if(i.length>8192)throw Error("Invalid entry delivery record");return tn.parse(JSON.parse(i)).runs}function w(t){let i=De.get(t.storage);i||De.set(t.storage,i=new Map);let u=i.get(t.key);return u||i.set(t.key,u=new Set),u}function h(t){if(!t)return;let i=De.get(t.storage),u=i?.get(t.key);u?.delete(t.requestId),u?.size===0&&i?.delete(t.key)}return{claim(t,i,u,y,P=!1){if(u!==void 0)try{let R=n.binding();if(!R)throw Error("Entry delivery identity is unavailable");let B={storage:n.storage??globalThis.sessionStorage,key:"indiana.funnel.delivery.v1."+JSON.stringify([...R,i,t]),requestId:y},z=b(B);if(Oe.get(B.storage)?.has(B.key))throw Error("Entry delivery storage is unavailable");B.storage.setItem(B.key,JSON.stringify({version:1,runs:z}));let m=w(B);return!P&&!m.has(y)&&z.length+m.size>=u?!1:(m.add(y),B)}catch{return f(),!1}},accept(t,i){if(t)try{let u=b(t);u.includes(i)||t.storage.setItem(t.key,JSON.stringify(tn.parse({version:1,runs:[...u,i].slice(-100)})))}catch{let u=Oe.get(t.storage);u||Oe.set(t.storage,u=new Set),u.add(t.key),f()}finally{h(t)}},release:h}}function Pe(){let n,d,f=()=>{clearTimeout(n),n=void 0;let b=d;d=void 0,b?.cancelled()};return{get active(){return d!==void 0},start(b,w,h,t){if(d)return;if(b===0){w()?h():t();return}let i={valid:w,cancelled:t};d=i,n=setTimeout(()=>{d===i&&(d=void 0,n=void 0,w()?h():t())},b*1e3)},recheck(){d&&!d.valid()&&f()},cancel:f}}var Re=n=>["running","waiting"].includes(n.status)&&!n.pendingRequest&&(n.stopped||!n.screen&&!n.paywall&&n.instruction?.type==="wait"&&n.instruction.kind!=="operation");function Cn(n){let d=we(n.baseUrl),f=n.scope,b=Ce(n),w=n.fetch??globalThis.fetch.bind(globalThis),h,t=!1,i=!1,u=0,y=0,P="",R=0,B=0,z=0,m=!1,s,E=!0,_,O,S,l,o,T=-1,g,M=e=>{g===e&&(F.release(e.deliveryTicket),g=void 0,x())},J=new Set,c=(e,a)=>Z(n.onStatus,e,a),$=Pe(),F=Se({storage:n.deliveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,"customer",e]:void 0},unavailable:()=>c("delivery_unavailable")}),ee=new Set,te=nn({storage:n.recoveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,n.appManifestRelease,e]:void 0},unavailable:()=>c("recovery_unavailable")}),Y=e=>te.forget(e.storageKey,e.command.requestId);function Q(e,a){a&&(e.runId=a.id,e.expiresAt=a.runExpiresAt),te.retain(e.storageKey,{command:e.command,target:e.target,...e.runId&&{runId:e.runId},...e.expiresAt&&{expiresAt:e.expiresAt},...e.deliveryLimit!==void 0&&{deliveryLimit:e.deliveryLimit}})}function re(){let e=o;o=void 0,e?.host.destroy(),e?.slot.remove(),e?.client.reset(),x()}let le=()=>$.active||g!==void 0||o!==void 0&&!o.background;function me(e,a){if(o?.client!==e)return;Q(o.recovery,a);let p=Re(a);o.slot.hidden=p,p!==o.background&&(o.background=p,p?c("run_background",o.entryId):T=y,x())}function pe(e,a,p){let v=e.client.view;if(!a||e.background||!v?.screen||v.paywall||v.pendingRequest||v.stopped||v.status!=="waiting")return;let K=Ke.parse({operation:"close",requestId:crypto.randomUUID(),nodeId:v.nodeId,visit:v.visit,revision:v.revision,customerToken:a}),j=Ce({...n,session:void 0});j.requestWithCredential("funnels",K,e.runToken,{keepalive:p}).then(()=>Y(e.recovery)).catch(()=>{}).finally(()=>j.dispose())}let ae=()=>{o&&pe(o,n.session.peek(),!0)},r=()=>Date.now()<B&&performance.now()<z;function C(e){if(e.target.release!==n.appManifestRelease||!r())return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return c("incompatible",e.id),!1}}function H(e){if(t||e.epoch!==R||e.visit!==y||document.visibilityState==="hidden")return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function W(e){if(le()){c("in_progress",e.id);return}let a=R,p=y;$.start(e.delivery?.delaySeconds??0,()=>!t&&a===R&&p===y&&document.visibilityState!=="hidden"&&C(e)&&h?.entries.some(v=>v.id===e.id&&v.funnelId===e.funnelId&&v.versionId===e.versionId&&v.event===e.event&&JSON.stringify(v.target)===JSON.stringify(e.target)&&JSON.stringify(v.delivery)===JSON.stringify(e.delivery))===!0,()=>{V(e)},()=>{J.delete(`${e.funnelId}:${e.id}`)})}async function V(e){if(le()){c("in_progress",e.id);return}if(!n.session.peek()){c("identity_required",e.id);return}let a=te.load(),p=a?.entries.find(A=>A.command.funnelId===e.funnelId&&(!A.expiresAt||Date.parse(A.expiresAt)>Date.now()));if(p){if(!X(p)){c("recovery_pending",e.id);return}let A={...p,storageKey:a.key,epoch:R,visit:y};ee.add(A.command.requestId),g=A,await N(A);return}let v=crypto.randomUUID(),K=F.claim(e.id,e.funnelId,e.delivery?.maxPerSession,v);if(K===!1){c("frequency",e.id),x();return}let j={freshStart:!0,deliveryLimit:e.delivery?.maxPerSession,deliveryTicket:K,command:ve.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:v,locale:document.documentElement.lang||"en"}),epoch:R,visit:y,target:e.target,storageKey:a?.key};ee.add(j.command.requestId),g=j,await N(j)}async function N(e){if(e.dispatching)return;e.dispatching=!0;let a=e.freshStart===!0;e.freshStart=!1;let p,v=!1,K=!1;async function j(A){if(e.epoch!==R)return;let D=A.view;if(!(e.storageKey&&D&&(Re(D)||D.paywall||D.pendingRequest))&&D&&["running","waiting"].includes(D.status))try{await A.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:D.nodeId,visit:D.visit,revision:D.revision}),Y(e)}catch(k){if(!(k instanceof G&&k.code==="FORBIDDEN"))throw k}}try{if(!e.deliveryTicket&&e.deliveryLimit!==void 0){let q=F.claim(e.command.entryId,e.command.funnelId,e.deliveryLimit,e.command.requestId,!0);q!==!1&&(e.deliveryTicket=q)}Q(e),c("starting",e.command.entryId);let A=await b.request("funnels",e.command),D=Ye.safeParse(A);if(D.success){if(D.data.scope.projectId!==f.projectId||D.data.scope.environment!==f.environment)throw new G("SCOPE_MISMATCH","Entry scope changed");e.epoch===R&&c(D.data.reason,e.command.entryId),Y(e),M(e);return}let k=Xe.parse(A);if(!k.runToken||k.scope.projectId!==f.projectId||k.scope.environment!==f.environment||k.run.source.type!=="funnel"||k.run.source.id!==e.command.funnelId||k.run.source.versionId!==e.command.versionId||e.runId!==void 0&&k.run.id!==e.runId)throw new G("INVALID_RESPONSE","Invalid entry Run");if(F.accept(e.deliveryTicket,k.run.id),e.epoch!==R){M(e),c("identity_changed",e.command.entryId);return}Q(e,k.run);let L=Ae({...n,runToken:k.runToken,funnelId:e.command.funnelId,initialResponse:a?A:void 0});p=L,K=!0,await L.get(),K=!1;let ne=L.view;if(!ne||ne.id!==k.run.id||ne.source.type!=="funnel"||ne.source.id!==e.command.funnelId||ne.source.versionId!==e.command.versionId)throw new G("INVALID_RESPONSE","Entry Run version changed");if(!["running","waiting"].includes(ne.status)){Y(e),M(e),c("run_ended",e.command.entryId);return}let{showFunnelRun:fe}=await import("./funnel-runtime-host-4KBMPKBE.js");if(!H(e)){await j(L),c("left_screen",e.command.entryId),M(e);return}let Ne=!1,xe=!1;if(o&&!o.background){await j(L),c("in_progress",e.command.entryId),M(e);return}o&&re();let ie=document.createElement("div");ie.hidden=Re(ne),n.container.append(ie);let ke=await fe(ie,{...n.host,client:L,appManifestRelease:n.appManifestRelease,onState(q){me(L,q),Z(n.host?.onState,q)},onDismiss(q){Ne=!0,ie.remove(),q&&!["running","waiting"].includes(q.status)&&Y(e),o?.client===L&&(o=void 0,L.reset(),x(),q&&q.status!=="completed"&&c("run_ended",e.command.entryId)),Z(n.host?.onDismiss,q)},onComplete(q){xe=!0,Y(e),o?.client===L&&re(),Z(n.host?.onComplete,q)},onError(q){Z(n.host?.onError,q),o?.client===L&&q instanceof G&&q.code==="FORBIDDEN"&&(Y(e),re(),c("run_ended",e.command.entryId))}}).catch(q=>{throw ie.remove(),q});if(!H(e)||Ne||xe){ke.destroy(),ie.remove(),H(e)||await j(L),M(e);return}let he=Re(L.view??ne);ie.hidden=he,o={host:ke,client:L,slot:ie,entryId:e.command.entryId,background:he,runToken:k.runToken,owner:n.session.peek(),recovery:e},he||(T=e.visit),v=!0,M(e),c("started",e.command.entryId),he&&c("run_background",e.command.entryId)}catch(A){A instanceof G&&(!p||K&&A.code==="FORBIDDEN")&&A.status!==void 0&&A.status>=400&&A.status<500&&!A.retryable&&(Y(e),M(e)),e.epoch===R&&!t&&(c("start_failed",e.command.entryId),Z(n.host?.onError,A))}finally{v||p?.reset(),e.dispatching=!1}}function X(e){if(e.command.release!==n.appManifestRelease||e.target.release!==n.appManifestRelease)return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function ye(){if(le())return!1;let e=te.load();for(let a of e?.entries??[]){if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now()){te.forget(e.key,a.command.requestId);continue}if(a.command.requestId===o?.recovery.command.requestId||ee.has(a.command.requestId)||!X(a))continue;ee.add(a.command.requestId);let p={...a,storageKey:e.key,epoch:R,visit:y};return g=p,N(p),!0}return!1}function ue(){if(m=!1,$.recheck(),t||!i||document.visibilityState==="hidden")return;se();let e=o!==void 0&&!o.background;if(e&&(T=y),!ye()){if(!r()){E=!0;return}E=!1;for(let a of h?.entries??[]){let p=`${a.funnelId}:${a.id}`;if(!(a.event!=="screen_enter"||J.has(p)||!C(a))){if(!n.session.peek()){c("identity_required",a.id);continue}if(T===y){J.add(p),e&&c("in_progress",a.id);continue}if(g||$.active){c("in_progress",a.id);return}J.add(p),W(a);break}}}}let x=()=>{!m&&!t&&(m=!0,queueMicrotask(ue))};function se(){let e=location.origin+location.pathname;return e===P?!1:(P=e,y++,$.cancel(),E=!0,J.clear(),ee.clear(),!0)}function oe(){se()&&x()}function ce(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let a=e.target;if(!(a instanceof Element)||a.closest("[data-indiana-funnel]"))return;let p=a.closest("button,a,input");if(!(!p||p.matches(":disabled,[aria-disabled='true']")||p.closest("[hidden],[inert],[aria-hidden='true']")))for(let v of h?.entries??[]){let K=v.target.button;if(!(v.event!=="button_click"||!K||!C(v))){try{let j=be(document);if(!p.matches(K.selector)||j(K.selector,p)!==1)continue}catch{c("incompatible",v.id);continue}W(v);break}}}async function Me(){if(t)return;if(s)return s;let e=++u,a=new AbortController;_=a;let p,v=new Promise((A,D)=>{p=()=>D(new G("TIMEOUT","Funnel entry configuration read cancelled or timed out")),a.signal.addEventListener("abort",p,{once:!0})}),K=setTimeout(()=>a.abort(),n.timeoutMs??5e3),j=(async()=>{let A=async()=>{let fe=await w(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:a.signal});if(!fe.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",fe.status);return ge.parse(await fe.json())},D=await Promise.race([A(),v]),k=Date.parse(D.validatedAt),L=Date.parse(D.validUntil);if(D.scope.projectId!==f.projectId||D.scope.environment!==f.environment||D.scope.environmentId!==n.environmentId||D.release!==n.appManifestRelease||L<=Date.now()||k>Date.now()+5e3||L-k>6e4||L<=k)throw new G("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(t||e!==u)return;let ne=h===void 0;h=D,B=L,z=performance.now()+Math.min(L-Date.now(),6e4),$.recheck(),(ne||E)&&x()})();s=j;try{await j}finally{clearTimeout(K),a.signal.removeEventListener("abort",p),s===j&&(s=void 0)}}async function on(){if(!(!i||t)){try{await Me()}catch{t||c("configuration_unavailable")}x()}}let Fe=Ie({document,run:on,delay:()=>i&&!t?15e3:void 0});return{async start(){i||t||(i=!0,P=location.origin+location.pathname,O=Ee(oe),S=n.session.subscribeIdentity(()=>{R++,$.cancel(),F.release(g?.deliveryTicket),E=!0,g=void 0,J.clear(),T=-1,ee.clear(),o&&pe(o,o.owner,!1),re(),x()}),l=new MutationObserver(x),l.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",ce,!0),document.addEventListener("visibilitychange",x),addEventListener("pagehide",ae),await Fe.refresh())},refresh:Me,async retry(){g&&!t&&g.epoch===R&&await N(g)},destroy(){t=!0,u++,$.cancel(),F.release(g?.deliveryTicket),Fe.destroy(),_?.abort(),l?.disconnect(),O?.(),S?.(),document.removeEventListener("click",ce,!0),document.removeEventListener("visibilitychange",x),removeEventListener("pagehide",ae),ae(),re(),b.dispose(),h=void 0}}}function An(n){let d=we(n.baseUrl),f=n.fetch??globalThis.fetch.bind(globalThis),b,w=0,h=0,t=!1,i=!1,u=!1,y=0,P=0,R=-1,B=!1,z="",m,s,E,_,O=new Set,S,l,o,T=(r,C)=>Z(n.onStatus,r,C),g=Pe(),M=()=>{try{return n.deliveryIdentity?.()}catch{return}},J=()=>JSON.stringify(M()),c=Se({storage:n.deliveryStorage,binding:()=>{let r=M();return r?.id?[d,n.scope.projectId,n.scope.environment,n.environmentId,r.type,r.id]:void 0},unavailable:()=>T("delivery_unavailable")}),$=()=>Date.now()<w&&performance.now()<h;function F(r){try{return $()&&r.target.release===n.appManifestRelease&&de(r.target.render,document,location.pathname,()=>{})}catch{return T("incompatible",r.id),!1}}function ee(){let r=o;o=void 0,r?.host.destroy(),r?.slot.remove()}async function te(r){if(r.dispatching)return;r.dispatching=!0;let C=y;try{let H=await r.process.open({operation:"entry_start",funnelId:r.entry.funnelId,versionId:r.entry.versionId,entryId:r.entry.id,release:n.appManifestRelease,locale:n.locale??"en"});c.accept(r.deliveryTicket,H.run.id);let{showFunnelRun:W}=await import("./funnel-runtime-host-4KBMPKBE.js");if(t||C!==y||l!==r)return;let V=document.createElement("div");n.container.append(V),R=P;let N=await W(V,{...n.host,client:H.controller,appManifestRelease:n.appManifestRelease,onDismiss(X){o?.process===r.process&&(o=void 0,V.remove()),Z(n.host?.onDismiss,X)}});if(t||C!==y||l!==r){N.destroy(),V.remove();return}o={entry:r.entry,process:r.process,host:N,slot:V,deliveryTicket:r.deliveryTicket},l=void 0,T("run_presented",r.entry.id)}catch(H){if(t||C!==y||l!==r)return;H instanceof G&&"result"in H?(c.release(r.deliveryTicket),l=void 0,r.process.destroy(),T("suppressed",r.entry.id),Q()):T("entry_unavailable",r.entry.id)}finally{r.dispatching=!1}}function Y(r){if(t||i||l||o||S||g.active||R===P||!F(r))return;let C=`${P}:${r.id}`;if(O.has(C))return;O.add(C);let H=P,W=y,V=J();g.start(r.delivery?.delaySeconds??0,()=>!t&&y===W&&P===H&&J()===V&&document.visibilityState!=="hidden"&&F(r)&&b?.entries.some(N=>N.id===r.id&&N.funnelId===r.funnelId&&N.versionId===r.versionId&&N.event===r.event&&JSON.stringify(N.target)===JSON.stringify(r.target)&&JSON.stringify(N.delivery)===JSON.stringify(r.delivery))===!0,()=>{let N=c.claim(r.id,r.funnelId,r.delivery?.maxPerSession,crypto.randomUUID());if(N===!1){T("frequency",r.id),Q();return}try{let X={entry:r,process:n.createProcess(r),visit:P,deliveryTicket:N};l=X,te(X)}catch(X){c.release(N),T("entry_unavailable",r.id),Z(n.host?.onError,X)}},()=>{O.delete(C)})}function Q(){B||t||(B=!0,queueMicrotask(()=>{if(B=!1,g.recheck(),!(t||i||document.visibilityState==="hidden"||!$()||l||o||S||g.active||R===P)){for(let r of b?.entries??[])if(r.event==="screen_enter"&&!O.has(`${P}:${r.id}`)&&F(r)){Y(r);break}}}))}function re(r){if(!r.isTrusted||r.defaultPrevented||!(r.target instanceof Element)||l||o||S||R===P)return;let C=be(document,()=>{});for(let H of b?.entries??[]){let W=H.target.button;if(H.event!=="button_click"||!W||!F(H))continue;let V=r.target.closest(W.selector);if(!(!V||V.tagName.toLowerCase()!==W.tag||C(W.selector)!==1||V.matches(":disabled")||V.closest('[inert],[hidden],[aria-hidden="true"]'))){Y(H);break}}}let le=()=>{let r=location.origin+location.pathname;r!==z&&(z=r,P++,g.cancel(),O.clear(),Q())};async function me(){if(t)return;if(s)return s;let r=y,C=new AbortController;m=C;let H,W=new Promise((ye,ue)=>{H=ue}),V=()=>H(new G("TIMEOUT","Funnel entry read cancelled"));C.signal.addEventListener("abort",V,{once:!0});let N=setTimeout(()=>C.abort(),n.timeoutMs??5e3),X=(async()=>{let ye=encodeURIComponent(JSON.stringify(["funnel-process/1"])),ue=async()=>{let ce=await f(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}&executionContracts=${ye}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:C.signal});if(!ce.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",ce.status);return ge.parse(await ce.json())},x=await Promise.race([ue(),W]),se=Date.parse(x.validatedAt),oe=Date.parse(x.validUntil);if(x.scope.projectId!==n.scope.projectId||x.scope.environment!==n.scope.environment||x.scope.environmentId!==n.environmentId||x.release!==n.appManifestRelease||oe<=Date.now()||se>Date.now()+5e3||oe<=se||oe-se>6e4)throw new G("INVALID_RESPONSE","Entry scope or deadline changed");t||r!==y||(b=x,w=oe,h=performance.now()+Math.min(oe-Date.now(),6e4),g.recheck(),Q())})();s=X;try{await X}finally{clearTimeout(N),C.signal.removeEventListener("abort",V),s===X&&(s=void 0)}}async function pe(){if(!(!u||t))try{await me()}catch{t||T("configuration_unavailable")}}let ae=Ie({document,run:pe,delay:()=>u&&!t?15e3:void 0});return{async start(){u||t||(u=!0,z=location.origin+location.pathname,E=Ee(le),_=new MutationObserver(Q),_.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",re,!0),document.addEventListener("visibilitychange",Q),await ae.refresh())},refresh:me,async retry(){l&&!t&&await te(l)},async syncIdentity(){g.cancel();let r=o??l??S;if(!r){i=!1,Q();return}try{let C=await r.process.syncIdentity();return i=!1,S===r&&(l={...r,visit:P},S=void 0,await te(l)),C}catch(C){throw r.process.view||(S={...r,visit:P},l=void 0,ee()),C}},async detach(){i=!0,y++,g.cancel(),m?.abort();let r=o??l??S;r&&(S={...r,visit:P}),l=void 0,ee(),r&&await r.process.detach()},destroy(){t=!0,y++,g.cancel(),ae.destroy(),m?.abort(),_?.disconnect(),E?.(),document.removeEventListener("click",re,!0),document.removeEventListener("visibilitychange",Q);let r=o??l??S;c.release(r?.deliveryTicket),l=void 0,S=void 0,ee(),r?.process.destroy(),b=void 0}}}async function Dn(n,d){return(await import("./paywall-22EYVJAK.js")).showPaywall(n,d)}async function dt(){return await Promise.all([import("./paywall-22EYVJAK.js"),import("./screen-renderer-HJOKBOZH.js")]),Dn}async function lt(...n){return n[1]=ze(n[1]),(await import("./paywall-session-TJ3X7NZA.js")).createPaywallSession(...n)}async function ut(...n){let d=n[1].signal?.aborted?void 0:We(n[1].client);try{return import("./screen-renderer-HJOKBOZH.js").catch(()=>{}),import("./paywall-22EYVJAK.js").catch(()=>{}),await(await rn(()=>import("./funnel-runtime-host-4KBMPKBE.js"),n[1].prepared)).showFunnelRun(...n)}finally{d?.()}}async function rn(n,d){try{return await n()}catch(f){throw d&&d.state!=="adopted"&&await import("./funnel-paywall-prerender-GVHYSFWI.js").then(b=>b.preparedInternals(d)?.release(),()=>{}),f}}async function ft(...n){return import("./screen-renderer-HJOKBOZH.js").catch(()=>{}),import("./paywall-22EYVJAK.js").catch(()=>{}),(await rn(()=>import("./funnel-host-purchase-526HVMXY.js"),n[1].prepared)).showFunnelPurchase(...n)}async function mt(...n){return import("./funnel-host-purchase-526HVMXY.js").catch(()=>{}),import("./screen-renderer-HJOKBOZH.js").catch(()=>{}),(await import("./funnel-paywall-prerender-GVHYSFWI.js")).prerenderFunnelPurchase(...n)}async function pt(){await Promise.all([import("./funnel-paywall-prerender-GVHYSFWI.js"),import("./funnel-host-purchase-526HVMXY.js"),import("./paywall-22EYVJAK.js"),import("./screen-renderer-HJOKBOZH.js"),import("./paywall-content-XH344BMX.js"),import("./check-response-XGOTG3KL.js"),import("./operation-contracts-3JEVPMO2.js")])}async function yt(...n){return(await import("./funnel-route-prediction-Q4HMRAVQ.js")).predictFunnelStart(...n)}async function ht(...n){return(await import("./funnel-route-prediction-Q4HMRAVQ.js")).predictedPaywallLoadingDocument(...n)}async function gt(...n){return(await import("./funnel-host-recovery-paywall-GRX7CLGF.js")).mountFunnelRecoveryPaywall(...n)}async function vt(...n){return(await import("./content-6MJOU3SX.js")).mountContent(...n)}async function It(...n){return(await import("./content-6MJOU3SX.js")).prepareContent(...n)}export{G as LongplayError,I as MerchantBridgeError,yn as createBrowserFunnelCommandStorage,En as createBrowserFunnelPurchaseStorage,vn as createConfigurationSync,mn as createFeatureClient,wn as createFunnelClient,Rn as createFunnelPageExperiments,Sn as createFunnelProcess,bn as createFunnelPurchaseClient,Ae as createFunnelRunController,Cn as createIamFunnelEntries,An as createIamFunnelProcessEntries,Pn as createLocalFunnelClient,pn as createLongplay,Tn as createMerchantBridge,lt as createPaywallSession,In as evaluateFunnelNode,sn as formatCouponDiscount,an as formatCouponMoney,cn as formatCouponTerms,hn as getPaywallRecovery,un as isPaywallOperationComplete,fn as isPaywallOperationPending,ln as isPaywallUpdateOperation,dn as isPaywallUpdateQuote,vt as mountContent,gt as mountFunnelRecoveryPaywall,yt as predictFunnelStart,ht as predictedPaywallLoadingDocument,pt as preloadFunnelPurchase,dt as preloadPaywall,It as prepareContent,gn as preparePaywallFallback,mt as prerenderFunnelPurchase,ft as showFunnelPurchase,ut as showFunnelRun,Dn as showPaywall};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{P as r,Q as m,j as e}from"./chunk-67WFVDTV.js";import"./chunk-KCUE2VFJ.js";import"./chunk-BOT6ZDLK.js";import"./chunk-LFR2LWYC.js";import"./chunk-W22ESUYY.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{m as merchantBridgeCommerceSchema,r as merchantBridgeOperationSchema,e as merchantOperationLookupSchema};
|