@tinkerlandai/indiana-sdk 0.9.5 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +30 -41
  3. package/README.zh-CN.md +24 -22
  4. package/dist/{ai-usage-CUTIHAU0.d.ts → ai-usage-Cn7dhvFw.d.ts} +3 -3
  5. package/dist/{api-BXu6TAoB.d.ts → api-DC44FaTV.d.ts} +6354 -904
  6. package/dist/chunk-ACF2FBUB.js +1 -0
  7. package/dist/{chunk-XSOEA4A5.js → chunk-CWHJKWOD.js} +1 -1
  8. package/dist/chunk-EARSGITJ.js +1 -0
  9. package/dist/chunk-FYGXGMRB.js +1 -0
  10. package/dist/chunk-GHJ65ILJ.js +1 -0
  11. package/dist/chunk-JPV7F5XI.js +1 -0
  12. package/dist/{chunk-AOGPGUWE.js → chunk-LCLCG2I2.js} +1 -1
  13. package/dist/chunk-Q64VNSPV.js +6 -0
  14. package/dist/chunk-SBPTOOYB.js +1 -0
  15. package/dist/{chunk-MKV726FV.js → chunk-V3RAOCVQ.js} +1 -1
  16. package/dist/chunk-VZVUZWP2.js +1 -0
  17. package/dist/{chunk-M7JWCLYX.js → chunk-X6BCUINI.js} +1 -1
  18. package/dist/{chunk-4C3HUZ3B.js → chunk-XO42OH3M.js} +1 -1
  19. package/dist/{configuration-sync-DuJl4SbM.d.ts → configuration-sync-CywDxRkX.d.ts} +12 -12
  20. package/dist/{content-PQJYLAGQ.js → content-QM75T7JO.js} +1 -1
  21. package/dist/{funnel-local-client-BhHdi5_V.d.ts → funnel-local-client-DXamAj1-.d.ts} +18475 -2597
  22. package/dist/funnel-node-evaluation-P5B4fPfJ.d.ts +2054 -0
  23. package/dist/{funnel-resource-client-BoIhL_my.d.ts → funnel-resource-client-md62M8Rv.d.ts} +5977 -1126
  24. package/dist/funnel-runtime-host-BJZUVJAI.js +1 -0
  25. package/dist/index.d.ts +9924 -1958
  26. package/dist/index.js +1 -1
  27. package/dist/native-shell.js +1 -1
  28. package/dist/openrouter.d.ts +3 -3
  29. package/dist/openrouter.js +1 -1
  30. package/dist/page.d.ts +4 -4
  31. package/dist/page.js +1 -1
  32. package/dist/paywall-527RPFAX.js +1 -0
  33. package/dist/popup.d.ts +1 -1
  34. package/dist/popup.js +1 -1
  35. package/dist/react-native.d.ts +19930 -7179
  36. package/dist/react-native.js +1 -1
  37. package/dist/{screen-renderer-VAMWY7ID.js → screen-renderer-ZSAR7LPS.js} +1 -1
  38. package/dist/server.d.ts +2737 -573
  39. package/dist/server.js +1 -1
  40. package/dist/visual.d.ts +1 -1
  41. package/dist/visual.js +1 -1
  42. package/package.json +2 -2
  43. package/dist/chunk-5ZWSFE2C.js +0 -1
  44. package/dist/chunk-6ZZUNGNE.js +0 -1
  45. package/dist/chunk-HEGNIATD.js +0 -1
  46. package/dist/chunk-LMO3FXRT.js +0 -1
  47. package/dist/chunk-QYECMZJJ.js +0 -1
  48. package/dist/chunk-UBMPFTGE.js +0 -1
  49. package/dist/chunk-UWFYBRM2.js +0 -6
  50. package/dist/chunk-XRXI3DMZ.js +0 -1
  51. package/dist/funnel-node-evaluation-DuPmqIo1.d.ts +0 -998
  52. package/dist/funnel-runtime-host-3YUGXD3Y.js +0 -1
  53. package/dist/paywall-CSAGKPCP.js +0 -1
  54. package/dist/{screen-CvfI_L41.d.ts → screen-D81zCpfi.d.ts} +2 -2
