@tinkerlandai/indiana-sdk 0.9.2 → 0.10.1
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 +21 -0
- package/README.md +50 -5
- package/README.zh-CN.md +30 -5
- package/dist/{ai-usage-DMNKvCiq.d.ts → ai-usage-Cn7dhvFw.d.ts} +5 -5
- package/dist/{api--Zf0gxfj.d.ts → api-DC44FaTV.d.ts} +6346 -749
- package/dist/chunk-2Y4G5364.js +6 -0
- package/dist/chunk-6ZZUNGNE.js +1 -0
- package/dist/chunk-ABNSU3ZG.js +4 -0
- package/dist/chunk-ACF2FBUB.js +1 -0
- package/dist/{chunk-65TBYVCS.js → chunk-AHXYGGAA.js} +1 -1
- package/dist/chunk-BOCKPUCM.js +2 -0
- package/dist/chunk-CCPNMQHZ.js +1 -0
- package/dist/chunk-CLXORAOK.js +1 -0
- package/dist/chunk-EDQCH2QS.js +1 -0
- package/dist/chunk-IWWKVNEX.js +1 -0
- package/dist/chunk-QUWPPZHH.js +1 -0
- package/dist/chunk-SBPTOOYB.js +1 -0
- package/dist/chunk-WYZI3TNB.js +1 -0
- package/dist/chunk-X6BCUINI.js +173 -0
- package/dist/chunk-Y46ALAKP.js +1 -0
- package/dist/{configuration-sync-E98CqVwh.d.ts → configuration-sync-CXe9Zcng.d.ts} +74 -21
- package/dist/content-ZRWZ26PF.js +1 -0
- package/dist/coupon-fA1QujHt.d.ts +184 -0
- package/dist/{customer-page-9B97Qdt_.d.ts → customer-page-km5f1PJZ.d.ts} +86 -182
- package/dist/{funnel-local-client-BjPwXlQb.d.ts → funnel-local-client-BQsdOjQ7.d.ts} +19985 -2451
- package/dist/funnel-node-evaluation-P5B4fPfJ.d.ts +2054 -0
- package/dist/funnel-resource-client-Zof1WLgA.d.ts +14525 -0
- package/dist/funnel-runtime-host-N7TX3LWI.js +1 -0
- package/dist/index.d.ts +13905 -13996
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +3 -3
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +4 -4
- package/dist/page.js +1 -1
- package/dist/paywall-DR65VN2G.js +1 -0
- package/dist/popup.d.ts +7 -5
- package/dist/popup.js +1 -1
- package/dist/react-native.d.ts +36432 -174
- package/dist/react-native.js +1 -1
- package/dist/{screen-BITZ11jn.d.ts → screen-D81zCpfi.d.ts} +159 -6
- package/dist/{screen-renderer-A6VYE2QL.js → screen-renderer-ZSAR7LPS.js} +1 -1
- package/dist/server.d.ts +2924 -500
- package/dist/server.js +1 -1
- package/dist/visual-dom-OFB7BFFB.js +1 -0
- package/dist/visual.d.ts +2 -2
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5O667MKA.js +0 -1
- package/dist/chunk-67A7I6MB.js +0 -1
- package/dist/chunk-CCQHYQ4P.js +0 -1
- package/dist/chunk-CPLLMISZ.js +0 -1
- package/dist/chunk-G23YNWWI.js +0 -1
- package/dist/chunk-L7LKE3MG.js +0 -173
- package/dist/chunk-NH2PTTNK.js +0 -2
- package/dist/chunk-PK5HYUHD.js +0 -1
- package/dist/chunk-SEW4YVR7.js +0 -1
- package/dist/chunk-UYSOTMY3.js +0 -1
- package/dist/chunk-WSVH6IQA.js +0 -1
- package/dist/chunk-YZSQDZXW.js +0 -4
- package/dist/content-3LOJVYQO.js +0 -1
- package/dist/errors-0TSUIbUi.d.ts +0 -115
- package/dist/funnel-runtime-host-NYHKQT6T.js +0 -1
- package/dist/paywall-ISCYOGPZ.js +0 -1
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{$ as Zn,A as qi,B as fn,C as as,D as ss,E as cs,F as us,G as ls,H as Pr,I as An,J as ps,K as ds,L as Kn,M as ms,N as hn,O as fs,Q as As,R as hs,S as gs,T as bs,X as Hn,Z as Pt,_ as it,a as Vn,aa as zi,b as La,ba as Tt,c as $a,d as Ga,e as Ka,ea as Ni,f as Ha,g as se,h as Ti,ha as kr,i as Za,ia as Zt,j as ft,ja as xt,k as we,ka as Fi,l as Mi,m as _t,n as Qa,na as Os,o as Or,p as Ja,q as Wa,qa as ue,r as mn,s as es,t as $n,u as ts,v as ns,w as rs,x as Gn,y as is,z as os}from"./chunk-ACF2FBUB.js";import{a as ve,b as ys,c as xs,d as Ss,e as Mt,f as vs,g as Cr,h as Is,i as ws}from"./chunk-G56XGVMS.js";import{a as js,b as _s}from"./chunk-IWWKVNEX.js";import{a as me,b as rt,c as Ht,d as Dt,e as _r}from"./chunk-7DXL3LHT.js";import{c as wr,d as jr,e as Xa,f as Bi,g as Ya,h as Ln}from"./chunk-3PZ4Y6UD.js";import{z as b}from"zod";import{z as f}from"zod";var He=f.string().min(1).max(200),et=f.iso.datetime({offset:!0}),De=f.number().int().nonnegative().max(1e8),Rr=f.string().regex(/^[A-Z]{3}$/),sd=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],Ps=f.enum(sd),Cs=f.strictObject({priceId:f.uuid(),productVersionId:f.uuid(),productId:He,quantity:f.number().int().min(1).max(1e6),unitAmountMinor:De,totalMinor:De,interval:f.enum(["week","month","year","one_off"]),intervalCount:f.number().int().min(1).max(52),kind:f.enum(["fixed","prepaid","seat"]),tiers:f.strictObject({mode:f.enum(["graduated","volume"]),tiers:f.array(f.strictObject({upTo:f.number().int().positive().nullable(),unitAmountMinor:De,flatAmountMinor:De.optional()})).min(2).max(12)}).nullable()}),cd=f.strictObject({grantId:f.uuid(),couponId:f.uuid(),amountMinor:De,terms:f.discriminatedUnion("type",[f.strictObject({type:f.literal("percent"),percentOff:f.number().gt(0).max(100)}),f.strictObject({type:f.literal("amount"),amountOffMinor:De,currency:Rr})]),duration:f.discriminatedUnion("type",[f.strictObject({type:f.literal("once")}),f.strictObject({type:f.literal("forever")}),f.strictObject({type:f.literal("repeating"),months:f.number().int().min(1).max(36)})])}),$i={provider:f.literal("merchant"),executor:f.literal("merchant"),operationId:f.uuid(),customerId:f.uuid(),configurationRevision:f.number().int().nonnegative(),connectionRevision:f.number().int().nonnegative(),currency:Rr,expiresAt:et},Er=f.strictObject({...$i,type:f.literal("purchase"),mode:f.enum(["payment","subscription"]),lineItems:f.array(Cs).min(1).max(100),catalogAmountMinor:De,discount:cd.nullable(),trialPeriodDays:f.number().int().min(1).max(730).nullable(),automaticTax:f.boolean()}).refine(e=>e.lineItems.reduce((t,n)=>t+n.totalMinor,0)===e.catalogAmountMinor&&(!e.discount||e.discount.amountMinor<=e.catalogAmountMinor)&&new Set(e.lineItems.map(t=>t.priceId)).size===e.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),Dr=f.strictObject({...$i,type:f.literal("subscription_change"),subscriptionId:f.uuid(),merchantSubscriptionId:He,membershipId:f.uuid(),subscriptionAction:f.enum(["update","cancel","schedule","release"]),supersedesOperationId:f.uuid().nullable(),change:f.discriminatedUnion("type",[f.strictObject({type:f.literal("cancel")}),f.strictObject({type:f.literal("uncancel")}),f.strictObject({type:f.literal("plan"),productVersionId:f.uuid()}),f.strictObject({type:f.literal("seats"),licenseKey:He,quantity:f.number().int().nonnegative().max(1e6)}),f.strictObject({type:f.literal("quantity"),internal_feature_id:f.uuid(),quantity:f.number().int().nonnegative().max(1e6)}),f.strictObject({type:f.literal("billing_cycle"),billingCycleAnchor:f.union([f.literal("now"),f.number().int().positive()])})]),timing:f.enum(["immediate","renewal"]),effectiveAt:et,creditMinor:De,debitMinor:De,totalMinor:De,discountMinor:De,taxMinor:De,proration:f.enum(["none","create_prorations","always_invoice"]),lineItems:f.array(Cs.extend({quantity:f.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:f.array(f.uuid()).max(100)}),Tr=f.strictObject({...$i,type:f.literal("refund"),invoiceId:f.uuid(),merchantInvoiceId:He,amountMinor:De.refine(e=>e>0),mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),cancelSubscriptions:f.array(He).max(100)}),ks=f.discriminatedUnion("type",[Er,Dr,Tr]);function Gh(e){let t=new Set;if(e.type==="purchase")t.add(e.mode==="subscription"?"purchase.subscription":"purchase.one_time"),e.lineItems.some(n=>n.kind==="prepaid")&&t.add("purchase.prepaid"),e.lineItems.some(n=>n.kind==="seat")&&t.add("purchase.seats"),e.lineItems.some(n=>n.tiers!==null)&&t.add("purchase.tiered"),e.trialPeriodDays!==null&&t.add("purchase.trial"),e.automaticTax&&t.add("tax.automatic"),e.discount&&t.add(`discount.${e.discount.terms.type}.${e.discount.duration.type}`);else if(e.type==="refund")t.add(`refund.${e.mode}`),e.entitlementAction==="revoke"&&t.add("refund.revoke");else{let n=e.change.type;n==="cancel"?t.add(`subscription.cancel.${e.timing}`):n==="uncancel"?t.add("subscription.resume"):n==="plan"?t.add(`subscription.plan.${e.timing}`):t.add(`subscription.${n}`),e.proration!=="none"&&t.add("subscription.proration")}return[...t].sort()}function Kh(e){return e.type==="purchase"?e.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:e.type==="subscription_change"?["subscription.change.completed","subscription.observed",...e.change.type==="cancel"||e.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...e.entitlementAction==="revoke"&&e.cancelSubscriptions.length?["subscription.observed"]:[]]}var Qn=f.strictObject({phase:f.enum(["execution","payment","fulfillment","recording"]),code:Vn,reason:$a.optional(),recovery:La,retryable:f.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ui={operationId:f.uuid(),customerId:f.uuid(),merchantExecutionId:He,fulfillmentStatus:f.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:f.enum(["not_ready","pending","accepted","failed"]),updatedAt:et,problem:Qn.nullable(),pollAfterMs:f.number().int().min(1e3).max(6e4).nullable()},Qt=f.discriminatedUnion("type",[f.strictObject({...Ui,type:f.literal("purchase"),merchantOrderId:He.nullable(),paymentStatus:f.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:et.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),f.strictObject({...Ui,type:f.literal("subscription_change"),status:f.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:He,scheduledFor:et.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),f.strictObject({...Ui,type:f.literal("refund"),status:f.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:He.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),Rs=f.discriminatedUnion("lookup",[f.strictObject({lookup:f.literal("found"),operationId:f.uuid(),customerId:f.uuid(),execution:Qt,readAt:et}),f.strictObject({lookup:f.literal("not_received"),operationId:f.uuid(),customerId:f.uuid(),execution:f.null(),readAt:et})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),Vi=f.strictObject({merchantSubscriptionId:He,revision:f.number().int().positive(),status:f.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:et,periodEndsAt:et,cancelAtPeriodEnd:f.boolean(),hasDiscounts:f.boolean(),items:f.array(f.strictObject({merchantItemId:He,priceId:f.uuid(),quantity:f.number().int().positive().max(1e6)})).min(1).max(100)}).refine(e=>Date.parse(e.periodEndsAt)>Date.parse(e.periodStartsAt)&&new Set(e.items.map(t=>t.priceId)).size===e.items.length,"Subscription periods and Price identities must be unambiguous"),Li=f.strictObject({merchantInvoiceId:He,currency:Rr,subtotalMinor:De,discountMinor:De,taxMinor:De,totalMinor:De,paidMinor:De,periodStartsAt:et.nullable(),periodEndsAt:et.nullable(),lines:f.array(f.strictObject({merchantLineId:He,priceId:f.uuid(),quantity:f.number().int().nonnegative().max(1e6),subtotalMinor:f.number().int().min(-1e8).max(1e8),discountMinor:De,taxMinor:De,totalMinor:f.number().int().min(-1e8).max(2e8),periodStartsAt:et.nullable(),periodEndsAt:et.nullable()}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&(e.subtotalMinor<0?e.discountMinor===0&&e.taxMinor===0:e.discountMinor<=e.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&e.discountMinor<=e.subtotalMinor&&e.paidMinor===e.totalMinor&&new Set(e.lines.map(t=>t.merchantLineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.subtotalMinor,0)===e.subtotalMinor&&e.lines.reduce((t,n)=>t+n.discountMinor,0)===e.discountMinor&&e.lines.reduce((t,n)=>t+n.taxMinor,0)===e.taxMinor&&e.lines.reduce((t,n)=>t+n.totalMinor,0)===e.totalMinor,"A paid Invoice retains the complete financial amounts"),gn={provider:f.literal("merchant"),eventId:f.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:f.uuid(),occurredAt:et},Es=f.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),Ds=f.discriminatedUnion("type",[f.strictObject({...gn,type:f.literal("purchase.completed"),operationId:f.uuid(),merchantOrderId:He,paymentStatus:f.enum(["paid","trialing","no_payment_required"]),invoice:Li.nullable(),subscription:Vi.nullable()}).refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),f.strictObject({...gn,type:f.literal("purchase.closed"),operationId:f.uuid(),status:f.enum(["failed","expired","canceled"])}),f.strictObject({...gn,type:f.literal("subscription.observed"),operationId:f.uuid().nullable(),subscription:Vi}),f.strictObject({...gn,type:f.literal("subscription.change.completed"),operationId:f.uuid(),status:f.enum(["scheduled","applied"]),scheduledFor:et.nullable(),subscription:Vi,invoice:Li.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),f.strictObject({...gn,type:f.literal("invoice.paid"),merchantSubscriptionId:He,invoice:Li}),f.strictObject({...gn,type:f.literal("refund.updated"),operationId:f.uuid(),merchantRefundId:He,status:f.enum(["pending","succeeded","failed"]),amountMinor:De.refine(e=>e>0),currency:Rr})]);import{z as Jt}from"zod";var Bt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,qt=Jt.object({customerId:Jt.uuid(),sessionId:Jt.uuid(),accessToken:Jt.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Jt.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Jt.iso.datetime(),refreshExpiresAt:Jt.iso.datetime()});var bn=3,Ms="/integrations/indiana",Yh="X-Indiana-Merchant-Bridge-Version",ud=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],ld=b.enum(ud),eg={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},Bs=b.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),qs=b.string().regex(/^[A-Za-z0-9_-]{1,64}$/),pd=b.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),Ki=b.strictObject({keyId:qs,signingSecret:pd}),dd=b.string().max(300).superRefine((e,t)=>{try{let n=new URL(e);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.port&&n.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(n.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(n.hostname))throw new Error("invalid origin")}catch{t.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(e=>new URL(e).origin),zs=b.array(ld).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),Ns=b.strictObject({bridgeVersion:b.literal(bn),projectId:b.uuid(),environmentId:b.uuid(),environment:b.enum(["sandbox","live"]),capabilities:zs,catalog:b.enum(["endpoint","static","none"]),billingEvents:b.array(Es).max(6),profiles:b.array(Ps).max(32).refine(e=>new Set(e).size===e.length,"Profiles must be unique")}).superRefine((e,t)=>{let n=r=>e.capabilities.includes(r);n("catalog")!==(e.catalog!=="none")&&t.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(n("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&t.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),Fs=b.strictObject({origin:dd,requiredCapabilities:zs}),md=b.strictObject({revision:b.number().int().nonnegative(),checkedAt:b.iso.datetime(),outcome:b.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:b.strictObject({ping:b.enum(["passed","failed","not_checked"]),authentication:b.enum(["passed","failed","not_checked"]),catalog:b.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:Ns.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),tg=b.strictObject({projectId:b.uuid(),environmentId:b.uuid(),environment:b.enum(["sandbox","live"]),execution:b.enum(["indiana","record_only"]),accountId:b.string().nullable(),revision:b.number().int().nonnegative(),authentication:b.strictObject({keyId:qs}).nullable(),secretStoreConfigured:b.boolean().optional(),connection:Fs.nullable(),check:md.nullable()});var Ts=b.strictObject({projectId:b.uuid(),environmentId:b.uuid()}),ng=b.discriminatedUnion("action",[Ts.extend({action:b.literal("save"),revision:b.number().int().nonnegative(),connection:Fs,authentication:Ki.optional()}),Ts.extend({action:b.literal("check"),revision:b.number().int().nonnegative()})]),Br=b.strictObject({projectId:b.uuid(),environmentId:b.uuid(),environment:b.enum(["sandbox","live"])});function rg(e){return b.strictObject({bridgeVersion:b.literal(bn),requestId:b.uuid(),command:Bs,scope:Br,data:e})}var fd=b.strictObject({nativeUserId:b.string().min(1).max(128),session:qt.strict()}),Ad=b.strictObject({nativeUserId:b.string().min(1).max(128),presentation:b.strictObject({customerId:b.uuid(),decisionId:b.uuid(),offeringVersionId:b.uuid(),paywallVersionId:b.uuid(),variant:b.string().min(1).max(128)}).nullable()}),hd=b.strictObject({decisionId:b.uuid(),eventId:b.uuid()}),Mr=b.strictObject({operationId:b.uuid(),customerId:b.uuid()}),qr=b.strictObject({scope:Br,operationId:b.uuid(),customerId:b.uuid(),confirmedAt:b.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:b.boolean(),instruction:ks}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),Gi=Qt,Ct=b.string().min(1).max(120),gd=b.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),bd=b.strictObject({revision:Ct,updatedAt:b.iso.datetime(),provider:b.literal("merchant"),items:b.array(b.strictObject({merchantProductId:Ct,productVersionId:b.uuid(),name:b.string().min(1).max(255),kind:b.enum(["subscription","credit_pack"]),merchantPriceId:Ct,currency:b.string().regex(/^[a-z]{3}$/),amountMinor:b.number().int().nonnegative().max(1e8),interval:b.enum(["one_time","month","year"]),intervalCount:b.literal(1),includedCredits:b.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:b.enum(["none","month"]),creditPolicyId:Ct,available:b.boolean()}).superRefine((e,t)=>{(e.kind==="credit_pack"&&(e.interval!=="one_time"||e.creditReset!=="none")||e.kind==="subscription"&&e.interval==="one_time"||e.available&&e.amountMinor===0)&&t.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),yd=b.strictObject({customerId:b.uuid(),revision:b.string().min(1).max(128),observedAt:b.iso.datetime(),subscriptions:b.array(b.strictObject({merchantSubscriptionId:Ct,merchantProductId:Ct,productVersionId:b.uuid().nullable(),status:b.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:b.iso.datetime().nullable(),currentPeriodEndsAt:b.iso.datetime().nullable(),cancelAtPeriodEnd:b.boolean(),scheduledChange:b.strictObject({effectiveAt:b.iso.datetime(),merchantProductId:Ct}).nullable()})).max(100),purchaseHistory:b.strictObject({complete:b.boolean(),hasPaidPurchase:b.boolean(),lastPaidAt:b.iso.datetime().nullable()}),balances:b.array(b.strictObject({bucketId:Ct,key:Ct,available:gd,expiresAt:b.iso.datetime().nullable(),nextResetAt:b.iso.datetime().nullable()})).max(100)}),ig=b.strictObject({bridgeVersion:b.literal(bn),requestId:b.uuid(),command:b.string().min(1).max(64),scope:Br,error:b.strictObject({code:b.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:b.string().min(1).max(500),retryable:b.boolean(),recovery:b.string().min(1).max(80)})}),Jn=b.strictObject({}),xd={"bridge.ping":b.strictObject({challenge:b.uuid()}),"bridge.describe":Jn,"session.create":Jn,"catalog.read":Jn,"customer.commerce.read":Jn,"presentation.resolve":Jn,"presentation.report":hd,"purchase.execute":Mr,"operation.read":Mr,"subscription.change":Mr,"refund.execute":Mr},og={"bridge.ping":b.strictObject({challenge:b.uuid()}),"bridge.describe":Ns,"session.create":fd,"catalog.read":bd,"customer.commerce.read":yd,"presentation.resolve":Ad,"presentation.report":b.strictObject({queued:b.literal(!0)}),"purchase.execute":Gi,"operation.read":Rs,"subscription.change":Gi,"refund.execute":Gi},ag=b.strictObject({bridgeVersion:b.literal(bn),requestId:b.uuid(),scope:Br,command:Bs,data:b.unknown()}).superRefine((e,t)=>{xd[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});var Us="X-Indiana-Bridge-Signature",Vs="X-Indiana-Bridge-Key-Id";function Sd(e){return new TextEncoder().encode(e)}function Ls(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}function $s(e,t,n){return Sd(`indiana-merchant-bridge:${bn}
|
|
2
|
+
${t}
|
|
3
|
+
POST
|
|
4
|
+
${Ms}
|
|
5
|
+
${n}
|
|
6
|
+
${e}`)}async function Gs(e){let t=Ki.parse(e);return crypto.subtle.importKey("raw",Ls(t.signingSecret),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function ug(e,t,n,r=Date.now()){let i=String(Math.floor(r/1e3)),a=new Uint8Array(await crypto.subtle.sign("HMAC",await Gs(t),$s(e,n,i))),s=btoa(String.fromCharCode(...a)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");return{[Vs]:t.keyId,[Us]:`t=${i},v1=${s}`}}async function lg(e,t,n,r,i=Date.now()){try{if(t.get(Vs)!==n.keyId)return!1;let a=/^t=([0-9]{1,12}),v1=([A-Za-z0-9_-]{43})$/.exec(t.get(Us)??"");return!a||Math.abs(i/1e3-Number(a[1]))>300?!1:await crypto.subtle.verify("HMAC",await Gs(n),Ls(a[2]),$s(e,r,a[1]))}catch{return!1}}var Ks={"zh-Hans":{merchandise:"\u51CF {discount}\uFF08\u5355\u6B21\u4F7F\u7528\uFF09",once:"\u9996\u671F\u51CF {discount}",repeating:"\u524D {months} \u4E2A\u6708\u6BCF\u6708\u51CF {discount}",forever:"\u6BCF\u671F\u51CF {discount}"},"zh-Hant":{merchandise:"\u6E1B {discount}\uFF08\u55AE\u6B21\u4F7F\u7528\uFF09",once:"\u9996\u671F\u6E1B {discount}",repeating:"\u524D {months} \u500B\u6708\u6BCF\u6708\u6E1B {discount}",forever:"\u6BCF\u671F\u6E1B {discount}"},en:{merchandise:"{discount} off \xB7 one use",once:"{discount} off your first payment",repeating:"{discount} off each month for the first {months} months",repeatingOne:"{discount} off the first month",forever:"{discount} off every payment"},ja:{merchandise:"{discount} \u5272\u5F15\uFF081\u56DE\u306E\u307F\uFF09",once:"\u521D\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15",repeating:"\u6700\u521D\u306E {months} \u304B\u6708\u9593\u3001\u6BCE\u6708 {discount} \u5272\u5F15",forever:"\u6BCE\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15"},ko:{merchandise:"{discount} \uD560\uC778 \xB7 1\uD68C \uC0AC\uC6A9",once:"\uCCAB \uACB0\uC81C {discount} \uD560\uC778",repeating:"\uCCAB {months}\uAC1C\uC6D4 \uB3D9\uC548 \uB9E4\uC6D4 {discount} \uD560\uC778",forever:"\uB9E4 \uACB0\uC81C {discount} \uD560\uC778"},es:{merchandise:"{discount} de descuento \xB7 un uso",once:"{discount} de descuento en el primer pago",repeating:"{discount} de descuento cada mes durante los primeros {months} meses",forever:"{discount} de descuento en cada pago",repeatingOne:"{discount} de descuento durante el primer mes"},fr:{merchandise:"{discount} de r\xE9duction \xB7 une utilisation",once:"{discount} de r\xE9duction sur le premier paiement",repeating:"{discount} de r\xE9duction par mois pendant les {months} premiers mois",forever:"{discount} de r\xE9duction sur chaque paiement",repeatingOne:"{discount} de r\xE9duction pendant le premier mois"},de:{merchandise:"{discount} Rabatt \xB7 einmalig",once:"{discount} Rabatt auf die erste Zahlung",repeating:"{discount} Rabatt pro Monat f\xFCr die ersten {months} Monate",forever:"{discount} Rabatt auf jede Zahlung",repeatingOne:"{discount} Rabatt im ersten Monat"},pt:{merchandise:"{discount} de desconto \xB7 um uso",once:"{discount} de desconto no primeiro pagamento",repeating:"{discount} de desconto por m\xEAs nos primeiros {months} meses",forever:"{discount} de desconto em cada pagamento",repeatingOne:"{discount} de desconto no primeiro m\xEAs"},it:{merchandise:"{discount} di sconto \xB7 un utilizzo",once:"{discount} di sconto sul primo pagamento",repeating:"{discount} di sconto al mese per i primi {months} mesi",forever:"{discount} di sconto su ogni pagamento",repeatingOne:"{discount} di sconto per il primo mese"},ru:{merchandise:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \xB7 \u043E\u0434\u043D\u043E \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435",once:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043F\u0435\u0440\u0432\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436",repeating:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043A\u0430\u0436\u0434\u044B\u0439 \u043C\u0435\u0441\u044F\u0446 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",repeatingOne:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u0432 \u043F\u0435\u0440\u0432\u044B\u0439 \u043C\u0435\u0441\u044F\u0446",forever:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043A\u0430\u0436\u0434\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436"},vi:{merchandise:"Gi\u1EA3m {discount} \xB7 d\xF9ng m\u1ED9t l\u1EA7n",once:"Gi\u1EA3m {discount} cho l\u1EA7n thanh to\xE1n \u0111\u1EA7u ti\xEAn",repeating:"Gi\u1EA3m {discount} m\u1ED7i th\xE1ng trong {months} th\xE1ng \u0111\u1EA7u",forever:"Gi\u1EA3m {discount} cho m\u1ED7i l\u1EA7n thanh to\xE1n"},th:{merchandise:"\u0E25\u0E14 {discount} \xB7 \u0E43\u0E0A\u0E49\u0E44\u0E14\u0E49\u0E04\u0E23\u0E31\u0E49\u0E07\u0E40\u0E14\u0E35\u0E22\u0E27",once:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E04\u0E23\u0E31\u0E49\u0E07\u0E41\u0E23\u0E01",repeating:"\u0E25\u0E14 {discount} \u0E15\u0E48\u0E2D\u0E40\u0E14\u0E37\u0E2D\u0E19\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",forever:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E17\u0E38\u0E01\u0E04\u0E23\u0E31\u0E49\u0E07"},id:{merchandise:"Diskon {discount} \xB7 sekali pakai",once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{merchandise:"\u062E\u0635\u0645 {discount} \xB7 \u0627\u0633\u062A\u062E\u062F\u0627\u0645 \u0648\u0627\u062D\u062F",once:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u062F\u0641\u0639\u0629 \u0627\u0644\u0623\u0648\u0644\u0649",repeating:"\u062E\u0635\u0645 {discount} \u0634\u0647\u0631\u064A\u064B\u0627 \u0644\u0645\u062F\u0629 {period}",forever:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0643\u0644 \u062F\u0641\u0639\u0629"}};function Hi(e){let t=es(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(a=>["TW","HK","MO"].includes(a))?"zh-Hant":"zh-Hans":n[0]??"en",i=Ks[r];return i?{locale:t,copy:i}:{locale:"en",copy:Ks.en}}function vd(e,t,n="zh-CN"){let r=Ti(t);return Za(e,t,Hi(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function Id(e,t="zh-CN"){let n=Hi(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(e.percentOff/100):vd(e.amountOffCents,e.currency,n)}var Hs={zh:"\u524D {months} \u4E2A\u6708\u5185\u5F00\u51FA\u7684\u8D26\u5355\u51CF {discount}","zh-Hant":"\u524D {months} \u500B\u6708\u5167\u958B\u51FA\u7684\u5E33\u55AE\u6E1B {discount}",en:"{discount} off invoices issued within the first {months} months",ja:"\u6700\u521D\u306E {months} \u304B\u6708\u4EE5\u5185\u306E\u8ACB\u6C42\u304C {discount} \u5272\u5F15",ko:"\uCCAB {months}\uAC1C\uC6D4 \uB0B4 \uCCAD\uAD6C\uC11C {discount} \uD560\uC778",es:"{discount} de descuento en facturas emitidas durante los primeros {months} meses",fr:"{discount} de r\xE9duction sur les factures \xE9mises pendant les {months} premiers mois",de:"{discount} Rabatt auf Rechnungen innerhalb der ersten {months} Monate",pt:"{discount} de desconto nas faturas emitidas nos primeiros {months} meses",it:"{discount} di sconto sulle fatture emesse nei primi {months} mesi",ru:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u0441\u0447\u0435\u0442\u0430 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",vi:"Gi\u1EA3m {discount} cho h\xF3a \u0111\u01A1n trong {months} th\xE1ng \u0111\u1EA7u",th:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E43\u0E1A\u0E41\u0E08\u0E49\u0E07\u0E2B\u0E19\u0E35\u0E49\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",id:"Diskon {discount} untuk tagihan dalam {months} bulan pertama",ar:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u0641\u0648\u0627\u062A\u064A\u0631 \u0627\u0644\u0635\u0627\u062F\u0631\u0629 \u062E\u0644\u0627\u0644 \u0623\u0648\u0644 {period}"};function fg(e,t="zh-CN",n="month"){let r=Hi(t),i=Id(e.discount,r.locale);if(e.appliesTo?.type==="merchandise")return r.copy.merchandise.replace("{discount}",i);let a=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",s=r.locale.split("-")[0]??"en",c=s==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":s,u=e.duration.type==="repeating"&&n!=="month"?Hs[c]??Hs.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],p=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return u.replace("{discount}",i).replace("{months}",a).replace("{period}",p)}import{z as X}from"zod";import{z as $e}from"zod";var Te=$e.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),Zi=$e.strictObject({type:$e.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:$e.boolean(),enum:$e.array($e.string().max(255)).min(1).max(100).optional()}),yn=Zi.extend({type:$e.enum([...Zi.shape.type.options,"array"]),items:Zi.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),xn=yn.safeExtend({source:$e.discriminatedUnion("type",[$e.strictObject({type:$e.literal("input")}),$e.strictObject({type:$e.literal("node")}),$e.strictObject({type:$e.enum(["parameter","attribute"]),key:Te})])}),Od=$e.record(Te,xn),zr=$e.record(Te,Te).refine(e=>Object.keys(e).length<=20);function lt(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>lt(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&$e.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function Qi(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&Qi(e.items,t.items)}function Wn(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,s=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,c=a.type==="parameter"||a.type==="attribute"?a.key:r,u=Object.hasOwn(s,c),p=s[c];if(a.type==="attribute"&&c.includes(".")&&(!u||c.startsWith("merchandise."))){p=s,u=!0;for(let y of c.split(".")){if(!p||typeof p!="object"||!Object.hasOwn(p,y)||Array.isArray(p)&&(!/^(0|[1-9]\d*)$/.test(y)||Number(y)>=p.length)){u=!1;break}p=p[y]}}if(!(!u||p===void 0)){if(!lt(i,p))throw new Error(`Invalid variable value: ${r}`);n[r]=p}}return n}function Wt(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function Ji(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,a]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!lt(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as Xt}from"zod";var At=Xt.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),St=Xt.discriminatedUnion("source",[Xt.strictObject({source:Xt.literal("literal"),value:me}),Xt.strictObject({source:Xt.literal("variable"),key:Xt.string().min(1).max(255),path:At.optional()})]);function Zs(e,t){if(!t)return e;for(let n of At.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Wi(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Wn(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(me.parse(Zs(n[e.key],e.path)))}function Xi(e,t){let n=[...t].sort((i,a)=>a.length-i.length).find(i=>e===i||e.startsWith(i+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!At.safeParse(r).success?null:{key:n,path:r}}function Yi(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Pt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(fs))]}function Nr(e){return Yi(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function ot(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let s=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let c=t.slice(s,i+1);if(!/[eE]/.test(c))continue;let[u="",p]=c.split(/[eE]/),y=u.replace(/^-/,""),w=y.replace(".","").length,N=(y.includes(".")?y.indexOf("."):w)+Number(p),O=N<=0?2-N+w:N>=w?N:w+1;n+=O+(u.startsWith("-")?1:0)-c.length}}return n}var zt=X.enum(["page","popup","banner"]),wd=3e5,Qs=X.strictObject({type:X.enum(["string","number","boolean","strings","json"]),nullable:X.boolean()}),jd=X.strictObject({inputs:X.record(Hn,Qs.extend({required:X.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:X.record(Hn,Qs).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),_d=X.strictObject({kind:zt,schemaVersion:X.literal(1),name:X.string().trim().min(1).max(80),screen:it,contract:jd}),Fr=_d.superRefine((e,t)=>{let n=(i,a)=>t.addIssue({code:"custom",message:i,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!r.has(i))||[...r].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),ot(e)>wd&&n("Content document exceeds its byte budget",[])});function Pd(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var Cd=Fr.superRefine((e,t)=>{for(let n of Nr(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],i=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!Pd(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}Tt(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Js=X.strictObject({id:X.uuid(),kind:zt,projectId:X.uuid(),environmentId:X.uuid(),name:X.string(),revision:X.number().int().nonnegative(),status:X.enum(["draft","published","archived"]),publishedVersionId:X.uuid().nullable(),createdAt:X.iso.datetime({offset:!0}),updatedAt:X.iso.datetime({offset:!0})}),Rg=Js.extend({draft:Fr}),Eg=X.strictObject({rows:X.array(Js).max(200),nextCursor:X.uuid().nullable()}),eo=X.strictObject({id:X.uuid(),kind:zt,resourceId:X.uuid(),projectId:X.uuid(),environmentId:X.uuid(),version:X.number().int().positive(),sourceRevision:X.number().int().nonnegative(),document:Cd,createdAt:X.iso.datetime({offset:!0})}),Dg=eo.omit({document:!0}),Tg=X.discriminatedUnion("action",[X.strictObject({action:X.literal("create"),kind:zt,id:X.uuid(),document:Fr}),X.strictObject({action:X.literal("save"),kind:zt,id:X.uuid(),revision:X.number().int().nonnegative(),document:Fr}),X.strictObject({action:X.enum(["publish","archive"]),kind:zt,id:X.uuid(),revision:X.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as Sn}from"zod";var Ur=Sn.strictObject({items:Sn.array(Sn.strictObject({productVersionId:Sn.string().min(1).max(200),label:Sn.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Sn.string().min(1).max(200).nullable(),grouping:hs.optional()});function zg(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}import{z as fe}from"zod";var Xn=fe.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Ws=fe.enum(["unknown","denied","provisional","granted"]),Xs=fe.enum(["ios","android"]),Vr=fe.strictObject({installationId:fe.uuid(),publicKey:fe.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:fe.iso.datetime({offset:!0}),signature:fe.string().regex(/^[A-Za-z0-9_-]{86}$/)}),to=fe.string().regex(/^[a-f0-9]{64}$/),Ys=Vr.extend({sequence:Xn,platform:Xs,credentialDigest:to}),ec=Vr.extend({credentialDigest:to}),Ug=Vr.extend({sequence:Xn,platform:Xs}),Lr=Vr.extend({sequence:Xn,credentialDigest:to,connectionId:fe.uuid().nullable(),kind:fe.enum(["fcm_token","apns_token"]).nullable(),token:fe.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Ws}),Vg=Lr,Lg=Lr.extend({challenge:fe.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),$g=fe.strictObject({requested:fe.literal(!0),expiresAt:fe.iso.datetime({offset:!0})}),$r=fe.strictObject({installationId:fe.uuid(),bound:fe.boolean(),identitySeq:Xn,bindingGeneration:Xn,addressSeq:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:fe.uuid().nullable(),addressStatus:fe.enum(["active","invalid"]).nullable(),permission:Ws}),no=fe.strictObject({channel:fe.enum(["email","sms","voice","push"]),state:fe.enum(["unknown","allowed","denied"]),revision:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:fe.iso.datetime({offset:!0}).nullable()}),Gg=fe.strictObject({state:fe.enum(["allowed","denied"]),revision:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Kg(e,t,n){let r=["indiana_push_v1",e,t.projectId,t.environment,n.installationId,n.publicKey,n.issuedAt];e==="bind"?r.push(n.sequence,n.platform,n.credentialDigest):e==="detach"?r.push(n.sequence,n.platform):e==="read"?r.push(n.credentialDigest):r.push(n.sequence,n.credentialDigest,n.connectionId,n.kind,n.token,n.permission),e==="recovery_confirm"&&r.push(n.challenge);let i=JSON.stringify(r);if([...i].some(a=>a.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(i,a=>a.charCodeAt(0))}var ro="X-Indiana-Protocol",tc="X-Indiana-SDK-Version";var io={current:"0.10"};import{z as vn}from"zod";var Gr=vn.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),Wg=vn.object({amountCents:vn.number().int().min(0).max(1e8),currency:se,interval:vn.enum(["free","month","year"]),currencyOptions:vn.partialRecord(se,vn.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");import{z as x}from"zod";var kd=x.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),ic=x.enum(["single_use","continuous_use"]),oo=x.record(x.string(),x.union([x.string(),x.number(),x.boolean()]).transform(String).pipe(x.string())),nc=x.string().min(1).max(64).refine(e=>!e.includes("::")),oc={credit_amount:x.number(),tier_behavior:x.never().optional(),tiers:x.never().optional()},ac={credit_amount:x.never().optional(),tier_behavior:x.literal("graduated"),tiers:x.array(x.strictObject({to:x.union([x.number(),x.literal("inf")]),credit_amount:x.number()}))},Rd=x.union([x.strictObject({match:oo,priority:x.number().int().optional(),...oc}),x.strictObject({match:oo,priority:x.number().int().optional(),...ac})]),Ed=x.strictObject({match:oo,factor:x.number().positive().optional(),add:x.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),rc={metered_feature_id:x.string(),feature_amount:x.number().optional(),dimensions:x.record(nc,Rd).optional(),multipliers:x.record(nc,Ed).optional()},ao=x.union([x.strictObject({...rc,...oc}),x.strictObject({...rc,...ac})]),Hr=x.number().min(-100),sc=x.record(x.string(),x.strictObject({markup:Hr})).nullish(),Zr=x.record(x.string().regex(/.+\/.+/),x.strictObject({markup:Hr.optional(),input_cost:x.number().min(0).optional(),output_cost:x.number().min(0).optional()})).nullish(),Dd=x.strictObject({default_markup:Hr.optional(),provider_markups:sc,model_markups:Zr}),eb=x.strictObject({schema:x.array(ao).optional(),markups:Dd.optional()}),Td=x.strictObject({filters:x.array(x.strictObject({property:x.string(),operator:x.string(),value:x.array(x.string())})),aggregate:x.strictObject({type:x.string(),property:x.string().nullable()}),usage_type:ic}),cc=x.strictObject({schema:x.array(ao).min(1).refine(e=>new Set(e.map(t=>t.metered_feature_id)).size===e.length,"Credit rates must name each metered feature once"),invoice_credit:x.boolean().optional(),usage_type:ic.default("single_use").overwrite(()=>"single_use"),default_markup:Hr.optional(),provider_markups:sc}),so=cc.safeExtend({schema:x.array(ao).length(0)}),Kr={id:kd,name:x.string().min(1),display:x.strictObject({singular:x.string().optional(),plural:x.string().optional()}).nullish(),event_names:x.array(x.string()).default([]),model_markups:Zr,stripe_meter:x.strictObject({id:x.string(),event_name:x.string()}).nullish(),stripe_product_id:x.string().nullish()},co=e=>x.discriminatedUnion("type",[x.strictObject({...Kr,...e,type:x.literal("boolean"),config:x.null()}),x.strictObject({...Kr,...e,type:x.literal("metered"),config:Td}),x.strictObject({...Kr,...e,type:x.literal("credit_system"),config:cc}),x.strictObject({...Kr,...e,type:x.literal("ai_credit_system"),config:so})]),tb=co({}),Md=x.strictObject({id:x.boolean(),type:x.boolean(),usage_type:x.boolean()}),Bd={internal_id:x.uuid(),org_id:x.uuid(),created_at:x.number(),env:x.enum(["sandbox","live"]),archived:x.boolean(),project_id:x.uuid(),environment_id:x.uuid(),revision:x.number().int().nonnegative(),update_rules:Md},uc=co(Bd),nb=x.strictObject({rows:x.array(uc).max(200),nextCursor:x.uuid().nullable()}),rb=x.strictObject({features:x.array(uc).max(500),limited:x.boolean()}),ib=x.union([co({action:x.literal("save"),internal_id:x.uuid().nullable(),revision:x.number().int().nonnegative()}),x.strictObject({action:x.enum(["archive","restore","delete"]),internal_id:x.uuid(),revision:x.number().int().nonnegative()})]);import{z as l}from"zod";import{z}from"zod";import{z as Ne}from"zod";function Nt(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,s){if(n(a))for(let[c,u]of Object.entries(a))c==="$elemMatch"?i(u,s):c==="$not"?r(u,s):c==="$all"&&Array.isArray(u)&&u.forEach(p=>r(p,s))}function i(a,s=""){if(n(a)){for(let[c,u]of Object.entries(a))if(["$and","$or","$nor"].includes(c)&&Array.isArray(u))u.forEach(p=>i(p,s));else if(c==="$not")i(u,s);else if(c==="$savedGroup"&&n(u))typeof u.attributeKey=="string"&&t.add(u.attributeKey);else if(!c.startsWith("$")){let p=s?`${s}.${c}`:c;t.add(p),r(u,p)}}}return i(e),[...t]}var qd=Ne.enum(["active","inactive"]),zd=Ne.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(s=>r(s,a+1));else if(i&&typeof i=="object")for(let[s,c]of Object.entries(i))["__proto__","constructor","prototype"].includes(s)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(c,a+1)}}return r(e,0),e},rt),Nd=Ne.strictObject({id:Ne.string().trim().min(1).max(255),name:Ne.string().trim().min(1).max(255),status:qd,metadata:zd}),lb=Nd.extend({internal_id:Ne.uuid(),project_id:Ne.uuid(),environment_id:Ne.uuid(),created_at:Ne.iso.datetime({offset:!0}),updated_at:Ne.iso.datetime({offset:!0})}),pc=Ne.union([Ne.strictObject({id:Ne.string().trim().min(1).max(255)}),Ne.strictObject({internalId:Ne.uuid()})]),pb=Ne.enum(["customer","merchandise","context"]),db=Ne.enum(["system","stored","request"]),mb=Ne.enum(["customer","merchandise","mixed"]),lc=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function uo(e,t={},n=new Set){if(Nt(e).some(lc))return!0;for(let r of Dt(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&lc(i.attributeKey)||i?.type==="condition"&&uo(i.condition,t,n))return!0}return!1}var yb=z.enum(["draft","active","paused","archived"]),Ft=z.discriminatedUnion("type",[z.object({type:z.literal("percent"),percentOff:z.number().min(1).max(100).multipleOf(.01)}).strict(),z.object({type:z.literal("amount"),amountOffCents:z.number().int().min(1).max(1e8),currency:se}).strict()]),at=z.discriminatedUnion("type",[z.object({type:z.literal("once")}).strict(),z.object({type:z.literal("repeating"),months:z.number().int().min(1).max(36)}).strict(),z.object({type:z.literal("forever")}).strict()]),dc=[z.object({type:z.literal("all")}).strict(),z.object({type:z.literal("plans"),planIds:z.array(z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Fd=z.discriminatedUnion("type",[...dc,z.strictObject({type:z.literal("merchandise"),scope:z.discriminatedUnion("type",[z.strictObject({type:z.literal("all")}),z.strictObject({type:z.literal("selected"),merchandiseIds:z.array(z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),z.strictObject({type:z.literal("condition"),condition:Ht})])})]),lo=z.discriminatedUnion("type",[...dc,z.strictObject({type:z.literal("merchandise"),scope:z.strictObject({type:z.enum(["all","selected","condition"])})})]),Ud=z.strictObject({firstPurchaseOnly:z.boolean(),condition:Ht}),xb=z.object({name:z.string().trim().min(1).max(80),description:z.string().max(500),discount:Ft,duration:at,appliesTo:Fd,eligibility:Ud,selfClaimEnabled:z.boolean().default(!1),startsAt:z.iso.datetime().nullable(),endsAt:z.iso.datetime().nullable(),totalLimit:z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:z.number().int().min(1).max(10),grantWindowHours:z.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!uo(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),Sb=z.object({code:z.string().trim().transform(e=>e.toUpperCase()).pipe(z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:z.number().int().min(1).max(1e6).nullable(),expiresAt:z.iso.datetime().nullable(),firstPurchaseOnly:z.boolean(),minimumAmountCents:z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:se.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Yn=z.object({id:z.uuid(),couponId:z.uuid(),status:z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:z.iso.datetime(),expiresAt:z.iso.datetime(),coupon:z.object({name:z.string(),discount:Ft,duration:at,appliesTo:lo}).strict()}).strict(),mc=z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var bc=l.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),po=l.string().regex(/^(0|[1-9]\d{0,14})$/),In=l.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Vd=l.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),er=Vd,kt=we.refine(e=>/[1-9]/.test(e)),Ze=l.iso.datetime({offset:!0}),Qr=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},Ld=l.array(l.object({upTo:kt.nullable(),unitAmountMinor:bc,flatAmountMinor:l.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&Qr(t.upTo)>Qr(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),$d=l.discriminatedUnion("kind",[l.object({kind:l.literal("flat"),units:kt,unitAmountMinor:bc}).strict(),l.object({kind:l.enum(["graduated","volume"]),units:kt,tiers:Ld}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),Gd=l.strictObject({interval:l.enum(["month","year"]),count:l.number().int().min(1).max(12),anchor:l.enum(["membership","calendar"])}),tr=l.object({currency:se,pricing:$d,billingCycle:Gd.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var fc={requestId:l.uuid(),productVersionId:l.uuid(),internal_feature_id:l.uuid(),currency:se},yc=l.strictObject({interval:l.enum(["hour","day","week","month"]),intervalCount:l.number().int().min(1).max(12),limit:l.number().int().min(1).max(1e6)}),xc=l.discriminatedUnion("kind",[l.object({...fc,kind:l.literal("auto_topup"),threshold:Mi,quantity:kt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:yc.optional()}).strict(),l.object({...fc,kind:l.literal("postpaid"),maxAmountMinorPerPeriod:er,maxOutstandingMinor:er}).strict()]),Ac={productVersionId:l.uuid(),internal_feature_id:l.uuid(),currency:se},Sc=l.discriminatedUnion("kind",[l.object({...Ac,kind:l.literal("auto_topup"),threshold:Mi,quantity:kt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:yc.optional(),purchaseAmountMinor:er,purchaseUnits:kt}).strict(),l.object({...Ac,kind:l.literal("postpaid"),maxAmountMinorPerPeriod:er,maxOutstandingMinor:er,cashPrice:tr}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Jr=l.object({id:l.uuid(),terms:Sc,status:l.enum(["prepared","active","revoked","blocked"]),createdAt:Ze,acceptedAt:Ze.nullable(),effectiveAt:Ze.nullable(),revokedAt:Ze.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),vc=l.object({authorizationId:l.uuid(),terms:Sc,setupUrl:l.url().nullable()}).strict(),Ic=l.object({authorizationId:l.uuid(),accepted:l.literal(!0)}).strict(),Oc=l.object({authorizationId:l.uuid(),requestId:l.uuid()}).strict(),wc=l.object({internal_feature_id:l.uuid(),entityId:l.uuid().nullable(),interval:l.enum(["day","week","month","year"]),anchor:l.enum(["billing_cycle","utc"]).optional(),basis:l.enum(["usage","credits"]),filter:_t.optional(),limit:we.nullable(),thresholds:l.array(l.number().positive().max(1)).max(8),includedThresholds:l.array(l.number().positive().max(1)).max(8).optional(),absoluteThresholds:l.array(kt).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&Qr(t)>Qr(i)}),"Notification thresholds must increase"),Kd=wc.safeExtend({requestId:l.uuid()}),hc={control:l.literal("overage"),requestId:l.uuid(),internal_feature_id:l.uuid(),entityId:l.uuid().nullable()},Hd=l.discriminatedUnion("action",[l.strictObject({...hc,action:l.literal("set"),allowed:l.boolean().nullable(),overageLimit:we.nullable(),skipOverageBilling:l.boolean()}),l.strictObject({...hc,action:l.literal("remove")})]),jc=l.union([Kd,Hd]),Zd=l.strictObject({internal_feature_id:l.uuid(),entityId:l.uuid().nullable(),allowed:l.boolean().nullable(),overageLimit:we.nullable(),skipOverageBilling:l.boolean(),interval:l.enum(["day","week","month","year"]),startsAt:Ze,endsAt:Ze,used:l.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:l.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:l.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Qd=l.object({internal_feature_id:l.uuid(),entityId:l.uuid().nullable(),interval:l.enum(["day","week","month","year"]),anchor:l.enum(["billing_cycle","utc"]).optional(),basis:l.enum(["usage","credits"]),filter:_t.optional(),startsAt:Ze,endsAt:Ze,used:ft,reserved:ft,limit:we.nullable(),thresholds:l.array(l.number().positive().max(1)).max(8),notifiedThresholds:l.array(l.number().positive().max(1)).max(1024),includedThresholds:l.array(l.number().positive().max(1)).max(8).optional(),includedAllowance:l.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:l.array(l.number().positive().max(1)).max(1024).optional(),absoluteThresholds:l.array(kt).max(8).optional(),notifiedAbsoluteThresholds:l.array(kt).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||we.safeParse(e.used).success&&we.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Jd=l.object({authorizationId:l.uuid(),status:l.enum(["idle","pending","blocked"]),taskId:l.uuid().nullable(),invoiceId:l.uuid().nullable(),hostedInvoiceUrl:l.url().nullable(),purchaseCount:l.number().int().nonnegative(),purchaseWindowEndsAt:Ze.nullable(),attemptCount:l.number().int().nonnegative(),failedAttemptCount:l.number().int().nonnegative(),suspendedAt:Ze.nullable(),nextAttemptAt:Ze.nullable(),failureReason:l.string().min(1).max(240).nullable()}).strict(),_c=l.object({internal_feature_id:l.uuid().optional(),entityId:l.uuid().optional()}).strict(),mo=l.object({authorizations:l.array(Jr).max(100),limits:l.array(wc).max(100),overages:l.array(Zd).max(100).optional(),windows:l.array(Qd).max(200),autoTopups:l.array(Jd).max(100),limited:l.boolean()}).strict(),Wd=l.object({id:l.uuid(),internal_feature_id:l.uuid(),productVersionId:l.uuid(),authorizationId:l.uuid(),entityId:l.uuid().nullable(),units:we,amountMinor:In,cashPrice:tr}).strict(),nr=l.object({id:l.uuid(),sourceKind:l.enum(["product","usage","manual"]),providerInvoiceId:l.string().min(1).max(240).nullable(),status:l.enum(["accruing","open","pending","paid","failed","void"]),currency:se,startsAt:Ze.nullable(),endsAt:Ze.nullable(),amountMinor:l.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:l.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:po,paidAmountMinor:po,refundedAmountMinor:po,createdAt:Ze,hostedInvoiceUrl:l.url().nullable(),adjustment:l.object({originalInvoiceId:l.uuid(),amountMinor:l.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:Ze.nullable(),reason:l.string().min(1).max(500).optional()}).strict().nullable(),lines:l.array(Wd).max(100),linesLimited:l.boolean()}).strict(),Pc=l.object({invoiceId:l.uuid(),accepted:l.literal(!0)}).strict(),Cc=l.strictObject({requestId:l.uuid(),originalInvoiceId:l.uuid(),amountMinor:l.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:l.string().trim().min(1).max(500)}),kc=l.object({after:l.uuid().nullable(),limit:l.number().int().min(1).max(100)}).strict(),Rc=l.object({rows:l.array(nr).max(100),nextCursor:l.uuid().nullable()}).strict(),gc=l.strictObject({id:l.string(),coupon:l.string(),start:l.number().nonnegative(),end:l.number().nullable()}),Xd=l.strictObject({subscriptionId:l.string(),customerId:l.string(),accountId:l.string(),sourceItems:l.array(l.strictObject({id:l.string(),price_id:l.string(),quantity:l.number().int(),discounts:l.array(gc).optional()})).max(100),items:l.array(l.strictObject({id:l.string(),price:l.string(),quantity:l.number().int(),discounts:l.array(l.strictObject({coupon:l.string().optional(),terms:l.strictObject({id:l.string(),name:l.string().optional(),percent_off:l.number().optional(),amount_off:l.number().optional(),currency:l.string().optional(),duration:l.enum(["once","forever","repeating"]),duration_in_months:l.number().optional()}).optional(),discount:l.string().optional(),receipt:gc.optional()})).max(20)})).max(100)}),Ec=l.strictObject({membershipId:l.uuid(),requestId:l.uuid(),grantIds:l.array(l.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Dc=l.strictObject({membershipId:l.uuid(),operationId:l.uuid(),status:l.enum(["pending","effective"]),execution:Xd.nullable(),grants:l.array(l.strictObject({id:l.uuid(),couponId:l.uuid(),name:l.string(),discount:Ft,duration:at,startedAt:Ze.nullable()})).max(20)});import{z as rr}from"zod";var Tc=rr.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Mc=rr.number().int().min(1).max(1e3),Wr=rr.object({cap:we.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:rr.number().positive().max(1e4).nullable(),cycles:rr.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as Ut}from"zod";var Bc=Ut.strictObject({itemKey:Ut.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:Ut.uuid(),includedAmount:Ut.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Ut.number().int().min(0).max(1e4),terms:Ja,pricing:Qa.optional(),unitAmountMinor:Ut.number().int().min(0).max(1e8),productId:Ut.string().min(1).max(255).nullable(),priceId:Ut.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{Wa(e.includedAmount,e.terms.units,e.quantity),Or({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as oe}from"zod";var Yt=oe.iso.datetime({offset:!0}),qc=we.refine(e=>/[1-9]/.test(e)),zc=oe.strictObject({interval:Tc.exclude(["lifetime"]),count:Mc}),Yd=oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),internal_feature_id:oe.uuid(),entityId:oe.uuid().nullable(),amount:qc.nullable(),expiresAt:Yt.nullable(),reset:zc.nullable(),rollover:Wr.nullable(),nextResetAt:Yt.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),Nc=oe.discriminatedUnion("action",[Yd,oe.strictObject({action:oe.literal("update"),requestId:oe.uuid(),grantId:oe.uuid(),revision:oe.number().int().nonnegative(),amount:qc.nullable(),expiresAt:Yt.nullable(),rollover:Wr.nullable(),nextResetAt:Yt.nullable()}),oe.strictObject({action:oe.enum(["add","subtract","set_remaining"]),requestId:oe.uuid(),grantId:oe.uuid(),revision:oe.number().int().nonnegative(),amount:we}),oe.strictObject({action:oe.literal("revoke"),requestId:oe.uuid(),grantId:oe.uuid(),revision:oe.number().int().nonnegative()})]),fo=oe.strictObject({id:oe.uuid(),internal_feature_id:oe.uuid(),entityId:oe.uuid().nullable(),amount:we.nullable(),reset:zc.nullable(),rollover:Wr.nullable(),nextResetAt:Yt.nullable(),startsAt:Yt,expiresAt:Yt.nullable(),revision:oe.number().int().nonnegative(),revoked:oe.boolean(),available:ft,held:ft,spent:ft}),Fc=oe.strictObject({customerId:oe.uuid(),after:oe.uuid().nullable(),limit:oe.number().int().min(1).max(100)}),Uc=oe.strictObject({rows:oe.array(fo).max(100),nextCursor:oe.uuid().nullable()});import{z as F}from"zod";var vt=F.iso.datetime({offset:!0}),Vc=F.strictObject({invoiceId:F.uuid(),after:F.string().min(1).max(180).nullable(),limit:F.number().int().min(1).max(100)}),em=F.strictObject({kind:F.literal("product"),key:F.string(),productVersionId:F.uuid(),productName:F.string(),itemKey:F.string(),entityId:F.uuid().nullable(),quantity:F.number().positive(),subtotalMinor:F.string().regex(/^-?\d+$/),discountMinor:F.string().regex(/^\d+$/),taxMinor:F.string().regex(/^-?\d+$/).nullable(),totalMinor:F.string().regex(/^-?\d+$/),startsAt:vt.nullable(),endsAt:vt.nullable(),providerLineId:F.string().nullable(),providerItemId:F.string()}),Lc=F.strictObject({invoice:nr,items:F.array(F.discriminatedUnion("kind",[em,F.strictObject({kind:F.literal("invoice_credit"),key:F.string(),internal_feature_id:F.uuid(),internal_credit_feature_id:F.uuid(),name:F.string(),units:we,reserved:we,amountMinor:In,grossAmountMinor:In,creditsAppliedMinor:In,properties:_t,cashPrice:tr,providerItemId:F.string().nullable(),creditProviderItemId:F.string().nullable()}),F.strictObject({kind:F.literal("usage"),key:F.string(),internal_feature_id:F.uuid(),name:F.string(),units:we,reserved:we,amountMinor:In,cashPrice:tr})])).max(100),nextCursor:F.string().min(1).max(180).nullable()}),tm=F.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Ao=F.strictObject({from:vt,to:vt,entityId:F.uuid().optional(),snapshotAt:vt.nullable(),after:F.strictObject({at:vt,id:F.uuid(),position:F.number().int().nonnegative()}).nullable(),limit:F.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),$c=F.strictObject({customerId:F.uuid(),entityId:F.uuid().nullable(),from:vt,to:vt,snapshotAt:vt,totals:F.array(F.strictObject({internal_credit_feature_id:F.uuid(),name:F.string(),consumed:ft,refunded:ft,net:tm})).max(1e3),rows:F.array(F.strictObject({operationId:F.uuid(),position:F.number().int().nonnegative(),kind:F.enum(["consume","confirm","refund"]),originalId:F.uuid().nullable(),occurredAt:vt,internal_feature_id:F.uuid(),entitlementName:F.string(),sourceId:F.uuid(),internal_credit_feature_id:F.uuid(),creditName:F.string(),units:ns,amount:ft,pricing:F.array(ts).max(12),properties:_t})).max(100),nextCursor:Ao.shape.after});import{z as K}from"zod";var Kc=K.object({customerId:K.uuid()}).strict(),Hc=K.discriminatedUnion("action",[K.object({customerId:K.uuid(),requestId:K.uuid(),action:K.literal("assign"),poolId:K.uuid(),memberCustomerId:K.uuid()}).strict(),K.strictObject({customerId:K.uuid(),requestId:K.uuid(),action:K.literal("assign_entity"),poolId:K.uuid(),entityId:K.uuid()}),K.object({customerId:K.uuid(),requestId:K.uuid(),action:K.literal("release"),poolId:K.uuid(),slotId:K.uuid()}).strict()]),ir=K.number().int().nonnegative(),ho=K.iso.datetime({offset:!0}),go=K.strictObject({internalId:K.uuid(),id:K.string(),name:K.string().nullable(),version:K.number().int().positive()}),Gc=K.enum(["active","past_due"]),bo=K.strictObject({customerId:K.uuid(),licenses:K.array(K.strictObject({id:K.uuid(),linkId:K.uuid(),parent:K.strictObject({customerProductId:K.uuid(),status:Gc,product:go}),product:go,planLicense:K.strictObject({id:K.uuid(),prepaidOnly:K.boolean(),isCustom:K.boolean()}).nullable(),granted:ir,included:ir,paidQuantity:ir,usage:ir,remaining:ir,createdAt:ho}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:K.array(K.strictObject({id:K.uuid(),linkId:K.uuid(),status:Gc,product:go,entity:K.strictObject({internalId:K.uuid(),id:K.string().nullable(),name:K.string().nullable()}).nullable(),beneficiary:K.strictObject({internalId:K.uuid(),id:K.string().nullable(),name:K.string().nullable()}).nullable(),startedAt:ho.nullable(),endedAt:ho.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:K.boolean()});import{z as G}from"zod";var or=G.enum(["email","sms","voice","push"]),Hb=G.enum(["resend","twilio","fcm","apns"]);var Zb=G.string().regex(/^\+[1-9]\d{1,14}$/),nm=G.enum(["email_recipient","sms_segment","voice_second","push_device"]);var rm=G.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),im=G.strictObject({subject:rm,html:G.string().min(1).max(131072).optional(),text:G.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),om=G.strictObject({body:G.string().min(1).max(1600).refine(e=>e.trim().length>0)}),am=G.strictObject({text:G.string().trim().min(1).max(4e3),language:G.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:G.number().int().min(1).max(900)}),sm=G.record(G.string().min(1).max(64),G.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),cm=G.strictObject({title:G.string().trim().min(1).max(200),body:G.string().trim().min(1).max(2e3),url:G.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:sm.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Zc=G.discriminatedUnion("channel",[G.strictObject({channel:G.literal("email"),content:im}),G.strictObject({channel:G.literal("sms"),content:om}),G.strictObject({channel:G.literal("voice"),content:am}),G.strictObject({channel:G.literal("push"),content:cm})]),Qc=G.strictObject({requestId:G.uuid(),customerId:G.uuid(),connectionId:G.uuid().optional(),message:Zc,expiresAt:G.iso.datetime({offset:!0})}),um=G.array(G.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),lm=G.discriminatedUnion("kind",[G.strictObject({kind:G.literal("all")}),G.strictObject({kind:G.literal("customers"),customerIds:um})]),Qb=G.strictObject({name:G.string().trim().min(1).max(120),connectionId:G.uuid().optional(),message:Zc,audience:lm,frequencyLimit:G.number().int().min(1).max(100)}),Jc=G.strictObject({requestId:G.uuid(),channel:or,state:G.enum(["allowed","denied"]),expectedRevision:G.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Wc=G.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Xc=G.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),Jb=G.strictObject({meter:nm,estimatedUnits:G.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:G.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Yc}from"zod";var On={funnelId:Yc.uuid().optional(),funnelVersionId:Yc.uuid().optional()};import{z as je}from"zod";import{z as le}from"zod";import{z as xe}from"zod";var ty=xe.discriminatedUnion("action",[xe.strictObject({action:xe.literal("create"),couponId:xe.uuid(),productBindingId:xe.uuid(),storeOfferId:xe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:xe.enum(["introductory","promotional"])}),xe.strictObject({action:xe.literal("set_enabled"),id:xe.uuid(),revision:xe.number().int().nonnegative(),enabled:xe.boolean()})]),ny=xe.array(xe.strictObject({id:xe.uuid(),couponId:xe.uuid(),productBindingId:xe.uuid(),storeOfferId:xe.string().min(1).max(255).nullable(),storeOfferType:xe.enum(["introductory","promotional"]),enabled:xe.boolean(),revision:xe.number().int().nonnegative()})).max(500),wn=xe.strictObject({offerKind:xe.enum(["none","introductory","promotional"]),offerId:xe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:xe.number().int().min(0).max(1e8),trialDays:xe.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),ry=xe.record(xe.uuid(),wn).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var yo=le.object({type:le.literal("native_purchase"),receiptId:le.uuid(),orderId:le.uuid(),productVersionId:le.uuid(),provider:le.enum(["apple","google"]),productId:le.string().min(1).max(255),productKind:ls,replacement:le.strictObject({sourceOrderId:le.uuid(),sourceProductId:le.string().min(1).max(255),policy:le.enum(["apple_store","google_full_price"]),sourceAccountTokens:le.array(le.uuid()).max(50)}).nullable(),appAccountToken:le.uuid().optional(),obfuscatedAccountId:le.string().min(1).max(64).optional(),obfuscatedProfileId:le.uuid().optional(),basePlanId:le.string().min(1).max(255).optional(),offerId:le.string().min(1).max(255).optional(),offerKind:le.enum(["none","introductory","promotional"]),currency:se,catalogAmountMinor:le.number().int().nonnegative().max(1e8),discountMinor:le.number().int().nonnegative().max(1e8),trialDays:le.number().int().min(1).max(730).nullable(),seatBundle:le.array(le.strictObject({key:le.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:le.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:le.strictObject({offerId:le.string().min(1).max(255),keyId:le.string().min(1).max(255),nonce:le.uuid(),signature:le.string().min(1).max(1024),timestamp:le.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as o}from"zod";import{z as ee}from"zod/v4";import{z as pm}from"zod/v4";var dm=pm.registry(),{BillingInterval:eu}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:mm}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(ee),{withSpecDefault:fm}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(dm),{COMMON:tu}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Am}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:hm}=(e=>({COMMON_SET:new Set(e)}))(tu),{hasNoDuplicateCurrencies:nu}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:ru}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:gm}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(ee),{Infinite:bm}={Infinite:"inf"},{TierBehavior:ym}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:iu}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:xm}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Sm}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:vm}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Im}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(ee),{ApiCreditTierSchema:ou}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(ee),{VIOLATION_MESSAGES:Om}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:au}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(ee),{ModelMarkupsSchema:wm}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(ee,au),{InvoiceUsageEntrySchema:jm}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(ee),{AttachDiscountSchema:su}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(ee),{CustomLineItemSchema:_m}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(ee),{UnixMsTimestampSchema:Pm}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(ee),{CreateInvoicePreviewLineSchema:Cm}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(ee),{ReissueInvoiceParamsSchema:xo}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(ee),{InvoiceModeParamsSchema:en}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(ee),{InvoiceTemplateSchema:km}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(ee),{BasePriceSchema:Rm}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(ee,eu,mm),{CURRENCY_CODES:Em}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(tu,Am,hm),{ApiPriceProcessorsSchema:cu}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(ee,gm),{AllocatedBillingFieldSchema:Dm}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(ee,xm),{CreditDimensionNameSchema:Tm}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(ee,Sm,vm),{ApiCreditMatchSchema:uu}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Im),{findCreditTierViolations:Mm}=(e=>({findCreditTierViolations:n=>{let r=[],i=(s,c)=>r.push({index:s,reason:c,message:e[c]}),a=0;for(let[s,c]of n.entries()){let u=s===n.length-1;if(c==="inf"){u||i(s,"non_final_infinity");continue}(!Number.isFinite(c)||c<=a)&&i(s,"not_increasing"),a=c,u&&i(s,"final_not_infinity")}return r}}))(Om),{ApiCreditMultiplierSchema:Bm}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(ee,uu),{ProviderMarkupsSchema:qm}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(ee,au),{InvoiceFeatureQuantitySchema:lu}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(ee,iu,jm),{CreateInvoicePreviewSchema:So}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(ee,Cm),{SUPPORTED_SET:zm}=(e=>({SUPPORTED_SET:new Set(e)}))(Em),{ApiCreditDimensionBaseSchema:Nm}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(ee,uu),{refineGraduatedTiers:pu}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:s}of i)r.addIssue({code:"custom",message:s,path:["tiers",a,"to"]})}}))(Mm),{ApiFeatureMarkupsOverrideSchema:Fm}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(ee,qm,wm),{isValidCurrencyCode:Um}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(zm),{ApiCreditDimensionSchema:Vm}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(ee,Nm,ou,pu),{CurrencyCodeSchema:du}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(ee,Um),{AdditionalCurrencyTierSchema:Lm}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(ee,du),{ApiCreditSchemaItemBaseSchema:mu}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(ee,Tm,Vm,Bm),{ApiFlatCreditSchemaItemSchema:$m}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(mu,ee),{AdditionalCurrencyPriceSchema:Gm}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(ee,du),{AdditionalCurrencyTierArraySchema:Km}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(ee,Lm,nu,ru),{ApiGraduatedCreditSchemaItemSchema:Hm}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(mu,ee,ou,pu),{AdditionalCurrencyPriceArraySchema:fu}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(ee,Gm,nu,ru),{ApiUsageTierWithCurrenciesSchema:Zm}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(ee,bm,Km),{ApiCreditSchemaItemSchema:Qm}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(ee,Hm,$m),{BasePriceParamsSchema:Jm}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(Rm,fm,ee,fu),{PlanItemPriceParamsSchema:Wm}=((e,t,n,r,i,a,s)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(u=>u??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:s,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(ee,fu,Zm,ym,eu,iu,Dm),{ApiFeatureOverrideSchema:Xm}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(ee,Qm,Fm),{InvoiceBasePriceParamsSchema:Au}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(Jm,cu),{InvoiceItemPriceParamsSchema:Ym}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(Wm,cu),{InvoiceLicenseQuantitySchema:ef}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(ee,Au,lu),{InvoiceCustomizeItemSchema:tf}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(ee,Ym,Xm),{InvoiceCustomizeSchema:nf}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(ee,Au,tf),{InvoicePlanParamsSchema:rf}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(ee,nf,lu,ef,su),{CreateInvoiceParamsSchema:jn}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(s=>s.period_start===void 0==(s.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(s=>s.period_start===void 0||s.period_end===void 0||s.period_end>s.period_start,{message:"period_end must be after period_start."})}))(ee,rf,_m,su,Pm);var bu=o.strictObject({requestId:o.uuid(),predecessorOperationId:o.uuid().optional(),invoiceMode:en.optional(),entityId:o.uuid().optional(),billingSubscriptionId:o.uuid().optional(),newBillingSubscription:o.literal(!0).optional(),offerId:o.uuid().optional(),nativeOffer:wn.optional(),plans:o.array(o.strictObject({productVersionId:o.uuid(),seatQuantities:o.record(Gr,o.number().int().min(0).max(1e4)).optional(),featureQuantities:o.record(o.uuid(),o.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:o.enum(["stripe","apple","google","merchant"]),currency:se}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),nn=o.strictObject({operationId:o.uuid()}),Fe=o.number().int().min(0).max(1e8),of=o.strictObject({lineId:o.uuid(),productVersionId:o.uuid(),productName:o.string().min(1).max(80),interval:o.enum(["free","week","month","year","one_time"]),intervalCount:o.number().int().min(1).max(156).optional(),baseAmountMinor:Fe,seats:o.array(o.strictObject({key:Gr,quantity:o.number().int().min(0).max(1e4),includedQuantity:o.number().int().min(0).max(1e4),maximumQuantity:o.number().int().min(0).max(1e4),unitAmountMinor:Fe})).max(20),prepaid:o.array(Bc).max(100).optional(),catalogAmountMinor:Fe,trial:o.strictObject({days:o.number().int().min(1).max(730),cardRequired:o.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+Or({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),yu=o.string().regex(/^[A-Za-z0-9_-]{1,200}$/),af=o.strictObject({id:yu,name:o.string().min(1).max(40),percent_off:o.number().gt(0).max(100).optional(),amount_off:o.number().int().positive().optional(),currency:o.string().regex(/^[a-z]{3}$/).optional(),duration:o.enum(["once","repeating","forever"]),duration_in_months:o.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),sf=o.strictObject({subscriptionId:o.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:o.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:o.array(o.strictObject({id:o.string(),price_id:o.string(),quantity:o.number().int().nonnegative(),discounts:o.array(o.strictObject({id:o.string(),coupon:o.string(),start:o.number(),end:o.number().nullable()})).optional()})).min(1).max(100),prorationDate:o.number().int().nonnegative(),amountMinor:o.number().int().positive(),periodStartMs:o.number(),periodEndMs:o.number()}),xu=o.strictObject({invoiceMode:en.optional(),append:sf.optional(),provider:o.literal("stripe"),executor:o.enum(["indiana","merchant"]),accountId:o.string().regex(/^acct_[A-Za-z0-9]+$/),mode:o.enum(["payment","subscription"]),lineItems:o.array(o.strictObject({price:o.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:o.number().int().min(1).max(1e4),priceId:o.uuid(),productName:o.string().min(1).max(80),amountMinor:o.number().int().min(0).max(1e8),currency:o.string().regex(/^[a-z]{3}$/),interval:o.enum(["week","month","year","one_off"]),intervalCount:o.number().int().min(1).max(52),slot:o.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:o.strictObject({mode:o.enum(["graduated","volume"]),tiers:o.array(o.strictObject({upTo:o.number().int().min(1).max(1e6).nullable(),unitAmountMinor:o.number().int().min(0).max(1e8),flatAmountMinor:o.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:o.array(o.strictObject({coupon:yu,terms:af})).max(1),trialPeriodDays:o.number().int().min(1).max(730).nullable(),metadata:o.strictObject({grooveCheckoutId:o.uuid(),grooveCustomerId:o.uuid()}),expiresAt:o.iso.datetime({offset:!0})}),_n=o.strictObject({operationId:o.uuid(),entityId:o.uuid().nullable(),billingSubscriptionId:o.uuid().nullable(),discount:o.strictObject({offerId:o.uuid(),couponId:o.uuid(),discount:Ft,duration:at,amountMinor:Fe,allocations:o.array(o.strictObject({productVersionId:o.uuid(),amountMinor:Fe})).min(1).max(20),expiresAt:o.iso.datetime({offset:!0})}).nullable(),charge:o.strictObject({effectiveAt:o.iso.datetime({offset:!0}),periodEndsAt:o.iso.datetime({offset:!0}),debitMinor:Fe,discountMinor:Fe,taxMinor:Fe,totalMinor:Fe}).nullable(),expiresAt:o.iso.datetime({offset:!0}),provider:o.enum(["stripe","apple","google","merchant"]),nativeOffer:wn.optional(),currency:se,lines:o.array(of).min(1).max(20),catalogAmountMinor:Fe,automaticTax:o.boolean(),execution:o.union([xu,Er]).nullable()}).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),Pn=o.strictObject({operationId:o.uuid(),orderId:o.uuid(),append:o.boolean().optional(),invoiceMode:o.boolean().optional(),status:o.enum(["pending","complete","cancelled","failed"]),executor:o.enum(["indiana","merchant"]),checkoutUrl:o.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:o.union([xu,Er]).nullable(),currency:se,catalogAmountMinor:Fe,taxMinor:Fe,totalMinor:o.number().int().min(0).max(2e8).nullable(),quoteFinalized:o.boolean(),nativePurchase:yo.nullable(),confirmedAt:o.iso.datetime({offset:!0}).nullable().optional(),quote:_n.optional(),merchantExecution:Qt.nullable().optional(),problem:Qn.nullable().optional(),authority:qr.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),Yr=o.strictObject({enabled:o.literal(!0),featureIds:o.array(o.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Su=o.strictObject({requestId:o.uuid(),invoiceMode:en.optional(),membershipId:o.uuid(),carryOverBalances:Yr.optional(),carryOverUsages:Yr.optional(),membershipIds:o.array(o.uuid()).min(1).max(20).optional(),prorationBehavior:o.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:o.enum(["immediate","renewal","store"]),change:o.discriminatedUnion("type",[o.strictObject({type:o.literal("plan"),productVersionId:o.uuid()}),o.strictObject({type:o.literal("seats"),licenseKey:Gr,quantity:o.number().int().min(0).max(1e4)}),o.strictObject({type:o.literal("quantity"),internal_feature_id:o.uuid(),quantity:o.number().int().min(0).max(1e4)}),o.strictObject({type:o.literal("cancel")}),o.strictObject({type:o.literal("uncancel")}),o.strictObject({type:o.literal("billing_cycle"),billingCycleAnchor:o.union([o.literal("now"),o.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Xr=o.string().regex(/^price_[A-Za-z0-9]+$/),hu=o.strictObject({grooveUpdateId:o.uuid(),grooveCustomerId:o.uuid()}),gu=o.strictObject({price:Xr.nullable(),priceId:o.uuid().optional(),quantity:o.number().int().min(0).max(1e4)}),vu=o.strictObject({provider:o.literal("stripe"),invoiceMode:en.optional(),executor:o.enum(["indiana","merchant"]),accountId:o.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:o.string().regex(/^sub_[A-Za-z0-9]+$/),action:o.enum(["update","cancel","schedule","release"]),update:o.strictObject({items:o.array(gu).max(20),remove:o.array(Xr).max(20),restoreItems:o.array(o.strictObject({price:Xr,quantity:o.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:o.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:o.number().int().positive().optional(),paymentBehavior:o.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:o.boolean().optional(),clearCancelAt:o.literal(!0).optional(),billingCycleAnchorNow:o.literal(!0).optional(),metadata:hu}).nullable(),cancel:o.strictObject({prorate:o.literal(!1),invoiceNow:o.literal(!1)}).nullable(),schedule:o.strictObject({currentItems:o.array(o.strictObject({price:Xr,quantity:o.number().int().min(0).max(1e4)})).max(20),nextItems:o.array(gu).min(1).max(20),switchAt:o.number().int().positive(),interval:o.enum(["week","month","year"]),intervalCount:o.number().int().min(1).max(52),resetBillingCycleAnchor:o.literal(!0).optional(),metadata:hu}).nullable(),release:o.strictObject({schedule:o.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:o.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),ei=o.strictObject({carryOverBalances:Yr.optional(),carryOverUsages:Yr.optional(),operationId:o.uuid(),membershipId:o.uuid(),productVersionId:o.uuid(),timing:o.enum(["immediate","renewal"]),effectiveAt:o.iso.datetime({offset:!0}),expiresAt:o.iso.datetime({offset:!0}),currency:se,creditMinor:Fe,debitMinor:Fe,discountMinor:Fe,taxMinor:Fe,totalMinor:Fe,retainedProductVersionIds:o.array(o.uuid()).max(19),execution:o.union([vu,Dr])}),cf=o.strictObject({operationId:o.uuid(),invoiceMode:o.boolean().optional(),membershipId:o.uuid(),productVersionId:o.uuid(),status:o.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:o.enum(["immediate","renewal"]),effectiveAt:o.iso.datetime({offset:!0}),checkoutUrl:o.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:o.enum(["indiana","merchant"]),execution:o.union([vu,Dr]).nullable(),confirmedAt:o.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Qt.nullable().optional(),problem:Qn.nullable().optional(),quote:ei.optional(),authority:qr.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),uf=o.strictObject({operationId:o.uuid(),membershipId:o.uuid(),productVersionId:o.uuid(),timing:o.literal("store"),effectiveAt:o.null(),expiresAt:o.iso.datetime({offset:!0}),currency:se,creditMinor:o.null(),debitMinor:o.null(),discountMinor:o.null(),taxMinor:o.null(),totalMinor:o.null(),retainedProductVersionIds:o.array(o.uuid()).max(19),store:o.strictObject({provider:o.enum(["apple","google"]),productId:o.string().min(1).max(255),catalogAmountMinor:Fe,policy:o.enum(["apple_store","google_full_price"])})}),lf=o.strictObject({operationId:o.uuid(),membershipId:o.uuid(),productVersionId:o.uuid(),status:o.enum(["prepared","pending","effective","cancelled","failed"]),timing:o.literal("store"),effectiveAt:o.iso.datetime({offset:!0}).nullable(),checkoutUrl:o.null(),nativePurchase:yo.nullable()}),Iu=o.union([ei,uf]),vo=o.union([cf,lf]),ar=o.number().int().positive().max(2e8),tn=o.number().int().min(0).max(2e8),Ou=o.strictObject({requestId:o.uuid(),invoiceId:o.uuid(),mode:o.enum(["full","partial"]),amountMinor:ar.optional(),entitlementAction:o.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),wu=o.strictObject({provider:o.literal("stripe"),executor:o.enum(["indiana","merchant"]),accountId:o.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:o.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:ar,currency:o.string().regex(/^[a-z]{3}$/),metadata:o.strictObject({indianaRefundId:o.uuid()}),idempotencyKey:o.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:o.array(o.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Io=o.strictObject({operationId:o.uuid(),invoiceId:o.uuid(),providerInvoiceId:o.string().min(1).max(200),currency:se,paidMinor:tn,refundedMinor:tn,pendingMinor:tn,amountMinor:ar,mode:o.enum(["full","partial"]),entitlementAction:o.enum(["retain","revoke"]),revokes:o.strictObject({customerProductIds:o.array(o.uuid()).max(100),subscriptionIds:o.array(o.string().min(1).max(200)).max(20)}),execution:o.union([wu,Tr]),expiresAt:o.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),ti=o.strictObject({operationId:o.uuid(),invoiceId:o.uuid(),providerInvoiceId:o.string().min(1).max(200),status:o.enum(["quoted","pending","succeeded","failed","expired"]),executor:o.enum(["indiana","merchant"]),currency:se,amountMinor:ar,mode:o.enum(["full","partial"]),entitlementAction:o.enum(["retain","revoke"]),refundId:o.string().min(1).max(200).nullable(),quote:Io.optional(),execution:o.union([wu,Tr]).nullable(),confirmedAt:o.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Qt.nullable().optional(),problem:Qn.nullable().optional(),authority:qr.optional(),failureReason:o.string().min(1).max(200).nullable(),createdAt:o.iso.datetime({offset:!0}),completedAt:o.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),Iy=o.strictObject({invoiceId:o.uuid(),currency:se,paidMinor:tn,refundedMinor:tn,pendingMinor:tn,refundableMinor:tn,executor:o.enum(["indiana","merchant"]).nullable(),canRefund:o.boolean(),operations:o.array(ti).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),Oy=o.strictObject({requestId:o.uuid(),mode:o.enum(["full","partial"]),amountMinor:ar.optional(),entitlementAction:o.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var ju=je.strictObject({requestId:je.uuid(),targets:je.array(je.strictObject({membershipId:je.uuid(),action:je.enum(["cancel","uncancel"]),timing:je.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),ni=je.strictObject({batchId:je.uuid()}),pf=je.strictObject({operationId:je.uuid(),membershipIds:je.array(je.uuid()).min(1).max(20),provider:je.enum(["stripe","apple","google"]),action:je.enum(["cancel","uncancel"]),timing:je.enum(["immediate","renewal"]),status:je.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:ei.nullable(),managementUrl:je.url().nullable(),failureCode:je.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),sr=je.strictObject({batchId:je.uuid(),ready:je.boolean(),status:je.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:je.iso.datetime({offset:!0}),acceptedAt:je.iso.datetime({offset:!0}).nullable(),groups:je.array(pf).min(1).max(100)});import{z as re}from"zod";var df=re.string().trim().min(1).max(240),Oo={requestId:re.uuid(),reason:df},ri=re.discriminatedUnion("action",[re.strictObject({...Oo,action:re.literal("start"),productVersionId:re.uuid(),entityId:re.uuid().optional(),days:re.number().int().min(1).max(730).optional()}),re.strictObject({...Oo,action:re.literal("extend"),membershipId:re.uuid(),days:re.number().int().min(1).max(730)}),re.strictObject({...Oo,action:re.literal("end"),membershipId:re.uuid()})]),_u=re.strictObject({operationId:re.uuid()}),Pu=re.iso.datetime({offset:!0}),mf=re.strictObject({provider:re.literal("stripe"),executor:re.enum(["indiana","merchant"]),accountId:re.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:re.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:re.union([re.literal("now"),Pu]),prorationBehavior:re.literal("none")}),wo=re.strictObject({operationId:re.uuid(),action:re.enum(["start","extend","end"]),status:re.enum(["pending","effective"]),managedBy:re.enum(["indiana","stripe"]),membershipIds:re.array(re.uuid()).min(1).max(20),endsAt:Pu.nullable(),execution:mf.nullable()}).refine(e=>e.execution!==null==(e.managedBy==="stripe"&&e.status==="pending")&&e.action==="end"==(e.endsAt===null)&&(e.action!=="start"||e.managedBy==="indiana")&&(e.execution===null||e.execution.trialEnd==="now"==(e.action==="end")),"Only a pending Stripe trial change carries execution instructions"),ky=re.strictObject({groupId:re.uuid(),productVersionId:re.uuid(),enabled:re.boolean()});import{z as be}from"zod";var Cu=be.strictObject({requestId:be.uuid(),currency:se,makeDefault:be.boolean()}),ku=be.strictObject({setupId:be.uuid()}),ff=be.strictObject({provider:be.literal("stripe"),executor:be.literal("merchant"),accountId:be.string().regex(/^acct_[A-Za-z0-9]+$/),mode:be.literal("setup"),currency:be.string().regex(/^[a-z]{3}$/),customer:be.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:be.uuid(),metadata:be.strictObject({grooveProjectId:be.uuid(),grooveEnvironmentId:be.uuid(),grooveCustomerId:be.uuid(),groovePaymentSetupId:be.uuid()}),setDefaultPaymentMethod:be.boolean(),expiresAt:be.iso.datetime({offset:!0})}),jo=be.strictObject({id:be.uuid(),provider:be.literal("stripe"),status:be.enum(["prepared","complete","expired"]),currency:se,makeDefault:be.boolean(),url:be.url().nullable(),createdAt:be.iso.datetime({offset:!0}),expiresAt:be.iso.datetime({offset:!0}),completedAt:be.iso.datetime({offset:!0}).nullable(),execution:ff.nullable()});import{z as Ue}from"zod";var Ru=Ue.union([Ue.string(),Ue.number(),Ue.boolean(),Ue.null()]),Eu=Ue.strictObject({customerId:Ue.uuid()}),Du=Ue.strictObject({customerId:Ue.uuid(),provider:Ue.literal("stripe"),checkedAt:Ue.iso.datetime({offset:!0}),status:Ue.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ue.number().int().nonnegative(),differences:Ue.array(Ue.strictObject({subscriptionId:Ue.string().startsWith("sub_"),itemId:Ue.string().nullable(),field:Ue.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Ru,actual:Ru})).max(1e4)});import{z as Q}from"zod";var ii=Q.iso.datetime({offset:!0}),oi=Q.strictObject({createdAt:ii,id:Q.uuid()}),ai=Q.strictObject({customerId:Q.uuid().optional(),entityId:Q.uuid().optional(),productId:Q.string().min(1).max(256).optional(),provider:Q.enum(["stripe","apple","google","merchant","free"]).optional(),status:Q.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:oi.optional(),limit:Q.number().int().min(1).max(100).optional()}),_o={id:Q.uuid(),customerId:Q.uuid(),entityId:Q.uuid().nullable(),productId:Q.string().min(1).max(256),productVersionId:Q.uuid(),name:Q.string().min(1).max(120),provider:Q.enum(["stripe","apple","google","merchant","free"]),createdAt:ii},Af=Q.strictObject({..._o,status:Q.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:Q.boolean(),billingSubscriptionId:Q.uuid().nullable()}),hf=Q.strictObject({..._o,status:Q.enum(["active","ended","refunded"]),orderId:Q.uuid().nullable(),transactionId:Q.uuid().nullable(),currency:se.nullable(),amountMinor:Q.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),gf=Q.strictObject({..._o,status:Q.enum(["blocked","resolved"]),conflict:Q.strictObject({detectedAt:ii,blockingMembershipIds:Q.array(Q.uuid()).min(1).max(100),transactionId:Q.uuid()}),resolvedAt:ii.nullable()}),Tu=ai.extend({status:Q.enum(["blocked","resolved"]).optional()}),Mu=Q.strictObject({customerId:Q.uuid(),orderId:Q.uuid()}),Bu=Q.strictObject({orderId:Q.uuid(),status:Q.enum(["blocked","resolved"])}),qu=Q.strictObject({items:Q.array(Af).max(100),nextCursor:oi.nullable()}),zu=Q.strictObject({items:Q.array(hf).max(100),nextCursor:oi.nullable()}),Nu=Q.strictObject({items:Q.array(gf).max(100),nextCursor:oi.nullable()});import{z as Ie}from"zod";var Fu=Ie.union([Ie.strictObject({intent:Ie.literal("read"),requestId:Ie.uuid(),purchaseIntentId:Ie.uuid()}),Ie.strictObject({requestId:Ie.uuid(),provider:Ie.literal("apple"),purchaseIntentId:Ie.uuid(),productId:Ie.string().min(1).max(255).optional(),signedTransaction:Ie.string().min(1).max(131072)}),Ie.strictObject({requestId:Ie.uuid(),provider:Ie.literal("google"),purchaseIntentId:Ie.uuid(),productId:Ie.string().min(1).max(255).optional(),purchaseToken:Ie.string().min(1).max(16384)})]),Uu=Ie.strictObject({requestId:Ie.uuid(),orderId:Ie.uuid(),purchaseIntentId:Ie.uuid(),status:Ie.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:se,refunded:Ie.boolean(),completion:Ie.strictObject({transactionIds:Ie.array(Ie.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Ie.boolean()}).nullable()});import{z as P}from"zod";var Co=P.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),bf=P.record(P.string(),P.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),yf=3,cr=20,xf=yf*cr,Po=P.strictObject({type:P.literal("product"),productId:Co}),Vu={type:P.literal("group"),key:P.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:P.string().trim().min(1).max(80)},Sf=P.discriminatedUnion("type",[Po,P.strictObject({...Vu,items:P.array(Po).max(cr)})]),vf=P.discriminatedUnion("type",[Po,P.strictObject({...Vu,items:P.array(Sf).max(cr)})]),If=P.array(vf).max(cr).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(s){for(let c of s){i++;let u=c.type==="product"?n:r,p=c.type==="product"?c.productId:c.key;u.has(p)&&t.addIssue({code:"custom",message:c.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),u.add(p),c.type==="group"&&a(c.items)}}a(e),(n.size>cr||i>xf)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function ko(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:ko(t))}var Cn=P.strictObject({lookupKey:P.string().trim().min(1).max(200),displayName:P.string().trim().min(1).max(1500),items:If,metadata:bf}),Of=P.strictObject({product:P.record(P.string(),P.json()),prices:P.array(P.record(P.string(),P.json())),entitlements:P.array(P.record(P.string(),P.json())),freeTrials:P.array(P.record(P.string(),P.json())),licenses:P.array(P.record(P.string(),P.json()))}),Lu=Cn.extend({id:P.uuid(),projectId:P.uuid(),environmentId:P.uuid(),state:P.enum(["active","archived"]),isCurrent:P.boolean(),revision:P.number().int().nonnegative(),publishedVersionId:P.uuid().nullable(),createdAt:P.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),$u=P.strictObject({id:P.uuid(),offeringId:P.uuid(),projectId:P.uuid(),environmentId:P.uuid(),version:P.number().int().positive(),document:Cn,productEvidence:P.record(Co,Of),createdAt:P.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=ko(e.document);(!n.length||_f(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),wf=P.strictObject({rows:P.array(Lu).max(200),versions:P.array($u).max(500)}),$y=P.discriminatedUnion("action",[P.strictObject({action:P.literal("create"),document:Cn}),P.strictObject({action:P.literal("save"),id:P.uuid(),revision:P.number().int().nonnegative(),document:Cn}),P.strictObject({action:P.enum(["publish","set_current","archive","restore"]),id:P.uuid(),revision:P.number().int().nonnegative()})]),Gy=P.strictObject({record:Lu,version:$u.nullable()}),Gu=P.discriminatedUnion("type",[P.strictObject({type:P.literal("current")}),P.strictObject({type:P.literal("id"),id:P.uuid()}),P.strictObject({type:P.literal("lookup_key"),lookupKey:P.string().min(1).max(200)}),P.strictObject({type:P.literal("version"),versionId:P.uuid()})]),jf=P.strictObject({internalId:Co,id:P.string(),name:P.string().nullable(),version:P.number().int().positive(),archived:P.boolean()}),Ky=wf.extend({products:P.array(jf).max(500),pagination:P.strictObject({rows:P.string().nullable(),versions:P.string().nullable(),products:P.string().nullable()}).optional()});function _f(e){let t=[];ko(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}import{z as si}from"zod";var Ku=si.strictObject({id:si.uuid(),offeringId:si.uuid(),version:si.number().int().positive(),document:Cn});import{z as Be}from"zod";import{z as H}from"zod";import{z as Me}from"zod";var Pf=Me.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ci=Me.discriminatedUnion("type",[Me.object({type:Me.literal("fixed"),productVersionId:Me.string().min(1).max(200)}).strict(),Me.object({type:Me.literal("picker"),pickerId:Pf,allowedProductVersionIds:Me.array(Me.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Rt=Me.discriminatedUnion("type",[Me.object({type:Me.literal("modal"),size:Me.enum(["sm","md","lg"])}).strict(),Me.object({type:Me.literal("sheet"),size:Me.enum(["sm","md","lg"])}).strict(),Me.object({type:Me.literal("fullscreen")}).strict(),Me.object({type:Me.literal("inline")}).strict()]);var Ro=H.discriminatedUnion("type",[H.strictObject({type:H.literal("event"),event:H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),H.strictObject({type:H.literal("open_url"),url:H.url().refine(e=>new URL(e).protocol==="https:")})]),Cf=it,kf=H.discriminatedUnion("type",[H.object({type:H.literal("checkout"),product:ci}).strict(),H.object({type:H.literal("close")}).strict(),H.object({type:H.literal("action"),action:Ro}).strict()]),kn=H.object({schemaVersion:H.literal(3),kind:H.literal("paywall"),name:H.string().trim().min(1).max(80),presentation:Rt,requirement:An.optional(),products:Ur,offeringVersionId:H.uuid().nullable(),offeringId:H.uuid(),screen:Cf,buttons:H.record(H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),kf)}).strict(),ax=kn.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of Ef(e))t.addIssue({code:"custom",message:r});for(let r of Rf(e))t.addIssue({code:"custom",message:r});Tt(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function Rf(e){let t=e.products.items.map(a=>a.productVersionId),n=As(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!gs(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(s=>s.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let s=a.product;if(s.type==="fixed")r.add(s.productVersionId);else{s.allowedProductVersionIds.forEach(p=>r.add(p));let c=!1,u=n[s.pickerId];u&&(c=!0,(s.allowedProductVersionIds.some(p=>!u.ids.includes(p))||u.ids.some(p=>!s.allowedProductVersionIds.includes(p)))&&i.push("picker")),Pt(e.screen,p=>{if(p.id!==s.pickerId||p.type!=="plan_picker")return;c=!0,(JSON.stringify(p.planIds)!==JSON.stringify(t)||JSON.stringify(s.allowedProductVersionIds)!==JSON.stringify(t)||p.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let y=p.grouping?{tiers:p.grouping.tiers,assignments:p.grouping.assignments}:void 0;JSON.stringify(y)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),c||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Pt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(s=>!t.includes(s)))&&i.push("binding")}),[...new Set(i)]}function Ef(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let c of e.screen.pages)r.set(c.id,[]),Zn(c.root,u=>{let p=u.type==="button"?u.action:u.type==="stack"?u.purchaseAction:void 0;if(p){let y=e.screen.actions.find(N=>N.id===p);y?.type==="navigate"&&r.get(c.id).push(y.pageId);let w=e.buttons[p];c.id!==n.id&&w&&w.type!=="close"&&t.push(`purchaseScreen:${u.id}`)}c.id!==n.id&&(u.type==="plan_picker"||u.type==="stack"&&u.productSlot)&&t.push(`packageScreen:${u.id}`)});let i=new Set;function a(c){if(!i.has(c)){i.add(c);for(let u of r.get(c)??[])a(u)}}let s=e.screen.initialPageId??e.screen.pages[0]?.id;s?a(s):t.push("initialPage");for(let c of e.screen.pages)i.has(c.id)||t.push(`unreachableScreen:${c.id}`);return[...new Set(t)]}var Hu=H.object({id:H.uuid(),projectId:H.uuid(),environmentId:H.uuid(),revision:H.number().int().nonnegative(),state:H.enum(["active","archived"]),publishedVersionId:H.uuid().nullable(),updatedAt:H.iso.datetime({offset:!0}),draft:kn}).strict(),sx=H.object({rows:H.array(Hu).max(200),nextCursor:H.uuid().nullable()}).strict(),cx=Hu.omit({draft:!0}).extend({name:H.string(),productCount:H.number().int().nonnegative()}).strict(),ux=H.discriminatedUnion("action",[H.object({action:H.literal("save"),id:H.uuid().nullable(),revision:H.number().int().nonnegative(),document:kn}).strict(),H.object({action:H.enum(["publish","archive"]),id:H.uuid(),revision:H.number().int().nonnegative()}).strict()]),lx=H.object({paywalls:H.array(H.object({id:H.uuid(),paywallId:H.uuid(),version:H.number().int().positive(),name:H.string().min(1).max(80),presentation:Rt,buttons:kn.shape.buttons}).strict()).max(500),limited:H.boolean()}).strict();import{z as te}from"zod";import{z as Qe}from"zod";var Rn=Qe.string().regex(/^[a-f0-9]{64}$/),Df=ms.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Zu=Qe.strictObject({couponDigests:Qe.record(Qe.uuid(),Rn),variables:Qe.record(mn,Qe.record(Qe.uuid(),Qe.partialRecord(Qe.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Qe.string()))),locales:Qe.record(mn,hn.extend({nodes:Qe.record(Qe.string(),Qe.strictObject({base:Df})),plans:Qe.object({}).strict(),pickers:Qe.object({}).strict()}).omit({paywall:!0}))});import{z as pe}from"zod";import{z as ui}from"zod";var Eo=ui.strictObject({eventsEnabled:ui.boolean(),experimentViewsEnabled:ui.boolean(),featureUsageEnabled:ui.boolean()}),gx=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function bx(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var Do=Mt.extend({analyticsConfig:Eo,remoteFeatures:pe.array(pe.string().min(1).max(255)).max(500)}),Tf=Do.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),Qu=pe.strictObject({attributes:rt,features:pe.array(pe.string().min(1).max(255)).max(500).optional(),customerId:pe.uuid().optional()}),Mf=pe.strictObject({value:me,source:pe.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:pe.boolean(),off:pe.boolean(),ruleId:pe.string(),experimentResult:xs.optional()}),Ju=pe.strictObject({generation:Mt.shape.generation,evaluatedAt:Mt.shape.evaluatedAt,expiresAt:Mt.shape.expiresAt,features:pe.record(pe.string(),Mf),merchandiseContext:pe.strictObject({merchandiseId:pe.uuid(),merchandise:rt}).optional()}),Wu=pe.strictObject({customerId:pe.uuid().optional(),events:pe.array(pe.strictObject({eventUuid:pe.uuid(),timestamp:pe.iso.datetime({offset:!0}),name:pe.string().min(1).max(255),merchandise:pc.optional(),properties:pe.record(pe.string(),me).default({}),deviceId:pe.string().min(1).max(255).optional(),sessionId:pe.string().min(1).max(255).optional()})).min(1).max(100)}),Xu=pe.strictObject({inserted:pe.number().int().nonnegative(),duplicates:pe.number().int().nonnegative(),rejected:pe.number().int().nonnegative(),skipped:pe.number().int().nonnegative(),analyticsConfig:Eo});import{z as C}from"zod";function To(e,t=[]){let n=[];Pt(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(zi(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let s of Object.keys(a))r.has(s)||n.push(`Unused string ${s} must not be delivered (${i})`);return n}function Yu(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Yu(t)??[])}}function Bf(e){let t=e.pages.map(i=>{let a=Yu(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(zi({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([s])=>n.has(s)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function el(e,t=[]){let n=it.parse(structuredClone(Bf(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=To(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as E}from"zod";import{z as En}from"zod";var tl=En.strictObject({id:En.uuid(),name:En.string().trim().min(1).max(80),client:Is,source:Cr,event:En.enum(["screen_enter","button_click"]),cooldownSeconds:En.number().int().min(0).max(2592e3),behavior:En.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as Ae}from"zod";var Mo=me,qf=["parameters","answers","results","variables"];function Bo(e){return qf.some(t=>e===t||e.startsWith(t+"."))}function qo(e){let t={};for(let[r,i]of Object.entries(Wn(e.declarations,e))){let a=r.split(".");if(a.some(u=>["__proto__","constructor","prototype"].includes(u)))throw new Error("Reserved result path");let s=t;for(let u of a.slice(0,-1)){Object.hasOwn(s,u)||(s[u]={});let p=s[u];if(!p||typeof p!="object"||Array.isArray(p))throw new Error("Ambiguous result path");s=p}let c=a.at(-1);if(c===void 0)throw new Error("Empty result path");s[c]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!Bo(r))),variables:t}}import{z as zf}from"zod";var li=zf.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var zo=Ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),nl=Ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),rl=xt.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),No=Ae.record(zo,Ae.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),Nf=St,il=Ae.strictObject({type:Ae.literal("external_task"),endpointId:Ae.uuid(),taskKey:zo,inputs:Ae.record(zo,Nf).refine(e=>Object.keys(e).length<=20),outputs:No}),ol=Ae.strictObject({maxAttempts:Ae.number().int().min(1).max(5),retryDelaySeconds:Ae.number().int().min(1).max(30),backoff:Ae.enum(["fixed","exponential"]),requestTimeoutSeconds:Ae.number().int().min(1).max(10),timeoutSeconds:Ae.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var Lx=Ae.strictObject({outcome:Ae.enum(["success","failure"]),data:rl});var $x=Ae.discriminatedUnion("operation",[Ae.strictObject({operation:Ae.literal("signal"),runId:Ae.uuid(),nodeId:nl,eventName:li,eventId:Ae.uuid(),data:rl}),Ae.strictObject({operation:Ae.literal("read_results"),runId:Ae.uuid()})]),Gx=Ae.strictObject({scope:ve,runId:Ae.uuid(),eventId:Ae.uuid(),accepted:Ae.boolean()}),Ff=Ae.record(nl,Mo),Kx=Ae.strictObject({scope:ve,runId:Ae.uuid(),results:Ff});var ht={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},al="00000000-0000-0000-0000-000000000000";import{z as T}from"zod";import{z as ye}from"zod";var Xx=ye.enum(["local","remote"]),Fo=ye.strictObject({port:ye.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:me.optional(),sticky:ye.array(ye.strictObject({expected:_r.nullable(),next:_r})).max(100),exposures:ye.array(me).max(100),features:ye.array(me).max(100)}),sl=ye.strictObject({type:ye.literal("evaluate"),receiptId:ye.uuid(),environmentId:ye.uuid(),policyRevision:ye.number().int().nonnegative(),attributes:rt,sticky:ye.record(ye.string(),_r)}),cl=sl.extend({runId:ye.uuid(),versionId:ye.uuid(),nodeId:ye.string().min(1).max(64),visit:ye.number().int().nonnegative(),revision:ye.number().int().nonnegative()}),Uo=sl.omit({type:!0,receiptId:!0}).extend({type:ye.literal("evaluate_segment")}),ul=ye.strictObject({nodeId:ye.string().min(1).max(64),result:Fo}),ll=Uo.extend({runId:ye.uuid(),versionId:ye.uuid(),nodeId:ye.string().min(1).max(64),visit:ye.number().int().nonnegative(),revision:ye.number().int().nonnegative(),parameters:xt,answers:Zt,variables:ye.record(ye.string(),me)});import{z as $}from"zod";var Vo=$.array($.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),pi=$.intersection(rt,$.looseObject({tags:Vo.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),di=$.string().trim().max(80),mi=$.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),fi=$.union([$.email().max(254),$.literal("")]),Ai=$.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),pl=$.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),dl=$.object({externalUserId:pl.optional(),name:di.default(""),email:fi.default(""),phone:mi.optional(),attributes:pi.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Dn=$.discriminatedUnion("type",[$.strictObject({type:$.literal("id"),value:$.uuid()}),$.strictObject({type:$.literal("externalUserId"),value:pl})]),Tn=$.strictObject({name:di.optional(),email:fi.optional(),phone:mi.optional(),attributes:pi.optional(),fingerprint:Ai.optional()}),rn=e=>!e.customerData||e.customer?.type==="externalUserId",on="customerData requires an externalUserId customer",Mn=$.object({id:$.uuid(),externalUserId:$.string().min(1).max(255).nullable(),name:di,email:fi,phone:mi.optional(),attributes:pi,createdAt:$.iso.datetime()}).strict(),ml=$.object({customer:Mn,changed:$.boolean(),replayed:$.boolean()}).strict(),Uf=$.discriminatedUnion("type",[$.object({type:$.literal("id"),value:$.uuid()}).strict(),$.object({type:$.literal("externalUserId"),value:$.string().trim().min(1).max(255)}).strict()]),Vf=$.object({name:di.optional(),email:fi.optional(),phone:mi.optional(),attributes:pi.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:$.array($.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:$.strictObject({add:Vo,remove:Vo}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Lo=$.object({lookup:Uf}).strict(),fl=Lo.extend({requestId:$.uuid(),patch:Vf}).strict(),Al=$.object({search:$.string().trim().max(200).default(""),tag:$.string().trim().max(40).default(""),planId:$.string().max(200).default(""),versionId:$.string().max(200).default(""),holdingStatus:$.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:$.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:$.union([$.iso.datetime(),$.literal("")]).default(""),createdUntil:$.union([$.iso.datetime(),$.literal("")]).default(""),offset:$.coerce.number().int().min(0).max(1e5).default(0),limit:$.coerce.number().int().min(1).max(100).default(50)}).strict(),hl=$.object({customers:Mn.array(),hasMore:$.boolean(),total:$.number().int().nonnegative().nullable(),evaluatedAt:$.iso.datetime()}).strict();var ur=T.discriminatedUnion("type",[T.strictObject({type:T.literal("literal"),value:me}),T.strictObject({type:T.literal("variable"),key:Te,path:At.optional()}),T.strictObject({type:T.literal("feature"),featureKey:T.string().min(1).max(128)})]),Lf=T.strictObject({requestId:T.uuid(),decisionId:T.uuid(),customerId:T.uuid(),externalUserId:T.string().min(1).max(255).nullable(),versionId:T.uuid(),receiptId:T.uuid(),value:me}),$o={funnelId:T.uuid(),requestId:T.uuid(),customer:Dn,customerData:Tn.optional(),attributes:rt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},lS=T.discriminatedUnion("operation",[T.strictObject({operation:T.literal("decide"),...$o}).refine(rn,on),T.strictObject({operation:T.literal("read_decision"),decisionId:T.uuid()}),T.strictObject({operation:T.literal("evaluate_decision"),decisionId:T.uuid(),requestId:T.uuid(),nodeId:T.string().min(1).max(64),visit:T.number().int().nonnegative(),revision:T.number().int().nonnegative(),receiptId:T.uuid(),policyRevision:T.number().int().nonnegative(),generation:T.string().min(1).max(256),result:Fo}),T.strictObject({operation:T.literal("feature_config"),funnelId:T.uuid()}),T.strictObject({operation:T.literal("commit_decision_segment"),decisionId:T.uuid(),requestId:T.uuid(),nodeId:T.string().min(1).max(64),visit:T.number().int().nonnegative(),revision:T.number().int().nonnegative(),policyRevision:T.number().int().nonnegative(),generation:T.string().min(1).max(256),steps:T.array(ul).max(32),boundary:T.strictObject({nodeId:T.string().min(1).max(64),visit:T.number().int().nonnegative()}).optional()}),T.strictObject({operation:T.literal("segment_configuration"),funnelId:T.uuid(),versionId:T.uuid()}),T.strictObject({operation:T.literal("configuration"),funnelId:T.uuid(),versionId:T.uuid().optional()}),T.strictObject({operation:T.literal("local_configuration"),funnelId:T.uuid()}),T.strictObject({operation:T.literal("report_used"),decisionId:T.uuid(),eventId:T.uuid(),occurredAt:T.iso.datetime({offset:!0}),reference:T.string().min(1).max(128).optional()})]),pS=T.strictObject({scope:ve,decisionId:T.uuid(),requestId:T.uuid(),status:T.enum(["pending","completed","failed"]),decision:Lf.nullable(),evaluation:T.discriminatedUnion("type",[cl,ll]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),dS=T.strictObject({scope:ve,decisionId:T.uuid(),eventId:T.uuid(),source:T.literal("caller_reported")});import{z as Ve}from"zod";var gl=Ve.strictObject({type:Ve.literal("bundle"),paywall:St.optional(),offering:St.optional(),coupons:St,data:St}),$f=e=>Ve.strictObject({type:Ve.literal(e),id:Ve.uuid()}),bS=Ve.strictObject({type:Ve.literal("bundle"),paywallVersionId:Ve.uuid().optional(),offeringVersionId:Ve.uuid().optional(),couponIds:Ve.array(Ve.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:me});var yS=Ve.strictObject({type:Ve.literal("bundle"),offering:$f("offering_version").nullable(),paywall:Ve.strictObject({versionId:Ve.uuid(),paywallId:Ve.uuid(),offeringVersionId:Ve.uuid()}).nullable(),coupons:Ve.array(Yn).max(20),data:me});import{z as gt}from"zod";import{z as pt}from"zod";var bl=pt.union([pt.string(),pt.number().finite(),pt.boolean(),pt.null()]),Gf=pt.union([bl,pt.array(bl).min(1).max(20)]),Kf=pt.record(At,Gf).refine(e=>Object.keys(e).length<=10),yl=pt.strictObject({path:At,type:pt.enum(["string","number","boolean","strings"]),nullable:pt.boolean().optional(),aggregation:pt.enum(["count","exists"]).optional(),where:Kf.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var Hf=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],xl=gt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Zf=St,Sl=gt.discriminatedUnion("type",[il,gt.strictObject({type:gt.literal("claim_offer"),coupon:St}),gt.strictObject({type:gt.literal("event"),event:xl}),gt.strictObject({type:gt.literal("api"),operation:gt.enum(Hf),inputs:gt.record(At,Zf).refine(e=>Object.keys(e).length<=40),outputs:gt.record(xl,yl).refine(e=>Object.keys(e).length<=20)})]);var Pe=li,Qf=E.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),st={id:Pe,name:E.string().trim().min(1).max(80),position:E.strictObject({x:E.number().finite(),y:E.number().finite()}).optional()},Jf={success:Pe,cancel:Pe,unavailable:Pe,failure:Pe},Go=E.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Ko=E.enum(["same_window","new_window"]),Wf=E.discriminatedUnion("type",[E.strictObject({...st,type:E.literal("entry"),next:Pe,triggers:E.array(tl).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),E.strictObject({...st,type:E.literal("screen"),screenId:Pe,presentation:Rt,outputs:E.record(Pe,Pe),offering:E.discriminatedUnion("source",[E.strictObject({source:E.literal("variable"),key:Te}),E.strictObject({source:E.literal("fixed"),versionId:E.uuid()})]).optional()}),E.strictObject({...st,type:E.literal("offering"),configuration:E.discriminatedUnion("source",[E.strictObject({source:E.literal("fixed"),versionId:E.uuid()}),E.strictObject({source:E.literal("feature"),featureKey:E.string().min(1).max(128)})]),writes:E.strictObject({value:Te}),next:Pe}),E.strictObject({...st,type:E.literal("coupon"),couponId:E.uuid(),writes:E.strictObject({value:Te}),next:Pe}),E.strictObject({...st,type:E.literal("coupons"),couponIds:E.array(E.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:E.strictObject({value:Te}),next:Pe}),E.strictObject({...st,type:E.literal("output"),value:E.discriminatedUnion("type",[...ur.options,gl,E.strictObject({type:E.literal("selection"),screenId:Pe,offeringKey:Te})])}),E.strictObject({...st,type:E.literal("condition"),cases:E.array(E.strictObject({condition:Ht,target:Pe})).min(1).max(50),default:Pe}),E.strictObject({...st,type:E.literal("feature"),featureKey:E.string().min(1).max(128),writes:E.strictObject({value:Te}),next:Pe}),E.strictObject({...st,type:E.literal("split"),experimentId:E.uuid(),applyPageExperiment:E.literal(!0).optional(),routes:E.record(Qf,Pe).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:Pe}),E.strictObject({...st,type:E.literal("action"),...Jf,execution:ol,action:Sl,writes:zr.optional()}),E.strictObject({...st,type:E.literal("external_page"),appManifest:Cr.optional(),url:Go,openIn:Ko,opened:Pe,failed:Pe}),E.strictObject({...st,type:E.literal("end"),outcome:E.enum(["completed","closed","ineligible","failed"]),output:ur.optional()}),E.strictObject({...st,type:E.literal("wait"),writes:zr.optional(),wait:E.discriminatedUnion("type",[E.strictObject({type:E.literal("duration"),delaySeconds:E.number().int().min(1).max(2592e3),elapsed:Pe}),E.strictObject({type:E.literal("event"),eventName:Pe,outputs:No,timeoutSeconds:E.number().int().min(1).max(2592e3),received:Pe,timeout:Pe})])})]),Ho=E.strictObject({version:E.literal(5),entry:Pe,nodes:E.array(Wf).min(1).max(ht.flowNodes)}),Zo=Ho.superRefine((e,t)=>{Xf(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function hi(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function Xf(e,t){let n=[],r=new Map(e.nodes.map(y=>[y.id,y])),i=(y,w,N)=>{n.push(y),t?.({message:y,reason:w,path:N?["nodes",e.nodes.indexOf(N)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(y=>y.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(y=>y.type==="screen").length>ht.pages||e.nodes.filter(y=>!["screen","entry","end","output"].includes(y.type)).length>ht.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let y of e.nodes){for(let w of hi(y))w===e.entry&&i("An entry cannot be a transition target","entryTarget",y),r.has(w)||i(`Missing target ${w}`,"missingTarget",y);y.type==="screen"&&(a.has(y.screenId)&&i("Every screen has exactly one node owner","screenOwner",y),a.add(y.screenId))}let s=new Set,c=new Set,u=new Set;function p(y){if(s.has(y)){i("Flow edges must not form a cycle","cycle",r.get(y));return}if(!(c.has(y)||!r.has(y))){s.add(y),u.add(y);for(let w of hi(r.get(y)))p(w);s.delete(y),c.add(y)}}p(e.entry);for(let y of e.nodes)u.has(y.id)||i("Every node must be reachable from Entry","unreachable",y);return[...new Set(n)]}var Qo={maxTransitions:1e4,runTimeoutSeconds:2592e3};function vl(e,t,n){let r=[...t].sort((c,u)=>u.length-c.length),i=new Set,a=(c,u=!1)=>{let p=r.find(y=>c===y||u&&c.startsWith(y+"."));i.add(p??c)};if(e.type==="condition"){let c=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let u of e.cases.slice(0,c+1))for(let p of Nt(u.condition))p.startsWith("variables.")&&a(p.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let c of Object.values(e.action.inputs))c.source==="variable"&&a(c.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let s=e.type==="output"?e.value:e.type==="end"?e.output:null;if(s?.type==="variable"&&a(s.key),s?.type==="bundle")for(let c of[s.paywall,s.offering,s.coupons,s.data])c?.source==="variable"&&a(c.key);return s?.type==="selection"&&a(s.offeringKey),[...i]}import{z as S}from"zod";var Bn=S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),gi=e=>S.record(S.string(),me).refine(t=>ot(t)<=e,"Funnel evidence exceeds its byte budget"),JS=S.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Wo=S.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Xo=S.discriminatedUnion("type",[S.strictObject({type:S.literal("flag"),key:S.string().min(1).max(128)}),S.strictObject({type:S.literal("experiment"),id:S.uuid()}),S.strictObject({type:S.literal("saved_group"),id:S.uuid()}),S.strictObject({type:S.literal("config"),key:S.string().min(1).max(128)}),S.strictObject({type:S.literal("constant"),key:S.string().min(1).max(128)}),S.strictObject({type:S.literal("paywall_version"),id:S.uuid()}),S.strictObject({type:S.literal("offering_version"),id:S.uuid()}),S.strictObject({type:S.literal("reward"),id:S.uuid()})]),lr=S.strictObject({schemaVersion:S.literal(1),kind:Wo,selector:Xo.nullable(),context:gi(131072),contract:S.strictObject({version:S.number().int().positive(),evaluator:S.string().min(1).max(128),policyRevision:S.number().int().nonnegative()})}).refine(e=>ot(e)<=131072,"Node input exceeds its byte budget"),Il=S.strictObject({schemaVersion:S.literal(1),kind:Wo,outcome:S.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:gi(131072),route:S.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:gi(131072)}).refine(e=>ot(e)<=131072,"Node result exceeds its byte budget"),WS=S.strictObject({schemaVersion:S.literal(1),operations:S.record(Bn,S.strictObject({attempts:S.number().int().nonnegative(),maxAttempts:S.number().int().min(1).max(5),deadlineAt:S.iso.datetime({offset:!0}),retryAt:S.iso.datetime({offset:!0}).nullable(),error:S.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:S.strictObject({type:Bn,id:S.uuid()}).nullable()}))}).refine(e=>ot(e)<=65536,"Execution state exceeds its byte budget"),an={receiptId:S.uuid()},Jo=S.iso.datetime({offset:!0}),XS=S.discriminatedUnion("type",[S.strictObject({type:S.literal("node_entered"),details:S.strictObject({kind:Wo})}),S.strictObject({type:S.literal("presentation_shown"),details:S.strictObject({...an,source:S.literal("client"),occurredAt:Jo.optional()})}),S.strictObject({type:S.literal("decision_accepted"),details:S.strictObject(an)}),S.strictObject({type:S.literal("signal_received"),details:S.strictObject({signalId:S.uuid(),nodeId:Bn,eventName:Bn,data:gi(8192),source:S.literal("server"),occurredAt:Jo})}),S.strictObject({type:S.literal("signal_consumed"),details:S.strictObject({...an,signalId:S.uuid()})}),S.strictObject({type:S.literal("wait_elapsed"),details:S.strictObject(an)}),S.strictObject({type:S.literal("wait_timeout"),details:S.strictObject(an)}),S.strictObject({type:S.literal("operation_completed"),details:S.strictObject({...an,operation:Bn,reference:S.strictObject({type:Bn,id:S.uuid()}).nullable()})}),S.strictObject({type:S.literal("execution_recovered"),details:S.strictObject({generation:S.number().int().positive(),reason:S.enum(["interrupted","expired_lease","delivery_failed"])})}),S.strictObject({type:S.literal("execution_failed"),details:S.strictObject({generation:S.number().int().positive(),code:S.string().regex(/^[a-z_]{1,64}$/)})}),S.strictObject({type:S.literal("run_completed"),details:S.strictObject({outcome:S.enum(["completed","ineligible","failed"])})}),S.strictObject({type:S.literal("run_closed"),details:S.strictObject({source:S.enum(["client","server","expiry"])})}),S.strictObject({type:S.literal("treatment_used"),details:S.strictObject({...an,source:S.enum(["client","server"]),occurredAt:Jo,reference:S.string().min(1).max(128).optional()})})]);var dt=C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Yf=C.discriminatedUnion("type",[C.strictObject({id:dt,type:C.literal("owned"),publicData:Zu.optional(),document:it.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),C.strictObject({id:dt,type:C.literal("paywall"),paywallVersionId:C.uuid()})]),Yo={kind:C.literal("funnel"),schemaVersion:C.literal(4),screens:C.array(Yf).max(ht.pages),references:C.record(dt,Xo).refine(e=>Object.keys(e).length<=500),inputs:C.array(C.strictObject({variable:dt,screenId:dt,componentId:dt,required:C.boolean()})).max(ht.questions),variables:C.record(Te,xn).refine(e=>Object.keys(e).length<=ht.logicNodes),outputSchema:yn,execution:C.strictObject({runTimeoutSeconds:C.number().int().min(1).max(Qo.runTimeoutSeconds),maxTransitions:C.number().int().min(1).max(Qo.maxTransitions)})},g0=C.strictObject({...Yo,graph:Ho});function eA(e,t){let n=!1,r=(i,a)=>{let s=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(c=>c[i.text]?.includes("{{offer."))&&!(s&&t(s))&&(n=!0),i.type==="stack"&&i.children.forEach(c=>r(c,s))};for(let i of e.pages)r(i.root);return n}function yi(e){return Array.isArray(e)?e.some(yi):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===al:yi(n))}function tA(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,i]of e.screens.entries()){if(i.type!=="owned")continue;let a;try{a=el(i.document)}catch(s){t.push({message:s instanceof Error?s.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[s,c]of e.inputs.entries())c.screenId===i.id&&!Ni(a,c.componentId)&&t.push({message:`Local Funnel input ${c.variable} targets hidden component ${c.componentId} on screen ${c.screenId}`,reason:"inputBinding",path:["inputs",s]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],s=i.type==="screen"?e.screens.find(c=>c.id===i.screenId):void 0;s?.type==="owned"&&(s.document.actions.some(c=>typeof c.properties.templateKey=="string"&&c.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),eA(s.document,c=>n.has(c))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&yi(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&yi(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Ol(e,t){for(let{message:n,reason:r,path:i}of tA(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function wl(e,t){let n=(O,d,g=[])=>t.addIssue({code:"custom",message:O,path:g,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(O=>[O.id,O])),a=(O,d)=>r.some(g=>g.type===O&&("id"in g?g.id:g.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let s=e.graph.nodes.filter(O=>O.type==="screen");(s.length!==i.size||s.some(O=>!i.has(O.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let c=new Map,u=Object.keys(e.variables);u.some(O=>u.some(d=>O!==d&&d.startsWith(O+".")))&&n("Variable paths must not overlap","variable");function p(O,d){Object.hasOwn(e.variables,O)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let g=c.get(O)??new Set;g.add(d.id),c.set(O,g)}for(let[O,d]of e.graph.nodes.entries()){let g=["graph","nodes",O],D=d.type==="feature"?d.featureKey:d.type==="offering"&&d.configuration.source==="feature"?d.configuration.featureKey:d.type==="output"&&d.value.type==="feature"?d.value.featureKey:d.type==="end"&&d.output?.type==="feature"?d.output.featureKey:null;D&&!a("flag",D)&&n("Flag selectors require an explicit GB resource reference","feature",g);let Y=d.type==="feature"||d.type==="offering"||d.type==="coupon"||d.type==="coupons"||d.type==="action"&&d.action.type==="api"?["value"]:d.type==="action"&&d.action.type==="external_task"?Object.keys(d.action.outputs):d.type==="wait"&&d.wait.type==="event"?Object.keys(d.wait.outputs):[],ne="writes"in d?d.writes??{}:{};(Y.length!==Object.keys(ne).length||Y.some(B=>!Object.hasOwn(ne,B))||new Set(Object.values(ne)).size!==Object.values(ne).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[B,ce]of Object.entries(ne)){p(ce,d);let ie=e.variables[ce],L=d.type==="offering"?"offering_version":d.type==="coupon"?"reward":d.type==="action"&&d.action.type==="api"?"json":d.type==="action"&&d.action.type==="external_task"?d.action.outputs[B]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[B]:void 0;(ie?.source.type!=="node"||L&&ie.type!==L)&&n("Node writer source or output type does not match declaration","variable",g)}if(d.type==="coupons"){let B=e.variables[d.writes.value];(B?.type!=="array"||B.items?.type!=="reward"||B.items.nullable||B.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let ce of d.couponIds)a("reward",ce)||n("Coupons require Reward references","coupon",g)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let B=d.action.coupon.value;(!B||typeof B!="object"||Array.isArray(B)||B.type!=="reward"||typeof B.id!="string"||Object.keys(B).length!==2||!a("reward",B.id))&&n("Coupon claims require a Reward reference","coupon",g)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),d.type==="screen"&&d.offering?.source==="variable"&&e.variables[d.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",g),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="variable"&&(e.variables[d.action.coupon.key]?.type!=="reward"||d.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",g),d.type==="screen"){let B=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",g),B?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",g),B?.type==="paywall"&&!a("paywall_version",B.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),B?.type==="owned"){let ce=B.document.pages[0];if(!ce){n("Owned screen requires a page","screen",g);continue}Tt(B.document).some(L=>!L.complete)&&n("Owned screens require complete local content","translations",g);let ie=new Set(B.document.actions.map(L=>L.id));(ie.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(L=>!ie.has(L)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",g),Zn(ce.root,L=>{!d.offering&&(L.type==="plan_picker"||(L.type==="stack"||L.type==="button")&&L.bind?.plan||L.type==="customer_data"&&["customer_plans","credit_packs"].includes(L.data.source))&&n("Product presentation requires an Offering Version","offering",g),L.type==="customer_data"&&Object.values(L.data.outputs??{}).some(Xe=>Xe!==void 0&&!ie.has(Xe))&&n("Customer components require declared screen outcomes","componentOutput",g)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",g),d.type==="end"&&d.output?.type==="literal"&&!lt(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",g),d.type==="output"&&d.value.type==="literal"&&!lt(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",g);let Se=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(Se?.type==="variable"&&!Se.path){let B=e.variables[Se.key];B&&!Qi(B,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(d.type==="screen"){let B=i.get(d.screenId);if(B?.type==="owned")for(let ce of Yi(B.document))(/^(input|params)\./.test(ce)||ce.startsWith("variables.")&&!Xi(ce.slice(10),u))&&n("Screen values must reference registered variables","variable",g)}if(d.type==="condition")for(let B of d.cases){for(let ce of Dt(B.condition))a("saved_group",ce)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let ce of Nt(B.condition))ce.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[B,ce]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let ie=d.value[B];if(ie)if(ie.source==="literal"){let L=B==="coupons"?ie.value:[ie.value];(!Array.isArray(L)||L.length>20||L.some(Xe=>!lt({type:ce,nullable:!1},Xe)||!a(ce,Xe.id))||B==="coupons"&&new Set(L.map(Xe=>Xe.id)).size!==L.length)&&n("Bundle requires distinct scoped resource references",B==="coupons"?"coupon":B==="paywall"?"paywall":"offering",[...g,"value",B])}else{let L=e.variables[ie.key];(ie.path||!L||L.nullable||(B==="coupons"?L.type!=="array"||L.items?.type!=="reward"||L.items.nullable:L.type!==ce))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[O,d]of e.graph.nodes.entries()){let g=d.type==="screen"?i.get(d.screenId):void 0,D=[...vl(d,u),...g?.type==="owned"?Nr(g.document).map(Y=>Xi(Y,u)?.key??Y):[]];for(let Y of new Set(D)){let ce=function(ie){if(ie===d.id)return!0;if(B.has(ie))return!1;B.add(ie);let L=e.graph.nodes.find(Ye=>Ye.id===ie);return L?(Se.has(ie)?L.type==="action"?[L.cancel,L.unavailable,L.failure]:L.type==="wait"&&L.wait.type==="event"?[L.wait.timeout]:[]:hi(L)).some(ce):!1};var N=ce;if(!Object.hasOwn(e.variables,Y)){n("Consumed variable is undeclared","variable",["graph","nodes",O]);continue}let ne=e.variables[Y];if(d.type==="screen"&&ne.source.type==="input"&&e.inputs.some(ie=>ie.screenId===d.screenId&&ie.variable===Y)||ne.source.type==="parameter"||ne.source.type==="attribute")continue;let Se=ne.source.type==="input"?new Set(e.inputs.filter(ie=>ie.variable===Y&&ie.required).flatMap(ie=>s.filter(L=>L.screenId===ie.screenId).map(L=>L.id))):c.get(Y)??new Set,B=new Set;(!Se.size||ce(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",O])}}(new Set(e.inputs.map(O=>O.variable)).size!==e.inputs.length||new Set(e.inputs.map(O=>`${O.screenId}:${O.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[O,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",O]);let g=i.get(d.screenId),D=g?.type==="owned"?Ni(g.document,d.componentId):null;if((D?.type!=="stack"||!D.interaction||!["input","toggle","select","multiselect","tabs"].includes(D.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",O]),D?.type==="stack"&&D.interaction){let Y=D.interaction.type==="toggle"?"boolean":D.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==Y&&n("Input variable type does not match component","inputBinding",["inputs",O]);let ne=e.variables[d.variable]?.enum;ne&&!D.children.filter(Se=>!Se.hidden).every(Se=>ne.includes(Se.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",O])}}for(let[O,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",O]),d.source.type==="input"&&!e.inputs.some(g=>g.variable===O)&&n("Input variable requires a component binding","inputBinding",["variables",O]);let y=0,w=0;for(let O of e.screens)if(O.type==="owned"){for(let d of O.document.pages)Zn(d.root,()=>{y++});w+=O.document.actions.length}(y>ht.components||w>ht.actions||ot(e)>ht.documentBytes)&&n("Funnel document exceeds its budget","budget")}var nA=C.strictObject({...Yo,graph:Zo}).superRefine(wl),Vt=C.strictObject({...Yo,graph:Zo,displayName:C.string().trim().min(1).max(80)}).superRefine(wl),b0=Vt.superRefine(Ol),y0=nA.superRefine(Ol),bi=C.string().regex(Bt),pr={requestId:C.uuid(),nodeId:dt,visit:C.number().int().nonnegative(),revision:C.number().int().nonnegative(),customerToken:bi.optional()},rA=C.discriminatedUnion("type",[C.strictObject({type:C.literal("screen"),output:dt,answers:Zt,selection:C.record(dt,C.union([C.string().max(200),C.boolean(),C.number().int().min(0).max(1e4)])).optional()}),C.strictObject({type:C.literal("paywall_quote"),featureQuantities:C.record(C.uuid(),C.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:dt,productVersionId:C.uuid(),offerId:C.uuid().optional(),nativeOffer:wn.optional(),predecessor:C.strictObject({operationId:C.uuid().nullable(),generation:C.number().int().positive()}).optional()}),C.strictObject({type:C.literal("paywall_confirm"),operationId:C.uuid()}),C.strictObject({type:C.literal("paywall_cancel"),operationId:C.uuid()}),C.strictObject({type:C.literal("client_action"),receiptId:C.uuid(),outcome:C.enum(["success","cancel","failure","opened","failed"])})]),iA=C.object({nodeId:dt,visit:C.number().int().nonnegative(),revision:C.number().int().nonnegative(),components:C.record(dt,C.object({resourceKey:C.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:C.number().int().min(1).max(1e5),after:kr.nullable(),filter:C.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),x0=C.discriminatedUnion("operation",[C.strictObject({operation:C.literal("start"),funnelId:C.uuid(),requestId:C.uuid(),customer:Dn.optional(),customerData:Tn.optional(),locale:C.string().min(1).max(35),parameters:xt}).refine(rn,on),C.strictObject({operation:C.literal("get"),settlementRequestId:C.uuid().optional(),data:iA.optional(),purchase:C.strictObject({receiptId:C.uuid(),operationId:C.uuid()}).optional(),customerToken:bi.optional()}),C.strictObject({operation:C.literal("resume"),requestId:C.uuid(),customerToken:bi.optional()}),C.strictObject({operation:C.literal("submit"),...pr,input:rA}),C.strictObject({operation:C.literal("back"),...pr}),C.strictObject({operation:C.literal("shown"),...pr}),C.strictObject({operation:C.literal("close"),...pr}),C.strictObject({operation:C.literal("commit_segment"),...pr,policyRevision:C.number().int().nonnegative(),generation:C.string().min(1).max(256)}),C.strictObject({operation:C.literal("review"),receiptId:C.uuid().optional(),customerToken:bi.optional()})]);function xi(e,t){let n=new Set,r=new Set,i=new Set,a=[],s=new Map,c=new Map,u=new Map;function p(d){for(let g of Dt(d))y(g)}function y(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let g=t.savedGroups[d];g&&(i.add(d),u.set(d,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&p(g.condition)}))}function w(d){for(let g of["hashAttribute","fallbackAttribute"])if(d[g]!==void 0&&Bo(d[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);p(d.condition);for(let g of d.parentConditions??[])N(g.id),p(g.condition)}function N(d,g=!1){let D=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!D){if(g)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),s.set(d,D),a.push(()=>{for(let Y of D.rules??[]){w(Y);for(let ne of Y.tracks??[])w(ne.experiment)}}))}function O(d){let g=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),c.set(d,g),a.push(()=>w(g)))}for(let d of e.graph.nodes){d.type==="feature"&&N(d.featureKey,!0),d.type==="split"&&O(d.experimentId),d.type==="condition"&&d.cases.forEach(D=>p(D.condition)),d.type==="offering"&&d.configuration.source==="feature"&&N(d.configuration.featureKey,!0);let g=d.type==="output"?d.value:d.type==="end"?d.output:null;g?.type==="feature"&&N(g.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(s),experiments:Object.fromEntries(c),savedGroups:Object.fromEntries(u)}}import{z as V}from"zod";import{z as dr}from"zod";var jl=dr.object({defaultLocale:mn,locales:dr.record(mn,dr.object({name:dr.string().max(80),description:dr.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var oA=["customer_data","coupon_code"],aA=V.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),_l=V.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Si=(e,t)=>new Set(e.map(t)).size===e.length,sA=V.strictObject({currency:se,amountMinor:V.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),cA=V.strictObject({featureId:V.uuid(),name:V.string().trim().min(1).max(120),allowance:V.string().max(40).nullable(),access:V.boolean()}),uA=V.strictObject({stripe:V.strictObject({prices:V.array(sA).min(1).max(50)}).optional(),apple:V.strictObject({productIds:V.array(aA).min(1).max(10)}).optional(),google:V.strictObject({products:V.array(V.strictObject({productId:_l,basePlanId:_l.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Si(e.stripe.prices,n=>n.currency)||e.apple&&!Si(e.apple.productIds,n=>n)||e.google&&!Si(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),lA=V.strictObject({name:V.string().trim().min(1).max(80),interval:V.enum(["free","week","month","year","one_time"]),intervalCount:V.number().int().min(1).max(100),trial:V.strictObject({days:V.number().int().min(1).max(730),cardRequired:V.boolean()}).nullable(),benefits:V.array(cA).max(50).refine(e=>Si(e,t=>t.featureId),"Duplicate benefit"),channels:uA,prepaid:V.array(us).max(100).optional()}),pA=V.strictObject({digest:Rn,content:V.strictObject({discount:Ft,duration:at,appliesTo:lo,displayCopy:jl.nullable(),firstPurchaseOnly:V.boolean(),qualificationRequired:V.boolean(),startsAt:V.iso.datetime().nullable(),endsAt:V.iso.datetime().nullable(),grantWindowHours:V.number().int().positive(),perCustomerLimit:V.number().int().positive()})}),dA=V.discriminatedUnion("type",[V.strictObject({type:V.literal("checkout"),product:ci}),V.strictObject({type:V.literal("close")}),V.strictObject({type:V.literal("action"),action:Ro})]),Pl=V.strictObject({kind:V.literal("paywall"),formatVersion:V.literal(1),name:V.string().trim().min(1).max(80),offeringVersionId:V.uuid(),presentation:Rt,screen:it,products:Ur,catalog:V.record(V.uuid(),lA),buttons:V.record(Hn,dA),coupons:V.record(V.uuid(),pA)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;Os(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),To(r,oA).forEach(n),Tt(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,s=new Set;Pt(r,g=>{let D="bind"in g?g.bind:void 0;D?.promotionCode&&n("Promotion codes must not be published"),D?.plan&&i.add(D.plan),D?.coupon&&a.add(D.coupon),g.type==="plan_picker"&&(g.planIds?.forEach(Y=>i.add(Y)),g.defaultPlan&&i.add(g.defaultPlan)),g.type==="text"&&g.feature&&s.add(g.feature.id)});let c=e.products.items.map(g=>g.productVersionId),u=Object.keys(e.catalog);(c.length!==u.length||c.some(g=>!Object.hasOwn(e.catalog,g)))&&n("Catalog must contain exactly the displayed Products");let p=new Set(c);e.products.defaultProductVersionId!==null&&!p.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let g of i)p.has(g)||n("Screen references a Product that is not displayed");for(let g of Object.values(e.catalog))!g.channels.stripe&&!g.channels.apple&&!g.channels.google&&n("A displayed Product needs at least one sales channel");let y=new Set(Object.values(e.catalog).flatMap(g=>g.benefits.map(D=>D.featureId)));for(let g of s)y.has(g)||n("Feature text must read a displayed benefit");let w=r.actions.filter(g=>g.type!=="navigate");r.actions.some(g=>g.type!=="event"&&g.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==w.length||w.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let O=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;O=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(Y=>!p.has(Y))&&n("Checkout may only sell displayed Products")}O||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),Cl=V.strictObject({state:V.enum(["published","archived"]),controlRevision:V.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:V.uuid(),versions:V.record(V.uuid(),V.strictObject({version:V.number().int().positive(),artifact:V.string().min(1),sourceDigest:V.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var mA={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},ea=te.string().regex(/^[a-f0-9]{64}$/),ta=te.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),fA=ve.extend({environmentId:te.uuid()}),kl=te.strictObject({features:te.array(te.string()).max(500),experiments:te.record(te.uuid(),te.array(te.string()).max(20)),savedGroups:te.array(te.string()).max(1e3)}),ra=te.strictObject({kind:te.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:te.number().int().positive(),url:te.string().min(1).max(2048),sha256:ea,byteLength:te.number().int().positive().max(mA.maxArtifactBytes),generation:ea.optional()}),AA=te.strictObject({state:te.enum(["active","paused","archived"]),controlRevision:ta,evaluationMode:te.enum(["local","remote"]),evaluationRevision:ta,currentVersionId:te.uuid(),versions:te.record(te.uuid(),te.strictObject({artifact:te.string(),dependencies:kl,definitionDigest:Rn.optional(),couponDigests:te.record(te.uuid(),Rn).optional()}))}),W0=te.strictObject({kind:te.literal("sdk_configuration"),schemaVersion:te.literal(1),scope:fA,revision:ta,generation:ea,policy:te.strictObject({refreshIntervalSeconds:te.number().positive().max(15),maxControlAgeSeconds:te.number().positive().max(60)}),gb:te.strictObject({features:te.string().nullable(),pageExperiments:te.string().nullable()}),artifacts:te.record(te.string(),ra),funnels:te.record(te.uuid(),AA),paywalls:te.record(te.uuid(),Cl).optional()}).superRefine((e,t)=>{let n=(r,i)=>{r!==null&&e.artifacts[r]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let i of Object.values(r.versions))n(i.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(r.versions))n(i.artifact,"funnel")}});function na(e){if(Array.isArray(e))return`[${e.map(na).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${na(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function hA(e){return wr(jr(typeof e=="string"?new TextEncoder().encode(e):e))}function X0(e){return hA(na(e))}function Y0(e,t){for(let s of Object.values(e.references))if(s.type==="flag"&&(!Object.hasOwn(t.features,s.key)||t.remoteFeatures.includes(s.key))||s.type==="experiment"&&!Object.hasOwn(t.experiments,s.id)||s.type==="saved_group"&&!Object.hasOwn(t.savedGroups,s.id))throw new Error("Funnel dependency is absent from GB public delivery");let n=xi(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),r=new Set(t.remoteFeatures);for(let s of e.graph.nodes){let c=s.type==="feature"?s.featureKey:s.type==="end"&&s.output?.type==="feature"?s.output.featureKey:s.type==="output"&&s.value.type==="feature"?s.value.featureKey:void 0;if(!c)continue;let u=n.features[c],p=s.type==="feature"?e.variables[s.writes.value]:e.outputSchema;if(!u||!p)throw new Error("Required public Feature declaration is unavailable");if([u.defaultValue,...(u.rules??[]).flatMap(w=>[...Object.hasOwn(w,"force")?[w.force]:[],...w.variations??[],...(w.tracks??[]).flatMap(N=>N.experiment.variations)])].some(w=>w===void 0||!lt(p,w)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,a=s=>{for(let c of Dt(s)){if(i.has(c))continue;let u=t.savedGroups[c];if(!u)throw new Error("Required public Saved Group is unavailable");i.add(c),!Array.isArray(u)&&u.type==="condition"&&a(u.condition)}};for(let s of e.graph.nodes)if(s.type==="condition")for(let c of s.cases)a(c.condition);for(let s of Object.values(n.features))for(let c of s.rules??[]){a(c.condition);for(let u of[...c.parentConditions??[],...(c.tracks??[]).flatMap(p=>p.experiment.parentConditions??[])]){if(r.has(u.id)||!t.features[u.id])throw new Error("Local Funnel requires public Local prerequisites");a(u.condition)}for(let u of c.tracks??[])a(u.experiment.condition)}for(let s of Object.values(n.experiments)){a(s.condition);for(let c of s.parentConditions??[]){if(r.has(c.id)||!t.features[c.id])throw new Error("Local Funnel requires public Local prerequisites");a(c.condition)}}for(let s of e.graph.nodes)if(s.type==="split"){let c=n.experiments[s.experimentId];if(!c)throw new Error("Local Funnel requires a public Experiment");for(let u=0;u<c.variations.length;u++){let p=c.meta?.[u]?.key??String(u);if(!s.routes[p])throw new Error("Experiment variation has no declared Funnel route")}}return kl.parse({features:Object.keys(n.features).sort(),experiments:Object.fromEntries(Object.entries(n.experiments).map(([s,c])=>[s,c.variations.map((u,p)=>c.meta?.[p]?.key??String(p))])),savedGroups:[...i].sort()})}function ev(e){return Vt.parse(e)}var Rl=Be.strictObject({...On,selector:Be.discriminatedUnion("type",[Be.strictObject({type:Be.literal("paywall"),paywallId:Be.uuid()}),Be.strictObject({type:Be.literal("version"),versionId:Be.uuid()})]),customerId:Be.uuid().optional(),commerce:Pr,locale:Be.string().min(1).max(35),requirement:An.optional()}),mr=Be.strictObject({id:Be.uuid(),paywallId:Be.uuid(),version:Be.number().int().positive(),document:kn.omit({requirement:!0,offeringId:!0}),offering:Be.strictObject({id:Be.uuid()}),content:Be.strictObject({environmentId:Be.uuid(),offeringVersionId:Be.uuid(),artifact:ra.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:hn,check:Kn.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),fr=Be.strictObject(mr.shape).omit({document:!0,offering:!0}).extend({content:mr.shape.content.unwrap()});function pv(e,t){let n=Pl.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let s=r.plans[i],c=a.channels.stripe?.prices.find(u=>u.currency===s?.currency);s&&c&&Object.assign(s,{amountMinor:c.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return mr.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Je}from"zod";var El={requestId:Je.uuid(),sourceId:Je.uuid(),expectedAvailable:fn},Dl=Je.discriminatedUnion("action",[Je.strictObject({...El,action:Je.enum(["add","subtract","set_remaining"]),amount:we}),Je.strictObject({...El,action:Je.literal("edit"),granted:we,expiresAt:Je.iso.datetime({offset:!0}).nullable(),nextResetAt:Je.iso.datetime({offset:!0}).nullable(),expectedRevision:Je.number().int().nonnegative()})]),ia=Je.strictObject({sourceId:Je.uuid(),available:fn,held:fn,spent:fn,adjustmentGrantId:Je.uuid().nullable()}),Tl=ia.extend({granted:fn,expiresAt:Je.iso.datetime({offset:!0}).nullable(),nextResetAt:Je.iso.datetime({offset:!0}).nullable(),revision:Je.number().int().nonnegative()});import{z as ct}from"zod";var Ml=ct.discriminatedUnion("action",[ct.object({action:ct.literal("upsert"),externalId:ct.string().min(1).max(128),name:ct.string().trim().min(1).max(80)}).strict(),ct.object({action:ct.literal("archive"),entityId:ct.uuid()}).strict()]),Bl=ct.object({id:ct.uuid(),externalId:ct.string().min(1).max(128),name:ct.string().min(1).max(80),archived:ct.boolean()}).strict();import{z as Ge}from"zod";import{z as cn}from"zod";var zl=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],ql=cn.string().regex(/.+\/.+/),oa=cn.number().min(-100),sn=cn.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),gA=cn.strictObject({input:sn,output:sn,cache_read:sn.optional(),cache_write:sn.optional(),reasoning:sn.optional(),input_audio:sn.optional(),output_audio:sn.optional()}),aa=(e,t)=>cn.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),xv=cn.strictObject({defaultMarkup:oa,providerMarkups:aa(cn.string().min(1),oa),modelMarkups:aa(ql,oa),customModels:aa(ql,gA.partial())});import{z as Z}from"zod";var un=Z.iso.datetime({offset:!0}),Lt=Z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),bA=Z.discriminatedUnion("kind",[Z.object({kind:Z.literal("absolute"),from:un,to:un}).strict(),Z.object({kind:Z.literal("last_days"),days:Z.union([Z.literal(1),Z.literal(7),Z.literal(30),Z.literal(90)])}).strict(),Z.object({kind:Z.literal("billing_cycles"),membershipId:Z.uuid(),count:Z.number().int().min(1).max(12),includeCurrent:Z.boolean()}).strict()]),Nl=Z.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),yA=Z.object({key:Z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:Z.array(Z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),ln=Z.object({range:bA,timezone:Nl,filterBy:Z.array(yA).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:Z.enum(["hour","day","week","month"]),internal_feature_id:Z.uuid().nullable(),entityId:Z.uuid().nullable(),topN:Z.number().int().min(1).max(50).nullable(),groupBy:Z.union([Z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),Z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Z.object({bucket:un,group:Z.string().max(240),isOther:Z.boolean(),internal_feature_id:Z.uuid(),resourceId:Z.uuid()}).strict().nullable(),limit:Z.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Fl=Z.object({from:un,to:un,interval:Z.enum(["hour","day","week","month"]),timezone:Nl,rows:Z.array(Z.object({bucket:un,group:Z.string().max(240),isOther:Z.boolean(),internal_feature_id:Z.uuid(),resourceId:Z.uuid(),consumedUnits:Lt,refundedUnits:Lt,reservedUnits:Lt,charged:Lt,refunded:Lt,reserved:Lt,netUnits:Lt,netCharged:Lt}).strict()).max(100),nextCursor:Z.object({bucket:un,group:Z.string().max(240),isOther:Z.boolean(),internal_feature_id:Z.uuid(),resourceId:Z.uuid()}).strict().nullable()}).strict();var qn=Ge.string().regex(/^(0|[1-9]\d{0,29})$/),Ul=Ge.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),sa=Ge.strictObject({bucket:Ge.iso.datetime({offset:!0}),group:Ge.string().max(240),isOther:Ge.boolean(),internal_feature_id:Ge.uuid()}),Vl=Ge.strictObject({...ln.shape,groupBy:Ge.union([Ge.enum(["customer","entity","entitlement"]),Ge.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:sa.nullable()}).superRefine((e,t)=>{let n=ln.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Ll=Ge.strictObject({from:Ge.iso.datetime({offset:!0}),to:Ge.iso.datetime({offset:!0}),interval:ln.shape.interval,timezone:ln.shape.timezone,rows:Ge.array(Ge.strictObject({...sa.shape,eventCount:qn,units:Ul,tokenEventCount:qn,tokens:Ge.strictObject(Object.fromEntries(zl.map(e=>[e,qn]))),totalTokens:qn,providerCostEventCount:qn,providerCostUsd:Ul,invalidTelemetryEventCount:qn})).max(100),nextCursor:sa.nullable()});import{z as Ee}from"zod";var $l=Ee.object({requestId:Ee.uuid(),items:Ee.array(Ee.object({customerId:Ee.uuid(),command:$n.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),Gl=Ee.object({batchId:Ee.uuid(),after:Ee.number().int().min(-1).max(999),limit:Ee.number().int().min(1).max(100)}).strict(),Kl=Ee.object({batchId:Ee.uuid(),status:Ee.enum(["queued","complete"]),total:Ee.number().int().min(1).max(1e3),processed:Ee.number().int().min(0).max(1e3),items:Ee.array(Ee.object({position:Ee.number().int().min(0).max(999),customerId:Ee.uuid(),idempotencyKey:Ee.string().min(1).max(120),status:Ee.enum(["queued","accepted","rejected","failed"]),receipt:Gn.nullable(),errorCode:Ee.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:Ee.number().int().min(0).max(999).nullable()}).strict();import{z as h}from"zod";var xA=h.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Hl=h.enum(["draft","active","paused","archived"]),Zl=h.string().min(1).max(256),Ql=h.array(Zl).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),SA=h.strictObject({duration:h.enum(["day","week","month","year"]),length:h.number().int().min(1).max(3660)}),vA=h.strictObject({internal_feature_id:h.uuid(),allowance:h.number().nonnegative().max(1e15).nullable(),expiry:SA.nullable()}),IA=h.discriminatedUnion("type",[h.strictObject({type:h.literal("feature_grant"),grants:h.array(vA).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),h.strictObject({type:h.literal("free_product"),productId:Zl,duration:at}),h.strictObject({type:h.literal("invoice_credits"),amount:h.number().positive().max(1e8),duration:at,rollover:h.boolean(),productIds:Ql})]),OA=h.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Jl=h.object({key:OA,name:h.string().trim().min(1).max(80),configuration:IA}).strict(),Wl=h.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),ca=h.object({code:Wl,maxUses:h.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:h.boolean()}).strict(),Xl=h.object({key:h.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:h.string().trim().min(1).max(80),rewardId:h.uuid(),redeemOn:h.enum(["customer_creation","checkout"]),receivedBy:h.enum(["referrer","all"]),maxRedemptions:h.number().int().min(1).max(1e6).nullable(),productIds:Ql,excludeTrial:h.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Yl={id:h.uuid(),projectId:h.uuid(),environmentId:h.uuid(),revision:h.number().int().nonnegative(),status:Hl,createdAt:h.iso.datetime({offset:!0}),updatedAt:h.iso.datetime({offset:!0})},wA=Jl.extend(Yl).strict(),jA=Xl.safeExtend(Yl).strict(),Tv=h.strictObject({id:h.uuid(),key:h.string(),name:h.string(),type:xA,status:Hl}),Mv=h.discriminatedUnion("action",[h.object({action:h.literal("save"),id:h.uuid().nullable(),revision:h.number().int().nonnegative(),input:Jl}).strict(),h.object({action:h.enum(["activate","pause","resume","archive","delete"]),id:h.uuid(),revision:h.number().int().nonnegative()}).strict()]),Bv=h.discriminatedUnion("action",[h.object({action:h.literal("save"),id:h.uuid().nullable(),revision:h.number().int().nonnegative(),input:Xl}).strict(),h.object({action:h.enum(["activate","pause","resume","archive","delete"]),id:h.uuid(),revision:h.number().int().nonnegative()}).strict()]),ep=h.object({id:h.uuid(),rewardId:h.uuid(),programId:h.uuid().nullable(),customerId:h.uuid(),referrerId:h.uuid().nullable(),status:h.enum(["pending","applied","unavailable"]),result:h.record(h.string(),h.unknown()).nullable(),createdAt:h.iso.datetime({offset:!0})}).strict(),tp=h.object({code:Wl,requestId:h.uuid()}).strict(),np=h.strictObject({redemptionId:h.uuid(),currency:se,requestId:h.uuid(),accepted:h.literal(!0)}),_A=h.strictObject({type:h.literal("checkout"),orderId:h.uuid(),productVersionId:h.uuid(),currency:se,duration:at,renewalAmountMinor:h.number().int().positive().max(1e8),status:h.enum(["created","pending","trialing","paid","cancelled","failed"]),url:h.url().nullable()}),rp=h.discriminatedUnion("type",[_A,h.strictObject({type:h.literal("subscription"),operationId:h.uuid(),membershipId:h.uuid(),productVersionId:h.uuid(),currency:se,duration:at,renewalAmountMinor:h.number().int().positive().max(1e8),status:h.enum(["pending","running","applied","failed"])})]),ip=h.object({programId:h.uuid(),requestId:h.uuid()}).strict(),op=h.object({id:h.uuid(),programId:h.uuid(),code:ca.shape.code,createdAt:h.iso.datetime({offset:!0})}).strict(),qv=h.object({rows:h.array(wA).max(100),nextCursor:h.uuid().nullable()}).strict(),zv=h.object({rows:h.array(jA).max(100),nextCursor:h.uuid().nullable()}).strict(),PA=ca.extend({id:h.uuid(),redemptions:h.number().int().nonnegative()}).strict(),CA=h.strictObject({id:h.uuid(),programId:h.uuid().nullable(),customerId:h.uuid().nullable(),referrerId:h.uuid().nullable(),code:h.string().nullable(),status:h.enum(["pending","triggered","applied"]),createdAt:h.iso.datetime({offset:!0})}),Nv=h.object({codes:h.array(PA).max(100),redemptions:h.array(CA).max(100),customers:h.record(h.uuid(),h.string()),codesCursor:h.uuid().nullable(),redemptionsCursor:h.uuid().nullable()}).strict(),Fv=h.discriminatedUnion("action",[h.object({action:h.literal("create"),rewardId:h.uuid(),revision:h.number().int().nonnegative(),input:ca}).strict(),h.object({action:h.literal("remove"),rewardId:h.uuid(),revision:h.number().int().nonnegative(),codeId:h.uuid()}).strict()]);import{z as m}from"zod";import{z as M}from"zod";var It={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Ar=e=>new Set(e).size===e.length,ua=M.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),kA=M.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),hr=M.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),RA=M.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),ap=M.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var sp=M.strictObject({id:M.uuid(),repo:kA,platform:M.enum(["github","gitlab","bitbucket"]),branches:M.array(hr).min(1).max(4).refine(Ar),workflow:M.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:M.array(M.uuid()).min(1).max(4).refine(Ar),include:M.array(ap).min(1).max(16),exclude:M.array(ap).max(16),methods:M.array(M.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Ar),maxAgeHours:M.number().int().min(1).max(720)}),cp=sp.extend({revision:M.number().int().positive()}),Lv=M.strictObject({repository:sp,expectedRevision:M.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),up=M.strictObject({repositoryId:M.uuid(),branch:hr}),EA=M.array(ua).max(It.keys).refine(Ar),lp=M.strictObject({repository:cp.omit({keyIds:!0}),branch:hr,keys:EA,keySetHash:M.string().regex(/^[a-f0-9]{64}$/)}),DA=M.strictObject({filePath:RA,startingLineNumber:M.number().int().min(1).max(1e7)}),la=M.strictObject({protocol:M.literal(1),repositoryId:M.uuid(),branch:hr,workflow:M.string().max(200),configurationRevision:M.number().int().positive(),keySetHash:M.string().regex(/^[a-f0-9]{64}$/),commit:M.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:M.uuid(),runNumber:M.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:M.number().int().min(1).max(1e4),scannerVersion:M.literal("1"),scannedAt:M.iso.datetime({offset:!0}),coverage:M.strictObject({complete:M.literal(!0),files:M.number().int().min(0).max(It.files),sourceBytes:M.number().int().min(0).max(It.sourceBytes),unresolvedCalls:M.number().int().min(0).max(1e6),unsupportedFiles:M.number().int().min(0).max(It.files)}),features:M.array(M.strictObject({key:ua,refs:M.array(DA).max(It.referencesPerKey)})).max(It.keys)}).superRefine((e,t)=>{Ar(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>It.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),pa=M.strictObject({scanId:M.uuid(),commit:M.string(),receivedAt:M.string(),references:M.number().int().nonnegative(),removedReferences:M.number().int().nonnegative()}),TA=pa.extend({repositoryId:M.uuid(),branch:hr,workflow:M.string(),digest:M.string(),configurationRevision:M.number().int().positive(),runNumber:M.number().int().positive(),runAttempt:M.number().int().positive(),scannedAt:M.string(),keySetHash:M.string(),coverage:la.shape.coverage}),MA=M.strictObject({repositories:M.array(cp).max(It.repositories),scans:M.array(TA).max(It.repositories*It.branches)}),BA=M.strictObject({key:ua,references:M.number().int().nonnegative(),coveredTargets:M.number().int().nonnegative(),expiredTargets:M.number().int().nonnegative(),uncertainTargets:M.number().int().nonnegative()}),$v=M.strictObject({available:M.boolean().default(!0),settings:MA,expectedTargets:M.number().int().min(0).max(80),features:M.array(BA).max(2001),truncated:M.boolean()});import{z as qe}from"zod";var qA=qe.enum(["checkout.session.completed","checkout.session.expired","checkout.session.async_payment_succeeded","checkout.session.async_payment_failed","customer.subscription.created","customer.subscription.updated","customer.subscription.deleted","customer.subscription.paused","customer.subscription.resumed","invoice.created","invoice.paid","customer.discount.created","customer.discount.updated","refund.created","refund.updated","refund.failed","charge.refunded"]),zA=qe.strictObject({provider:qe.literal("stripe"),accountId:qe.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:qe.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:qA,occurredAt:qe.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:qe.record(qe.string(),qe.unknown()).and(qe.object({id:qe.string().min(1).max(255),object:qe.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:qe.boolean()}))}),pp=qe.union([zA,Ds]),dp=qe.strictObject({id:qe.uuid(),eventId:qe.string().min(1).max(200),source:qe.literal("merchant"),providerVerified:qe.literal(!1),outcome:qe.string().min(1).max(100)});import{z as We}from"zod";var fp={customerId:We.uuid(),eventId:We.string().trim().min(1).max(200),grantId:We.uuid(),occurredAt:We.iso.datetime({offset:!0})},Ap=We.strictObject({...fp,productVersionId:We.uuid(),subscriptionId:We.string().trim().min(1).max(255)}),hp=We.strictObject({...fp,merchandiseId:We.uuid()}),gp=We.union([Ap,hp]),mp={id:We.uuid(),couponId:We.uuid(),status:We.literal("redeemed"),source:We.literal("merchant"),recordedAt:We.iso.datetime({offset:!0})},bp=We.union([Ap.extend(mp),hp.extend(mp)]);import{z as U}from"zod";var da=U.strictObject({name:U.string().trim().min(1).max(255),memo:U.string().max(1e4).nullable().optional(),footer:U.string().max(1e4).nullable().optional(),net_terms_days:U.number().int().positive().nullable().optional()}),NA=da.extend({id:U.string().min(1).max(255),created_at:U.number().nullable()}),yp=U.strictObject({items:U.array(NA).max(50),nextCursor:U.uuid().nullable()}),Yv=U.discriminatedUnion("action",[U.strictObject({action:U.literal("create"),requestId:U.uuid(),values:da}),U.strictObject({action:U.literal("update"),id:U.string().min(1).max(255),values:da}),U.strictObject({action:U.literal("delete"),id:U.string().min(1).max(255)})]),xp=U.discriminatedUnion("action",[U.strictObject({action:U.literal("create"),requestId:U.uuid(),params:jn}),U.strictObject({action:U.enum(["finalize","send","pay","void"]),requestId:U.uuid(),invoiceId:U.uuid()}),U.strictObject({action:U.literal("reissue"),requestId:U.uuid(),invoiceId:U.uuid(),params:xo})]),ma=U.strictObject({id:U.uuid(),customerId:U.uuid(),providerInvoiceId:U.string().nullable(),status:U.enum(["draft","open","paid","void","uncollectible"]),currency:U.string(),totalMinor:U.string().regex(/^-?\d+$/),paidMinor:U.string().regex(/^\d+$/),refundedMinor:U.string().regex(/^\d+$/),hostedInvoiceUrl:U.url().nullable(),createdAt:U.number(),collectionMethod:U.enum(["send_invoice","charge_automatically"]).nullable()}),Sp=ma.extend({lines:U.array(U.strictObject({id:U.uuid(),description:U.string(),amountMinor:U.string().regex(/^-?\d+$/),netAmountMinor:U.string().regex(/^-?\d+$/),quantity:U.number().nullable(),periodStart:U.number().nullable(),periodEnd:U.number().nullable()})).max(1e3)}),zn=U.strictObject({taskId:U.uuid(),status:U.enum(["ready","running","done","dead"]),invoice:ma.nullable(),errorCode:U.string().nullable()}),vp=U.strictObject({items:U.array(ma).max(50),nextCursor:U.uuid().nullable(),operations:U.array(zn).max(50),operationsLimited:U.boolean()});var FA=m.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Ip={scope:ve,permissions:m.array(FA),expiresAt:m.iso.datetime().nullable()},$I=m.discriminatedUnion("kind",[m.object({...Ip,kind:m.literal("server"),keyId:m.string().min(1)}),m.object({...Ip,kind:m.literal("customer"),customerId:m.string().min(1),identityKind:m.enum(["identified","guest"]),expiresAt:m.iso.datetime()})]),_=m.object({requestId:m.uuid(),scope:ve}).strict(),UA=dl.safeExtend({fingerprint:Ai.optional()}).strict(),VA=_.extend({customer:Mn,created:m.boolean()});function Op(){return _.extend({offer:Yn.nullable(),reason:mc.nullable()})}var j={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Qc,response:_.extend({message:m.object({messageId:m.uuid(),channel:or,acceptedAt:m.iso.datetime({offset:!0}),status:m.enum(["accepted","sending","completed","canceled"]),replayed:m.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:m.strictObject({messageId:m.uuid()}),response:_.extend({message:m.object({id:m.uuid(),channel:or,status:m.enum(["accepted","sending","completed","canceled"]),deliveries:m.array(m.object({id:m.uuid(),status:Wc,attempts:m.number().int().nonnegative(),receipts:m.array(m.object({kind:Xc,occurredAt:m.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Ys,response:_.extend({installation:$r})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:ec,response:_.extend({installation:$r})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Lr,response:_.extend({installation:$r})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:m.strictObject({channel:or}),response:_.extend({preference:no})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Jc,response:_.extend({preference:no})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:m.strictObject({cursor:m.uuid().optional()}),response:_.extend({templates:yp})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:m.strictObject({customerId:m.uuid(),params:jn}),response:_.extend({preview:So})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:m.strictObject({customerId:m.uuid(),requestId:m.uuid(),params:jn}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:_.extend({operation:zn})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:m.strictObject({customerId:m.uuid(),command:xp}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:_.extend({operation:zn})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:m.strictObject({customerId:m.uuid(),taskId:m.uuid()}),response:_.extend({operation:zn})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:m.strictObject({customerId:m.uuid(),cursor:m.uuid().optional()}),response:_.extend({invoices:vp})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:m.strictObject({customerId:m.uuid(),invoiceId:m.uuid()}),response:_.extend({invoice:Sp})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:up,response:_.extend({config:lp})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:la,response:_.extend({receipt:pa})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:m.strictObject({}),response:_.extend({payload:Do})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Qu,response:_.merge(Ju)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Wu,response:_.merge(Xu)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:m.strictObject({customerId:m.uuid(),sourceId:m.uuid()}),response:_.extend({balance:Tl})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:m.strictObject({customerId:m.uuid(),command:Dl}),response:_.extend({balance:ia})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:m.strictObject({internal_feature_id:m.uuid(),customerId:m.uuid().optional(),entityId:m.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:_.extend({internal_feature_id:m.uuid(),config:so,model_markups:Zr})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:m.strictObject({customerId:m.uuid(),query:is}),response:_.extend({usage:qi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:m.strictObject({customerId:m.uuid(),command:os}),response:_.extend({usage:qi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:m.strictObject({customerId:m.uuid(),command:Nc}),response:_.extend({grant:fo})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Fc,response:_.extend({grants:Uc})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:m.union(Fu.options.map(e=>e.extend({customerId:m.uuid().optional(),customerToken:m.string().regex(Bt).optional()}))),response:_.extend({operation:Uu})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Cu.extend({customerId:m.uuid().optional()}),response:_.extend({setup:jo})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:ku.extend({customerId:m.uuid().optional()}),response:_.extend({setup:jo})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:ju.safeExtend({customerId:m.uuid()}),response:_.extend({batch:sr})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ni.extend({customerId:m.uuid()}),response:_.extend({batch:sr})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ni.extend({customerId:m.uuid()}),response:_.extend({batch:sr})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ni.extend({customerId:m.uuid()}),response:_.extend({batch:sr})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:m.discriminatedUnion("action",[ri.options[0].extend({customerId:m.uuid()}),ri.options[1].extend({customerId:m.uuid()}),ri.options[2].extend({customerId:m.uuid()})]),response:_.extend({trial:wo})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:_u.extend({customerId:m.uuid()}),response:_.extend({trial:wo})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:ai,response:_.extend({subscriptions:qu})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:ai,response:_.extend({purchases:zu})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Tu,response:_.extend({conflicts:Nu})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Mu,response:_.extend({resolution:Bu})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Eu,response:_.extend({verification:Du})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:bu.safeExtend({...On,customerId:m.uuid().optional()}),response:_.extend({quote:_n})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:pp,response:_.extend({record:dp})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:nn.extend({customerId:m.uuid().optional(),intent:m.enum(["confirm","cancel"]).optional()}),response:_.extend({operation:Pn})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:nn.extend({customerId:m.uuid().optional()}),response:_.extend({operation:Pn})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Su.safeExtend({customerId:m.uuid().optional()}),response:_.extend({quote:Iu})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:nn.extend({customerId:m.uuid().optional(),intent:m.enum(["confirm","cancel"]).optional()}),response:_.extend({operation:vo})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:nn.extend({customerId:m.uuid().optional()}),response:_.extend({operation:vo})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Ou.safeExtend({customerId:m.uuid()}),response:_.extend({quote:Io})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:nn.extend({customerId:m.uuid()}),response:_.extend({operation:ti})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:nn.extend({customerId:m.uuid()}),response:_.extend({operation:ti})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:_c,response:_.extend({controls:mo})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:xc,response:_.extend({prepared:vc})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Ic,response:_.extend({authorization:Jr})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Ec,response:_.extend({coupons:Dc})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Oc,response:_.extend({authorization:Jr})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:kc,response:_.extend({invoices:Rc})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Cc.extend({customerId:m.uuid()}),response:_.extend({operation:zn})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Pc,response:_.extend({invoice:nr})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:m.object({customerId:m.uuid(),command:jc}).strict(),response:_.extend({controls:mo})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:m.object({customerId:m.uuid(),command:Ml}).strict(),response:_.extend({entity:Bl})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:m.strictObject({customerId:m.uuid().nullable(),query:Vl}),response:_.extend({analytics:Ll})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:m.object({customerId:m.uuid().nullable(),query:ln}).strict(),response:_.extend({analytics:Fl})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:$l,response:_.extend({batchId:m.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Gl,response:_.extend({batch:Kl})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:ps.extend({customerId:m.string().min(1).optional()}),response:_.extend({check:Kn})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:m.strictObject({kind:zt,selector:m.discriminatedUnion("type",[m.strictObject({type:m.literal("resource"),id:m.uuid()}),m.strictObject({type:m.literal("version"),id:m.uuid()})]),customerId:m.string().min(1).optional()}),response:_.extend({content:eo})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Rl,response:_.extend({paywall:fr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:m.strictObject({...On,selector:Gu,customerId:m.string().min(1).optional(),commerce:Pr,requirement:An.optional()}),response:_.extend({offering:Ku,candidates:m.array(ds).max(20),availability:m.array(m.strictObject({productVersionId:m.uuid(),available:m.boolean(),reason:m.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:Kn.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:m.object({customerId:m.uuid().optional(),entityId:m.uuid().optional()}).strict(),response:_.extend({holdings:as})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:m.object({customerId:m.uuid().optional(),query:ss}).strict(),response:_.extend({ledger:cs})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Vc.extend({customerId:m.uuid().optional()}),response:_.extend({detail:Lc})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Ao.safeExtend({customerId:m.uuid().optional()}),response:_.extend({statement:$c})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:m.object({customerId:m.uuid().optional(),command:$n.options[0]}).strict(),response:_.extend({quote:rs})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:m.strictObject({customerId:m.uuid(),command:m.union([m.strictObject({eventName:m.string().min(1),quantity:we.optional(),properties:_t.optional(),entityId:m.uuid().optional(),idempotencyKey:m.string().min(1).max(120)}),m.strictObject({internal_feature_id:m.uuid(),quantity:we.optional(),properties:_t.optional(),entityId:m.uuid().optional(),idempotencyKey:m.string().min(1).max(120)})])}),response:_.extend({receipts:m.array(Gn).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:m.object({customerId:m.uuid(),command:$n.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:_.extend({receipt:Gn})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:tp,response:_.extend({redemption:ep})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:ip,response:_.extend({referralCode:op})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:np,response:_.extend({checkout:rp})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Kc,response:_.extend({seats:bo})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Hc,response:_.extend({seats:bo})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:UA,response:VA},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Lo,response:_.extend({customer:Mn})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Al,response:_.extend(hl.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:fl,response:_.extend(ml.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:m.object({customerId:m.uuid()}).strict(),response:_.extend(qt.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:m.strictObject({}),response:_.extend(qt.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:m.strictObject({customerId:m.uuid(),sessionId:m.uuid().optional()}),response:_.extend({revoked:m.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:m.strictObject({guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ai.optional()}),response:_.extend({customerId:m.uuid(),guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:m.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:m.strictObject({guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:_.extend(qt.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:m.strictObject({guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:m.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:m.uuid()}),response:_.extend({customer:Mn,switched:m.boolean(),replayed:m.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:m.strictObject({code:m.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:m.uuid()}),response:Op()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:m.object({}).strict(),response:_.extend({offers:m.array(Yn)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:m.object({customerId:m.string().min(1).max(255).optional(),couponId:m.uuid(),...On,requestId:m.uuid(),couponContentDigest:m.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Op()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:gp,response:_.extend({receipt:bp})}},GI={sendMessage:j.sendMessage,readMessage:j.readMessage,bindPushInstallation:j.bindPushInstallation,readPushInstallation:j.readPushInstallation,updatePushAddress:j.updatePushAddress,readMessagingPreference:j.readMessagingPreference,setMessagingPreference:j.setMessagingPreference,listInvoiceTemplates:j.listInvoiceTemplates,previewInvoice:j.previewInvoice,createInvoice:j.createInvoice,manageInvoice:j.manageInvoice,readInvoiceOperation:j.readInvoiceOperation,listInvoices:j.listInvoices,getInvoice:j.getInvoice,getCodeReferenceConfig:j.getCodeReferenceConfig,submitCodeReferences:j.submitCodeReferences,getFeatures:j.getFeatures,evaluateFeatures:j.evaluateFeatures,trackEvents:j.trackEvents,setupPayment:j.setupPayment,readPaymentSetup:j.readPaymentSetup,previewSubscriptionBatch:j.previewSubscriptionBatch,confirmSubscriptionBatch:j.confirmSubscriptionBatch,readSubscriptionBatch:j.readSubscriptionBatch,abandonSubscriptionBatch:j.abandonSubscriptionBatch,manageSubscriptionTrial:j.manageSubscriptionTrial,readSubscriptionTrial:j.readSubscriptionTrial,listSubscriptions:j.listSubscriptions,listPurchases:j.listPurchases,listSubscriptionConflicts:j.listSubscriptionConflicts,retrySubscriptionConflict:j.retrySubscriptionConflict,readAiPricing:j.readAiPricing,readUsage:j.readUsage,setUsage:j.setUsage,previewRefund:j.previewRefund,refund:j.refund,readRefund:j.readRefund,previewUpdate:j.previewUpdate,update:j.update,readSubscriptionUpdate:j.readSubscriptionUpdate,restoreNativePurchase:j.restoreNativePurchase,verifySubscriptions:j.verifySubscriptions,previewAttach:j.previewAttach,attach:j.attach,readSubscriptionOperation:j.readSubscriptionOperation,manageBalanceGrant:j.manageBalanceGrant,readBalanceSource:j.readBalanceSource,adjustBalance:j.adjustBalance,listBalanceGrants:j.listBalanceGrants,readBillingControls:j.readBillingControls,prepareBillingAuthorization:j.prepareBillingAuthorization,confirmBillingAuthorization:j.confirmBillingAuthorization,setBillingCoupons:j.setBillingCoupons,revokeBillingAuthorization:j.revokeBillingAuthorization,listBillingInvoices:j.listBillingInvoices,confirmBillingAdjustment:j.confirmBillingAdjustment,prepareBillingAdjustment:j.prepareBillingAdjustment,manageBillingLimits:j.manageBillingLimits,createCustomer:j.createCustomer,getCustomer:j.getCustomer,listCustomers:j.listCustomers,updateCustomer:j.updateCustomer,createSession:j.createSession,refreshSession:j.refreshSession,revokeSessions:j.revokeSessions,createGuestCustomer:j.createGuestCustomer,resumeGuestSession:j.resumeGuestSession,claimGuestCustomer:j.claimGuestCustomer,checkEntitlement:j.checkEntitlement,resolveOffering:j.resolveOffering,resolveContent:j.resolveContent,resolvePaywall:j.resolvePaywall,readHoldings:j.readHoldings,readLedger:j.readLedger,readBillingInvoice:j.readBillingInvoice,readCreditStatement:j.readCreditStatement,quoteBalance:j.quoteBalance,trackUsage:j.trackUsage,mutateBalance:j.mutateBalance,manageUsageEntity:j.manageUsageEntity,readUsageAnalytics:j.readUsageAnalytics,readCreditAnalytics:j.readCreditAnalytics,submitUsageBatch:j.submitUsageBatch,readUsageBatch:j.readUsageBatch,listOffers:j.listOffers,grantOffer:j.grantOffer,recordCouponRedemption:j.recordCouponRedemption,redeemCoupon:j.redeemCoupon,redeemReward:j.redeemReward,createReferralCode:j.createReferralCode,claimRewardProduct:j.claimRewardProduct,readSeats:j.readSeats,manageSeat:j.manageSeat};import{z as fa}from"zod";var gr=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Aa(e,t,n){let r={},i,a,s,c="next",u;switch(e.type){case"entry":u=e.next;break;case"condition":{let p=e.cases.findIndex(y=>Bi(t.attributes??{},y.condition,t.savedGroups??{}));c=p<0?"default":`case:${p}`,u=p<0?e.default:e.cases[p].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new gr("Required GB Feature is unavailable");i=Ln(e.featureKey,t),s=i.value,Object.assign(r,Wt(e,{value:s})),u=e.next;break;case"split":{let p=n[e.experimentId];if(!p)throw new gr("Required GB Experiment is unavailable");if(a=Ya(p,t),s=a.value,c=a.inExperiment&&!a.passthrough&&typeof s=="string"?s:"notParticipating",u=c==="notParticipating"?e.notParticipating:e.routes[c],!u)throw new gr("Experiment Variation has no published route");break}case"offering":{let p=e.configuration.source==="fixed"?e.configuration.versionId:Ln(e.configuration.featureKey,t).value;s={type:"offering_version",id:fa.uuid().parse(p)},Object.assign(r,Wt(e,{value:s})),u=e.next;break}case"coupon":case"coupons":s=e.type==="coupons"?e.couponIds.map(p=>({type:"reward",id:p})):{type:"reward",id:e.couponId},Object.assign(r,Wt(e,{value:s})),u=e.next;break}return{port:c,target:u,projections:r,...s===void 0?{}:{value:s},...i?{feature:i}:{},...a?{experiment:a}:{}}}function YI(e,t,n){fa.uuid().parse(e),fa.number().int().nonnegative().parse(t);let r=wr(jr(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as R}from"zod";var $t=R.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),LA=R.enum(["running","waiting","completed","closed","ineligible","failed"]),$A=R.discriminatedUnion("type",[Uo,R.strictObject({type:R.literal("wait"),receiptId:R.uuid(),kind:R.enum(["timer","event","operation"]),deadline:R.iso.datetime({offset:!0}).nullable(),eventName:$t.optional()}),R.strictObject({type:R.literal("open_url"),receiptId:R.uuid(),url:Go,openIn:Ko}),R.strictObject({type:R.literal("event"),receiptId:R.uuid(),event:$t})]),GA=R.strictObject({type:R.literal("funnel"),id:R.uuid(),versionId:R.uuid()}),KA={id:$t,presentation:Rt,outputs:R.array($t).max(250),inputs:Fi,values:R.record(R.string(),me).optional(),offeringKey:Te.optional(),capabilities:hn,customerData:bs,dataCursors:R.record($t,kr.nullable())},HA=R.strictObject({...KA,content:R.strictObject({type:R.literal("document"),document:it})}),ha=R.strictObject({id:R.uuid(),source:GA,revision:R.number().int().nonnegative(),visit:R.number().int().nonnegative(),nodeId:$t,nodeType:R.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:LA,stopped:R.boolean(),canBack:R.boolean(),authenticated:R.boolean(),locale:R.string().min(1).max(35),answers:Zt,parameters:xt,variables:R.record(R.string(),me),output:me.nullable(),screen:HA.nullable(),paywall:R.strictObject({receiptId:R.uuid(),resolution:R.union([mr,fr]),quote:_n.nullable(),operation:Pn.nullable(),purchaseRequestId:R.uuid().nullable(),selectionGeneration:R.number().int().nonnegative().optional(),canReselect:R.boolean().optional()}).nullable(),instruction:$A.nullable(),pendingRequest:R.strictObject({requestId:R.uuid(),authenticationRequired:R.boolean()}).nullable(),runExpiresAt:R.iso.datetime({offset:!0}),credentialExpiresAt:R.iso.datetime({offset:!0}).nullable()}),ga=R.strictObject({scope:ve,run:ha,settlement:R.strictObject({requestId:R.uuid(),state:R.enum(["pending","unknown","settled"]),operationId:R.uuid().nullable(),receiptId:R.uuid().nullable().optional()}).optional(),purchase:R.strictObject({receiptId:R.uuid(),quote:_n.nullable(),operation:Pn.nullable(),canReselect:R.boolean().optional()}).optional(),review:R.strictObject({activeOperationId:R.uuid().nullable(),pages:R.array(R.strictObject({receiptId:R.uuid(),nodeId:$t,visit:R.number().int().nonnegative()})).max(100),page:R.strictObject({receiptId:R.uuid(),nodeId:$t,visit:R.number().int().nonnegative(),document:it,answers:Zt,inputs:Fi,values:R.record(R.string(),me).optional()}).nullable(),coupons:R.array(R.strictObject({grantId:R.uuid(),status:R.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:R.string().nullable()})).max(100),purchases:R.array(R.strictObject({receiptId:R.uuid(),operationId:R.uuid(),status:R.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:R.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:R.uuid().optional()}),wp=ga.extend({run:ha.extend({paywall:ha.shape.paywall.unwrap().extend({resolution:fr}).nullable()})});var AO="X-Indiana-Server-Key";import{z as tt}from"zod";import{z as vi}from"zod";var yO=vi.strictObject({operation:vi.literal("renew_run"),runId:vi.uuid(),customerId:vi.uuid()}),jp=ga.refine(e=>!!e.runToken,"Renewal returns a credential"),_p=wp.refine(e=>!!e.runToken,"Renewal returns a credential");var _O=tt.discriminatedUnion("operation",[tt.strictObject({operation:tt.literal("campaign_decide"),...$o}).refine(rn,on),tt.strictObject({operation:tt.literal("campaign_start"),funnelId:tt.uuid(),requestId:tt.uuid(),customer:Dn,customerData:Tn.optional(),locale:tt.string().min(1).max(35),parameters:xt,cooldownSeconds:tt.number().int().min(1).max(2592e3)}).refine(rn,on)]),ZA=tt.union([tt.strictObject({scope:ve,suppressed:tt.literal(!0),reason:tt.enum(["frequency","in_progress"]),retryAt:tt.iso.datetime({offset:!0})}),jp]),PO=tt.union([ZA.options[0],_p]);import{z as ae}from"zod";var Nn=ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cp=ae.strictObject({entry:Nn,nodes:ae.array(ae.strictObject({id:Nn,type:ae.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:ae.record(ae.string(),Nn),writes:ae.record(Te,Te),resources:ae.strictObject({screenId:Nn.optional(),paywallVersionId:ae.uuid().optional(),couponId:ae.uuid().optional(),couponIds:ae.array(ae.uuid()).max(20).optional(),experimentId:ae.uuid().optional(),featureKey:ae.string().optional(),offeringVersionId:ae.uuid().optional()})})).min(1).max(500)}),Pp={scope:ve,funnelId:ae.uuid(),versionId:ae.uuid(),evaluationRevision:ae.number().int().nonnegative(),expiresAt:ae.iso.datetime({offset:!0}).nullable(),topology:Cp},Fn=ae.discriminatedUnion("evaluationMode",[ae.strictObject({...Pp,evaluationMode:ae.literal("local"),growth:Mt,conditions:ae.record(Nn,ae.array(ae.strictObject({condition:Ht,port:ae.string()})))}),ae.strictObject({...Pp,evaluationMode:ae.literal("remote")})]),QA=Fn.options[0].extend({evaluation:ae.strictObject({maxTransitions:ae.number().int().min(1).max(1e4),variables:ae.record(Te,xn),outputSchema:yn,terminals:ae.record(Nn,ae.strictObject({outcome:ae.enum(["completed","closed","ineligible","failed"]),output:ur.nullable()}))})});function JA(e){return Cp.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(s=>s.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,s)=>{n[`case:${s}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=ae.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function WA(e){let t=Vt.parse(e.document),n=e.evaluationMode==="local"?Mt.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:JA(t)};return Fn.parse(e.evaluationMode==="remote"?r:{...r,growth:xi(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,s)=>({condition:a.condition,port:`case:${s}`}))]))})}function zO(e){let t=WA(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Vt.parse(e.document);return QA.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}import{z as mt}from"zod";import{z as Ke}from"zod";var kp=Ke.discriminatedUnion("provider",[Ke.strictObject({provider:Ke.literal("apple"),orderId:Ke.uuid(),receiptId:Ke.uuid(),signedTransaction:Ke.string().min(1).max(131072)}),Ke.strictObject({provider:Ke.literal("google"),orderId:Ke.uuid(),receiptId:Ke.uuid(),purchaseToken:Ke.string().min(1).max(16384)})]),Rp=Ke.strictObject({orderId:Ke.uuid(),receiptId:Ke.uuid(),transactionIds:Ke.array(Ke.string().min(1).max(255)).min(1).max(50),membership:Ke.boolean()});var KO=mt.strictObject({operation:mt.literal("native_receipt"),requestId:mt.uuid(),customerToken:mt.string().regex(Bt),orderId:mt.uuid(),receiptId:mt.uuid(),nativeEvidence:kp.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),HO=mt.strictObject({scope:ve,requestId:mt.uuid(),orderId:mt.uuid(),receiptId:mt.uuid(),orderStatus:mt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:mt.boolean(),nativeCompletion:Rp.optional()});import{z as Oe}from"zod";var Ep=Oe.string().regex(/^[a-f0-9]{64}$/),XA=ys.omit({variations:!0,active:!0}).extend({changeId:Ep,variations:Oe.array(Oe.strictObject({urlRedirect:Oe.string().max(2048)})).min(2).max(20)}),WO=Oe.strictObject({environmentId:Oe.uuid(),trackExposures:Oe.boolean(),generation:Ep,experiments:Oe.array(XA).max(100),savedGroups:Ss}),YA=Oe.strictObject({eventUuid:Oe.uuid(),timestamp:Oe.iso.datetime({offset:!0}).optional(),deviceId:Oe.string().min(1).max(128),sessionId:Oe.string().min(1).max(128).optional(),url:Oe.url().max(2048),pageTitle:Oe.string().max(512).optional(),experimentKey:Oe.string().min(1).max(255),variationKey:Oe.string().min(1).max(64)}),XO=Oe.strictObject({events:Oe.array(YA).min(1).max(20)}),YO=Oe.strictObject({inserted:Oe.number().int().nonnegative(),duplicates:Oe.number().int().nonnegative(),skipped:Oe.number().int().nonnegative(),rejected:Oe.array(Oe.strictObject({index:Oe.number().int().nonnegative(),reason:Oe.string()}))});import{z as Ce}from"zod";var ya=32,eh=522240;function xa(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var th=Ce.strictObject({nodeId:Ce.string().min(1).max(64),visit:Ce.number().int().nonnegative(),revision:Ce.number().int().nonnegative()}),ba=Ce.record(Ce.string(),me),nh=Ce.strictObject({id:Ce.uuid(),nodeId:Ce.string().min(1).max(64),visit:Ce.number().int().nonnegative(),input:Ce.strictObject({schemaVersion:lr.shape.schemaVersion,kind:lr.shape.kind,selector:lr.shape.selector,contract:lr.shape.contract}),context:ba,removed:Ce.array(Ce.string()).max(100),attributes:ba,removedAttributes:Ce.array(Ce.string()).max(100),result:Il,offeringVersionId:Ce.uuid().nullable(),events:Ce.strictObject({entered:Ce.string().regex(/^[1-9][0-9]{0,18}$/),decision:Ce.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),ow=Ce.strictObject({schemaVersion:Ce.literal(1),mode:Ce.enum(["local","remote"]),versionId:Ce.uuid(),generation:Ce.number().int().positive(),base:th,context:ba,steps:Ce.array(nh).min(1).max(ya)}).refine(e=>ot(e)<=eh,"Segment exceeds its byte budget");var Sa=class extends Error{constructor(n,r){super(r);this.code=n;this.name="FunnelLocalCalculationError"}code},Ii=(e,t)=>new Sa(e,t),rh=e=>({experiments:e.experiments,features:e.features});function ih(e,t=Ii){let n=new Map(e.topology.nodes.map(s=>[s.id,s])),r=Xa(e.growth.savedGroups),i=rh(e.growth);function a(s,c){if(!Object.hasOwn(e.growth.features,s))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Ln(s,c).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(s,c){let u=n.get(s);if(!u)throw t("NOT_FOUND","Funnel node is unavailable");let p,y;if(u.type==="condition"){let N=e.conditions[u.id];if(!N)throw t("INVALID_RESPONSE","Local condition rules are unavailable");p=Aa({id:u.id,name:u.id,type:"condition",cases:N.map(O=>({condition:O.condition,target:u.outputs[O.port]})),default:u.outputs.default},c,i.experiments).port}else if(u.type==="feature"){if(!u.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");y=a(u.resources.featureKey,c),p="next"}else if(u.type==="split"){if(!(u.resources.experimentId?e.growth.experiments[u.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let O=Aa({id:u.id,name:u.id,type:"split",experimentId:u.resources.experimentId,routes:u.outputs,notParticipating:u.outputs.notParticipating},c,i.experiments);y=O.value,p=O.port}else if(["offering","end","output"].includes(u.type)&&u.resources.featureKey)y=a(u.resources.featureKey,c),p=u.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let w=u.outputs[p]??(p==="value"?u.id:void 0);if(!w)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:s,port:p,target:w,...y===void 0?{}:{value:y}}}}}function hw(e,t,n,r=Ii){return va(e,r)(t,n)}function va(e,t){let n=Fn.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=ih(n,t);return(s,c)=>(i(),oh(a,s,c))}function oh(e,t,n){let r=rt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:s}=n,c={attributes:r,...i?{saveStickyBucketAssignmentDoc:u=>i(structuredClone(u))}:{},...a?{onFeatureUsage:(u,p)=>a(u,structuredClone(p))}:{},...s?{onExperimentViewed:(u,p)=>s(structuredClone(u),structuredClone(p))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function gw(e,t,n,r=Ii){return Dp(va(e,r),t,n)}function Dp(e,t,n){let r=[],i=[],a=[],s=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(c){let u=r.findIndex(w=>w.next.attributeName===c.attributeName&&w.next.attributeValue===c.attributeValue),p=c.attributeName+"||"+c.attributeValue,y={expected:n.sticky[p]??null,next:c};u<0?r.push(y):r[u]=y},onExperimentViewed(c,u){u.inExperiment&&u.hashUsed&&!u.passthrough&&i.push(me.parse({key:c.key,variationId:u.variationId,keyUsed:u.key,hashAttribute:u.hashAttribute,hashValue:u.hashValue}))},onFeatureUsage(c,u){a.push(me.parse({feature:c,value:u.value,source:u.source,...u.ruleId?{ruleId:u.ruleId}:{}}))}});return{port:s.port,...s.value===void 0?{}:{value:s.value},sticky:r,exposures:i,features:a}}function bw(e,t,n,r=Ii){let i=n,a=new Map(t.graph.nodes.map(g=>[g.id,g])),s=structuredClone(n.variables),c=structuredClone(i.sticky),u=[],p=n.nodeId,y=n.visit,w=!1,N,O=g=>(N??=va(e,r),Dp(N,g,{attributes:qo({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:s,savedGroups:{}}),sticky:c}));for(let g=0;g<ya;g++){let D=a.get(p);if(!D||!xa(D))break;if(y>=t.execution.maxTransitions&&(y>t.execution.maxTransitions||D.type!=="end"&&D.type!=="output")){if(!u.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let Y,ne;if(["condition","feature","split"].includes(D.type)||D.type==="offering"&&D.configuration.source==="feature")Y=O(D.id),D.type==="offering"&&(Y.value={type:"offering_version",id:String(Y.value)}),D.type==="condition"?ne=Y.port==="default"?D.default:D.cases[Number(Y.port.slice(5))]?.target:D.type==="split"?ne=Y.port==="notParticipating"?D.notParticipating:D.routes[Y.port]:(D.type==="feature"||D.type==="offering")&&(ne=D.next);else if(Y={port:"next",sticky:[],exposures:[],features:[]},(D.type==="entry"||D.type==="coupon"||D.type==="coupons")&&(ne=D.next),D.type==="offering"&&D.configuration.source==="fixed"&&(Y.value={type:"offering_version",id:D.configuration.versionId},ne=D.next),D.type==="end"||D.type==="output"){let B=D.type==="end"?D.output:D.value;if(Y=B?.type==="feature"?O(D.id):{...Y,port:"value",value:B?.type==="literal"?B.value:B?.type==="variable"?Wi({source:"variable",key:B.key,...B.path?{path:B.path}:{}},{declarations:t.variables,answers:n.answers,results:s,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},B&&(Y.value===void 0||!lt(t.outputSchema,Y.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let Se=[...u,{nodeId:p,result:Y}];if(ot({steps:Se})>6e4){if(!u.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(u.push({nodeId:p,result:Y}),D.type==="feature"||D.type==="offering"||D.type==="coupon"||D.type==="coupons"){let B=D.type==="coupons"?D.couponIds.map(ie=>({type:"reward",id:ie})):D.type==="coupon"?{type:"reward",id:D.couponId}:Y.value;if(B===void 0)throw r("INVALID_RESPONSE","Node output is missing");let ce=Wt(D,{value:B});Ji(t.variables,D,ce),Object.assign(s,ce)}for(let B of Y.sticky)c[`${B.next.attributeName}||${B.next.attributeValue}`]=structuredClone(B.next);if(D.type==="end"||D.type==="output"){w=!0;break}if(!ne)throw r("INVALID_RESPONSE","Local pure exit is unavailable");p=ne,y++}let d=a.get(p);return{steps:u,...!w&&d&&!xa(d)?{boundary:{nodeId:p,visit:y}}:{}}}import{z as ah}from"zod";var Iw=ah.strictObject({document:Vt,configuration:Fn.options[0]});import{z as J}from"zod";var Oi=J.string().regex(/^[a-f0-9]{64}$/),sh=J.strictObject({release:Oi,render:vs,button:J.strictObject({selector:J.string().min(1).max(512),elementKey:J.string().min(1).max(256),tag:J.enum(["button","a","input"])}).nullable()}),kw=J.strictObject({scope:ve.extend({environmentId:J.uuid()}),release:Oi,validatedAt:J.iso.datetime({offset:!0}),validUntil:J.iso.datetime({offset:!0}),entries:J.array(J.strictObject({id:J.uuid(),funnelId:J.uuid(),versionId:J.uuid(),event:J.enum(["screen_enter","button_click"]),target:sh})).max(4e3)}),Rw=J.strictObject({operation:J.literal("entry_start"),funnelId:J.uuid(),versionId:J.uuid(),entryId:J.uuid(),release:Oi,requestId:J.uuid(),locale:J.string().min(1).max(35).default("en")}),Ew=J.strictObject({scope:ve,suppressed:J.literal(!0),reason:J.enum(["frequency","in_progress"]),retryAt:J.iso.datetime({offset:!0}).nullable()}),Dw=J.strictObject({experimentId:J.uuid(),splitNodeId:J.string().min(1).max(128)}),ch=J.strictObject({experimentId:J.uuid(),experimentKey:J.string().min(1).max(128),variationKey:J.string().min(1).max(128),inExperiment:J.boolean(),generation:J.string().min(1).max(256)}),Tw=J.strictObject({operation:J.literal("page_experiments"),release:Oi,usedReceiptIds:J.array(J.uuid()).max(20).default([]),customerToken:J.string().regex(Bt).optional()}),Mw=J.strictObject({scope:ve,runId:J.uuid(),assignments:J.array(ch.extend({receiptId:J.uuid()})).max(20),payload:ws});function ge(e){return typeof e=="string"?e:String(e)}var uh=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function lh(e){return e.replace(uh,"$1\uFFFD")}function ja(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function Vp(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function Tp(e){let t;if(Array.isArray(e)){let n=e.map(ge);if(n.length===2)return n}else if((t=Vp(e))!=null){let n=ja(t.next()),r=ja(t.next());if(!n.done&&!r.done)return[ge(n.value),ge(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Mp="0123456789ABCDEF",ph=/(?:%[0-9A-Fa-f]{2})+/g;function Ot(e){return`%${Mp[e>>4&15]}${Mp[15&e]}`}function Lp(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Ot(e):String.fromCharCode(e):e<=2047?Ot(192|e>>6)+Ot(128|63&e):e<=65535?Ot(224|e>>12)+Ot(128|e>>6&63)+Ot(128|63&e):Ot(240|e>>18)+Ot(128|e>>12&63)+Ot(128|e>>6&63)+Ot(128|63&e)}function _a(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Pa(e,t=!1){let n=0;for(;n<e.length;n++){let r=e.charCodeAt(n);if(r===37||t&&r===43)break}return n===e.length?e:(t?e.replace(/\+/g," "):e).replace(ph,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function xr(e){return e<=31||e>126}function dh(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return xr(e)}}function Ma(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return xr(e)}}function mh(e){return Ma(e)||e===39}function Ca(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return Ma(e)}}function Ci(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return Ca(e)}}function Bp(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return Ci(n)}})(e)}}function $p(e,t){return Lp(e=e||0,t)}function wt(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),s=a;if(a>=55296&&a<=56319&&r+1<e.length){let c=e.charCodeAt(r+1);c>=56320&&c<=57343&&(s=(a-55296<<10)+c-56320+65536,r++)}i+=Lp(s,t,n)}return i}function Ba(e){let t=[],n=0,r=0;for(;r<=e.length;){if(r=e.indexOf("&",n),r<0&&(r=e.length),r!==n){let i=e.slice(n,r),a=i.indexOf("=");a<0&&(a=i.length),t.push([Pa(i.slice(0,a),!0),Pa(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function ka(e){let t="";for(let n=0;n<e.length;n++){let r=wt(e[n][0],Bp,!0),i=wt(e[n][1],Bp,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var fh=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],Ah=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],hh=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],gh=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function bh(e){for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(n>65535&&t++,n<=32||n===37||n===127||n>=55296&&n<=57343||n>=128&&n<=159||n>=64976&&n<=65007||!(65534&~n)||n===65533)return!0}return!1}var[yh,xh,Sh,qp]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function vh(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function Gp(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function br(e,t){let[n,r,i]=e,a=t>>8;for(let u=0;u<n.length;u+=2)if(a>=n[u]&&a<=n[u+1])return!0;let s=r.indexOf(a);if(s<0)return!1;let c=255&t;return!!(i[32*s+(c>>3)]&1<<(7&c))}function Ih(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&Gp(gh,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&br(qp,t[i]);)i--;let a=n+1;for(;a<t.length&&br(qp,t[a]);)a++;if(!(i>=0&&a<t.length&&br(xh,t[i])&&br(Sh,t[a])))return!1}return!0}var Oh=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,wh=/\p{Script=Latin}/u;function jh(e){return!Oh.test(e)||!wh.test(e)}var Gt=36,ji=1,Ra=26,_h=38,Ph=700,Ch=72,kh=128,Rh=2147483647;function zp(e){return String.fromCharCode(e+22+75*+(e<26))}function Eh(e,t,n){let r=0;for(e=n?Math.floor(e/Ph):e>>1,e+=Math.floor(e/t);e>(Gt-ji)*Ra>>1;r+=Gt)e=Math.floor(e/(Gt-ji));return Math.floor(r+(Gt-ji+1)*e/(e+_h))}function Dh(e){let t=Array.from(e,u=>u.codePointAt(0)),n="",r=0;for(let u=0;u<t.length;u++){let p=t[u];p<128&&(n+=String.fromCharCode(p),r++)}let i=r;i&&(n+="-");let a=kh,s=0,c=Ch;for(;r<t.length;){let u=Rh;for(let p=0;p<t.length;p++){let y=t[p];y>=a&&y<u&&(u=y)}s+=(u-a)*(r+1),a=u;for(let p=0;p<t.length;p++){let y=t[p];if(y<a&&s++,y===a){let w=s;for(let N=Gt;;N+=Gt){let O=N<=c?ji:N>=c+Ra?Ra:N-c;if(w<O)break;n+=zp(O+(w-O)%(Gt-O)),w=Math.floor((w-O)/(Gt-O))}n+=zp(w),c=Eh(s,r+1,r===i),s=0,r++}}s++,a++}return n}function Ia(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let n=0;for(let r=0;r<e.length;r++){let i=_a(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function Np(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function Kp(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Hp(e){return e.length===2&&Kp(e.codePointAt(0),e.codePointAt(1))}function Fp(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function ke(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Zp(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function Ea(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,s=0,c=0,u=Array.from(r,p=>p.codePointAt(0));if(u[c]===58){if(u[c+1]!==58)return null;c+=2,s++,a=s}for(;c<u.length;){if(s===8)return null;if(u[c]===58){if(a!==null)return null;c++,s++,a=s;continue}let p=0,y=0,w=0;for(;w<4&&(p=_a(u[c]))>=0;)y=(y<<4)+p,c++,w++;if(u[c]===46){if(w===0||s>6)return null;c-=w;let N=0;for(;u[c]!==void 0;){let O=0;if(N>0)if(u[c]===46&&N<4)c++;else return null;if(u[c]==null||u[c]<48||u[c]>57)return null;for(;u[c]>=48&&u[c]<=57;){if(O=10*O+_a(u[c]),O>255)return null;c++}i[s]=256*i[s]+O,N++,N%2==0&&s++}if(N!==4)return null;break}else if(u[c]===58){if(u[++c]===void 0)return null}else if(u[c]!==void 0)return null;i[s]=y,s++}if(a!==null){let p=s-a;for(s=7;s!==0&&p>0;){let y=i[a+p-1];i[a+p-1]=i[s],i[s]=y,s--,p--}}else if(a===null&&s!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Fp(r)?null:wt(r,xr)})(e);{let n=(function(i){let a=!1,s=!1;for(let u=0;u<i.length;u++){let p=i.charCodeAt(u);if(p<=32||p===37||p===127)return null;if(p>=128){a=!0;break}p>=65&&p<=90&&(s=!0)}if(!a)return i!==""?s?i.toLowerCase():i:null;if((function(p){for(let y of p){let w=y.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(y)&&!Gp(fh,w)||br(yh,w))return!0}return!1})(i))return null;let c=(i=(function(p){let y="";for(let w of p){let N=w.codePointAt(0);if(N!==8204&&N!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(w))continue;let O=vh(w,N);if(O){y+=O;continue}let d=Ah.indexOf(N);y+=d<0?w:hh[d]}return y})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let u=0;u<c.length;u++){let p=c[u];if(p==="")continue;let y=/[^\0-\x7f]/.test(p);if(bh(p)||y&&(/^\p{Mark}/u.test(p)||!Ih(p)||!jh(p)||p.startsWith("xn--")))return null;y&&(c[u]=`xn--${Dh(p)}`)}return(i=c.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Pa(e));return n===null||Fp(n)?null:(function(i){let a=i.length,s=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=s)return!1;if(Ia(i.slice(s,a))>=0)return!0;for(;s<a;s++){let c=i.charCodeAt(s);if(c<48||c>57)return!1}return!0})(n)?(function(i){let a=i.split("."),s=a.length;if(a[s-1]||s--,s>4)return null;let c=0;for(let p=0;p<s-1;p++){let y=Ia(a[p]);if(y<0||y>255)return null;c+=y*(1<<8*(3-p))}let u=Ia(a[s-1]);return u<0||u>=256**(5-s)?null:(c+=u,c)})(n):n}}function Da(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(c){let u=-1,p=-1,y=1,w=0;for(let N=0;N<c.length;++N)c[N]!==0?(w>y&&(u=p,y=w),p=-1,w=0):(p===-1&&(p=N),++w);return w>y?p:u})(n),i="",a=!1;for(let s=0;s<=7;++s)if(!(a&&n[s]===0)){if(a&&(a=!1),r===s){i+=s===0?"::":":",a=!0;continue}i+=n[s].toString(16),s!==7&&(i+=":")}return i})(e)}]`:e}function Qp(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function Jp(e){return e.username!==""||e.password!==""}function Oa(e){return e.host===null||e.host===""||e.scheme==="file"}var A=0,v="",W="",de=null,I,_i=!1,Pi=!1,pn=!1,Re;function ut(e,t,n,r){t||(e=(function(s){let c=0,u=s.length;for(;c<u&&!(s.charCodeAt(c)>32);++c);for(;u>c&&!(s.charCodeAt(u-1)>32);--u);return s.substring(c,u)})(e)),e=(function(s){let c=0;for(;c<s.length;c++){let p=s.charCodeAt(c);if(p===9||p===10||p===13)break}if(c===s.length)return s;let u=s.slice(0,c);for(;c<s.length;c++){let p=s.charCodeAt(c);p!==9&&p!==10&&p!==13&&(u+=s[c])}return u})(e),A=0,v=e,W="",de=n||null,I=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},_i=!1,Pi=!1,pn=!1,Re=r||0;let i=Th;switch(r){case 3:case 4:i=ki;break;case 5:i=za;break;case 6:i=dn;break;case 7:i=Kt;break;case 8:i=jt}return i(k(e,A))!==1?I:null}function q(e,t){return A+=A===e?bt(t):1,A<=v.length}function k(e,t){return t<e.length?e.codePointAt(t):void 0}function bt(e){return e!=null&&e>65535?2:1}function Wp(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var Th=e=>{let t=A;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=A+1;for(e=v.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=v.charCodeAt(n);return W=v.slice(A,n).toLowerCase(),A=n,Mh(n<v.length?e:void 0)}else return Re?1:(--A,q(t,e)?Xp(k(v,A)):0)},Mh=e=>{let t=A;if(e===58){if(Re){if(ke(I.scheme)!==ke(W))return 0;if((Jp(I)||I.port!==null)&&W==="file")return 0;if(I.scheme==="file"&&I.host==="")return 0}return I.scheme=W,Re?(I.port===Zp(I.scheme)&&(I.port=null),0):(W="",I.scheme==="file"?q(t,e)?Na(k(v,A)):0:ke(I.scheme)&&de!==null&&de.scheme===I.scheme?q(t,e)?Bh(k(v,A)):0:ke(I.scheme)?q(t,e)?zh(k(v,A)):0:k(v,A+1)===47?(A++,q(t,e)?qh(k(v,A)):0):(I.path=[""],I.opaquePath=!0,q(t,e)?ed(k(v,A)):0))}else return Re?1:(W="",A=-1,q(t,e)?Xp(k(v,A)):0)},Xp=e=>{let t=A;return de===null||de.opaquePath&&e!==35?1:de.opaquePath&&e===35?(I.scheme=de.scheme,I.path=de.path.slice(),I.opaquePath=de.opaquePath,I.query=de.query,I.fragment="",q(t,e)?jt(k(v,A)):0):de.scheme==="file"?(A--,q(t,e)?Na(k(v,A)):0):(A--,q(t,e)?qa(k(v,A)):0)},Bh=e=>{let t=A;return e===47&&k(v,A+1)===47?(++A,q(t,e)?Ei(k(v,A)):0):(A--,q(t,e)?qa(k(v,A)):0)},qh=e=>{let t=A;return e===47?q(t,e)?Un(k(v,A)):0:(A--,q(t,e)?yt(k(v,A)):0)},qa=e=>{let t=A;return I.scheme=de.scheme,e===47||ke(I.scheme)&&e===92?q(t,e)?Up(k(v,A)):0:(I.username=de.username,I.password=de.password,I.host=de.host,I.port=de.port,I.path=de.path.slice(),I.query=de.query,e===63?(I.query="",q(t,e)?Kt(k(v,A)):0):e===35?(I.fragment="",q(t,e)?jt(k(v,A)):0):e!=null?(I.query=null,I.path.pop(),A--,q(t,e)?yt(k(v,A)):0):q(t,e)?qa(k(v,A)):0)},Up=e=>{let t=A;return ke(I.scheme)&&(e===47||e===92)?q(t,e)?Ei(k(v,A)):0:e===47?q(t,e)?Un(k(v,A)):0:(I.username=de.username,I.password=de.password,I.host=de.host,I.port=de.port,A--,q(t,e)?yt(k(v,A)):0)},zh=e=>{let t=A;return e===47&&k(v,A+1)===47?A++:A--,q(t,e)?Ei(k(v,A)):0},Ei=e=>{let t=A;return e!==47&&e!==92?(A--,q(t,e)?Un(k(v,A)):0):q(t,e)?Ei(k(v,A)):0},Un=e=>{let t=A;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!ke(I.scheme))){let n=A+bt(e);for(;n<v.length;){let r=k(v,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&ke(I.scheme))break;n+=bt(r)}return W+=v.slice(A,n),A=n-1,q(t,e)?Un(k(v,A)):0}if(e===64){_i&&(W=`%40${W}`),_i=!0;for(let n=0;n<W.length;n++){let r=W.codePointAt(n);if(r===58&&!Pi){Pi=!0;continue}let i=$p(r,Ci);Pi?I.password+=i:I.username+=i,r!=null&&r>65535&&n++}return W="",q(t,e)?Un(k(v,A)):0}else return e==null||e===35||e===47||e===63||e===92&&ke(I.scheme)?_i&&W===""?1:(A-=W.length+1,W="",q(t,e)?ki(k(v,A)):0):(W+=Wp(e),q(t,e)?Un(k(v,A)):0)},ki=e=>{let t=A;if(Re&&I.scheme==="file")return A--,q(t,e)?Fa(k(v,A)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!ke(I.scheme))){let n=A+bt(e);for(e===91?pn=!0:e===93&&(pn=!1);n<v.length;){let r=k(v,n);if(r==null||!pn&&r===58||r===35||r===47||r===63||r===92&&ke(I.scheme))break;r===91?pn=!0:r===93&&(pn=!1),n+=bt(r)}return W+=v.slice(A,n),A=n-1,q(t,e)?ki(k(v,A)):0}else if(e===58&&!pn){if(W===""||Re===4)return 1;let n=Ea(W,!ke(I.scheme));return n===null?1:(I.host=Da(n),W="",q(t,e)?za(k(v,A)):0)}else if(e==null||e===35||e===47||e===63||e===92&&ke(I.scheme)){if(A--,ke(I.scheme)&&W==="")return 1;if(Re&&W===""&&(Jp(I)||I.port!==null))return 1;let n=Ea(W,!ke(I.scheme));return n===null?1:(I.host=Da(n),W="",Re?0:q(t,e)?dn(k(v,A)):0)}else return W+=Wp(e),q(t,e)?ki(k(v,A)):0},za=e=>{let t=A;if(e!=null&&e>=48&&e<=57){let n=A+1;for(;n<v.length;){let r=v.charCodeAt(n);if(r<48||r>57)break;n++}return W+=v.slice(A,n),A=n-1,q(t,e)?za(k(v,A)):0}else if(Re||e==null||e===35||e===47||e===63||e===92&&ke(I.scheme)){if(W!==""){let n=parseInt(W,10);if(n>65535)return 1;if(I.port=n===Zp(I.scheme)?null:n,W="",Re)return 0}return Re?1:(A--,q(t,e)?dn(k(v,A)):0)}else return 1};function Yp(e,t){let n=e.length-t;if(n<2)return!1;if(Kp(k(e,t),k(e,t+1))){if(n===2)return!0;{let r=k(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var Na=e=>{let t=A;return I.scheme="file",I.host="",e===47||e===92?q(t,e)?Nh(k(v,A)):0:de?.scheme==="file"?(I.host=de.host,I.path=de.path.slice(),I.opaquePath=de.opaquePath,I.query=de.query,e===63?(I.query="",q(t,e)?Kt(k(v,A)):0):e===35?(I.fragment="",q(t,e)?jt(k(v,A)):0):e!=null?(I.query=null,Yp(v,A)?I.path=[]:Qp(I),A--,q(t,e)?yt(k(v,A)):0):q(t,e)?Na(k(v,A)):0):(A--,q(t,e)?yt(k(v,A)):0)},Nh=e=>{let t=A;return e===47||e===92?q(t,e)?Fa(k(v,A)):0:(de!==null&&de.scheme==="file"&&(!Yp(v,A)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})(de.path[0])&&I.path.push(de.path[0]),I.host=de.host),A--,q(t,e)?yt(k(v,A)):0)},Fa=e=>{let t=A;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=A+bt(e);for(;n<v.length;){let r=k(v,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=bt(r)}return W+=v.slice(A,n),A=n-1,q(t,e)?Fa(k(v,A)):0}else if(e==null||e===47||e===92||e===63||e===35){if(A--,!Re&&Hp(W))return q(t,e)?yt(k(v,A)):0;if(W==="")return I.host="",Re?0:q(t,e)?dn(k(v,A)):0;{let n=Ea(W,!ke(I.scheme));return n===null?1:(n==="localhost"&&(n=""),I.host=Da(n),W="",Re?0:q(t,e)?dn(k(v,A)):0)}}return 1},dn=e=>{let t=A;return ke(I.scheme)?(e!==92&&e!==47&&A--,q(t,e)?yt(k(v,A)):0):!Re&&e===63?(I.query="",q(t,e)?Kt(k(v,A)):0):!Re&&e===35?(I.fragment="",q(t,e)?jt(k(v,A)):0):e!=null?(e!==47&&A--,q(t,e)?yt(k(v,A)):0):(Re&&I.host===null&&I.path.push(""),q(t,e)?dn(k(v,A)):0)},yt=e=>{let t=A;if(e!=null&&e!==47&&(!ke(I.scheme)||e!==92)&&(Re||e!==63&&e!==35)){let n=A+bt(e);for(;n<v.length;){let r=k(v,n);if(r==null||r===47||ke(I.scheme)&&r===92||!Re&&(r===63||r===35))break;n+=bt(r)}W+=wt(v.slice(A,n),Ca),A=n,e=k(v,n)}if(e==null||e===47||ke(I.scheme)&&e===92||!Re&&(e===63||e===35)){let n=ke(I.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(W)?(Qp(I),e!==47&&!n&&I.path.push("")):Np(W)&&e!==47&&!n?I.path.push(""):Np(W)||(I.scheme==="file"&&I.path.length===0&&Hp(W)&&(W=`${W[0]}:`),I.path.push(W)),W="",e===63?(I.query="",q(t,e)?Kt(k(v,A)):0):e===35?(I.fragment="",q(t,e)?jt(k(v,A)):0):q(t,e)?yt(k(v,A)):0}else return W+=$p(e,Ca),q(t,e)?yt(k(v,A)):0},ed=e=>{let t=A;if(e===63)return I.query="",q(t,e)?Kt(k(v,A)):0;if(e===35)return I.fragment="",q(t,e)?jt(k(v,A)):0;if(e!=null){let n=A+bt(e);for(;n<v.length;){let i=k(v,n);if(i===63||i===35)break;n+=bt(i)}let r=v.slice(A,n);if(n<v.length&&r.charCodeAt(r.length-1)===32?I.path[0]+=wt(r.slice(0,-1),xr)+"%20":I.path[0]+=wt(r,xr),A=n,(e=k(v,n))===63)return I.query="",q(t,e)?Kt(k(v,A)):0;if(e===35)return I.fragment="",q(t,e)?jt(k(v,A)):0}return q(t,e)?ed(k(v,A)):0},Kt=e=>{let t=A,n=A;if(e!=null){if(Re)n=v.length;else{let i=v.indexOf("#",A);n=i===-1?v.length:i}let r=ke(I.scheme)?mh:Ma;I.query+=wt(v.slice(A,n),r)}return A=n,k(v,n)===35&&!Re?(I.fragment="",q(t,e)?jt(k(v,A)):0):q(t,e)?Kt(k(v,A)):0},jt=e=>{let t=A;return e!=null&&(I.fragment+=wt(v.slice(A),dh),A=v.length),q(t,e)?jt(k(v,A)):0};function Ta(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function td(e){switch(e.scheme){case"blob":{let t=ut(Ta(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":td(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var he=Symbol("URLImpl"),Sr=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=ge(t),n!=null&&(n=ge(n));let r=null;if(n!=null&&(r=ut(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=ut(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[he]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=ge(t),n!==void 0&&(n=ge(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=ge(t),n!==void 0&&(n=ge(n));let r=null;return n!=null&&(r=ut(n,null,null,0),r==null)?!1:ut(t,null,r,0)!=null}get href(){return(function(n){let r=`${n.scheme}:`;return n.host!==null&&(r+="//",(n.username!==""||n.password!=="")&&(r+=n.username,n.password!==""&&(r+=`:${n.password}`),r+="@"),r+=n.host,n.port!==null&&(r+=`:${n.port}`)),n.host===null&&!n.opaquePath&&n.path.length>1&&n.path[0]===""&&(r+="/."),r+=Ta(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[he].url)}set href(t){let n=ut(t=ge(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[he].url=n,this[he].query&&wa(this[he].query,n.query)}get origin(){return td(this[he].url)}get protocol(){return`${this[he].url.scheme}:`}set protocol(t){ut(`${t=ge(t)}:`,this[he].url,null,2)}get username(){return this[he].url.username}set username(t){t=ge(t),Oa(this[he].url)||(function(r,i){r.username=wt(i,Ci)})(this[he].url,t)}get password(){return this[he].url.password}set password(t){t=ge(t),Oa(this[he].url)||(function(r,i){r.password=wt(i,Ci)})(this[he].url,t)}get host(){let{url:t}=this[he];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=ge(t),this[he].url.opaquePath||ut(t,this[he].url,null,3)}get hostname(){let{url:t}=this[he];return t.host!=null?t.host:""}set hostname(t){t=ge(t),this[he].url.opaquePath||ut(t,this[he].url,null,4)}get port(){let{url:t}=this[he];return t.port!=null?`${t.port}`:""}set port(t){t=ge(t);let{url:n}=this[he];Oa(n)||(t?ut(t,n,null,5):n.port=null)}get pathname(){return Ta(this[he].url)}set pathname(t){t=ge(t);let{url:n}=this[he];n.opaquePath||(n.path=[],ut(t,n,null,6))}get search(){let{url:t}=this[he];return t.query?`?${t.query}`:""}set search(t){t=ge(t);let{url:n,query:r}=this[he];if(!t)n.query=null,r&&wa(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",ut(i,n,null,7),r&&wa(r,n.query)}}get searchParams(){let t=this[he],n=t.query;return n==null&&(n=t.query=(function(i,a){let s=new Ri;return s[_e].url=i,s[_e].serialized=a==null,a&&(s[_e].list=Ba(a)),s})(this,t.url.query)),n}get hash(){let{url:t}=this[he];return t.fragment?`#${t.fragment}`:""}set hash(t){t=ge(t);let{url:n}=this[he];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",ut(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(Sr.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var _e=Symbol("URLSearchParamsImpl"),Fh=Symbol.dispose||Symbol.for("dispose");function wa(e,t){t?e[_e].list=Ba(t):e[_e].list.length=0,e[_e].serialized=t==null}function wi(e){if(e.url){let t=ka(e.list);(function(r,i){r[he].url.query=i})(e.url,t||null),e.serialized=!0}}var Uh=typeof Iterator<"u"?Iterator:Object,yr=class extends Uh{constructor(t,n){super(),this[_e]={ptr:t,map:n,index:0}}next(){let t=this[_e];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[Fh](){}},Ri=class{constructor(t){let n=this[_e]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Tp(t[i]));else if((r=Vp(t))!=null){let i;for(;!(i=ja(r.next())).done;)n.list.push(Tp(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let s=i[a],c=lh(s),u=ge(t[s]),p=n.list.find(y=>y[0]===c);p?p[1]=u:n.list.push([c,u])}}else if(t!==void 0){let i=ge(t);i=i[0]==="?"?i.substring(1):i,n.list=Ba(i)}}get size(){return this[_e].list.length}append(t,n){t=ge(t),n=ge(n),this[_e].list.push([t,n]);let r=this[_e];r.url&&r.serialized?(function(a,s){let c=a[he].url;c.query=c.query?`${c.query}&${s}`:s})(r.url,ka([[t,n]])):wi(r)}delete(t,n){t=ge(t),n=n!=null?ge(n):void 0;let{list:r}=this[_e],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;wi(this[_e])}get(t){t=ge(t);let{list:n}=this[_e];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=ge(t);let n=[],{list:r}=this[_e];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=ge(t),n=n!=null?ge(n):void 0;let{list:r}=this[_e];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=ge(t),n=ge(n);let{list:r}=this[_e],i=!1,a=!1,s=0;for(;s<r.length;)r[s][0]===t?i?(r.splice(s,1),a=!0):(i=!0,r[s][1]!==n&&(r[s][1]=n,a=!0),s++):s++;i||(r.push([t,n]),a=!0),a&&wi(this[_e])}sort(){this[_e].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),wi(this[_e])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[_e];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new yr(this[_e],t=>t)}keys(){return new yr(this[_e],t=>t[0])}values(){return new yr(this[_e],t=>t[1])}toString(){return ka(this[_e].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Ri.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});function nd(e){let t,n,r=0,i,a=new Map,s=()=>{for(let w of[...a.keys()])try{w()}catch{}};function c(w,N){let O=++r;i=void 0,t=void 0,n=void 0;for(let d of[...a.values()])try{d?.()}catch{}O===r&&(t=w,n=N,s())}let u=()=>c();function p(w,N=!1){let O=qt.safeParse(w);if(!O.success||N&&Date.parse(O.data.expiresAt)<=Date.now()||Date.parse(O.data.refreshExpiresAt)<=Date.now()||Date.parse(O.data.refreshExpiresAt)<Date.parse(O.data.expiresAt))throw new ue("INVALID_RESPONSE","Invalid customer session credentials");return O.data}async function y(){if(i)return i;let w=t,N=r;if(!w||Date.parse(w.refreshExpiresAt)<=Date.now())throw w&&u(),new ue("UNAUTHENTICATED","Customer authentication is required",401);let O=(async()=>{try{let d=await e(w.refreshToken);if(N!==r)throw new ue("IDENTITY_CHANGED","Customer identity changed during refresh");let g=p(d,!0);if(g.customerId!==w.customerId||g.sessionId!==w.sessionId)throw new ue("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,n=g.accessToken,{...g}}catch(d){throw N!==r?new ue("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof ue&&d.status===401&&u(),d)}})();i=O;try{return await O}finally{i===O&&(i=void 0)}}return{identify(w){let N=typeof w=="string"?void 0:p(w),O=typeof w=="string"?w:N.accessToken;if(!O.trim()||/\s/.test(O)||O.length>4096)throw new ue("INVALID_TOKEN","A server-issued token is required");c(N,O)},reset:u,subscribeIdentity(w,N){return a.set(w,N),()=>{a.delete(w)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return y().then(()=>{if(!n)throw new ue("NOT_IDENTIFIED","Customer authentication is required");return n});if(!n)throw new ue("NOT_IDENTIFIED","Identify a customer session before making a request");return n},peek:()=>n,snapshot:()=>t&&{...t},refresh:y}}var rd=Symbol("IndianaNoContent");function s_(e,t,n=Sr){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?ve.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new ue("SCOPE_MISMATCH","Configuration belongs to another App/environment");let s=new n(e.baseUrl??_s);if(s.username||s.password||s.search||s.hash)throw new ue("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(s.hostname)))throw new ue("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let c=e.fetch??globalThis.fetch.bind(globalThis),u=e.timeoutMs??1e4;if(!Number.isFinite(u)||u<1||u>12e4)throw new ue("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,y=0,w=null,N=new Set,O=e.session??nd(async ne=>{let Se=await Y("customer-sessions/refresh",{},"POST",{},ne);if(!Se||typeof Se!="object")throw new ue("INVALID_RESPONSE","Invalid refresh response");let{requestId:B,scope:ce,...ie}=Se;return ie});function d(){y+=1,p=null,w=null;for(let ne of N)ne.abort();N.clear()}let g=O.subscribeIdentity(d);function D(){O.reset()}async function Y(ne,Se={},B="POST",ce={},ie){let L=ce.installationDetach===!0;if(L&&(ne!=="push/installations/detach"||B!=="POST"))throw new ue("INVALID_REQUEST","Installation authority only detaches this installation");if(!ie&&!p&&!L)throw new ue("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let Xe=y,Ye=new AbortController;L||N.add(Ye);let vr=()=>!L&&Xe!==y?new ue("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new ue("TIMEOUT","Indiana request timed out"),Di,id=new Promise((Le,nt)=>{Di=()=>nt(vr()),Ye.signal.addEventListener("abort",Di,{once:!0})}),od=setTimeout(()=>Ye.abort(),u),ad=async()=>{let Le=await c(`${s.href.replace(/\/$/,"")}/api/v1/${ne}`,{method:B,headers:{"Content-Type":"application/json",...L?{}:{Authorization:`Bearer ${ie??p}`},[ro]:io.current,[tc]:js.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:B==="POST"?JSON.stringify(Se):void 0,signal:Ye.signal,credentials:"omit",cache:"no-store",redirect:"error",...ce.keepalive?{keepalive:!0}:{}});if(Ye.signal.aborted)throw vr();let nt;try{nt=Le.status===204?rd:await Le.json()}catch{throw Ye.signal.aborted?vr():new ue(Le.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Le.status,Le.headers.get("X-Request-Id")??void 0)}if(Ye.signal.aborted)throw vr();if(!L&&Xe!==y)throw new ue("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Le.ok){let ze=Ka.safeParse(nt),Et=ze.success&&(!Vn.safeParse(ze.data.error.code).success||Ga(ze.data.error.code,Le.status)),Ua=Et?ze.data.error.code:"HTTP_ERROR",Va=Ha(Ua,Le.status,{retryAfter:Le.headers.get("Retry-After"),recovery:Et?ze.data.error.recovery:void 0,reason:Et?ze.data.error.reason:void 0});throw new ue(Ua,Et?ze.data.error.message:"Indiana request failed",Le.status,Le.headers.get("X-Request-Id")??(ze.success?ze.data.requestId:void 0),{...Va,...ze.success&&ze.data.error.retryable===!1?{retryable:!1}:{},...Va.retryAfterSeconds===void 0&&ze.success&&ze.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:ze.data.error.retryAfterSeconds}:{}})}if(Le.headers.get(ro)!==io.current)throw new ue("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&nt!==rd){let ze=nt&&typeof nt=="object"&&"scope"in nt?nt:nt&&typeof nt=="object"&&"configuration"in nt?nt.configuration:null;if(!ze||typeof ze!="object"||!("scope"in ze))throw new ue("INVALID_RESPONSE","Response is missing its App/environment scope");let Et=ve.safeParse(ze.scope);if(!Et.success||Et.data.projectId!==a.projectId||Et.data.environment!==a.environment)throw new ue("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Ir=Le.headers.get("X-Indiana-Telemetry-Subject");if(Ir){if(!/^[a-f0-9]{64}$/.test(Ir))throw new ue("INVALID_RESPONSE","Invalid telemetry identity");w!==Ir&&(w=Ir,t?.(w))}return nt};try{return await Promise.race([ad(),id])}catch(Le){throw!L&&Xe!==y?new ue("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Le instanceof ue?Le:new ue(Ye.signal.aborted?"TIMEOUT":"NETWORK_ERROR",Ye.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(od),Ye.signal.removeEventListener("abort",Di),N.delete(Ye)}}return{session:O,requestWithCredential(ne,Se,B){return Y(ne,Se,"POST",{},B)},subjectKey:()=>w,identify(ne){if(a&&typeof ne=="object"&&"scope"in ne){let Se=ve.safeParse(ne.scope);if(!Se.success||Se.data.projectId!==a.projectId||Se.data.environment!==a.environment)throw new ue("SCOPE_MISMATCH","Customer session belongs to another App/environment")}O.identify(ne),p=O.peek()??null},reset:D,dispose(){g(),d()},request(ne,Se={},B="POST",ce={}){if(ce.installationDetach)return Y(ne,Se,B,ce);let ie=y;try{let L=O.access(),Xe=Ye=>{if(ie!==y)throw new ue("IDENTITY_CHANGED","Customer identity changed before dispatch");return Y(ne,Se,B,ce,Ye)};return typeof L=="string"?Xe(L):L.then(Xe)}catch(L){return Promise.reject(L)}}}}export{Ug as a,Vg as b,Lg as c,$g as d,$r as e,Kg as f,Gh as g,Kh as h,Rs as i,Bt as j,bn as k,Ms as l,Yh as m,eg as n,dd as o,Ns as p,rg as q,fd as r,Ad as s,hd as t,Mr as u,qr as v,Gi as w,yd as x,ig as y,xd as z,og as A,ag as B,Vs as C,ug as D,lg as E,vd as F,Id as G,fg as H,lt as I,Ji as J,Wi as K,eo as L,zg as M,bx as N,Do as O,Tf as P,Ju as Q,qo as R,$x as S,Gx as T,Kx as U,lS as V,pS as W,dS as X,x0 as Y,Pl as Z,mA as _,fA as $,W0 as aa,na as ba,hA as ca,X0 as da,Y0 as ea,ev as fa,fr as ga,pv as ha,zl as ia,ql as ja,oa as ka,gA as la,xv as ma,j as na,YI as oa,GA as pa,ga as qa,wp as ra,AO as sa,yO as ta,jp as ua,_O as va,ZA as wa,PO as xa,Fn as ya,QA as za,WA as Aa,zO as Ba,KO as Ca,HO as Da,WO as Ea,ih as Fa,hw as Ga,gw as Ha,bw as Ia,Iw as Ja,kw as Ka,Rw as La,Ew as Ma,Tw as Na,Mw as Oa,Sr as Pa,s_ as Qa};
|