@tinkerlandai/longplay-sdk 0.10.23 → 0.10.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/README.md +79 -0
  3. package/README.zh-CN.md +31 -0
  4. package/dist/{ai-usage-WFwbPTiq.d.ts → ai-usage-B6RepnmH.d.ts} +1 -1
  5. package/dist/{api-rZ_QoNQi.d.ts → api-C9P338XT.d.ts} +1547 -6
  6. package/dist/{chunk-5SHVM4AF.js → chunk-2KI63SPJ.js} +2 -2
  7. package/dist/{chunk-7MF2YMN4.js → chunk-2ZJ5CS5Q.js} +1 -1
  8. package/dist/chunk-34I23EKZ.js +1 -0
  9. package/dist/{chunk-XFO4FBFG.js → chunk-5HJMAZ7A.js} +1 -1
  10. package/dist/chunk-7AXCG6NU.js +1 -0
  11. package/dist/chunk-BB5P5HPS.js +1 -0
  12. package/dist/chunk-C2BODHNY.js +1 -0
  13. package/dist/chunk-EIYWDWXP.js +1 -0
  14. package/dist/chunk-LFFBNGXP.js +1 -0
  15. package/dist/{chunk-HDVLCRC6.js → chunk-MHEYMXGZ.js} +2 -2
  16. package/dist/{chunk-EZLLTGV3.js → chunk-ML3BIPM6.js} +1 -1
  17. package/dist/{chunk-KZ63ANBP.js → chunk-O3LZPMS4.js} +1 -1
  18. package/dist/chunk-O4535GJR.js +6 -0
  19. package/dist/{chunk-PKLLZXNM.js → chunk-OEH47Y2L.js} +1 -1
  20. package/dist/chunk-RKREEPCT.js +1 -0
  21. package/dist/{chunk-QVGTHPWT.js → chunk-SJNF6JDJ.js} +1 -1
  22. package/dist/chunk-THGLNE4K.js +1 -0
  23. package/dist/chunk-TUYBXAAK.js +1 -0
  24. package/dist/chunk-ZX2RWS3T.js +1 -0
  25. package/dist/content-FD2Q6XD6.js +1 -0
  26. package/dist/{coupon-Btz_KFKp.d.ts → coupon-DyKA-BRG.d.ts} +8 -0
  27. package/dist/funnel-host-purchase-XW7IF52Y.js +1 -0
  28. package/dist/{funnel-local-client-BYdKGnMb.d.ts → funnel-local-client-CSA9XoC4.d.ts} +3270 -32
  29. package/dist/{funnel-node-evaluation-eLMEZIFz.d.ts → funnel-node-evaluation-Cg-4tcAs.d.ts} +88 -0
  30. package/dist/funnel-process-client-RXgS2i-R.d.ts +23184 -0
  31. package/dist/funnel-runtime-host-I6PJXVRC.js +1 -0
  32. package/dist/index.d.ts +1219 -31
  33. package/dist/index.js +1 -1
  34. package/dist/native-shell.js +1 -1
  35. package/dist/openrouter.d.ts +2 -2
  36. package/dist/openrouter.js +1 -1
  37. package/dist/page.js +1 -1
  38. package/dist/paywall-CGBFHFRU.js +1 -0
  39. package/dist/popup.d.ts +3 -3
  40. package/dist/popup.js +1 -1
  41. package/dist/{presentation-loading-Ctk1djAi.d.ts → presentation-loading-D0A9G_kT.d.ts} +16 -2
  42. package/dist/react-native.d.ts +6 -6
  43. package/dist/react-native.js +1 -1
  44. package/dist/screen-renderer-WOMWOEYL.js +1 -0
  45. package/dist/server.d.ts +2402 -17
  46. package/dist/server.js +1 -1
  47. package/dist/visual.js +1 -1
  48. package/package.json +1 -1
  49. package/dist/chunk-3J24TUO7.js +0 -1
  50. package/dist/chunk-6DTGBDYG.js +0 -1
  51. package/dist/chunk-DUZ2E7BK.js +0 -1
  52. package/dist/chunk-IIYIIXNB.js +0 -1
  53. package/dist/chunk-KRQESEG2.js +0 -6
  54. package/dist/chunk-WMIDEJTZ.js +0 -1
  55. package/dist/chunk-YAVWELIV.js +0 -1
  56. package/dist/content-FM52HLRX.js +0 -1
  57. package/dist/funnel-process-client-C87pmLC9.d.ts +0 -64499
  58. package/dist/funnel-runtime-host-MZKLVLC4.js +0 -1
  59. package/dist/paywall-JL4SXFXT.js +0 -1
  60. package/dist/screen-renderer-TEVGVUT5.js +0 -1