@@ -0,0 +1 @@
1
+ import{a as pe}from"./chunk-7DXL3LHT.js";import{z as yt}from"zod";var bt=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],C=yt.enum(bt);function ht(e){let t=C.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function me(e,t,i="en",r={}){let o=C.parse(t.toUpperCase());return new Intl.NumberFormat(i,{style:"currency",currency:o,...r}).format(e/10**ht(o))}import{z as x}from"zod";import{z as _}from"zod";var oe=_.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),I=_.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),xt=_.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),de=I.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ae=_.string().min(1).max(64),$=_.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Ne=_.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),T=_.record(Ae,_.union([_.string().max(120),_.number().finite(),_.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,i])=>[t,String(i)]))),Re=_.record(Ae,_.union([_.string().max(120),_.number().finite(),_.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),F=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[i,r=""]=e.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");let o=BigInt(i)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-o:o},ke=_.array(_.object({upTo:de.nullable(),cost:I}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,i)=>{let r=e[i-1]?.upTo;return t.upTo!==null&&(i===0||r!=null&&F(t.upTo)>F(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),St=_.object({key:Ne,match:Re,priority:_.number().int().default(0),cost:I.optional(),tiers:ke.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),_t=_.object({key:Ne,match:Re,factor:de.optional(),add:xt.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),It=_.object({units:de.default("1"),cost:I,tiers:ke.optional(),dimensions:_.array(St).max(12).optional(),multipliers:_.array(_t).max(4).optional()}).strict().superRefine((e,t)=>{let i=e.dimensions??[],r=e.multipliers??[];(new Set(i.map(s=>s.key)).size!==i.length||new Set(r.map(s=>s.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[s,u]of i.entries())for(let d of i.slice(s+1))Object.keys(u.match).length===Object.keys(d.match).length&&u.priority===d.priority&&!Object.keys(u.match).some(g=>d.match[g]!==void 0&&d.match[g]!==u.match[g])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let o=[e.cost,...(e.tiers??[]).map(s=>s.cost),...i.flatMap(s=>[...s.cost===void 0?[]:[s.cost],...(s.tiers??[]).map(u=>u.cost)])],c=F(e.units);for(let s of o)for(let u=0;u<1<<r.length;u++){let d=r.filter((O,A)=>u&1<<A);if(d.some((O,A)=>d.slice(A+1).some(M=>Object.keys(O.match).some(Q=>M.match[Q]!==void 0&&M.match[Q]!==O.match[Q]))))continue;let g=F(s),l=BigInt("1"),b=BigInt("0");for(let[O,A]of r.entries())u&1<<O&&(g*=F(A.factor??"1"),l*=BigInt("1000000"),b+=F(A.add??"0"));let S=(g+b*l)*BigInt("1000000"),k=l*c;(S<BigInt("0")||S%k!==BigInt("0")||S/k>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),Tr=It.safeExtend({featureKey:$});import{z as Et}from"zod";import{z as Z}from"zod";var Oe=Z.enum(["stripe","apple","google","merchant"]),Dr=Z.enum(["membership","credit_pack","lifetime"]),zr=Z.enum(["active","grace","suspended","inactive","revoked"]),vr=Z.strictObject({currency:Z.string().regex(/^[A-Z]{3}$/),micros:Z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var Ce=Et.object({provider:Oe,currency:C}).strict();var Pe=x.strictObject({internal_feature_id:x.uuid(),quantity:I.refine(e=>/[1-9]/.test(e)),properties:T,entityId:x.uuid().optional()}),Gr=x.strictObject({requirement:Pe,commerce:Ce.optional(),paywallId:x.uuid().optional()}),At=x.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Nt=x.strictObject({productId:x.string().min(1),productVersionId:x.string().min(1),name:x.string().min(1).max(120),action:x.enum(["purchase","upgrade","addon","topup"]),membershipId:x.string().min(1).nullable(),currency:C,amountMinor:x.string().regex(/^(0|[1-9]\d{0,8})$/),interval:x.enum(["free","week","month","year","one_time"]),intervalCount:x.number().int().min(1).max(156)}),we=x.strictObject({internal_feature_id:x.string().min(1),name:x.string().min(1).max(120),kind:x.enum(["access","metered","credit"]),quantity:I,allowed:x.boolean(),reason:At.nullable(),preview:x.strictObject({scenario:x.enum(["feature_flag","usage_limit"]),candidates:x.array(Nt).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(i=>i.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(i=>i.action==="upgrade"!=(i.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),Hr=x.strictObject({paywallId:x.uuid(),requirement:Pe});import{z as m}from"zod";import{z as K}from"zod";import{z as H}from"zod";import{z as G}from"zod";var Te=G.number().int().min(0).max(1e8),fe=G.strictObject({kind:G.enum(["graduated","volume"]),tiers:G.array(G.strictObject({upTo:G.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Te,flatAmountMinor:Te.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,i)=>{let r=e.tiers[i-1]?.upTo;return t.upTo!==null&&(i===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function ge(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let i=e.pricing?fe.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,o=0;if(!i)r=BigInt(e.amountMinor)*BigInt(t);else for(let c of i.tiers){let s=c.upTo??1e4;if(i.kind==="volume"){if(t<=s){r=BigInt(t)*BigInt(c.unitAmountMinor)+BigInt(c.flatAmountMinor??0);break}}else t>o&&(r+=BigInt(Math.min(t,s)-o)*BigInt(c.unitAmountMinor));o=s}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function je(e){return ge({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var Rt=I.refine(e=>/[1-9]/.test(e)),De=H.strictObject({units:Rt,prices:H.array(H.strictObject({currency:C,amountMinor:H.number().int().min(0).max(1e8),pricing:fe.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:H.number().int().min(0).max(1e4),maximumQuantity:H.number().int().min(0).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let i of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])i<=e.maximumQuantity&&ge({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},i);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function Le(e){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(e))throw new Error("Invalid quantity");let[t,i=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(i.padEnd(6,"0"))}function ze(e,t,i){if(!Number.isSafeInteger(i)||i<0||i>1e4)throw new Error("Invalid purchased quantity");let r=Le(e)+Le(t)*BigInt(i);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let o=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(o?"."+o:"")}var ye=K.strictObject({internalFeatureId:K.uuid(),name:K.string().min(1).max(120),includedAmount:K.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:K.enum(["hour","day","week","month","year","lifetime"]),resetCount:K.number().int().min(1).max(100),terms:De});var kt=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],ae=m.object({plan:m.string().min(1).max(200).optional(),coupon:m.uuid().optional(),promotionCode:m.uuid().optional(),picker:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ve=m.object({text:m.string().optional(),label:m.string().optional(),alt:m.string().optional(),html:m.string().max(32768).optional(),price:m.object({current:m.string(),original:m.string().nullable(),period:m.string()}).optional(),code:m.string().optional(),countdownAt:m.iso.datetime().optional(),planId:m.string().min(1).max(200).optional(),planVersionId:m.string().min(1).max(200).optional(),currency:C.optional(),couponId:m.uuid().optional(),offerId:m.uuid().optional(),unavailable:m.boolean().optional(),unavailableReason:m.string().optional(),missing:m.array(m.string()).optional()}).strict(),pn=m.object({paywall:we.optional(),nodes:m.record(m.string(),m.object({base:ve,picker:m.string().optional(),byPlan:m.record(m.string(),ve).optional()}).strict()),plans:m.record(m.string(),m.object({id:m.string().min(1).max(200),versionId:m.string().min(1).max(200),available:m.boolean(),name:m.string(),price:m.string(),period:m.string(),currency:C.optional(),amountMinor:m.number().int().nonnegative().optional(),interval:m.enum(["free","week","month","year","one_time"]).optional(),intervalCount:m.number().int().positive().optional(),prepaid:m.array(ye).max(100).optional()}).strict()),pickers:m.record(m.string(),m.object({options:m.array(m.string().min(1).max(200)).max(20),selected:m.string().min(1).max(200).nullable()}).strict()),quantities:m.record(m.string(),m.strictObject({minimum:m.number().int().nonnegative(),maximum:m.number().int().nonnegative(),step:m.number().int().positive(),value:m.number().int().nonnegative(),label:m.string(),available:m.boolean()})).optional(),diagnostics:m.array(m.object({nodeId:m.string(),message:m.string()}).strict())}).strict();function Ue(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function be(e){let t=Ue(e).filter(r=>!kt.includes(r)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(r)),i=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(i.includes("{{")||i.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function mn(e,t,i={}){let r=e?.nodes[t];if(!r)return;let o=r.picker?i[r.picker]??e?.pickers[r.picker]?.selected:void 0;return typeof o=="string"?r.byPlan?.[o]??r.base:r.base}import{z as f}from"zod";var Ot=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Ve=f.enum(Ot),Me=f.object({source:Ve,layout:f.enum(["full","compact"]),resourceKey:$.optional(),pageSize:f.number().int().min(1).max(50),showSources:f.boolean(),allowPurchase:f.boolean(),outputs:f.object({billing_adjustment:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),N=f.string().max(2e3),$e=f.object({id:f.string().max(100),label:N,detail:f.array(N).max(12),value:N.optional(),status:N.optional(),facts:f.array(f.object({label:N,value:N}).strict()).max(1e3),purchaseId:f.uuid().optional(),invoiceUrl:f.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:f.array(f.strictObject({action:f.literal("invoice_open"),label:N})).max(1).optional(),membershipActions:f.array(f.object({value:f.string().max(100),label:N}).strict()).max(3).optional()}).strict(),Ct=f.object({key:$,name:N,spendable:N,reserved:N,available:N,expiry:N.nullable(),sources:f.array($e).max(50),sourceCount:f.number().int().nonnegative(),sourcePage:f.number().int().positive(),hasNextSources:f.boolean(),hasPreviousSources:f.boolean()}).strict(),Pt=f.object({source:Ve,status:f.enum(["idle","loading","ready","error"]),stale:f.boolean(),preview:f.boolean(),errorCode:f.string().max(80).optional(),errorMessage:N.optional(),resources:f.array(Ct).max(500),rows:f.array($e).max(50),hasNext:f.boolean(),hasPrevious:f.boolean(),page:f.number().int().positive(),filter:f.string().max(40),updatedAt:f.iso.datetime().optional(),buyingId:f.uuid().optional(),membershipBusy:f.boolean().optional(),billingBusy:f.boolean().optional(),membershipReview:f.object({title:N,note:N,facts:f.array(f.object({label:N,value:N}).strict()).max(100)}).strict().optional(),membershipResult:N.optional()}).strict(),yn=f.object({nodes:f.record(f.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Pt)}).strict(),bn=f.object({nodeId:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:f.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:f.string().max(100).optional()}).strict();import{z as n}from"zod";function Be(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function qe(e){let t={};function i(r){if(Be(r)){let o=t[r.interaction.pickerId]??={ids:[],defaultId:null};for(let s of r.children){let u=s.type==="stack"?s.bind?.plan:void 0;u&&!o.ids.includes(u)&&o.ids.push(u)}let c=r.children[r.interaction.defaultIndex];!o.defaultId&&c?.type==="stack"&&(o.defaultId=c.bind?.plan??null)}r.type==="stack"&&r.children.forEach(i)}return e.pages.forEach(r=>i(r.root)),t}function Qe(e,t,i){let r={};function o(d){if(d.hidden)return;if(d.type==="plan_picker"){let b=i.pickers[d.id];r[d.id]={ids:b?.options??[],defaults:b?.selected?[b.selected]:[],remembered:[]};return}if(d.type!=="stack")return;let g=d.children.filter(b=>!b.hidden),l=d.interaction;if(Be(d)){let b=r[d.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},S=i.pickers[d.interaction.pickerId]?.options??[];for(let O of g){let A=O.type==="stack"?O.bind?.plan:void 0;A&&S.includes(A)&&!b.ids.includes(A)&&b.ids.push(A),A&&O.id===t[d.id]&&b.remembered.push(A)}let k=d.children[d.interaction.defaultIndex];k?.type==="stack"&&!k.hidden&&k.bind?.plan&&b.defaults.push(k.bind.plan)}if(l?.type==="tabs"){let b=g.find(S=>S.id===t[d.id])??d.children[l.defaultIndex];b&&o(b)}else if(l?.type==="toggle"){let b=typeof t[d.id]=="boolean"?t[d.id]:l.defaultEnabled,S=d.children[b?0:1];S&&o(S)}else g.forEach(o)}let c=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,s=e.pages.find(d=>d.id===c);s&&o(s.root);let u={};for(let[d,g]of Object.entries(r)){let l=t[d],b=g.remembered[0]??(g.ids.includes(i.pickers[d]?.selected??"")?i.pickers[d]?.selected:g.defaults[0]);u[d]=typeof l=="string"?g.ids.includes(l)?l:"":b&&g.ids.includes(b)?b:""}for(let d of Object.keys(qe(e)))u[d]??="";return u}import{z as V}from"zod";var Fe=V.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ze=V.strictObject({tiers:V.array(V.strictObject({id:Fe,name:V.string().trim().min(1).max(80)})).min(1).max(8),assignments:V.array(V.strictObject({productVersionId:V.string().min(1).max(200),tierId:Fe,period:V.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let i=e.tiers.map(r=>r.id);(new Set(i).size!==i.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!i.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Ge(e,t){return e.assignments.length===t.length&&e.assignments.every(i=>t.includes(i.productVersionId))}function En(e){let t=be(e).map(i=>`\u672A\u77E5\u53D8\u91CF\uFF1A${i}`);for(let i=0;i<e.length;i++){if(e[i]!=="<"||!/[A-Za-z!/?{]/.test(e[i+1]??""))continue;let r=i;if(e.startsWith("<!--",i)){let o=e.indexOf("-->",i+4);i=o<0?e.length:o+2}else{let o="";for(i++;i<e.length;i++){let c=e[i];if(o)c===o&&(o="");else if(c==='"'||c==="'")o=c;else if(c===">")break}}/\{\{|\}\}/.test(e.slice(r,i+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}import{z as wt}from"zod";var Ke=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,W=wt.string().max(16).regex(Ke,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");function he(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:i,script:r,region:o}=new Intl.Locale(t),c=[i,r,o].filter(Boolean).join("-");return Ke.test(c)?c:null}catch{return null}}var Tt=new Set(["TW","HK","MO"]);function He(e){let[t,i,r]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let o=i?.length===4?i:void 0,c=i?.length===4?r:i;return o?`zh-${o}`:c&&Tt.has(c)?"zh-Hant":"zh-Hans"}function We(e,t,i){let r=t.map(o=>({code:W.parse(o),normalized:o}));for(let o of e){let c=he(o);if(!c)continue;let s=r.find(l=>l.normalized===c);if(s)return s.code;let u=He(c),d=r.filter(l=>He(l.normalized)===u),g=d.find(l=>!l.normalized.includes("-")||l.normalized===u)??d[0];if(g)return g.code}return i}var jt=4,L={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},X=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),h=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Lt=n.enum(["none","xs","sm","md","lg","xl"]),Dt=n.enum(["none","sm","md","lg","full"]),xe=n.string().regex(/^#[0-9a-fA-F]{6}$/),Xe=n.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),Se=n.union([Xe,n.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),n.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),n.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Ye=n.object({primary:xe,background:xe,text:xe,radius:Dt,font:n.enum(["system","serif","rounded","mono"])}).strict(),ee=n.union([n.enum(["primary","text","muted","background","surface"]),n.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),y=(e,t)=>n.number().int().min(e).max(t),Je=n.union([n.enum(["fit","fill"]),y(1,1200)]),zt=n.object({top:y(0,200),right:y(0,200),bottom:y(0,200),left:y(0,200)}).strict(),vt=n.object({top:y(-100,200),right:y(-100,200),bottom:y(-100,200),left:y(-100,200)}).strict(),et=n.object({x:y(0,100),y:y(0,100)}).strict(),Ut=n.discriminatedUnion("type",[n.object({type:n.literal("color"),color:ee}).strict(),n.object({type:n.literal("linear"),angle:y(0,360),stops:n.array(n.object({color:ee,at:y(0,100)}).strict()).min(2).max(4)}).strict(),n.object({type:n.literal("image"),src:Se,fit:n.enum(["cover","contain"]),position:et.optional()}).strict()]),Vt=n.discriminatedUnion("type",[n.object({type:n.literal("rect"),radius:n.union([y(0,200),n.object({topLeft:y(0,200),topRight:y(0,200),bottomRight:y(0,200),bottomLeft:y(0,200)}).strict()])}).strict(),n.object({type:n.literal("pill")}).strict()]),Mt=n.object({width:y(0,12),color:ee,style:n.enum(["solid","dashed"])}).strict(),$t=n.object({x:y(-40,40),y:y(-40,40),blur:y(0,80),spread:y(-20,40),color:ee}).strict(),Bt=n.object({font:n.enum(["system","serif","rounded","mono"]),size:y(8,96),weight:n.number().int().min(100).max(900).multipleOf(100),lineHeight:n.number().min(.8).max(3),letterSpacing:n.number().min(-5).max(20),color:ee,align:n.enum(["start","center","end"]),italic:n.boolean(),decoration:n.enum(["none","underline","line-through"]),transform:n.enum(["none","uppercase"])}).strict().partial(),B=n.object({width:Je,height:Je,padding:zt,margin:vt,gap:y(0,120),grow:n.union([n.boolean(),n.number().min(0).max(12)]),background:Ut,opacity:n.number().min(0).max(1),clipContent:n.boolean(),shape:Vt,border:Mt,shadow:$t,text:Bt}).strict().partial(),P={id:X,name:n.string().trim().min(1).max(60).optional(),hidden:n.boolean().optional(),style:B.optional(),fallback:h.optional()},qt=n.object({...P,type:n.literal("text"),productField:n.enum(["name","price","trial","period"]).optional(),feature:n.object({id:n.uuid(),field:n.enum(["name","allowance"])}).strict().optional(),text:h,variant:n.enum(["title","heading","body","caption"])}).strict(),Qt=n.object({...P,type:n.literal("image"),src:Se,localizedSrc:n.record(W,Se).optional(),alt:h,aspect:n.enum(["auto","1:1","4:3","16:9","3:1"]),fit:n.enum(["cover","contain"]),position:et.optional()}).strict(),Ft=n.object({...P,type:n.literal("button"),label:h,variant:n.enum(["primary","secondary","link"]),action:h,purpose:n.enum(["purchase","navigation","close"]).optional(),bind:ae.optional()}).strict(),Zt=n.object({...P,type:n.literal("divider")}).strict(),Gt=n.object({...P,type:n.literal("customer_data"),title:h,data:Me}).strict(),Ht=n.object({...P,type:n.literal("spacer"),size:Lt}).strict(),Kt=n.object({...P,type:n.literal("custom_html"),html:n.record(W,n.string().max(L.customHtml)),css:n.string().max(L.customCss)}).strict(),Wt=n.object({...P,type:n.literal("price"),fallback:h,parts:n.object({current:B.optional(),original:B.optional(),period:B.optional()}).strict().optional()}).strict(),Yt=n.object({...P,type:n.literal("coupon_code"),label:h,fallback:h}).strict(),Jt=n.object({...P,type:n.literal("countdown"),source:n.enum(["offer.ends_at","offer.expires_at","fixed"]),at:n.iso.datetime().optional(),granularity:n.enum(["day","hour","minute","second"]),expired:h,fallback:h}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Xt=n.object({...P,type:n.literal("plan_picker"),label:h,fallback:h,planIds:n.array(n.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:n.string().min(1).max(200).optional(),grouping:Ze.safeExtend({monthLabel:h,yearLabel:h,unavailableLabel:h}).optional(),states:n.object({selected:B.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Ge(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),er=n.object({...P,type:n.literal("quantity_picker"),bind:ae.optional(),label:h,fallback:h,internalFeatureId:n.uuid(),minimumQuantity:y(0,1e4),maximumQuantity:y(0,1e4),defaultQuantity:y(0,1e4),step:y(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),tr=n.discriminatedUnion("type",[n.object({type:n.literal("input"),label:h,keyboard:n.enum(["text","email","tel","url"]),maxLength:y(1,500)}).strict(),n.object({type:n.literal("multiselect"),label:h,min:y(0,50),max:y(1,50)}).strict(),n.object({type:n.literal("select"),label:h,defaultIndex:y(0,49),purpose:n.enum(["option","product","tier"]).optional(),pickerId:X.optional(),selectedStyle:B.optional()}).strict(),n.object({type:n.literal("tabs"),label:h,defaultIndex:y(0,49),purpose:n.literal("tier").optional()}).strict(),n.object({type:n.literal("toggle"),label:h,defaultEnabled:n.boolean()}).strict(),n.object({type:n.literal("carousel"),label:h}).strict()]),j={...P,type:n.literal("stack"),direction:n.enum(["vertical","horizontal","overlay"]),align:n.enum(["start","center","end","stretch"]),justify:n.enum(["start","center","end","between"]),productSlot:n.object({index:y(0,19),period:n.enum(["month","year"]).optional(),requireBinding:n.boolean().optional()}).strict().optional(),interaction:tr.optional(),states:n.object({selected:B.optional()}).strict().optional(),purpose:n.literal("benefits").optional(),purchaseAction:h.optional(),buttonVariant:n.enum(["primary","secondary","link"]).optional(),bind:ae.optional()},tt=n.lazy(()=>n.object({...P,type:j.type,direction:j.direction,align:j.align,justify:j.justify,children:n.array(rr).max(L.children),productSlot:j.productSlot,interaction:j.interaction,states:j.states,purpose:j.purpose,purchaseAction:j.purchaseAction,buttonVariant:j.buttonVariant,bind:j.bind}).strict()),rr=n.lazy(()=>n.union([tt,qt,Qt,Ft,Zt,Ht,Kt,Wt,Yt,Jt,Xt,er,Gt])),nr=n.union([n.string().max(500),n.number().finite(),n.boolean(),n.null()]),J={id:h,event:h,properties:n.record(h,nr).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},ir=n.discriminatedUnion("type",[n.object({...J,type:n.literal("navigate"),close:n.literal(!1),pageId:X}).strict(),n.object({...J,type:n.literal("event"),close:n.boolean()}).strict(),n.object({...J,type:n.literal("close"),close:n.literal(!0)}).strict(),n.object({...J,type:n.literal("open_url"),close:n.boolean(),url:Xe}).strict(),n.object({...J,type:n.literal("claim_offer"),close:n.boolean(),couponId:n.uuid()}).strict()]),or=n.object({defaultLocale:W,locales:n.record(W,n.record(h,n.string().max(L.stringLength)))}).strict(),ar=n.enum(["popup","paywall","onboarding","page","banner"]);var sr=n.discriminatedUnion("type",[n.object({type:n.literal("modal"),size:n.enum(["sm","md","lg"])}).strict(),n.object({type:n.literal("sheet"),size:n.enum(["sm","md","lg"])}).strict(),n.object({type:n.literal("fullscreen")}).strict(),n.object({type:n.literal("inline")}).strict()]),jn={sm:360,md:420,lg:560},cr=n.object({kind:n.literal("screen"),schemaVersion:n.literal(jt),name:n.string().trim().min(1).max(80),surface:ar,initialPageId:X.optional(),presentation:sr,theme:Ye,pages:n.array(n.object({id:X,name:n.string().trim().min(1).max(60),root:tt,theme:Ye.optional(),editorPosition:n.object({x:n.number().finite().min(-1e5).max(1e5),y:n.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(L.pages),strings:or,actions:n.array(ir).max(L.actions)}).strict();function v(e,t){for(let i of e.pages)_e(i.root,t)}var Ln=cr.superRefine((e,t)=>{let i=L;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(l=>l.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let l of e.actions)l.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(b=>b.id===l.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>i.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${i.pages} \u4E2A`}),e.actions.length>i.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${i.actions} \u4E2A`});let r=l=>t.addIssue({code:"custom",message:l}),o=Object.keys(e.strings.locales);o.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),o.length>L.locales&&r(`\u6700\u591A ${L.locales} \u79CD\u8BED\u8A00`);let c=new Set;for(let l of e.actions)c.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),c.add(l.id);let s=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),s.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id);let u=new Set,d=0,g=!1;v(e,(l,b)=>{if(d++,b>L.depth&&(g=!0),u.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),u.add(l.id),l.type==="button"&&!c.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let S of Object.keys(l.html))o.includes(S)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${S}`);if(l.type==="image")for(let S of Object.keys(l.localizedSrc??{}))o.includes(S)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${S}`)}),d>i.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${i.nodes} \u4E2A`),g&&r(`\u5C42\u7EA7\u6700\u591A ${L.depth} \u5C42`)});function _e(e,t,i=1,r=null){if(t(e,i,r)!==!1&&e.type==="stack")for(let o of e.children)_e(o,t,i+1,e)}function rt(e){let t=[],i=new Set;return v(e,r=>{let o=(c,s,u)=>{i.has(c)||(i.add(c),t.push({key:c,nodeId:r.id,nodeType:r.type,field:s,required:u}))};r.type==="stack"&&r.interaction&&o(r.interaction.label,"label",!0),r.fallback&&o(r.fallback,"text",!0),r.type==="text"&&o(r.text,"text",!0),r.type==="customer_data"&&o(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&o(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(o(r.grouping.monthLabel,"label",!0),o(r.grouping.yearLabel,"label",!0),o(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&o(r.expired,"text",!0),r.type==="button"&&o(r.label,"label",!0),r.type==="image"&&(o(`image:${r.id}`,"src",!1),o(r.alt,"alt",!1)),r.type==="custom_html"&&o(`html:${r.id}`,"html",!0)}),t}function ur(e,t,i){if(t.field==="html"){let r;return v(e,o=>{o.id===t.nodeId&&o.type==="custom_html"&&(r=o.html[i])}),r}if(t.field==="src"){let r=Ie(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[i]??(i===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[i]?.[t.key]}function lr(e){let t=rt(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,o)=>r===e.strings.defaultLocale?-1:o===e.strings.defaultLocale?1:0).map(r=>{let o=t.filter(c=>!ur(e,c,r)?.trim()).map(c=>c.key);return{locale:r,total:t.length,filled:t.length-o.length,missing:o,complete:o.length===0}})}function pr(e){return lr(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Dn(e,t){return We(t,pr(e),e.strings.defaultLocale)}function zn(e,t){let i=e.strings.locales[t]??{},r=e.strings.locales[e.strings.defaultLocale]??{},o={};for(let s of rt(e)){if(s.field==="html"||s.field==="src")continue;let u=i[s.key]?.trim()?i[s.key]:r[s.key];u!==void 0&&(o[s.key]=u)}let c=s=>{if(s.type==="stack")return{...s,children:s.children.map(c)};if(s.type==="custom_html"){let u=s.html[t]?.trim()?s.html[t]:s.html[e.strings.defaultLocale];return{...s,html:u===void 0?{}:{[t]:u}}}if(s.type==="image"){let{localizedSrc:u,...d}=s;return{...d,src:u?.[t]??u?.[e.strings.defaultLocale]??s.src}}return s};return{...e,pages:e.pages.map(s=>({...s,root:c(s.root)})),strings:{defaultLocale:t,locales:{[t]:o}}}}function mr(e,t){let i=null;return _e(e,r=>{if(i)return!1;r.id===t&&(i=r)}),i}function Ie(e,t){for(let i of e.pages){let r=mr(i.root,t);if(r)return r}return null}function vn(e){let t=he(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function Un(e,t,i){let r={};if(!t||typeof t!="object"||Array.isArray(t))return r;let o=t;if(v(e,c=>{if(c.type==="quantity_picker"){let u=o[c.id];typeof u=="number"&&Number.isSafeInteger(u)&&u>=c.minimumQuantity&&u<=c.maximumQuantity&&(u-c.minimumQuantity)%c.step===0&&(r[c.id]=u);return}if(c.type==="plan_picker"){let u=o[c.id];typeof u=="string"&&(r[c.id]=i?.pickers[c.id]?.options.includes(u)?u:"");return}if(c.type!=="stack"||!c.interaction)return;let s=Object.hasOwn(o,c.id)?o[c.id]:void 0;["select","tabs"].includes(c.interaction.type)&&typeof s=="string"&&c.children.some(u=>u.id===s)&&(r[c.id]=s),c.interaction.type==="toggle"&&typeof s=="boolean"&&(r[c.id]=s)}),e.surface==="paywall"&&typeof o.__page=="string"&&e.pages.some(c=>c.id===o.__page)&&(r.__page=o.__page),i){let c={...r};for(let[s,u]of Object.entries(o))(typeof u=="string"||typeof u=="boolean")&&(c[s]=u);Object.assign(r,Qe(e,c,i))}return r}import{z as E}from"zod";import{z as a}from"zod";import{z as p}from"zod";var q=I.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),te=p.string().min(1).max(120),se=p.enum(["cap","overflow"]),w=(e,t)=>{let[i,r=""]=e.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");return BigInt(i)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},re=e=>{try{return e()}catch{return!1}},Bn=p.discriminatedUnion("operation",[p.object({operation:p.literal("quote"),overageBehavior:se.optional(),internal_feature_id:p.uuid(),entityId:p.uuid().optional(),quantity:q,properties:T}).strict(),p.object({operation:p.literal("consume"),overageBehavior:se.optional(),occurredAt:p.iso.datetime({offset:!0}).optional(),internal_feature_id:p.uuid(),entityId:p.uuid().optional(),quantity:I,properties:T,idempotencyKey:te}).strict(),p.object({operation:p.literal("reserve"),occurredAt:p.iso.datetime({offset:!0}).optional(),internal_feature_id:p.uuid(),entityId:p.uuid().optional(),quantity:q,properties:T,idempotencyKey:te,expiresInSeconds:p.number().int().min(1).max(86400)}).strict(),p.object({operation:p.literal("confirm"),operationId:p.uuid(),quantity:q,properties:T.optional(),idempotencyKey:te}).strict(),p.object({operation:p.literal("refund"),operationId:p.uuid(),quantity:q,idempotencyKey:te}).strict(),p.object({operation:p.literal("release"),operationId:p.uuid(),idempotencyKey:te}).strict()]),dr=p.object({internal_credit_feature_id:p.uuid().nullable(),internal_metered_feature_id:p.uuid(),dimension:p.string().min(1).max(64),counterKey:p.string().min(1).max(240),cycleStart:p.iso.datetime({offset:!0}),unitCost:I,units:q,amount:oe,tier:p.number().int().min(1).max(12).nullable()}).strict(),ne=p.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function nt(e,t){let i=e.reduce((r,o)=>r+w(o.units,12),0n)-w(t,12);return e.some(r=>r.funding==="balance")?i>=-100n&&i<=100n:i===0n}var it=p.discriminatedUnion("funding",[p.strictObject({funding:p.literal("balance"),sourceId:p.uuid(),rolloverId:p.uuid().nullable(),units:ne.refine(e=>/[1-9]/.test(e)),amount:oe}),p.strictObject({funding:p.literal("unbilled"),units:ne.refine(e=>/[1-9]/.test(e))}),p.object({funding:p.literal("prepaid"),sourceId:p.uuid(),units:q,amount:oe,pricing:p.array(dr).min(1).max(12)}).strict().refine(e=>re(()=>e.pricing.reduce((t,i)=>t+w(i.units,6),0n)===w(e.units,6)&&e.pricing.reduce((t,i)=>t+w(i.amount,12),0n)===w(e.amount,12)&&e.pricing.every(t=>w(t.unitCost,6)*w(t.units,6)===w(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),p.object({funding:p.literal("postpaid"),invoiceLineId:p.uuid().nullable(),units:q,authorizationId:p.uuid()}).strict()]),ce=p.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),qn=p.object({allowed:p.boolean(),internal_feature_id:p.uuid(),quantity:I,requestedQuantity:I.optional(),overageBehavior:se.optional(),reason:ce.nullable(),allocations:p.array(it).max(500)}).strict().refine(e=>re(()=>e.allowed?e.reason===null&&nt(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>re(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&w(e.requestedQuantity,6)>=w(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Qn=p.object({id:p.uuid(),internal_feature_id:p.uuid(),kind:p.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:p.uuid().nullable(),quantity:I,requestedQuantity:I.optional(),overageBehavior:se.optional(),accepted:p.boolean(),reason:p.enum([...ce.options,"expired"]).nullable(),createdAt:p.iso.datetime({offset:!0}),reservationStatus:p.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:p.iso.datetime({offset:!0}).nullable(),allocations:p.array(it).max(500)}).strict().refine(e=>re(()=>e.accepted?e.reason===null&&nt(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>re(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&w(e.requestedQuantity,6)>=w(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as D}from"zod";var fr=D.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),gr=D.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ot=D.strictObject({internal_feature_id:D.uuid(),entityId:D.uuid().nullable()}),Hn=ot.extend({quantity:I,expectedRevision:D.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:D.string().min(1).max(120),properties:T.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),at=ot.extend({operationId:D.uuid().nullable(),usage:I,capacity:fr.nullable(),remaining:gr.nullable(),withinLimit:D.boolean(),revision:D.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:D.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let i=r=>{let o=r.startsWith("-"),[c,s=""]=(o?r.slice(1):r).split(".");if(c===void 0||c==="")throw new Error("Invalid decimal value");return(o?-1n:1n)*(BigInt(c)*10n**12n+BigInt(s.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||i(e.remaining)!==i(e.capacity)-i(e.usage)||e.withinLimit!==i(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var U=a.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),z=a.iso.datetime({offset:!0}),yr=a.enum(["access","metered","credit"]),ie={internal_feature_id:a.uuid(),key:$,name:a.string().min(1).max(120),kind:yr},ti=a.object({customerId:a.uuid(),snapshotAt:z,memberships:a.array(a.object({id:a.uuid(),productId:a.string().min(1).max(255),productVersionId:a.uuid(),billingProductVersionId:a.uuid(),version:a.number().int().positive(),key:a.string().min(1).max(64),name:a.string().min(1).max(120),groupId:a.string().max(255).nullable(),membershipType:a.enum(["main","addon"]),status:a.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:a.boolean(),accessEnabled:a.boolean(),renewalChange:a.object({productVersionId:a.uuid(),name:a.string().min(1).max(120),version:a.number().int().positive(),effectiveAt:z,benefitsAppliedAt:z.nullable(),timing:a.enum(["immediate","renewal"]),changeKind:a.enum(["plan","seats","quantity"]),feature:a.strictObject({internal_feature_id:a.uuid(),name:a.string().min(1).max(80),fromQuantity:a.number().int().min(0).max(1e4),toQuantity:a.number().int().min(0).max(1e4)}).optional(),seat:a.object({key:a.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:a.number().int().min(0).max(1e4),toQuantity:a.number().int().min(0).max(1e4)}).strict().nullable(),status:a.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:a.object({phase:a.enum(["paid","trial"]),startsAt:z,endsAt:z.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:a.boolean(),balances:a.array(a.object({...ie,usageType:a.enum(["consumable","non_consumable"]).nullable(),accessible:a.boolean(),unlimited:a.boolean(),available:U,held:U,debt:U,nextExpiresAt:z.nullable(),usage:at.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:a.boolean()}).strict(),st=a.enum(["source","usage","transaction","invoice","debt","settlement"]),ue=a.object({at:z,id:a.uuid(),type:st}).strict(),ri=a.object({type:st.nullable(),resourceKey:$.optional(),kind:a.enum(["purchase","refund"]).optional(),topup:a.boolean().optional(),from:a.iso.date().nullable(),to:a.iso.date().nullable(),after:ue.nullable(),limit:a.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Y={id:a.uuid(),occurredAt:z},br=a.discriminatedUnion("type",[a.strictObject({...Y,type:a.literal("invoice"),status:a.string().min(1).max(80),paid:U,refunded:U,currency:C,externalId:a.string().nullable()}),a.object({...Y,...ie,type:a.literal("source"),reason:a.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:U,unlimited:a.boolean(),status:a.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:z,expiresAt:z.nullable(),orderId:a.uuid().nullable(),parentSourceId:a.uuid().nullable()}).strict(),a.object({...Y,type:a.literal("usage"),internal_feature_id:a.uuid(),name:a.string().min(1).max(120),kind:a.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:a.uuid().nullable(),quantity:I,accepted:a.boolean(),reason:a.enum([...ce.options,"expired"]).nullable(),properties:T,reservationStatus:a.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:z.nullable(),charges:a.array(a.discriminatedUnion("funding",[a.strictObject({funding:a.literal("balance"),sourceId:a.uuid(),rolloverId:a.uuid().nullable(),units:ne,amount:U}),a.strictObject({funding:a.literal("unbilled"),units:ne}),a.object({...ie,funding:a.literal("prepaid"),amount:U}).strict(),a.object({funding:a.literal("postpaid"),invoiceId:a.uuid(),invoiceLineId:a.uuid(),authorizationId:a.uuid(),units:I,currency:C}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),a.object({...Y,type:a.literal("transaction"),purpose:a.enum(["product","invoice"]),productVersionId:a.uuid().nullable(),productName:a.string().min(1).max(120).nullable(),productVersion:a.number().int().positive().nullable(),invoiceId:a.uuid().nullable(),orderId:a.uuid(),originalId:a.uuid().nullable(),kind:a.enum(["purchase","refund"]),amountMinor:a.number().int().nonnegative().max(2e8).nullable(),currency:C.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),a.object({...Y,...ie,type:a.literal("debt"),sourceId:a.uuid(),transactionId:a.uuid(),amount:U}).strict(),a.object({...Y,...ie,type:a.literal("settlement"),sourceId:a.uuid(),debtId:a.uuid(),kind:a.enum(["payment","usage_refund","payment_return"]),amount:U}).strict()]),ni=a.object({customerId:a.uuid(),rows:a.array(br).max(50),nextCursor:ue.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");var ci=E.discriminatedUnion("kind",[E.object({kind:E.literal("ledger"),cursor:ue}).strict(),E.object({kind:E.literal("billing"),cursor:E.uuid()}).strict()]),hr=E.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),xr=E.record(E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),E.union([E.string().max(500),E.boolean(),E.array(E.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),Sr=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Ee(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(i=>Ee(i,t+1)):Object.entries(e).some(([i,r])=>["__proto__","constructor","prototype"].includes(i)||Sr.test(i)||Ee(r,t+1)))}var _r=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ui=E.record(hr,pe).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Ee(e)&&!_r.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var ct=E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ir=E.array(E.object({variable:ct,componentId:ct,required:E.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),li=E.object({bindings:Ir,answers:xr,values:E.record(E.string(),pe).optional()}).strict();function ut(e,t,i=1){if(e==="free")return"";if(e==="one_time")return t.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let r=t.split("-")[0]??"en",o={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},c={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},s=e==="week"?`/${c[r]??c.en}`:(o[r]??o.en)[e==="month"?0:1];return i===1?s:`/${i} ${s.slice(1)}${r==="en"?"s":""}`}function hi(e,t){let i=[],r={};v(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker")return;let c=o.bind?.plan?[o.bind.plan]:[];o.bind?.picker&&v(e,s=>{if(s.type==="plan_picker"&&s.id===o.bind?.picker&&c.push(...s.planIds??[]),s.type==="stack"&&s.interaction?.type==="select"&&s.interaction.pickerId===o.bind?.picker)for(let u of s.children)u.type==="stack"&&u.bind?.plan&&c.push(u.bind.plan)}),c.length||i.push(`Quantity control ${o.id} needs a Product binding`);for(let s of new Set(c)){let u=t[s]?.prepaid?.find(g=>g.internalFeatureId===o.internalFeatureId)?.terms,d=r[s]??=new Set;(!u||d.has(o.internalFeatureId)||o.minimumQuantity<u.minimumQuantity||o.maximumQuantity>u.maximumQuantity)&&i.push(`Quantity control ${o.id} must match its Product's prepaid Feature and bounds`),d.add(o.internalFeatureId)}});for(let[o,c]of Object.entries(t))for(let s of c.prepaid??[])r[o]?.has(s.internalFeatureId)||i.push(`Product ${o} needs a quantity control for ${s.internalFeatureId}`);return i}function xi(e,t,i,r){let o=r.plans[t];if(!o?.available)throw new Error("Selected Product is unavailable");let c={};if(v(e,s=>{if(s.hidden)return!1;if(s.type!=="quantity_picker"||s.hidden||(s.bind?.plan??(s.bind?.picker?i[s.bind.picker]:void 0))!==t)return;let d=o.prepaid?.find(l=>l.internalFeatureId===s.internalFeatureId)?.terms,g=i[s.id];if(!d||typeof g!="number"||!Number.isSafeInteger(g)||g<Math.max(d.minimumQuantity,s.minimumQuantity)||g>Math.min(d.maximumQuantity,s.maximumQuantity)||(g-s.minimumQuantity)%s.step!==0||c[s.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");c[s.internalFeatureId]=g}),(o.prepaid??[]).some(s=>c[s.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return c}function Er(e,t,i){let r=e.terms.prices.find(o=>o.currency===t);if(!r||i<e.terms.minimumQuantity||i>e.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:je({quantity:i,unitAmountMinor:r.amountMinor,...r.pricing?{pricing:r.pricing}:{}}),allowance:ze(e.includedAmount,e.terms.units,i)}}function Si(e,t,i,r){let o=!1;if(v(e,u=>{u.type==="quantity_picker"&&(o=!0)}),!o)return t;let c=structuredClone(t);c.quantities={};let s=new Map;v(e,u=>{if(u.hidden)return!1;if(u.type!=="quantity_picker")return;let d=u.bind?.plan??(u.bind?.picker?i[u.bind.picker]??c.pickers[u.bind.picker]?.selected:void 0),g=typeof d=="string"?c.plans[d]:void 0,l=g?.prepaid?.find(gt=>gt.internalFeatureId===u.internalFeatureId),b=Math.max(u.minimumQuantity,l?.terms.minimumQuantity??0),S=Math.min(u.maximumQuantity,l?.terms.maximumQuantity??0),k=i[u.id]??u.defaultQuantity,O=typeof k=="number"&&Number.isSafeInteger(k)?k:u.defaultQuantity,A=!!l&&!!g?.available&&O>=b&&O<=S&&(O-u.minimumQuantity)%u.step===0,M=c.quantities[u.id]={minimum:b,maximum:Math.max(b,S),step:u.step,value:O,label:"",available:A};if(!A||!l||!g?.currency||g.amountMinor===void 0)return;let Q=Er(l,g.currency,O);M.label=`${new Intl.NumberFormat(r).format(Number(Q.allowance))} ${l.name}${["week","month","year"].includes(l.reset)?ut(l.reset,r,l.resetCount):l.reset==="lifetime"?"":` / ${l.resetCount} ${l.reset}`}`,s.set(String(d),(s.get(String(d))??g.amountMinor)+Q.amountMinor)});for(let[u,d]of s){let g=c.plans[u];if(!g?.currency)continue;let l=me(d,g.currency,r);g.price=l;for(let[b,S]of Object.entries(c.nodes)){let k=Ie(e,b),O=A=>{if(A.price&&(A.price={...A.price,current:l,original:null}),k?.type==="text"){let M=e.strings.locales[r]?.[k.text]??e.strings.locales[e.strings.defaultLocale]?.[k.text];M?.includes("{{plan.price")&&(A.text=M.replace(/\{\{\s*plan.price\s*\}\}/g,l).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,me(Math.round(d/((g.interval==="year"?12:1)*(g.intervalCount??1))),g.currency,r)))}};S.byPlan?.[u]&&O(S.byPlan[u]),(S.base.planVersionId===u||k&&"bind"in k&&k.bind?.plan===u)&&O(S.base)}}return c}import{z as R}from"zod";var le=R.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),Ai=R.enum([...le.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),Ni=R.enum([...le.options,"stale_revision"]),Ar=R.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),Nr=R.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),pt={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var lt={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function Rr(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(lt,e)){let r=lt[e];return{retryable:r==="retry_same_request",recovery:r}}let i=le.safeParse(e);return i.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:pt[i.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Ri(e,t){let i=le.safeParse(e);if(i.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):pt[i.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&(r[e]?.includes(t)??!1)}function kr(e,t=Date.now()){if(e===null)return;let i=e.trim();if(/^\d+$/.test(i)){let o=Number(i);return Number.isSafeInteger(o)?o:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(i))return;let r=Date.parse(i);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var mt=R.object({retryable:R.boolean(),recovery:Ar,reason:Nr.optional(),retryAfterSeconds:R.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),Or=R.object({requestId:R.uuid().optional(),error:R.object({code:R.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:R.string(),...mt.partial().shape})}),ki=R.object({error:Or.shape.error.extend({requestId:R.uuid().optional()})}),Oi=R.object({error:R.string(),code:R.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:R.uuid(),...mt.shape});function dt(e,t,i={}){let r=Rr(e,t),o=i.reason==="RESULT_UNKNOWN"?"recover_operation":i.recovery??r.recovery,c=r.retryable&&i.retryable!==!1&&o!=="recover_operation",s=c?kr(i.retryAfter??null):void 0;return{...r,retryable:c,recovery:o,...s===void 0?{}:{retryAfterSeconds:s},...i.reason?{reason:i.reason}:{}}}var ft=class extends Error{constructor(i,r,o,c,s){super(r);this.code=i;this.status=o;this.requestId=c;this.name="IndianaError",this.reason=s?.reason;let u=dt(i,o??0,{...s,retryAfter:s?.retryAfterSeconds===void 0?void 0:String(s.retryAfterSeconds)});this.retryable=u.retryable,this.recovery=u.recovery,this.retryAfterSeconds=u.retryAfterSeconds}code;status;requestId;retryable;recovery;retryAfterSeconds;reason};export{le as a,Ar as b,Nr as c,Ri as d,Or as e,dt as f,C as g,ht as h,me as i,oe as j,I as k,xt as l,T as m,fe as n,je as o,De as p,ze as q,W as r,he as s,Bn as t,dr as u,ne as v,qn as w,Qn as x,ot as y,Hn as z,at as A,U as B,ti as C,ri as D,ni as E,ye as F,Dr as G,Ce as H,Pe as I,Gr as J,Nt as K,we as L,ve as M,pn as N,Ue as O,mn as P,qe as Q,Ze as R,Ge as S,yn as T,bn as U,En as V,L as W,h as X,jn as Y,v as Z,Ln as _,_e as $,rt as aa,lr as ba,Dn as ca,zn as da,Ie as ea,vn as fa,Un as ga,ci as ha,xr as ia,ui as ja,Ir as ka,li as la,ut as ma,hi as na,xi as oa,Si as pa,ft as qa};
@@ -1,4 +1,4 @@
1
- import{a as j,b as N,c as $,d as Y}from"./chunk-4C3HUZ3B.js";import{a as D}from"./chunk-DSPLGTQI.js";import{a as O}from"./chunk-LMO3FXRT.js";import{b as U,e as _,g as C}from"./chunk-3PZ4Y6UD.js";var te=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function re(e,t){let n=e,r=o=>Number.isInteger(o)&&o>=0;return!!n&&typeof n=="object"&&r(n.inserted)&&r(n.duplicates)&&r(n.skipped)&&Array.isArray(n.rejected)&&n.inserted+n.duplicates+n.skipped+n.rejected.length===t}function V(e){let t=[],n,r=(a,i)=>e.log?.(`${e.label} ${a}`,i);function o(a){n===void 0&&t.length&&(n=setTimeout(()=>{u()},a))}async function s(a){let i;try{i=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:a}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(p){return r("not sent",{error:p}),!1}if(i.status===408||i.status===429||i.status>=500)return r("not sent",{status:i.status}),!1;if(!i.ok)return r("rejected",{status:i.status,events:a.length}),!0;let f;try{f=await i.json()}catch{f=void 0}return re(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:i.status}),!1)}function u(){clearTimeout(n),n=void 0;let a=[];for(;t.length&&a.length<20&&(!a.length||te([...a,t[0]].map(i=>i.event))<=65536);)a.push(t.shift());return a.length?s(a.map(i=>i.event)).then(i=>{if(i)return o(1e3);let f=a.filter(p=>++p.attempts<5);f.length<a.length&&r("dropped after retries",{events:a.length-f.length}),t.unshift(...f),o(5e3)}):Promise.resolve()}return{push(a){t.push({event:a,attempts:0}),t.length>=20?u():o(1e3)},flush:u}}async function q(e,t,n,r={}){let o=r.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(o);let u=e.body.getReader(),a=[],i=0,f=!1,p=()=>{},g=new Promise((v,h)=>{p=()=>h(Error(o)),n.addEventListener("abort",p,{once:!0}),n.aborted&&p()});try{for(;;){let m=await Promise.race([u.read(),g]);if(m.done){f=!0;break}if(i+=m.value.byteLength,i>t)throw Error(o);a.push(m.value)}let v=new Uint8Array(i),h=0;for(let m of a)v.set(m,h),h+=m.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(v))}finally{n.removeEventListener("abort",p),f||u.cancel().catch(()=>{}),u.releaseLock()}}async function B(e,t){let n=e?.body;if(!n)return;let r=n.getReader(),o=0,s=!1,u,a=new Promise((p,g)=>{u=setTimeout(()=>g(Error("Exposure response timeout")),2e3)}),i=()=>{},f=new Promise((p,g)=>{i=()=>g(t?.reason),t?.addEventListener("abort",i,{once:!0}),t?.aborted&&i()});try{for(;;){let p=await Promise.race([r.read(),a,f]);if(p.done){s=!0;return}if(o+=p.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(u),t?.removeEventListener("abort",i),s||r.cancel().catch(()=>{}),r.releaseLock()}}var fe=2*1024*1024,J=256*1024;async function G(e,t,n,r){let o=()=>{},s=new Promise((u,a)=>{o=()=>a(r.reason),r.addEventListener("abort",o,{once:!0}),r.aborted&&o()});try{let u=e(t,{...n,signal:r});return u.then(a=>{r.aborted&&a.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{r.removeEventListener("abort",o)}}async function pe(e,t,n,r=!1){if(new TextEncoder().encode(n).byteLength>65536)throw Error("Exposure request budget");let o=new URL(t);o.searchParams.set("sdkVersion",O.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let a=await G(e,o.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:n,credentials:"omit",keepalive:r,redirect:"error"},s.signal);await B(a,s.signal)}finally{clearTimeout(u)}}function M(e){let t,n=!1;return{async read(r,o){if(n)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,a=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let i=await G(e,r,{cache:"no-cache",credentials:"omit",redirect:"error"},u),f=await q(i,o,u);return u.throwIfAborted(),f}finally{clearTimeout(a),t===s&&(t=void 0)}},destroy(){n=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}/*!
1
+ import{a as j,b as N,c as $,d as Y}from"./chunk-XO42OH3M.js";import{a as D}from"./chunk-DSPLGTQI.js";import{a as O}from"./chunk-GHJ65ILJ.js";import{b as U,e as _,g as C}from"./chunk-3PZ4Y6UD.js";var te=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function re(e,t){let n=e,r=o=>Number.isInteger(o)&&o>=0;return!!n&&typeof n=="object"&&r(n.inserted)&&r(n.duplicates)&&r(n.skipped)&&Array.isArray(n.rejected)&&n.inserted+n.duplicates+n.skipped+n.rejected.length===t}function V(e){let t=[],n,r=(a,i)=>e.log?.(`${e.label} ${a}`,i);function o(a){n===void 0&&t.length&&(n=setTimeout(()=>{u()},a))}async function s(a){let i;try{i=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:a}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(p){return r("not sent",{error:p}),!1}if(i.status===408||i.status===429||i.status>=500)return r("not sent",{status:i.status}),!1;if(!i.ok)return r("rejected",{status:i.status,events:a.length}),!0;let f;try{f=await i.json()}catch{f=void 0}return re(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:i.status}),!1)}function u(){clearTimeout(n),n=void 0;let a=[];for(;t.length&&a.length<20&&(!a.length||te([...a,t[0]].map(i=>i.event))<=65536);)a.push(t.shift());return a.length?s(a.map(i=>i.event)).then(i=>{if(i)return o(1e3);let f=a.filter(p=>++p.attempts<5);f.length<a.length&&r("dropped after retries",{events:a.length-f.length}),t.unshift(...f),o(5e3)}):Promise.resolve()}return{push(a){t.push({event:a,attempts:0}),t.length>=20?u():o(1e3)},flush:u}}async function q(e,t,n,r={}){let o=r.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(o);let u=e.body.getReader(),a=[],i=0,f=!1,p=()=>{},g=new Promise((v,h)=>{p=()=>h(Error(o)),n.addEventListener("abort",p,{once:!0}),n.aborted&&p()});try{for(;;){let m=await Promise.race([u.read(),g]);if(m.done){f=!0;break}if(i+=m.value.byteLength,i>t)throw Error(o);a.push(m.value)}let v=new Uint8Array(i),h=0;for(let m of a)v.set(m,h),h+=m.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(v))}finally{n.removeEventListener("abort",p),f||u.cancel().catch(()=>{}),u.releaseLock()}}async function B(e,t){let n=e?.body;if(!n)return;let r=n.getReader(),o=0,s=!1,u,a=new Promise((p,g)=>{u=setTimeout(()=>g(Error("Exposure response timeout")),2e3)}),i=()=>{},f=new Promise((p,g)=>{i=()=>g(t?.reason),t?.addEventListener("abort",i,{once:!0}),t?.aborted&&i()});try{for(;;){let p=await Promise.race([r.read(),a,f]);if(p.done){s=!0;return}if(o+=p.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(u),t?.removeEventListener("abort",i),s||r.cancel().catch(()=>{}),r.releaseLock()}}var fe=2*1024*1024,J=256*1024;async function G(e,t,n,r){let o=()=>{},s=new Promise((u,a)=>{o=()=>a(r.reason),r.addEventListener("abort",o,{once:!0}),r.aborted&&o()});try{let u=e(t,{...n,signal:r});return u.then(a=>{r.aborted&&a.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{r.removeEventListener("abort",o)}}async function pe(e,t,n,r=!1){if(new TextEncoder().encode(n).byteLength>65536)throw Error("Exposure request budget");let o=new URL(t);o.searchParams.set("sdkVersion",O.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let a=await G(e,o.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:n,credentials:"omit",keepalive:r,redirect:"error"},s.signal);await B(a,s.signal)}finally{clearTimeout(u)}}function M(e){let t,n=!1;return{async read(r,o){if(n)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,a=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let i=await G(e,r,{cache:"no-cache",credentials:"omit",redirect:"error"},u),f=await q(i,o,u);return u.throwIfAborted(),f}finally{clearTimeout(a),t===s&&(t=void 0)}},destroy(){n=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}/*!
2
2
  Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
3
  plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
4
  */function ne(e,t){let n,r;try{n=new URL(e),r=new URL(t)}catch{return t}return n.searchParams.forEach((o,s)=>{r.searchParams.has(s)||r.searchParams.set(s,o)}),r.toString()}function oe(e,t){let n=navigator.userAgent,r=new URLSearchParams(t.search),o={};for(let s of["source","medium","campaign","term","content"]){let u=r.get(`utm_${s}`);u!==null&&(o[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(n)?"edge":/Chrome/.test(n)?"chrome":/Firefox/.test(n)?"firefox":/Safari/.test(n)?"safari":"unknown",deviceType:/Mobi/.test(n)?"mobile":"desktop",...o}}function ie(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(r=>!!r&&!["namespace","status","url","groups"].some(o=>Object.hasOwn(r,o))&&(r.hashVersion===void 0||r.hashVersion===2)&&typeof r.key=="string"&&Array.isArray(r.variations)&&r.variations.length>=2&&r.variations.every(o=>!!o&&typeof o.urlRedirect=="string")&&(r.urlPatterns===void 0||Array.isArray(r.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function be(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=$(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),r=M(async(c,d)=>{let l=await n(c,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),o=e.log?(c,d)=>D(e.log,c,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=j(e.deviceIdCookie??"indiana_did"),a=N(),i=null,f={...e.attributes??{}},p="",g=!1,v=!1,h=0,m=0,w=new Map,T=V({endpoint:`${s}/events`,fetch:n,log:o,label:"Exposure"}),P=T.flush,E={trackedExperiments:new Set,log:o,onExperimentViewed:(c,d)=>{e.trackExposures===!1||i?.trackExposures===!1||T.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...a?{sessionId:a}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:c.key,variationKey:d.key})}},H=()=>{E.url=location.href,E.attributes={...oe(u,location),...f}};function Q(c){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return c.variations.some(l=>{if(!l.urlRedirect)return!1;let y=new URL(l.urlRedirect);return y.protocol!==d.protocol||y.host!==d.host})}catch{return!0}}function K(c,d){let l=e.configuration?.snapshot?.generation,y=m,z=location.href;p=c;let W=e.navigate??(x=>location.replace(x)),Z=e.navigateDelay??(e.navigate?0:100),ee=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(x=>setTimeout(x,ee))]),new Promise(x=>setTimeout(x,Z))]).then(()=>{!g&&y===m&&location.href===z&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&W(c)})}function b(){if(!(!i||g||e.configuration&&!e.configuration.fresh)){H();for(let c of i.experiments){if(Q(c)){o?.("Auto experiment blocked",{id:c.key});continue}let d;try{d=C(c,E)}catch(l){o?.("Skipping page experiment",{id:c.key,error:String(l)});continue}if(w.set(c.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=c.persistQueryString?ne(location.href,d.value.urlRedirect):d.value.urlRedirect;U(l,c.urlPatterns??[])?o?.("Skipping redirect because original URL matches redirect URL",{id:c.key}):l!==p&&K(l,P())}break}}}}let R="",F=()=>{location.href!==R&&(m++,R=location.href,p="",b())},A,S;function X(){A??=Y(F),addEventListener("pagehide",L)}let L=()=>{P()};async function k(){if(g)return!1;let c=++h,d;try{d=e.configuration?await e.configuration.pageExperiments():await r.read(s,J)}catch(y){if(g||c!==h)return!1;throw y}if(g||c!==h)return!1;let l=ie(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return i?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),i=l,E.savedGroups=_(l.savedGroups),!0}function I(){g||(S??=e.configuration?.subscribe(()=>{!g&&e.configuration?.fresh&&k().then(c=>{c&&b()}).catch(c=>o?.("Page configuration unavailable",{error:String(c)}))}),X(),R=location.href)}return{async start(){v||g||(v=!0,await k()&&(I(),b()))},async refresh(){await k()&&(m++,v&&I(),p="",b())},setAttributes(c){m++,p="",f={...c},b()},getResults(){return new Map(w)},get generation(){return i?.generation??null},destroy(){g||(g=!0,h++,r.destroy(),S?.(),A?.(),removeEventListener("pagehide",L),i=null,w.clear(),P())}}}export{fe as a,pe as b,M as c,ne as d,oe as e,ie as f,be as g};
@@ -0,0 +1 @@
1
+ async function R(e,r,i){let t=new URL(e,r.baseURI),h=r.defaultView?.location.origin,l=/^(?:\/[^/?#]+)*\/\.well-known\/indiana\/releases\/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\.json$/.exec(t.pathname)?.[1];if(!l||t.origin!==h||t.search||t.hash||t.username||t.password)throw Error("Invalid IAM release URL");let a=AbortSignal.any([i,AbortSignal.timeout(2e3)]),f=await fetch(t,{credentials:"omit",redirect:"error",cache:"force-cache",signal:a}),o=f.headers.get("content-length");if(!f.ok||!/^application\/json(?:;|$)/i.test(f.headers.get("content-type")??"")||o!==null&&(!/^\d+$/.test(o)||Number(o)>512))throw f.body?.cancel().catch(()=>{}),Error("IAM release is unavailable");let d=f.body?.getReader();if(!d)throw Error("IAM release is unavailable");let n=[],b=0,c=()=>{},w=new Promise((u,E)=>{c=()=>E(Error("IAM release timeout")),a.addEventListener("abort",c,{once:!0}),a.aborted&&c()}),p=!1;try{for(;;){let u=await Promise.race([d.read(),w]);if(u.done){p=!0;break}if(b+=u.value.length,b>512)throw Error("IAM release budget");n.push(u.value)}}finally{a.removeEventListener("abort",c),p||d.cancel().catch(()=>{}),d.releaseLock()}let m=new Uint8Array(b),M=0;for(let u of n)m.set(u,M),M+=u.length;let I=new TextDecoder("utf-8",{fatal:!0}).decode(m),s=JSON.parse(I);if(I.trim()!==JSON.stringify(s))throw Error("Noncanonical IAM release descriptor");if(!s||typeof s!="object"||Array.isArray(s)||Object.keys(s).sort().join(",")!=="format,manifestDigest,releaseId,schemaVersion"||Reflect.get(s,"format")!=="indiana-app-manifest-release"||Reflect.get(s,"schemaVersion")!==2||Reflect.get(s,"releaseId")!==l||!/^[a-f0-9]{64}$/.test(String(Reflect.get(s,"manifestDigest"))))throw Error("Invalid IAM release descriptor");return Reflect.get(s,"manifestDigest")}var A=new WeakMap;function x(e,r=document){if(!/^[a-f0-9]{64}$/.test(e))throw new Error("Invalid IAM manifest digest");let i="data-indiana-release",t=r.documentElement,h=()=>new Set((t.getAttribute(i)??"").split(/\s+/).filter(Boolean)),l=A.get(r);if(!l){let n=new Map,b=new MutationObserver(()=>{let c=h(),w=!1;for(let[p,m]of n)m.count&&!c.has(p)&&(c.add(p),w=!0);w&&t.setAttribute(i,[...c].join(" "))});b.observe(t,{attributes:!0,attributeFilter:[i]}),l={releases:n,observer:b},A.set(r,l)}let{releases:a,observer:f}=l,o=a.get(e);if(!o){let n=h();o={count:0,owned:!n.has(e)},a.set(e,o),n.add(e),t.setAttribute(i,[...n].join(" "))}o.count++;let d=!1;return{attributes:{indianaAppManifestRelease:e},destroy(){if(!d&&(d=!0,o.count--,!o.count&&(a.delete(e),a.size||(f.disconnect(),A.delete(r)),o.owned))){let n=h();n.delete(e),n.size?t.setAttribute(i,[...n].join(" ")):t.removeAttribute(i)}}}}var g=new Map,v=new Set,y=()=>{for(let e of[...v])e()},D=e=>g.has(e);function O(e){return v.add(e),()=>{v.delete(e)}}function k(e,r){if(g.has(e)&&g.get(e)!==r)throw new Error("A different Funnel owns this page experiment");return g.set(e,r),y(),()=>{g.get(e)===r&&(g.delete(e),y())}}export{R as a,x as b,D as c,O as d,k as e};
@@ -0,0 +1 @@
1
+ import{b as dn,c as mn,d as fn,e as pn}from"./chunk-SBPTOOYB.js";import{$ as Ke,Aa as rn,Ba as on,Ea as an,Fa as sn,Ia as un,M as Ge,Na as ln,O as Je,Oa as cn,P as Be,Pa as te,Q as je,Qa as Q,Y as H,Z as ze,_ as q,aa as Ee,ba as L,ca as Qe,da as Ye,ea as $e,fa as We,ga as Ze,ha as Xe,j as ie,na as ne,oa as en,qa as we,ra as nn,sa as tn}from"./chunk-Q64VNSPV.js";import{oa as He,qa as l}from"./chunk-ACF2FBUB.js";import{a as Me,e as ye}from"./chunk-G56XGVMS.js";import{b as ae}from"./chunk-GHJ65ILJ.js";import{b as ge}from"./chunk-7DXL3LHT.js";import{e as Ue,h as qe}from"./chunk-3PZ4Y6UD.js";function Un(e){let n=null,t=null,f=0,u=0,g=!1,c=new Set,r=null,o=null,a=new Set,w=()=>{for(let m of a)try{m()}catch{}},d={attributes:ge.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(m,v)=>{!c.has(m)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(m,structuredClone(v),structuredClone(d.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(m,v)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(m),structuredClone(v),structuredClone(d.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?m=>e.saveStickyBucketAssignmentDoc(structuredClone(m)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},C=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function _(m,v=new Set){return c.has(m)?!r||!r.features[m]||["unknownFeature","cyclicPrerequisite"].includes(r.features[m].source):v.has(m)?!1:(v.add(m),(n?.features[m]?.rules??[]).some(S=>[...S.parentConditions??[],...(S.tracks??[]).flatMap(R=>R.experiment.parentConditions??[])].some(R=>_(R.id,v))))}let E=m=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return r?.expiresAt&&Date.parse(r.expiresAt)<=Date.now()&&(r=null,d.features=n.features),c.has(m)?!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()?C():structuredClone(r.features[m]??C()):e.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!g||_(m)?C():structuredClone(qe(m,d))};async function F(){if(!n||!c.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(c.size)throw new Error("Remote Feature evaluation requires a server loader");return}let m=u;if(o?.revision===m)return o.loading;let v=f,S=n,R=[...c],P=(async()=>{let T=je.parse(await e.evaluateRemote({attributes:structuredClone(d.attributes),features:R}));if(!(v!==f||m!==u||S!==n)){if(e.assertUsable?.(S.generation),T.generation!==S.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(R.some(O=>!Object.hasOwn(T.features,O))||Object.keys(T.features).some(O=>!c.has(O)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=ge.parse({...d.attributes,...T.merchandiseContext}),g=!0}r=structuredClone(T),d.features={...S.features,...Object.fromEntries(Object.entries(r.features).map(([O,k])=>[O,{defaultValue:k.value}]))},w()}})();o={revision:m,loading:P};try{await P}finally{o?.loading===P&&(o=null)}}function i(){F().catch(m=>{try{e.onError?.(m)}catch{}})}async function s(){if(t)return t;let m=f,v=(async()=>{let S=await e.load(),R="remoteFeatures"in S?Je.parse(S):null,P=R??ye.parse(S);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(m!==f)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===P.generation){let{evaluatedAt:O,expiresAt:k,...G}=n,{evaluatedAt:W,expiresAt:J,...Z}=P;if(L(G)!==L(Z))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=P.evaluatedAt,n.expiresAt=P.expiresAt,w(),(!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())&&i(),structuredClone(n)}let T=new Set(R?.remoteFeatures??[]);if([...T].some(O=>Object.hasOwn(P.features,O)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in P&&!n.analyticsConfig.experimentViewsEnabled&&R?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),n=structuredClone(P),c=T,r=null,o=null,u++,d.features=n.features,d.savedGroups=Ue(n.savedGroups),d.trackedFeatureUsage={},w(),i(),structuredClone(n)})();t=v;try{return await v}finally{t===v&&(t=null)}}return{init:s,refresh:s,refreshRemote:F,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(m){return a.add(m),()=>{a.delete(m)}},setAttributes(m){let v=ge.parse(m);(d.attributes?.merchandise||d.attributes?.merchandiseId||m.merchandise||m.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=v,u++,g=!1,r=null,o=null,d.features=n?.features??{},d.trackedFeatureUsage={},w(),i()},evalFeature:E,isOn(m){return E(m).on},isOff(m){return E(m).off},getFeatureValue(m,v){let S=E(m).value;return structuredClone(S===null?v:S)},reset(){f++,u++,t=null,o=null,n=null,r=null,c.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),w()}}}function gn(e){let n,t,f=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),u=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw f();let r=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ae).href,e.runToken])),o=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return"indiana.funnel.commands.v1."+Array.from(o,a=>a.toString(16).padStart(2,"0")).join("")});u.catch(()=>{});async function g(r){try{let o=await u;return await t.request(o,{mode:"exclusive"},()=>r(o))}catch(o){throw o instanceof l?o:f()}}function c(r){let o=n.getItem(r);if(o===null)return{revision:0,entry:null};if(o.length>1048576)throw f();let a=JSON.parse(o);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw f();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>g(c),write:(r,o)=>g(a=>{if(c(a).revision!==r)return null;if(!Number.isSafeInteger(r+1))throw f();return n.setItem(a,JSON.stringify({revision:r+1,entry:o})),r+1})}}async function he(e,n){let t=nn.safeParse(n);if(!t.success)throw new l("INVALID_RESPONSE","Funnel response contract changed");let f=t.data;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Funnel scope changed");return f}async function Ae(e,n,t){if(Number(e.headers.get("content-length"))>n)throw t.error("limit");let f=e.body?.getReader();if(!f)throw t.error("missing");let u=[],g=0;try{for(;;){t.signal?.throwIfAborted();let o=await f.read();if(o.done)break;if(g+=o.value.length,g>n)throw t.error("limit");u.push(o.value)}}finally{await f.cancel().catch(()=>{})}t.signal?.throwIfAborted();let c=new Uint8Array(g),r=0;for(let o of u)c.set(o,r),r+=o.length;return c}async function yn(e,n,t){return new TextDecoder("utf-8",{fatal:!0}).decode(await Ae(e,n,t))}function Ie(e,n){let t=typeof e=="string"?new TextEncoder().encode(e):e;return t.byteLength===n.byteLength&&Qe(t)===n.sha256}async function ve(e,n){let t=Ze.parse(n),{artifact:f,environmentId:u}=t.content,g=new te(e.baseUrl??ae).origin,c=new te(f.url,g);if(c.origin!==g||c.username||c.password||c.search||c.hash||c.pathname!==`/api/v1/configuration/${u}/artifacts/${f.sha256}`)throw new l("INVALID_RESPONSE","Public Paywall locator is not trusted");let r=new AbortController,o=setTimeout(()=>r.abort(),q.initializationMs);try{let a=await(e.fetch??globalThis.fetch)(c,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:r.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>f.byteLength)throw new l("INVALID_RESPONSE","Public Paywall is unavailable");let w=await Ae(a,f.byteLength,{signal:r.signal,error:d=>new l("INVALID_RESPONSE",d==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ie(w,f))throw new l("INVALID_RESPONSE","Public Paywall digest or size changed");return Xe(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(w)))}finally{clearTimeout(o)}}var Fe=(e,n)=>new l(e,n);function rt(e){return sn(e,Fe)}async function Ne(e,n,{predict:t=!0}={}){let f=n.instruction;if(f?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==f.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let u=null,g;if(t)try{let c=await e.funnel(n.source.id,n.source.versionId);g=c.manifest.generation,u=Tn(e,n,c)}catch{u=null}return g??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:f.policyRevision,generation:g},prediction:u}}function Tn(e,n,t){let f=n.instruction;if(f?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==f.policyRevision)return null;let{analyticsConfig:u,remoteFeatures:g,...c}=t.growth,r=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:f.policyRevision,document:t.document,payload:ye.parse(c)}),o=On(r,t.document,{...n,...f}),a=o.steps.at(-1),w=o.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+o.steps.length-1}:null);return w?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:w.nodeId,visit:w.visit,terminal:!o.boundary}:null}function On(e,n,t){return un(e,n,t,Fe)}import{z as B}from"zod";var wn=H.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=B.strictObject({schemaVersion:B.literal(1),scope:Me,runId:B.uuid(),funnelId:B.uuid(),versionId:B.uuid(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:B.strictObject({receiptId:B.uuid(),operationId:B.uuid(),generation:B.number().int().nonnegative()}).optional(),closed:B.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"),M=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Re=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function In(e){let n=0,t=null,f=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),u=Promise.resolve();async function g(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:hn.parse(o.entry)}}function c(o){let a=u.then(o);return u=a.catch(()=>{}),a}async function r(o){for(let a=0;a<4;a++){let w=await g();if(w.entry&&t!==null&&f(w.entry)!==t)throw M();let d=o(w.entry,w.revision);if(Re(w.entry,d)){n=w.revision;return}let C=await e.write(w.revision,d);if(C!==null){if(!Number.isSafeInteger(C)||C<=w.revision)throw M();n=C;return}}throw M()}return{bind(o){let a=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(t!==null&&t!==a)throw M();t=a},async load(){let o=await g();return n=o.revision,t=o.entry?f(o.entry):null,o.entry},retain(o){let a=hn.parse(o),w=a.command;return!w||t!==null&&f(a)!==t?Promise.reject(M()):(t??=f(a),c(()=>r((d,C)=>{if(d&&!Re(f(d),f(a)))throw M();if(!d){if(C!==n&&w.operation!=="close")throw M();return a}if(!d.command)return{...d,command:w,...w.operation==="close"?{closed:!0}:{}};if(w.operation==="close"&&d.command.operation!=="close"){if(d.command.requestId===w.requestId||d.closeCommand&&!Re(d.closeCommand,w))throw M();return{...d,closeCommand:w,closed:!0}}if(!Re(d.command,w))throw M();return d})))},observePurchase(o,a,w){return c(()=>r((d,C)=>{if(!d&&C!==n||d&&f(d)!==f({...o,schemaVersion:1}))throw M();if(d?.purchase&&d.purchase.generation>a.generation)return d;if(d?.purchase&&d.purchase.generation===a.generation&&d.purchase.operationId!==a.operationId)throw M();return w?!d?.purchase||d.purchase.operationId!==a.operationId?d:d.command?{...d,purchase:void 0}:null:{schemaVersion:1,...o,...d,purchase:a}}))},settle(o){return c(()=>r(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===o?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===o?{...a,closeCommand:void 0}:a:null))}}}function ft(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function se(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((u,g)=>se(u,n[g]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),f=Object.entries(n);return t.length===f.length&&t.every(([u,g])=>Object.hasOwn(n,u)&&se(g,Reflect.get(n,u)))}function vn(e){let n=null,t=0,f=!1,u,g=0,c=new Set;return{get view(){return n},get generation(){return t},get disposed(){return f},get customerToken(){return u},get readSequence(){return g},nextRead(){return++g},assertCurrent(r,o="Run identity changed during the request"){if(r!==t||f)throw new l("IDENTITY_CHANGED",o)},assertRun(r){if(n&&(r.id!==n.id||r.source.type!==n.source.type||r.source.id!==n.source.id||r.source.versionId!==n.source.versionId||r.locale!==n.locale||!se(r.parameters,n.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e&&r.source.id!==e)throw new l("INVALID_RESPONSE","Run belongs to another Funnel")},publish(r,o,a,w,d){if(!(r.operation==="review"&&n&&n!==a&&o.run.revision<=n.revision)&&!(n&&o.run.revision===n.revision&&w!==void 0&&w<g)&&(r.operation==="review"&&!o.run.stopped&&["running","waiting"].includes(o.run.status)&&n&&o.run.nodeId===n.nodeId&&o.run.visit===n.visit&&o.run.revision===n.revision&&(o.run.screen=n.screen,(n.paywall?.quote?.operationId===o.review?.activeOperationId||!n.paywall?.quote&&o.review?.activeOperationId===null)&&(o.run.paywall=n.paywall)),!(n?.paywall&&o.run.paywall&&n.paywall.receiptId===o.run.paywall.receiptId&&(o.run.paywall.selectionGeneration??0)<(n.paywall.selectionGeneration??0)))){if(!n||o.run.revision>=n.revision)n=o.run;else if(!d)return;if(n)for(let C of c)try{C(structuredClone(n))}catch{}}},identify(r){if(!ie.test(r))throw new l("INVALID_TOKEN","Customer credential required");t++,u=r},subscribe(r){return c.add(r),()=>c.delete(r)},reset(){f=!0,t++,u=void 0,n=null,c.clear()}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function vt(e,n,t="A server API key is required"){if(typeof window<"u")throw new l("SERVER_ONLY",n);if(!re.test(e))throw new l("INVALID_TOKEN",t)}function Rt(e){let n=Q(e);return n.identify(e.apiKey),n}function Y(e){let{customerToken:n,...t}=e;return t}var _n=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function Rn({options:e,journal:n,state:t,call:f}){let u=null,g=null,c=!1,r={command:null,close:null},o=!1,a,w=null,d=n?n.load().then(i=>{if(t.disposed)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(w=i,!i)return;if(e.scope&&(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=i.purchase,c=i.closed===!0,!i.command)return;let s=H.parse(i.command);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");u=s,i.closeCommand&&(g=i.closeCommand,c=!0),s.operation==="close"&&(c=!0),o=!0}):Promise.resolve();d.catch(()=>{});async function C(i=u){if(n&&await d,!i)throw new l("INVALID_REQUEST","No command is pending");let s=i,m=t.generation;if(n){if(!t.view||!e.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await n.retain({schemaVersion:1,scope:e.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:Y(s)})}if(m!==t.generation||u!==s&&g!==s)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let v={...s,...t.customerToken?{customerToken:t.customerToken}:{}},S=o;o=!0;try{return await f(v,R=>{if(!R.settlement)throw new l("INVALID_RESPONSE","Exact command settlement is missing");if(R.settlement.requestId!==s.requestId)throw new l("INVALID_RESPONSE","Command settlement identity changed");if(m===t.generation&&(u===s||g===s)&&R.run.pendingRequest?.requestId!==s.requestId&&R.settlement.state==="settled"&&(!c||s.operation==="close"||R.settlement?.state==="settled"&&!["running","waiting"].includes(R.run.status))){let P=()=>m!==t.generation||u!==s&&g!==s?!1:(u===s&&(u=null),g===s&&(g=null),o=u!==null,w=null,!0);return n?n.settle(s.requestId).then(P):P()}return!1})}catch(R){throw m===t.generation&&u===s&&!S&&!_n(R)&&(n&&await n.settle(s.requestId),m===t.generation&&u===s&&(u=null,o=!1,w=null)),R}}function _(i){let s=H.parse(i);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(c&&s.operation!=="close"){if(u?.requestId===s.requestId)return F(s.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(s.operation==="close"&&u?.operation!=="close"){if(c=!0,g&&JSON.stringify(Y(g))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original Close");return g??=s,r.close?r.close:E(g,"close")}if(u){if(JSON.stringify(Y(u))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(r.command)return r.command}else u=s,o=!1;return E(u,"command")}function E(i,s){let m=C(i);r[s]=m;let v=()=>{r[s]===m&&(r[s]=null)};return m.then(v,v),m}async function F(i){let s=await f({operation:"get",settlementRequestId:i,...t.customerToken?{customerToken:t.customerToken}:{}});if(s.settlement?.requestId!==i)throw new l("INVALID_RESPONSE","Exact command settlement is missing");return s.settlement.state==="settled"&&(n&&await n.settle(i),u?.requestId===i&&(u=null,o=!1),g?.requestId===i&&(g=null)),s}return{ready:d,get pending(){return u},get closing(){return g},get closeRequested(){return c},get inFlight(){return r.command},get closeFlight(){return r.close},get purchase(){return a},assertBinding(i){if(w&&(i.run.id!==w.runId||i.run.source.id!==w.funnelId||i.run.source.versionId!==w.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(i,s,m,v){n?.bind({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId}),n&&!e.scope&&(e.scope=s.scope);let S=s.run.paywall,R=S??s.purchase,P=R?.operation,T=s.settlement&&(!S||S.purchaseRequestId===s.settlement.requestId)&&(!a||a.operationId===s.settlement.operationId)?s.settlement:void 0,O=P?.operationId??R?.quote?.operationId??T?.operationId,k=R?.receiptId??T?.receiptId,G=S?.selectionGeneration??a?.generation??0;if(n&&O&&k&&i.operation!=="review"&&(!t.view||s.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!a||G>=a.generation)){let W={receiptId:k,operationId:O,generation:G},J=P?.status==="complete"||R?.canReselect===!0;return n.observePurchase({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId},W,J).then(()=>{t.assertCurrent(m),J?a?.operationId===W.operationId&&(a=void 0):a=W})}},stop(){c=!0},submit:_,executePending:C,settle:F,reset(){u=null,g=null,r.close=null,o=!1,r.command=null}}}function Pn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new l("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Q({...e,session:void 0,...e.serverKey?{fetch:(i,s)=>{let m=new Headers(s?.headers),v=typeof s?.body=="string"?JSON.parse(s.body):null;return v!==null&&typeof v=="object"&&"customerToken"in v&&typeof v.customerToken=="string"&&v.customerToken.length>0||m.set(tn,e.serverKey),(e.fetch??globalThis.fetch)(i,{...s,headers:m})}}:{},...e.session?{fetch:async(i,s)=>{let m=await e.session.access(),v=typeof s?.body=="string"?JSON.parse(s.body):{};if(!v||typeof v!="object"||Array.isArray(v))throw new l("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(i,{...s,body:JSON.stringify({...v,customerToken:m})})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let t=vn(e.funnelId),f=e.session?.subscribeIdentity(()=>{t.reset(),n.reset()}),u=null,g=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?gn(e):void 0),c=g&&In(g),r=Rn({options:e,journal:c,state:t,call:o});async function o(i,s,m){let v=t.generation,S=()=>t.assertCurrent(v);c&&await r.ready,S();let R=t.view,P=we.parse(await he(e,await n.request("funnels",H.parse(i))));if(i.operation==="review"&&!P.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(S(),P.runToken&&P.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let T=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0;if(T&&P.settlement?.requestId!==T)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(P),t.assertRun(P.run);let O=r.observePurchase(i,P,v,m);if(O&&await O,!P.run.stopped&&["running","waiting"].includes(P.run.status)&&i.operation==="get"&&i.settlementRequestId)return P;let k=s?.(P),G=typeof k=="boolean"?k:k?await k:!1;return S(),["running","waiting"].includes(P.run.status)||r.stop(),t.publish(i,P,R,m,G),P}let a=r.submit,w=null,d=new WeakMap;function C(i){let s=d.get(i);if(s)return s;let m=E(i);return d.set(i,m),m}let _=!1;async function E(i){let s=await i;if(s.run.instruction?.type!=="evaluate_segment")return s;if(w)return w;_=!0;let m=t.generation,v=(async()=>{for(let S=0;S<32&&s.run.instruction?.type==="evaluate_segment";S++){if(r.pending||r.closeRequested)return s;let R=s.run;if(s.run.instruction?.type==="evaluate_segment"){let{advance:T}=await Ne(e.configuration,R,{predict:!1});if(m!==t.generation)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return s;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return o({operation:"get",...t.customerToken?{customerToken:t.customerToken}:{}});let O=!0;Ne(e.configuration,R).then(({prediction:k})=>{O&&m===t.generation&&!r.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(u=k)}).catch(()=>{});try{s=await a({operation:"commit_segment",requestId:en(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...T})}finally{O=!1,u=null}}}return s})();w=v;try{return await v}finally{w===v&&(w=null)}}let F={get configuration(){return _?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let i=r.closing??r.pending;return i?structuredClone(Y(i)):null},get pendingCommands(){return[r.pending,r.closing].filter(i=>i!==null).map(i=>structuredClone(Y(i)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get prediction(){let i=t.view;return u&&i&&!i.stopped&&["running","waiting"].includes(i.status)&&i.id===u.runId&&i.nodeId===u.from.nodeId&&i.visit===u.from.visit&&i.revision===u.from.revision&&!r.closeRequested?structuredClone(u):null},settle:r.settle,get webViewUrl(){return"bundled"},resolvePaywall(i){return ve(e,i)},async pageExperiments(i,s=[]){let m=t.generation;t.assertCurrent(m);let v=t.view?.id;if(!v)throw new l("INVALID_REQUEST","Read the Run before its page experiments");let S=cn.parse(await n.request("funnels",ln.parse({operation:"page_experiments",release:i,usedReceiptIds:s,...t.customerToken?{customerToken:t.customerToken}:{}})));if(t.assertCurrent(m),S.runId!==v||S.scope.projectId!==e.scope?.projectId||S.scope.environment!==e.scope?.environment)throw new l("SCOPE_MISMATCH","Page experiment Run changed");return S},review(i){return o({operation:"review",...i?{receiptId:i}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,t.nextRead())},async get(i,s){c&&await r.ready,s??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let m=t.nextRead();return C(o({operation:"get",...i?{data:i}:{},...s?{purchase:s}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,m))},resume(i=t.view?.pendingRequest?.requestId){return i?r.closeRequested?F.settle(i):r.pending?.requestId===i?C(a(r.pending)):C(a({operation:"resume",requestId:i})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(i){return C(a(i))},retry(){return r.closeFlight?r.closeFlight:r.closing?r.executePending(r.closing):r.closeRequested&&r.pending?F.settle(r.pending.requestId):r.inFlight?C(r.inFlight):r.pending?C(a(r.pending)):Promise.reject(new l("INVALID_REQUEST","No command is pending"))},identify(i){t.identify(i),u=null,n.identify(e.runToken)},subscribe:t.subscribe,reset(){f?.(),t.reset(),r.reset(),u=null,n.reset()}};return F}import{ZodError as Dn}from"zod";function Sn(e,n,t,f){try{return e.parse(n)}catch(u){throw f&&u instanceof Dn?new l(t,f):u}}async function Pe(e,n,t,f={},u){let g=typeof f=="function"?{}:f,c=Sn(n.request,t,"INVALID_REQUEST",g.request),r=await e(n.path,c,n.method,u),o=typeof f=="function"?f:f.parseResponse;return o?o(n.response,r):Sn(n.response,r,"INVALID_RESPONSE",g.response)}async function Kt(e,n){if(!ie.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");let t=Q(e);if(!e.session)t.identify(n.customerToken);else if(e.session.peek()!==n.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let f=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),u=null,g=!1,c=null,r=null,o=null,a=null,w=e.session?.subscribeIdentity(()=>{g=!0,t.dispose(),u=null,c=null,r=null,o=null});async function d(){if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");let E=ne.resolvePaywall,F=await Pe(t.request,E,{...f,selector:u?{type:"version",versionId:u.id}:f.selector}),i={paywall:await ve(e,F.paywall)};if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");if(n.paywallVersionId?i.paywall.id!==n.paywallVersionId:i.paywall.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(u&&(!dn(i.paywall,u)||i.paywall.paywallId!==u.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return u=i.paywall,structuredClone(u)}async function C(E){if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let F=E==="read"?ne.readSubscriptionOperation:ne.attach,i=await Pe(t.request,F,{operationId:c.operationId,...E==="read"?{}:{intent:E}});return mn(i.operation,{operationId:c.operationId,currency:f.commerce.currency},"The purchase operation changed"),r=pn(r,i.operation),structuredClone(r)}let _={get view(){return u?structuredClone(u):null},get quote(){return c?structuredClone(c):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return"bundled"},refresh:d,async preview(E){if(!u)throw new l("INVALID_REQUEST","Load the Paywall first");let F=u.document.buttons[E.actionId];if(F?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let i=Ge(F.product,E.selection,u.capabilities);if(!i)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let s=He(u.document.screen,i,E.selection,u.capabilities),m=ne.previewAttach.request.parse({funnelId:f.funnelId,funnelVersionId:f.funnelVersionId,requestId:E.requestId,plans:[{productVersionId:i,...Object.keys(s).length?{featureQuantities:s}:{}}],provider:f.commerce.provider,currency:f.commerce.currency,...E.offerId?{offerId:E.offerId}:{},...E.nativeOffer?{nativeOffer:E.nativeOffer}:{}}),v=JSON.stringify(m);if(o&&o!==v&&(!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===v){if(a)return a;if(c)return structuredClone(c)}o=v;let S=(async()=>{let R=ne.previewAttach,P=await Pe(t.request,R,m);return fn(P.quote,{productVersionId:i,featureQuantities:s,currency:f.commerce.currency,provider:f.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=P.quote,r=null,structuredClone(c)})();a=S;try{return await S}finally{a===S&&(a=null)}},confirm:()=>C("confirm"),cancel:()=>C("cancel"),read:()=>C("read"),destroy(){w?.(),g=!0,t.dispose(),u=null,c=null,r=null,o=null}};return await d(),_}import{z as kn}from"zod";import{z as ce}from"zod";var xn=ce.record(ce.string().regex(/^[a-f0-9]{64}$/),ce.strictObject({at:ce.number(),text:ce.string()})),bn=2*1048576,Ln=100;function Vn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Cn(e,n){let t=n===void 0?Vn():n,f=Promise.resolve();async function u(c){if(!t)return null;let r;try{return await Promise.race([Promise.resolve().then(()=>t.getItem(c)),new Promise(o=>{r=setTimeout(()=>o(null),Ln)})])}catch{return null}finally{clearTimeout(r)}}async function g(){try{let c=await u(`${e}:artifacts`);if(c&&c.length<=bn)return xn.parse(JSON.parse(c))}catch{}return{}}return{async readManifest(){return u(e)},writeManifest(c){Promise.resolve().then(()=>t?.setItem(e,c)).catch(()=>{})},async readArtifact(c){let r=(await g())[c];return r&&Date.now()>=r.at&&Date.now()-r.at<=q.retentionMs?r.text:void 0},writeArtifact(c,r){t&&(f=f.catch(()=>{}).then(async()=>{let o=await g(),a=Date.now();o[c]={at:a,text:r};let w={},d=2,C=0;for(let[_,E]of Object.entries(o).sort(([,F],[,i])=>i.at-F.at)){if(E.at>a||a-E.at>q.retentionMs)continue;let F=new TextEncoder().encode(JSON.stringify({[_]:E})).byteLength;d+F>bn||C>=128||(w[_]=E,d+=F,C++)}await t.setItem(`${e}:artifacts`,JSON.stringify(w))}).catch(()=>{}))}}}var b=(e,n)=>new l(e,n),$=()=>performance.now(),En=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function ir(e){let n=Ke.parse(e.scope),t=new te(e.origin??ae);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw b("INVALID_URL","Configuration requires a trusted HTTPS origin");let f=new Set([t.origin,...(e.assetOrigins??[]).map(y=>{let p=new te(y);if(p.protocol!=="https:"||p.username||p.password||p.search||p.hash||p.pathname!=="/")throw b("INVALID_URL","Invalid configuration asset origin");return p.origin})]),u=e.fetch??globalThis.fetch.bind(globalThis),g=`/api/v1/configuration/${n.environmentId}`,c=`indiana:configuration:1:${t.origin}:${L(n)}`,r=Cn(c,e.storage),o,a=0,w=0,d=!1,C=!1,_=0,E=0,F,i,s,m,v=0,S=new Set,R=new Set,P=new Map,T=new Map,O=0,k=!1;function G(){for(let y of S)try{y()}catch{}}function W(y){try{e.onError?.(y)}catch{}}let J=()=>!C&&!d&&!!o&&$()<a&&Date.now()<w;function Z(){if(!J())throw b("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Te(y,p){let h=new TextEncoder().encode(p).byteLength;if(!P.has(y)){for(;P.size&&(P.size>=128||O+h>q.maxCacheBytes);){let I=P.entries().next().value;O-=new TextEncoder().encode(I[1]).byteLength,P.delete(I[0])}P.set(y,p),O+=h}}function Oe(y,p,h){return yn(y,p,{signal:h,error:I=>b("INVALID_RESPONSE",I==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function _e(y){let p=new te(y,t);if(!f.has(p.origin)||p.username||p.password||p.hash||p.search)throw b("INVALID_URL","Configuration artifact origin is not trusted");return p.href}async function Se(y,p,h=!1){let I=await u(_e(y),{method:"GET",credentials:"omit",redirect:"error",cache:h?"default":"no-cache",signal:p,headers:{}});if(I.status===429){let A=I.headers.get("retry-after")??"";v=/^\d+$/.test(A)?Number(A)*1e3:Math.max(0,Date.parse(A)-Date.now())||15e3}if(!I.ok&&I.status!==304)throw b(`CONFIGURATION_HTTP_${I.status}`,"Configuration synchronization failed");return I}function Fn(y,p,h){let I=Date.parse(y.headers.get("x-indiana-config-validated-at")??""),A=Date.parse(y.headers.get("x-indiana-config-valid-until")??""),D=Date.parse(y.headers.get("date")??""),N=y.headers.get("age"),U=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![I,A,D,U].every(Number.isFinite)||A<=I||A-I>q.maxControlAgeMs||I>D+1e3)throw b("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(A-I,h.maxControlAgeSeconds*1e3,q.maxControlAgeMs)-Math.max(U,D-I,0)-($()-p);if(x<=0)throw b("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return $()+x}function be(){if(clearTimeout(s),clearTimeout(m),C||!S.size)return;J()&&(m=setTimeout(()=>{J()?be():G()},Math.max(1,a-$())),En(m));let y=E?Math.min(15e3,1e3*2**Math.min(E-1,4)):Math.min(15e3,(o?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{oe().catch(W)},Math.max(v,y*(.8+Math.random()*.2))),En(s)}async function oe(){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(F)return F;let y=_,p=new AbortController;i=p;let h=(async()=>{if(!k){k=!0;try{let pe=await r.readManifest();if(pe&&!o){let j=Ee.parse(JSON.parse(pe));L(j.scope)===L(n)&&(o=j)}}catch{}}p.signal.throwIfAborted();let N=o,U=$(),V=await Se(g,p.signal);V.status===304&&(!N||!V.headers.has("x-indiana-config-validated-at")||!V.headers.has("x-indiana-config-valid-until")||!V.headers.has("age"))&&(V=await Se(g,p.signal));let x=V.status===304?N:Ee.parse(JSON.parse(await Oe(V,q.maxManifestBytes,p.signal))),{generation:z,...K}=x,X=V.headers.get("etag");if(L(x.scope)!==L(n)||Ye(K)!==z||X!==`"${z}"`&&X!==`W/"${z}"`)throw b("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(x.revision<N.revision||x.revision===N.revision&&x.generation!==N.generation))throw b("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[pe,j]of Object.entries(N?.funnels??{})){let ee=x.funnels[pe];if(ee&&(ee.controlRevision<j.controlRevision||ee.evaluationRevision<j.evaluationRevision||ee.controlRevision===j.controlRevision&&ee.state!==j.state||ee.evaluationRevision===j.evaluationRevision&&ee.evaluationMode!==j.evaluationMode))throw b("INVALID_RESPONSE","Funnel control revision changed identity")}let ke=Fn(V,U,x.policy);if(p.signal.throwIfAborted(),y!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return o=x,a=ke,w=Date.now()+Math.max(0,ke-$()),d=!1,E=0,v=0,r.writeManifest(L(x)),G(),structuredClone(x)})(),I=setTimeout(()=>p.abort(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs),A=new Promise((N,U)=>p.signal.addEventListener("abort",()=>U(p.signal.reason),{once:!0})),D=Promise.race([h,A]).catch(N=>{throw E++,(N instanceof kn.ZodError||N instanceof SyntaxError||N instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,d=!0,G()),N}).finally(()=>{clearTimeout(I),F===D&&(F=void 0),be()});return F=D,D}async function de(y){let p=y.sha256,h=z=>Ie(z,y);_e(y.url);let I=P.get(p);if(I&&h(I))return P.delete(p),P.set(p,I),I;if(T.has(p))return T.get(p);let A=new AbortController;R.add(A);let D=_,N=(async()=>{try{let X=await r.readArtifact(p);if(X&&h(X))return Te(p,X),X}catch{}A.signal.throwIfAborted();let z=await Se(y.url,A.signal,!0),K=await Oe(z,y.byteLength,A.signal);if(!h(K))throw b("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(C||D!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return Te(p,K),r.writeArtifact(p,K),K})(),U=setTimeout(()=>A.abort(b("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),q.initializationMs),V=new Promise((z,K)=>A.signal.addEventListener("abort",()=>K(A.signal.reason),{once:!0})),x=Promise.race([N,V]).finally(()=>{clearTimeout(U),R.delete(A),T.delete(p)});return T.set(p,x),x}async function me(){return J()||await oe(),Z(),o}async function ue(y){let p,h=new Promise((I,A)=>{p=setTimeout(()=>A(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs)});try{return await Promise.race([y(),h])}finally{clearTimeout(p)}}function le(y,p){if(Z(),o?.generation!==y.generation)throw b("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(p&&o.funnels[p]?.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function De(y){let p=y.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let I=Be.parse(JSON.parse(await de(h)));if(L(I.scope)!==L({projectId:n.projectId,environment:n.environment})||I.generation!==h.generation||I.remoteFeatures.some(A=>Object.hasOwn(I.features,A)))throw b("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return le(y),{...I,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-$())).toISOString()}}async function xe(y,p){let h=await me(),I=h.funnels[y];p&&(!I||I.evaluationMode==="local"&&!I.versions[p])&&(F&&await F,h=await oe()),le(h,y);let A=h.funnels[y];if(A.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let D=p??A.currentVersionId,N=A.versions[D];if(!N)throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(h.artifacts[N.artifact].formatVersion!==3)throw b("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[U,V]=await Promise.all([de(h.artifacts[N.artifact]).then(x=>We(JSON.parse(x))),A.evaluationMode==="local"?De(h):void 0]);if(V&&L($e(U,V))!==L(N.dependencies))throw b("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return le(h,y),{document:U,growth:V,versionId:D,control:structuredClone(A),manifest:structuredClone(h)}}async function Le(y,p){try{return await xe(y,p)}catch(h){if(!(h instanceof l)||!(h.code==="CONFIGURATION_CHANGED"||h.code==="CONFIGURATION_HTTP_404"&&J()))throw h;let I=o?.generation;if(F&&await F,await oe(),h.code!=="CONFIGURATION_CHANGED"&&o?.generation===I)throw h;return xe(y,p)}}function Ce(){d=!0,G(),oe().catch(W)}let fe=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ce()};function Nn(y){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return S.add(y),S.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ce),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),be()),()=>{S.delete(y),S.size||(clearTimeout(s),clearTimeout(m),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",Ce),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:oe,subscribe:Nn,assertFresh:Z,assertFeatures(y){Z();let p=o.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(y!==void 0&&o.artifacts[p].generation!==y)throw b("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return J()},get snapshot(){return o?structuredClone(o):null},get remainingMs(){return J()?Math.max(0,a-$()):0},async features(){return ue(async()=>De(await me()))},pageExperiments:()=>ue(async()=>{let y=await me(),p=y.gb.pageExperiments;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let I=an.parse(JSON.parse(await de(h)));if(I.environmentId!==n.environmentId||I.generation!==h.generation)throw b("INVALID_RESPONSE","Page experiment scope or generation changed");return le(y),I}),funnel:(y,p)=>ue(()=>Le(y,p)),paywall:(y,p)=>ue(async()=>{let h=await me(),I=h.paywalls?.[y];if(!I||!p&&I.state!=="published")throw b("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let A=p??I.currentVersionId,D=I.versions[A],N=D&&h.artifacts[D.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let U=ze.parse(JSON.parse(await de(N)));return le(h),{document:U,versionId:A,version:D.version,control:structuredClone(I),manifest:structuredClone(h)}}),async localFunnel(y,p){let h=await ue(()=>Le(y,p));if(!h.growth)throw b("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:I,remoteFeatures:A,...D}=h.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:y,versionId:h.versionId,evaluationMode:"local",evaluationRevision:h.control.evaluationRevision,document:h.document,payload:D})},assertFunnel(y,p,h){Z();let I=o.funnels[y];if(!I||I.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable");if(I.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel now executes at Longplay");if(p!==void 0&&I.controlRevision!==p)throw b("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(h!==void 0&&!I.versions[h])throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!C){C=!0,_++,a=0,i?.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(m),Ve(),G(),S.clear();for(let y of R)y.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),O=0}}}}function An(e){let n=ie.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");let t=Q({...e,timeoutMs:e.timeoutMs??35e3});return e.session||t.identify(e.apiKey),{async start(f){let u=H.safeParse({...f,operation:"start"});if(!u.success||u.data.operation!=="start"||(n?u.data.customer!==void 0:u.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let g=u.data,c=we.safeParse(await he(e,await t.request("funnels",g)));if(!c.success||!c.data.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");let r=c.data;if(r.run.source.id!==g.funnelId||r.run.locale!==(g.locale??"en")||!se(r.run.parameters,g.parameters??{})||(g.customer?!r.customerId||g.customer.type==="id"&&r.customerId!==g.customer.value:r.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...r,runToken:r.runToken}}}}async function hr(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(t)!==L(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let u=re.test(e.credential);if(u?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let g=An({...e,scope:t,apiKey:e.credential}),c=r=>{let o=Pn({...e,scope:t,runToken:r,...u?{serverKey:e.credential}:{}});return u||o.identify(e.credential),o};return{async start(r){let o=await g.start({...r,funnelId:e.funnelId,...u?{customer:{type:"id",value:e.customerId}}:{}}),a=c(o.runToken),w=await a.get();return{...o,...w,controller:a}},async restore(r){let o=c(r),a=await o.get();if(a.run.source.id!==e.funnelId)throw o.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:r,controller:o}}}}export{Pe as a,Un as b,he as c,Fe as d,rt as e,On as f,gn as g,ft as h,se as i,vt as j,Rt as k,Pn as l,Kt as m,ir as n,An as o,hr as p};
@@ -0,0 +1 @@
1
+ var s={name:"@tinkerlandai/indiana-sdk",version:"0.10.2",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"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var i="https://api.longplayai.com";export{s as a,i as b};
@@ -0,0 +1 @@
1
+ import{d as t}from"./chunk-FYGXGMRB.js";import{Ga as n}from"./chunk-Q64VNSPV.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
@@ -1 +1 @@
1
- import{a as ue,b as me,c as ye,d as ge,e as ve}from"./chunk-5ZWSFE2C.js";import{I as fe,U as le}from"./chunk-UWFYBRM2.js";import{ca as pe,ma as we,oa as m}from"./chunk-HEGNIATD.js";import{b as he,e as be}from"./chunk-6ZZUNGNE.js";import{d as Ie}from"./chunk-4C3HUZ3B.js";import{a as z}from"./chunk-DSPLGTQI.js";import{b as de}from"./chunk-3PZ4Y6UD.js";function Ce(e){let b=e.view;if(!b?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let n=b.paywall.receiptId,P=b.nodeId,y=b.visit,p=b.paywall.resolution,u=p,f="document"in p?p:null;function s(t){if(!me(t,p))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let o=b.paywall.quote,D=b.paywall.operation,C=!1,$=new AbortController,d=b.paywall.purchaseRequestId,r=0,c=b.paywall.selectionGeneration??0,T=b.paywall.canReselect===!0,A=null,O=new Map,g=new Map,V=new Map;function L(t){if(t.purchase&&t.purchase.receiptId!==n)throw new m("INVALID_RESPONSE","Purchase receipt changed");let a=t.run.paywall;return t.purchase??(a?.receiptId===n?a:null)}function S(){if(C)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function _(t,a,l){if(S(),a!==r||l!==void 0&&o?.operationId!==l)return!1;let I=c,w=t.run.paywall;if(w?.receiptId===n){if((w.selectionGeneration??0)<c)return!1;c=w.selectionGeneration??0,T=w.canReselect===!0,s(w.resolution)}let v=L(t),h=c>I,k=h?v?.quote??null:v?.quote??o,E=v?.operation??(k?.operationId===o?.operationId?D:null);return k&&E&&ye(E,{operationId:k.operationId},"Purchase operation changed"),w?.receiptId===n&&(u=w.resolution,f="document"in u?u:f?{...u,document:f.document,offering:f.offering,capabilities:ue(u.capabilities,f.capabilities)}:null),(h||k?.operationId!==o?.operationId)&&(r++,w?.receiptId===n&&(d=w.purchaseRequestId)),o=k,D=ve(D,E,!0),!0}function x(t,a,l){return new Promise((I,w)=>{let v=!1,h=()=>{clearTimeout(B),$.signal.removeEventListener("abort",H)},k=F=>{v||(v=!0,h(),I(F))},E=F=>{v||(v=!0,h(),w(F))},H=()=>E(new m("IDENTITY_CHANGED","Paywall presentation has closed")),B=setTimeout(()=>E(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,l)),Math.max(0,a-Date.now()));$.signal.addEventListener("abort",H,{once:!0}),$.signal.aborted&&H(),t.then(k,E)})}function J(t){return new Promise(a=>{let l=()=>{clearTimeout(I),$.signal.removeEventListener("abort",l),a()},I=setTimeout(l,t);$.signal.addEventListener("abort",l,{once:!0}),$.signal.aborted&&l()})}async function j(t,a,l){S();let I=O.get(t);if(!I){let h=e.pendingCommands?.find(k=>k.requestId===t)??e.pendingCommand;if(h?.operation==="submit"&&h.requestId===t&&h.nodeId===P&&h.visit===y){a.type==="paywall_quote"&&h.input.type==="paywall_quote"&&h.input.predecessor&&!a.predecessor&&(a={...a,predecessor:h.input.predecessor});let k=le.parse(h),E=le.parse({...h,input:a});if(E.operation!=="submit"||k.operation!=="submit"||JSON.stringify(E.input)!==JSON.stringify(k.input))throw new m("CONFLICT","A restored purchase request cannot change its input");a=E.input,I=k,O.set(t,I)}}if(I){if(JSON.stringify(I.input)!==JSON.stringify(a))throw new m("CONFLICT","A purchase request cannot change its input")}else{let h=e.view;if(!h||h.nodeId!==P||h.visit!==y||h.paywall?.receiptId!==n)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");I={operation:"submit",requestId:t,nodeId:P,visit:y,revision:h.revision,input:a},O.set(t,I)}let w=Date.now()+3e4,v=await x(e.submit(I),w,t);for(;v.run.pendingRequest?.requestId===t&&Date.now()<w&&!C&&(await J(Math.min(1e3,w-Date.now())),!(C||Date.now()>=w));)v=await x(e.resume(t),w,t);if(C)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(v.run.pendingRequest?.requestId===t)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!_(v,l,a.type==="paywall_confirm"||a.type==="paywall_cancel"?a.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed")}async function q(t){if(!o)throw new m("INVALID_REQUEST","A quoted purchase is required");let a=`${t}:${o.operationId}`,l=g.get(a);if(!l){let I=t==="confirm"?"paywall_confirm":"paywall_cancel",w=e.pendingCommands?.find(v=>v.operation==="submit"&&v.input.type===I&&"operationId"in v.input&&v.input.operationId===o.operationId)??e.pendingCommand;l=w?.operation==="submit"&&w.input.type===I&&"operationId"in w.input&&w.input.operationId===o.operationId?w.requestId:crypto.randomUUID(),g.set(a,l)}if(await j(l,{type:t==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.operationId},r),!D)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(D)}return{get view(){return structuredClone(f)},get quote(){return o?structuredClone(o):null},get operation(){return D?structuredClone(D):null},get webViewUrl(){return e.webViewUrl},get canReselect(){return T},async refresh(){S();let t=r,a=await e.get();if(_(a,t),a.run.paywall?.receiptId!==n)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");if(!f){if("document"in u||!e.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let l=await e.resolvePaywall(u);S(),s(l),f={...u,document:l.document,offering:l.offering,capabilities:ue(u.capabilities,l.capabilities)}}return structuredClone(f)},preview(t){if(!f)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(d&&d!==t.requestId&&(A||!T))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let a=f.document.buttons[t.actionId],l=a?.type==="checkout"?fe(a.product,t.selection,f.capabilities):null;if(!l)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let I=we(f.document.screen,l,t.selection,f.capabilities),w=JSON.stringify({actionId:t.actionId,product:l,featureQuantities:I,offerId:t.offerId,nativeOffer:t.nativeOffer});if(V.has(t.requestId)&&V.get(t.requestId)!==w)return Promise.reject(new m("CONFLICT","A purchase request cannot change its quantities or Product"));if(V.set(t.requestId,w),d===t.requestId&&A)return A;let v=d!==t.requestId&&c>0?{operationId:o?.operationId??null,generation:c}:void 0;if(v&&(!T||c<=0))return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));d!==t.requestId&&r++;let h=r;d=t.requestId;let k=(async()=>{if(await j(t.requestId,{type:"paywall_quote",actionId:t.actionId,productVersionId:l,...Object.keys(I).length?{featureQuantities:I}:{},...v?{predecessor:v}:{},...t.offerId?{offerId:t.offerId}:{},...t.nativeOffer?{nativeOffer:t.nativeOffer}:{}},h),!o)throw new m("INVALID_RESPONSE","The accepted quote is missing");return ge(o,{productVersionId:l,featureQuantities:I},"The selected purchase changed"),structuredClone(o)})();return A=k,k.then(()=>{A===k&&(A=null)},E=>{A===k&&(A=null),d===t.requestId&&e.pendingCommand?.requestId!==t.requestId&&E instanceof m&&E.status!==void 0&&E.status<500&&![401,425].includes(E.status)&&(d=null)}),k},confirm:()=>q("confirm"),cancel:()=>q("cancel"),async read(){if(S(),!o)throw new m("INVALID_REQUEST","A quoted purchase is required");let t=o.operationId,a=r,l=e.pendingCommands?.find(h=>h.operation==="submit"&&(h.input.type==="paywall_confirm"||h.input.type==="paywall_cancel")&&h.input.operationId===t)??e.pendingCommand;l?.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===t&&await e.settle?.(l.requestId);let I=await e.get(void 0,{receiptId:n,operationId:t});S();let w=L(I);if(w?.quote&&w.quote.operationId!==t||w?.operation&&w.operation.operationId!==t)throw new m("INVALID_RESPONSE","Purchase operation changed");let v=_(I,a,t)?D:w?.operation;if(!v)throw new m("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(v)},destroy(){C=!0,$.abort(),O.clear(),g.clear(),V.clear()}}}function Ee(e){let b=new Set,n=new Set,P=null;function y(p){if(e.reviewing||b.has(p)||n.has(p)||e.stopped)return;n.add(p);let u=async()=>{if(e.reviewing||e.stopped||e.key!==p){n.delete(p);return}if(e.busy||e.client.pendingCommand){setTimeout(()=>{u()},250);return}let f=(async()=>{let o=e.client.view,D=e.expected(),C=D.requestId,$=!1;try{await e.client.submit({operation:"shown",...D})}catch(d){if(!(d instanceof m)||d.code!=="CONFLICT"||d.status!==409||e.client.pendingCommand)throw d;await e.client.get();let r=e.client.view;if(e.stopped||e.reviewing||e.key!==p||!r||!o||r.id!==o.id||r.source.versionId!==o.source.versionId||r.nodeId!==D.nodeId||r.visit!==D.visit||r.revision<=D.revision||r.stopped||!r.screen||!["running","waiting"].includes(r.status)||e.client.pendingCommand)throw d;let c=e.expected();C=c.requestId,await e.client.submit({operation:"shown",...c})}for(;!e.stopped&&e.key===p&&e.client.pendingCommand?.requestId===C;){if(!e.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await e.client.settle(C),$=!0,e.client.pendingCommand?.requestId===C&&await new Promise(d=>setTimeout(d,1500))}e.stopped||e.key!==p||($&&await e.client.get(),!(e.stopped||e.key!==p)&&b.add(p))})();P=f;let s=()=>{P===f&&(P=null),n.delete(p)};f.then(s,o=>{s(),e.busy||e.fail(o)})};u()}return{report:y,get inFlight(){return P}}}function Pe(e){let b={},n=new Map;async function P(y){let p=e.client.view,u=p?.screen,f=u?.customerData.nodes[y.nodeId];if(e.stopped||e.busy||!p||!u||!f)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(y.action)){let r=e.document,c=r?pe(r,y.nodeId):null,T=c?.type==="customer_data"?c.data.outputs?.[y.action]:void 0;T&&u.outputs.includes(T)?await e.perform(()=>e.client.submit({operation:"submit",...e.expected(),input:{type:"screen",output:T,answers:e.answers,selection:y.value?{[y.nodeId]:y.value}:{}}})):await e.onIntent?.(y,p);return}let o=y.action.startsWith("sources_")?f.resources.find(r=>r.key===y.value):null;if(y.action.startsWith("sources_")&&!o)throw new m("INVALID_REQUEST","Choose a current resource");let D=`${p.visit}:${y.nodeId}:${o?.key??""}`,C=n.get(D)??[null],d=b[y.nodeId]??{page:1,after:null,filter:"all",...o?{resourceKey:o.key}:{}};if(y.action==="filter"){let r=y.value;if(!r||!(f.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(r))throw new m("INVALID_REQUEST","Unknown data filter");d={page:1,after:null,filter:r},C.splice(0,C.length,null)}else if(y.action==="next"||y.action==="sources_next"){let r=o?.sources.at(-1),c=o?r?{kind:"ledger",cursor:{at:r.detail[0],id:r.id,type:"source"}}:null:u.dataCursors[y.nodeId];if(!c||!o&&!f.hasNext)return;C[d.page]=c,d={...d,page:d.page+1,after:c}}else if(y.action==="previous"||y.action==="sources_previous"){if(d.page<=1)return;d={...d,page:d.page-1,after:C[d.page-2]??null}}n.set(D,C),b={...b,[y.nodeId]:d},await e.perform(()=>e.client.get({nodeId:p.nodeId,visit:p.visit,revision:p.revision,components:b}))}return{get queries(){return b},intent:P,reset(){b={},n.clear()}}}function Re(e){let{doc:b,holder:n,reviewHolder:P,mountScreenPreview:y}=e,p=!1,u,f=0,s=null,o="",D=new Map,C=r=>r?`${r.id}:${r.nodeId}:${r.visit}:${r.revision}:${r.paywall?.quote?.operationId??""}`:"";async function $(r){if(e.stopped||!e.client.review)return;p||(o=C(e.client.view),D.set(o,structuredClone(e.answers))),p=!0,u=r,n.hidden=!0,e.suspend(!0),P.hidden=!1;let c=++f;try{let T=await e.client.review(r);if(e.stopped||c!==f||!p)return;if(!T.review)throw new m("INVALID_RESPONSE","Historical projection is missing");s?.destroy(),s=null,P.replaceChildren();let A=T.run.locale.startsWith("zh"),O=b.createElement("p");O.textContent=A?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",P.append(O);for(let[L,S]of T.review.pages.entries()){let _=b.createElement("button");_.type="button",_.textContent=A?`\u7B2C ${L+1} \u9875`:`Page ${L+1}`,_.onclick=()=>{$(S.receiptId)},P.append(_)}if(T.review.page){let L=T.review.page,S=b.createElement("div");if(S.inert=!0,P.append(S),s=y(S,{mode:"live",rendererUrl:e.client.webViewUrl,title:L.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{d()}}),s.update(L.document,T.run.locale,{serverInput:{bindings:L.inputs,answers:L.answers,values:L.values}}),await s.ready,e.stopped||c!==f||!p)return}let g=A?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},V=A?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let L of[...T.review.coupons.map((S,_)=>`${A?"\u4F18\u60E0\u5238":"Coupon"} ${_+1}: ${g[S.status]}`),...T.review.purchases.map((S,_)=>`${A?"\u8D2D\u4E70":"Purchase"} ${_+1}: ${V[S.status]}`)]){let S=b.createElement("p");S.textContent=L,P.append(S)}e.client.view&&await e.enqueue(e.client.view)}catch(T){if(c!==f||e.stopped)return;s?.destroy(),s=null,P.replaceChildren(),e.fail(T)}}async function d(){if(!p||e.stopped||!e.client.review)return;let r=++f;try{if(await e.client.review(),e.stopped||r!==f)return;p=!1,f++,s?.destroy(),s=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1;let c=e.client.view;C(c)!==o?(D.set(o,structuredClone(e.answers)),e.resetScreen()):(D.delete(o),e.suspend(!1)),c&&await e.enqueue(c)}catch(c){if(r!==f||e.stopped)return;s?.destroy(),s=null,P.replaceChildren(),e.fail(c)}}return{get active(){return p},get receipt(){return u},open:$,exit:d,get drafts(){return new Map([...D].map(([r,c])=>[r,structuredClone(c)]))},stop(){p=!1,f++,s?.destroy(),s=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1}}}function De(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let b=e.client.pageExperiments.bind(e.client),n=!1,P=!1,y=0,p=!1,u=!1,f,s=new Map,o=new Set,D={},C=new Map,$=he(e.appManifestRelease),d=()=>{for(let g of s.values())g.effect.revert();s.clear();for(let g of C.values())g();C.clear()};function r(g){n||o.has(g)||(o.add(g),b(e.appManifestRelease,[g]).catch(V=>{o.delete(g),z(e.onError,V)}))}async function c(){if(n)return;let g=e.client.view;if(!g||g.stopped||!["running","waiting"].includes(g.status)){y++,d();return}if(p){u=!0;return}p=!0;let V=++y,L=`${g.id}:${g.visit}:${g.revision}`,S=location.href;try{let[_,{applyVisualVariation:x}]=await Promise.all([b(e.appManifestRelease),import("./visual-dom-OFB7BFFB.js")]),J=e.client.view;if(n||V!==y||!J||J.stopped||!["running","waiting"].includes(J.status)||`${J.id}:${J.visit}:${J.revision}`!==L||location.href!==S)return;let j=new Set,q=new Set;for(let t of _.assignments){let a=`${_.payload.environmentId}:${t.experimentKey}`;if(q.add(a),C.has(a)||C.set(a,be(a,D)),!!t.inExperiment)for(let l of _.payload.experiments){if(l.key!==t.experimentKey||!de(location.href,l.urlPatterns??[]))continue;let I=l.meta?.findIndex(H=>H.key===t.variationKey)??-1,w=l.variations[I];if(!w?.renderGuard)continue;let v=t.receiptId+":"+l.changeId,h=JSON.stringify([t.variationKey,w]);j.add(v);let k=s.get(v);if(k?.signature===h){k.effect.applied&&r(t.receiptId);continue}s.get(v)?.effect.revert(),s.delete(v);let E=x(w,{requireUniqueTargets:!0,boundVariations:l.variations,allowJs:!1,onApplied:()=>r(t.receiptId),onError:H=>z(e.onError,H)});s.set(v,{signature:h,effect:E}),E.applied&&r(t.receiptId)}}for(let[t,a]of s)j.has(t)||(a.effect.revert(),s.delete(t));for(let[t,a]of C)q.has(t)||(a(),C.delete(t))}catch(_){V===y&&d(),z(e.onError,_)}finally{p=!1,u&&!n&&(u=!1,c())}}let T=e.client.subscribe(()=>{y++,c()}),A=Ie(()=>{y++,d(),c()}),O=async()=>{await c(),n||(f=setTimeout(()=>{O()},15e3))};return{async start(){P||n||(P=!0,await O())},refresh:c,destroy(){n=!0,y++,clearTimeout(f),T(),A(),d(),$.destroy()}}}async function rn(e,b){let n=b,{mountScreenPreview:P}=await import("./screen-renderer-VAMWY7ID.js"),{showPaywall:y}=await import("./paywall-CSAGKPCP.js"),p=n.appManifestRelease?De({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;p?.start();let u=e.ownerDocument,f=u.activeElement,s=u.createElement("section"),o=u.createElement("div"),D=u.createElement("div"),C=u.createElement("div"),$=u.createElement("button");C.hidden=!0,$.type="button";let d=u.createElement("p"),r=u.createElement("p"),c=u.createElement("button"),T=u.createElement("button"),A=u.createElement("button"),O=u.createElement("dialog");s.dataset.indianaFunnel="",s.setAttribute("aria-busy","false"),s.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",D.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",d.setAttribute("role","status"),r.setAttribute("role","alert"),r.hidden=!0,c.type=T.type=A.type="button",D.append(c,d,r,A,$,T),s.append(o,C,D),e.append(s);let g=null,V=null,L=null,S="",_="",x="",J="",j="",q=!1,t=0,a=!1,l="",I=null,w=Promise.resolve(),v=null,h=null,k=new Set,E={},H=(i,R=null)=>{q||(h=R,r.textContent=i instanceof Error?i.message:"Request failed",r.hidden=!1,A.hidden=n.client.pendingCommand===null,z(n.onError,i))};function B(){let i=n.client.view;if(!i)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:i.nodeId,visit:i.visit,revision:i.revision}}let F=Re({client:n.client,doc:u,holder:o,reviewHolder:C,mountScreenPreview:P,get stopped(){return q},get answers(){return E},suspend(i){V?.setSuspended(i)},resetScreen(){S="",_="",x=""},enqueue:Y,fail:H}),Z=Ee({client:n.client,expected:B,fail:H,get stopped(){return q},get reviewing(){return F.active},get key(){return S},get busy(){return t}}),ee=Pe({client:n.client,expected:B,perform:W,onIntent:n.onCustomerDataIntent,get stopped(){return q},get busy(){return t},get document(){return g?.document},get answers(){return E}}),oe=i=>i&&(i.screen||i.paywall)?`${i.id}:${i.nodeId}:${i.visit}`:"";function X(){let i=n.client.view;c.disabled=!F.active&&(t>0||!!n.client.pendingCommand||!i?.canBack||i.stopped||!["running","waiting"].includes(i.status)||!oe(i)||_!==oe(i))}async function W(i,R=!1){if(!(t&&!R||q||F.active&&!R)){t++,s.setAttribute("aria-busy","true"),X(),r.hidden=!0,h=null;try{if(!R&&Z.inFlight){let N=n.client.view;await Z.inFlight;let U=n.client.view;if(!N||!U||U.id!==N.id||U.nodeId!==N.nodeId||U.visit!==N.visit||U.stopped||!["running","waiting"].includes(U.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(q)return;let Q=await i();q||await Y(n.client.view??Q.run)}catch(Q){H(Q,n.client.pendingCommand?.requestId??null)}finally{t=Math.max(0,t-1),s.setAttribute("aria-busy",String(t>0)),q||(A.hidden=n.client.pendingCommand===null,X())}}}function ne(){I&&clearTimeout(I),!(q||!L||!["running","waiting"].includes(L.status)&&!n.client.pendingCommand)&&(I=setTimeout(()=>{I=null,ce().finally(ne)},L.pendingRequest||n.client.pendingCommand?1500:5e3))}async function ce(){if(!(q||a||t)){if(F.active){await F.open(F.receipt);return}a=!0;try{let i=n.client.pendingCommand;i&&n.client.settle&&await n.client.settle(i.requestId);let R=n.client.view,Q=ee.queries,N=await n.client.get(R?.screen&&Object.keys(Q).length?{nodeId:R.nodeId,visit:R.visit,revision:R.revision,components:Q}:void 0);!q&&Q===ee.queries&&await Y(n.client.view??N.run)}catch(i){H(i)}finally{a=!1}}}function Se(i){let R=i.screen?.presentation;if(!R||R.type==="inline"){O.open&&O.close(),s.parentElement!==e&&e.append(s);return}s.parentElement!==O&&(O.append(s),e.append(O));let Q={sm:420,md:640,lg:900};O.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in R?Q[R.size]+"px":"100vw"}`,O.setAttribute("aria-label",g?.document?.name??i.screen?.content.document.name??"Funnel"),O.open||O.showModal()}async function Fe(i){if(q)return;L=i,h&&n.client.pendingCommand?.requestId!==h&&(r.hidden=!0,h=null);let R=i.locale.startsWith("zh");if($.textContent=R?"\u56DE\u770B":"History",$.hidden=!n.client.review,c.textContent=F.active?R?"\u8FD4\u56DE\u5F53\u524D":"Return to current":R?"\u8FD4\u56DE":"Back",T.textContent=R?"\u5173\u95ED":"Close",A.textContent=R?"\u91CD\u8BD5":"Retry",X(),A.hidden=n.client.pendingCommand===null,d.textContent=i.pendingRequest?R?"\u6B63\u5728\u5904\u7406":"Processing":i.instruction?.type==="wait"?R?"\u7B49\u5F85\u4E2D":"Waiting":"",l!==`${i.revision}:${i.visit}:${i.status}:${i.stopped}`&&(l=`${i.revision}:${i.visit}:${i.status}:${i.stopped}`,z(n.onState,structuredClone(i))),i.stopped||n.client.configurationReady===!1){F.stop(),g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S="",_="",x="",j="",O.open&&O.close(),s.hidden=!0,ne();return}if(s.hidden=!1,F.active){ne();return}let Q=oe(i);if(Q!==S&&(_="",g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S=Q,x="",j="",E={...i.answers},ee.reset()),Se(i),i.screen){let U=i.screen.content;g||(g=P(o,{mode:"live",rendererUrl:n.client.webViewUrl,title:U.document.name,onAction(G,se={},ae={}){if(F.active)return;E={...E,...ae};let Te=Object.fromEntries((i.screen?.inputs??[]).filter(({variable:re})=>Object.hasOwn(E,re)).map(({variable:re})=>[re,E[re]]));W(()=>n.client.submit({operation:"submit",...B(),input:{type:"screen",output:G,answers:Te,selection:se}}))},onAnswers:G=>{F.active||(E={...E,...G})},onCustomerDataIntent:G=>{F.active||ee.intent(G).catch(H)},onEscape:()=>{F.active||te()},onError:G=>H(new Error(G)),onRendered:()=>Z.report(Q)}));let M={capabilities:i.screen.capabilities,customerData:i.screen.customerData,parameters:i.parameters,serverInput:{bindings:i.screen.inputs,answers:E,values:i.screen.values}},K=JSON.stringify([U,i.locale,M.parameters,i.screen.inputs,i.screen.values]);if(K!==x)g.update(U.document,i.locale,M),x=K,J=JSON.stringify(M.capabilities),j=JSON.stringify(M.customerData);else{let G=JSON.stringify(M.capabilities);G!==J&&(g.updateCapabilities(M.capabilities),J=G),JSON.stringify(M.customerData)!==j&&(g.updateCustomerData(M.customerData),j=JSON.stringify(M.customerData))}await g.ready}else if(i.paywall&&!V){let U=await y(o,{canInteract:()=>!F.active&&!q,start:async()=>Ce(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:M=>n.onOpenUrl?n.onOpenUrl({receiptId:i.paywall.receiptId,url:M,openIn:"same_window"}):u.defaultView?.location.assign(M),onAction:async M=>{if(F.active)return;let K=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:i.nodeId,visit:i.visit,revision:i.revision,input:{type:"screen",output:M,answers:{}}});await Y(n.client.view??K.run)},onError:H,onDismiss:()=>{!F.active&&!q&&n.client.view?.visit===i.visit&&te()}});q?U.host?.destroy():(V=U.host,V?.setSuspended(F.active)),Z.report(Q)}if(q)return;_=Q,X();let N=i.instruction;if(N&&(N.type==="open_url"||N.type==="event")&&!k.has(N.receiptId)){let U=u.createElement("button");U.type="button",U.textContent=N.type==="open_url"?`${R?"\u524D\u5F80":"Continue to"} ${new URL(N.url).host}`:R?"\u7EE7\u7EED":"Continue",U.onclick=()=>{let M=B(),K=N.type==="open_url"&&!n.onOpenUrl&&N.openIn==="new_window"?Ne(N.url):null;W(async()=>{let G="success";if(N.type==="open_url")if(n.onOpenUrl)try{G=await n.onOpenUrl({receiptId:N.receiptId,url:N.url,openIn:N.openIn})===!1?"failed":"opened"}catch(ae){z(n.onError,ae),G="failed"}else G=N.openIn==="new_window"&&!K?"failed":"opened";if(N.type==="event"){if(!n.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(N.event)}if(q||n.client.view?.nodeId!==M.nodeId||n.client.view.visit!==M.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let se=await n.client.submit({operation:"submit",...M,input:{type:"client_action",receiptId:N.receiptId,outcome:G}});return k.add(N.receiptId),N.type==="open_url"&&!n.onOpenUrl&&N.openIn==="same_window"&&u.defaultView?.location.assign(N.url),se})},o.replaceChildren(U)}!i.pendingRequest&&i.status==="completed"&&!k.has(`complete:${i.id}`)&&(k.add(`complete:${i.id}`),z(n.onComplete,structuredClone(i))),ne()}function Ne(i){let R=u.defaultView?.open(i,"_blank")??null;return R&&(R.opener=null),R}function Y(i){return X(),w=w.catch(()=>{}).then(()=>Fe(i)),w}let Oe=n.client.subscribe(i=>{n.client.configurationReady===!1&&(s.hidden=!0,g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S="",_="",x="",j="",O.open&&O.close()),Y(i).catch(H)}),ke=n.client.subscribeError?.(H);function te(){return v||(q?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ie(),Promise.resolve()):(v=W(()=>n.client.submit({operation:"close",...B()}),!0).then(()=>{n.client.view?.status==="closed"&&ie()}).finally(()=>{v=null}),v))}function ie(){p?.destroy(),!q&&(q=!0,I&&clearTimeout(I),Oe(),ke?.(),g?.destroy(),F.stop(),V?.destroy(),O.close(),O.remove(),s.remove(),f instanceof HTMLElement&&f.isConnected&&f.focus(),z(n.onDismiss,L?structuredClone(L):null))}c.onclick=()=>{if(!c.disabled){if(F.active){F.exit();return}W(()=>n.client.submit({operation:"back",...B()}))}},$.onclick=()=>{F.open()},T.onclick=()=>{te()},A.onclick=()=>{W(()=>n.client.retry())},O.addEventListener("cancel",i=>{i.preventDefault(),te()});try{let i=await n.client.get();await Y(n.client.view??i.run)}catch(i){throw ie(),i}return{destroy:ie,refresh:ce,review:F.open,exitReview:F.exit,get unappliedDrafts(){return F.drafts}}}export{De as a,rn as b};
1
+ import{a as ue,b as me,c as ye,d as ge,e as ve}from"./chunk-SBPTOOYB.js";import{M as fe,Y as le}from"./chunk-Q64VNSPV.js";import{ea as pe,oa as we,qa as m}from"./chunk-ACF2FBUB.js";import{b as he,e as be}from"./chunk-EARSGITJ.js";import{d as Ie}from"./chunk-XO42OH3M.js";import{a as z}from"./chunk-DSPLGTQI.js";import{b as de}from"./chunk-3PZ4Y6UD.js";function Ce(e){let b=e.view;if(!b?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let n=b.paywall.receiptId,P=b.nodeId,y=b.visit,p=b.paywall.resolution,u=p,f="document"in p?p:null;function s(i){if(!me(i,p))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let o=b.paywall.quote,D=b.paywall.operation,C=!1,$=new AbortController,d=b.paywall.purchaseRequestId,r=0,c=b.paywall.selectionGeneration??0,T=b.paywall.canReselect===!0,A=null,O=new Map,g=new Map,V=new Map;function L(i){if(i.purchase&&i.purchase.receiptId!==n)throw new m("INVALID_RESPONSE","Purchase receipt changed");let a=i.run.paywall;return i.purchase??(a?.receiptId===n?a:null)}function S(){if(C)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function _(i,a,l){if(S(),a!==r||l!==void 0&&o?.operationId!==l)return!1;let I=c,w=i.run.paywall;if(w?.receiptId===n){if((w.selectionGeneration??0)<c)return!1;c=w.selectionGeneration??0,T=w.canReselect===!0,s(w.resolution)}let v=L(i),h=c>I,k=h?v?.quote??null:v?.quote??o,E=v?.operation??(k?.operationId===o?.operationId?D:null);return k&&E&&ye(E,{operationId:k.operationId},"Purchase operation changed"),w?.receiptId===n&&(u=w.resolution,f="document"in u?u:f?{...u,document:f.document,offering:f.offering,capabilities:ue(u.capabilities,f.capabilities)}:null),(h||k?.operationId!==o?.operationId)&&(r++,w?.receiptId===n&&(d=w.purchaseRequestId)),o=k,D=ve(D,E,!0),!0}function x(i,a,l){return new Promise((I,w)=>{let v=!1,h=()=>{clearTimeout(B),$.signal.removeEventListener("abort",H)},k=F=>{v||(v=!0,h(),I(F))},E=F=>{v||(v=!0,h(),w(F))},H=()=>E(new m("IDENTITY_CHANGED","Paywall presentation has closed")),B=setTimeout(()=>E(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,l)),Math.max(0,a-Date.now()));$.signal.addEventListener("abort",H,{once:!0}),$.signal.aborted&&H(),i.then(k,E)})}function J(i){return new Promise(a=>{let l=()=>{clearTimeout(I),$.signal.removeEventListener("abort",l),a()},I=setTimeout(l,i);$.signal.addEventListener("abort",l,{once:!0}),$.signal.aborted&&l()})}async function j(i,a,l){S();let I=O.get(i);if(!I){let h=e.pendingCommands?.find(k=>k.requestId===i)??e.pendingCommand;if(h?.operation==="submit"&&h.requestId===i&&h.nodeId===P&&h.visit===y){a.type==="paywall_quote"&&h.input.type==="paywall_quote"&&h.input.predecessor&&!a.predecessor&&(a={...a,predecessor:h.input.predecessor});let k=le.parse(h),E=le.parse({...h,input:a});if(E.operation!=="submit"||k.operation!=="submit"||JSON.stringify(E.input)!==JSON.stringify(k.input))throw new m("CONFLICT","A restored purchase request cannot change its input");a=E.input,I=k,O.set(i,I)}}if(I){if(JSON.stringify(I.input)!==JSON.stringify(a))throw new m("CONFLICT","A purchase request cannot change its input")}else{let h=e.view;if(!h||h.nodeId!==P||h.visit!==y||h.paywall?.receiptId!==n)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");I={operation:"submit",requestId:i,nodeId:P,visit:y,revision:h.revision,input:a},O.set(i,I)}let w=Date.now()+3e4,v=await x(e.submit(I),w,i);for(;v.run.pendingRequest?.requestId===i&&Date.now()<w&&!C&&(await J(Math.min(1e3,w-Date.now())),!(C||Date.now()>=w));)v=await x(e.resume(i),w,i);if(C)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(v.run.pendingRequest?.requestId===i)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,i);if(!_(v,l,a.type==="paywall_confirm"||a.type==="paywall_cancel"?a.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed")}async function q(i){if(!o)throw new m("INVALID_REQUEST","A quoted purchase is required");let a=`${i}:${o.operationId}`,l=g.get(a);if(!l){let I=i==="confirm"?"paywall_confirm":"paywall_cancel",w=e.pendingCommands?.find(v=>v.operation==="submit"&&v.input.type===I&&"operationId"in v.input&&v.input.operationId===o.operationId)??e.pendingCommand;l=w?.operation==="submit"&&w.input.type===I&&"operationId"in w.input&&w.input.operationId===o.operationId?w.requestId:crypto.randomUUID(),g.set(a,l)}if(await j(l,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.operationId},r),!D)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(D)}return{get view(){return structuredClone(f)},get quote(){return o?structuredClone(o):null},get operation(){return D?structuredClone(D):null},get webViewUrl(){return e.webViewUrl},get canReselect(){return T},async refresh(){S();let i=r,a=await e.get();if(_(a,i),a.run.paywall?.receiptId!==n)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");if(!f){if("document"in u||!e.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let l=await e.resolvePaywall(u);S(),s(l),f={...u,document:l.document,offering:l.offering,capabilities:ue(u.capabilities,l.capabilities)}}return structuredClone(f)},preview(i){if(!f)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(d&&d!==i.requestId&&(A||!T))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let a=f.document.buttons[i.actionId],l=a?.type==="checkout"?fe(a.product,i.selection,f.capabilities):null;if(!l)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let I=we(f.document.screen,l,i.selection,f.capabilities),w=JSON.stringify({actionId:i.actionId,product:l,featureQuantities:I,offerId:i.offerId,nativeOffer:i.nativeOffer});if(V.has(i.requestId)&&V.get(i.requestId)!==w)return Promise.reject(new m("CONFLICT","A purchase request cannot change its quantities or Product"));if(V.set(i.requestId,w),d===i.requestId&&A)return A;let v=d!==i.requestId&&c>0?{operationId:o?.operationId??null,generation:c}:void 0;if(v&&(!T||c<=0))return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));d!==i.requestId&&r++;let h=r;d=i.requestId;let k=(async()=>{if(await j(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:l,...Object.keys(I).length?{featureQuantities:I}:{},...v?{predecessor:v}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}},h),!o)throw new m("INVALID_RESPONSE","The accepted quote is missing");return ge(o,{productVersionId:l,featureQuantities:I},"The selected purchase changed"),structuredClone(o)})();return A=k,k.then(()=>{A===k&&(A=null)},E=>{A===k&&(A=null),d===i.requestId&&e.pendingCommand?.requestId!==i.requestId&&E instanceof m&&E.status!==void 0&&E.status<500&&![401,425].includes(E.status)&&(d=null)}),k},confirm:()=>q("confirm"),cancel:()=>q("cancel"),async read(){if(S(),!o)throw new m("INVALID_REQUEST","A quoted purchase is required");let i=o.operationId,a=r,l=e.pendingCommands?.find(h=>h.operation==="submit"&&(h.input.type==="paywall_confirm"||h.input.type==="paywall_cancel")&&h.input.operationId===i)??e.pendingCommand;l?.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===i&&await e.settle?.(l.requestId);let I=await e.get(void 0,{receiptId:n,operationId:i});S();let w=L(I);if(w?.quote&&w.quote.operationId!==i||w?.operation&&w.operation.operationId!==i)throw new m("INVALID_RESPONSE","Purchase operation changed");let v=_(I,a,i)?D:w?.operation;if(!v)throw new m("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(v)},destroy(){C=!0,$.abort(),O.clear(),g.clear(),V.clear()}}}function Ee(e){let b=new Set,n=new Set,P=null;function y(p){if(e.reviewing||b.has(p)||n.has(p)||e.stopped)return;n.add(p);let u=async()=>{if(e.reviewing||e.stopped||e.key!==p){n.delete(p);return}if(e.busy||e.client.pendingCommand){setTimeout(()=>{u()},250);return}let f=(async()=>{let o=e.client.view,D=e.expected(),C=D.requestId,$=!1;try{await e.client.submit({operation:"shown",...D})}catch(d){if(!(d instanceof m)||d.code!=="CONFLICT"||d.status!==409||e.client.pendingCommand)throw d;await e.client.get();let r=e.client.view;if(e.stopped||e.reviewing||e.key!==p||!r||!o||r.id!==o.id||r.source.versionId!==o.source.versionId||r.nodeId!==D.nodeId||r.visit!==D.visit||r.revision<=D.revision||r.stopped||!r.screen||!["running","waiting"].includes(r.status)||e.client.pendingCommand)throw d;let c=e.expected();C=c.requestId,await e.client.submit({operation:"shown",...c})}for(;!e.stopped&&e.key===p&&e.client.pendingCommand?.requestId===C;){if(!e.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await e.client.settle(C),$=!0,e.client.pendingCommand?.requestId===C&&await new Promise(d=>setTimeout(d,1500))}e.stopped||e.key!==p||($&&await e.client.get(),!(e.stopped||e.key!==p)&&b.add(p))})();P=f;let s=()=>{P===f&&(P=null),n.delete(p)};f.then(s,o=>{s(),e.busy||e.fail(o)})};u()}return{report:y,get inFlight(){return P}}}function Pe(e){let b={},n=new Map;async function P(y){let p=e.client.view,u=p?.screen,f=u?.customerData.nodes[y.nodeId];if(e.stopped||e.busy||!p||!u||!f)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(y.action)){let r=e.document,c=r?pe(r,y.nodeId):null,T=c?.type==="customer_data"?c.data.outputs?.[y.action]:void 0;T&&u.outputs.includes(T)?await e.perform(()=>e.client.submit({operation:"submit",...e.expected(),input:{type:"screen",output:T,answers:e.answers,selection:y.value?{[y.nodeId]:y.value}:{}}})):await e.onIntent?.(y,p);return}let o=y.action.startsWith("sources_")?f.resources.find(r=>r.key===y.value):null;if(y.action.startsWith("sources_")&&!o)throw new m("INVALID_REQUEST","Choose a current resource");let D=`${p.visit}:${y.nodeId}:${o?.key??""}`,C=n.get(D)??[null],d=b[y.nodeId]??{page:1,after:null,filter:"all",...o?{resourceKey:o.key}:{}};if(y.action==="filter"){let r=y.value;if(!r||!(f.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(r))throw new m("INVALID_REQUEST","Unknown data filter");d={page:1,after:null,filter:r},C.splice(0,C.length,null)}else if(y.action==="next"||y.action==="sources_next"){let r=o?.sources.at(-1),c=o?r?{kind:"ledger",cursor:{at:r.detail[0],id:r.id,type:"source"}}:null:u.dataCursors[y.nodeId];if(!c||!o&&!f.hasNext)return;C[d.page]=c,d={...d,page:d.page+1,after:c}}else if(y.action==="previous"||y.action==="sources_previous"){if(d.page<=1)return;d={...d,page:d.page-1,after:C[d.page-2]??null}}n.set(D,C),b={...b,[y.nodeId]:d},await e.perform(()=>e.client.get({nodeId:p.nodeId,visit:p.visit,revision:p.revision,components:b}))}return{get queries(){return b},intent:P,reset(){b={},n.clear()}}}function Re(e){let{doc:b,holder:n,reviewHolder:P,mountScreenPreview:y}=e,p=!1,u,f=0,s=null,o="",D=new Map,C=r=>r?`${r.id}:${r.nodeId}:${r.visit}:${r.revision}:${r.paywall?.quote?.operationId??""}`:"";async function $(r){if(e.stopped||!e.client.review)return;p||(o=C(e.client.view),D.set(o,structuredClone(e.answers))),p=!0,u=r,n.hidden=!0,e.suspend(!0),P.hidden=!1;let c=++f;try{let T=await e.client.review(r);if(e.stopped||c!==f||!p)return;if(!T.review)throw new m("INVALID_RESPONSE","Historical projection is missing");s?.destroy(),s=null,P.replaceChildren();let A=T.run.locale.startsWith("zh"),O=b.createElement("p");O.textContent=A?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",P.append(O);for(let[L,S]of T.review.pages.entries()){let _=b.createElement("button");_.type="button",_.textContent=A?`\u7B2C ${L+1} \u9875`:`Page ${L+1}`,_.onclick=()=>{$(S.receiptId)},P.append(_)}if(T.review.page){let L=T.review.page,S=b.createElement("div");if(S.inert=!0,P.append(S),s=y(S,{mode:"live",rendererUrl:e.client.webViewUrl,title:L.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{d()}}),s.update(L.document,T.run.locale,{serverInput:{bindings:L.inputs,answers:L.answers,values:L.values}}),await s.ready,e.stopped||c!==f||!p)return}let g=A?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},V=A?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let L of[...T.review.coupons.map((S,_)=>`${A?"\u4F18\u60E0\u5238":"Coupon"} ${_+1}: ${g[S.status]}`),...T.review.purchases.map((S,_)=>`${A?"\u8D2D\u4E70":"Purchase"} ${_+1}: ${V[S.status]}`)]){let S=b.createElement("p");S.textContent=L,P.append(S)}e.client.view&&await e.enqueue(e.client.view)}catch(T){if(c!==f||e.stopped)return;s?.destroy(),s=null,P.replaceChildren(),e.fail(T)}}async function d(){if(!p||e.stopped||!e.client.review)return;let r=++f;try{if(await e.client.review(),e.stopped||r!==f)return;p=!1,f++,s?.destroy(),s=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1;let c=e.client.view;C(c)!==o?(D.set(o,structuredClone(e.answers)),e.resetScreen()):(D.delete(o),e.suspend(!1)),c&&await e.enqueue(c)}catch(c){if(r!==f||e.stopped)return;s?.destroy(),s=null,P.replaceChildren(),e.fail(c)}}return{get active(){return p},get receipt(){return u},open:$,exit:d,get drafts(){return new Map([...D].map(([r,c])=>[r,structuredClone(c)]))},stop(){p=!1,f++,s?.destroy(),s=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1}}}function De(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let b=e.client.pageExperiments.bind(e.client),n=!1,P=!1,y=0,p=!1,u=!1,f,s=new Map,o=new Set,D={},C=new Map,$=he(e.appManifestRelease),d=()=>{for(let g of s.values())g.effect.revert();s.clear();for(let g of C.values())g();C.clear()};function r(g){n||o.has(g)||(o.add(g),b(e.appManifestRelease,[g]).catch(V=>{o.delete(g),z(e.onError,V)}))}async function c(){if(n)return;let g=e.client.view;if(!g||g.stopped||!["running","waiting"].includes(g.status)){y++,d();return}if(p){u=!0;return}p=!0;let V=++y,L=`${g.id}:${g.visit}:${g.revision}`,S=location.href;try{let[_,{applyVisualVariation:x}]=await Promise.all([b(e.appManifestRelease),import("./visual-dom-OFB7BFFB.js")]),J=e.client.view;if(n||V!==y||!J||J.stopped||!["running","waiting"].includes(J.status)||`${J.id}:${J.visit}:${J.revision}`!==L||location.href!==S)return;let j=new Set,q=new Set;for(let i of _.assignments){let a=`${_.payload.environmentId}:${i.experimentKey}`;if(q.add(a),C.has(a)||C.set(a,be(a,D)),!!i.inExperiment)for(let l of _.payload.experiments){if(l.key!==i.experimentKey||!de(location.href,l.urlPatterns??[]))continue;let I=l.meta?.findIndex(H=>H.key===i.variationKey)??-1,w=l.variations[I];if(!w?.renderGuard)continue;let v=i.receiptId+":"+l.changeId,h=JSON.stringify([i.variationKey,w]);j.add(v);let k=s.get(v);if(k?.signature===h){k.effect.applied&&r(i.receiptId);continue}s.get(v)?.effect.revert(),s.delete(v);let E=x(w,{requireUniqueTargets:!0,boundVariations:l.variations,allowJs:!1,onApplied:()=>r(i.receiptId),onError:H=>z(e.onError,H)});s.set(v,{signature:h,effect:E}),E.applied&&r(i.receiptId)}}for(let[i,a]of s)j.has(i)||(a.effect.revert(),s.delete(i));for(let[i,a]of C)q.has(i)||(a(),C.delete(i))}catch(_){V===y&&d(),z(e.onError,_)}finally{p=!1,u&&!n&&(u=!1,c())}}let T=e.client.subscribe(()=>{y++,c()}),A=Ie(()=>{y++,d(),c()}),O=async()=>{await c(),n||(f=setTimeout(()=>{O()},15e3))};return{async start(){P||n||(P=!0,await O())},refresh:c,destroy(){n=!0,y++,clearTimeout(f),T(),A(),d(),$.destroy()}}}async function rn(e,b){let n=b,{mountScreenPreview:P}=await import("./screen-renderer-ZSAR7LPS.js"),{showPaywall:y}=await import("./paywall-527RPFAX.js"),p=n.appManifestRelease?De({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;p?.start();let u=e.ownerDocument,f=u.activeElement,s=u.createElement("section"),o=u.createElement("div"),D=u.createElement("div"),C=u.createElement("div"),$=u.createElement("button");C.hidden=!0,$.type="button";let d=u.createElement("p"),r=u.createElement("p"),c=u.createElement("button"),T=u.createElement("button"),A=u.createElement("button"),O=u.createElement("dialog");s.dataset.indianaFunnel="",s.setAttribute("aria-busy","false"),s.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",D.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",d.setAttribute("role","status"),r.setAttribute("role","alert"),r.hidden=!0,c.type=T.type=A.type="button",D.append(c,d,r,A,$,T),s.append(o,C,D),e.append(s);let g=null,V=null,L=null,S="",_="",x="",J="",j="",q=!1,i=0,a=!1,l="",I=null,w=Promise.resolve(),v=null,h=null,k=new Set,E={},H=(t,R=null)=>{q||(h=R,r.textContent=t instanceof Error?t.message:"Request failed",r.hidden=!1,A.hidden=n.client.pendingCommand===null,z(n.onError,t))};function B(){let t=n.client.view;if(!t)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let F=Re({client:n.client,doc:u,holder:o,reviewHolder:C,mountScreenPreview:P,get stopped(){return q},get answers(){return E},suspend(t){V?.setSuspended(t)},resetScreen(){S="",_="",x=""},enqueue:Y,fail:H}),ee=Ee({client:n.client,expected:B,fail:H,get stopped(){return q},get reviewing(){return F.active},get key(){return S},get busy(){return i}}),ne=Pe({client:n.client,expected:B,perform:W,onIntent:n.onCustomerDataIntent,get stopped(){return q},get busy(){return i},get document(){return g?.document},get answers(){return E}}),oe=t=>t&&(t.screen||t.paywall)?`${t.id}:${t.nodeId}:${t.visit}`:"";function X(){let t=n.client.view;c.disabled=!F.active&&(i>0||!!n.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!oe(t)||_!==oe(t))}async function W(t,R=!1){if(!(i&&!R||q||F.active&&!R)){i++,s.setAttribute("aria-busy","true"),X(),r.hidden=!0,h=null;try{if(!R&&ee.inFlight){let N=n.client.view;await ee.inFlight;let U=n.client.view;if(!N||!U||U.id!==N.id||U.nodeId!==N.nodeId||U.visit!==N.visit||U.stopped||!["running","waiting"].includes(U.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(q)return;let Q=await t();q||await Y(n.client.view??Q.run)}catch(Q){H(Q,n.client.pendingCommand?.requestId??null)}finally{i=Math.max(0,i-1),s.setAttribute("aria-busy",String(i>0)),q||(A.hidden=n.client.pendingCommand===null,X())}}}function te(){I&&clearTimeout(I),!(q||!L||!["running","waiting"].includes(L.status)&&!n.client.pendingCommand)&&(I=setTimeout(()=>{I=null,ce().finally(te)},L.pendingRequest||n.client.pendingCommand?1500:5e3))}async function ce(){if(!(q||a||i)){if(F.active){await F.open(F.receipt);return}a=!0;try{let t=n.client.pendingCommand;t&&n.client.settle&&await n.client.settle(t.requestId);let R=n.client.view,Q=ne.queries,N=await n.client.get(R?.screen&&Object.keys(Q).length?{nodeId:R.nodeId,visit:R.visit,revision:R.revision,components:Q}:void 0);!q&&Q===ne.queries&&await Y(n.client.view??N.run)}catch(t){H(t)}finally{a=!1}}}function Se(t){let R=t.screen?.presentation;if(!R||R.type==="inline"){O.open&&O.close(),s.parentElement!==e&&e.append(s);return}s.parentElement!==O&&(O.append(s),e.append(O));let Q={sm:420,md:640,lg:900};O.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in R?Q[R.size]+"px":"100vw"}`,O.setAttribute("aria-label",g?.document?.name??t.screen?.content.document.name??"Funnel"),O.open||O.showModal()}async function Fe(t){if(q)return;L=t,h&&n.client.pendingCommand?.requestId!==h&&(r.hidden=!0,h=null);let R=t.locale.startsWith("zh");if($.textContent=R?"\u56DE\u770B":"History",$.hidden=!n.client.review,c.textContent=F.active?R?"\u8FD4\u56DE\u5F53\u524D":"Return to current":R?"\u8FD4\u56DE":"Back",T.textContent=R?"\u5173\u95ED":"Close",A.textContent=R?"\u91CD\u8BD5":"Retry",X(),A.hidden=n.client.pendingCommand===null,d.textContent=t.pendingRequest?R?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?R?"\u7B49\u5F85\u4E2D":"Waiting":"",l!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(l=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,z(n.onState,structuredClone(t))),!t.pendingRequest&&["closed","ineligible","failed"].includes(t.status)){Z();return}if(t.stopped||n.client.configurationReady===!1){F.stop(),g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S="",_="",x="",j="",O.open&&O.close(),s.hidden=!0,te();return}if(s.hidden=!1,F.active){te();return}let Q=oe(t);if(Q!==S&&(_="",g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S=Q,x="",j="",E={...t.answers},ne.reset()),Se(t),t.screen){let U=t.screen.content;g||(g=P(o,{mode:"live",rendererUrl:n.client.webViewUrl,title:U.document.name,onAction(G,se={},ae={}){if(F.active)return;E={...E,...ae};let Te=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:re})=>Object.hasOwn(E,re)).map(({variable:re})=>[re,E[re]]));W(()=>n.client.submit({operation:"submit",...B(),input:{type:"screen",output:G,answers:Te,selection:se}}))},onAnswers:G=>{F.active||(E={...E,...G})},onCustomerDataIntent:G=>{F.active||ne.intent(G).catch(H)},onEscape:()=>{F.active||ie()},onError:G=>H(new Error(G)),onRendered:()=>ee.report(Q)}));let M={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:E,values:t.screen.values}},K=JSON.stringify([U,t.locale,M.parameters,t.screen.inputs,t.screen.values]);if(K!==x)g.update(U.document,t.locale,M),x=K,J=JSON.stringify(M.capabilities),j=JSON.stringify(M.customerData);else{let G=JSON.stringify(M.capabilities);G!==J&&(g.updateCapabilities(M.capabilities),J=G),JSON.stringify(M.customerData)!==j&&(g.updateCustomerData(M.customerData),j=JSON.stringify(M.customerData))}await g.ready}else if(t.paywall&&!V){let U=await y(o,{canInteract:()=>!F.active&&!q,start:async()=>Ce(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:M=>n.onOpenUrl?n.onOpenUrl({receiptId:t.paywall.receiptId,url:M,openIn:"same_window"}):u.defaultView?.location.assign(M),onAction:async M=>{if(F.active)return;let K=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision,input:{type:"screen",output:M,answers:{}}});await Y(n.client.view??K.run)},onError:H,onDismiss:()=>{!F.active&&!q&&n.client.view?.visit===t.visit&&ie()}});q?U.host?.destroy():(V=U.host,V?.setSuspended(F.active)),ee.report(Q)}if(q)return;_=Q,X();let N=t.instruction;if(N&&(N.type==="open_url"||N.type==="event")&&!k.has(N.receiptId)){let U=u.createElement("button");U.type="button",U.textContent=N.type==="open_url"?`${R?"\u524D\u5F80":"Continue to"} ${new URL(N.url).host}`:R?"\u7EE7\u7EED":"Continue",U.onclick=()=>{let M=B(),K=N.type==="open_url"&&!n.onOpenUrl&&N.openIn==="new_window"?Ne(N.url):null;W(async()=>{let G="success";if(N.type==="open_url")if(n.onOpenUrl)try{G=await n.onOpenUrl({receiptId:N.receiptId,url:N.url,openIn:N.openIn})===!1?"failed":"opened"}catch(ae){z(n.onError,ae),G="failed"}else G=N.openIn==="new_window"&&!K?"failed":"opened";if(N.type==="event"){if(!n.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(N.event)}if(q||n.client.view?.nodeId!==M.nodeId||n.client.view.visit!==M.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let se=await n.client.submit({operation:"submit",...M,input:{type:"client_action",receiptId:N.receiptId,outcome:G}});return k.add(N.receiptId),N.type==="open_url"&&!n.onOpenUrl&&N.openIn==="same_window"&&u.defaultView?.location.assign(N.url),se})},o.replaceChildren(U)}!t.pendingRequest&&t.status==="completed"&&!k.has(`complete:${t.id}`)&&(k.add(`complete:${t.id}`),z(n.onComplete,structuredClone(t))),te()}function Ne(t){let R=u.defaultView?.open(t,"_blank")??null;return R&&(R.opener=null),R}function Y(t){return X(),w=w.catch(()=>{}).then(()=>Fe(t)),w}let Oe=n.client.subscribe(t=>{n.client.configurationReady===!1&&(s.hidden=!0,g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S="",_="",x="",j="",O.open&&O.close()),Y(t).catch(H)}),ke=n.client.subscribeError?.(H);function ie(){return v||(q?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(Z(),Promise.resolve()):(v=W(()=>n.client.submit({operation:"close",...B()}),!0).then(()=>{n.client.view?.status==="closed"&&Z()}).finally(()=>{v=null}),v))}function Z(){p?.destroy(),!q&&(q=!0,I&&clearTimeout(I),Oe(),ke?.(),g?.destroy(),F.stop(),V?.destroy(),O.close(),O.remove(),s.remove(),f instanceof HTMLElement&&f.isConnected&&f.focus(),z(n.onDismiss,L?structuredClone(L):null))}c.onclick=()=>{if(!c.disabled){if(F.active){F.exit();return}W(()=>n.client.submit({operation:"back",...B()}))}},$.onclick=()=>{F.open()},T.onclick=()=>{ie()},A.onclick=()=>{W(()=>n.client.retry())},O.addEventListener("cancel",t=>{t.preventDefault(),ie()});try{let t=await n.client.get();await Y(n.client.view??t.run)}catch(t){throw Z(),t}return{destroy:Z,refresh:ce,review:F.open,exitReview:F.exit,get unappliedDrafts(){return F.drafts}}}export{De as a,rn as b};