@tinkerlandai/longplay-sdk 0.10.4 → 0.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.md +6 -2
- package/dist/{chunk-ACF2FBUB.js → chunk-5BWSWP6H.js} +1 -1
- package/dist/{chunk-KBM7BYQY.js → chunk-5FAUO337.js} +1 -1
- package/dist/{chunk-HOW7NIIR.js → chunk-ABL2UMTI.js} +1 -1
- package/dist/{chunk-SBPTOOYB.js → chunk-BEBSMWPR.js} +1 -1
- package/dist/{chunk-2HFA34QO.js → chunk-EK6IPAY5.js} +2 -2
- package/dist/chunk-FSTRGSM5.js +1 -0
- package/dist/{chunk-RE6BIFLN.js → chunk-KMCA4Y2Q.js} +1 -1
- package/dist/{chunk-MRN4HP4W.js → chunk-MSOVR5KN.js} +1 -1
- package/dist/{chunk-G56XGVMS.js → chunk-O3FHA25D.js} +1 -1
- package/dist/{chunk-VMM3GA3L.js → chunk-OHYC6K3A.js} +1 -1
- package/dist/{chunk-ZPZVSC4J.js → chunk-QOUOTUVB.js} +1 -1
- package/dist/{chunk-X6BCUINI.js → chunk-ZDT32X4G.js} +1 -1
- package/dist/{chunk-YQHPEP4X.js → chunk-ZEEDAM4H.js} +1 -1
- package/dist/{chunk-JB46ZKGZ.js → chunk-ZIUBXO6M.js} +1 -1
- package/dist/{content-NYMIZRNR.js → content-QPJOW6OT.js} +1 -1
- package/dist/funnel-runtime-host-EHYY7OIZ.js +1 -0
- package/dist/index.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-EJCNWDHK.js → paywall-EYRLWKC5.js} +1 -1
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-KOKMHO6R.js +1 -0
- package/dist/server.js +1 -1
- package/dist/visual-dom-YGLIHSKU.js +1 -0
- package/dist/visual.js +1 -1
- package/package.json +10 -9
- package/dist/chunk-VOEFXEPP.js +0 -1
- package/dist/funnel-runtime-host-UL4DEJDU.js +0 -1
- package/dist/screen-renderer-JMHV4GPP.js +0 -1
- package/dist/visual-dom-DQLPBZ2Z.js +0 -1
- /package/dist/{chunk-XSVQHPQT.js → chunk-BI4R5Q7Z.js} +0 -0
- /package/dist/{chunk-CLXORAOK.js → chunk-MPE7OZTE.js} +0 -0
- /package/dist/{chunk-7DXL3LHT.js → chunk-XVT5BKJW.js} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.5 — 2026-11-01
|
|
4
|
+
|
|
5
|
+
- Make IAM Funnel entries recover from configuration timeouts, delayed scene changes, hidden retained pages and earlier refused entries; recheck the selected scene before mounting a Run.
|
|
6
|
+
- Accept up to 100 deduplicated Funnel page assignments so eligible changesets are no longer truncated at 20. Requires the matching GOP contract and IAM reliability SQL migration; wire protocol stays `0.10`.
|
|
7
|
+
|
|
3
8
|
## 0.10.4 — 2026-10-31
|
|
4
9
|
|
|
5
10
|
- Add Longplay public package names, `createLongplay*` factories, error/options aliases, browser readiness and native/Python entry points. Retain legacy exports, commands, downloads, protocol and saved identities; publication is a separate release step.
|
package/README.md
CHANGED
|
@@ -69,8 +69,8 @@ The SDK sends current protocol and SDK version headers and validates the protoco
|
|
|
69
69
|
|
|
70
70
|
## Public entry points
|
|
71
71
|
|
|
72
|
-
| Import
|
|
73
|
-
|
|
|
72
|
+
| Import | Purpose |
|
|
73
|
+
| ----------------------------------------- | ---------------------------------------------------------------------------------- |
|
|
74
74
|
| `@tinkerlandai/longplay-sdk` | Browser Customer, Funnel, Feature, and standalone Paywall clients |
|
|
75
75
|
| `@tinkerlandai/longplay-sdk/server` | Trusted Node.js backend, Customer Sessions, business writes, and Funnel decisions |
|
|
76
76
|
| `@tinkerlandai/longplay-sdk/react-native` | Portable Customer core and authenticated-backend usage relay; no DOM presentation |
|
|
@@ -394,8 +394,12 @@ entries.destroy();
|
|
|
394
394
|
|
|
395
395
|
The host observes original button behavior, matches unique render/element guards and attempts automatic entries once per pathname visit. GOP selects the Funnel, checks entry publication, suppresses an existing Customer/Funnel Run and enforces the automatic-entry cooldown. The host retains unknown requests in memory; page reload recovery is not included. When a Run is stopped from Console or expires, the host removes its UI and reports `run_ended`, whether the Run reads `closed` or its next command is refused with `FORBIDDEN`; a later trigger can then start again. An IAM binding supplies no Customer credential or business permission.
|
|
396
396
|
|
|
397
|
+
The entry scope is the route template plus render, covering every matching dynamic URL instance. Query/hash changes do not create a new visit. Supported anchor and inline-display changes recheck delayed scenes; hidden retained pages do not block the single active button. Multiple active targets remain refused. Configuration fetch/body reads default to a five-second deadline (`timeoutMs` overrides it), recover on the next 15-second poll, and discard late responses. Inspect `onStatus` for `identity_required`, `configuration_unavailable`, `incompatible` and `start_failed`. Definitively refused entries allow the next matching entry in delivered order; pending unknown starts wait for `retry()`. Other entries are preserved while a Run is mounted and reconsidered when it ends. Original button navigation continues, so full-page navigation can prevent presentation.
|
|
398
|
+
|
|
397
399
|
An opted-in Split (`applyPageExperiment: true`) uses its accepted experiment variation for the merchant page. The entry host automatically shares `appManifestRelease` with `showFunnelRun`; manual hosts pass that option explicitly. `createFunnelPageExperiments({client, appManifestRelease})` is available for hosts without the standard UI. The consumer never rebuckets, reports use against the accepted receipt, and reverts on stop, completion or destruction. A separately installed visual consumer yields ownership of that experiment during the Run. This Web source feature requires matching GOP contracts and the IAM/Funnel database migration; installation alone does not promote runtime support.
|
|
398
400
|
|
|
401
|
+
All eligible changesets are delivered within the visual payload's existing 100-item/2 MiB budget, with one assignment per accepted Split receipt and up to 100 assignments. More than 20 distinct assignments require the matching GOP response contract and SDK before the SQL is activated. Used-receipt requests keep their existing 20-ID limit. After a source upgrade, check **Version applicability** in the App page map: invalid published Funnel entries link to the affected Funnel for reselection and publication. Missing current versions, read failures and incomplete inventories remain explicit. Follow the [two-layer integration guide](https://longplayai.com/docs/iam?lang=en#funnel-entries) for build binding and host lifecycle.
|
|
402
|
+
|
|
399
403
|
## Funnel-scoped resource requests
|
|
400
404
|
|
|
401
405
|
Formal Local Runs submit advance signals to Longplay; the canonical executor supplies the original Run/node/visit/receipt when it issues a Coupon or performs commerce. An application consuming a pure Funnel result can bind its Customer client explicitly:
|
|
@@ -1 +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
|
+
import{a as pe}from"./chunk-XVT5BKJW.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 +1 @@
|
|
|
1
|
-
import{a as u,b as Y,l as W,o as $}from"./chunk-JB46ZKGZ.js";import{N as Q,Qa as K,a as J,b as H,c as z,d as U,e as B,f as G,j,na as i,pa as L}from"./chunk-2HFA34QO.js";import{qa as a}from"./chunk-ACF2FBUB.js";import{a as M}from"./chunk-G56XGVMS.js";var x=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new a("INVALID_STATE","Installation sequence exhausted");return t+1},me=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function V(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new a("INVALID_STATE","Installation journal is invalid");return e({...n})})}function X(t,e,n){let r=null,d=0,p=0,c=0,m=Promise.resolve();if(t&&(!n||M.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new a("SCOPE_MISMATCH","Push installation belongs to another scope");let A=()=>{if(!t)throw new a("NOT_CONFIGURED","Configure this client's native Push host first");return t},h=o=>{if(o!==d)throw new a("IDENTITY_CHANGED","Identity changed during Push operation")};async function T(o){let s=A();if(!s.sha256&&!globalThis.crypto?.subtle)throw new a("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let l=s.sha256?await s.sha256(Uint8Array.from(o,f=>f.charCodeAt(0))):await me(o);if(!/^[a-f0-9]{64}$/.test(l))throw new a("INVALID_STATE","Push credential digest is invalid");return l}function C(o){let s=B.parse(o);if(s.installationId.toLowerCase()!==A().installationId.toLowerCase())throw new a("INVALID_RESPONSE","Push response belongs to another installation");return s}async function R(o,s){let l=A(),f={installationId:l.installationId,publicKey:l.publicKey,issuedAt:new Date().toISOString(),...s},g=await l.sign(G(o,l.scope,f));return{...f,signature:g}}let k=(o,s,l)=>e.requestWithCredential?e.requestWithCredential(o,s,l):e.request(o,s);async function S(){let o=A(),s=d,l=r?await(e.session?.access()??r):null,f=V(o,y=>y),g;if(f.detachSeq!==null){let y=f.detachSeq,b=J.parse(await R("detach",{sequence:y,platform:o.platform}));try{let w=await e.request("push/installations/detach",{...o.scope,...b},"POST",{installationDetach:!0});if(!w||typeof w!="object"||!("installation"in w))throw new a("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=C(w.installation);if(_.bound||_.identitySeq!==y)throw new a("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(w){if(w instanceof a&&w.status===404)g=w;else if(!(w instanceof a)||w.status!==412)throw w}g||V(o,w=>({...w,detachSeq:w.detachSeq===y?null:w.detachSeq}))}if(h(s),!l){if(g)throw g;return null}let E=i.bindPushInstallation,N=E.request.parse(await R("bind",{sequence:c,platform:o.platform,credentialDigest:await T(l)}));h(s);let D=E.response.parse(await k(E.path,N,l));h(s);let v=C(D.installation);if(!v.bound||v.identitySeq!==c)throw new a("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return g&&f.detachSeq!==null&&c>f.detachSeq&&V(o,y=>({...y,detachSeq:y.detachSeq===f.detachSeq?null:y.detachSeq})),v}async function P(){A();let o=d,s=r?await(e.session?.access()??r):null;if(!s)throw new a("NOT_IDENTIFIED","Identify before reading this installation");let l=i.readPushInstallation,f=l.request.parse(await R("read",{credentialDigest:await T(s)}));h(o);let g=l.response.parse(await k(l.path,f,s));return h(o),C(g.installation)}function O(o=S){let s=m.catch(()=>{}).then(o);return m=s,s.catch(l=>{try{t?.onError?.(l instanceof Error?l:new Error("Push synchronization failed"))}catch{}}),s}async function q(o,s,l){let f=A(),g=s.identity,E=s.observation,N=r?await(e.session?.access()??r):null;if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");if(!N)throw new a("NOT_IDENTIFIED","Identify before recovering a Push address");if(!o.connectionId||!o.kind||!o.token||!["granted","provisional"].includes(o.permission))throw new a("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await O(async()=>{if(h(g),await S(),h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let D=V(f,_=>l?_:{..._,addressSeq:x(_.addressSeq)}),y=await R(l?"recovery_confirm":"recovery_request",{...o,sequence:D.addressSeq,credentialDigest:await T(N),...l?{challenge:l}:{}}),b=l?z.parse(y):H.parse(y);if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let w=await k(`push/installations/recovery/${l?"confirm":"request"}`,b,N);if(h(g),E!==p||V(f,_=>_).addressSeq!==D.addressSeq)throw new a("INVALID_STATE","Push observation changed during recovery");if(l){let _=i.updatePushAddress.response.parse(w),F=C(_.installation);if(!F.bound||F.identitySeq!==c||F.addressSeq!==D.addressSeq||F.connectionId!==o.connectionId||F.addressStatus!=="active")throw new a("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return F}if(!w||typeof w!="object"||!("recovery"in w))throw new a("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return U.parse(w.recovery)})}return{recoveryObserver(){A();let o={identity:d,observation:++p};return{async request(s){return U.parse(await q(s,o))},async confirm(s,l){return B.parse(await q(l,o,s))}}},identify(o){if(!t)return;c=V(t,l=>({...l,identitySeq:x(l.identitySeq)})).identitySeq,r=o,d++,p++},reset(){if(t)try{V(t,o=>{let s=x(o.identitySeq);return{...o,identitySeq:s,detachSeq:s}})}finally{r=null,d++,p++}},start(){t&&O()},async sync(){return await O()},read:P,async recover(){let o=A(),s=d,l=c;return p++,await O(async()=>{h(s);let f=await P();return h(s),c=V(o,E=>{if(E.identitySeq!==l)throw new a("IDENTITY_CHANGED","A newer installation intent exists");return{...E,identitySeq:x(Math.max(E.identitySeq,f.identitySeq)),addressSeq:Math.max(E.addressSeq,f.addressSeq)}}).identitySeq,await S()})},tokenObserver(){A();let o=++p,s=d;return async l=>{if(o!==p||s!==d)return null;let f=A(),g=r?await(e.session?.access()??r):null;if(!g)throw new a("NOT_IDENTIFIED","Identify before registering a Push token");if(await O(),h(s),o!==p)return null;let E=V(f,y=>({...y,addressSeq:x(y.addressSeq)})),N=i.updatePushAddress,D=N.request.parse(await R("address",{...l,sequence:E.addressSeq,credentialDigest:await T(g)}));if(h(s),o!==p)return null;let v=N.response.parse(await k(N.path,D,g));return h(s),C(v.installation)}}}}function Z(t,e){return{messaging:{async preference(n){let r=i.readMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse(n))).preference}},push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){let n=i.readMessagingPreference;return n.response.parse(await t(n.path,{channel:"push"})).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}function ee(t,e,n={}){let r=!!t.session.peek(),d=new Set,p=c=>{for(let m of d)try{m(c)}catch{}};return t.session.subscribeIdentity(()=>{r=!!t.session.peek(),p(r),n.afterChange?.()},()=>{r=!1,e()}),{isIdentified:()=>r,methods:{subscribeIdentity(c){return d.add(c),()=>{d.delete(c)}},identify(c){let m=typeof c=="string"?c:c.accessToken;if(!j.test(m))throw new a("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(m),t.identify(c)},reset(){try{n.beforeReset?.()}finally{t.reset()}}}}}function I(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new a("INVALID_REQUEST","Customer requests use the verified session identity")}function te(t){return{async checkEntitlement(e){I(e);let n=i.checkEntitlement;return u(t,n,e)},async readHoldings(e={}){let n=i.readHoldings;return u(t,{...n,request:n.request.omit({customerId:!0})},e)}}}function ne(t){return{async readLedger(e){let n=i.readLedger;return u(t,n,{query:e})},async readCreditStatement(e){I(e);let n=i.readCreditStatement;return u(t,n,e)},async quoteBalance(e){I(e);let n=i.quoteBalance;return u(t,n,{command:e})}}}function re(t){return{async setupPayment(e){I(e);let n=i.setupPayment;return u(t,n,e)},async readPaymentSetup(e){I(e);let n=i.readPaymentSetup;return u(t,n,e)},async readBillingInvoice(e){I(e);let n=i.readBillingInvoice;return u(t,n,e)},async readBillingControls(e={}){I(e);let n=i.readBillingControls;return u(t,n,e)},async prepareBillingAuthorization(e){I(e);let n=i.prepareBillingAuthorization;return u(t,n,e)},async confirmBillingAuthorization(e){I(e);let n=i.confirmBillingAuthorization;return u(t,n,e)},async setBillingCoupons(e){I(e);let n=i.setBillingCoupons;return u(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){I(e);let n=i.revokeBillingAuthorization;return u(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){I(e);let n=i.listBillingInvoices;return u(t,n,e)},async confirmBillingAdjustment(e){I(e);let n=i.confirmBillingAdjustment;return u(t,n,e)}}}function ie(t){return{async previewUpdate(e){I(e);let n=i.previewUpdate;return u(t,n,e)},async update(e){I(e);let n=i.update;return u(t,n,e)},async readSubscriptionUpdate(e){I(e);let n=i.readSubscriptionUpdate;return u(t,n,e)},async restoreNativePurchase(e){I(e);let n=i.restoreNativePurchase;return u(t,n,e)},async previewAttach(e){I(e);let n=i.previewAttach;return u(t,n,e)},async attach(e){I(e);let n=i.attach;return u(t,n,e)},async readSubscriptionOperation(e){I(e);let n=i.readSubscriptionOperation;return u(t,n,e)}}}function oe(t){return{async redeemReward(e){return I(e),(await u(t,i.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return I(e),(await u(t,i.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return I(e),(await u(t,i.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await u(t,i.listOffers,{},{response:"Invalid offers response"})).offers}}}function se(t){return{...te(t),...ne(t),...re(t),...ie(t),...oe(t)}}function ae(t){return{async resolveContent(e){I(e);let n=i.resolveContent;return u(t,n,e)},async resolvePaywall(e){I(e);let n=i.resolvePaywall;return u(t,n,e)},async resolveOffering(e){I(e);let n=i.resolveOffering;return u(t,n,e)}}}var ce=t=>new TextEncoder().encode(JSON.stringify(t)).length,ue=16384;function de(t,e){let n=0,r,d=S=>{r={config:structuredClone(S),until:Date.now()+3e4}},p=[],c=null,m;function A(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}function h(){m||!p.length||(m=setTimeout(()=>{m=void 0,C().catch(()=>{}).finally(h)},5e3),typeof m=="object"&&"unref"in m&&m.unref())}function T(S,P={},O={}){if(A(),r&&Date.now()<r.until&&!Q(r.config,S))return;k();let q=i.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:S,properties:P,...O}]}).events[0];if(ce({events:[q]})>ue)throw new a("INVALID_REQUEST","Event exceeds the delivery size limit");if(p.length>=500)throw new a("EVENT_QUEUE_FULL","Flush pending events before tracking more");p.push(structuredClone(q)),h()}async function C(S=!1){if(A(),c)return c;let P=n,O=(async()=>{let q={inserted:0,duplicates:0,rejected:0,skipped:0},o=p.length;for(;o&&P===n;){let s=[];for(let g of p.slice(0,Math.min(o,100))){if(s.length&&ce({events:[...s,g]})>ue)break;s.push(g)}let l=i.trackEvents,f=await u(t,l,{events:s},void 0,{keepalive:S});if(P!==n)throw new a("IDENTITY_CHANGED","Event identity changed during delivery");if(f.inserted+f.duplicates+f.rejected+f.skipped!==s.length)throw new a("INVALID_RESPONSE","Incomplete event acknowledgement");d(f.analyticsConfig),p.splice(0,s.length),o-=s.length,q.inserted+=f.inserted,q.duplicates+=f.duplicates,q.rejected+=f.rejected,q.skipped+=f.skipped}return q})();c=O;try{return await O}finally{c===O&&(c=null)}}let R;function k(){if(R||typeof document>"u")return;let S=()=>{document.visibilityState==="hidden"&&e()&&p.length&&C(!0).catch(()=>{})};document.addEventListener("visibilitychange",S),R=()=>document.removeEventListener("visibilitychange",S)}return{rememberConfiguration:d,track(S,P,O={}){return k(),T(S,P,O)},flush:C,reset(){n++,r=void 0,clearTimeout(m),m=void 0,p=[],c=null},detachVisibility(){R?.(),R=void 0}}}function pe(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function ye(t){let e=pe(t),{merchandiseId:n,merchandise:r,...d}=t;return{...d,...e?{merchandise:e}:{}}}function le(t,e,n,r,d){if(d&&r&&(d.scope.projectId!==r.projectId||d.scope.environment!==r.environment))throw new a("SCOPE_MISMATCH","Configuration belongs to another App/environment");let p=0,c=new Set;function m(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}async function A(h={}){d||m();let T=p,C=!1,R=async()=>{if(C||T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let v=i.getFeatures,y=d?{scope:{projectId:d.scope.projectId,environment:d.scope.environment},payload:await d.features()}:await u(t,v,{});if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");if(r&&(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment))throw new a("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(y.payload.analyticsConfig),y},k=await R(),S=!0,P,O=v=>{try{h.onError?.(v)}catch{}},q=(v,y,b)=>{try{let w=pe(b);n.track(v,y,w?{merchandise:w}:{})}catch(w){O(w)}},o=Y({assertUsable:d?.assertFeatures,scope:k.scope,attributes:h.attributes,onError:h.onError,load:async()=>S?(S=!1,k.payload):(await R()).payload,evaluateRemote:async v=>{if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let y=i.evaluateFeatures,b=await u(t,y,{...v,attributes:ye(v.attributes)});if(b.scope.projectId!==k.scope.projectId||b.scope.environment!==k.scope.environment)throw new a("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:b.generation,evaluatedAt:b.evaluatedAt,expiresAt:b.expiresAt,features:b.features,...b.merchandiseContext?{merchandiseContext:b.merchandiseContext}:{}}},onExperimentViewed:(v,y,b)=>q("Experiment Viewed",{experimentId:v.key,variationId:y.key},b),onFeatureUsage:(v,y,b)=>q("Feature Evaluated",{feature:v,value:y.value,source:y.source,ruleId:y.ruleId,...y.experimentResult?{variationId:y.experimentResult.key}:{}},b)}),s=o.refresh;function l(){clearTimeout(P),!d&&(C||T!==p||!o.expiresAt||(P=setTimeout(()=>{f().catch(O)},Math.min(2147483647,Math.max(1e3,Date.parse(o.expiresAt)-Date.now()))),typeof P=="object"&&"unref"in P&&P.unref()))}async function f(){try{return await s()}finally{l()}}let g=()=>{C||f().catch(O)},E=o.subscribe(l),N=d?.subscribe(()=>{!C&&d.fresh&&f().catch(O)});function D(){C||(C=!0,clearTimeout(P),typeof window<"u"&&window.removeEventListener("focus",g),E(),N?.(),o.reset(),c.delete(D))}c.add(D);try{await o.init(),(h.attributes?.merchandise||h.attributes?.merchandiseId)&&await o.refreshRemote()}catch(v){throw D(),v}return l(),!d&&typeof window<"u"&&window.addEventListener("focus",g),Object.assign(o,{refresh:f,destroy:D})}return{features:A,reset(h){p++,h();for(let T of c)T()}}}import{z as Ie}from"zod";function fe(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=Ie.object({funnelId:L.shape.id,funnelVersionId:L.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new a("INVALID_REQUEST","A valid Funnel source is required");let d=Object.freeze(r.data);function p(c){if("customerId"in c)throw new a("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in c&&c.funnelId!==void 0&&c.funnelId!==d.funnelId||"funnelVersionId"in c&&c.funnelVersionId!==void 0&&c.funnelVersionId!==d.funnelVersionId)throw new a("SCOPE_MISMATCH","The original Funnel source cannot change");return{...c,...d}}return{async claimCoupon(c,m=crypto.randomUUID()){let A=i.grantOffer,h=await u(t,A,p({couponId:c,requestId:m}));return{offer:h.offer,reason:h.reason}},async resolveOffering(c){let m=i.resolveOffering;return u(t,m,p(c))},async resolvePaywall(c){let m=i.resolvePaywall;return u(t,m,p(c))},async previewAttach(c){let m=i.previewAttach;return u(t,m,p(c))}}}function Pt(t){return he(t)}function he(t){let e=K(t),n=e.request,r=X(t.push,e,t.scope??t.configuration?.scope),d=ee(e,()=>{c.reset(p.reset),p.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),p=de(n,d.isIdentified),c=le(n,d.isIdentified,p,t.scope,t.configuration);return{session:e.session,...Z(n,r),...se(n),...ae(n),forFunnel(m){return fe(n,m)},async features(m={}){return c.features(m)},track(m,A,h={}){return p.track(m,A,h)},flush(){return p.flush()},...d.methods}}function Nt(t){if(!j.test(t.customerToken))throw new a("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new a("INVALID_REQUEST","An explicit App and environment scope is required");let e=$({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),d=W({...t,runToken:r.runToken});d.identify(t.customerToken);let p=r.run.instruction?.type==="evaluate_segment"?await d.get():r;return{...r,...p,controller:d}}}}export{Pt as a,he as b,Nt as c};
|
|
1
|
+
import{a as u,b as Y,l as W,o as $}from"./chunk-ZIUBXO6M.js";import{N as Q,Qa as K,a as J,b as H,c as z,d as U,e as B,f as G,j,na as i,pa as L}from"./chunk-EK6IPAY5.js";import{qa as a}from"./chunk-5BWSWP6H.js";import{a as M}from"./chunk-O3FHA25D.js";var x=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new a("INVALID_STATE","Installation sequence exhausted");return t+1},me=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function V(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new a("INVALID_STATE","Installation journal is invalid");return e({...n})})}function X(t,e,n){let r=null,d=0,p=0,c=0,m=Promise.resolve();if(t&&(!n||M.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new a("SCOPE_MISMATCH","Push installation belongs to another scope");let A=()=>{if(!t)throw new a("NOT_CONFIGURED","Configure this client's native Push host first");return t},h=o=>{if(o!==d)throw new a("IDENTITY_CHANGED","Identity changed during Push operation")};async function T(o){let s=A();if(!s.sha256&&!globalThis.crypto?.subtle)throw new a("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let l=s.sha256?await s.sha256(Uint8Array.from(o,f=>f.charCodeAt(0))):await me(o);if(!/^[a-f0-9]{64}$/.test(l))throw new a("INVALID_STATE","Push credential digest is invalid");return l}function C(o){let s=B.parse(o);if(s.installationId.toLowerCase()!==A().installationId.toLowerCase())throw new a("INVALID_RESPONSE","Push response belongs to another installation");return s}async function R(o,s){let l=A(),f={installationId:l.installationId,publicKey:l.publicKey,issuedAt:new Date().toISOString(),...s},g=await l.sign(G(o,l.scope,f));return{...f,signature:g}}let k=(o,s,l)=>e.requestWithCredential?e.requestWithCredential(o,s,l):e.request(o,s);async function S(){let o=A(),s=d,l=r?await(e.session?.access()??r):null,f=V(o,y=>y),g;if(f.detachSeq!==null){let y=f.detachSeq,b=J.parse(await R("detach",{sequence:y,platform:o.platform}));try{let w=await e.request("push/installations/detach",{...o.scope,...b},"POST",{installationDetach:!0});if(!w||typeof w!="object"||!("installation"in w))throw new a("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=C(w.installation);if(_.bound||_.identitySeq!==y)throw new a("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(w){if(w instanceof a&&w.status===404)g=w;else if(!(w instanceof a)||w.status!==412)throw w}g||V(o,w=>({...w,detachSeq:w.detachSeq===y?null:w.detachSeq}))}if(h(s),!l){if(g)throw g;return null}let E=i.bindPushInstallation,N=E.request.parse(await R("bind",{sequence:c,platform:o.platform,credentialDigest:await T(l)}));h(s);let D=E.response.parse(await k(E.path,N,l));h(s);let v=C(D.installation);if(!v.bound||v.identitySeq!==c)throw new a("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return g&&f.detachSeq!==null&&c>f.detachSeq&&V(o,y=>({...y,detachSeq:y.detachSeq===f.detachSeq?null:y.detachSeq})),v}async function P(){A();let o=d,s=r?await(e.session?.access()??r):null;if(!s)throw new a("NOT_IDENTIFIED","Identify before reading this installation");let l=i.readPushInstallation,f=l.request.parse(await R("read",{credentialDigest:await T(s)}));h(o);let g=l.response.parse(await k(l.path,f,s));return h(o),C(g.installation)}function O(o=S){let s=m.catch(()=>{}).then(o);return m=s,s.catch(l=>{try{t?.onError?.(l instanceof Error?l:new Error("Push synchronization failed"))}catch{}}),s}async function q(o,s,l){let f=A(),g=s.identity,E=s.observation,N=r?await(e.session?.access()??r):null;if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");if(!N)throw new a("NOT_IDENTIFIED","Identify before recovering a Push address");if(!o.connectionId||!o.kind||!o.token||!["granted","provisional"].includes(o.permission))throw new a("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await O(async()=>{if(h(g),await S(),h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let D=V(f,_=>l?_:{..._,addressSeq:x(_.addressSeq)}),y=await R(l?"recovery_confirm":"recovery_request",{...o,sequence:D.addressSeq,credentialDigest:await T(N),...l?{challenge:l}:{}}),b=l?z.parse(y):H.parse(y);if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let w=await k(`push/installations/recovery/${l?"confirm":"request"}`,b,N);if(h(g),E!==p||V(f,_=>_).addressSeq!==D.addressSeq)throw new a("INVALID_STATE","Push observation changed during recovery");if(l){let _=i.updatePushAddress.response.parse(w),F=C(_.installation);if(!F.bound||F.identitySeq!==c||F.addressSeq!==D.addressSeq||F.connectionId!==o.connectionId||F.addressStatus!=="active")throw new a("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return F}if(!w||typeof w!="object"||!("recovery"in w))throw new a("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return U.parse(w.recovery)})}return{recoveryObserver(){A();let o={identity:d,observation:++p};return{async request(s){return U.parse(await q(s,o))},async confirm(s,l){return B.parse(await q(l,o,s))}}},identify(o){if(!t)return;c=V(t,l=>({...l,identitySeq:x(l.identitySeq)})).identitySeq,r=o,d++,p++},reset(){if(t)try{V(t,o=>{let s=x(o.identitySeq);return{...o,identitySeq:s,detachSeq:s}})}finally{r=null,d++,p++}},start(){t&&O()},async sync(){return await O()},read:P,async recover(){let o=A(),s=d,l=c;return p++,await O(async()=>{h(s);let f=await P();return h(s),c=V(o,E=>{if(E.identitySeq!==l)throw new a("IDENTITY_CHANGED","A newer installation intent exists");return{...E,identitySeq:x(Math.max(E.identitySeq,f.identitySeq)),addressSeq:Math.max(E.addressSeq,f.addressSeq)}}).identitySeq,await S()})},tokenObserver(){A();let o=++p,s=d;return async l=>{if(o!==p||s!==d)return null;let f=A(),g=r?await(e.session?.access()??r):null;if(!g)throw new a("NOT_IDENTIFIED","Identify before registering a Push token");if(await O(),h(s),o!==p)return null;let E=V(f,y=>({...y,addressSeq:x(y.addressSeq)})),N=i.updatePushAddress,D=N.request.parse(await R("address",{...l,sequence:E.addressSeq,credentialDigest:await T(g)}));if(h(s),o!==p)return null;let v=N.response.parse(await k(N.path,D,g));return h(s),C(v.installation)}}}}function Z(t,e){return{messaging:{async preference(n){let r=i.readMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse(n))).preference}},push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){let n=i.readMessagingPreference;return n.response.parse(await t(n.path,{channel:"push"})).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}function ee(t,e,n={}){let r=!!t.session.peek(),d=new Set,p=c=>{for(let m of d)try{m(c)}catch{}};return t.session.subscribeIdentity(()=>{r=!!t.session.peek(),p(r),n.afterChange?.()},()=>{r=!1,e()}),{isIdentified:()=>r,methods:{subscribeIdentity(c){return d.add(c),()=>{d.delete(c)}},identify(c){let m=typeof c=="string"?c:c.accessToken;if(!j.test(m))throw new a("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(m),t.identify(c)},reset(){try{n.beforeReset?.()}finally{t.reset()}}}}}function I(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new a("INVALID_REQUEST","Customer requests use the verified session identity")}function te(t){return{async checkEntitlement(e){I(e);let n=i.checkEntitlement;return u(t,n,e)},async readHoldings(e={}){let n=i.readHoldings;return u(t,{...n,request:n.request.omit({customerId:!0})},e)}}}function ne(t){return{async readLedger(e){let n=i.readLedger;return u(t,n,{query:e})},async readCreditStatement(e){I(e);let n=i.readCreditStatement;return u(t,n,e)},async quoteBalance(e){I(e);let n=i.quoteBalance;return u(t,n,{command:e})}}}function re(t){return{async setupPayment(e){I(e);let n=i.setupPayment;return u(t,n,e)},async readPaymentSetup(e){I(e);let n=i.readPaymentSetup;return u(t,n,e)},async readBillingInvoice(e){I(e);let n=i.readBillingInvoice;return u(t,n,e)},async readBillingControls(e={}){I(e);let n=i.readBillingControls;return u(t,n,e)},async prepareBillingAuthorization(e){I(e);let n=i.prepareBillingAuthorization;return u(t,n,e)},async confirmBillingAuthorization(e){I(e);let n=i.confirmBillingAuthorization;return u(t,n,e)},async setBillingCoupons(e){I(e);let n=i.setBillingCoupons;return u(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){I(e);let n=i.revokeBillingAuthorization;return u(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){I(e);let n=i.listBillingInvoices;return u(t,n,e)},async confirmBillingAdjustment(e){I(e);let n=i.confirmBillingAdjustment;return u(t,n,e)}}}function ie(t){return{async previewUpdate(e){I(e);let n=i.previewUpdate;return u(t,n,e)},async update(e){I(e);let n=i.update;return u(t,n,e)},async readSubscriptionUpdate(e){I(e);let n=i.readSubscriptionUpdate;return u(t,n,e)},async restoreNativePurchase(e){I(e);let n=i.restoreNativePurchase;return u(t,n,e)},async previewAttach(e){I(e);let n=i.previewAttach;return u(t,n,e)},async attach(e){I(e);let n=i.attach;return u(t,n,e)},async readSubscriptionOperation(e){I(e);let n=i.readSubscriptionOperation;return u(t,n,e)}}}function oe(t){return{async redeemReward(e){return I(e),(await u(t,i.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return I(e),(await u(t,i.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return I(e),(await u(t,i.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await u(t,i.listOffers,{},{response:"Invalid offers response"})).offers}}}function se(t){return{...te(t),...ne(t),...re(t),...ie(t),...oe(t)}}function ae(t){return{async resolveContent(e){I(e);let n=i.resolveContent;return u(t,n,e)},async resolvePaywall(e){I(e);let n=i.resolvePaywall;return u(t,n,e)},async resolveOffering(e){I(e);let n=i.resolveOffering;return u(t,n,e)}}}var ce=t=>new TextEncoder().encode(JSON.stringify(t)).length,ue=16384;function de(t,e){let n=0,r,d=S=>{r={config:structuredClone(S),until:Date.now()+3e4}},p=[],c=null,m;function A(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}function h(){m||!p.length||(m=setTimeout(()=>{m=void 0,C().catch(()=>{}).finally(h)},5e3),typeof m=="object"&&"unref"in m&&m.unref())}function T(S,P={},O={}){if(A(),r&&Date.now()<r.until&&!Q(r.config,S))return;k();let q=i.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:S,properties:P,...O}]}).events[0];if(ce({events:[q]})>ue)throw new a("INVALID_REQUEST","Event exceeds the delivery size limit");if(p.length>=500)throw new a("EVENT_QUEUE_FULL","Flush pending events before tracking more");p.push(structuredClone(q)),h()}async function C(S=!1){if(A(),c)return c;let P=n,O=(async()=>{let q={inserted:0,duplicates:0,rejected:0,skipped:0},o=p.length;for(;o&&P===n;){let s=[];for(let g of p.slice(0,Math.min(o,100))){if(s.length&&ce({events:[...s,g]})>ue)break;s.push(g)}let l=i.trackEvents,f=await u(t,l,{events:s},void 0,{keepalive:S});if(P!==n)throw new a("IDENTITY_CHANGED","Event identity changed during delivery");if(f.inserted+f.duplicates+f.rejected+f.skipped!==s.length)throw new a("INVALID_RESPONSE","Incomplete event acknowledgement");d(f.analyticsConfig),p.splice(0,s.length),o-=s.length,q.inserted+=f.inserted,q.duplicates+=f.duplicates,q.rejected+=f.rejected,q.skipped+=f.skipped}return q})();c=O;try{return await O}finally{c===O&&(c=null)}}let R;function k(){if(R||typeof document>"u")return;let S=()=>{document.visibilityState==="hidden"&&e()&&p.length&&C(!0).catch(()=>{})};document.addEventListener("visibilitychange",S),R=()=>document.removeEventListener("visibilitychange",S)}return{rememberConfiguration:d,track(S,P,O={}){return k(),T(S,P,O)},flush:C,reset(){n++,r=void 0,clearTimeout(m),m=void 0,p=[],c=null},detachVisibility(){R?.(),R=void 0}}}function pe(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function ye(t){let e=pe(t),{merchandiseId:n,merchandise:r,...d}=t;return{...d,...e?{merchandise:e}:{}}}function le(t,e,n,r,d){if(d&&r&&(d.scope.projectId!==r.projectId||d.scope.environment!==r.environment))throw new a("SCOPE_MISMATCH","Configuration belongs to another App/environment");let p=0,c=new Set;function m(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}async function A(h={}){d||m();let T=p,C=!1,R=async()=>{if(C||T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let v=i.getFeatures,y=d?{scope:{projectId:d.scope.projectId,environment:d.scope.environment},payload:await d.features()}:await u(t,v,{});if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");if(r&&(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment))throw new a("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(y.payload.analyticsConfig),y},k=await R(),S=!0,P,O=v=>{try{h.onError?.(v)}catch{}},q=(v,y,b)=>{try{let w=pe(b);n.track(v,y,w?{merchandise:w}:{})}catch(w){O(w)}},o=Y({assertUsable:d?.assertFeatures,scope:k.scope,attributes:h.attributes,onError:h.onError,load:async()=>S?(S=!1,k.payload):(await R()).payload,evaluateRemote:async v=>{if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let y=i.evaluateFeatures,b=await u(t,y,{...v,attributes:ye(v.attributes)});if(b.scope.projectId!==k.scope.projectId||b.scope.environment!==k.scope.environment)throw new a("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:b.generation,evaluatedAt:b.evaluatedAt,expiresAt:b.expiresAt,features:b.features,...b.merchandiseContext?{merchandiseContext:b.merchandiseContext}:{}}},onExperimentViewed:(v,y,b)=>q("Experiment Viewed",{experimentId:v.key,variationId:y.key},b),onFeatureUsage:(v,y,b)=>q("Feature Evaluated",{feature:v,value:y.value,source:y.source,ruleId:y.ruleId,...y.experimentResult?{variationId:y.experimentResult.key}:{}},b)}),s=o.refresh;function l(){clearTimeout(P),!d&&(C||T!==p||!o.expiresAt||(P=setTimeout(()=>{f().catch(O)},Math.min(2147483647,Math.max(1e3,Date.parse(o.expiresAt)-Date.now()))),typeof P=="object"&&"unref"in P&&P.unref()))}async function f(){try{return await s()}finally{l()}}let g=()=>{C||f().catch(O)},E=o.subscribe(l),N=d?.subscribe(()=>{!C&&d.fresh&&f().catch(O)});function D(){C||(C=!0,clearTimeout(P),typeof window<"u"&&window.removeEventListener("focus",g),E(),N?.(),o.reset(),c.delete(D))}c.add(D);try{await o.init(),(h.attributes?.merchandise||h.attributes?.merchandiseId)&&await o.refreshRemote()}catch(v){throw D(),v}return l(),!d&&typeof window<"u"&&window.addEventListener("focus",g),Object.assign(o,{refresh:f,destroy:D})}return{features:A,reset(h){p++,h();for(let T of c)T()}}}import{z as Ie}from"zod";function fe(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=Ie.object({funnelId:L.shape.id,funnelVersionId:L.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new a("INVALID_REQUEST","A valid Funnel source is required");let d=Object.freeze(r.data);function p(c){if("customerId"in c)throw new a("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in c&&c.funnelId!==void 0&&c.funnelId!==d.funnelId||"funnelVersionId"in c&&c.funnelVersionId!==void 0&&c.funnelVersionId!==d.funnelVersionId)throw new a("SCOPE_MISMATCH","The original Funnel source cannot change");return{...c,...d}}return{async claimCoupon(c,m=crypto.randomUUID()){let A=i.grantOffer,h=await u(t,A,p({couponId:c,requestId:m}));return{offer:h.offer,reason:h.reason}},async resolveOffering(c){let m=i.resolveOffering;return u(t,m,p(c))},async resolvePaywall(c){let m=i.resolvePaywall;return u(t,m,p(c))},async previewAttach(c){let m=i.previewAttach;return u(t,m,p(c))}}}function Pt(t){return he(t)}function he(t){let e=K(t),n=e.request,r=X(t.push,e,t.scope??t.configuration?.scope),d=ee(e,()=>{c.reset(p.reset),p.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),p=de(n,d.isIdentified),c=le(n,d.isIdentified,p,t.scope,t.configuration);return{session:e.session,...Z(n,r),...se(n),...ae(n),forFunnel(m){return fe(n,m)},async features(m={}){return c.features(m)},track(m,A,h={}){return p.track(m,A,h)},flush(){return p.flush()},...d.methods}}function Nt(t){if(!j.test(t.customerToken))throw new a("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new a("INVALID_REQUEST","An explicit App and environment scope is required");let e=$({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),d=W({...t,runToken:r.runToken});d.identify(t.customerToken);let p=r.run.instruction?.type==="evaluate_segment"?await d.get():r;return{...r,...p,controller:d}}}}export{Pt as a,he as b,Nt as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u}from"./chunk-DSPLGTQI.js";import{b as d}from"./chunk-
|
|
1
|
+
import{a as u}from"./chunk-DSPLGTQI.js";import{b as d}from"./chunk-MSOVR5KN.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{qa as o}from"./chunk-
|
|
1
|
+
import{qa as o}from"./chunk-5BWSWP6H.js";function s(r,n){let i=structuredClone(r);for(let[a,e]of Object.entries(i.plans)){let t=n.plans[a];!t||t.versionId!==e.versionId||(t.amountMinor!==void 0&&(e.amountMinor=t.amountMinor),t.interval!==void 0&&(e.interval=t.interval),t.intervalCount!==void 0&&(e.intervalCount=t.intervalCount),t.prepaid!==void 0&&(e.prepaid=structuredClone(t.prepaid)))}return i}function c(r,n){let i=a=>"document"in a?a.offering.id:a.content.offeringVersionId;return r.id===n.id&&i(r)===i(n)&&r.content?.artifact.sha256===n.content?.artifact.sha256}function l(r,n,i){if(r.operationId!==n.operationId||n.currency!==void 0&&r.currency!==n.currency)throw new o("INVALID_RESPONSE",i)}function p(r,n,i){let a=Object.fromEntries((r.lines[0]?.prepaid??[]).map(e=>[e.internal_feature_id,e.quantity]));if(n.featureQuantities&&(Object.keys(a).length!==Object.keys(n.featureQuantities).length||Object.entries(n.featureQuantities).some(([e,t])=>a[e]!==t)))throw new o("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(r.lines.length!==1||r.lines[0].productVersionId!==n.productVersionId||n.currency!==void 0&&r.currency!==n.currency||n.provider!==void 0&&r.provider!==n.provider&&!(n.provider==="stripe"&&r.provider==="merchant"&&r.execution?.provider==="merchant"))throw new o("INVALID_RESPONSE",i)}function f(r,n,i=!1){return!r||r.operationId!==n?.operationId?n:r.status==="complete"&&n.status!=="complete"||r.status!=="pending"&&(n.status==="pending"||i&&n.status!=="complete")?r:n}export{s as a,c as b,l as c,p as d,f as e};
|