@tinkerlandai/longplay-sdk 0.10.18 → 0.10.19

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