@tinkerlandai/indiana-sdk 0.6.4 → 0.7.0

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 (53) hide show
  1. package/CHANGELOG.md +9 -4
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +3 -3
  4. package/dist/{ai-usage-B4W5m4Ie.d.ts → ai-usage-BsrSG955.d.ts} +334 -518
  5. package/dist/chunk-3SONNXFG.js +1 -0
  6. package/dist/chunk-467Z5ISI.js +11 -0
  7. package/dist/{chunk-2EJSV6BA.js → chunk-4AWSZWZD.js} +1 -1
  8. package/dist/{chunk-5TEZEOHX.js → chunk-6MO6Y24B.js} +1 -1
  9. package/dist/chunk-HD74AAFS.js +1 -0
  10. package/dist/chunk-J4RHVU3W.js +1 -0
  11. package/dist/chunk-KQCTDXVD.js +17 -0
  12. package/dist/chunk-NOFNOHUI.js +1 -0
  13. package/dist/chunk-QO4YQLZ4.js +1 -0
  14. package/dist/chunk-RRII2DMC.js +1 -0
  15. package/dist/chunk-WCFVNF5D.js +1 -0
  16. package/dist/chunk-YAFMBXIE.js +4 -0
  17. package/dist/{client-OYRHOMUQ.js → client-F6UPJMHR.js} +1 -1
  18. package/dist/{configuration-sync-C2mytNwU.d.ts → configuration-sync-Bvd956GL.d.ts} +333 -25
  19. package/dist/controls-XG46TKUU.js +2 -0
  20. package/dist/funnel-runtime-host-26QI2W3S.js +1 -0
  21. package/dist/{funnel-runtime-start-sZ8ZCNlq.d.ts → funnel-runtime-start-ChVYbLzV.d.ts} +6655 -2785
  22. package/dist/iam.js +1 -1
  23. package/dist/index.d.ts +3634 -1485
  24. package/dist/index.js +1 -1
  25. package/dist/native-shell.js +1 -1
  26. package/dist/openrouter.d.ts +2 -3
  27. package/dist/openrouter.js +1 -1
  28. package/dist/page.d.ts +13 -13
  29. package/dist/page.js +1 -1
  30. package/dist/paywall-WKOHBYW7.js +1 -0
  31. package/dist/popup.d.ts +9 -16
  32. package/dist/popup.js +12 -12
  33. package/dist/react-native.d.ts +14 -14
  34. package/dist/react-native.js +1 -1
  35. package/dist/server.d.ts +4 -4
  36. package/dist/server.js +1 -1
  37. package/dist/src-UHLPVD6E.js +1 -0
  38. package/dist/visual.js +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-63BWE27V.js +0 -1
  41. package/dist/chunk-CB63JLGT.js +0 -1
  42. package/dist/chunk-D7YHFS6B.js +0 -4
  43. package/dist/chunk-HTRQPMJO.js +0 -11
  44. package/dist/chunk-ISUXYPYL.js +0 -1
  45. package/dist/chunk-QG3WUJG5.js +0 -1
  46. package/dist/chunk-RMJJOSVZ.js +0 -1
  47. package/dist/chunk-S2MSIA57.js +0 -17
  48. package/dist/chunk-VVSQKVE7.js +0 -1
  49. package/dist/funnel-runtime-host-NWS3URFA.js +0 -1
  50. package/dist/paywall-4XZ6NDMY.js +0 -1
  51. package/dist/src-WV6GZYWA.js +0 -1
  52. package/dist/{customer-page-B4FGCVpt.d.ts → customer-page-B4LkIr5q.d.ts} +4 -4
  53. package/dist/{screen-16d-xADb.d.ts → screen-iFngkxaL.d.ts} +185 -185
@@ -0,0 +1,11 @@
1
+ import{a as wu,b as ke,c as Yu,d as Ju,g as Xu,h as on,i as zu}from"./chunk-3SONNXFG.js";import{Ab as br,Da as Wu,Eb as Ua,Hb as si,Kb as no,Lb as Qn,M as ri,Ma as Hu,Mb as $t,N as Tu,O as Ru,Ob as Ma,Pa as Qu,R as ju,S as ii,T as ku,U as Du,V as Na,W as kt,X as Nu,_ as Fu,a as Hn,aa as Uu,b as re,c as Qi,ca as Mu,f as Au,fa as to,g as Ot,ga as hr,h as _e,ha as Bu,i as ka,j as Zi,ja as Lu,k as Xt,ka as oi,ma as qu,na as Vu,pa as Gu,q as bn,qb as Zu,r as eo,s as Eu,ta as $u,ua as gr,ub as Et,va as Ku,wb as nt,xb as ai,yb as Fa}from"./chunk-HD74AAFS.js";import{a as ge,b as Ct,c as wn,d as Da,e as fr,i as Cu,k as ni,q as zi}from"./chunk-RRII2DMC.js";import{f as Yi,g as Ji,h as Pu,i as Xi,k as Ou,l as ti}from"./chunk-KQCTDXVD.js";import{z as zt}from"zod";import{z as w}from"zod/v4";import{z as Og}from"zod/v4";var el=Og.registry();var{AppEnv:ro}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:tl}={IGNORE_PAST_DUE_DESCRIPTION:"If true, entitlements attached to this plan will still reset on schedule even when the customer's product is in a past_due state."},{PurchaseLimitInterval:Cg}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:Eg}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(w),{ResetInterval:ci}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{ResetInterval:e}})(),{USAGE_LIMIT_ANCHORS:Tg}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:Rg}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:jg}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:kg}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:Dg}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(w),{BALANCE_BASES:Ng}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:nl}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:Ba}=(e=>({DbOverageAllowedSchema:e.object({feature_id:e.string().meta({description:"The feature ID this overage allowed control applies to."}),enabled:e.boolean().default(!1).meta({description:"Whether overage is allowed for this feature."})})}))(w),{ProductMetadataSchema:_r}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(w),{findDuplicate:Fg}={findDuplicate:t=>{let n=new Set;for(let r of t){if(n.has(r))return r;n.add(r)}}},{BillingInterval:Pn}=(()=>{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:La}=(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:ui}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(el),{COMMON:rl}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Ug}={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:Mg}=(e=>({COMMON_SET:new Set(e)}))(rl),{hasNoDuplicateCurrencies:il}={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:ol}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:qa}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(w),{Infinite:io}={Infinite:"inf"},{TierBehavior:li}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:oo}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:al}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:Bg}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:ao}=(()=>{var e;return(function(t){t.BillImmediately="bill_immediately",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.BillNextCycle="bill_next_cycle"})(e||(e={})),{OnIncrease:e}})(),{OnDecrease:so}=(()=>{var e;return(function(t){t.Prorate="prorate",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.None="none",t.NoProrations="no_prorations"})(e||(e={})),{OnDecrease:e}})(),{RolloverExpiryDurationType:Va}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:sl}=(()=>{var e;return(function(t){t.Day="day",t.Week="week",t.Month="month",t.Year="year"})(e||(e={})),{EntitlementDuration:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Lg}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:qg}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Ga}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(w),{ApiCreditTierSchema:cl}=(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:Vg}={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:ul}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(w),{ModelMarkupsSchema:$a}=((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,ul),{additionalCurrencyPlanItemIssues:ll}={additionalCurrencyPlanItemIssues:t=>{if(!t)return[];let n=[];t.additional_currencies&&t.additional_currencies.length>0&&(typeof t.amount!="number"||(t.tiers?.length??0)>0)&&n.push("price.additional_currencies requires a flat 'amount'; tiered prices carry per-currency amounts on each tier.");let r=t.tiers;if(r&&r.length>0){let i=a=>(a.additional_currencies??[]).map(s=>s.currency.toLowerCase()),o=new Set(r.flatMap(i));o.size>0&&(r.every(s=>{let c=new Set(i(s));return c.size===o.size&&[...o].every(u=>c.has(u))})||n.push("Each additional currency must be present on every tier or none."))}return n}},{PlanItemFilterSchema:Ka}=((e,t,n,r,i)=>({PlanItemFilterSchema:e.object({feature_id:e.string().optional().meta({description:"Match items linked to this feature."}),billing_method:e.enum(t).optional().meta({description:"Match items with this billing method (prepaid or usage_based)."}),interval:e.union([e.enum(n),e.enum(r)]).optional().meta({description:"Match items with this interval. Accepts either a BillingInterval (price-side) or a ResetInterval (reset-side, includes day/hour/minute) so price-less items keyed by reset.interval can be disambiguated."}),interval_count:e.number().int().positive().optional().meta({description:"Match items with this interval_count. Disambiguates between items that share an interval but differ in count."}),included:i.optional().meta({description:"Match items whose grant equals this included usage. Omitted is a wildcard."})}).refine(a=>a.feature_id!==void 0||a.billing_method!==void 0||a.interval!==void 0||a.interval_count!==void 0,{message:"PlanItemFilter must have at least one field set."}).meta({title:"PlanItemFilter",description:"Filter for matching plan items. All provided fields must match (AND)."})}))(w,oo,Pn,ci,qa),{UpdatePlanItemParamsV1Schema:Gg}=((e,t,n)=>({UpdatePlanItemParamsV1Schema:e.object({filter:t.meta({description:"Filter selecting which existing plan item(s) to update. Same shape as remove_items filters."}),included:e.number().nonnegative().optional().meta({description:"Override the matched item's included usage / allowance. Existing usage carries forward."}),interval:e.enum(n).optional().meta({description:"Override the matched item's reset interval. Use 'one_off' for non-resetting balances."})}).meta({title:"UpdatePlanItem",description:"Deprecated. Use remove_items and add_items to replace plan items.",deprecated:!0})}))(w,Ka,ci),{FreeTrialDuration:di}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:$g}=((e,t)=>({laneParam:({schema:r,description:i})=>e({schema:t.array(r).optional(),defaultValue:[],description:i})}))(ui,w),{findDuplicateInControls:Kg}={findDuplicateInControls:({controlKey:t,controls:n,rule:r})=>{let i=new Set;for(let[o,a]of n.entries()){let s=r.identityOf(a);if(s!==void 0){if(i.has(s))return{code:"custom",message:r.message,input:a[r.field],path:[t,o,r.field]};i.add(s)}}}},{featureIdIdentity:Wg}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:dl}={usageLimitFilterKey:t=>t?.properties?Object.entries(t.properties).map(([n,r])=>[n,String(r)]).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${n}=${r}`).join("&"):""},{usageAlertIdentity:Hg}=((e,t)=>({usageAlertIdentity:r=>[r.feature_id??"",r.basis??e,t(r.filter),r.threshold_type,r.threshold].join("|")}))(nl,dl),{RemovePlanLicenseSchema:Qg}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(w),{ApiStripePriceProcessorSchema:Zg}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(w),{ApiFeatureType:Yg}=(()=>{var e;return(function(t){t.Static="static",t.Boolean="boolean",t.SingleUsage="single_use",t.ContinuousUse="continuous_use",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{ApiFeatureType:e}})(),{ApiStripePlanProcessorSchema:Jg}=(e=>({ApiStripePlanProcessorSchema:e.object({product_id:e.string().meta({description:"Stripe product ID this plan is billed under."}),additional_product_ids:e.array(e.string()).optional().meta({description:"Extra Stripe product IDs aliased to this plan."})})}))(w),{ApiRevenueCatProductSchema:Xg}=(e=>({ApiRevenueCatProductSchema:e.object({product_id:e.string().meta({description:"RevenueCat product ID that grants this plan when purchased."}),feature_quantities:e.array(e.object({feature_id:e.string(),quantity:e.number().nonnegative().optional()})).optional().meta({description:"Prepaid quantities granted when this specific RevenueCat product is purchased, in feature units."})})}))(w),{TrialOnEnd:co}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:zg}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:eb}=(()=>{var e;return(function(t){t.Activate="activate",t.Upgrade="upgrade",t.Downgrade="downgrade",t.None="none",t.Purchase="purchase"})(e||(e={})),{AttachAction:e}})(),{AttachScenario:tb}=(()=>{var e;return(function(t){t.Scheduled="scheduled",t.Active="active",t.New="new",t.Renew="renew",t.Upgrade="upgrade",t.UpdatePrepaidQuantity="update_prepaid_quantity",t.Downgrade="downgrade",t.Cancel="cancel",t.Expired="expired",t.PastDue="past_due"})(e||(e={})),{AttachScenario:e}})(),{UsageWindowDimensionSchema:nb}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(w),{UsageWindowScopeSchema:rb}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(w),{EntInterval:pl}=(()=>{var e;return(function(t){t.Lifetime="lifetime",t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{EntInterval:e}})(),{FeatureType:ib}=(()=>{var e;return(function(t){t.Boolean="boolean",t.Metered="metered",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{FeatureType:e}})(),{FeatureStripeMeterSchema:ob}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(w),{FreeTrialSchema:ab}=((e,t,n)=>({FreeTrialSchema:e.object({id:e.string(),duration:e.enum(t),length:e.number(),unique_fingerprint:e.boolean(),created_at:e.number(),internal_product_id:e.string(),is_custom:e.boolean(),card_required:e.boolean(),on_end:e.enum(n).nullish()})}))(w,di,co),{BillingType:sb}=(()=>{var e;return(function(t){t.OneOff="one_off",t.FixedCycle="fixed_cycle",t.UsageBelowThreshold="usage_below_threshold",t.UsageInAdvance="usage_in_advance",t.UsageInArrear="usage_in_arrear",t.InArrearProrated="in_arrear_prorated"})(e||(e={})),{BillingType:e}})(),{UsageTierSchema:Wa}=((e,t)=>({UsageTierSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional()}).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"]}).transform(r=>({...r,amount:r.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional()}))}))(w,io),{IgnoredFixedPriceMetadataSchema:cb}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(w),{BillWhen:ub}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:ml}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:lb}=((e,t,n)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(n).default(n.ProrateImmediately)})}))(w,ao,so),{AllowanceType:db}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:fl}=((e,t)=>({RolloverConfigSchema:e.object({max:e.number().nullable().optional(),max_percentage:e.number().nullable().optional(),duration:e.enum(t).default(t.Month),length:e.number()})}))(w,Va),{CreditDimensionBaseSchema:pb}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(w,Ga),{flatCreditRateShape:hl}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(w),{CreditTierSchema:mb}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(w),{CreditMultiplierSchema:fb}=((e,t)=>({CreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional(),add:e.number().optional()}).refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add"})}))(w,Ga),{idRegex:uo}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:gl}={descriptions:{id:"The ID of the product. Used to identify the product in other API calls like checkout or update product.",name:"The name of the product",description:"The description of the product",is_add_on:"Whether the product is an add-on. Add-on products can be attached multiple times and don't to through upgrade / downgrade flows.",is_default:"Whether the product is the default product. Default products are enabled by default for new customers.",group:"Product group which this product belongs to. Products within a group have upgrade / downgrade logic when the customer moves between them.",items:"Array of product items that define the product's features and pricing",free_trial:"Free trial configuration for this product, if available",metadata:"Arbitrary key-value metadata for your own use (e.g. UI copy, feature highlights). Values can be any JSON-serializable value. Metadata is shared across all versions of a plan.",archived:"Archive this product using this flag. Archived products are hidden on the dashboard."}},{ProductItemType:hb}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:gb}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{ProductItemInterval:bb}=(()=>{var e;return(function(t){t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{ProductItemInterval:e}})(),{UsageModel:_b}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:yb}={TierInfinite:"inf"},{CreateFreeTrialSchema:bl}=((e,t,n)=>({CreateFreeTrialSchema:e.object({length:e.string().or(e.number()).transform(i=>Number(i)).refine(i=>i>0,{message:"Free trial length must be greater than 0"}),unique_fingerprint:e.boolean().default(!1),duration:e.enum(t).default(t.Day),card_required:e.boolean().default(!0),on_end:e.enum(n).nullish()})}))(w,di,co),{ProductConfigParamsSchema:Ha}=((e,t,n)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:n})})}))(w,ui,tl),{CREATE_PRODUCT_EXAMPLE:Sb}={CREATE_PRODUCT_EXAMPLE:{id:"Pro Product",name:"Pro Plan",is_add_on:!1,is_default:!1,items:[{price:20,interval:"month"},{feature_id:"messages",included_usage:1e3,price:.5,interval:"month",usage_model:"pay_per_use"}],free_trial:{duration:"day",length:7,unique_fingerprint:!1,card_required:!0}}},{ApiFreeTrialSchema:vb}=((e,t,n)=>({ApiFreeTrialSchema:e.object({duration:e.enum(t).meta({description:"The duration type of the free trial"}),length:e.number().meta({description:"The length of the duration type specified"}),unique_fingerprint:e.boolean().meta({description:"Whether the free trial is limited to one per customer fingerprint"}),card_required:e.boolean().meta({description:"Whether the free trial requires a card. If false, the customer can attach the product without going through a checkout flow or having a card on file."}),on_end:e.enum(n).nullish().meta({description:"Behavior when the trial ends. 'bill' charges the customer (default). 'revert' expires the trial and restores the customer's previous plan."}),trial_available:e.boolean().default(!0).nullish().meta({description:"Used in customer context. Whether the free trial is available for the customer if they were to attach the product."})})}))(w,di,co),{CreateProductSchema:QP}=(e=>({CreateProductSchema:e.object({id:e.string(),name:e.string().min(1,"Product name cannot be empty").default("Untitled Product"),is_add_on:e.boolean().default(!1),is_default:e.boolean().default(!1),version:e.number().optional().default(1),group:e.string().optional().default("")})}))(w),{isUsageLimitBasisAlert:xb}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:_l}=(e=>({PromoCodeSchema:e.object({code:e.string(),global_max_redemption:e.number().positive().optional(),first_time_transaction:e.boolean().optional(),max_redemptions:e.number().positive().optional()})}))(w),{RewardType:yl}=(()=>{var e;return(function(t){t.PercentageDiscount="percentage_discount",t.FixedDiscount="fixed_discount",t.FreeProduct="free_product",t.InvoiceCredits="invoice_credits",t.FeatureGrant="feature_grant"})(e||(e={})),{RewardType:e}})(),{CouponDurationType:Sl}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:vl}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(w,Sl),{RewardTriggerEvent:Ib}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:Ab}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:lo}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(w,tl),{PurchaseLimitIntervalEnum:wb}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(w,Cg),{DbSpendLimitSchema:Qa}=((e,t)=>({DbSpendLimitSchema:e.object({feature_id:e.string().optional().meta({description:"Optional feature ID this spend limit applies to."}),enabled:e.boolean().default(!1).meta({description:"Whether the overage spend limit is enabled."}),limit_type:t.optional().meta({description:"How overage_limit is interpreted: an absolute overage cap (default) or a percentage of the main-plan allowance."}),overage_limit:e.number().min(0).optional().meta({description:"Overage cap for the feature: absolute units, or a percent (e.g. 120) when limit_type is usage_percentage."}),skip_overage_billing:e.boolean().optional().meta({description:"When true, overage for this feature is not posted to Stripe. Usage tracking and balance resets still behave normally."})}).refine(r=>r.overage_limit===void 0&&r.skip_overage_billing===void 0||r.feature_id!==void 0,{message:"feature_id is required when overage_limit or skip_overage_billing is provided",path:["feature_id"]})}))(w,Eg),{USAGE_LIMIT_INTERVALS:Pb}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(ci),{UsageLimitAnchorSchema:xl}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(w,Tg),{UsageLimitFilterValueSchema:Ob}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(w,jg),{USAGE_ALERT_BASES:Cb}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(Ng),{licensePatchIssues:Eb}=(e=>({licensePatchIssues:({upsertLicenses:n=[]})=>{let r=e(n.map(i=>i.license_plan_id));return r===void 0?[]:[{message:`Duplicate license ${r} in upsert_licenses`,path:["upsert_licenses"]}]}}))(Fg),{BasePriceSchema:Tb}=((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,Pn,La),{CURRENCY_CODES:Rb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(rl,Ug,Mg),{AllocatedBillingFieldSchema:Il}=((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,al),{EntitlementExpirySchema:po}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(w,sl),{CreditDimensionNameSchema:Al}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(w,Lg,qg),{ApiCreditMatchSchema:wl}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Ga),{findCreditTierViolations:jb}=(e=>({findCreditTierViolations:n=>{let r=[],i=(a,s)=>r.push({index:a,reason:s,message:e[s]}),o=0;for(let[a,s]of n.entries()){let c=a===n.length-1;if(s==="inf"){c||i(a,"non_final_infinity");continue}(!Number.isFinite(s)||s<=o)&&i(a,"not_increasing"),o=s,c&&i(a,"final_not_infinity")}return r}}))(Vg),{ApiCreditMultiplierSchema:kb}=((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,wl),{ProviderMarkupsSchema:Pl}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(w,ul),{planItemParamsIssues:Db}=((e,t,n,r,i)=>({planItemParamsIssues:a=>{let s=[],c=a.reset?.interval,u=a.price?.interval,l=a.reset?.interval_count??1,d=a.price?.interval_count??1;if(c&&u&&(String(c)!==String(u)||l!==d)&&a.price?.billing_method!==e.Prepaid&&s.push({message:"reset.interval and price.interval can only differ for prepaid prices.",input:a}),a.threshold_billing&&(!a.price||a.unlimited)&&s.push({message:"threshold_billing requires a finite usage-based price",input:a.threshold_billing}),a.expiry&&(a.price?.billing_method===e.Prepaid&&String(a.price.interval)===String(t.OneOff)||s.push({message:"expiry is only supported on one-off prepaid items. Recurring items are already bounded by their reset cadence.",input:a.expiry}),a.entity_feature_id&&s.push({message:"expiry is not supported on entity-scoped items; each entity's balance would have to expire on its own clock.",input:a.expiry}),a.pooled&&s.push({message:"expiry is not supported on pooled items; pooled balances have no per-purchase lifetime.",input:a.expiry}),a.expiry.length<=0&&s.push({message:"expiry.length must be greater than 0",input:a.expiry})),a.price){a.threshold_billing&&a.price.billing_method!==e.UsageBased&&s.push({message:"threshold_billing requires a finite usage-based price",input:a.threshold_billing});let{amount:g,tiers:p}=a.price;a.threshold_billing&&p?.length&&s.push({message:"threshold_billing currently requires a flat usage price",input:a.threshold_billing});let f=a.price.billing_method===e.UsageBased&&a.price.allocated_billing===n.ProratedLegacy;a.proration&&a.price.billing_method!==e.Prepaid&&!f&&s.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:a.proration});let y=typeof g=="number",x=Array.isArray(p)&&p.length>0;y||x?y&&x&&s.push({message:"'amount' and 'tiers' cannot both be defined in 'price'.",input:a.price}):s.push({message:"If 'price' is present, either 'amount' or 'tiers' must be defined.",input:a.price})}if(a.price?.tiers){let g=a.price.tiers.some(p=>p.flat_amount&&p.flat_amount>0);g&&a.price.tier_behavior!==r.VolumeBased&&s.push({message:"flat_amount on tiers is only supported for volume-based pricing.",input:a.price}),g&&a.price.tiers.length<=1&&s.push({message:"flat_amount is not supported on single-tier pricing.",input:a.price}),a.price.tiers.some(p=>p.flat_amount!=null&&p.flat_amount<0)&&s.push({message:"flat_amount must be 0 or greater.",input:a.price}),a.price?.tier_behavior===r.VolumeBased&&a.price?.billing_method!==e.Prepaid&&s.push({message:"volume-based pricing is only supported for prepaid features.",input:a.price}),a.price?.tiers.length===0?s.push({message:"tiers cannot be empty.",input:a.price}):a.included&&typeof a.price?.tiers[0].to=="number"&&a.price?.tiers[0].to<=a.included&&s.push({message:"tiers[0].to must be greater than included.",input:a.price})}for(let g of i(a.price))s.push({message:g,input:a.price});return s}}))(oo,Pn,al,li,ll),{FreeTrialParamsV1Schema:Za}=((e,t,n)=>({FreeTrialParamsV1Schema:e.object({duration_length:e.number().meta({description:"Number of duration_type periods the trial lasts."}),duration_type:e.enum(t).default(t.Month).meta({description:"Unit of time for the trial ('day', 'month', 'year')."}),card_required:e.boolean().default(!1).meta({description:"If true, a payment method is required to start the trial and the customer is charged when it ends. Defaults to false."}),on_end:n({schema:e.enum(["bill","revert"]).optional(),defaultValue:"bill",description:"Behavior when the trial ends. 'bill' charges the customer (default). 'revert' expires the trial and restores the customer's previous plan."})}).meta({title:"FreeTrialParams",description:"Free trial configuration for a plan."})}))(w,di,ui),{duplicateCheck:Nb}=(e=>({duplicateCheck:({controlKey:n,...r})=>i=>e({controlKey:n,controls:i[n]??[],rule:r})}))(Kg),{usageLimitIdentity:Ya}=(e=>({usageLimitIdentity:n=>`${n.feature_id}|${e(n.filter)}`}))(dl),{ApiPriceProcessorsSchema:Ol}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(w,Zg),{ApiFeatureV0Schema:Cl}=((e,t)=>({ApiFeatureV0Schema:e.object({id:e.string().meta({description:"The ID of the feature, used to refer to it in other API calls like /track or /check."}),name:e.string().nullish().meta({description:"The name of the feature."}),type:e.enum(t).meta({description:"The type of the feature"}),display:e.object({singular:e.string().meta({description:"The singular display name for the feature."}),plural:e.string().meta({description:"The plural display name for the feature."})}).nullish().meta({description:"Singular and plural display names for the feature."}),credit_schema:e.array(e.object({metered_feature_id:e.string().meta({description:"The ID of the metered feature (should be a single_use feature)."}),credit_cost:e.number().meta({description:"The credit cost of the metered feature."})})).nullish().meta({description:"Credit cost schema for credit system features."}),archived:e.boolean().nullish().meta({description:"Whether or not the feature is archived."})})}))(w,Yg),{ApiRevenueCatPlanProcessorSchema:Fb}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(w,Xg),{ApiFreeTrialV2Schema:Ub}=((e,t,n)=>({ApiFreeTrialV2Schema:e.object({duration_length:e.number().meta({description:"Number of duration_type periods the trial lasts."}),duration_type:e.enum(t).meta({description:"Unit of time for the trial duration ('day', 'month', 'year')."}),card_required:e.boolean().meta({description:"Whether a payment method is required to start the trial. If true, customer will be charged after trial ends."}),on_end:e.enum(n).nullish().meta({description:"Behavior when the trial ends. 'bill' charges the customer (default). 'revert' expires the trial and restores the customer's previous plan."})})}))(w,di,co),{CustomerEligibilitySchema:Mb}=((e,t,n,r)=>({CustomerEligibilitySchema:e.object({object:e.literal("customer_eligibility").optional().meta({internal:!0}),trial_available:e.boolean().optional().meta({description:"Whether the trial on this plan is available to this customer. For example, if the customer used the trial in the past, this will be false."}),status:e.enum(t).optional().meta({description:"The customer's current status with this plan. 'active' if attached, 'scheduled' if pending activation."}),canceling:e.boolean().optional().meta({description:"Whether the customer's active instance of this plan is set to cancel."}),trialing:e.boolean().optional().meta({description:"Whether the customer is currently on a free trial of this plan."}),attach_action:e.enum(n).meta({description:"The action that would occur if this plan were attached to the customer."}),scenario:e.enum(r).optional().meta({description:"Legacy attach scenario. Internal use only.",internal:!0})})}))(w,zg,eb,tb),{UsageWindowLimitSchema:ZP}=((e,t,n,r,i)=>({UsageWindowLimitSchema:e.object({feature_id:e.string(),internal_feature_id:e.string(),internal_customer_id:e.string(),key:e.string(),dimension_type:t,dimension_feature_id:e.string().nullable(),scope_type:n,entity_id:e.string().nullable(),internal_entity_id:e.string().nullable(),filter_key:e.string().nullable(),filter_properties:e.record(e.string(),e.string()).nullable(),interval:e.enum(r),window_start_at:e.number(),window_end_at:e.number(),limit:e.number(),anchor_customer_entitlement_id:e.string().nullable(),anchor_mode:i.default("billing_cycle"),new_window_id:e.string().optional()})}))(w,nb,rb,pl,xl),{FeatureSchema:Bb}=((e,t,n,r,i)=>({FeatureSchema:e.object({internal_id:e.string(),org_id:e.string(),created_at:e.number(),env:e.nativeEnum(t),id:e.string().nonempty("Features must have an ID"),name:e.string().nonempty("Features must have a name"),type:e.nativeEnum(n,{message:"Features must have a type"}),config:e.any(),display:e.object({singular:e.string().optional(),plural:e.string().optional()}).nullish(),archived:e.boolean(),event_names:e.array(e.string()).default([]),model_markups:r.nullish(),stripe_meter:i.nullish(),stripe_product_id:e.string().nullish()})}))(w,ro,ib,$a,ob),{PriceCurrencyConfigSchema:El}=((e,t)=>({PriceCurrencyConfigSchema:e.object({amount:e.number().nullish(),usage_tiers:e.array(t).nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish()})}))(w,Wa),{UsagePriceConfigSchema:Lb}=((e,t,n,r,i,o)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(n),interval:e.enum(r),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(o).optional()})}))(w,ub,Wa,Pn,El,ml),{graduatedCreditRateShape:Tl}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(w,mb),{FeatureMarkupsOverrideSchema:qb}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(w,Pl,$a),{usageAlertTargetLimitIdentity:Vb}=(e=>({usageAlertTargetLimitIdentity:n=>e({feature_id:n.feature_id??"",filter:n.filter})}))(Ya),{DiscountConfigSchema:Rl}=((e,t)=>({DiscountConfigSchema:e.object({discount_value:e.number(),duration_type:e.nativeEnum(t),duration_value:e.number(),should_rollover:e.boolean().optional(),apply_to_all:e.boolean().optional(),price_ids:e.array(e.string()).optional(),product_ids:e.array(e.string()).optional()})}))(w,Sl),{RewardEntitlementSchema:jl}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(w,po),{UpdateRewardSchema:YP}=((e,t,n,r,i,o)=>({UpdateRewardSchema:e.object({name:e.string().nullish(),promo_codes:e.array(t).optional(),id:e.string().optional(),type:e.nativeEnum(n).optional(),discount_config:r.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(o).nullish()})}))(w,_l,yl,Rl,vl,jl),{CreateRewardProgram:JP}=((e,t,n)=>({CreateRewardProgram:e.object({id:e.string(),when:e.enum(t),product_ids:e.array(e.string()).optional(),exclude_trial:e.boolean().optional(),internal_reward_id:e.string(),max_redemptions:e.number().optional(),received_by:e.enum(n)})}))(w,Ib,Ab),{AutoTopupPurchaseLimitSchema:kl}=((e,t)=>({AutoTopupPurchaseLimitSchema:e.object({interval:t.meta({description:"The time interval for the purchase limit window."}),interval_count:e.number().min(1).default(1).meta({description:"Number of intervals in the purchase limit window."}),limit:e.number().min(1).meta({description:"Maximum number of auto top-ups allowed within the interval."})})}))(w,wb),{UsageLimitFilterSchema:Dl}=((e,t,n,r)=>({UsageLimitFilterSchema:e.object({properties:e.record(e.string().min(1).max(t),n).meta({description:"Event property equality conditions. A usage event counts toward this cap only when every listed property matches (AND)."}).check(o=>{let a=Object.keys(o.value).length;(a<1||a>r)&&o.issues.push({code:"custom",message:`filter.properties must have between 1 and ${r} keys`,input:o.value})})})}))(w,Rg,Ob,kg),{UsageAlertBasisSchema:Gb}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(w,Cb),{refineCustomizePlanV1Schema:Nl}=(e=>({refineCustomizePlanV1Schema:(n,{includeItems:r=!0,includeFreeTrial:i=!0,includeUpdateItems:o=!0,includeLicenses:a=!0}={})=>{let s=["price",r&&"items","add_items","remove_items",o&&"update_items",i&&"free_trial","billing_controls",a&&"upsert_licenses",a&&"remove_licenses"].filter(Boolean),c=u=>u==="update_items"?"deprecated update_items":u;return n.refine(u=>s.some(l=>u[l]!==void 0),{message:`When using customize, at least one of ${s.map(c).join(", ")} must be provided`}).superRefine((u,l)=>{if(a)for(let d of e({upsertLicenses:u.upsert_licenses}))l.addIssue({code:"custom",...d})}).refine(u=>!(u.items!==void 0&&(u.add_items!==void 0||u.remove_items!==void 0||o&&u.update_items!==void 0)),{message:`customize.items (PUT-style) cannot be combined with ${["add_items","remove_items",o?"deprecated update_items":null].filter(Boolean).join(" / ")} (PATCH-style); pick one approach`})}}))(Eb),{SUPPORTED_SET:$b}=(e=>({SUPPORTED_SET:new Set(e)}))(Rb),{ApiCreditDimensionBaseSchema:Kb}=((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,wl),{refineGraduatedTiers:Fl}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(o=>o.to));for(let{index:o,message:a}of i)r.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(jb),{ApiFeatureMarkupsOverrideSchema:Wb}=((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,Pl,$a),{AutoTopupPurchaseLimitParamsSchema:Hb}=((e,t)=>({AutoTopupPurchaseLimitParamsSchema:e.extend({count:t.number().min(0).optional().meta({description:"Set the current window's consumed auto top-up count. Omit to leave runtime state unchanged."})})}))(kl,w),{DUPLICATE_CHECKS:Qb}=((e,t,n,r)=>({DUPLICATE_CHECKS:[e({controlKey:"auto_topups",identityOf:t,field:"feature_id",message:"Only one auto top-up entry is allowed per feature_id"}),e({controlKey:"spend_limits",identityOf:t,field:"feature_id",message:"Only one spend limit entry is allowed per feature_id"}),e({controlKey:"usage_limits",identityOf:n,field:"feature_id",message:"Only one usage limit entry is allowed per feature_id and filter"}),e({controlKey:"usage_alerts",identityOf:r,field:"threshold",message:"Only one usage alert entry is allowed per feature_id, basis, filter, threshold_type and threshold"}),e({controlKey:"overage_allowed",identityOf:t,field:"feature_id",message:"Only one overage_allowed entry is allowed per feature_id"})]}))(Nb,Wg,Ya,Hg),{ApiPlanProcessorsSchema:Zb}=((e,t,n)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:n.nullish()}).meta({"x-atmn-mapping":!0})}))(w,Jg,Fb),{FixedPriceConfigSchema:Yb}=((e,t,n,r,i)=>({FixedPriceConfigSchema:e.object({type:e.string(),amount:e.number().min(0),interval:e.enum(t),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),n).nullish(),billing_units:e.number().nullish(),usage_tiers:e.array(r).nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),feature_id:i,internal_feature_id:i})}))(w,Pn,El,Wa,cb),{CreditDimensionSchema:Jb}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(w,pb,hl,Tl),{filterUnresolvableUsageLimitAlerts:Xb}=((e,t,n)=>({filterUnresolvableUsageLimitAlerts:({usageAlerts:i,usageLimitLists:o})=>{let a=new Set(o.flatMap(s=>(s??[]).map(e)));return i.flatMap((s,c)=>t(s)&&!a.has(n(s))?[{index:c,usageAlert:s}]:[])}}))(Ya,xb,Vb),{CreateRewardSchema:XP}=((e,t,n,r,i,o)=>({CreateRewardSchema:e.object({name:e.string(),promo_codes:e.array(t),id:e.string(),type:e.nativeEnum(n).nullish(),discount_config:r.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(o).nullish()}).refine(s=>s.type!==n.FeatureGrant?!0:s.entitlements&&s.entitlements.length>0,{message:"Feature grant rewards require at least one entitlement"}).refine(s=>s.type!==n.FeatureGrant?!0:s.promo_codes.some(c=>c.code.length>0),{message:"Feature grant rewards require at least one promo code"})}))(w,_l,yl,Rl,vl,jl),{AutoTopupSchema:Ja}=((e,t)=>({AutoTopupSchema:e.object({feature_id:e.string().meta({description:"The ID of the feature (credit balance) to auto top-up."}),enabled:e.boolean().default(!1).meta({description:"Whether auto top-up is enabled."}),threshold:e.number().meta({description:"When the balance drops below this threshold, an auto top-up will be purchased."}),quantity:e.number().min(1).meta({description:"Amount of credits to add per auto top-up."}),purchase_limit:t.optional().meta({description:"Optional rate limit to cap how often auto top-ups occur."}),invoice_mode:e.boolean().optional().meta({description:"When true, auto top-up creates a send_invoice invoice instead of auto-charging."})})}))(w,kl),{DbUsageLimitSchema:Xa}=((e,t,n,r)=>({DbUsageLimitSchema:e.object({feature_id:e.string().meta({description:"The feature this usage limit applies to."}),enabled:e.boolean().default(!0).meta({description:"Whether this usage limit is enabled."}),limit:e.number().min(0).meta({description:"Maximum units allowed per interval."}),interval:e.enum(t).meta({description:"Interval for the cap, aligned to the customer's billing cycle."}),anchor:n.optional().meta({description:"Window alignment. 'billing_cycle' phases the interval to the customer's renewal time; 'utc' aligns to the UTC calendar."}),filter:r.optional().meta({description:"When set, only usage from events whose properties match counts toward this cap. Omit to count all usage of the feature."})})}))(w,Pb,xl,Dl),{DbUsageAlertSchema:za}=((e,t,n,r,i)=>({DbUsageAlertSchema:e.object({feature_id:e.string().optional().meta({description:"The feature ID this alert applies to."}),enabled:e.boolean().default(!0).meta({description:"Whether this usage alert is enabled."}),threshold:e.number().min(0).meta({description:"The threshold value that triggers the alert. For usage or remaining, this is an absolute count. For usage_percentage or remaining_percentage, this is a percentage (0-100)."}),threshold_type:t.meta({description:"Whether the threshold is an absolute count or a percentage of the usage allowance or remaining balance."}),basis:n.default(r).meta({description:"What 100% means. balance: every grant on the feature. included: the plan allowance only. recurring: grants that reset. usage_limit: the cap of the usage limit with the same feature and filter."}),filter:i.optional().meta({description:"Only valid with basis usage_limit. Points the alert at the usage limit carrying the same filter."}),name:e.string().optional().meta({description:"Optional user-defined label to distinguish multiple alerts on the same feature."})}).check(a=>{let{feature_id:s,threshold_type:c,threshold:u,basis:l,filter:d}=a.value;c==="remaining_percentage"&&u>100&&a.issues.push({code:"custom",input:u,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),l==="usage_limit"&&!s&&a.issues.push({code:"custom",input:s,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),d&&l!=="usage_limit"&&a.issues.push({code:"custom",input:d,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(w,Dg,Gb,nl,Dl),{isValidCurrencyCode:zb}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))($b),{ApiCreditDimensionSchema:e_}=((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,Kb,cl,Fl),{AutoTopupParamsSchema:t_}=((e,t)=>({AutoTopupParamsSchema:e.extend({purchase_limit:t.optional().meta({description:"Optional rate limit to cap how often auto top-ups occur. Pass count to set the current window's consumed top-ups."})})}))(Ja,Hb),{findDuplicateBillingControlIssue:n_}=(e=>({findDuplicateBillingControlIssue:n=>{for(let r of e){let i=r(n);if(i)return i}}}))(Qb),{CustomerBillingControlsSchema:es}=((e,t,n,r,i,o)=>({CustomerBillingControlsSchema:e.object({auto_topups:e.array(t).optional().meta({description:"List of auto top-up configurations per feature."}),spend_limits:e.array(n).optional().meta({description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:e.array(r).optional().meta({description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:e.array(i).optional().meta({description:"List of usage alert configurations per feature."}),overage_allowed:e.array(o).optional().meta({description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})})}))(w,Ja,Qa,Xa,za,Ba),{PriceSchema:r_}=((e,t,n,r,i,o)=>({PriceSchema:e.object({id:e.string(),internal_product_id:e.string().nullable(),org_id:e.string().optional(),created_at:e.number().optional(),billing_type:e.nativeEnum(t).nullish(),tier_behavior:e.nativeEnum(n).nullish(),is_custom:e.boolean().optional(),config:r.or(i),entitlement_id:e.string().nullish(),proration_config:o.nullable()})}))(w,sb,li,Yb,Lb,lb),{CreditSchemaItemBaseSchema:Ul}=((e,t,n,r)=>({CreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(t,n).optional(),multipliers:e.record(t,r).optional()})}))(w,Al,Jb,fb),{GraduatedCreditSchemaItemSchema:i_}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(Ul,Tl),{UpdateProductSchema:zP}=((e,t,n)=>({UpdateProductSchema:e.object({id:e.string().nullish(),name:e.string().min(1,"Product name cannot be empty").optional(),description:e.string().nullish(),is_add_on:e.boolean().optional(),is_default:e.boolean().optional(),group:e.string().nullish(),archived:e.boolean().optional(),config:t.partial().optional(),billing_controls:n.optional()})}))(w,lo,es),{DbBillingControlsSchema:o_}=((e,t,n,r,i,o)=>({DbBillingControlsSchema:e.object({auto_topups:e.array(t).nullish(),spend_limits:e.array(n).nullish(),usage_limits:e.array(r).nullish(),usage_alerts:e.array(i).nullish(),overage_allowed:e.array(o).nullish()})}))(w,Ja,Qa,Xa,za,Ba),{CurrencyCodeSchema:Ml}=((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,zb),{AdditionalCurrencyTierSchema:a_}=((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,Ml),{ApiCreditSchemaItemBaseSchema:Bl}=((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,Al,e_,kb),{ApiFlatCreditSchemaItemSchema:s_}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Bl,w),{rejectDuplicateBillingControls:c_}=(e=>({rejectDuplicateBillingControls:n=>{let r=e(n.value);r&&n.issues.push(r)}}))(n_),{FlatCreditSchemaItemSchema:u_}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(Ul,hl),{ProductSchema:l_}=((e,t,n,r,i)=>({ProductSchema:e.object({id:e.string(),name:e.string().min(1,"Product name cannot be empty"),description:e.string().nullable(),is_add_on:e.boolean(),is_default:e.boolean(),version:e.number(),version_slug:e.string().nullable().default(null),active:e.boolean().default(!1),deleted_at:e.number().nullable().default(null),previous_version_slug:e.string().nullable().default(null),group:e.string(),env:e.enum(t),internal_id:e.string(),org_id:e.string(),created_at:e.number(),processor:e.object({type:e.string(),id:e.string(),additional_ids:e.array(e.string()).optional()}).nullish(),base_variant_id:e.string().nullable(),base_internal_product_id:e.string().nullish(),archived:e.boolean().default(!1),config:n.default(()=>({ignore_past_due:!1})),...r.shape,metadata:i.default(()=>({}))})}))(w,ro,lo,o_,_r),{AdditionalCurrencyPriceSchema:d_}=((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,Ml),{AdditionalCurrencyTierArraySchema:Ll}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(w,a_,il,ol),{ApiGraduatedCreditSchemaItemSchema:p_}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Bl,w,cl,Fl),{CustomerBillingControlsParamsSchema:mo}=((e,t,n,r,i,o,a,s)=>({CustomerBillingControlsParamsSchema:e.object({auto_topups:t({schema:n,description:"List of auto top-up configurations per feature."}),spend_limits:t({schema:r,description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:t({schema:i,description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:t({schema:o,description:"List of usage alert configurations per feature."}),overage_allowed:t({schema:a,description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})}).check(s)}))(w,$g,t_,Qa,Xa,za,Ba,c_),{CreditSchemaItemSchema:m_}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(w,u_,i_),{PriceTierSchema:f_}=((e,t,n)=>({PriceTierSchema:e.object({to:e.number().or(e.literal(t)).meta({description:"The maximum amount of usage for this tier.",example:100}),amount:e.number().optional().meta({description:"The price of the product item for this tier.",example:10}),flat_amount:e.number().optional().meta({description:"A flat fee charged for this tier, in addition to the per-unit amount."}),additional_currencies:n.nullish().meta({description:"Per-currency amounts for this tier. Boundaries ('to') are shared across currencies."})}).refine(i=>i.amount!=null||i.flat_amount!=null,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0}))}))(w,yb,Ll),{PlanBillingControlsParamsSchema:h_}=((e,t)=>({PlanBillingControlsParamsSchema:e.check(r=>{let i=t({usageAlerts:r.value.usage_alerts??[],usageLimitLists:[r.value.usage_limits??[]]});for(let{index:o,usageAlert:a}of i)r.issues.push({code:"custom",message:`No usage limit on this plan matches the usage_limit alert for feature ${a.feature_id}`,input:a,path:["usage_alerts",o,"basis"]})})}))(mo,Xb),{AdditionalCurrencyPriceArraySchema:pi}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(w,d_,il,ol),{ApiUsageTierWithCurrenciesSchema:ql}=((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,io,Ll),{ApiCreditSchemaItemSchema:g_}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(w,p_,s_),{FeatureConfigOverrideSchema:Vl}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(w,m_,qb),{ProductItemConfigSchema:b_}=((e,t,n,r,i,o,a)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(n).nullish(),on_decrease:e.enum(r).nullish(),rollover:i.nullish(),expiry:o.nullish(),feature_override:a.nullish()})}))(w,ml,ao,so,fl,po,Vl),{BasePriceParamsSchema:fo}=((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."})}))(Tb,ui,w,pi),{PlanItemPriceParamsSchema:__}=((e,t,n,r,i,o,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??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(o).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,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,pi,ql,li,Pn,oo,Il),{ApiFeatureOverrideSchema:Gl}=((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,g_,Wb),{ApiPlanItemV1Schema:y_}=((e,t,n,r,i,o,a,s,c,u,l,d,m,g,p,f,y)=>({ApiPlanItemV1Schema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature this item configures."}),feature:t.optional().meta({description:"The full feature object if expanded."}),included:e.number().meta({description:"Number of free units included. For consumable features, balance resets to this number each interval."}),unlimited:e.boolean().meta({description:"Whether the customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"The interval at which the feature balance resets (e.g. 'month', 'year'). For consumable features, usage resets to 0 and included units are restored."}),interval_count:e.number().optional().meta({description:"Number of intervals between resets. Defaults to 1."})}).nullable().meta({description:"Reset configuration for consumable features. Null for non-consumable features like seats where usage persists across billing cycles."}),price:e.object({amount:e.number().optional().meta({description:"Price per billing_units after included usage is consumed. Mutually exclusive with tiers."}),additional_currencies:r.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' (tiered prices carry per-currency amounts on each tier)."}),tiers:e.array(i).optional().meta({description:"Tiered pricing configuration. Each tier's 'to' INCLUDES the included amount. Either 'tiers' or 'amount' is required."}),tier_behavior:e.enum(o).optional(),interval:e.enum(a).meta({description:"Billing interval for this price. For consumable features, should match reset.interval."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().meta({description:"Number of units per price increment. Usage is rounded UP to the nearest billing_units when billed (e.g. billing_units=100 means 101 usage rounds to 200)."}),billing_method:e.enum(s).meta({description:"'prepaid' for features like seats where customers pay upfront, 'usage_based' for pay-as-you-go after included usage."}),allocated_billing:c,max_purchase:e.number().nullable().meta({description:"Maximum units a customer can purchase beyond included. E.g. if included=100 and max_purchase=300, customer can use up to 400 total before usage is capped. Null for no limit."}),processors:u.optional().meta({description:"Payment processors this item price is connected to. Omitted when unset."})}).nullable().meta({description:"Pricing configuration for usage beyond included units. Null if feature is entirely free."}),display:l.optional().meta({description:"Display text for showing this item in pricing pages."}),rollover:e.object({max:e.number().nullable().meta({description:"Maximum rollover units. Null for unlimited rollover."}),max_percentage:e.number().nullable().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(d).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover configuration for unused units. If set, unused included units roll over to the next period."}),proration:e.object({on_increase:e.enum(m).optional().meta({description:"How to handle billing when quantity increases mid-cycle."}),on_decrease:e.enum(g).optional().meta({description:"How to handle credits when quantity decreases mid-cycle."})}).optional().meta({internal:!0}),expiry:p.nullish().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:f.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),mapping_identity:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})}).check(S=>{let j=S.value.reset?.interval,A=S.value.price?.interval,v=S.value.reset?.interval_count??1,G=S.value.price?.interval_count??1;if(j&&A&&(String(j)!==String(A)||v!==G)&&S.value.price?.billing_method!==s.Prepaid&&S.issues.push({code:"custom",message:"reset.interval and price.interval can only differ for prepaid prices.",input:S.value}),S.value!==void 0&&S.value.price!==void 0&&S.value.price!==null){S.value.price.amount&&S.value.price.tiers&&S.value.price.tiers.length>0&&S.issues.push({code:"custom",message:"Price amount and tiers are mutually exclusive.",input:S.value});for(let Pe of y(S.value.price))S.issues.push({code:"custom",message:Pe,input:S.value.price})}})}))(w,Cl,ci,pi,ql,li,Pn,oo,Il,Ol,La,Va,ao,so,po,Gl,ll),{EntitlementSchema:S_}=((e,t,n,r,i,o)=>({EntitlementSchema:e.object({id:e.string(),created_at:e.number(),internal_feature_id:e.string(),internal_product_id:e.string().nullable(),internal_reward_id:e.string().nullish(),is_custom:e.boolean().default(!1),allowance_type:e.nativeEnum(t).optional().nullable(),allowance:e.number().nullish(),interval:e.nativeEnum(n).optional().nullable(),interval_count:e.number().default(1),carry_from_previous:e.boolean().default(!1).optional(),entity_feature_id:e.string().nullish(),pooled:e.boolean().default(!1).optional(),org_id:e.string().optional(),feature_id:e.string().optional(),usage_limit:e.number().nullable().optional().default(null),expiry_duration:e.nativeEnum(r).nullish(),expiry_length:e.number().nullish(),rollover:i.nullish(),feature_override:o.nullish()})}))(w,db,pl,sl,fl,Vl),{ProductItemSchema:$l}=((e,t,n,r,i,o,a,s,c,u,l)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(m=>{if(m==="")throw new Error("Interval cannot be empty.");return m},e.enum(o).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(a).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(u).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:l.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(o).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(w,hb,gb,Cl,io,bb,_b,f_,pi,li,b_),{ProductV2Schema:Kl}=((e,t,n,r,i,o,a)=>({ProductV2Schema:e.object({internal_id:e.string().nullish(),id:e.string(),name:e.string(),description:e.string().nullish(),is_add_on:e.boolean(),is_default:e.boolean(),version:e.number().default(1),version_slug:e.string().nullable().optional(),active:e.boolean().optional(),group:e.string().nullable(),env:e.nativeEnum(t),free_trial:n.nullish(),items:e.array(r),created_at:e.number(),stripe_id:e.string().nullish(),archived:e.boolean().default(!1).nullish(),base_internal_product_id:e.string().nullish(),base_id:e.string().nullish(),config:i.partial().optional(),billing_controls:o.optional(),metadata:a.optional()})}))(w,ro,vb,$l,lo,es,_r),{PlanItemParamsObjectSchema:v_}=((e,t,n,r,i,o,a,s,c,u,l)=>({PlanItemParamsObjectSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature to configure."}),included:t.optional().meta({description:"Number of free units included. Balance resets to this each interval for consumable features."}),unlimited:e.boolean().optional().meta({description:"If true, customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"Interval at which balance resets (e.g. 'month', 'year'). For consumable features only."}),interval_count:r({schema:e.number().optional(),defaultValue:1,description:"Number of intervals between resets. Defaults to 1."})}).optional().meta({description:"Reset configuration for consumable features. Omit for non-consumable features like seats."}),price:i.optional().meta({description:o}),proration:e.object({on_increase:e.enum(a).meta({description:"Billing behavior when quantity increases mid-cycle."}),on_decrease:e.enum(s).meta({description:"Credit behavior when quantity decreases mid-cycle."})}).optional().meta({description:"Proration settings for prepaid features. Controls mid-cycle quantity change billing."}),rollover:e.object({max:e.number().optional().meta({description:"Max rollover units. Omit for unlimited rollover."}),max_percentage:e.number().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(c).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover config for unused units. If set, unused included units carry over."}),expiry:u.optional().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:l.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})})}))(w,qa,ci,ui,__,Bg,ao,so,Va,po,Gl),{FullProductWithoutLicensesSchema:eO}=((e,t,n,r,i,o)=>({FullProductWithoutLicensesSchema:e.extend({description:t.string().nullable().optional().default(null),prices:t.array(n),entitlements:t.array(r.extend({feature:i})),free_trial:o.nullish(),free_trials:t.array(o).nullish(),free_trial_ids:t.array(t.string()).nullish()})}))(l_,w,r_,S_,Bb,ab),{CreateProductItemParamsSchema:Wl}=((e,t,n,r)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(n.literal(r)).nullish()})}))($l,qa,w,io),{CreatePlanItemParamsV1Schema:ts}=((e,t)=>({CreatePlanItemParamsV1Schema:e.check(r=>{for(let{message:i,input:o}of t(r.value))r.issues.push({code:"custom",message:i,input:o})}).meta({title:"PlanItem",description:"Configuration for a feature item in a plan, including usage limits, pricing, and rollover settings."})}))(v_,Db),{LicenseCustomizeSchema:Hl}=((e,t,n,r)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(n).optional(),remove_items:e.array(r).optional()})}))(w,fo,ts,Ka),{PlanLicenseParamsSchema:ns}=((e,t)=>({PlanLicenseParamsSchema:e.object({license_plan_id:e.string(),version_slug:e.string().optional(),included:e.number().int().min(0).optional(),prepaid_only:e.boolean().optional(),customize:t.nullish(),metadata:e.record(e.string(),e.unknown()).optional()})}))(w,Hl),{UpdateProductV2ParamsSchema:tO}=((e,t,n,r,i,o,a,s,c)=>({UpdateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).optional().meta({description:n.id}),name:e.string().refine(l=>l.length>0,{message:"name must be a non-empty string"}).optional().meta({description:n.name}),is_add_on:e.boolean().optional().meta({description:n.is_add_on}),is_default:e.boolean().optional().meta({description:n.is_default}),base_plan_id:e.string().nonempty().regex(t).nullable().optional().meta({description:"The base plan this plan should be linked to as a variant. Set to null to detach it from its base plan."}),description:e.string().nullish().optional().meta({description:n.description}),group:e.string().nonempty().nullable().optional().meta({description:n.group}),archived:e.boolean().optional().meta({description:n.archived}),items:e.array(r).optional(),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:o.nullish().meta({description:n.free_trial}),config:a.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata})})}))(w,uo,gl,Wl,ns,bl,Ha,mo,_r),{CreatePlanParamsV1Schema:x_}=((e,t,n,r,i,o,a,s,c)=>({CreatePlanParamsV1Schema:e.object({id:e.string().nonempty().regex(t).meta({description:"Unique identifier for the plan."}),group:e.string().default("").meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),name:e.string().nonempty().meta({description:"Display name of the plan."}),description:e.string().nullable().default(null).meta({description:"Optional description of the plan."}),add_on:e.boolean().default(!1).meta({description:"If true, this plan can be attached alongside other plans. Otherwise, attaching replaces existing plans in the same group."}),auto_enable:e.boolean().default(!1).meta({description:"If true, plan is automatically attached when a customer is created. Use for free tiers."}),price:n.optional().meta({description:"Base recurring price for the plan. Omit for free or usage-only plans."}),items:e.array(r).optional().meta({description:"Feature configurations for this plan. Each item defines included units, pricing, and reset behavior."}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:o.optional().meta({description:"Free trial configuration. Customers can try this plan before being charged."}),config:a.optional().meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:"Arbitrary key-value metadata defined by you for your own use (e.g. UI copy, feature highlights). Values can be any JSON-serializable value. Shared across all versions of the plan."}),create_in_stripe:e.boolean().default(!0).meta({internal:!0})})}))(w,uo,fo,ts,ns,Za,Ha,h_,_r),{UpdatePlanParamsV1Schema:nO}=((e,t,n,r,i)=>({UpdatePlanParamsV1Schema:e.partial().extend({group:e.shape.group.removeDefault().optional(),version:t.number().optional(),archived:t.boolean().default(!1).optional(),price:n.nullable().optional().meta({description:"The price of the plan. Set to null to remove the base price."}),free_trial:r.nullable().optional().meta({description:"The free trial of the plan. Set to null to remove the free trial."}),base_plan_id:t.string().nonempty().regex(i).nullable().optional().meta({description:"The base plan this plan should be linked to as a variant. Set to null to detach it from its base plan."})})}))(x_,w,fo,Za,uo),{CustomizePlanLicenseSchema:rs}=((e,t)=>({CustomizePlanLicenseSchema:e.object({license_plan_id:e.string(),version_slug:e.string().optional(),included:e.number().int().min(0).optional(),prepaid_only:e.boolean().optional(),customize:t.nullish(),metadata:e.record(e.string(),e.unknown()).optional()})}))(w,Hl),{CreateProductV2ParamsSchema:rO}=((e,t,n,r,i,o,a,s,c,u)=>({CreateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).meta({description:n.id}),name:e.string().refine(d=>d.length>0,{message:"name must be a non-empty string"}).meta({description:n.name}),description:e.string().nullish().meta({description:n.description}),is_add_on:e.boolean().default(!1).meta({description:n.is_add_on}),is_default:e.boolean().default(!1).meta({description:n.is_default}),group:e.string().nullable().default("").meta({description:n.group}),items:e.array(r).optional().meta({description:n.items}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:o.nullish().default(null).meta({description:n.free_trial}),config:a.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata}),create_in_stripe:e.boolean().optional().meta({internal:!0}),archived:e.boolean().optional().meta({internal:!0}),base_internal_product_id:e.string().nullable().optional().meta({internal:!0})}).meta({examples:[u]})}))(w,uo,gl,Wl,ns,bl,Ha,mo,_r,Sb),{CustomizePlanV1BaseSchema:Ql}=((e,t,n,r,i,o,a,s,c)=>({CustomizePlanV1BaseSchema:e.object({price:t.nullable().optional().meta({description:"Override the base price of the plan. Pass null to remove the base price."}),items:e.array(n).optional().meta({description:"Override the items in the plan (PUT-style \u2014 replaces all existing items). Mutually exclusive with add_items / remove_items / deprecated update_items."}),add_items:e.array(n).optional().meta({description:"Items to add to the plan."}),remove_items:e.array(r).optional().meta({description:"Filters selecting items to remove from the plan."}),update_items:e.array(i).optional().meta({description:"Deprecated. Use remove_items and add_items to replace matched plan items.",internal:!0,deprecated:!0}),free_trial:o.nullable().optional().meta({description:"Override the plan's default free trial. Pass an object to set a custom trial, or null to remove the trial entirely."}),billing_controls:a.optional().meta({description:"Override the plan's billing controls (auto top-ups, spend limits, usage limits, usage alerts, overage allowed) for this customer."}),upsert_licenses:e.array(s).optional().meta({description:"License links to add or override for this customer, keyed by license_plan_id. Omitted fields inherit the plan catalog link (included defaults to 1 when the license is not in the catalog). A bare entry restores the license to pure catalog inheritance."}),remove_licenses:e.array(c).optional().meta({description:"License links to drop, keyed by license_plan_id. Parallel to remove_items."})})}))(w,fo,ts,Ka,Gg,Za,mo,rs,Qg),{VariantCustomizeSchema:I_}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(Nl,Ql),{DiffedCustomizePlanV1Schema:iO}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(Nl,Ql),{ApiPlanV1Schema:oO}=((e,t,n,r,i,o,a,s,c,u,l,d,m,g)=>({ApiPlanV1Schema:e.object({id:e.string().meta({description:"Unique identifier for the plan."}),internal_id:e.string().nullable().optional().meta({description:"Stable row id. Survives renames of plan_id and version_slug, so config files address rows by it.",internal:!0}),name:e.string().meta({description:"Display name of the plan."}),description:e.string().nullable().meta({description:"Optional description of the plan."}),group:e.string().nullable().meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),version:e.number().meta({description:"Version number of the plan. Incremented when plan configuration changes."}),version_slug:e.string().nullable().optional().meta({description:"User-facing version identity. Defaults to v{n} when the version is minted."}),active:e.boolean().optional().meta({description:"Whether this is the active version of the plan. At most one version is active."}),add_on:e.boolean().meta({description:"Whether this is an add-on plan that can be attached alongside a main plan."}),auto_enable:e.boolean().meta({description:"If true, this plan is automatically attached when a customer is created. Used for free plans."}),price:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),additional_currencies:t.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),interval:e.enum(n).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0}),display:r.optional().meta({description:"Display text for showing this price in pricing pages."}),processors:i.optional().meta({description:"Payment processors this base price is connected to. Omitted when unset."})}).nullable().meta({description:"Base recurring price for the plan. Null for free plans or usage-only plans."}),items:e.array(o).meta({description:"Feature configurations included in this plan. Each item defines included units, pricing, and reset behavior for a feature."}),processors:a.optional().meta({description:"Payment processors this plan is connected to. Omitted when unset."}),free_trial:s.optional().meta({description:"Free trial configuration. If set, new customers can try this plan before being charged."}),created_at:e.number().meta({description:"Unix timestamp (ms) when the plan was created."}),env:e.enum(c).meta({description:"Environment this plan belongs to ('sandbox' or 'live')."}),archived:e.boolean().meta({description:"Whether the plan is archived. Archived plans cannot be attached to new customers."}),config:u.meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:l.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:d.meta({description:"Arbitrary key-value metadata defined by you for your own use. Shared across all versions of the plan."}),customer_eligibility:m.optional(),base_variant_id:e.string().nullable().meta({description:"Deprecated. Use variant_details.base_plan_id instead. If this is a variant, the ID of the base plan it was created from.",deprecated:!0}),variant_details:e.object({base_plan_id:e.string().meta({description:"The ID of the base plan this variant was derived from."}),customize:g.optional().meta({description:"The customization that transforms the base plan into this variant."})}).optional().meta({description:"Details about how this variant relates to its latest base plan."})})}))(w,pi,Pn,La,Ol,y_,Zb,Ub,ro,lo,es,_r,Mb,I_);import{z as P}from"zod";var A_=P.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Jl=P.enum(["single_use","continuous_use"]),is=P.record(P.string(),P.union([P.string(),P.number(),P.boolean()]).transform(String).pipe(P.string())),Zl=P.string().min(1).max(64).refine(e=>!e.includes("::")),Xl={credit_amount:P.number(),tier_behavior:P.never().optional(),tiers:P.never().optional()},zl={credit_amount:P.never().optional(),tier_behavior:P.literal("graduated"),tiers:P.array(P.strictObject({to:P.union([P.number(),P.literal("inf")]),credit_amount:P.number()}))},w_=P.union([P.strictObject({match:is,priority:P.number().int().optional(),...Xl}),P.strictObject({match:is,priority:P.number().int().optional(),...zl})]),P_=P.strictObject({match:is,factor:P.number().positive().optional(),add:P.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Yl={metered_feature_id:P.string(),feature_amount:P.number().optional(),dimensions:P.record(Zl,w_).optional(),multipliers:P.record(Zl,P_).optional()},os=P.union([P.strictObject({...Yl,...Xl}),P.strictObject({...Yl,...zl})]),go=P.number().min(-100),ed=P.record(P.string(),P.strictObject({markup:go})).nullish(),bo=P.record(P.string().regex(/.+\/.+/),P.strictObject({markup:go.optional(),input_cost:P.number().min(0).optional(),output_cost:P.number().min(0).optional()})).nullish(),O_=P.strictObject({default_markup:go.optional(),provider_markups:ed,model_markups:bo}),as=P.strictObject({schema:P.array(os).optional(),markups:O_.optional()}),C_=P.strictObject({filters:P.array(P.strictObject({property:P.string(),operator:P.string(),value:P.array(P.string())})),aggregate:P.strictObject({type:P.string(),property:P.string().nullable()}),usage_type:Jl}),td=P.strictObject({schema:P.array(os).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:P.boolean().optional(),usage_type:Jl.default("single_use").overwrite(()=>"single_use"),default_markup:go.optional(),provider_markups:ed}),ss=td.safeExtend({schema:P.array(os).length(0)}),ho={id:A_,name:P.string().min(1),display:P.strictObject({singular:P.string().optional(),plural:P.string().optional()}).nullish(),event_names:P.array(P.string()).default([]),model_markups:bo,stripe_meter:P.strictObject({id:P.string(),event_name:P.string()}).nullish(),stripe_product_id:P.string().nullish()},cs=e=>P.discriminatedUnion("type",[P.strictObject({...ho,...e,type:P.literal("boolean"),config:P.null()}),P.strictObject({...ho,...e,type:P.literal("metered"),config:C_}),P.strictObject({...ho,...e,type:P.literal("credit_system"),config:td}),P.strictObject({...ho,...e,type:P.literal("ai_credit_system"),config:ss})]),cO=cs({}),E_=P.strictObject({id:P.boolean(),type:P.boolean(),usage_type:P.boolean()}),T_={internal_id:P.uuid(),org_id:P.uuid(),created_at:P.number(),env:P.enum(["sandbox","live"]),archived:P.boolean(),project_id:P.uuid(),environment_id:P.uuid(),revision:P.number().int().nonnegative(),update_rules:E_},nd=cs(T_),uO=P.strictObject({rows:P.array(nd).max(200),nextCursor:P.uuid().nullable()}),rd=P.strictObject({features:P.array(nd).max(500),limited:P.boolean()}),lO=P.union([cs({action:P.literal("save"),internal_id:P.uuid().nullable(),revision:P.number().int().nonnegative()}),P.strictObject({action:P.enum(["archive","restore","delete"]),internal_id:P.uuid(),revision:P.number().int().nonnegative()})]);import{z as yr}from"zod";var id=yr.number().int().min(0).max(1e8),mi=yr.strictObject({kind:yr.enum(["graduated","volume"]),tiers:yr.array(yr.strictObject({upTo:yr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:id,flatAmountMinor:id.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function us(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?mi.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let o of n.tiers){let a=o.upTo??1e4;if(n.kind==="volume"){if(t<=a){r=BigInt(t)*BigInt(o.unitAmountMinor)+BigInt(o.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,a)-i)*BigInt(o.unitAmountMinor));i=a}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function _o(e){return us({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}import{z as R}from"zod";import{z as K}from"zod";import{z as an}from"zod";import{z as _n}from"zod";var gO={plans:Hn,creditPacks:Hn,paidSeats:Hn,postpaid:Hn},od=_n.partialRecord(_n.enum(Hn),_n.number().int().min(1).max(1e8)),R_=_n.strictObject({currency:_n.enum(Hn),automaticTax:_n.boolean()}),j_=_n.strictObject({projectId:_n.uuid(),environmentId:_n.uuid()}),bO=j_.extend({settings:R_});var k_=an.string().regex(/^[a-z][a-z0-9_]{0,63}$/),ad=an.number().int().min(0).max(1e4),ls=an.object({key:k_,featureId:an.uuid(),planVersionId:an.uuid(),includedQuantity:ad,maximumQuantity:ad,unitAmountCents:an.number().int().min(0).max(1e8),currency:re,currencyOptions:od.optional(),stripePriceId:an.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),pooledResources:an.array(an.string().regex(/^(?:[a-z][a-z0-9_]{0,63}|pool:[0-9a-f-]{36})$/)).max(100),requireAssignment:an.boolean()}).strict().refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency),"Additional prices cannot repeat the default currency").refine(e=>e.maximumQuantity>=e.includedQuantity,"\u6700\u5927\u5E2D\u4F4D\u6570\u4E0D\u80FD\u5C0F\u4E8E\u5305\u542B\u5E2D\u4F4D\u6570").refine(e=>new Set(e.pooledResources).size===e.pooledResources.length,"\u5171\u4EAB\u6765\u6E90\u4E0D\u80FD\u91CD\u590D");import{z as Oe}from"zod";import{z as st}from"zod";var ds=st.object({days:st.number().int().min(1).max(730),cardRequired:st.boolean(),featureAllowances:st.record(st.uuid(),st.number().int().min(0).max(1e9)),creditAmounts:st.record(st.uuid(),_e)}).strict(),ps=st.object({id:st.uuid(),planVersionId:st.uuid(),slot:st.string(),cardRequired:st.boolean(),status:st.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:st.iso.datetime().nullable(),endsAt:st.iso.datetime().nullable(),createdAt:st.iso.datetime()}).strict();var ms=Oe.object({group:Oe.string().regex(/^[a-z][a-z0-9_]{0,63}$/).default("main"),kind:Oe.enum(["main","addon"]).default("main")}).strict(),D_=Oe.enum(["immediate","end_of_cycle"]),N_=Oe.enum(["attach","change","cancel","resume","cancel_change"]),sd=Oe.object({id:Oe.uuid(),subscriptionId:Oe.uuid().nullable(),targetPlanVersionId:Oe.uuid().nullable(),action:N_,timing:D_,status:Oe.enum(["preparing","payment_pending","scheduled","completed","canceled","failed"]),effectiveAt:Oe.iso.datetime().nullable(),createdAt:Oe.iso.datetime()}),F_=Oe.object({id:Oe.uuid(),planVersionId:Oe.uuid(),planId:Oe.uuid(),basePlanId:Oe.uuid().nullable(),name:Oe.string(),group:Oe.string(),kind:Oe.enum(["main","addon"]),source:Oe.enum(["subscription","assignment","license","apple","google"]),status:Oe.string(),accessEnabled:Oe.boolean(),startsAt:Oe.iso.datetime().nullable(),endsAt:Oe.iso.datetime().nullable(),cancelAtPeriodEnd:Oe.boolean(),scheduledChange:sd.nullable(),trial:ps.nullable().optional()}),CO=Oe.object({customerId:Oe.uuid(),evaluatedAt:Oe.iso.datetime(),holdings:Oe.array(F_),changes:Oe.array(sd),trials:Oe.array(ps).optional()});var sn=K.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"),FO=K.record(K.string().min(1).max(80),K.union([K.string().max(500),K.number().finite(),K.boolean(),K.null()])).refine(e=>Object.keys(e).length<=30,"\u6700\u591A 30 \u4E2A\u5C5E\u6027"),cd=K.object({key:sn,name:K.string().trim().min(1).max(80),description:K.string().trim().max(240),type:K.enum(["boolean","metered"]),usageType:K.enum(["consumable","non_consumable"]).optional()}),UO=cd.extend({...ke.shape,id:K.string().min(1),archived:K.boolean(),createdAt:K.iso.datetime()}),ud=K.object({amountCents:K.number().int().min(0).max(1e8),currency:re,interval:K.enum(["free","month","year"]),currencyOptions:K.partialRecord(re,K.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"),U_=K.object({featureId:K.string().min(1),allowance:K.number().int().min(0).max(1e9).nullable(),pooled:K.boolean().optional()}),ld=K.object({name:K.string().trim().min(1).max(80),description:K.string().trim().max(240),price:ud,membership:ms.optional(),trial:ds.nullable().optional(),licenses:K.array(ls).max(20).optional(),items:K.array(U_).max(100).refine(e=>new Set(e.map(t=>t.featureId)).size===e.length,"\u540C\u4E00\u529F\u80FD\u4E0D\u80FD\u91CD\u590D\u52A0\u5165\u5957\u9910")}),MO=K.object({key:sn,config:ld}),BO=ke.extend({id:K.string().min(1),key:sn,draft:ld,status:K.enum(["draft","published","archived"]),publishedVersionId:K.string().nullable(),isDefault:K.boolean(),updatedAt:K.iso.datetime()}),M_=cd.pick({key:!0,name:!0,type:!0}).extend({featureId:K.string(),allowance:K.number().int().min(0).max(1e9).nullable(),pooled:K.boolean().optional()}).refine(e=>e.type==="boolean"?e.allowance===null:e.allowance!==null,"\u5F00\u5173\u578B\u65E0\u6570\u91CF\uFF0C\u8BA1\u91CF\u578B\u5FC5\u987B\u6307\u5B9A\u989D\u5EA6"),dd=ke.extend({id:K.string().min(1),planId:K.string().min(1),variant:K.object({basePlanId:K.uuid(),baseVersionId:K.uuid()}).nullable(),version:K.number().int().positive(),name:K.string(),description:K.string(),price:ud,membership:ms.optional(),trial:ds.nullable().optional(),licenses:K.array(ls).optional(),items:K.array(M_),publishedAt:K.iso.datetime()}).strict(),fs=K.object({startsAt:K.iso.datetime(),endsAt:K.iso.datetime().nullable()}).refine(e=>e.endsAt===null||Date.parse(e.endsAt)>Date.parse(e.startsAt),"\u5230\u671F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u751F\u6548\u65F6\u95F4"),LO=ke.extend({id:K.string(),customerId:K.string(),planVersionId:K.string(),assignedAt:K.iso.datetime(),source:K.literal("demo"),validity:fs.nullable().default(null),used:K.record(K.string(),K.number().int().min(0))}),qO=ke.extend({id:K.string(),customerId:K.string(),at:K.iso.datetime(),message:K.string()});import{z as b}from"zod";import{z as ie}from"zod";var pd={"zh-Hans":{once:"\u9996\u671F\u51CF {discount}",repeating:"\u524D {months} \u4E2A\u6708\u6BCF\u6708\u51CF {discount}",forever:"\u6BCF\u671F\u51CF {discount}"},"zh-Hant":{once:"\u9996\u671F\u6E1B {discount}",repeating:"\u524D {months} \u500B\u6708\u6BCF\u6708\u6E1B {discount}",forever:"\u6BCF\u671F\u6E1B {discount}"},en:{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:{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:{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:{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:{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:{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:{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:{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:{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:{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:{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:{once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{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"}},KO=["zh-CN","zh-TW","zh-HK","en","ja","ko","es","fr","de","pt-BR","it","ru","vi","th","id","ar"];function hs(e){let t=eo(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(o=>["TW","HK","MO"].includes(o))?"zh-Hant":"zh-Hans":n[0]??"en",i=pd[r];return i?{locale:t,copy:i}:{locale:"en",copy:pd.en}}function B_(e,t,n="zh-CN"){let r=Qi(t);return Au(e,t,hs(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function L_(e,t="zh-CN"){let n=hs(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e.percentOff/100):B_(e.amountOffCents,e.currency,n)}var md={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 fd(e,t="zh-CN",n="month"){let r=hs(t),i=L_(e.discount,r.locale),o=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",a=r.locale.split("-")[0]??"en",s=a==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":a,c=e.duration.type==="repeating"&&n!=="month"?md[s]??md.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],u=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return c.replace("{discount}",i).replace("{months}",o).replace("{period}",u)}var JO=ie.enum(["draft","active","paused","archived"]),On=ie.discriminatedUnion("type",[ie.object({type:ie.literal("percent"),percentOff:ie.number().int().min(1).max(100)}).strict(),ie.object({type:ie.literal("amount"),amountOffCents:ie.number().int().min(1).max(1e8),currency:re}).strict()]),Dt=ie.discriminatedUnion("type",[ie.object({type:ie.literal("once")}).strict(),ie.object({type:ie.literal("repeating"),months:ie.number().int().min(1).max(36)}).strict(),ie.object({type:ie.literal("forever")}).strict()]),yo=ie.discriminatedUnion("type",[ie.object({type:ie.literal("all")}).strict(),ie.object({type:ie.literal("plans"),planIds:ie.array(ie.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()]),q_=ie.strictObject({firstPurchaseOnly:ie.boolean(),condition:wn}),hd=ie.object({name:ie.string().trim().min(1).max(80),description:ie.string().max(500),discount:On,duration:Dt,appliesTo:yo,eligibility:q_,selfClaimEnabled:ie.boolean().default(!1),startsAt:ie.iso.datetime().nullable(),endsAt:ie.iso.datetime().nullable(),totalLimit:ie.number().int().min(1).max(1e6).nullable(),perCustomerLimit:ie.number().int().min(1).max(10),grantWindowHours:ie.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"]}),XO=ie.object({code:ie.string().trim().transform(e=>e.toUpperCase()).pipe(ie.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:ie.number().int().min(1).max(1e6).nullable(),expiresAt:ie.iso.datetime().nullable(),firstPurchaseOnly:ie.boolean(),minimumAmountCents:ie.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:re.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");function zO(){return{name:"\u65B0\u4F18\u60E0\u5238",description:"",discount:{type:"percent",percentOff:20},duration:{type:"once"},appliesTo:{type:"all"},eligibility:{firstPurchaseOnly:!1,condition:{}},selfClaimEnabled:!1,startsAt:null,endsAt:null,totalLimit:null,perCustomerLimit:1,grantWindowHours:72}}var gs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function eC(e,t,n){if(e==="draft")return[];if(e==="archived")return[{field:"name",reason:"archived"}];let r=[];return gs(t.discount,n.discount)||r.push({field:"discount",reason:"immutable"}),gs(t.duration,n.duration)||r.push({field:"duration",reason:"immutable"}),gs(t.appliesTo,n.appliesTo)||r.push({field:"appliesTo",reason:"immutable"}),t.startsAt!==n.startsAt&&r.push({field:"startsAt",reason:"immutable"}),t.endsAt!==n.endsAt&&(n.endsAt===null||t.endsAt!==null&&Date.parse(n.endsAt)>Date.parse(t.endsAt))&&r.push({field:"endsAt",reason:"only_earlier"}),t.totalLimit!==n.totalLimit&&(n.totalLimit===null||t.totalLimit!==null&&n.totalLimit>t.totalLimit)&&r.push({field:"totalLimit",reason:"only_reduce"}),n.perCustomerLimit>t.perCustomerLimit&&r.push({field:"perCustomerLimit",reason:"only_reduce"}),r}var V_=e=>`$${(e/100).toFixed(e%100===0?0:2)}`;function tC(e,t="zh-CN"){return fd(e,t)}function nC(e){return V_(e)}function rC(e,t){return e.startsAt&&Date.parse(e.startsAt)>t?"scheduled":e.endsAt&&Date.parse(e.endsAt)<=t?"ended":"open"}var fi=ie.object({id:ie.uuid(),couponId:ie.uuid(),status:ie.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:ie.iso.datetime(),expiresAt:ie.iso.datetime(),coupon:ie.object({name:ie.string(),discount:On,duration:Dt,appliesTo:yo}).strict()}).strict(),So=ie.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Sd=b.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),bs=b.string().regex(/^(0|[1-9]\d{0,14})$/),Sr=b.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),G_=b.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),hi=G_,yn=_e.refine(e=>/[1-9]/.test(e)),gt=b.iso.datetime({offset:!0}),Zn=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"))},$_=b.array(b.object({upTo:yn.nullable(),unitAmountMinor:Sd,flatAmountMinor:b.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&&Zn(t.upTo)>Zn(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),K_=b.discriminatedUnion("kind",[b.object({kind:b.literal("flat"),units:yn,unitAmountMinor:Sd}).strict(),b.object({kind:b.enum(["graduated","volume"]),units:yn,tiers:$_}).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"),W_=b.strictObject({interval:b.enum(["month","year"]),count:b.number().int().min(1).max(12),anchor:b.enum(["membership","calendar"])}),Cn=b.object({currency:re,pricing:K_,billingCycle:W_.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function vd(e){return e.pricing.kind==="flat"&&Zn(e.pricing.units)>0n&&Zn(e.pricing.unitAmountMinor)===Zn(e.pricing.units)*BigInt(10**Qi(e.currency))}var gd={requestId:b.uuid(),productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:re},xd=b.strictObject({interval:b.enum(["hour","day","week","month"]),intervalCount:b.number().int().min(1).max(12),limit:b.number().int().min(1).max(1e6)}),Id=b.discriminatedUnion("kind",[b.object({...gd,kind:b.literal("auto_topup"),threshold:ka,quantity:yn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:xd.optional()}).strict(),b.object({...gd,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:hi,maxOutstandingMinor:hi}).strict()]),bd={productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:re},Ad=b.discriminatedUnion("kind",[b.object({...bd,kind:b.literal("auto_topup"),threshold:ka,quantity:yn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:xd.optional(),purchaseAmountMinor:hi,purchaseUnits:yn}).strict(),b.object({...bd,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:hi,maxOutstandingMinor:hi,cashPrice:Cn}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),vo=b.object({id:b.uuid(),terms:Ad,status:b.enum(["prepared","active","revoked","blocked"]),createdAt:gt,acceptedAt:gt.nullable(),effectiveAt:gt.nullable(),revokedAt:gt.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"),wd=b.object({authorizationId:b.uuid(),terms:Ad,setupUrl:b.url().nullable()}).strict(),Pd=b.object({authorizationId:b.uuid(),accepted:b.literal(!0)}).strict(),Od=b.object({authorizationId:b.uuid(),requestId:b.uuid()}).strict(),Cd=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),anchor:b.enum(["billing_cycle","utc"]).optional(),basis:b.enum(["usage","credits"]),filter:Xt.optional(),limit:_e.nullable(),thresholds:b.array(b.number().positive().max(1)).max(8),includedThresholds:b.array(b.number().positive().max(1)).max(8).optional(),absoluteThresholds:b.array(yn).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&&Zn(t)>Zn(i)}),"Notification thresholds must increase"),H_=Cd.safeExtend({requestId:b.uuid()}),_d={control:b.literal("overage"),requestId:b.uuid(),internal_feature_id:b.uuid(),entityId:b.uuid().nullable()},Q_=b.discriminatedUnion("action",[b.strictObject({..._d,action:b.literal("set"),allowed:b.boolean().nullable(),overageLimit:_e.nullable(),skipOverageBilling:b.boolean()}),b.strictObject({..._d,action:b.literal("remove")})]),Ed=b.union([H_,Q_]),Z_=b.strictObject({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),allowed:b.boolean().nullable(),overageLimit:_e.nullable(),skipOverageBilling:b.boolean(),interval:b.enum(["day","week","month","year"]),startsAt:gt,endsAt:gt,used:b.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:b.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:b.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Y_=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),anchor:b.enum(["billing_cycle","utc"]).optional(),basis:b.enum(["usage","credits"]),filter:Xt.optional(),startsAt:gt,endsAt:gt,used:Ot,reserved:Ot,limit:_e.nullable(),thresholds:b.array(b.number().positive().max(1)).max(8),notifiedThresholds:b.array(b.number().positive().max(1)).max(1024),includedThresholds:b.array(b.number().positive().max(1)).max(8).optional(),includedAllowance:b.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:b.array(b.number().positive().max(1)).max(1024).optional(),absoluteThresholds:b.array(yn).max(8).optional(),notifiedAbsoluteThresholds:b.array(yn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||_e.safeParse(e.used).success&&_e.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),J_=b.object({authorizationId:b.uuid(),status:b.enum(["idle","pending","blocked"]),taskId:b.uuid().nullable(),invoiceId:b.uuid().nullable(),hostedInvoiceUrl:b.url().nullable(),purchaseCount:b.number().int().nonnegative(),purchaseWindowEndsAt:gt.nullable(),attemptCount:b.number().int().nonnegative(),failedAttemptCount:b.number().int().nonnegative(),suspendedAt:gt.nullable(),nextAttemptAt:gt.nullable(),failureReason:b.string().min(1).max(240).nullable()}).strict(),Td=b.object({internal_feature_id:b.uuid().optional(),entityId:b.uuid().optional()}).strict(),_s=b.object({authorizations:b.array(vo).max(100),limits:b.array(Cd).max(100),overages:b.array(Z_).max(100).optional(),windows:b.array(Y_).max(200),autoTopups:b.array(J_).max(100),limited:b.boolean()}).strict(),X_=b.object({id:b.uuid(),internal_feature_id:b.uuid(),productVersionId:b.uuid(),authorizationId:b.uuid(),entityId:b.uuid().nullable(),units:_e,amountMinor:Sr,cashPrice:Cn}).strict(),gi=b.object({id:b.uuid(),sourceKind:b.enum(["product","usage","manual"]),providerInvoiceId:b.string().min(1).max(240).nullable(),status:b.enum(["accruing","open","pending","paid","failed","void"]),currency:re,startsAt:gt.nullable(),endsAt:gt.nullable(),amountMinor:b.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:b.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:bs,paidAmountMinor:bs,refundedAmountMinor:bs,createdAt:gt,hostedInvoiceUrl:b.url().nullable(),adjustment:b.object({originalInvoiceId:b.uuid(),amountMinor:b.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:gt.nullable()}).strict().nullable(),lines:b.array(X_).max(100),linesLimited:b.boolean()}).strict(),Rd=b.object({invoiceId:b.uuid(),accepted:b.literal(!0)}).strict(),jd=b.object({after:b.uuid().nullable(),limit:b.number().int().min(1).max(100)}).strict(),kd=b.object({rows:b.array(gi).max(100),nextCursor:b.uuid().nullable()}).strict(),yd=b.strictObject({id:b.string(),coupon:b.string(),start:b.number().nonnegative(),end:b.number().nullable()}),z_=b.strictObject({subscriptionId:b.string(),customerId:b.string(),accountId:b.string(),sourceItems:b.array(b.strictObject({id:b.string(),price_id:b.string(),quantity:b.number().int(),discounts:b.array(yd).optional()})).max(100),items:b.array(b.strictObject({id:b.string(),price:b.string(),quantity:b.number().int(),discounts:b.array(b.strictObject({coupon:b.string().optional(),terms:b.strictObject({id:b.string(),name:b.string().optional(),percent_off:b.number().optional(),amount_off:b.number().optional(),currency:b.string().optional(),duration:b.enum(["once","forever","repeating"]),duration_in_months:b.number().optional()}).optional(),discount:b.string().optional(),receipt:yd.optional()})).max(20)})).max(100)}),Dd=b.strictObject({membershipId:b.uuid(),requestId:b.uuid(),grantIds:b.array(b.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Nd=b.strictObject({membershipId:b.uuid(),operationId:b.uuid(),status:b.enum(["pending","effective"]),execution:z_.nullable(),grants:b.array(b.strictObject({id:b.uuid(),couponId:b.uuid(),name:b.string(),discount:On,duration:Dt,startedAt:gt.nullable()})).max(20)});import{z as bi}from"zod";var _i=bi.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),yi=bi.number().int().min(1).max(1e3),Yn=bi.object({cap:_e.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:bi.number().positive().max(1e4).nullable(),cycles:bi.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var ys={key:sn,name:R.string().trim().min(1).max(80),description:R.string().trim().max(240)},Fd=_e.refine(e=>/[1-9]/.test(e)),xo=R.array(R.object({currency:re,amountMinor:R.number().int().min(0).max(1e8)}).strict()).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique"),Ss=R.strictObject({units:Fd,prices:R.array(R.strictObject({currency:re,amountMinor:R.number().int().min(0).max(1e8),pricing:mi.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:R.number().int().min(0).max(1e4),maximumQuantity:R.number().int().min(1).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&us({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit"),ey=R.discriminatedUnion("kind",[R.object({kind:R.literal("access"),internal_feature_id:R.uuid()}).strict(),R.object({kind:R.literal("metered"),internal_feature_id:R.uuid(),usageUnit:R.enum(["count","micro_usd"]),amount:_e.nullable(),reset:_i,resetCount:yi,pooled:R.boolean(),rollover:Yn.nullable().optional(),cashPrice:Cn.nullable().optional(),prepaidPrice:Ss.optional(),feature_override:as.nullish()}).strict().refine(e=>!e.cashPrice||e.amount!==null,"Cash pricing requires a finite prepaid allowance").refine(e=>!e.rollover||e.amount!==null&&e.reset!=="lifetime","Rollover requires a finite recurring consumable allowance").refine(e=>!e.prepaidPrice||e.amount!==null,"Purchased quantities require a finite included allowance").refine(e=>{if(!e.prepaidPrice||e.amount===null)return!0;try{return xs(e.amount,e.prepaidPrice.units,e.prepaidPrice.maximumQuantity),!0}catch{return!1}},"The maximum purchased allowance must fit the quantity ledger"),R.object({kind:R.literal("credit"),internal_feature_id:R.uuid(),amount:_e,reset:_i,resetCount:yi,rollover:Yn.nullable(),pooled:R.boolean(),feature_override:as.nullish(),cashPrice:Cn.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&vd(e.cashPrice),"Itemized invoice credits require a recurring, unpooled allowance without rollover priced at one currency unit per credit").refine(e=>!e.rollover||e.reset!=="lifetime","Rollover requires a recurring allowance")]),vs=R.array(ey).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),Ud=R.object({days:R.number().int().min(1).max(730),cardRequired:R.boolean(),allowances:vs}).strict().refine(e=>e.allowances.every(t=>t.kind==="access"||!t.cashPrice&&(t.kind!=="metered"||!t.prepaidPrice)),"Trial allowances do not charge cash overages or purchased quantities"),Md=R.object({key:sn,internal_feature_id:R.uuid(),productVersionId:R.uuid(),includedQuantity:R.number().int().min(0).max(1e4),maximumQuantity:R.number().int().min(0).max(1e4),prices:xo,pooled_internal_feature_ids:R.array(R.uuid()).max(100),requireAssignment:R.boolean()}).strict().refine(e=>e.maximumQuantity>=e.includedQuantity,"Capacity cannot be less than included seats").refine(e=>new Set(e.pooled_internal_feature_ids).size===e.pooled_internal_feature_ids.length,"Shared entitlements must be unique"),Si=R.discriminatedUnion("kind",[R.object({...ys,kind:R.literal("membership"),groupId:R.uuid(),membershipType:R.enum(["main","addon"]),interval:R.enum(["free","week","month","year","one_time"]),intervalCount:R.number().int().min(1).max(156).optional(),prices:xo,allowances:vs,trial:Ud.nullable(),licenses:R.array(Md).max(20).refine(e=>new Set(e.map(t=>t.key)).size===e.length,"License keys must be unique")}).strict().refine(e=>e.interval==="free"?e.prices.every(t=>t.amountMinor===0):e.prices.every(t=>e.interval==="one_time"?t.amountMinor>0||e.allowances.some(n=>n.kind==="metered"&&n.prepaidPrice?.prices.some(r=>r.currency===t.currency&&r.amountMinor>0)):t.amountMinor>=0),"Prices must match the billing interval").refine(e=>e.interval!=="one_time"||e.trial===null,"Lifetime plans cannot have a subscription trial").refine(e=>e.intervalCount===void 0||(e.interval==="week"||e.interval==="month"||e.interval==="year")&&e.intervalCount<=(e.interval==="year"?3:e.interval==="month"?36:156),"Recurring billing intervals cannot exceed three years").refine(e=>e.allowances.every(t=>t.kind!=="metered"||!t.prepaidPrice||e.interval!=="free"&&t.prepaidPrice.prices.length===e.prices.length&&t.prepaidPrice.prices.every(n=>e.prices.some(r=>r.currency===n.currency))),"Purchased features require a paid plan and all its published currencies"),R.object({...ys,kind:R.literal("topup"),interval:R.literal("one_time"),prices:xo,internal_feature_id:R.uuid(),amount:Fd,expiresDays:R.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),Io=R.object({interval:R.enum(["free","week","month","year","one_time"]).optional(),intervalCount:R.number().int().min(1).max(156).nullable().optional(),prices:xo.optional(),allowances:R.object({upsert:vs,remove:R.array(R.uuid()).max(100)}).strict().refine(e=>new Set(e.remove).size===e.remove.length&&e.upsert.every(t=>!e.remove.includes(t.internal_feature_id)),"An allowance cannot be removed and replaced together").optional(),trial:Ud.nullable().optional(),licenses:R.array(Md).max(20).optional()}).strict(),Bd=R.object({...ys,kind:R.literal("variant"),baseProductVersionId:R.uuid(),overrides:Io}).strict(),xC=R.union([Si,Bd]);function IC(e,t){let n=Bd.parse(t);if(e.kind!=="membership")throw new Error("A variant requires a membership base");let{allowances:r,intervalCount:i,...o}=n.overrides,a=new Map(e.allowances.map(c=>[c.internal_feature_id,c]));for(let c of r?.remove??[])if(!a.delete(c))throw new Error("Removed allowance is absent from the base");for(let c of r?.upsert??[])a.delete(c.internal_feature_id);for(let c of r?.upsert??[])a.set(c.internal_feature_id,c);let s={...structuredClone(e),...structuredClone(o),key:n.key,name:n.name,description:n.description,allowances:structuredClone([...a.values()])};return i===null?delete s.intervalCount:i!==void 0&&(s.intervalCount=i),Si.parse(s)}function AC(e,t){if(e.kind!=="membership"||t.kind!=="membership"||e.groupId!==t.groupId||e.membershipType!==t.membershipType)throw new Error("Variant group and membership type must match the base");let n={};for(let s of["interval","intervalCount","prices","trial","licenses"])(s==="intervalCount"&&["week","month","year"].includes(t.interval)?(e.intervalCount??1)===(t.intervalCount??1):JSON.stringify(e[s])===JSON.stringify(t[s]))||Object.assign(n,{[s]:s==="intervalCount"&&t[s]===void 0?null:structuredClone(t[s])});let r=new Map(e.allowances.map(s=>[s.internal_feature_id,s])),i=new Set(t.allowances.map(s=>s.internal_feature_id)),o=t.allowances.filter(s=>JSON.stringify(r.get(s.internal_feature_id))!==JSON.stringify(s)),a=e.allowances.filter(s=>!i.has(s.internal_feature_id)).map(s=>s.internal_feature_id);return(o.length||a.length)&&(n.allowances={upsert:o,remove:a}),Io.parse(n)}var wC=R.object({products:R.array(R.object({id:R.uuid(),productId:R.string().min(1),name:R.string(),kind:R.enum(["membership","topup"]),version:R.number().int().positive()}).strict()).max(500),limited:R.boolean()}).strict(),ty=Kl.and(R.object({internal_id:R.uuid(),revision:R.number().int().nonnegative(),licenses:R.array(rs)})),PC=R.strictObject({rows:R.array(ty).max(200),nextCursor:R.uuid().nullable()}),OC=R.object({groups:R.array(R.object({id:R.uuid(),name:R.string(),defaultProductVersionId:R.uuid().nullable()}).strict()).max(500),features:rd.shape.features,products:R.array(R.object({id:R.uuid(),productId:R.uuid(),version:R.number().int().positive(),configuration:Si,baseProductVersionId:R.uuid().nullable()}).strict()).max(500),limited:R.boolean()}).strict();function xs(e,t,n){let r=a=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(a))throw new Error("Invalid quantity");let[s,c=""]=a.split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return BigInt(s)*1000000n+BigInt(c.padEnd(6,"0"))};if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let i=r(e)+r(t)*BigInt(n);if(i>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let o=(i%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(i/1000000n).toString()+(o?"."+o:"")}var RC=zt.object({requestId:zt.uuid(),baseProductVersionId:zt.uuid(),name:zt.string().trim().min(1).max(80),description:zt.string().trim().max(240),overrides:Io}).strict(),jC=zt.object({productId:zt.uuid(),productVersionId:zt.uuid(),bindingStatus:zt.enum(["ready","requires_binding"]),missingCurrencies:zt.array(zt.string().regex(/^[A-Z]{3}$/)).max(20)}).strict();var qd="X-Indiana-Protocol",ny="X-Indiana-SDK-Version",DC="X-Indiana-Supported-Protocols",Ld={stableSupportMonths:12,retirementNoticeDays:180,documentation:"/docs/release-notes#support-policy"},ry={current:"0.7",unversioned:"0.2",releases:[{protocol:"0.2",firstReleasedAt:"2026-10-16T04:05:43.170Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.2.0",integrity:"sha512-kyzHFrt+zuS2hfDZsknCE3AIA9EZXakCDhorO0Ayn2wTpITbm32GMaqVFyhlPufDhkjkV4C0UvXJMyLT5FWIoQ==",sha256:"7e20dd8df9c5e965f67bcdad6c95bf0d0aa5e61a372e5ece88173e32190a1c4c"}]},{protocol:"0.3",firstReleasedAt:"2026-10-16T16:18:04.572Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.3.0",integrity:"sha512-jrh4DH2DBYL5tRkr9BNBVIgD1ts0hUPx8+AhiNkkt2uWV27R8tXGRCW1HBLOw2bfomyuIsAXBAY6niJfjkazCg==",sha256:"33f7ca369d509c44df95c5c8b94775c2afe9d8e3a94163275fe59754739e6815"},{version:"0.3.1",integrity:"sha512-Ifp24kv236advquxa78jx49XKz9oKsg5zZZvFMkId4+KxsylsGxHS44fqYJL/b84PVHl3DLuc+Ru2btdLEctIw==",sha256:"4cc047fe94477e77c5403ce47afea0db2806bd4c3cb94a2dd48c453b4e942163"}]},{protocol:"0.4",firstReleasedAt:"2026-10-18T12:44:12.148Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.4.0",integrity:"sha512-QYuxMdw63RzPLkqmFRc7xv8VWYKYWG+KuKM+f5ZeRX879n6sKyr38bxkMiozFXT+kvH0lDfTF73uJPY2yQX1pQ==",sha256:"ef22d0f6a89897bfbaf71487c4e805997528c8dbad2921ab5c90ed3aa0c01244"}]},{protocol:"0.5",firstReleasedAt:"2026-10-19T08:12:17.954Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.5.0",integrity:"sha512-tzdmoHdvaSoDIvGmg+JpmzE+o1kv7DXpSyvNUSuBj5rHX2pD1GDsMf7ioudUVT5MiKaBDVVtJVE+GpxMOBBLLA==",sha256:"d8b1909bebe1bca0c8c029a68b71477e06ba0c9317c3a2b4bf657951ae3449ca"}]},{protocol:"0.6",firstReleasedAt:"2026-10-21T11:41:57.832Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.6.0",integrity:"sha512-M4szAkM52gqiGPZbtpdhoAvYW2uNRQ2aRw0mdnpr2ErTnuG2i1++76fHjo0qiEMSlePdqu99T1Smecp/FZ2//g==",sha256:"141b058b485fb17b416a2f7961ca55e2da413c9afb7ff22f9fdec2561890bd82"},{version:"0.6.1",integrity:"sha512-KbZUP4XCRblj4mF//JG9t4AAMHSP7uENTi7edxJE55QZjvxH4n1/ypWtKZq32xgt9qGu9o3iZzL8tcHoM3B7Ng==",sha256:"e87930eaec7735629e27e930a462dcecb65fdc4e396cc8ab075845a4f4d22396"},{version:"0.6.2",integrity:"sha512-CUXfh46gSh1S7cdgStI3NAzRROlCQxOcvna2KKlDWFq8L7DXtcILLBOKw5Y1e+QQdDPsXGrsMVBOwIJxFyoIlw==",sha256:"dee5f6e605133ec6c509f390fafdf1d0cb66984a02bea0bb5c05828276c64a15"},{version:"0.6.3",integrity:"sha512-MJXbEoZdLym8a7IHUhY9Oh6eXaSRZPdkwYmfGvfsu5O/kTzfIg+OJuaNrFHYzK76msTxR76IMtQ1R45/FddGdg==",sha256:"fcff156ee9ae90a0f5c906721c8e12715f5fd7a97bca494d64a4303283ec633a"},{version:"0.6.4",integrity:"sha512-djTPwCCgNbp/dt0pFnwEgutZExBZ//wmA2GnObRtXydGrzfi8Z9W7RdeGUFvufblJaGAmcWwVqUgmzEi9SLyjA==",sha256:"bd8e53823728b1e45a27e187c538dcb18af005f24e55120d0cc6b5a618a033f7"}]},{protocol:"0.7",firstReleasedAt:null,noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[]}]},Vd=/^(?:0\.(?:0|[1-9]\d*)|[1-9]\d*)$/,iy=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Gd(e){let t=iy.exec(e);return!t?.[1]||!t[2]?null:t[1]==="0"?`0.${t[2]}`:t[1]}var As=e=>/^[1-9]\d*$/.test(e);function oy(e,t){let n=new Date(e),r=n.getUTCDate();n.setUTCDate(1),n.setUTCMonth(n.getUTCMonth()+t);let i=new Date(n.getTime());return i.setUTCMonth(i.getUTCMonth()+1,0),n.setUTCDate(Math.min(r,i.getUTCDate())),n.getTime()}var Is=e=>/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{3})?Z$/.test(e)&&Number.isFinite(Date.parse(e))&&new Date(e).toISOString().replace(".000Z","Z")===e.replace(".000Z","Z");function NC(e){let t=[],n=new Set;for(let r of e.releases){let i=r.protocol;(!Vd.test(i)||n.has(i))&&t.push(`Invalid/duplicate protocol ${i}`),n.add(i),(r.firstReleasedAt===null?i!==e.current:!Is(r.firstReleasedAt))&&t.push(`${i}: invalid first release date`),r.noticePublishedAt!==null&&!Is(r.noticePublishedAt)&&t.push(`${i}: invalid notice date`),r.sunsetAt!==null&&!Is(r.sunsetAt)&&t.push(`${i}: invalid sunset date`),r.noticePublishedAt&&(!r.firstReleasedAt||Date.parse(r.noticePublishedAt)<Date.parse(r.firstReleasedAt))&&t.push(`${i}: notice predates release`),r.noticeUrl!==null&&!/^(?:https:\/\/[^\s<>]+|\/docs\/[\w/#.-]+)$/.test(r.noticeUrl)&&t.push(`${i}: invalid notice URL`),r.firstReleasedAt&&!r.baselines.length&&t.push(`${i}: missing published SDK baseline`),!r.firstReleasedAt&&r.baselines.length&&t.push(`${i}: unpublished current protocol cannot claim published baselines`);let o=new Set;for(let a of r.baselines)(Gd(a.version)!==i||o.has(a.version))&&t.push(`${i}: invalid/duplicate baseline ${a.version}`),o.add(a.version),(!/^sha512-[A-Za-z0-9+/]{86}==$/.test(a.integrity)||!/^[a-f0-9]{64}$/.test(a.sha256))&&t.push(`${i}: unpinned baseline ${a.version}`);if(As(i)&&r.sunsetAt!==null){let a=e.releases.filter(s=>s.firstReleasedAt!==null&&As(s.protocol)&&Number(s.protocol)>Number(i)).sort((s,c)=>Date.parse(s.firstReleasedAt)-Date.parse(c.firstReleasedAt))[0];a?Date.parse(r.sunsetAt)<oy(a.firstReleasedAt,Ld.stableSupportMonths)&&t.push(`${i}: retirement violates 12 calendar months`):t.push(`${i}: retirement requires a released successor major`),!r.noticePublishedAt||!r.noticeUrl?t.push(`${i}: retirement requires a published notice`):Date.parse(r.sunsetAt)-Date.parse(r.noticePublishedAt)<Ld.retirementNoticeDays*864e5&&t.push(`${i}: retirement violates 180 days notice`)}}return(!n.has(e.current)||!n.has(e.unversioned))&&t.push("Current/unversioned protocol is not registered"),e.releases.find(r=>r.protocol===e.current)?.sunsetAt!==null&&t.push("Current protocol cannot be scheduled for retirement"),t}var Jn=class extends Error{constructor(n,r,i=400){super(r);this.code=n;this.status=i}code;status};function FC(e,t=ry,n=Date.now()){let r=e.get(qd)??t.unversioned;if(!Vd.test(r))throw new Jn("INVALID_PROTOCOL_VERSION","Invalid Indiana protocol version");let i=t.releases.find(a=>a.protocol===r);if(!i)throw new Jn("UNSUPPORTED_PROTOCOL_VERSION","Indiana protocol version is not supported");if(!As(r)&&r!==t.current)throw new Jn("UNSUPPORTED_PROTOCOL_VERSION","Only the current pre-1.0 Indiana protocol is supported");if(i.sunsetAt&&n>=Date.parse(i.sunsetAt))throw new Jn("PROTOCOL_RETIRED","Indiana protocol version has retired; follow the published migration notice",410);let o=e.get(ny);if(o!==null&&Gd(o)!==r)throw new Jn("INVALID_PROTOCOL_VERSION","SDK version and protocol version do not match");return i}function UC(e,t=Date.now()){let n={[qd]:e.protocol};return e.noticePublishedAt&&Date.parse(e.noticePublishedAt)<=t&&(n.Deprecation=`@${Math.floor(Date.parse(e.noticePublishedAt)/1e3)}`,e.noticeUrl&&(n.Link=`<${e.noticeUrl}>; rel="deprecation"; type="text/html"`),e.sunsetAt&&(n.Sunset=new Date(e.sunsetAt).toUTCString())),n}import{z as $e}from"zod";var ay=$e.object({minAccountAgeDays:$e.number().int().min(0).max(3650),paymentStatus:$e.enum(["all","unpaid","paid"])}),sy=$e.object({percentOff:$e.number().int().min(1).max(100),redemptionWindowHours:$e.number().int().min(1).max(2160)}),cy=$e.object({title:$e.string().trim().min(1).max(80),description:$e.string().trim().min(1).max(240),buttonLabel:$e.string().trim().min(1).max(30)}),uy=$e.object({name:$e.string().trim().min(1).max(80),audience:ay,offer:sy,popup:cy}),qC=uy.extend({id:$e.string().min(1),projectId:$e.string().min(1),environment:wu,status:$e.enum(["draft","active","paused"]),updatedAt:$e.iso.datetime()}),VC=ke.extend({id:$e.string().min(1),externalUserId:$e.string().min(1),name:$e.string().min(1),email:$e.union([$e.email(),$e.literal("")]),createdAt:$e.iso.datetime(),paymentStatus:$e.enum(["unpaid","paid"]),stripeCustomerId:$e.string().nullable()});import{z as En}from"zod";var $d=En.strictObject({itemKey:En.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:En.uuid(),includedAmount:En.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:En.number().int().min(0).max(1e4),terms:Ss,pricing:mi.optional(),unitAmountMinor:En.number().int().min(0).max(1e8),productId:En.string().min(1).max(255).nullable(),priceId:En.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{xs(e.includedAmount,e.terms.units,e.quantity),_o({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 W}from"zod";var ws=W.object({id:W.uuid(),productVersionId:W.uuid(),connectionId:W.uuid(),currency:W.string().regex(/^[A-Z]{3}$/),productId:W.string().min(1).max(255),priceId:W.string().min(1).max(255),enabled:W.boolean()}).strict(),YC=W.object({productId:W.uuid(),name:W.string(),environment:W.enum(["sandbox","live"]),versions:W.array(W.object({id:W.uuid(),version:W.number().int().positive(),configuration:Si}).strict()),connections:W.array(W.object({id:W.uuid(),accountId:W.string()}).strict()),bindings:W.array(ws),seatBindings:W.array(ws.extend({key:W.string().regex(/^[a-z][a-z0-9_]{0,63}$/)}).strict()),featureBindings:W.array(ws.extend({internal_feature_id:W.uuid()}).strict()),limited:W.boolean()}).strict(),JC=W.discriminatedUnion("action",[W.strictObject({action:W.literal("bind_feature"),requestId:W.uuid(),productId:W.uuid(),productVersionId:W.uuid(),connectionId:W.uuid(),currency:W.string().regex(/^[A-Z]{3}$/),internal_feature_id:W.uuid(),priceId:W.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}),W.strictObject({action:W.literal("disable_feature"),productId:W.uuid(),bindingId:W.uuid()}),W.object({action:W.literal("bind_seat"),requestId:W.uuid(),productId:W.uuid(),productVersionId:W.uuid(),connectionId:W.uuid(),currency:W.string().regex(/^[A-Z]{3}$/),key:W.string().regex(/^[a-z][a-z0-9_]{0,63}$/),priceId:W.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),W.object({action:W.literal("disable_seat"),productId:W.uuid(),bindingId:W.uuid()}).strict(),W.object({action:W.literal("bind"),requestId:W.uuid(),productId:W.uuid(),productVersionId:W.uuid(),connectionId:W.uuid(),currency:W.string().regex(/^[A-Z]{3}$/),priceId:W.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),W.object({action:W.literal("disable"),productId:W.uuid(),bindingId:W.uuid()}).strict()]);import{z as he}from"zod";var Kd=he.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Wd=he.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),vi=he.enum(["apple","google"]),ly=he.strictObject({id:he.uuid(),productVersionId:he.uuid(),priceId:he.uuid(),connectionId:vi,provider:vi,namespace:he.string().min(1).max(255),currency:re,productId:Kd,basePlanId:Wd.nullable(),enabled:he.boolean()}),tE=he.strictObject({productId:he.uuid(),publicId:he.string().min(1),name:he.string().min(1).max(80),environment:he.enum(["sandbox","live"]),versions:he.array(he.strictObject({id:he.uuid(),version:he.number().int().positive(),prices:he.array(he.strictObject({id:he.uuid(),currency:re,amount:he.number().nonnegative(),interval:he.string().nullable()})).max(50),recurring:he.boolean()})).max(100),connections:he.array(he.strictObject({id:vi,provider:vi,applicationId:he.string().min(1).max(255)})).max(2),bindings:he.array(ly).max(500),limited:he.boolean()}),nE=he.discriminatedUnion("action",[he.strictObject({action:he.literal("bind"),requestId:he.uuid(),productId:he.uuid(),productVersionId:he.uuid(),priceId:he.uuid(),connectionId:vi,storeProductId:Kd,basePlanId:Wd.nullable()}),he.strictObject({action:he.literal("disable"),productId:he.uuid(),bindingId:he.uuid()})]);import{z as ye}from"zod";var Xn=ye.iso.datetime({offset:!0}),Hd=_e.refine(e=>/[1-9]/.test(e)),Qd=ye.strictObject({interval:_i.exclude(["lifetime"]),count:yi}),dy=ye.strictObject({action:ye.literal("create"),requestId:ye.uuid(),internal_feature_id:ye.uuid(),entityId:ye.uuid().nullable(),amount:Hd.nullable(),expiresAt:Xn.nullable(),reset:Qd.nullable(),rollover:Yn.nullable(),nextResetAt:Xn.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"),Zd=ye.discriminatedUnion("action",[dy,ye.strictObject({action:ye.literal("update"),requestId:ye.uuid(),grantId:ye.uuid(),revision:ye.number().int().nonnegative(),amount:Hd.nullable(),expiresAt:Xn.nullable(),rollover:Yn.nullable(),nextResetAt:Xn.nullable()}),ye.strictObject({action:ye.enum(["add","subtract","set_remaining"]),requestId:ye.uuid(),grantId:ye.uuid(),revision:ye.number().int().nonnegative(),amount:_e}),ye.strictObject({action:ye.literal("revoke"),requestId:ye.uuid(),grantId:ye.uuid(),revision:ye.number().int().nonnegative()})]),Ps=ye.strictObject({id:ye.uuid(),internal_feature_id:ye.uuid(),entityId:ye.uuid().nullable(),amount:_e.nullable(),reset:Qd.nullable(),rollover:Yn.nullable(),nextResetAt:Xn.nullable(),startsAt:Xn,expiresAt:Xn.nullable(),revision:ye.number().int().nonnegative(),revoked:ye.boolean(),available:Ot,held:Ot,spent:Ot}),Yd=ye.strictObject({customerId:ye.uuid(),after:ye.uuid().nullable(),limit:ye.number().int().min(1).max(100)}),Jd=ye.strictObject({rows:ye.array(Ps).max(100),nextCursor:ye.uuid().nullable()});import{z as H}from"zod";var cn=H.iso.datetime({offset:!0}),Xd=H.strictObject({invoiceId:H.uuid(),after:H.string().min(1).max(180).nullable(),limit:H.number().int().min(1).max(100)}),py=H.strictObject({kind:H.literal("product"),key:H.string(),productVersionId:H.uuid(),productName:H.string(),itemKey:H.string(),entityId:H.uuid().nullable(),quantity:H.number().int().positive(),subtotalMinor:H.string().regex(/^-?\d+$/),discountMinor:H.string().regex(/^\d+$/),taxMinor:H.string().regex(/^-?\d+$/).nullable(),totalMinor:H.string().regex(/^-?\d+$/),startsAt:cn.nullable(),endsAt:cn.nullable(),providerLineId:H.string().nullable(),providerItemId:H.string()}),zd=H.strictObject({invoice:gi,items:H.array(H.discriminatedUnion("kind",[py,H.strictObject({kind:H.literal("invoice_credit"),key:H.string(),internal_feature_id:H.uuid(),internal_credit_feature_id:H.uuid(),name:H.string(),units:_e,reserved:_e,amountMinor:Sr,grossAmountMinor:Sr,creditsAppliedMinor:Sr,properties:Xt,cashPrice:Cn,providerItemId:H.string().nullable(),creditProviderItemId:H.string().nullable()}),H.strictObject({kind:H.literal("usage"),key:H.string(),internal_feature_id:H.uuid(),name:H.string(),units:_e,reserved:_e,amountMinor:Sr,cashPrice:Cn})])).max(100),nextCursor:H.string().min(1).max(180).nullable()}),my=H.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Os=H.strictObject({from:cn,to:cn,entityId:H.uuid().optional(),snapshotAt:cn.nullable(),after:H.strictObject({at:cn,id:H.uuid(),position:H.number().int().nonnegative()}).nullable(),limit:H.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"),ep=H.strictObject({customerId:H.uuid(),entityId:H.uuid().nullable(),from:cn,to:cn,snapshotAt:cn,totals:H.array(H.strictObject({internal_credit_feature_id:H.uuid(),name:H.string(),consumed:Ot,refunded:Ot,net:my})).max(1e3),rows:H.array(H.strictObject({operationId:H.uuid(),position:H.number().int().nonnegative(),kind:H.enum(["consume","confirm","refund"]),originalId:H.uuid().nullable(),occurredAt:cn,internal_feature_id:H.uuid(),entitlementName:H.string(),sourceId:H.uuid(),internal_credit_feature_id:H.uuid(),creditName:H.string(),units:Ru,amount:Ot,pricing:H.array(Tu).max(12),properties:Xt})).max(100),nextCursor:Os.shape.after});import{z as Nt}from"zod";var hE=Nt.enum(["billing.updated","invoice.finalized","billing.auto_topup_failed","billing.auto_topup_succeeded","billing.conflict","billing.purchase","billing.refund","usage.consume","usage.confirm","usage.refund","usage.limit","usage.alert","usage.allowance"]),tp=Nt.object({operationId:Nt.uuid(),windowId:Nt.uuid(),customerId:Nt.uuid(),entityId:Nt.uuid().nullable(),internal_feature_id:Nt.uuid(),entitlementKey:Zi,basis:Nt.enum(["usage","credits"]),interval:Nt.enum(["day","week","month","year"]),filter:Xt,startsAt:Nt.iso.datetime({offset:!0}),endsAt:Nt.iso.datetime({offset:!0}),limit:_e.refine(e=>/[1-9]/.test(e)),used:Ot,reserved:Ot,threshold:Nt.number().positive().max(1)}).strict(),gE=tp.omit({threshold:!0,limit:!0}).extend({alertThreshold:_e.refine(e=>/[1-9]/.test(e)),limit:_e.nullable()}),bE=tp.omit({limit:!0}).extend({includedAllowance:Nt.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>/[1-9]/.test(e))});import{z}from"zod";var rp=z.object({customerId:z.uuid()}).strict(),ip=z.discriminatedUnion("action",[z.object({customerId:z.uuid(),requestId:z.uuid(),action:z.literal("assign"),poolId:z.uuid(),memberCustomerId:z.uuid()}).strict(),z.strictObject({customerId:z.uuid(),requestId:z.uuid(),action:z.literal("assign_entity"),poolId:z.uuid(),entityId:z.uuid()}),z.object({customerId:z.uuid(),requestId:z.uuid(),action:z.literal("release"),poolId:z.uuid(),slotId:z.uuid()}).strict()]),xi=z.number().int().nonnegative(),Cs=z.iso.datetime({offset:!0}),Es=z.strictObject({internalId:z.uuid(),id:z.string(),name:z.string().nullable(),version:z.number().int().positive()}),np=z.enum(["active","past_due"]),Ts=z.strictObject({customerId:z.uuid(),licenses:z.array(z.strictObject({id:z.uuid(),linkId:z.uuid(),parent:z.strictObject({customerProductId:z.uuid(),status:np,product:Es}),product:Es,planLicense:z.strictObject({id:z.uuid(),prepaidOnly:z.boolean(),isCustom:z.boolean()}).nullable(),granted:xi,included:xi,paidQuantity:xi,usage:xi,remaining:xi,createdAt:Cs}).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:z.array(z.strictObject({id:z.uuid(),linkId:z.uuid(),status:np,product:Es,entity:z.strictObject({internalId:z.uuid(),id:z.string().nullable(),name:z.string().nullable()}).nullable(),beneficiary:z.strictObject({internalId:z.uuid(),id:z.string().nullable(),name:z.string().nullable()}).nullable(),startedAt:Cs.nullable(),endedAt:Cs.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:z.boolean()});import{z as Tn}from"zod";var fy=Tn.object({name:Tn.string().trim().min(1,"\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0").max(80),slug:Tn.string().trim().max(63).regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"\u9879\u76EE\u6807\u8BC6\u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26")}),op=Tn.object({description:Tn.string().trim().max(240)}),xE=Tn.object({project:fy.extend({id:Tn.string().min(1)}),environments:Tn.object({sandbox:op,live:op})});import{z as ap}from"zod";var vr={funnelId:ap.uuid().optional(),funnelVersionId:ap.uuid().optional()};import{z as Ve}from"zod";import{z as Ce}from"zod";import{z as Fe}from"zod";var hy=Fe.discriminatedUnion("action",[Fe.strictObject({action:Fe.literal("create"),couponId:Fe.uuid(),productBindingId:Fe.uuid(),storeOfferId:Fe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Fe.enum(["introductory","promotional"])}),Fe.strictObject({action:Fe.literal("set_enabled"),id:Fe.uuid(),revision:Fe.number().int().nonnegative(),enabled:Fe.boolean()})]),gy=Fe.array(Fe.strictObject({id:Fe.uuid(),couponId:Fe.uuid(),productBindingId:Fe.uuid(),storeOfferId:Fe.string().min(1).max(255).nullable(),storeOfferType:Fe.enum(["introductory","promotional"]),enabled:Fe.boolean(),revision:Fe.number().int().nonnegative()})).max(500),Rn=Fe.strictObject({offerKind:Fe.enum(["none","introductory","promotional"]),offerId:Fe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Fe.number().int().min(0).max(1e8),trialDays:Fe.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"})}),sp=Fe.record(Fe.uuid(),Rn).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");function by(e,t){if(e.nativeOffers!==void 0)return sp.parse(e.nativeOffers)[t]}function _y(e,t,n,r){return Rn.safeParse(n).success?n.discountMinor<=r.catalogAmountMinor&&n.discountMinor===r.discountMinor&&n.trialDays===r.trialDays&&(t==="membership"||n.offerKind==="none")&&(e==="apple"?n.offerKind==="promotional"==(n.offerId!==null):n.offerKind==="none"==(n.offerId===null)&&(n.offerId===null||/^[a-z0-9][a-z0-9-]*$/.test(n.offerId))):!1}var Rs=Ce.object({type:Ce.literal("native_purchase"),receiptId:Ce.uuid(),orderId:Ce.uuid(),productVersionId:Ce.uuid(),provider:Ce.enum(["apple","google"]),productId:Ce.string().min(1).max(255),productKind:Mu,replacement:Ce.strictObject({sourceOrderId:Ce.uuid(),sourceProductId:Ce.string().min(1).max(255),policy:Ce.enum(["apple_store","google_full_price"]),sourceAccountTokens:Ce.array(Ce.uuid()).max(50)}).nullable(),appAccountToken:Ce.uuid().optional(),obfuscatedAccountId:Ce.string().min(1).max(64).optional(),obfuscatedProfileId:Ce.uuid().optional(),basePlanId:Ce.string().min(1).max(255).optional(),offerId:Ce.string().min(1).max(255).optional(),offerKind:Ce.enum(["none","introductory","promotional"]),currency:re,catalogAmountMinor:Ce.number().int().nonnegative().max(1e8),discountMinor:Ce.number().int().nonnegative().max(1e8),trialDays:Ce.number().int().min(1).max(730).nullable(),seatBundle:Ce.array(Ce.strictObject({key:Ce.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Ce.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Ce.strictObject({offerId:Ce.string().min(1).max(255),keyId:Ce.string().min(1).max(255),nonce:Ce.uuid(),signature:Ce.string().min(1).max(1024),timestamp:Ce.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 h}from"zod";import{z as le}from"zod/v4";import{z as yy}from"zod/v4";var Sy=yy.registry(),{BillingInterval:cp}=(()=>{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:vy}=(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')."})})}))(le),{withSpecDefault:xy}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Sy),{COMMON:up}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Iy}={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:Ay}=(e=>({COMMON_SET:new Set(e)}))(up),{hasNoDuplicateCurrencies:lp}={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:dp}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:wy}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(le),{Infinite:Py}={Infinite:"inf"},{TierBehavior:Oy}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:pp}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Cy}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Ey}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ty}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Ry}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(le),{ApiCreditTierSchema:mp}=(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."})})}))(le),{VIOLATION_MESSAGES:jy}={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:fp}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(le),{ModelMarkupsSchema:ky}=((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()}))(le,fp),{InvoiceUsageEntrySchema:Dy}=(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()}))(le),{AttachDiscountSchema:hp}=(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."})}))(le),{CustomLineItemSchema:Ny}=(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."})})}))(le),{UnixMsTimestampSchema:Fy}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(le),{CreateInvoicePreviewLineSchema:Uy}=(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()})}))(le),{ReissueInvoiceParamsSchema:js}=(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."})})}))(le),{InvoiceModeParamsSchema:jn}=(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."})}))(le),{InvoiceTemplateSchema:My}=(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."})})}))(le),{BasePriceSchema:By}=((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."})})}))(le,cp,vy),{CURRENCY_CODES:Ly}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(up,Iy,Ay),{ApiPriceProcessorsSchema:gp}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(le,wy),{AllocatedBillingFieldSchema:qy}=((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'."})}))(le,Cy),{CreditDimensionNameSchema:Vy}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(le,Ey,Ty),{ApiCreditMatchSchema:bp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Ry),{findCreditTierViolations:Gy}=(e=>({findCreditTierViolations:n=>{let r=[],i=(a,s)=>r.push({index:a,reason:s,message:e[s]}),o=0;for(let[a,s]of n.entries()){let c=a===n.length-1;if(s==="inf"){c||i(a,"non_final_infinity");continue}(!Number.isFinite(s)||s<=o)&&i(a,"not_increasing"),o=s,c&&i(a,"final_not_infinity")}return r}}))(jy),{ApiCreditMultiplierSchema:$y}=((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."})}))(le,bp),{ProviderMarkupsSchema:Ky}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(le,fp),{InvoiceFeatureQuantitySchema:_p}=((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."})}))(le,pp,Dy),{CreateInvoicePreviewSchema:ks}=((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()})}))(le,Uy),{SUPPORTED_SET:Wy}=(e=>({SUPPORTED_SET:new Set(e)}))(Ly),{ApiCreditDimensionBaseSchema:Hy}=((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."})})}))(le,bp),{refineGraduatedTiers:yp}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(o=>o.to));for(let{index:o,message:a}of i)r.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(Gy),{ApiFeatureMarkupsOverrideSchema:Qy}=((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."})})}))(le,Ky,ky),{isValidCurrencyCode:Zy}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Wy),{ApiCreditDimensionSchema:Yy}=((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()])}))(le,Hy,mp,yp),{CurrencyCodeSchema:Sp}=((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')."})}))(le,Zy),{AdditionalCurrencyTierSchema:Jy}=((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"]})}))(le,Sp),{ApiCreditSchemaItemBaseSchema:vp}=((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."})})}))(le,Vy,Yy,$y),{ApiFlatCreditSchemaItemSchema:Xy}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(vp,le),{AdditionalCurrencyPriceSchema:zy}=((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."})})}))(le,Sp),{AdditionalCurrencyTierArraySchema:eS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(le,Jy,lp,dp),{ApiGraduatedCreditSchemaItemSchema:tS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(vp,le,mp,yp),{AdditionalCurrencyPriceArraySchema:xp}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(le,zy,lp,dp),{ApiUsageTierWithCurrenciesSchema:nS}=((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()}))}))(le,Py,eS),{ApiCreditSchemaItemSchema:rS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(le,tS,Xy),{BasePriceParamsSchema:iS}=((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."})}))(By,xy,le,xp),{PlanItemPriceParamsSchema:oS}=((e,t,n,r,i,o,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??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(o).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,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."})})}))(le,xp,nS,Oy,cp,pp,qy),{ApiFeatureOverrideSchema:aS}=((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."})})}))(le,rS,Qy),{InvoiceBasePriceParamsSchema:Ip}=((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()}))(iS,gp),{InvoiceItemPriceParamsSchema:sS}=((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()}))(oS,gp),{InvoiceLicenseQuantitySchema:cS}=((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()}))(le,Ip,_p),{InvoiceCustomizeItemSchema:uS}=((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()}))(le,sS,aS),{InvoiceCustomizeSchema:lS}=((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."})}))(le,Ip,uS),{InvoicePlanParamsSchema:dS}=((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()}))(le,lS,_p,cS,hp),{CreateInvoiceParamsSchema:xr}=((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(a=>a.period_start===void 0==(a.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(a=>a.period_start===void 0||a.period_end===void 0||a.period_end>a.period_start,{message:"period_end must be after period_start."})}))(le,dS,Ny,hp,Fy);var Pp=h.strictObject({requestId:h.uuid(),predecessorOperationId:h.uuid().optional(),invoiceMode:jn.optional(),entityId:h.uuid().optional(),billingSubscriptionId:h.uuid().optional(),newBillingSubscription:h.literal(!0).optional(),offerId:h.uuid().optional(),nativeOffer:Rn.optional(),plans:h.array(h.strictObject({productVersionId:h.uuid(),seatQuantities:h.record(sn,h.number().int().min(0).max(1e4)).optional(),featureQuantities:h.record(h.uuid(),h.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:h.enum(["stripe","apple","google"]),currency:re}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(e.provider==="stripe"||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||e.provider!=="stripe"&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||e.provider==="stripe"&&!e.billingSubscriptionId,"A new billing subscription requires Stripe and no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),er=h.strictObject({operationId:h.uuid()}),rt=h.number().int().min(0).max(1e8),pS=h.strictObject({lineId:h.uuid(),productVersionId:h.uuid(),productName:h.string().min(1).max(80),interval:h.enum(["free","week","month","year","one_time"]),intervalCount:h.number().int().min(1).max(156).optional(),baseAmountMinor:rt,seats:h.array(h.strictObject({key:sn,quantity:h.number().int().min(0).max(1e4),includedQuantity:h.number().int().min(0).max(1e4),maximumQuantity:h.number().int().min(0).max(1e4),unitAmountMinor:rt})).max(20),prepaid:h.array($d).max(100).optional(),catalogAmountMinor:rt,trial:h.strictObject({days:h.number().int().min(1).max(730),cardRequired:h.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+_o({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"),Op=h.string().regex(/^[A-Za-z0-9_-]{1,200}$/),mS=h.strictObject({id:Op,name:h.string().min(1).max(40),percent_off:h.number().gt(0).max(100).optional(),amount_off:h.number().int().positive().optional(),currency:h.string().regex(/^[a-z]{3}$/).optional(),duration:h.enum(["once","repeating","forever"]),duration_in_months:h.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"),fS=h.strictObject({subscriptionId:h.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:h.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:h.array(h.strictObject({id:h.string(),price_id:h.string(),quantity:h.number().int().nonnegative(),discounts:h.array(h.strictObject({id:h.string(),coupon:h.string(),start:h.number(),end:h.number().nullable()})).optional()})).min(1).max(100),prorationDate:h.number().int().nonnegative(),amountMinor:h.number().int().positive(),periodStartMs:h.number(),periodEndMs:h.number()}),Cp=h.strictObject({invoiceMode:jn.optional(),append:fS.optional(),provider:h.literal("stripe"),executor:h.enum(["indiana","merchant"]),accountId:h.string().regex(/^acct_[A-Za-z0-9]+$/),mode:h.enum(["payment","subscription"]),lineItems:h.array(h.strictObject({price:h.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:h.number().int().min(1).max(1e4),priceId:h.uuid(),productName:h.string().min(1).max(80),amountMinor:h.number().int().min(0).max(1e8),currency:h.string().regex(/^[a-z]{3}$/),interval:h.enum(["week","month","year","one_off"]),intervalCount:h.number().int().min(1).max(52),slot:h.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:h.strictObject({mode:h.enum(["graduated","volume"]),tiers:h.array(h.strictObject({upTo:h.number().int().min(1).max(1e6).nullable(),unitAmountMinor:h.number().int().min(0).max(1e8),flatAmountMinor:h.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:h.array(h.strictObject({coupon:Op,terms:mS})).max(1),trialPeriodDays:h.number().int().min(1).max(730).nullable(),metadata:h.strictObject({grooveCheckoutId:h.uuid(),grooveCustomerId:h.uuid()}),expiresAt:h.iso.datetime({offset:!0})}),Ii=h.strictObject({operationId:h.uuid(),entityId:h.uuid().nullable(),billingSubscriptionId:h.uuid().nullable(),discount:h.strictObject({offerId:h.uuid(),couponId:h.uuid(),discount:On,duration:Dt,amountMinor:rt,allocations:h.array(h.strictObject({productVersionId:h.uuid(),amountMinor:rt})).min(1).max(20),expiresAt:h.iso.datetime({offset:!0})}).nullable(),charge:h.strictObject({effectiveAt:h.iso.datetime({offset:!0}),periodEndsAt:h.iso.datetime({offset:!0}),debitMinor:rt,discountMinor:rt,taxMinor:rt,totalMinor:rt}).nullable(),expiresAt:h.iso.datetime({offset:!0}),provider:h.enum(["stripe","apple","google"]),nativeOffer:Rn.optional(),currency:re,lines:h.array(pS).min(1).max(20),catalogAmountMinor:rt,automaticTax:h.boolean(),execution:Cp.nullable()}).refine(e=>e.provider==="stripe"?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&&(e.provider==="stripe"||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)&&(e.provider==="stripe"?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"),Ir=h.strictObject({operationId:h.uuid(),orderId:h.uuid(),append:h.boolean().optional(),invoiceMode:h.boolean().optional(),status:h.enum(["pending","complete","cancelled","failed"]),executor:h.enum(["indiana","merchant"]),checkoutUrl:h.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:Cp.nullable(),currency:re,catalogAmountMinor:rt,taxMinor:rt,totalMinor:h.number().int().min(0).max(2e8).nullable(),quoteFinalized:h.boolean(),nativePurchase:Rs.nullable()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),wo=h.strictObject({enabled:h.literal(!0),featureIds:h.array(h.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Ep=h.strictObject({requestId:h.uuid(),invoiceMode:jn.optional(),membershipId:h.uuid(),carryOverBalances:wo.optional(),carryOverUsages:wo.optional(),membershipIds:h.array(h.uuid()).min(1).max(20).optional(),prorationBehavior:h.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:h.enum(["immediate","renewal","store"]),change:h.discriminatedUnion("type",[h.strictObject({type:h.literal("plan"),productVersionId:h.uuid()}),h.strictObject({type:h.literal("seats"),licenseKey:sn,quantity:h.number().int().min(0).max(1e4)}),h.strictObject({type:h.literal("quantity"),internal_feature_id:h.uuid(),quantity:h.number().int().min(0).max(1e4)}),h.strictObject({type:h.literal("cancel")}),h.strictObject({type:h.literal("uncancel")}),h.strictObject({type:h.literal("billing_cycle"),billingCycleAnchor:h.union([h.literal("now"),h.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"),Ao=h.string().regex(/^price_[A-Za-z0-9]+$/),Ap=h.strictObject({grooveUpdateId:h.uuid(),grooveCustomerId:h.uuid()}),wp=h.strictObject({price:Ao.nullable(),priceId:h.uuid().optional(),quantity:h.number().int().min(0).max(1e4)}),Tp=h.strictObject({provider:h.literal("stripe"),invoiceMode:jn.optional(),executor:h.enum(["indiana","merchant"]),accountId:h.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:h.string().regex(/^sub_[A-Za-z0-9]+$/),action:h.enum(["update","cancel","schedule","release"]),update:h.strictObject({items:h.array(wp).max(20),remove:h.array(Ao).max(20),restoreItems:h.array(h.strictObject({price:Ao,quantity:h.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:h.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:h.number().int().positive().optional(),paymentBehavior:h.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:h.boolean().optional(),clearCancelAt:h.literal(!0).optional(),billingCycleAnchorNow:h.literal(!0).optional(),metadata:Ap}).nullable(),cancel:h.strictObject({prorate:h.literal(!1),invoiceNow:h.literal(!1)}).nullable(),schedule:h.strictObject({currentItems:h.array(h.strictObject({price:Ao,quantity:h.number().int().min(0).max(1e4)})).max(20),nextItems:h.array(wp).min(1).max(20),switchAt:h.number().int().positive(),interval:h.enum(["week","month","year"]),intervalCount:h.number().int().min(1).max(52),resetBillingCycleAnchor:h.literal(!0).optional(),metadata:Ap}).nullable(),release:h.strictObject({schedule:h.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:h.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"),Ds=h.strictObject({carryOverBalances:wo.optional(),carryOverUsages:wo.optional(),operationId:h.uuid(),membershipId:h.uuid(),productVersionId:h.uuid(),timing:h.enum(["immediate","renewal"]),effectiveAt:h.iso.datetime({offset:!0}),expiresAt:h.iso.datetime({offset:!0}),currency:re,creditMinor:rt,debitMinor:rt,discountMinor:rt,taxMinor:rt,totalMinor:rt,retainedProductVersionIds:h.array(h.uuid()).max(19),execution:Tp}),hS=h.strictObject({operationId:h.uuid(),invoiceMode:h.boolean().optional(),membershipId:h.uuid(),productVersionId:h.uuid(),status:h.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:h.enum(["immediate","renewal"]),effectiveAt:h.iso.datetime({offset:!0}),checkoutUrl:h.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:h.enum(["indiana","merchant"]),execution:Tp.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),gS=h.strictObject({operationId:h.uuid(),membershipId:h.uuid(),productVersionId:h.uuid(),timing:h.literal("store"),effectiveAt:h.null(),expiresAt:h.iso.datetime({offset:!0}),currency:re,creditMinor:h.null(),debitMinor:h.null(),discountMinor:h.null(),taxMinor:h.null(),totalMinor:h.null(),retainedProductVersionIds:h.array(h.uuid()).max(19),store:h.strictObject({provider:h.enum(["apple","google"]),productId:h.string().min(1).max(255),catalogAmountMinor:rt,policy:h.enum(["apple_store","google_full_price"])})}),bS=h.strictObject({operationId:h.uuid(),membershipId:h.uuid(),productVersionId:h.uuid(),status:h.enum(["prepared","pending","effective","cancelled","failed"]),timing:h.literal("store"),effectiveAt:h.iso.datetime({offset:!0}).nullable(),checkoutUrl:h.null(),nativePurchase:Rs.nullable()}),Rp=h.union([Ds,gS]),Ns=h.union([hS,bS]),Ai=h.number().int().positive().max(2e8),zn=h.number().int().min(0).max(2e8),jp=h.strictObject({requestId:h.uuid(),invoiceId:h.uuid(),mode:h.enum(["full","partial"]),amountMinor:Ai.optional(),entitlementAction:h.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),kp=h.strictObject({provider:h.literal("stripe"),executor:h.enum(["indiana","merchant"]),accountId:h.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:h.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Ai,currency:h.string().regex(/^[a-z]{3}$/),metadata:h.strictObject({indianaRefundId:h.uuid()}),idempotencyKey:h.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:h.array(h.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Dp=h.strictObject({operationId:h.uuid(),invoiceId:h.uuid(),providerInvoiceId:h.string().regex(/^in_[A-Za-z0-9]+$/),currency:re,paidMinor:zn,refundedMinor:zn,pendingMinor:zn,amountMinor:Ai,mode:h.enum(["full","partial"]),entitlementAction:h.enum(["retain","revoke"]),revokes:h.strictObject({customerProductIds:h.array(h.uuid()).max(100),subscriptionIds:h.array(h.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:kp,expiresAt:h.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&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"),Po=h.strictObject({operationId:h.uuid(),invoiceId:h.uuid(),providerInvoiceId:h.string().regex(/^in_[A-Za-z0-9]+$/),status:h.enum(["quoted","pending","succeeded","failed","expired"]),executor:h.enum(["indiana","merchant"]),currency:re,amountMinor:Ai,mode:h.enum(["full","partial"]),entitlementAction:h.enum(["retain","revoke"]),refundId:h.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:kp.nullable(),failureReason:h.string().min(1).max(200).nullable(),createdAt:h.iso.datetime({offset:!0}),completedAt:h.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"),KE=h.strictObject({invoiceId:h.uuid(),currency:re,paidMinor:zn,refundedMinor:zn,pendingMinor:zn,refundableMinor:zn,executor:h.enum(["indiana","merchant"]).nullable(),canRefund:h.boolean(),operations:h.array(Po).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),WE=h.strictObject({requestId:h.uuid(),mode:h.enum(["full","partial"]),amountMinor:Ai.optional(),entitlementAction:h.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var Np=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"),Oo=Ve.strictObject({batchId:Ve.uuid()}),_S=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:Ds.nullable(),managementUrl:Ve.url().nullable(),failureCode:Ve.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),wi=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(_S).min(1).max(100)});import{z as be}from"zod";var yS=be.string().trim().min(1).max(240),Fs={requestId:be.uuid(),reason:yS},Co=be.discriminatedUnion("action",[be.strictObject({...Fs,action:be.literal("start"),productVersionId:be.uuid(),entityId:be.uuid().optional(),days:be.number().int().min(1).max(730).optional()}),be.strictObject({...Fs,action:be.literal("extend"),membershipId:be.uuid(),days:be.number().int().min(1).max(730)}),be.strictObject({...Fs,action:be.literal("end"),membershipId:be.uuid()})]),Fp=be.strictObject({operationId:be.uuid()}),Up=be.iso.datetime({offset:!0}),SS=be.strictObject({provider:be.literal("stripe"),executor:be.enum(["indiana","merchant"]),accountId:be.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:be.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:be.union([be.literal("now"),Up]),prorationBehavior:be.literal("none")}),Us=be.strictObject({operationId:be.uuid(),action:be.enum(["start","extend","end"]),status:be.enum(["pending","effective"]),managedBy:be.enum(["indiana","stripe"]),membershipIds:be.array(be.uuid()).min(1).max(20),endsAt:Up.nullable(),execution:SS.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"),XE=be.strictObject({groupId:be.uuid(),productVersionId:be.uuid(),enabled:be.boolean()});import{z as De}from"zod";var Mp=De.strictObject({requestId:De.uuid(),currency:re,makeDefault:De.boolean()}),Bp=De.strictObject({setupId:De.uuid()}),vS=De.strictObject({provider:De.literal("stripe"),executor:De.literal("merchant"),accountId:De.string().regex(/^acct_[A-Za-z0-9]+$/),mode:De.literal("setup"),currency:De.string().regex(/^[a-z]{3}$/),customer:De.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:De.uuid(),metadata:De.strictObject({grooveProjectId:De.uuid(),grooveEnvironmentId:De.uuid(),grooveCustomerId:De.uuid(),groovePaymentSetupId:De.uuid()}),setDefaultPaymentMethod:De.boolean(),expiresAt:De.iso.datetime({offset:!0})}),Ms=De.strictObject({id:De.uuid(),provider:De.literal("stripe"),status:De.enum(["prepared","complete","expired"]),currency:re,makeDefault:De.boolean(),url:De.url().nullable(),createdAt:De.iso.datetime({offset:!0}),expiresAt:De.iso.datetime({offset:!0}),completedAt:De.iso.datetime({offset:!0}).nullable(),execution:vS.nullable()});import{z as it}from"zod";var Lp=it.union([it.string(),it.number(),it.boolean(),it.null()]),qp=it.strictObject({customerId:it.uuid()}),Vp=it.strictObject({customerId:it.uuid(),provider:it.literal("stripe"),checkedAt:it.iso.datetime({offset:!0}),status:it.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:it.number().int().nonnegative(),differences:it.array(it.strictObject({subscriptionId:it.string().startsWith("sub_"),itemId:it.string().nullable(),field:it.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Lp,actual:Lp})).max(1e4)});import{z as ue}from"zod";var Eo=ue.iso.datetime({offset:!0}),To=ue.strictObject({createdAt:Eo,id:ue.uuid()}),Ro=ue.strictObject({customerId:ue.uuid().optional(),entityId:ue.uuid().optional(),productId:ue.string().min(1).max(256).optional(),provider:ue.enum(["stripe","apple","google","free"]).optional(),status:ue.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:To.optional(),limit:ue.number().int().min(1).max(100).optional()}),Bs={id:ue.uuid(),customerId:ue.uuid(),entityId:ue.uuid().nullable(),productId:ue.string().min(1).max(256),productVersionId:ue.uuid(),name:ue.string().min(1).max(120),provider:ue.enum(["stripe","apple","google","free"]),createdAt:Eo},xS=ue.strictObject({...Bs,status:ue.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:ue.boolean(),billingSubscriptionId:ue.uuid().nullable()}),IS=ue.strictObject({...Bs,status:ue.enum(["active","ended","refunded"]),orderId:ue.uuid().nullable(),transactionId:ue.uuid().nullable(),currency:re.nullable(),amountMinor:ue.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),AS=ue.strictObject({...Bs,status:ue.enum(["blocked","resolved"]),conflict:ue.strictObject({detectedAt:Eo,blockingMembershipIds:ue.array(ue.uuid()).min(1).max(100),transactionId:ue.uuid()}),resolvedAt:Eo.nullable()}),Gp=Ro.extend({status:ue.enum(["blocked","resolved"]).optional()}),$p=ue.strictObject({customerId:ue.uuid(),orderId:ue.uuid()}),Kp=ue.strictObject({orderId:ue.uuid(),status:ue.enum(["blocked","resolved"])}),Wp=ue.strictObject({items:ue.array(xS).max(100),nextCursor:To.nullable()}),Hp=ue.strictObject({items:ue.array(IS).max(100),nextCursor:To.nullable()}),Qp=ue.strictObject({items:ue.array(AS).max(100),nextCursor:To.nullable()});import{z as Me}from"zod";var Zp=Me.union([Me.strictObject({intent:Me.literal("read"),requestId:Me.uuid(),purchaseIntentId:Me.uuid()}),Me.strictObject({requestId:Me.uuid(),provider:Me.literal("apple"),purchaseIntentId:Me.uuid(),productId:Me.string().min(1).max(255).optional(),signedTransaction:Me.string().min(1).max(131072)}),Me.strictObject({requestId:Me.uuid(),provider:Me.literal("google"),purchaseIntentId:Me.uuid(),productId:Me.string().min(1).max(255).optional(),purchaseToken:Me.string().min(1).max(16384)})]),Yp=Me.strictObject({requestId:Me.uuid(),orderId:Me.uuid(),purchaseIntentId:Me.uuid(),status:Me.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:re,refunded:Me.boolean(),completion:Me.strictObject({transactionIds:Me.array(Me.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Me.boolean()}).nullable()});import{z as T}from"zod";var Vs=T.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),wS=T.record(T.string(),T.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),PS=3,Pi=20,OS=PS*Pi,Ls=T.strictObject({type:T.literal("product"),productId:Vs}),Jp={type:T.literal("group"),key:T.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:T.string().trim().min(1).max(80)},CS=T.discriminatedUnion("type",[Ls,T.strictObject({...Jp,items:T.array(Ls).max(Pi)})]),ES=T.discriminatedUnion("type",[Ls,T.strictObject({...Jp,items:T.array(CS).max(Pi)})]),TS=T.array(ES).max(Pi).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function o(a){for(let s of a){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&o(s.items)}}o(e),(n.size>Pi||i>OS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Gs(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Gs(t))}function pT(e){function t(n,r){return n.flatMap(i=>i.type==="product"?[{productId:i.productId,groups:r}]:t(i.items,[...r,i.name]))}return t(e.items,[])}var jo=T.strictObject({lookupKey:T.string().trim().min(1).max(200),displayName:T.string().trim().min(1).max(1500),items:TS,metadata:wS}),qs=jo.extend({paywallId:T.uuid().nullable()}),RS=T.strictObject({product:T.record(T.string(),T.json()),prices:T.array(T.record(T.string(),T.json())),entitlements:T.array(T.record(T.string(),T.json())),freeTrials:T.array(T.record(T.string(),T.json())),licenses:T.array(T.record(T.string(),T.json()))}),Xp=qs.extend({id:T.uuid(),projectId:T.uuid(),environmentId:T.uuid(),state:T.enum(["active","archived"]),isCurrent:T.boolean(),revision:T.number().int().nonnegative(),publishedVersionId:T.uuid().nullable(),createdAt:T.number().nonnegative().nullable()}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),zp=T.strictObject({id:T.uuid(),offeringId:T.uuid(),projectId:T.uuid(),environmentId:T.uuid(),version:T.number().int().positive(),document:jo,productEvidence:T.record(Vs,RS),createdAt:T.number().nonnegative().nullable()}).superRefine((e,t)=>{let n=Gs(e.document);(!n.length||DS(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"})}),jS=T.strictObject({rows:T.array(Xp).max(200),versions:T.array(zp).max(500)}),mT=T.discriminatedUnion("action",[T.strictObject({action:T.literal("create"),document:qs}),T.strictObject({action:T.literal("save"),id:T.uuid(),revision:T.number().int().nonnegative(),document:qs}),T.strictObject({action:T.enum(["publish","set_current","archive","restore"]),id:T.uuid(),revision:T.number().int().nonnegative()})]),fT=T.strictObject({record:Xp,version:zp.nullable()}),em=T.discriminatedUnion("type",[T.strictObject({type:T.literal("current")}),T.strictObject({type:T.literal("id"),id:T.uuid()}),T.strictObject({type:T.literal("lookup_key"),lookupKey:T.string().min(1).max(200)}),T.strictObject({type:T.literal("version"),versionId:T.uuid()})]),kS=T.strictObject({internalId:Vs,id:T.string(),name:T.string().nullable(),version:T.number().int().positive(),archived:T.boolean()}),hT=jS.extend({products:T.array(kS).max(500),paywalls:T.array(T.strictObject({id:T.uuid(),name:T.string()})).max(200)});function DS(e){let t=[];Gs(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 ko}from"zod";var Do=ko.strictObject({id:ko.uuid(),offeringId:ko.uuid(),version:ko.number().int().positive(),document:jo});import{z as Xe}from"zod";import{z as te}from"zod";import{z as Ar}from"zod";var No=Ar.strictObject({items:Ar.array(Ar.strictObject({productVersionId:Ar.string().min(1).max(200),label:Ar.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Ar.string().min(1).max(200).nullable(),grouping:qu.optional()});function xT(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 Je}from"zod";var NS=Je.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Fo=Je.discriminatedUnion("type",[Je.object({type:Je.literal("fixed"),productVersionId:Je.string().min(1).max(200)}).strict(),Je.object({type:Je.literal("picker"),pickerId:NS,allowedProductVersionIds:Je.array(Je.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),en=Je.discriminatedUnion("type",[Je.object({type:Je.literal("modal"),size:Je.enum(["sm","md","lg"])}).strict(),Je.object({type:Je.literal("sheet"),size:Je.enum(["sm","md","lg"])}).strict(),Je.object({type:Je.literal("fullscreen")}).strict(),Je.object({type:Je.literal("inline")}).strict()]);var $s=te.discriminatedUnion("type",[te.strictObject({type:te.literal("event"),event:te.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),te.strictObject({type:te.literal("open_url"),url:te.url().refine(e=>new URL(e).protocol==="https:")})]),FS=nt,US=te.discriminatedUnion("type",[te.object({type:te.literal("checkout"),product:Fo}).strict(),te.object({type:te.literal("close")}).strict(),te.object({type:te.literal("action"),action:$s}).strict()]),wr=te.object({schemaVersion:te.literal(3),kind:te.literal("paywall"),name:te.string().trim().min(1).max(80),presentation:en,requirement:hr.optional(),products:No,offeringVersionId:te.uuid().nullable(),offeringId:te.uuid().nullable(),screen:FS,buttons:te.record(te.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),US)}).strict(),tm=wr.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 BS(e))t.addIssue({code:"custom",message:r});for(let r of MS(e))t.addIssue({code:"custom",message:r});br(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 MS(e){let t=e.products.items.map(o=>o.productVersionId),n=Gu(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),(!e.offeringVersionId||!e.offeringId)&&i.push("offering"),e.products.grouping&&(!Vu(e.products.grouping,t)||e.products.grouping.tiers.some(o=>!e.products.grouping.assignments.some(a=>a.tierId===o.id)))&&i.push("grouping");for(let o of Object.values(e.buttons))if(o.type==="checkout"){let a=o.product;if(a.type==="fixed")r.add(a.productVersionId);else{a.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[a.pickerId];c&&(s=!0,(a.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!a.allowedProductVersionIds.includes(u)))&&i.push("picker")),Et(e.screen,u=>{if(u.id!==a.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(a.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(o=>!t.includes(o)))&&i.push("purchase"),Et(e.screen,o=>{o.type==="stack"&&o.productSlot&&!o.bind?.plan&&i.push(`productBinding:${o.id}`),(o.type==="stack"||o.type==="button")&&o.bind?.plan&&!t.includes(o.bind.plan)&&i.push("binding"),o.type==="plan_picker"&&(!o.planIds?.length||o.planIds.some(a=>!t.includes(a)))&&i.push("binding")}),[...new Set(i)]}function BS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),ai(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(m=>m.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let d=e.buttons[u];s.id!==n.id&&d&&d.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function o(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])o(c)}}let a=e.screen.initialPageId??e.screen.pages[0]?.id;a?o(a):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var nm=te.object({id:te.uuid(),projectId:te.uuid(),environmentId:te.uuid(),revision:te.number().int().nonnegative(),status:te.enum(["draft","published","archived"]),publishedVersionId:te.uuid().nullable(),updatedAt:te.iso.datetime({offset:!0}),draft:wr}).strict(),kT=te.object({rows:te.array(nm).max(200),nextCursor:te.uuid().nullable()}).strict(),DT=nm.omit({draft:!0}).extend({name:te.string(),productCount:te.number().int().nonnegative()}).strict(),NT=te.discriminatedUnion("action",[te.object({action:te.literal("save"),id:te.uuid().nullable(),revision:te.number().int().nonnegative(),document:wr}).strict(),te.object({action:te.enum(["publish","archive"]),id:te.uuid(),revision:te.number().int().nonnegative()}).strict()]),FT=te.object({paywalls:te.array(te.object({id:te.uuid(),paywallId:te.uuid(),version:te.number().int().positive(),name:te.string().min(1).max(80),presentation:en,buttons:wr.shape.buttons}).strict()).max(500),limited:te.boolean()}).strict();import{z as de}from"zod";import{z as bt}from"zod";var kn=bt.string().regex(/^[a-f0-9]{64}$/),LS=$u.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),rm=bt.strictObject({couponDigests:bt.record(bt.uuid(),kn),variables:bt.record(bn,bt.record(bt.uuid(),bt.partialRecord(bt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),bt.string()))),locales:bt.record(bn,gr.extend({nodes:bt.record(bt.string(),bt.strictObject({base:LS})),plans:bt.object({}).strict(),pickers:bt.object({}).strict()}).omit({paywall:!0}))});import{z as je}from"zod";import{z as Uo}from"zod";var Ks=Uo.strictObject({eventsEnabled:Uo.boolean(),experimentViewsEnabled:Uo.boolean(),featureUsageEnabled:Uo.boolean()}),GT=Object.freeze({eventsEnabled:!1,experimentViewsEnabled:!0,featureUsageEnabled:!1});function $T(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var Ws=on.extend({analyticsConfig:Ks,remoteFeatures:je.array(je.string().min(1).max(255)).max(500)}),qS=Ws.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"})}),im=je.strictObject({attributes:Ct,features:je.array(je.string().min(1).max(255)).min(1).max(500).optional(),customerId:je.uuid().optional()}),VS=je.strictObject({value:ge,source:je.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:je.boolean(),off:je.boolean(),ruleId:je.string(),experimentResult:Ju.optional()}),om=je.strictObject({generation:on.shape.generation,evaluatedAt:on.shape.evaluatedAt,expiresAt:on.shape.expiresAt,features:je.record(je.string(),VS)}),am=je.strictObject({customerId:je.uuid().optional(),events:je.array(je.strictObject({eventUuid:je.uuid(),timestamp:je.iso.datetime({offset:!0}),name:je.string().min(1).max(255),properties:je.record(je.string(),ge).default({}),deviceId:je.string().min(1).max(255).optional(),sessionId:je.string().min(1).max(255).optional()})).min(1).max(100)}),sm=je.strictObject({inserted:je.number().int().nonnegative(),duplicates:je.number().int().nonnegative(),rejected:je.number().int().nonnegative(),skipped:je.number().int().nonnegative(),analyticsConfig:Ks});import{z as E}from"zod";function Hs(e,t=[]){let n=[];Et(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(Fa(e).map(i=>i.key));for(let[i,o]of Object.entries(e.strings.locales))for(let a of Object.keys(o))r.has(a)||n.push(`Unused string ${a} must not be delivered (${i})`);return n}function cm(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>cm(t)??[])}}function GS(e){let t=e.pages.map(i=>{let o=cm(i.root);return o?.type==="stack"?{...i,root:o}:{...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(Fa({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,o])=>[i,Object.fromEntries(Object.entries(o).filter(([a])=>n.has(a)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function Mo(e,t=[]){let n=nt.parse(structuredClone(GS(e))),r=o=>o.type!=="stack"||o.interaction!==void 0||o.children.some(r);for(let o of n.pages)if(!r(o.root))throw new Error(`Page ${o.id} has no visible content`);let i=Hs(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Ne}from"zod";var Qs=Ne.enum(["local","remote"]),Oi=Ne.strictObject({port:Ne.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ge.optional(),sticky:Ne.array(Ne.strictObject({expected:zi.nullable(),next:zi})).max(100),exposures:Ne.array(ge).max(100),features:Ne.array(ge).max(100)}),Bo=Ne.strictObject({type:Ne.literal("evaluate"),receiptId:Ne.uuid(),environmentId:Ne.uuid(),policyRevision:Ne.number().int().nonnegative(),attributes:Ct,sticky:Ne.record(Ne.string(),zi)}),um=Bo.extend({runId:Ne.uuid(),versionId:Ne.uuid(),nodeId:Ne.string().min(1).max(64),visit:Ne.number().int().nonnegative(),revision:Ne.number().int().nonnegative()}),Zs=Bo.omit({type:!0,receiptId:!0}).extend({type:Ne.literal("evaluate_segment")}),Lo=Ne.strictObject({nodeId:Ne.string().min(1).max(64),result:Oi}),lm=Zs.extend({runId:Ne.uuid(),versionId:Ne.uuid(),nodeId:Ne.string().min(1).max(64),visit:Ne.number().int().nonnegative(),revision:Ne.number().int().nonnegative(),parameters:$t,answers:Qn,variables:Ne.record(Ne.string(),ge)});import{z as M}from"zod";import{z as Ee}from"zod";import{z as ct}from"zod";var Ye=ct.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"),Ys=ct.strictObject({type:ct.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:ct.boolean(),enum:ct.array(ct.string().max(255)).min(1).max(100).optional()}),Pr=Ys.extend({type:ct.enum([...Ys.shape.type.options,"array"]),items:Ys.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"})}),Or=Pr.safeExtend({source:ct.discriminatedUnion("type",[ct.strictObject({type:ct.literal("input")}),ct.strictObject({type:ct.literal("node")}),ct.strictObject({type:ct.enum(["parameter","attribute"]),key:Ye})])}),$S=ct.record(Ye,Or),qo=ct.record(Ye,Ye).refine(e=>Object.keys(e).length<=20);function Ft(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=>Ft(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&&ct.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 Js(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&&Js(e.items,t.items)}function tr(e,t){let n={};for(let[r,i]of Object.entries(e)){let o=i.source,a=o.type==="input"?t.answers:o.type==="node"?t.results??{}:o.type==="parameter"?t.parameters:t.attributes,s=o.type==="parameter"||o.type==="attribute"?o.key:r;if(!Object.hasOwn(a,s))continue;let c=a[s];if(!Ft(i,c))throw new Error(`Invalid variable value: ${r}`);n[r]=c}return n}function nr(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 Xs(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,o]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!Ft(e[i],o))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var Ci=ge;function Vo(e){let t={};for(let[n,r]of Object.entries(tr(e.declarations,e))){let i=n.split(".");if(i.some(s=>["__proto__","constructor","prototype"].includes(s)))throw new Error("Reserved result path");let o=t;for(let s of i.slice(0,-1)){Object.hasOwn(o,s)||(o[s]={});let c=o[s];if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Ambiguous result path");o=c}let a=i.at(-1);if(a===void 0)throw new Error("Empty result path");o[a]=r}return{...e.attributes,variables:t}}function zs(e,t){return Xi(Vo(t),e,t.savedGroups)}function Ei(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r))i.startsWith("$")||t.add(i),i==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.attributeKey=="string"&&t.add(o.attributeKey),["$and","$or","$nor","$not"].includes(i)&&n(o)}return n(e),[...t]}import{z as KS}from"zod";var Go=KS.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);import{z as rr}from"zod";var Kt=rr.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"),un=rr.discriminatedUnion("source",[rr.strictObject({source:rr.literal("literal"),value:ge}),rr.strictObject({source:rr.literal("variable"),key:rr.string().min(1).max(255),path:Kt.optional()})]);function Cr(e,t){if(!t)return e;for(let n of Kt.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 ir(e,t){if(e.source==="literal")return structuredClone(e.value);let n=tr(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ge.parse(Cr(n[e.key],e.path)))}function dm(e,t){let n={},r=Object.entries(e).sort(([i],[o])=>i.split(".").length-o.split(".").length||i.localeCompare(o,"en",{numeric:!0}));for(let[i,o]of r){let a=Kt.parse(i).split("."),s=n;for(let u=0;u<a.length-1;u++){let l=a[u],d=a[u+1];if(l===void 0||d===void 0)throw new Error("Invalid binding path");if(Array.isArray(s)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>s.length))throw new Error("Invalid array binding index");Object.hasOwn(s,l)||Reflect.set(s,l,/^(0|[1-9]\d*)$/.test(d)?[]:{});let m=Array.isArray(s)?s[Number(l)]:s[l];if(!m||typeof m!="object")throw new Error("Nested input requires an object or array");if(Array.isArray(m)!==/^(0|[1-9]\d*)$/.test(d))throw new Error("Nested input container does not match its path");s=m}let c=a.at(-1);if(Array.isArray(s)&&(!/^(0|[1-9]\d*)$/.test(c)||Number(c)>s.length))throw new Error("Invalid array binding index");Reflect.set(s,c,ir(o,t))}return n}var ec=Ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),pm=Ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),$o=$t.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),tc=Ee.record(ec,Ee.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),WS=un,mm=Ee.strictObject({type:Ee.literal("external_task"),endpointId:Ee.uuid(),taskKey:ec,inputs:Ee.record(ec,WS).refine(e=>Object.keys(e).length<=20),outputs:tc}),fm=Ee.strictObject({maxAttempts:Ee.number().int().min(1).max(5),retryDelaySeconds:Ee.number().int().min(1).max(30),backoff:Ee.enum(["fixed","exponential"]),requestTimeoutSeconds:Ee.number().int().min(1).max(10),timeoutSeconds:Ee.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline"),hm={maxAttempts:4,retryDelaySeconds:5,backoff:"fixed",requestTimeoutSeconds:8,timeoutSeconds:120},SR=Ee.strictObject({outcome:Ee.enum(["success","failure"]),data:$o});function vR(e,t){let n=$o.parse(t);if(Object.keys(n).length!==Object.keys(e).length||Object.entries(e).some(([r,i])=>!Object.hasOwn(n,r)||(i==="strings"?!Array.isArray(n[r])||!n[r].every(o=>typeof o=="string"):typeof n[r]!==i)))throw new Error("Task data does not match its declared outputs");return n}function xR(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=ir(i,t);return $o.parse(n)}var IR=Ee.discriminatedUnion("operation",[Ee.strictObject({operation:Ee.literal("signal"),runId:Ee.uuid(),nodeId:pm,eventName:Go,eventId:Ee.uuid(),data:$o}),Ee.strictObject({operation:Ee.literal("read_results"),runId:Ee.uuid()})]),AR=Ee.strictObject({scope:ke,runId:Ee.uuid(),eventId:Ee.uuid(),accepted:Ee.boolean()}),HS=Ee.record(pm,Ci),wR=Ee.strictObject({scope:ke,runId:Ee.uuid(),results:HS});var Qe={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},gm="00000000-0000-0000-0000-000000000000";import{z as F}from"zod";import{z as J}from"zod";var nc=J.array(J.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"),Er=J.intersection(Ct,J.object({tags:nc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ko=J.string().trim().max(80),Wo=J.union([J.email().max(254),J.literal("")]),Ho=J.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),bm=J.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),_m=J.object({externalUserId:bm.optional(),name:Ko.default(""),email:Wo.default(""),attributes:Er.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Tr=J.discriminatedUnion("type",[J.strictObject({type:J.literal("id"),value:J.uuid()}),J.strictObject({type:J.literal("externalUserId"),value:bm})]),Rr=J.strictObject({name:Ko.optional(),email:Wo.optional(),attributes:Er.optional(),fingerprint:Ho.optional()}),or=e=>!e.customerData||e.customer?.type==="externalUserId",ar="customerData requires an externalUserId customer",jr=J.object({id:J.uuid(),externalUserId:J.string().min(1).max(255).nullable(),name:Ko,email:Wo,attributes:Er,createdAt:J.iso.datetime()}).strict(),ym=J.object({customer:jr,changed:J.boolean(),replayed:J.boolean()}).strict(),QS=J.discriminatedUnion("type",[J.object({type:J.literal("id"),value:J.uuid()}).strict(),J.object({type:J.literal("externalUserId"),value:J.string().trim().min(1).max(255)}).strict()]),ZS=J.object({name:Ko.optional(),email:Wo.optional(),attributes:Er.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:J.array(J.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:J.strictObject({add:nc,remove:nc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),rc=J.object({lookup:QS}).strict(),Sm=rc.extend({requestId:J.uuid(),patch:ZS}).strict(),vm=J.object({search:J.string().trim().max(200).default(""),tag:J.string().trim().max(40).default(""),planId:J.string().max(200).default(""),versionId:J.string().max(200).default(""),holdingStatus:J.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:J.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:J.union([J.iso.datetime(),J.literal("")]).default(""),createdUntil:J.union([J.iso.datetime(),J.literal("")]).default(""),offset:J.coerce.number().int().min(0).max(1e5).default(0),limit:J.coerce.number().int().min(1).max(100).default(50)}).strict(),xm=J.object({customers:jr.array(),hasMore:J.boolean(),total:J.number().int().nonnegative().nullable(),evaluatedAt:J.iso.datetime()}).strict();var Ti=F.discriminatedUnion("type",[F.strictObject({type:F.literal("literal"),value:ge}),F.strictObject({type:F.literal("variable"),key:Ye,path:Kt.optional()}),F.strictObject({type:F.literal("feature"),featureKey:F.string().min(1).max(128)})]),YS=F.strictObject({requestId:F.uuid(),decisionId:F.uuid(),customerId:F.uuid(),externalUserId:F.string().min(1).max(255).nullable(),versionId:F.uuid(),receiptId:F.uuid(),value:ge}),ic={funnelId:F.uuid(),requestId:F.uuid(),customer:Tr,customerData:Rr.optional(),attributes:Ct.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},MR=F.discriminatedUnion("operation",[F.strictObject({operation:F.literal("decide"),...ic}).refine(or,ar),F.strictObject({operation:F.literal("read_decision"),decisionId:F.uuid()}),F.strictObject({operation:F.literal("evaluate_decision"),decisionId:F.uuid(),requestId:F.uuid(),nodeId:F.string().min(1).max(64),visit:F.number().int().nonnegative(),revision:F.number().int().nonnegative(),receiptId:F.uuid(),policyRevision:F.number().int().nonnegative(),generation:F.string().min(1).max(256),result:Oi}),F.strictObject({operation:F.literal("feature_config"),funnelId:F.uuid()}),F.strictObject({operation:F.literal("commit_decision_segment"),decisionId:F.uuid(),requestId:F.uuid(),nodeId:F.string().min(1).max(64),visit:F.number().int().nonnegative(),revision:F.number().int().nonnegative(),policyRevision:F.number().int().nonnegative(),generation:F.string().min(1).max(256),steps:F.array(Lo).max(32),boundary:F.strictObject({nodeId:F.string().min(1).max(64),visit:F.number().int().nonnegative()}).optional()}),F.strictObject({operation:F.literal("segment_configuration"),funnelId:F.uuid(),versionId:F.uuid()}),F.strictObject({operation:F.literal("configuration"),funnelId:F.uuid(),versionId:F.uuid().optional()}),F.strictObject({operation:F.literal("local_configuration"),funnelId:F.uuid()}),F.strictObject({operation:F.literal("report_used"),decisionId:F.uuid(),eventId:F.uuid(),occurredAt:F.iso.datetime({offset:!0}),reference:F.string().min(1).max(128).optional()})]),BR=F.strictObject({scope:ke,decisionId:F.uuid(),requestId:F.uuid(),status:F.enum(["pending","completed","failed"]),decision:YS.nullable(),evaluation:F.discriminatedUnion("type",[um,lm]).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"),LR=F.strictObject({scope:ke,decisionId:F.uuid(),eventId:F.uuid(),source:F.literal("caller_reported")});import{z as ze}from"zod";var Im=ze.strictObject({type:ze.literal("bundle"),paywall:un.optional(),offering:un.optional(),coupons:un,data:un}),Qo=e=>ze.strictObject({type:ze.literal(e),id:ze.uuid()}),JS=ze.strictObject({type:ze.literal("bundle"),paywallVersionId:ze.uuid().optional(),offeringVersionId:ze.uuid().optional(),couponIds:ze.array(ze.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ge});function WR(e,t,n){let r=o=>ir(o,t),i=ze.array(Qo("reward")).max(20).parse(r(e.coupons));for(let o of[e.paywall,e.offering,e.coupons]){if(!o)continue;let a=r(o);for(let s of Array.isArray(a)?a:[a])if(!s||typeof s!="object"||Array.isArray(s)||!Object.values(n).some(c=>c.type===s.type&&c.id===s.id))throw new Error("Bundle resource outside pinned references")}return JS.parse({type:"bundle",...e.paywall?{paywallVersionId:Qo("paywall_version").parse(r(e.paywall)).id}:{},...e.offering?{offeringVersionId:Qo("offering_version").parse(r(e.offering)).id}:{},couponIds:i.map(o=>o.id),data:r(e.data)})}var HR=ze.strictObject({type:ze.literal("bundle"),offering:Qo("offering_version").nullable(),paywall:ze.strictObject({versionId:ze.uuid(),paywallId:ze.uuid(),offeringVersionId:ze.uuid()}).nullable(),coupons:ze.array(fi).max(20),data:ge});function QR(e){let t=o=>o?.source==="literal"&&o.value&&typeof o.value=="object"&&!Array.isArray(o.value)&&typeof o.value.id=="string"?o.value.id:void 0,n=e.coupons.source==="literal"&&Array.isArray(e.coupons.value)?e.coupons.value:[],r=t(e.paywall),i=t(e.offering);return{type:"bundle",...r?{paywallVersionId:r}:{},...i?{offeringVersionId:i}:{},couponIds:n.flatMap(o=>o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.id=="string"?[o.id]:[]),data:e.data.source==="literal"?e.data.value:{variable:e.data.key}}}import{z as tn}from"zod";import{z as ut}from"zod";var Am=ut.union([ut.string(),ut.number().finite(),ut.boolean(),ut.null()]),XS=ut.union([Am,ut.array(Am).min(1).max(20)]),zS=ut.record(Kt,XS).refine(e=>Object.keys(e).length<=10),oc=ut.strictObject({path:Kt,type:ut.enum(["string","number","boolean","strings"]),nullable:ut.boolean().optional(),aggregation:ut.enum(["count","exists"]).optional(),where:zS.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"})});function XR(e,t){return Object.fromEntries(Object.entries(e).map(([n,r])=>{let i=oc.parse(r),o=Cr(t,i.path);if(i.nullable&&o==null)return[n,null];if(i.aggregation){if(!Array.isArray(o))throw new Error("Collection projection requires an array");let s=o.filter(c=>Object.entries(i.where??{}).every(([u,l])=>{let d=Cr(c,u);return Array.isArray(l)?l.some(m=>m===d):l===d}));return[n,i.aggregation==="count"?s.length:s.length>0]}let a=i.type==="strings"?ut.array(ut.string()):i.type==="string"?ut.string():i.type==="number"?ut.number().finite():ut.boolean();return[n,a.parse(o)]}))}var ev=["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"],wm=tn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),tv=un,Pm=tn.discriminatedUnion("type",[mm,tn.strictObject({type:tn.literal("claim_offer"),coupon:un}),tn.strictObject({type:tn.literal("event"),event:wm}),tn.strictObject({type:tn.literal("api"),operation:tn.enum(ev),inputs:tn.record(Kt,tv).refine(e=>Object.keys(e).length<=40),outputs:tn.record(wm,oc).refine(e=>Object.keys(e).length<=20)})]);function ij(e,t){return dm(e,t)}var Ke=Go,nv=M.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),Ut={id:Ke,name:M.string().trim().min(1).max(80),position:M.strictObject({x:M.number().finite(),y:M.number().finite()}).optional()},rv={success:Ke,cancel:Ke,unavailable:Ke,failure:Ke},ac=M.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),sc=M.enum(["same_window","new_window"]),iv=M.discriminatedUnion("type",[M.strictObject({...Ut,type:M.literal("entry"),next:Ke}),M.strictObject({...Ut,type:M.literal("screen"),screenId:Ke,presentation:en,outputs:M.record(Ke,Ke),offering:M.discriminatedUnion("source",[M.strictObject({source:M.literal("variable"),key:Ye}),M.strictObject({source:M.literal("fixed"),versionId:M.uuid()})]).optional()}),M.strictObject({...Ut,type:M.literal("offering"),configuration:M.discriminatedUnion("source",[M.strictObject({source:M.literal("fixed"),versionId:M.uuid()}),M.strictObject({source:M.literal("feature"),featureKey:M.string().min(1).max(128)})]),writes:M.strictObject({value:Ye}),next:Ke}),M.strictObject({...Ut,type:M.literal("coupon"),couponId:M.uuid(),writes:M.strictObject({value:Ye}),next:Ke}),M.strictObject({...Ut,type:M.literal("coupons"),couponIds:M.array(M.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:M.strictObject({value:Ye}),next:Ke}),M.strictObject({...Ut,type:M.literal("output"),value:M.discriminatedUnion("type",[...Ti.options,Im,M.strictObject({type:M.literal("selection"),screenId:Ke,offeringKey:Ye})])}),M.strictObject({...Ut,type:M.literal("condition"),cases:M.array(M.strictObject({condition:wn,target:Ke})).min(1).max(50),default:Ke}),M.strictObject({...Ut,type:M.literal("feature"),featureKey:M.string().min(1).max(128),writes:M.strictObject({value:Ye}),next:Ke}),M.strictObject({...Ut,type:M.literal("split"),experimentId:M.uuid(),routes:M.record(nv,Ke).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:Ke}),M.strictObject({...Ut,type:M.literal("action"),...rv,execution:fm,action:Pm,writes:qo.optional()}),M.strictObject({...Ut,type:M.literal("external_page"),appManifest:zu.optional(),url:ac,openIn:sc,opened:Ke,failed:Ke}),M.strictObject({...Ut,type:M.literal("end"),outcome:M.enum(["completed","closed","ineligible","failed"]),output:Ti.optional()}),M.strictObject({...Ut,type:M.literal("wait"),writes:qo.optional(),wait:M.discriminatedUnion("type",[M.strictObject({type:M.literal("duration"),delaySeconds:M.number().int().min(1).max(2592e3),elapsed:Ke}),M.strictObject({type:M.literal("event"),eventName:Ke,outputs:tc,timeoutSeconds:M.number().int().min(1).max(2592e3),received:Ke,timeout:Ke})])})]),cc=M.strictObject({version:M.literal(5),entry:Ke,nodes:M.array(iv).min(1).max(Qe.flowNodes)}),uc=cc.superRefine((e,t)=>{ov(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function kr(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 ov(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,d,m)=>{n.push(l),t?.({message:l,reason:d,path:m?["nodes",e.nodes.indexOf(m)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>Qe.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Qe.logicNodes)&&i("Flow node limit exceeded","budget");let o=new Set;for(let l of e.nodes){for(let d of kr(l))d===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(d)||i(`Missing target ${d}`,"missingTarget",l);l.type==="screen"&&(o.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),o.add(l.screenId))}let a=new Set,s=new Set,c=new Set;function u(l){if(a.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){a.add(l),c.add(l);for(let d of kr(r.get(l)))u(d);a.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}function av(e,t){let n=e.cases.findIndex(r=>zs(r.condition,t));return{ruleIndex:n<0?null:n,target:e.cases[n]?.target??e.default}}function _j(e,t,n,r){let i=e.nodes.find(c=>c.id===t.nodeId),o=[...t.history];if(!i||!["running","waiting"].includes(t.status))throw new Error("Flow is not active");let a,s=[];switch(n.type){case"start":if(i.type!=="entry")throw new Error("Flow already started");a=i.next;break;case"next":if(i.type!=="screen"||!Object.hasOwn(i.outputs,n.output)||i.outputs[n.output]===void 0)throw new Error("Invalid screen output");{let c=i.outputs[n.output];if(c===void 0)throw new Error("Invalid screen output");a=c}o.push(i.id);break;case"back":if(i.type!=="screen"||!o.length)throw new Error("No previous screen");if(a=o.pop(),e.nodes.find(c=>c.id===a)?.type!=="screen")throw new Error("Invalid screen history");break;case"condition":if(i.type!=="condition")throw new Error("Not a condition node");{let c=av(i,r);a=c.target,s.push({nodeId:i.id,...c})}break;case"feature":if(i.type!=="feature")throw new Error("Not a Feature node");a=i.next;break;case"configuration":if(i.type!=="offering"&&i.type!=="coupon")throw new Error("Not a configuration node");a=i.next;break;case"assignment":if(i.type!=="split")throw new Error("Not an Experiment node");{let c=n.variantId===null?i.notParticipating:i.routes[n.variantId];if(!c)throw new Error("Unknown native Variant key");a=c}break;case"result":if(i.type!=="action")throw new Error("Not a capability invocation");a=i[n.result];break;case"page":if(i.type!=="external_page")throw new Error("Not an external page");a=i[n.result];break;case"wait":if(i.type!=="wait")throw new Error("Not a wait node");if(i.wait.type==="duration"){if(n.result!=="elapsed")throw new Error("Invalid timer result");a=i.wait.elapsed}else{if(n.result==="elapsed")throw new Error("Invalid event result");a=i.wait[n.result]}break}if(!e.nodes.some(c=>c.id===a))throw new Error("Target does not exist");return{state:{nodeId:a,history:o.slice(-Qe.pages),status:"running"},entered:[a],routed:s}}var Zo={maxTransitions:1e4,runTimeoutSeconds:2592e3},vj={detailBytes:16384};function xj(e,t){return Number.isInteger(e)&&e>=1&&e<=Zo.maxTransitions&&Number.isInteger(t)&&t>=0&&t<e}function _t(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 o=t.charAt(i);if(r)o==="\\"?i++:o==='"'&&(r=!1);else if(o==='"')r=!0;else if(o===":"||o===",")n++;else if(o==="-"||o>="0"&&o<="9"){let a=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(a,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),d=l.replace(".","").length,m=(l.includes(".")?l.indexOf("."):d)+Number(u),g=m<=0?2-m+d:m>=d?m:d+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}function Yo(e,t){let n=[...t].sort((i,o)=>o.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&&!Kt.safeParse(r).success?null:{key:n,path:r}}function lc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Et(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Ku))]}function dc(e){return lc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function Tj(e,t){let n=tr(t.declarations,t);return Object.fromEntries(dc(e).flatMap(r=>{let i=Yo(r,Object.keys(t.declarations)),o=i&&Object.hasOwn(n,i.key)?Cr(n[i.key],i.path):void 0;return o!==void 0?[[r,ge.parse(o)]]:[]}))}function Rj(e,t,n){let r=i=>i.replace(/\{\{\s*variables\.([^{}]+?)\s*\}\}/g,(o,a)=>(a=a.trim(),a===t||a.startsWith(t+".")?"{{ variables."+n+a.slice(t.length)+" }}":o));return e.screens.map(i=>{if(i.type!=="owned")return i;let o=structuredClone(i.document);for(let a of Object.values(o.strings.locales))for(let s of Object.keys(a))a[s]=r(a[s]);return Et(o,a=>{if(a.type==="custom_html")for(let s of Object.keys(a.html))a.html[s]=r(a.html[s])}),{...i,document:o}})}function Om(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,o=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of Ei(c.condition))u.startsWith("variables.")&&o(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&o(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&o(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&o(e.action.coupon.key);let a=e.type==="output"?e.value:e.type==="end"?e.output:null;if(a?.type==="variable"&&o(a.key),a?.type==="bundle")for(let s of[a.paywall,a.offering,a.coupons,a.data])s?.source==="variable"&&o(s.key);return a?.type==="selection"&&o(a.offeringKey),[...i]}import{z as O}from"zod";var Dr=O.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Jo=e=>O.record(O.string(),ge).refine(t=>_t(t)<=e,"Funnel evidence exceeds its byte budget"),Mj=O.enum(["local_segment","evaluation","presentation","timer","event","operation"]),mc=O.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),fc=O.discriminatedUnion("type",[O.strictObject({type:O.literal("flag"),key:O.string().min(1).max(128)}),O.strictObject({type:O.literal("experiment"),id:O.uuid()}),O.strictObject({type:O.literal("saved_group"),id:O.uuid()}),O.strictObject({type:O.literal("config"),key:O.string().min(1).max(128)}),O.strictObject({type:O.literal("constant"),key:O.string().min(1).max(128)}),O.strictObject({type:O.literal("paywall_version"),id:O.uuid()}),O.strictObject({type:O.literal("offering_version"),id:O.uuid()}),O.strictObject({type:O.literal("reward"),id:O.uuid()})]),Nr=O.strictObject({schemaVersion:O.literal(1),kind:mc,selector:fc.nullable(),context:Jo(131072),contract:O.strictObject({version:O.number().int().positive(),evaluator:O.string().min(1).max(128),policyRevision:O.number().int().nonnegative()})}).refine(e=>_t(e)<=131072,"Node input exceeds its byte budget"),Cm=O.strictObject({schemaVersion:O.literal(1),kind:mc,outcome:O.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Jo(131072),route:O.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Jo(131072)}).refine(e=>_t(e)<=131072,"Node result exceeds its byte budget"),Bj=O.strictObject({schemaVersion:O.literal(1),operations:O.record(Dr,O.strictObject({attempts:O.number().int().nonnegative(),maxAttempts:O.number().int().min(1).max(5),deadlineAt:O.iso.datetime({offset:!0}),retryAt:O.iso.datetime({offset:!0}).nullable(),error:O.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:O.strictObject({type:Dr,id:O.uuid()}).nullable()}))}).refine(e=>_t(e)<=65536,"Execution state exceeds its byte budget"),sr={receiptId:O.uuid()},pc=O.iso.datetime({offset:!0}),Lj=O.discriminatedUnion("type",[O.strictObject({type:O.literal("node_entered"),details:O.strictObject({kind:mc})}),O.strictObject({type:O.literal("presentation_shown"),details:O.strictObject({...sr,source:O.literal("client"),occurredAt:pc.optional()})}),O.strictObject({type:O.literal("decision_accepted"),details:O.strictObject(sr)}),O.strictObject({type:O.literal("signal_received"),details:O.strictObject({signalId:O.uuid(),nodeId:Dr,eventName:Dr,data:Jo(8192),source:O.literal("server"),occurredAt:pc})}),O.strictObject({type:O.literal("signal_consumed"),details:O.strictObject({...sr,signalId:O.uuid()})}),O.strictObject({type:O.literal("wait_elapsed"),details:O.strictObject(sr)}),O.strictObject({type:O.literal("wait_timeout"),details:O.strictObject(sr)}),O.strictObject({type:O.literal("operation_completed"),details:O.strictObject({...sr,operation:Dr,reference:O.strictObject({type:Dr,id:O.uuid()}).nullable()})}),O.strictObject({type:O.literal("execution_recovered"),details:O.strictObject({generation:O.number().int().positive(),reason:O.enum(["interrupted","expired_lease","delivery_failed"])})}),O.strictObject({type:O.literal("execution_failed"),details:O.strictObject({generation:O.number().int().positive(),code:O.string().regex(/^[a-z_]{1,64}$/)})}),O.strictObject({type:O.literal("run_completed"),details:O.strictObject({outcome:O.enum(["completed","ineligible","failed"])})}),O.strictObject({type:O.literal("run_closed"),details:O.strictObject({source:O.enum(["client","server","expiry"])})}),O.strictObject({type:O.literal("treatment_used"),details:O.strictObject({...sr,source:O.enum(["client","server"]),occurredAt:pc,reference:O.string().min(1).max(128).optional()})})]);var Wt=E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),sv=E.discriminatedUnion("type",[E.strictObject({id:Wt,type:E.literal("owned"),publicData:rm.optional(),document:nt.refine(e=>e.surface!=="paywall"&&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")}),E.strictObject({id:Wt,type:E.literal("paywall"),paywallVersionId:E.uuid()})]),gc={kind:E.literal("funnel"),schemaVersion:E.literal(4),screens:E.array(sv).max(Qe.pages),references:E.record(Wt,fc).refine(e=>Object.keys(e).length<=500),inputs:E.array(E.strictObject({variable:Wt,screenId:Wt,componentId:Wt,required:E.boolean()})).max(Qe.questions),variables:E.record(Ye,Or).refine(e=>Object.keys(e).length<=Qe.logicNodes),outputSchema:Pr,execution:E.strictObject({runTimeoutSeconds:E.number().int().min(1).max(Zo.runTimeoutSeconds),maxTransitions:E.number().int().min(1).max(Zo.maxTransitions)})},Mt=E.strictObject({...gc,graph:cc});function cv(e,t){let n=!1,r=(i,o)=>{let a=i.type==="stack"||i.type==="button"?i.bind?.coupon??o:o;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(a&&t(a))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,a))};for(let i of e.pages)r(i.root);return n}function zo(e){return Array.isArray(e)?e.some(zo):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===gm:zo(n))}function uv(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 o;try{o=Mo(i.document)}catch(a){t.push({message:a instanceof Error?a.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[a,s]of e.inputs.entries())s.screenId===i.id&&!si(o,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",a]})}for(let[r,i]of e.graph.nodes.entries()){let o=["graph","nodes",r],a=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;a?.type==="owned"&&(a.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:o}),cv(a.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:o})),(i.type==="output"&&i.value.type==="literal"&&zo(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&zo(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:o})}return t}function Em(e,t){for(let{message:n,reason:r,path:i}of uv(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Tm(e,t){let n=(g,p,f=[])=>t.addIssue({code:"custom",message:g,path:f,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),o=(g,p)=>r.some(f=>f.type===g&&("id"in f?f.id:f.key)===p);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let a=e.graph.nodes.filter(g=>g.type==="screen");(a.length!==i.size||a.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(p=>g!==p&&p.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,p){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let f=s.get(g)??new Set;f.add(p.id),s.set(g,f)}for(let[g,p]of e.graph.nodes.entries()){let f=["graph","nodes",g],y=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;y&&!o("flag",y)&&n("Flag selectors require an explicit GB resource reference","feature",f);let x=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):[],S="writes"in p?p.writes??{}:{};(x.length!==Object.keys(S).length||x.some(A=>!Object.hasOwn(S,A))||new Set(Object.values(S)).size!==Object.values(S).length)&&n("Node writes must map every named output exactly once","variable",f);for(let[A,v]of Object.entries(S)){u(v,p);let G=e.variables[v],$=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[A]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[A]:void 0;(G?.source.type!=="node"||$&&G.type!==$)&&n("Node writer source or output type does not match declaration","variable",f)}if(p.type==="coupons"){let A=e.variables[p.writes.value];(A?.type!=="array"||A.items?.type!=="reward"||A.items.nullable||A.nullable)&&n("Coupons output requires a non-null Reward array","variable",f);for(let v of p.couponIds)o("reward",v)||n("Coupons require Reward references","coupon",f)}if(p.type==="split"&&!o("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",f),p.type==="coupon"&&!o("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",f),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="literal"){let A=p.action.coupon.value;(!A||typeof A!="object"||Array.isArray(A)||A.type!=="reward"||typeof A.id!="string"||Object.keys(A).length!==2||!o("reward",A.id))&&n("Coupon claims require a Reward reference","coupon",f)}if(p.type==="offering"&&p.configuration.source==="fixed"&&!o("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",f),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",f),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",f),p.type==="screen"){let A=i.get(p.screenId);if(p.offering?.source==="fixed"&&!o("offering_version",p.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",f),A?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",f),A?.type==="paywall"&&!o("paywall_version",A.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",f),A?.type==="owned"){let v=A.document.pages[0];if(!v){n("Owned screen requires a page","screen",f);continue}br(A.document).some($=>!$.complete)&&n("Owned screens require complete local content","translations",f);let G=new Set(A.document.actions.map($=>$.id));(G.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some($=>!G.has($)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",f),ai(v.root,$=>{!p.offering&&($.type==="plan_picker"||($.type==="stack"||$.type==="button")&&$.bind?.plan||$.type==="customer_data"&&["customer_plans","credit_packs"].includes($.data.source))&&n("Product presentation requires an Offering Version","offering",f),$.type==="customer_data"&&Object.values($.data.outputs??{}).some(Pe=>Pe!==void 0&&!G.has(Pe))&&n("Customer components require declared screen outcomes","componentOutput",f)})}}p.type==="end"&&["completed","ineligible"].includes(p.outcome)&&!p.output&&n("Completed and ineligible ends require a declared output","output",f),p.type==="end"&&p.output?.type==="literal"&&!Ft(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",f),p.type==="output"&&p.value.type==="literal"&&!Ft(e.outputSchema,p.value.value)&&n("Terminal output does not match outputSchema","output",f);let j=p.type==="output"?p.value:p.type==="end"?p.output:void 0;if(j?.type==="variable"&&!j.path){let A=e.variables[j.key];A&&!Js(A,e.outputSchema)&&n("Variable output does not match outputSchema","output",f)}if(p.type==="screen"){let A=i.get(p.screenId);if(A?.type==="owned")for(let v of lc(A.document))(/^(input|params)\./.test(v)||v.startsWith("variables.")&&!Yo(v.slice(10),c))&&n("Screen values must reference registered variables","variable",f)}if(p.type==="condition")for(let A of p.cases){for(let v of fr(A.condition))o("saved_group",v)||n("Conditions require explicit Saved Group references","savedGroup",f);for(let v of Ei(A.condition))v.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",f)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",f);for(let[A,v]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let G=p.value[A];if(G)if(G.source==="literal"){let $=A==="coupons"?G.value:[G.value];(!Array.isArray($)||$.length>20||$.some(Pe=>!Ft({type:v,nullable:!1},Pe)||!o(v,Pe.id))||A==="coupons"&&new Set($.map(Pe=>Pe.id)).size!==$.length)&&n("Bundle requires distinct scoped resource references",A==="coupons"?"coupon":A==="paywall"?"paywall":"offering",[...f,"value",A])}else{let $=e.variables[G.key];(G.path||!$||$.nullable||(A==="coupons"?$.type!=="array"||$.items?.type!=="reward"||$.items.nullable:$.type!==v))&&n("Bundle binding type does not match its slot","output",f)}}}}for(let[g,p]of e.graph.nodes.entries()){let f=p.type==="screen"?i.get(p.screenId):void 0,y=[...Om(p,c),...f?.type==="owned"?dc(f.document).map(x=>Yo(x,c)?.key??x):[]];for(let x of new Set(y)){let v=function(G){if(G===p.id)return!0;if(A.has(G))return!1;A.add(G);let $=e.graph.nodes.find(Re=>Re.id===G);return $?(j.has(G)?$.type==="action"?[$.cancel,$.unavailable,$.failure]:$.type==="wait"&&$.wait.type==="event"?[$.wait.timeout]:[]:kr($)).some(v):!1};var m=v;if(!Object.hasOwn(e.variables,x)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let S=e.variables[x];if(p.type==="screen"&&S.source.type==="input"&&e.inputs.some(G=>G.screenId===p.screenId&&G.variable===x)||S.source.type==="parameter"||S.source.type==="attribute")continue;let j=S.source.type==="input"?new Set(e.inputs.filter(G=>G.variable===x&&G.required).flatMap(G=>a.filter($=>$.screenId===G.screenId).map($=>$.id))):s.get(x)??new Set,A=new Set;(!j.size||v(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}}(new Set(e.inputs.map(g=>g.variable)).size!==e.inputs.length||new Set(e.inputs.map(g=>`${g.screenId}:${g.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[g,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",g]);let f=i.get(p.screenId),y=f?.type==="owned"?si(f.document,p.componentId):null;if((y?.type!=="stack"||!y.interaction||!["input","toggle","select","multiselect","tabs"].includes(y.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g]),y?.type==="stack"&&y.interaction){let x=y.interaction.type==="toggle"?"boolean":y.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==x&&n("Input variable type does not match component","inputBinding",["inputs",g]);let S=e.variables[p.variable]?.enum;S&&!y.children.filter(j=>!j.hidden).every(j=>S.includes(j.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",g])}}for(let[g,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",g]),p.source.type==="input"&&!e.inputs.some(f=>f.variable===g)&&n("Input variable requires a component binding","inputBinding",["variables",g]);let l=0,d=0;for(let g of e.screens)if(g.type==="owned"){for(let p of g.document.pages)ai(p.root,()=>{l++});d+=g.document.actions.length}(l>Qe.components||d>Qe.actions||_t(e)>Qe.documentBytes)&&n("Funnel document exceeds its budget","budget")}var bc=E.strictObject({...gc,graph:uc}).superRefine(Tm),ln=E.strictObject({...gc,graph:uc,displayName:E.string().trim().min(1).max(80)}).superRefine(Tm),ok=ln.superRefine(Em),ak=bc.superRefine(Em),Xo=E.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),Fr={requestId:E.uuid(),nodeId:Wt,visit:E.number().int().nonnegative(),revision:E.number().int().nonnegative(),customerToken:Xo.optional()},lv=E.discriminatedUnion("type",[E.strictObject({type:E.literal("screen"),output:Wt,answers:Qn,selection:E.record(Wt,E.union([E.string().max(200),E.boolean()])).optional()}),E.strictObject({type:E.literal("paywall_quote"),actionId:Wt,productVersionId:E.uuid(),offerId:E.uuid().optional(),nativeOffer:Rn.optional(),predecessor:E.strictObject({operationId:E.uuid().nullable(),generation:E.number().int().positive()}).optional()}),E.strictObject({type:E.literal("paywall_confirm"),operationId:E.uuid()}),E.strictObject({type:E.literal("paywall_cancel"),operationId:E.uuid()}),E.strictObject({type:E.literal("client_action"),receiptId:E.uuid(),outcome:E.enum(["success","cancel","failure","opened","failed"])})]),dv=E.object({nodeId:Wt,visit:E.number().int().nonnegative(),revision:E.number().int().nonnegative(),components:E.record(Wt,E.object({resourceKey:E.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:E.number().int().min(1).max(1e5),after:no.nullable(),filter:E.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Ri=E.discriminatedUnion("operation",[E.strictObject({operation:E.literal("start"),funnelId:E.uuid(),requestId:E.uuid(),customer:Tr.optional(),customerData:Rr.optional(),locale:E.string().min(1).max(35),parameters:$t}).refine(or,ar),E.strictObject({operation:E.literal("get"),settlementRequestId:E.uuid().optional(),data:dv.optional(),purchase:E.strictObject({receiptId:E.uuid(),operationId:E.uuid()}).optional(),customerToken:Xo.optional()}),E.strictObject({operation:E.literal("resume"),requestId:E.uuid(),customerToken:Xo.optional()}),E.strictObject({operation:E.literal("submit"),...Fr,input:lv}),E.strictObject({operation:E.literal("back"),...Fr}),E.strictObject({operation:E.literal("shown"),...Fr}),E.strictObject({operation:E.literal("close"),...Fr}),E.strictObject({operation:E.literal("commit_segment"),...Fr,policyRevision:E.number().int().nonnegative(),generation:E.string().min(1).max(256),steps:E.array(Lo).max(32),boundary:E.strictObject({nodeId:E.string().min(1).max(64),visit:E.number().int().nonnegative()}).optional()}),E.strictObject({operation:E.literal("evaluate"),...Fr,receiptId:E.uuid(),policyRevision:E.number().int().nonnegative(),generation:E.string().min(1).max(256),result:Oi}),E.strictObject({operation:E.literal("review"),receiptId:E.uuid().optional(),customerToken:Xo.optional()})]);function hc(e,t){if(!e||e.hidden)return null;if(e.id===t)return e;if(e.type!=="stack")return null;for(let n of e.children){let r=hc(n,t);if(r)return r}return null}function pv(e,t,n,r,i){let o=e.graph.nodes.find(u=>u.id===t);if(o?.type!=="screen")throw new Error("Input is only accepted on a screen");let a=e.screens.find(u=>u.id===o.screenId),s=e.inputs.filter(u=>u.screenId===o.screenId),c={...r};for(let[u,l]of Object.entries(n)){let d=s.find(f=>f.variable===u);if(!d||a?.type!=="owned")throw new Error("Unknown screen input");let m=hc(a.document.pages[0]?.root,d.componentId);if(m?.type!=="stack"||!m.interaction)throw new Error("Input is unavailable");let g=m.interaction;switch(g.type){case"input":if(typeof l!="string"||l.length>g.maxLength)throw new Error("Invalid input text");if(l&&g.keyboard==="email"&&!E.email().safeParse(l).success)throw new Error("Invalid email");if(l&&g.keyboard==="url"&&!E.url().safeParse(l).success)throw new Error("Invalid URL");break;case"toggle":if(typeof l!="boolean")throw new Error("Invalid toggle value");break;case"select":case"tabs":if(typeof l!="string"||!m.children.some(f=>f.id===l&&!f.hidden))throw new Error("Invalid selected option");break;case"multiselect":if(!Array.isArray(l)||new Set(l).size!==l.length||l.length>g.max||i&&l.length<g.min||l.some(f=>!m.children.some(y=>y.id===f&&!y.hidden)))throw new Error("Invalid selected options");break;default:throw new Error("Component cannot accept input")}let p=e.variables[u];if(p?.source.type!=="input"||!Ft(p,l))throw new Error("Invalid input variable");c[u]=l}if(i)for(let u of s){let l=c[u.variable];if(u.required&&(l===void 0||l===""||Array.isArray(l)&&l.length===0))throw new Error(`Required input: ${u.variable}`);l!==void 0&&!Object.hasOwn(n,u.variable)&&pv(e,t,{[u.variable]:l},{},!1);let d=a?.type==="owned"?hc(a.document.pages[0]?.root,u.componentId):null;if(d?.type==="stack"&&d.interaction?.type==="multiselect"&&Array.isArray(l)&&l.length<d.interaction.min)throw new Error("Not enough selected options")}return c}function ea(e,t){let n=new Set,r=new Set,i=new Set,o=[],a=new Map,s=new Map,c=new Map;function u(p){for(let f of fr(p))l(f)}function l(p){if(i.has(p)||!Object.hasOwn(t.savedGroups,p))return;let f=t.savedGroups[p];f&&(i.add(p),c.set(p,f),o.push(()=>{!Array.isArray(f)&&f.type==="condition"&&u(f.condition)}))}function d(p){u(p.condition);for(let f of p.parentConditions??[])m(f.id),u(f.condition)}function m(p,f=!1){let y=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!y){if(f)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),a.set(p,y),o.push(()=>{for(let x of y.rules??[]){d(x);for(let S of x.tracks??[])d(S.experiment)}}))}function g(p){let f=Object.hasOwn(t.experiments,p)?t.experiments[p]:void 0;if(!f)throw new Error("Required GB Experiment is unavailable");r.has(p)||(r.add(p),s.set(p,f),o.push(()=>d(f)))}for(let p of e.graph.nodes){p.type==="feature"&&m(p.featureKey,!0),p.type==="split"&&g(p.experimentId),p.type==="condition"&&p.cases.forEach(y=>u(y.condition)),p.type==="offering"&&p.configuration.source==="feature"&&m(p.configuration.featureKey,!0);let f=p.type==="output"?p.value:p.type==="end"?p.output:null;f?.type==="feature"&&m(f.featureKey,!0)}for(let p of o)p();return{...t,features:Object.fromEntries(a),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as Z}from"zod";import{z as ji}from"zod";var Rm=ji.object({defaultLocale:bn,locales:ji.record(bn,ji.object({name:ji.string().max(80),description:ji.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"})});function mk(e,t){let n=e.displayCopy;if(!n)return{name:e.name,description:""};let r=Object.keys(n.locales).filter(s=>n.locales[s]?.name.trim()),i=Eu([t],r,n.defaultLocale),o=n.locales[i],a=n.locales[n.defaultLocale];return{name:o?.name.trim()?o.name:a?.name.trim()?a.name:e.name,description:o?.description.trim()?o.description:a?.description.trim()?a.description:""}}var mv=["customer_data","coupon_code"],fv=Z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),jm=Z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),ta=(e,t)=>new Set(e.map(t)).size===e.length,hv=Z.strictObject({currency:re,amountMinor:Z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),gv=Z.strictObject({featureId:Z.uuid(),name:Z.string().trim().min(1).max(120),allowance:Z.string().max(40).nullable(),access:Z.boolean()}),bv=Z.strictObject({stripe:Z.strictObject({prices:Z.array(hv).min(1).max(50)}).optional(),apple:Z.strictObject({productIds:Z.array(fv).min(1).max(10)}).optional(),google:Z.strictObject({products:Z.array(Z.strictObject({productId:jm,basePlanId:jm.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!ta(e.stripe.prices,n=>n.currency)||e.apple&&!ta(e.apple.productIds,n=>n)||e.google&&!ta(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),_v=Z.strictObject({name:Z.string().trim().min(1).max(80),interval:Z.enum(["free","week","month","year","one_time"]),intervalCount:Z.number().int().min(1).max(100),trial:Z.strictObject({days:Z.number().int().min(1).max(730),cardRequired:Z.boolean()}).nullable(),benefits:Z.array(gv).max(50).refine(e=>ta(e,t=>t.featureId),"Duplicate benefit"),channels:bv}),yv=Z.strictObject({digest:kn,content:Z.strictObject({discount:On,duration:Dt,appliesTo:yo,displayCopy:Rm.nullable(),firstPurchaseOnly:Z.boolean(),qualificationRequired:Z.boolean(),startsAt:Z.iso.datetime().nullable(),endsAt:Z.iso.datetime().nullable(),grantWindowHours:Z.number().int().positive(),perCustomerLimit:Z.number().int().positive()})}),Sv=Z.discriminatedUnion("type",[Z.strictObject({type:Z.literal("checkout"),product:Fo}),Z.strictObject({type:Z.literal("close")}),Z.strictObject({type:Z.literal("action"),action:$s})]),km=Z.strictObject({kind:Z.literal("paywall"),formatVersion:Z.literal(1),name:Z.string().trim().min(1).max(80),offeringVersionId:Z.uuid(),presentation:en,screen:nt,products:No,catalog:Z.record(Z.uuid(),_v),buttons:Z.record(Hu,Sv),coupons:Z.record(Z.uuid(),yv)}).superRefine((e,t)=>{let n=f=>t.addIssue({code:"custom",message:f}),{screen:r}=e;r.surface!=="paywall"&&n("Screen must be a Paywall"),Hs(r,mv).forEach(n),br(r).some(f=>!f.complete)&&n("Every published locale must be complete");let i=new Set,o=new Set,a=new Set;Et(r,f=>{let y="bind"in f?f.bind:void 0;y?.promotionCode&&n("Promotion codes must not be published"),y?.plan&&i.add(y.plan),y?.coupon&&o.add(y.coupon),f.type==="plan_picker"&&(f.planIds?.forEach(x=>i.add(x)),f.defaultPlan&&i.add(f.defaultPlan)),f.type==="text"&&f.feature&&a.add(f.feature.id)});let s=e.products.items.map(f=>f.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(f=>!Object.hasOwn(e.catalog,f)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let f of i)u.has(f)||n("Screen references a Product that is not displayed");for(let f of Object.values(e.catalog))!f.channels.stripe&&!f.channels.apple&&!f.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(f=>f.benefits.map(y=>y.featureId)));for(let f of a)l.has(f)||n("Feature text must read a displayed benefit");let d=r.actions.filter(f=>f.type!=="navigate");r.actions.some(f=>f.type!=="event"&&f.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==d.length||d.some(f=>!Object.hasOwn(e.buttons,f.id)))&&n("Buttons must match the screen's actions");let g=!1;for(let f of Object.values(e.buttons)){if(f.type!=="checkout")continue;g=!0,(f.product.type==="fixed"?[f.product.productVersionId]:f.product.allowedProductVersionIds).some(x=>!u.has(x))&&n("Checkout may only sell displayed Products")}g||n("A Paywall needs a checkout button");let p=Object.keys(e.coupons);(p.length!==o.size||p.some(f=>!o.has(f)))&&n("Coupons must be exactly the bound Coupons")}),Dm=Z.strictObject({state:Z.enum(["published","archived"]),controlRevision:Z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:Z.uuid(),versions:Z.record(Z.uuid(),Z.strictObject({version:Z.number().int().positive(),artifact:Z.string().min(1),sourceDigest:Z.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var vv={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},_c=de.string().regex(/^[a-f0-9]{64}$/),yc=de.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),xv=ke.extend({environmentId:de.uuid()}),Nm=de.strictObject({features:de.array(de.string()).max(500),experiments:de.record(de.uuid(),de.array(de.string()).max(20)),savedGroups:de.array(de.string()).max(1e3)}),vc=de.strictObject({kind:de.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:de.number().int().positive(),url:de.string().min(1).max(2048),sha256:_c,byteLength:de.number().int().positive().max(vv.maxArtifactBytes),generation:_c.optional()}),Iv=de.strictObject({state:de.enum(["active","paused","archived"]),controlRevision:yc,evaluationMode:de.enum(["local","remote"]),evaluationRevision:yc,currentVersionId:de.uuid(),versions:de.record(de.uuid(),de.strictObject({artifact:de.string(),dependencies:Nm,definitionDigest:kn.optional(),couponDigests:de.record(de.uuid(),kn).optional()}))}),Nk=de.strictObject({kind:de.literal("sdk_configuration"),schemaVersion:de.literal(1),scope:xv,revision:yc,generation:_c,policy:de.strictObject({refreshIntervalSeconds:de.number().positive().max(15),maxControlAgeSeconds:de.number().positive().max(60)}),gb:de.strictObject({features:de.string().nullable(),pageExperiments:de.string().nullable()}),artifacts:de.record(de.string(),vc),funnels:de.record(de.uuid(),Iv),paywalls:de.record(de.uuid(),Dm).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 Sc(e){if(Array.isArray(e))return`[${e.map(Sc).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)}:${Sc(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Av(e){return Yi(Ji(typeof e=="string"?new TextEncoder().encode(e):e))}function Fk(e){return Av(Sc(e))}function Uk(e,t){for(let a of Object.values(e.references))if(a.type==="flag"&&(!Object.hasOwn(t.features,a.key)||t.remoteFeatures.includes(a.key))||a.type==="experiment"&&!Object.hasOwn(t.experiments,a.id)||a.type==="saved_group"&&!Object.hasOwn(t.savedGroups,a.id))throw new Error("Funnel dependency is absent from GB public delivery");let n=ea(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),r=new Set(t.remoteFeatures);for(let a of e.graph.nodes){let s=a.type==="feature"?a.featureKey:a.type==="end"&&a.output?.type==="feature"?a.output.featureKey:a.type==="output"&&a.value.type==="feature"?a.value.featureKey:void 0;if(!s)continue;let c=n.features[s],u=a.type==="feature"?e.variables[a.writes.value]:e.outputSchema;if(!c||!u)throw new Error("Required public Feature declaration is unavailable");if([c.defaultValue,...(c.rules??[]).flatMap(d=>[...Object.hasOwn(d,"force")?[d.force]:[],...d.variations??[],...(d.tracks??[]).flatMap(m=>m.experiment.variations)])].some(d=>d===void 0||!Ft(u,d)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,o=a=>{for(let s of fr(a)){if(i.has(s))continue;let c=t.savedGroups[s];if(!c)throw new Error("Required public Saved Group is unavailable");i.add(s),!Array.isArray(c)&&c.type==="condition"&&o(c.condition)}};for(let a of e.graph.nodes)if(a.type==="condition")for(let s of a.cases)o(s.condition);for(let a of Object.values(n.features))for(let s of a.rules??[]){o(s.condition);for(let c of[...s.parentConditions??[],...(s.tracks??[]).flatMap(u=>u.experiment.parentConditions??[])]){if(r.has(c.id)||!t.features[c.id])throw new Error("Local Funnel requires public Local prerequisites");o(c.condition)}for(let c of s.tracks??[])o(c.experiment.condition)}for(let a of Object.values(n.experiments)){o(a.condition);for(let s of a.parentConditions??[]){if(r.has(s.id)||!t.features[s.id])throw new Error("Local Funnel requires public Local prerequisites");o(s.condition)}}for(let a of e.graph.nodes)if(a.type==="split"){let s=n.experiments[a.experimentId];if(!s)throw new Error("Local Funnel requires a public Experiment");for(let c=0;c<s.variations.length;c++){let u=s.meta?.[c]?.key??String(c);if(!a.routes[u])throw new Error("Experiment variation has no declared Funnel route")}}return Nm.parse({features:Object.keys(n.features).sort(),experiments:Object.fromEntries(Object.entries(n.experiments).map(([a,s])=>[a,s.variations.map((c,u)=>s.meta?.[u]?.key??String(u))])),savedGroups:[...i].sort()})}function Mk(e){return ln.parse(e)}var Fm=Xe.strictObject({...vr,selector:Xe.discriminatedUnion("type",[Xe.strictObject({type:Xe.literal("paywall"),paywallId:Xe.uuid()}),Xe.strictObject({type:Xe.literal("version"),versionId:Xe.uuid()})]),customerId:Xe.uuid().optional(),commerce:to,locale:Xe.string().min(1).max(35),requirement:hr.optional()}),ki=Xe.strictObject({id:Xe.uuid(),paywallId:Xe.uuid(),version:Xe.number().int().positive(),document:wr.omit({requirement:!0,offeringId:!0}),offering:Xe.strictObject({id:Xe.uuid()}),content:Xe.strictObject({environmentId:Xe.uuid(),offeringVersionId:Xe.uuid(),artifact:vc.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:gr,check:oi.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"})}),Ur=Xe.strictObject(ki.shape).omit({document:!0,offering:!0}).extend({content:ki.shape.content.unwrap()});function Um(e){let{document:t,offering:n,...r}=e;return Ur.parse(r)}function Zk(e,t){let n=km.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");return ki.parse({...e,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 yt}from"zod";var Mm={requestId:yt.uuid(),sourceId:yt.uuid(),expectedAvailable:kt},Bm=yt.discriminatedUnion("action",[yt.strictObject({...Mm,action:yt.enum(["add","subtract","set_remaining"]),amount:_e}),yt.strictObject({...Mm,action:yt.literal("edit"),granted:_e,expiresAt:yt.iso.datetime({offset:!0}).nullable(),nextResetAt:yt.iso.datetime({offset:!0}).nullable(),expectedRevision:yt.number().int().nonnegative()})]),xc=yt.strictObject({sourceId:yt.uuid(),available:kt,held:kt,spent:kt,adjustmentGrantId:yt.uuid().nullable()}),Lm=xc.extend({granted:kt,expiresAt:yt.iso.datetime({offset:!0}).nullable(),nextResetAt:yt.iso.datetime({offset:!0}).nullable(),revision:yt.number().int().nonnegative()});import{z as Bt}from"zod";var qm=Bt.discriminatedUnion("action",[Bt.object({action:Bt.literal("upsert"),externalId:Bt.string().min(1).max(128),name:Bt.string().trim().min(1).max(80)}).strict(),Bt.object({action:Bt.literal("archive"),entityId:Bt.uuid()}).strict()]),Vm=Bt.object({id:Bt.uuid(),externalId:Bt.string().min(1).max(128),name:Bt.string().min(1).max(80),archived:Bt.boolean()}).strict();import{z as lt}from"zod";import{z as ur}from"zod";var $m=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Gm=ur.string().regex(/.+\/.+/),Ic=ur.number().min(-100),cr=ur.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),wv=ur.strictObject({input:cr,output:cr,cache_read:cr.optional(),cache_write:cr.optional(),reasoning:cr.optional(),input_audio:cr.optional(),output_audio:cr.optional()}),Ac=(e,t)=>ur.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),iD=ur.strictObject({defaultMarkup:Ic,providerMarkups:Ac(ur.string().min(1),Ic),modelMarkups:Ac(Gm,Ic),customModels:Ac(Gm,wv.partial())});import{z as oe}from"zod";var lr=oe.iso.datetime({offset:!0}),Dn=oe.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Pv=oe.discriminatedUnion("kind",[oe.object({kind:oe.literal("absolute"),from:lr,to:lr}).strict(),oe.object({kind:oe.literal("last_days"),days:oe.union([oe.literal(1),oe.literal(7),oe.literal(30),oe.literal(90)])}).strict(),oe.object({kind:oe.literal("billing_cycles"),membershipId:oe.uuid(),count:oe.number().int().min(1).max(12),includeCurrent:oe.boolean()}).strict()]),Km=oe.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"),Ov=oe.object({key:oe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:oe.array(oe.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),dr=oe.object({range:Pv,timezone:Km,filterBy:oe.array(Ov).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:oe.enum(["hour","day","week","month"]),internal_feature_id:oe.uuid().nullable(),entityId:oe.uuid().nullable(),topN:oe.number().int().min(1).max(50).nullable(),groupBy:oe.union([oe.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),oe.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:oe.object({bucket:lr,group:oe.string().max(240),isOther:oe.boolean(),internal_feature_id:oe.uuid(),resourceId:oe.uuid()}).strict().nullable(),limit:oe.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)"})}),Wm=oe.object({from:lr,to:lr,interval:oe.enum(["hour","day","week","month"]),timezone:Km,rows:oe.array(oe.object({bucket:lr,group:oe.string().max(240),isOther:oe.boolean(),internal_feature_id:oe.uuid(),resourceId:oe.uuid(),consumedUnits:Dn,refundedUnits:Dn,reservedUnits:Dn,charged:Dn,refunded:Dn,reserved:Dn,netUnits:Dn,netCharged:Dn}).strict()).max(100),nextCursor:oe.object({bucket:lr,group:oe.string().max(240),isOther:oe.boolean(),internal_feature_id:oe.uuid(),resourceId:oe.uuid()}).strict().nullable()}).strict();var Mr=lt.string().regex(/^(0|[1-9]\d{0,29})$/),Hm=lt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),wc=lt.strictObject({bucket:lt.iso.datetime({offset:!0}),group:lt.string().max(240),isOther:lt.boolean(),internal_feature_id:lt.uuid()}),Qm=lt.strictObject({...dr.shape,groupBy:lt.union([lt.enum(["customer","entity","entitlement"]),lt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:wc.nullable()}).superRefine((e,t)=>{let n=dr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Zm=lt.strictObject({from:lt.iso.datetime({offset:!0}),to:lt.iso.datetime({offset:!0}),interval:dr.shape.interval,timezone:dr.shape.timezone,rows:lt.array(lt.strictObject({...wc.shape,eventCount:Mr,units:Hm,tokenEventCount:Mr,tokens:lt.strictObject(Object.fromEntries($m.map(e=>[e,Mr]))),totalTokens:Mr,providerCostEventCount:Mr,providerCostUsd:Hm,invalidTelemetryEventCount:Mr})).max(100),nextCursor:wc.nullable()});import{z as Ze}from"zod";var Ym=Ze.object({requestId:Ze.uuid(),items:Ze.array(Ze.object({customerId:Ze.uuid(),command:ri.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"),Jm=Ze.object({batchId:Ze.uuid(),after:Ze.number().int().min(-1).max(999),limit:Ze.number().int().min(1).max(100)}).strict(),Xm=Ze.object({batchId:Ze.uuid(),status:Ze.enum(["queued","complete"]),total:Ze.number().int().min(1).max(1e3),processed:Ze.number().int().min(0).max(1e3),items:Ze.array(Ze.object({position:Ze.number().int().min(0).max(999),customerId:Ze.uuid(),idempotencyKey:Ze.string().min(1).max(120),status:Ze.enum(["queued","accepted","rejected","failed"]),receipt:ii.nullable(),errorCode:Ze.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:Ze.number().int().min(0).max(999).nullable()}).strict();import{z as I}from"zod";var Cv=I.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),zm=I.enum(["draft","active","paused","archived"]),ef=I.string().min(1).max(256),tf=I.array(ef).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Ev=I.strictObject({duration:I.enum(["day","week","month","year"]),length:I.number().int().min(1).max(3660)}),Tv=I.strictObject({internal_feature_id:I.uuid(),allowance:I.number().nonnegative().max(1e15).nullable(),expiry:Ev.nullable()}),Rv=I.discriminatedUnion("type",[I.strictObject({type:I.literal("feature_grant"),grants:I.array(Tv).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),I.strictObject({type:I.literal("free_product"),productId:ef,duration:Dt}),I.strictObject({type:I.literal("invoice_credits"),amount:I.number().positive().max(1e8),duration:Dt,rollover:I.boolean(),productIds:tf})]),jv=I.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),nf=I.object({key:jv,name:I.string().trim().min(1).max(80),configuration:Rv}).strict(),rf=I.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Pc=I.object({code:rf,maxUses:I.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:I.boolean()}).strict(),of=I.object({key:I.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:I.string().trim().min(1).max(80),rewardId:I.uuid(),redeemOn:I.enum(["customer_creation","checkout"]),receivedBy:I.enum(["referrer","all"]),maxRedemptions:I.number().int().min(1).max(1e6).nullable(),productIds:tf,excludeTrial:I.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),af={id:I.uuid(),projectId:I.uuid(),environmentId:I.uuid(),revision:I.number().int().nonnegative(),status:zm,createdAt:I.iso.datetime({offset:!0}),updatedAt:I.iso.datetime({offset:!0})},kv=nf.extend(af).strict(),Dv=of.safeExtend(af).strict(),_D=I.strictObject({id:I.uuid(),key:I.string(),name:I.string(),type:Cv,status:zm}),yD=I.discriminatedUnion("action",[I.object({action:I.literal("save"),id:I.uuid().nullable(),revision:I.number().int().nonnegative(),input:nf}).strict(),I.object({action:I.enum(["activate","pause","resume","archive","delete"]),id:I.uuid(),revision:I.number().int().nonnegative()}).strict()]),SD=I.discriminatedUnion("action",[I.object({action:I.literal("save"),id:I.uuid().nullable(),revision:I.number().int().nonnegative(),input:of}).strict(),I.object({action:I.enum(["activate","pause","resume","archive","delete"]),id:I.uuid(),revision:I.number().int().nonnegative()}).strict()]),sf=I.object({id:I.uuid(),rewardId:I.uuid(),programId:I.uuid().nullable(),customerId:I.uuid(),referrerId:I.uuid().nullable(),status:I.enum(["pending","applied","unavailable"]),result:I.record(I.string(),I.unknown()).nullable(),createdAt:I.iso.datetime({offset:!0})}).strict(),cf=I.object({code:rf,requestId:I.uuid()}).strict(),uf=I.strictObject({redemptionId:I.uuid(),currency:re,requestId:I.uuid(),accepted:I.literal(!0)}),Nv=I.strictObject({type:I.literal("checkout"),orderId:I.uuid(),productVersionId:I.uuid(),currency:re,duration:Dt,renewalAmountMinor:I.number().int().positive().max(1e8),status:I.enum(["created","pending","trialing","paid","cancelled","failed"]),url:I.url().nullable()}),lf=I.discriminatedUnion("type",[Nv,I.strictObject({type:I.literal("subscription"),operationId:I.uuid(),membershipId:I.uuid(),productVersionId:I.uuid(),currency:re,duration:Dt,renewalAmountMinor:I.number().int().positive().max(1e8),status:I.enum(["pending","running","applied","failed"])})]),df=I.object({programId:I.uuid(),requestId:I.uuid()}).strict(),pf=I.object({id:I.uuid(),programId:I.uuid(),code:Pc.shape.code,createdAt:I.iso.datetime({offset:!0})}).strict(),vD=I.object({rows:I.array(kv).max(100),nextCursor:I.uuid().nullable()}).strict(),xD=I.object({rows:I.array(Dv).max(100),nextCursor:I.uuid().nullable()}).strict(),Fv=Pc.extend({id:I.uuid(),redemptions:I.number().int().nonnegative()}).strict(),Uv=I.strictObject({id:I.uuid(),programId:I.uuid().nullable(),customerId:I.uuid().nullable(),referrerId:I.uuid().nullable(),code:I.string().nullable(),status:I.enum(["pending","triggered","applied"]),createdAt:I.iso.datetime({offset:!0})}),ID=I.object({codes:I.array(Fv).max(100),redemptions:I.array(Uv).max(100),customers:I.record(I.uuid(),I.string()),codesCursor:I.uuid().nullable(),redemptionsCursor:I.uuid().nullable()}).strict(),AD=I.discriminatedUnion("action",[I.object({action:I.literal("create"),rewardId:I.uuid(),revision:I.number().int().nonnegative(),input:Pc}).strict(),I.object({action:I.literal("remove"),rewardId:I.uuid(),revision:I.number().int().nonnegative(),codeId:I.uuid()}).strict()]);import{z as _}from"zod";import{z as U}from"zod";var dn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Di=e=>new Set(e).size===e.length,Oc=U.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Mv=U.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Ni=U.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"))),Bv=U.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),mf=U.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),OD=["isOn","isOff","getFeatureValue","evalFeature","eval_feature"],ff=U.strictObject({id:U.uuid(),repo:Mv,platform:U.enum(["github","gitlab","bitbucket"]),branches:U.array(Ni).min(1).max(4).refine(Di),workflow:U.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:U.array(U.uuid()).min(1).max(4).refine(Di),include:U.array(mf).min(1).max(16),exclude:U.array(mf).max(16),methods:U.array(U.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Di),maxAgeHours:U.number().int().min(1).max(720)}),hf=ff.extend({revision:U.number().int().positive()}),CD=U.strictObject({repository:ff,expectedRevision:U.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),gf=U.strictObject({repositoryId:U.uuid(),branch:Ni}),Lv=U.array(Oc).max(dn.keys).refine(Di),bf=U.strictObject({repository:hf.omit({keyIds:!0}),branch:Ni,keys:Lv,keySetHash:U.string().regex(/^[a-f0-9]{64}$/)}),qv=U.strictObject({filePath:Bv,startingLineNumber:U.number().int().min(1).max(1e7)}),Cc=U.strictObject({protocol:U.literal(1),repositoryId:U.uuid(),branch:Ni,workflow:U.string().max(200),configurationRevision:U.number().int().positive(),keySetHash:U.string().regex(/^[a-f0-9]{64}$/),commit:U.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:U.uuid(),runNumber:U.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:U.number().int().min(1).max(1e4),scannerVersion:U.literal("1"),scannedAt:U.iso.datetime({offset:!0}),coverage:U.strictObject({complete:U.literal(!0),files:U.number().int().min(0).max(dn.files),sourceBytes:U.number().int().min(0).max(dn.sourceBytes),unresolvedCalls:U.number().int().min(0).max(1e6),unsupportedFiles:U.number().int().min(0).max(dn.files)}),features:U.array(U.strictObject({key:Oc,refs:U.array(qv).max(dn.referencesPerKey)})).max(dn.keys)}).superRefine((e,t)=>{Di(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)>dn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Ec=U.strictObject({scanId:U.uuid(),commit:U.string(),receivedAt:U.string(),references:U.number().int().nonnegative(),removedReferences:U.number().int().nonnegative()}),Vv=Ec.extend({repositoryId:U.uuid(),branch:Ni,workflow:U.string(),digest:U.string(),configurationRevision:U.number().int().positive(),runNumber:U.number().int().positive(),runAttempt:U.number().int().positive(),scannedAt:U.string(),keySetHash:U.string(),coverage:Cc.shape.coverage}),Gv=U.strictObject({repositories:U.array(hf).max(dn.repositories),scans:U.array(Vv).max(dn.repositories*dn.branches)}),$v=U.strictObject({key:Oc,references:U.number().int().nonnegative(),coveredTargets:U.number().int().nonnegative(),expiredTargets:U.number().int().nonnegative(),uncertainTargets:U.number().int().nonnegative()}),ED=U.strictObject({available:U.boolean().default(!0),settings:Gv,expectedTargets:U.number().int().min(0).max(80),features:U.array($v).max(2001),truncated:U.boolean()});import{z as Ht}from"zod";var Tc=Ht.strictObject({customerId:Ht.uuid(),eventId:Ht.string().trim().min(1).max(200),grantId:Ht.uuid(),productVersionId:Ht.uuid(),subscriptionId:Ht.string().trim().min(1).max(255),occurredAt:Ht.iso.datetime({offset:!0})}),_f=Tc.extend({id:Ht.uuid(),couponId:Ht.uuid(),status:Ht.literal("redeemed"),source:Ht.literal("merchant"),recordedAt:Ht.iso.datetime({offset:!0})});import{z as Q}from"zod";var Rc=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()}),Kv=Rc.extend({id:Q.string().min(1).max(255),created_at:Q.number().nullable()}),yf=Q.strictObject({items:Q.array(Kv).max(50),nextCursor:Q.string().nullable()}),ND=Q.discriminatedUnion("action",[Q.strictObject({action:Q.literal("create"),requestId:Q.uuid(),values:Rc}),Q.strictObject({action:Q.literal("update"),id:Q.string().min(1).max(255),values:Rc}),Q.strictObject({action:Q.literal("delete"),id:Q.string().min(1).max(255)})]),Sf=Q.discriminatedUnion("action",[Q.strictObject({action:Q.literal("create"),requestId:Q.uuid(),params:xr}),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:js})]),jc=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()}),vf=jc.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)}),Fi=Q.strictObject({taskId:Q.uuid(),status:Q.enum(["ready","running","done","dead"]),invoice:jc.nullable(),errorCode:Q.string().nullable()}),xf=Q.strictObject({items:Q.array(jc).max(50),nextCursor:Q.uuid().nullable(),operations:Q.array(Fi).max(50),operationsLimited:Q.boolean()}),FD=jn;var Wv=_.enum(["customers:read","customers:write","entitlements:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","code-references:read","code-references:write"]),If={scope:ke,permissions:_.array(Wv),expiresAt:_.iso.datetime().nullable()},IN=_.discriminatedUnion("kind",[_.object({...If,kind:_.literal("server"),keyId:_.string().min(1)}),_.object({...If,kind:_.literal("customer"),customerId:_.string().min(1),identityKind:_.enum(["identified","guest"]),expiresAt:_.iso.datetime()})]),D=_.object({requestId:_.uuid(),scope:ke}).strict(),Hv=_m.safeExtend({fingerprint:Ho.optional()}).strict(),Qv=D.extend({customer:jr,created:_.boolean()}),Zv=_.enum(["unassigned","unknown","scheduled","active","expired"]),AN=_.object({customerId:_.string().min(1),evaluatedAt:_.iso.datetime(),status:Zv,validity:fs.nullable(),planVersion:dd.nullable(),holdings:_.array(_.object({id:_.uuid(),planVersionId:_.uuid(),source:_.enum(["subscription","assignment","license","license_pool","entity_pool"])})).optional(),entitlements:_.array(_.object({featureId:_.string(),featureKey:_.string(),featureName:_.string(),type:_.enum(["boolean","metered"]),allowance:_.number().int().nonnegative().nullable(),used:_.number().finite().nonnegative(),remaining:_.number().finite().nonnegative().nullable(),allowed:_.boolean(),sources:_.array(_.object({holdingId:_.uuid(),planVersionId:_.uuid(),group:_.string(),kind:_.enum(["main","addon"]),allowance:_.number().nullable()})).optional()}))});function Af(){return D.extend({offer:fi.nullable(),reason:So.nullable()})}var k={listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:_.strictObject({cursor:_.uuid().optional()}),response:D.extend({templates:yf})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),params:xr}),response:D.extend({preview:ks})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),requestId:_.uuid(),params:xr}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:D.extend({operation:Fi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),command:Sf}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:D.extend({operation:Fi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),taskId:_.uuid()}),response:D.extend({operation:Fi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),cursor:_.uuid().optional()}),response:D.extend({invoices:xf})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),invoiceId:_.uuid()}),response:D.extend({invoice:vf})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:gf,response:D.extend({config:bf})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Cc,response:D.extend({receipt:Ec})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:_.strictObject({}),response:D.extend({payload:Ws})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:im,response:D.merge(om)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:am,response:D.merge(sm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid(),sourceId:_.uuid()}),response:D.extend({balance:Lm})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:Bm}),response:D.extend({balance:xc})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:_.strictObject({internal_feature_id:_.uuid(),customerId:_.uuid().optional(),entityId:_.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:D.extend({internal_feature_id:_.uuid(),config:ss,model_markups:bo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid(),query:ku}),response:D.extend({usage:Na})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:Du}),response:D.extend({usage:Na})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:Zd}),response:D.extend({grant:Ps})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Yd,response:D.extend({grants:Jd})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:_.union(Zp.options.map(e=>e.extend({customerId:_.uuid().optional(),customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/).optional()}))),response:D.extend({operation:Yp})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Mp.extend({customerId:_.uuid().optional()}),response:D.extend({setup:Ms})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Bp.extend({customerId:_.uuid().optional()}),response:D.extend({setup:Ms})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Np.safeExtend({customerId:_.uuid()}),response:D.extend({batch:wi})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Oo.extend({customerId:_.uuid()}),response:D.extend({batch:wi})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Oo.extend({customerId:_.uuid()}),response:D.extend({batch:wi})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Oo.extend({customerId:_.uuid()}),response:D.extend({batch:wi})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:_.discriminatedUnion("action",[Co.options[0].extend({customerId:_.uuid()}),Co.options[1].extend({customerId:_.uuid()}),Co.options[2].extend({customerId:_.uuid()})]),response:D.extend({trial:Us})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Fp.extend({customerId:_.uuid()}),response:D.extend({trial:Us})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Ro,response:D.extend({subscriptions:Wp})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Ro,response:D.extend({purchases:Hp})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Gp,response:D.extend({conflicts:Qp})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:$p,response:D.extend({resolution:Kp})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:qp,response:D.extend({verification:Vp})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Pp.safeExtend({...vr,customerId:_.uuid().optional()}),response:D.extend({quote:Ii})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:er.extend({customerId:_.uuid().optional(),intent:_.enum(["confirm","cancel"]).optional()}),response:D.extend({operation:Ir})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:er.extend({customerId:_.uuid().optional()}),response:D.extend({operation:Ir})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Ep.safeExtend({customerId:_.uuid().optional()}),response:D.extend({quote:Rp})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:er.extend({customerId:_.uuid().optional(),intent:_.enum(["confirm","cancel"]).optional()}),response:D.extend({operation:Ns})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:er.extend({customerId:_.uuid().optional()}),response:D.extend({operation:Ns})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:jp.safeExtend({customerId:_.uuid()}),response:D.extend({quote:Dp})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:er.extend({customerId:_.uuid()}),response:D.extend({operation:Po})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:er.extend({customerId:_.uuid()}),response:D.extend({operation:Po})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Td,response:D.extend({controls:_s})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Id,response:D.extend({prepared:wd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Pd,response:D.extend({authorization:vo})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Dd,response:D.extend({coupons:Nd})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Od,response:D.extend({authorization:vo})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:jd,response:D.extend({invoices:kd})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Rd,response:D.extend({invoice:gi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:_.object({customerId:_.uuid(),command:Ed}).strict(),response:D.extend({controls:_s})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:_.object({customerId:_.uuid(),command:qm}).strict(),response:D.extend({entity:Vm})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid().nullable(),query:Qm}),response:D.extend({analytics:Zm})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:_.object({customerId:_.uuid().nullable(),query:dr}).strict(),response:D.extend({analytics:Wm})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Ym,response:D.extend({batchId:_.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Jm,response:D.extend({batch:Xm})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Bu.extend({customerId:_.string().min(1).optional()}),response:D.extend({check:oi})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Fm,response:D.extend({paywall:Ur})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:_.strictObject({...vr,selector:em,customerId:_.string().min(1).optional(),commerce:to,requirement:hr.optional()}),response:D.extend({offering:Do,candidates:_.array(Lu).max(20),availability:_.array(_.strictObject({productVersionId:_.uuid(),available:_.boolean(),reason:_.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:oi.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),entityId:_.uuid().optional()}).strict(),response:D.extend({holdings:Nu})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),query:Fu}).strict(),response:D.extend({ledger:Uu})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Xd.extend({customerId:_.uuid().optional()}),response:D.extend({detail:zd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Os.safeExtend({customerId:_.uuid().optional()}),response:D.extend({statement:ep})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),command:ri.options[0]}).strict(),response:D.extend({quote:ju})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:_.strictObject({customerId:_.uuid(),command:_.union([_.strictObject({eventName:_.string().min(1),quantity:_e.optional(),properties:Xt.optional(),entityId:_.uuid().optional(),idempotencyKey:_.string().min(1).max(120)}),_.strictObject({internal_feature_id:_.uuid(),quantity:_e.optional(),properties:Xt.optional(),entityId:_.uuid().optional(),idempotencyKey:_.string().min(1).max(120)})])}),response:D.extend({receipts:_.array(ii).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:_.object({customerId:_.uuid(),command:ri.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:D.extend({receipt:ii})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:cf,response:D.extend({redemption:sf})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:df,response:D.extend({referralCode:pf})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:uf,response:D.extend({checkout:lf})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:rp,response:D.extend({seats:Ts})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:ip,response:D.extend({seats:Ts})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:Hv,response:Qv},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:rc,response:D.extend({customer:jr})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:vm,response:D.extend(xm.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Sm,response:D.extend(ym.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:_.object({customerId:_.uuid()}).strict(),response:D.extend({customerToken:_.string().min(1),expiresAt:_.iso.datetime(),sessionId:_.uuid()})},renewSession:{method:"POST",path:"customer-sessions/renew",permission:"sessions:create",audience:"server",request:_.strictObject({customerId:_.uuid(),customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/)}),response:D.extend({customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:_.uuid(),expiresAt:_.iso.datetime()})},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:_.strictObject({customerId:_.uuid(),sessionId:_.uuid().optional()}),response:D.extend({revoked:_.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:_.strictObject({guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ho.optional()}),response:D.extend({customerId:_.uuid(),guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:_.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:_.strictObject({guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:D.extend({customerId:_.uuid(),customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:_.uuid(),expiresAt:_.iso.datetime()})},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:_.strictObject({guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:_.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:_.uuid()}),response:D.extend({customer:jr,switched:_.boolean(),replayed:_.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:_.strictObject({code:_.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:_.uuid()}),response:Af()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:_.object({}).strict(),response:D.extend({offers:_.array(fi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:_.object({customerId:_.string().min(1).max(255).optional(),couponId:_.uuid(),...vr,requestId:_.uuid(),couponContentDigest:_.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Af()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:Tc,response:D.extend({receipt:_f})}},wN={listInvoiceTemplates:k.listInvoiceTemplates,previewInvoice:k.previewInvoice,createInvoice:k.createInvoice,manageInvoice:k.manageInvoice,readInvoiceOperation:k.readInvoiceOperation,listInvoices:k.listInvoices,getInvoice:k.getInvoice,getCodeReferenceConfig:k.getCodeReferenceConfig,submitCodeReferences:k.submitCodeReferences,getFeatures:k.getFeatures,evaluateFeatures:k.evaluateFeatures,trackEvents:k.trackEvents,setupPayment:k.setupPayment,readPaymentSetup:k.readPaymentSetup,previewSubscriptionBatch:k.previewSubscriptionBatch,confirmSubscriptionBatch:k.confirmSubscriptionBatch,readSubscriptionBatch:k.readSubscriptionBatch,abandonSubscriptionBatch:k.abandonSubscriptionBatch,manageSubscriptionTrial:k.manageSubscriptionTrial,readSubscriptionTrial:k.readSubscriptionTrial,listSubscriptions:k.listSubscriptions,listPurchases:k.listPurchases,listSubscriptionConflicts:k.listSubscriptionConflicts,retrySubscriptionConflict:k.retrySubscriptionConflict,readAiPricing:k.readAiPricing,readUsage:k.readUsage,setUsage:k.setUsage,previewRefund:k.previewRefund,refund:k.refund,readRefund:k.readRefund,previewUpdate:k.previewUpdate,update:k.update,readSubscriptionUpdate:k.readSubscriptionUpdate,restoreNativePurchase:k.restoreNativePurchase,verifySubscriptions:k.verifySubscriptions,previewAttach:k.previewAttach,attach:k.attach,readSubscriptionOperation:k.readSubscriptionOperation,manageBalanceGrant:k.manageBalanceGrant,readBalanceSource:k.readBalanceSource,adjustBalance:k.adjustBalance,listBalanceGrants:k.listBalanceGrants,readBillingControls:k.readBillingControls,prepareBillingAuthorization:k.prepareBillingAuthorization,confirmBillingAuthorization:k.confirmBillingAuthorization,setBillingCoupons:k.setBillingCoupons,revokeBillingAuthorization:k.revokeBillingAuthorization,listBillingInvoices:k.listBillingInvoices,confirmBillingAdjustment:k.confirmBillingAdjustment,manageBillingLimits:k.manageBillingLimits,createCustomer:k.createCustomer,getCustomer:k.getCustomer,listCustomers:k.listCustomers,updateCustomer:k.updateCustomer,createSession:k.createSession,renewSession:k.renewSession,revokeSessions:k.revokeSessions,createGuestCustomer:k.createGuestCustomer,resumeGuestSession:k.resumeGuestSession,claimGuestCustomer:k.claimGuestCustomer,checkEntitlement:k.checkEntitlement,resolveOffering:k.resolveOffering,resolvePaywall:k.resolvePaywall,readHoldings:k.readHoldings,readLedger:k.readLedger,readBillingInvoice:k.readBillingInvoice,readCreditStatement:k.readCreditStatement,quoteBalance:k.quoteBalance,trackUsage:k.trackUsage,mutateBalance:k.mutateBalance,manageUsageEntity:k.manageUsageEntity,readUsageAnalytics:k.readUsageAnalytics,readCreditAnalytics:k.readCreditAnalytics,submitUsageBatch:k.submitUsageBatch,readUsageBatch:k.readUsageBatch,listOffers:k.listOffers,grantOffer:k.grantOffer,recordCouponRedemption:k.recordCouponRedemption,redeemCoupon:k.redeemCoupon,redeemReward:k.redeemReward,createReferralCode:k.createReferralCode,claimRewardProduct:k.claimRewardProduct,readSeats:k.readSeats,manageSeat:k.manageSeat};function wf(e,t){if(t!=="en"&&t!=="zh-CN")throw new Error("Unsupported blank content language");let n=t==="en"?{popup:"popup",paywall:"paywall",onboarding:"funnel",page:"page"}:{popup:"\u5F39\u7A97",paywall:"\u4ED8\u8D39\u5899",onboarding:"\u5F15\u5BFC\u6D41\u7A0B",page:"\u9875\u9762"};return{kind:"screen",schemaVersion:4,theme:{primary:"#2C3C96",background:"#FFFFFF",text:"#1B1D24",radius:"md",font:"system"},name:t==="en"?`Untitled ${n[e]}`:`\u672A\u547D\u540D${n[e]}`,surface:e,presentation:e==="popup"?{type:"modal",size:"md"}:{type:"fullscreen"},pages:[{id:"main",name:t==="en"?e==="onboarding"?"Start":"Main page":e==="onboarding"?"\u5F00\u59CB":"\u4E3B\u9875\u9762",root:{type:"stack",id:"root",direction:"vertical",align:"stretch",justify:"start",name:t==="en"?"Canvas":"\u753B\u5E03",style:e==="popup"?{gap:16,padding:{top:32,right:28,bottom:28,left:28}}:{gap:16,padding:{top:24,right:24,bottom:24,left:24}},children:[]}}],strings:{defaultLocale:t,locales:{[t]:{}}},actions:[]}}import{z as fe}from"zod";var Ui=fe.number().int().min(0).max(1e4),jN=fe.strictObject({couponId:fe.uuid(),couponRevision:fe.number().int().nonnegative(),savedGroupId:fe.uuid(),savedGroupRevision:fe.number().int().nonnegative(),savedGroupName:fe.string().min(1).max(128),count:Ui,snapshotHash:fe.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:fe.iso.datetime({offset:!0})}),Yv=fe.strictObject({id:fe.uuid(),couponId:fe.uuid(),couponName:fe.string().min(1).max(80),savedGroupId:fe.uuid(),savedGroupName:fe.string().min(1).max(128),savedGroupRevision:fe.number().int().nonnegative(),status:fe.enum(["pending","running","completed"]),total:Ui,issued:Ui,skipped:Ui,remaining:Ui,createdAt:fe.iso.datetime({offset:!0}),completedAt:fe.iso.datetime({offset:!0}).nullable()}).refine(e=>e.total>0&&e.total===e.issued+e.skipped+e.remaining&&e.status==="completed"==(e.completedAt!==null)&&(e.status!=="completed"||e.remaining===0)),Jv=fe.strictObject({id:fe.uuid(),customerId:fe.uuid(),customerName:fe.string().max(255),position:fe.number().int().min(1).max(1e4),status:fe.enum(["pending","issued","skipped"]),grantId:fe.uuid().nullable(),reason:So.nullable()}).refine(e=>e.status==="issued"==(e.grantId!==null)&&e.status==="skipped"==(e.reason!==null)),kN=fe.strictObject({batch:Yv,recipients:fe.array(Jv).max(50),nextPosition:fe.number().int().min(1).max(1e4).nullable()}),DN=fe.discriminatedUnion("action",[fe.strictObject({action:fe.literal("create"),requestId:fe.uuid(),couponId:fe.uuid(),couponRevision:fe.number().int().nonnegative(),savedGroupId:fe.uuid(),savedGroupRevision:fe.number().int().nonnegative(),snapshotHash:fe.string().regex(/^[a-f0-9]{64}$/)}),fe.strictObject({action:fe.literal("process"),batchId:fe.uuid()})]);import{z as L}from"zod";var St=L.number().int().min(0),Mi=L.iso.datetime({offset:!0}),na=L.strictObject({internalId:L.uuid(),version:L.number().int().positive()}),Pf=L.enum(["subscription_change_required","unsupported_operation_input"]),Xv=L.enum([...Pf.options,"internal_error"]),UN=L.strictObject({productId:L.string().min(1),productName:L.string(),from:na,to:na,noBillingChanges:L.boolean(),counts:L.strictObject({customers:St,movable:St,blocked:St,unsupported:St,canceled:St,custom:St}),rows:L.array(L.strictObject({customerId:L.uuid(),customerKey:L.string().nullable(),name:L.string().nullable(),email:L.string().nullable(),holdings:L.number().int().positive(),outcome:L.enum(["move","blocked","unsupported"]),reason:Pf.nullable()})).max(50),nextCursor:L.uuid().nullable()}),zv=L.enum(["queued","running","succeeded","no_changes","failed","canceled"]),Of=L.enum(["running","succeeded","skipped","failed"]),Cf=L.strictObject({internalId:L.uuid(),id:L.string().min(1),productId:L.string().min(1),productName:L.string(),from:na,to:na,noBillingChanges:L.boolean(),retryFailed:L.boolean(),step:L.enum(["queued","received","get_customers","migrate_customers","finished","failed"]),snapshot:L.strictObject({total_customers:St,canceled_customers:St,custom_customers:St,migration_customers:St}),createdAt:Mi,run:L.strictObject({id:L.uuid(),status:zv,errorMessage:L.string().nullable(),createdAt:Mi,startedAt:Mi.nullable(),finishedAt:Mi.nullable()}).nullable(),totals:L.strictObject({succeeded:St,skipped:St,failed:St,running:St,blocked:St,remaining:St})}),e0=L.strictObject({customerId:L.uuid(),customerKey:L.string().nullable(),name:L.string().nullable(),email:L.string().nullable(),status:Of,skipReason:L.enum(["no_updates_needed","ineligible"]).nullable(),updatedAt:Mi,error:L.strictObject({code:Xv,message:L.string().nullable()}).nullable()}),MN=L.strictObject({migration:Cf,items:L.array(e0).max(50),nextCursor:L.uuid().nullable()}),BN=L.array(Cf).max(20),LN=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),requestId:L.uuid(),fromInternalId:L.uuid(),toInternalId:L.uuid()}),L.strictObject({action:L.enum(["process","retry","cancel"]),migrationId:L.uuid()})]),qN=L.discriminatedUnion("action",[L.strictObject({action:L.literal("preview"),from:L.uuid(),to:L.uuid(),after:L.uuid().optional()}),L.strictObject({action:L.literal("read"),migrationId:L.uuid(),status:Of.optional(),after:L.uuid().optional()}),L.strictObject({action:L.literal("list"),productId:L.string().min(1).max(120)})]);import{z as dt}from"zod";var kc=dt.iso.datetime({offset:!0}),Ef=dt.strictObject({internalId:dt.uuid(),productId:dt.string().min(1),name:dt.string(),version:dt.number().int().positive()}),t0=dt.strictObject({id:dt.uuid(),status:dt.literal("scheduled"),effectiveAt:kc,createdAt:kc,entityId:dt.string().nullable(),to:Ef,from:Ef.extend({customerProductId:dt.uuid(),status:dt.enum(["active","past_due","trialing"]),endsAt:kc.nullable()}).nullable(),scheduleId:dt.uuid().nullable(),providerManaged:dt.boolean()}),$N=dt.array(t0).max(100),KN=dt.strictObject({customerProductId:dt.uuid()});import{z as Bi}from"zod";var n0=Bi.url().refine(e=>new URL(e).protocol==="https:"),QN=Bi.strictObject({requestId:Bi.uuid()}),ZN=Bi.strictObject({url:n0,createdAt:Bi.iso.datetime()});import{z as We}from"zod";var r0=We.union([Qu,We.string().max(200).regex(/^\/template-covers\/[a-z0-9-]+-[a-f0-9]{16}\.webp$/)]),Tf=We.object({id:We.uuid(),key:We.string().nullable(),label:We.string().min(1).max(80),description:We.string().max(300),category:We.string().min(1).max(40),tags:We.array(We.string().max(30)).max(10),surface:Zu,source:We.enum(["official","private"]),cover_image:r0.nullable().default(null),document:nt,revision:We.number().int().positive(),archived_at:We.string().nullable(),created_at:We.string()}).strict(),zN=We.object({projectId:We.uuid(),environmentId:We.uuid(),label:We.string().trim().min(1).max(80),description:We.string().trim().max(300),category:We.string().trim().min(1).max(40),document:nt}).strict(),eF=We.object({projectId:We.uuid(),environmentId:We.uuid(),id:We.uuid(),revision:We.number().int().positive()}).strict();import{z as Dc}from"zod";var Li=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Nc(e,t,n){let r={},i,o,a,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>Xi(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new Li("Required GB Feature is unavailable");i=ti(e.featureKey,t),a=i.value,Object.assign(r,nr(e,{value:a})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new Li("Required GB Experiment is unavailable");if(o=Ou(u,t),a=o.value,s=o.inExperiment&&!o.passthrough&&typeof a=="string"?a:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new Li("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:ti(e.configuration.featureKey,t).value;a={type:"offering_version",id:Dc.uuid().parse(u)},Object.assign(r,nr(e,{value:a})),c=e.next;break}case"coupon":case"coupons":a=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,nr(e,{value:a})),c=e.next;break}return{port:s,target:c,projections:r,...a===void 0?{}:{value:a},...i?{feature:i}:{},...o?{experiment:o}:{}}}function Rf(e,t,n){Dc.uuid().parse(e),Dc.number().int().nonnegative().parse(t);let r=Yi(Ji(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 ot}from"zod";var jf=ot.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),pF=ot.strictObject({operation:ot.literal("resolve_screen"),funnelId:ot.uuid(),versionId:ot.uuid(),screenId:jf,locale:bn,customerId:ot.uuid().optional()}),mF=ot.strictObject({scope:ke,funnelId:ot.uuid(),versionId:ot.uuid(),screenId:jf,locale:bn,coupons:ot.record(ot.uuid(),ot.strictObject({available:ot.boolean(),offer:ot.strictObject({id:ot.uuid(),expiresAt:ot.iso.datetime()}).nullable()})),couponDigests:ot.record(ot.uuid(),kn)});import{z as Se}from"zod";var i0=Se.strictObject({id:Se.uuid(),projectId:Se.uuid(),environmentId:Se.uuid(),name:Se.string().min(1).max(80),revision:Se.number().int().nonnegative(),evaluationMode:Qs,evaluationRevision:Se.number().int().nonnegative(),state:Se.enum(["active","paused","archived"]),publishedVersionId:Se.uuid().nullable(),updatedAt:Se.iso.datetime({offset:!0}),draft:Mt}),vF=Se.strictObject({rows:Se.array(i0).max(200),nextCursor:Se.uuid().nullable()}),xF=Se.discriminatedUnion("action",[Se.strictObject({action:Se.literal("setEvaluationMode"),id:Se.uuid(),revision:Se.number().int().nonnegative(),evaluationMode:Qs}),Se.strictObject({action:Se.literal("create"),requestId:Se.uuid(),name:Se.string().trim().min(1).max(80),document:Mt}),Se.strictObject({action:Se.literal("save"),id:Se.uuid(),revision:Se.number().int().nonnegative(),name:Se.string().trim().min(1).max(80),document:Mt}),Se.strictObject({action:Se.literal("terminateRun"),id:Se.uuid(),revision:Se.number().int().nonnegative(),runId:Se.uuid()}),Se.strictObject({action:Se.enum(["publish","archive","pause","activate","stop"]),id:Se.uuid(),revision:Se.number().int().nonnegative()})]).superRefine((e,t)=>{(e.action==="create"||e.action==="save")&&_t(e.document)>Qe.documentBytes&&t.addIssue({code:"custom",path:["document"],message:"Funnel document exceeds its byte budget"})});function IF(e){let t=e==="en",n=wf("popup",e);n.name=t?"Welcome":"\u6B22\u8FCE";let r=n.pages[0];if(!r)throw new Error("Blank screen requires a page");return r.root.children=[{id:"heading",type:"text",text:"heading",variant:"title",style:{text:{align:"center"}}},{id:"body",type:"text",text:"body",variant:"body",style:{text:{align:"center"}}},{id:"continue_button",type:"button",label:"continue",variant:"primary",action:"continue",style:{width:"fill",margin:{top:8,right:0,bottom:0,left:0}}}],n.actions=[{id:"continue",type:"event",event:"continue",properties:{},close:!1}],n.strings.locales[e]={heading:t?"Welcome":"\u6B22\u8FCE",body:t?"Tell people what this step is for and what happens next.":"\u544A\u8BC9\u7528\u6237\u8FD9\u4E00\u6B65\u7684\u4F5C\u7528\uFF0C\u4EE5\u53CA\u63A5\u4E0B\u6765\u4F1A\u53D1\u751F\u4EC0\u4E48\u3002",continue:t?"Continue":"\u7EE7\u7EED"},bc.parse({schemaVersion:4,references:{},variables:{},outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",inputs:[],screens:[{id:"welcome",type:"owned",document:n}],graph:{version:5,entry:"entry",nodes:[{id:"entry",name:t?"Entry":"\u5165\u53E3",type:"entry",next:"welcome"},{id:"welcome",name:t?"Welcome":"\u6B22\u8FCE",type:"screen",screenId:"welcome",presentation:{type:"modal",size:"md"},outputs:{continue:"done"}},{id:"done",name:t?"Completed":"\u5B8C\u6210",type:"end",outcome:"completed",output:{type:"literal",value:null}}]}})}import{z as N}from"zod";var Nn=N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Fc=N.enum(["running","waiting","completed","closed","ineligible","failed"]),o0=N.discriminatedUnion("type",[Bo,Zs,N.strictObject({type:N.literal("wait"),receiptId:N.uuid(),kind:N.enum(["timer","event","operation"]),deadline:N.iso.datetime({offset:!0}).nullable(),eventName:Nn.optional()}),N.strictObject({type:N.literal("open_url"),receiptId:N.uuid(),url:ac,openIn:sc}),N.strictObject({type:N.literal("event"),receiptId:N.uuid(),event:Nn})]),a0=N.strictObject({type:N.literal("funnel"),id:N.uuid(),versionId:N.uuid()}),s0={id:Nn,presentation:en,outputs:N.array(Nn).max(250),inputs:Ma,values:N.record(N.string(),ge).optional(),offeringKey:Ye.optional(),capabilities:gr,customerData:Wu,dataCursors:N.record(Nn,no.nullable())},c0=N.strictObject({...s0,content:N.strictObject({type:N.literal("document"),document:nt})}),qi=N.strictObject({id:N.uuid(),source:a0,revision:N.number().int().nonnegative(),visit:N.number().int().nonnegative(),nodeId:Nn,nodeType:N.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Fc,stopped:N.boolean(),canBack:N.boolean(),recoveryRestricted:N.boolean().optional(),authenticated:N.boolean(),locale:N.string().min(1).max(35),answers:Qn,parameters:$t,variables:N.record(N.string(),ge),output:ge.nullable(),screen:c0.nullable(),paywall:N.strictObject({receiptId:N.uuid(),resolution:N.union([ki,Ur]),quote:Ii.nullable(),operation:Ir.nullable(),purchaseRequestId:N.uuid().nullable(),selectionGeneration:N.number().int().nonnegative().optional(),canReselect:N.boolean().optional()}).nullable(),instruction:o0.nullable(),pendingRequest:N.strictObject({requestId:N.uuid(),authenticationRequired:N.boolean()}).nullable(),runExpiresAt:N.iso.datetime({offset:!0}),credentialExpiresAt:N.iso.datetime({offset:!0}).nullable()}),Uc=N.strictObject({scope:ke,run:qi,settlement:N.strictObject({requestId:N.uuid(),state:N.enum(["pending","unknown","settled"]),operationId:N.uuid().nullable(),receiptId:N.uuid().nullable().optional()}).optional(),purchase:N.strictObject({receiptId:N.uuid(),quote:Ii.nullable(),operation:Ir.nullable(),canReselect:N.boolean().optional()}).optional(),review:N.strictObject({activeOperationId:N.uuid().nullable(),pages:N.array(N.strictObject({receiptId:N.uuid(),nodeId:Nn,visit:N.number().int().nonnegative()})).max(100),page:N.strictObject({receiptId:N.uuid(),nodeId:Nn,visit:N.number().int().nonnegative(),document:nt,answers:Qn,inputs:Ma,values:N.record(N.string(),ge).optional()}).nullable(),coupons:N.array(N.strictObject({grantId:N.uuid(),status:N.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:N.string().nullable()})).max(100),purchases:N.array(N.strictObject({receiptId:N.uuid(),operationId:N.uuid(),status:N.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:N.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:N.uuid().optional()}),Mc=Uc.extend({run:qi.extend({paywall:qi.shape.paywall.unwrap().extend({resolution:Ur}).nullable()})});function MF(e){return Mc.parse({...e,run:{...e.run,paywall:e.run.paywall?{...e.run.paywall,resolution:"document"in e.run.paywall.resolution?Um(e.run.paywall.resolution):e.run.paywall.resolution}:null}})}var BF="X-Indiana-Server-Key";import{z as At}from"zod";import{z as ra}from"zod";var GF=ra.strictObject({operation:ra.literal("renew_run"),runId:ra.uuid(),customerId:ra.uuid()}),kf=Uc.refine(e=>!!e.runToken,"Renewal returns a credential"),Df=Mc.refine(e=>!!e.runToken,"Renewal returns a credential");var JF=At.discriminatedUnion("operation",[At.strictObject({operation:At.literal("campaign_decide"),...ic}).refine(or,ar),At.strictObject({operation:At.literal("campaign_start"),funnelId:At.uuid(),requestId:At.uuid(),customer:Tr,customerData:Rr.optional(),locale:At.string().min(1).max(35),parameters:$t,cooldownSeconds:At.number().int().min(1).max(2592e3)}).refine(or,ar)]),u0=At.union([At.strictObject({scope:ke,suppressed:At.literal(!0),reason:At.enum(["frequency","in_progress"]),retryAt:At.iso.datetime({offset:!0})}),kf]),XF=At.union([u0.options[0],Df]);import{z as ve}from"zod";var Br=ve.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ff=ve.strictObject({entry:Br,nodes:ve.array(ve.strictObject({id:Br,type:ve.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:ve.record(ve.string(),Br),writes:ve.record(Ye,Ye),resources:ve.strictObject({screenId:Br.optional(),paywallVersionId:ve.uuid().optional(),couponId:ve.uuid().optional(),couponIds:ve.array(ve.uuid()).max(20).optional(),experimentId:ve.uuid().optional(),featureKey:ve.string().optional(),offeringVersionId:ve.uuid().optional()})})).min(1).max(500)}),Nf={scope:ke,funnelId:ve.uuid(),versionId:ve.uuid(),evaluationRevision:ve.number().int().nonnegative(),expiresAt:ve.iso.datetime({offset:!0}).nullable(),topology:Ff},Lr=ve.discriminatedUnion("evaluationMode",[ve.strictObject({...Nf,evaluationMode:ve.literal("local"),growth:on,conditions:ve.record(Br,ve.array(ve.strictObject({condition:wn,port:ve.string()})))}),ve.strictObject({...Nf,evaluationMode:ve.literal("remote")})]),l0=Lr.options[0].extend({evaluation:ve.strictObject({maxTransitions:ve.number().int().min(1).max(1e4),variables:ve.record(Ye,Or),outputSchema:Pr,terminals:ve.record(Br,ve.strictObject({outcome:ve.enum(["completed","closed","ineligible","failed"]),output:Ti.nullable()}))})});function d0(e){return Ff.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 o=e.screens.find(a=>a.id===t.screenId);o?.type==="paywall"&&(r.paywallVersionId=o.paywallVersionId)}break;case"condition":t.cases.forEach((o,a)=>{n[`case:${a}`]=o.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 o of["success","cancel","unavailable","failure"])n[o]=t[o];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=ve.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 p0(e){let t=ln.parse(e.document),n=e.evaluationMode==="local"?on.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:d0(t)};return Lr.parse(e.evaluationMode==="remote"?r:{...r,growth:ea(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((o,a)=>({condition:o.condition,port:`case:${a}`}))]))})}function c2(e){let t=p0(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=ln.parse(e.document);return l0.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 B}from"zod";var Mf={commands:Qe.flowNodes*4,receipts:Qe.flowNodes*2,requestBytes:Qe.documentBytes+2e6},qr=B.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Uf={requestId:B.uuid(),nodeId:qr,visit:B.number().int().nonnegative(),revision:B.number().int().nonnegative()},m0=B.union([Ri.options[3].omit({customerToken:!0}),Ri.options[4].omit({customerToken:!0}),Ri.options[5].omit({customerToken:!0}),Ri.options[6].omit({customerToken:!0}),B.strictObject({operation:B.literal("wait"),...Uf,result:B.enum(["elapsed","received","timeout"])}),B.strictObject({operation:B.literal("simulate"),...Uf,outcome:B.enum(["success","cancel","failure","unavailable"])})]),Bc=B.enum(["success","cancel","failure","unavailable","pending"]),Lc=B.strictObject({seed:B.uuid(),now:B.iso.datetime({offset:!0}),locale:B.string().min(2).max(35),currency:re,parameters:$t,attributes:B.record(B.string(),Ci).refine(e=>Object.keys(e).length<=100),authenticated:B.boolean(),holdings:B.enum(["sample","empty"]),results:B.record(B.string(),ge).optional(),outcomes:B.record(qr,Bc),variants:B.record(qr,B.string().min(1).max(128).nullable())}),qc=B.strictObject({schemaVersion:B.literal(1),growth:on,paywalls:B.record(B.uuid(),tm),offerings:B.record(B.uuid(),Do),surfaces:B.record(qr,ge)}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=1e6,"Preview dependencies exceed their byte budget"),f0=B.array(B.strictObject({command:m0,authenticated:B.boolean(),outcome:Bc})).max(Mf.commands),h0=B.discriminatedUnion("type",[B.strictObject({type:B.literal("draft"),document:Mt}),B.strictObject({type:B.literal("snapshot"),id:B.uuid()})]),v2=B.strictObject({previewId:B.uuid(),source:h0,scenario:Lc,journal:f0,dependencySnapshot:qc.optional()}),x2=B.strictObject({mode:B.literal("simulation"),run:qi,dependencySnapshot:qc,traceTruncated:B.boolean(),trace:B.array(B.strictObject({nodeId:qr,visit:B.number().int().nonnegative(),type:B.enum(["entered","shown","assigned","feature_evaluated","action","closed","wait_elapsed","wait_timeout","wait_received"]),details:B.record(B.string(),B.union([B.string(),B.number(),B.boolean(),B.null()]))})).max(2e3),receipts:B.array(B.strictObject({id:B.uuid(),nodeId:qr,visit:B.number().int().nonnegative(),outcome:Bc})).max(Mf.receipts)}),I2=B.strictObject({id:B.uuid(),projectId:B.uuid(),environmentId:B.uuid(),document:Mt,scenario:Lc,dependencySnapshot:qc,expiresAt:B.iso.datetime({offset:!0})}),A2=B.discriminatedUnion("action",[B.strictObject({action:B.literal("create"),requestId:B.uuid(),document:Mt,scenario:Lc}),B.strictObject({action:B.literal("revoke"),id:B.uuid()})]);import{z as Ie}from"zod";var O2=Ie.object({overall:Ie.object({entered:Ie.number(),running:Ie.number(),closed:Ie.number(),completed:Ie.number(),authenticated:Ie.number(),authReached:Ie.number(),paid:Ie.number(),free:Ie.number()}),steps:Ie.array(Ie.object({node_id:Ie.string(),visitors:Ie.number()})),edges:Ie.array(Ie.object({node_id:Ie.string(),target:Ie.string(),visitors:Ie.number()})),currencies:Ie.array(Ie.object({currency:Ie.string(),grossCents:Ie.number(),refundCents:Ie.number()})),variants:Ie.array(Ie.object({experimentId:Ie.uuid(),revision:Ie.number(),variantId:Ie.string(),exposed:Ie.number(),completed:Ie.number(),paid:Ie.number(),exposedRuns:Ie.number().optional(),completedRuns:Ie.number().optional(),paidRuns:Ie.number().optional()}))});var Vc={zh:["\u5168\u90E8\u4ED8\u8D39\u5957\u9910","\u6307\u5B9A\u5957\u9910","\u6240\u6709\u5BA2\u6237","\u4EC5\u9996\u8D2D","\u9700\u8981\u6807\u7B7E","\u5F00\u59CB","\u622A\u6B62","\u65E0\u622A\u6B62\u65E5\u671F","\u9886\u53D6\u540E\u6709\u6548","\u5C0F\u65F6","\u6BCF\u4EBA\u6B21\u6570","\u603B\u540D\u989D"],"zh-Hant":["\u5168\u90E8\u4ED8\u8CBB\u65B9\u6848","\u6307\u5B9A\u65B9\u6848","\u6240\u6709\u5BA2\u6236","\u50C5\u9996\u8CFC","\u9700\u8981\u6A19\u7C64","\u958B\u59CB","\u622A\u6B62","\u7121\u622A\u6B62\u65E5\u671F","\u9818\u53D6\u5F8C\u6709\u6548","\u5C0F\u6642","\u6BCF\u4EBA\u6B21\u6578","\u7E3D\u540D\u984D"],en:["All paid plans","Selected plans","All customers","First purchase only","Required tags","Starts","Ends","No end date","Valid after claim","hours","Uses per customer","Total limit"],ja:["\u5168\u6709\u6599\u30D7\u30E9\u30F3","\u5BFE\u8C61\u30D7\u30E9\u30F3","\u3059\u3079\u3066\u306E\u304A\u5BA2\u69D8","\u521D\u56DE\u8CFC\u5165\u9650\u5B9A","\u5FC5\u8981\u306A\u30BF\u30B0","\u958B\u59CB","\u7D42\u4E86","\u7D42\u4E86\u65E5\u306A\u3057","\u53D7\u53D6\u5F8C\u306E\u6709\u52B9\u671F\u9593","\u6642\u9593","\u9867\u5BA2\u3054\u3068\u306E\u5229\u7528\u56DE\u6570","\u5229\u7528\u4E0A\u9650"],ko:["\uBAA8\uB4E0 \uC720\uB8CC \uC694\uAE08\uC81C","\uC9C0\uC815 \uC694\uAE08\uC81C","\uBAA8\uB4E0 \uACE0\uAC1D","\uCCAB \uAD6C\uB9E4\uB9CC","\uD544\uC218 \uD0DC\uADF8","\uC2DC\uC791","\uC885\uB8CC","\uC885\uB8CC\uC77C \uC5C6\uC74C","\uC218\uB839 \uD6C4 \uC720\uD6A8 \uAE30\uAC04","\uC2DC\uAC04","\uACE0\uAC1D\uBCC4 \uC0AC\uC6A9 \uD69F\uC218","\uCD1D \uD55C\uB3C4"],es:["Todos los planes de pago","Planes seleccionados","Todos los clientes","Solo primera compra","Etiquetas requeridas","Inicio","Fin","Sin fecha de fin","Validez tras reclamar","horas","Usos por cliente","L\xEDmite total"],fr:["Tous les forfaits payants","Forfaits s\xE9lectionn\xE9s","Tous les clients","Premier achat uniquement","\xC9tiquettes requises","D\xE9but","Fin","Sans date de fin","Validit\xE9 apr\xE8s obtention","heures","Utilisations par client","Limite totale"],de:["Alle kostenpflichtigen Tarife","Ausgew\xE4hlte Tarife","Alle Kunden","Nur erster Kauf","Erforderliche Tags","Beginn","Ende","Kein Enddatum","G\xFCltigkeit nach Erhalt","Stunden","Nutzungen pro Kunde","Gesamtlimit"],pt:["Todos os planos pagos","Planos selecionados","Todos os clientes","Apenas primeira compra","Etiquetas necess\xE1rias","In\xEDcio","Fim","Sem data final","Validade ap\xF3s resgate","horas","Usos por cliente","Limite total"],it:["Tutti i piani a pagamento","Piani selezionati","Tutti i clienti","Solo primo acquisto","Tag richiesti","Inizio","Fine","Senza data finale","Validit\xE0 dopo il ritiro","ore","Utilizzi per cliente","Limite totale"],ru:["\u0412\u0441\u0435 \u043F\u043B\u0430\u0442\u043D\u044B\u0435 \u043F\u043B\u0430\u043D\u044B","\u0412\u044B\u0431\u0440\u0430\u043D\u043D\u044B\u0435 \u043F\u043B\u0430\u043D\u044B","\u0412\u0441\u0435 \u043A\u043B\u0438\u0435\u043D\u0442\u044B","\u0422\u043E\u043B\u044C\u043A\u043E \u043F\u0435\u0440\u0432\u0430\u044F \u043F\u043E\u043A\u0443\u043F\u043A\u0430","\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u044B\u0435 \u0442\u0435\u0433\u0438","\u041D\u0430\u0447\u0430\u043B\u043E","\u041E\u043A\u043E\u043D\u0447\u0430\u043D\u0438\u0435","\u0411\u0435\u0437 \u0434\u0430\u0442\u044B \u043E\u043A\u043E\u043D\u0447\u0430\u043D\u0438\u044F","\u0421\u0440\u043E\u043A \u043F\u043E\u0441\u043B\u0435 \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u044F","\u0447\u0430\u0441\u043E\u0432","\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0439 \u043D\u0430 \u043A\u043B\u0438\u0435\u043D\u0442\u0430","\u041E\u0431\u0449\u0438\u0439 \u043B\u0438\u043C\u0438\u0442"],vi:["M\u1ECDi g\xF3i tr\u1EA3 ph\xED","G\xF3i \u0111\u01B0\u1EE3c ch\u1ECDn","M\u1ECDi kh\xE1ch h\xE0ng","Ch\u1EC9 l\u1EA7n mua \u0111\u1EA7u","Th\u1EBB b\u1EAFt bu\u1ED9c","B\u1EAFt \u0111\u1EA7u","K\u1EBFt th\xFAc","Kh\xF4ng c\xF3 ng\xE0y k\u1EBFt th\xFAc","Hi\u1EC7u l\u1EF1c sau khi nh\u1EADn","gi\u1EDD","L\u01B0\u1EE3t m\u1ED7i kh\xE1ch","T\u1ED5ng gi\u1EDBi h\u1EA1n"],th:["\u0E17\u0E38\u0E01\u0E41\u0E1E\u0E47\u0E01\u0E40\u0E01\u0E08\u0E41\u0E1A\u0E1A\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19","\u0E41\u0E1E\u0E47\u0E01\u0E40\u0E01\u0E08\u0E17\u0E35\u0E48\u0E40\u0E25\u0E37\u0E2D\u0E01","\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32\u0E17\u0E38\u0E01\u0E04\u0E19","\u0E40\u0E09\u0E1E\u0E32\u0E30\u0E01\u0E32\u0E23\u0E0B\u0E37\u0E49\u0E2D\u0E04\u0E23\u0E31\u0E49\u0E07\u0E41\u0E23\u0E01","\u0E41\u0E17\u0E47\u0E01\u0E17\u0E35\u0E48\u0E08\u0E33\u0E40\u0E1B\u0E47\u0E19","\u0E40\u0E23\u0E34\u0E48\u0E21","\u0E2A\u0E34\u0E49\u0E19\u0E2A\u0E38\u0E14","\u0E44\u0E21\u0E48\u0E21\u0E35\u0E27\u0E31\u0E19\u0E2A\u0E34\u0E49\u0E19\u0E2A\u0E38\u0E14","\u0E2D\u0E32\u0E22\u0E38\u0E2B\u0E25\u0E31\u0E07\u0E23\u0E31\u0E1A\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C","\u0E0A\u0E31\u0E48\u0E27\u0E42\u0E21\u0E07","\u0E04\u0E23\u0E31\u0E49\u0E07\u0E15\u0E48\u0E2D\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32","\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E31\u0E49\u0E07\u0E2B\u0E21\u0E14"],id:["Semua paket berbayar","Paket terpilih","Semua pelanggan","Hanya pembelian pertama","Tag wajib","Mulai","Berakhir","Tanpa tanggal akhir","Masa berlaku setelah klaim","jam","Penggunaan per pelanggan","Batas total"],ar:["\u062C\u0645\u064A\u0639 \u0627\u0644\u062E\u0637\u0637 \u0627\u0644\u0645\u062F\u0641\u0648\u0639\u0629","\u0627\u0644\u062E\u0637\u0637 \u0627\u0644\u0645\u062D\u062F\u062F\u0629","\u062C\u0645\u064A\u0639 \u0627\u0644\u0639\u0645\u0644\u0627\u0621","\u0627\u0644\u0634\u0631\u0627\u0621 \u0627\u0644\u0623\u0648\u0644 \u0641\u0642\u0637","\u0627\u0644\u0648\u0633\u0648\u0645 \u0627\u0644\u0645\u0637\u0644\u0648\u0628\u0629","\u062A\u0628\u062F\u0623","\u062A\u0646\u062A\u0647\u064A","\u0628\u0644\u0627 \u062A\u0627\u0631\u064A\u062E \u0627\u0646\u062A\u0647\u0627\u0621","\u0627\u0644\u0635\u0644\u0627\u062D\u064A\u0629 \u0628\u0639\u062F \u0627\u0644\u0645\u0637\u0627\u0644\u0628\u0629","\u0633\u0627\u0639\u0627\u062A","\u0627\u0644\u0627\u0633\u062A\u062E\u062F\u0627\u0645\u0627\u062A \u0644\u0643\u0644 \u0639\u0645\u064A\u0644","\u0627\u0644\u062D\u062F \u0627\u0644\u0625\u062C\u0645\u0627\u0644\u064A"]};function T2(e,t,n=[],r={}){let i=eo(t)??"en",[o="en",...a]=i.split("-"),s=o==="zh"&&!a.includes("Hans")&&a.some(f=>["Hant","TW","HK","MO"].includes(f))?"zh-Hant":o,c=Vc[s]??Vc.en,u=Vc[s]?i:"en",l=f=>new Intl.NumberFormat(u).format(f),d=f=>new Intl.DateTimeFormat(u,{dateStyle:"medium",timeStyle:"short",timeZone:"UTC"}).format(new Date(f))+" UTC",m=[e.appliesTo.type==="all"?c[0]:`${c[1]}${n.length?`: ${n.slice(0,3).join(", ")+(n.length>3?` (+${l(n.length-3)})`:"")}`:""}`,e.eligibility.firstPurchaseOnly?c[3]:c[2],Object.keys(e.eligibility.condition).length||r.qualificationRequired?`${c[4]}${r.includeQualificationTags!==!1&&Bf(e.eligibility.condition)?`: ${Bf(e.eligibility.condition)}`:""}`:null].filter(Boolean).join(" \xB7 "),g=[e.startsAt?`${c[5]}: ${d(e.startsAt)}`:null,e.endsAt?`${c[6]}: ${d(e.endsAt)}`:c[7]].filter(Boolean).join(" \xB7 "),p=[m,g,`${c[8]}: ${l(e.grantWindowHours)} ${c[9]}`,`${c[10]}: ${l(e.perCustomerLimit)}`,e.totalLimit===null?null:`${c[11]}: ${l(e.totalLimit)}`].filter(Boolean).join(" \xB7 ");return{eligibility:m,validity:g,terms:p}}function Bf(e){let t=e.tags;if(!t||typeof t!="object"||Array.isArray(t))return"";let n=t.$all??t.$in;return Array.isArray(n)&&n.every(r=>typeof r=="string")?n.join(", "):""}var Gc={"popup-coupon-welcome-ticket":{discount:"20%",zh:"\u9996\u671F\u8BA2\u9605\u4F18\u60E0",en:"Off your first subscription payment"},"popup-coupon-return-ticket":{discount:"$5",zh:"\u56DE\u6765\u7EE7\u7EED\u4F60\u7684\u8BA1\u5212",en:"Pick up where you left off"},"popup-coupon-launch-poster":{discount:"30%",zh:"\u65B0\u7248\u672C\u4E0A\u7EBF\u4F18\u60E0",en:"A special offer for our new release"},"popup-coupon-friday-poster":{discount:"40%",zh:"\u6D3B\u52A8\u671F\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for the campaign"},"popup-coupon-studio-split":{discount:"25%",zh:"\u4E3A\u521B\u4F5C\u8005\u51C6\u5907\u7684\u8BA2\u9605\u793C\u9047",en:"A subscription offer for creators"},"popup-coupon-team-split":{discount:"$10",zh:"\u56E2\u961F\u65B9\u6848\u9996\u671F\u51CF\u514D",en:"Off the first payment on a team plan"},"popup-coupon-member-letter":{discount:"20%",zh:"\u4E00\u4EFD\u4E13\u5C5E\u7684\u4F1A\u5458\u793C\u9047",en:"A membership offer just for you"},"popup-coupon-founder-letter":{discount:"30%",zh:"\u7ED9\u65E9\u671F\u652F\u6301\u8005\u7684\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for early supporters"},"popup-coupon-gift-box":{discount:"$5",zh:"\u4F60\u7684\u4E0B\u4E00\u6B21\u8BA2\u9605\u4F18\u60E0",en:"An offer for your next subscription"},"popup-coupon-birthday-box":{discount:"25%",zh:"\u751F\u65E5\u4E3B\u9898\u4F1A\u5458\u4F18\u60E0",en:"A birthday-themed membership offer"},"popup-coupon-first-receipt":{discount:"20%",zh:"\u9996\u671F\u4ED8\u6B3E\u6298\u6263",en:"A discount on the first payment"},"popup-coupon-loyalty-receipt":{discount:"$8",zh:"\u8001\u5BA2\u6237\u8BA2\u9605\u793C\u9047",en:"A subscription offer for returning customers"},"popup-coupon-upgrade-sheet":{discount:"20%",zh:"\u4E86\u89E3\u8BA2\u9605\u4F18\u60E0",en:"Explore a subscription offer"},"popup-coupon-return-sheet":{discount:"$5",zh:"\u56DE\u5F52\u8BA2\u9605\u4F18\u60E0",en:"A returning subscriber offer"},"popup-coupon-minimal-number":{discount:"20%",zh:"\u9996\u671F\u8BA2\u9605\u51CF\u514D",en:"Off the first subscription payment"},"popup-coupon-bold-number":{discount:"50%",zh:"\u6D3B\u52A8\u8BA2\u9605\u6298\u6263",en:"A campaign subscription discount"},"popup-coupon-studio-editorial":{discount:"25%",zh:"\u4E13\u4E1A\u8BA2\u9605\u65B9\u6848\u4F18\u60E0",en:"An offer on a professional subscription"},"popup-coupon-autumn-editorial":{discount:"30%",zh:"\u79CB\u5B63\u8BA2\u9605\u6D3B\u52A8",en:"An autumn subscription campaign"},"popup-coupon-vip-pass":{discount:"20%",zh:"\u4F1A\u5458\u8BA2\u9605\u793C\u9047",en:"A membership subscription offer"},"popup-coupon-beta-pass":{discount:"35%",zh:"\u65E9\u671F\u4F53\u9A8C\u8005\u4F18\u60E0",en:"An offer for early adopters"},"popup-coupon-welcome-stamp":{discount:"20%",zh:"\u9996\u6B21\u8BA2\u9605\u793C\u9047",en:"A first subscription offer"},"popup-coupon-milestone-stamp":{discount:"$5",zh:"\u7EE7\u7EED\u524D\u884C\u7684\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for your next step"},"popup-coupon-quiet-frame":{discount:"15%",zh:"\u4E13\u6CE8\u5DE5\u4F5C\u6D41\u8BA2\u9605\u4F18\u60E0",en:"An offer for a focused workflow"},"popup-coupon-premium-frame":{discount:"25%",zh:"\u7CBE\u9009\u4F1A\u5458\u65B9\u6848\u793C\u9047",en:"An offer on selected membership plans"},"popup-coupon-starter-steps":{discount:"20%",zh:"\u4E86\u89E3\u4F18\u60E0\uFF0C\u9886\u53D6\u540E\u9009\u5957\u9910",en:"Explore the offer, then choose your plan"},"popup-coupon-comeback-steps":{discount:"$5",zh:"\u4E3A\u56DE\u5F52\u51C6\u5907\u7684\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for your return"},"popup-coupon-spring-banner":{discount:"20%",zh:"\u6625\u5B63\u8BA2\u9605\u793C\u9047",en:"A spring subscription offer"},"popup-coupon-year-banner":{discount:"30%",zh:"\u65B0\u5E74\u4F1A\u5458\u8BA2\u9605\u4F18\u60E0",en:"A new-year membership offer"},"popup-coupon-mono-card":{discount:"20%",zh:"\u4E13\u4E1A\u5DE5\u5177\u8BA2\u9605\u4F18\u60E0",en:"An offer on professional tools"},"popup-coupon-night-card":{discount:"$5",zh:"\u521B\u4F5C\u5DE5\u5177\u8BA2\u9605\u4F18\u60E0",en:"An offer on creative tools"},"popup-coupon-spotlight-panel":{discount:"30%",zh:"\u4E13\u4E1A\u7248\u8BA2\u9605\u6D3B\u52A8",en:"A professional subscription campaign"},"popup-coupon-summer-panel":{discount:"25%",zh:"\u590F\u5B63\u8BA2\u9605\u4F18\u60E0",en:"A summer subscription offer"}};function Lf(e){return e.actions.map(t=>t.properties.templateKey).find(t=>typeof t=="string"&&t.startsWith("popup-coupon-"))}function D2(e,t){let n=Lf(e);if(!n||!Object.hasOwn(Gc,n))return e;let r=i=>{let o={...i.root.bind,coupon:t};return i.root.bind?.coupon!==t&&delete o.promotionCode,{bind:o}};return{...e,pages:e.pages.map(i=>({...i,root:{...i.root,...r(i)}})),actions:e.actions.map(i=>i.properties.templateKey===n&&i.type!=="close"?{id:i.id,type:"claim_offer",couponId:t,event:"offer.claimed",properties:i.properties,close:i.close}:i)}}function N2(e){let t=Lf(e),n=t?Gc[t]:void 0;return!n||e.actions.some(r=>r.type==="claim_offer")?e:{...e,strings:{...e.strings,locales:Object.fromEntries(Object.entries(e.strings.locales).map(([r,i])=>[r,Object.fromEntries(Object.entries(i).map(([o,a])=>[o,a.replaceAll("{{offer.discount}}",n.discount).replaceAll("{{offer.headline}}",r.startsWith("zh")?n.zh:n.en).replaceAll("{{offer.terms}}",r.startsWith("zh")?"\u6F14\u793A\u91D1\u989D \xB7 \u7ED1\u5B9A\u4F18\u60E0\u5238\u540E\u81EA\u52A8\u663E\u793A\u771F\u5B9E\u6761\u6B3E":"Demo amount \xB7 Bind a coupon to show actual terms")]))]))}}}import{z as ee}from"zod";var Qt=ee.string().min(1).max(255),Fn=ee.number().finite().nonnegative(),qf=ee.strictObject({properties:ee.record(ee.string().min(1).max(64),ee.union([ee.string().min(1).max(128),ee.number().finite(),ee.boolean()]).transform(String).pipe(ee.string())).refine(e=>Object.keys(e).length>=1&&Object.keys(e).length<=4)}),g0=ee.strictObject({feature_id:Qt,enabled:ee.boolean().default(!1),threshold:ee.number().finite(),quantity:ee.number().finite().min(1),purchase_limit:ee.strictObject({interval:ee.enum(["hour","day","week","month"]),interval_count:ee.number().finite().min(1).default(1),limit:ee.number().finite().min(1)}).optional(),invoice_mode:ee.boolean().optional()}),b0=ee.strictObject({feature_id:Qt.optional(),enabled:ee.boolean().default(!1),limit_type:ee.enum(["absolute","usage_percentage"]).optional(),overage_limit:Fn.optional(),skip_overage_billing:ee.boolean().optional()}).refine(e=>e.overage_limit===void 0&&e.skip_overage_billing===void 0||e.feature_id!==void 0,"A feature is required for overage limits and billing controls"),_0=ee.strictObject({feature_id:Qt,enabled:ee.boolean().default(!0),limit:Fn,interval:ee.enum(["day","week","month","year"]),anchor:ee.enum(["billing_cycle","utc"]).optional(),filter:qf.optional()}),y0=ee.strictObject({feature_id:Qt.optional(),enabled:ee.boolean().default(!0),threshold:Fn,threshold_type:ee.enum(["usage","usage_percentage","remaining","remaining_percentage"]),basis:ee.enum(["balance","included","recurring","usage_limit"]).default("balance"),filter:qf.optional(),name:ee.string().optional()}).refine(e=>e.threshold_type!=="remaining_percentage"||e.threshold<=100,"Remaining percentage cannot exceed 100").refine(e=>e.basis!=="usage_limit"||e.feature_id!==void 0,"Usage-limit alerts require a feature").refine(e=>e.filter===void 0||e.basis==="usage_limit","Filters apply only to usage-limit alerts"),S0=ee.strictObject({feature_id:Qt,enabled:ee.boolean().default(!1)}),v0=ee.strictObject({auto_topups:ee.array(g0).nullable(),spend_limits:ee.array(b0).nullable(),usage_limits:ee.array(_0).nullable(),usage_alerts:ee.array(y0).nullable(),overage_allowed:ee.array(S0).nullable()}),B2=v0.omit({auto_topups:!0}),x0=Er,L2=ee.strictObject({internal_id:ee.uuid(),id:Qt.nullable(),project_id:ee.uuid(),environment_id:ee.uuid(),name:ee.string().max(80).nullable(),email:ee.string().max(254).nullable(),metadata:x0.nullable(),created_at:ee.number().finite().nonnegative().max(864e13)}),q2=ee.strictObject({id:Qt,internal_product_id:Qt,product_id:Qt.nullable(),status:ee.enum(["scheduled","pending","active","past_due","expired","unknown","trialing","paused"]),canceled_at:Fn.nullable(),free_trial_id:Qt.nullable(),trial_ends_at:Fn.nullable(),starts_at:Fn.nullable(),access_starts_at:Fn.nullable(),ended_at:Fn.nullable(),product:ee.strictObject({internal_id:Qt,id:Qt,name:ee.string(),version:ee.number().int().positive(),is_add_on:ee.boolean()})});import{z as Te}from"zod";import{z as pe}from"zod";var I0=pe.enum(["customer","coupon","audience"]),A0=pe.enum(["name","description","email","metadata","tags","config","status","terms","codes","content"]),ia=pe.object({baseRevision:pe.number().int().nonnegative(),latestRevision:pe.number().int().nonnegative(),mode:pe.enum(["merge","use_latest"]),decisions:pe.array(pe.object({field:A0,mine:pe.number().int().min(0).max(1e3),latest:pe.number().int().min(0).max(1e3)}).strict().refine(e=>e.mine+e.latest>0)).max(28)}).strict().refine(e=>e.latestRevision>e.baseRevision).refine(e=>new Set(e.decisions.map(t=>t.field)).size===e.decisions.length).refine(e=>e.mode!=="use_latest"||e.decisions.length===0),Vf=pe.number().int().nonnegative().nullable(),w0=pe.object({resource:I0,id:pe.uuid(),projectId:pe.uuid(),environmentId:pe.uuid(),fromRevision:Vf,toRevision:Vf,provenance:pe.enum(["recorded","historical"]),changes:pe.array(pe.object({field:pe.string(),redacted:pe.boolean(),before:pe.union([pe.string(),pe.number(),pe.boolean(),pe.null()]),after:pe.union([pe.string(),pe.number(),pe.boolean(),pe.null()])})),merge:ia.safeExtend({source:pe.literal("client")}).nullable()}),P0=pe.object({createdAt:pe.iso.datetime({offset:!0}),id:pe.uuid()}).strict(),$2=pe.object({events:pe.array(pe.object({id:pe.uuid(),action:pe.string(),actorId:pe.uuid().nullable(),actorEmail:pe.email().nullable(),createdAt:pe.iso.datetime({offset:!0}),object:w0})),nextCursor:P0.nullable()});var Z2={type:"condition",condition:{}},Y2=Te.strictObject({id:Te.uuid(),name:Te.string().min(1).max(80),description:Te.string().max(500),config:Da,revision:Te.number().int().min(1),status:Te.enum(["active","archived"]),batchable:Te.boolean(),created_at:Te.iso.datetime({offset:!0}),updated_at:Te.iso.datetime({offset:!0})}),J2=Te.discriminatedUnion("action",[Te.strictObject({action:Te.literal("save"),id:Te.uuid().nullable(),audit:ia.nullable().optional(),revision:Te.number().int().min(0),name:Te.string().trim().min(1).max(80),description:Te.string().max(500),config:Da}),Te.strictObject({action:Te.literal("archive"),id:Te.uuid(),audit:ia.nullable().optional(),revision:Te.number().int().min(1)})]),O0=Te.object({id:Te.uuid(),name:Te.string().nullable(),external_user_id:Te.string(),attributes:Ct,created_at:Te.iso.datetime({offset:!0})}),X2=Te.object({customers:O0.array(),hasMore:Te.boolean(),offset:Te.number().int().min(0),limit:Te.number().int().min(1),evaluatedAt:Te.iso.datetime({offset:!0}),revision:Te.number().int().min(1)});var Gf="#172033",oa="#667085",C0="#E2E6EE",E0="#2C3C96",wt=e=>({top:e,right:e,bottom:e,left:e}),pt=e=>({type:"color",color:e}),Lt=class{constructor(t,n={}){this.name=t;this.design=n}name;design;zh={};en={};text(t,n,r,i=13,o=oa,a={}){return this.zh[t]=n,this.en[t]=r,{id:t,type:"text",text:t,variant:i>=30?"title":"body",style:{text:{size:i,color:o,weight:i>=30?600:400,lineHeight:1.35,...i>=30?{letterSpacing:-1.2}:{}},...a}}}stack(t,n,r={},i=!1){return{id:t,type:"stack",direction:i?"horizontal":"vertical",align:"stretch",justify:"start",children:n,style:{gap:i?40:24,...r}}}widget(t,n,r,i,o=!1,a={}){let s=t+"_title";return this.zh[s]=r,this.en[s]=i,{id:t,type:"customer_data",title:s,data:{source:n,layout:o?"compact":"full",pageSize:n==="credit_transactions"?5:4,showSources:n==="credit_balance"&&!o,allowPurchase:n==="credit_packs"},style:a}}rule(t,n=C0){return{id:t,type:"divider",style:{background:pt(n),height:1}}}header(t,n,r,i,o,a=!1){return this.stack("account_header",[this.stack("intro",[this.text("eyebrow","\u5DE5\u4F5C\u7A7A\u95F4 / \u8D26\u6237","WORKSPACE / ACCOUNT",11,a?"#A9B4CB":oa,{text:{size:11,color:a?"#A9B4CB":oa,letterSpacing:1.4,weight:600}}),this.text("heading",t,n,28,a?"#FFFFFF":Gf),this.text("description",r,i,14,a?"#A9B4CB":oa)],{gap:12,width:660,grow:!0}),...o?[o]:[]],{gap:32},!0)}document(t,n=!1){return nt.parse({kind:"screen",schemaVersion:4,name:this.name,surface:"page",presentation:{type:"fullscreen"},theme:{primary:E0,background:n?"#101A30":"#F5F6FA",text:Gf,radius:"md",font:"system",...this.design.theme},pages:[{id:"account_page",name:this.name,root:{...this.stack("root",[this.stack("content",t,{width:this.design.width??1200,gap:this.design.gap??32})],{padding:this.design.padding??{top:40,right:24,bottom:36,left:24}}),align:"center"}}],strings:{defaultLocale:"zh-CN",locales:{"zh-CN":this.zh,en:this.en}},actions:[]})}};var sa="#19202E",T0="#667080",$c="#2C3C96",$f="#DDE2E9",Kf="#F0F3FA",R0=(e=72,t=sa)=>({text:{size:e,color:t,weight:600,font:"system"}}),aa=(e,t=1)=>({width:e,grow:t}),j0={background:pt("#FFFFFF"),shape:{type:"rect",radius:10}};function k0(e){return new Lt(e,{theme:{background:"#FFFFFF",text:sa,primary:$c},width:1184,gap:32,padding:{top:24,right:24,bottom:40,left:24}})}function D0(e,t,n,r,i){let o=e.text("wordmark","GROW / \u8D26\u6237","GROW / ACCOUNT",13,$c,{text:{size:13,color:$c,weight:700,letterSpacing:.8}});return e.stack("page_header",[o,e.text("heading",t,n,40,sa,{text:{size:40,color:sa,weight:700,lineHeight:1.18,letterSpacing:-1.4}}),e.text("description",r,i,14,T0)],{gap:12,padding:{top:8,right:0,bottom:8,left:0}})}function Wf(){let e="#FAF7F0",t="#302923",n="#A63C25",r="#73665A",i=new Lt("\u8D26\u6237\u4E00\u89C8",{theme:{background:e,text:t,primary:n,radius:"none"},width:1120,gap:36,padding:{top:32,right:24,bottom:48,left:24}}),o=(a,s,c)=>i.text(a,s,c,12,n,{text:{size:12,color:n,font:"mono",weight:500,letterSpacing:1.1}});return i.document([i.stack("journal_masthead",[i.stack("journal_identity",[i.text("wordmark","GROW","GROW",22,t,{text:{size:22,color:t,weight:700,letterSpacing:-1}}),o("edition","\u8D26\u6237 / ACCOUNT","ACCOUNT / JOURNAL")],{gap:16},!0),i.rule("masthead_rule",t),i.stack("journal_intro",[i.text("heading","\u8D26\u6237\u4E00\u89C8","Your account.",64,t,{width:720,grow:2,text:{size:64,color:t,font:"serif",weight:400,lineHeight:1.12,letterSpacing:-2}}),i.stack("intro_note",[o("intro_index","\u4E3A\u4F60\u7684\u4E0B\u4E00\u6B21\u521B\u4F5C","FOR YOUR NEXT CHAPTER"),i.text("description",`\u4F60\u7684\u4F1A\u5458\u3001\u79EF\u5206\u4E0E\u8D2D\u4E70\u8BB0\u5F55\uFF0C
2
+ \u5728\u4E00\u5904\u4ECE\u5BB9\u638C\u63E1\u3002`,`Membership, credits and purchases.
3
+ A little clarity for what's next.`,14,r)],{width:300,grow:1,gap:12,padding:{top:8,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("account_summary",[i.stack("member_column",[o("member_index","01 / \u4F1A\u5458","01 / MEMBERSHIP"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:t,font:"serif",size:40,weight:400}})],{width:660,grow:2,gap:16}),i.stack("balance_column",[o("balance_index","02 / \u79EF\u5206","02 / CREDITS"),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:t,font:"serif",size:64,weight:400}})],{width:340,grow:1,gap:16})],{gap:48,padding:{top:12,right:0,bottom:12,left:0}},!0),i.rule("records_rule","#D9CFC1"),i.stack("account_records",[i.stack("purchase_column",[o("purchase_index","03 / \u8D2D\u4E70\u8BB0\u5F55","03 / PURCHASES"),i.widget("orders","credit_pack_orders","\u6BCF\u4E00\u7B14\u8D2D\u4E70","Your purchases",!1,{text:{color:t}})],{width:660,grow:2,gap:16}),i.stack("offer_column",[o("offer_index","04 / \u4E13\u5C5E\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u53EF\u7528\u4F18\u60E0","Available offers",!0,{text:{color:t}})],{width:340,grow:1,gap:16})],{gap:48},!0),i.rule("catalog_rule","#D9CFC1"),i.stack("account_catalog",[o("catalog_index","05 / \u65B9\u6848","05 / PLANS"),i.widget("plans","customer_plans","\u63A2\u7D22\u9002\u5408\u4F60\u7684\u65B9\u6848","Find your next plan",!0,{text:{color:t}})],{gap:16}),i.text("journal_footer","GROW / \u8BA9\u521B\u4F5C\u7EE7\u7EED","GROW / KEEP CREATING",11,r,{text:{size:11,color:r,font:"mono",letterSpacing:1}})])}function Hf(){let e="#182C4A",t="#596B83",n="#CCD6E4",r=new Lt("\u79EF\u5206\u5DE5\u4F5C\u53F0",{theme:{background:"#EDF1F7",text:e,primary:"#244F9E",radius:"sm"},width:1200,gap:24,padding:{top:24,right:24,bottom:40,left:24}}),i=(o,a,s)=>r.text(o,a,s,11,t,{text:{size:11,color:t,font:"mono",weight:500,letterSpacing:1}});return r.document([r.stack("terminal_header",[i("wordmark","GROW / \u79EF\u5206\u5DE5\u4F5C\u53F0","GROW / CREDIT WORKSPACE"),r.stack("terminal_intro",[r.text("heading","\u79EF\u5206\u4E0E\u7528\u91CF","Credits & usage",36,e,{width:780,grow:2,text:{size:36,color:e,weight:600,letterSpacing:-1.2,lineHeight:1.15}}),r.text("description","\u4F59\u989D\u3001\u5230\u671F\u6765\u6E90\u4E0E\u6BCF\u4E00\u7B14\u4F7F\u7528\u3002","Balance, expiry and every transaction.",13,t,{width:340,grow:1})],{gap:32},!0)],{gap:16,padding:{top:8,right:0,bottom:8,left:0}}),r.stack("terminal_workspace",[r.stack("ledger_workspace",[r.stack("credit_summary",[i("balance_index","01 / \u8D26\u6237\u4F59\u989D","01 / BALANCE"),r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,{text:{size:80,color:e,font:"mono",weight:500}})],{gap:16,padding:wt(28),background:pt("#E0E8F4")}),r.stack("ledger_panel",[i("activity_index","02 / \u8D26\u76EE\u660E\u7EC6","02 / ACTIVITY"),r.widget("activity","credit_transactions","\u79EF\u5206\u6D41\u6C34","Credit history",!1,{text:{color:e}})],{gap:16,padding:wt(28),background:pt("#FFFFFF")})],{width:820,grow:2,gap:2}),r.stack("purchase_rail",[r.stack("plan_context",[i("membership_index","\u8D26\u6237 / \u65B9\u6848","ACCOUNT / PLAN"),r.widget("membership","membership","\u5F53\u524D\u65B9\u6848","Current plan",!0,{text:{color:e}})],{gap:16,padding:wt(24),background:pt("#FFFFFF")}),r.stack("purchase_panel",[i("purchase_index","03 / \u8865\u5145\u79EF\u5206","03 / TOP UP"),r.widget("packs","credit_packs","\u8D2D\u4E70\u79EF\u5206","Buy credits",!0,{text:{color:e}}),r.text("purchase_note","\u8D2D\u4E70\u524D\u67E5\u770B\u79EF\u5206\u6570\u91CF\u4E0E\u6709\u6548\u671F\u3002","Check the credit amount and validity before purchase.",12,t)],{gap:16,padding:wt(24),background:pt("#FFFFFF")}),r.stack("orders_panel",[i("orders_index","04 / \u8D2D\u4E70\u8BB0\u5F55","04 / PURCHASES"),r.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0,{text:{color:e}})],{gap:16,padding:wt(24),background:pt("#FFFFFF")})],{width:348,grow:1,gap:2})],{gap:24},!0),r.rule("terminal_rule",n),i("terminal_footer","GROW / \u6309\u8D44\u6E90\u67E5\u770B\u4F59\u989D \xB7 \u6309\u8BB0\u5F55\u6838\u5BF9\u4F7F\u7528","GROW / RESOURCE BALANCES \xB7 TRANSACTION RECORDS")])}function Qf(){let e="#253F34",t="#F5F3EC",n="#5C6A60",r="#DBE8B8",i=new Lt("\u4F1A\u5458\u4FF1\u4E50\u90E8",{theme:{background:t,text:e,primary:e,radius:"none"},width:1160,gap:32,padding:{top:28,right:24,bottom:48,left:24}}),o=(a,s,c,u=n)=>i.text(a,s,c,12,u,{text:{size:12,color:u,font:"mono",letterSpacing:1,weight:500}});return i.document([i.stack("club_masthead",[i.stack("club_identity",[i.text("wordmark","GROW CLUB","GROW CLUB",22,e,{text:{size:22,color:e,weight:700,letterSpacing:-.6}}),o("club_edition","\u4F1A\u5458 / MEMBERSHIP","MEMBERSHIP / YOUR SPACE")],{gap:20},!0),i.rule("club_rule",e),i.stack("club_intro",[i.text("heading","\u4F1A\u5458\u4E0E\u65B9\u6848","Room to grow.",64,e,{width:752,grow:2,text:{size:64,color:e,font:"serif",weight:400,lineHeight:1.1,letterSpacing:-2}}),i.stack("club_description",[o("club_intro_label","\u4E3A\u6301\u7EED\u7684\u521B\u9020\u529B","FOR WHAT COMES NEXT"),i.text("description",`\u67E5\u770B\u4F60\u7684\u4F1A\u5458\u72B6\u6001\uFF0C
4
+ \u627E\u5230\u9002\u5408\u4E0B\u4E00\u6B65\u7684\u65B9\u6848\u3002`,`Your membership, at a glance.
5
+ A plan for what comes next.`,14,n)],{width:320,grow:1,gap:12,padding:{top:10,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("membership_summary",[i.stack("member_spread",[o("member_index","01 / \u4F60\u7684\u4F1A\u5458","01 / YOUR MEMBERSHIP","#CCD9CA"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:"#FFFFFF",font:"serif",size:52,weight:400}})],{width:744,grow:2,gap:20,padding:wt(32),background:pt(e)}),i.stack("balance_inset",[o("balance_index","02 / \u521B\u4F5C\u4F59\u989D","02 / CREDIT BALANCE",e),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:e,size:60,weight:500}})],{width:376,grow:1,gap:20,padding:wt(28),background:pt(r)})],{gap:0},!0),i.stack("plan_comparison",[o("plans_index","03 / \u9009\u62E9\u4F60\u7684\u4E0B\u4E00\u6B65","03 / YOUR NEXT STEP"),i.widget("plans","customer_plans","\u627E\u5230\u9002\u5408\u4F60\u7684\u65B9\u6848","A plan to make it yours",!1,{text:{color:e,font:"serif"}})],{gap:16,padding:{top:8,right:0,bottom:8,left:0}}),i.rule("benefits_rule","#C8CEC2"),i.stack("benefit_records",[i.stack("member_offers",[o("offers_index","04 / \u4F60\u7684\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u4F1A\u5458\u4F18\u60E0","Member offers",!1,{text:{color:e}})],{width:556,grow:1,gap:16}),i.stack("member_purchases",[o("orders_index","05 / \u8D2D\u4E70\u8BB0\u5F55","05 / PURCHASES"),i.widget("orders","credit_pack_orders","\u8D2D\u4E70\u4E0E\u8BB0\u5F55","Purchases & records",!1,{text:{color:e}})],{width:556,grow:1,gap:16})],{gap:48},!0),i.rule("footer_rule","#C8CEC2"),o("club_footer","GROW CLUB / \u7559\u51FA\u521B\u9020\u7684\u7A7A\u95F4","GROW CLUB / ROOM FOR WHAT'S NEXT")])}function Zf(){let e=k0("\u521B\u4F5C\u5DE5\u4F5C\u533A");return e.document([D0(e,"\u521B\u4F5C\u5DE5\u4F5C\u533A","Your workspace","\u79EF\u5206\u3001\u4F1A\u5458\u548C\u4F7F\u7528\u8BB0\u5F55\uFF0C\u90FD\u5728\u8FD9\u91CC\u3002","Your credits, membership and activity."),e.stack("studio_summary",[e.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,{...aa(784,2),...R0(80)}),e.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!1,{...aa(328),background:pt(Kf),padding:wt(24),shape:{type:"rect",radius:10}})],{gap:48,padding:{top:12,right:0,bottom:8,left:0}},!0),e.rule("workspace_rule",$f),e.stack("studio_workspace",[e.widget("transactions","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",!1,aa(784,2)),e.stack("credit_shop",[e.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!0),e.rule("shop_rule",$f),e.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0)],{...aa(328),...j0,padding:wt(24),gap:24,background:pt(Kf)})],{gap:48},!0)])}function Yf(){return Zf()}var pn=(e,t=1)=>({width:e,grow:t}),ca=(e=16)=>({shape:{type:"rect",radius:e}}),et=(e,t,n="system")=>({text:{color:e,...t?{size:t,font:n,weight:500}:{}}}),Sn=(e,t,n=e)=>({top:e,right:t,bottom:n,left:t});function N0(e,t,n,r,i="system"){return e.text("heading",t,n,28,r,{text:{size:28,font:i,weight:600,color:r,lineHeight:1.2,letterSpacing:-.8}})}function F0(e,t,n,r,i){return e.text(t,n,r,11,i,{text:{size:11,font:"system",weight:500,color:i,letterSpacing:.6}})}function Vi(e,t,n,r,i,o="system"){let a=e.stack("masthead",[N0(e,t,n,r,o),F0(e,"scope","\u4E2A\u4EBA\u8D26\u6237","PERSONAL ACCOUNT",i)],{gap:20},!0);return a.justify="between",a.align="center",a}function Jf(e,t,n=!1,r=5){let i=e.widget("activity","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",n,et(t));return i.data.pageSize=r,i}function U0(){let e="#171D1A",t="#F2F5ED",n="#9EADA2",r="#D5E7B0",i=new Lt("\u6697\u7EFF\u79EF\u5206\u53F0",{theme:{background:e,text:t,primary:e},width:1120,gap:32,padding:Sn(32,24,48)});return i.document([Vi(i,"\u79EF\u5206\u8D26\u6237","Credits",t,n),i.rule("header_rule","#354039"),i.stack("wallet_workspace",[i.stack("wallet_primary",[i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,et(t,96)),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,et(t))],{...pn(680,2),gap:32,padding:Sn(20,0,12)}),i.stack("purchase_sheet",[i.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!1,et(e))],{...pn(328),background:pt(r),padding:wt(24),...ca(20)})],{gap:72},!0),i.rule("activity_rule","#354039"),Jf(i,t,!1,4)])}function M0(){let e="#302C26",t="#7D766B",n="#D8D1C5",r=new Lt("\u8D26\u6237\u6863\u6848",{theme:{background:"#F7F3EB",text:e,primary:"#84503B"},width:1080,gap:32,padding:Sn(40,24,48)});return r.document([Vi(r,"\u8D26\u6237\u6863\u6848","Account journal",e,t,"serif"),r.rule("header_rule",e),r.stack("statement",[r.stack("balance_column",[r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,et(e,96,"serif"))],{...pn(628,2),padding:Sn(12,0),gap:24}),r.stack("membership_column",[r.widget("membership","membership","\u4F1A\u5458\u72B6\u6001","Membership",!1,et(e)),r.widget("offers","offer_history","\u8D26\u6237\u4F18\u60E0","Your offers",!0,et(e))],{...pn(356),gap:20,padding:Sn(12,0)})],{gap:96},!0),r.rule("orders_rule",n),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Purchases",!1,et(e))])}function B0(){let e="#223E33",t="#687C70",n="#254A3B",r="#F7F9F5",i=new Lt("\u4F1A\u5458\u7A7A\u95F4",{theme:{background:r,text:e,primary:n},width:1120,gap:32,padding:Sn(32,24,48)});return i.document([Vi(i,"\u4F1A\u5458\u4E2D\u5FC3","Membership",e,t),i.stack("current_membership",[i.stack("member_credential",[i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,et("#F4F7F0"))],{...pn(640,2),gap:24,background:pt(n),padding:wt(32),...ca(20)}),i.stack("credit_context",[i.widget("balance","credit_balance","\u8D26\u6237\u79EF\u5206","Account credits",!0,et(e,64))],{...pn(400),background:pt("#E9EFE5"),padding:wt(28),...ca(20)})],{gap:24},!0),i.widget("plans","customer_plans","\u65B9\u6848\u4E0E\u4EF7\u683C","Plans & pricing",!1,et(e)),i.rule("offer_rule","#D5DFD3"),i.widget("offers","offer_history","\u6211\u7684\u4F18\u60E0","Your offers",!0,et(e))])}function L0(){let e="#23262B",t="#797E87",n="#DFE2E7",r=new Lt("\u7528\u91CF\u8D26\u518C",{theme:{background:"#FFFFFF",text:e,primary:e},width:1160,gap:28,padding:Sn(32,24,48)});return r.document([Vi(r,"\u7528\u91CF\u4E0E\u8BB0\u5F55","Usage & history",e,t),r.rule("header_rule",e),r.stack("account_context",[r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{...pn(688,2),...et(e,56,"mono")}),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,{...pn(372),...et(e)})],{gap:72,padding:Sn(4,0,8)},!0),r.rule("activity_rule",n),Jf(r,e),r.rule("order_rule",n),r.widget("orders","credit_pack_orders","\u79EF\u5206\u8D2D\u4E70","Credit purchases",!0,et(e))])}function q0(){let e="#3F3029",t="#8B766A",n="#A34525",r=new Lt("\u79EF\u5206\u8865\u7ED9",{theme:{background:"#FEFAF5",text:e,primary:n},width:1160,gap:32,padding:Sn(32,24,48)});return r.document([Vi(r,"\u8865\u5145\u79EF\u5206","Add credits",e,t),r.rule("header_rule","#E8DDD3"),r.stack("purchase_workspace",[r.stack("account_context",[r.widget("balance","credit_balance","\u73B0\u6709\u79EF\u5206","Current credits",!0,et(e,56)),r.rule("context_rule","#DBC5B5"),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,et(e))],{...pn(304),gap:28,padding:wt(24),background:pt("#F1E5D9"),...ca(16)}),r.stack("purchase_catalog",[r.widget("packs","credit_packs","\u53EF\u8D2D\u4E70\u7684\u79EF\u5206\u5305","Available credit packs",!1,et(e))],{...pn(800,2),gap:24})],{gap:32},!0),r.rule("orders_rule","#E8DDD3"),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Recent purchases",!1,et(e))])}function Xf(){return[{key:"page-credits-midnight",label:"\u6697\u7EFF\u79EF\u5206\u53F0 \xB7 \u591C\u95F4\u6A21\u5F0F",description:"\u4EE5\u5B9E\u65F6\u4F59\u989D\u4E3A\u4E3B\u89C6\u89C9\uFF0C\u6D45\u7EFF\u8D2D\u4E70\u533A\u4E0E\u5B8C\u6574\u6D41\u6C34\u5F62\u6210\u660E\u786E\u64CD\u4F5C\u987A\u5E8F\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u6697\u8272","\u79EF\u5206","\u8D2D\u4E70","\u684C\u9762"],create:U0},{key:"page-account-journal",label:"\u8D26\u6237\u6863\u6848 \xB7 \u7EB8\u611F\u6392\u7248",description:"\u7EB8\u611F\u8D26\u76EE\u3001\u886C\u7EBF\u4F59\u989D\u3001\u8FB9\u680F\u4F1A\u5458\u4E0E\u4F18\u60E0\uFF0C\u4FDD\u7559\u6E05\u6670\u7684\u8D2D\u4E70\u8BB0\u5F55\u3002",category:"\u8D26\u6237\u7A7A\u95F4",tags:["\u7EB8\u611F","\u886C\u7EBF","\u8D26\u6237","\u8BB0\u5F55"],create:M0},{key:"page-membership-sage",label:"\u4F1A\u5458\u7A7A\u95F4 \xB7 \u677E\u7EFF",description:"\u677E\u7EFF\u4F1A\u5458\u51ED\u8BC1\u4E0E\u4F59\u989D\u5E76\u6392\uFF0C\u4E0B\u65B9\u5C55\u793A\u5F53\u524D\u5BA2\u6237\u53EF\u89C1\u7684\u65B9\u6848\u4E0E\u4EF7\u683C\u3002",category:"\u4F1A\u5458\u4E0E\u65B9\u6848",tags:["\u677E\u7EFF","\u4F1A\u5458","\u65B9\u6848","\u684C\u9762"],create:B0},{key:"page-wallet-violet",label:"\u521B\u4F5C\u5DE5\u4F5C\u533A \xB7 \u79EF\u5206\u4E0E\u8BB0\u5F55",description:"\u8D26\u6237\u72B6\u6001\u3001\u5B8C\u6574\u4F7F\u7528\u8BB0\u5F55\u548C\u4FA7\u680F\u79EF\u5206\u8D2D\u4E70\uFF0C\u96C6\u4E2D\u5728\u6E05\u6670\u7684\u5DE5\u4F5C\u533A\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u5DE5\u4F5C\u533A","\u521B\u4F5C","\u79EF\u5206","\u8BB0\u5F55"],create:Yf},{key:"page-usage-ledger",label:"\u7528\u91CF\u8D26\u518C \xB7 \u9ED1\u767D",description:"\u7D27\u51D1\u8D26\u6237\u72B6\u6001\u3001\u5BBD\u5E45\u6D41\u6C34\u4E0E\u8D2D\u4E70\u8BB0\u5F55\uFF0C\u9002\u5408\u7528\u91CF\u5BC6\u96C6\u7684\u4EA7\u54C1\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u9ED1\u767D","\u7B49\u5BBD","\u6D41\u6C34","\u684C\u9762"],create:L0},{key:"page-topup-orange",label:"\u79EF\u5206\u8865\u7ED9 \xB7 \u6696\u6A59",description:"\u5546\u54C1\u4EF7\u683C\u4E0E\u8D2D\u4E70\u5165\u53E3\u5E76\u6392\u5448\u73B0\uFF0C\u65C1\u8FB9\u4FDD\u7559\u5B9E\u65F6\u4F59\u989D\u548C\u4F1A\u5458\u72B6\u6001\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u6696\u6A59","\u8D2D\u4E70","\u79EF\u5206\u5305","\u8BA2\u5355"],create:q0}].map(({create:e,...t})=>({...t,document:e()}))}function V0(){return Hf()}function G0(){return Wf()}function $0(){return Qf()}function dU(){return[...Xf(),{key:"page-credit-center-wallet",label:"\u79EF\u5206\u5DE5\u4F5C\u53F0 \xB7 Terminal",description:"\u84DD\u7070\u8D26\u76EE\u5DE5\u4F5C\u53F0\uFF1A\u7CBE\u786E\u4F59\u989D\u4E0E\u5B8C\u6574\u6D41\u6C34\u4E3A\u4E3B\uFF0C\u65B9\u6848\u3001\u79EF\u5206\u8D2D\u4E70\u4E0E\u8BA2\u5355\u7F6E\u4E8E\u72EC\u7ACB\u64CD\u4F5C\u680F\u3002",category:"\u8D26\u6237\u4E0E\u79EF\u5206",tags:["\u79EF\u5206","\u6D41\u6C34","\u771F\u5B9E\u6570\u636E","\u684C\u9762"],document:V0()},{key:"page-account-overview",label:"\u8D26\u6237\u4E00\u89C8 \xB7 Journal",description:"\u6696\u7EB8\u8272\u4E0E\u886C\u7EBF\u5B57\u4F53\u7684\u6742\u5FD7\u5F0F\u8D26\u6237\u9875\uFF1A\u4F1A\u5458\u4E0E\u79EF\u5206\u5C55\u5F00\u5448\u73B0\uFF0C\u8D2D\u4E70\u3001\u4F18\u60E0\u548C\u65B9\u6848\u5206\u533A\u9605\u8BFB\u3002",category:"\u8D26\u6237\u4E0E\u79EF\u5206",tags:["\u8D26\u6237","\u4F1A\u5458","\u4F18\u60E0","\u771F\u5B9E\u6570\u636E"],document:G0()},{key:"page-membership-catalog",label:"\u4F1A\u5458\u4FF1\u4E50\u90E8 \xB7 Club",description:"\u68EE\u6797\u7EFF\u4E0E\u8C61\u7259\u767D\u7684\u54C1\u724C\u4F1A\u5458\u9875\uFF1A\u5F3A\u5B57\u4F53\u3001\u5BF9\u6BD4\u8272\u4F1A\u5458\u533A\u3001\u5F00\u653E\u5F0F\u65B9\u6848\u6BD4\u8F83\u4E0E\u5B8C\u6574\u8D26\u6237\u8BB0\u5F55\u3002",category:"\u8D26\u6237\u4E0E\u79EF\u5206",tags:["\u4F1A\u5458","\u5957\u9910","\u8D44\u683C","\u771F\u5B9E\u6570\u636E"],document:$0()}]}import{z as Tt}from"zod";var zf=Tt.object({id:Tt.string().min(1).max(136),name:Tt.string().min(1).max(128),type:Tt.enum(["entry","condition","feature"])}).strict(),K0=Tt.object({id:Tt.uuid(),name:Tt.string().min(1).max(80),status:Tt.enum(["draft","published","archived"]),draftNodes:Tt.array(zf).max(600),publishedNodes:Tt.array(zf).max(600),runningVersions:Tt.number().int().nonnegative()}).strict().refine(e=>e.draftNodes.length>0||e.publishedNodes.length>0||e.runningVersions>0,"A Funnel usage must have a current reference or an unfinished run"),fU=Tt.object({rows:Tt.array(K0).max(50),nextCursor:Tt.uuid().nullable()}).strict();import{z as xe}from"zod";var vt=xe.number().int().nonnegative(),eh=xe.strictObject({at:xe.iso.datetime({offset:!0}),id:xe.uuid()}),yU=xe.strictObject({versionId:xe.uuid().nullable(),from:xe.iso.datetime({offset:!0}).nullable(),to:xe.iso.datetime({offset:!0}).nullable(),after:eh.nullable()}).refine(e=>!e.from||!e.to||Date.parse(e.from)<Date.parse(e.to),"Time range must increase"),SU=xe.strictObject({funnelId:xe.uuid(),snapshotAt:xe.iso.datetime({offset:!0}),versions:xe.array(xe.strictObject({id:xe.uuid(),version:xe.number().int().positive(),createdAt:xe.iso.datetime({offset:!0})})).max(100),versionsLimited:xe.boolean(),overall:xe.strictObject({started:vt,completed:vt,closed:vt,failed:vt,waiting:vt,paid:vt}),decisions:xe.strictObject({queries:vt,completed:vt,reportedUsed:vt,pending:vt,failed:vt}),revenue:xe.array(xe.strictObject({currency:re,grossMinor:xe.string().regex(/^\d+$/),refundMinor:xe.string().regex(/^\d+$/),netMinor:xe.string().regex(/^-?\d+$/)})).max(100),nodes:xe.array(xe.strictObject({versionId:xe.uuid(),nodeId:xe.string(),visits:vt,completed:vt,shown:vt,waiting:vt})).max(1e4),recentRuns:xe.array(xe.strictObject({id:xe.uuid(),versionId:xe.uuid(),customerId:xe.uuid(),status:Fc,nodeId:xe.string(),visit:vt,createdAt:xe.iso.datetime({offset:!0}),updatedAt:xe.iso.datetime({offset:!0})})).max(100),nextCursor:eh.nullable()});import{z as Un}from"zod";var wU=Un.object({requestId:Un.uuid(),coupon:hd,audienceId:Un.uuid().nullable(),productVersionId:Un.uuid().optional(),presentation:en,locale:Un.enum(["en","zh-CN"])}).strict(),PU=Un.object({couponId:Un.uuid(),funnelId:Un.uuid()}).strict();import{z as we}from"zod";var mt=we.number().int().nonnegative(),ua=we.string().regex(/^-?\d+$/),W0=we.object({currency:re,grossMinor:ua,refundMinor:ua,netMinor:ua,purchases:mt,refunds:mt}).strict(),TU=we.object({snapshotAt:we.iso.datetime({offset:!0}),customers:we.object({total:mt,created:mt,paid:mt}).strict(),memberships:we.object({active:mt,trial:mt,pastDue:mt,ended:mt}).strict(),runs:we.object({started:mt,completed:mt,closed:mt,paid:mt}).strict(),revenue:we.array(W0).max(100),unknownMoney:mt,funnels:we.array(we.object({id:we.uuid(),name:we.string(),started:mt,completed:mt,paid:mt}).strict()).max(50),daily:we.array(we.object({date:we.iso.date(),currency:re,netMinor:ua}).strict()).max(9e3)}).strict(),RU=we.object({customerId:we.uuid(),rows:we.array(we.object({id:we.string().regex(/^\d+$/),funnelId:we.uuid(),funnelName:we.string(),versionId:we.uuid(),runId:we.uuid(),nodeId:we.string(),experimentId:we.uuid(),visit:we.number().int().nonnegative(),variationKey:we.string(),inExperiment:we.boolean(),hashUsed:we.boolean(),acceptedAt:we.iso.datetime({offset:!0}),runStatus:we.string()}).strict()).max(50),nextCursor:we.string().regex(/^\d+$/).nullable()}).strict();import{z as Zt}from"zod";import{z as ft}from"zod";var th=ft.discriminatedUnion("provider",[ft.strictObject({provider:ft.literal("apple"),orderId:ft.uuid(),receiptId:ft.uuid(),signedTransaction:ft.string().min(1).max(131072)}),ft.strictObject({provider:ft.literal("google"),orderId:ft.uuid(),receiptId:ft.uuid(),purchaseToken:ft.string().min(1).max(16384)})]),nh=ft.strictObject({orderId:ft.uuid(),receiptId:ft.uuid(),transactionIds:ft.array(ft.string().min(1).max(255)).min(1).max(50),membership:ft.boolean()});var MU=Zt.strictObject({operation:Zt.literal("native_receipt"),requestId:Zt.uuid(),customerToken:Zt.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/),orderId:Zt.uuid(),receiptId:Zt.uuid(),nativeEvidence:th.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),BU=Zt.strictObject({scope:ke,requestId:Zt.uuid(),orderId:Zt.uuid(),receiptId:Zt.uuid(),orderStatus:Zt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:Zt.boolean(),nativeCompletion:nh.optional()});import{z as H0}from"zod";var Q0=Tf.extend({document:H0.union([nt.refine(e=>e.pages.length===1,"Use a single owned screen template"),Mt.refine(e=>e.screens.every(t=>t.type==="owned"),"Flow templates own their screens")])}).superRefine((e,t)=>{if((e.document.kind==="funnel"?e.surface!=="onboarding":e.surface!==e.document.surface)&&t.addIssue({code:"custom",message:"Template category does not match its document"}),e.document.kind==="funnel"){let n=e.document,r=n.graph.nodes.filter(i=>i.type==="screen");(new Set(n.screens.map(i=>i.id)).size!==n.screens.length||new Set(n.graph.nodes.map(i=>i.id)).size!==n.graph.nodes.length||r.length!==n.screens.length||n.screens.some(i=>r.filter(o=>o.screenId===i.id).length!==1))&&t.addIssue({code:"custom",message:"Every template screen requires one unique flow node"})}});function ZU(e,t=0){if(e.document.kind==="screen")return e.document;let n=e.document.screens[t];if(n?.type!=="owned")throw new Error("Owned template screen required");let r=e.document.graph.nodes.find(i=>i.type==="screen"&&i.screenId===n.id);if(r?.type!=="screen")throw new Error("Template screen node required");return{...n.document,presentation:r.presentation.type==="inline"?{type:"fullscreen"}:r.presentation}}var mn="00000000-0000-0000-0000-000000000000";function Z0(e){return e.type==="event"&&typeof e.properties.templateKey=="string"&&e.properties.templateKey.startsWith("popup-coupon-")}function Y0(e,t){let n=structuredClone(Q0.parse(e).document);if(n.kind==="funnel"){let m=function(g){if(Array.isArray(g)){g.forEach(m);return}if(!g||typeof g!="object")return;let p=g;p.type==="experiment-ref"&&(p.experimentId=mn),p.$savedGroup&&typeof p.$savedGroup=="object"&&(p.$savedGroup.id=mn),typeof p.$inGroup=="string"&&(p.$inGroup=mn),typeof p.$notInGroup=="string"&&(p.$notInGroup=mn),Object.values(p).forEach(m)};var d=m;for(let[g,p]of Object.entries(n.references))"id"in p&&delete n.references[g];for(let g of n.graph.nodes)g.type==="condition"&&g.cases.forEach(p=>m(p.condition));for(let g of n.screens)g.type==="owned"&&rh(g.document);return Mt.parse({...n,screens:n.screens.map(g=>g.type==="owned"?{...g,document:{...g.document,strings:{...g.document.strings,defaultLocale:Ua(g.document,[t])}}}:g),graph:{...n.graph,nodes:n.graph.nodes.map(g=>{if(g.type==="split")return{...g,experimentId:"00000000-0000-0000-0000-000000000000"};if(g.type==="offering")return{...g,configuration:g.configuration.source==="fixed"?{source:"fixed",versionId:mn}:g.configuration};if(g.type==="coupons")return{...g,couponIds:[]};if(g.type==="coupon")return{...g,couponId:mn};if(g.type==="screen"&&g.offering?.source==="fixed")return{...g,offering:{source:"fixed",versionId:mn}};if(g.type==="action"&&g.action.type==="claim_offer"&&g.action.coupon.source==="literal")return{...g,action:{...g.action,coupon:{source:"literal",value:{type:"reward",id:mn}}}};if(g.type==="output"&&g.value.type==="bundle"){let p={...g.value};for(let[f,y]of[["paywall","paywall_version"],["offering","offering_version"]])p[f]?.source==="literal"&&(p[f]={source:"literal",value:{type:y,id:mn}});return p.coupons.source==="literal"&&(p.coupons={source:"literal",value:[]}),{...g,value:p}}return g})}})}let r={...n,strings:{...n.strings,defaultLocale:Ua(n,[t])}},i=[{id:"entry",type:"entry",name:t==="en"?"Entry":"\u5165\u53E3",next:"screen"},{id:"done",name:t==="en"?"Completed":"\u5B8C\u6210",type:"end",outcome:"completed",output:{type:"literal",value:null}},{id:"closed",name:t==="en"?"Closed":"\u5173\u95ED",type:"end",outcome:"closed"}],o={},a=t==="en",s,c=()=>s||(s="claim",i.push({id:s,name:a?"Claim Coupon":"\u9886\u53D6 Coupon",type:"action",execution:{...hm},action:{type:"claim_offer",coupon:{source:"literal",value:{type:"reward",id:mn}}},success:"done",cancel:"closed",unavailable:"unavailable",failure:"failed"},{id:"unavailable",name:a?"Offer unavailable":"\u4F18\u60E0\u4E0D\u53EF\u7528",type:"end",outcome:"ineligible",output:{type:"literal",value:null}},{id:"failed",name:a?"Claim failed":"\u9886\u53D6\u5931\u8D25",type:"end",outcome:"failed"}),s);r.actions=r.actions.map((m,g)=>{let p=`action_${g}`;return o[m.id]=m.close?"closed":"done",m.type==="open_url"?(o[m.id]=p,i.push({id:p,name:m.id,type:"output",value:{type:"literal",value:{intent:"open_url",url:m.url}}})):(m.type==="claim_offer"||Z0(m))&&(o[m.id]=c()),{id:m.id,type:"event",event:m.id,properties:{},close:!1}}),rh(r),i.push({id:"screen",name:e.label,type:"screen",screenId:"screen",presentation:e.surface==="page"?{type:"inline"}:n.presentation,outputs:o});let u=new Set(i.flatMap(kr)),l={};return Mt.parse({references:{},variables:l,outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",schemaVersion:4,inputs:(()=>{let m=[];return Et(r,g=>{if(g.type==="stack"&&g.interaction&&["input","select","multiselect","toggle","tabs"].includes(g.interaction.type)){let p=`answer_${crypto.randomUUID().replaceAll("-","")}`;l[p]={type:g.interaction.type==="toggle"?"boolean":g.interaction.type==="multiselect"?"strings":"string",nullable:!1,source:{type:"input"}},m.push({variable:p,screenId:"screen",componentId:g.id,required:!1})}}),m})(),screens:[{id:"screen",type:"owned",document:r}],graph:{version:5,entry:"entry",nodes:i.filter(m=>m.type!=="end"||u.has(m.id))}})}function YU(e,t,n){if(t.document.kind!=="screen")throw new Error("Choose a single screen template");let r=Y0(t,n),i=`tpl_${crypto.randomUUID().replaceAll("-","").slice(0,16)}_`,o=new Map,a=d=>d==="unconnected"?d:(o.has(d)||o.set(d,`${i}${crypto.randomUUID().replaceAll("-","").slice(0,24)}`),o.get(d)),s=r.graph.nodes.slice().sort((d,m)=>+(m.type==="screen")-+(d.type==="screen")).filter(d=>d.type!=="entry").map(d=>d.type==="screen"?{...d,id:a(d.id),screenId:a(d.screenId),outputs:Object.fromEntries(Object.entries(d.outputs).map(([m,g])=>[m,a(g)]))}:d.type==="action"?{...d,id:a(d.id),success:a(d.success),cancel:a(d.cancel),unavailable:a(d.unavailable),failure:a(d.failure)}:d.type==="external_page"?{...d,id:a(d.id),opened:a(d.opened),failed:a(d.failed)}:{...d,id:a(d.id)}),c=Mt.parse({...e,variables:{...e.variables,...r.variables},screens:[...e.screens,...r.screens.map(d=>({...d,id:a(d.id)}))],inputs:[...e.inputs,...r.inputs.map(d=>({...d,screenId:a(d.screenId)}))],graph:{...e.graph,nodes:[...e.graph.nodes,...s]}}),u=0,l=0;for(let d of c.screens)d.type==="owned"&&(Et(d.document,()=>{u++}),l+=d.document.actions.length);if(u>Qe.components||l>Qe.actions||_t(c)>Qe.documentBytes)throw new Error("Template exceeds the flow capacity");return c}function rh(e){Et(e,t=>{t.type==="stack"&&t.bind?(delete t.bind.plan,delete t.bind.coupon,delete t.bind.promotionCode,Object.keys(t.bind).length||delete t.bind):t.type==="plan_picker"&&(delete t.planIds,delete t.defaultPlan)})}function J0(e){return e.kind==="membership"&&["week","month","year"].includes(e.interval)}function XU(e){return e.kind==="topup"?"credit_pack":e.interval==="one_time"?"lifetime":"membership"}function ih(e){return J0(e)?e.intervalCount??1:1}function zU(e,t){return e.interval===t.interval&&ih(e)===ih(t)}function eM(e,t,n=1){if(e==="free")return"";if(e==="one_time")return t.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let r=t.split("-")[0]??"en",i={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},o={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},a=e==="week"?`/${o[r]??o.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?a:`/${n} ${a.slice(1)}${r==="en"?"s":""}`}import{z as Ge}from"zod";var oh=Ge.enum(["membership","trial","topup","manual","rollover","seat"]),ah=Ge.enum(["scheduled","active","expired","revoked","unavailable"]),oM=Ge.strictObject({customerId:Ge.uuid().nullable(),entityId:Ge.uuid().nullable(),internal_feature_id:Ge.uuid().nullable(),reason:oh.nullable(),status:ah.nullable(),after:Ge.uuid().nullable(),limit:Ge.number().int().min(1).max(50)}),aM=Ge.strictObject({snapshotAt:Ge.iso.datetime({offset:!0}),rows:Ge.array(Ge.strictObject({id:Ge.uuid(),customerId:Ge.uuid(),fundingCustomerId:Ge.uuid(),entityId:Ge.uuid().nullable(),internal_feature_id:Ge.uuid(),key:Zi,name:Ge.string().min(1).max(120),kind:Ge.enum(["access","metered","credit"]),reason:oh,status:ah,unlimited:Ge.boolean(),granted:kt,available:kt,held:kt,spent:kt,revoked:kt,transferred:kt,startsAt:Ge.iso.datetime({offset:!0}).nullable(),expiresAt:Ge.iso.datetime({offset:!0}).nullable(),grantId:Ge.uuid().nullable(),membershipId:Ge.uuid().nullable(),seatPoolId:Ge.uuid().nullable()})).max(50),nextCursor:Ge.uuid().nullable()});import{z as Be}from"zod";var sh=Be.string().regex(/^[a-f0-9]{64}$/),X0=Yu.omit({variations:!0,active:!0}).extend({changeId:sh,variations:Be.array(Be.strictObject({urlRedirect:Be.string().max(2048)})).min(2).max(20)}),pM=Be.strictObject({environmentId:Be.uuid(),trackExposures:Be.boolean(),generation:sh,experiments:Be.array(X0).max(100),savedGroups:Xu}),z0=Be.strictObject({eventUuid:Be.uuid(),timestamp:Be.iso.datetime({offset:!0}).optional(),deviceId:Be.string().min(1).max(128),sessionId:Be.string().min(1).max(128).optional(),url:Be.url().max(2048),pageTitle:Be.string().max(512).optional(),experimentKey:Be.string().min(1).max(255),variationKey:Be.string().min(1).max(64)}),mM=Be.strictObject({events:Be.array(z0).min(1).max(20)}),fM=Be.strictObject({inserted:Be.number().int().nonnegative(),duplicates:Be.number().int().nonnegative(),skipped:Be.number().int().nonnegative(),rejected:Be.array(Be.strictObject({index:Be.number().int().nonnegative(),reason:Be.string()}))});import{z as q}from"zod";var uh=q.strictObject({property:q.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/),datatype:q.enum(["boolean","string","number","enum","string[]","number[]","object","array","json"]),enumValues:q.array(q.string()).min(1).nullable(),format:q.enum(["","version","date","isoCountryCode"]),hashAttribute:q.boolean(),stored:q.boolean(),description:q.string().max(2e3),status:q.enum(["active","archived"])}).superRefine((e,t)=>{["parameters","answers","results","__proto__","constructor","prototype"].includes(e.property)&&t.addIssue({code:"custom",message:"Reserved attribute property"}),(e.datatype==="enum"!=(e.enumValues!==null)||e.hashAttribute&&!["string","number","enum"].includes(e.datatype))&&t.addIssue({code:"custom",message:"Hash attributes must be scalar strings or numbers; enums require values"})}),lh=q.strictObject({name:q.string().min(1).max(128),label:q.string().min(1).max(80),description:q.string().max(2e3),status:q.enum(["active","inactive"]),hashAttribute:q.string().min(1).max(128),seed:q.string().min(1).max(128)}),Kc={id:q.uuid(),revision:q.number().int().positive()},yM=q.strictObject({groups:q.array(q.strictObject({id:q.uuid(),name:q.string(),type:q.enum(["condition","list"])})),experiments:q.array(q.strictObject({...Kc,configuration:ni,archivedAt:q.iso.datetime({offset:!0}).nullable()})),namespaces:q.array(q.strictObject({...Kc,configuration:lh})),attributes:q.array(q.strictObject({...Kc,configuration:uh})),truncated:q.boolean()}),Wc={id:q.uuid().nullable(),revision:q.number().int().min(0)},SM=q.discriminatedUnion("resource",[q.strictObject({...Wc,resource:q.literal("experiment"),configuration:ni.safeExtend({archivedAt:q.iso.datetime({offset:!0}).nullable()})}),q.strictObject({...Wc,resource:q.literal("namespace"),configuration:lh}),q.strictObject({...Wc,resource:q.literal("attribute"),configuration:uh})]),vM=q.strictObject({operation:q.literal("evaluate"),attributes:Ct,condition:wn.optional(),features:Cu,featureKey:q.string().min(1).max(128),customerId:q.uuid().nullable()}),xM=q.strictObject({experimentId:q.uuid(),participants:q.number().int().nonnegative(),cohorts:q.array(q.strictObject({variationKey:q.string().nullable(),participants:q.number().int().nonnegative()})),phases:q.array(q.strictObject({phaseIndex:q.number().int().nonnegative(),participants:q.number().int().nonnegative()})),stickyIdentities:q.number().int().nonnegative(),snapshotAt:q.iso.datetime()}),ch=q.strictObject({resource:q.enum(["group","experiment","coupon"]),id:q.uuid()}),IM=q.strictObject({rows:q.array(ch.extend({name:q.string(),status:q.string()})).max(50),total:q.number().int().nonnegative(),nextCursor:ch.nullable()});var la=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ex(e,t){let n=e.phases.at(-1),r=t.phases.at(-1),i=[];(!la(n.condition,r.condition)||!la(n.savedGroups,r.savedGroups))&&i.push("targeting"),r.coverage<n.coverage&&i.push("coverage"),r.namespace&&(!n.namespace||n.namespace.id!==r.namespace.id)&&i.push("namespace"),r.namespace&&n.namespace?.id===r.namespace.id&&n.namespace.ranges.some(([c,u])=>{let l=c;for(let[d,m]of[...r.namespace.ranges].sort((g,p)=>g[0]-p[0]))d<=l&&m>l&&(l=m);return l<u})&&i.push("namespaceRange"),(!la(n.variationWeights,r.variationWeights)||!la(e.variations.map(c=>c.key),t.variations.map(c=>c.key)))&&i.push("weights"),(e.disableStickyBucketing!==t.disableStickyBucketing||n.seed!==r.seed)&&i.push("identity");let o=i.some(c=>["namespace","namespaceRange","weights","identity"].includes(c)),a=!t.disableStickyBucketing,s=o||i.length>0&&!a?"new-phase":a?"same-phase-sticky":"same-phase-everyone";return{reasons:i,disableSamePhase:o,recommended:s,risk:i.length?o?"danger":"warning":"safe"}}function PM(e,t,n,r,i){let o=structuredClone(t),a=o.phases.at(-1),s=!o.disableStickyBucketing;if(n==="same-phase-sticky"&&!s||n==="new-phase-block-sticky"&&!s)throw Error("Sticky bucketing is required");if(ex(e,t).disableSamePhase&&n.startsWith("same-phase"))throw Error("Start a new phase for these changes");if(o.bucketVersion=e.bucketVersion+(s&&n!=="same-phase-sticky"?1:0),o.minBucketVersion=n==="new-phase-block-sticky"?o.bucketVersion:e.minBucketVersion,n.startsWith("new-phase")){o.phases=structuredClone(e.phases);let c=o.phases.at(-1);if(!c)throw new Error("Experiment requires a phase");c.dateEnded=r,o.phases.push({...a,name:a.name,reason:a.reason,dateStarted:r,dateEnded:null,seed:i})}return ni.parse(o)}import{z as tx}from"zod";var EM=tx.enum(["owner","admin","developer","sales","member"]),nx=["organisation","customers","features","plans","rewards","balances","billing","migrations","analytics","apiKeys","platform"],dh=nx.flatMap(e=>e==="analytics"?["analytics:read"]:[`${e}:read`,`${e}:write`]),ph={owner:dh,admin:dh,developer:["organisation:read","customers:write","features:write","plans:write","rewards:write","balances:write","billing:write","migrations:write","analytics:read","apiKeys:write","platform:write"],sales:["customers:write","features:read","plans:read","rewards:write","balances:write","billing:write","analytics:read"],member:["organisation:read","customers:read","features:read","plans:read","rewards:read","balances:read","billing:read","analytics:read","apiKeys:read","platform:read"]};function TM(e,t){if(!e||!Object.hasOwn(ph,e))return!1;let n=ph[e];return n.includes(t)||t.endsWith(":read")&&n.includes(t.replace(/:read$/,":write"))}var jM=["boolean","metered","credit_system","ai_credit_system"];function kM(e,t,n,r=!1){let i=[],o=(a,s)=>i.push({field:a,code:s});return e.type!==t.type&&(e.type==="credit_system"!=(t.type==="credit_system")&&o("type","type_switch_credit_system"),n.customerHistory&&o("type","attached_to_customer"),n.entityFeature&&o("type","used_as_entity_feature"),n.usagePrice&&o("type","has_usage_price"),n.creditSystems&&o("type","used_in_credit_system"),n.productEntitlements&&(e.type==="credit_system"||t.type==="credit_system")&&o("type","used_in_product_credit_system")),e.id!==t.id&&(r&&o("id","id_already_exists"),n.customerHistory&&o("id","attached_to_customer")),e.type!=="boolean"&&t.type!=="boolean"&&e.config?.usage_type!==t.config?.usage_type&&t.config?.usage_type&&(n.creditSystems&&o("usage_type","used_in_credit_system"),n.entityFeature&&o("usage_type","used_as_entity_feature"),n.customerHistory&&o("usage_type","attached_to_customer")),i}/*!
6
+ * decimal.js v10.6.0
7
+ * An arbitrary-precision Decimal type for JavaScript.
8
+ * https://github.com/MikeMcl/decimal.js
9
+ * Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
10
+ * MIT Licence
11
+ */var Vr=9e15,qn=1e9,Hc="0123456789abcdef",ma="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",fa="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Qc={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Vr,maxE:Vr,crypto:!1},gh,vn,ce=!0,ga="[DecimalError] ",Ln=ga+"Invalid argument: ",bh=ga+"Precision limit exceeded",_h=ga+"crypto unavailable",yh="[object Decimal]",xt=Math.floor,tt=Math.pow,rx=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,ix=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,ox=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Sh=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,nn=1e7,ne=7,ax=9007199254740991,sx=ma.length-1,Zc=fa.length-1,C={toStringTag:yh};C.absoluteValue=C.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),X(e)};C.ceil=function(){return X(new this.constructor(this),this.e+1,2)};C.clampedTo=C.clamp=function(e,t){var n,r=this,i=r.constructor;if(e=new i(e),t=new i(t),!e.s||!t.s)return new i(NaN);if(e.gt(t))throw Error(Ln+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};C.comparedTo=C.cmp=function(e){var t,n,r,i,o=this,a=o.d,s=(e=new o.constructor(e)).d,c=o.s,u=e.s;if(!a||!s)return!c||!u?NaN:c!==u?c:a===s?0:!a^c<0?1:-1;if(!a[0]||!s[0])return a[0]?c:s[0]?-u:0;if(c!==u)return c;if(o.e!==e.e)return o.e>e.e^c<0?1:-1;for(r=a.length,i=s.length,t=0,n=r<i?r:i;t<n;++t)if(a[t]!==s[t])return a[t]>s[t]^c<0?1:-1;return r===i?0:r>i^c<0?1:-1};C.cosine=C.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+ne,r.rounding=1,n=cx(r,wh(r,n)),r.precision=e,r.rounding=t,X(vn==2||vn==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};C.cubeRoot=C.cbrt=function(){var e,t,n,r,i,o,a,s,c,u,l=this,d=l.constructor;if(!l.isFinite()||l.isZero())return new d(l);for(ce=!1,o=l.s*tt(l.s*l,1/3),!o||Math.abs(o)==1/0?(n=ht(l.d),e=l.e,(o=(e-n.length+1)%3)&&(n+=o==1||o==-2?"0":"00"),o=tt(n,1/3),e=xt((e+1)/3)-(e%3==(e<0?-1:2)),o==1/0?n="5e"+e:(n=o.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new d(n),r.s=l.s):r=new d(o.toString()),a=(e=d.precision)+3;;)if(s=r,c=s.times(s).times(s),u=c.plus(l),r=Le(u.plus(l).times(s),u.plus(c),a+2,1),ht(s.d).slice(0,a)===(n=ht(r.d)).slice(0,a))if(n=n.slice(a-3,a+1),n=="9999"||!i&&n=="4999"){if(!i&&(X(s,e+1,0),s.times(s).times(s).eq(l))){r=s;break}a+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(X(r,e+1,1),t=!r.times(r).times(r).eq(l));break}return ce=!0,X(r,e,d.rounding,t)};C.decimalPlaces=C.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-xt(this.e/ne))*ne,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};C.dividedBy=C.div=function(e){return Le(this,new this.constructor(e))};C.dividedToIntegerBy=C.divToInt=function(e){var t=this,n=t.constructor;return X(Le(t,new n(e),0,1,1),n.precision,n.rounding)};C.equals=C.eq=function(e){return this.cmp(e)===0};C.floor=function(){return X(new this.constructor(this),this.e+1,3)};C.greaterThan=C.gt=function(e){return this.cmp(e)>0};C.greaterThanOrEqualTo=C.gte=function(e){var t=this.cmp(e);return t==1||t===0};C.hyperbolicCosine=C.cosh=function(){var e,t,n,r,i,o=this,a=o.constructor,s=new a(1);if(!o.isFinite())return new a(o.s?1/0:NaN);if(o.isZero())return s;n=a.precision,r=a.rounding,a.precision=n+Math.max(o.e,o.sd())+4,a.rounding=1,i=o.d.length,i<32?(e=Math.ceil(i/3),t=(1/_a(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),o=Gr(a,1,o.times(t),new a(1),!0);for(var c,u=e,l=new a(8);u--;)c=o.times(o),o=s.minus(c.times(l.minus(c.times(l))));return X(o,a.precision=n,a.rounding=r,!0)};C.hyperbolicSine=C.sinh=function(){var e,t,n,r,i=this,o=i.constructor;if(!i.isFinite()||i.isZero())return new o(i);if(t=o.precision,n=o.rounding,o.precision=t+Math.max(i.e,i.sd())+4,o.rounding=1,r=i.d.length,r<3)i=Gr(o,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/_a(5,e)),i=Gr(o,2,i,i,!0);for(var a,s=new o(5),c=new o(16),u=new o(20);e--;)a=i.times(i),i=i.times(s.plus(a.times(c.times(a).plus(u))))}return o.precision=t,o.rounding=n,X(i,t,n,!0)};C.hyperbolicTangent=C.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,Le(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};C.inverseCosine=C.acos=function(){var e=this,t=e.constructor,n=e.abs().cmp(1),r=t.precision,i=t.rounding;return n!==-1?n===0?e.isNeg()?fn(t,r,i):new t(0):new t(NaN):e.isZero()?fn(t,r+4,i).times(.5):(t.precision=r+6,t.rounding=1,e=new t(1).minus(e).div(e.plus(1)).sqrt().atan(),t.precision=r,t.rounding=i,e.times(2))};C.inverseHyperbolicCosine=C.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,ce=!1,n=n.times(n).minus(1).sqrt().plus(n),ce=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};C.inverseHyperbolicSine=C.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,ce=!1,n=n.times(n).plus(1).sqrt().plus(n),ce=!0,r.precision=e,r.rounding=t,n.ln())};C.inverseHyperbolicTangent=C.atanh=function(){var e,t,n,r,i=this,o=i.constructor;return i.isFinite()?i.e>=0?new o(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=o.precision,t=o.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?X(new o(i),e,t,!0):(o.precision=n=r-i.e,i=Le(i.plus(1),new o(1).minus(i),n+e,1),o.precision=e+4,o.rounding=1,i=i.ln(),o.precision=e,o.rounding=t,i.times(.5))):new o(NaN)};C.inverseSine=C.asin=function(){var e,t,n,r,i=this,o=i.constructor;return i.isZero()?new o(i):(t=i.abs().cmp(1),n=o.precision,r=o.rounding,t!==-1?t===0?(e=fn(o,n+4,r).times(.5),e.s=i.s,e):new o(NaN):(o.precision=n+6,o.rounding=1,i=i.div(new o(1).minus(i.times(i)).sqrt().plus(1)).atan(),o.precision=n,o.rounding=r,i.times(2)))};C.inverseTangent=C.atan=function(){var e,t,n,r,i,o,a,s,c,u=this,l=u.constructor,d=l.precision,m=l.rounding;if(u.isFinite()){if(u.isZero())return new l(u);if(u.abs().eq(1)&&d+4<=Zc)return a=fn(l,d+4,m).times(.25),a.s=u.s,a}else{if(!u.s)return new l(NaN);if(d+4<=Zc)return a=fn(l,d+4,m).times(.5),a.s=u.s,a}for(l.precision=s=d+10,l.rounding=1,n=Math.min(28,s/ne+2|0),e=n;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(ce=!1,t=Math.ceil(s/ne),r=1,c=u.times(u),a=new l(u),i=u;e!==-1;)if(i=i.times(c),o=a.minus(i.div(r+=2)),i=i.times(c),a=o.plus(i.div(r+=2)),a.d[t]!==void 0)for(e=t;a.d[e]===o.d[e]&&e--;);return n&&(a=a.times(2<<n-1)),ce=!0,X(a,l.precision=d,l.rounding=m,!0)};C.isFinite=function(){return!!this.d};C.isInteger=C.isInt=function(){return!!this.d&&xt(this.e/ne)>this.d.length-2};C.isNaN=function(){return!this.s};C.isNegative=C.isNeg=function(){return this.s<0};C.isPositive=C.isPos=function(){return this.s>0};C.isZero=function(){return!!this.d&&this.d[0]===0};C.lessThan=C.lt=function(e){return this.cmp(e)<0};C.lessThanOrEqualTo=C.lte=function(e){return this.cmp(e)<1};C.logarithm=C.log=function(e){var t,n,r,i,o,a,s,c,u=this,l=u.constructor,d=l.precision,m=l.rounding,g=5;if(e==null)e=new l(10),t=!0;else{if(e=new l(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new l(NaN);t=e.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new l(n&&!n[0]?-1/0:u.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)o=!0;else{for(i=n[0];i%10===0;)i/=10;o=i!==1}if(ce=!1,s=d+g,a=Bn(u,s),r=t?ha(l,s+10):Bn(e,s),c=Le(a,r,s,1),Gi(c.d,i=d,m))do if(s+=10,a=Bn(u,s),r=t?ha(l,s+10):Bn(e,s),c=Le(a,r,s,1),!o){+ht(c.d).slice(i+1,i+15)+1==1e14&&(c=X(c,d+1,0));break}while(Gi(c.d,i+=10,m));return ce=!0,X(c,d,m)};C.minus=C.sub=function(e){var t,n,r,i,o,a,s,c,u,l,d,m,g=this,p=g.constructor;if(e=new p(e),!g.d||!e.d)return!g.s||!e.s?e=new p(NaN):g.d?e.s=-e.s:e=new p(e.d||g.s!==e.s?g:NaN),e;if(g.s!=e.s)return e.s=-e.s,g.plus(e);if(u=g.d,m=e.d,s=p.precision,c=p.rounding,!u[0]||!m[0]){if(m[0])e.s=-e.s;else if(u[0])e=new p(g);else return new p(c===3?-0:0);return ce?X(e,s,c):e}if(n=xt(e.e/ne),l=xt(g.e/ne),u=u.slice(),o=l-n,o){for(d=o<0,d?(t=u,o=-o,a=m.length):(t=m,n=l,a=u.length),r=Math.max(Math.ceil(s/ne),a)+2,o>r&&(o=r,t.length=1),t.reverse(),r=o;r--;)t.push(0);t.reverse()}else{for(r=u.length,a=m.length,d=r<a,d&&(a=r),r=0;r<a;r++)if(u[r]!=m[r]){d=u[r]<m[r];break}o=0}for(d&&(t=u,u=m,m=t,e.s=-e.s),a=u.length,r=m.length-a;r>0;--r)u[a++]=0;for(r=m.length;r>o;){if(u[--r]<m[r]){for(i=r;i&&u[--i]===0;)u[i]=nn-1;--u[i],u[r]+=nn}u[r]-=m[r]}for(;u[--a]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=ba(u,n),ce?X(e,s,c):e):new p(c===3?-0:0)};C.modulo=C.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?X(new r(n),r.precision,r.rounding):(ce=!1,r.modulo==9?(t=Le(n,e.abs(),0,3,1),t.s*=e.s):t=Le(n,e,0,r.modulo,1),t=t.times(e),ce=!0,n.minus(t))};C.naturalExponential=C.exp=function(){return Yc(this)};C.naturalLogarithm=C.ln=function(){return Bn(this)};C.negated=C.neg=function(){var e=new this.constructor(this);return e.s=-e.s,X(e)};C.plus=C.add=function(e){var t,n,r,i,o,a,s,c,u,l,d=this,m=d.constructor;if(e=new m(e),!d.d||!e.d)return!d.s||!e.s?e=new m(NaN):d.d||(e=new m(e.d||d.s===e.s?d:NaN)),e;if(d.s!=e.s)return e.s=-e.s,d.minus(e);if(u=d.d,l=e.d,s=m.precision,c=m.rounding,!u[0]||!l[0])return l[0]||(e=new m(d)),ce?X(e,s,c):e;if(o=xt(d.e/ne),r=xt(e.e/ne),u=u.slice(),i=o-r,i){for(i<0?(n=u,i=-i,a=l.length):(n=l,r=o,a=u.length),o=Math.ceil(s/ne),a=o>a?o+1:a+1,i>a&&(i=a,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(a=u.length,i=l.length,a-i<0&&(i=a,n=l,l=u,u=n),t=0;i;)t=(u[--i]=u[i]+l[i]+t)/nn|0,u[i]%=nn;for(t&&(u.unshift(t),++r),a=u.length;u[--a]==0;)u.pop();return e.d=u,e.e=ba(u,r),ce?X(e,s,c):e};C.precision=C.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(Ln+e);return n.d?(t=vh(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};C.round=function(){var e=this,t=e.constructor;return X(new t(e),e.e+1,t.rounding)};C.sine=C.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+ne,r.rounding=1,n=lx(r,wh(r,n)),r.precision=e,r.rounding=t,X(vn>2?n.neg():n,e,t,!0)):new r(NaN)};C.squareRoot=C.sqrt=function(){var e,t,n,r,i,o,a=this,s=a.d,c=a.e,u=a.s,l=a.constructor;if(u!==1||!s||!s[0])return new l(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);for(ce=!1,u=Math.sqrt(+a),u==0||u==1/0?(t=ht(s),(t.length+c)%2==0&&(t+="0"),u=Math.sqrt(t),c=xt((c+1)/2)-(c<0||c%2),u==1/0?t="5e"+c:(t=u.toExponential(),t=t.slice(0,t.indexOf("e")+1)+c),r=new l(t)):r=new l(u.toString()),n=(c=l.precision)+3;;)if(o=r,r=o.plus(Le(a,o,n+2,1)).times(.5),ht(o.d).slice(0,n)===(t=ht(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(X(o,c+1,0),o.times(o).eq(a))){r=o;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(X(r,c+1,1),e=!r.times(r).eq(a));break}return ce=!0,X(r,c,l.rounding,e)};C.tangent=C.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=Le(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,X(vn==2||vn==4?n.neg():n,e,t,!0)):new r(NaN)};C.times=C.mul=function(e){var t,n,r,i,o,a,s,c,u,l=this,d=l.constructor,m=l.d,g=(e=new d(e)).d;if(e.s*=l.s,!m||!m[0]||!g||!g[0])return new d(!e.s||m&&!m[0]&&!g||g&&!g[0]&&!m?NaN:!m||!g?e.s/0:e.s*0);for(n=xt(l.e/ne)+xt(e.e/ne),c=m.length,u=g.length,c<u&&(o=m,m=g,g=o,a=c,c=u,u=a),o=[],a=c+u,r=a;r--;)o.push(0);for(r=u;--r>=0;){for(t=0,i=c+r;i>r;)s=o[i]+g[r]*m[i-r-1]+t,o[i--]=s%nn|0,t=s/nn|0;o[i]=(o[i]+t)%nn|0}for(;!o[--a];)o.pop();return t?++n:o.shift(),e.d=o,e.e=ba(o,n),ce?X(e,d.precision,d.rounding):e};C.toBinary=function(e,t){return Jc(this,2,e,t)};C.toDecimalPlaces=C.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(Rt(e,0,qn),t===void 0?t=r.rounding:Rt(t,0,8),X(n,e+n.e+1,t))};C.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=hn(r,!0):(Rt(e,0,qn),t===void 0?t=i.rounding:Rt(t,0,8),r=X(new i(r),e+1,t),n=hn(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};C.toFixed=function(e,t){var n,r,i=this,o=i.constructor;return e===void 0?n=hn(i):(Rt(e,0,qn),t===void 0?t=o.rounding:Rt(t,0,8),r=X(new o(i),e+i.e+1,t),n=hn(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};C.toFraction=function(e){var t,n,r,i,o,a,s,c,u,l,d,m,g=this,p=g.d,f=g.constructor;if(!p)return new f(g);if(u=n=new f(1),r=c=new f(0),t=new f(r),o=t.e=vh(p)-g.e-1,a=o%ne,t.d[0]=tt(10,a<0?ne+a:a),e==null)e=o>0?t:u;else{if(s=new f(e),!s.isInt()||s.lt(u))throw Error(Ln+s);e=s.gt(t)?o>0?t:u:s}for(ce=!1,s=new f(ht(p)),l=f.precision,f.precision=o=p.length*ne*2;d=Le(s,t,0,1,1),i=n.plus(d.times(r)),i.cmp(e)!=1;)n=r,r=i,i=u,u=c.plus(d.times(i)),c=i,i=t,t=s.minus(d.times(i)),s=i;return i=Le(e.minus(n),r,0,1,1),c=c.plus(i.times(u)),n=n.plus(i.times(r)),c.s=u.s=g.s,m=Le(u,r,o,1).minus(g).abs().cmp(Le(c,n,o,1).minus(g).abs())<1?[u,r]:[c,n],f.precision=l,ce=!0,m};C.toHexadecimal=C.toHex=function(e,t){return Jc(this,16,e,t)};C.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:Rt(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(ce=!1,n=Le(n,e,0,t,1).times(e),ce=!0,X(n)):(e.s=n.s,n=e),n};C.toNumber=function(){return+this};C.toOctal=function(e,t){return Jc(this,8,e,t)};C.toPower=C.pow=function(e){var t,n,r,i,o,a,s=this,c=s.constructor,u=+(e=new c(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new c(tt(+s,u));if(s=new c(s),s.eq(1))return s;if(r=c.precision,o=c.rounding,e.eq(1))return X(s,r,o);if(t=xt(e.e/ne),t>=e.d.length-1&&(n=u<0?-u:u)<=ax)return i=xh(c,s,n,r),e.s<0?new c(1).div(i):X(i,r,o);if(a=s.s,a<0){if(t<e.d.length-1)return new c(NaN);if((e.d[t]&1)==0&&(a=1),s.e==0&&s.d[0]==1&&s.d.length==1)return s.s=a,s}return n=tt(+s,u),t=n==0||!isFinite(n)?xt(u*(Math.log("0."+ht(s.d))/Math.LN10+s.e+1)):new c(n+"").e,t>c.maxE+1||t<c.minE-1?new c(t>0?a/0:0):(ce=!1,c.rounding=s.s=1,n=Math.min(12,(t+"").length),i=Yc(e.times(Bn(s,r+n)),r),i.d&&(i=X(i,r+5,1),Gi(i.d,r,o)&&(t=r+10,i=X(Yc(e.times(Bn(s,t+n)),t),t+5,1),+ht(i.d).slice(r+1,r+15)+1==1e14&&(i=X(i,r+1,0)))),i.s=a,ce=!0,c.rounding=o,X(i,r,o))};C.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=hn(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(Rt(e,1,qn),t===void 0?t=i.rounding:Rt(t,0,8),r=X(new i(r),e,t),n=hn(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};C.toSignificantDigits=C.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(Rt(e,1,qn),t===void 0?t=r.rounding:Rt(t,0,8)),X(new r(n),e,t)};C.toString=function(){var e=this,t=e.constructor,n=hn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};C.truncated=C.trunc=function(){return X(new this.constructor(this),this.e+1,1)};C.valueOf=C.toJSON=function(){var e=this,t=e.constructor,n=hn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function ht(e){var t,n,r,i=e.length-1,o="",a=e[0];if(i>0){for(o+=a,t=1;t<i;t++)r=e[t]+"",n=ne-r.length,n&&(o+=Mn(n)),o+=r;a=e[t],r=a+"",n=ne-r.length,n&&(o+=Mn(n))}else if(a===0)return"0";for(;a%10===0;)a/=10;return o+a}function Rt(e,t,n){if(e!==~~e||e<t||e>n)throw Error(Ln+e)}function Gi(e,t,n,r){var i,o,a,s;for(o=e[0];o>=10;o/=10)--t;return--t<0?(t+=ne,i=0):(i=Math.ceil((t+1)/ne),t%=ne),o=tt(10,ne-t),s=e[i]%o|0,r==null?t<3?(t==0?s=s/100|0:t==1&&(s=s/10|0),a=n<4&&s==99999||n>3&&s==49999||s==5e4||s==0):a=(n<4&&s+1==o||n>3&&s+1==o/2)&&(e[i+1]/o/100|0)==tt(10,t-2)-1||(s==o/2||s==0)&&(e[i+1]/o/100|0)==0:t<4?(t==0?s=s/1e3|0:t==1?s=s/100|0:t==2&&(s=s/10|0),a=(r||n<4)&&s==9999||!r&&n>3&&s==4999):a=((r||n<4)&&s+1==o||!r&&n>3&&s+1==o/2)&&(e[i+1]/o/1e3|0)==tt(10,t-3)-1,a}function da(e,t,n){for(var r,i=[0],o,a=0,s=e.length;a<s;){for(o=i.length;o--;)i[o]*=t;for(i[0]+=Hc.indexOf(e.charAt(a++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function cx(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/_a(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=Gr(e,1,t.times(i),new e(1));for(var o=n;o--;){var a=t.times(t);t=a.times(a).minus(a).times(8).plus(1)}return e.precision-=n,t}var Le=(function(){function e(r,i,o){var a,s=0,c=r.length;for(r=r.slice();c--;)a=r[c]*i+s,r[c]=a%o|0,s=a/o|0;return s&&r.unshift(s),r}function t(r,i,o,a){var s,c;if(o!=a)c=o>a?1:-1;else for(s=c=0;s<o;s++)if(r[s]!=i[s]){c=r[s]>i[s]?1:-1;break}return c}function n(r,i,o,a){for(var s=0;o--;)r[o]-=s,s=r[o]<i[o]?1:0,r[o]=s*a+r[o]-i[o];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,o,a,s,c){var u,l,d,m,g,p,f,y,x,S,j,A,v,G,$,Pe,Re,se,V,Ue,Y=r.constructor,at=r.s==i.s?1:-1,me=r.d,ae=i.d;if(!me||!me[0]||!ae||!ae[0])return new Y(!r.s||!i.s||(me?ae&&me[0]==ae[0]:!ae)?NaN:me&&me[0]==0||!ae?at*0:at/0);for(c?(g=1,l=r.e-i.e):(c=nn,g=ne,l=xt(r.e/g)-xt(i.e/g)),V=ae.length,Re=me.length,x=new Y(at),S=x.d=[],d=0;ae[d]==(me[d]||0);d++);if(ae[d]>(me[d]||0)&&l--,o==null?(G=o=Y.precision,a=Y.rounding):s?G=o+(r.e-i.e)+1:G=o,G<0)S.push(1),p=!0;else{if(G=G/g+2|0,d=0,V==1){for(m=0,ae=ae[0],G++;(d<Re||m)&&G--;d++)$=m*c+(me[d]||0),S[d]=$/ae|0,m=$%ae|0;p=m||d<Re}else{for(m=c/(ae[0]+1)|0,m>1&&(ae=e(ae,m,c),me=e(me,m,c),V=ae.length,Re=me.length),Pe=V,j=me.slice(0,V),A=j.length;A<V;)j[A++]=0;Ue=ae.slice(),Ue.unshift(0),se=ae[0],ae[1]>=c/2&&++se;do m=0,u=t(ae,j,V,A),u<0?(v=j[0],V!=A&&(v=v*c+(j[1]||0)),m=v/se|0,m>1?(m>=c&&(m=c-1),f=e(ae,m,c),y=f.length,A=j.length,u=t(f,j,y,A),u==1&&(m--,n(f,V<y?Ue:ae,y,c))):(m==0&&(u=m=1),f=ae.slice()),y=f.length,y<A&&f.unshift(0),n(j,f,A,c),u==-1&&(A=j.length,u=t(ae,j,V,A),u<1&&(m++,n(j,V<A?Ue:ae,A,c))),A=j.length):u===0&&(m++,j=[0]),S[d++]=m,u&&j[0]?j[A++]=me[Pe]||0:(j=[me[Pe]],A=1);while((Pe++<Re||j[0]!==void 0)&&G--);p=j[0]!==void 0}S[0]||S.shift()}if(g==1)x.e=l,gh=p;else{for(d=1,m=S[0];m>=10;m/=10)d++;x.e=d+l*g-1,X(x,s?o+x.e+1:o,a,p)}return x}})();function X(e,t,n,r){var i,o,a,s,c,u,l,d,m,g=e.constructor;e:if(t!=null){if(d=e.d,!d)return e;for(i=1,s=d[0];s>=10;s/=10)i++;if(o=t-i,o<0)o+=ne,a=t,l=d[m=0],c=l/tt(10,i-a-1)%10|0;else if(m=Math.ceil((o+1)/ne),s=d.length,m>=s)if(r){for(;s++<=m;)d.push(0);l=c=0,i=1,o%=ne,a=o-ne+1}else break e;else{for(l=s=d[m],i=1;s>=10;s/=10)i++;o%=ne,a=o-ne+i,c=a<0?0:l/tt(10,i-a-1)%10|0}if(r=r||t<0||d[m+1]!==void 0||(a<0?l:l%tt(10,i-a-1)),u=n<4?(c||r)&&(n==0||n==(e.s<0?3:2)):c>5||c==5&&(n==4||r||n==6&&(o>0?a>0?l/tt(10,i-a):0:d[m-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,u?(t-=e.e+1,d[0]=tt(10,(ne-t%ne)%ne),e.e=-t||0):d[0]=e.e=0,e;if(o==0?(d.length=m,s=1,m--):(d.length=m+1,s=tt(10,ne-o),d[m]=a>0?(l/tt(10,i-a)%tt(10,a)|0)*s:0),u)for(;;)if(m==0){for(o=1,a=d[0];a>=10;a/=10)o++;for(a=d[0]+=s,s=1;a>=10;a/=10)s++;o!=s&&(e.e++,d[0]==nn&&(d[0]=1));break}else{if(d[m]+=s,d[m]!=nn)break;d[m--]=0,s=1}for(o=d.length;d[--o]===0;)d.pop()}return ce&&(e.e>g.maxE?(e.d=null,e.e=NaN):e.e<g.minE&&(e.e=0,e.d=[0])),e}function hn(e,t,n){if(!e.isFinite())return Ah(e);var r,i=e.e,o=ht(e.d),a=o.length;return t?(n&&(r=n-a)>0?o=o.charAt(0)+"."+o.slice(1)+Mn(r):a>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(e.e<0?"e":"e+")+e.e):i<0?(o="0."+Mn(-i-1)+o,n&&(r=n-a)>0&&(o+=Mn(r))):i>=a?(o+=Mn(i+1-a),n&&(r=n-i-1)>0&&(o=o+"."+Mn(r))):((r=i+1)<a&&(o=o.slice(0,r)+"."+o.slice(r)),n&&(r=n-a)>0&&(i+1===a&&(o+="."),o+=Mn(r))),o}function ba(e,t){var n=e[0];for(t*=ne;n>=10;n/=10)t++;return t}function ha(e,t,n){if(t>sx)throw ce=!0,n&&(e.precision=n),Error(bh);return X(new e(ma),t,1,!0)}function fn(e,t,n){if(t>Zc)throw Error(bh);return X(new e(fa),t,n,!0)}function vh(e){var t=e.length-1,n=t*ne+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function Mn(e){for(var t="";e--;)t+="0";return t}function xh(e,t,n,r){var i,o=new e(1),a=Math.ceil(r/ne+4);for(ce=!1;;){if(n%2&&(o=o.times(t),fh(o.d,a)&&(i=!0)),n=xt(n/2),n===0){n=o.d.length-1,i&&o.d[n]===0&&++o.d[n];break}t=t.times(t),fh(t.d,a)}return ce=!0,o}function mh(e){return e.d[e.d.length-1]&1}function Ih(e,t,n){for(var r,i,o=new e(t[0]),a=0;++a<t.length;){if(i=new e(t[a]),!i.s){o=i;break}r=o.cmp(i),(r===n||r===0&&o.s===n)&&(o=i)}return o}function Yc(e,t){var n,r,i,o,a,s,c,u=0,l=0,d=0,m=e.constructor,g=m.rounding,p=m.precision;if(!e.d||!e.d[0]||e.e>17)return new m(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(ce=!1,c=p):c=t,s=new m(.03125);e.e>-2;)e=e.times(s),d+=5;for(r=Math.log(tt(2,d))/Math.LN10*2+5|0,c+=r,n=o=a=new m(1),m.precision=c;;){if(o=X(o.times(e),c,1),n=n.times(++l),s=a.plus(Le(o,n,c,1)),ht(s.d).slice(0,c)===ht(a.d).slice(0,c)){for(i=d;i--;)a=X(a.times(a),c,1);if(t==null)if(u<3&&Gi(a.d,c-r,g,u))m.precision=c+=10,n=o=s=new m(1),l=0,u++;else return X(a,m.precision=p,g,ce=!0);else return m.precision=p,a}a=s}}function Bn(e,t){var n,r,i,o,a,s,c,u,l,d,m,g=1,p=10,f=e,y=f.d,x=f.constructor,S=x.rounding,j=x.precision;if(f.s<0||!y||!y[0]||!f.e&&y[0]==1&&y.length==1)return new x(y&&!y[0]?-1/0:f.s!=1?NaN:y?0:f);if(t==null?(ce=!1,l=j):l=t,x.precision=l+=p,n=ht(y),r=n.charAt(0),Math.abs(o=f.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(e),n=ht(f.d),r=n.charAt(0),g++;o=f.e,r>1?(f=new x("0."+n),o++):f=new x(r+"."+n.slice(1))}else return u=ha(x,l+2,j).times(o+""),f=Bn(new x(r+"."+n.slice(1)),l-p).plus(u),x.precision=j,t==null?X(f,j,S,ce=!0):f;for(d=f,c=a=f=Le(f.minus(1),f.plus(1),l,1),m=X(f.times(f),l,1),i=3;;){if(a=X(a.times(m),l,1),u=c.plus(Le(a,new x(i),l,1)),ht(u.d).slice(0,l)===ht(c.d).slice(0,l))if(c=c.times(2),o!==0&&(c=c.plus(ha(x,l+2,j).times(o+""))),c=Le(c,new x(g),l,1),t==null)if(Gi(c.d,l-p,S,s))x.precision=l+=p,u=a=f=Le(d.minus(1),d.plus(1),l,1),m=X(f.times(f),l,1),i=s=1;else return X(c,x.precision=j,S,ce=!0);else return x.precision=j,c;c=u,i+=2}}function Ah(e){return String(e.s*e.s/0)}function pa(e,t){var n,r,i;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(i=t.length;t.charCodeAt(i-1)===48;--i);if(t=t.slice(r,i),t){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%ne,n<0&&(r+=ne),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=ne;r<i;)e.d.push(+t.slice(r,r+=ne));t=t.slice(r),r=ne-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),ce&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}function ux(e,t){var n,r,i,o,a,s,c,u,l;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),Sh.test(t))return pa(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(ix.test(t))n=16,t=t.toLowerCase();else if(rx.test(t))n=2;else if(ox.test(t))n=8;else throw Error(Ln+t);for(o=t.search(/p/i),o>0?(c=+t.slice(o+1),t=t.substring(2,o)):t=t.slice(2),o=t.indexOf("."),a=o>=0,r=e.constructor,a&&(t=t.replace(".",""),s=t.length,o=s-o,i=xh(r,new r(n),o,o*2)),u=da(t,n,nn),l=u.length-1,o=l;u[o]===0;--o)u.pop();return o<0?new r(e.s*0):(e.e=ba(u,l),e.d=u,ce=!1,a&&(e=Le(e,i,s*4)),c&&(e=e.times(Math.abs(c)<54?tt(2,c):rn.pow(2,c))),ce=!0,e)}function lx(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:Gr(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/_a(5,n)),t=Gr(e,2,t,t);for(var i,o=new e(5),a=new e(16),s=new e(20);n--;)i=t.times(t),t=t.times(o.plus(i.times(a.times(i).minus(s))));return t}function Gr(e,t,n,r,i){var o,a,s,c,u=1,l=e.precision,d=Math.ceil(l/ne);for(ce=!1,c=n.times(n),s=new e(r);;){if(a=Le(s.times(c),new e(t++*t++),l,1),s=i?r.plus(a):r.minus(a),r=Le(a.times(c),new e(t++*t++),l,1),a=s.plus(r),a.d[d]!==void 0){for(o=d;a.d[o]===s.d[o]&&o--;);if(o==-1)break}o=s,s=r,r=a,a=o,u++}return ce=!0,a.d.length=d+1,a}function _a(e,t){for(var n=e;--t;)n*=e;return n}function wh(e,t){var n,r=t.s<0,i=fn(e,e.precision,1),o=i.times(.5);if(t=t.abs(),t.lte(o))return vn=r?4:1,t;if(n=t.divToInt(i),n.isZero())vn=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(o))return vn=mh(n)?r?2:3:r?4:1,t;vn=mh(n)?r?1:4:r?3:2}return t.minus(i).abs()}function Jc(e,t,n,r){var i,o,a,s,c,u,l,d,m,g=e.constructor,p=n!==void 0;if(p?(Rt(n,1,qn),r===void 0?r=g.rounding:Rt(r,0,8)):(n=g.precision,r=g.rounding),!e.isFinite())l=Ah(e);else{for(l=hn(e),a=l.indexOf("."),p?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,a>=0&&(l=l.replace(".",""),m=new g(1),m.e=l.length-a,m.d=da(hn(m),10,i),m.e=m.d.length),d=da(l,10,i),o=c=d.length;d[--c]==0;)d.pop();if(!d[0])l=p?"0p+0":"0";else{if(a<0?o--:(e=new g(e),e.d=d,e.e=o,e=Le(e,m,n,r,0,i),d=e.d,o=e.e,u=gh),a=d[n],s=i/2,u=u||d[n+1]!==void 0,u=r<4?(a!==void 0||u)&&(r===0||r===(e.s<0?3:2)):a>s||a===s&&(r===4||u||r===6&&d[n-1]&1||r===(e.s<0?8:7)),d.length=n,u)for(;++d[--n]>i-1;)d[n]=0,n||(++o,d.unshift(1));for(c=d.length;!d[c-1];--c);for(a=0,l="";a<c;a++)l+=Hc.charAt(d[a]);if(p){if(c>1)if(t==16||t==8){for(a=t==16?4:3,--c;c%a;c++)l+="0";for(d=da(l,i,t),c=d.length;!d[c-1];--c);for(a=1,l="1.";a<c;a++)l+=Hc.charAt(d[a])}else l=l.charAt(0)+"."+l.slice(1);l=l+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)l="0"+l;l="0."+l}else if(++o>c)for(o-=c;o--;)l+="0";else o<c&&(l=l.slice(0,o)+"."+l.slice(o))}l=(t==16?"0x":t==2?"0b":t==8?"0o":"")+l}return e.s<0?"-"+l:l}function fh(e,t){if(e.length>t)return e.length=t,!0}function dx(e){return new this(e).abs()}function px(e){return new this(e).acos()}function mx(e){return new this(e).acosh()}function fx(e,t){return new this(e).plus(t)}function hx(e){return new this(e).asin()}function gx(e){return new this(e).asinh()}function bx(e){return new this(e).atan()}function _x(e){return new this(e).atanh()}function yx(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,o=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=fn(this,o,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?fn(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=fn(this,o,1).times(.5),n.s=e.s):t.s<0?(this.precision=o,this.rounding=1,n=this.atan(Le(e,t,o,1)),t=fn(this,o,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(Le(e,t,o,1)),n}function Sx(e){return new this(e).cbrt()}function vx(e){return X(e=new this(e),e.e+1,2)}function xx(e,t,n){return new this(e).clamp(t,n)}function Ix(e){if(!e||typeof e!="object")throw Error(ga+"Object expected");var t,n,r,i=e.defaults===!0,o=["precision",1,qn,"rounding",0,8,"toExpNeg",-Vr,0,"toExpPos",0,Vr,"maxE",0,Vr,"minE",-Vr,0,"modulo",0,9];for(t=0;t<o.length;t+=3)if(n=o[t],i&&(this[n]=Qc[n]),(r=e[n])!==void 0)if(xt(r)===r&&r>=o[t+1]&&r<=o[t+2])this[n]=r;else throw Error(Ln+n+": "+r);if(n="crypto",i&&(this[n]=Qc[n]),(r=e[n])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(_h);else this[n]=!1;else throw Error(Ln+n+": "+r);return this}function Ax(e){return new this(e).cos()}function wx(e){return new this(e).cosh()}function Ph(e){var t,n,r;function i(o){var a,s,c,u=this;if(!(u instanceof i))return new i(o);if(u.constructor=i,hh(o)){u.s=o.s,ce?!o.d||o.e>i.maxE?(u.e=NaN,u.d=null):o.e<i.minE?(u.e=0,u.d=[0]):(u.e=o.e,u.d=o.d.slice()):(u.e=o.e,u.d=o.d?o.d.slice():o.d);return}if(c=typeof o,c==="number"){if(o===0){u.s=1/o<0?-1:1,u.e=0,u.d=[0];return}if(o<0?(o=-o,u.s=-1):u.s=1,o===~~o&&o<1e7){for(a=0,s=o;s>=10;s/=10)a++;ce?a>i.maxE?(u.e=NaN,u.d=null):a<i.minE?(u.e=0,u.d=[0]):(u.e=a,u.d=[o]):(u.e=a,u.d=[o]);return}if(o*0!==0){o||(u.s=NaN),u.e=NaN,u.d=null;return}return pa(u,o.toString())}if(c==="string")return(s=o.charCodeAt(0))===45?(o=o.slice(1),u.s=-1):(s===43&&(o=o.slice(1)),u.s=1),Sh.test(o)?pa(u,o):ux(u,o);if(c==="bigint")return o<0?(o=-o,u.s=-1):u.s=1,pa(u,o.toString());throw Error(Ln+o)}if(i.prototype=C,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=Ix,i.clone=Ph,i.isDecimal=hh,i.abs=dx,i.acos=px,i.acosh=mx,i.add=fx,i.asin=hx,i.asinh=gx,i.atan=bx,i.atanh=_x,i.atan2=yx,i.cbrt=Sx,i.ceil=vx,i.clamp=xx,i.cos=Ax,i.cosh=wx,i.div=Px,i.exp=Ox,i.floor=Cx,i.hypot=Ex,i.ln=Tx,i.log=Rx,i.log10=kx,i.log2=jx,i.max=Dx,i.min=Nx,i.mod=Fx,i.mul=Ux,i.pow=Mx,i.random=Bx,i.round=Lx,i.sign=qx,i.sin=Vx,i.sinh=Gx,i.sqrt=$x,i.sub=Kx,i.sum=Wx,i.tan=Hx,i.tanh=Qx,i.trunc=Zx,e===void 0&&(e={}),e&&e.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function Px(e,t){return new this(e).div(t)}function Ox(e){return new this(e).exp()}function Cx(e){return X(e=new this(e),e.e+1,3)}function Ex(){var e,t,n=new this(0);for(ce=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return ce=!0,new this(1/0);n=t}return ce=!0,n.sqrt()}function hh(e){return e instanceof rn||e&&e.toStringTag===yh||!1}function Tx(e){return new this(e).ln()}function Rx(e,t){return new this(e).log(t)}function jx(e){return new this(e).log(2)}function kx(e){return new this(e).log(10)}function Dx(){return Ih(this,arguments,-1)}function Nx(){return Ih(this,arguments,1)}function Fx(e,t){return new this(e).mod(t)}function Ux(e,t){return new this(e).mul(t)}function Mx(e,t){return new this(e).pow(t)}function Bx(e){var t,n,r,i,o=0,a=new this(1),s=[];if(e===void 0?e=this.precision:Rt(e,1,qn),r=Math.ceil(e/ne),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));o<r;)i=t[o],i>=429e7?t[o]=crypto.getRandomValues(new Uint32Array(1))[0]:s[o++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);o<r;)i=t[o]+(t[o+1]<<8)+(t[o+2]<<16)+((t[o+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,o):(s.push(i%1e7),o+=4);o=r/4}else throw Error(_h);else for(;o<r;)s[o++]=Math.random()*1e7|0;for(r=s[--o],e%=ne,r&&e&&(i=tt(10,ne-e),s[o]=(r/i|0)*i);s[o]===0;o--)s.pop();if(o<0)n=0,s=[0];else{for(n=-1;s[0]===0;n-=ne)s.shift();for(r=1,i=s[0];i>=10;i/=10)r++;r<ne&&(n-=ne-r)}return a.e=n,a.d=s,a}function Lx(e){return X(e=new this(e),e.e+1,this.rounding)}function qx(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function Vx(e){return new this(e).sin()}function Gx(e){return new this(e).sinh()}function $x(e){return new this(e).sqrt()}function Kx(e,t){return new this(e).sub(t)}function Wx(){var e=0,t=arguments,n=new this(t[e]);for(ce=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return ce=!0,X(n,this.precision,this.rounding)}function Hx(e){return new this(e).tan()}function Qx(e){return new this(e).tanh()}function Zx(e){return X(e=new this(e),e.e+1,1)}C[Symbol.for("nodejs.util.inspect.custom")]=C.toString;C[Symbol.toStringTag]="Decimal";var rn=C.constructor=Ph(Qc);ma=new rn(ma);fa=new rn(fa);var{PAYLOAD_BYTES:Yx}={PAYLOAD_BYTES:20},{KSUID_EPOCH:Jx}={KSUID_EPOCH:14e8},{getRandomBytes:Xx}={getRandomBytes:({size:t})=>{let n=new Uint8Array(t);return globalThis.crypto.getRandomValues(n),n}},{ALPHABET:zx}={ALPHABET:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},{ENCODED_LENGTH:eI}={ENCODED_LENGTH:27},{base62Encode:tI}=(e=>({base62Encode:({bytes:n,padTo:r})=>{let i=[],o=new Uint8Array(n),a=!1;for(;!a;){a=!0;let s=0;for(let c=0;c<o.length;c++){let u=s*256+o[c];o[c]=Math.floor(u/62),s=u%62,o[c]!==0&&(a=!1)}i.push(s)}for(i.reverse();i.length<r;)i.unshift(0);return i.map(s=>e[s]).join("")}}))(zx),{generateKsuid:Oh}=((e,t,n,r,i)=>({generateKsuid:({prefix:a=""}={})=>{let s=new Uint8Array(e),c=Math.floor(Date.now()/1e3)-t;s[0]=c>>>24&255,s[1]=c>>>16&255,s[2]=c>>>8&255,s[3]=c&255;let u=n({size:16});s.set(u,4);let l=r({bytes:s,padTo:i});return`${a}${l}`}}))(Yx,Jx,Xx,tI,eI);var Ch={randomSync:()=>({string:Oh({})})};import{z as Ae}from"zod/v4";var nI=202,rI=502,iI=400,oI=409,aI=100,sI=201,cI=417;var uI=403,lI=504,dI=410,pI=505,mI=418,fI=419,hI=507,gI=500,bI=411,_I=423,yI=420,SI=405,vI=301,xI=302,II=207,AI=300,wI=511,PI=204,OI=203,CI=406,EI=404,TI=501,RI=304,jI=200,kI=206,DI=402,NI=308,FI=412,UI=428,MI=102,BI=407,LI=431,qI=408,VI=413,GI=414,$I=416,KI=205,WI=303,HI=503,QI=101,ZI=307,YI=429,JI=401,XI=422,zI=415,eA=305,Eh={ACCEPTED:nI,BAD_GATEWAY:rI,BAD_REQUEST:iI,CONFLICT:oI,CONTINUE:aI,CREATED:sI,EXPECTATION_FAILED:cI,FORBIDDEN:uI,GATEWAY_TIMEOUT:lI,GONE:dI,HTTP_VERSION_NOT_SUPPORTED:pI,IM_A_TEAPOT:mI,INSUFFICIENT_SPACE_ON_RESOURCE:fI,INSUFFICIENT_STORAGE:hI,INTERNAL_SERVER_ERROR:gI,LENGTH_REQUIRED:bI,LOCKED:_I,METHOD_FAILURE:yI,METHOD_NOT_ALLOWED:SI,MOVED_PERMANENTLY:vI,MOVED_TEMPORARILY:xI,MULTI_STATUS:II,MULTIPLE_CHOICES:AI,NETWORK_AUTHENTICATION_REQUIRED:wI,NO_CONTENT:PI,NON_AUTHORITATIVE_INFORMATION:OI,NOT_ACCEPTABLE:CI,NOT_FOUND:EI,NOT_IMPLEMENTED:TI,NOT_MODIFIED:RI,OK:jI,PARTIAL_CONTENT:kI,PAYMENT_REQUIRED:DI,PERMANENT_REDIRECT:NI,PRECONDITION_FAILED:FI,PRECONDITION_REQUIRED:UI,PROCESSING:MI,PROXY_AUTHENTICATION_REQUIRED:BI,REQUEST_HEADER_FIELDS_TOO_LARGE:LI,REQUEST_TIMEOUT:qI,REQUEST_TOO_LONG:VI,REQUEST_URI_TOO_LONG:GI,REQUESTED_RANGE_NOT_SATISFIABLE:$I,RESET_CONTENT:KI,SEE_OTHER:WI,SERVICE_UNAVAILABLE:HI,SWITCHING_PROTOCOLS:QI,TEMPORARY_REDIRECT:ZI,TOO_MANY_REQUESTS:YI,UNAUTHORIZED:JI,UNPROCESSABLE_ENTITY:XI,UNSUPPORTED_MEDIA_TYPE:zI,USE_PROXY:eA};var Th={202:"Accepted",502:"Bad Gateway",400:"Bad Request",409:"Conflict",100:"Continue",201:"Created",417:"Expectation Failed",424:"Failed Dependency",403:"Forbidden",504:"Gateway Timeout",410:"Gone",505:"HTTP Version Not Supported",418:"I'm a teapot",419:"Insufficient Space on Resource",507:"Insufficient Storage",500:"Internal Server Error",411:"Length Required",423:"Locked",420:"Method Failure",405:"Method Not Allowed",301:"Moved Permanently",302:"Moved Temporarily",207:"Multi-Status",300:"Multiple Choices",511:"Network Authentication Required",204:"No Content",203:"Non Authoritative Information",406:"Not Acceptable",404:"Not Found",501:"Not Implemented",304:"Not Modified",200:"OK",206:"Partial Content",402:"Payment Required",308:"Permanent Redirect",412:"Precondition Failed",428:"Precondition Required",102:"Processing",103:"Early Hints",426:"Upgrade Required",407:"Proxy Authentication Required",431:"Request Header Fields Too Large",408:"Request Timeout",413:"Request Entity Too Large",414:"Request-URI Too Long",416:"Requested Range Not Satisfiable",205:"Reset Content",303:"See Other",503:"Service Unavailable",101:"Switching Protocols",307:"Temporary Redirect",429:"Too Many Requests",401:"Unauthorized",451:"Unavailable For Legal Reasons",422:"Unprocessable Entity",415:"Unsupported Media Type",305:"Use Proxy",421:"Misdirected Request"},Rh={Accepted:202,"Bad Gateway":502,"Bad Request":400,Conflict:409,Continue:100,Created:201,"Expectation Failed":417,"Failed Dependency":424,Forbidden:403,"Gateway Timeout":504,Gone:410,"HTTP Version Not Supported":505,"I'm a teapot":418,"Insufficient Space on Resource":419,"Insufficient Storage":507,"Internal Server Error":500,"Length Required":411,Locked:423,"Method Failure":420,"Method Not Allowed":405,"Moved Permanently":301,"Moved Temporarily":302,"Multi-Status":207,"Multiple Choices":300,"Network Authentication Required":511,"No Content":204,"Non Authoritative Information":203,"Not Acceptable":406,"Not Found":404,"Not Implemented":501,"Not Modified":304,OK:200,"Partial Content":206,"Payment Required":402,"Permanent Redirect":308,"Precondition Failed":412,"Precondition Required":428,Processing:102,"Early Hints":103,"Upgrade Required":426,"Proxy Authentication Required":407,"Request Header Fields Too Large":431,"Request Timeout":408,"Request Entity Too Large":413,"Request-URI Too Long":414,"Requested Range Not Satisfiable":416,"Reset Content":205,"See Other":303,"Service Unavailable":503,"Switching Protocols":101,"Temporary Redirect":307,"Too Many Requests":429,Unauthorized:401,"Unavailable For Legal Reasons":451,"Unprocessable Entity":422,"Unsupported Media Type":415,"Use Proxy":305,"Misdirected Request":421};function tA(e){var t=Th[e.toString()];if(!t)throw new Error("Status code does not exist: "+e);return t}function jh(e){var t=Rh[e];if(!t)throw new Error("Reason phrase does not exist: "+e);return t}var kh=tA;var Vn;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(Vn||(Vn={}));var ya=function(){return ya=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},ya.apply(this,arguments)},WM=ya(ya({},Eh),{getStatusCode:jh,getStatusText:kh});var{generateId:$r}=(e=>({generateId:n=>n?`${n}_${e.randomSync().string}`:e.randomSync().string}))(Ch),{BILLING_CONTROL_KEYS:Sa}={BILLING_CONTROL_KEYS:["auto_topups","spend_limits","usage_limits","usage_alerts","overage_allowed"]},{PurchaseLimitInterval:nA}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{entToPrice:Dh}={entToPrice:({ent:t,prices:n})=>{let r=n.filter(i=>i.entitlement_id===t.id);return r.find(i=>i.internal_product_id===t.internal_product_id)??r[0]}},{nullish:Yt}={nullish:t=>t==null},{FeatureType:It}=(()=>{var e;return(function(t){t.Boolean="boolean",t.Metered="metered",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{FeatureType:e}})(),{AllowanceType:va}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{Infinite:$i}={Infinite:"inf"},{EntInterval:Kr}=(()=>{var e;return(function(t){t.Lifetime="lifetime",t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{EntInterval:e}})(),{BillingInterval:xn}=(()=>{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}})(),{fixedCurrenciesToApi:rA}={fixedCurrenciesToApi:t=>{if(!t)return;let n=Object.entries(t);if(n.length!==0)return n.map(([r,i])=>({currency:r,amount:i.amount??0}))}},{usageCurrenciesToTiers:iA}={usageCurrenciesToTiers:(t,n)=>{if(!t||n<=0)return;let r=Object.entries(t);if(r.length===0)return;let i=Array.from({length:n},()=>[]);for(let[o,a]of r)(a.usage_tiers??[]).forEach((s,c)=>{c<n&&i[c].push({currency:o,amount:s.amount,...s.flat_amount!==void 0?{flat_amount:s.flat_amount}:{}})});return i}},{TierInfinite:Xc}={TierInfinite:"inf"},{FeatureUsageType:Gn}=(()=>{var e;return(function(t){t.Single="single_use",t.Continuous="continuous_use"})(e||(e={})),{FeatureUsageType:e}})(),{PriceType:Wr}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Usage="usage"})(e||(e={})),{PriceType:e}})(),{BillingType:Hr}=(()=>{var e;return(function(t){t.OneOff="one_off",t.FixedCycle="fixed_cycle",t.UsageBelowThreshold="usage_below_threshold",t.UsageInAdvance="usage_in_advance",t.UsageInArrear="usage_in_arrear",t.InArrearProrated="in_arrear_prorated"})(e||(e={})),{BillingType:e}})(),{BillWhen:Ki}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:$n}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProductItemFeatureType:In}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{UsageModel:Qr}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{InternalError:oA}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=500,data:o}){super(n),this.name="InternalError",this.code=r||"internal_error",this.statusCode=i,this.data=o}}return{InternalError:e}})(),{getItemFeatureType:Nh}=((e,t)=>({getItemFeatureType:({item:r,features:i})=>{let o=i.find(a=>a.id===r.feature_id);if(o)return o.type===e.Boolean?t.Static:o.type===e.CreditSystem?t.SingleUse:o.config?.usage_type}}))(It,In),{billingControlsFromColumns:Fh}=(e=>({billingControlsFromColumns:n=>n?Object.fromEntries(e.flatMap(r=>n[r]==null?[]:[[r,n[r]]])):{}}))(Sa),{nullish:Zr}={nullish:t=>t==null},{RecaseError:jt}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=400,data:o}){super(n),this.name="RecaseError",this.code=r||"invalid_request",this.statusCode=i,this.data=o}}return{RecaseError:e}})(),{ErrCode:qt}={ErrCode:{PlanAlreadyAttached:"plan_already_attached",PendingPlanConflict:"pending_plan_conflict",IdempotencyKeyAlreadyExists:"idempotency_key_already_exists",IdempotencyKeyNotFound:"idempotency_key_not_found",DuplicateIdempotencyKey:"duplicate_idempotency_key",InvalidApiVersion:"invalid_api_version",NoSecretKey:"no_secret_key",InvalidSecretKey:"invalid_secret_key",NoAuthHeader:"no_auth_header",InvalidAuthHeader:"invalid_auth_header",FailedToVerifySecretKey:"failed_to_verify_secret_key",FailedToFetchKeyFromAutumn:"failed_to_fetch_key_from_autumn",InsufficientScopes:"insufficient_scopes",NoPublishableKey:"no_publishable_key",InvalidPublishableKey:"invalid_publishable_key",GetOrgFromPublishableKeyFailed:"get_org_from_publishable_key_failed",EndpointNotPublic:"endpoint_not_public",FailedToVerifyPublishableKey:"failed_to_verify_publishable_key",InvalidInputs:"invalid_inputs",InvalidRequest:"invalid_request",InvalidExpand:"invalid_expand",InvalidOptions:"invalid_options",InvalidCursor:"invalid_cursor",RequestTemporarilyDisabled:"request_temporarily_disabled",OrgNotFound:"org_not_found",OrgHasCustomers:"org_has_customers",MigrationNotFound:"migration_not_found",FeatureNotFound:"feature_not_found",InvalidFeature:"invalid_feature",DuplicateFeatureId:"duplicate_feature_id",InvalidEventName:"invalid_event_name",FeatureLimitReached:"feature_limit_reached",InternalError:"internal_error",DuplicateCustomerId:"duplicate_customer_id",StripeKeyNotFound:"stripe_key_not_found",DuplicateCustomerEmail:"duplicate_customer_email",StripeError:"stripe_error",StripeKeyInvalid:"stripe_key_invalid",StripeAccountMismatch:"stripe_account_mismatch",StripeConfigNotFound:"stripe_config_not_found",StripeDeleteCustomerFailed:"stripe_delete_customer_failed",StripeCreateCustomerFailed:"stripe_create_customer_failed",StripeCreateProductFailed:"stripe_create_product_failed",StripeCancelSubscriptionFailed:"stripe_cancel_subscription_failed",StripeGetPaymentMethodFailed:"stripe_get_payment_method_failed",StripeCardDeclined:"stripe_card_declined",StripeUpdateSubscriptionFailed:"stripe_update_subscription_failed",StripeCancelSubscriptionScheduleFailed:"stripe_cancel_subscription_schedule_failed",StripeCreateSubscriptionFailed:"stripe_create_subscription_failed",PriceNotFound:"price_not_found",CreatePriceFailed:"create_price_failed",InvalidPrice:"invalid_price",InvalidPriceId:"invalid_price_id",InvalidPriceOptions:"invalid_price_options",InvalidPriceConfig:"invalid_price_config",CusPriceNotFound:"cus_price_not_found",InvalidCustomer:"invalid_customer",CreateCustomerFailed:"create_customer_failed",CustomerNotFound:"customer_not_found",CustomersNotFound:"customers_not_found",CustomerAlreadyHasProduct:"customer_already_has_product",CustomerHasNoPaymentMethod:"customer_has_no_payment_method",CustomerHasNoBaseProduct:"customer_has_no_base_product",AttachProductToCustomerFailed:"attach_product_to_customer_failed",CustomerEntitlementNotFound:"customer_entitlement_not_found",MultipleCustomersFound:"multiple_customers_found",InvalidUpdateCustomerParams:"invalid_update_customer_params",CurrencyMismatch:"currency_mismatch",CreateStripeProductFailed:"create_stripe_product_failed",DeleteStripeProductFailed:"delete_stripe_product_failed",CreateStripeSubscriptionFailed:"create_stripe_subscription_failed",CusProductNotFound:"cus_product_not_found",DuplicateSubscriptionId:"duplicate_subscription_id",InvalidEntitlement:"invalid_entitlement",CreateEntitlementFailed:"create_entitlement_failed",DeleteEntitlementFailed:"delete_entitlement_failed",InsufficientBalance:"insufficient_balance",CreateInvoiceFailed:"create_invoice_failed",InvalidEvent:"invalid_event",CreateEventFailed:"create_event_failed",DuplicateEvent:"duplicate_event",NoActiveCusProducts:"no_active_cus_products",GetCusProductsFailed:"get_cus_products_failed",GetCusPriceFailed:"get_cus_price_failed",PayInvoiceFailed:"invoice_payment_failed",InvalidReward:"invalid_reward",ProductNotInStripe:"product_not_in_stripe",DuplicateRewardId:"duplicate_reward_id",DuplicatePromoCode:"duplicate_promo_code",PromoCodeAlreadyExistsInStripe:"promo_code_already_exists_in_stripe",PromoCodeFirstTimeOnly:"promo_code_first_time_only",EntityNotFound:"entity_not_found",EntityAlreadyDeleted:"entity_already_deleted",ReferralCodeMaxRedemptionsReached:"referral_code_max_redemptions_reached",ReferralNotFound:"referral_not_found",CustomerAlreadyRedeemedReferralCode:"customer_already_redeemed_referral_code",CustomerCannotRedeemOwnCode:"customer_cannot_redeem_own_code",InvalidProductItem:"invalid_product_item",EntityIdRequired:"entity_id_required",LockAlreadyExists:"lock_already_exists",InsertSubscriptionFailed:"insert_subscription_failed",UpdateSubscriptionFailed:"update_subscription_failed",RewardNotFound:"reward_not_found",RewardProgramNotFound:"reward_program_not_found",InsertRewardProgramFailed:"insert_reward_program_failed",InsertReferralCodeFailed:"insert_referral_code_failed",ReferralCodeNotFound:"referral_code_not_found",UpdateRewardRedemptionFailed:"update_reward_redemption_failed",RewardRedemptionNotFound:"reward_redemption_not_found",InsertRewardRedemptionFailed:"insert_reward_redemption_failed",InsertMigrationJobFailed:"insert_migration_job_failed",InsertMigrationErrorFailed:"insert_migration_error_failed",MigrationJobNotFound:"migration_job_not_found",MigrationAlreadyInProgress:"migration_already_in_progress",CustomerExportInProgress:"customer_export_in_progress",SupabaseNotFound:"supabase_not_found",EntityBalanceNotFound:"entity_balance_not_found",TinybirdDisabled:"tinybird_disabled",ClickHouseDisabled:"tinybird_disabled",PaymentMethodNotFound:"payment_method_not_found",VercelSubscriptionAlreadyExists:"vercel_subscription_already_exists",VercelSubscriptionNotFound:"vercel_subscription_not_found",VercelResourceNotFound:"vercel_resource_not_found",ProductNotFound:"product_not_found",NestedVariantNotAllowed:"nested_variant_not_allowed",CannotForkArchivedBase:"cannot_fork_archived_base",ProductIdAlreadyExists:"product_id_already_exists",DuplicateVersionSlug:"duplicate_version_slug",CannotPreviewOnVariant:"cannot_preview_on_variant",InvalidPropagationTarget:"invalid_propagation_target",ConflictingVariantAnchor:"conflicting_variant_anchor",VariantCrossPlanAnchor:"variant_cross_plan_anchor",TooManyVariants:"too_many_variants",ConflictingVersionFlags:"conflicting_version_flags",VariantCannotBeDefault:"variant_cannot_be_default",HistoricalPlanVersionCannotBeDefault:"historical_plan_version_cannot_be_default",UnderMaintenance:"under_maintenance"}},{validateFeatureId:aA}=((e,t)=>({validateFeatureId:r=>{if(!r.match(/^[a-zA-Z0-9_-]+$/))throw new e({message:"Feature ID can only contain alphanumeric characters, underscores, and hyphens",code:t.InvalidFeature,statusCode:400})}}))(jt,qt),{notNullish:Yr}=(e=>({notNullish:n=>!e(n)}))(Zr),{keyToTitle:Uh}={keyToTitle:t=>t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())},{AggregateType:sA}=(()=>{var e;return(function(t){t.Sum="sum"})(e||(e={})),{AggregateType:e}})(),{ProductItemType:cA}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ApiFeatureType:uA}=(()=>{var e;return(function(t){t.Static="static",t.Boolean="boolean",t.SingleUsage="single_use",t.ContinuousUse="continuous_use",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{ApiFeatureType:e}})(),{ProductItemInterval:zc}=(()=>{var e;return(function(t){t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{ProductItemInterval:e}})(),{COMMON:Mh}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:lA}={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:dA}=(e=>({COMMON_SET:new Set(e)}))(Mh),{hasNoDuplicateCurrencies:Bh}={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:Lh}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{TierBehavior:xa}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{OnIncrease:Jr}=(()=>{var e;return(function(t){t.BillImmediately="bill_immediately",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.BillNextCycle="bill_next_cycle"})(e||(e={})),{OnIncrease:e}})(),{OnDecrease:Wi}=(()=>{var e;return(function(t){t.Prorate="prorate",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.None="none",t.NoProrations="no_prorations"})(e||(e={})),{OnDecrease:e}})(),{RolloverExpiryDurationType:eu}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:pA}=(()=>{var e;return(function(t){t.Day="day",t.Week="week",t.Month="month",t.Year="year"})(e||(e={})),{EntitlementDuration:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:mA}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:fA}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:qh}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ae),{flatCreditRateShape:Vh}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(Ae),{CreditTierSchema:hA}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(Ae),{CreditMultiplierSchema:gA}=((e,t)=>({CreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional(),add:e.number().optional()}).refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add"})}))(Ae,qh),{MarkupEntrySchema:Gh}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ae),{ModelMarkupsSchema:bA}=((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()}))(Ae,Gh),{isFeaturePriceItem:tu}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(Yr),{notNullish:pr}={notNullish:t=>t!=null},{isAiCreditSystem:nu}=(e=>({isAiCreditSystem:n=>n===e.AiCreditSystem}))(It),{VIOLATION_MESSAGES:_A}={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."}},{sameSpecificity:yA}={sameSpecificity:(t,n)=>Object.keys(t.match).length===Object.keys(n.match).length&&(t.priority??null)===(n.priority??null)},{matchesCanCoexist:$h}={matchesCanCoexist:(t,n)=>Object.entries(t).every(([r,i])=>{let o=Object.entries(n).find(([a])=>a===r)?.[1];return o===void 0||o===i})},{formatCreditMatch:SA}={formatCreditMatch:t=>Object.entries(t).map(([n,r])=>`${n}=${r}`).join(", ")},{validateMultiplierShape:vA}={validateMultiplierShape:({name:t,multiplier:n,invalidCreditSystem:r})=>{let i=n.factor!==void 0,o=n.add!==void 0;!i&&!o&&r(`Multiplier "${t}" needs a factor or an add.`);let a=Number(n.factor);i&&!(Number.isFinite(a)&&a>0)&&r(`Multiplier "${t}" factor must be greater than zero.`);let s=Number(n.add);o&&!Number.isFinite(s)&&r(`Multiplier "${t}" add must be a number.`),i&&(n.factor=a),o&&(n.add=s)}},{minimumCreditRateAmount:xA}={minimumCreditRateAmount:t=>t.tier_behavior!=="graduated"?t.credit_amount??0:(t.tiers??[]).reduce((n,r)=>Math.min(n,r.credit_amount),Number.POSITIVE_INFINITY)},{worstCaseRate:IA}=((e,t)=>({worstCaseRate:({multipliers:r,cheapestRate:i})=>r.reduce((o,a)=>{let s=[];for(let u of r){let l=u.factor!==void 0&&u.factor<1||u.add!==void 0&&u.add<0,d=s.every(m=>e(m.match,u.match));(l||u===a)&&e(a.match,u.match)&&d&&s.push(u)}let c=s.reduce((u,l)=>u.mul(l.factor!==void 0&&l.factor<1?l.factor:1).add(l.add!==void 0&&l.add<0?l.add:0),new t(i));return t.min(o,c)},new t(i))}))($h,rn),{validateCreditSystemSchemaReferences:AA}=((e,t,n,r)=>({validateCreditSystemSchemaReferences:({config:o,allFeatures:a,selfFeatureId:s})=>{let c=Array.isArray(o?.schema)?o.schema:[];if(c.length!==0)for(let u of c){let l=u.metered_feature_id;if(!l||l===s)continue;let d=a.find(m=>m.id===l);if(d){if(d.type===e.CreditSystem)throw new t({message:`Credit system schema cannot reference another credit system (${l}). Only metered or AI credit features are allowed.`,code:n.InvalidFeature,statusCode:400});if(d.type===e.Boolean)throw new t({message:`Credit system schema cannot reference boolean feature ${l}. Only consumable (single-use) metered or AI credit features are allowed.`,code:n.InvalidFeature,statusCode:400});if(d.type===e.Metered&&d.config?.usage_type===r.Continuous)throw new t({message:`Credit system schema cannot reference continuous feature ${l}. Only consumable (single-use) metered features are allowed.`,code:n.InvalidFeature,statusCode:400})}}}}))(It,jt,qt,Gn),{isPriceItem:ru}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(Yr,Zr),{isFeatureItem:Ia}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)}))(Yr,Zr),{itemToBillingInterval:Kn}=((e,t)=>({itemToBillingInterval:({item:r})=>{let i=r.price_interval??r.interval;return e(i)?t.OneOff:i}}))(Yt,xn),{rolloverConfigToIssue:wA}={rolloverConfigToIssue:({rollover:t})=>t==null?null:t.max!=null&&t.max_percentage!=null?"Rollover max and max_percentage are mutually exclusive. Set one or the other, not both.":t.max_percentage!=null?t.max_percentage<=0||t.max_percentage>100?"Rollover max_percentage must be between 0 (exclusive) and 100 (inclusive)":null:t.max!=null&&t.max<=0?"Rollover maximum amount must be greater than 0":null},{itemToEntInterval:Aa}=((e,t,n)=>({itemToEntInterval:({item:i})=>e(i.interval)||i.feature_type===n.ContinuousUse?t.Lifetime:i.interval}))(Yt,Kr,In),{itemToEntIntervalCount:wa}={itemToEntIntervalCount:({item:t})=>t.interval_count??1},{itemToBillingIntervalCount:Xr}={itemToBillingIntervalCount:({item:t})=>t.price_interval_count??t.interval_count??1},{isFeatureItem:Pa}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price===0)&&t(r.tiers)}))(pr,Yt),{toKey:Kh}={toKey:t=>t.toLowerCase()},{priceOwnedStripePriceId:PA}=(e=>({priceOwnedStripePriceId:({price:n})=>{let r=n.config,i=r.stripe_prepaid_price_v2_id||r.stripe_price_id;return e(i)?null:i}}))(Yt),{UsageTierSchema:iu}=((e,t)=>({UsageTierSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional()}).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"]}).transform(r=>({...r,amount:r.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional()}))}))(Ae,$i),{IgnoredFixedPriceMetadataSchema:OA}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(Ae),{hasCatalogCurrencies:CA}={hasCatalogCurrencies:t=>Object.keys(t??{}).length>0},{usageTiersToComparisonShape:EA}={usageTiersToComparisonShape:t=>t.map((n,r)=>({amount:n.amount,flat_amount:n.flat_amount??0,to:r===t.length-1?null:n.to}))},{normalizedAllocatedBillingBehavior:TA}=(e=>({normalizedAllocatedBillingBehavior:n=>n.allocated_billing_behavior??(n.should_prorate?e.Prorated:e.Arrear)}))($n),{getResetUsage:Wh}=((e,t,n,r)=>({getResetUsage:({item:o,feature:a})=>{if(o.feature_id)return e(o.reset_usage_when_enabled)&&(t(o)||n(o))&&a?a?.config?.usage_type===r.Single:o.reset_usage_when_enabled}}))(Zr,Ia,tu,Gn),{hasUnlimitedAllowanceType:RA}=(e=>({hasUnlimitedAllowanceType:n=>n.allowance_type===e.Unlimited}))(va),{normalizedEntitlementInterval:Hh}=(e=>({normalizedEntitlementInterval:n=>n.interval??e.Lifetime}))(Kr),{normalizedEntitlementIntervalCount:jA}=((e,t)=>({normalizedEntitlementIntervalCount:r=>e(r)===t.Lifetime?1:r.interval_count??1}))(Hh,Kr),{normalizeOptionalId:kA}={normalizeOptionalId:t=>t||null},{rolloversAreSame:DA}=(e=>({rolloversAreSame:({rollover1:n,rollover2:r})=>!n&&!r?!0:!n&&r||n&&!r?!1:n?.max==r?.max&&n?.max_percentage==r?.max_percentage&&(n?.duration??e.Month)===(r?.duration??e.Month)&&n?.length==r?.length}))(eu),{deterministicStringify:ou}=(()=>{let e=t=>{if(t==null)return"null";if(typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(e).join(",")}]`;let n=t;return typeof n.toJSON=="function"?e(n.toJSON()):`{${Object.keys(n).filter(i=>n[i]!==void 0).sort().map(i=>`${JSON.stringify(i)}:${e(n[i])}`).join(",")}}`};return{deterministicStringify:e}})(),{MARKUP_FIELDS:NA}={MARKUP_FIELDS:["markup","input_cost","output_cost"]},{expiriesAreSame:FA}={expiriesAreSame:(t,n)=>(t.expiry_duration??null)===(n.expiry_duration??null)&&(t.expiry_length??null)==(n.expiry_length??null)},{itemToFeature:Qh}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{isFeaturePriceItem:zr}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(pr),{ProductErrorCode:UA}={ProductErrorCode:{ProductNotFound:"product_not_found",ProductAlreadyExists:"product_already_exists",InvalidProductItem:"invalid_product_item"}},{buildUsagePriceCurrencies:MA}=(e=>({buildUsagePriceCurrencies:({baseTiers:n,itemTiers:r,flatCurrencies:i})=>{if(r?.length){let o=[...new Set(r.flatMap(s=>(s.additional_currencies??[]).map(c=>e(c.currency))))];if(o.length===0)return;let a={};for(let s of o)a[s]={usage_tiers:n.map((c,u)=>{let l=(r[u]?.additional_currencies??[]).find(d=>e(d.currency)===s);return{to:c.to,amount:l?.amount??0,...l?.flat_amount!==void 0?{flat_amount:l.flat_amount}:{}}})};return a}if(i?.length&&n.length>0){let o={};for(let{currency:a,amount:s}of i)o[e(a)]={usage_tiers:[{to:n[0].to,amount:s}]};return o}}}))(Kh),{itemToFeature:BA}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{shouldProrate:LA}=((e,t)=>({shouldProrate:r=>r?r===e.ProrateNextCycle||r===e.ProrateImmediately||r===t.ProrateImmediately||r===t.ProrateNextCycle:!0}))(Jr,Wi),{getBillingType:qA}=((e,t,n,r)=>({getBillingType:o=>{if(o.type===e.Fixed&&o.interval===t.OneOff)return n.OneOff;if(o.type===e.Fixed)return n.FixedCycle;let a=o;return a.bill_when===r.InAdvance||a.bill_when===r.StartOfPeriod?n.UsageInAdvance:a.bill_when===r.EndOfPeriod&&a.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(Wr,xn,Hr,Ki),{stripeResourceFields:VA}={stripeResourceFields:["stripe_product_id","stripe_price_id","stripe_empty_price_id","stripe_placeholder_price_id","stripe_prepaid_price_v2_id","stripe_meter_id","stripe_event_name"]},{PREVIEW_STRIPE_PRICE_ID_PREFIX:GA}={PREVIEW_STRIPE_PRICE_ID_PREFIX:"price_PREVIEW_"},{PREVIEW_STRIPE_PRODUCT_ID_PREFIX:$A}={PREVIEW_STRIPE_PRODUCT_ID_PREFIX:"prod_PREVIEW_"},{normalizeOptionalId:KA}={normalizeOptionalId:t=>t||null},{stripeProductOnlyFields:WA}={stripeProductOnlyFields:["stripe_product_id","stripe_meter_id"]},{copyField:HA}=(e=>({copyField:({fromConfig:n,toConfig:r,field:i})=>!e(r[i])||e(n[i])?!1:(r[i]=n[i],!0)}))(Yt),{stripeResourceFields:QA}={stripeResourceFields:["stripe_product_id","stripe_price_id","stripe_empty_price_id","stripe_placeholder_price_id","stripe_prepaid_price_v2_id","stripe_meter_id","stripe_event_name"]},{handleCustomProductItems:ZA}={handleCustomProductItems:({newPrices:t,newEnts:n,updatedPrices:r,updatedEnts:i,samePrices:o,sameEnts:a,features:s})=>({prices:[...t,...r,...o],entitlements:[...n,...i,...a].map(c=>({...c,feature:s.find(u=>u.id===c.feature_id)})),customPrices:[...t,...r],customEnts:[...n,...i],features:s})},{validateLicenseBillingMode:YA}=((e,t)=>({validateLicenseBillingMode:({prepaidOnly:r})=>{if(r===!1)throw new e({message:"License overflow billing (prepaid_only: false) is not yet available. Set prepaid_only to true.",code:t.InvalidRequest,statusCode:400})}}))(jt,qt),{PlanItemMatchPrecision:JA}=(()=>{var e;return(function(t){t.FeatureBillingMethodCadence="feature_billing_method_cadence",t.FeatureCadence="feature_cadence"})(e||(e={})),{PlanItemMatchPrecision:e}})(),{catalogPlanItemIdentity:XA}={catalogPlanItemIdentity:{responseField:"mapping_identity",components:[{paths:["feature_id"],default:""},{paths:["price.billing_method"],default:""},{paths:["price.interval","reset.interval"],default:""},{paths:["price.interval_count","reset.interval_count"],default:"",defaultWhen:{component:2,value:1}}]}},{applyPrice:zA}={applyPrice:(t,n)=>n===void 0?t:n===null?null:{...n}},{planItemMatchesFilter:ew}={planItemMatchesFilter:({item:t,filter:n})=>{if(n.feature_id!==void 0&&t.feature_id!==n.feature_id||n.billing_method!==void 0&&t.price?.billing_method!==n.billing_method)return!1;if(n.interval!==void 0){let r=t.price?.interval??t.reset?.interval;if(String(r)!==String(n.interval))return!1}return!(n.interval_count!==void 0&&(t.price?.interval_count??t.reset?.interval_count??1)!==n.interval_count||n.included!==void 0&&(t.unlimited===!0||(t.included??0)!==n.included))}},{isFreeNonResetEntitlement:tw}={isFreeNonResetEntitlement:t=>t.price==null&&t.reset==null},{toApiPlanItemPrice:nw}={toApiPlanItemPrice:t=>t?{...t,billing_units:t.billing_units??1,max_purchase:t.max_purchase??null}:null},{toApiPlanItemRollover:rw}={toApiPlanItemRollover:t=>{if(t)return{...t,max:t.max??null}}},{applyFreeTrial:iw}={applyFreeTrial:(t,n)=>{if(n===void 0)return t;if(n!==null)return{...n}}},{applyLicenseUpsert:ow}={applyLicenseUpsert:({existing:t,upsert:n})=>{let r=n.customize===null?void 0:n.customize??t?.customize;return{license_plan_id:n.license_plan_id,version:t?.version??1,included:n.included??t?.included??0,prepaid_only:n.prepaid_only??t?.prepaid_only??!1,...r!==void 0?{customize:r}:{},...t?.plan!==void 0?{plan:t.plan}:{}}}},{PlanItemFilterPrecision:Zh}=(()=>{var e;return(function(t){t.Identity="identity",t.IdentityAndIncluded="identity_and_included"})(e||(e={})),{PlanItemFilterPrecision:e}})(),{additionalCurrenciesCompatible:au}={additionalCurrenciesCompatible:(t,n)=>(t??[]).every(r=>{let i=(n??[]).find(o=>o.currency.toLowerCase()===r.currency.toLowerCase());return!i||(r.amount??null)===(i.amount??null)&&(r.flat_amount??null)===(i.flat_amount??null)})},{toBasePriceParams:aw}={toBasePriceParams:(t,{includeInternalIds:n=!1}={})=>({amount:t.amount,interval:t.interval,...t.interval_count!==void 0?{interval_count:t.interval_count}:{},...t.additional_currencies?.length?{additional_currencies:t.additional_currencies}:{},...n&&t.entitlement_id!==void 0?{entitlement_id:t.entitlement_id}:{},...n&&t.price_id!==void 0?{price_id:t.price_id}:{},...n&&"stripe_price_id"in t&&t.stripe_price_id!==void 0?{stripe_price_id:t.stripe_price_id}:{}})},{tiersEqual:sw}=(e=>({tiersEqual:(n,r)=>!n?.length&&!r?.length?!0:!n||!r||n.length!==r.length?!1:n.every((i,o)=>{let a=r[o];return i.to===a.to&&(i.amount??0)===(a.amount??0)&&(i.flat_amount??null)===(a.flat_amount??null)&&e(i.additional_currencies,a.additional_currencies)})}))(au),{rolloversEqual:cw}={rolloversEqual:(t,n)=>t==null&&n==null?!0:t==null||n==null?!1:t.expiry_duration_type===n.expiry_duration_type&&(t.expiry_duration_length??null)===(n.expiry_duration_length??null)&&(t.max??null)===(n.max??null)&&(t.max_percentage??null)===(n.max_percentage??null)},{prorationsEqual:uw}={prorationsEqual:(t,n)=>t==null&&n==null?!0:t==null||n==null?!1:(t.on_increase??null)===(n.on_increase??null)&&(t.on_decrease??null)===(n.on_decrease??null)},{creditSchemaFingerprint:lw}=(e=>({creditSchemaFingerprint:n=>e(Object.fromEntries((n??[]).map(r=>[r.metered_feature_id,{...r,billing_units:r.billing_units??1}])))}))(ou),{toCreatePlanItemParams:dw}={toCreatePlanItemParams:(t,{includeInternalIds:n=!1}={})=>{let r={feature_id:t.feature_id};return t.entity_feature_id!==void 0&&(r.entity_feature_id=t.entity_feature_id),t.pooled&&(r.pooled=t.pooled),n&&t.entitlement_id!==void 0&&(r.entitlement_id=t.entitlement_id),n&&t.price_id!==void 0&&(r.price_id=t.price_id),t.included!==void 0&&t.included!==null&&(r.included=t.included),t.unlimited!==void 0&&t.unlimited!==null&&(r.unlimited=t.unlimited),t.reset&&(r.reset=t.reset),t.price&&(r.price=t.price),t.rollover&&(r.rollover={expiry_duration_type:t.rollover.expiry_duration_type,...t.rollover.max!=null?{max:t.rollover.max}:{},...t.rollover.max_percentage!=null?{max_percentage:t.rollover.max_percentage}:{},...t.rollover.expiry_duration_length!==void 0?{expiry_duration_length:t.rollover.expiry_duration_length}:{}}),t.proration?.on_increase&&t.proration.on_decrease&&(r.proration={on_increase:t.proration.on_increase,on_decrease:t.proration.on_decrease}),t.feature_override&&(r.feature_override=t.feature_override),r}},{buildRemoveFilter:pw}=(e=>({buildRemoveFilter:({item:n,filterPrecision:r})=>{let i={feature_id:n.feature_id};n.price?.billing_method!==void 0&&(i.billing_method=n.price.billing_method);let o=n.price?.interval??n.reset?.interval;o!==void 0&&(i.interval=o);let a=n.price?.interval_count??n.reset?.interval_count;return o!==void 0&&(i.interval_count=a??1),r===e.IdentityAndIncluded&&typeof n.included=="number"&&n.unlimited!==!0&&(n.reset!=null||n.price!=null)&&(i.included=n.included),i}}))(Zh),{FreeTrialDuration:mw}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{arraysEqual:fw}={arraysEqual:({left:t,right:n,equals:r})=>{if(!t?.length&&!n?.length)return!0;if(!t||!n||t.length!==n.length)return!1;let i=[...n];return t.every(o=>{let a=i.findIndex(s=>r(o,s));return a===-1?!1:(i.splice(a,1),!0)})}},{normalizeIntervalCount:hw}={normalizeIntervalCount:({interval:t,intervalCount:n})=>t?n??1:n??""},{hasLicenseCustomize:Yh}={hasLicenseCustomize:t=>t!=null&&(t.price!==void 0||t.add_items!==void 0||t.remove_items!==void 0)},{byLicensePlanId:gw}={byLicensePlanId:(t,n)=>t.license_plan_id.localeCompare(n.license_plan_id)},{variantSettingKeys:bw}={variantSettingKeys:["name","description","group","add_on","config","billing_controls","metadata"]},{valuesEqual:_w}={valuesEqual:(t,n)=>JSON.stringify(t)===JSON.stringify(n)},{omitVariantOwnedSettings:e4}={omitVariantOwnedSettings:({name:t,...n})=>n},{isFreeProductV2:yw}=(e=>({isFreeProductV2:({items:n})=>n.every(r=>e(r.price)&&e(r.tiers))}))(Yt),{isPriceItem:Oa}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(pr,Yt),{isDefaultTrialV2:t4}=(e=>({isDefaultTrialV2:({freeTrial:n,items:r,isDefault:i})=>n?n.card_required===!1&&i&&!e({items:r}):!1}))(yw),{variantSettingsFields:Sw}={variantSettingsFields:["description","group","is_add_on","is_default","config","billing_controls","metadata"]},{sortDeep:Jh}=(()=>{let e=t=>Array.isArray(t)?t.map(e):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(n=>[n,e(t[n])])):t;return{sortDeep:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:vw}={IGNORE_PAST_DUE_DESCRIPTION:"If true, entitlements attached to this plan will still reset on schedule even when the customer's product is in a past_due state."},{propagatedSettingFields:xw}={propagatedSettingFields:["description","group","is_add_on","config","billing_controls","metadata"]},{licenseParentTargetKey:Iw}={licenseParentTargetKey:({planId:t,version:n})=>`${t}@${n}`},{STRIPE_ZERO_DECIMAL_CURRENCIES:Xh}={STRIPE_ZERO_DECIMAL_CURRENCIES:new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"])},{STRIPE_THREE_DECIMAL_CURRENCIES:Aw}={STRIPE_THREE_DECIMAL_CURRENCIES:new Set(["bhd","jod","kwd","omr","tnd"])},{currencyInputDecimals:zh}=(e=>({currencyInputDecimals:n=>e.has((n??"usd").toLowerCase())?0:2}))(Xh),{entIntervalToValue:ww}=((e,t)=>({entIntervalToValue:(r,i)=>{if(!r)return new e(1e7);let a={[t.Minute]:1,[t.Hour]:60,[t.Day]:1440,[t.Week]:1440*7,[t.Month]:1440*30,[t.Quarter]:1440*90,[t.SemiAnnual]:1440*180,[t.Year]:1440*365,[t.Lifetime]:1e9}[r];return new e(a).mul(i??1)}}))(rn,Kr),{intervalToValue:Pw}=(e=>({intervalToValue:(n,r)=>({[e.OneOff]:0,[e.Week]:.25,[e.Month]:1,[e.Quarter]:3,[e.SemiAnnual]:6,[e.Year]:12})[n]*(r??1)}))(xn),{normalizeIncludedUsage:eg}={normalizeIncludedUsage:t=>t??0},{rolloversAreSame:tg}={rolloversAreSame:({rollover1:t,rollover2:n})=>t&&!n||!t&&n?!1:(t?.max??null)===(n?.max??null)&&(t?.max_percentage??null)===(n?.max_percentage??null)&&t?.duration===n?.duration&&t?.length===n?.length},{prorationConfigsAreSame:Ow}=((e,t)=>({prorationConfigsAreSame:({config1:r,config2:i})=>(r?.on_increase??e.ProrateImmediately)===(i?.on_increase??e.ProrateImmediately)&&(r?.on_decrease??t.Prorate)===(i?.on_decrease??t.Prorate)}))(Jr,Wi),{itemToExplicitAllocatedBillingBehavior:Cw}=((e,t)=>({itemToExplicitAllocatedBillingBehavior:r=>e(r.config?.allocated_billing_behavior)?r.config.allocated_billing_behavior:(e(r.config?.on_increase)||e(r.config?.on_decrease),t.Prorated)}))(pr,$n),{additionalCurrenciesAreSame:su}={additionalCurrenciesAreSame:(t,n)=>{let r=t??[],i=n??[];if(r.length!==i.length)return!1;let o=(c,u)=>c.currency.localeCompare(u.currency),a=[...r].sort(o),s=[...i].sort(o);return a.every((c,u)=>c.currency===s[u].currency&&(c.amount??null)===(s[u].amount??null)&&(c.flat_amount??null)===(s[u].flat_amount??null))}},{itemPricingTiers:Ew}={itemPricingTiers:t=>t.tiers?.length?t.tiers:t.price!=null?[{amount:t.price,to:"inf"}]:null},{priceItemsAreSame:Tw}=((e,t,n)=>({priceItemsAreSame:({item1:i,item2:o,logDifferences:a=!1})=>{let s=i.price===o.price&&e({item:i})==e({item:o})&&t({item:i})==t({item:o})&&n(i.additional_currencies,o.additional_currencies);return!s&&a&&console.log(`Price items different: ${i.price}`),s}}))(Kn,Xr,su),{calculateProrationAmount:Rw}=(e=>({calculateProrationAmount:({periodEnd:n,periodStart:r,now:i,amount:o,allowNegative:a=!1})=>{let s=new e(n).minus(i),c=new e(n).minus(r),u=s.div(c).mul(o);return u.lte(0)&&!a?0:u.toNumber()}}))(rn),{getResetUsage:jw}=((e,t,n,r)=>({getResetUsage:({item:o,feature:a})=>{if(o.feature_id)return e(o.reset_usage_when_enabled)&&(t(o)||n(o))&&a?a?.config?.usage_type===r.Single:o.reset_usage_when_enabled}}))(Yt,Pa,zr,Gn),{compareDetails:kw}={compareDetails:({newProductV2:t,curProductV2:n})=>{let r={is_add_on:{condition:t?.is_add_on===n?.is_add_on,message:`Is add-on different: ${t?.is_add_on} !== ${n?.is_add_on}`},is_default:{condition:t?.is_default===n?.is_default,message:`Is default different: ${t?.is_default} !== ${n?.is_default}`},archived:{condition:t?.archived===n?.archived,message:`Archived different: ${t?.archived} !== ${n?.archived}`},group:{condition:t?.group==n?.group,message:`Group different: ${t?.group} !== ${n?.group}`},name:{condition:t?.name==n?.name,message:`Name different: ${t?.name} !== ${n?.name}`},id:{condition:t?.id===n?.id,message:`ID different: ${t?.id} !== ${n?.id}`}};return Object.values(r).every(o=>o.condition)}},{compareConfig:Dw}={compareConfig:({newConfig:t,curConfig:n})=>{let r={ignore_past_due:{condition:!!t?.ignore_past_due==!!n?.ignore_past_due,message:`Ignore past due different: ${t?.ignore_past_due} !== ${n?.ignore_past_due}`}};return Object.values(r).every(o=>o.condition)}},{normalizeBillingControlsForCompare:Nw}=(e=>({normalizeBillingControlsForCompare:n=>{if(!n)return;let r=n.spend_limits?.map(o=>{if(o.skip_overage_billing===!0)return o;let{skip_overage_billing:a,...s}=o;return s}),i=Object.fromEntries(e.flatMap(o=>{let a=o==="spend_limits"?r:n[o];return a==null||a.length===0?[]:[[o,a]]}));return Object.keys(i).length>0?i:void 0}}))(Sa),{sortControls:Fw}={sortControls:t=>[...t].sort((n,r)=>{let i=(n.feature_id??"").localeCompare(r.feature_id??"");return i!==0?i:JSON.stringify(n).localeCompare(JSON.stringify(r))})},{compareMetadata:Uw}={compareMetadata:({newMetadata:t,curMetadata:n})=>{let r=i=>JSON.stringify(i??{},(o,a)=>a&&typeof a=="object"&&!Array.isArray(a)?Object.keys(a).sort().reduce((s,c)=>(s[c]=a[c],s),{}):a);return r(t)===r(n)}},{freeTrialsAreSame:Mw}={freeTrialsAreSame:({ft1:t,ft2:n})=>{if(!t&&!n)return!0;if(!t||!n)return!1;let r={length:{condition:t.length!==n.length,message:`Length different: ${t.length} !== ${n.length}`},unique_fingerprint:{condition:t.unique_fingerprint!==n.unique_fingerprint,message:`Unique fingerprint different: ${t.unique_fingerprint} !== ${n.unique_fingerprint}`},duration:{condition:t.duration!==n.duration,message:`Duration different: ${t.duration} !== ${n.duration}`},card_required:{condition:t.card_required!==n.card_required,message:`Card required different: ${t.card_required} !== ${n.card_required}`},on_end:{condition:(t.on_end??"bill")!==(n.on_end??"bill"),message:`On end different: ${t.on_end??"bill"} !== ${n.on_end??"bill"}`}};return!Object.values(r).some(o=>o.condition)}},{prodOptionsAreSame:Bw}={prodOptionsAreSame:({curProduct:t,newProduct:n})=>t.is_default===n.is_default&&t.is_add_on===n.is_add_on},{PurchaseLimitIntervalEnum:Lw}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(Ae,nA),{entToItemInterval:ng}=(e=>({entToItemInterval:({entInterval:n})=>!n||n===e.Lifetime?null:n}))(Kr),{billingToItemInterval:rg}=(e=>({billingToItemInterval:({billingInterval:n})=>n===e.OneOff?null:n}))(xn),{isContUseFeature:ig}=(e=>({isContUseFeature:({feature:n})=>n.config?.usage_type===e.Continuous}))(Gn),{getBillingType:cu}=((e,t,n,r)=>({getBillingType:o=>{if(o.type===e.Fixed&&o.interval===t.OneOff)return n.OneOff;if(o.type===e.Fixed)return n.FixedCycle;let a=o;return a.bill_when===r.InAdvance||a.bill_when===r.StartOfPeriod?n.UsageInAdvance:a.bill_when===r.EndOfPeriod&&a.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(Wr,xn,Hr,Ki),{isAllocatedPrice:og}=((e,t)=>({isAllocatedPrice:r=>r?e(r.config)===t.InArrearProrated:!1}))(cu,Hr),{priceToEnt:uu}=(e=>{function t({price:n,entitlements:r,errorOnNotFound:i}){let o=r.filter(s=>s.id===n.entitlement_id),a=o.find(s=>s.internal_product_id===n.internal_product_id)??o[0];if(!a&&i)throw new e({message:`Entitlement not found for price ${n.id}`});return a}return{priceToEnt:t}})(oA),{isBooleanFeatureItem:ag}=((e,t)=>({isBooleanFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)&&t(r.interval)&&t(r.included_usage)}))(Yr,Zr),{constructBooleanFeature:qw}=((e,t,n)=>({constructBooleanFeature:({featureId:i,orgId:o,env:a,name:s})=>({internal_id:e("fe"),org_id:o,env:a,created_at:Date.now(),id:i,name:s||t(i),type:n.Boolean,config:null,archived:!1,event_names:[],model_markups:null})}))($r,Uh,It),{constructMeteredFeature:Vw}=((e,t,n,r)=>({constructMeteredFeature:({featureId:o,name:a,orgId:s,env:c,usageType:u,eventNames:l=[]})=>({internal_id:e("fe"),org_id:s,env:c,created_at:Date.now(),id:o,name:a||t(o),type:n.Metered,config:{filters:[{property:"event_name",operator:"eq",value:[]}],aggregate:{type:r.Sum,property:"value"},usage_type:u},archived:!1,event_names:l,model_markups:null})}))($r,Uh,It,sA),{ApiFeatureV0Schema:Gw}=((e,t)=>({ApiFeatureV0Schema:e.object({id:e.string().meta({description:"The ID of the feature, used to refer to it in other API calls like /track or /check."}),name:e.string().nullish().meta({description:"The name of the feature."}),type:e.enum(t).meta({description:"The type of the feature"}),display:e.object({singular:e.string().meta({description:"The singular display name for the feature."}),plural:e.string().meta({description:"The plural display name for the feature."})}).nullish().meta({description:"Singular and plural display names for the feature."}),credit_schema:e.array(e.object({metered_feature_id:e.string().meta({description:"The ID of the metered feature (should be a single_use feature)."}),credit_cost:e.number().meta({description:"The credit cost of the metered feature."})})).nullish().meta({description:"Credit cost schema for credit system features."}),archived:e.boolean().nullish().meta({description:"Whether or not the feature is archived."})})}))(Ae,uA),{CURRENCY_CODES:$w}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Mh,lA,dA),{RolloverConfigSchema:Kw}=((e,t)=>({RolloverConfigSchema:e.object({max:e.number().nullable().optional(),max_percentage:e.number().nullable().optional(),duration:e.enum(t).default(t.Month),length:e.number()})}))(Ae,eu),{EntitlementExpirySchema:Ww}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(Ae,pA),{CreditDimensionNameSchema:Hw}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ae,mA,fA),{CreditDimensionBaseSchema:Qw}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(Ae,qh),{graduatedCreditRateShape:sg}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(Ae,hA),{ProviderMarkupsSchema:Zw}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ae,Gh),{isAnyCreditSystem:Yw}=((e,t)=>({isAnyCreditSystem:r=>r===e.CreditSystem||t(r)}))(It,nu),{findCreditTierViolations:Jw}=(e=>({findCreditTierViolations:n=>{let r=[],i=(a,s)=>r.push({index:a,reason:s,message:e[s]}),o=0;for(let[a,s]of n.entries()){let c=a===n.length-1;if(s==="inf"){c||i(a,"non_final_infinity");continue}(!Number.isFinite(s)||s<=o)&&i(a,"not_increasing"),o=s,c&&i(a,"final_not_infinity")}return r}}))(_A),{findAmbiguousCreditDimensions:Xw}=((e,t)=>({findAmbiguousCreditDimensions:r=>{let i=Object.entries(r),o=[];for(let[a,[s,c]]of i.entries())for(let[u,l]of i.slice(a+1))e(c,l)&&t(c.match,l.match)&&o.push({names:[s,u],example:{...c.match,...l.match}});return o}}))(yA,$h),{validateMultipliersKeepRatesNonNegative:zw}=((e,t)=>({validateMultipliersKeepRatesNonNegative:({schemaItem:r,invalidCreditSystem:i})=>{let o=Object.values(r.multipliers??{}),a=[r,...Object.values(r.dimensions??{})],s=Math.min(...a.map(e));t({multipliers:o,cheapestRate:s}).lt(0)&&i(`Multipliers on ${r.metered_feature_id} can take a rate below zero.`)}}))(xA,IA),{buildFixedPriceCurrencies:e1}=(e=>({buildFixedPriceCurrencies:n=>{if(!n?.length)return;let r={};for(let{currency:i,amount:o}of n)r[e(i)]={amount:o};return r}}))(Kh),{PriceCurrencyConfigSchema:cg}=((e,t)=>({PriceCurrencyConfigSchema:e.object({amount:e.number().nullish(),usage_tiers:e.array(t).nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish()})}))(Ae,iu),{baseCurrenciesAreCompatible:t1}=(e=>({baseCurrenciesAreCompatible:({base1:n,base2:r,currencies1:i,currencies2:o})=>(n??null)===(r??null)||e(i)!==e(o)}))(CA),{tiersAreSame:ug}=(e=>({tiersAreSame:(n,r)=>{if(n.length!==r.length)return!1;let i=e(n),o=e(r);return i.every((a,s)=>{let c=o[s];return a.amount===c?.amount&&a.flat_amount===c.flat_amount&&a.to===c.to})}}))(EA),{UsagePriceConfigSchema:n1}=((e,t,n,r,i,o)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(n),interval:e.enum(r),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(o).optional()})}))(Ae,Ki,iu,xn,cg,$n),{toFeature:r1}=((e,t,n,r,i,o,a)=>({toFeature:({item:c,orgId:u,internalFeatureId:l,internalProductId:d,isCustom:m,newVersion:g,feature:p,curEnt:f})=>{let y=p?.type===e.Boolean,x=t({item:c,feature:p}),S={id:c.entitlement_id||f?.id||n("ent"),org_id:u,created_at:c.created_at||Date.now(),is_custom:m,internal_product_id:d||null,internal_feature_id:l,feature_id:c.feature_id,allowance:c.included_usage===r?null:c.included_usage,allowance_type:y?null:c.included_usage===r?i.Unlimited:i.Fixed,interval:y?null:o({item:c}),interval_count:a({item:c}),carry_from_previous:!x,entity_feature_id:c.entity_feature_id,pooled:c.pooled??!1,usage_limit:null,rollover:c.config?.rollover,expiry_duration:c.config?.expiry?.duration,expiry_length:c.config?.expiry?.length,feature_override:c.config?.feature_override};return(m||g)&&(S={...S,id:n("ent"),created_at:Date.now()}),{price:null,ent:S}}}))(It,Wh,$r,$i,va,Aa,wa),{creditDimensionRulesEqual:i1}=(e=>({creditDimensionRulesEqual:({left:n,right:r})=>e(n.dimensions??{})===e(r.dimensions??{})&&e(n.multipliers??{})===e(r.multipliers??{})}))(ou),{markupRecordsAreSame:o1}=(e=>({markupRecordsAreSame:(n,r)=>[...new Set([...Object.keys(n??{}),...Object.keys(r??{})])].every(i=>e.every(o=>(n?.[i]?.[o]??null)===(r?.[i]?.[o]??null)))}))(NA),{itemToUsageType:a1}=((e,t,n)=>({itemToUsageType:({item:i,features:o})=>{let a=e({item:i,features:o});return!a||!a.config?null:a.type===t.Boolean?n.Static:a.type===t.CreditSystem?n.SingleUse:a.config.usage_type}}))(Qh,It,In),{itemToUsageType:s1}=((e,t,n)=>({itemToUsageType:({item:i,features:o})=>{let a=e({item:i,features:o});return a?a.type==t.Boolean?n.Static:a.type==t.CreditSystem?n.SingleUse:a.config.usage_type:null}}))(BA,It,In),{isPreviewStripeId:c1}=((e,t)=>({isPreviewStripeId:({stripeId:r})=>r?.startsWith(e)===!0||r?.startsWith(t)===!0}))(GA,$A),{findPairedEntitlement:u1}=(e=>({findPairedEntitlement:({price:n,entitlements:r})=>e({price:n,entitlements:r})}))(uu),{isConsumablePrice:l1}=((e,t)=>({isConsumablePrice:r=>r?e(r.config)===t.UsageInArrear:!1}))(cu,Hr),{validateLicenseLink:n4}=((e,t,n)=>({validateLicenseLink:({parentProduct:i,licenseProduct:o,prepaidOnly:a,licensePlanId:s})=>{if(a!==void 0&&e({prepaidOnly:a}),s&&o.archived)throw new t({message:`License plan ${s} is archived and cannot be linked.`,code:n.InvalidRequest,statusCode:400});if(o.base_internal_product_id)throw new t({message:`A variant cannot be used as a plan license (${s??o.id}).`,code:n.InvalidRequest});if(i&&o.id===i.id)throw new t({message:`A plan cannot be linked as a license to itself (${s??o.id}).`,code:n.InvalidRequest,statusCode:400})}}))(YA,jt,qt),{evaluateCatalogItemIdentity:d1}=(e=>({evaluateCatalogItemIdentity:({item:n,recipe:r=e})=>{let i=[];for(let o of r.components){let a;for(let c of o.paths){a=n;for(let u of c.split("."))a=a!==null&&typeof a=="object"?a[u]:void 0;if(a!=null)break}let s=o.defaultWhen&&i[o.defaultWhen.component]?o.defaultWhen.value:o.default;if(a!=null&&typeof a!="string"&&typeof a!="number")throw new Error("Catalog identity components must be strings or numbers");i.push(a??s)}return i}}))(XA),{removeItems:p1}=(e=>({removeItems:(n,r)=>n.filter(i=>!r.some(o=>e({item:i,filter:o})))}))(ew),{toApiPlanItem:m1}=((e,t)=>({toApiPlanItem:r=>({...r,included:r.included??0,unlimited:r.unlimited??!1,reset:r.reset??null,price:e(r.price),rollover:t(r.rollover)})}))(nw,rw),{applyLicenses:f1}=(e=>({applyLicenses:({base:n,diff:r})=>{if(r.upsert_licenses===void 0&&r.remove_licenses===void 0)return;let i=new Set((r.remove_licenses??[]).map(s=>s.license_plan_id)),o=new Map((r.upsert_licenses??[]).map(s=>[s.license_plan_id,s])),a=[];for(let s of n.licenses??[]){if(i.has(s.license_plan_id))continue;let c=o.get(s.license_plan_id);if(c){a.push(e({existing:s,upsert:c})),o.delete(s.license_plan_id);continue}a.push(s)}for(let s of r.upsert_licenses??[])o.has(s.license_plan_id)&&a.push(e({upsert:s}));return a}}))(ow),{pricesEqual:lg}=(e=>({pricesEqual:(n,r)=>n===void 0&&r===void 0||n===null&&r===null?!0:n==null||r==null?!1:n.amount===r.amount&&n.interval===r.interval&&(n.interval_count??1)===(r.interval_count??1)&&e(n.additional_currencies,r.additional_currencies)}))(au),{itemPricesEqual:h1}=((e,t,n)=>({itemPricesEqual:(i,o)=>{if(i==null&&o==null)return!0;if(i==null||o==null)return!1;let a=i.tiers?.length?i.tier_behavior??e.Graduated:null,s=o.tiers?.length?o.tier_behavior??e.Graduated:null;return(i.amount??null)===(o.amount??null)&&t(i.additional_currencies,o.additional_currencies)&&n(i.tiers,o.tiers)&&a===s&&i.interval===o.interval&&(i.interval_count??1)===(o.interval_count??1)&&(i.billing_units??1)===(o.billing_units??1)&&i.billing_method===o.billing_method&&(i.max_purchase??null)===(o.max_purchase??null)}}))(xa,au,sw),{featureOverridesEqual:g1}=((e,t)=>({featureOverridesEqual:(r,i)=>r==null&&i==null?!0:r==null||i==null?!1:e(r.credit_schema)===e(i.credit_schema)&&t(r.markups??{})===t(i.markups??{})}))(lw,ou),{freeTrialsEqual:b1}=(e=>({freeTrialsEqual:(n,r)=>n===void 0&&r===void 0||n===null&&r===null?!0:n==null||r==null?!1:n.duration_length===r.duration_length&&(n.duration_type??e.Month)===(r.duration_type??e.Month)&&(n.card_required??!0)===(r.card_required??!0)&&(n.on_end??"bill")===(r.on_end??"bill")}))(mw),{planItemFiltersEqual:_1}=(e=>({planItemFiltersEqual:(n,r)=>n.feature_id===r.feature_id&&(n.billing_method??null)===(r.billing_method??null)&&(n.interval??null)===(r.interval??null)&&e({interval:n.interval,intervalCount:n.interval_count})===e({interval:r.interval,intervalCount:r.interval_count})&&(n.included??null)===(r.included??null)}))(hw),{toUpsertLicense:y1}=(e=>({toUpsertLicense:({license:n,clearCustomize:r=!1})=>({license_plan_id:n.license_plan_id,...n.version_slug!==void 0?{version_slug:n.version_slug}:{},included:n.included,prepaid_only:n.prepaid_only,...r?{customize:null}:e(n.customize)?{customize:n.customize}:{}})}))(Yh),{getVariantSettingsPatch:r4}=((e,t)=>({getVariantSettingsPatch:({from:r,to:i})=>{let o={};for(let a of e)t(r[a],i[a])||(o[a]=i[a]);return o}}))(bw,_w),{isOneOffProductV2:i4}=((e,t,n,r)=>({isOneOffProductV2:({items:o})=>{let a=o.filter(s=>e(s)||t(s));return a.length>0&&a.every(s=>n({item:s})===r.OneOff)}}))(Oa,zr,Kn,xn),{canonicalizeBillingControls:S1}=(e=>({canonicalizeBillingControls:n=>{let r=n??{},i={};for(let o of Object.keys(r)){let a=r[o];Array.isArray(a)&&a.length===0||(i[o]=Array.isArray(a)?[...a].sort((s,c)=>String(s?.feature_id??"").localeCompare(String(c?.feature_id??""))):a)}return JSON.stringify(e(i))}}))(Jh),{ProductConfigSchema:v1}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(Ae,vw),{shouldApplyVariantUpdates:o4}=(e=>({shouldApplyVariantUpdates:({oldBase:n,latestBase:r,propagateToVariants:i,variantUpdates:o,updates:a})=>i.length>0||o.length>0||n.internal_id!==r.internal_id?!0:e.some(s=>a[s]!==void 0)}))(xw),{resolveLicenseParentTargets:a4}=((e,t,n)=>({resolveLicenseParentTargets:({contexts:i,targets:o,childPlanId:a})=>{let s=new Map(i.map(l=>[e({planId:l.parent.id,version:l.parent.version}),l])),c=new Set,u=[];for(let l of o){let d=e({planId:l.plan_id,version:l.version});if(c.has(d))throw new t({message:`Parent plan target ${d} was selected more than once.`,code:n.InvalidPropagationTarget,statusCode:400});let m=s.get(d);if(!m)throw new t({message:`Plan ${l.plan_id} v${l.version} does not offer ${a} as a license.`,code:n.InvalidPropagationTarget,statusCode:400});c.add(d),u.push(m)}return u}}))(Iw,jt,qt),{stripeMinorUnitFactor:Ca}=((e,t)=>({stripeMinorUnitFactor:r=>{let i=(r??"usd").toLowerCase();return e.has(i)?1:t.has(i)?1e3:100}}))(Xh,Aw),{entIntervalsSame:x1}=(e=>({entIntervalsSame:({intervalA:n,intervalB:r})=>{let i=e(n.interval,n.intervalCount),o=e(r.interval,r.intervalCount);return i.eq(o)}}))(ww),{intervalsDifferent:I1}=((e,t)=>({intervalsDifferent:({intervalA:r,intervalB:i})=>{if(e(r)&&e(i))return!1;if(e(r)||e(i))return!0;let o=t(r.interval,r.intervalCount),a=t(i.interval,i.intervalCount);return o!==a}}))(Yt,Pw),{allocatedBillingBehaviorAreSame:A1}=(e=>({allocatedBillingBehaviorAreSame:({item1:n,item2:r})=>{let i=e(n),o=e(r);return i===o}}))(Cw),{tiersAreSame:w1}=(e=>({tiersAreSame:(n,r)=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every((i,o)=>i.amount===r[o].amount&&i.to===r[o].to&&(i.flat_amount??null)===(r[o].flat_amount??null)&&e(i.additional_currencies,r[o].additional_currencies))}))(su),{itemToPriceOrTiers:P1}=(e=>({itemToPriceOrTiers:({item:n,proration:r,now:i})=>{if(i=i||Date.now(),n.price)return{price:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:n.price}):n.price,tiers:void 0};if(n.tiers)return n.tiers.length>1?{price:void 0,tiers:n.tiers.map(o=>({...o,amount:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:o.amount}):o.amount}))}:{price:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:n.tiers[0].amount}):n.tiers[0].amount,tiers:void 0}}}))(Rw),{normalizeBillingControls:O1}=((e,t,n)=>({normalizeBillingControls:i=>{let o=e(i);return JSON.stringify(t.flatMap(a=>{let s=o?.[a];return s?.length?[[a,n(s)]]:[]}))}}))(Nw,Sa,Fw),{AutoTopupPurchaseLimitSchema:C1}=((e,t)=>({AutoTopupPurchaseLimitSchema:e.object({interval:t.meta({description:"The time interval for the purchase limit window."}),interval_count:e.number().min(1).default(1).meta({description:"Number of intervals in the purchase limit window."}),limit:e.number().min(1).meta({description:"Maximum number of auto top-ups allowed within the interval."})})}))(Ae,Lw),{toFeatureItem:E1}=((e,t,n,r)=>({toFeatureItem:({ent:o})=>{if(o.feature.type===e.Boolean)return{feature_id:o.feature.id,entity_feature_id:o.entity_feature_id,entitlement_id:o.id};let a=o.rollover||o.feature_override?{rollover:o.rollover??void 0,feature_override:o.feature_override??void 0}:void 0;return{feature_id:o.feature.id,included_usage:o.allowance_type===t.Unlimited?n:o.allowance,interval:r({entInterval:o.interval}),interval_count:o.interval_count??1,entity_feature_id:o.entity_feature_id,pooled:o.pooled??!1,reset_usage_when_enabled:!o.carry_from_previous,config:a,entitlement_id:o.id,created_at:o.created_at}}}))(It,va,$i,ng),{toPriceItem:T1}=((e,t)=>({toPriceItem:({price:r})=>{let i=r.config;return{feature_id:null,interval:e({billingInterval:i.interval}),interval_count:i.interval_count??1,price:i.amount,additional_currencies:t(i.currencies)??void 0,base_currency:i.base_currency??void 0,price_id:r.id,created_at:r.created_at,price_config:r.config}}}))(rg,rA),{isPayPerUsePrice:dg}=((e,t)=>({isPayPerUsePrice:({price:r})=>{let i=e(r.config);return i===t.UsageInArrear||i===t.InArrearProrated}}))(cu,Hr),{createFeaturesFromItems:R1}=((e,t,n,r,i,o,a,s,c,u)=>({createFeaturesFromItems:({items:d,curFeatures:m,orgId:g,env:p})=>{let f=[];for(let y of d){if(!y.feature_id)continue;let x=m.find(S=>S.id===y.feature_id);if(x){if(e(y.feature_type))continue;if(y.feature_type===t.Static){if(y.feature_type===t.Static&&x.type!==n.Boolean)throw new r({message:`Feature ${y.feature_id} already exists but is not a static feature`,code:i.InvalidRequest,statusCode:400})}else if(y.feature_type!==x.config?.usage_type)throw new r({message:`Feature ${y.feature_id} already exists but is not a ${y.feature_type} feature`,code:i.InvalidRequest,statusCode:400});continue}if(o(y.feature_id),a(y)){let S=s({featureId:y.feature_id,orgId:g,env:p});f.push(S)}else{if(!y.feature_type)throw new r({message:`Feature type is required for ${y.feature_id}. Either 'continuous_use' or 'single_use'`,code:i.InvalidRequest,statusCode:400});let S=c({featureId:y.feature_id,orgId:g,env:p,usageType:y.feature_type===t.ContinuousUse?u.Continuous:u.Single});f.push(S)}}return{allFeatures:[...m,...f],newFeatures:f}}}))(Zr,In,It,jt,qt,aA,ag,qw,Vw,Gn),{SUPPORTED_SET:j1}=(e=>({SUPPORTED_SET:new Set(e)}))($w),{CreditDimensionSchema:k1}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(Ae,Qw,Vh,sg),{FeatureMarkupsOverrideSchema:D1}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(Ae,Zw,bA),{validateCreditRate:pg}=(e=>({validateCreditRate:({rate:n,invalidCreditSystem:r})=>{if(n.tier_behavior==="graduated"){(!Array.isArray(n.tiers)||n.tiers.length===0)&&r("Graduated credit schemas require at least one tier.");let o=n.tiers??[];for(let s of o){let c=Number(s.credit_amount);(!Number.isFinite(c)||c<0)&&r("Tier credit costs must be zero or greater."),s.credit_amount=c,s.to!=="inf"&&(s.to=Number(s.to))}let[a]=e(o.map(s=>s.to));a&&r(a.message);return}let i=Number(n.credit_amount);(!Number.isFinite(i)||i<0)&&r("Credit cost must be zero or greater."),n.credit_amount=i}}))(Jw),{validateDimensionsAreSeparable:N1}=((e,t)=>({validateDimensionsAreSeparable:({dimensions:r,invalidCreditSystem:i})=>{let[o]=e(r);if(!o)return;let[a,s]=o.names;i(`Dimensions "${a}" and "${s}" can both match the same event (${t(o.example)}). Give one more match keys or a priority.`)}}))(Xw,SA),{validateCreditMultipliers:F1}=((e,t)=>({validateCreditMultipliers:({schemaItem:r,invalidCreditSystem:i})=>{for(let[o,a]of Object.entries(r.multipliers??{}))e({name:o,multiplier:a,invalidCreditSystem:i});t({schemaItem:r,invalidCreditSystem:i})}}))(vA,zw),{FixedPriceConfigSchema:U1}=((e,t,n,r,i)=>({FixedPriceConfigSchema:e.object({type:e.string(),amount:e.number().min(0),interval:e.enum(t),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),n).nullish(),billing_units:e.number().nullish(),usage_tiers:e.array(r).nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),feature_id:i,internal_feature_id:i})}))(Ae,xn,cg,iu,OA),{currenciesAreCompatible:M1}=(e=>({currenciesAreCompatible:(n,r)=>{let i=n??{},o=r??{};for(let a of Object.keys(i)){let s=o[a];if(!s)continue;let c=i[a];if((c?.amount??null)!==(s.amount??null)||!e(c?.usage_tiers??[],s.usage_tiers??[]))return!1}return!0}}))(ug),{creditSchemaItemsAreSame:B1}=(e=>({creditSchemaItemsAreSame:({left:n,right:r})=>(n.feature_amount??1)==(r.feature_amount??1)&&e({left:n,right:r})&&n.credit_amount==r.credit_amount&&(n.tier_behavior??null)===(r.tier_behavior??null)&&(n.tiers??[]).length===(r.tiers??[]).length&&(n.tiers??[]).every((i,o)=>i.to===r.tiers?.[o]?.to&&i.credit_amount==r.tiers?.[o]?.credit_amount)}))(i1),{markupOverridesAreSame:L1}=(e=>({markupOverridesAreSame:({markups1:n,markups2:r})=>n&&r?(n.default_markup??null)===(r.default_markup??null)&&e(n.provider_markups,r.provider_markups)&&e(n.model_markups,r.model_markups):!(n||r)}))(o1),{resolveAllocatedBillingBehavior:q1}=((e,t,n,r)=>({resolveAllocatedBillingBehavior:({item:o,curPrice:a})=>{if(e(o.config?.allocated_billing_behavior))return o.config.allocated_billing_behavior;if(e(o.config?.on_increase)||e(o.config?.on_decrease))return t.Prorated;if(a&&n({price:a})){let c=a.config;return e(c.allocated_billing_behavior)?c.allocated_billing_behavior:r(a)?t.Prorated:t.Arrear}return t.Arrear}}))(pr,$n,dg,og),{itemCanBeProrated:V1}=((e,t,n)=>({itemCanBeProrated:({item:i,features:o})=>{let a=e({item:i,features:o});return a===t.SingleUse&&i.usage_model===n.Prepaid?!0:a===t.ContinuousUse}}))(s1,In,Qr),{priceHasPreviewStripeId:G1}=((e,t)=>({priceHasPreviewStripeId:({price:r})=>{let i=r.config;return e.some(o=>t({stripeId:i[o]}))}}))(VA,c1),{buildPlanItemKey:$1}=((e,t)=>({buildPlanItemKey:({item:r,matchPrecision:i=e.FeatureBillingMethodCadence})=>{let o=t({item:r});return i===e.FeatureCadence&&o.splice(1,1),o.join("|")}}))(JA,d1),{itemsEqual:mg}=((e,t,n,r)=>({itemsEqual:(o,a)=>o.feature_id===a.feature_id&&(o.entity_feature_id??null)===(a.entity_feature_id??null)&&(o.pooled??!1)===(a.pooled??!1)&&(o.included??0)===(a.included??0)&&(o.unlimited??!1)===(a.unlimited??!1)&&(o.reset?.interval??null)===(a.reset?.interval??null)&&(o.reset?.interval_count??1)===(a.reset?.interval_count??1)&&e(o.price,a.price)&&t(o.rollover,a.rollover)&&n(o.proration,a.proration)&&r(o.feature_override,a.feature_override)}))(h1,cw,uw,g1),{licenseCustomizesAreSame:K1}=((e,t,n,r)=>({licenseCustomizesAreSame:({left:o,right:a})=>{let s=o??{},c=a??{},u={price:!e(s.price,c.price),addItems:!t({left:s.add_items,right:c.add_items,equals:n}),removeItems:!t({left:s.remove_items,right:c.remove_items,equals:r})};return!Object.values(u).some(Boolean)}}))(lg,fw,mg,_1),{normalizeVariantSettingValue:W1}=((e,t,n)=>({normalizeVariantSettingValue:({field:i,value:o})=>{if(i==="group")return o||"";if(i==="description")return o||null;if(i==="billing_controls")return e(o);if(i==="config"){let a=t.safeParse(o??{});return JSON.stringify(n(a.success?a.data:o??{}))}return i==="metadata"?JSON.stringify(n(o??{})):o}}))(S1,v1,Jh),{intervalsSame:H1}=(e=>({intervalsSame:({intervalA:n,intervalB:r})=>!e({intervalA:n,intervalB:r})}))(I1),{sanitizeItems:Q1}=((e,t,n,r)=>({sanitizeItems:({items:o,features:a})=>o.map(s=>{let c=s.tiers?.length===1&&s.tiers[0].additional_currencies?.length?{price:void 0,tiers:s.tiers}:e({item:s}),u={...s,reset_usage_when_enabled:t({item:s,feature:a.find(l=>l.id===s.feature_id)}),...c};return u.config||(u.config={on_increase:n.ProrateImmediately,on_decrease:r.ProrateImmediately}),u})}))(P1,jw,Jr,Wi),{compareBillingControls:Z1}=(e=>({compareBillingControls:({newBillingControls:n,curBillingControls:r})=>e(n)===e(r)}))(O1),{AutoTopupSchema:Y1}=((e,t)=>({AutoTopupSchema:e.object({feature_id:e.string().meta({description:"The ID of the feature (credit balance) to auto top-up."}),enabled:e.boolean().default(!1).meta({description:"Whether auto top-up is enabled."}),threshold:e.number().meta({description:"When the balance drops below this threshold, an auto top-up will be purchased."}),quantity:e.number().min(1).meta({description:"Amount of credits to add per auto top-up."}),purchase_limit:t.optional().meta({description:"Optional rate limit to cap how often auto top-ups occur."}),invoice_mode:e.boolean().optional().meta({description:"When true, auto top-up creates a send_invoice invoice instead of auto-charging."})})}))(Ae,C1),{toFeaturePriceItem:J1}=((e,t,n,r,i,o,a,s,c,u,l)=>({toFeaturePriceItem:({ent:m,price:g})=>{let p=g.config,f=e(p.currencies,p.usage_tiers.length),y=p.usage_tiers.map((j,A)=>({amount:j.amount,to:j.to===-1?t:j.to,flat_amount:j.flat_amount,...f?.[A]?.length?{additional_currencies:f[A]}:{}})),x={};return g.proration_config&&(x={...g.proration_config}),n({feature:m.feature})&&r({price:g})&&(x.allocated_billing_behavior=p.allocated_billing_behavior??(i(g)?o.Prorated:o.Arrear)),m.rollover&&(x.rollover=m.rollover),m.expiry_duration&&m.expiry_length!=null&&(x.expiry={duration:m.expiry_duration,length:m.expiry_length}),m.feature_override&&(x.feature_override=m.feature_override),p.threshold_billing&&(x.threshold_billing=p.threshold_billing),{feature_id:m.feature.id,feature_type:m.feature.config?.usage_type||a.SingleUse,included_usage:m.allowance,interval:s({entInterval:m.interval}),interval_count:m.interval_count??1,price_interval:c({billingInterval:p.interval}),price_interval_count:p.interval_count??1,price:null,tiers:y,base_currency:p.base_currency??void 0,billing_units:p.billing_units,tier_behavior:g.tier_behavior??null,entity_feature_id:m.entity_feature_id,pooled:m.pooled??!1,reset_usage_when_enabled:!m.carry_from_previous,usage_model:p.bill_when===u.StartOfPeriod||p.bill_when===u.InAdvance?l.Prepaid:l.PayPerUse,created_at:m.created_at,entitlement_id:m.id,price_id:g.id,price_config:g.config,config:Object.keys(x).length>0?x:void 0,usage_limit:m.usage_limit}}}))(iA,Xc,ig,dg,og,$n,In,ng,rg,Ki,Qr),{isValidCurrencyCode:lu}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(j1),{CreditSchemaItemBaseSchema:fg}=((e,t,n,r)=>({CreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(t,n).optional(),multipliers:e.record(t,r).optional()})}))(Ae,Hw,k1,gA),{GraduatedCreditSchemaItemSchema:X1}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(fg,sg),{validateCreditDimensionRules:z1}=((e,t,n)=>({validateCreditDimensionRules:({schemaItem:i,invalidCreditSystem:o})=>{let a=i.dimensions??{};for(let[s,c]of Object.entries(a))c.priority!==void 0&&!Number.isInteger(c.priority)&&o(`Dimension "${s}" priority must be an integer.`),e({rate:c,invalidCreditSystem:o});t({dimensions:a,invalidCreditSystem:o}),n({schemaItem:i,invalidCreditSystem:o})}}))(pg,N1,F1),{pricesAreSame:Ea}=((e,t,n,r,i,o,a,s)=>({pricesAreSame:(u,l,d=!1)=>{let m=u.config,g=l.config;if(m.type!==g.type)return!1;if(m.type===e.Fixed){let A=t.parse(m),v=t.parse(g),G={amount:A.amount!==v.amount,interval:A.interval!==v.interval,intervalCount:(A.interval_count??1)!==(v.interval_count??1),baseCurrency:!n({base1:A.base_currency,base2:v.base_currency,currencies1:A.currencies,currencies2:v.currencies}),currencies:!r(A.currencies,v.currencies)};return!Object.values(G).some(Boolean)}let p=i.parse(m),f=i.parse(g),y={shouldProrate:(p.should_prorate??!1)!==(f.should_prorate??!1),allocatedBillingBehavior:o(p)!==o(f),billWhen:p.bill_when!==f.bill_when,billingUnits:(p.billing_units??1)!==(f.billing_units??1),thresholdBilling:p.threshold_billing?.threshold!==f.threshold_billing?.threshold,interval:p.interval!==f.interval,intervalCount:(p.interval_count??1)!==(f.interval_count??1),internalFeatureId:p.internal_feature_id!==f.internal_feature_id,featureId:p.feature_id!==f.feature_id,usageTiers:!a(p.usage_tiers,f.usage_tiers),baseCurrency:!n({base1:p.base_currency,base2:f.base_currency,currencies1:p.currencies,currencies2:f.currencies}),currencies:!r(p.currencies,f.currencies)},x=p.usage_tiers.length<=1&&f.usage_tiers.length<=1,S={onIncrease:u.proration_config?.on_increase!=l.proration_config?.on_increase,onDecrease:u.proration_config?.on_decrease!=l.proration_config?.on_decrease,tierBehavior:!x&&(u.tier_behavior??s.Graduated)!==(l.tier_behavior??s.Graduated)},j=Object.values(y).some(Boolean)||Object.values(S).some(Boolean);return j&&d&&console.log("Prices are different",{configDiffs:y,prorationDiffs:S}),!j}}))(Wr,U1,t1,M1,n1,TA,ug,xa),{creditSchemasAreSame:eP}=(e=>({creditSchemasAreSame:({schema1:n,schema2:r})=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every(i=>{let o=r.find(a=>a.metered_feature_id===i.metered_feature_id);return o?e({left:i,right:o}):!1})}))(B1),{itemToAllocatedBillingBehavior:tP}=((e,t,n,r,i,o,a,s,c)=>({itemToAllocatedBillingBehavior:({item:l,features:d,curPrice:m})=>{if(!(e({item:l,features:d})===t.ContinuousUse&&n(l)&&l.usage_model!==r.Prepaid))return null;let f=i({item:l,curPrice:m});if(f===o.Arrear){if(a(l.config?.on_increase)||a(l.config?.on_decrease))throw new s({message:`on_increase / on_decrease are not supported for allocated arrear billing (feature: ${l.feature_id})`,code:c.InvalidProductItem,statusCode:400});if(a(l.config?.rollover))throw new s({message:`rollover is not supported for allocated arrear billing because the balance never resets (feature: ${l.feature_id})`,code:c.InvalidProductItem,statusCode:400})}return f}}))(a1,In,zr,Qr,q1,$n,pr,jt,UA),{composeMatchKey:Hi}=(e=>({composeMatchKey:n=>e({item:n})}))($1),{applyItems:nP}=((e,t,n,r)=>({applyItems:(o,a)=>{let s=[...o];if(a.remove_items&&(s=e(s,a.remove_items)),a.add_items){let c=new Set;for(let u of s)t(u)&&c.add(n(u));for(let u of a.add_items){let l=n(u);t(u)&&c.has(l)||(s.push(r(u)),t(u)&&c.add(l))}}return s}}))(p1,tw,Hi,m1),{dedupeItemsByMatchKey:rP}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let o=e(i);return r.has(o)?!1:(r.add(o),!0)})}}))(Hi),{planLicensesAreSame:iP}=(e=>({planLicensesAreSame:({left:n,right:r})=>{let i={licensePlanId:n.license_plan_id!==r.license_plan_id,versionSlug:n.version_slug!==r.version_slug,included:n.included!==r.included,prepaidOnly:n.prepaid_only!==r.prepaid_only,customize:!e({left:n.customize,right:r.customize})};return!Object.values(i).some(Boolean)}}))(K1),{dedupeItemsByMatchKey:oP}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let o=e(i);return r.has(o)?!1:(r.add(o),!0)})}}))(Hi),{validateVariantSettingsUpdate:s4}=((e,t,n,r)=>({validateVariantSettingsUpdate:({allowVariantSettingsUpdate:o,fullProduct:a,currentProduct:s,updates:c})=>{if(o||a.base_internal_product_id==null)return;let u=e.find(l=>c[l]===void 0?!1:t({field:l,value:c[l]})!==t({field:l,value:s[l]}));if(u)throw new n({message:`Cannot update ${u} directly on a variant plan.`,code:r.InvalidPropagationTarget,statusCode:400})}}))(Sw,W1,jt,qt),{findSimilarItem:du}=((e,t,n,r,i,o,a,s,c)=>({findSimilarItem:({item:l,items:d})=>e(l)?d.find(m=>e(m)&&m.feature_id===l.feature_id&&m.entity_feature_id==l.entity_feature_id&&t({intervalA:{interval:n({item:m}),intervalCount:r({item:m})},intervalB:{interval:n({item:l}),intervalCount:r({item:l})}})):i(l)?d.find(m=>i(m)&&m.feature_id===l.feature_id&&m.entity_feature_id==l.entity_feature_id&&o({intervalA:{interval:a({item:m}),intervalCount:s({item:m})},intervalB:{interval:a({item:l}),intervalCount:s({item:l})}})&&l.usage_model==m.usage_model):c(l)?d.find(m=>c(m)&&m.price==l.price&&a({item:m})==a({item:l})&&s({item:m})==s({item:l})):null}))(Pa,x1,Aa,wa,zr,H1,Kn,Xr,Oa),{stripAutoTopupCountsForStorage:aP}=(e=>({stripAutoTopupCountsForStorage:n=>n==null?n:n.map(r=>e.parse({...r,purchase_limit:r.purchase_limit?{interval:r.purchase_limit.interval,interval_count:r.purchase_limit.interval_count??1,limit:r.purchase_limit.limit}:void 0}))}))(Y1),{toProductItem:hg}=((e,t,n,r)=>({toProductItem:({ent:o,price:a})=>e(a)?t({ent:o}):e(o)?n({price:a}):r({ent:o,price:a})}))(Yt,E1,T1,J1),{CurrencyCodeSchema:gg}=((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')."})}))(Ae,lu),{AdditionalCurrencyPriceSchema:sP}=((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."})})}))(Ae,gg),{FlatCreditSchemaItemSchema:cP}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(fg,Vh),{validateCreditSystem:uP}=((e,t,n,r,i,o,a,s)=>({validateCreditSystem:(u,l=e.CreditSystem)=>{let d=Array.isArray(u?.schema)?u.schema:[],m=S=>{throw new t({message:S,code:n.InvalidFeature,statusCode:r.BAD_REQUEST})};!i(l)&&d.length===0&&m("At least one metered feature is required for credit system"),i(l)&&d.length>0&&m("AI credit systems are leaf features and cannot define a schema. Model rates live in model_markups.");let g=d.map(S=>S.metered_feature_id),p=Array.from(new Set(g));g.length!==p.length&&m("Credit system contains multiple of the same metered_feature_id");let f={...u,schema:d,usage_type:o.Single},y=f.default_markup;if(y!=null){let S=Number(y);if(Number.isNaN(S)||S<-100)throw new t({message:"Default markup must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});f.default_markup=S}let x=f.provider_markups;if(x!=null)for(let[S,j]of Object.entries(x)){let A=Number(j?.markup);if(!S||Number.isNaN(A)||A<-100)throw new t({message:"Provider markups must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});j.markup=A}for(let S of f.schema){if(S.feature_amount!==void 0){let j=Number(S.feature_amount);(!Number.isFinite(j)||j<=0)&&m("Billing units must be greater than zero."),S.feature_amount=j}a({rate:S,invalidCreditSystem:m}),s({schemaItem:S,invalidCreditSystem:m})}return f}}))(It,jt,qt,Vn,nu,Gn,pg,z1),{stripePriceIdForInitializedPrice:bg}=((e,t,n)=>({stripePriceIdForInitializedPrice:({requestedStripePriceId:i,currentPrice:o,newPrice:a})=>{if(!e(i)&&(!o||i!==t({price:o})||n(o,a)))return i}}))(Yt,PA,Ea),{featureOverridesAreSame:pu}=((e,t)=>({featureOverridesAreSame:({override1:r,override2:i})=>e({schema1:r?.schema,schema2:i?.schema})&&t({markups1:r?.markups,markups2:i?.markups})}))(eP,L1),{applyDiff:_g}=((e,t,n,r)=>({applyDiff:({base:o,diff:a})=>{let s={price:e(o.price,a.price),items:t(o.items,a),free_trial:n(o.free_trial,a.free_trial)},c=r({base:o,diff:a});return c===void 0?s:{...s,licenses:c}}}))(zA,nP,iw,f1),{diffPlanLicenses:lP}=((e,t,n,r)=>({diffPlanLicenses:({from:o,to:a,includeAdds:s=!1,includeRemoves:c=!1})=>{let u=new Map((o??[]).map(g=>[g.license_plan_id,g])),l=new Map((a??[]).map(g=>[g.license_plan_id,g])),d=[];for(let g of l.values()){let p=u.get(g.license_plan_id);!p&&!s||p&&e({left:p,right:g})||d.push(t({license:g,clearCustomize:p!=null&&n(p.customize)&&!n(g.customize)}))}let m=c?[...u.keys()].filter(g=>!l.has(g)).map(g=>({license_plan_id:g})):[];return{...d.length>0?{upsert_licenses:d.sort(r)}:{},...m.length>0?{remove_licenses:m.sort(r)}:{}}}}))(iP,y1,Yh,gw),{applyDiffToVariantPlan:c4}=((e,t)=>({applyDiffToVariantPlan:({plan:r,diff:i,settingsPatch:o={}})=>{let a=e({base:r,diff:i});return{...r,...a,...o,items:t(a.items)}}}))(_g,oP),{mapToProductItems:yg}=((e,t,n,r)=>({mapToProductItems:({prices:o,entitlements:a,features:s})=>{let c=[];o??=[],a??=[];for(let u of a){let l=e({ent:u,prices:o}),d=t({ent:u,price:l});c.push(d)}for(let u of o)n({price:u,entitlements:a})||c.push(t({price:u}));for(let u of c)s.find(d=>d.id===u.feature_id)&&(u.feature_type=r({item:u,features:s}));return c}}))(Dh,hg,uu,Nh),{featureItemsAreSame:dP}=((e,t,n)=>({featureItemsAreSame:({item1:i,item2:o,logDifferences:a=!1})=>{let s={feature_id:{condition:i.feature_id===o.feature_id,message:`Feature ID different: ${i.feature_id} != ${o.feature_id}`},included_usage:{condition:e(i.included_usage)==e(o.included_usage),message:`Included usage different: ${i.included_usage} != ${o.included_usage}`},interval:{condition:i.interval==o.interval,message:`Interval different: ${i.interval} != ${o.interval}`},interval_count:{condition:(i.interval_count||1)==(o.interval_count||1),message:`Interval count different: ${i.interval_count} != ${o.interval_count}`},entity_feature_id:{condition:i.entity_feature_id==o.entity_feature_id,message:`Entity feature ID different: ${i.entity_feature_id} != ${o.entity_feature_id}`},pooled:{condition:(i.pooled??!1)===(o.pooled??!1),message:`Pooled different: ${i.pooled} != ${o.pooled}`},reset_usage_when_enabled:{condition:(i.reset_usage_when_enabled??!1)===(o.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${i.reset_usage_when_enabled} !== ${o.reset_usage_when_enabled}`},rollover_config:{condition:t({rollover1:i.config?.rollover||void 0,rollover2:o.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(i.config?.rollover)} !== ${JSON.stringify(o.config?.rollover)}`},feature_override:{condition:n({override1:i.config?.feature_override,override2:o.config?.feature_override}),message:`Feature override different: ${JSON.stringify(i.config?.feature_override)} !== ${JSON.stringify(o.config?.feature_override)}`},threshold_billing:{condition:(i.config?.threshold_billing?.threshold??null)===(o.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(i.config?.threshold_billing)} !== ${JSON.stringify(o.config?.threshold_billing)}`}},c=Object.values(s).every(u=>u.condition);return!c&&a&&console.log("Feature items different:",Object.values(s).filter(u=>!u.condition).map(u=>u.message)),c}}))(eg,tg,pu),{featurePriceItemsAreSame:pP}=((e,t,n,r,i,o,a,s,c,u)=>({featurePriceItemsAreSame:({item1:d,item2:m,logDifferences:g=!1})=>{let p={included_usage:{condition:e(d.included_usage)==e(m.included_usage),message:`Included usage different: ${d.included_usage} != ${m.included_usage}`},usage_limit:{condition:d.usage_limit==m.usage_limit,message:`Usage limit different: ${d.usage_limit} !== ${m.usage_limit}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(m.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${m.reset_usage_when_enabled}`},proration_config:{condition:t({config1:d.config||void 0,config2:m.config||void 0}),message:`Proration config different: ${JSON.stringify(d.config)} !== ${JSON.stringify(m.config)}`},allocated_billing_behavior:{condition:n({item1:d,item2:m}),message:`Allocated billing behavior different: ${d.config?.allocated_billing_behavior} !== ${m.config?.allocated_billing_behavior}`},rollover_config:{condition:r({rollover1:d.config?.rollover||void 0,rollover2:m.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(d.config?.rollover)} !== ${JSON.stringify(m.config?.rollover)}`},feature_override:{condition:i({override1:d.config?.feature_override,override2:m.config?.feature_override}),message:`Feature override different: ${JSON.stringify(d.config?.feature_override)} !== ${JSON.stringify(m.config?.feature_override)}`},threshold_billing:{condition:(d.config?.threshold_billing?.threshold??null)===(m.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(d.config?.threshold_billing)} !== ${JSON.stringify(m.config?.threshold_billing)}`},entity_feature_id:{condition:d.entity_feature_id==m.entity_feature_id,message:`Entity feature ID different: ${d.entity_feature_id} != ${m.entity_feature_id}`},pooled:{condition:(d.pooled??!1)===(m.pooled??!1),message:`Pooled different: ${d.pooled} != ${m.pooled}`}},f={feature_id:{condition:d.feature_id===m.feature_id,message:`Feature ID different: ${d.feature_id} != ${m.feature_id}`},interval:{condition:o({item:d})==o({item:m}),message:`Billing interval different: ${o({item:d})} != ${o({item:m})}`},interval_count:{condition:a({item:d})==a({item:m}),message:`Billing interval count different: ${a({item:d})} != ${a({item:m})}`},usage_model:{condition:d.usage_model===m.usage_model,message:`Usage model different: ${d.usage_model} != ${m.usage_model}`},pricing:{condition:s(c(d),c(m)),message:`Pricing different: ${JSON.stringify(c(d))} != ${JSON.stringify(c(m))}`},additional_currencies:{condition:u(d.additional_currencies,m.additional_currencies),message:"Additional currencies different"},tier_behavior:{condition:(c(d)?.length??0)<=1&&(c(m)?.length??0)<=1?!0:d.tier_behavior==m.tier_behavior,message:`Tiers type different: ${d.tier_behavior} != ${m.tier_behavior}`},billing_units:{condition:d.billing_units==m.billing_units,message:`Billing units different: ${d.billing_units} !== ${m.billing_units}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(m.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${m.reset_usage_when_enabled}`}},y=Object.values(f).every(S=>S.condition)&&Object.values(p).every(S=>S.condition),x=Object.values(f).some(S=>!S.condition);return!y&&g&&console.log("Feature price items different:",Object.values(p).filter(S=>!S.condition).map(S=>S.message),Object.values(f).filter(S=>!S.condition).map(S=>S.message)),{same:y,pricesChanged:x}}}))(eg,Ow,A1,tg,pu,Kn,Xr,w1,Ew,su),{pickBillingControlColumns:mP}=((e,t)=>({pickBillingControlColumns:r=>{if(!r)return{};let i=Object.fromEntries(e.flatMap(o=>r[o]===void 0?[]:[[o,r[o]]]));return i.auto_topups!==void 0&&(i.auto_topups=t(i.auto_topups)),i}}))(Sa,aP),{mapToProductV2:u4}=((e,t,n,r,i)=>({mapToProductV2:({product:a,features:s})=>{let c=[];for(let l of a.entitlements){let d=e({ent:l,prices:a.prices});c.push(t({ent:l,price:d}))}for(let l of a.prices)n({price:l,entitlements:a.entitlements})||c.push(t({price:l}));s||(s=a.entitlements.map(l=>l.feature));for(let l of c)l.feature_type=r({item:l,features:s});return{internal_id:a.internal_id,id:a.id,name:a.name,description:a.description??null,is_add_on:a.is_add_on,is_default:a.is_default,version:a.version,version_slug:a.version_slug??null,active:a.active??!1,group:a.group||null,free_trial:a.free_trial,created_at:a.created_at,env:a.env,items:c,stripe_id:a.processor?.id||null,archived:a.archived||!1,config:a.config??void 0,billing_controls:i(a),metadata:a.metadata??{}}}}))(Dh,hg,uu,Nh,Fh),{AdditionalCurrencyTierSchema:fP}=((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"]})}))(Ae,gg),{AdditionalCurrencyPriceArraySchema:hP}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ae,sP,Bh,Lh),{CreditSchemaItemSchema:gP}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(Ae,cP,X1),{validateItemFeatureOverride:bP}=((e,t,n,r,i,o,a,s,c)=>({validateItemFeatureOverride:({item:l,feature:d,features:m})=>{let g=l.config?.feature_override;if(!g)return;let p=y=>{throw new e({message:`${y} (feature: ${l.feature_id})`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})};if(!(d&&r(d.type))){p("feature_override is only supported on credit system items");return}if(g.schema&&d.type!==i.CreditSystem&&p("feature_override.credit_schema is not supported on AI credit system items"),g.markups&&!o(d.type)&&p("feature_override.markups is only supported on AI credit system items"),!g.schema)return;let f={schema:g.schema,usage_type:a.Single};s(f,d.type),c({config:f,allFeatures:m});for(let y of g.schema)if(!m.find(S=>S.id===y.metered_feature_id))throw new e({message:`feature_override on ${d.id} references unknown feature ${y.metered_feature_id}`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})}}))(jt,qt,Vn,Yw,It,nu,Gn,uP,AA),{toPrice:_P}=((e,t,n,r,i,o,a)=>({toPrice:({item:c,orgId:u,internalProductId:l,isCustom:d,newVersion:m,curPrice:g})=>{let p={type:e.Fixed,amount:t(c.price)?c.price:c.tiers[0].amount,interval:n({item:c}),interval_count:r({item:c}),stripe_product_id:null,stripe_price_id:void 0,feature_id:null,internal_feature_id:null},f=i(c.additional_currencies);f&&(p.currencies=f);let y=c.base_currency??(f?g?.config?.base_currency:void 0);y&&(p.base_currency=y);let x={id:c.price_id||g?.id||o("pr"),created_at:c.created_at||Date.now(),org_id:u,internal_product_id:l,is_custom:d,config:p,proration_config:null};return(d||m)&&(x={...x,id:o("pr"),created_at:Date.now()}),p.stripe_price_id=a({requestedStripePriceId:c.stripe_price_id,currentPrice:g,newPrice:x}),{price:x,ent:null}}}))(Wr,Yr,Kn,Xr,e1,$r,bg),{entsAreSame:mu}=((e,t,n,r,i,o,a)=>({entsAreSame:(c,u)=>{if(c.internal_feature_id!==u.internal_feature_id||e(c)!==e(u))return!1;let l=e(c),d={interval:t(c)!==t(u),intervalCount:n(c)!==n(u),allowance:!l&&c.allowance!=u.allowance,carryFromPrevious:(c.carry_from_previous??!1)!==(u.carry_from_previous??!1),entityFeatureId:r(c.entity_feature_id)!==r(u.entity_feature_id),pooled:(c.pooled??!1)!==(u.pooled??!1),usageLimit:c.usage_limit!=u.usage_limit,rollover:!i({rollover1:c.rollover,rollover2:u.rollover}),featureOverride:!o({override1:c.feature_override,override2:u.feature_override}),expiry:!a(c,u)};return!Object.values(d).some(Boolean)}}))(RA,Hh,jA,kA,DA,pu,FA),{toFeatureAndPrice:yP}=((e,t,n,r,i,o,a,s,c,u,l,d,m,g,p,f,y,x,S,j,A,v,G,$,Pe,Re,se,V)=>({toFeatureAndPrice:({item:Y,orgId:at,internalFeatureId:me,internalProductId:ae,isCustom:Vt,curPrice:He,curEnt:Gt,newVersion:An,features:Jt})=>{let Ig=e({item:Y,feature:Jt.find(Pt=>Pt.id===Y.feature_id)}),ja=t({item:Y,features:Jt,curPrice:He}),Su=ja===n.Arrear,mr={id:Y.entitlement_id||Gt?.id||r("ent"),org_id:at,created_at:Y.created_at||Date.now(),is_custom:Vt,internal_product_id:ae,internal_feature_id:me,feature_id:Y.feature_id,allowance:Y.included_usage||0,allowance_type:i.Fixed,interval:o({item:Y}),interval_count:a({item:Y}),carry_from_previous:!Ig,entity_feature_id:Y.entity_feature_id,pooled:Y.pooled??!1,usage_limit:Y.usage_limit||null,rollover:Y.config?.rollover,expiry_duration:Y.config?.expiry?.duration,expiry_length:Y.config?.expiry?.length,feature_override:Y.config?.feature_override};(!Gt||Vt&&!s(Gt,mr)||An)&&(mr={...mr,id:r("ent"),created_at:Date.now()});let Ag=o({item:Y}),ei={type:c.Usage,bill_when:Y.usage_model===u.Prepaid?l.StartOfPeriod:l.EndOfPeriod,billing_units:Y.billing_units||1,...Y.config?.threshold_billing?{threshold_billing:Y.config.threshold_billing}:{},should_prorate:Ag===d.Lifetime&&!Su,...ja?{allocated_billing_behavior:ja}:{},internal_feature_id:me,feature_id:Y.feature_id,usage_tiers:m(Y.price)?[{amount:Y.price,to:g}]:Y.tiers?.map(Pt=>({to:Pt.to,amount:Pt.amount??0,...Pt.flat_amount!=null?{flat_amount:Pt.flat_amount}:{}})),interval:p({item:Y}),interval_count:f({item:Y}),stripe_price_id:void 0},vu=y({baseTiers:ei.usage_tiers,itemTiers:Y.tiers,flatCurrencies:Y.additional_currencies});vu&&(ei.currencies=vu,ei.base_currency=Y.base_currency??He?.config?.base_currency??void 0);let wg=x({item:Y,features:Jt})&&!Su,xu=null;if(wg){let Pt=Y.config?.on_increase||S.ProrateImmediately,Wn=Y.config?.on_decrease||j.Prorate;(A(Wn)||Wn===j.Prorate)&&(Wn=Pt===S.ProrateImmediately||Pt===S.BillImmediately?j.ProrateImmediately:j.ProrateNextCycle),xu={on_increase:Pt,on_decrease:Wn}}let gn={id:Y.price_id||He?.id||r("pr"),created_at:Y.created_at||Date.now(),org_id:at,internal_product_id:ae,is_custom:Vt,config:ei,entitlement_id:mr.id,proration_config:xu,tier_behavior:Y.tier_behavior??null},Iu=v(gn.config);if((Iu===G.UsageInArrear||Iu===G.InArrearProrated)&&gn.config.interval===$.OneOff)throw new Pe({message:`Usage prices cannot be one-off if not set to prepaid (feature: ${Y.feature_id})`,code:Re.InvalidPrice,statusCode:400});let Pg=He&&!se(He,gn,!0)||Gt&&!s(Gt,mr);if(He&&(Pg||An)){let Pt=gn.config,Wn=He.config;Pt.stripe_meter_id=Wn.stripe_meter_id,Pt.stripe_product_id=Wn.stripe_product_id,gn.config=Pt}return(Vt||An)&&(gn={...gn,id:r("pr"),created_at:Date.now()}),ei.stripe_price_id=V({requestedStripePriceId:Y.stripe_price_id,currentPrice:He,newPrice:gn}),{price:gn,ent:mr}}}))(Wh,tP,$n,$r,va,Aa,wa,mu,Wr,Qr,Ki,Kr,Yr,Xc,Kn,Xr,MA,V1,Jr,Wi,LA,qA,Hr,xn,jt,qt,Ea,bg),{getPriceStripeReuseLevel:SP}=((e,t,n,r,i,o)=>({getPriceStripeReuseLevel:({newPrice:s,candidatePrice:c,newEntitlements:u,candidateEntitlements:l})=>{if(e({price:c})||s.config?.type!==c.config?.type)return"none";if(t(c,s,!1)){if(s.config?.type!==n.Usage)return"full";let f=r({price:s,entitlements:u}),y=r({price:c,entitlements:l});if(!f&&!y)return"full";if(!f||!y)return"none";if(i(y,f))return"full"}if(s.config?.type!==n.Usage)return"none";let d=s.config,m=c.config;if(d.feature_id!==m.feature_id)return"none";let g=r({price:s,entitlements:u}),p=r({price:c,entitlements:l});return!g&&!p?"stripeProductOnly":!g||!p||o(g.entity_feature_id)!==o(p.entity_feature_id)?"none":"stripeProductOnly"}}))(G1,Ea,Wr,u1,mu,KA),{applyLicenseCustomizeToBasePlan:l4}=((e,t,n)=>({applyLicenseCustomizeToBasePlan:({basePlan:i,customize:o})=>{let a=new Set((o.add_items??[]).map(u=>e(u))),s={...i,items:i.items.filter(u=>!a.has(e(u)))},c=t({base:s,diff:o});return{...s,...c,items:n(c.items)}}}))(Hi,_g,rP),{diffPlanV1:vP}=((e,t,n,r,i,o,a,s,c)=>({diffPlanV1:({from:l,to:d,includeAdds:m=!1,includeRemoves:g=!1,filterPrecision:p=e.Identity})=>{let f={};t(l.price,d.price)||(f.price=d.price===null?null:n(d.price));let y=new Map(l.items.map(A=>[r(A),A])),x=new Map(d.items.map(A=>[r(A),A])),S=[];for(let A of d.items){let v=y.get(r(A));(!v||!i(v,A))&&S.push(o(A))}S.length>0&&(f.add_items=S);let j=[];for(let A of l.items){let v=x.get(r(A));(!v||!i(A,v))&&j.push(a({item:A,filterPrecision:p}))}if(j.length>0&&(f.remove_items=j),!s(l.free_trial,d.free_trial))if(d.free_trial==null)f.free_trial=null;else{let{on_end:A,...v}=d.free_trial;f.free_trial=A==null?v:{...v,on_end:A}}return Object.assign(f,c({from:l.licenses,to:d.licenses,includeAdds:m,includeRemoves:g})),f}}))(Zh,lg,aw,Hi,mg,dw,pw,b1,lP),{currentItemsOf:Sg}=(e=>({currentItemsOf:({currentFullProduct:n,features:r})=>e({prices:n.prices,entitlements:n.entitlements,features:r})}))(yg),{itemsAreSame:vg}=((e,t,n,r,i,o,a,s)=>({itemsAreSame:({item1:u,item2:l,features:d,logDifferences:m=!1})=>{let g=!1,p=!1;if(e(u)){if(!e(l))return{same:!1,pricesChanged:!0};g=t({item1:u,item2:l,logDifferences:m}),p=!1}if(n(u)){if(!n(l))return{same:!1,pricesChanged:!0};let{same:f,pricesChanged:y}=r({item1:u,item2:l,logDifferences:m});g=f,i({item:u,features:d||[]})?.config?.usage_type===o.Continuous?p=!0:p=y}return a(u)&&(g=s({item1:u,item2:l,logDifferences:m}),g||(p=!0)),{same:g,pricesChanged:!g&&p}}}))(Pa,dP,zr,pP,Qh,Gn,Oa,Tw),{productsAreSame:d4}=((e,t,n,r,i,o,a,s,c,u,l,d,m)=>({productsAreSame:({newProductV1:p,newProductV2:f,curProductV1:y,curProductV2:x,features:S})=>{if(!p&&!f)throw new Error("productsAreSame error: product1 not provided");if(!y&&!x)throw new Error("productsAreSame error: product2 not provided");let j=f?.items||e({prices:p?.prices||[],entitlements:p?.entitlements||[],features:S}),A=x?.items||e({prices:y?.prices||[],entitlements:y?.entitlements||[],features:S});j=t({items:j,features:S}),A=t({items:A,features:S});let v=!0,G=!1,$=!0,Pe=!0,Re=!0,se=[],V=[];$=n({newProductV2:f,curProductV2:x}),Pe=r({newConfig:f?.config,curConfig:x?.config}),Re=i({newBillingControls:f?.billing_controls??(p?o(p):void 0),curBillingControls:x?.billing_controls??(y?o(y):void 0)});let Ue=a({newMetadata:f?.metadata,curMetadata:x?.metadata});j.length!==A.length&&(v=!1),j.length!==A.length&&(v=!1);for(let He of j){let Gt=s({item:He,items:A});if(!Gt){(c(He)||u(He))&&(G=!0),v=!1,se.push(He);continue}let{same:An,pricesChanged:Jt}=l({item1:He,item2:Gt,features:S,logDifferences:!1});An||(v=!1,se.push(He)),Jt&&(G=!0)}for(let He of A)s({item:He,items:j})||(v=!1,(c(He)||u(He))&&(G=!0),V.push(He));let Y=y?.free_trial||x?.free_trial,at=p?.free_trial||f?.free_trial,me=d({ft1:Y,ft2:at}),ae=m({curProduct:x||y,newProduct:f||p});return{itemsSame:v,freeTrialsSame:me,onlyEntsChanged:!G,newItems:se,removedItems:V,detailsSame:$,optionsSame:ae,configSame:Pe,billingControlsSame:Re,metadataSame:Ue,same:v&&$&&me&&Pe&&Ue&&Re}}}))(yg,Q1,kw,Dw,Z1,Fh,Uw,du,zr,Oa,vg,Mw,Bw),{constructProduct:p4}=((e,t)=>({constructProduct:({productData:r,version:i=1,orgId:o,env:a,processor:s,baseInternalProductId:c})=>({id:r.id,name:r.name,description:r.description??null,is_add_on:r.is_add_on,is_default:r.is_default,version:i,version_slug:`v${i}`,active:!0,group:r.group||"",env:a,internal_id:e("prod"),org_id:o,created_at:Date.now(),processor:s,base_variant_id:null,base_internal_product_id:c??r.base_internal_product_id??null,archived:r.archived??!1,deleted_at:null,previous_version_slug:null,config:{...r.config,ignore_past_due:r.config?.ignore_past_due??!1},...t(r.billing_controls),metadata:r.metadata??{}})}))($r,mP),{AdditionalCurrencyTierArraySchema:xP}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ae,fP,Bh,Lh),{FeatureConfigOverrideSchema:IP}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(Ae,gP,D1),{itemToPriceAndEnt:AP}=((e,t,n,r,i,o,a,s,c,u)=>({itemToPriceAndEnt:({item:d,orgId:m,internalProductId:g,feature:p,curPrice:f,curEnt:y,isCustom:x,newVersion:S,features:j})=>{let A=null,v=null,G=null,$=null,Pe=null,Re=null;if(e(d)){let{price:se}=t({item:d,orgId:m,internalProductId:g,isCustom:x,newVersion:S,curPrice:f});!f||S?A=se:n(f,se,!0)?Pe=f:G=se}else if(r(d)){if(!p)throw new i({message:`Feature ${d.feature_id} not found`,code:o.InvalidRequest});let se=p?.type===a.Boolean,{ent:V}=s({item:d,orgId:m,internalFeatureId:p.internal_id,internalProductId:g,isCustom:x,newVersion:S,feature:p,curEnt:y});!y||S?v=V:c(y,V)?Re=y:$=V}else{if(!p)throw new i({message:`Feature ${d.feature_id} not found`,code:o.InvalidRequest});let{price:se,ent:V}=u({item:d,orgId:m,internalFeatureId:p.internal_id,internalProductId:g,isCustom:x,curPrice:f,curEnt:y,newVersion:S,features:j}),Ue=y&&c(y,V);!f||S?A=se:!Ue||!n(f,se,!1)?G=se:Pe=f,!y||S?v=V:Ue?Re=y:$=V}return{newPrice:A,newEnt:v,updatedPrice:G,updatedEnt:$,samePrice:Pe,sameEnt:Re}}}))(ru,_P,Ea,Ia,jt,qt,It,r1,mu,yP),{copyStripeResourcesToMatchingPrice:wP}=((e,t,n,r,i)=>({copyStripeResourcesToMatchingPrice:({targetPrice:a,candidatePrices:s,targetEntitlements:c,candidateEntitlements:u})=>{let l=s.map(x=>({candidatePrice:x,level:e({newPrice:a,candidatePrice:x,newEntitlements:c,candidateEntitlements:u})})),d=l.find(x=>x.level==="full"),g=(d??l.find(x=>x.level==="stripeProductOnly"))?.candidatePrice,p=d?.candidatePrice,f=a.config,y=[];if(g){let x=g.config;for(let S of t)S==="stripe_meter_id"&&(!n(a)||!n(g))||r({fromConfig:x,toConfig:f,field:S})&&y.push(S)}if(p){let x=p.config;for(let S of i)t.includes(S)||r({fromConfig:x,toConfig:f,field:S})&&y.push(S)}return{copiedFields:y}}}))(SP,WA,l1,HA,QA),{getApiPlanDiff:m4}=(e=>({getApiPlanDiff:({from:n,to:r})=>e({from:n,to:r})}))(vP),{backfillExistingItemIds:PP}=((e,t)=>({backfillExistingItemIds:({items:r,currentFullProduct:i,features:o})=>{let a=e({currentFullProduct:i,features:o});return r.map(s=>{if(s.entitlement_id||s.price_id)return s;let c=t({item:s,items:a});return c?{...s,...c.entitlement_id?{entitlement_id:c.entitlement_id}:{},...c.price_id?{price_id:c.price_id}:{}}:s})}}))(Sg,du),{PriceTierSchema:OP}=((e,t,n)=>({PriceTierSchema:e.object({to:e.number().or(e.literal(t)).meta({description:"The maximum amount of usage for this tier.",example:100}),amount:e.number().optional().meta({description:"The price of the product item for this tier.",example:10}),flat_amount:e.number().optional().meta({description:"A flat fee charged for this tier, in addition to the per-unit amount."}),additional_currencies:n.nullish().meta({description:"Per-currency amounts for this tier. Boundaries ('to') are shared across currencies."})}).refine(i=>i.amount!=null||i.flat_amount!=null,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0}))}))(Ae,Xc,xP),{ProductItemConfigSchema:CP}=((e,t,n,r,i,o,a)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(n).nullish(),on_decrease:e.enum(r).nullish(),rollover:i.nullish(),expiry:o.nullish(),feature_override:a.nullish()})}))(Ae,$n,Jr,Wi,Kw,Ww,IP),{carryForwardStripeResources:EP}=(e=>({carryForwardStripeResources:({targetPrices:n,targetEntitlements:r,candidatePrices:i,candidateEntitlements:o})=>{for(let a of n)e({targetPrice:a,candidatePrices:i,targetEntitlements:r,candidateEntitlements:o})}}))(wP),{resolveInPlaceEdit:f4}=((e,t,n,r)=>({resolveInPlaceEdit:async({db:o,items:a,currentFullProduct:s,features:c})=>{let u=e({items:a,currentFullProduct:s,features:c}),l=t({currentFullProduct:s,features:c}),d=[],m=[];for(let f of l){let y=n({item:f,items:u}),x=!y,S=y&&!r({item1:y,item2:f,features:c}).same;(x||S)&&(f.entitlement_id&&d.push(f.entitlement_id),f.price_id&&m.push(f.price_id))}let g=new Set([...d,...m]),p=u.map(f=>{let y=f.entitlement_id&&g.has(f.entitlement_id),x=f.price_id&&g.has(f.price_id);return y||x?{...f,entitlement_id:void 0,price_id:void 0}:f});return{retiredEntitlementIds:d,retiredPriceIds:m,items:p,curPrices:s.prices.filter(f=>!g.has(f.id)),curEnts:s.entitlements.filter(f=>!g.has(f.id))}}}))(PP,Sg,du,vg),{ProductItemSchema:TP}=((e,t,n,r,i,o,a,s,c,u,l)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(m=>{if(m==="")throw new Error("Interval cannot be empty.");return m},e.enum(o).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(a).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(u).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:l.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(o).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(Ae,cA,In,Gw,$i,zc,Qr,OP,hP,xa,CP),{validateProductItem:RP}=((e,t,n,r,i,o,a,s,c,u,l,d,m,g,p,f,y,x,S,j)=>({validateProductItem:({item:v,features:G,multiCurrencyEnabled:$,validateRollover:Pe})=>{v=e.parse(v);let Re=G.find(me=>me.id===v.feature_id);if(t(v.feature_id)&&t(v.price)&&t(v.tiers))throw new n({message:"Either 'feature_id', 'price', or both should be set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let se=v.pooled&&Re?.type===o.Boolean,V=a(v)||s(v.included_usage)&&v.included_usage!==0||s(v.interval)||s(v.config?.rollover);if(se&&V)throw new n({message:"Pooled boolean items cannot include balance or pricing fields",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(c({item:v,feature:Re,features:G}),a(v)&&v.included_usage===u)throw new n({message:"Unlimited items cannot include pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(v.pooled&&a(v)&&v.usage_model===l.PayPerUse)throw new n({message:"Pooled items cannot use usage-based pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(s(v.price)&&s(v.tiers))throw new n({message:"Either 'price' or 'tiers' should be set, not both",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let Ue=(v.additional_currencies?.length??0)>0||(v.tiers?.some(me=>(me.additional_currencies?.length??0)>0)??!1);if(Ue&&!$)throw new n({message:"Multi-currency is not enabled for this organization",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(Ue&&t(v.base_currency))throw new n({message:"'base_currency' is required when 'additional_currencies' are set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if((v.additional_currencies?.length??0)>0){if(s(v.tiers))throw new n({message:"Tiered items carry 'additional_currencies' on each tier, not at the item level",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(s(v.price)&&v.price<=0)throw new n({message:"'additional_currencies' require a non-zero 'price' \u2014 a plan that is free in the base currency is free in every currency",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST})}if(d(v)&&v.price&&v.price.toString().split(".")[1]?.length>2)throw new n({message:"One off prices can have at most 2 decimal places",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(a(v)||m(v)){if(typeof v.included_usage!="number"&&v.included_usage!==u&&s(v.included_usage))throw new n({message:`Included usage for feature ${v.feature_id} must be a number or '${u}'`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(t(v.included_usage)&&(v.included_usage=0),typeof v.included_usage=="number"&&v.included_usage<0)throw new n({message:"Included usage must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(a(v)||d(v)){let me=g({item:v});if(String(me)===p.Day||String(me)===p.Minute||String(me)===p.Hour)throw new n({message:"Price can't have day, minute or hour interval",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(a(v)&&t(v.usage_model))throw new n({message:`Usage model is required for priced features. Please select one for the feature ${v.feature_id}`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(a(v)&&v.tiers){if(v.included_usage===u)throw new n({message:`Included usage can't be '${u}' for tiered prices`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.billing_units&&v.billing_units<=0)throw new n({message:"Billing units must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.tier_behavior===f.VolumeBased&&v.tiers.length>1&&v.usage_model!==l.Prepaid)throw new n({message:"Volume-based pricing is only supported for prepaid items",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.tiers.some(ae=>ae.flat_amount!=null&&ae.flat_amount>0)){if(v.tier_behavior!==f.VolumeBased)throw new n({message:"flat_amount on tiers is only supported for volume-based pricing",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.tiers.length<=1)throw new n({message:"flat_amount is not supported on single-tier pricing",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(v.tiers.some(ae=>ae.flat_amount!=null&&ae.flat_amount<0))throw new n({message:"flat_amount must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(v.usage_model===l.Prepaid&&v.config?.on_increase===y.BillImmediately)throw new n({message:"Bill immediately is not supported for prepaid just yet, contact us at hey@useautumn.com if you're interested!",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.config?.expiry&&Re&&(Re.type===o.Boolean||x({feature:Re})))throw new n({message:`expiry is only supported on consumable features (feature: ${v.feature_id})`,code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(!v.config?.rollover)return;let Y=v.config.rollover;if(Y.duration===S.Forever&&(Y.length=0),!Pe)return;if(v.included_usage===u)throw new n({message:"Unlimited items cannot have rollover",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let at=j({rollover:Y});if(at)throw new n({message:at,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(Y.duration===S.Month&&(typeof Y.length!="number"||Y.length<0))throw new n({message:"Rollover length must be a positive number for monthly durations",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(s(v.usage_limit)&&v.usage_limit<=0)throw new n({message:"Usage limit must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}}))(TP,Yt,jt,qt,Vn,It,tu,pr,bP,$i,Qr,ru,Ia,Kn,zc,xa,Jr,ig,eu,wA),{validateProductItems:jP}=((e,t,n,r,i,o,a,s,c,u,l,d,m,g,p)=>({validateProductItems:({newItems:y,features:x,orgId:S,env:j,multiCurrencyEnabled:A,validateRollover:v=!0})=>{let{allFeatures:G,newFeatures:$}=e({items:y,curFeatures:x,orgId:S,env:j});x=G;for(let se=0;se<y.length;se++){t({item:y[se],features:x,multiCurrencyEnabled:A,validateRollover:v});let V=x.find(Ue=>Ue.id===y[se].feature_id);V&&V.type===n.Metered&&(y[se].feature_type=V.config?.usage_type)}for(let se=0;se<y.length;se++){let V=y[se],Ue=r({item:V}),Y=i({item:V});if(o(V)&&y.find((ae,Vt)=>ae.feature_id===V.feature_id&&Vt!==se&&V.entity_feature_id===ae.entity_feature_id))throw new a({message:`Feature ${V.feature_id} is duplicated`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});let at=y.find((me,ae)=>me.feature_id===V.feature_id&&ae!==se&&r({item:me})===Ue&&i({item:me})===Y&&me.entity_feature_id===V.entity_feature_id);if(at){if(u(at)&&u(V))throw new a({message:`You're trying to create two items for the same feature (${V.feature_id}) with the same interval. Please make them into one item.`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(V.usage_model&&V.usage_model===at?.usage_model)throw new a({message:`You're trying to add the same feature (${V.feature_id}), with the same reset interval. You should either change the reset interval of one of the items, or make one of them a prepaid quantity`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(l(V)&&y.find((ae,Vt)=>d({item:ae})===d({item:V})&&m({item:ae})===m({item:V})&&Vt!==se))throw new a({message:"Can't have two fixed prices with the same interval",code:s.InvalidInputs,statusCode:c.BAD_REQUEST})}}let Pe=y.some(se=>(l(se)||g(se))&&String(d({item:se}))===p.Week),Re=y.some(se=>(l(se)||g(se))&&String(d({item:se}))===p.Month);if(Pe&&Re)throw new a({message:"Can't have both weekly and monthly price items in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(y.filter(l).length>1)throw new a({message:"Can't have more than one price item in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});return{allFeatures:G,newFeatures:$}}}))(R1,RP,It,Aa,wa,ag,jt,qt,Vn,Ia,ru,Kn,Xr,tu,zc),{handleNewProductItems:h4}=((e,t,n,r,i)=>({handleNewProductItems:async({db:a,curPrices:s,curEnts:c,newItems:u,features:l,product:d,logger:m,isCustom:g,newVersion:p,saveToDb:f=!0,multiCurrencyEnabled:y})=>{if(!u)return{prices:[],entitlements:[],customPrices:[],customEnts:[],features:l};let{allFeatures:x,newFeatures:S}=e({newItems:u,features:l,orgId:d.org_id,env:d.env,multiCurrencyEnabled:y,validateRollover:!g});l=x;let j=[],A=[],v=[],G=[],$=s.filter(V=>{let Ue=u.find(Y=>Y.price_id===V.id);return Ue?t(Ue):!0}),Pe=c.filter(V=>!u.some(Ue=>Ue.entitlement_id===V.id)),Re=[],se=[];for(let V of u){let Ue=l.find(Jt=>Jt.id===V.feature_id),Y=c.find(Jt=>Jt.id===V.entitlement_id),at=s.find(Jt=>Jt.id===V.price_id),{newPrice:me,newEnt:ae,updatedPrice:Vt,updatedEnt:He,samePrice:Gt,sameEnt:An}=n({item:V,orgId:d.org_id,internalProductId:d.internal_id,feature:Ue,curPrice:at,curEnt:Y,isCustom:g,newVersion:p,features:l});me&&j.push(me),ae&&A.push(ae),Vt&&v.push(Vt),He&&G.push(He),Gt&&Re.push(Gt),An&&se.push(An)}return r({targetPrices:[...j,...v],targetEntitlements:[...A,...G,...se],candidatePrices:s,candidateEntitlements:c}),(g||p)&&f?{...i({newPrices:j,newEnts:A,updatedPrices:v,updatedEnts:G,samePrices:Re,sameEnts:se,features:l}),samePrices:Re,sameEnts:se,newFeatures:S,retiredPriceIds:$.map(V=>V.id),retiredEntitlementIds:Pe.map(V=>V.id)}:{prices:[...j,...v],entitlements:[...A,...G].map(V=>({...V,feature:l.find(Ue=>Ue.id===V.feature_id)})),customPrices:[],customEnts:[],features:l,samePrices:Re,sameEnts:se,newFeatures:S,retiredPriceIds:$.map(V=>V.id),retiredEntitlementIds:Pe.map(V=>V.id)}}}))(jP,Pa,AP,EP,ZA);var kP=rn.clone({precision:40});function fu(e){if(!lu(e))throw new Error("A supported explicit currency is required");return e.toLowerCase()}function hu(e){let t=new kP(e);if(!t.isFinite())throw new Error("Amount must be finite");return t}function y4(e,t){let n=fu(t),i=hu(e).toDecimalPlaces(zh(n),rn.ROUND_HALF_CEIL).mul(Ca(n));if(!i.isInteger()||i.abs().gt(Number.MAX_SAFE_INTEGER))throw new Error("Minor amount exceeds the exact integer boundary");return i.toNumber()}function S4(e,t){let n=fu(t),r=hu(e);if(!r.isInteger()||r.abs().gt(Number.MAX_SAFE_INTEGER))throw new Error("Minor amount must be an exact safe integer");return r.div(Ca(n)).toString()}function v4(e,t){let n=hu(e).mul(Ca(fu(t)));if(n.isNegative())throw new Error("Usage unit price must be nonnegative");if(n.decimalPlaces()>12||n.abs().gt(Number.MAX_SAFE_INTEGER))throw new Error("Usage unit amount cannot be represented exactly by the provider");return n.toFixed()}function P4(e){let t=e.screens.map(n=>n.type==="owned"?{...n,document:Mo(n.document)}:n);for(let n of e.inputs){let r=t.find(i=>i.id===n.screenId);if(r?.type==="owned"&&!si(r.document,n.componentId))throw new Error(`Local Funnel input ${n.variable} targets hidden component ${n.componentId} on screen ${n.screenId}`)}return ln.parse({...e,screens:t})}import{z as qe}from"zod";var bu=32,DP=522240;function _u(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 NP=qe.strictObject({nodeId:qe.string().min(1).max(64),visit:qe.number().int().nonnegative(),revision:qe.number().int().nonnegative()}),gu=qe.record(qe.string(),ge),FP=qe.strictObject({id:qe.uuid(),nodeId:qe.string().min(1).max(64),visit:qe.number().int().nonnegative(),input:qe.strictObject({schemaVersion:Nr.shape.schemaVersion,kind:Nr.shape.kind,selector:Nr.shape.selector,contract:Nr.shape.contract}),context:gu,removed:qe.array(qe.string()).max(100),attributes:gu,removedAttributes:qe.array(qe.string()).max(100),result:Cm,offeringVersionId:qe.uuid().nullable(),events:qe.strictObject({entered:qe.string().regex(/^[1-9][0-9]{0,18}$/),decision:qe.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),UP=qe.strictObject({schemaVersion:qe.literal(1),mode:qe.enum(["local","remote"]),versionId:qe.uuid(),generation:qe.number().int().positive(),base:NP,context:gu,steps:qe.array(FP).min(1).max(bu)}).refine(e=>_t(e)<=DP,"Segment exceeds its byte budget"),k4=(e,t,n)=>Rf(e,t,`step:${n}`);function Ta(e){return Array.isArray(e)?e.some(t=>Ta(t)):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>(t==="hashAttribute"||t==="fallbackAttribute")&&n==="results"||Ta(n))}function D4(e,t){let n={};for(let[s,c]of Object.entries(t))JSON.stringify(e[s])!==JSON.stringify(c)&&(n[s]=c);let r=e.attributes,i=t.attributes,o={},a=[];if(r&&typeof r=="object"&&!Array.isArray(r)&&i&&typeof i=="object"&&!Array.isArray(i)){for(let[s,c]of Object.entries(i))JSON.stringify(r[s])!==JSON.stringify(c)&&(o[s]=c);a=Object.keys(r).filter(s=>!Object.hasOwn(i,s)),delete n.attributes}return{context:n,removed:Object.keys(e).filter(s=>!Object.hasOwn(t,s)),attributes:o,removedAttributes:a}}function N4(e){let t=UP.parse(e),n=structuredClone(t.context);return t.steps.map(r=>{for(let i of r.removed)delete n[i];if(n={...n,...r.context},Object.keys(r.attributes).length||r.removedAttributes.length){let i=qe.record(qe.string(),ge).parse(n.attributes);for(let o of r.removedAttributes)delete i[o];n.attributes={...i,...r.attributes}}return{...r,input:Nr.parse({...r.input,context:structuredClone(n)})}})}var yu=class extends Error{constructor(n,r){super(r);this.code=n;this.name="FunnelLocalCalculationError"}code},Ra=(e,t)=>new yu(e,t),MP=e=>({experiments:e.experiments,features:e.features});function BP(e,t=Ra){let n=new Map(e.topology.nodes.map(a=>[a.id,a])),r=Pu(e.growth.savedGroups),i=MP(e.growth);function o(a,s){if(!Object.hasOwn(e.growth.features,a))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return ti(a,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:o,evaluate(a,s){let c=n.get(a);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let m=e.conditions[c.id];if(!m)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=Nc({id:c.id,name:c.id,type:"condition",cases:m.map(g=>({condition:g.condition,target:c.outputs[g.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=o(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let g=Nc({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=g.value,u=g.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=o(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let d=c.outputs[u]??(u==="value"?c.id:void 0);if(!d)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:a,port:u,target:d,...l===void 0?{}:{value:l}}}}}function LP(e,t,n,r=Ra){let i=Lr.parse(e);if(i.evaluationMode!=="local")throw r("EVALUATION_MODE","Remote nodes are evaluated by Grow");if(i.expiresAt&&Date.parse(i.expiresAt)<=Date.now())throw r("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition");let o=BP(i,r),a=Ct.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:s,onFeatureUsage:c,onExperimentViewed:u}=n,l={attributes:a,...s?{saveStickyBucketAssignmentDoc:d=>s(structuredClone(d))}:{},...c?{onFeatureUsage:(d,m)=>c(d,structuredClone(m))}:{},...u?{onExperimentViewed:(d,m)=>u(structuredClone(d),structuredClone(m))}:{},features:o.features,savedGroups:o.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return o.evaluate(t,l)}function xg(e,t,n,r=Ra){let i=[],o=[],a=[],s=LP(e,t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(c){let u=i.findIndex(m=>m.next.attributeName===c.attributeName&&m.next.attributeValue===c.attributeValue),l=c.attributeName+"||"+c.attributeValue,d={expected:n.sticky[l]??null,next:c};u<0?i.push(d):i[u]=d},onExperimentViewed(c,u){u.inExperiment&&u.hashUsed&&!u.passthrough&&o.push(ge.parse({key:c.key,variationId:u.variationId,keyUsed:u.key,hashAttribute:u.hashAttribute,hashValue:u.hashValue}))},onFeatureUsage(c,u){a.push(ge.parse({feature:c,value:u.value,source:u.source,...u.ruleId?{ruleId:u.ruleId}:{}}))}},r);return{port:s.port,...s.value===void 0?{}:{value:s.value},sticky:i,exposures:o,features:a}}function W4(e,t,n,r=Ra){let i=n,o=new Map(t.graph.nodes.map(p=>[p.id,p])),a=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=e.evaluationMode==="local"&&Ta(e.growth),l=n.nodeId,d=n.visit,m=!1;for(let p=0;p<bu;p++){let f=o.get(l);if(!f||!_u(f))break;if(d>=t.execution.maxTransitions)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");let y={attributes:f.type==="condition"?Vo({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:a,savedGroups:{}}):{...i.attributes,parameters:n.parameters,answers:n.answers,results:a},sticky:s},x,S;if(["condition","feature","split"].includes(f.type)||f.type==="offering"&&f.configuration.source==="feature")x=xg(e,f.id,y,r),f.type==="offering"&&(x.value={type:"offering_version",id:String(x.value)}),f.type==="condition"?S=x.port==="default"?f.default:f.cases[Number(x.port.slice(5))]?.target:f.type==="split"?S=x.port==="notParticipating"?f.notParticipating:f.routes[x.port]:(f.type==="feature"||f.type==="offering")&&(S=f.next);else if(x={port:"next",sticky:[],exposures:[],features:[]},(f.type==="entry"||f.type==="coupon"||f.type==="coupons")&&(S=f.next),f.type==="offering"&&f.configuration.source==="fixed"&&(x.value={type:"offering_version",id:f.configuration.versionId},S=f.next),f.type==="end"||f.type==="output"){let A=f.type==="end"?f.output:f.value;if(x=A?.type==="feature"?xg(e,f.id,y,r):{...x,port:"value",value:A?.type==="literal"?A.value:A?.type==="variable"?ir({source:"variable",key:A.key,...A.path?{path:A.path}:{}},{declarations:t.variables,answers:n.answers,results:a,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},A&&(x.value===void 0||!Ft(t.outputSchema,x.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let j=[...c,{nodeId:l,result:x}];if(_t({steps:j})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:l,result:x}),f.type==="feature"||f.type==="offering"||f.type==="coupon"||f.type==="coupons"){let A=f.type==="coupons"?f.couponIds.map(G=>({type:"reward",id:G})):f.type==="coupon"?{type:"reward",id:f.couponId}:x.value;if(A===void 0)throw r("INVALID_RESPONSE","Node output is missing");let v=nr(f,{value:A});Xs(t.variables,f,v),Object.assign(a,v)}for(let A of x.sticky)s[`${A.next.attributeName}||${A.next.attributeValue}`]=structuredClone(A.next);if(f.type==="end"||f.type==="output"){m=!0;break}if(!S)throw r("INVALID_RESPONSE","Local pure exit is unavailable");if(l=S,d++,u&&["feature","offering","coupon","coupons"].includes(f.type))break}let g=o.get(l);return{steps:c,...!m&&g&&!_u(g)?{boundary:{nodeId:l,visit:d}}:{}}}import{z as qP}from"zod";var J4=qP.strictObject({document:ln,configuration:Lr.options[0]});var VP=["checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","readSubscriptionOperation","readSubscriptionUpdate","readPaymentSetup","readRefund","readBillingControls","listBillingInvoices","readSeats","quoteBalance","readUsage","readBalanceSource","listBalanceGrants","readUsageAnalytics","readCreditAnalytics","readUsageBatch","listOffers"];function z4(e){return e.type==="external_page"||e.type==="wait"||e.type==="action"&&!(e.action.type==="api"&&VP.includes(e.action.operation))||e.type==="output"&&e.value.type==="bundle"}export{A_ as a,Jl as b,os as c,ed as d,bo as e,O_ as f,as as g,C_ as h,td as i,ss as j,cO as k,E_ as l,nd as m,uO as n,rd as o,lO as p,mi as q,us as r,_o as s,gO as t,od as u,R_ as v,j_ as w,bO as x,ls as y,ds as z,ps as A,ms as B,D_ as C,N_ as D,sd as E,F_ as F,CO as G,sn as H,FO as I,cd as J,UO as K,ud as L,U_ as M,ld as N,MO as O,BO as P,M_ as Q,dd as R,fs as S,LO as T,qO as U,KO as V,B_ as W,L_ as X,fd as Y,JO as Z,On as _,Dt as $,yo as aa,q_ as ba,hd as ca,XO as da,zO as ea,eC as fa,tC as ga,nC as ha,rC as ia,fi as ja,So as ka,Sd as la,bs as ma,Sr as na,G_ as oa,$_ as pa,K_ as qa,W_ as ra,Cn as sa,vd as ta,xd as ua,Id as va,Ad as wa,vo as xa,wd as ya,Pd as za,Od as Aa,Cd as Ba,Q_ as Ca,Ed as Da,Z_ as Ea,Y_ as Fa,J_ as Ga,Td as Ha,_s as Ia,X_ as Ja,gi as Ka,Rd as La,jd as Ma,kd as Na,z_ as Oa,Dd as Pa,Nd as Qa,_i as Ra,yi as Sa,Yn as Ta,xo as Ua,Ss as Va,ey as Wa,Ud as Xa,Md as Ya,Si as Za,Io as _a,Bd as $a,xC as ab,IC as bb,AC as cb,wC as db,ty as eb,PC as fb,OC as gb,xs as hb,RC as ib,jC as jb,qd as kb,ny as lb,DC as mb,Ld as nb,ry as ob,Gd as pb,As as qb,oy as rb,NC as sb,Jn as tb,FC as ub,UC as vb,ay as wb,sy as xb,cy as yb,uy as zb,qC as Ab,VC as Bb,$d as Cb,ws as Db,YC as Eb,JC as Fb,ly as Gb,tE as Hb,nE as Ib,dy as Jb,Zd as Kb,Ps as Lb,Yd as Mb,Jd as Nb,Xd as Ob,py as Pb,zd as Qb,Os as Rb,ep as Sb,hE as Tb,tp as Ub,gE as Vb,bE as Wb,rp as Xb,ip as Yb,Ts as Zb,fy as _b,op as $b,xE as ac,hy as bc,gy as cc,Rn as dc,sp as ec,by as fc,_y as gc,Rs as hc,js as ic,jn as jc,My as kc,ks as lc,xr as mc,Pp as nc,er as oc,mS as pc,fS as qc,Cp as rc,Ii as sc,Ir as tc,wo as uc,Ep as vc,Tp as wc,Ds as xc,hS as yc,gS as zc,bS as Ac,Rp as Bc,Ns as Cc,jp as Dc,kp as Ec,Dp as Fc,Po as Gc,KE as Hc,WE as Ic,Np as Jc,Oo as Kc,_S as Lc,wi as Mc,Co as Nc,Fp as Oc,SS as Pc,Us as Qc,XE as Rc,Mp as Sc,Bp as Tc,vS as Uc,Ms as Vc,qp as Wc,Vp as Xc,To as Yc,Ro as Zc,xS as _c,IS as $c,AS as ad,Gp as bd,$p as cd,Kp as dd,Wp as ed,Hp as fd,Qp as gd,Zp as hd,Yp as id,Vs as jd,wS as kd,PS as ld,Pi as md,OS as nd,ES as od,TS as pd,Gs as qd,pT as rd,jo as sd,qs as td,RS as ud,Xp as vd,zp as wd,jS as xd,mT as yd,fT as zd,em as Ad,kS as Bd,hT as Cd,DS as Dd,Do as Ed,No as Fd,xT as Gd,Fo as Hd,en as Id,$s as Jd,wr as Kd,tm as Ld,MS as Md,BS as Nd,nm as Od,kT as Pd,DT as Qd,NT as Rd,FT as Sd,kn as Td,rm as Ud,Ks as Vd,GT as Wd,$T as Xd,Ws as Yd,qS as Zd,im as _d,VS as $d,om as ae,am as be,sm as ce,Hs as de,GS as ee,Mo as fe,Qs as ge,Oi as he,Bo as ie,um as je,Zs as ke,Lo as le,lm as me,Pr as ne,Or as oe,$S as pe,qo as qe,Ft as re,tr as se,nr as te,Xs as ue,Ci as ve,Vo as we,zs as xe,Ei as ye,Kt as ze,un as Ae,Cr as Be,ir as Ce,dm as De,$o as Ee,tc as Fe,WS as Ge,mm as He,fm as Ie,hm as Je,SR as Ke,vR as Le,xR as Me,IR as Ne,AR as Oe,HS as Pe,wR as Qe,Qe as Re,gm as Se,nc as Te,Er as Ue,Ho as Ve,_m as We,Tr as Xe,Rr as Ye,or as Ze,ar as _e,jr as $e,ym as af,QS as bf,ZS as cf,rc as df,Sm as ef,vm as ff,xm as gf,Ti as hf,YS as if,ic as jf,MR as kf,BR as lf,LR as mf,Im as nf,JS as of,WR as pf,HR as qf,QR as rf,XS as sf,zS as tf,oc as uf,XR as vf,ev as wf,tv as xf,Pm as yf,ij as zf,ac as Af,sc as Bf,iv as Cf,cc as Df,uc as Ef,kr as Ff,ov as Gf,av as Hf,_j as If,Zo as Jf,vj as Kf,xj as Lf,_t as Mf,Yo as Nf,lc as Of,dc as Pf,Tj as Qf,Rj as Rf,Om as Sf,Mj as Tf,mc as Uf,fc as Vf,Nr as Wf,Cm as Xf,Bj as Yf,Lj as Zf,sv as _f,Mt as $f,cv as ag,uv as bg,bc as cg,ln as dg,ok as eg,ak as fg,lv as gg,dv as hg,Ri as ig,pv as jg,Rm as kg,mk as lg,mv as mg,hv as ng,gv as og,bv as pg,_v as qg,yv as rg,Sv as sg,km as tg,Dm as ug,vv as vg,xv as wg,Nm as xg,vc as yg,Iv as zg,Nk as Ag,Sc as Bg,Av as Cg,Fk as Dg,Uk as Eg,Mk as Fg,Fm as Gg,ki as Hg,Ur as Ig,Um as Jg,Zk as Kg,Bm as Lg,xc as Mg,Lm as Ng,qm as Og,Vm as Pg,$m as Qg,Gm as Rg,Ic as Sg,wv as Tg,iD as Ug,Pv as Vg,Km as Wg,Ov as Xg,dr as Yg,Wm as Zg,Qm as _g,Zm as $g,Ym as ah,Jm as bh,Xm as ch,Cv as dh,zm as eh,Ev as fh,Tv as gh,Rv as hh,jv as ih,nf as jh,Pc as kh,of as lh,kv as mh,Dv as nh,_D as oh,yD as ph,SD as qh,sf as rh,cf as sh,uf as th,lf as uh,df as vh,pf as wh,vD as xh,xD as yh,Fv as zh,Uv as Ah,ID as Bh,AD as Ch,dn as Dh,Oc as Eh,Mv as Fh,Ni as Gh,Bv as Hh,OD as Ih,ff as Jh,hf as Kh,CD as Lh,gf as Mh,bf as Nh,Cc as Oh,Ec as Ph,Vv as Qh,Gv as Rh,$v as Sh,ED as Th,Tc as Uh,_f as Vh,Rc as Wh,Kv as Xh,yf as Yh,ND as Zh,Sf as _h,jc as $h,vf as ai,Fi as bi,xf as ci,FD as di,Wv as ei,IN as fi,D as gi,Hv as hi,Qv as ii,Zv as ji,AN as ki,k as li,wN as mi,wf as ni,jN as oi,Yv as pi,Jv as qi,kN as ri,DN as si,Pf as ti,Xv as ui,UN as vi,zv as wi,Of as xi,Cf as yi,e0 as zi,MN as Ai,BN as Bi,LN as Ci,qN as Di,t0 as Ei,$N as Fi,KN as Gi,QN as Hi,ZN as Ii,r0 as Ji,Tf as Ki,zN as Li,eF as Mi,Li as Ni,Nc as Oi,Rf as Pi,pF as Qi,mF as Ri,i0 as Si,vF as Ti,xF as Ui,IF as Vi,Fc as Wi,o0 as Xi,a0 as Yi,qi as Zi,Uc as _i,Mc as $i,MF as aj,BF as bj,GF as cj,kf as dj,Df as ej,JF as fj,u0 as gj,XF as hj,Ff as ij,Lr as jj,l0 as kj,d0 as lj,p0 as mj,c2 as nj,Mf as oj,m0 as pj,Bc as qj,Lc as rj,qc as sj,f0 as tj,h0 as uj,v2 as vj,x2 as wj,I2 as xj,A2 as yj,O2 as zj,T2 as Aj,Lf as Bj,D2 as Cj,N2 as Dj,g0 as Ej,b0 as Fj,_0 as Gj,y0 as Hj,S0 as Ij,v0 as Jj,B2 as Kj,x0 as Lj,L2 as Mj,q2 as Nj,I0 as Oj,A0 as Pj,ia as Qj,w0 as Rj,P0 as Sj,$2 as Tj,Z2 as Uj,Y2 as Vj,J2 as Wj,O0 as Xj,X2 as Yj,V0 as Zj,G0 as _j,$0 as $j,dU as ak,zf as bk,K0 as ck,fU as dk,eh as ek,yU as fk,SU as gk,wU as hk,PU as ik,W0 as jk,TU as kk,RU as lk,th as mk,nh as nk,MU as ok,BU as pk,Q0 as qk,ZU as rk,Y0 as sk,YU as tk,J0 as uk,XU as vk,ih as wk,zU as xk,eM as yk,oh as zk,ah as Ak,oM as Bk,aM as Ck,X0 as Dk,pM as Ek,z0 as Fk,mM as Gk,fM as Hk,uh as Ik,lh as Jk,yM as Kk,SM as Lk,vM as Mk,xM as Nk,ch as Ok,IM as Pk,ex as Qk,PM as Rk,EM as Sk,nx as Tk,ph as Uk,TM as Vk,jM as Wk,kM as Xk,y4 as Yk,S4 as Zk,v4 as _k,P4 as $k,bu as al,DP as bl,_u as cl,NP as dl,FP as el,UP as fl,k4 as gl,Ta as hl,D4 as il,N4 as jl,yu as kl,BP as ll,LP as ml,xg as nl,W4 as ol,J4 as pl,VP as ql,z4 as rl};