@@ -0,0 +1,6 @@
1
+ import{$ as fs,A as ns,Aa as Et,B as rs,D as is,Da as Qi,E as Dr,F as os,G as as,Ga as zr,Ha as Gt,Ia as gt,J as ss,Ja as Ji,K as Li,L as cs,M as Kn,Ma as As,O as ne,P as Ye,Q as lt,R as Rt,S as qr,T as ln,U as us,V as Ln,W as ps,X as ls,Y as ms,Z as Zn,_ as ds,a as me,aa as Zi,b as Gi,ba as mn,c as Qa,ca as hs,d as Ja,da as gs,ea as bs,fa as ys,ga as xs,h as ce,ha as dn,i as $i,ia as Ss,j as Wa,k as Rr,ka as Is,l as Er,la as vs,m as Mr,ma as Os,n as Xa,na as js,o as Gn,p as pt,q as le,qa as Br,r as Ki,ra as vt,s as It,t as Ya,u as Tr,ua as Hn,v as pn,w as es,wa as Ot,x as ts,xa as et,ya as fn,z as $n,za as Hi}from"./chunk-MHEYMXGZ.js";import{z as re}from"zod";import{z as p}from"zod";import{z as nm}from"zod";var Qn=nm.enum(["replace","stack_native"]);var Pe=p.string().min(1).max(200),Ke=p.iso.datetime({offset:!0}),_e=p.number().int().nonnegative().max(1e8),Jn=p.string().regex(/^[A-Z]{3}$/),rm=["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=p.enum(rm),jt=p.strictObject({priceId:p.uuid(),productVersionId:p.uuid(),productId:Pe,quantity:p.number().int().min(1).max(1e6),unitAmountMinor:_e,totalMinor:_e,interval:p.enum(["week","month","year","one_off"]),intervalCount:p.number().int().min(1).max(52),kind:p.enum(["fixed","prepaid","seat"]),tiers:p.strictObject({mode:p.enum(["graduated","volume"]),tiers:p.array(p.strictObject({upTo:p.number().int().positive().nullable(),unitAmountMinor:_e,flatAmountMinor:_e.optional()})).min(2).max(12)}).nullable()}),Wn=p.strictObject({grantId:p.uuid(),couponId:p.uuid(),amountMinor:_e,applicationPolicy:Qn.optional(),applicableProductIds:p.array(Pe).min(1).max(100).optional(),terms:p.discriminatedUnion("type",[p.strictObject({type:p.literal("percent"),percentOff:p.number().gt(0).max(100)}),p.strictObject({type:p.literal("amount"),amountOffMinor:_e,currency:Jn})]),duration:p.discriminatedUnion("type",[p.strictObject({type:p.literal("once")}),p.strictObject({type:p.literal("forever")}),p.strictObject({type:p.literal("repeating"),months:p.number().int().min(1).max(36)})])}),Xi={provider:p.literal("merchant"),executor:p.literal("merchant"),operationId:p.uuid(),customerId:p.uuid(),configurationRevision:p.number().int().nonnegative(),connectionRevision:p.number().int().nonnegative(),currency:Jn,expiresAt:Ke},Fr=p.strictObject({...Xi,type:p.literal("purchase"),mode:p.enum(["payment","subscription"]),lineItems:p.array(jt).min(1).max(100),catalogAmountMinor:_e,nativeDiscountMinor:_e.optional(),discount:Wn.nullable(),trialPeriodDays:p.number().int().min(1).max(730).nullable(),automaticTax:p.boolean()}).refine(e=>e.lineItems.reduce((t,n)=>t+n.totalMinor,0)===e.catalogAmountMinor&&(e.discount?.amountMinor??0)+(e.nativeDiscountMinor??0)<=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"),Mt=p.strictObject({...Xi,type:p.literal("subscription_change"),subscriptionId:p.uuid(),merchantSubscriptionId:Pe,membershipId:p.uuid(),subscriptionAction:p.enum(["update","cancel","schedule","release"]),supersedesOperationId:p.uuid().nullable(),change:p.discriminatedUnion("type",[p.strictObject({type:p.literal("cancel")}),p.strictObject({type:p.literal("uncancel")}),p.strictObject({type:p.literal("plan"),productVersionId:p.uuid()}),p.strictObject({type:p.literal("seats"),licenseKey:Pe,quantity:p.number().int().nonnegative().max(1e6)}),p.strictObject({type:p.literal("quantity"),internal_feature_id:p.uuid(),quantity:p.number().int().nonnegative().max(1e6)}),p.strictObject({type:p.literal("billing_cycle"),billingCycleAnchor:p.union([p.literal("now"),p.number().int().positive()])})]),timing:p.enum(["immediate","renewal"]),effectiveAt:Ke,creditMinor:_e,debitMinor:_e,totalMinor:_e,discountMinor:_e,discount:Wn.nullable().optional(),taxMinor:_e,proration:p.enum(["none","create_prorations","always_invoice"]),lineItems:p.array(jt.extend({quantity:p.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:p.array(p.uuid()).max(100),sourceLineItems:p.array(jt).min(1).max(100).optional()}),Nr=p.strictObject({...Xi,type:p.literal("refund"),invoiceId:p.uuid(),merchantInvoiceId:Pe,amountMinor:_e.refine(e=>e>0),mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),cancelSubscriptions:p.array(Pe).max(100)}),Cs=p.discriminatedUnion("type",[Fr,Mt,Nr]);function Yg(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"),e.discount&&t.add(`discount.${e.discount.terms.type}.${e.discount.duration.type}`)}return[...t].sort()}function eb(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.change.closed","subscription.observed",...e.change.type==="cancel"||e.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...e.entitlementAction==="revoke"&&e.cancelSubscriptions.length?["subscription.observed"]:[]]}var Xn=p.strictObject({phase:p.enum(["execution","payment","fulfillment","recording"]),code:Gi,reason:Ja.optional(),recovery:Qa,retryable:p.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),im=p.strictObject({type:p.literal("redirect"),url:p.url().startsWith("https://"),expiresAt:Ke}),Wi={operationId:p.uuid(),customerId:p.uuid(),merchantExecutionId:Pe,fulfillmentStatus:p.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:p.enum(["not_ready","pending","accepted","failed"]),updatedAt:Ke,problem:Xn.nullable(),pollAfterMs:p.number().int().min(1e3).max(6e4).nullable()},$t=p.discriminatedUnion("type",[p.strictObject({...Wi,type:p.literal("purchase"),merchantOrderId:Pe.nullable(),paymentStatus:p.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:Ke.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),p.strictObject({...Wi,type:p.literal("subscription_change"),status:p.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:Pe,scheduledFor:Ke.nullable(),nextAction:im.optional()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),p.strictObject({...Wi,type:p.literal("refund"),status:p.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:Pe.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ks=p.discriminatedUnion("lookup",[p.strictObject({lookup:p.literal("found"),operationId:p.uuid(),customerId:p.uuid(),execution:$t,readAt:Ke}),p.strictObject({lookup:p.literal("not_received"),operationId:p.uuid(),customerId:p.uuid(),execution:p.null(),readAt:Ke})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),Rs=p.strictObject({merchantPriceId:Pe,productId:Pe,kind:p.enum(["fixed","prepaid"]),currency:Jn,unitAmountMinor:_e,interval:p.enum(["one_off","day","week","month","year"]),intervalCount:p.number().int().min(1).max(100)}),_s={merchantItemId:Pe,quantity:p.number().int().positive().max(1e6)},om=e=>e.priceId??JSON.stringify(e.nativePrice),Yi=p.strictObject({merchantSubscriptionId:Pe,revision:p.number().int().positive(),status:p.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:Ke,periodEndsAt:Ke,cancelAtPeriodEnd:p.boolean(),hasDiscounts:p.boolean(),items:p.array(p.union([p.strictObject({..._s,priceId:p.uuid()}),p.strictObject({..._s,nativePrice:Rs})])).min(1).max(100)}).refine(e=>Date.parse(e.periodEndsAt)>Date.parse(e.periodStartsAt)&&new Set(e.items.map(om)).size===e.items.length&&new Set(e.items.map(t=>t.merchantItemId)).size===e.items.length,"Subscription periods and Price identities must be unambiguous"),ws={merchantLineId:Pe,quantity:p.number().int().nonnegative().max(1e6),subtotalMinor:p.number().int().min(-1e8).max(1e8),discountMinor:_e,taxMinor:_e,totalMinor:p.number().int().min(-1e8).max(2e8),periodStartsAt:Ke.nullable(),periodEndsAt:Ke.nullable()},eo=p.strictObject({merchantInvoiceId:Pe,reason:p.enum(["renewal","adjustment"]).optional(),currency:Jn,subtotalMinor:_e,discountMinor:_e,taxMinor:_e,totalMinor:_e,paidMinor:_e,periodStartsAt:Ke.nullable(),periodEndsAt:Ke.nullable(),lines:p.array(p.union([p.strictObject({...ws,priceId:p.uuid()}),p.strictObject({...ws,nativePrice:Rs})]).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"),Le={eventId:p.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:p.uuid(),occurredAt:Ke},Es=p.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]),am=p.strictObject({...Le,type:p.literal("purchase.completed"),operationId:p.uuid(),merchantOrderId:Pe,paymentStatus:p.enum(["paid","trialing","no_payment_required"]),invoice:eo.refine(e=>e.lines.every(t=>"priceId"in t),"An operation result retains its quoted Price identities").nullable(),subscription:Yi.refine(e=>e.items.every(t=>"priceId"in t),"An operation result retains its quoted Price identities").nullable()}),sm=p.strictObject({...Le,type:p.literal("purchase.closed"),operationId:p.uuid(),status:p.enum(["failed","expired","canceled"])}),cm=p.strictObject({...Le,type:p.literal("subscription.observed"),operationId:p.uuid().nullable(),subscription:Yi}),um=p.strictObject({...Le,type:p.literal("subscription.change.completed"),operationId:p.uuid(),status:p.enum(["scheduled","applied"]),scheduledFor:Ke.nullable(),subscription:Yi.refine(e=>e.items.every(t=>"priceId"in t),"An operation result retains its quoted Price identities"),invoice:eo.refine(e=>e.lines.every(t=>"priceId"in t),"An operation result retains its quoted Price identities").nullable()}),pm=p.strictObject({...Le,type:p.literal("subscription.change.closed"),operationId:p.uuid(),merchantSubscriptionId:Pe,merchantInvoiceId:Pe.nullable(),status:p.enum(["failed","expired","canceled"])}),lm=p.strictObject({...Le,type:p.literal("invoice.paid"),merchantSubscriptionId:Pe.nullable(),invoice:eo}),mm=p.strictObject({...Le,type:p.literal("refund.updated"),operationId:p.uuid().nullable(),merchantInvoiceId:Pe.optional(),merchantRefundId:Pe,status:p.enum(["pending","succeeded","failed"]),amountMinor:_e.refine(e=>e>0),currency:Jn}),Ms=[am.refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),sm,cm.refine(e=>e.operationId===null||e.subscription.items.every(t=>"priceId"in t),"Native Price references cannot replace an operation's quoted Prices"),um.refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),pm,lm,mm.refine(e=>e.operationId!==null||e.merchantInvoiceId!==void 0,"A native refund names its Invoice")];import{z as qe}from"zod";var Yn=qe.strictObject({days:qe.number().int().min(1).max(730),cardRequired:qe.boolean()}),ib=qe.object({...Yn.shape,featureAllowances:qe.record(qe.uuid(),qe.number().int().min(0).max(1e9)),creditAmounts:qe.record(qe.uuid(),le)}).strict(),ob=qe.object({id:qe.uuid(),planVersionId:qe.uuid(),slot:qe.string(),cardRequired:qe.boolean(),status:qe.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:qe.iso.datetime().nullable(),endsAt:qe.iso.datetime().nullable(),createdAt:qe.iso.datetime()}).strict();import{z as er}from"zod";var to=er.number().int().positive().max(2e8),Vr=er.number().int().min(0).max(2e8),tr=e=>e.mode==="partial"==(e.amountMinor!==void 0),Kt=er.strictObject({mode:er.enum(["full","partial"]),amountMinor:to.optional(),entitlementAction:er.enum(["retain","revoke"])});var Be=re.string().min(1).max(200),hn=re.iso.datetime({offset:!0}),gn=Vr,Ts=gn.maxValue,Gr=re.number().int().min(-Ts).max(Ts),Ur=re.string().regex(/^[A-Z]{3}$/),Ds=re.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),qs=re.array(Be).max(100).refine(e=>new Set(e).size===e.length),dm=re.strictObject({merchantProductId:Be,merchantPriceId:Be,productVersionId:re.uuid().optional(),quantity:le.refine(e=>/[1-9]/.test(e))}),no={subject:Xa,operationId:re.uuid(),configurationRevision:Ds,connectionRevision:Ds,expiresAt:hn},ro=re.discriminatedUnion("action",[re.strictObject({...no,action:re.literal("purchase"),mode:re.enum(["payment","subscription"]),currency:Ur,items:re.array(dm).min(1).max(100),offerRefs:qs}),re.strictObject({...no,action:re.literal("subscription_change"),currency:Ur,merchantSubscriptionId:Be,change:Mt.shape.change,timing:Mt.shape.timing,proration:Mt.shape.proration,offerRefs:qs}),re.strictObject({...no,action:re.literal("refund"),currency:Ur,merchantInvoiceId:Be,mode:Kt.shape.mode,amountMinor:Kt.shape.amountMinor,entitlementAction:Kt.shape.entitlementAction}).refine(tr,"Only a partial refund chooses amountMinor")]),Bs=re.strictObject({request:ro,requestedAt:hn,preparationAllowed:re.boolean()}).refine(e=>!e.preparationAllowed||Date.parse(e.requestedAt)<Date.parse(e.request.expiresAt),"Preparation authority must be within its original validity"),fm=re.strictObject({merchantLineId:Be,merchantPriceId:Be.nullable(),quantity:le.refine(e=>/[1-9]/.test(e)),subtotalMinor:Gr,discountMinor:gn,taxMinor:gn.nullable(),totalMinor:Gr.nullable()}).refine(e=>e.taxMinor===null==(e.totalMinor===null)&&(e.totalMinor===null||e.totalMinor===e.subtotalMinor-e.discountMinor+e.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),hm=re.strictObject({items:re.array(re.strictObject({merchantPriceId:Be,quantity:le.refine(e=>/[1-9]/.test(e)),interval:jt.shape.interval.exclude(["one_off"]),intervalCount:jt.shape.intervalCount,amountMinor:jt.shape.totalMinor,amountAfterOfferMinor:jt.shape.totalMinor.optional()})).min(1).max(100),trial:Yn.nullable(),discount:Wn.nullable().optional(),discountExpiresAt:hn.nullable().optional(),initialAmountMinor:jt.shape.totalMinor.optional()}),zs=re.strictObject({request:ro,requestDigest:Mr,merchantQuoteId:Be,quoteTermsDigest:Mr,termsVersion:Be,sourceRevisions:re.array(re.strictObject({reference:Be,revision:Be})).max(100),observedAt:hn,expiresAt:hn,currency:Ur,automaticTax:re.boolean(),lines:re.array(fm).max(100),subscriptionTerms:hm.nullable(),subtotalMinor:Gr,discountMinor:gn,nativeDiscountMinor:gn.optional(),discount:Wn.nullable().optional(),taxMinor:gn.nullable(),totalMinor:Gr.nullable(),effectiveAt:hn.nullable(),expectedEffects:re.array(re.strictObject({reference:Be,kind:re.enum(["grant","revoke","change"]),description:re.string().min(1).max(1e3),quantity:le.nullable(),unit:Be.nullable()}).refine(e=>e.quantity===null==(e.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:re.array(re.strictObject({reference:Be,version:Be,summary:re.string().min(1).max(1e3)})).max(20)}),At=zs.superRefine((e,t)=>{let{quoteTermsDigest:n,...r}=e,i=e.lines.every(c=>c.taxMinor!==null),a=e.request.action==="purchase"&&e.request.mode==="subscription"!=(e.subscriptionTerms!==null),m=e.subscriptionTerms!==null&&(e.request.action==="refund"||e.request.action==="subscription_change"&&e.request.change.type==="cancel");(e.requestDigest!==Gn(e.request)||e.quoteTermsDigest!==Gn(r)||e.currency!==e.request.currency||a||m||e.lines.length===0&&(e.request.action!=="subscription_change"||e.subtotalMinor!==0||e.discountMinor!==0||e.taxMinor!==0||e.totalMinor!==0)||Date.parse(e.observedAt)>=Date.parse(e.expiresAt)||Date.parse(e.expiresAt)>Date.parse(e.request.expiresAt)||new Set(e.lines.map(c=>c.merchantLineId)).size!==e.lines.length||new Set(e.sourceRevisions.map(c=>c.reference)).size!==e.sourceRevisions.length||new Set(e.requiredConsents.map(c=>c.reference)).size!==e.requiredConsents.length||e.subtotalMinor!==e.lines.reduce((c,d)=>c+d.subtotalMinor,0)||e.discountMinor!==e.lines.reduce((c,d)=>c+d.discountMinor,0)||e.taxMinor!==null!==i||!i&&!e.automaticTax||e.taxMinor===null!=(e.totalMinor===null)||i&&(e.taxMinor!==e.lines.reduce((c,d)=>c+d.taxMinor,0)||e.totalMinor!==e.subtotalMinor-e.discountMinor+e.taxMinor)||e.request.action!=="subscription_change"&&(e.subtotalMinor<0||e.totalMinor!==null&&e.totalMinor<0)||e.request.action==="refund"&&(e.taxMinor===null||e.totalMinor===null||e.totalMinor<=0||e.request.mode==="partial"&&e.totalMinor!==e.request.amountMinor))&&t.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function $r(e,t,n,r){return e.request.operationId===t&&e.request.action===n&&e.currency===r}function hb(e){return Gn(ro.parse(e))}function gb(e){return Gn(zs.omit({quoteTermsDigest:!0}).parse(e))}var nr=re.strictObject({quoteTermsDigest:Mr,consents:re.array(re.strictObject({reference:Be,version:Be})).max(20)});function bb(e){return{quoteTermsDigest:e.quoteTermsDigest,consents:e.requiredConsents.map(({reference:t,version:n})=>({reference:t,version:n}))}}var gm=nr.extend({operationId:re.uuid()}).refine(e=>new Set(e.consents.map(t=>t.reference)).size===e.consents.length);function yb(e,t){let n=At.parse(e),r=gm.parse(t);return r.operationId===n.request.operationId&&r.quoteTermsDigest===n.quoteTermsDigest&&r.consents.length===n.requiredConsents.length&&n.requiredConsents.every(i=>r.consents.some(a=>a.reference===i.reference&&a.version===i.version))}import{z as h}from"zod";import{z as Lt}from"zod";var bt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,bn=Lt.object({customerId:Lt.uuid(),sessionId:Lt.uuid(),accessToken:Lt.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Lt.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Lt.iso.datetime(),refreshExpiresAt:Lt.iso.datetime()});var Zt=3,Ns="/integrations/indiana",_b="X-Indiana-Merchant-Bridge-Version",oo=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],bm=h.enum(oo),wb={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"}},Vs=h.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),Us=h.string().regex(/^[A-Za-z0-9_-]{1,64}$/),ym=h.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),ao=h.strictObject({keyId:Us,signingSecret:ym}),xm=h.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),Gs=h.array(bm).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),Lr=h.strictObject({bridgeVersion:h.literal(Zt),projectId:h.uuid(),environmentId:h.uuid(),environment:h.enum(["sandbox","live"]),capabilities:Gs,catalog:h.enum(["endpoint","static","none"]),billingEvents:h.array(Es).max(7),profiles:h.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"})}),$s=h.strictObject({origin:xm,requiredCapabilities:Gs}),Sm=h.strictObject({revision:h.number().int().nonnegative(),checkedAt:h.iso.datetime(),outcome:h.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:h.strictObject({ping:h.enum(["passed","failed","not_checked"]),authentication:h.enum(["passed","failed","not_checked"]),catalog:h.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:Lr.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),Pb=h.strictObject({projectId:h.uuid(),environmentId:h.uuid(),environment:h.enum(["sandbox","live"]),execution:h.enum(["indiana","record_only"]),accountId:h.string().nullable(),revision:h.number().int().nonnegative(),authentication:h.strictObject({keyId:Us}).nullable(),secretStoreConfigured:h.boolean().optional(),connection:$s.nullable(),check:Sm.nullable()});var Fs=h.strictObject({projectId:h.uuid(),environmentId:h.uuid()}),Cb=h.discriminatedUnion("action",[Fs.extend({action:h.literal("save"),revision:h.number().int().nonnegative(),connection:$s,authentication:ao.optional()}),Fs.extend({action:h.literal("check"),revision:h.number().int().nonnegative()})]),Ht=h.strictObject({projectId:h.uuid(),environmentId:h.uuid(),environment:h.enum(["sandbox","live"])});function kb(e){return h.strictObject({bridgeVersion:h.literal(Zt),requestId:h.uuid(),command:Vs,scope:Ht,data:e})}var Im=h.strictObject({nativeUserId:h.string().min(1).max(128),session:bn.strict()}),vm=h.strictObject({nativeUserId:h.string().min(1).max(128),presentation:h.strictObject({customerId:h.uuid(),decisionId:h.uuid(),offeringVersionId:h.uuid(),paywallVersionId:h.uuid(),variant:h.string().min(1).max(128)}).nullable()}),Om=h.strictObject({decisionId:h.uuid(),eventId:h.uuid()}),Kr=h.strictObject({operationId:h.uuid(),customerId:h.uuid()}),Zr=h.strictObject({scope:Ht,operationId:h.uuid(),customerId:h.uuid(),confirmedAt:h.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:h.boolean(),instruction:Cs,merchantTerms:At.optional()}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId&&(!e.merchantTerms||e.merchantTerms.request.operationId===e.operationId&&e.merchantTerms.request.subject.customerId===e.customerId&&e.merchantTerms.request.action===e.instruction.type&&e.merchantTerms.currency===e.instruction.currency&&Object.entries(e.scope).every(([t,n])=>e.merchantTerms.request.subject.scope[t]===n)),"Authority must refer to the original Customer and operation"),io=$t,_t=h.string().min(1).max(120),jm=h.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Am=h.strictObject({revision:_t,updatedAt:h.iso.datetime(),provider:h.literal("merchant"),items:h.array(h.strictObject({merchantProductId:_t,productVersionId:h.uuid(),name:h.string().min(1).max(255),kind:h.enum(["subscription","credit_pack"]),merchantPriceId:_t,currency:h.string().regex(/^[a-z]{3}$/),amountMinor:h.number().int().nonnegative().max(1e8),interval:h.enum(["one_time","month","year"]),intervalCount:h.literal(1),includedCredits:h.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:h.enum(["none","month"]),creditPolicyId:_t,available:h.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)}),_m=h.strictObject({customerId:h.uuid(),revision:h.string().min(1).max(128),observedAt:h.iso.datetime(),subscriptions:h.array(h.strictObject({merchantSubscriptionId:_t,merchantProductId:_t,productVersionId:h.uuid().nullable(),status:h.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:h.iso.datetime().nullable(),currentPeriodEndsAt:h.iso.datetime().nullable(),cancelAtPeriodEnd:h.boolean(),scheduledChange:h.strictObject({effectiveAt:h.iso.datetime(),merchantProductId:_t}).nullable()})).max(100),purchaseHistory:h.strictObject({complete:h.boolean(),hasPaidPurchase:h.boolean(),lastPaidAt:h.iso.datetime().nullable()}),balances:h.array(h.strictObject({bucketId:_t,key:_t,available:jm,expiresAt:h.iso.datetime().nullable(),nextResetAt:h.iso.datetime().nullable()})).max(100)}),Rb=h.strictObject({bridgeVersion:h.literal(Zt),requestId:h.uuid(),command:h.string().min(1).max(64),scope:Ht,error:h.strictObject({code:h.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:h.string().min(1).max(500),retryable:h.boolean(),recovery:h.string().min(1).max(80)})}),rr=h.strictObject({}),wm={"bridge.ping":h.strictObject({challenge:h.uuid()}),"bridge.describe":rr,"session.create":rr,"catalog.read":rr,"customer.commerce.read":rr,"presentation.resolve":rr,"presentation.report":Om,"purchase.execute":Kr,"operation.read":Kr,"subscription.change":Kr,"refund.execute":Kr},Eb={"bridge.ping":h.strictObject({challenge:h.uuid()}),"bridge.describe":Lr,"session.create":Im,"catalog.read":Am,"customer.commerce.read":_m,"presentation.resolve":vm,"presentation.report":h.strictObject({queued:h.literal(!0)}),"purchase.execute":io,"operation.read":ks,"subscription.change":io,"refund.execute":io},Mb=h.strictObject({bridgeVersion:h.literal(Zt),requestId:h.uuid(),scope:Ht,command:Vs,data:h.unknown()}).superRefine((e,t)=>{wm[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});var Ks="X-Indiana-Bridge-Signature",Ls="X-Indiana-Bridge-Key-Id";function Pm(e){return new TextEncoder().encode(e)}function Zs(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}function Hs(e,t,n,r){return Pm(`indiana-merchant-bridge:${r}
2
+ ${t}
3
+ POST
4
+ ${Ns}
5
+ ${n}
6
+ ${e}`)}async function Qs(e){let t=ao.parse(e);return crypto.subtle.importKey("raw",Zs(t.signingSecret),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function qb(e,t,n,r=Date.now(),i=Zt){let a=String(Math.floor(r/1e3)),m=new Uint8Array(await crypto.subtle.sign("HMAC",await Qs(t),Hs(e,n,a,i))),c=btoa(String.fromCharCode(...m)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");return{[Ls]:t.keyId,[Ks]:`t=${a},v1=${c}`}}async function Bb(e,t,n,r,i=Date.now(),a=Zt){try{if(t.get(Ls)!==n.keyId)return!1;let m=/^t=([0-9]{1,12}),v1=([A-Za-z0-9_-]{43})$/.exec(t.get(Ks)??"");return!m||Math.abs(i/1e3-Number(m[1]))>300?!1:await crypto.subtle.verify("HMAC",await Qs(n),Zs(m[2]),Hs(e,r,m[1],a))}catch{return!1}}var Js={"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 so(e){let t=us(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=Js[r];return i?{locale:t,copy:i}:{locale:"en",copy:Js.en}}function Cm(e,t,n="zh-CN"){let r=$i(t);return Wa(e,t,so(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function km(e,t="zh-CN"){let n=so(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(e.percentOff/100):Cm(e.amountOffCents,e.currency,n)}var Ws={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 Vb(e,t="zh-CN",n="month"){let r=so(t),i=km(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):"",m=r.locale.split("-")[0]??"en",c=m==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":m,d=e.duration.type==="repeating"&&n!=="month"?Ws[c]??Ws.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],I=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return d.replace("{discount}",i).replace("{months}",a).replace("{period}",I)}import{z as X}from"zod";import{z as Ve}from"zod";var Re=Ve.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"),co=Ve.strictObject({type:Ve.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Ve.boolean(),enum:Ve.array(Ve.string().max(255)).min(1).max(100).optional()}),yn=co.extend({type:Ve.enum([...co.shape.type.options,"array"]),items:co.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:Ve.discriminatedUnion("type",[Ve.strictObject({type:Ve.literal("input")}),Ve.strictObject({type:Ve.literal("node")}),Ve.strictObject({type:Ve.enum(["parameter","attribute"]),key:Re})])}),Rm=Ve.record(Re,xn),Hr=Ve.record(Re,Re).refine(e=>Object.keys(e).length<=20);function at(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=>at(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&&Ve.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 uo(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&&uo(e.items,t.items)}function ir(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,m=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,d=Object.hasOwn(m,c),I=m[c];if(a.type==="attribute"&&c.includes(".")&&(!d||c.startsWith("merchandise."))){I=m,d=!0;for(let g of c.split(".")){if(!I||typeof I!="object"||!Object.hasOwn(I,g)||Array.isArray(I)&&(!/^(0|[1-9]\d*)$/.test(g)||Number(g)>=I.length)){d=!1;break}I=I[g]}}if(!(!d||I===void 0)){if(!at(i,I))throw new Error(`Invalid variable value: ${r}`);n[r]=I}}return n}function Qt(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 po(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"||!at(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 Jt}from"zod";var mt=Jt.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"),yt=Jt.discriminatedUnion("source",[Jt.strictObject({source:Jt.literal("literal"),value:ne}),Jt.strictObject({source:Jt.literal("variable"),key:Jt.string().min(1).max(255),path:mt.optional()})]);function Xs(e,t){if(!t)return e;for(let n of mt.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 lo(e,t){if(e.source==="literal")return structuredClone(e.value);let n=ir(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ne.parse(Xs(n[e.key],e.path)))}function mo(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&&!mt.safeParse(r).success?null:{key:n,path:r}}function fo(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Ot(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Ss))]}function Qr(e){return fo(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function tt(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 m=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let c=t.slice(m,i+1);if(!/[eE]/.test(c))continue;let[d="",I]=c.split(/[eE]/),g=d.replace(/^-/,""),T=g.replace(".","").length,$=(g.includes(".")?g.indexOf("."):T)+Number(I),C=$<=0?2-$+T:$>=T?$:T+1;n+=C+(d.startsWith("-")?1:0)-c.length}}return n}var Tt=X.enum(["page","popup","banner"]),Em=3e5,Ys=X.strictObject({type:X.enum(["string","number","boolean","strings","json"]),nullable:X.boolean()}),Mm=X.strictObject({inputs:X.record(Hn,Ys.extend({required:X.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:X.record(Hn,Ys).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Tm=X.strictObject({kind:Tt,schemaVersion:X.literal(1),name:X.string().trim().min(1).max(80),screen:et,contract:Mm}),Jr=Tm.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"]),tt(e)>Em&&n("Content document exceeds its byte budget",[])});function Dm(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 qm=Jr.superRefine((e,t)=>{for(let n of Qr(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&&!Dm(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}Et(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),ec=X.strictObject({id:X.uuid(),kind:Tt,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})}),oy=ec.extend({draft:Jr}),ay=X.strictObject({rows:X.array(ec).max(200),nextCursor:X.uuid().nullable()}),ho=X.strictObject({id:X.uuid(),kind:Tt,resourceId:X.uuid(),projectId:X.uuid(),environmentId:X.uuid(),version:X.number().int().positive(),sourceRevision:X.number().int().nonnegative(),document:qm,createdAt:X.iso.datetime({offset:!0})}),sy=ho.omit({document:!0}),cy=X.discriminatedUnion("action",[X.strictObject({action:X.literal("create"),kind:Tt,id:X.uuid(),document:Jr}),X.strictObject({action:X.literal("save"),kind:Tt,id:X.uuid(),revision:X.number().int().nonnegative(),document:Jr}),X.strictObject({action:X.enum(["publish","archive"]),kind:Tt,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 Wr=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:vs.optional()});function my(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 te}from"zod";import{z as Ze}from"zod";var In=Ze.string().regex(/^[a-f0-9]{64}$/),Bm=xs.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),tc=Ze.strictObject({couponDigests:Ze.record(Ze.uuid(),In),variables:Ze.record(ln,Ze.record(Ze.uuid(),Ze.partialRecord(Ze.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Ze.string()))),locales:Ze.record(ln,dn.extend({nodes:Ze.record(Ze.string(),Ze.strictObject({base:Bm})),plans:Ze.object({}).strict(),pickers:Ze.object({}).strict()}).omit({paywall:!0}))});import{z as H}from"zod";import{z as Xr}from"zod";var go=Xr.strictObject({eventsEnabled:Xr.boolean(),experimentViewsEnabled:Xr.boolean(),featureUsageEnabled:Xr.boolean()}),xy=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Sy(e,t){return t==="experiment_exposure"?e.experimentViewsEnabled:t==="feature_usage"?e.featureUsageEnabled:e.eventsEnabled}import{z as _}from"zod";var bo=_.tuple([_.number().min(0).max(1),_.number().min(0).max(1)]).refine(([e,t])=>e<=t),zm=_.strictObject({attribute:_.string().optional(),seed:_.string(),hashVersion:_.literal(2),ranges:_.array(bo).max(100)}),Fm=_.strictObject({id:_.string().min(1).max(255),condition:lt,gate:_.boolean().optional()}),Nm=_.strictObject({key:_.string().optional(),name:_.string().optional(),passthrough:_.boolean().optional()}),nc={condition:lt.optional(),parentConditions:_.array(Fm).max(100).optional(),weights:_.array(_.number().min(0).max(1)).max(20).optional(),coverage:_.number().min(0).max(1).optional(),hashAttribute:_.string().optional(),fallbackAttribute:_.string().optional(),hashVersion:_.literal(2).optional(),disableStickyBucketing:_.boolean().optional(),bucketVersion:_.number().int().nonnegative().optional(),minBucketVersion:_.number().int().nonnegative().optional(),filters:_.array(zm).max(100).optional(),ranges:_.array(bo).max(20).optional(),meta:_.array(Nm).max(20).optional(),seed:_.string().optional(),name:_.string().optional(),phase:_.string().optional()},vn=_.strictObject({...nc,key:_.string().min(1).max(255),variations:_.tuple([ne,ne]).rest(ne).refine(e=>e.length<=20),urlPatterns:_.array(_.strictObject({include:_.boolean(),type:_.enum(["regex","simple"]),pattern:_.string()})).max(100).optional(),force:_.number().int().nonnegative().optional(),active:_.boolean().optional(),persistQueryString:_.boolean().optional()}),yo=_.strictObject({value:ne,variationId:_.number().int(),key:_.string(),name:_.string().optional(),bucket:_.number().optional(),passthrough:_.boolean().optional(),inExperiment:_.boolean(),hashUsed:_.boolean().optional(),hashAttribute:_.string(),hashValue:_.string(),featureId:_.string().nullable(),stickyBucketUsed:_.boolean().optional()}),Vm=_.strictObject({...nc,id:_.string().max(255).optional(),force:ne.optional(),variations:_.array(ne).min(2).max(20).optional(),key:_.string().optional(),range:bo.optional(),tracks:_.array(_.strictObject({experiment:vn,result:yo})).max(100).optional()}),Um=_.strictObject({defaultValue:ne.optional(),rules:_.array(Vm).max(500).optional()}),or=_.record(_.string(),_.union([_.strictObject({type:_.literal("hashed"),attributeKey:_.string(),values:_.array(_.string().regex(/^[a-f0-9]{64}$/))}),_.strictObject({type:_.literal("list"),attributeKey:_.string(),values:_.array(_.union([_.string(),_.number()]))}),_.strictObject({type:_.literal("condition"),condition:lt})])),wt=_.strictObject({scope:me,generation:_.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:_.iso.datetime({offset:!0}),expiresAt:_.iso.datetime({offset:!0}).nullable(),features:_.record(_.string(),Um),savedGroups:or,experiments:_.record(_.uuid(),vn)});import{z as ze}from"zod";function Dt(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,m){if(n(a))for(let[c,d]of Object.entries(a))c==="$elemMatch"?i(d,m):c==="$not"?r(d,m):c==="$all"&&Array.isArray(d)&&d.forEach(I=>r(I,m))}function i(a,m=""){if(n(a)){for(let[c,d]of Object.entries(a))if(["$and","$or","$nor"].includes(c)&&Array.isArray(d))d.forEach(I=>i(I,m));else if(c==="$not")i(d,m);else if(c==="$savedGroup"&&n(d))typeof d.attributeKey=="string"&&t.add(d.attributeKey);else if(!c.startsWith("$")){let I=m?`${m}.${c}`:c;t.add(I),r(d,I)}}}return i(e),[...t]}var Gm=ze.enum(["active","inactive"]),$m=ze.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(m=>r(m,a+1));else if(i&&typeof i=="object")for(let[m,c]of Object.entries(i))["__proto__","constructor","prototype"].includes(m)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(c,a+1)}}return r(e,0),e},Ye),Km=ze.strictObject({id:ze.string().trim().min(1).max(255),name:ze.string().trim().min(1).max(255),status:Gm,metadata:$m}),ky=Km.extend({internal_id:ze.uuid(),project_id:ze.uuid(),environment_id:ze.uuid(),created_at:ze.iso.datetime({offset:!0}),updated_at:ze.iso.datetime({offset:!0})}),ic=ze.union([ze.strictObject({id:ze.string().trim().min(1).max(255)}),ze.strictObject({internalId:ze.uuid()})]),Ry=ze.enum(["customer","merchandise","context"]),Ey=ze.enum(["system","stored","request"]),My=ze.enum(["customer","merchandise","mixed"]),rc=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function xo(e,t={},n=new Set){if(Dt(e).some(rc))return!0;for(let r of Rt(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&rc(i.attributeKey)||i?.type==="condition"&&xo(i.condition,t,n))return!0}return!1}var So=wt.extend({analyticsConfig:go,remoteFeatures:H.array(H.string().min(1).max(255)).max(500)}),Lm=So.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"})}),ac=H.strictObject({attributes:Ye,features:H.array(H.string().min(1).max(255)).max(500).optional(),customerId:H.uuid().optional()}),sc=H.strictObject({value:ne,source:H.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:H.boolean(),off:H.boolean(),ruleId:H.string(),experimentResult:yo.optional()}),cc=H.strictObject({generation:wt.shape.generation,evaluatedAt:wt.shape.evaluatedAt,expiresAt:wt.shape.expiresAt,features:H.record(H.string(),sc),merchandiseContext:H.strictObject({merchandiseId:H.uuid(),merchandise:Ye}).optional()}),uc={eventUuid:H.uuid(),timestamp:H.iso.datetime({offset:!0}),merchandise:ic.optional(),deviceId:H.string().min(1).max(255).optional(),sessionId:H.string().min(1).max(255).optional()},oc={...uc,generation:wt.shape.generation},Zm=H.discriminatedUnion("kind",[H.strictObject({...uc,kind:H.literal("custom"),name:H.string().min(1).max(255),properties:H.record(H.string(),ne).default({})}),H.strictObject({...oc,kind:H.literal("experiment_exposure"),experimentId:H.string().min(1).max(255),variationId:H.string().min(1).max(255)}),H.strictObject({...oc,kind:H.literal("feature_usage"),feature:H.string().min(1).max(255),value:ne,source:sc.shape.source,ruleId:H.string().max(255),variationId:H.string().min(1).max(255).optional()})]),pc=H.strictObject({customerId:H.uuid().optional(),events:H.array(Zm).min(1).max(100)}),Hm=H.strictObject({eventUuid:H.uuid(),reason:H.enum(["invalid_event","invalid_merchandise","not_delivered","reserved_name"])}),lc=H.strictObject({inserted:H.number().int().nonnegative(),duplicates:H.number().int().nonnegative(),rejected:H.number().int().nonnegative(),skipped:H.number().int().nonnegative(),rejections:H.array(Hm).max(100),analyticsConfig:go});import{z as j}from"zod";import{z as Qm}from"zod";var Io=Qm.enum(["funnel-run/1","funnel-process/1"]),vo="funnel-process/1";function Oo(e,t=[]){let n=[];Ot(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(Hi(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let m of Object.keys(a))r.has(m)||n.push(`Unused string ${m} must not be delivered (${i})`);return n}function mc(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>mc(t)??[])}}function Jm(e){let t=e.pages.map(i=>{let a=mc(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(Hi({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([m])=>n.has(m)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function dc(e,t=[]){let n=et.parse(structuredClone(Jm(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=Oo(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Se}from"zod";var Ly=Se.discriminatedUnion("action",[Se.strictObject({action:Se.literal("create"),couponId:Se.uuid(),productBindingId:Se.uuid(),storeOfferId:Se.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Se.enum(["introductory","promotional"])}),Se.strictObject({action:Se.literal("set_enabled"),id:Se.uuid(),revision:Se.number().int().nonnegative(),enabled:Se.boolean()})]),Zy=Se.array(Se.strictObject({id:Se.uuid(),couponId:Se.uuid(),productBindingId:Se.uuid(),storeOfferId:Se.string().min(1).max(255).nullable(),storeOfferType:Se.enum(["introductory","promotional"]),enabled:Se.boolean(),revision:Se.number().int().nonnegative()})).max(500),On=Se.strictObject({offerKind:Se.enum(["none","introductory","promotional"]),offerId:Se.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Se.number().int().min(0).max(1e8),trialDays:Se.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"})}),Hy=Se.record(Se.uuid(),On).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");import{z as P}from"zod";import{z as x}from"zod";import{z as we}from"zod";var Yr=we.strictObject({schemaVersion:we.literal(1),renderKey:we.string().min(1).max(256),routeTemplate:we.string().startsWith("/").max(2048),selectors:we.array(we.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:we.array(we.number().int().min(0)).min(1),absent:we.array(we.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),fc=we.strictObject({renderKey:we.string().min(1).max(256),routeKey:we.string().min(1).max(256),stateKey:we.string().min(1).max(256),documentKey:we.string().min(1).max(256),documentHash:we.string().regex(/^[a-f0-9]{64}$/),compositionKey:we.string().min(1).max(256),entryMode:we.enum(["hard","soft"]),match:we.strictObject({present:we.array(we.number().int().min(0)),absent:we.array(we.number().int().min(0))})});import{z as Wt}from"zod";var Wm=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],jo="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Xm=Wt.string().regex(new RegExp(`^${jo}/${jo}/${jo}/manifest\\.json$`)),hc=Wt.strictObject({kind:Wt.literal("gcs-resumable"),url:Wt.url(),bucket:Wt.enum(Wm),objectKey:Xm,byteLength:Wt.number().int().positive(),expiresAt:Wt.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var Ce=x.string().min(1).max(256),nt=x.string().regex(/^[a-f0-9]{64}$/),ei=x.strictObject({versionId:x.uuid(),manifestDigest:nt,sourceGraphDigest:nt,pageKey:Ce,stateKey:Ce,documentKey:Ce,documentHash:nt,elementKey:Ce.optional(),nodeId:Ce.optional(),contentHash:nt.optional(),renderKey:Ce.optional()}),gc=x.strictObject({pageKey:Ce,documentKey:Ce,expectedDocumentHash:nt,renderKey:Ce.optional(),nodeId:Ce,elementKey:Ce,expectedContentHash:nt,property:x.enum(["text","fontSize","color"]),value:x.union([x.string().max(4e3),x.number().finite()])}),bc=x.strictObject({versionId:x.uuid(),manifestDigest:nt,sourceGraphDigest:nt,pageKey:Ce,stateKey:Ce,documentKey:Ce,documentHash:nt,renderKey:Ce.optional(),patches:x.array(gc.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),Ym=/^[a-z][a-z0-9-]{0,39}$/,ar=x.string().regex(Ym),_o=x.enum(["web","ios","android"]),rx=x.discriminatedUnion("action",[x.strictObject({action:x.literal("register"),requestId:x.uuid(),client:ar,platform:_o,label:x.string().trim().min(1).max(100),sha256:nt,bytes:x.number().int().min(1),transferBytes:x.number().int().min(1)}),x.strictObject({action:x.literal("complete"),versionId:x.uuid()}),x.strictObject({action:x.literal("current"),versionId:x.uuid(),expectedCurrent:x.uuid().nullable()}),x.strictObject({action:x.literal("delivery"),enabled:x.boolean()}),x.strictObject({action:x.literal("changes"),versionId:x.uuid(),experimentId:x.uuid(),variationId:Ce,changesetId:x.uuid().nullable(),expectedRevision:nt.nullable(),editorUrl:x.string().url().max(2048),patches:x.array(gc).max(200)})]),wo=x.strictObject({id:x.uuid(),projectId:x.uuid(),environmentId:x.uuid(),clientKey:ar,platform:_o,label:x.string(),sha256:nt,bytes:x.number().int().positive(),objectKey:x.string(),state:x.enum(["uploading","ready","rejected"]),isCurrent:x.boolean(),revision:x.number().int().nonnegative(),createdAt:x.string(),expiresAt:x.string(),readyAt:x.string().nullable(),summary:x.record(x.string(),x.json()),routeTree:x.json().nullable(),validation:x.record(x.string(),x.json())}),ed=x.strictObject({key:ar,platform:_o,currentId:x.uuid().nullable()}),ix=x.strictObject({rows:x.array(wo).max(100),nextCursor:x.uuid().nullable(),clients:x.array(ed).max(20)}),Ao=x.strictObject({storedBytes:x.number().int().nonnegative(),reservedBytes:x.number().int().nonnegative(),chargedBytes:x.number().int().nonnegative(),versions:x.number().int().nonnegative(),objects:x.number().int().nonnegative(),orphanObjects:x.number().int().nonnegative(),missingReadyObjects:x.number().int().nonnegative(),unknownObjectSizes:x.number().int().nonnegative(),byteLimit:x.number().int().positive(),versionLimit:x.number().int().positive(),remainingBytes:x.number().int().nonnegative()}),ox=x.strictObject({asOf:x.iso.datetime({offset:!0}),reclamation:x.literal("manual-review-required"),buckets:x.strictObject({source:Ao,runtime:Ao,previews:Ao})}),ax=x.strictObject({version:wo,actorId:x.uuid(),claims:x.record(x.string(),x.json())}),sx=x.strictObject({version:wo,upload:hc.nullable()}),cx=x.object({format:x.literal("indiana-route-state-index"),schemaVersion:x.literal(3),routes:x.array(x.object({routeKey:Ce,path:x.string(),documentKey:Ce,documentHash:nt,initialStateKey:Ce,initialRenderKey:Ce})),renders:x.array(fc)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),ux=x.strictObject({rows:x.array(x.object({id:x.uuid(),name:x.string(),status:x.string(),variations:x.array(x.object({id:Ce,key:Ce,name:x.string().optional()}).loose())}).loose()),limited:x.boolean()}),px=x.strictObject({enabled:x.boolean(),allowedOrigins:x.array(x.string())});import{z as jn}from"zod";var yc=jn.strictObject({id:jn.uuid(),name:jn.string().trim().min(1).max(80),client:ar,source:ei,event:jn.enum(["screen_enter","button_click"]),cooldownSeconds:jn.number().int().min(0).max(2592e3),behavior:jn.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 he}from"zod";var Po=ne,td=["parameters","answers","results","variables"];function Co(e){return td.some(t=>e===t||e.startsWith(t+"."))}function ko(e){let t={};for(let[r,i]of Object.entries(ir(e.declarations,e))){let a=r.split(".");if(a.some(d=>["__proto__","constructor","prototype"].includes(d)))throw new Error("Reserved result path");let m=t;for(let d of a.slice(0,-1)){Object.hasOwn(m,d)||(m[d]={});let I=m[d];if(!I||typeof I!="object"||Array.isArray(I))throw new Error("Ambiguous result path");m=I}let c=a.at(-1);if(c===void 0)throw new Error("Empty result path");m[c]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!Co(r))),variables:t}}import{z as nd}from"zod";var ti=nd.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var Ro=he.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),xc=he.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),Sc=gt.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Eo=he.record(Ro,he.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),rd=yt,Ic=he.strictObject({type:he.literal("external_task"),endpointId:he.uuid(),taskKey:Ro,inputs:he.record(Ro,rd).refine(e=>Object.keys(e).length<=20),outputs:Eo}),vc=he.strictObject({maxAttempts:he.number().int().min(1).max(5),retryDelaySeconds:he.number().int().min(1).max(30),backoff:he.enum(["fixed","exponential"]),requestTimeoutSeconds:he.number().int().min(1).max(10),timeoutSeconds:he.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var wx=he.strictObject({outcome:he.enum(["success","failure"]),data:Sc});var Px=he.discriminatedUnion("operation",[he.strictObject({operation:he.literal("signal"),runId:he.uuid(),nodeId:xc,eventName:ti,eventId:he.uuid(),data:Sc}),he.strictObject({operation:he.literal("read_results"),runId:he.uuid()})]),Cx=he.strictObject({scope:me,runId:he.uuid(),eventId:he.uuid(),accepted:he.boolean()}),id=he.record(xc,Po),kx=he.strictObject({scope:me,runId:he.uuid(),results:id});var dt={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},Oc="00000000-0000-0000-0000-000000000000";import{z as k}from"zod";import{z as ye}from"zod";var qx=ye.enum(["local","remote"]),Mo=ye.strictObject({port:ye.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ne.optional(),sticky:ye.array(ye.strictObject({expected:qr.nullable(),next:qr})).max(100),exposures:ye.array(ne).max(100),features:ye.array(ne).max(100)}),jc=ye.strictObject({type:ye.literal("evaluate"),receiptId:ye.uuid(),environmentId:ye.uuid(),policyRevision:ye.number().int().nonnegative(),attributes:Ye,sticky:ye.record(ye.string(),qr)}),Ac=jc.extend({runId:ye.uuid(),versionId:ye.uuid(),nodeId:ye.string().min(1).max(64),visit:ye.number().int().nonnegative(),revision:ye.number().int().nonnegative()}),To=jc.omit({type:!0,receiptId:!0}).extend({type:ye.literal("evaluate_segment")}),_c=ye.strictObject({nodeId:ye.string().min(1).max(64),result:Mo}),wc=To.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:gt,answers:Gt,variables:ye.record(ye.string(),ne)});import{z as F}from"zod";var od=["id","externalUserId","createdAt","ageDays","subscription"],Do=F.array(F.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"),ni=F.intersection(Ye,F.looseObject({tags:Do.optional()})).refine(e=>![...od,"parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),ri=F.string().trim().max(80),ii=F.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),oi=F.union([F.email().max(254),F.literal("")]),ai=F.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Pc=F.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Cc=F.object({externalUserId:Pc.optional(),name:ri.default(""),email:oi.default(""),phone:ii.optional(),attributes:ni.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Pt=F.discriminatedUnion("type",[F.strictObject({type:F.literal("id"),value:F.uuid()}),F.strictObject({type:F.literal("externalUserId"),value:Pc})]),qt=F.strictObject({name:ri.optional(),email:oi.optional(),phone:ii.optional(),attributes:ni.optional(),fingerprint:ai.optional()}),Xt=e=>!e.customerData||e.customer?.type==="externalUserId",Yt="customerData requires an externalUserId customer",An=F.object({id:F.uuid(),externalUserId:F.string().min(1).max(255).nullable(),name:ri,email:oi,phone:ii.optional(),attributes:ni,createdAt:F.iso.datetime()}).strict(),kc=F.object({customer:An,changed:F.boolean(),replayed:F.boolean()}).strict(),ad=F.discriminatedUnion("type",[F.object({type:F.literal("id"),value:F.uuid()}).strict(),F.object({type:F.literal("externalUserId"),value:F.string().trim().min(1).max(255)}).strict()]),sd=F.object({name:ri.optional(),email:oi.optional(),phone:ii.optional(),attributes:ni.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:F.array(F.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:F.strictObject({add:Do,remove:Do}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),qo=F.object({lookup:ad}).strict(),Rc=qo.extend({requestId:F.uuid(),patch:sd}).strict(),Ec=F.object({search:F.string().trim().max(200).default(""),tag:F.string().trim().max(40).default(""),planId:F.string().max(200).default(""),versionId:F.string().max(200).default(""),holdingStatus:F.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:F.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:F.union([F.iso.datetime(),F.literal("")]).default(""),createdUntil:F.union([F.iso.datetime(),F.literal("")]).default(""),offset:F.coerce.number().int().min(0).max(1e5).default(0),limit:F.coerce.number().int().min(1).max(100).default(50)}).strict(),Mc=F.object({customers:An.array(),hasMore:F.boolean(),total:F.number().int().nonnegative().nullable(),evaluatedAt:F.iso.datetime()}).strict();var sr=k.discriminatedUnion("type",[k.strictObject({type:k.literal("literal"),value:ne}),k.strictObject({type:k.literal("variable"),key:Re,path:mt.optional()}),k.strictObject({type:k.literal("feature"),featureKey:k.string().min(1).max(128)})]),cd=k.strictObject({requestId:k.uuid(),decisionId:k.uuid(),customerId:k.uuid(),externalUserId:k.string().min(1).max(255).nullable(),versionId:k.uuid(),receiptId:k.uuid(),value:ne}),Bo={funnelId:k.uuid(),requestId:k.uuid(),customer:Pt,customerData:qt.optional(),attributes:Ye.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},Hx=k.discriminatedUnion("operation",[k.strictObject({operation:k.literal("decide"),...Bo}).refine(Xt,Yt),k.strictObject({operation:k.literal("read_decision"),decisionId:k.uuid()}),k.strictObject({operation:k.literal("evaluate_decision"),decisionId:k.uuid(),requestId:k.uuid(),nodeId:k.string().min(1).max(64),visit:k.number().int().nonnegative(),revision:k.number().int().nonnegative(),receiptId:k.uuid(),policyRevision:k.number().int().nonnegative(),generation:k.string().min(1).max(256),result:Mo}),k.strictObject({operation:k.literal("feature_config"),funnelId:k.uuid()}),k.strictObject({operation:k.literal("commit_decision_segment"),decisionId:k.uuid(),requestId:k.uuid(),nodeId:k.string().min(1).max(64),visit:k.number().int().nonnegative(),revision:k.number().int().nonnegative(),policyRevision:k.number().int().nonnegative(),generation:k.string().min(1).max(256),steps:k.array(_c).max(32),boundary:k.strictObject({nodeId:k.string().min(1).max(64),visit:k.number().int().nonnegative()}).optional()}),k.strictObject({operation:k.literal("segment_configuration"),funnelId:k.uuid(),versionId:k.uuid()}),k.strictObject({operation:k.literal("configuration"),funnelId:k.uuid(),versionId:k.uuid().optional()}),k.strictObject({operation:k.literal("local_configuration"),funnelId:k.uuid()}),k.strictObject({operation:k.literal("report_used"),decisionId:k.uuid(),eventId:k.uuid(),occurredAt:k.iso.datetime({offset:!0}),reference:k.string().min(1).max(128).optional()})]),Qx=k.strictObject({scope:me,decisionId:k.uuid(),requestId:k.uuid(),status:k.enum(["pending","completed","failed"]),decision:cd.nullable(),evaluation:k.discriminatedUnion("type",[Ac,wc]).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"),Jx=k.strictObject({scope:me,decisionId:k.uuid(),eventId:k.uuid(),source:k.literal("caller_reported")});import{z as Fe}from"zod";import{z as M}from"zod";var rS=M.enum(["draft","active","paused","archived"]),Bt=M.discriminatedUnion("type",[M.object({type:M.literal("percent"),percentOff:M.number().min(1).max(100).multipleOf(.01)}).strict(),M.object({type:M.literal("amount"),amountOffCents:M.number().int().min(1).max(1e8),currency:ce}).strict()]),rt=M.discriminatedUnion("type",[M.object({type:M.literal("once")}).strict(),M.object({type:M.literal("repeating"),months:M.number().int().min(1).max(36)}).strict(),M.object({type:M.literal("forever")}).strict()]),Tc=[M.object({type:M.literal("all")}).strict(),M.object({type:M.literal("plans"),planIds:M.array(M.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],ud=M.discriminatedUnion("type",[...Tc,M.strictObject({type:M.literal("merchandise"),scope:M.discriminatedUnion("type",[M.strictObject({type:M.literal("all")}),M.strictObject({type:M.literal("selected"),merchandiseIds:M.array(M.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),M.strictObject({type:M.literal("condition"),condition:lt})])})]),zo=M.discriminatedUnion("type",[...Tc,M.strictObject({type:M.literal("merchandise"),scope:M.strictObject({type:M.enum(["all","selected","condition"])})})]),pd=M.strictObject({firstPurchaseOnly:M.boolean(),condition:lt}),iS=M.object({name:M.string().trim().min(1).max(80),description:M.string().max(500),discount:Bt,duration:rt,nativeDiscountPolicy:Qn.optional(),appliesTo:ud,eligibility:pd,selfClaimEnabled:M.boolean().default(!1),startsAt:M.iso.datetime().nullable(),endsAt:M.iso.datetime().nullable(),totalLimit:M.number().int().min(1).max(1e6).nullable(),perCustomerLimit:M.number().int().min(1).max(10),grantWindowHours:M.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=>!xo(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"]}),oS=M.object({code:M.string().trim().transform(e=>e.toUpperCase()).pipe(M.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:M.number().int().min(1).max(1e6).nullable(),expiresAt:M.iso.datetime().nullable(),firstPurchaseOnly:M.boolean(),minimumAmountCents:M.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:ce.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var cr=M.object({id:M.uuid(),couponId:M.uuid(),status:M.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:M.iso.datetime(),expiresAt:M.iso.datetime(),coupon:M.object({name:M.string(),discount:Bt,duration:rt,nativeDiscountPolicy:Qn.optional(),appliesTo:zo}).strict()}).strict(),Dc=M.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var qc=Fe.strictObject({type:Fe.literal("bundle"),paywall:yt.optional(),offering:yt.optional(),coupons:yt,data:yt}),ld=e=>Fe.strictObject({type:Fe.literal(e),id:Fe.uuid()}),lS=Fe.strictObject({type:Fe.literal("bundle"),paywallVersionId:Fe.uuid().optional(),offeringVersionId:Fe.uuid().optional(),couponIds:Fe.array(Fe.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ne});var mS=Fe.strictObject({type:Fe.literal("bundle"),offering:ld("offering_version").nullable(),paywall:Fe.strictObject({versionId:Fe.uuid(),paywallId:Fe.uuid(),offeringVersionId:Fe.uuid()}).nullable(),coupons:Fe.array(cr).max(20),data:ne});import{z as ft}from"zod";import{z as st}from"zod";var Bc=st.union([st.string(),st.number().finite(),st.boolean(),st.null()]),md=st.union([Bc,st.array(Bc).min(1).max(20)]),dd=st.record(mt,md).refine(e=>Object.keys(e).length<=10),zc=st.strictObject({path:mt,type:st.enum(["string","number","boolean","strings"]),nullable:st.boolean().optional(),aggregation:st.enum(["count","exists"]).optional(),where:dd.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 fd=["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"],Fc=ft.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),hd=yt,Nc=ft.discriminatedUnion("type",[Ic,ft.strictObject({type:ft.literal("claim_offer"),coupon:yt}),ft.strictObject({type:ft.literal("event"),event:Fc}),ft.strictObject({type:ft.literal("api"),operation:ft.enum(fd),inputs:ft.record(mt,hd).refine(e=>Object.keys(e).length<=40),outputs:ft.record(Fc,zc).refine(e=>Object.keys(e).length<=20)})]);var je=ti,gd=P.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),it={id:je,name:P.string().trim().min(1).max(80),position:P.strictObject({x:P.number().finite(),y:P.number().finite()}).optional()},bd={success:je,cancel:je,unavailable:je,failure:je},Fo=P.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),No=P.enum(["same_window","new_window"]),yd=P.discriminatedUnion("type",[P.strictObject({...it,type:P.literal("entry"),next:je,triggers:P.array(yc).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),P.strictObject({...it,type:P.literal("screen"),screenId:je,presentation:vt,outputs:P.record(je,je),offering:P.discriminatedUnion("source",[P.strictObject({source:P.literal("variable"),key:Re}),P.strictObject({source:P.literal("fixed"),versionId:P.uuid()})]).optional()}),P.strictObject({...it,type:P.literal("offering"),configuration:P.discriminatedUnion("source",[P.strictObject({source:P.literal("fixed"),versionId:P.uuid()}),P.strictObject({source:P.literal("feature"),featureKey:P.string().min(1).max(128)})]),writes:P.strictObject({value:Re}),next:je}),P.strictObject({...it,type:P.literal("coupon"),couponId:P.uuid(),writes:P.strictObject({value:Re}),next:je}),P.strictObject({...it,type:P.literal("coupons"),couponIds:P.array(P.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:P.strictObject({value:Re}),next:je}),P.strictObject({...it,type:P.literal("output"),value:P.discriminatedUnion("type",[...sr.options,qc,P.strictObject({type:P.literal("selection"),screenId:je,offeringKey:Re})])}),P.strictObject({...it,type:P.literal("condition"),cases:P.array(P.strictObject({condition:lt,target:je})).min(1).max(50),default:je}),P.strictObject({...it,type:P.literal("feature"),featureKey:P.string().min(1).max(128),writes:P.strictObject({value:Re}),next:je}),P.strictObject({...it,type:P.literal("split"),experimentId:P.uuid(),applyPageExperiment:P.literal(!0).optional(),routes:P.record(gd,je).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:je}),P.strictObject({...it,type:P.literal("action"),...bd,execution:vc,action:Nc,writes:Hr.optional()}),P.strictObject({...it,type:P.literal("external_page"),appManifest:ei.optional(),url:Fo,openIn:No,opened:je,failed:je}),P.strictObject({...it,type:P.literal("end"),outcome:P.enum(["completed","closed","ineligible","failed"]),output:sr.optional()}),P.strictObject({...it,type:P.literal("wait"),writes:Hr.optional(),wait:P.discriminatedUnion("type",[P.strictObject({type:P.literal("duration"),delaySeconds:P.number().int().min(1).max(2592e3),elapsed:je}),P.strictObject({type:P.literal("event"),eventName:je,outputs:Eo,timeoutSeconds:P.number().int().min(1).max(2592e3),received:je,timeout:je})])})]),Vo=P.strictObject({version:P.literal(5),entry:je,nodes:P.array(yd).min(1).max(dt.flowNodes)}),Uo=Vo.superRefine((e,t)=>{xd(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function si(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 xd(e,t){let n=[],r=new Map(e.nodes.map(g=>[g.id,g])),i=(g,T,$)=>{n.push(g),t?.({message:g,reason:T,path:$?["nodes",e.nodes.indexOf($)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(g=>g.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(g=>g.type==="screen").length>dt.pages||e.nodes.filter(g=>!["screen","entry","end","output"].includes(g.type)).length>dt.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let g of e.nodes){for(let T of si(g))T===e.entry&&i("An entry cannot be a transition target","entryTarget",g),r.has(T)||i(`Missing target ${T}`,"missingTarget",g);g.type==="screen"&&(a.has(g.screenId)&&i("Every screen has exactly one node owner","screenOwner",g),a.add(g.screenId))}let m=new Set,c=new Set,d=new Set;function I(g){if(m.has(g)){i("Flow edges must not form a cycle","cycle",r.get(g));return}if(!(c.has(g)||!r.has(g))){m.add(g),d.add(g);for(let T of si(r.get(g)))I(T);m.delete(g),c.add(g)}}I(e.entry);for(let g of e.nodes)d.has(g.id)||i("Every node must be reachable from Entry","unreachable",g);return[...new Set(n)]}var Go={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Vc(e,t,n){let r=[...t].sort((c,d)=>d.length-c.length),i=new Set,a=(c,d=!1)=>{let I=r.find(g=>c===g||d&&c.startsWith(g+"."));i.add(I??c)};if(e.type==="condition"){let c=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let d of e.cases.slice(0,c+1))for(let I of Dt(d.condition))I.startsWith("variables.")&&a(I.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 m=e.type==="output"?e.value:e.type==="end"?e.output:null;if(m?.type==="variable"&&a(m.key),m?.type==="bundle")for(let c of[m.paywall,m.offering,m.coupons,m.data])c?.source==="variable"&&a(c.key);return m?.type==="selection"&&a(m.offeringKey),[...i]}import{z as S}from"zod";var _n=S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ci=e=>S.record(S.string(),ne).refine(t=>tt(t)<=e,"Funnel evidence exceeds its byte budget"),GS=S.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Ko=S.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Lo=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()})]),ur=S.strictObject({schemaVersion:S.literal(1),kind:Ko,selector:Lo.nullable(),context:ci(131072),contract:S.strictObject({version:S.number().int().positive(),evaluator:S.string().min(1).max(128),policyRevision:S.number().int().nonnegative()})}).refine(e=>tt(e)<=131072,"Node input exceeds its byte budget"),Uc=S.strictObject({schemaVersion:S.literal(1),kind:Ko,outcome:S.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ci(131072),route:S.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ci(131072)}).refine(e=>tt(e)<=131072,"Node result exceeds its byte budget"),$S=S.strictObject({schemaVersion:S.literal(1),operations:S.record(_n,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:_n,id:S.uuid()}).nullable()}))}).refine(e=>tt(e)<=65536,"Execution state exceeds its byte budget"),en={receiptId:S.uuid()},$o=S.iso.datetime({offset:!0}),KS=S.discriminatedUnion("type",[S.strictObject({type:S.literal("node_entered"),details:S.strictObject({kind:Ko})}),S.strictObject({type:S.literal("presentation_shown"),details:S.strictObject({...en,source:S.literal("client"),occurredAt:$o.optional()})}),S.strictObject({type:S.literal("decision_accepted"),details:S.strictObject(en)}),S.strictObject({type:S.literal("signal_received"),details:S.strictObject({signalId:S.uuid(),nodeId:_n,eventName:_n,data:ci(8192),source:S.literal("server"),occurredAt:$o})}),S.strictObject({type:S.literal("signal_consumed"),details:S.strictObject({...en,signalId:S.uuid()})}),S.strictObject({type:S.literal("wait_elapsed"),details:S.strictObject(en)}),S.strictObject({type:S.literal("wait_timeout"),details:S.strictObject(en)}),S.strictObject({type:S.literal("operation_completed"),details:S.strictObject({...en,operation:_n,reference:S.strictObject({type:_n,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({...en,source:S.enum(["client","server"]),occurredAt:$o,reference:S.string().min(1).max(128).optional()})})]);var ct=j.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Sd=j.discriminatedUnion("type",[j.strictObject({id:ct,type:j.literal("owned"),publicData:tc.optional(),document:et.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")}),j.strictObject({id:ct,type:j.literal("paywall"),paywallVersionId:j.uuid()})]),Zo={executionContract:Io.optional(),kind:j.literal("funnel"),schemaVersion:j.literal(4),screens:j.array(Sd).max(dt.pages),references:j.record(ct,Lo).refine(e=>Object.keys(e).length<=500),inputs:j.array(j.strictObject({variable:ct,screenId:ct,componentId:ct,required:j.boolean()})).max(dt.questions),variables:j.record(Re,xn).refine(e=>Object.keys(e).length<=dt.logicNodes),outputSchema:yn,execution:j.strictObject({runTimeoutSeconds:j.number().int().min(1).max(Go.runTimeoutSeconds),maxTransitions:j.number().int().min(1).max(Go.maxTransitions)})},lI=j.strictObject({...Zo,graph:Vo});function Id(e,t){let n=!1,r=(i,a)=>{let m=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."))&&!(m&&t(m))&&(n=!0),i.type==="stack"&&i.children.forEach(c=>r(c,m))};for(let i of e.pages)r(i.root);return n}function pi(e){return Array.isArray(e)?e.some(pi):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===Oc:pi(n))}function vd(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=dc(i.document)}catch(m){t.push({message:m instanceof Error?m.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[m,c]of e.inputs.entries())c.screenId===i.id&&!Qi(a,c.componentId)&&t.push({message:`Local Funnel input ${c.variable} targets hidden component ${c.componentId} on screen ${c.screenId}`,reason:"inputBinding",path:["inputs",m]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],m=i.type==="screen"?e.screens.find(c=>c.id===i.screenId):void 0;m?.type==="owned"&&(m.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}),Id(m.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"&&pi(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&pi(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Gc(e,t){for(let{message:n,reason:r,path:i}of vd(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function $c(e,t){let n=(C,l,b=[])=>t.addIssue({code:"custom",message:C,path:b,params:{reason:l}}),r=Object.values(e.references),i=new Map(e.screens.map(C=>[C.id,C])),a=(C,l)=>r.some(b=>b.type===C&&("id"in b?b.id:b.key)===l);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let m=e.graph.nodes.filter(C=>C.type==="screen");(m.length!==i.size||m.some(C=>!i.has(C.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let c=new Map,d=Object.keys(e.variables);d.some(C=>d.some(l=>C!==l&&l.startsWith(C+".")))&&n("Variable paths must not overlap","variable");function I(C,l){Object.hasOwn(e.variables,C)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(l)]);let b=c.get(C)??new Set;b.add(l.id),c.set(C,b)}for(let[C,l]of e.graph.nodes.entries()){let b=["graph","nodes",C],Q=l.type==="feature"?l.featureKey:l.type==="offering"&&l.configuration.source==="feature"?l.configuration.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:null;Q&&!a("flag",Q)&&n("Flag selectors require an explicit GB resource reference","feature",b);let E=l.type==="feature"||l.type==="offering"||l.type==="coupon"||l.type==="coupons"||l.type==="action"&&l.action.type==="api"?["value"]:l.type==="action"&&l.action.type==="external_task"?Object.keys(l.action.outputs):l.type==="wait"&&l.wait.type==="event"?Object.keys(l.wait.outputs):[],pe="writes"in l?l.writes??{}:{};(E.length!==Object.keys(pe).length||E.some(Z=>!Object.hasOwn(pe,Z))||new Set(Object.values(pe)).size!==Object.values(pe).length)&&n("Node writes must map every named output exactly once","variable",b);for(let[Z,ie]of Object.entries(pe)){I(ie,l);let be=e.variables[ie],J=l.type==="offering"?"offering_version":l.type==="coupon"?"reward":l.type==="action"&&l.action.type==="api"?"json":l.type==="action"&&l.action.type==="external_task"?l.action.outputs[Z]:l.type==="wait"&&l.wait.type==="event"?l.wait.outputs[Z]:void 0;(be?.source.type!=="node"||J&&be.type!==J)&&n("Node writer source or output type does not match declaration","variable",b)}if(l.type==="coupons"){let Z=e.variables[l.writes.value];(Z?.type!=="array"||Z.items?.type!=="reward"||Z.items.nullable||Z.nullable)&&n("Coupons output requires a non-null Reward array","variable",b);for(let ie of l.couponIds)a("reward",ie)||n("Coupons require Reward references","coupon",b)}if(l.type==="split"&&!a("experiment",l.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",b),l.type==="coupon"&&!a("reward",l.couponId)&&n("Coupon selectors require a Reward reference","coupon",b),l.type==="action"&&l.action.type==="claim_offer"&&l.action.coupon.source==="literal"){let Z=l.action.coupon.value;(!Z||typeof Z!="object"||Array.isArray(Z)||Z.type!=="reward"||typeof Z.id!="string"||Object.keys(Z).length!==2||!a("reward",Z.id))&&n("Coupon claims require a Reward reference","coupon",b)}if(l.type==="offering"&&l.configuration.source==="fixed"&&!a("offering_version",l.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",b),l.type==="screen"&&l.offering?.source==="variable"&&e.variables[l.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",b),l.type==="action"&&l.action.type==="claim_offer"&&l.action.coupon.source==="variable"&&(e.variables[l.action.coupon.key]?.type!=="reward"||l.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",b),l.type==="screen"){let Z=i.get(l.screenId);if(l.offering?.source==="fixed"&&!a("offering_version",l.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",b),Z?.type==="paywall"&&l.offering&&n("Paywall owns its fixed Offering Version","offering",b),Z?.type==="paywall"&&!a("paywall_version",Z.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",b),Z?.type==="owned"){let ie=Z.document.pages[0];if(!ie){n("Owned screen requires a page","screen",b);continue}Et(Z.document).some(J=>!J.complete)&&n("Owned screens require complete local content","translations",b);let be=new Set(Z.document.actions.map(J=>J.id));(be.size!==Object.keys(l.outputs).length||Object.keys(l.outputs).some(J=>!be.has(J)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",b),fn(ie.root,J=>{!l.offering&&(J.type==="plan_picker"||(J.type==="stack"||J.type==="button")&&J.bind?.plan||J.type==="customer_data"&&["customer_plans","credit_packs"].includes(J.data.source))&&n("Product presentation requires an Offering Version","offering",b),J.type==="customer_data"&&Object.values(J.data.outputs??{}).some(kt=>kt!==void 0&&!be.has(kt))&&n("Customer components require declared screen outcomes","componentOutput",b)})}}l.type==="end"&&["completed","ineligible"].includes(l.outcome)&&!l.output&&n("Completed and ineligible ends require a declared output","output",b),l.type==="end"&&l.output?.type==="literal"&&!at(e.outputSchema,l.output.value)&&n("Terminal output does not match outputSchema","output",b),l.type==="output"&&l.value.type==="literal"&&!at(e.outputSchema,l.value.value)&&n("Terminal output does not match outputSchema","output",b);let De=l.type==="output"?l.value:l.type==="end"?l.output:void 0;if(De?.type==="variable"&&!De.path){let Z=e.variables[De.key];Z&&!uo(Z,e.outputSchema)&&n("Variable output does not match outputSchema","output",b)}if(l.type==="screen"){let Z=i.get(l.screenId);if(Z?.type==="owned")for(let ie of fo(Z.document))(/^(input|params)\./.test(ie)||ie.startsWith("variables.")&&!mo(ie.slice(10),d))&&n("Screen values must reference registered variables","variable",b)}if(l.type==="condition")for(let Z of l.cases){for(let ie of Rt(Z.condition))a("saved_group",ie)||n("Conditions require explicit Saved Group references","savedGroup",b);for(let ie of Dt(Z.condition))ie.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",b)}if(l.type==="output"&&l.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",b);for(let[Z,ie]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let be=l.value[Z];if(be)if(be.source==="literal"){let J=Z==="coupons"?be.value:[be.value];(!Array.isArray(J)||J.length>20||J.some(kt=>!at({type:ie,nullable:!1},kt)||!a(ie,kt.id))||Z==="coupons"&&new Set(J.map(kt=>kt.id)).size!==J.length)&&n("Bundle requires distinct scoped resource references",Z==="coupons"?"coupon":Z==="paywall"?"paywall":"offering",[...b,"value",Z])}else{let J=e.variables[be.key];(be.path||!J||J.nullable||(Z==="coupons"?J.type!=="array"||J.items?.type!=="reward"||J.items.nullable:J.type!==ie))&&n("Bundle binding type does not match its slot","output",b)}}}}for(let[C,l]of e.graph.nodes.entries()){let b=l.type==="screen"?i.get(l.screenId):void 0,Q=[...Vc(l,d),...b?.type==="owned"?Qr(b.document).map(E=>mo(E,d)?.key??E):[]];for(let E of new Set(Q)){let ie=function(be){if(be===l.id)return!0;if(Z.has(be))return!1;Z.add(be);let J=e.graph.nodes.find(tm=>tm.id===be);return J?(De.has(be)?J.type==="action"?[J.cancel,J.unavailable,J.failure]:J.type==="wait"&&J.wait.type==="event"?[J.wait.timeout]:[]:si(J)).some(ie):!1};var $=ie;if(!Object.hasOwn(e.variables,E)){n("Consumed variable is undeclared","variable",["graph","nodes",C]);continue}let pe=e.variables[E];if(l.type==="screen"&&pe.source.type==="input"&&e.inputs.some(be=>be.screenId===l.screenId&&be.variable===E)||pe.source.type==="parameter"||pe.source.type==="attribute")continue;let De=pe.source.type==="input"?new Set(e.inputs.filter(be=>be.variable===E&&be.required).flatMap(be=>m.filter(J=>J.screenId===be.screenId).map(J=>J.id))):c.get(E)??new Set,Z=new Set;(!De.size||ie(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",C])}}(new Set(e.inputs.map(C=>C.variable)).size!==e.inputs.length||new Set(e.inputs.map(C=>`${C.screenId}:${C.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[C,l]of e.inputs.entries()){e.variables[l.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",C]);let b=i.get(l.screenId),Q=b?.type==="owned"?Qi(b.document,l.componentId):null;if((Q?.type!=="stack"||!Q.interaction||!["input","toggle","select","multiselect","tabs"].includes(Q.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",C]),Q?.type==="stack"&&Q.interaction){let E=Q.interaction.type==="toggle"?"boolean":Q.interaction.type==="multiselect"?"strings":"string";e.variables[l.variable]?.type!==E&&n("Input variable type does not match component","inputBinding",["inputs",C]);let pe=e.variables[l.variable]?.enum;pe&&!Q.children.filter(De=>!De.hidden).every(De=>pe.includes(De.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",C])}}for(let[C,l]of Object.entries(e.variables))l.enum&&l.type!=="string"&&n("Only string variables support enum","variable",["variables",C]),l.source.type==="input"&&!e.inputs.some(b=>b.variable===C)&&n("Input variable requires a component binding","inputBinding",["variables",C]);let g=0,T=0;for(let C of e.screens)if(C.type==="owned"){for(let l of C.document.pages)fn(l.root,()=>{g++});T+=C.document.actions.length}(g>dt.components||T>dt.actions||tt(e)>dt.documentBytes)&&n("Funnel document exceeds its budget","budget")}var Od=j.strictObject({...Zo,graph:Uo}).superRefine($c),zt=j.strictObject({...Zo,graph:Uo,displayName:j.string().trim().min(1).max(80)}).superRefine($c),mI=zt.superRefine(Gc),dI=Od.superRefine(Gc),ui=j.string().regex(bt),pr={requestId:j.uuid(),nodeId:ct,visit:j.number().int().nonnegative(),revision:j.number().int().nonnegative(),customerToken:ui.optional()},jd=j.discriminatedUnion("type",[j.strictObject({type:j.literal("screen"),output:ct,answers:Gt,selection:j.record(ct,j.union([j.string().max(200),j.boolean(),j.number().int().min(0).max(1e4)])).optional()}),j.strictObject({type:j.literal("paywall_quote"),featureQuantities:j.record(j.uuid(),j.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:ct,productVersionId:j.uuid(),offerId:j.uuid().optional(),nativeOffer:On.optional(),predecessor:j.strictObject({operationId:j.uuid().nullable(),generation:j.number().int().positive()}).optional()}),j.strictObject({type:j.literal("paywall_confirm"),operationId:j.uuid()}),j.strictObject({type:j.literal("paywall_cancel"),operationId:j.uuid()}),j.strictObject({type:j.literal("client_action"),receiptId:j.uuid(),outcome:j.enum(["success","cancel","failure","opened","failed"])})]),Ad=j.object({nodeId:ct,visit:j.number().int().nonnegative(),revision:j.number().int().nonnegative(),components:j.record(ct,j.object({resourceKey:j.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:j.number().int().min(1).max(1e5),after:zr.nullable(),filter:j.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),We=j.discriminatedUnion("operation",[j.strictObject({operation:j.literal("start"),funnelId:j.uuid(),requestId:j.uuid(),customer:Pt.optional(),customerData:qt.optional(),locale:j.string().min(1).max(35),parameters:gt}).refine(Xt,Yt),j.strictObject({operation:j.literal("get"),settlementRequestId:j.uuid().optional(),data:Ad.optional(),purchase:j.strictObject({receiptId:j.uuid(),operationId:j.uuid()}).optional(),customerToken:ui.optional()}),j.strictObject({operation:j.literal("resume"),requestId:j.uuid(),customerToken:ui.optional()}),j.strictObject({operation:j.literal("submit"),...pr,input:jd}),j.strictObject({operation:j.literal("back"),...pr}),j.strictObject({operation:j.literal("shown"),...pr}),j.strictObject({operation:j.literal("close"),...pr}),j.strictObject({operation:j.literal("commit_segment"),...pr,policyRevision:j.number().int().nonnegative(),generation:j.string().min(1).max(256)}),j.strictObject({operation:j.literal("review"),receiptId:j.uuid().optional(),customerToken:ui.optional()})]);function li(e,t){let n=new Set,r=new Set,i=new Set,a=[],m=new Map,c=new Map,d=new Map;function I(l){for(let b of Rt(l))g(b)}function g(l){if(i.has(l)||!Object.hasOwn(t.savedGroups,l))return;let b=t.savedGroups[l];b&&(i.add(l),d.set(l,b),a.push(()=>{!Array.isArray(b)&&b.type==="condition"&&I(b.condition)}))}function T(l){for(let b of["hashAttribute","fallbackAttribute"])if(l[b]!==void 0&&Co(l[b]))throw new Error(`Funnel GB ${b} uses a reserved flow namespace`);I(l.condition);for(let b of l.parentConditions??[])$(b.id),I(b.condition)}function $(l,b=!1){let Q=Object.hasOwn(t.features,l)?t.features[l]:void 0;if(!Q){if(b)throw new Error("Required GB Feature is unavailable");return}n.has(l)||(n.add(l),m.set(l,Q),a.push(()=>{for(let E of Q.rules??[]){T(E);for(let pe of E.tracks??[])T(pe.experiment)}}))}function C(l){let b=Object.hasOwn(t.experiments,l)?t.experiments[l]:void 0;if(!b)throw new Error("Required GB Experiment is unavailable");r.has(l)||(r.add(l),c.set(l,b),a.push(()=>T(b)))}for(let l of e.graph.nodes){l.type==="feature"&&$(l.featureKey,!0),l.type==="split"&&C(l.experimentId),l.type==="condition"&&l.cases.forEach(Q=>I(Q.condition)),l.type==="offering"&&l.configuration.source==="feature"&&$(l.configuration.featureKey,!0);let b=l.type==="output"?l.value:l.type==="end"?l.output:null;b?.type==="feature"&&$(b.featureKey,!0)}for(let l of a)l();return{...t,features:Object.fromEntries(m),experiments:Object.fromEntries(c),savedGroups:Object.fromEntries(d)}}import{z as B}from"zod";import{z as lr}from"zod";var Kc=lr.object({defaultLocale:ln,locales:lr.record(ln,lr.object({name:lr.string().max(80),description:lr.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"})});import{z as G}from"zod";var Ho=G.discriminatedUnion("type",[G.strictObject({type:G.literal("event"),event:G.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),G.strictObject({type:G.literal("open_url"),url:G.url().refine(e=>new URL(e).protocol==="https:")})]),_d=et,wd=G.discriminatedUnion("type",[G.object({type:G.literal("checkout"),product:Br}).strict(),G.object({type:G.literal("close")}).strict(),G.object({type:G.literal("action"),action:Ho}).strict()]),wn=G.object({schemaVersion:G.literal(3),kind:G.literal("paywall"),name:G.string().trim().min(1).max(80),presentation:vt,requirement:pn.optional(),products:Wr,offeringVersionId:G.uuid().nullable(),offeringId:G.uuid(),screen:_d,buttons:G.record(G.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),wd)}).strict(),kI=wn.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 Cd(e))t.addIssue({code:"custom",message:r});for(let r of Pd(e))t.addIssue({code:"custom",message:r});Et(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 Pd(e){let t=e.products.items.map(a=>a.productVersionId),n=Is(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&&(!Os(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(m=>m.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let m=a.product;if(m.type==="fixed")r.add(m.productVersionId);else{m.allowedProductVersionIds.forEach(I=>r.add(I));let c=!1,d=n[m.pickerId];d&&(c=!0,(m.allowedProductVersionIds.some(I=>!d.ids.includes(I))||d.ids.some(I=>!m.allowedProductVersionIds.includes(I)))&&i.push("picker")),Ot(e.screen,I=>{if(I.id!==m.pickerId||I.type!=="plan_picker")return;c=!0,(JSON.stringify(I.planIds)!==JSON.stringify(t)||JSON.stringify(m.allowedProductVersionIds)!==JSON.stringify(t)||I.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let g=I.grouping?{tiers:I.grouping.tiers,assignments:I.grouping.assignments}:void 0;JSON.stringify(g)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),c||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Ot(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(m=>!t.includes(m)))&&i.push("binding")}),[...new Set(i)]}function Cd(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let c of e.screen.pages)r.set(c.id,[]),fn(c.root,d=>{let I=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(I){let g=e.screen.actions.find($=>$.id===I);g?.type==="navigate"&&r.get(c.id).push(g.pageId);let T=e.buttons[I];c.id!==n.id&&T&&T.type!=="close"&&t.push(`purchaseScreen:${d.id}`)}c.id!==n.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&t.push(`packageScreen:${d.id}`)});let i=new Set;function a(c){if(!i.has(c)){i.add(c);for(let d of r.get(c)??[])a(d)}}let m=e.screen.initialPageId??e.screen.pages[0]?.id;m?a(m):t.push("initialPage");for(let c of e.screen.pages)i.has(c.id)||t.push(`unreachableScreen:${c.id}`);return[...new Set(t)]}var Lc=G.object({id:G.uuid(),projectId:G.uuid(),environmentId:G.uuid(),revision:G.number().int().nonnegative(),state:G.enum(["active","archived"]),publishedVersionId:G.uuid().nullable(),updatedAt:G.iso.datetime({offset:!0}),draft:wn}).strict(),RI=G.object({rows:G.array(Lc).max(200),nextCursor:G.uuid().nullable()}).strict(),EI=Lc.omit({draft:!0}).extend({name:G.string(),productCount:G.number().int().nonnegative()}).strict(),MI=G.discriminatedUnion("action",[G.object({action:G.literal("save"),id:G.uuid().nullable(),revision:G.number().int().nonnegative(),document:wn}).strict(),G.object({action:G.enum(["publish","archive"]),id:G.uuid(),revision:G.number().int().nonnegative()}).strict()]),TI=G.object({paywalls:G.array(G.object({id:G.uuid(),paywallId:G.uuid(),version:G.number().int().positive(),name:G.string().min(1).max(80),presentation:vt,buttons:wn.shape.buttons}).strict()).max(500),limited:G.boolean()}).strict();var kd=["customer_data","coupon_code"],Zc=B.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Rd=B.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),mi=(e,t)=>new Set(e.map(t)).size===e.length,Ed=B.strictObject({currency:ce,amountMinor:B.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Md=B.strictObject({featureId:B.uuid(),name:B.string().trim().min(1).max(120),allowance:B.string().max(40).nullable(),access:B.boolean()}),Td=B.strictObject({stripe:B.strictObject({prices:B.array(Ed).min(1).max(50)}).optional(),apple:B.strictObject({productIds:B.array(Zc).min(1).max(10)}).optional(),google:B.strictObject({products:B.array(B.strictObject({productId:Zc,basePlanId:Rd.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!mi(e.stripe.prices,n=>n.currency)||e.apple&&!mi(e.apple.productIds,n=>n)||e.google&&!mi(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),Dd=B.strictObject({name:B.string().trim().min(1).max(80),interval:B.enum(["free","week","month","year","one_time"]),intervalCount:B.number().int().min(1).max(100),trial:B.strictObject({days:B.number().int().min(1).max(730),cardRequired:B.boolean()}).nullable(),benefits:B.array(Md).max(50).refine(e=>mi(e,t=>t.featureId),"Duplicate benefit"),channels:Td,prepaid:B.array(ys).max(100).optional()}),qd=B.strictObject({digest:In,content:B.strictObject({discount:Bt,duration:rt,appliesTo:zo,displayCopy:Kc.nullable(),firstPurchaseOnly:B.boolean(),qualificationRequired:B.boolean(),startsAt:B.iso.datetime().nullable(),endsAt:B.iso.datetime().nullable(),grantWindowHours:B.number().int().positive(),perCustomerLimit:B.number().int().positive()})}),Bd=B.discriminatedUnion("type",[B.strictObject({type:B.literal("checkout"),product:Br}),B.strictObject({type:B.literal("close")}),B.strictObject({type:B.literal("action"),action:Ho})]),Hc=B.strictObject({kind:B.literal("paywall"),formatVersion:B.literal(1),name:B.string().trim().min(1).max(80),offeringVersionId:B.uuid(),presentation:vt,screen:et,products:Wr,catalog:B.record(B.uuid(),Dd),buttons:B.record(Hn,Bd),coupons:B.record(B.uuid(),qd)}).superRefine((e,t)=>{let n=b=>t.addIssue({code:"custom",message:b}),{screen:r}=e;As(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Oo(r,kd).forEach(n),Et(r).some(b=>!b.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,m=new Set;Ot(r,b=>{let Q="bind"in b?b.bind:void 0;Q?.promotionCode&&n("Promotion codes must not be published"),Q?.plan&&i.add(Q.plan),Q?.coupon&&a.add(Q.coupon),b.type==="plan_picker"&&(b.planIds?.forEach(E=>i.add(E)),b.defaultPlan&&i.add(b.defaultPlan)),b.type==="text"&&b.feature&&m.add(b.feature.id)});let c=e.products.items.map(b=>b.productVersionId),d=Object.keys(e.catalog);(c.length!==d.length||c.some(b=>!Object.hasOwn(e.catalog,b)))&&n("Catalog must contain exactly the displayed Products");let I=new Set(c);e.products.defaultProductVersionId!==null&&!I.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let b of i)I.has(b)||n("Screen references a Product that is not displayed");for(let b of Object.values(e.catalog))!b.channels.stripe&&!b.channels.apple&&!b.channels.google&&n("A displayed Product needs at least one sales channel");let g=new Set(Object.values(e.catalog).flatMap(b=>b.benefits.map(Q=>Q.featureId)));for(let b of m)g.has(b)||n("Feature text must read a displayed benefit");let T=r.actions.filter(b=>b.type!=="navigate");r.actions.some(b=>b.type!=="event"&&b.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==T.length||T.some(b=>!Object.hasOwn(e.buttons,b.id)))&&n("Buttons must match the screen's actions");let C=!1;for(let b of Object.values(e.buttons)){if(b.type!=="checkout")continue;C=!0,(b.product.type==="fixed"?[b.product.productVersionId]:b.product.allowedProductVersionIds).some(E=>!I.has(E))&&n("Checkout may only sell displayed Products")}C||n("A Paywall needs a checkout button");let l=Object.keys(e.coupons);(l.length!==a.size||l.some(b=>!a.has(b)))&&n("Coupons must be exactly the bound Coupons")}),Qc=B.strictObject({state:B.enum(["published","archived"]),controlRevision:B.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:B.uuid(),versions:B.record(B.uuid(),B.strictObject({version:B.number().int().positive(),artifact:B.string().min(1),sourceDigest:B.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var zd={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Qo=te.string().regex(/^[a-f0-9]{64}$/),Jo=te.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Fd=me.extend({environmentId:te.uuid()}),Jc=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)}),Yo=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:Qo,byteLength:te.number().int().positive().max(zd.maxArtifactBytes),generation:Qo.optional()}),Nd=te.strictObject({state:te.enum(["active","paused","archived"]),controlRevision:Jo,evaluationMode:te.enum(["local","remote"]),evaluationRevision:Jo,currentVersionId:te.uuid(),versions:te.record(te.uuid(),te.strictObject({artifact:te.string(),dependencies:Jc,definitionDigest:In.optional(),couponDigests:te.record(te.uuid(),In).optional()}))}),rv=te.strictObject({kind:te.literal("sdk_configuration"),schemaVersion:te.literal(1),scope:Fd,revision:Jo,generation:Qo,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(),Yo),funnels:te.record(te.uuid(),Nd),paywalls:te.record(te.uuid(),Qc).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 Wo(e){if(Array.isArray(e))return`[${e.map(Wo).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)}:${Wo(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Vd(e){return Rr(Er(typeof e=="string"?new TextEncoder().encode(e):e))}function iv(e){return Vd(Wo(e))}var Xo=class extends Error{constructor(n,r){super(n);this.dependency=r}dependency};function ov(e,t){let n=g=>g.type==="feature"?g.featureKey:g.type==="end"&&g.output?.type==="feature"?g.output.featureKey:g.type==="output"&&g.value.type==="feature"?g.value.featureKey:void 0,r=(g,T)=>e.graph.nodes.find($=>g==="experiment"?$.type==="split"&&$.experimentId===T:g==="feature"&&n($)===T)?.name,i=(g,T,$=r(T.type,T.resource))=>new Xo(g,{...T,...$?{step:$}:{}});for(let g of Object.values(e.references)){let T=g.type==="flag"?!Object.hasOwn(t.features,g.key)||t.remoteFeatures.includes(g.key)?{type:"feature",resource:g.key}:null:g.type==="experiment"?Object.hasOwn(t.experiments,g.id)?null:{type:"experiment",resource:g.id}:g.type==="saved_group"&&!Object.hasOwn(t.savedGroups,g.id)?{type:"saved_group",resource:g.id}:null;if(T)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...T})}let a=li(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),m=new Set(t.remoteFeatures);for(let g of e.graph.nodes){let T=n(g);if(!T)continue;let $=a.features[T],C=g.type==="feature"?e.variables[g.writes.value]:e.outputSchema,l={type:"feature",resource:T};if(!$||!C)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...l},g.name);if([$.defaultValue,...($.rules??[]).flatMap(Q=>[...Object.hasOwn(Q,"force")?[Q.force]:[],...Q.variations??[],...(Q.tracks??[]).flatMap(E=>E.experiment.variations)])].some(Q=>Q===void 0||!at(C,Q)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...l},g.name)}let c=new Set,d=(g,T)=>{for(let $ of Rt(g)){if(c.has($))continue;let C=t.savedGroups[$];if(!C)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:$},T);c.add($),!Array.isArray(C)&&C.type==="condition"&&d(C.condition,T)}},I=(g,T)=>{if(m.has(g)||!t.features[g])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:g},T)};for(let g of e.graph.nodes)if(g.type==="condition")for(let T of g.cases)d(T.condition,g.name);for(let[g,T]of Object.entries(a.features)){let $=r("feature",g);for(let C of T.rules??[]){d(C.condition,$);for(let l of[...C.parentConditions??[],...(C.tracks??[]).flatMap(b=>b.experiment.parentConditions??[])])I(l.id,$),d(l.condition,$);for(let l of C.tracks??[])d(l.experiment.condition,$)}}for(let[g,T]of Object.entries(a.experiments)){let $=r("experiment",g);d(T.condition,$);for(let C of T.parentConditions??[])I(C.id,$),d(C.condition,$)}for(let g of e.graph.nodes)if(g.type==="split"){let T=a.experiments[g.experimentId],$={type:"experiment",resource:g.experimentId};if(!T)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...$},g.name);for(let C of T.variations)if(typeof C!="string"||!Object.hasOwn(g.routes,C))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...$},g.name)}return Jc.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([g,T])=>[g,T.variations.map(String)])),savedGroups:[...c].sort()})}function av(e){return zt.parse(e)}import{z as ge}from"zod";var mr=ge.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Wc=ge.enum(["unknown","denied","provisional","granted"]),Xc=ge.enum(["ios","android"]),di=ge.strictObject({installationId:ge.uuid(),publicKey:ge.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:ge.iso.datetime({offset:!0}),signature:ge.string().regex(/^[A-Za-z0-9_-]{86}$/)}),ea=ge.string().regex(/^[a-f0-9]{64}$/),Yc=di.extend({sequence:mr,platform:Xc,credentialDigest:ea}),eu=di.extend({credentialDigest:ea}),pv=di.extend({sequence:mr,platform:Xc}),fi=di.extend({sequence:mr,credentialDigest:ea,connectionId:ge.uuid().nullable(),kind:ge.enum(["fcm_token","apns_token"]).nullable(),token:ge.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Wc}),lv=fi,mv=fi.extend({challenge:ge.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),dv=ge.strictObject({requested:ge.literal(!0),expiresAt:ge.iso.datetime({offset:!0})}),hi=ge.strictObject({installationId:ge.uuid(),bound:ge.boolean(),identitySeq:mr,bindingGeneration:mr,addressSeq:ge.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:ge.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:ge.uuid().nullable(),addressStatus:ge.enum(["active","invalid"]).nullable(),permission:Wc}),ta=ge.strictObject({channel:ge.enum(["email","sms","voice","push"]),state:ge.enum(["unknown","allowed","denied"]),revision:ge.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:ge.iso.datetime({offset:!0}).nullable()}),fv=ge.strictObject({state:ge.enum(["allowed","denied"]),revision:ge.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function hv(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 bv="X-Indiana-Protocol",yv="X-Indiana-SDK-Version";var xv={current:"0.10"};import{z as de}from"zod";import{z as ue}from"zod";var dr=ue.strictObject({operationId:ue.uuid(),customerId:ue.uuid(),externalUserId:ue.string().min(1).max(256),modelId:ue.string().min(1).max(256),quantity:ue.number().int().min(1).max(1e6),validForDays:ue.number().int().min(1).max(3660)}),bi=ue.strictObject({operationId:ue.uuid(),customerId:ue.uuid(),status:ue.literal("applied"),voucherId:ue.uuid(),modelId:ue.string().min(1).max(256),quantity:ue.number().int().positive(),issuedAt:ue.iso.datetime({offset:!0}),expiresAt:ue.iso.datetime({offset:!0})}).refine(e=>Date.parse(e.expiresAt)>Date.parse(e.issuedAt),{message:"A benefit must expire after it is issued"}),gi=ue.strictObject({operationId:ue.uuid(),customerId:ue.uuid()}),tu=ue.discriminatedUnion("lookup",[gi.extend({lookup:ue.literal("not_received")}),gi.extend({lookup:ue.literal("found"),result:bi}).refine(e=>e.result.operationId===e.operationId&&e.result.customerId===e.customerId)]),nu=ue.strictObject({customerId:ue.string().min(1).max(256),modelId:ue.string().min(1).max(256),quantity:dr.shape.quantity,validForDays:dr.shape.validForDays,requestId:ue.uuid()}),ru=ue.strictObject({customerId:ue.string().min(1).max(256),operationId:ue.uuid()}),na=ue.strictObject({operationId:ue.uuid(),customerId:ue.uuid(),taskId:ue.uuid(),status:ue.enum(["pending","applied","rejected"]),terms:dr,receipt:bi.nullable(),failureCode:ue.enum(["INVALID_REQUEST","CONNECTION_CHANGED"]).nullable()}).superRefine((e,t)=>{(e.terms.operationId!==e.operationId||e.terms.customerId!==e.customerId||e.status==="applied"!=(e.receipt!==null)||e.status==="rejected"!=(e.failureCode!==null)||e.receipt&&(e.receipt.operationId!==e.operationId||e.receipt.customerId!==e.customerId||e.receipt.modelId!==e.terms.modelId||e.receipt.quantity!==e.terms.quantity))&&t.addIssue({code:"custom",message:"Benefit result differs from the original accepted operation"})});var iu=4,ou=[...oo,"requirement_checks","native_offers","preparations","benefit_claims","authorizations","business_results"],Ud=de.enum(ou),Pn=(e,t)=>de.array(e).max(t).refine(n=>new Set(n).size===n.length,"Declarations must be unique"),Gd=de.strictObject({...Lr.shape,bridgeVersion:de.literal(iu),capabilities:Pn(Ud,ou.length),checkKinds:Pn(de.enum(["access","metered","credit"]),3),preparationActions:Pn(de.enum(["purchase","subscription_change","refund"]),3),authorizationKinds:Pn(de.enum(["auto_topup"]),1),nextActionTypes:Pn(de.enum(["redirect","authenticate"]),2),resultEvents:Pn(de.enum(["benefit.claimed","authorization.updated"]),2)}).superRefine((e,t)=>{e.capabilities.includes("catalog")!==(e.catalog!=="none")&&t.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(e.capabilities.includes("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&t.addIssue({code:"custom",path:["billingEvents"],message:"Declare unique supported billing events"});let n=i=>e.capabilities.includes(i),r=(i,a)=>t.addIssue({code:"custom",path:[i],message:a});n("requirement_checks")!==e.checkKinds.length>0&&r("checkKinds","Declare the supported Check kinds"),n("preparations")!==e.preparationActions.length>0&&r("preparationActions","Declare the supported preparation actions"),n("authorizations")!==e.authorizationKinds.length>0&&r("authorizationKinds","Declare the supported authorization kinds"),n("business_results")!==e.resultEvents.length>0&&r("resultEvents","Declare the supported non-financial results");for(let[i,a,m]of[["purchases","purchase","purchase.completed"],["subscription_changes","subscription_change","subscription.change.completed"],["refunds","refund","refund.updated"]])n(i)&&(!n("operation_status")||!n("billing_records")||!n("preparations")||!e.preparationActions.includes(a)||!e.billingEvents.includes(m))&&r("capabilities",`${i} requires preparation, original lookup and its billing result`);n("purchases")&&!e.billingEvents.includes("purchase.closed")&&r("billingEvents","Purchase execution requires its terminal closure result"),n("subscription_changes")&&!e.billingEvents.includes("subscription.change.closed")&&r("billingEvents","Subscription change execution requires its terminal closure result");for(let[i,a]of[["benefit_claims","benefit.claimed"],["authorizations","authorization.updated"]])n(i)&&(!n("operation_status")||!n("business_results")||!e.resultEvents.includes(a))&&r("capabilities",`${i} requires original lookup and its non-financial result`)}),Cn={"bridge.ping":de.strictObject({challenge:de.uuid()}),"bridge.describe":de.strictObject({}),"requirement.check":ns,"operation.prepare":Bs,"benefit.claim":dr,"operation.read":gi},$d={"bridge.ping":de.strictObject({challenge:de.uuid()}),"bridge.describe":Gd,"requirement.check":rs,"operation.prepare":At,"benefit.claim":bi,"operation.read":tu},Pv=de.enum(["bridge.ping","bridge.describe","requirement.check","operation.prepare","benefit.claim","operation.read"]);function kn(e,t){return de.strictObject({bridgeVersion:de.literal(iu),requestId:de.uuid(),scope:Ht,command:de.literal(e),data:t})}var Cv=de.discriminatedUnion("command",[kn("bridge.ping",Cn["bridge.ping"]),kn("bridge.describe",Cn["bridge.describe"]),kn("requirement.check",Cn["requirement.check"]),kn("operation.prepare",Cn["operation.prepare"]),kn("benefit.claim",Cn["benefit.claim"]),kn("operation.read",Cn["operation.read"])]),Kd=de.strictObject({code:de.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:de.string().min(1).max(500),retryable:de.boolean(),recovery:de.string().min(1).max(80),effect:de.enum(["none","unknown"])}).refine(e=>e.effect!=="unknown"||!e.retryable&&e.recovery==="recover_operation","Unknown effects require original-operation recovery");function kv(e){let t={bridgeVersion:de.literal(4),requestId:de.uuid(),scope:Ht,command:de.literal(e)};return de.union([de.strictObject({...t,data:$d[e]}),de.strictObject({...t,error:Kd})])}import{z as Rn}from"zod";var yi=Rn.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"),Tv=Rn.object({amountCents:Rn.number().int().min(0).max(1e8),currency:ce,interval:Rn.enum(["free","month","year"]),currencyOptions:Rn.partialRecord(ce,Rn.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 y}from"zod";var Ld=y.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),cu=y.enum(["single_use","continuous_use"]),ra=y.record(y.string(),y.union([y.string(),y.number(),y.boolean()]).transform(String).pipe(y.string())),au=y.string().min(1).max(64).refine(e=>!e.includes("::")),uu={credit_amount:y.number(),tier_behavior:y.never().optional(),tiers:y.never().optional()},pu={credit_amount:y.never().optional(),tier_behavior:y.literal("graduated"),tiers:y.array(y.strictObject({to:y.union([y.number(),y.literal("inf")]),credit_amount:y.number()}))},Zd=y.union([y.strictObject({match:ra,priority:y.number().int().optional(),...uu}),y.strictObject({match:ra,priority:y.number().int().optional(),...pu})]),Hd=y.strictObject({match:ra,factor:y.number().positive().optional(),add:y.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),su={metered_feature_id:y.string(),feature_amount:y.number().optional(),dimensions:y.record(au,Zd).optional(),multipliers:y.record(au,Hd).optional()},ia=y.union([y.strictObject({...su,...uu}),y.strictObject({...su,...pu})]),Si=y.number().min(-100),lu=y.record(y.string(),y.strictObject({markup:Si})).nullish(),Ii=y.record(y.string().regex(/.+\/.+/),y.strictObject({markup:Si.optional(),input_cost:y.number().min(0).optional(),output_cost:y.number().min(0).optional()})).nullish(),Qd=y.strictObject({default_markup:Si.optional(),provider_markups:lu,model_markups:Ii}),Bv=y.strictObject({schema:y.array(ia).optional(),markups:Qd.optional()}),Jd=y.strictObject({filters:y.array(y.strictObject({property:y.string(),operator:y.string(),value:y.array(y.string())})),aggregate:y.strictObject({type:y.string(),property:y.string().nullable()}),usage_type:cu}),mu=y.strictObject({schema:y.array(ia).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:y.boolean().optional(),usage_type:cu.default("single_use").overwrite(()=>"single_use"),default_markup:Si.optional(),provider_markups:lu}),oa=mu.safeExtend({schema:y.array(ia).length(0)}),xi={id:Ld,name:y.string().min(1),display:y.strictObject({singular:y.string().optional(),plural:y.string().optional()}).nullish(),event_names:y.array(y.string()).default([]),model_markups:Ii,stripe_meter:y.strictObject({id:y.string(),event_name:y.string()}).nullish(),stripe_product_id:y.string().nullish()},aa=e=>y.discriminatedUnion("type",[y.strictObject({...xi,...e,type:y.literal("boolean"),config:y.null()}),y.strictObject({...xi,...e,type:y.literal("metered"),config:Jd}),y.strictObject({...xi,...e,type:y.literal("credit_system"),config:mu}),y.strictObject({...xi,...e,type:y.literal("ai_credit_system"),config:oa})]),zv=aa({}),Wd=y.strictObject({id:y.boolean(),type:y.boolean(),usage_type:y.boolean()}),Xd={internal_id:y.uuid(),org_id:y.uuid(),created_at:y.number(),env:y.enum(["sandbox","live"]),archived:y.boolean(),project_id:y.uuid(),environment_id:y.uuid(),revision:y.number().int().nonnegative(),update_rules:Wd},du=aa(Xd),Fv=y.strictObject({rows:y.array(du).max(200),nextCursor:y.uuid().nullable()}),Nv=y.strictObject({features:y.array(du).max(500),limited:y.boolean()}),Vv=y.union([aa({action:y.literal("save"),internal_id:y.uuid().nullable(),revision:y.number().int().nonnegative()}),y.strictObject({action:y.enum(["archive","restore","delete"]),internal_id:y.uuid(),revision:y.number().int().nonnegative()})]);import{z as s}from"zod";var yu=s.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),sa=s.string().regex(/^(0|[1-9]\d{0,14})$/),En=s.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Yd=s.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),fr=Yd,Ct=le.refine(e=>/[1-9]/.test(e)),He=s.iso.datetime({offset:!0}),vi=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"))},ef=s.array(s.object({upTo:Ct.nullable(),unitAmountMinor:yu,flatAmountMinor:s.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&&vi(t.upTo)>vi(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),tf=s.discriminatedUnion("kind",[s.object({kind:s.literal("flat"),units:Ct,unitAmountMinor:yu}).strict(),s.object({kind:s.enum(["graduated","volume"]),units:Ct,tiers:ef}).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"),nf=s.strictObject({interval:s.enum(["month","year"]),count:s.number().int().min(1).max(12),anchor:s.enum(["membership","calendar"])}),hr=s.object({currency:ce,pricing:tf,billingCycle:nf.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var fu={requestId:s.uuid(),productVersionId:s.uuid(),internal_feature_id:s.uuid(),currency:ce},xu=s.strictObject({interval:s.enum(["hour","day","week","month"]),intervalCount:s.number().int().min(1).max(12),limit:s.number().int().min(1).max(1e6)}),Su=s.discriminatedUnion("kind",[s.object({...fu,kind:s.literal("auto_topup"),threshold:Ki,quantity:Ct.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:xu.optional()}).strict(),s.object({...fu,kind:s.literal("postpaid"),maxAmountMinorPerPeriod:fr,maxOutstandingMinor:fr}).strict()]),hu={productVersionId:s.uuid(),internal_feature_id:s.uuid(),currency:ce},Iu=s.discriminatedUnion("kind",[s.object({...hu,kind:s.literal("auto_topup"),threshold:Ki,quantity:Ct.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:xu.optional(),purchaseAmountMinor:fr,purchaseUnits:Ct}).strict(),s.object({...hu,kind:s.literal("postpaid"),maxAmountMinorPerPeriod:fr,maxOutstandingMinor:fr,cashPrice:hr}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Oi=s.object({id:s.uuid(),terms:Iu,status:s.enum(["prepared","active","revoked","blocked"]),createdAt:He,acceptedAt:He.nullable(),effectiveAt:He.nullable(),revokedAt:He.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"),vu=s.object({authorizationId:s.uuid(),terms:Iu,setupUrl:s.url().nullable()}).strict(),Ou=s.object({authorizationId:s.uuid(),accepted:s.literal(!0)}).strict(),ju=s.object({authorizationId:s.uuid(),requestId:s.uuid()}).strict(),Au=s.object({internal_feature_id:s.uuid(),entityId:s.uuid().nullable(),interval:s.enum(["day","week","month","year"]),anchor:s.enum(["billing_cycle","utc"]).optional(),basis:s.enum(["usage","credits"]),filter:It.optional(),limit:le.nullable(),thresholds:s.array(s.number().positive().max(1)).max(8),includedThresholds:s.array(s.number().positive().max(1)).max(8).optional(),absoluteThresholds:s.array(Ct).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&&vi(t)>vi(i)}),"Notification thresholds must increase"),rf=Au.safeExtend({requestId:s.uuid()}),gu={control:s.literal("overage"),requestId:s.uuid(),internal_feature_id:s.uuid(),entityId:s.uuid().nullable()},of=s.discriminatedUnion("action",[s.strictObject({...gu,action:s.literal("set"),allowed:s.boolean().nullable(),overageLimit:le.nullable(),skipOverageBilling:s.boolean()}),s.strictObject({...gu,action:s.literal("remove")})]),_u=s.union([rf,of]),af=s.strictObject({internal_feature_id:s.uuid(),entityId:s.uuid().nullable(),allowed:s.boolean().nullable(),overageLimit:le.nullable(),skipOverageBilling:s.boolean(),interval:s.enum(["day","week","month","year"]),startsAt:He,endsAt:He,used:s.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:s.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:s.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),sf=s.object({internal_feature_id:s.uuid(),entityId:s.uuid().nullable(),interval:s.enum(["day","week","month","year"]),anchor:s.enum(["billing_cycle","utc"]).optional(),basis:s.enum(["usage","credits"]),filter:It.optional(),startsAt:He,endsAt:He,used:pt,reserved:pt,limit:le.nullable(),thresholds:s.array(s.number().positive().max(1)).max(8),notifiedThresholds:s.array(s.number().positive().max(1)).max(1024),includedThresholds:s.array(s.number().positive().max(1)).max(8).optional(),includedAllowance:s.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:s.array(s.number().positive().max(1)).max(1024).optional(),absoluteThresholds:s.array(Ct).max(8).optional(),notifiedAbsoluteThresholds:s.array(Ct).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||le.safeParse(e.used).success&&le.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),cf=s.object({authorizationId:s.uuid(),status:s.enum(["idle","pending","blocked"]),taskId:s.uuid().nullable(),invoiceId:s.uuid().nullable(),hostedInvoiceUrl:s.url().nullable(),purchaseCount:s.number().int().nonnegative(),purchaseWindowEndsAt:He.nullable(),attemptCount:s.number().int().nonnegative(),failedAttemptCount:s.number().int().nonnegative(),suspendedAt:He.nullable(),nextAttemptAt:He.nullable(),failureReason:s.string().min(1).max(240).nullable()}).strict(),wu=s.object({internal_feature_id:s.uuid().optional(),entityId:s.uuid().optional()}).strict(),ca=s.object({authorizations:s.array(Oi).max(100),limits:s.array(Au).max(100),overages:s.array(af).max(100).optional(),windows:s.array(sf).max(200),autoTopups:s.array(cf).max(100),limited:s.boolean()}).strict(),uf=s.object({id:s.uuid(),internal_feature_id:s.uuid(),productVersionId:s.uuid(),authorizationId:s.uuid(),entityId:s.uuid().nullable(),units:le,amountMinor:En,cashPrice:hr}).strict(),gr=s.object({id:s.uuid(),sourceKind:s.enum(["product","usage","manual"]),providerInvoiceId:s.string().min(1).max(240).nullable(),status:s.enum(["accruing","open","pending","paid","failed","void"]),currency:ce,startsAt:He.nullable(),endsAt:He.nullable(),amountMinor:s.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:s.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:sa,paidAmountMinor:sa,refundedAmountMinor:sa,createdAt:He,hostedInvoiceUrl:s.url().nullable(),adjustment:s.object({originalInvoiceId:s.uuid(),amountMinor:s.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:He.nullable(),reason:s.string().min(1).max(500).optional()}).strict().nullable(),lines:s.array(uf).max(100),linesLimited:s.boolean()}).strict(),Pu=s.object({invoiceId:s.uuid(),accepted:s.literal(!0)}).strict(),Cu=s.strictObject({requestId:s.uuid(),originalInvoiceId:s.uuid(),amountMinor:s.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:s.string().trim().min(1).max(500)}),ku=s.object({after:s.uuid().nullable(),limit:s.number().int().min(1).max(100)}).strict(),Ru=s.object({rows:s.array(gr).max(100),nextCursor:s.uuid().nullable()}).strict(),bu=s.strictObject({id:s.string(),coupon:s.string(),start:s.number().nonnegative(),end:s.number().nullable()}),pf=s.strictObject({subscriptionId:s.string(),customerId:s.string(),accountId:s.string(),sourceItems:s.array(s.strictObject({id:s.string(),price_id:s.string(),quantity:s.number().int(),discounts:s.array(bu).optional()})).max(100),items:s.array(s.strictObject({id:s.string(),price:s.string(),quantity:s.number().int(),discounts:s.array(s.strictObject({coupon:s.string().optional(),terms:s.strictObject({id:s.string(),name:s.string().optional(),percent_off:s.number().optional(),amount_off:s.number().optional(),currency:s.string().optional(),duration:s.enum(["once","forever","repeating"]),duration_in_months:s.number().optional()}).optional(),discount:s.string().optional(),receipt:bu.optional()})).max(20)})).max(100)}),Eu=s.strictObject({membershipId:s.uuid(),requestId:s.uuid(),grantIds:s.array(s.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Mu=s.strictObject({membershipId:s.uuid(),operationId:s.uuid(),status:s.enum(["pending","effective"]),execution:pf.nullable(),grants:s.array(s.strictObject({id:s.uuid(),couponId:s.uuid(),name:s.string(),discount:Bt,duration:rt,startedAt:He.nullable()})).max(20)});import{z as br}from"zod";var Tu=br.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Du=br.number().int().min(1).max(1e3),ji=br.object({cap:le.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:br.number().positive().max(1e4).nullable(),cycles:br.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 Ft}from"zod";var qu=Ft.strictObject({itemKey:Ft.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:Ft.uuid(),includedAmount:Ft.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Ft.number().int().min(0).max(1e4),terms:os,pricing:is.optional(),unitAmountMinor:Ft.number().int().min(0).max(1e8),productId:Ft.string().min(1).max(255).nullable(),priceId:Ft.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{as(e.includedAmount,e.terms.units,e.quantity),Dr({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 ae}from"zod";var tn=ae.iso.datetime({offset:!0}),Bu=le.refine(e=>/[1-9]/.test(e)),zu=ae.strictObject({interval:Tu.exclude(["lifetime"]),count:Du}),lf=ae.strictObject({action:ae.literal("create"),requestId:ae.uuid(),internal_feature_id:ae.uuid(),entityId:ae.uuid().nullable(),amount:Bu.nullable(),expiresAt:tn.nullable(),reset:zu.nullable(),rollover:ji.nullable(),nextResetAt:tn.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"),Fu=ae.discriminatedUnion("action",[lf,ae.strictObject({action:ae.literal("update"),requestId:ae.uuid(),grantId:ae.uuid(),revision:ae.number().int().nonnegative(),amount:Bu.nullable(),expiresAt:tn.nullable(),rollover:ji.nullable(),nextResetAt:tn.nullable()}),ae.strictObject({action:ae.enum(["add","subtract","set_remaining"]),requestId:ae.uuid(),grantId:ae.uuid(),revision:ae.number().int().nonnegative(),amount:le}),ae.strictObject({action:ae.literal("revoke"),requestId:ae.uuid(),grantId:ae.uuid(),revision:ae.number().int().nonnegative()})]),ua=ae.strictObject({id:ae.uuid(),internal_feature_id:ae.uuid(),entityId:ae.uuid().nullable(),amount:le.nullable(),reset:zu.nullable(),rollover:ji.nullable(),nextResetAt:tn.nullable(),startsAt:tn,expiresAt:tn.nullable(),revision:ae.number().int().nonnegative(),revoked:ae.boolean(),available:pt,held:pt,spent:pt}),Nu=ae.strictObject({customerId:ae.uuid(),after:ae.uuid().nullable(),limit:ae.number().int().min(1).max(100)}),Vu=ae.strictObject({rows:ae.array(ua).max(100),nextCursor:ae.uuid().nullable()});import{z as D}from"zod";var xt=D.iso.datetime({offset:!0}),Uu=D.strictObject({invoiceId:D.uuid(),after:D.string().min(1).max(180).nullable(),limit:D.number().int().min(1).max(100)}),mf=D.strictObject({kind:D.literal("product"),key:D.string(),productVersionId:D.uuid(),productName:D.string(),itemKey:D.string(),entityId:D.uuid().nullable(),quantity:D.number().positive(),subtotalMinor:D.string().regex(/^-?\d+$/),discountMinor:D.string().regex(/^\d+$/),taxMinor:D.string().regex(/^-?\d+$/).nullable(),totalMinor:D.string().regex(/^-?\d+$/),startsAt:xt.nullable(),endsAt:xt.nullable(),providerLineId:D.string().nullable(),providerItemId:D.string()}),Gu=D.strictObject({invoice:gr,items:D.array(D.discriminatedUnion("kind",[mf,D.strictObject({kind:D.literal("invoice_credit"),key:D.string(),internal_feature_id:D.uuid(),internal_credit_feature_id:D.uuid(),name:D.string(),units:le,reserved:le,amountMinor:En,grossAmountMinor:En,creditsAppliedMinor:En,properties:It,cashPrice:hr,providerItemId:D.string().nullable(),creditProviderItemId:D.string().nullable()}),D.strictObject({kind:D.literal("usage"),key:D.string(),internal_feature_id:D.uuid(),name:D.string(),units:le,reserved:le,amountMinor:En,cashPrice:hr})])).max(100),nextCursor:D.string().min(1).max(180).nullable()}),df=D.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),pa=D.strictObject({from:xt,to:xt,entityId:D.uuid().optional(),snapshotAt:xt.nullable(),after:D.strictObject({at:xt,id:D.uuid(),position:D.number().int().nonnegative()}).nullable(),limit:D.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"),$u=D.strictObject({customerId:D.uuid(),entityId:D.uuid().nullable(),from:xt,to:xt,snapshotAt:xt,totals:D.array(D.strictObject({internal_credit_feature_id:D.uuid(),name:D.string(),consumed:pt,refunded:pt,net:df})).max(1e3),rows:D.array(D.strictObject({operationId:D.uuid(),position:D.number().int().nonnegative(),kind:D.enum(["consume","confirm","refund"]),originalId:D.uuid().nullable(),occurredAt:xt,internal_feature_id:D.uuid(),entitlementName:D.string(),sourceId:D.uuid(),internal_credit_feature_id:D.uuid(),creditName:D.string(),units:ls,amount:pt,pricing:D.array(ps).max(12),properties:It})).max(100),nextCursor:pa.shape.after});import{z as U}from"zod";var Lu=U.object({customerId:U.uuid()}).strict(),Zu=U.discriminatedUnion("action",[U.object({customerId:U.uuid(),requestId:U.uuid(),action:U.literal("assign"),poolId:U.uuid(),memberCustomerId:U.uuid()}).strict(),U.strictObject({customerId:U.uuid(),requestId:U.uuid(),action:U.literal("assign_entity"),poolId:U.uuid(),entityId:U.uuid()}),U.object({customerId:U.uuid(),requestId:U.uuid(),action:U.literal("release"),poolId:U.uuid(),slotId:U.uuid()}).strict()]),yr=U.number().int().nonnegative(),la=U.iso.datetime({offset:!0}),ma=U.strictObject({internalId:U.uuid(),id:U.string(),name:U.string().nullable(),version:U.number().int().positive()}),Ku=U.enum(["active","past_due"]),da=U.strictObject({customerId:U.uuid(),licenses:U.array(U.strictObject({id:U.uuid(),linkId:U.uuid(),parent:U.strictObject({customerProductId:U.uuid(),status:Ku,product:ma}),product:ma,planLicense:U.strictObject({id:U.uuid(),prepaidOnly:U.boolean(),isCustom:U.boolean()}).nullable(),granted:yr,included:yr,paidQuantity:yr,usage:yr,remaining:yr,createdAt:la}).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:U.array(U.strictObject({id:U.uuid(),linkId:U.uuid(),status:Ku,product:ma,entity:U.strictObject({internalId:U.uuid(),id:U.string().nullable(),name:U.string().nullable()}).nullable(),beneficiary:U.strictObject({internalId:U.uuid(),id:U.string().nullable(),name:U.string().nullable()}).nullable(),startedAt:la.nullable(),endedAt:la.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:U.boolean()});import{z as V}from"zod";var xr=V.enum(["email","sms","voice","push"]),d0=V.enum(["resend","twilio","fcm","apns"]);var f0=V.string().regex(/^\+[1-9]\d{1,14}$/),ff=V.enum(["email_recipient","sms_segment","voice_second","push_device"]);var hf=V.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),gf=V.strictObject({subject:hf,html:V.string().min(1).max(131072).optional(),text:V.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),bf=V.strictObject({body:V.string().min(1).max(1600).refine(e=>e.trim().length>0)}),yf=V.strictObject({text:V.string().trim().min(1).max(4e3),language:V.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:V.number().int().min(1).max(900)}),xf=V.record(V.string().min(1).max(64),V.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"),Sf=V.strictObject({title:V.string().trim().min(1).max(200),body:V.string().trim().min(1).max(2e3),url:V.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:xf.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Hu=V.discriminatedUnion("channel",[V.strictObject({channel:V.literal("email"),content:gf}),V.strictObject({channel:V.literal("sms"),content:bf}),V.strictObject({channel:V.literal("voice"),content:yf}),V.strictObject({channel:V.literal("push"),content:Sf})]),Qu=V.strictObject({requestId:V.uuid(),customerId:V.uuid(),connectionId:V.uuid().optional(),message:Hu,expiresAt:V.iso.datetime({offset:!0})}),If=V.array(V.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),vf=V.discriminatedUnion("kind",[V.strictObject({kind:V.literal("all")}),V.strictObject({kind:V.literal("customers"),customerIds:If})]),h0=V.strictObject({name:V.string().trim().min(1).max(120),connectionId:V.uuid().optional(),message:Hu,audience:vf,frequencyLimit:V.number().int().min(1).max(100)}),Ju=V.strictObject({requestId:V.uuid(),channel:xr,state:V.enum(["allowed","denied"]),expectedRevision:V.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Wu=V.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Xu=V.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),g0=V.strictObject({meter:ff,estimatedUnits:V.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:V.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Yu}from"zod";var Mn={funnelId:Yu.uuid().optional(),funnelVersionId:Yu.uuid().optional()};import{z as Ai}from"zod";var _i=Ai.strictObject({runId:Ai.uuid(),bindingId:Ai.uuid(),receiptId:Ai.uuid()});import{z as Oe}from"zod";import{z as fe}from"zod";var fa=fe.object({type:fe.literal("native_purchase"),receiptId:fe.uuid(),orderId:fe.uuid(),productVersionId:fe.uuid(),provider:fe.enum(["apple","google"]),productId:fe.string().min(1).max(255),productKind:Ya,replacement:fe.strictObject({sourceOrderId:fe.uuid(),sourceProductId:fe.string().min(1).max(255),policy:fe.enum(["apple_store","google_full_price"]),sourceAccountTokens:fe.array(fe.uuid()).max(50)}).nullable(),appAccountToken:fe.uuid().optional(),obfuscatedAccountId:fe.string().min(1).max(64).optional(),obfuscatedProfileId:fe.uuid().optional(),basePlanId:fe.string().min(1).max(255).optional(),offerId:fe.string().min(1).max(255).optional(),offerKind:fe.enum(["none","introductory","promotional"]),currency:ce,catalogAmountMinor:fe.number().int().nonnegative().max(1e8),discountMinor:fe.number().int().nonnegative().max(1e8),trialDays:fe.number().int().min(1).max(730).nullable(),seatBundle:fe.array(fe.strictObject({key:fe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:fe.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:fe.strictObject({offerId:fe.string().min(1).max(255),keyId:fe.string().min(1).max(255),nonce:fe.uuid(),signature:fe.string().min(1).max(1024),timestamp:fe.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 Y}from"zod/v4";import{z as Of}from"zod/v4";var jf=Of.registry(),{BillingInterval:ep}=(()=>{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:Af}=(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')."})})}))(Y),{withSpecDefault:_f}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(jf),{COMMON:tp}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:wf}={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:Pf}=(e=>({COMMON_SET:new Set(e)}))(tp),{hasNoDuplicateCurrencies:np}={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:rp}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Cf}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(Y),{Infinite:kf}={Infinite:"inf"},{TierBehavior:Rf}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:ip}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Ef}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Mf}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Tf}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Df}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Y),{ApiCreditTierSchema:op}=(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."})})}))(Y),{VIOLATION_MESSAGES:qf}={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:ap}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Y),{ModelMarkupsSchema:Bf}=((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()}))(Y,ap),{InvoiceUsageEntrySchema:zf}=(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()}))(Y),{AttachDiscountSchema:sp}=(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."})}))(Y),{CustomLineItemSchema:Ff}=(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."})})}))(Y),{UnixMsTimestampSchema:Nf}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(Y),{CreateInvoicePreviewLineSchema:Vf}=(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()})}))(Y),{ReissueInvoiceParamsSchema:cp}=(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."})})}))(Y),{InvoiceModeParamsSchema:nn}=(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."})}))(Y),{InvoiceTemplateSchema:Uf}=(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."})})}))(Y),{BasePriceSchema:Gf}=((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."})})}))(Y,ep,Af),{CURRENCY_CODES:$f}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(tp,wf,Pf),{ApiPriceProcessorsSchema:up}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(Y,Cf),{AllocatedBillingFieldSchema:Kf}=((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'."})}))(Y,Ef),{CreditDimensionNameSchema:Lf}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Y,Mf,Tf),{ApiCreditMatchSchema:pp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Df),{findCreditTierViolations:Zf}=(e=>({findCreditTierViolations:n=>{let r=[],i=(m,c)=>r.push({index:m,reason:c,message:e[c]}),a=0;for(let[m,c]of n.entries()){let d=m===n.length-1;if(c==="inf"){d||i(m,"non_final_infinity");continue}(!Number.isFinite(c)||c<=a)&&i(m,"not_increasing"),a=c,d&&i(m,"final_not_infinity")}return r}}))(qf),{ApiCreditMultiplierSchema:Hf}=((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."})}))(Y,pp),{ProviderMarkupsSchema:Qf}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Y,ap),{InvoiceFeatureQuantitySchema:lp}=((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."})}))(Y,ip,zf),{CreateInvoicePreviewSchema:ha}=((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()})}))(Y,Vf),{SUPPORTED_SET:Jf}=(e=>({SUPPORTED_SET:new Set(e)}))($f),{ApiCreditDimensionBaseSchema:Wf}=((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."})})}))(Y,pp),{refineGraduatedTiers:mp}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:m}of i)r.addIssue({code:"custom",message:m,path:["tiers",a,"to"]})}}))(Zf),{ApiFeatureMarkupsOverrideSchema:Xf}=((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."})})}))(Y,Qf,Bf),{isValidCurrencyCode:Yf}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Jf),{ApiCreditDimensionSchema:eh}=((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()])}))(Y,Wf,op,mp),{CurrencyCodeSchema:dp}=((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')."})}))(Y,Yf),{AdditionalCurrencyTierSchema:th}=((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"]})}))(Y,dp),{ApiCreditSchemaItemBaseSchema:fp}=((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."})})}))(Y,Lf,eh,Hf),{ApiFlatCreditSchemaItemSchema:nh}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(fp,Y),{AdditionalCurrencyPriceSchema:rh}=((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."})})}))(Y,dp),{AdditionalCurrencyTierArraySchema:ih}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Y,th,np,rp),{ApiGraduatedCreditSchemaItemSchema:oh}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(fp,Y,op,mp),{AdditionalCurrencyPriceArraySchema:hp}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Y,rh,np,rp),{ApiUsageTierWithCurrenciesSchema:ah}=((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()}))}))(Y,kf,ih),{ApiCreditSchemaItemSchema:sh}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(Y,oh,nh),{BasePriceParamsSchema:ch}=((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."})}))(Gf,_f,Y,hp),{PlanItemPriceParamsSchema:uh}=((e,t,n,r,i,a,m)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(d=>d??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:m,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."})})}))(Y,hp,ah,Rf,ep,ip,Kf),{ApiFeatureOverrideSchema:ph}=((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."})})}))(Y,sh,Xf),{InvoiceBasePriceParamsSchema:gp}=((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()}))(ch,up),{InvoiceItemPriceParamsSchema:lh}=((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()}))(uh,up),{InvoiceLicenseQuantitySchema:mh}=((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()}))(Y,gp,lp),{InvoiceCustomizeItemSchema:dh}=((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()}))(Y,lh,ph),{InvoiceCustomizeSchema:fh}=((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."})}))(Y,gp,dh),{InvoicePlanParamsSchema:hh}=((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()}))(Y,fh,lp,mh,sp),{CreateInvoiceParamsSchema:Tn}=((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(m=>m.period_start===void 0==(m.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(m=>m.period_start===void 0||m.period_end===void 0||m.period_end>m.period_start,{message:"period_end must be after period_start."})}))(Y,hh,Ff,sp,Nf);var xp=o.strictObject({requestId:o.uuid(),predecessorOperationId:o.uuid().optional(),invoiceMode:nn.optional(),entityId:o.uuid().optional(),billingSubscriptionId:o.uuid().optional(),newBillingSubscription:o.literal(!0).optional(),offerId:o.uuid().optional(),nativeOffer:On.optional(),plans:o.array(o.strictObject({productVersionId:o.uuid(),seatQuantities:o.record(yi,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:ce}).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"),on=o.strictObject({operationId:o.uuid()}),Te=o.number().int().min(0).max(1e8),gh=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:Te,seats:o.array(o.strictObject({key:yi,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:Te})).max(20),prepaid:o.array(qu).max(100).optional(),catalogAmountMinor:Te,trial:Yn.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+Dr({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"),Sp=o.string().regex(/^[A-Za-z0-9_-]{1,200}$/),bh=o.strictObject({id:Sp,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"),yh=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()}),Ip=o.strictObject({invoiceMode:nn.optional(),append:yh.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:Sp,terms:bh})).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})}),Dn=o.strictObject({operationId:o.uuid(),merchantTerms:At.optional(),entityId:o.uuid().nullable(),billingSubscriptionId:o.uuid().nullable(),discount:o.strictObject({offerId:o.uuid(),couponId:o.uuid(),discount:Bt,duration:rt,amountMinor:Te,allocations:o.array(o.strictObject({productVersionId:o.uuid(),amountMinor:Te})).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:Te,discountMinor:Te,taxMinor:Te,totalMinor:Te}).nullable(),expiresAt:o.iso.datetime({offset:!0}),provider:o.enum(["stripe","apple","google","merchant"]),nativeOffer:On.optional(),currency:ce,lines:o.array(gh).min(1).max(20),catalogAmountMinor:Te,nativeDiscountMinor:Te.optional(),automaticTax:o.boolean(),execution:o.union([Ip,Fr]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&$r(e.merchantTerms,e.operationId,"purchase",e.currency)).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"),qn=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([Ip,Fr]).nullable(),currency:ce,catalogAmountMinor:Te,taxMinor:Te,totalMinor:o.number().int().min(0).max(2e8).nullable(),quoteFinalized:o.boolean(),nativePurchase:fa.nullable(),confirmedAt:o.iso.datetime({offset:!0}).nullable().optional(),quote:Dn.optional(),merchantExecution:$t.nullable().optional(),problem:Xn.nullable().optional(),authority:Zr.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"),Pi=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()}),vp=o.strictObject({requestId:o.uuid(),offerId:o.uuid().optional(),invoiceMode:nn.optional(),membershipId:o.uuid(),carryOverBalances:Pi.optional(),carryOverUsages:Pi.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:yi,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.offerId||e.change.type==="plan"&&e.timing!=="store","A selected plan-change offer requires a merchant target Product").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"),wi=o.string().regex(/^price_[A-Za-z0-9]+$/),bp=o.strictObject({grooveUpdateId:o.uuid(),grooveCustomerId:o.uuid()}),yp=o.strictObject({price:wi.nullable(),priceId:o.uuid().optional(),quantity:o.number().int().min(0).max(1e4)}),Op=o.strictObject({provider:o.literal("stripe"),invoiceMode:nn.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(yp).max(20),remove:o.array(wi).max(20),restoreItems:o.array(o.strictObject({price:wi,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:bp}).nullable(),cancel:o.strictObject({prorate:o.literal(!1),invoiceNow:o.literal(!1)}).nullable(),schedule:o.strictObject({currentItems:o.array(o.strictObject({price:wi,quantity:o.number().int().min(0).max(1e4)})).max(20),nextItems:o.array(yp).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:bp}).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"),Ci=o.strictObject({merchantTerms:At.optional(),carryOverBalances:Pi.optional(),carryOverUsages:Pi.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:ce,creditMinor:Te,debitMinor:Te,discountMinor:Te,taxMinor:Te,totalMinor:Te,retainedProductVersionIds:o.array(o.uuid()).max(19),execution:o.union([Op,Mt])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&$r(e.merchantTerms,e.operationId,"subscription_change",e.currency)),xh=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([Op,Mt]).nullable(),confirmedAt:o.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:$t.nullable().optional(),problem:Xn.nullable().optional(),quote:Ci.optional(),authority:Zr.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),Sh=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:ce,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:Te,policy:o.enum(["apple_store","google_full_price"])})}),Ih=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:fa.nullable()}),jp=o.union([Ci,Sh]),ga=o.union([xh,Ih]),ba=to,rn=Vr,Ap=o.strictObject({requestId:o.uuid(),invoiceId:o.uuid(),...Kt.shape}).refine(tr,"A partial refund states amountMinor; a full refund refunds the remaining amount"),_p=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:ba,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)}),ya=o.strictObject({operationId:o.uuid(),merchantTerms:At.optional(),invoiceId:o.uuid(),providerInvoiceId:o.string().min(1).max(200),currency:ce,paidMinor:rn,refundedMinor:rn,pendingMinor:rn,amountMinor:ba,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([_p,Nr]),expiresAt:o.iso.datetime({offset:!0})}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&$r(e.merchantTerms,e.operationId,"refund",e.currency)).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"),ki=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:ce,amountMinor:ba,mode:o.enum(["full","partial"]),entitlementAction:o.enum(["retain","revoke"]),refundId:o.string().min(1).max(200).nullable(),quote:ya.optional(),execution:o.union([_p,Nr]).nullable(),confirmedAt:o.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:$t.nullable().optional(),problem:Xn.nullable().optional(),authority:Zr.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"),G0=o.strictObject({invoiceId:o.uuid(),currency:ce,paidMinor:rn,refundedMinor:rn,pendingMinor:rn,refundableMinor:rn,executor:o.enum(["indiana","merchant"]).nullable(),canRefund:o.boolean(),operations:o.array(ki).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),$0=o.strictObject({requestId:o.uuid(),...Kt.shape}).refine(tr,"A partial refund states amountMinor; a full refund refunds the remaining amount");var wp=Oe.strictObject({requestId:Oe.uuid(),targets:Oe.array(Oe.strictObject({membershipId:Oe.uuid(),action:Oe.enum(["cancel","uncancel"]),timing:Oe.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"),Ri=Oe.strictObject({batchId:Oe.uuid()}),vh=Oe.strictObject({operationId:Oe.uuid(),membershipIds:Oe.array(Oe.uuid()).min(1).max(20),provider:Oe.enum(["stripe","apple","google"]),action:Oe.enum(["cancel","uncancel"]),timing:Oe.enum(["immediate","renewal"]),status:Oe.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Ci.nullable(),managementUrl:Oe.url().nullable(),failureCode:Oe.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Sr=Oe.strictObject({batchId:Oe.uuid(),ready:Oe.boolean(),status:Oe.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:Oe.iso.datetime({offset:!0}),acceptedAt:Oe.iso.datetime({offset:!0}).nullable(),groups:Oe.array(vh).min(1).max(100)});import{z as oe}from"zod";var Oh=oe.string().trim().min(1).max(240),xa={requestId:oe.uuid(),reason:Oh},Ei=oe.discriminatedUnion("action",[oe.strictObject({...xa,action:oe.literal("start"),productVersionId:oe.uuid(),entityId:oe.uuid().optional(),days:oe.number().int().min(1).max(730).optional()}),oe.strictObject({...xa,action:oe.literal("extend"),membershipId:oe.uuid(),days:oe.number().int().min(1).max(730)}),oe.strictObject({...xa,action:oe.literal("end"),membershipId:oe.uuid()})]),Pp=oe.strictObject({operationId:oe.uuid()}),Cp=oe.iso.datetime({offset:!0}),jh=oe.strictObject({provider:oe.literal("stripe"),executor:oe.enum(["indiana","merchant"]),accountId:oe.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:oe.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:oe.union([oe.literal("now"),Cp]),prorationBehavior:oe.literal("none")}),Sa=oe.strictObject({operationId:oe.uuid(),action:oe.enum(["start","extend","end"]),status:oe.enum(["pending","effective"]),managedBy:oe.enum(["indiana","stripe"]),membershipIds:oe.array(oe.uuid()).min(1).max(20),endsAt:Cp.nullable(),execution:jh.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"),J0=oe.strictObject({groupId:oe.uuid(),productVersionId:oe.uuid(),enabled:oe.boolean()});import{z as xe}from"zod";var kp=xe.strictObject({requestId:xe.uuid(),currency:ce,makeDefault:xe.boolean()}),Rp=xe.strictObject({setupId:xe.uuid()}),Ah=xe.strictObject({provider:xe.literal("stripe"),executor:xe.literal("merchant"),accountId:xe.string().regex(/^acct_[A-Za-z0-9]+$/),mode:xe.literal("setup"),currency:xe.string().regex(/^[a-z]{3}$/),customer:xe.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:xe.uuid(),metadata:xe.strictObject({grooveProjectId:xe.uuid(),grooveEnvironmentId:xe.uuid(),grooveCustomerId:xe.uuid(),groovePaymentSetupId:xe.uuid()}),setDefaultPaymentMethod:xe.boolean(),expiresAt:xe.iso.datetime({offset:!0})}),Ia=xe.strictObject({id:xe.uuid(),provider:xe.literal("stripe"),status:xe.enum(["prepared","complete","expired"]),currency:ce,makeDefault:xe.boolean(),url:xe.url().nullable(),createdAt:xe.iso.datetime({offset:!0}),expiresAt:xe.iso.datetime({offset:!0}),completedAt:xe.iso.datetime({offset:!0}).nullable(),execution:Ah.nullable()});import{z as Ne}from"zod";var Ep=Ne.union([Ne.string(),Ne.number(),Ne.boolean(),Ne.null()]),Mp=Ne.strictObject({customerId:Ne.uuid()}),Tp=Ne.strictObject({customerId:Ne.uuid(),provider:Ne.literal("stripe"),checkedAt:Ne.iso.datetime({offset:!0}),status:Ne.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ne.number().int().nonnegative(),differences:Ne.array(Ne.strictObject({subscriptionId:Ne.string().startsWith("sub_"),itemId:Ne.string().nullable(),field:Ne.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Ep,actual:Ep})).max(1e4)});import{z as W}from"zod";var Mi=W.iso.datetime({offset:!0}),Ti=W.strictObject({createdAt:Mi,id:W.uuid()}),Di=W.strictObject({customerId:W.uuid().optional(),entityId:W.uuid().optional(),productId:W.string().min(1).max(256).optional(),provider:W.enum(["stripe","apple","google","merchant","free"]).optional(),status:W.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Ti.optional(),limit:W.number().int().min(1).max(100).optional()}),va={id:W.uuid(),customerId:W.uuid(),entityId:W.uuid().nullable(),productId:W.string().min(1).max(256),productVersionId:W.uuid(),name:W.string().min(1).max(120),provider:W.enum(["stripe","apple","google","merchant","free"]),createdAt:Mi},_h=W.strictObject({...va,status:W.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:W.boolean(),billingSubscriptionId:W.uuid().nullable()}),wh=W.strictObject({...va,status:W.enum(["active","ended","refunded"]),orderId:W.uuid().nullable(),transactionId:W.uuid().nullable(),currency:ce.nullable(),amountMinor:W.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),Ph=W.strictObject({...va,status:W.enum(["blocked","resolved"]),conflict:W.strictObject({detectedAt:Mi,blockingMembershipIds:W.array(W.uuid()).min(1).max(100),transactionId:W.uuid()}),resolvedAt:Mi.nullable()}),Dp=Di.extend({status:W.enum(["blocked","resolved"]).optional()}),qp=W.strictObject({customerId:W.uuid(),orderId:W.uuid()}),Bp=W.strictObject({orderId:W.uuid(),status:W.enum(["blocked","resolved"])}),zp=W.strictObject({items:W.array(_h).max(100),nextCursor:Ti.nullable()}),Fp=W.strictObject({items:W.array(wh).max(100),nextCursor:Ti.nullable()}),Np=W.strictObject({items:W.array(Ph).max(100),nextCursor:Ti.nullable()});import{z as Ie}from"zod";var Vp=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)})]),Up=Ie.strictObject({requestId:Ie.uuid(),orderId:Ie.uuid(),purchaseIntentId:Ie.uuid(),status:Ie.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:ce,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 A}from"zod";var ja=A.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),Ch=A.record(A.string(),A.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),kh=3,Ir=20,Rh=kh*Ir,Oa=A.strictObject({type:A.literal("product"),productId:ja}),Gp={type:A.literal("group"),key:A.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:A.string().trim().min(1).max(80)},Eh=A.discriminatedUnion("type",[Oa,A.strictObject({...Gp,items:A.array(Oa).max(Ir)})]),Mh=A.discriminatedUnion("type",[Oa,A.strictObject({...Gp,items:A.array(Eh).max(Ir)})]),Th=A.array(Mh).max(Ir).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(m){for(let c of m){i++;let d=c.type==="product"?n:r,I=c.type==="product"?c.productId:c.key;d.has(I)&&t.addIssue({code:"custom",message:c.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),d.add(I),c.type==="group"&&a(c.items)}}a(e),(n.size>Ir||i>Rh)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Aa(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Aa(t))}var Bn=A.strictObject({lookupKey:A.string().trim().min(1).max(200),displayName:A.string().trim().min(1).max(1500),items:Th,metadata:Ch}),Dh=A.strictObject({product:A.record(A.string(),A.json()),prices:A.array(A.record(A.string(),A.json())),entitlements:A.array(A.record(A.string(),A.json())),freeTrials:A.array(A.record(A.string(),A.json())),licenses:A.array(A.record(A.string(),A.json()))}),$p=Bn.extend({id:A.uuid(),projectId:A.uuid(),environmentId:A.uuid(),state:A.enum(["active","archived"]),isCurrent:A.boolean(),revision:A.number().int().nonnegative(),publishedVersionId:A.uuid().nullable(),createdAt:A.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"})}),Kp=A.strictObject({id:A.uuid(),offeringId:A.uuid(),projectId:A.uuid(),environmentId:A.uuid(),version:A.number().int().positive(),document:Bn,productEvidence:A.record(ja,Dh),createdAt:A.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Aa(e.document);(!n.length||zh(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"})}),qh=A.strictObject({rows:A.array($p).max(200),versions:A.array(Kp).max(500)}),pO=A.discriminatedUnion("action",[A.strictObject({action:A.literal("create"),document:Bn}),A.strictObject({action:A.literal("save"),id:A.uuid(),revision:A.number().int().nonnegative(),document:Bn}),A.strictObject({action:A.enum(["publish","set_current","archive","restore"]),id:A.uuid(),revision:A.number().int().nonnegative()})]),lO=A.strictObject({record:$p,version:Kp.nullable()}),Lp=A.discriminatedUnion("type",[A.strictObject({type:A.literal("current")}),A.strictObject({type:A.literal("id"),id:A.uuid()}),A.strictObject({type:A.literal("lookup_key"),lookupKey:A.string().min(1).max(200)}),A.strictObject({type:A.literal("version"),versionId:A.uuid()})]),Bh=A.strictObject({internalId:ja,id:A.string(),name:A.string().nullable(),version:A.number().int().positive(),archived:A.boolean()}),mO=qh.extend({products:A.array(Bh).max(500),pagination:A.strictObject({rows:A.string().nullable(),versions:A.string().nullable(),products:A.string().nullable()}).optional()});function zh(e){let t=[];Aa(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 qi}from"zod";var Zp=qi.strictObject({id:qi.uuid(),offeringId:qi.uuid(),version:qi.number().int().positive(),document:Bn});import{z as Ee}from"zod";var Hp=Ee.strictObject({processContext:_i.optional(),...Mn,selector:Ee.discriminatedUnion("type",[Ee.strictObject({type:Ee.literal("paywall"),paywallId:Ee.uuid()}),Ee.strictObject({type:Ee.literal("version"),versionId:Ee.uuid()})]),customerId:Ee.uuid().optional(),commerce:Tr,locale:Ee.string().min(1).max(35),requirement:pn.optional()}),vr=Ee.strictObject({id:Ee.uuid(),paywallId:Ee.uuid(),version:Ee.number().int().positive(),document:wn.omit({requirement:!0,offeringId:!0}),offering:Ee.strictObject({id:Ee.uuid()}),content:Ee.strictObject({environmentId:Ee.uuid(),offeringVersionId:Ee.uuid(),artifact:Yo.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:dn,check:$n.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"})}),Or=Ee.strictObject(vr.shape).omit({document:!0,offering:!0}).extend({content:vr.shape.content.unwrap()});function _O(e,t){let n=Hc.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 m=r.plans[i],c=a.channels.stripe?.prices.find(d=>d.currency===m?.currency);m&&c&&Object.assign(m,{amountMinor:c.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return vr.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 Qe}from"zod";var Qp={requestId:Qe.uuid(),sourceId:Qe.uuid(),expectedAvailable:mn},Jp=Qe.discriminatedUnion("action",[Qe.strictObject({...Qp,action:Qe.enum(["add","subtract","set_remaining"]),amount:le}),Qe.strictObject({...Qp,action:Qe.literal("edit"),granted:le,expiresAt:Qe.iso.datetime({offset:!0}).nullable(),nextResetAt:Qe.iso.datetime({offset:!0}).nullable(),expectedRevision:Qe.number().int().nonnegative()})]),_a=Qe.strictObject({sourceId:Qe.uuid(),available:mn,held:mn,spent:mn,adjustmentGrantId:Qe.uuid().nullable()}),Wp=_a.extend({granted:mn,expiresAt:Qe.iso.datetime({offset:!0}).nullable(),nextResetAt:Qe.iso.datetime({offset:!0}).nullable(),revision:Qe.number().int().nonnegative()});import{z as ot}from"zod";var Xp=ot.discriminatedUnion("action",[ot.object({action:ot.literal("upsert"),externalId:ot.string().min(1).max(128),name:ot.string().trim().min(1).max(80)}).strict(),ot.object({action:ot.literal("archive"),entityId:ot.uuid()}).strict()]),Yp=ot.object({id:ot.uuid(),externalId:ot.string().min(1).max(128),name:ot.string().min(1).max(80),archived:ot.boolean()}).strict();import{z as Ue}from"zod";import{z as sn}from"zod";var tl=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],el=sn.string().regex(/.+\/.+/),wa=sn.number().min(-100),an=sn.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),Fh=sn.strictObject({input:an,output:an,cache_read:an.optional(),cache_write:an.optional(),reasoning:an.optional(),input_audio:an.optional(),output_audio:an.optional()}),Pa=(e,t)=>sn.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),DO=sn.strictObject({defaultMarkup:wa,providerMarkups:Pa(sn.string().min(1),wa),modelMarkups:Pa(el,wa),customModels:Pa(el,Fh.partial())});import{z as L}from"zod";var cn=L.iso.datetime({offset:!0}),Nt=L.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Nh=L.discriminatedUnion("kind",[L.object({kind:L.literal("absolute"),from:cn,to:cn}).strict(),L.object({kind:L.literal("last_days"),days:L.union([L.literal(1),L.literal(7),L.literal(30),L.literal(90)])}).strict(),L.object({kind:L.literal("billing_cycles"),membershipId:L.uuid(),count:L.number().int().min(1).max(12),includeCurrent:L.boolean()}).strict()]),nl=L.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"),Vh=L.object({key:L.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:L.array(L.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),un=L.object({range:Nh,timezone:nl,filterBy:L.array(Vh).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:L.enum(["hour","day","week","month"]),internal_feature_id:L.uuid().nullable(),entityId:L.uuid().nullable(),topN:L.number().int().min(1).max(50).nullable(),groupBy:L.union([L.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),L.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:L.object({bucket:cn,group:L.string().max(240),isOther:L.boolean(),internal_feature_id:L.uuid(),resourceId:L.uuid()}).strict().nullable(),limit:L.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)"})}),rl=L.object({from:cn,to:cn,interval:L.enum(["hour","day","week","month"]),timezone:nl,rows:L.array(L.object({bucket:cn,group:L.string().max(240),isOther:L.boolean(),internal_feature_id:L.uuid(),resourceId:L.uuid(),consumedUnits:Nt,refundedUnits:Nt,reservedUnits:Nt,charged:Nt,refunded:Nt,reserved:Nt,netUnits:Nt,netCharged:Nt}).strict()).max(100),nextCursor:L.object({bucket:cn,group:L.string().max(240),isOther:L.boolean(),internal_feature_id:L.uuid(),resourceId:L.uuid()}).strict().nullable()}).strict();var zn=Ue.string().regex(/^(0|[1-9]\d{0,29})$/),il=Ue.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Ca=Ue.strictObject({bucket:Ue.iso.datetime({offset:!0}),group:Ue.string().max(240),isOther:Ue.boolean(),internal_feature_id:Ue.uuid()}),ol=Ue.strictObject({...un.shape,groupBy:Ue.union([Ue.enum(["customer","entity","entitlement"]),Ue.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Ca.nullable()}).superRefine((e,t)=>{let n=un.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),al=Ue.strictObject({from:Ue.iso.datetime({offset:!0}),to:Ue.iso.datetime({offset:!0}),interval:un.shape.interval,timezone:un.shape.timezone,rows:Ue.array(Ue.strictObject({...Ca.shape,eventCount:zn,units:il,tokenEventCount:zn,tokens:Ue.strictObject(Object.fromEntries(tl.map(e=>[e,zn]))),totalTokens:zn,providerCostEventCount:zn,providerCostUsd:il,invalidTelemetryEventCount:zn})).max(100),nextCursor:Ca.nullable()});import{z as ke}from"zod";var sl=ke.object({requestId:ke.uuid(),items:ke.array(ke.object({customerId:ke.uuid(),command:Ln.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"),cl=ke.object({batchId:ke.uuid(),after:ke.number().int().min(-1).max(999),limit:ke.number().int().min(1).max(100)}).strict(),ul=ke.object({batchId:ke.uuid(),status:ke.enum(["queued","complete"]),total:ke.number().int().min(1).max(1e3),processed:ke.number().int().min(0).max(1e3),items:ke.array(ke.object({position:ke.number().int().min(0).max(999),customerId:ke.uuid(),idempotencyKey:ke.string().min(1).max(120),status:ke.enum(["queued","accepted","rejected","failed"]),receipt:Zn.nullable(),errorCode:ke.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:ke.number().int().min(0).max(999).nullable()}).strict();import{z as f}from"zod";var Uh=f.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),pl=f.enum(["draft","active","paused","archived"]),ll=f.string().min(1).max(256),ml=f.array(ll).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Gh=f.strictObject({duration:f.enum(["day","week","month","year"]),length:f.number().int().min(1).max(3660)}),$h=f.strictObject({internal_feature_id:f.uuid(),allowance:f.number().nonnegative().max(1e15).nullable(),expiry:Gh.nullable()}),Kh=f.discriminatedUnion("type",[f.strictObject({type:f.literal("feature_grant"),grants:f.array($h).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),f.strictObject({type:f.literal("free_product"),productId:ll,duration:rt}),f.strictObject({type:f.literal("invoice_credits"),amount:f.number().positive().max(1e8),duration:rt,rollover:f.boolean(),productIds:ml})]),Lh=f.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),dl=f.object({key:Lh,name:f.string().trim().min(1).max(80),configuration:Kh}).strict(),fl=f.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),ka=f.object({code:fl,maxUses:f.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:f.boolean()}).strict(),hl=f.object({key:f.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:f.string().trim().min(1).max(80),rewardId:f.uuid(),redeemOn:f.enum(["customer_creation","checkout"]),receivedBy:f.enum(["referrer","all"]),maxRedemptions:f.number().int().min(1).max(1e6).nullable(),productIds:ml,excludeTrial:f.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),gl={id:f.uuid(),projectId:f.uuid(),environmentId:f.uuid(),revision:f.number().int().nonnegative(),status:pl,createdAt:f.iso.datetime({offset:!0}),updatedAt:f.iso.datetime({offset:!0})},Zh=dl.extend(gl).strict(),Hh=hl.safeExtend(gl).strict(),QO=f.strictObject({id:f.uuid(),key:f.string(),name:f.string(),type:Uh,status:pl,ended:f.boolean()}),JO=f.discriminatedUnion("action",[f.object({action:f.literal("save"),id:f.uuid().nullable(),revision:f.number().int().nonnegative(),input:dl}).strict(),f.object({action:f.enum(["activate","pause","resume","archive","delete"]),id:f.uuid(),revision:f.number().int().nonnegative()}).strict()]),WO=f.discriminatedUnion("action",[f.object({action:f.literal("save"),id:f.uuid().nullable(),revision:f.number().int().nonnegative(),input:hl}).strict(),f.object({action:f.enum(["activate","pause","resume","archive","delete"]),id:f.uuid(),revision:f.number().int().nonnegative()}).strict()]),bl=f.object({id:f.uuid(),rewardId:f.uuid(),programId:f.uuid().nullable(),customerId:f.uuid(),referrerId:f.uuid().nullable(),status:f.enum(["pending","applied","unavailable"]),result:f.record(f.string(),f.unknown()).nullable(),createdAt:f.iso.datetime({offset:!0})}).strict(),yl=f.object({code:fl,requestId:f.uuid()}).strict(),xl=f.strictObject({redemptionId:f.uuid(),currency:ce,requestId:f.uuid(),accepted:f.literal(!0)}),Qh=f.strictObject({type:f.literal("checkout"),orderId:f.uuid(),productVersionId:f.uuid(),currency:ce,duration:rt,renewalAmountMinor:f.number().int().positive().max(1e8),status:f.enum(["created","pending","trialing","paid","cancelled","failed"]),url:f.url().nullable()}),Sl=f.discriminatedUnion("type",[Qh,f.strictObject({type:f.literal("subscription"),operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),currency:ce,duration:rt,renewalAmountMinor:f.number().int().positive().max(1e8),status:f.enum(["pending","running","applied","failed"])})]),Il=f.object({programId:f.uuid(),requestId:f.uuid()}).strict(),vl=f.object({id:f.uuid(),programId:f.uuid(),code:ka.shape.code,createdAt:f.iso.datetime({offset:!0})}).strict(),XO=f.object({rows:f.array(Zh).max(100),nextCursor:f.uuid().nullable()}).strict(),YO=f.object({rows:f.array(Hh).max(100),nextCursor:f.uuid().nullable()}).strict(),Jh=ka.extend({id:f.uuid(),redemptions:f.number().int().nonnegative()}).strict(),Wh=f.strictObject({id:f.uuid(),programId:f.uuid().nullable(),customerId:f.uuid().nullable(),referrerId:f.uuid().nullable(),code:f.string().nullable(),status:f.enum(["pending","triggered","applied"]),createdAt:f.iso.datetime({offset:!0})}),ej=f.object({codes:f.array(Jh).max(100),redemptions:f.array(Wh).max(100),customers:f.record(f.uuid(),f.string()),codesCursor:f.uuid().nullable(),redemptionsCursor:f.uuid().nullable()}).strict(),tj=f.discriminatedUnion("action",[f.object({action:f.literal("create"),rewardId:f.uuid(),revision:f.number().int().nonnegative(),input:ka}).strict(),f.object({action:f.literal("remove"),rewardId:f.uuid(),revision:f.number().int().nonnegative(),codeId:f.uuid()}).strict()]);import{z as u}from"zod";import{z as R}from"zod";var St={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},jr=e=>new Set(e).size===e.length,Ra=R.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Xh=R.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Ar=R.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"))),Yh=R.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Ol=R.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var jl=R.strictObject({id:R.uuid(),repo:Xh,platform:R.enum(["github","gitlab","bitbucket"]),branches:R.array(Ar).min(1).max(4).refine(jr),workflow:R.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:R.array(R.uuid()).min(1).max(4).refine(jr),include:R.array(Ol).min(1).max(16),exclude:R.array(Ol).max(16),methods:R.array(R.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(jr),maxAgeHours:R.number().int().min(1).max(720)}),Al=jl.extend({revision:R.number().int().positive()}),ij=R.strictObject({repository:jl,expectedRevision:R.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),_l=R.strictObject({repositoryId:R.uuid(),branch:Ar}),eg=R.array(Ra).max(St.keys).refine(jr),wl=R.strictObject({repository:Al.omit({keyIds:!0}),branch:Ar,keys:eg,keySetHash:R.string().regex(/^[a-f0-9]{64}$/)}),tg=R.strictObject({filePath:Yh,startingLineNumber:R.number().int().min(1).max(1e7)}),Ea=R.strictObject({protocol:R.literal(1),repositoryId:R.uuid(),branch:Ar,workflow:R.string().max(200),configurationRevision:R.number().int().positive(),keySetHash:R.string().regex(/^[a-f0-9]{64}$/),commit:R.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:R.uuid(),runNumber:R.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:R.number().int().min(1).max(1e4),scannerVersion:R.literal("1"),scannedAt:R.iso.datetime({offset:!0}),coverage:R.strictObject({complete:R.literal(!0),files:R.number().int().min(0).max(St.files),sourceBytes:R.number().int().min(0).max(St.sourceBytes),unresolvedCalls:R.number().int().min(0).max(1e6),unsupportedFiles:R.number().int().min(0).max(St.files)}),features:R.array(R.strictObject({key:Ra,refs:R.array(tg).max(St.referencesPerKey)})).max(St.keys)}).superRefine((e,t)=>{jr(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)>St.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Ma=R.strictObject({scanId:R.uuid(),commit:R.string(),receivedAt:R.string(),references:R.number().int().nonnegative(),removedReferences:R.number().int().nonnegative()}),ng=Ma.extend({repositoryId:R.uuid(),branch:Ar,workflow:R.string(),digest:R.string(),configurationRevision:R.number().int().positive(),runNumber:R.number().int().positive(),runAttempt:R.number().int().positive(),scannedAt:R.string(),keySetHash:R.string(),coverage:Ea.shape.coverage}),rg=R.strictObject({repositories:R.array(Al).max(St.repositories),scans:R.array(ng).max(St.repositories*St.branches)}),ig=R.strictObject({key:Ra,references:R.number().int().nonnegative(),coveredTargets:R.number().int().nonnegative(),expiredTargets:R.number().int().nonnegative(),uncertainTargets:R.number().int().nonnegative()}),oj=R.strictObject({available:R.boolean().default(!0),settings:rg,expectedTargets:R.number().int().min(0).max(80),features:R.array(ig).max(2001),truncated:R.boolean()});import{z as ee}from"zod";var Xe=ee.string().min(1).max(200),Bi=ee.iso.datetime({offset:!0}),_r=ee.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Ta=ee.number().int().min(0).max(1e12),kl=ee.number().int().min(1).max(1e12),Pl={...Le,type:ee.literal("coupon.redeemed"),grantId:ee.uuid()},Cl={...Le,type:ee.literal("usage.observed"),merchantTransactionId:Xe,resource:Xe,unit:Xe,quantity:kl},og=ee.strictObject({...Le,type:ee.literal("fulfillment.updated"),operationId:ee.uuid(),merchantFulfillmentId:Xe,status:ee.enum(["pending","applied","failed"])}),ag=ee.strictObject({...Le,type:ee.literal("benefit.claimed"),merchantBenefitId:Xe,resource:Xe,unit:Xe,quantity:kl,expiresAt:Bi.nullable(),revision:_r}),sg=ee.strictObject({...Le,type:ee.literal("benefit.closed"),merchantBenefitId:Xe,status:ee.enum(["failed","expired","canceled"]),revision:_r}),cg=ee.strictObject({...Le,type:ee.literal("benefit.updated"),merchantBenefitId:Xe,status:ee.enum(["active","expired","revoked"]),remainingQuantity:Ta.nullable(),expiresAt:Bi.nullable(),revision:_r}),ug=ee.strictObject({...Le,type:ee.literal("authorization.updated"),merchantAuthorizationId:Xe,kind:ee.literal("auto_topup"),status:ee.enum(["pending","effective","revoked","failed"]),termsReference:Xe.nullable(),revision:_r}),pg=ee.strictObject({...Le,type:ee.literal("balance.observed"),resource:Xe,unit:Xe,availableQuantity:Ta,reservedQuantity:Ta,periodStartsAt:Bi.nullable(),periodEndsAt:Bi.nullable(),revision:_r}),Rl=ee.union([ee.discriminatedUnion("type",[...Ms,og,ag,sg,cg,ug,pg]),ee.strictObject({...Pl,productVersionId:ee.uuid(),subscriptionId:ee.string().trim().min(1).max(255)}),ee.strictObject({...Pl,merchandiseId:ee.uuid()}),ee.strictObject({...Cl,operation:ee.literal("consume")}),ee.strictObject({...Cl,operation:ee.literal("reverse"),reversalOf:Xe})]),El=ee.strictObject({id:ee.uuid(),eventId:ee.string().min(1).max(200),source:ee.literal("merchant"),providerVerified:ee.literal(!1),outcome:ee.string().min(1).max(100)});import{z as q}from"zod";var Ml=cp,lg=Ml.extend({invoice_id:Ml.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Da=q.strictObject({name:q.string().trim().min(1).max(255),memo:q.string().max(1e4).nullable().optional(),footer:q.string().max(1e4).nullable().optional(),net_terms_days:q.number().int().positive().nullable().optional()}),mg=Da.extend({id:q.string().min(1).max(255),created_at:q.number().nullable()}),Tl=q.strictObject({items:q.array(mg).max(50),nextCursor:q.uuid().nullable()}),mj=q.discriminatedUnion("action",[q.strictObject({action:q.literal("create"),requestId:q.uuid(),values:Da}),q.strictObject({action:q.literal("update"),id:q.string().min(1).max(255),values:Da}),q.strictObject({action:q.literal("delete"),id:q.string().min(1).max(255)})]),Dl=q.discriminatedUnion("action",[q.strictObject({action:q.literal("create"),requestId:q.uuid(),params:Tn}),q.strictObject({action:q.enum(["finalize","send","pay","void"]),requestId:q.uuid(),invoiceId:q.uuid()}),q.strictObject({action:q.literal("reissue"),requestId:q.uuid(),invoiceId:q.uuid(),params:lg})]),qa=q.strictObject({id:q.uuid(),customerId:q.uuid(),providerInvoiceId:q.string().nullable(),status:q.enum(["draft","open","paid","void","uncollectible"]),currency:q.string(),totalMinor:q.string().regex(/^-?\d+$/),paidMinor:q.string().regex(/^\d+$/),refundedMinor:q.string().regex(/^\d+$/),hostedInvoiceUrl:q.url().nullable(),createdAt:q.number(),collectionMethod:q.enum(["send_invoice","charge_automatically"]).nullable()}),ql=qa.extend({lines:q.array(q.strictObject({id:q.uuid(),description:q.string(),amountMinor:q.string().regex(/^-?\d+$/),netAmountMinor:q.string().regex(/^-?\d+$/),quantity:q.number().nullable(),periodStart:q.number().nullable(),periodEnd:q.number().nullable()})).max(1e3)}),Fn=q.strictObject({taskId:q.uuid(),status:q.enum(["ready","running","done","dead"]),invoice:qa.nullable(),errorCode:q.string().nullable()}),Bl=q.strictObject({items:q.array(qa).max(50),nextCursor:q.uuid().nullable(),operations:q.array(Fn).max(50),operationsLimited:q.boolean()});var dg=u.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"]),zl={scope:me,permissions:u.array(dg),expiresAt:u.iso.datetime().nullable()},oA=u.discriminatedUnion("kind",[u.object({...zl,kind:u.literal("server"),keyId:u.string().min(1)}),u.object({...zl,kind:u.literal("customer"),customerId:u.string().min(1),identityKind:u.enum(["identified","guest"]),expiresAt:u.iso.datetime()})]),O=u.object({requestId:u.uuid(),scope:me}).strict(),fg=Cc.safeExtend({fingerprint:ai.optional()}).strict(),hg=O.extend({customer:An,created:u.boolean()});function Fl(){return O.extend({offer:cr.nullable(),reason:Dc.nullable()})}var v={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Qu,response:O.extend({message:u.object({messageId:u.uuid(),channel:xr,acceptedAt:u.iso.datetime({offset:!0}),status:u.enum(["accepted","sending","completed","canceled"]),replayed:u.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:u.strictObject({messageId:u.uuid()}),response:O.extend({message:u.object({id:u.uuid(),channel:xr,status:u.enum(["accepted","sending","completed","canceled"]),deliveries:u.array(u.object({id:u.uuid(),status:Wu,attempts:u.number().int().nonnegative(),receipts:u.array(u.object({kind:Xu,occurredAt:u.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Yc,response:O.extend({installation:hi})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:eu,response:O.extend({installation:hi})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:fi,response:O.extend({installation:hi})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:u.strictObject({channel:xr}),response:O.extend({preference:ta})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Ju,response:O.extend({preference:ta})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:u.strictObject({cursor:u.uuid().optional()}),response:O.extend({templates:Tl})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:u.strictObject({customerId:u.uuid(),params:Tn}),response:O.extend({preview:ha})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:u.strictObject({customerId:u.uuid(),requestId:u.uuid(),params:Tn}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:O.extend({operation:Fn})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:u.strictObject({customerId:u.uuid(),command:Dl}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:O.extend({operation:Fn})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:u.strictObject({customerId:u.uuid(),taskId:u.uuid()}),response:O.extend({operation:Fn})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:u.strictObject({customerId:u.uuid(),cursor:u.uuid().optional()}),response:O.extend({invoices:Bl})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:u.strictObject({customerId:u.uuid(),invoiceId:u.uuid()}),response:O.extend({invoice:ql})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:_l,response:O.extend({config:wl})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Ea,response:O.extend({receipt:Ma})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:u.strictObject({}),response:O.extend({payload:So})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:ac,response:O.merge(cc)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:pc,response:O.merge(lc)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:u.strictObject({customerId:u.uuid(),sourceId:u.uuid()}),response:O.extend({balance:Wp})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:u.strictObject({customerId:u.uuid(),command:Jp}),response:O.extend({balance:_a})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:u.strictObject({internal_feature_id:u.uuid(),customerId:u.uuid().optional(),entityId:u.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:O.extend({internal_feature_id:u.uuid(),config:oa,model_markups:Ii})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:u.strictObject({customerId:u.uuid(),query:ds}),response:O.extend({usage:Zi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:u.strictObject({customerId:u.uuid(),command:fs}),response:O.extend({usage:Zi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:u.strictObject({customerId:u.uuid(),command:Fu}),response:O.extend({grant:ua})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Nu,response:O.extend({grants:Vu})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:u.union(Vp.options.map(e=>e.extend({customerId:u.uuid().optional(),customerToken:u.string().regex(bt).optional()}))),response:O.extend({operation:Up})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:kp.extend({customerId:u.uuid().optional()}),response:O.extend({setup:Ia})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Rp.extend({customerId:u.uuid().optional()}),response:O.extend({setup:Ia})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:wp.safeExtend({customerId:u.uuid()}),response:O.extend({batch:Sr})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Ri.extend({customerId:u.uuid()}),response:O.extend({batch:Sr})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Ri.extend({customerId:u.uuid()}),response:O.extend({batch:Sr})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Ri.extend({customerId:u.uuid()}),response:O.extend({batch:Sr})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:u.discriminatedUnion("action",[Ei.options[0].extend({customerId:u.uuid()}),Ei.options[1].extend({customerId:u.uuid()}),Ei.options[2].extend({customerId:u.uuid()})]),response:O.extend({trial:Sa})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Pp.extend({customerId:u.uuid()}),response:O.extend({trial:Sa})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Di,response:O.extend({subscriptions:zp})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Di,response:O.extend({purchases:Fp})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Dp,response:O.extend({conflicts:Np})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:qp,response:O.extend({resolution:Bp})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Mp,response:O.extend({verification:Tp})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:xp.safeExtend({...Mn,customerId:u.uuid().optional()}),response:O.extend({quote:Dn})},recordMerchantEvent:{replay:"immutable_event",method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Rl,response:O.extend({record:El})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:on.extend({customerId:u.uuid().optional(),intent:u.enum(["confirm","cancel"]).optional(),merchantConfirmation:nr.optional()}),response:O.extend({operation:qn})},readSubscriptionOperation:{replay:"read",method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:on.extend({customerId:u.uuid().optional()}),response:O.extend({operation:qn})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:vp.safeExtend({customerId:u.uuid().optional()}),response:O.extend({quote:jp})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:on.extend({customerId:u.uuid().optional(),intent:u.enum(["confirm","cancel"]).optional(),merchantConfirmation:nr.optional()}),response:O.extend({operation:ga})},readSubscriptionUpdate:{replay:"read",method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:on.extend({customerId:u.uuid().optional()}),response:O.extend({operation:ga})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Ap.safeExtend({customerId:u.uuid()}),response:O.extend({quote:ya})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:on.extend({customerId:u.uuid(),merchantConfirmation:nr.optional()}),response:O.extend({operation:ki})},readRefund:{replay:"read",method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:on.extend({customerId:u.uuid()}),response:O.extend({operation:ki})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:wu,response:O.extend({controls:ca})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Su,response:O.extend({prepared:vu})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Ou,response:O.extend({authorization:Oi})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Eu,response:O.extend({coupons:Mu})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:ju,response:O.extend({authorization:Oi})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:ku,response:O.extend({invoices:Ru})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Cu.extend({customerId:u.uuid()}),response:O.extend({operation:Fn})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Pu,response:O.extend({invoice:gr})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:u.object({customerId:u.uuid(),command:_u}).strict(),response:O.extend({controls:ca})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:u.object({customerId:u.uuid(),command:Xp}).strict(),response:O.extend({entity:Yp})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:u.strictObject({customerId:u.uuid().nullable(),query:ol}),response:O.extend({analytics:al})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:u.object({customerId:u.uuid().nullable(),query:un}).strict(),response:O.extend({analytics:rl})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:sl,response:O.extend({batchId:u.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:cl,response:O.extend({batch:ul})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:es.extend({customerId:u.string().min(1).optional()}),response:O.extend({check:$n})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:u.strictObject({kind:Tt,selector:u.discriminatedUnion("type",[u.strictObject({type:u.literal("resource"),id:u.uuid()}),u.strictObject({type:u.literal("version"),id:u.uuid()})]),customerId:u.string().min(1).optional()}),response:O.extend({content:ho})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Hp,response:O.extend({paywall:Or})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:u.strictObject({processContext:_i.optional(),...Mn,selector:Lp,customerId:u.string().min(1).optional(),commerce:Tr,requirement:pn.optional()}),response:O.extend({offering:Zp,candidates:u.array(ts).max(20),availability:u.array(u.strictObject({productVersionId:u.uuid(),available:u.boolean(),reason:u.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:$n.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:u.object({customerId:u.uuid().optional(),entityId:u.uuid().optional()}).strict(),response:O.extend({holdings:hs})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:u.object({customerId:u.uuid().optional(),query:gs}).strict(),response:O.extend({ledger:bs})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Uu.extend({customerId:u.uuid().optional()}),response:O.extend({detail:Gu})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:pa.safeExtend({customerId:u.uuid().optional()}),response:O.extend({statement:$u})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:u.object({customerId:u.uuid().optional(),command:Ln.options[0]}).strict(),response:O.extend({quote:ms})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:u.strictObject({customerId:u.uuid(),command:u.union([u.strictObject({eventName:u.string().min(1),quantity:le.optional(),properties:It.optional(),entityId:u.uuid().optional(),idempotencyKey:u.string().min(1).max(120)}),u.strictObject({internal_feature_id:u.uuid(),quantity:le.optional(),properties:It.optional(),entityId:u.uuid().optional(),idempotencyKey:u.string().min(1).max(120)})])}),response:O.extend({receipts:u.array(Zn).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:u.object({customerId:u.uuid(),command:Ln.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:O.extend({receipt:Zn})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:yl,response:O.extend({redemption:bl})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Il,response:O.extend({referralCode:vl})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:xl,response:O.extend({checkout:Sl})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Lu,response:O.extend({seats:da})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Zu,response:O.extend({seats:da})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:fg,response:hg},getCustomer:{replay:"read",method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:qo,response:O.extend({customer:An})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Ec,response:O.extend(Mc.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Rc,response:O.extend(kc.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:u.object({customerId:u.uuid()}).strict(),response:O.extend(bn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:u.strictObject({}),response:O.extend(bn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:u.strictObject({customerId:u.uuid(),sessionId:u.uuid().optional()}),response:O.extend({revoked:u.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:u.strictObject({guestToken:u.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ai.optional()}),response:O.extend({customerId:u.uuid(),guestToken:u.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:u.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:u.strictObject({guestToken:u.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:O.extend(bn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:u.strictObject({guestToken:u.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:u.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:u.uuid()}),response:O.extend({customer:An,switched:u.boolean(),replayed:u.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:u.strictObject({code:u.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:u.uuid()}),response:Fl()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:u.object({}).strict(),response:O.extend({offers:u.array(cr)})},grantModelBenefit:{method:"POST",path:"benefits/model-usage/grant",permission:"offers:grant",audience:"server",request:nu,response:O.extend({operation:na})},readModelBenefit:{method:"POST",path:"benefits/model-usage/read",permission:"offers:grant",audience:"server",request:ru,response:O.extend({operation:na})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:u.object({customerId:u.string().min(1).max(255).optional(),couponId:u.uuid(),...Mn,requestId:u.uuid(),couponContentDigest:u.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Fl()}},aA={recordMerchantEvent:v.recordMerchantEvent,sendMessage:v.sendMessage,readMessage:v.readMessage,bindPushInstallation:v.bindPushInstallation,readPushInstallation:v.readPushInstallation,updatePushAddress:v.updatePushAddress,readMessagingPreference:v.readMessagingPreference,setMessagingPreference:v.setMessagingPreference,listInvoiceTemplates:v.listInvoiceTemplates,previewInvoice:v.previewInvoice,createInvoice:v.createInvoice,manageInvoice:v.manageInvoice,readInvoiceOperation:v.readInvoiceOperation,listInvoices:v.listInvoices,getInvoice:v.getInvoice,getCodeReferenceConfig:v.getCodeReferenceConfig,submitCodeReferences:v.submitCodeReferences,getFeatures:v.getFeatures,evaluateFeatures:v.evaluateFeatures,trackEvents:v.trackEvents,setupPayment:v.setupPayment,readPaymentSetup:v.readPaymentSetup,previewSubscriptionBatch:v.previewSubscriptionBatch,confirmSubscriptionBatch:v.confirmSubscriptionBatch,readSubscriptionBatch:v.readSubscriptionBatch,abandonSubscriptionBatch:v.abandonSubscriptionBatch,manageSubscriptionTrial:v.manageSubscriptionTrial,readSubscriptionTrial:v.readSubscriptionTrial,listSubscriptions:v.listSubscriptions,listPurchases:v.listPurchases,listSubscriptionConflicts:v.listSubscriptionConflicts,retrySubscriptionConflict:v.retrySubscriptionConflict,readAiPricing:v.readAiPricing,readUsage:v.readUsage,setUsage:v.setUsage,previewRefund:v.previewRefund,refund:v.refund,readRefund:v.readRefund,previewUpdate:v.previewUpdate,update:v.update,readSubscriptionUpdate:v.readSubscriptionUpdate,restoreNativePurchase:v.restoreNativePurchase,verifySubscriptions:v.verifySubscriptions,previewAttach:v.previewAttach,attach:v.attach,readSubscriptionOperation:v.readSubscriptionOperation,manageBalanceGrant:v.manageBalanceGrant,readBalanceSource:v.readBalanceSource,adjustBalance:v.adjustBalance,listBalanceGrants:v.listBalanceGrants,readBillingControls:v.readBillingControls,prepareBillingAuthorization:v.prepareBillingAuthorization,confirmBillingAuthorization:v.confirmBillingAuthorization,setBillingCoupons:v.setBillingCoupons,revokeBillingAuthorization:v.revokeBillingAuthorization,listBillingInvoices:v.listBillingInvoices,confirmBillingAdjustment:v.confirmBillingAdjustment,prepareBillingAdjustment:v.prepareBillingAdjustment,manageBillingLimits:v.manageBillingLimits,createCustomer:v.createCustomer,getCustomer:v.getCustomer,listCustomers:v.listCustomers,updateCustomer:v.updateCustomer,createSession:v.createSession,refreshSession:v.refreshSession,revokeSessions:v.revokeSessions,createGuestCustomer:v.createGuestCustomer,resumeGuestSession:v.resumeGuestSession,claimGuestCustomer:v.claimGuestCustomer,checkEntitlement:v.checkEntitlement,resolveOffering:v.resolveOffering,resolveContent:v.resolveContent,resolvePaywall:v.resolvePaywall,readHoldings:v.readHoldings,readLedger:v.readLedger,readBillingInvoice:v.readBillingInvoice,readCreditStatement:v.readCreditStatement,quoteBalance:v.quoteBalance,trackUsage:v.trackUsage,mutateBalance:v.mutateBalance,manageUsageEntity:v.manageUsageEntity,readUsageAnalytics:v.readUsageAnalytics,readCreditAnalytics:v.readCreditAnalytics,submitUsageBatch:v.submitUsageBatch,readUsageBatch:v.readUsageBatch,listOffers:v.listOffers,grantOffer:v.grantOffer,grantModelBenefit:v.grantModelBenefit,readModelBenefit:v.readModelBenefit,redeemCoupon:v.redeemCoupon,redeemReward:v.redeemReward,createReferralCode:v.createReferralCode,claimRewardProduct:v.claimRewardProduct,readSeats:v.readSeats,manageSeat:v.manageSeat};import{z as Ba}from"zod";var wr=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function za(e,t,n){let r={},i,a,m,c="next",d;switch(e.type){case"entry":d=e.next;break;case"condition":{let I=e.cases.findIndex(g=>Li(t.attributes??{},g.condition,t.savedGroups??{}));c=I<0?"default":`case:${I}`,d=I<0?e.default:e.cases[I].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new wr("Required GB Feature is unavailable");i=Kn(e.featureKey,t),m=i.value,Object.assign(r,Qt(e,{value:m})),d=e.next;break;case"split":{let I=n[e.experimentId];if(!I)throw new wr("Required GB Experiment is unavailable");if(a=cs(I,t),m=a.value,c=a.inExperiment&&!a.passthrough&&typeof m=="string"?m:"notParticipating",d=c==="notParticipating"?e.notParticipating:e.routes[c],!d)throw new wr("Experiment Variation has no published route");break}case"offering":{let I=e.configuration.source==="fixed"?e.configuration.versionId:Kn(e.configuration.featureKey,t).value;m={type:"offering_version",id:Ba.uuid().parse(I)},Object.assign(r,Qt(e,{value:m})),d=e.next;break}case"coupon":case"coupons":m=e.type==="coupons"?e.couponIds.map(I=>({type:"reward",id:I})):{type:"reward",id:e.couponId},Object.assign(r,Qt(e,{value:m})),d=e.next;break}return{port:c,target:d,projections:r,...m===void 0?{}:{value:m},...i?{feature:i}:{},...a?{experiment:a}:{}}}function fA(e,t,n){Ba.uuid().parse(e),Ba.number().int().nonnegative().parse(t);let r=Rr(Er(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 w}from"zod";var Vt=w.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gg=w.enum(["running","waiting","completed","closed","ineligible","failed"]),Fa=w.discriminatedUnion("type",[To,w.strictObject({type:w.literal("wait"),receiptId:w.uuid(),kind:w.enum(["timer","event","operation"]),deadline:w.iso.datetime({offset:!0}).nullable(),eventName:Vt.optional()}),w.strictObject({type:w.literal("open_url"),receiptId:w.uuid(),url:Fo,openIn:No}),w.strictObject({type:w.literal("event"),receiptId:w.uuid(),event:Vt})]),bg=w.strictObject({type:w.literal("funnel"),id:w.uuid(),versionId:w.uuid()}),yg={id:Vt,presentation:vt,outputs:w.array(Vt).max(250),inputs:Ji,values:w.record(w.string(),ne).optional(),offeringKey:Re.optional(),capabilities:dn,customerData:js,dataCursors:w.record(Vt,zr.nullable())},xg=w.strictObject({...yg,content:w.strictObject({type:w.literal("document"),document:et})}),Pr=w.strictObject({id:w.uuid(),source:bg,revision:w.number().int().nonnegative(),visit:w.number().int().nonnegative(),nodeId:Vt,nodeType:w.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:gg,stopped:w.boolean(),canBack:w.boolean(),authenticated:w.boolean(),locale:w.string().min(1).max(35),answers:Gt,parameters:gt,variables:w.record(w.string(),ne),output:ne.nullable(),screen:xg.nullable(),paywall:w.strictObject({receiptId:w.uuid(),resolution:w.union([vr,Or]),quote:Dn.nullable(),operation:qn.nullable(),purchaseRequestId:w.uuid().nullable(),selectionGeneration:w.number().int().nonnegative().optional(),canReselect:w.boolean().optional()}).nullable(),instruction:Fa.nullable(),pendingRequest:w.strictObject({requestId:w.uuid(),authenticationRequired:w.boolean()}).nullable(),runExpiresAt:w.iso.datetime({offset:!0}),credentialExpiresAt:w.iso.datetime({offset:!0}).nullable()}),Nn=w.strictObject({scope:me,run:Pr,settlement:w.strictObject({requestId:w.uuid(),state:w.enum(["pending","unknown","settled"]),operationId:w.uuid().nullable(),receiptId:w.uuid().nullable().optional()}).optional(),purchase:w.strictObject({receiptId:w.uuid(),quote:Dn.nullable(),operation:qn.nullable(),canReselect:w.boolean().optional()}).optional(),review:w.strictObject({activeOperationId:w.uuid().nullable(),pages:w.array(w.strictObject({receiptId:w.uuid(),nodeId:Vt,visit:w.number().int().nonnegative()})).max(100),page:w.strictObject({receiptId:w.uuid(),nodeId:Vt,visit:w.number().int().nonnegative(),document:et,answers:Gt,inputs:Ji,values:w.record(w.string(),ne).optional()}).nullable(),coupons:w.array(w.strictObject({grantId:w.uuid(),status:w.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:w.string().nullable()})).max(100),purchases:w.array(w.strictObject({receiptId:w.uuid(),operationId:w.uuid(),status:w.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:w.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:w.uuid().optional()}),Ut=Nn.extend({run:Pr.extend({paywall:Pr.shape.paywall.unwrap().extend({resolution:Or}).nullable()})});var kA="X-Indiana-Server-Key";import{z}from"zod";import{z as K}from"zod";import{z as Me}from"zod";var Sg=Me.strictObject({selector:Me.string().min(1).max(2048),action:Me.enum(["set","append","remove"]),attribute:Me.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:Me.string().max(5e4).optional(),parentSelector:Me.string().max(2048).optional(),insertBeforeSelector:Me.string().max(2048).optional()}),Ig=Me.strictObject({variation:Me.string().min(1).max(128),description:Me.string().max(2e3).default(""),css:Me.string().max(1e5).default(""),js:Me.string().max(1e5).default(""),domMutations:Me.array(Sg).max(200).default([]),iam:bc.optional(),renderGuard:Yr.optional()}),Na=Ig.omit({variation:!0,description:!0,iam:!0}),vg=vn.omit({variations:!0,active:!0}).extend({changeId:Me.string().regex(/^[a-f0-9]{64}$/),variations:Me.tuple([Na,Na]).rest(Na).refine(e=>e.length<=20)}),Nl=Me.strictObject({trackExposures:Me.boolean(),environmentId:Me.uuid(),generation:Me.string().regex(/^[a-f0-9]{64}$/),experiments:Me.array(vg).max(100),savedGroups:or});var Cr=K.string().regex(/^[a-f0-9]{64}$/),UA=K.strictObject({iam:Cr,executionContracts:K.union([K.tuple([K.literal("funnel-run/1")]),K.tuple([K.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Og=K.strictObject({release:Cr,render:Yr,button:K.strictObject({selector:K.string().min(1).max(512),elementKey:K.string().min(1).max(256),tag:K.enum(["button","a","input"])}).nullable()}),GA=K.strictObject({scope:me.extend({environmentId:K.uuid()}),release:Cr,validatedAt:K.iso.datetime({offset:!0}),validUntil:K.iso.datetime({offset:!0}),entries:K.array(K.strictObject({id:K.uuid(),funnelId:K.uuid(),versionId:K.uuid(),event:K.enum(["screen_enter","button_click"]),target:Og})).max(4e3)}),Vl=K.strictObject({operation:K.literal("entry_start"),funnelId:K.uuid(),versionId:K.uuid(),entryId:K.uuid(),release:Cr,requestId:K.uuid(),locale:K.string().min(1).max(35).default("en")}),Ul=K.strictObject({scope:me,suppressed:K.literal(!0),reason:K.enum(["frequency","in_progress"]),retryAt:K.iso.datetime({offset:!0}).nullable()}),$A=K.strictObject({experimentId:K.uuid(),splitNodeId:K.string().min(1).max(128)}),jg=K.strictObject({experimentId:K.uuid(),experimentKey:K.string().min(1).max(128),variationKey:K.string().min(1).max(128),inExperiment:K.boolean(),generation:K.string().min(1).max(256)}),zi=K.strictObject({operation:K.literal("page_experiments"),release:Cr,usedReceiptIds:K.array(K.uuid()).max(20).default([]),customerToken:K.string().regex(bt).optional()}),KA=K.strictObject({scope:me,runId:K.uuid(),assignments:K.array(jg.extend({receiptId:K.uuid()})).max(100),payload:Nl});var ht=z.literal(vo),Ag=z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Va=z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Gl=z.discriminatedUnion("type",[z.strictObject({type:z.literal("guest"),guestToken:Va}),z.strictObject({type:z.literal("customer"),customer:Pt,customerData:qt.optional()})]),Ua=z.strictObject({id:z.uuid(),runId:z.uuid(),customerId:z.uuid(),requestId:z.uuid(),acceptedAt:z.iso.datetime({offset:!0})}),_g=z.strictObject({participantId:z.uuid(),startedAs:z.enum(["guest","identified"]),binding:Ua.omit({runId:!0,requestId:!0}).nullable()}),wg=z.union([Fa,z.strictObject({type:z.literal("authentication_required"),reason:z.enum(["customer_required","customer_experiment_required"]),nodeId:z.string().min(1).max(64),visit:z.number().int().nonnegative()})]),Pg=Pr.omit({authenticated:!0}).extend({identity:_g,instruction:wg.nullable()}),Cg=z.discriminatedUnion("operation",[We.options[2].omit({customerToken:!0}),We.options[3].omit({customerToken:!0}),We.options[4].omit({customerToken:!0}),We.options[5].omit({customerToken:!0}),We.options[6].omit({customerToken:!0}),We.options[7].omit({customerToken:!0})]),Fi={contract:ht,customerToken:z.string().regex(bt)},$l={contract:ht,requestId:z.uuid(),runToken:Ag,externalUserId:Pt.options[1].shape.value},Kl=z.discriminatedUnion("operation",[z.strictObject({contract:ht,operation:z.literal("describe")}),z.strictObject({contract:ht,operation:z.literal("start"),source:Gl,funnelId:We.options[0].shape.funnelId,requestId:z.uuid(),locale:We.options[0].shape.locale,parameters:We.options[0].shape.parameters}),Vl.omit({operation:!0}).extend({contract:ht,operation:z.literal("entry_start"),source:Gl}),z.strictObject({...$l,operation:z.literal("bind_customer"),guestToken:Va,claimRequestId:z.uuid(),expectedBindingId:z.null()}),z.strictObject({...$l,operation:z.literal("binding_status"),guestToken:Va.optional()}),We.options[1].omit({operation:!0,customerToken:!0}).extend({...Fi,operation:z.literal("get"),settlementBindingId:z.uuid().nullable().optional()}),We.options[8].omit({operation:!0,customerToken:!0}).extend({...Fi,operation:z.literal("review")}),zi.omit({customerToken:!0}).extend(Fi),z.strictObject({...Fi,operation:z.literal("command"),identity:z.strictObject({bindingId:z.uuid().nullable()}),command:Cg})]),kg=Nn.omit({run:!0}).extend({contract:ht,run:Pg,settlement:Nn.shape.settlement.unwrap().extend({accepted:z.boolean().nullable().optional()}).optional()}),t_=Ul.extend({contract:ht}),n_=z.discriminatedUnion("operation",[Kl.options[1].omit({contract:!0,source:!0,requestId:!0}),Kl.options[2].omit({contract:!0,source:!0,requestId:!0})]),r_=kg.extend({binding:Ua,outcome:z.enum(["bound","already_bound"]),replayed:z.boolean()}),i_=z.discriminatedUnion("state",[z.strictObject({contract:ht,scope:me,state:z.literal("not_accepted")}),z.strictObject({contract:ht,scope:me,state:z.literal("conflict")}),z.strictObject({contract:ht,scope:me,state:z.literal("bound"),binding:Ua})]),o_=z.strictObject({contract:ht,scope:me,keyId:z.uuid(),operations:z.array(z.string()).max(20)});import{z as Je}from"zod";import{z as Ni}from"zod";var p_=Ni.strictObject({operation:Ni.literal("renew_run"),runId:Ni.uuid(),customerId:Ni.uuid()}),Ll=Nn.refine(e=>!!e.runToken,"Renewal returns a credential"),Zl=Ut.refine(e=>!!e.runToken,"Renewal returns a credential");var y_=Je.discriminatedUnion("operation",[Je.strictObject({operation:Je.literal("campaign_decide"),...Bo}).refine(Xt,Yt),Je.strictObject({operation:Je.literal("campaign_start"),funnelId:Je.uuid(),requestId:Je.uuid(),customer:Pt,customerData:qt.optional(),locale:Je.string().min(1).max(35),parameters:gt,cooldownSeconds:Je.number().int().min(1).max(2592e3)}).refine(Xt,Yt)]),Rg=Je.union([Je.strictObject({scope:me,suppressed:Je.literal(!0),reason:Je.enum(["frequency","in_progress"]),retryAt:Je.iso.datetime({offset:!0})}),Ll]),x_=Je.union([Rg.options[0],Zl]);import{z as se}from"zod";var Vn=se.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ql=se.strictObject({entry:Vn,nodes:se.array(se.strictObject({id:Vn,type:se.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:se.record(se.string(),Vn),writes:se.record(Re,Re),resources:se.strictObject({screenId:Vn.optional(),paywallVersionId:se.uuid().optional(),couponId:se.uuid().optional(),couponIds:se.array(se.uuid()).max(20).optional(),experimentId:se.uuid().optional(),featureKey:se.string().optional(),offeringVersionId:se.uuid().optional()})})).min(1).max(500)}),Hl={scope:me,funnelId:se.uuid(),versionId:se.uuid(),evaluationRevision:se.number().int().nonnegative(),expiresAt:se.iso.datetime({offset:!0}).nullable(),topology:Ql},Un=se.discriminatedUnion("evaluationMode",[se.strictObject({...Hl,evaluationMode:se.literal("local"),growth:wt,conditions:se.record(Vn,se.array(se.strictObject({condition:lt,port:se.string()})))}),se.strictObject({...Hl,evaluationMode:se.literal("remote")})]),Eg=Un.options[0].extend({evaluation:se.strictObject({maxTransitions:se.number().int().min(1).max(1e4),variables:se.record(Re,xn),outputSchema:yn,terminals:se.record(Vn,se.strictObject({outcome:se.enum(["completed","closed","ineligible","failed"]),output:sr.nullable()}))})});function Mg(e){return Ql.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(m=>m.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,m)=>{n[`case:${m}`]=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=se.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 Tg(e){let t=zt.parse(e.document),n=e.evaluationMode==="local"?wt.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:Mg(t)};return Un.parse(e.evaluationMode==="remote"?r:{...r,growth:li(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,m)=>({condition:a.condition,port:`case:${m}`}))]))})}function C_(e){let t=Tg(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=zt.parse(e.document);return Eg.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 N}from"zod";var Ge=We.options,Dg=N.discriminatedUnion("operation",[Ge[1].omit({customerToken:!0}),Ge[2].omit({customerToken:!0}),Ge[3].omit({customerToken:!0}),Ge[4].omit({customerToken:!0}),Ge[5].omit({customerToken:!0}),Ge[6].omit({customerToken:!0}),Ge[7].omit({customerToken:!0}),Ge[8].omit({customerToken:!0}),zi.omit({customerToken:!0})]),qg=N.strictObject({receiptId:N.uuid(),operationId:N.uuid()}),q_=N.discriminatedUnion("operation",[N.strictObject({operation:N.literal("recover_start"),intent:N.enum(["lookup","resume"]),start:N.strictObject({requestId:Ge[0].shape.requestId,funnelId:Ge[0].shape.funnelId,locale:Ge[0].shape.locale,parameters:Ge[0].shape.parameters})}),N.strictObject({operation:N.literal("recover_run"),runId:N.uuid(),funnelId:N.uuid()}),N.strictObject({operation:N.literal("recover_purchase"),runId:N.uuid(),funnelId:N.uuid(),purchase:qg}),N.strictObject({operation:N.literal("settle_command"),runId:N.uuid(),funnelId:N.uuid(),requestId:N.uuid(),command:N.discriminatedUnion("operation",[Ge[3].omit({customerToken:!0}),Ge[4].omit({customerToken:!0}),Ge[5].omit({customerToken:!0}),Ge[6].omit({customerToken:!0}),Ge[7].omit({customerToken:!0})]).optional()}).refine(e=>!e.command||e.requestId===e.command.requestId),N.strictObject({operation:N.literal("run_command"),runId:N.uuid(),funnelId:N.uuid(),command:Dg})]),Ga=N.strictObject({runId:N.uuid(),funnelId:N.uuid(),versionId:N.uuid(),startRequestId:N.uuid(),runExpiresAt:N.iso.datetime({offset:!0}),status:Ut.shape.run.shape.status}),Vi={scope:me,customerId:N.uuid()},B_=N.discriminatedUnion("outcome",[N.strictObject({...Vi,outcome:N.literal("unknown"),target:N.null(),view:N.null(),access:N.null()}),N.strictObject({...Vi,outcome:N.literal("resolved"),target:Ga,view:Ut.shape.run.nullable(),access:N.discriminatedUnion("type",[N.strictObject({type:N.literal("customer")}),N.strictObject({type:N.literal("operation_only"),cause:N.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((e,t)=>{e.outcome==="resolved"&&(e.access.type==="customer"!=(e.view!==null)||e.view&&(e.view.id!==e.target.runId||e.view.source.id!==e.target.funnelId||e.view.source.versionId!==e.target.versionId||e.view.status!==e.target.status||e.view.runExpiresAt!==e.target.runExpiresAt||e.view.credentialExpiresAt!==null))&&t.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),z_=N.strictObject({...Vi,target:Ga,view:Ut.shape.run.nullable(),settlement:N.strictObject({requestId:N.uuid(),state:N.enum(["pending","unknown","settled"]),acceptance:N.enum(["accepted","not_accepted","unknown"]),receiptPhase:N.enum(["accepted","processing","done"]).nullable(),basis:N.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:N.uuid().nullable(),operationId:N.uuid().nullable()}),purchase:Ut.shape.purchase.unwrap().nullable()}).superRefine((e,t)=>{let n=e.settlement;(n.acceptance==="accepted"!=(n.receiptPhase!==null)||n.acceptance==="accepted"&&n.basis!=="receipt"||n.acceptance==="unknown"&&(n.state!=="unknown"||n.basis!=="none")||n.acceptance!=="accepted"&&(n.operationId!==null||n.receiptId!==null)||n.acceptance==="not_accepted"&&(n.state!=="settled"||!["run_terminal","position_advanced"].includes(n.basis))||e.purchase&&(e.purchase.receiptId!==n.receiptId||e.purchase.operation&&e.purchase.operation.operationId!==n.operationId||e.purchase.quote&&e.purchase.quote.operationId!==n.operationId)||e.view&&(e.view.id!==e.target.runId||e.view.source.id!==e.target.funnelId||e.view.source.versionId!==e.target.versionId||e.view.status!==e.target.status||e.view.runExpiresAt!==e.target.runExpiresAt||e.view.credentialExpiresAt!==null))&&t.addIssue({code:"custom",message:"Original command settlement binding differs"})}),F_=N.strictObject({...Vi,target:Ga,purchase:Ut.shape.purchase.unwrap()}).superRefine((e,t)=>{(!e.purchase.operation||typeof e.purchase.canReselect!="boolean"||e.purchase.quote&&e.purchase.quote.operationId!==e.purchase.operation.operationId)&&t.addIssue({code:"custom",message:"Original purchase proof is incomplete"})});import{z as ut}from"zod";import{z as $e}from"zod";var Jl=$e.discriminatedUnion("provider",[$e.strictObject({provider:$e.literal("apple"),orderId:$e.uuid(),receiptId:$e.uuid(),signedTransaction:$e.string().min(1).max(131072)}),$e.strictObject({provider:$e.literal("google"),orderId:$e.uuid(),receiptId:$e.uuid(),purchaseToken:$e.string().min(1).max(16384)})]),Wl=$e.strictObject({orderId:$e.uuid(),receiptId:$e.uuid(),transactionIds:$e.array($e.string().min(1).max(255)).min(1).max(50),membership:$e.boolean()});var Z_=ut.strictObject({operation:ut.literal("native_receipt"),requestId:ut.uuid(),customerToken:ut.string().regex(bt),orderId:ut.uuid(),receiptId:ut.uuid(),nativeEvidence:Jl.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),H_=ut.strictObject({scope:me,requestId:ut.uuid(),orderId:ut.uuid(),receiptId:ut.uuid(),orderStatus:ut.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:ut.boolean(),nativeCompletion:Wl.optional()});import{z as ve}from"zod";var Xl=ve.string().regex(/^[a-f0-9]{64}$/),Bg=vn.omit({variations:!0,active:!0}).extend({changeId:Xl,variations:ve.array(ve.strictObject({urlRedirect:ve.string().max(2048)})).min(2).max(20)}),X_=ve.strictObject({environmentId:ve.uuid(),trackExposures:ve.boolean(),generation:Xl,experiments:ve.array(Bg).max(100),savedGroups:or}),zg=ve.strictObject({eventUuid:ve.uuid(),timestamp:ve.iso.datetime({offset:!0}).optional(),deviceId:ve.string().min(1).max(128),sessionId:ve.string().min(1).max(128).optional(),url:ve.url().max(2048),pageTitle:ve.string().max(512).optional(),experimentKey:ve.string().min(1).max(255),variationKey:ve.string().min(1).max(64)}),Y_=ve.strictObject({events:ve.array(zg).min(1).max(20)}),ew=ve.strictObject({inserted:ve.number().int().nonnegative(),duplicates:ve.number().int().nonnegative(),skipped:ve.number().int().nonnegative(),rejected:ve.array(ve.strictObject({index:ve.number().int().nonnegative(),reason:ve.string()}))});import{z as Ae}from"zod";var Ka=32,Fg=522240;function La(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 Ng=Ae.strictObject({nodeId:Ae.string().min(1).max(64),visit:Ae.number().int().nonnegative(),revision:Ae.number().int().nonnegative()}),$a=Ae.record(Ae.string(),ne),Vg=Ae.strictObject({id:Ae.uuid(),nodeId:Ae.string().min(1).max(64),visit:Ae.number().int().nonnegative(),input:Ae.strictObject({schemaVersion:ur.shape.schemaVersion,kind:ur.shape.kind,selector:ur.shape.selector,contract:ur.shape.contract}),context:$a,removed:Ae.array(Ae.string()).max(100),attributes:$a,removedAttributes:Ae.array(Ae.string()).max(100),result:Uc,offeringVersionId:Ae.uuid().nullable(),events:Ae.strictObject({entered:Ae.string().regex(/^[1-9][0-9]{0,18}$/),decision:Ae.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),aw=Ae.strictObject({schemaVersion:Ae.literal(1),mode:Ae.enum(["local","remote"]),versionId:Ae.uuid(),generation:Ae.number().int().positive(),base:Ng,context:$a,steps:Ae.array(Vg).min(1).max(Ka)}).refine(e=>tt(e)<=Fg,"Segment exceeds its byte budget");var Ug=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function kr(e){return Array.isArray(e)?e.some(kr):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&kr(n):!Ug.test(t))}function Yl(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(c=>c.id===t.screenId&&c.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(c=>kr(c.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(c=>c.id===t.screenId):null]);for(let[c,d]of Object.entries(e.variables))if(d.source.type==="attribute"&&d.source.key!=="funnelParticipantId"&&(a.includes(`variables.${c}`)||a.includes(JSON.stringify(c))))return"customer_required";if(t.type==="split"){let c=n.experiments?.[t.experimentId];if((c?.hashAttribute??"id")!=="funnelParticipantId"||kr(c?.condition)||c?.parentConditions?.length)return"customer_experiment_required"}let m=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return m&&n.features?.[m]?.rules?.some(c=>(c.hashAttribute??"id")!=="funnelParticipantId"||kr(c.condition)||c.parentConditions?.length)?"customer_experiment_required":null}var Za=class extends Error{constructor(n,r){super(r);this.code=n;this.name="FunnelLocalCalculationError"}code},Ui=(e,t)=>new Za(e,t),Gg=e=>({experiments:e.experiments,features:e.features});function $g(e,t=Ui){let n=new Map(e.topology.nodes.map(m=>[m.id,m])),r=ss(e.growth.savedGroups),i=Gg(e.growth);function a(m,c){if(!Object.hasOwn(e.growth.features,m))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Kn(m,c).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(m,c){let d=n.get(m);if(!d)throw t("NOT_FOUND","Funnel node is unavailable");let I,g;if(d.type==="condition"){let $=e.conditions[d.id];if(!$)throw t("INVALID_RESPONSE","Local condition rules are unavailable");I=za({id:d.id,name:d.id,type:"condition",cases:$.map(C=>({condition:C.condition,target:d.outputs[C.port]})),default:d.outputs.default},c,i.experiments).port}else if(d.type==="feature"){if(!d.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=a(d.resources.featureKey,c),I="next"}else if(d.type==="split"){if(!(d.resources.experimentId?e.growth.experiments[d.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let C=za({id:d.id,name:d.id,type:"split",experimentId:d.resources.experimentId,routes:d.outputs,notParticipating:d.outputs.notParticipating},c,i.experiments);g=C.value,I=C.port}else if(["offering","end","output"].includes(d.type)&&d.resources.featureKey)g=a(d.resources.featureKey,c),I=d.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let T=d.outputs[I]??(I==="value"?d.id:void 0);if(!T)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:m,port:I,target:T,...g===void 0?{}:{value:g}}}}}function xw(e,t,n,r=Ui){return Ha(e,r)(t,n)}function Ha(e,t){let n=Un.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=$g(n,t);return(m,c)=>(i(),Kg(a,m,c))}function Kg(e,t,n){let r=Ye.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:m}=n,c={attributes:r,...i?{saveStickyBucketAssignmentDoc:d=>i(structuredClone(d))}:{},...a?{onFeatureUsage:(d,I)=>a(d,structuredClone(I))}:{},...m?{onExperimentViewed:(d,I)=>m(structuredClone(d),structuredClone(I))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function Sw(e,t,n,r=Ui){return em(Ha(e,r),t,n)}function em(e,t,n){let r=[],i=[],a=[],m=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(c){let d=r.findIndex(T=>T.next.attributeName===c.attributeName&&T.next.attributeValue===c.attributeValue),I=c.attributeName+"||"+c.attributeValue,g={expected:n.sticky[I]??null,next:c};d<0?r.push(g):r[d]=g},onExperimentViewed(c,d){d.inExperiment&&d.hashUsed&&!d.passthrough&&i.push(ne.parse({key:c.key,variationId:d.variationId,keyUsed:d.key,hashAttribute:d.hashAttribute,hashValue:d.hashValue}))},onFeatureUsage(c,d){a.push(ne.parse({feature:c,value:d.value,source:d.source,...d.ruleId?{ruleId:d.ruleId}:{}}))}});return{port:m.port,...m.value===void 0?{}:{value:m.value},sticky:r,exposures:i,features:a}}function Iw(e,t,n,r=Ui){let i=n,a=new Map(t.graph.nodes.map(Q=>[Q.id,Q])),m=structuredClone(n.variables),c=structuredClone(i.sticky),d=[],I=n.nodeId,g=n.visit,T=!1,$,C=Q=>Yl(t,Q,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),l=Q=>($??=Ha(e,r),em($,Q,{attributes:ko({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:m,savedGroups:{}}),sticky:c}));for(let Q=0;Q<Ka;Q++){let E=a.get(I);if(!E||!La(E)||C(E))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||E.type!=="end"&&E.type!=="output")){if(!d.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let pe,De;if(["condition","feature","split"].includes(E.type)||E.type==="offering"&&E.configuration.source==="feature")pe=l(E.id),E.type==="offering"&&(pe.value={type:"offering_version",id:String(pe.value)}),E.type==="condition"?De=pe.port==="default"?E.default:E.cases[Number(pe.port.slice(5))]?.target:E.type==="split"?De=pe.port==="notParticipating"?E.notParticipating:E.routes[pe.port]:(E.type==="feature"||E.type==="offering")&&(De=E.next);else if(pe={port:"next",sticky:[],exposures:[],features:[]},(E.type==="entry"||E.type==="coupon"||E.type==="coupons")&&(De=E.next),E.type==="offering"&&E.configuration.source==="fixed"&&(pe.value={type:"offering_version",id:E.configuration.versionId},De=E.next),E.type==="end"||E.type==="output"){let ie=E.type==="end"?E.output:E.value;if(pe=ie?.type==="feature"?l(E.id):{...pe,port:"value",value:ie?.type==="literal"?ie.value:ie?.type==="variable"?lo({source:"variable",key:ie.key,...ie.path?{path:ie.path}:{}},{declarations:t.variables,answers:n.answers,results:m,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},ie&&(pe.value===void 0||!at(t.outputSchema,pe.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let Z=[...d,{nodeId:I,result:pe}];if(tt({steps:Z})>6e4){if(!d.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(d.push({nodeId:I,result:pe}),E.type==="feature"||E.type==="offering"||E.type==="coupon"||E.type==="coupons"){let ie=E.type==="coupons"?E.couponIds.map(J=>({type:"reward",id:J})):E.type==="coupon"?{type:"reward",id:E.couponId}:pe.value;if(ie===void 0)throw r("INVALID_RESPONSE","Node output is missing");let be=Qt(E,{value:ie});po(t.variables,E,be),Object.assign(m,be)}for(let ie of pe.sticky)c[`${ie.next.attributeName}||${ie.next.attributeValue}`]=structuredClone(ie.next);if(E.type==="end"||E.type==="output"){T=!0;break}if(!De)throw r("INVALID_RESPONSE","Local pure exit is unavailable");I=De,g++}let b=a.get(I);return{steps:d,...!T&&b&&(!La(b)||C(b))?{boundary:{nodeId:I,visit:g}}:{}}}import{z as Lg}from"zod";var _w=Lg.strictObject({document:zt,configuration:Un.options[0]});var HC={name:"@tinkerlandai/longplay-sdk",version:"0.10.25",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var QC="https://api.longplayai.com";export{pv as a,lv as b,mv as c,dv as d,hi as e,hv as f,bv as g,yv as h,xv as i,Yg as j,eb as k,ks as l,hb as m,gb as n,bb as o,yb as p,bt as q,bn as r,Zt as s,Ns as t,_b as u,wb as v,ao as w,xm as x,Lr as y,kb as z,Im as A,vm as B,Om as C,Kr as D,Zr as E,io as F,_m as G,Rb as H,wm as I,Eb as J,Mb as K,Gd as L,Cv as M,Kd as N,kv as O,Ls as P,qb as Q,Bb as R,Cm as S,km as T,Vb as U,at as V,po as W,lo as X,ho as Y,my as Z,Sy as _,wt as $,So as aa,Lm as ba,cc as ca,vo as da,ko as ea,Px as fa,Cx as ga,kx as ha,od as ia,Hx as ja,Qx as ka,Jx as la,We as ma,Hc as na,zd as oa,Fd as pa,rv as qa,Wo as ra,Vd as sa,iv as ta,ov as ua,av as va,Or as wa,_O as xa,tl as ya,el as za,wa as Aa,Fh as Ba,DO as Ca,v as Da,fA as Ea,bg as Fa,Pr as Ga,Nn as Ha,Ut as Ia,kA as Ja,Og as Ka,GA as La,Vl as Ma,Ul as Na,zi as Oa,KA as Pa,Kl as Qa,kg as Ra,t_ as Sa,n_ as Ta,r_ as Ua,i_ as Va,o_ as Wa,p_ as Xa,Ll as Ya,y_ as Za,x_ as _a,Un as $a,Eg as ab,Tg as bb,C_ as cb,B_ as db,z_ as eb,F_ as fb,Z_ as gb,H_ as hb,X_ as ib,$g as jb,xw as kb,Sw as lb,Iw as mb,_w as nb,HC as ob,QC as pb};