@tinkerlandai/indiana-sdk 0.1.0 → 0.3.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.
@@ -0,0 +1,11 @@
1
+ import{e as Ca}from"./chunk-MJG7X7LM.js";import{z as nn}from"zod";import{z as A}from"zod/v4";import{z as Gg}from"zod/v4";var cu=Gg.registry();var{AppEnv:Qi}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:uu}={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:Kg}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:Hg}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(A),{ResetInterval:ti}=(()=>{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:zg}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:Wg}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:Qg}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:Zg}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:Yg}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(A),{BALANCE_BASES:Jg}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:lu}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:Ea}=(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."})})}))(A),{ProductMetadataSchema:_r}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(A),{findDuplicate:Xg}={findDuplicate:t=>{let n=new Set;for(let r of t){if(n.has(r))return r;n.add(r)}}},{BillingInterval:Tn}=(()=>{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:Ta}=(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')."})})}))(A),{withSpecDefault:ni}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(cu),{COMMON:du}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:eh}={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:th}=(e=>({COMMON_SET:new Set(e)}))(du),{hasNoDuplicateCurrencies:pu}={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:mu}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:Ra}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(A),{Infinite:Zi}={Infinite:"inf"},{TierBehavior:ri}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Yi}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:fu}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:nh}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:Ji}=(()=>{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:Xi}=(()=>{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:ka}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:gu}=(()=>{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:rh}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:ih}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:ja}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(A),{ApiCreditTierSchema:hu}=(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."})})}))(A),{VIOLATION_MESSAGES:oh}={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:bu}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(A),{ModelMarkupsSchema:Na}=((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()}))(A,bu),{additionalCurrencyPlanItemIssues:_u}={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(l=>c.has(l))})||n.push("Each additional currency must be present on every tier or none."))}return n}},{PlanItemFilterSchema:Da}=((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)."})}))(A,Yi,Tn,ti,Ra),{UpdatePlanItemParamsV1Schema:ah}=((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})}))(A,Da,ti),{FreeTrialDuration:ii}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:sh}=((e,t)=>({laneParam:({schema:r,description:i})=>e({schema:t.array(r).optional(),defaultValue:[],description:i})}))(ni,A),{findDuplicateInControls:ch}={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:uh}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:yu}={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:lh}=((e,t)=>({usageAlertIdentity:r=>[r.feature_id??"",r.basis??e,t(r.filter),r.threshold_type,r.threshold].join("|")}))(lu,yu),{RemovePlanLicenseSchema:dh}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(A),{ApiStripePriceProcessorSchema:ph}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(A),{ApiFeatureType:mh}=(()=>{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:fh}=(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."})})}))(A),{ApiRevenueCatProductSchema:gh}=(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."})})}))(A),{TrialOnEnd:eo}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:hh}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:bh}=(()=>{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:_h}=(()=>{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:yh}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(A),{UsageWindowScopeSchema:Sh}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(A),{EntInterval:Su}=(()=>{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:xh}=(()=>{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:Ih}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(A),{FreeTrialSchema:vh}=((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()})}))(A,ii,eo),{BillingType:Ah}=(()=>{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:Fa}=((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()}))}))(A,Zi),{IgnoredFixedPriceMetadataSchema:wh}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(A),{BillWhen:Oh}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:xu}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:Ph}=((e,t,n)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(n).default(n.ProrateImmediately)})}))(A,Ji,Xi),{AllowanceType:Ch}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:Iu}=((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()})}))(A,ka),{CreditDimensionBaseSchema:Eh}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(A,ja),{flatCreditRateShape:vu}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(A),{CreditTierSchema:Th}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(A),{CreditMultiplierSchema:Rh}=((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"})}))(A,ja),{idRegex:to}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:Au}={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:kh}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:jh}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{ProductItemInterval:Nh}=(()=>{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:Dh}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:Fh}={TierInfinite:"inf"},{CreateFreeTrialSchema:wu}=((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()})}))(A,ii,eo),{ProductConfigParamsSchema:Ua}=((e,t,n)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:n})})}))(A,ni,uu),{CREATE_PRODUCT_EXAMPLE:Uh}={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:Mh}=((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."})})}))(A,ii,eo),{CreateProductSchema:nO}=(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("")})}))(A),{isUsageLimitBasisAlert:Lh}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:Ou}=(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()})}))(A),{RewardType:Pu}=(()=>{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:Cu}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:Eu}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(A,Cu),{RewardTriggerEvent:Bh}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:qh}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:no}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(A,uu),{PurchaseLimitIntervalEnum:Vh}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(A,Kg),{DbSpendLimitSchema:Ma}=((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"]})}))(A,Hg),{USAGE_LIMIT_INTERVALS:$h}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(ti),{UsageLimitAnchorSchema:Tu}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(A,zg),{UsageLimitFilterValueSchema:Gh}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(A,Qg),{USAGE_ALERT_BASES:Kh}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(Jg),{licensePatchIssues:Hh}=(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"]}]}}))(Xg),{BasePriceSchema:zh}=((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."})})}))(A,Tn,Ta),{CURRENCY_CODES:Wh}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(du,eh,th),{AllocatedBillingFieldSchema:Ru}=((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'."})}))(A,fu),{EntitlementExpirySchema:ro}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(A,gu),{CreditDimensionNameSchema:ku}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(A,rh,ih),{ApiCreditMatchSchema:ju}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(ja),{findCreditTierViolations:Qh}=(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}}))(oh),{ApiCreditMultiplierSchema:Zh}=((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."})}))(A,ju),{ProviderMarkupsSchema:Nu}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(A,bu),{planItemParamsIssues:Yh}=((e,t,n,r,i)=>({planItemParamsIssues:a=>{let s=[],c=a.reset?.interval,l=a.price?.interval,u=a.reset?.interval_count??1,d=a.price?.interval_count??1;if(c&&l&&(String(c)!==String(l)||u!==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:f}=a.price;a.threshold_billing&&f?.length&&s.push({message:"threshold_billing currently requires a flat usage price",input:a.threshold_billing});let h=a.price.billing_method===e.UsageBased&&a.price.allocated_billing===n.ProratedLegacy;a.proration&&a.price.billing_method!==e.Prepaid&&!h&&s.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:a.proration});let I=typeof g=="number",v=Array.isArray(f)&&f.length>0;I||v?I&&v&&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(f=>f.flat_amount&&f.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(f=>f.flat_amount!=null&&f.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}}))(Yi,Tn,fu,ri,_u),{FreeTrialParamsV1Schema:La}=((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."})}))(A,ii,ni),{duplicateCheck:Jh}=(e=>({duplicateCheck:({controlKey:n,...r})=>i=>e({controlKey:n,controls:i[n]??[],rule:r})}))(ch),{usageLimitIdentity:Ba}=(e=>({usageLimitIdentity:n=>`${n.feature_id}|${e(n.filter)}`}))(yu),{ApiPriceProcessorsSchema:Du}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(A,ph),{ApiFeatureV0Schema:Fu}=((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."})})}))(A,mh),{ApiRevenueCatPlanProcessorSchema:Xh}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(A,gh),{ApiFreeTrialV2Schema:eb}=((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."})})}))(A,ii,eo),{CustomerEligibilitySchema:tb}=((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})})}))(A,hh,bh,_h),{UsageWindowLimitSchema:rO}=((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()})}))(A,yh,Sh,Su,Tu),{FeatureSchema:nb}=((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()})}))(A,Qi,xh,Na,Ih),{PriceCurrencyConfigSchema:Uu}=((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()})}))(A,Fa),{UsagePriceConfigSchema:rb}=((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()})}))(A,Oh,Fa,Tn,Uu,xu),{graduatedCreditRateShape:Mu}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(A,Th),{FeatureMarkupsOverrideSchema:ib}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(A,Nu,Na),{usageAlertTargetLimitIdentity:ob}=(e=>({usageAlertTargetLimitIdentity:n=>e({feature_id:n.feature_id??"",filter:n.filter})}))(Ba),{DiscountConfigSchema:Lu}=((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()})}))(A,Cu),{RewardEntitlementSchema:Bu}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(A,ro),{UpdateRewardSchema:iO}=((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()})}))(A,Ou,Pu,Lu,Eu,Bu),{CreateRewardProgram:oO}=((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)})}))(A,Bh,qh),{AutoTopupPurchaseLimitSchema:qu}=((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."})})}))(A,Vh),{UsageLimitFilterSchema:Vu}=((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})})})}))(A,Wg,Gh,Zg),{UsageAlertBasisSchema:ab}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(A,Kh),{refineCustomizePlanV1Schema:$u}=(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=l=>l==="update_items"?"deprecated update_items":l;return n.refine(l=>s.some(u=>l[u]!==void 0),{message:`When using customize, at least one of ${s.map(c).join(", ")} must be provided`}).superRefine((l,u)=>{if(a)for(let d of e({upsertLicenses:l.upsert_licenses}))u.addIssue({code:"custom",...d})}).refine(l=>!(l.items!==void 0&&(l.add_items!==void 0||l.remove_items!==void 0||o&&l.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`})}}))(Hh),{SUPPORTED_SET:sb}=(e=>({SUPPORTED_SET:new Set(e)}))(Wh),{ApiCreditDimensionBaseSchema:cb}=((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."})})}))(A,ju),{refineGraduatedTiers:Gu}=(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"]})}}))(Qh),{ApiFeatureMarkupsOverrideSchema:ub}=((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."})})}))(A,Nu,Na),{AutoTopupPurchaseLimitParamsSchema:lb}=((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."})})}))(qu,A),{DUPLICATE_CHECKS:db}=((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"})]}))(Jh,uh,Ba,lh),{ApiPlanProcessorsSchema:pb}=((e,t,n)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:n.nullish()}).meta({"x-atmn-mapping":!0})}))(A,fh,Xh),{FixedPriceConfigSchema:mb}=((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})}))(A,Tn,Uu,Fa,wh),{CreditDimensionSchema:fb}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(A,Eh,vu,Mu),{filterUnresolvableUsageLimitAlerts:gb}=((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}]:[])}}))(Ba,Lh,ob),{CreateRewardSchema:aO}=((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"})}))(A,Ou,Pu,Lu,Eu,Bu),{AutoTopupSchema:qa}=((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."})})}))(A,qu),{DbUsageLimitSchema:Va}=((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."})})}))(A,$h,Tu,Vu),{DbUsageAlertSchema:$a}=((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:l,basis:u,filter:d}=a.value;c==="remaining_percentage"&&l>100&&a.issues.push({code:"custom",input:l,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),u==="usage_limit"&&!s&&a.issues.push({code:"custom",input:s,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),d&&u!=="usage_limit"&&a.issues.push({code:"custom",input:d,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(A,Yg,ab,lu,Vu),{isValidCurrencyCode:hb}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(sb),{ApiCreditDimensionSchema:bb}=((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()])}))(A,cb,hu,Gu),{AutoTopupParamsSchema:_b}=((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."})})}))(qa,lb),{findDuplicateBillingControlIssue:yb}=(e=>({findDuplicateBillingControlIssue:n=>{for(let r of e){let i=r(n);if(i)return i}}}))(db),{CustomerBillingControlsSchema:Ga}=((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."})})}))(A,qa,Ma,Va,$a,Ea),{PriceSchema:Sb}=((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()})}))(A,Ah,ri,mb,rb,Ph),{CreditSchemaItemBaseSchema:Ku}=((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()})}))(A,ku,fb,Rh),{GraduatedCreditSchemaItemSchema:xb}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(Ku,Mu),{UpdateProductSchema:sO}=((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()})}))(A,no,Ga),{DbBillingControlsSchema:Ib}=((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()})}))(A,qa,Ma,Va,$a,Ea),{CurrencyCodeSchema:Hu}=((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')."})}))(A,hb),{AdditionalCurrencyTierSchema:vb}=((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"]})}))(A,Hu),{ApiCreditSchemaItemBaseSchema:zu}=((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."})})}))(A,ku,bb,Zh),{ApiFlatCreditSchemaItemSchema:Ab}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(zu,A),{rejectDuplicateBillingControls:wb}=(e=>({rejectDuplicateBillingControls:n=>{let r=e(n.value);r&&n.issues.push(r)}}))(yb),{FlatCreditSchemaItemSchema:Ob}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(Ku,vu),{ProductSchema:Pb}=((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(()=>({}))})}))(A,Qi,no,Ib,_r),{AdditionalCurrencyPriceSchema:Cb}=((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."})})}))(A,Hu),{AdditionalCurrencyTierArraySchema:Wu}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(A,vb,pu,mu),{ApiGraduatedCreditSchemaItemSchema:Eb}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(zu,A,hu,Gu),{CustomerBillingControlsParamsSchema:io}=((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)}))(A,sh,_b,Ma,Va,$a,Ea,wb),{CreditSchemaItemSchema:Tb}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(A,Ob,xb),{PriceTierSchema:Rb}=((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}))}))(A,Fh,Wu),{PlanBillingControlsParamsSchema:kb}=((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"]})})}))(io,gb),{AdditionalCurrencyPriceArraySchema:oi}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(A,Cb,pu,mu),{ApiUsageTierWithCurrenciesSchema:Qu}=((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()}))}))(A,Zi,Wu),{ApiCreditSchemaItemSchema:jb}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(A,Eb,Ab),{FeatureConfigOverrideSchema:Zu}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(A,Tb,ib),{ProductItemConfigSchema:Nb}=((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()})}))(A,xu,Ji,Xi,Iu,ro,Zu),{BasePriceParamsSchema:oo}=((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."})}))(zh,ni,A,oi),{PlanItemPriceParamsSchema:Db}=((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."})})}))(A,oi,Qu,ri,Tn,Yi,Ru),{ApiFeatureOverrideSchema:Yu}=((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."})})}))(A,jb,ub),{ApiPlanItemV1Schema:Fb}=((e,t,n,r,i,o,a,s,c,l,u,d,p,g,f,h,I)=>({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:l.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:u.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(p).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:f.nullish().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:h.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 R=S.value.reset?.interval,D=S.value.price?.interval,P=S.value.reset?.interval_count??1,be=S.value.price?.interval_count??1;if(R&&D&&(String(R)!==String(D)||P!==be)&&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 We of I(S.value.price))S.issues.push({code:"custom",message:We,input:S.value.price})}})}))(A,Fu,ti,oi,Qu,ri,Tn,Yi,Ru,Du,Ta,ka,Ji,Xi,ro,Yu,_u),{EntitlementSchema:Ub}=((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()})}))(A,Ch,Su,gu,Iu,Zu),{ProductItemSchema:Ju}=((e,t,n,r,i,o,a,s,c,l,u)=>({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(p=>{if(p==="")throw new Error("Interval cannot be empty.");return p},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(l).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:u.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})})}))(A,kh,jh,Fu,Zi,Nh,Dh,Rb,oi,ri,Nb),{ProductV2Schema:Xu}=((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()})}))(A,Qi,Mh,Ju,no,Ga,_r),{PlanItemParamsObjectSchema:Mb}=((e,t,n,r,i,o,a,s,c,l,u)=>({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:l.optional().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:u.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})})}))(A,Ra,ti,ni,Db,nh,Ji,Xi,ka,ro,Yu),{FullProductWithoutLicensesSchema:cO}=((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()})}))(Pb,A,Sb,Ub,nb,vh),{CreateProductItemParamsSchema:el}=((e,t,n,r)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(n.literal(r)).nullish()})}))(Ju,Ra,A,Zi),{CreatePlanItemParamsV1Schema:Ka}=((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."})}))(Mb,Yh),{LicenseCustomizeSchema:tl}=((e,t,n,r)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(n).optional(),remove_items:e.array(r).optional()})}))(A,oo,Ka,Da),{PlanLicenseParamsSchema:Ha}=((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()})}))(A,tl),{UpdateProductV2ParamsSchema:uO}=((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(u=>u.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})})}))(A,to,Au,el,Ha,wu,Ua,io,_r),{CreatePlanParamsV1Schema:Lb}=((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})})}))(A,to,oo,Ka,Ha,La,Ua,kb,_r),{UpdatePlanParamsV1Schema:lO}=((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."})})}))(Lb,A,oo,La,to),{CustomizePlanLicenseSchema:za}=((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()})}))(A,tl),{CreateProductV2ParamsSchema:dO}=((e,t,n,r,i,o,a,s,c,l)=>({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:[l]})}))(A,to,Au,el,Ha,wu,Ua,io,_r,Uh),{CustomizePlanV1BaseSchema:nl}=((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."})})}))(A,oo,Ka,Da,ah,La,io,za,dh),{VariantCustomizeSchema:Bb}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))($u,nl),{DiffedCustomizePlanV1Schema:pO}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))($u,nl),{ApiPlanV1Schema:mO}=((e,t,n,r,i,o,a,s,c,l,u,d,p,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:l.meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:u.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:p.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."})})}))(A,oi,Tn,Ta,Du,Fb,pb,eb,Qi,no,Ga,_r,tb,Bb);import{z as C}from"zod";var qb=C.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),ol=C.enum(["single_use","continuous_use"]),Wa=C.record(C.string(),C.union([C.string(),C.number(),C.boolean()]).transform(String).pipe(C.string())),rl=C.string().min(1).max(64).refine(e=>!e.includes("::")),al={credit_amount:C.number(),tier_behavior:C.never().optional(),tiers:C.never().optional()},sl={credit_amount:C.never().optional(),tier_behavior:C.literal("graduated"),tiers:C.array(C.strictObject({to:C.union([C.number(),C.literal("inf")]),credit_amount:C.number()}))},Vb=C.union([C.strictObject({match:Wa,priority:C.number().int().optional(),...al}),C.strictObject({match:Wa,priority:C.number().int().optional(),...sl})]),$b=C.strictObject({match:Wa,factor:C.number().positive().optional(),add:C.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),il={metered_feature_id:C.string(),feature_amount:C.number().optional(),dimensions:C.record(rl,Vb).optional(),multipliers:C.record(rl,$b).optional()},Qa=C.union([C.strictObject({...il,...al}),C.strictObject({...il,...sl})]),so=C.number().min(-100),cl=C.record(C.string(),C.strictObject({markup:so})).nullish(),co=C.record(C.string().regex(/.+\/.+/),C.strictObject({markup:so.optional(),input_cost:C.number().min(0).optional(),output_cost:C.number().min(0).optional()})).nullish(),Gb=C.strictObject({default_markup:so.optional(),provider_markups:cl,model_markups:co}),Za=C.strictObject({schema:C.array(Qa).optional(),markups:Gb.optional()}),Kb=C.strictObject({filters:C.array(C.strictObject({property:C.string(),operator:C.string(),value:C.array(C.string())})),aggregate:C.strictObject({type:C.string(),property:C.string().nullable()}),usage_type:ol}),ul=C.strictObject({schema:C.array(Qa).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:C.boolean().optional(),usage_type:ol.default("single_use").overwrite(()=>"single_use"),default_markup:so.optional(),provider_markups:cl}),Ya=ul.safeExtend({schema:C.array(Qa).length(0)}),ao={id:qb,name:C.string().min(1),display:C.strictObject({singular:C.string().optional(),plural:C.string().optional()}).nullish(),event_names:C.array(C.string()).default([]),model_markups:co,stripe_meter:C.strictObject({id:C.string(),event_name:C.string()}).nullish(),stripe_product_id:C.string().nullish()},Ja=e=>C.discriminatedUnion("type",[C.strictObject({...ao,...e,type:C.literal("boolean"),config:C.null()}),C.strictObject({...ao,...e,type:C.literal("metered"),config:Kb}),C.strictObject({...ao,...e,type:C.literal("credit_system"),config:ul}),C.strictObject({...ao,...e,type:C.literal("ai_credit_system"),config:Ya})]),hO=Ja({}),Hb=C.strictObject({id:C.boolean(),type:C.boolean(),usage_type:C.boolean()}),zb={internal_id:C.uuid(),org_id:C.uuid(),created_at:C.number(),env:C.enum(["sandbox","live"]),archived:C.boolean(),project_id:C.uuid(),environment_id:C.uuid(),revision:C.number().int().nonnegative(),update_rules:Hb},ll=Ja(zb),bO=C.strictObject({rows:C.array(ll).max(200),nextCursor:C.uuid().nullable()}),dl=C.strictObject({features:C.array(ll).max(500),limited:C.boolean()}),_O=C.union([Ja({action:C.literal("save"),internal_id:C.uuid().nullable(),revision:C.number().int().nonnegative()}),C.strictObject({action:C.enum(["archive","restore","delete"]),internal_id:C.uuid(),revision:C.number().int().nonnegative()})]);import{z as yr}from"zod";var pl=yr.number().int().min(0).max(1e8),ai=yr.strictObject({kind:yr.enum(["graduated","volume"]),tiers:yr.array(yr.strictObject({upTo:yr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:pl,flatAmountMinor:pl.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>t.upTo!==null&&(n===0||t.upTo>e.tiers[n-1].upTo)),"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 Xa(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?ai.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 uo(e){return Xa({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}import{z as j}from"zod";import{z as K}from"zod";import{z as dn}from"zod";import{z as Wb}from"zod";var Rn=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],W=Wb.enum(Rn);function Zn(e){let t=W.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function vO(e,t){let n=Zn(t),r=e.trim().match(/^(\d+)(?:\.(\d+))?$/);if(!r||(r[2]?.length??0)>n)throw new Error("Amount has invalid currency precision");let i=BigInt(r[1])*BigInt(10**n)+BigInt((r[2]??"").padEnd(n,"0")||"0");if(i>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Amount exceeds the supported range");return Number(i)}function AO(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let n=Zn(t),r=String(e).padStart(n+1,"0");return n?`${r.slice(0,-n)}.${r.slice(-n)}`:r}function ml(e,t,n="en",r={}){let i=W.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:i,...r}).format(e/10**Zn(i))}import{z as xn}from"zod";var CO={plans:Rn,creditPacks:Rn,paidSeats:Rn,postpaid:Rn},fl=xn.partialRecord(xn.enum(Rn),xn.number().int().min(1).max(1e8)),Qb=xn.strictObject({currency:xn.enum(Rn),automaticTax:xn.boolean()}),Zb=xn.strictObject({projectId:xn.uuid(),environmentId:xn.uuid()}),EO=Zb.extend({settings:Qb});var Yb=dn.string().regex(/^[a-z][a-z0-9_]{0,63}$/),gl=dn.number().int().min(0).max(1e4),es=dn.object({key:Yb,featureId:dn.uuid(),planVersionId:dn.uuid(),includedQuantity:gl,maximumQuantity:gl,unitAmountCents:dn.number().int().min(0).max(1e8),currency:W,currencyOptions:fl.optional(),stripePriceId:dn.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),pooledResources:dn.array(dn.string().regex(/^(?:[a-z][a-z0-9_]{0,63}|pool:[0-9a-f-]{36})$/)).max(100),requireAssignment:dn.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 pt}from"zod";import{z as He}from"zod";var ct=He.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),Y=He.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),lo=He.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),ts=Y.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),hl=He.string().min(1).max(64),Xt=He.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),bl=He.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Je=He.record(hl,He.union([He.string().max(120),He.number().finite(),He.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),_l=He.record(hl,He.union([He.string().max(120),He.number().finite(),He.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Sr=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split("."),i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},yl=He.array(He.object({upTo:ts.nullable(),cost:Y}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>t.upTo!==null&&(n===0||Sr(t.upTo)>Sr(e[n-1].upTo))),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),Jb=He.object({key:bl,match:_l,priority:He.number().int().default(0),cost:Y.optional(),tiers:yl.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),Xb=He.object({key:bl,match:_l,factor:ts.optional(),add:lo.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),e_=He.object({units:ts.default("1"),cost:Y,tiers:yl.optional(),dimensions:He.array(Jb).max(12).optional(),multipliers:He.array(Xb).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(a=>a.key)).size!==n.length||new Set(r.map(a=>a.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let a=0;a<n.length;a++)for(let s=a+1;s<n.length;s++){let c=n[a],l=n[s];Object.keys(c.match).length===Object.keys(l.match).length&&c.priority===l.priority&&!Object.keys(c.match).some(u=>l.match[u]!==void 0&&l.match[u]!==c.match[u])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"})}let i=[e.cost,...(e.tiers??[]).map(a=>a.cost),...n.flatMap(a=>[...a.cost===void 0?[]:[a.cost],...(a.tiers??[]).map(s=>s.cost)])],o=Sr(e.units);for(let a of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((f,h)=>s&1<<h);if(c.some((f,h)=>c.slice(h+1).some(I=>Object.keys(f.match).some(v=>I.match[v]!==void 0&&I.match[v]!==f.match[v]))))continue;let l=Sr(a),u=BigInt("1"),d=BigInt("0");for(let f=0;f<r.length;f++)s&1<<f&&(l*=Sr(r[f].factor??"1"),u*=BigInt("1000000"),d+=Sr(r[f].add??"0"));let p=(l+d*u)*BigInt("1000000"),g=u*o;(p<BigInt("0")||p%g!==BigInt("0")||p/g>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),FO=e_.safeExtend({featureKey:Xt});var ns=pt.object({days:pt.number().int().min(1).max(730),cardRequired:pt.boolean(),featureAllowances:pt.record(pt.uuid(),pt.number().int().min(0).max(1e9)),creditAmounts:pt.record(pt.uuid(),Y)}).strict(),rs=pt.object({id:pt.uuid(),planVersionId:pt.uuid(),slot:pt.string(),cardRequired:pt.boolean(),status:pt.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:pt.iso.datetime().nullable(),endsAt:pt.iso.datetime().nullable(),createdAt:pt.iso.datetime()}).strict();var is=Oe.object({group:Oe.string().regex(/^[a-z][a-z0-9_]{0,63}$/).default("main"),kind:Oe.enum(["main","addon"]).default("main")}).strict(),t_=Oe.enum(["immediate","end_of_cycle"]),n_=Oe.enum(["attach","change","cancel","resume","cancel_change"]),Sl=Oe.object({id:Oe.uuid(),subscriptionId:Oe.uuid().nullable(),targetPlanVersionId:Oe.uuid().nullable(),action:n_,timing:t_,status:Oe.enum(["preparing","payment_pending","scheduled","completed","canceled","failed"]),effectiveAt:Oe.iso.datetime().nullable(),createdAt:Oe.iso.datetime()}),r_=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:Sl.nullable(),trial:rs.nullable().optional()}),$O=Oe.object({customerId:Oe.uuid(),evaluatedAt:Oe.iso.datetime(),holdings:Oe.array(r_),changes:Oe.array(Sl),trials:Oe.array(rs).optional()});import{z as os}from"zod";var as=os.enum(["sandbox","live"]),Fe=os.object({projectId:os.string().min(1),environment:as}).strict();var pn=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"),XO=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"),xl=K.object({key:pn,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()}),eP=xl.extend({...Fe.shape,id:K.string().min(1),archived:K.boolean(),createdAt:K.iso.datetime()}),Il=K.object({amountCents:K.number().int().min(0).max(1e8),currency:W,interval:K.enum(["free","month","year"]),currencyOptions:K.partialRecord(W,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"),i_=K.object({featureId:K.string().min(1),allowance:K.number().int().min(0).max(1e9).nullable(),pooled:K.boolean().optional()}),vl=K.object({name:K.string().trim().min(1).max(80),description:K.string().trim().max(240),price:Il,membership:is.optional(),trial:ns.nullable().optional(),licenses:K.array(es).max(20).optional(),items:K.array(i_).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")}),tP=K.object({key:pn,config:vl}),nP=Fe.extend({id:K.string().min(1),key:pn,draft:vl,status:K.enum(["draft","published","archived"]),publishedVersionId:K.string().nullable(),isDefault:K.boolean(),updatedAt:K.iso.datetime()}),o_=xl.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"),Al=Fe.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:Il,membership:is.optional(),trial:ns.nullable().optional(),licenses:K.array(es).optional(),items:K.array(o_),publishedAt:K.iso.datetime()}).strict(),ss=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"),rP=Fe.extend({id:K.string(),customerId:K.string(),planVersionId:K.string(),assignedAt:K.iso.datetime(),source:K.literal("demo"),validity:ss.nullable().default(null),used:K.record(K.string(),K.number().int().min(0))}),iP=Fe.extend({id:K.string(),customerId:K.string(),at:K.iso.datetime(),message:K.string()});import{z as b}from"zod";import{z as se}from"zod";import{z as w}from"zod";var Ae=w.json().superRefine((e,t)=>{let n=0;function r(i,o){if(++n>1e4||o>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(a=>r(a,o+1));else if(i&&typeof i=="object")for(let[a,s]of Object.entries(i))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,o+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),Ft=w.record(w.string().min(1).max(128),Ae).superRefine((e,t)=>{(!Ae.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),a_=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),St=Ft.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r)){if(i==="$savedGroup"&&!w.strictObject({id:w.uuid(),attributeKey:w.string().min(1).max(128).optional()}).safeParse(o).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!a_.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof o=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(o)||[...o.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(o.replace(/\\u([0-9a-f]{4})/gi,(a,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(o)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(o)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),po=w.discriminatedUnion("type",[w.strictObject({type:w.literal("condition"),condition:St}),w.strictObject({type:w.literal("list"),attributeKey:w.string().min(1).max(128),values:w.array(w.union([w.string(),w.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function si(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==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.id=="string"?t.add(o.id):["$inGroup","$notInGroup"].includes(i)&&typeof o=="string"?t.add(o):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(o)}return n(e),[...t]}var s_=w.record(w.uuid(),po).superRefine((e,t)=>{let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(o),a.type==="condition"&&si(a.condition).forEach(i),n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),us=w.tuple([w.number().min(0).max(1),w.number().min(0).max(1)]).refine(([e,t])=>e<=t),wl=w.strictObject({attribute:w.string().optional(),seed:w.string().min(1),hashVersion:w.literal(2),ranges:w.array(us).min(1).max(100)}),c_=w.strictObject({id:w.string().min(1).max(128),condition:St,gate:w.boolean().optional()}),cs={id:w.string().max(128).optional(),condition:St.optional(),parentConditions:w.array(c_).max(50).optional(),filters:w.array(wl).max(20).optional()},u_=w.union([w.strictObject({...cs}),w.strictObject({...cs,force:Ae,coverage:w.number().min(0).max(1).optional(),range:us.optional(),seed:w.string().min(1).optional(),hashAttribute:w.string().optional(),hashVersion:w.literal(2).optional()}),w.strictObject({...cs,type:w.literal("experiment-ref"),experimentId:w.uuid(),values:w.record(w.string().min(1),Ae),meta:w.record(w.string().min(1),w.strictObject({passthrough:w.boolean()})).optional()})]),l_=w.strictObject({defaultValue:Ae,rules:w.array(u_).max(100)}),Ol=w.record(w.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),l_).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${o}`});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${o}`});return}n.add(o);for(let s of a.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),d_=w.strictObject({name:w.string().max(80),reason:w.string().max(500),dateStarted:w.iso.datetime({offset:!0}),dateEnded:w.iso.datetime({offset:!0}).nullable(),coverage:w.number().min(0).max(1),variationWeights:w.array(w.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:St,savedGroups:w.array(w.strictObject({match:w.enum(["any","all","none"]),ids:w.array(w.uuid()).min(1)})).max(50),namespace:w.strictObject({id:w.uuid(),ranges:w.array(us).min(1)}).nullable(),seed:w.string().min(1).max(128)}),xr=w.strictObject({key:w.string().min(1).max(128),name:w.string().min(1).max(80),hypothesis:w.string().max(2e3),status:w.enum(["draft","running","stopped"]),hashAttribute:w.string().min(1).max(128),fallbackAttribute:w.string().max(128).nullable(),hashVersion:w.literal(2),disableStickyBucketing:w.boolean(),bucketVersion:w.number().int().min(0).max(1e3),minBucketVersion:w.number().int().min(0).max(1e3),variations:w.array(w.strictObject({id:w.string().min(1),key:w.string().min(1),name:w.string().max(80),description:w.string().max(500)})).min(2).max(20),phases:w.array(d_).min(1).max(100),releasedVariationId:w.string().nullable(),excludeFromPayload:w.boolean(),statusSchedule:w.strictObject({startAt:w.iso.datetime({offset:!0}).nullable(),stopAt:w.iso.datetime({offset:!0}).nullable(),stopAfter:w.strictObject({value:w.number().int().positive().max(36500),unit:w.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>r>0&&(Date.parse(n.dateStarted)<Date.parse(e.phases[r-1].dateStarted)||!e.phases[r-1].dateEnded||Date.parse(e.phases[r-1].dateEnded)>Date.parse(n.dateStarted)))||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],o,a)=>r>=i||a.some(([s,c],l)=>l!==o&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});function dP(e,t,n=Date.now()){return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,{defaultValue:i.defaultValue,rules:i.rules.flatMap(o=>{if(!("experimentId"in o))return[{...o,hashVersion:2}];let a=t[o.experimentId];if(!a)throw new Error(`Missing experiment: ${o.experimentId}`);let s=a.phases[a.phases.length-1],c=a.statusSchedule?.startAt?Date.parse(a.statusSchedule.startAt):null,l=Pl(a),u=a.status!=="stopped"&&(a.status==="running"||c!==null&&n>=c)&&(c===null||n>=c)&&(l===null||n<l),{type:d,experimentId:p,values:g,meta:f,...h}=o;if(a.variations.some(S=>!Object.hasOwn(g,S.key))||Object.keys(g).length!==a.variations.length||Object.keys(f??{}).some(S=>!a.variations.some(R=>R.key===S)))throw new Error("Every variation needs a Feature value");let I={$and:[s.condition,...h.condition?[h.condition]:[],...s.savedGroups.map(S=>{let R=S.ids.map(D=>({$savedGroup:{id:D}}));return S.match==="all"?{$and:R}:S.match==="none"?{$nor:R}:{$or:R}})]},v=a.variations.find(S=>S.id===a.releasedVariationId);return v&&!a.excludeFromPayload?f?.[v.key]?.passthrough?[{...h,condition:I}]:[{...h,condition:I,force:g[v.key]}]:[{...h,condition:I,key:a.key,variations:a.variations.map(S=>g[S.key]),meta:a.variations.map(S=>({key:S.key,name:S.name,...f?.[S.key]})),weights:s.variationWeights,coverage:u?s.coverage:0,seed:s.seed,hashVersion:2,hashAttribute:a.hashAttribute,fallbackAttribute:a.fallbackAttribute??void 0,disableStickyBucketing:!u||a.disableStickyBucketing,bucketVersion:a.bucketVersion,minBucketVersion:a.minBucketVersion,filters:[...h.filters??[],...a.filters??[]]}]})}]))}function Pl(e){if(e.statusSchedule?.stopAt)return Date.parse(e.statusSchedule.stopAt);let t=e.statusSchedule?.stopAfter;return!t||e.status==="draft"&&!e.statusSchedule?.startAt?null:Date.parse(e.statusSchedule?.startAt??e.phases[e.phases.length-1].dateStarted)+t.value*(t.unit==="days"?864e5:36e5)}function pP(e,t=Date.now()){let n=Object.values(e).filter(r=>r.status!=="stopped"&&!(r.releasedVariationId&&!r.excludeFromPayload)).flatMap(r=>[r.statusSchedule?.startAt?Date.parse(r.statusSchedule.startAt):null,Pl(r)]).filter(r=>r!==null&&r>t);return n.length?new Date(Math.min(...n)).toISOString():null}var p_=xr.safeExtend({filters:w.array(wl).optional()}),m_=w.strictObject({experiments:w.record(w.uuid(),p_),savedGroups:s_}),f_=w.strictObject({attributeName:w.string(),attributeValue:w.string(),assignments:w.record(w.string(),w.string())}),mP=w.strictObject({snapshot:m_,attributes:Ft,results:Ft,stickyBucketAssignmentDocs:w.record(w.string(),f_)}),fP=w.strictObject({variantKey:w.string().nullable(),bucketVersion:w.number().int().min(0),source:w.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:w.number().min(0).max(1).optional(),stickyBucketUsed:w.boolean().optional(),hashUsed:w.boolean().optional()});import{z as g_}from"zod";var El=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,en=g_.string().max(16).regex(El,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");function Yn(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:n,script:r,region:i}=new Intl.Locale(t),o=[n,r,i].filter(Boolean).join("-");return El.test(o)?o:null}catch{return null}}var h_=new Set(["TW","HK","MO"]);function Cl(e){let[t,n,r]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let i=n?.length===4?n:void 0,o=n?.length===4?r:n;return i?`zh-${i}`:o&&h_.has(o)?"zh-Hant":"zh-Hans"}function mo(e,t,n){let r=t.map(i=>({code:en.parse(i),normalized:i}));for(let i of e){let o=Yn(i);if(!o)continue;let a=r.find(l=>l.normalized===o);if(a)return a.code;let s=Cl(o),c=r.filter(l=>Cl(l.normalized)===s);if(c.length>0)return(c.find(l=>!l.normalized.includes("-")||l.normalized===s)??c[0]).code}return n}var b_=[{code:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{code:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u53F0\u7063\uFF09"},{code:"zh-HK",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u9999\u6E2F\uFF09"},{code:"en",label:"English"},{code:"ja",label:"\u65E5\u672C\u8A9E"},{code:"ko",label:"\uD55C\uAD6D\uC5B4"},{code:"es",label:"Espa\xF1ol"},{code:"fr",label:"Fran\xE7ais"},{code:"de",label:"Deutsch"},{code:"pt-BR",label:"Portugu\xEAs (Brasil)"},{code:"it",label:"Italiano"},{code:"ru",label:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"vi",label:"Ti\u1EBFng Vi\u1EC7t"},{code:"th",label:"\u0E44\u0E17\u0E22"},{code:"id",label:"Bahasa Indonesia"},{code:"ar",label:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629"}];function bP(e){return b_.find(t=>t.code===e)?.label??e}var ls={"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"}},xP=["zh-CN","zh-TW","zh-HK","en","ja","ko","es","fr","de","pt-BR","it","ru","vi","th","id","ar"];function ds(e){let t=Yn(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(i=>["TW","HK","MO"].includes(i))?"zh-Hant":"zh-Hans":n[0];return ls[r]?{locale:t,copy:ls[r]}:{locale:"en",copy:ls.en}}function __(e,t,n="zh-CN"){let r=Zn(t);return ml(e,t,ds(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function y_(e,t="zh-CN"){let n=ds(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e.percentOff/100):__(e.amountOffCents,e.currency,n)}var Tl={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 Rl(e,t="zh-CN",n="month"){let r=ds(t),i=y_(e.discount,r.locale),o=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",a=r.locale.split("-")[0],s=a==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":a,c=e.duration.type==="repeating"&&n!=="month"?Tl[s]??Tl.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],l=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}",l)}var PP=se.enum(["draft","active","paused","archived"]),Ir=se.discriminatedUnion("type",[se.object({type:se.literal("percent"),percentOff:se.number().int().min(1).max(100)}).strict(),se.object({type:se.literal("amount"),amountOffCents:se.number().int().min(1).max(1e8),currency:W}).strict()]),tn=se.discriminatedUnion("type",[se.object({type:se.literal("once")}).strict(),se.object({type:se.literal("repeating"),months:se.number().int().min(1).max(36)}).strict(),se.object({type:se.literal("forever")}).strict()]),kl=se.discriminatedUnion("type",[se.object({type:se.literal("all")}).strict(),se.object({type:se.literal("plans"),planIds:se.array(se.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()]),S_=se.strictObject({firstPurchaseOnly:se.boolean(),condition:St}),jl=se.object({name:se.string().trim().min(1).max(80),description:se.string().max(500),discount:Ir,duration:tn,appliesTo:kl,eligibility:S_,startsAt:se.iso.datetime().nullable(),endsAt:se.iso.datetime().nullable(),totalLimit:se.number().int().min(1).max(1e6).nullable(),perCustomerLimit:se.number().int().min(1).max(10),grantWindowHours:se.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"]}),CP=se.object({code:se.string().trim().transform(e=>e.toUpperCase()).pipe(se.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:se.number().int().min(1).max(1e6).nullable(),expiresAt:se.iso.datetime().nullable(),firstPurchaseOnly:se.boolean(),minimumAmountCents:se.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:W.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");function EP(){return{name:"\u65B0\u4F18\u60E0\u5238",description:"",discount:{type:"percent",percentOff:20},duration:{type:"once"},appliesTo:{type:"all"},eligibility:{firstPurchaseOnly:!1,condition:{}},startsAt:null,endsAt:null,totalLimit:null,perCustomerLimit:1,grantWindowHours:72}}var ps=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function TP(e,t,n){if(e==="draft")return[];if(e==="archived")return[{field:"name",reason:"archived"}];let r=[];return ps(t.discount,n.discount)||r.push({field:"discount",reason:"immutable"}),ps(t.duration,n.duration)||r.push({field:"duration",reason:"immutable"}),ps(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 x_=e=>`$${(e/100).toFixed(e%100===0?0:2)}`;function RP(e,t="zh-CN"){return Rl(e,t)}function kP(e){return x_(e)}function jP(e,t){return e.startsAt&&Date.parse(e.startsAt)>t?"scheduled":e.endsAt&&Date.parse(e.endsAt)<=t?"ended":"open"}var ms=se.object({id:se.uuid(),couponId:se.uuid(),status:se.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:se.iso.datetime(),expiresAt:se.iso.datetime(),coupon:se.object({name:se.string(),discount:Ir,duration:tn,appliesTo:kl}).strict()}).strict(),fo=se.enum(["inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Ml=b.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),ci=b.string().regex(/^(0|[1-9]\d{0,14})$/),vr=b.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),I_=b.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),ui=I_,In=Y.refine(e=>/[1-9]/.test(e)),xt=b.iso.datetime({offset:!0}),Jn=e=>{let[t,n=""]=e.split(".");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},v_=b.array(b.object({upTo:In.nullable(),unitAmountMinor:Ml,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)=>t.upTo!==null&&(n===0||Jn(t.upTo)>Jn(e[n-1].upTo)))}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),A_=b.discriminatedUnion("kind",[b.object({kind:b.literal("flat"),units:In,unitAmountMinor:Ml}).strict(),b.object({kind:b.enum(["graduated","volume"]),units:In,tiers:v_}).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"])}),kn=b.object({currency:W,pricing:A_,billingCycle:w_.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function Ll(e){return e.pricing.kind==="flat"&&Jn(e.pricing.units)>0n&&Jn(e.pricing.unitAmountMinor)===Jn(e.pricing.units)*BigInt(10**Zn(e.currency))}var Nl={requestId:b.uuid(),productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:W},Bl=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)}),ql=b.discriminatedUnion("kind",[b.object({...Nl,kind:b.literal("auto_topup"),threshold:lo,quantity:In.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Bl.optional()}).strict(),b.object({...Nl,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:ui,maxOutstandingMinor:ui}).strict()]),Dl={productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:W},Vl=b.discriminatedUnion("kind",[b.object({...Dl,kind:b.literal("auto_topup"),threshold:lo,quantity:In.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Bl.optional(),purchaseAmountMinor:ui,purchaseUnits:In}).strict(),b.object({...Dl,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:ui,maxOutstandingMinor:ui,cashPrice:kn}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),go=b.object({id:b.uuid(),terms:Vl,status:b.enum(["prepared","active","revoked","blocked"]),createdAt:xt,acceptedAt:xt.nullable(),effectiveAt:xt.nullable(),revokedAt:xt.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"),$l=b.object({authorizationId:b.uuid(),terms:Vl,setupUrl:b.url().nullable()}).strict(),Gl=b.object({authorizationId:b.uuid(),accepted:b.literal(!0)}).strict(),Kl=b.object({authorizationId:b.uuid(),requestId:b.uuid()}).strict(),Hl=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),basis:b.enum(["usage","credits"]),filter:Je.optional(),limit:Y.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(In).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>n===0||t>e.thresholds[n-1])&&(e.includedThresholds??[]).every((t,n,r)=>n===0||t>r[n-1])&&(e.absoluteThresholds??[]).every((t,n,r)=>n===0||Jn(t)>Jn(r[n-1])),"Notification thresholds must increase"),O_=Hl.safeExtend({requestId:b.uuid()}),Fl={control:b.literal("overage"),requestId:b.uuid(),internal_feature_id:b.uuid(),entityId:b.uuid().nullable()},P_=b.discriminatedUnion("action",[b.strictObject({...Fl,action:b.literal("set"),allowed:b.boolean().nullable(),overageLimit:Y.nullable(),skipOverageBilling:b.boolean()}),b.strictObject({...Fl,action:b.literal("remove")})]),zl=b.union([O_,P_]),C_=b.strictObject({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),allowed:b.boolean().nullable(),overageLimit:Y.nullable(),skipOverageBilling:b.boolean(),interval:b.enum(["day","week","month","year"]),startsAt:xt,endsAt:xt,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()}),E_=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),basis:b.enum(["usage","credits"]),filter:Je.optional(),startsAt:xt,endsAt:xt,used:ct,reserved:ct,limit:Y.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(In).max(8).optional(),notifiedAbsoluteThresholds:b.array(In).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||Y.safeParse(e.used).success&&Y.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),T_=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:xt.nullable(),attemptCount:b.number().int().nonnegative(),failedAttemptCount:b.number().int().nonnegative(),suspendedAt:xt.nullable(),nextAttemptAt:xt.nullable(),failureReason:b.string().min(1).max(240).nullable()}).strict(),Wl=b.object({internal_feature_id:b.uuid().optional(),entityId:b.uuid().optional()}).strict(),fs=b.object({authorizations:b.array(go).max(100),limits:b.array(Hl).max(100),overages:b.array(C_).max(100).optional(),windows:b.array(E_).max(200),autoTopups:b.array(T_).max(100),limited:b.boolean()}).strict(),R_=b.object({id:b.uuid(),internal_feature_id:b.uuid(),productVersionId:b.uuid(),authorizationId:b.uuid(),entityId:b.uuid().nullable(),units:Y,amountMinor:vr,cashPrice:kn}).strict(),li=b.object({id:b.uuid(),sourceKind:b.enum(["product","usage"]),providerInvoiceId:b.string().min(1).max(240).nullable(),status:b.enum(["accruing","open","pending","paid","failed","void"]),currency:W,startsAt:xt.nullable(),endsAt:xt.nullable(),amountMinor:ci,grossAmountMinor:ci,discountMinor:ci,paidAmountMinor:ci,refundedAmountMinor:ci,createdAt:xt,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:xt.nullable()}).strict().nullable(),lines:b.array(R_).max(100),linesLimited:b.boolean()}).strict(),Ql=b.object({invoiceId:b.uuid(),accepted:b.literal(!0)}).strict(),Zl=b.object({after:b.uuid().nullable(),limit:b.number().int().min(1).max(100)}).strict(),Yl=b.object({rows:b.array(li).max(100),nextCursor:b.uuid().nullable()}).strict(),Ul=b.strictObject({id:b.string(),coupon:b.string(),start:b.number().nonnegative(),end:b.number().nullable()}),k_=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(Ul).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:Ul.optional()})).max(20)})).max(100)}),Jl=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")}),Xl=b.strictObject({membershipId:b.uuid(),operationId:b.uuid(),status:b.enum(["pending","effective"]),execution:k_.nullable(),grants:b.array(b.strictObject({id:b.uuid(),couponId:b.uuid(),name:b.string(),discount:Ir,duration:tn,startedAt:xt.nullable()})).max(20)});import{z as di}from"zod";var pi=di.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),mi=di.number().int().min(1).max(1e3),Xn=di.object({cap:Y.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:di.number().positive().max(1e4).nullable(),cycles:di.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var gs={key:pn,name:j.string().trim().min(1).max(80),description:j.string().trim().max(240)},ed=Y.refine(e=>/[1-9]/.test(e)),ho=j.array(j.object({currency:W,amountMinor:j.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"),hs=j.strictObject({units:ed,prices:j.array(j.strictObject({currency:W,amountMinor:j.number().int().min(0).max(1e8),pricing:ai.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:j.number().int().min(0).max(1e4),maximumQuantity:j.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&&Xa(t,n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit"),j_=j.discriminatedUnion("kind",[j.object({kind:j.literal("access"),internal_feature_id:j.uuid()}).strict(),j.object({kind:j.literal("metered"),internal_feature_id:j.uuid(),usageUnit:j.enum(["count","micro_usd"]),amount:Y.nullable(),reset:pi,resetCount:mi,pooled:j.boolean(),rollover:Xn.nullable().optional(),cashPrice:kn.nullable().optional(),prepaidPrice:hs.optional(),feature_override:Za.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 _s(e.amount,e.prepaidPrice.units,e.prepaidPrice.maximumQuantity),!0}catch{return!1}},"The maximum purchased allowance must fit the quantity ledger"),j.object({kind:j.literal("credit"),internal_feature_id:j.uuid(),amount:Y,reset:pi,resetCount:mi,rollover:Xn.nullable(),pooled:j.boolean(),feature_override:Za.nullish(),cashPrice:kn.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&Ll(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")]),bs=j.array(j_).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),td=j.object({days:j.number().int().min(1).max(730),cardRequired:j.boolean(),allowances:bs}).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"),nd=j.object({key:pn,internal_feature_id:j.uuid(),productVersionId:j.uuid(),includedQuantity:j.number().int().min(0).max(1e4),maximumQuantity:j.number().int().min(0).max(1e4),prices:ho,pooled_internal_feature_ids:j.array(j.uuid()).max(100),requireAssignment:j.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"),fi=j.discriminatedUnion("kind",[j.object({...gs,kind:j.literal("membership"),groupId:j.uuid(),membershipType:j.enum(["main","addon"]),interval:j.enum(["free","week","month","year","one_time"]),intervalCount:j.number().int().min(1).max(156).optional(),prices:ho,allowances:bs,trial:td.nullable(),licenses:j.array(nd).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"),j.object({...gs,kind:j.literal("topup"),interval:j.literal("one_time"),prices:ho,internal_feature_id:j.uuid(),amount:ed,expiresDays:j.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),bo=j.object({interval:j.enum(["free","week","month","year","one_time"]).optional(),intervalCount:j.number().int().min(1).max(156).nullable().optional(),prices:ho.optional(),allowances:j.object({upsert:bs,remove:j.array(j.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:td.nullable().optional(),licenses:j.array(nd).max(20).optional()}).strict(),rd=j.object({...gs,kind:j.literal("variant"),baseProductVersionId:j.uuid(),overrides:bo}).strict(),JP=j.union([fi,rd]);function XP(e,t){let n=rd.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),fi.parse(s)}function eC(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}),bo.parse(n)}var tC=j.object({products:j.array(j.object({id:j.uuid(),productId:j.string().min(1),name:j.string(),kind:j.enum(["membership","topup"]),version:j.number().int().positive()}).strict()).max(500),limited:j.boolean()}).strict(),N_=Xu.and(j.object({internal_id:j.uuid(),revision:j.number().int().nonnegative(),licenses:j.array(za)})),nC=j.strictObject({rows:j.array(N_).max(200),nextCursor:j.uuid().nullable()}),rC=j.object({groups:j.array(j.object({id:j.uuid(),name:j.string(),defaultProductVersionId:j.uuid().nullable()}).strict()).max(500),features:dl.shape.features,products:j.array(j.object({id:j.uuid(),productId:j.uuid(),version:j.number().int().positive(),configuration:fi,baseProductVersionId:j.uuid().nullable()}).strict()).max(500),limited:j.boolean()}).strict();function _s(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(".");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 sC=nn.object({requestId:nn.uuid(),baseProductVersionId:nn.uuid(),name:nn.string().trim().min(1).max(80),description:nn.string().trim().max(240),overrides:bo}).strict(),cC=nn.object({productId:nn.uuid(),productVersionId:nn.uuid(),bindingStatus:nn.enum(["ready","requires_binding"]),missingCurrencies:nn.array(nn.string().regex(/^[A-Z]{3}$/)).max(20)}).strict();import{z as it}from"zod";var gi=it.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),dC=it.enum([...gi.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),pC=it.enum([...gi.options,"stale_revision"]),D_=it.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),F_=it.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),id={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};function mC(e){return[400,405,415,422].includes(e)?"INVALID_REQUEST":e===401?"UNAUTHENTICATED":e===403?"FORBIDDEN":e===404?"NOT_FOUND":[409,412,425].includes(e)?"CONFLICT":e===413?"PAYLOAD_TOO_LARGE":e===429?"RATE_LIMITED":e===501?"NOT_CONFIGURED":[408,502,503,504].includes(e)?"SERVICE_UNAVAILABLE":"INTERNAL_ERROR"}function U_(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(["TIMEOUT","NETWORK_ERROR","HTTP_ERROR","INVALID_RESPONSE","INVALID_SERVER_RESPONSE"].includes(e))return{retryable:!1,recovery:"recover_operation"};if(e==="NOT_IDENTIFIED"||e==="INVALID_TOKEN")return{retryable:!1,recovery:"authenticate"};if(["INVALID_URL","INVALID_TIMEOUT","SERVER_ONLY","AMBIGUOUS_AUTHENTICATION"].includes(e))return{retryable:!1,recovery:"fix_request"};if(e==="PROTOCOL_MISMATCH")return{retryable:!1,recovery:"upgrade_sdk"};if(e==="IDENTITY_CHANGED")return{retryable:!1,recovery:"reload_state"};if(e==="CAPABILITY_UNAVAILABLE")return{retryable:!1,recovery:"check_availability"};let n=gi.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:id[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function fC(e,t){let n=gi.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):id[n.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&r[e].includes(t)}function M_(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var od=it.object({retryable:it.boolean(),recovery:D_,reason:F_.optional(),retryAfterSeconds:it.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),L_=it.object({requestId:it.uuid().optional(),error:it.object({code:it.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:it.string(),...od.partial().shape})}),gC=it.object({error:L_.shape.error.extend({requestId:it.uuid().optional()})}),hC=it.object({error:it.string(),code:it.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:it.uuid(),...od.shape});function bC(e,t,n={}){let r=U_(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,o=r.retryable&&n.retryable!==!1&&i!=="recover_operation",a=o?M_(n.retryAfter??null):void 0;return{...r,retryable:o,recovery:i,...a===void 0?{}:{retryAfterSeconds:a},...n.reason?{reason:n.reason}:{}}}var sd="X-Indiana-Protocol",B_="X-Indiana-SDK-Version",yC="X-Indiana-Supported-Protocols",ad={stableSupportMonths:12,retirementNoticeDays:180,documentation:"/docs/release-notes#support-policy"},q_={current:"0.3",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:null,noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[]}]},cd=/^(?:0\.(?:0|[1-9]\d*)|[1-9]\d*)$/,V_=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function ud(e){let t=V_.exec(e);return t?t[1]==="0"?`0.${t[2]}`:t[1]:null}var Ss=e=>/^[1-9]\d*$/.test(e);function $_(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 ys=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 SC(e){let t=[],n=new Set;for(let r of e.releases){let i=r.protocol;(!cd.test(i)||n.has(i))&&t.push(`Invalid/duplicate protocol ${i}`),n.add(i),(r.firstReleasedAt===null?i!==e.current:!ys(r.firstReleasedAt))&&t.push(`${i}: invalid first release date`),r.noticePublishedAt!==null&&!ys(r.noticePublishedAt)&&t.push(`${i}: invalid notice date`),r.sunsetAt!==null&&!ys(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)(ud(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(Ss(i)&&r.sunsetAt!==null){let a=e.releases.filter(s=>s.firstReleasedAt!==null&&Ss(s.protocol)&&Number(s.protocol)>Number(i)).sort((s,c)=>Date.parse(s.firstReleasedAt)-Date.parse(c.firstReleasedAt))[0];a?Date.parse(r.sunsetAt)<$_(a.firstReleasedAt,ad.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)<ad.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 er=class extends Error{constructor(n,r,i=400){super(r);this.code=n;this.status=i}code;status};function xC(e,t=q_,n=Date.now()){let r=e.get(sd)??t.unversioned;if(!cd.test(r))throw new er("INVALID_PROTOCOL_VERSION","Invalid Indiana protocol version");let i=t.releases.find(a=>a.protocol===r);if(!i)throw new er("UNSUPPORTED_PROTOCOL_VERSION","Indiana protocol version is not supported");if(!Ss(r)&&r!==t.current)throw new er("UNSUPPORTED_PROTOCOL_VERSION","Only the current pre-1.0 Indiana protocol is supported");if(i.sunsetAt&&n>=Date.parse(i.sunsetAt))throw new er("PROTOCOL_RETIRED","Indiana protocol version has retired; follow the published migration notice",410);let o=e.get(B_);if(o!==null&&ud(o)!==r)throw new er("INVALID_PROTOCOL_VERSION","SDK version and protocol version do not match");return i}function IC(e,t=Date.now()){let n={[sd]: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 G_=$e.object({minAccountAgeDays:$e.number().int().min(0).max(3650),paymentStatus:$e.enum(["all","unpaid","paid"])}),K_=$e.object({percentOff:$e.number().int().min(1).max(100),redemptionWindowHours:$e.number().int().min(1).max(2160)}),H_=$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)}),z_=$e.object({name:$e.string().trim().min(1).max(80),audience:G_,offer:K_,popup:H_}),OC=z_.extend({id:$e.string().min(1),projectId:$e.string().min(1),environment:as,status:$e.enum(["draft","active","paused"]),updatedAt:$e.iso.datetime()}),PC=Fe.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 jn}from"zod";var ld=jn.strictObject({itemKey:jn.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:jn.uuid(),includedAmount:jn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:jn.number().int().min(0).max(1e4),terms:hs,pricing:ai.optional(),unitAmountMinor:jn.number().int().min(0).max(1e8),productId:jn.string().min(1).max(255).nullable(),priceId:jn.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{_s(e.includedAmount,e.terms.units,e.quantity),uo(e)}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as H}from"zod";var xs=H.object({id:H.uuid(),productVersionId:H.uuid(),connectionId:H.uuid(),currency:H.string().regex(/^[A-Z]{3}$/),productId:H.string().min(1).max(255),priceId:H.string().min(1).max(255),enabled:H.boolean()}).strict(),DC=H.object({productId:H.uuid(),name:H.string(),environment:H.enum(["sandbox","live"]),versions:H.array(H.object({id:H.uuid(),version:H.number().int().positive(),configuration:fi}).strict()),connections:H.array(H.object({id:H.uuid(),accountId:H.string()}).strict()),bindings:H.array(xs),seatBindings:H.array(xs.extend({key:H.string().regex(/^[a-z][a-z0-9_]{0,63}$/)}).strict()),featureBindings:H.array(xs.extend({internal_feature_id:H.uuid()}).strict()),limited:H.boolean()}).strict(),FC=H.discriminatedUnion("action",[H.strictObject({action:H.literal("bind_feature"),requestId:H.uuid(),productId:H.uuid(),productVersionId:H.uuid(),connectionId:H.uuid(),currency:H.string().regex(/^[A-Z]{3}$/),internal_feature_id:H.uuid(),priceId:H.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}),H.strictObject({action:H.literal("disable_feature"),productId:H.uuid(),bindingId:H.uuid()}),H.object({action:H.literal("bind_seat"),requestId:H.uuid(),productId:H.uuid(),productVersionId:H.uuid(),connectionId:H.uuid(),currency:H.string().regex(/^[A-Z]{3}$/),key:H.string().regex(/^[a-z][a-z0-9_]{0,63}$/),priceId:H.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),H.object({action:H.literal("disable_seat"),productId:H.uuid(),bindingId:H.uuid()}).strict(),H.object({action:H.literal("bind"),requestId:H.uuid(),productId:H.uuid(),productVersionId:H.uuid(),connectionId:H.uuid(),currency:H.string().regex(/^[A-Z]{3}$/),priceId:H.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),H.object({action:H.literal("disable"),productId:H.uuid(),bindingId:H.uuid()}).strict()]);import{z as he}from"zod";var dd=he.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),pd=he.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),hi=he.enum(["apple","google"]),W_=he.strictObject({id:he.uuid(),productVersionId:he.uuid(),priceId:he.uuid(),connectionId:hi,provider:hi,namespace:he.string().min(1).max(255),currency:W,productId:dd,basePlanId:pd.nullable(),enabled:he.boolean()}),BC=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:W,amount:he.number().nonnegative(),interval:he.string().nullable()})).max(50),recurring:he.boolean()})).max(100),connections:he.array(he.strictObject({id:hi,provider:hi,applicationId:he.string().min(1).max(255)})).max(2),bindings:he.array(W_).max(500),limited:he.boolean()}),qC=he.discriminatedUnion("action",[he.strictObject({action:he.literal("bind"),requestId:he.uuid(),productId:he.uuid(),productVersionId:he.uuid(),priceId:he.uuid(),connectionId:hi,storeProductId:dd,basePlanId:pd.nullable()}),he.strictObject({action:he.literal("disable"),productId:he.uuid(),bindingId:he.uuid()})]);import{z as G}from"zod";var tr=Y.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),bi=G.string().min(1).max(120),_o=G.enum(["cap","overflow"]),Ut=(e,t)=>{let[n,r=""]=e.split(".");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},_i=e=>{try{return e()}catch{return!1}},yi=G.discriminatedUnion("operation",[G.object({operation:G.literal("quote"),overageBehavior:_o.optional(),internal_feature_id:G.uuid(),entityId:G.uuid().optional(),quantity:tr,properties:Je}).strict(),G.object({operation:G.literal("consume"),overageBehavior:_o.optional(),occurredAt:G.iso.datetime({offset:!0}).optional(),internal_feature_id:G.uuid(),entityId:G.uuid().optional(),quantity:Y,properties:Je,idempotencyKey:bi}).strict(),G.object({operation:G.literal("reserve"),occurredAt:G.iso.datetime({offset:!0}).optional(),internal_feature_id:G.uuid(),entityId:G.uuid().optional(),quantity:tr,properties:Je,idempotencyKey:bi,expiresInSeconds:G.number().int().min(1).max(86400)}).strict(),G.object({operation:G.literal("confirm"),operationId:G.uuid(),quantity:tr,properties:Je.optional(),idempotencyKey:bi}).strict(),G.object({operation:G.literal("refund"),operationId:G.uuid(),quantity:tr,idempotencyKey:bi}).strict(),G.object({operation:G.literal("release"),operationId:G.uuid(),idempotencyKey:bi}).strict()]),Is=G.object({internal_credit_feature_id:G.uuid().nullable(),internal_metered_feature_id:G.uuid(),dimension:G.string().min(1).max(64),counterKey:G.string().min(1).max(240),cycleStart:G.iso.datetime({offset:!0}),unitCost:Y,units:tr,amount:ct,tier:G.number().int().min(1).max(12).nullable()}).strict(),nr=G.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function md(e,t){let n=e.reduce((r,i)=>r+Ut(i.units,12),0n)-Ut(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var fd=G.discriminatedUnion("funding",[G.strictObject({funding:G.literal("balance"),sourceId:G.uuid(),rolloverId:G.uuid().nullable(),units:nr.refine(e=>/[1-9]/.test(e)),amount:ct}),G.strictObject({funding:G.literal("unbilled"),units:nr.refine(e=>/[1-9]/.test(e))}),G.object({funding:G.literal("prepaid"),sourceId:G.uuid(),units:tr,amount:ct,pricing:G.array(Is).min(1).max(12)}).strict().refine(e=>_i(()=>e.pricing.reduce((t,n)=>t+Ut(n.units,6),0n)===Ut(e.units,6)&&e.pricing.reduce((t,n)=>t+Ut(n.amount,12),0n)===Ut(e.amount,12)&&e.pricing.every(t=>Ut(t.unitCost,6)*Ut(t.units,6)===Ut(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),G.object({funding:G.literal("postpaid"),invoiceLineId:G.uuid().nullable(),units:tr,authorizationId:G.uuid()}).strict()]),yo=G.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),gd=G.object({allowed:G.boolean(),internal_feature_id:G.uuid(),quantity:Y,requestedQuantity:Y.optional(),overageBehavior:_o.optional(),reason:yo.nullable(),allocations:G.array(fd).max(500)}).strict().refine(e=>_i(()=>e.allowed?e.reason===null&&md(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>_i(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&Ut(e.requestedQuantity,6)>=Ut(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Si=G.object({id:G.uuid(),internal_feature_id:G.uuid(),kind:G.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:G.uuid().nullable(),quantity:Y,requestedQuantity:Y.optional(),overageBehavior:_o.optional(),accepted:G.boolean(),reason:G.enum([...yo.options,"expired"]).nullable(),createdAt:G.iso.datetime({offset:!0}),reservationStatus:G.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:G.iso.datetime({offset:!0}).nullable(),allocations:G.array(fd).max(500)}).strict().refine(e=>_i(()=>e.accepted?e.reason===null&&md(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>_i(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&Ut(e.requestedQuantity,6)>=Ut(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as ye}from"zod";var rr=ye.iso.datetime({offset:!0}),hd=Y.refine(e=>/[1-9]/.test(e)),bd=ye.strictObject({interval:pi.exclude(["lifetime"]),count:mi}),Q_=ye.strictObject({action:ye.literal("create"),requestId:ye.uuid(),internal_feature_id:ye.uuid(),entityId:ye.uuid().nullable(),amount:hd.nullable(),expiresAt:rr.nullable(),reset:bd.nullable(),rollover:Xn.nullable(),nextResetAt:rr.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"),_d=ye.discriminatedUnion("action",[Q_,ye.strictObject({action:ye.literal("update"),requestId:ye.uuid(),grantId:ye.uuid(),revision:ye.number().int().nonnegative(),amount:hd.nullable(),expiresAt:rr.nullable(),rollover:Xn.nullable(),nextResetAt:rr.nullable()}),ye.strictObject({action:ye.enum(["add","subtract","set_remaining"]),requestId:ye.uuid(),grantId:ye.uuid(),revision:ye.number().int().nonnegative(),amount:Y}),ye.strictObject({action:ye.literal("revoke"),requestId:ye.uuid(),grantId:ye.uuid(),revision:ye.number().int().nonnegative()})]),vs=ye.strictObject({id:ye.uuid(),internal_feature_id:ye.uuid(),entityId:ye.uuid().nullable(),amount:Y.nullable(),reset:bd.nullable(),rollover:Xn.nullable(),nextResetAt:rr.nullable(),startsAt:rr,expiresAt:rr.nullable(),revision:ye.number().int().nonnegative(),revoked:ye.boolean(),available:ct,held:ct,spent:ct}),yd=ye.strictObject({customerId:ye.uuid(),after:ye.uuid().nullable(),limit:ye.number().int().min(1).max(100)}),Sd=ye.strictObject({rows:ye.array(vs).max(100),nextCursor:ye.uuid().nullable()});import{z}from"zod";var mn=z.iso.datetime({offset:!0}),xd=z.strictObject({invoiceId:z.uuid(),after:z.string().min(1).max(180).nullable(),limit:z.number().int().min(1).max(100)}),Z_=z.strictObject({kind:z.literal("product"),key:z.string(),productVersionId:z.uuid(),productName:z.string(),itemKey:z.string(),entityId:z.uuid().nullable(),quantity:z.number().int().positive(),subtotalMinor:z.string().regex(/^-?\d+$/),discountMinor:z.string().regex(/^\d+$/),taxMinor:z.string().regex(/^-?\d+$/).nullable(),totalMinor:z.string().regex(/^-?\d+$/),startsAt:mn.nullable(),endsAt:mn.nullable(),providerLineId:z.string().nullable(),providerItemId:z.string()}),Id=z.strictObject({invoice:li,items:z.array(z.discriminatedUnion("kind",[Z_,z.strictObject({kind:z.literal("invoice_credit"),key:z.string(),internal_feature_id:z.uuid(),internal_credit_feature_id:z.uuid(),name:z.string(),units:Y,reserved:Y,amountMinor:vr,grossAmountMinor:vr,creditsAppliedMinor:vr,properties:Je,cashPrice:kn,providerItemId:z.string().nullable(),creditProviderItemId:z.string().nullable()}),z.strictObject({kind:z.literal("usage"),key:z.string(),internal_feature_id:z.uuid(),name:z.string(),units:Y,reserved:Y,amountMinor:vr,cashPrice:kn})])).max(100),nextCursor:z.string().min(1).max(180).nullable()}),Y_=z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),As=z.strictObject({from:mn,to:mn,entityId:z.uuid().optional(),snapshotAt:mn.nullable(),after:z.strictObject({at:mn,id:z.uuid(),position:z.number().int().nonnegative()}).nullable(),limit:z.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"),vd=z.strictObject({customerId:z.uuid(),entityId:z.uuid().nullable(),from:mn,to:mn,snapshotAt:mn,totals:z.array(z.strictObject({internal_credit_feature_id:z.uuid(),name:z.string(),consumed:ct,refunded:ct,net:Y_})).max(1e3),rows:z.array(z.strictObject({operationId:z.uuid(),position:z.number().int().nonnegative(),kind:z.enum(["consume","confirm","refund"]),originalId:z.uuid().nullable(),occurredAt:mn,internal_feature_id:z.uuid(),entitlementName:z.string(),sourceId:z.uuid(),internal_credit_feature_id:z.uuid(),creditName:z.string(),units:nr,amount:ct,pricing:z.array(Is).max(12),properties:Je})).max(100),nextCursor:As.shape.after});import{z as Mt}from"zod";var rE=Mt.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"]),Ad=Mt.object({operationId:Mt.uuid(),windowId:Mt.uuid(),customerId:Mt.uuid(),entityId:Mt.uuid().nullable(),internal_feature_id:Mt.uuid(),entitlementKey:Xt,basis:Mt.enum(["usage","credits"]),interval:Mt.enum(["day","week","month","year"]),filter:Je,startsAt:Mt.iso.datetime({offset:!0}),endsAt:Mt.iso.datetime({offset:!0}),limit:Y.refine(e=>/[1-9]/.test(e)),used:ct,reserved:ct,threshold:Mt.number().positive().max(1)}).strict(),iE=Ad.omit({threshold:!0,limit:!0}).extend({alertThreshold:Y.refine(e=>/[1-9]/.test(e)),limit:Y.nullable()}),oE=Ad.omit({limit:!0}).extend({includedAllowance:Mt.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>/[1-9]/.test(e))});import{z as O}from"zod";import{z as rn}from"zod";var J_=rn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),X_=rn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),So=rn.strictObject({internal_feature_id:rn.uuid(),entityId:rn.uuid().nullable()}),wd=So.extend({quantity:Y,expectedRevision:rn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:rn.string().min(1).max(120),properties:Je.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),xi=So.extend({operationId:rn.uuid().nullable(),usage:Y,capacity:J_.nullable(),remaining:X_.nullable(),withinLimit:rn.boolean(),revision:rn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:rn.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[o,a=""]=(i?r.slice(1):r).split(".");return(i?-1n:1n)*(BigInt(o)*10n**12n+BigInt(a.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Ze=O.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),on=O.iso.datetime({offset:!0}),ey=O.enum(["access","metered","credit"]),Ii={internal_feature_id:O.uuid(),key:Xt,name:O.string().min(1).max(120),kind:ey},Od=O.object({customerId:O.uuid(),snapshotAt:on,memberships:O.array(O.object({id:O.uuid(),productId:O.string().min(1).max(255),productVersionId:O.uuid(),billingProductVersionId:O.uuid(),version:O.number().int().positive(),key:O.string().min(1).max(64),name:O.string().min(1).max(120),groupId:O.string().max(255).nullable(),membershipType:O.enum(["main","addon"]),status:O.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:O.boolean(),accessEnabled:O.boolean(),renewalChange:O.object({productVersionId:O.uuid(),name:O.string().min(1).max(120),version:O.number().int().positive(),effectiveAt:on,benefitsAppliedAt:on.nullable(),timing:O.enum(["immediate","renewal"]),changeKind:O.enum(["plan","seats","quantity"]),feature:O.strictObject({internal_feature_id:O.uuid(),name:O.string().min(1).max(80),fromQuantity:O.number().int().min(0).max(1e4),toQuantity:O.number().int().min(0).max(1e4)}).optional(),seat:O.object({key:O.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:O.number().int().min(0).max(1e4),toQuantity:O.number().int().min(0).max(1e4)}).strict().nullable(),status:O.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:O.object({phase:O.enum(["paid","trial"]),startsAt:on,endsAt:on.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:O.boolean(),balances:O.array(O.object({...Ii,usageType:O.enum(["consumable","non_consumable"]).nullable(),accessible:O.boolean(),unlimited:O.boolean(),available:Ze,held:Ze,debt:Ze,nextExpiresAt:on.nullable(),usage:xi.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:O.boolean()}).strict(),Pd=O.enum(["source","usage","transaction","invoice","debt","settlement"]),xo=O.object({at:on,id:O.uuid(),type:Pd}).strict(),Cd=O.object({type:Pd.nullable(),resourceKey:Xt.optional(),kind:O.enum(["purchase","refund"]).optional(),topup:O.boolean().optional(),from:O.iso.date().nullable(),to:O.iso.date().nullable(),after:xo.nullable(),limit:O.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Ar={id:O.uuid(),occurredAt:on},ty=O.discriminatedUnion("type",[O.strictObject({...Ar,type:O.literal("invoice"),status:O.string().min(1).max(80),paid:Ze,refunded:Ze,currency:W,externalId:O.string().nullable()}),O.object({...Ar,...Ii,type:O.literal("source"),reason:O.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Ze,unlimited:O.boolean(),status:O.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:on,expiresAt:on.nullable(),orderId:O.uuid().nullable(),parentSourceId:O.uuid().nullable()}).strict(),O.object({...Ar,type:O.literal("usage"),internal_feature_id:O.uuid(),name:O.string().min(1).max(120),kind:O.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:O.uuid().nullable(),quantity:Y,accepted:O.boolean(),reason:O.enum([...yo.options,"expired"]).nullable(),properties:Je,reservationStatus:O.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:on.nullable(),charges:O.array(O.discriminatedUnion("funding",[O.strictObject({funding:O.literal("balance"),sourceId:O.uuid(),rolloverId:O.uuid().nullable(),units:nr,amount:Ze}),O.strictObject({funding:O.literal("unbilled"),units:nr}),O.object({...Ii,funding:O.literal("prepaid"),amount:Ze}).strict(),O.object({funding:O.literal("postpaid"),invoiceId:O.uuid(),invoiceLineId:O.uuid(),authorizationId:O.uuid(),units:Y,currency:W}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),O.object({...Ar,type:O.literal("transaction"),purpose:O.enum(["product","invoice"]),productVersionId:O.uuid().nullable(),productName:O.string().min(1).max(120).nullable(),productVersion:O.number().int().positive().nullable(),invoiceId:O.uuid().nullable(),orderId:O.uuid(),originalId:O.uuid().nullable(),kind:O.enum(["purchase","refund"]),amountMinor:O.number().int().nonnegative().max(2e8).nullable(),currency:W.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),O.object({...Ar,...Ii,type:O.literal("debt"),sourceId:O.uuid(),transactionId:O.uuid(),amount:Ze}).strict(),O.object({...Ar,...Ii,type:O.literal("settlement"),sourceId:O.uuid(),debtId:O.uuid(),kind:O.enum(["payment","usage_refund","payment_return"]),amount:Ze}).strict()]),Ed=O.object({customerId:O.uuid(),rows:O.array(ty).max(50),nextCursor:xo.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as ee}from"zod";var Rd=ee.object({customerId:ee.uuid()}).strict(),kd=ee.discriminatedUnion("action",[ee.object({customerId:ee.uuid(),requestId:ee.uuid(),action:ee.literal("assign"),poolId:ee.uuid(),memberCustomerId:ee.uuid()}).strict(),ee.strictObject({customerId:ee.uuid(),requestId:ee.uuid(),action:ee.literal("assign_entity"),poolId:ee.uuid(),entityId:ee.uuid()}),ee.object({customerId:ee.uuid(),requestId:ee.uuid(),action:ee.literal("release"),poolId:ee.uuid(),slotId:ee.uuid()}).strict()]),vi=ee.number().int().nonnegative(),ws=ee.iso.datetime({offset:!0}),Os=ee.strictObject({internalId:ee.uuid(),id:ee.string(),name:ee.string().nullable(),version:ee.number().int().positive()}),Td=ee.enum(["active","past_due"]),Ps=ee.strictObject({customerId:ee.uuid(),licenses:ee.array(ee.strictObject({id:ee.uuid(),linkId:ee.uuid(),parent:ee.strictObject({customerProductId:ee.uuid(),status:Td,product:Os}),product:Os,planLicense:ee.strictObject({id:ee.uuid(),prepaidOnly:ee.boolean(),isCustom:ee.boolean()}).nullable(),granted:vi,included:vi,paidQuantity:vi,usage:vi,remaining:vi,createdAt:ws}).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:ee.array(ee.strictObject({id:ee.uuid(),linkId:ee.uuid(),status:Td,product:Os,entity:ee.strictObject({internalId:ee.uuid(),id:ee.string().nullable(),name:ee.string().nullable()}).nullable(),beneficiary:ee.strictObject({internalId:ee.uuid(),id:ee.string().nullable(),name:ee.string().nullable()}).nullable(),startedAt:ws.nullable(),endedAt:ws.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:ee.boolean()});import{z as Nn}from"zod";var ny=Nn.object({name:Nn.string().trim().min(1,"\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0").max(80),slug:Nn.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")}),jd=Nn.object({description:Nn.string().trim().max(240)}),yE=Nn.object({project:ny.extend({id:Nn.string().min(1)}),environments:Nn.object({sandbox:jd,live:jd})});import{z as Be}from"zod";import{z as Pe}from"zod";import{z as wr}from"zod";var Nd=wr.enum(["stripe","apple","google"]),Dd=wr.enum(["membership","credit_pack","lifetime"]),IE=wr.enum(["active","grace","suspended","inactive","revoked"]),vE=wr.strictObject({currency:wr.string().regex(/^[A-Z]{3}$/),micros:wr.string().regex(/^(0|[1-9][0-9]{0,29})$/)});import{z as Ne}from"zod";var ry=Ne.discriminatedUnion("action",[Ne.strictObject({action:Ne.literal("create"),couponId:Ne.uuid(),productBindingId:Ne.uuid(),storeOfferId:Ne.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Ne.enum(["introductory","promotional"])}),Ne.strictObject({action:Ne.literal("set_enabled"),id:Ne.uuid(),revision:Ne.number().int().nonnegative(),enabled:Ne.boolean()})]),iy=Ne.array(Ne.strictObject({id:Ne.uuid(),couponId:Ne.uuid(),productBindingId:Ne.uuid(),storeOfferId:Ne.string().min(1).max(255).nullable(),storeOfferType:Ne.enum(["introductory","promotional"]),enabled:Ne.boolean(),revision:Ne.number().int().nonnegative()})).max(500),Dn=Ne.strictObject({offerKind:Ne.enum(["none","introductory","promotional"]),offerId:Ne.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Ne.number().int().min(0).max(1e8),trialDays:Ne.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"})}),Fd=Ne.record(Ne.uuid(),Dn).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");function oy(e,t){if(e.nativeOffers!==void 0)return Fd.parse(e.nativeOffers)[t]}function ay(e,t,n,r){return Dn.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 Cs=Pe.object({type:Pe.literal("native_purchase"),receiptId:Pe.uuid(),orderId:Pe.uuid(),productVersionId:Pe.uuid(),provider:Pe.enum(["apple","google"]),productId:Pe.string().min(1).max(255),productKind:Dd,replacement:Pe.strictObject({sourceOrderId:Pe.uuid(),sourceProductId:Pe.string().min(1).max(255),policy:Pe.enum(["apple_store","google_full_price"]),sourceAccountTokens:Pe.array(Pe.uuid()).max(50)}).nullable(),appAccountToken:Pe.uuid().optional(),obfuscatedAccountId:Pe.string().min(1).max(64).optional(),obfuscatedProfileId:Pe.uuid().optional(),basePlanId:Pe.string().min(1).max(255).optional(),offerId:Pe.string().min(1).max(255).optional(),offerKind:Pe.enum(["none","introductory","promotional"]),currency:W,catalogAmountMinor:Pe.number().int().nonnegative().max(1e8),discountMinor:Pe.number().int().nonnegative().max(1e8),trialDays:Pe.number().int().min(1).max(730).nullable(),seatBundle:Pe.array(Pe.strictObject({key:Pe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Pe.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Pe.strictObject({offerId:Pe.string().min(1).max(255),keyId:Pe.string().min(1).max(255),nonce:Pe.uuid(),signature:Pe.string().min(1).max(1024),timestamp:Pe.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 m}from"zod";var Ld=m.strictObject({requestId:m.uuid(),entityId:m.uuid().optional(),billingSubscriptionId:m.uuid().optional(),newBillingSubscription:m.literal(!0).optional(),offerId:m.uuid().optional(),nativeOffer:Dn.optional(),plans:m.array(m.strictObject({productVersionId:m.uuid(),seatQuantities:m.record(pn,m.number().int().min(0).max(1e4)).optional(),featureQuantities:m.record(m.uuid(),m.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:m.enum(["stripe","apple","google"]),currency:W}).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"),or=m.strictObject({operationId:m.uuid()}),ut=m.number().int().min(0).max(1e8),sy=m.strictObject({lineId:m.uuid(),productVersionId:m.uuid(),productName:m.string().min(1).max(80),interval:m.enum(["free","week","month","year","one_time"]),intervalCount:m.number().int().min(1).max(156).optional(),baseAmountMinor:ut,seats:m.array(m.strictObject({key:pn,quantity:m.number().int().min(0).max(1e4),includedQuantity:m.number().int().min(0).max(1e4),maximumQuantity:m.number().int().min(0).max(1e4),unitAmountMinor:ut})).max(20),prepaid:m.array(ld).max(100).optional(),catalogAmountMinor:ut,trial:m.strictObject({days:m.number().int().min(1).max(730),cardRequired:m.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+uo(n),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Bd=m.string().regex(/^[A-Za-z0-9_-]{1,200}$/),cy=m.strictObject({id:Bd,name:m.string().min(1).max(40),percent_off:m.number().gt(0).max(100).optional(),amount_off:m.number().int().positive().optional(),currency:m.string().regex(/^[a-z]{3}$/).optional(),duration:m.enum(["once","repeating","forever"]),duration_in_months:m.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"),uy=m.strictObject({subscriptionId:m.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:m.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:m.array(m.strictObject({id:m.string(),price_id:m.string(),quantity:m.number().int().nonnegative(),discounts:m.array(m.strictObject({id:m.string(),coupon:m.string(),start:m.number(),end:m.number().nullable()})).optional()})).min(1).max(100),prorationDate:m.number().int().nonnegative(),amountMinor:m.number().int().positive(),periodStartMs:m.number(),periodEndMs:m.number()}),qd=m.strictObject({append:uy.optional(),provider:m.literal("stripe"),executor:m.enum(["indiana","merchant"]),accountId:m.string().regex(/^acct_[A-Za-z0-9]+$/),mode:m.enum(["payment","subscription"]),lineItems:m.array(m.strictObject({price:m.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:m.number().int().min(1).max(1e4),priceId:m.uuid(),productName:m.string().min(1).max(80),amountMinor:m.number().int().min(0).max(1e8),currency:m.string().regex(/^[a-z]{3}$/),interval:m.enum(["week","month","year","one_off"]),intervalCount:m.number().int().min(1).max(52),slot:m.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:m.strictObject({mode:m.enum(["graduated","volume"]),tiers:m.array(m.strictObject({upTo:m.number().int().min(1).max(1e6).nullable(),unitAmountMinor:m.number().int().min(0).max(1e8),flatAmountMinor:m.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:m.array(m.strictObject({coupon:Bd,terms:cy})).max(1),trialPeriodDays:m.number().int().min(1).max(730).nullable(),metadata:m.strictObject({grooveCheckoutId:m.uuid(),grooveCustomerId:m.uuid()}),expiresAt:m.iso.datetime({offset:!0})}),Ai=m.strictObject({operationId:m.uuid(),entityId:m.uuid().nullable(),billingSubscriptionId:m.uuid().nullable(),discount:m.strictObject({offerId:m.uuid(),couponId:m.uuid(),discount:Ir,duration:tn,amountMinor:ut,allocations:m.array(m.strictObject({productVersionId:m.uuid(),amountMinor:ut})).min(1).max(20),expiresAt:m.iso.datetime({offset:!0})}).nullable(),charge:m.strictObject({effectiveAt:m.iso.datetime({offset:!0}),periodEndsAt:m.iso.datetime({offset:!0}),debitMinor:ut,discountMinor:ut,taxMinor:ut,totalMinor:ut}).nullable(),expiresAt:m.iso.datetime({offset:!0}),provider:m.enum(["stripe","apple","google"]),nativeOffer:Dn.optional(),currency:W,lines:m.array(sy).min(1).max(20),catalogAmountMinor:ut,automaticTax:m.boolean(),execution:qd.nullable()}).refine(e=>e.provider==="stripe"?e.lines[0].trial?.cardRequired===!1?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)=>t.productVersionId===e.lines[n].productVersionId&&t.amountMinor<=e.lines[n].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"),Or=m.strictObject({operationId:m.uuid(),orderId:m.uuid(),append:m.boolean().optional(),status:m.enum(["pending","complete","cancelled","failed"]),executor:m.enum(["indiana","merchant"]),checkoutUrl:m.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:qd.nullable(),currency:W,catalogAmountMinor:ut,taxMinor:ut,totalMinor:m.number().int().min(0).max(2e8).nullable(),quoteFinalized:m.boolean(),nativePurchase:Cs.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"),vo=m.strictObject({enabled:m.literal(!0),featureIds:m.array(m.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Vd=m.strictObject({requestId:m.uuid(),membershipId:m.uuid(),carryOverBalances:vo.optional(),carryOverUsages:vo.optional(),membershipIds:m.array(m.uuid()).min(1).max(20).optional(),prorationBehavior:m.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:m.enum(["immediate","renewal","store"]),change:m.discriminatedUnion("type",[m.strictObject({type:m.literal("plan"),productVersionId:m.uuid()}),m.strictObject({type:m.literal("seats"),licenseKey:pn,quantity:m.number().int().min(0).max(1e4)}),m.strictObject({type:m.literal("quantity"),internal_feature_id:m.uuid(),quantity:m.number().int().min(0).max(1e4)}),m.strictObject({type:m.literal("cancel")}),m.strictObject({type:m.literal("uncancel")})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").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"),Io=m.string().regex(/^price_[A-Za-z0-9]+$/),Ud=m.strictObject({grooveUpdateId:m.uuid(),grooveCustomerId:m.uuid()}),Md=m.strictObject({price:Io.nullable(),priceId:m.uuid().optional(),quantity:m.number().int().min(0).max(1e4)}),$d=m.strictObject({provider:m.literal("stripe"),executor:m.enum(["indiana","merchant"]),accountId:m.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:m.string().regex(/^sub_[A-Za-z0-9]+$/),action:m.enum(["update","cancel","schedule","release"]),update:m.strictObject({items:m.array(Md).max(20),remove:m.array(Io).max(20),restoreItems:m.array(m.strictObject({price:Io,quantity:m.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:m.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:m.number().int().positive().optional(),paymentBehavior:m.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:m.boolean().optional(),clearCancelAt:m.literal(!0).optional(),metadata:Ud}).nullable(),cancel:m.strictObject({prorate:m.literal(!1),invoiceNow:m.literal(!1)}).nullable(),schedule:m.strictObject({currentItems:m.array(m.strictObject({price:Io,quantity:m.number().int().min(0).max(1e4)})).max(20),nextItems:m.array(Md).min(1).max(20),switchAt:m.number().int().positive(),interval:m.enum(["week","month","year"]),intervalCount:m.number().int().min(1).max(52),metadata:Ud}).nullable(),release:m.strictObject({schedule:m.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:m.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"),Es=m.strictObject({carryOverBalances:vo.optional(),carryOverUsages:vo.optional(),operationId:m.uuid(),membershipId:m.uuid(),productVersionId:m.uuid(),timing:m.enum(["immediate","renewal"]),effectiveAt:m.iso.datetime({offset:!0}),expiresAt:m.iso.datetime({offset:!0}),currency:W,creditMinor:ut,debitMinor:ut,discountMinor:ut,taxMinor:ut,totalMinor:ut,retainedProductVersionIds:m.array(m.uuid()).max(19),execution:$d}),ly=m.strictObject({operationId:m.uuid(),membershipId:m.uuid(),productVersionId:m.uuid(),status:m.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:m.enum(["immediate","renewal"]),effectiveAt:m.iso.datetime({offset:!0}),checkoutUrl:m.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:m.enum(["indiana","merchant"]),execution:$d.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),dy=m.strictObject({operationId:m.uuid(),membershipId:m.uuid(),productVersionId:m.uuid(),timing:m.literal("store"),effectiveAt:m.null(),expiresAt:m.iso.datetime({offset:!0}),currency:W,creditMinor:m.null(),debitMinor:m.null(),discountMinor:m.null(),taxMinor:m.null(),totalMinor:m.null(),retainedProductVersionIds:m.array(m.uuid()).max(19),store:m.strictObject({provider:m.enum(["apple","google"]),productId:m.string().min(1).max(255),catalogAmountMinor:ut,policy:m.enum(["apple_store","google_full_price"])})}),py=m.strictObject({operationId:m.uuid(),membershipId:m.uuid(),productVersionId:m.uuid(),status:m.enum(["prepared","pending","effective","cancelled","failed"]),timing:m.literal("store"),effectiveAt:m.iso.datetime({offset:!0}).nullable(),checkoutUrl:m.null(),nativePurchase:Cs.nullable()}),Gd=m.union([Es,dy]),Ts=m.union([ly,py]),wi=m.number().int().positive().max(2e8),ir=m.number().int().min(0).max(2e8),Kd=m.strictObject({requestId:m.uuid(),invoiceId:m.uuid(),mode:m.enum(["full","partial"]),amountMinor:wi.optional(),entitlementAction:m.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Hd=m.strictObject({provider:m.literal("stripe"),executor:m.enum(["indiana","merchant"]),accountId:m.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:m.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:wi,currency:m.string().regex(/^[a-z]{3}$/),metadata:m.strictObject({indianaRefundId:m.uuid()}),idempotencyKey:m.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:m.array(m.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),zd=m.strictObject({operationId:m.uuid(),invoiceId:m.uuid(),providerInvoiceId:m.string().regex(/^in_[A-Za-z0-9]+$/),currency:W,paidMinor:ir,refundedMinor:ir,pendingMinor:ir,amountMinor:wi,mode:m.enum(["full","partial"]),entitlementAction:m.enum(["retain","revoke"]),revokes:m.strictObject({customerProductIds:m.array(m.uuid()).max(100),subscriptionIds:m.array(m.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:Hd,expiresAt:m.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"),Ao=m.strictObject({operationId:m.uuid(),invoiceId:m.uuid(),providerInvoiceId:m.string().regex(/^in_[A-Za-z0-9]+$/),status:m.enum(["quoted","pending","succeeded","failed","expired"]),executor:m.enum(["indiana","merchant"]),currency:W,amountMinor:wi,mode:m.enum(["full","partial"]),entitlementAction:m.enum(["retain","revoke"]),refundId:m.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:Hd.nullable(),failureReason:m.string().min(1).max(200).nullable(),createdAt:m.iso.datetime({offset:!0}),completedAt:m.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"),BE=m.strictObject({invoiceId:m.uuid(),currency:W,paidMinor:ir,refundedMinor:ir,pendingMinor:ir,refundableMinor:ir,executor:m.enum(["indiana","merchant"]).nullable(),canRefund:m.boolean(),operations:m.array(Ao).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),qE=m.strictObject({requestId:m.uuid(),mode:m.enum(["full","partial"]),amountMinor:wi.optional(),entitlementAction:m.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 Wd=Be.strictObject({requestId:Be.uuid(),targets:Be.array(Be.strictObject({membershipId:Be.uuid(),action:Be.enum(["cancel","uncancel"]),timing:Be.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"),wo=Be.strictObject({batchId:Be.uuid()}),my=Be.strictObject({operationId:Be.uuid(),membershipIds:Be.array(Be.uuid()).min(1).max(20),provider:Be.enum(["stripe","apple","google"]),action:Be.enum(["cancel","uncancel"]),timing:Be.enum(["immediate","renewal"]),status:Be.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Es.nullable(),managementUrl:Be.url().nullable(),failureCode:Be.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Oi=Be.strictObject({batchId:Be.uuid(),ready:Be.boolean(),status:Be.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:Be.iso.datetime({offset:!0}),acceptedAt:Be.iso.datetime({offset:!0}).nullable(),groups:Be.array(my).min(1).max(100)});import{z as _e}from"zod";var fy=_e.string().trim().min(1).max(240),Rs={requestId:_e.uuid(),reason:fy},Oo=_e.discriminatedUnion("action",[_e.strictObject({...Rs,action:_e.literal("start"),productVersionId:_e.uuid(),entityId:_e.uuid().optional(),days:_e.number().int().min(1).max(730).optional()}),_e.strictObject({...Rs,action:_e.literal("extend"),membershipId:_e.uuid(),days:_e.number().int().min(1).max(730)}),_e.strictObject({...Rs,action:_e.literal("end"),membershipId:_e.uuid()})]),Qd=_e.strictObject({operationId:_e.uuid()}),Zd=_e.iso.datetime({offset:!0}),gy=_e.strictObject({provider:_e.literal("stripe"),executor:_e.enum(["indiana","merchant"]),accountId:_e.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:_e.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:_e.union([_e.literal("now"),Zd]),prorationBehavior:_e.literal("none")}),ks=_e.strictObject({operationId:_e.uuid(),action:_e.enum(["start","extend","end"]),status:_e.enum(["pending","effective"]),managedBy:_e.enum(["indiana","stripe"]),membershipIds:_e.array(_e.uuid()).min(1).max(20),endsAt:Zd.nullable(),execution:gy.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"),zE=_e.strictObject({groupId:_e.uuid(),productVersionId:_e.uuid(),enabled:_e.boolean()});import{z as Re}from"zod";var Yd=Re.strictObject({requestId:Re.uuid(),currency:W,makeDefault:Re.boolean()}),Jd=Re.strictObject({setupId:Re.uuid()}),hy=Re.strictObject({provider:Re.literal("stripe"),executor:Re.literal("merchant"),accountId:Re.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Re.literal("setup"),currency:Re.string().regex(/^[a-z]{3}$/),customer:Re.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Re.uuid(),metadata:Re.strictObject({grooveProjectId:Re.uuid(),grooveEnvironmentId:Re.uuid(),grooveCustomerId:Re.uuid(),groovePaymentSetupId:Re.uuid()}),setDefaultPaymentMethod:Re.boolean(),expiresAt:Re.iso.datetime({offset:!0})}),js=Re.strictObject({id:Re.uuid(),provider:Re.literal("stripe"),status:Re.enum(["prepared","complete","expired"]),currency:W,makeDefault:Re.boolean(),url:Re.url().nullable(),createdAt:Re.iso.datetime({offset:!0}),expiresAt:Re.iso.datetime({offset:!0}),completedAt:Re.iso.datetime({offset:!0}).nullable(),execution:hy.nullable()});import{z as lt}from"zod";var Xd=lt.union([lt.string(),lt.number(),lt.boolean(),lt.null()]),ep=lt.strictObject({customerId:lt.uuid()}),tp=lt.strictObject({customerId:lt.uuid(),provider:lt.literal("stripe"),checkedAt:lt.iso.datetime({offset:!0}),status:lt.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:lt.number().int().nonnegative(),differences:lt.array(lt.strictObject({subscriptionId:lt.string().startsWith("sub_"),itemId:lt.string().nullable(),field:lt.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Xd,actual:Xd})).max(1e4)});import{z as de}from"zod";var Po=de.iso.datetime({offset:!0}),Co=de.strictObject({createdAt:Po,id:de.uuid()}),Eo=de.strictObject({customerId:de.uuid().optional(),entityId:de.uuid().optional(),productId:de.string().min(1).max(256).optional(),provider:de.enum(["stripe","apple","google","free"]).optional(),status:de.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Co.optional(),limit:de.number().int().min(1).max(100).optional()}),Ns={id:de.uuid(),customerId:de.uuid(),entityId:de.uuid().nullable(),productId:de.string().min(1).max(256),productVersionId:de.uuid(),name:de.string().min(1).max(120),provider:de.enum(["stripe","apple","google","free"]),createdAt:Po},by=de.strictObject({...Ns,status:de.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:de.boolean(),billingSubscriptionId:de.uuid().nullable()}),_y=de.strictObject({...Ns,status:de.enum(["active","ended","refunded"]),orderId:de.uuid().nullable(),transactionId:de.uuid().nullable(),currency:W.nullable(),amountMinor:de.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),yy=de.strictObject({...Ns,status:de.enum(["blocked","resolved"]),conflict:de.strictObject({detectedAt:Po,blockingMembershipIds:de.array(de.uuid()).min(1).max(100),transactionId:de.uuid()}),resolvedAt:Po.nullable()}),np=Eo.extend({status:de.enum(["blocked","resolved"]).optional()}),rp=de.strictObject({customerId:de.uuid(),orderId:de.uuid()}),ip=de.strictObject({orderId:de.uuid(),status:de.enum(["blocked","resolved"])}),op=de.strictObject({items:de.array(by).max(100),nextCursor:Co.nullable()}),ap=de.strictObject({items:de.array(_y).max(100),nextCursor:Co.nullable()}),sp=de.strictObject({items:de.array(yy).max(100),nextCursor:Co.nullable()});import{z as Ue}from"zod";var cp=Ue.union([Ue.strictObject({intent:Ue.literal("read"),requestId:Ue.uuid(),purchaseIntentId:Ue.uuid()}),Ue.strictObject({requestId:Ue.uuid(),provider:Ue.literal("apple"),purchaseIntentId:Ue.uuid(),productId:Ue.string().min(1).max(255).optional(),signedTransaction:Ue.string().min(1).max(131072)}),Ue.strictObject({requestId:Ue.uuid(),provider:Ue.literal("google"),purchaseIntentId:Ue.uuid(),productId:Ue.string().min(1).max(255).optional(),purchaseToken:Ue.string().min(1).max(16384)})]),up=Ue.strictObject({requestId:Ue.uuid(),orderId:Ue.uuid(),purchaseIntentId:Ue.uuid(),status:Ue.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:W,refunded:Ue.boolean(),completion:Ue.strictObject({transactionIds:Ue.array(Ue.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Ue.boolean()}).nullable()});import{z as Ge}from"zod";import{z as Sy}from"zod";var Pr=Sy.object({provider:Nd,currency:W}).strict();var Fn=Ge.strictObject({internal_feature_id:Ge.uuid(),quantity:Y.refine(e=>/[1-9]/.test(e)),properties:Je,entityId:Ge.uuid().optional()}),lp=Ge.strictObject({requirement:Fn,commerce:Pr.optional(),paywallId:Ge.uuid().optional()}),xy=Ge.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Ds=Ge.strictObject({productId:Ge.string().min(1),productVersionId:Ge.string().min(1),name:Ge.string().min(1).max(120),action:Ge.enum(["purchase","upgrade","addon","topup"]),membershipId:Ge.string().min(1).nullable(),currency:W,amountMinor:Ge.string().regex(/^(0|[1-9]\d{0,8})$/),interval:Ge.enum(["free","week","month","year","one_time"]),intervalCount:Ge.number().int().min(1).max(156)}),ar=Ge.strictObject({internal_feature_id:Ge.string().min(1),name:Ge.string().min(1).max(120),kind:Ge.enum(["access","metered","credit"]),quantity:Y,allowed:Ge.boolean(),reason:xy.nullable(),preview:Ge.strictObject({scenario:Ge.enum(["feature_flag","usage_limit"]),candidates:Ge.array(Ds).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),fT=Ge.strictObject({paywallId:Ge.uuid(),requirement:Fn});import{z as k}from"zod";var Ms=k.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),Iy=k.record(k.string(),k.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),vy=3,Pi=20,Ay=vy*Pi,Fs=k.strictObject({type:k.literal("product"),productId:Ms}),dp={type:k.literal("group"),key:k.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:k.string().trim().min(1).max(80)},wy=k.discriminatedUnion("type",[Fs,k.strictObject({...dp,items:k.array(Fs).max(Pi)})]),Oy=k.discriminatedUnion("type",[Fs,k.strictObject({...dp,items:k.array(wy).max(Pi)})]),Py=k.array(Oy).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,l=s.type==="product"?s.productId:s.key;c.has(l)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(l),s.type==="group"&&o(s.items)}}o(e),(n.size>Pi||i>Ay)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Ci(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Ci(t))}function bT(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 To=k.strictObject({lookupKey:k.string().trim().min(1).max(200),displayName:k.string().trim().min(1).max(1500),items:Py,metadata:Iy}),Us=To.extend({paywallId:k.uuid().nullable()}),Cy=k.strictObject({product:k.record(k.string(),k.json()),prices:k.array(k.record(k.string(),k.json())),entitlements:k.array(k.record(k.string(),k.json())),freeTrials:k.array(k.record(k.string(),k.json())),licenses:k.array(k.record(k.string(),k.json()))}),pp=Us.extend({id:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),state:k.enum(["active","archived"]),isCurrent:k.boolean(),revision:k.number().int().nonnegative(),publishedVersionId:k.uuid().nullable(),createdAt:k.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"})}),mp=k.strictObject({id:k.uuid(),offeringId:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),version:k.number().int().positive(),document:To,productEvidence:k.record(Ms,Cy),createdAt:k.number().nonnegative().nullable()}).superRefine((e,t)=>{let n=Ci(e.document);(!n.length||Ry(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"})}),Ey=k.strictObject({rows:k.array(pp).max(200),versions:k.array(mp).max(500)}),_T=k.discriminatedUnion("action",[k.strictObject({action:k.literal("create"),document:Us}),k.strictObject({action:k.literal("save"),id:k.uuid(),revision:k.number().int().nonnegative(),document:Us}),k.strictObject({action:k.enum(["publish","set_current","archive","restore"]),id:k.uuid(),revision:k.number().int().nonnegative()})]),yT=k.strictObject({record:pp,version:mp.nullable()}),fp=k.discriminatedUnion("type",[k.strictObject({type:k.literal("current")}),k.strictObject({type:k.literal("id"),id:k.uuid()}),k.strictObject({type:k.literal("lookup_key"),lookupKey:k.string().min(1).max(200)}),k.strictObject({type:k.literal("version"),versionId:k.uuid()})]),Ty=k.strictObject({internalId:Ms,id:k.string(),name:k.string().nullable(),version:k.number().int().positive(),archived:k.boolean()}),ST=Ey.extend({products:k.array(Ty).max(500),paywalls:k.array(k.strictObject({id:k.uuid(),name:k.string()})).max(200)});function Ry(e){let t=[];Ci(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 Ro}from"zod";var Cr=Ro.strictObject({id:Ro.uuid(),offeringId:Ro.uuid(),version:Ro.number().int().positive(),document:To});import{z as Rt}from"zod";import{z as ne}from"zod";import{z as Er}from"zod";import{z as vn}from"zod";var gp=vn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ko=vn.strictObject({tiers:vn.array(vn.strictObject({id:gp,name:vn.string().trim().min(1).max(80)})).min(1).max(8),assignments:vn.array(vn.strictObject({productVersionId:vn.string().min(1).max(200),tierId:gp,period:vn.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function jo(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var hp=Er.strictObject({items:Er.array(Er.strictObject({productVersionId:Er.string().min(1).max(200),label:Er.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Er.string().min(1).max(200).nullable(),grouping:ko.optional()});function ET(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}function bp(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Tr(e){let t={};function n(r){if(bp(r)){let i=t[r.interaction.pickerId]??={ids:[],defaultId:null};for(let a of r.children){let s=a.type==="stack"?a.bind?.plan:void 0;s&&!i.ids.includes(s)&&i.ids.push(s)}let o=r.children[r.interaction.defaultIndex];!i.defaultId&&o?.type==="stack"&&(i.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}function _p(e,t,n){let r={};function i(c){if(c.hidden)return;if(c.type==="plan_picker"){let d=n.pickers[c.id];r[c.id]={ids:d?.options??[],defaults:d?.selected?[d.selected]:[],remembered:[]};return}if(c.type!=="stack")return;let l=c.children.filter(d=>!d.hidden),u=c.interaction;if(bp(c)){let d=r[c.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},p=n.pickers[c.interaction.pickerId]?.options??[];for(let f of l){let h=f.type==="stack"?f.bind?.plan:void 0;h&&p.includes(h)&&!d.ids.includes(h)&&d.ids.push(h),h&&f.id===t[c.id]&&d.remembered.push(h)}let g=c.children[c.interaction.defaultIndex];g?.type==="stack"&&!g.hidden&&g.bind?.plan&&d.defaults.push(g.bind.plan)}if(u?.type==="tabs"){let d=l.find(p=>p.id===t[c.id])??c.children[u.defaultIndex];d&&i(d)}else if(u?.type==="toggle"){let d=typeof t[c.id]=="boolean"?t[c.id]:u.defaultEnabled,p=c.children[d?0:1];p&&i(p)}else l.forEach(i)}let o=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,a=e.pages.find(c=>c.id===o);a&&i(a.root);let s={};for(let[c,l]of Object.entries(r)){let u=t[c],d=l.remembered[0]??(l.ids.includes(n.pickers[c]?.selected??"")?n.pickers[c]?.selected:l.defaults[0]);s[c]=typeof u=="string"?l.ids.includes(u)?u:"":d&&l.ids.includes(d)?d:""}for(let c of Object.keys(Tr(e)))s[c]??="";return s}import{z as oe}from"zod";var ky=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],Ls=oe.object({plan:oe.string().min(1).max(200).optional(),coupon:oe.uuid().optional(),promotionCode:oe.uuid().optional(),picker:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),yp=oe.object({text:oe.string().optional(),label:oe.string().optional(),alt:oe.string().optional(),html:oe.string().max(32768).optional(),price:oe.object({current:oe.string(),original:oe.string().nullable(),period:oe.string()}).optional(),code:oe.string().optional(),countdownAt:oe.iso.datetime().optional(),planId:oe.string().min(1).max(200).optional(),planVersionId:oe.string().min(1).max(200).optional(),currency:W.optional(),couponId:oe.uuid().optional(),offerId:oe.uuid().optional(),unavailable:oe.boolean().optional(),unavailableReason:oe.string().optional(),missing:oe.array(oe.string()).optional()}).strict(),No=oe.object({paywall:ar.optional(),nodes:oe.record(oe.string(),oe.object({base:yp,picker:oe.string().optional(),byPlan:oe.record(oe.string(),yp).optional()}).strict()),plans:oe.record(oe.string(),oe.object({id:oe.string().min(1).max(200),versionId:oe.string().min(1).max(200),available:oe.boolean(),name:oe.string(),price:oe.string(),period:oe.string(),currency:W.optional()}).strict()),pickers:oe.record(oe.string(),oe.object({options:oe.array(oe.string().min(1).max(200)).max(20),selected:oe.string().min(1).max(200).nullable()}).strict()),diagnostics:oe.array(oe.object({nodeId:oe.string(),message:oe.string()}).strict())}).strict();function Do(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].map(t=>t[1].trim())}function Fo(e){let t=Do(e).filter(r=>!ky.includes(r)),n=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(n.includes("{{")||n.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function DT(e,t,n,r=!1){let i=Do(e).filter(o=>!/^(input|params)\.[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(o)&&t[o]===void 0);return i.length&&!r?{value:n,missing:i}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(o,a)=>t[a.trim()]??o),missing:i}}function FT(e,t,n={}){let r=e?.nodes[t];if(!r)return;let i=r.picker?n[r.picker]??e?.pickers[r.picker]?.selected:void 0;return typeof i=="string"?r.byPlan?.[i]??r.base:r.base}import{z as _}from"zod";import{z as Z}from"zod";var jy=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Sp=Z.enum(jy),xp=Z.object({source:Sp,layout:Z.enum(["full","compact"]),resourceKey:Xt.optional(),pageSize:Z.number().int().min(1).max(50),showSources:Z.boolean(),allowPurchase:Z.boolean(),outputs:Z.object({billing_adjustment:Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),ot=Z.string().max(2e3),Ip=Z.object({id:Z.string().max(100),label:ot,detail:Z.array(ot).max(12),value:ot.optional(),status:ot.optional(),facts:Z.array(Z.object({label:ot,value:ot}).strict()).max(1e3),purchaseId:Z.uuid().optional(),invoiceUrl:Z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:Z.array(Z.strictObject({action:Z.literal("invoice_open"),label:ot})).max(1).optional(),membershipActions:Z.array(Z.object({value:Z.string().max(100),label:ot}).strict()).max(3).optional()}).strict(),Ny=Z.object({key:Xt,name:ot,spendable:ot,reserved:ot,available:ot,expiry:ot.nullable(),sources:Z.array(Ip).max(50),sourceCount:Z.number().int().nonnegative(),sourcePage:Z.number().int().positive(),hasNextSources:Z.boolean(),hasPreviousSources:Z.boolean()}).strict(),Dy=Z.object({source:Sp,status:Z.enum(["idle","loading","ready","error"]),stale:Z.boolean(),preview:Z.boolean(),errorCode:Z.string().max(80).optional(),errorMessage:ot.optional(),resources:Z.array(Ny).max(500),rows:Z.array(Ip).max(50),hasNext:Z.boolean(),hasPrevious:Z.boolean(),page:Z.number().int().positive(),filter:Z.string().max(40),updatedAt:Z.iso.datetime().optional(),buyingId:Z.uuid().optional(),membershipBusy:Z.boolean().optional(),billingBusy:Z.boolean().optional(),membershipReview:Z.object({title:ot,note:ot,facts:Z.array(Z.object({label:ot,value:ot}).strict()).max(100)}).strict().optional(),membershipResult:ot.optional()}).strict(),vp=Z.object({nodes:Z.record(Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Dy)}).strict(),BT=Z.object({nodeId:Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:Z.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:Z.string().max(100).optional()}).strict();function Ap(e){return{source:e,status:"idle",stale:!0,preview:!1,resources:[],rows:[],hasNext:!1,hasPrevious:!1,page:1,filter:"all"}}function Bs(e){let t=Fo(e).map(n=>`\u672A\u77E5\u53D8\u91CF\uFF1A${n}`);for(let n=0;n<e.length;n++){if(e[n]!=="<"||!/[A-Za-z!/?{]/.test(e[n+1]??""))continue;let r=n;if(e.startsWith("<!--",n)){let i=e.indexOf("-->",n+4);n=i<0?e.length:i+2}else{let i="";for(n++;n<e.length;n++){let o=e[n];if(i)o===i&&(i="");else if(o==='"'||o==="'")i=o;else if(o===">")break}}/\{\{|\}\}/.test(e.slice(r,n+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}function wp(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function $T(e,t,n,r=!1){let i=Bs(e);if(i.length)throw new Error(i[0]);let o=[...new Set(Do(e).filter(a=>t[a]===void 0))];return o.length&&!r?{value:wp(n),missing:o}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(a,s)=>t[s.trim()]===void 0?a:wp(t[s.trim()])),missing:o}}var Fy=4,an={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Ti=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Me=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Uy=_.enum(["none","xs","sm","md","lg","xl"]),My=_.enum(["none","sm","md","lg","full"]),qs=_.string().regex(/^#[0-9a-fA-F]{6}$/),Cp=_.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),Vs=_.union([Cp,_.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),_.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),_.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Op=_.object({primary:qs,background:qs,text:qs,radius:My,font:_.enum(["system","serif","rounded","mono"])}).strict(),Ri=_.union([_.enum(["primary","text","muted","background","surface"]),_.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Ce=(e,t)=>_.number().int().min(e).max(t),Pp=_.union([_.enum(["fit","fill"]),Ce(1,1200)]),Ly=_.object({top:Ce(0,200),right:Ce(0,200),bottom:Ce(0,200),left:Ce(0,200)}).strict(),By=_.object({top:Ce(-100,200),right:Ce(-100,200),bottom:Ce(-100,200),left:Ce(-100,200)}).strict(),Ep=_.object({x:Ce(0,100),y:Ce(0,100)}).strict(),qy=_.discriminatedUnion("type",[_.object({type:_.literal("color"),color:Ri}).strict(),_.object({type:_.literal("linear"),angle:Ce(0,360),stops:_.array(_.object({color:Ri,at:Ce(0,100)}).strict()).min(2).max(4)}).strict(),_.object({type:_.literal("image"),src:Vs,fit:_.enum(["cover","contain"]),position:Ep.optional()}).strict()]),Vy=_.discriminatedUnion("type",[_.object({type:_.literal("rect"),radius:_.union([Ce(0,200),_.object({topLeft:Ce(0,200),topRight:Ce(0,200),bottomRight:Ce(0,200),bottomLeft:Ce(0,200)}).strict()])}).strict(),_.object({type:_.literal("pill")}).strict()]),$y=_.object({width:Ce(0,12),color:Ri,style:_.enum(["solid","dashed"])}).strict(),Gy=_.object({x:Ce(-40,40),y:Ce(-40,40),blur:Ce(0,80),spread:Ce(-20,40),color:Ri}).strict(),Ky=_.object({font:_.enum(["system","serif","rounded","mono"]),size:Ce(8,96),weight:_.number().int().min(100).max(900).multipleOf(100),lineHeight:_.number().min(.8).max(3),letterSpacing:_.number().min(-5).max(20),color:Ri,align:_.enum(["start","center","end"]),italic:_.boolean(),decoration:_.enum(["none","underline","line-through"]),transform:_.enum(["none","uppercase"])}).strict().partial(),sr=_.object({width:Pp,height:Pp,padding:Ly,margin:By,gap:Ce(0,120),grow:_.union([_.boolean(),_.number().min(0).max(12)]),background:qy,opacity:_.number().min(0).max(1),clipContent:_.boolean(),shape:Vy,border:$y,shadow:Gy,text:Ky}).strict().partial(),Kt={id:Ti,name:_.string().trim().min(1).max(60).optional(),hidden:_.boolean().optional(),style:sr.optional(),fallback:Me.optional()},Hy=_.object({...Kt,type:_.literal("text"),productField:_.enum(["name","price","trial","period"]).optional(),feature:_.object({id:_.uuid(),field:_.enum(["name","allowance"])}).strict().optional(),text:Me,variant:_.enum(["title","heading","body","caption"])}).strict(),zy=_.object({...Kt,type:_.literal("image"),src:Vs,localizedSrc:_.record(en,Vs).optional(),alt:Me,aspect:_.enum(["auto","1:1","4:3","16:9","3:1"]),fit:_.enum(["cover","contain"]),position:Ep.optional()}).strict(),Wy=_.object({...Kt,type:_.literal("button"),label:Me,variant:_.enum(["primary","secondary","link"]),action:Me,purpose:_.enum(["purchase","navigation","close"]).optional(),bind:Ls.optional()}).strict(),Qy=_.object({...Kt,type:_.literal("divider")}).strict(),Zy=_.object({...Kt,type:_.literal("customer_data"),title:Me,data:xp}).strict(),Yy=_.object({...Kt,type:_.literal("spacer"),size:Uy}).strict(),Jy=_.object({...Kt,type:_.literal("custom_html"),html:_.record(en,_.string().max(an.customHtml)),css:_.string().max(an.customCss)}).strict(),Xy=_.object({...Kt,type:_.literal("price"),fallback:Me,parts:_.object({current:sr.optional(),original:sr.optional(),period:sr.optional()}).strict().optional()}).strict(),eS=_.object({...Kt,type:_.literal("coupon_code"),label:Me,fallback:Me}).strict(),tS=_.object({...Kt,type:_.literal("countdown"),source:_.enum(["offer.ends_at","offer.expires_at","fixed"]),at:_.iso.datetime().optional(),granularity:_.enum(["day","hour","minute","second"]),expired:Me,fallback:Me}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),nS=_.object({...Kt,type:_.literal("plan_picker"),label:Me,fallback:Me,planIds:_.array(_.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:_.string().min(1).max(200).optional(),grouping:ko.safeExtend({monthLabel:Me,yearLabel:Me,unavailableLabel:Me}).optional(),states:_.object({selected:sr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!jo(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),rS=_.discriminatedUnion("type",[_.object({type:_.literal("input"),label:Me,keyboard:_.enum(["text","email","tel","url"]),maxLength:Ce(1,500)}).strict(),_.object({type:_.literal("multiselect"),label:Me,min:Ce(0,50),max:Ce(1,50)}).strict(),_.object({type:_.literal("select"),label:Me,defaultIndex:Ce(0,49),purpose:_.enum(["option","product","tier"]).optional(),pickerId:Ti.optional(),selectedStyle:sr.optional()}).strict(),_.object({type:_.literal("tabs"),label:Me,defaultIndex:Ce(0,49),purpose:_.literal("tier").optional()}).strict(),_.object({type:_.literal("toggle"),label:Me,defaultEnabled:_.boolean()}).strict(),_.object({type:_.literal("carousel"),label:Me}).strict()]),Tp=_.lazy(()=>_.object({...Kt,type:_.literal("stack"),direction:_.enum(["vertical","horizontal","overlay"]),align:_.enum(["start","center","end","stretch"]),justify:_.enum(["start","center","end","between"]),children:_.array(iS).max(an.children),productSlot:_.object({index:Ce(0,19),period:_.enum(["month","year"]).optional(),requireBinding:_.boolean().optional()}).strict().optional(),interaction:rS.optional(),states:_.object({selected:sr.optional()}).strict().optional(),purpose:_.literal("benefits").optional(),purchaseAction:Me.optional(),buttonVariant:_.enum(["primary","secondary","link"]).optional(),bind:Ls.optional()}).strict()),iS=_.lazy(()=>_.union([Tp,Hy,zy,Wy,Qy,Yy,Jy,Xy,eS,tS,nS,Zy])),oS=_.union([_.string().max(500),_.number().finite(),_.boolean(),_.null()]),Ei={id:Me,event:Me,properties:_.record(Me,oS).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},aS=_.discriminatedUnion("type",[_.object({...Ei,type:_.literal("navigate"),close:_.literal(!1),pageId:Ti}).strict(),_.object({...Ei,type:_.literal("event"),close:_.boolean()}).strict(),_.object({...Ei,type:_.literal("close"),close:_.literal(!0)}).strict(),_.object({...Ei,type:_.literal("open_url"),close:_.boolean(),url:Cp}).strict(),_.object({...Ei,type:_.literal("claim_offer"),close:_.boolean(),couponId:_.uuid()}).strict()]),sS=_.object({defaultLocale:en,locales:_.record(en,_.record(Me,_.string().max(an.stringLength)))}).strict(),$s=_.enum(["popup","paywall","onboarding","page"]),JT={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages"},cS=_.discriminatedUnion("type",[_.object({type:_.literal("modal"),size:_.enum(["sm","md","lg"])}).strict(),_.object({type:_.literal("sheet"),size:_.enum(["sm","md","lg"])}).strict(),_.object({type:_.literal("fullscreen")}).strict()]),XT={sm:360,md:420,lg:560},uS=_.object({kind:_.literal("screen"),schemaVersion:_.literal(Fy),name:_.string().trim().min(1).max(80),surface:$s,initialPageId:Ti.optional(),presentation:cS,theme:Op,pages:_.array(_.object({id:Ti,name:_.string().trim().min(1).max(60),root:Tp,theme:Op.optional(),editorPosition:_.object({x:_.number().finite().min(-1e5).max(1e5),y:_.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(an.pages),strings:sS,actions:_.array(aS).max(an.actions)}).strict();function Pt(e,t){for(let n of e.pages)fn(n.root,t)}function eR(e,t){return{...e,pages:e.pages.map((n,r)=>r===0?{...n,root:t}:n)}}var Tt=uS.superRefine((e,t)=>{let n=an;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(u=>u.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let u of e.actions)u.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(d=>d.id===u.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=u=>t.addIssue({code:"custom",message:u}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>an.locales&&r(`\u6700\u591A ${an.locales} \u79CD\u8BED\u8A00`);let o=new Set;for(let u of e.actions)o.has(u.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${u.id}`),o.add(u.id);let a=new Set;for(let u of e.pages)["next","back"].includes(u.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${u.id}`),a.has(u.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${u.id}`),a.add(u.id);let s=new Set,c=0,l=!1;Pt(e,(u,d)=>{if(c++,d>an.depth&&(l=!0),s.has(u.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${u.id}`),s.add(u.id),u.type==="button"&&!o.has(u.action)&&r(`\u6309\u94AE ${u.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${u.action}`),u.type==="custom_html")for(let p of Object.keys(u.html))i.includes(p)||r(`\u81EA\u5B9A\u4E49 HTML ${u.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${p}`);if(u.type==="image")for(let p of Object.keys(u.localizedSrc??{}))i.includes(p)||r(`\u56FE\u7247 ${u.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${p}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),l&&r(`\u5C42\u7EA7\u6700\u591A ${an.depth} \u5C42`)});function fn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)fn(i,t,n+1,e)}function Gs(e){let t=[],n=new Set;return Pt(e,r=>{let i=(o,a,s)=>{n.has(o)||(n.add(o),t.push({key:o,nodeId:r.id,nodeType:r.type,field:a,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function lS(e,t,n){if(t.field==="html"){let r;return Pt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=ki(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function Rr(e){let t=Gs(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(o=>!lS(e,o,r)?.trim()).map(o=>o.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function tR(e){let t=[],n=e.actions.some(c=>typeof c.properties.templateKey=="string"&&c.properties.templateKey.startsWith("popup-coupon-"));n&&(!e.actions.some(c=>c.type==="claim_offer")||e.actions.some(c=>c.type==="event"&&typeof c.properties.templateKey=="string"&&c.properties.templateKey.startsWith("popup-coupon-")))&&t.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u8BF7\u5C06\u9886\u53D6\u6309\u94AE\u8BBE\u4E3A\u300C\u9886\u53D6\u4F18\u60E0\u300D\u5E76\u9009\u62E9\u751F\u6548\u4E2D\u7684\u5238");function r(c,l){let u=c.type==="stack"||c.type==="button"?c.bind?.coupon??l:l;if(n&&c.type==="text"&&Object.values(e.strings.locales).some(d=>d[c.text]?.includes("{{offer."))&&!u&&t.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u52A8\u6001\u6587\u6848\u9700\u8981\u7EE7\u627F\u4F18\u60E0\u5238\u7ED1\u5B9A"),c.type==="button"){let d=e.actions.find(p=>p.id===c.action);d?.type==="claim_offer"&&u&&u!==d.couponId&&t.push(`\u9886\u53D6\u6309\u94AE ${c.id} \u4E0E\u5C55\u793A\u5185\u5BB9\u7ED1\u5B9A\u4E86\u4E0D\u540C\u7684\u4F18\u60E0\u5238`)}c.type==="stack"&&c.children.forEach(d=>r(d,u))}e.pages.forEach(c=>r(c.root));let i=[],o=Tt.safeParse(e);o.success||t.push(...o.error.issues.map(c=>c.message));for(let c of Object.values(e.strings.locales))for(let l of Object.values(c))for(let u of Fo(l))t.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${u}`);Pt(e,c=>{if(c.type==="customer_data"&&Object.values(e.strings.locales).some(u=>/\{\{|\}\}/.test(u[c.title]??""))&&t.push(`\u6570\u636E\u7EC4\u4EF6 ${c.id} \u7684\u6807\u9898\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),(c.type==="text"?[c.text]:c.type==="button"?[c.label]:[]).some(u=>Object.values(e.strings.locales).some(d=>d[u]?.includes("{{")))&&!c.fallback&&t.push(`\u7EC4\u4EF6 ${c.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),c.fallback&&Object.values(e.strings.locales).some(u=>u[c.fallback]?.includes("{{"))&&t.push(`\u7EC4\u4EF6 ${c.id} \u7684\u5907\u7528\u6587\u6848\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),c.type==="custom_html"){for(let u of Object.values(c.html))t.push(...Bs(u).map(d=>`HTML ${c.id}\uFF1A${d}`));Object.values(c.html).some(u=>u.includes("{{"))&&!c.fallback&&t.push(`HTML ${c.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),/\{\{/.test(c.css)&&t.push(`HTML ${c.id} \u7684 CSS \u4E0D\u652F\u6301\u53D8\u91CF`)}(c.type==="stack"||c.type==="button")&&c.bind?.picker&&ki(e,c.bind.picker)?.type!=="plan_picker"&&!Object.hasOwn(Tr(e),c.bind.picker)&&t.push(`\u5BB9\u5668 ${c.id} \u5F15\u7528\u7684\u5957\u9910\u9009\u62E9\u4E0D\u5B58\u5728`)});for(let c of Object.keys(Tr(e)))ki(e,c)||t.push(`Product selection scope ${c} must reference a UI node`);let a=Rr(e);for(let c of a)c.complete||(c.locale===e.strings.defaultLocale?t.push(`\u9ED8\u8BA4\u8BED\u8A00 ${c.locale} \u8FD8\u6709 ${c.missing.length} \u5904\u5185\u5BB9\u6CA1\u586B`):t.push(`${c.locale} \u8FD8\u6709 ${c.missing.length} \u5904\u6CA1\u7FFB\u8BD1\uFF0C\u8BF7\u8865\u9F50\u6216\u5220\u9664\u8FD9\u79CD\u8BED\u8A00\u540E\u53D1\u5E03`));Gs(e).length===0&&!e.pages.some(c=>dS(c.root))&&t.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let s=new Set;Pt(e,c=>{c.type==="button"&&s.add(c.action)});for(let c of e.actions)!s.has(c.id)&&!e.pages.some(l=>pS(l.root,c.id))&&i.push(`\u52A8\u4F5C ${c.id} \u6CA1\u6709\u88AB\u4EFB\u4F55\u6309\u94AE\u4F7F\u7528`);return{errors:t,warnings:i}}function dS(e){let t=!1;return fn(e,n=>{if(n.hidden)return!1;n.type==="image"&&(t=!0)}),t}function pS(e,t){let n=!1;return fn(e,r=>{if(r.type==="custom_html")for(let i of Object.values(r.html))i.includes(`data-grow-action="${t}"`)&&(n=!0)}),n}function mS(e){return Rr(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Ks(e,t){return mo(t,mS(e),e.strings.defaultLocale)}function nR(e,t){let n=e.strings.locales[t]??{},r=e.strings.locales[e.strings.defaultLocale]??{},i={};for(let a of Gs(e)){if(a.field==="html"||a.field==="src")continue;let s=n[a.key]?.trim()?n[a.key]:r[a.key];s!==void 0&&(i[a.key]=s)}let o=a=>{if(a.type==="stack")return{...a,children:a.children.map(o)};if(a.type==="custom_html"){let s=a.html[t]?.trim()?a.html[t]:a.html[e.strings.defaultLocale];return{...a,html:s===void 0?{}:{[t]:s}}}if(a.type==="image"){let{localizedSrc:s,...c}=a;return{...c,src:s?.[t]??s?.[e.strings.defaultLocale]??a.src}}return a};return{...e,pages:e.pages.map(a=>({...a,root:o(a.root)})),strings:{defaultLocale:t,locales:{[t]:i}}}}function fS(e,t){let n=null;return fn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function ki(e,t){for(let n of e.pages){let r=fS(n.root,t);if(r)return r}return null}function rR(e){let t=Yn(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function iR(e,t,n){let r={};if(!t||typeof t!="object"||Array.isArray(t))return r;let i=t;if(Pt(e,o=>{if(o.type==="plan_picker"){let s=i[o.id];typeof s=="string"&&(r[o.id]=n?.pickers[o.id]?.options.includes(s)?s:"");return}if(o.type!=="stack"||!o.interaction)return;let a=Object.hasOwn(i,o.id)?i[o.id]:void 0;["select","tabs"].includes(o.interaction.type)&&typeof a=="string"&&o.children.some(s=>s.id===a)&&(r[o.id]=a),o.interaction.type==="toggle"&&typeof a=="boolean"&&(r[o.id]=a)}),e.surface==="paywall"&&typeof i.__page=="string"&&e.pages.some(o=>o.id===i.__page)&&(r.__page=i.__page),n){let o={...r};for(let[a,s]of Object.entries(i))(typeof s=="string"||typeof s=="boolean")&&(o[a]=s);Object.assign(r,_p(e,o,n))}return r}import{z as rt}from"zod";var gS=rt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Rp=rt.discriminatedUnion("type",[rt.object({type:rt.literal("fixed"),productVersionId:rt.string().min(1).max(200)}).strict(),rt.object({type:rt.literal("picker"),pickerId:gS,allowedProductVersionIds:rt.array(rt.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")]),An=rt.discriminatedUnion("type",[rt.object({type:rt.literal("modal"),size:rt.enum(["sm","md","lg"])}).strict(),rt.object({type:rt.literal("sheet"),size:rt.enum(["sm","md","lg"])}).strict(),rt.object({type:rt.literal("fullscreen")}).strict(),rt.object({type:rt.literal("inline")}).strict()]);var hS=ne.discriminatedUnion("type",[ne.strictObject({type:ne.literal("event"),event:ne.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ne.strictObject({type:ne.literal("open_url"),url:ne.url().refine(e=>new URL(e).protocol==="https:")})]),bS=Tt,_S=ne.discriminatedUnion("type",[ne.object({type:ne.literal("checkout"),product:Rp}).strict(),ne.object({type:ne.literal("close")}).strict(),ne.object({type:ne.literal("action"),action:hS}).strict()]),Uo=ne.object({schemaVersion:ne.literal(3),kind:ne.literal("paywall"),name:ne.string().trim().min(1).max(80),presentation:An,requirement:Fn.optional(),products:hp,offeringVersionId:ne.uuid().nullable(),offeringId:ne.uuid().nullable(),screen:bS,buttons:ne.record(ne.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),_S)}).strict(),Mo=Uo.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 SS(e))t.addIssue({code:"custom",message:r});for(let r of yS(e))t.addIssue({code:"custom",message:r});Rr(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 yS(e){let t=e.products.items.map(o=>o.productVersionId),n=Tr(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&&(!jo(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(c=>r.add(c));let s=!1;n[a.pickerId]&&(s=!0,(a.allowedProductVersionIds.some(c=>!n[a.pickerId].ids.includes(c))||n[a.pickerId].ids.some(c=>!a.allowedProductVersionIds.includes(c)))&&i.push("picker")),Pt(e.screen,c=>{if(c.id!==a.pickerId||c.type!=="plan_picker")return;s=!0,(JSON.stringify(c.planIds)!==JSON.stringify(t)||JSON.stringify(a.allowedProductVersionIds)!==JSON.stringify(t)||c.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=c.grouping?{tiers:c.grouping.tiers,assignments:c.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"),Pt(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 SS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let a of e.screen.pages)r.set(a.id,[]),fn(a.root,s=>{let c=s.type==="button"?s.action:s.type==="stack"?s.purchaseAction:void 0;if(c){let l=e.screen.actions.find(d=>d.id===c);l?.type==="navigate"&&r.get(a.id).push(l.pageId);let u=e.buttons[c];a.id!==n.id&&u&&u.type!=="close"&&t.push(`purchaseScreen:${s.id}`)}a.id!==n.id&&(s.type==="plan_picker"||s.type==="stack"&&s.productSlot)&&t.push(`packageScreen:${s.id}`)});let i=new Set;function o(a){if(!i.has(a)){i.add(a);for(let s of r.get(a)??[])o(s)}}o(e.screen.initialPageId??e.screen.pages[0].id);for(let a of e.screen.pages)i.has(a.id)||t.push(`unreachableScreen:${a.id}`);return[...new Set(t)]}var kp=ne.object({id:ne.uuid(),projectId:ne.uuid(),environmentId:ne.uuid(),revision:ne.number().int().nonnegative(),status:ne.enum(["draft","published","archived"]),publishedVersionId:ne.uuid().nullable(),updatedAt:ne.iso.datetime({offset:!0}),draft:Uo}).strict(),gR=ne.object({rows:ne.array(kp).max(200),nextCursor:ne.uuid().nullable()}).strict(),hR=kp.omit({draft:!0}).extend({name:ne.string(),productCount:ne.number().int().nonnegative()}).strict(),bR=ne.discriminatedUnion("action",[ne.object({action:ne.literal("save"),id:ne.uuid().nullable(),revision:ne.number().int().nonnegative(),document:Uo}).strict(),ne.object({action:ne.enum(["publish","archive"]),id:ne.uuid(),revision:ne.number().int().nonnegative()}).strict()]),_R=ne.object({paywalls:ne.array(ne.object({id:ne.uuid(),paywallId:ne.uuid(),version:ne.number().int().positive(),name:ne.string().min(1).max(80),presentation:An,buttons:Uo.shape.buttons}).strict()).max(500),limited:ne.boolean()}).strict();var jp=Rt.strictObject({selector:Rt.discriminatedUnion("type",[Rt.strictObject({type:Rt.literal("paywall"),paywallId:Rt.uuid()}),Rt.strictObject({type:Rt.literal("version"),versionId:Rt.uuid()})]),customerId:Rt.uuid().optional(),commerce:Pr,locale:Rt.string().min(1).max(35),requirement:Fn.optional()}),Lo=Rt.strictObject({id:Rt.uuid(),paywallId:Rt.uuid(),version:Rt.number().int().positive(),document:Mo,offering:Cr,capabilities:No,check:ar.nullable()}).superRefine((e,t)=>{let n=new Set(Ci(e.offering.document)),r=new Set(e.document.products.items.map(i=>i.productVersionId));(e.document.offeringVersionId!==e.offering.id||e.document.offeringId!==e.offering.offeringId||[...r].some(i=>!n.has(i))||Object.values(e.capabilities.plans).some(i=>!r.has(i.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})});import{z as It}from"zod";var Np={requestId:It.uuid(),sourceId:It.uuid(),expectedAvailable:Ze},Dp=It.discriminatedUnion("action",[It.strictObject({...Np,action:It.enum(["add","subtract","set_remaining"]),amount:Y}),It.strictObject({...Np,action:It.literal("edit"),granted:Y,expiresAt:It.iso.datetime({offset:!0}).nullable(),nextResetAt:It.iso.datetime({offset:!0}).nullable(),expectedRevision:It.number().int().nonnegative()})]),Hs=It.strictObject({sourceId:It.uuid(),available:Ze,held:Ze,spent:Ze,adjustmentGrantId:It.uuid().nullable()}),Fp=Hs.extend({granted:Ze,expiresAt:It.iso.datetime({offset:!0}).nullable(),nextResetAt:It.iso.datetime({offset:!0}).nullable(),revision:It.number().int().nonnegative()});import{z as Lt}from"zod";var Up=Lt.discriminatedUnion("action",[Lt.object({action:Lt.literal("upsert"),externalId:Lt.string().min(1).max(128),name:Lt.string().trim().min(1).max(80)}).strict(),Lt.object({action:Lt.literal("archive"),entityId:Lt.uuid()}).strict()]),Mp=Lt.object({id:Lt.uuid(),externalId:Lt.string().min(1).max(128),name:Lt.string().min(1).max(80),archived:Lt.boolean()}).strict();import{z as mt}from"zod";import{z as ur}from"zod";var Bp=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Lp=ur.string().regex(/.+\/.+/),zs=ur.number().min(-100),cr=ur.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),xS=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()}),Ws=(e,t)=>ur.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),DR=ur.strictObject({defaultMarkup:zs,providerMarkups:Ws(ur.string().min(1),zs),modelMarkups:Ws(Lp,zs),customModels:Ws(Lp,xS.partial())});import{z as ae}from"zod";var lr=ae.iso.datetime({offset:!0}),Un=ae.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),IS=ae.discriminatedUnion("kind",[ae.object({kind:ae.literal("absolute"),from:lr,to:lr}).strict(),ae.object({kind:ae.literal("last_days"),days:ae.union([ae.literal(1),ae.literal(7),ae.literal(30),ae.literal(90)])}).strict(),ae.object({kind:ae.literal("billing_cycles"),membershipId:ae.uuid(),count:ae.number().int().min(1).max(12),includeCurrent:ae.boolean()}).strict()]),qp=ae.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"),vS=ae.object({key:ae.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:ae.array(ae.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),dr=ae.object({range:IS,timezone:qp,filterBy:ae.array(vS).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:ae.enum(["hour","day","week","month"]),internal_feature_id:ae.uuid().nullable(),entityId:ae.uuid().nullable(),topN:ae.number().int().min(1).max(50).nullable(),groupBy:ae.union([ae.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),ae.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:ae.object({bucket:lr,group:ae.string().max(240),isOther:ae.boolean(),internal_feature_id:ae.uuid(),resourceId:ae.uuid()}).strict().nullable(),limit:ae.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)"})}),Vp=ae.object({from:lr,to:lr,interval:ae.enum(["hour","day","week","month"]),timezone:qp,rows:ae.array(ae.object({bucket:lr,group:ae.string().max(240),isOther:ae.boolean(),internal_feature_id:ae.uuid(),resourceId:ae.uuid(),consumedUnits:Un,refundedUnits:Un,reservedUnits:Un,charged:Un,refunded:Un,reserved:Un,netUnits:Un,netCharged:Un}).strict()).max(100),nextCursor:ae.object({bucket:lr,group:ae.string().max(240),isOther:ae.boolean(),internal_feature_id:ae.uuid(),resourceId:ae.uuid()}).strict().nullable()}).strict();var kr=mt.string().regex(/^(0|[1-9]\d{0,29})$/),$p=mt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Qs=mt.strictObject({bucket:mt.iso.datetime({offset:!0}),group:mt.string().max(240),isOther:mt.boolean(),internal_feature_id:mt.uuid()}),Gp=mt.strictObject({...dr.shape,groupBy:mt.union([mt.enum(["customer","entity","entitlement"]),mt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Qs.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})}),Kp=mt.strictObject({from:mt.iso.datetime({offset:!0}),to:mt.iso.datetime({offset:!0}),interval:dr.shape.interval,timezone:dr.shape.timezone,rows:mt.array(mt.strictObject({...Qs.shape,eventCount:kr,units:$p,tokenEventCount:kr,tokens:mt.strictObject(Object.fromEntries(Bp.map(e=>[e,kr]))),totalTokens:kr,providerCostEventCount:kr,providerCostUsd:$p,invalidTelemetryEventCount:kr})).max(100),nextCursor:Qs.nullable()});import{z as Xe}from"zod";var Hp=Xe.object({requestId:Xe.uuid(),items:Xe.array(Xe.object({customerId:Xe.uuid(),command:yi.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"),zp=Xe.object({batchId:Xe.uuid(),after:Xe.number().int().min(-1).max(999),limit:Xe.number().int().min(1).max(100)}).strict(),Wp=Xe.object({batchId:Xe.uuid(),status:Xe.enum(["queued","complete"]),total:Xe.number().int().min(1).max(1e3),processed:Xe.number().int().min(0).max(1e3),items:Xe.array(Xe.object({position:Xe.number().int().min(0).max(999),customerId:Xe.uuid(),idempotencyKey:Xe.string().min(1).max(120),status:Xe.enum(["queued","accepted","rejected","failed"]),receipt:Si.nullable(),errorCode:Xe.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:Xe.number().int().min(0).max(999).nullable()}).strict();import{z as x}from"zod";var AS=x.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Qp=x.enum(["draft","active","paused","archived"]),Zp=x.string().min(1).max(256),Yp=x.array(Zp).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),wS=x.strictObject({duration:x.enum(["day","week","month","year"]),length:x.number().int().min(1).max(3660)}),OS=x.strictObject({internal_feature_id:x.uuid(),allowance:x.number().nonnegative().max(1e15).nullable(),expiry:wS.nullable()}),PS=x.discriminatedUnion("type",[x.strictObject({type:x.literal("feature_grant"),grants:x.array(OS).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),x.strictObject({type:x.literal("free_product"),productId:Zp,duration:tn}),x.strictObject({type:x.literal("invoice_credits"),amount:x.number().positive().max(1e8),duration:tn,rollover:x.boolean(),productIds:Yp})]),CS=x.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Jp=x.object({key:CS,name:x.string().trim().min(1).max(80),configuration:PS}).strict(),Xp=x.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Zs=x.object({code:Xp,maxUses:x.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:x.boolean()}).strict(),em=x.object({key:x.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:x.string().trim().min(1).max(80),rewardId:x.uuid(),redeemOn:x.enum(["customer_creation","checkout"]),receivedBy:x.enum(["referrer","all"]),maxRedemptions:x.number().int().min(1).max(1e6).nullable(),productIds:Yp,excludeTrial:x.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),tm={id:x.uuid(),projectId:x.uuid(),environmentId:x.uuid(),revision:x.number().int().nonnegative(),status:Qp,createdAt:x.iso.datetime({offset:!0}),updatedAt:x.iso.datetime({offset:!0})},ES=Jp.extend(tm).strict(),TS=em.safeExtend(tm).strict(),QR=x.strictObject({id:x.uuid(),key:x.string(),name:x.string(),type:AS,status:Qp}),ZR=x.discriminatedUnion("action",[x.object({action:x.literal("save"),id:x.uuid().nullable(),revision:x.number().int().nonnegative(),input:Jp}).strict(),x.object({action:x.enum(["activate","pause","resume","archive","delete"]),id:x.uuid(),revision:x.number().int().nonnegative()}).strict()]),YR=x.discriminatedUnion("action",[x.object({action:x.literal("save"),id:x.uuid().nullable(),revision:x.number().int().nonnegative(),input:em}).strict(),x.object({action:x.enum(["activate","pause","resume","archive","delete"]),id:x.uuid(),revision:x.number().int().nonnegative()}).strict()]),nm=x.object({id:x.uuid(),rewardId:x.uuid(),programId:x.uuid().nullable(),customerId:x.uuid(),referrerId:x.uuid().nullable(),status:x.enum(["pending","applied"]),result:x.record(x.string(),x.unknown()).nullable(),createdAt:x.iso.datetime({offset:!0})}).strict(),rm=x.object({code:Xp,requestId:x.uuid()}).strict(),im=x.strictObject({redemptionId:x.uuid(),currency:W,requestId:x.uuid(),accepted:x.literal(!0)}),RS=x.strictObject({type:x.literal("checkout"),orderId:x.uuid(),productVersionId:x.uuid(),currency:W,duration:tn,renewalAmountMinor:x.number().int().positive().max(1e8),status:x.enum(["created","pending","trialing","paid","cancelled","failed"]),url:x.url().nullable()}),om=x.discriminatedUnion("type",[RS,x.strictObject({type:x.literal("subscription"),operationId:x.uuid(),membershipId:x.uuid(),productVersionId:x.uuid(),currency:W,duration:tn,renewalAmountMinor:x.number().int().positive().max(1e8),status:x.enum(["pending","running","applied","failed"])})]),am=x.object({programId:x.uuid(),requestId:x.uuid()}).strict(),sm=x.object({id:x.uuid(),programId:x.uuid(),code:Zs.shape.code,createdAt:x.iso.datetime({offset:!0})}).strict(),JR=x.object({rows:x.array(ES).max(100),nextCursor:x.uuid().nullable()}).strict(),XR=x.object({rows:x.array(TS).max(100),nextCursor:x.uuid().nullable()}).strict(),kS=Zs.extend({id:x.uuid(),redemptions:x.number().int().nonnegative()}).strict(),jS=x.strictObject({id:x.uuid(),programId:x.uuid().nullable(),customerId:x.uuid().nullable(),referrerId:x.uuid().nullable(),code:x.string().nullable(),status:x.enum(["pending","triggered","applied"]),createdAt:x.iso.datetime({offset:!0})}),ek=x.object({codes:x.array(kS).max(100),redemptions:x.array(jS).max(100),customers:x.record(x.uuid(),x.string()),codesCursor:x.uuid().nullable(),redemptionsCursor:x.uuid().nullable()}).strict(),tk=x.discriminatedUnion("action",[x.object({action:x.literal("create"),rewardId:x.uuid(),revision:x.number().int().nonnegative(),input:Zs}).strict(),x.object({action:x.literal("remove"),rewardId:x.uuid(),revision:x.number().int().nonnegative(),codeId:x.uuid()}).strict()]);import{z as y}from"zod";import{z as J}from"zod";var Ys=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"),jr=J.intersection(Ft,J.object({tags:Ys.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Bo=J.string().trim().max(80),qo=J.union([J.email().max(254),J.literal("")]),Vo=J.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),cm=J.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),um=J.object({externalUserId:cm.optional(),name:Bo.default(""),email:qo.default(""),attributes:jr.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Nr=J.discriminatedUnion("type",[J.strictObject({type:J.literal("id"),value:J.uuid()}),J.strictObject({type:J.literal("externalUserId"),value:cm})]),Dr=J.strictObject({name:Bo.optional(),email:qo.optional(),attributes:jr.optional(),fingerprint:Vo.optional()}),pr=e=>!e.customerData||e.customer?.type==="externalUserId",mr="customerData requires an externalUserId customer",Fr=J.object({id:J.uuid(),externalUserId:J.string().min(1).max(255).nullable(),name:Bo,email:qo,attributes:jr,createdAt:J.iso.datetime()}).strict(),lm=J.object({customer:Fr,changed:J.boolean(),replayed:J.boolean()}).strict(),NS=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()]),DS=J.object({name:Bo.optional(),email:qo.optional(),attributes:jr.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:Ys,remove:Ys}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Js=J.object({lookup:NS}).strict(),dm=Js.extend({requestId:J.uuid(),patch:DS}).strict(),pm=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(),mm=J.object({customers:Fr.array(),hasMore:J.boolean(),total:J.number().int().nonnegative().nullable(),evaluatedAt:J.iso.datetime()}).strict();import{z as ke}from"zod";import{z as N}from"zod";var Xs=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),FS=N.strictObject({attribute:N.string().optional(),seed:N.string(),hashVersion:N.literal(2),ranges:N.array(Xs).max(100)}),US=N.strictObject({id:N.string().min(1).max(255),condition:St,gate:N.boolean().optional()}),MS=N.strictObject({key:N.string().optional(),name:N.string().optional(),passthrough:N.boolean().optional()}),fm={condition:St.optional(),parentConditions:N.array(US).max(100).optional(),weights:N.array(N.number().min(0).max(1)).max(20).optional(),coverage:N.number().min(0).max(1).optional(),hashAttribute:N.string().optional(),fallbackAttribute:N.string().optional(),hashVersion:N.literal(2).optional(),disableStickyBucketing:N.boolean().optional(),bucketVersion:N.number().int().nonnegative().optional(),minBucketVersion:N.number().int().nonnegative().optional(),filters:N.array(FS).max(100).optional(),ranges:N.array(Xs).max(20).optional(),meta:N.array(MS).max(20).optional(),seed:N.string().optional(),name:N.string().optional(),phase:N.string().optional()},$o=N.strictObject({...fm,key:N.string().min(1).max(255),variations:N.tuple([Ae,Ae]).rest(Ae).refine(e=>e.length<=20),urlPatterns:N.array(N.strictObject({include:N.boolean(),type:N.enum(["regex","simple"]),pattern:N.string()})).max(100).optional(),force:N.number().int().nonnegative().optional(),active:N.boolean().optional(),persistQueryString:N.boolean().optional()}),ec=N.strictObject({value:Ae,variationId:N.number().int(),key:N.string(),name:N.string().optional(),bucket:N.number().optional(),passthrough:N.boolean().optional(),inExperiment:N.boolean(),hashUsed:N.boolean().optional(),hashAttribute:N.string(),hashValue:N.string(),featureId:N.string().nullable(),stickyBucketUsed:N.boolean().optional()}),LS=N.strictObject({...fm,id:N.string().max(255).optional(),force:Ae.optional(),variations:N.array(Ae).min(2).max(20).optional(),key:N.string().optional(),range:Xs.optional(),tracks:N.array(N.strictObject({experiment:$o,result:ec})).max(100).optional()}),BS=N.strictObject({defaultValue:Ae.optional(),rules:N.array(LS).max(500).optional()}),tc=N.record(N.string(),N.union([N.strictObject({type:N.literal("hashed"),attributeKey:N.string(),values:N.array(N.string().regex(/^[a-f0-9]{64}$/))}),N.strictObject({type:N.literal("list"),attributeKey:N.string(),values:N.array(N.union([N.string(),N.number()]))}),N.strictObject({type:N.literal("condition"),condition:St})])),gn=N.strictObject({scope:Fe,generation:N.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:N.iso.datetime({offset:!0}),expiresAt:N.iso.datetime({offset:!0}).nullable(),features:N.record(N.string(),BS),savedGroups:tc,experiments:N.record(N.uuid(),$o)});var gm=gn.extend({remoteFeatures:ke.array(ke.string().min(1).max(255)).max(500)}),hm=ke.strictObject({attributes:Ft,features:ke.array(ke.string().min(1).max(255)).min(1).max(500).optional(),customerId:ke.uuid().optional()}),qS=ke.strictObject({value:Ae,source:ke.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ke.boolean(),off:ke.boolean(),ruleId:ke.string(),experimentResult:ec.optional()}),bm=ke.strictObject({generation:gn.shape.generation,evaluatedAt:gn.shape.evaluatedAt,expiresAt:gn.shape.expiresAt,features:ke.record(ke.string(),qS)}),_m=ke.strictObject({customerId:ke.uuid().optional(),events:ke.array(ke.strictObject({eventUuid:ke.uuid(),timestamp:ke.iso.datetime({offset:!0}),name:ke.string().min(1).max(255),properties:ke.record(ke.string(),Ae).default({}),deviceId:ke.string().min(1).max(255).optional(),sessionId:ke.string().min(1).max(255).optional()})).min(1).max(100)}),ym=ke.strictObject({inserted:ke.number().int().nonnegative(),duplicates:ke.number().int().nonnegative(),rejected:ke.number().int().nonnegative()});var VS=y.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"]),Sm={scope:Fe,permissions:y.array(VS),expiresAt:y.iso.datetime().nullable()},Wk=y.discriminatedUnion("kind",[y.object({...Sm,kind:y.literal("server"),keyId:y.string().min(1)}),y.object({...Sm,kind:y.literal("customer"),customerId:y.string().min(1),identityKind:y.enum(["identified","guest"]),expiresAt:y.iso.datetime()})]),M=y.object({requestId:y.uuid(),scope:Fe}).strict(),$S=um.safeExtend({fingerprint:Vo.optional()}).strict(),GS=M.extend({customer:Fr,created:y.boolean()}),KS=y.enum(["unassigned","unknown","scheduled","active","expired"]),Qk=y.object({customerId:y.string().min(1),evaluatedAt:y.iso.datetime(),status:KS,validity:ss.nullable(),planVersion:Al.nullable(),holdings:y.array(y.object({id:y.uuid(),planVersionId:y.uuid(),source:y.enum(["subscription","assignment","license","license_pool","entity_pool"])})).optional(),entitlements:y.array(y.object({featureId:y.string(),featureKey:y.string(),featureName:y.string(),type:y.enum(["boolean","metered"]),allowance:y.number().int().nonnegative().nullable(),used:y.number().finite().nonnegative(),remaining:y.number().finite().nonnegative().nullable(),allowed:y.boolean(),sources:y.array(y.object({holdingId:y.uuid(),planVersionId:y.uuid(),group:y.string(),kind:y.enum(["main","addon"]),allowance:y.number().nullable()})).optional()}))});function xm(){return M.extend({offer:ms.nullable(),reason:fo.nullable()})}var U={getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:y.strictObject({}),response:M.extend({payload:gm})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:hm,response:M.merge(bm)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:_m,response:M.merge(ym)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:y.strictObject({customerId:y.uuid(),sourceId:y.uuid()}),response:M.extend({balance:Fp})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:y.strictObject({customerId:y.uuid(),command:Dp}),response:M.extend({balance:Hs})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:y.strictObject({internal_feature_id:y.uuid(),customerId:y.uuid().optional(),entityId:y.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:M.extend({internal_feature_id:y.uuid(),config:Ya,model_markups:co})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:y.strictObject({customerId:y.uuid(),query:So}),response:M.extend({usage:xi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:y.strictObject({customerId:y.uuid(),command:wd}),response:M.extend({usage:xi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:y.strictObject({customerId:y.uuid(),command:_d}),response:M.extend({grant:vs})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:yd,response:M.extend({grants:Sd})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:y.union(cp.options.map(e=>e.extend({customerId:y.uuid().optional(),customerToken:y.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/).optional()}))),response:M.extend({operation:up})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Yd.extend({customerId:y.uuid().optional()}),response:M.extend({setup:js})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Jd.extend({customerId:y.uuid().optional()}),response:M.extend({setup:js})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Wd.safeExtend({customerId:y.uuid()}),response:M.extend({batch:Oi})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:wo.extend({customerId:y.uuid()}),response:M.extend({batch:Oi})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:wo.extend({customerId:y.uuid()}),response:M.extend({batch:Oi})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:wo.extend({customerId:y.uuid()}),response:M.extend({batch:Oi})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:y.discriminatedUnion("action",[Oo.options[0].extend({customerId:y.uuid()}),Oo.options[1].extend({customerId:y.uuid()}),Oo.options[2].extend({customerId:y.uuid()})]),response:M.extend({trial:ks})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Qd.extend({customerId:y.uuid()}),response:M.extend({trial:ks})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Eo,response:M.extend({subscriptions:op})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Eo,response:M.extend({purchases:ap})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:np,response:M.extend({conflicts:sp})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:rp,response:M.extend({resolution:ip})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:ep,response:M.extend({verification:tp})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Ld.safeExtend({customerId:y.uuid().optional()}),response:M.extend({quote:Ai})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:or.extend({customerId:y.uuid().optional(),intent:y.enum(["confirm","cancel"]).optional()}),response:M.extend({operation:Or})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:or.extend({customerId:y.uuid().optional()}),response:M.extend({operation:Or})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Vd.safeExtend({customerId:y.uuid().optional()}),response:M.extend({quote:Gd})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:or.extend({customerId:y.uuid().optional(),intent:y.enum(["confirm","cancel"]).optional()}),response:M.extend({operation:Ts})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:or.extend({customerId:y.uuid().optional()}),response:M.extend({operation:Ts})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Kd.safeExtend({customerId:y.uuid()}),response:M.extend({quote:zd})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:or.extend({customerId:y.uuid()}),response:M.extend({operation:Ao})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:or.extend({customerId:y.uuid()}),response:M.extend({operation:Ao})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Wl,response:M.extend({controls:fs})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:ql,response:M.extend({prepared:$l})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Gl,response:M.extend({authorization:go})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Jl,response:M.extend({coupons:Xl})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Kl,response:M.extend({authorization:go})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Zl,response:M.extend({invoices:Yl})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Ql,response:M.extend({invoice:li})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:y.object({customerId:y.uuid(),command:zl}).strict(),response:M.extend({controls:fs})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:y.object({customerId:y.uuid(),command:Up}).strict(),response:M.extend({entity:Mp})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:y.strictObject({customerId:y.uuid().nullable(),query:Gp}),response:M.extend({analytics:Kp})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:y.object({customerId:y.uuid().nullable(),query:dr}).strict(),response:M.extend({analytics:Vp})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Hp,response:M.extend({batchId:y.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:zp,response:M.extend({batch:Wp})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:lp.extend({customerId:y.string().min(1).optional()}),response:M.extend({check:ar})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:jp,response:M.extend({paywall:Lo})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:y.strictObject({selector:fp,customerId:y.string().min(1).optional(),commerce:Pr,requirement:Fn.optional()}),response:M.extend({offering:Cr,candidates:y.array(Ds).max(20),availability:y.array(y.strictObject({productVersionId:y.uuid(),available:y.boolean(),reason:y.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:ar.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:y.object({customerId:y.uuid().optional(),entityId:y.uuid().optional()}).strict(),response:M.extend({holdings:Od})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:y.object({customerId:y.uuid().optional(),query:Cd}).strict(),response:M.extend({ledger:Ed})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:xd.extend({customerId:y.uuid().optional()}),response:M.extend({detail:Id})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:As.safeExtend({customerId:y.uuid().optional()}),response:M.extend({statement:vd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:y.object({customerId:y.uuid().optional(),command:yi.options[0]}).strict(),response:M.extend({quote:gd})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:y.strictObject({customerId:y.uuid(),command:y.union([y.strictObject({eventName:y.string().min(1),quantity:Y.optional(),properties:Je.optional(),entityId:y.uuid().optional(),idempotencyKey:y.string().min(1).max(120)}),y.strictObject({internal_feature_id:y.uuid(),quantity:Y.optional(),properties:Je.optional(),entityId:y.uuid().optional(),idempotencyKey:y.string().min(1).max(120)})])}),response:M.extend({receipts:y.array(Si).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:y.object({customerId:y.uuid(),command:yi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:M.extend({receipt:Si})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:rm,response:M.extend({redemption:nm})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:am,response:M.extend({referralCode:sm})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:im,response:M.extend({checkout:om})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Rd,response:M.extend({seats:Ps})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:kd,response:M.extend({seats:Ps})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:$S,response:GS},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Js,response:M.extend({customer:Fr})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:pm,response:M.extend(mm.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:dm,response:M.extend(lm.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:y.object({customerId:y.uuid()}).strict(),response:M.extend({customerToken:y.string().min(1),expiresAt:y.iso.datetime(),sessionId:y.uuid()})},renewSession:{method:"POST",path:"customer-sessions/renew",permission:"sessions:create",audience:"server",request:y.strictObject({customerId:y.uuid(),customerToken:y.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/)}),response:M.extend({customerToken:y.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:y.uuid(),expiresAt:y.iso.datetime()})},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:y.strictObject({customerId:y.uuid(),sessionId:y.uuid().optional()}),response:M.extend({revoked:y.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:y.strictObject({guestToken:y.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Vo.optional()}),response:M.extend({customerId:y.uuid(),guestToken:y.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:y.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:y.strictObject({guestToken:y.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:M.extend({customerId:y.uuid(),customerToken:y.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:y.uuid(),expiresAt:y.iso.datetime()})},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:y.strictObject({guestToken:y.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:y.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:y.uuid()}),response:M.extend({customer:Fr,switched:y.boolean(),replayed:y.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:y.strictObject({code:y.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:y.uuid()}),response:xm()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:y.object({}).strict(),response:M.extend({offers:y.array(ms)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"server",request:y.object({customerId:y.string().min(1).max(255),couponId:y.uuid(),requestId:y.uuid()}).strict(),response:xm()}},Zk={getFeatures:U.getFeatures,evaluateFeatures:U.evaluateFeatures,trackEvents:U.trackEvents,setupPayment:U.setupPayment,readPaymentSetup:U.readPaymentSetup,previewSubscriptionBatch:U.previewSubscriptionBatch,confirmSubscriptionBatch:U.confirmSubscriptionBatch,readSubscriptionBatch:U.readSubscriptionBatch,abandonSubscriptionBatch:U.abandonSubscriptionBatch,manageSubscriptionTrial:U.manageSubscriptionTrial,readSubscriptionTrial:U.readSubscriptionTrial,listSubscriptions:U.listSubscriptions,listPurchases:U.listPurchases,listSubscriptionConflicts:U.listSubscriptionConflicts,retrySubscriptionConflict:U.retrySubscriptionConflict,readAiPricing:U.readAiPricing,readUsage:U.readUsage,setUsage:U.setUsage,previewRefund:U.previewRefund,refund:U.refund,readRefund:U.readRefund,previewUpdate:U.previewUpdate,update:U.update,readSubscriptionUpdate:U.readSubscriptionUpdate,restoreNativePurchase:U.restoreNativePurchase,verifySubscriptions:U.verifySubscriptions,previewAttach:U.previewAttach,attach:U.attach,readSubscriptionOperation:U.readSubscriptionOperation,manageBalanceGrant:U.manageBalanceGrant,readBalanceSource:U.readBalanceSource,adjustBalance:U.adjustBalance,listBalanceGrants:U.listBalanceGrants,readBillingControls:U.readBillingControls,prepareBillingAuthorization:U.prepareBillingAuthorization,confirmBillingAuthorization:U.confirmBillingAuthorization,setBillingCoupons:U.setBillingCoupons,revokeBillingAuthorization:U.revokeBillingAuthorization,listBillingInvoices:U.listBillingInvoices,confirmBillingAdjustment:U.confirmBillingAdjustment,manageBillingLimits:U.manageBillingLimits,createCustomer:U.createCustomer,getCustomer:U.getCustomer,listCustomers:U.listCustomers,updateCustomer:U.updateCustomer,createSession:U.createSession,renewSession:U.renewSession,revokeSessions:U.revokeSessions,createGuestCustomer:U.createGuestCustomer,resumeGuestSession:U.resumeGuestSession,claimGuestCustomer:U.claimGuestCustomer,checkEntitlement:U.checkEntitlement,resolveOffering:U.resolveOffering,resolvePaywall:U.resolvePaywall,readHoldings:U.readHoldings,readLedger:U.readLedger,readBillingInvoice:U.readBillingInvoice,readCreditStatement:U.readCreditStatement,quoteBalance:U.quoteBalance,trackUsage:U.trackUsage,mutateBalance:U.mutateBalance,manageUsageEntity:U.manageUsageEntity,readUsageAnalytics:U.readUsageAnalytics,readCreditAnalytics:U.readCreditAnalytics,submitUsageBatch:U.submitUsageBatch,readUsageBatch:U.readUsageBatch,listOffers:U.listOffers,grantOffer:U.grantOffer,redeemCoupon:U.redeemCoupon,redeemReward:U.redeemReward,createReferralCode:U.createReferralCode,claimRewardProduct:U.claimRewardProduct,readSeats:U.readSeats,manageSeat:U.manageSeat};import{z as nc}from"zod";var HS="[a-f0-9]{64}",Im="[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",zS="[a-zA-Z][a-zA-Z0-9_.-]{0,63}",WS="[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?",rc=new RegExp(`^/web-view/screens/(${HS})/(?:funnel/(${Im})/(${zS})|paywall/(${Im}))/(${WS})$`),vm=nc.string().max(256).regex(rc,"Invalid screen render address"),Am=nc.union([vm,nc.string().max(512).regex(new RegExp(`^(?:https://[a-z0-9.-]+(?::[0-9]{1,5})?|http://(?:localhost|127\\.0\\.0\\.1)(?::[0-9]{1,5})?)${rc.source.slice(1)}`),"Invalid screen render URL")]);function tj(e){let t=e.kind==="funnel"?`/web-view/screens/${e.tag}/funnel/${e.versionId}/${e.screenId}/${e.locale}`:`/web-view/screens/${e.tag}/paywall/${e.versionId}/${e.locale}`;return vm.parse(t)}function nj(e){let t=rc.exec(e);if(!t||!en.safeParse(t[5]).success)return null;let[,n,r,i,o,a]=t;return r?{kind:"funnel",tag:n,versionId:r,screenId:i,locale:a}:{kind:"paywall",tag:n,versionId:o,locale:a}}var rj={funnel:e=>`screen-render:funnel:${e}`,funnelVersion:e=>`screen-render:funnel-version:${e}`,paywall:e=>`screen-render:paywall:${e}`,paywallVersion:e=>`screen-render:paywall-version:${e}`};var et={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},oj="00000000-0000-0000-0000-000000000000";var Om={primary:"#2C3C96",background:"#FFFFFF",text:"#1B1D24",radius:"md",font:"system"},ji=(e,t,n,r,i)=>({kind:"screen",schemaVersion:4,name:e,surface:"popup",presentation:{type:"modal",size:"md"},theme:{...Om},pages:[{id:"main",name:"\u4E3B\u9875\u9762",root:t}],strings:{defaultLocale:"zh-CN",locales:{"zh-CN":n,en:r}},actions:i}),Ur=e=>({type:"stack",id:"root",direction:"vertical",align:"stretch",justify:"start",children:e,style:{gap:12,padding:{top:24,right:24,bottom:24,left:24}}}),Go={id:"dismiss",type:"close",event:"popup.dismissed",properties:{},close:!0},wm=[{id:"blank",label:"\u7A7A\u767D",description:"\u4E00\u4E2A\u6807\u9898\u548C\u4E00\u4E2A\u6309\u94AE\uFF0C\u4ECE\u96F6\u5F00\u59CB\u642D\u3002",document:ji("\u672A\u547D\u540D\u5F39\u7A97",Ur([{type:"text",id:"title",text:"title",variant:"heading"},{type:"button",id:"cta",label:"cta",variant:"primary",action:"dismiss",style:{width:"fill"}}]),{title:"\u6807\u9898",cta:"\u77E5\u9053\u4E86"},{title:"Title",cta:"Got it"},[Go])},{id:"announcement",label:"\u516C\u544A",description:"\u65B0\u529F\u80FD\u6216\u91CD\u8981\u901A\u77E5\uFF0C\u4E00\u4E2A\u4E3B\u6309\u94AE\u3002",document:ji("\u65B0\u529F\u80FD\u516C\u544A",Ur([{type:"text",id:"eyebrow",text:"eyebrow",variant:"caption",style:{text:{color:"primary",weight:700}}},{type:"text",id:"title",text:"title",variant:"heading"},{type:"text",id:"body",text:"body",variant:"body",style:{text:{color:"muted"}}},{type:"button",id:"cta",label:"cta",variant:"primary",action:"learn_more",style:{width:"fill"}},{type:"button",id:"later",label:"later",variant:"link",action:"dismiss",style:{width:"fill"}}]),{eyebrow:"\u65B0\u529F\u80FD",title:"\u73B0\u5728\u53EF\u4EE5\u4E00\u952E\u5BFC\u51FA\u62A5\u8868",body:"\u5728\u4EFB\u610F\u6570\u636E\u9875\u70B9\u51FB\u53F3\u4E0A\u89D2\u300C\u5BFC\u51FA\u300D\uFF0C\u5373\u53EF\u4E0B\u8F7D CSV \u6216 PDF\u3002",cta:"\u53BB\u770B\u770B",later:"\u4EE5\u540E\u518D\u8BF4"},{eyebrow:"NEW",title:"Export reports in one click",body:"Click Export on any data page to download a CSV or PDF.",cta:"Take a look",later:"Not now"},[{id:"learn_more",type:"event",event:"announcement_clicked",properties:{},close:!0},Go])},{id:"upgrade",label:"\u5347\u7EA7\u5230 Pro",description:"\u5217\u51FA\u51E0\u9879\u6743\u76CA\uFF0C\u5F15\u5BFC\u5347\u7EA7\u3002",document:ji("\u5347\u7EA7\u5230 Pro",Ur([{type:"text",id:"eyebrow",text:"eyebrow",variant:"caption",style:{text:{color:"primary",weight:700}}},{type:"text",id:"title",text:"title",variant:"heading"},{type:"stack",id:"benefits",name:"\u6743\u76CA\u5217\u8868",direction:"vertical",align:"stretch",justify:"start",children:[{type:"text",id:"benefit1",text:"benefit1",variant:"body"},{type:"text",id:"benefit2",text:"benefit2",variant:"body"},{type:"text",id:"benefit3",text:"benefit3",variant:"body"}],style:{background:{type:"color",color:"surface"},shape:{type:"rect",radius:8},gap:4,padding:{top:16,right:16,bottom:16,left:16}}},{type:"button",id:"cta",label:"cta",variant:"primary",action:"upgrade",style:{width:"fill"}},{type:"button",id:"later",label:"later",variant:"link",action:"dismiss",style:{width:"fill"}}]),{eyebrow:"PRO",title:"\u89E3\u9501\u5168\u90E8\u9AD8\u7EA7\u529F\u80FD",benefit1:"\u2713 \u65E0\u9650\u9879\u76EE\u4E0E\u6210\u5458",benefit2:"\u2713 \u9AD8\u7EA7\u6570\u636E\u5206\u6790",benefit3:"\u2713 \u4F18\u5148\u5BA2\u670D\u652F\u6301",cta:"\u67E5\u770B Pro \u65B9\u6848",later:"\u7EE7\u7EED\u4F7F\u7528\u514D\u8D39\u7248"},{eyebrow:"PRO",title:"Unlock every advanced feature",benefit1:"\u2713 Unlimited projects and members",benefit2:"\u2713 Advanced analytics",benefit3:"\u2713 Priority support",cta:"See Pro plans",later:"Stay on Free"},[{id:"upgrade",type:"event",event:"checkout_requested",properties:{planId:"pro"},close:!0},Go])},{id:"offer",label:"\u9650\u65F6\u4F18\u60E0",description:"\u6E10\u53D8\u5934\u56FE + \u89D2\u6807 + \u539F\u4EF7\u5212\u7EBF\u7684\u4F18\u60E0\u4EF7\uFF0C\u9002\u5408\u9886\u5238\u5F39\u7A97\u3002",document:{...ji("\u9650\u65F6\u4F18\u60E0",{type:"stack",id:"root",direction:"vertical",align:"stretch",justify:"start",children:[{type:"stack",id:"hero",name:"\u5934\u56FE",direction:"overlay",align:"start",justify:"start",children:[{type:"stack",id:"heroContent",name:"\u5934\u56FE\u5185\u5BB9",direction:"vertical",align:"center",justify:"center",children:[{type:"text",id:"eyebrow",text:"eyebrow",variant:"caption",style:{width:"fit",padding:{top:3,right:10,bottom:3,left:10},background:{type:"color",color:"#FFFFFF2E"},shape:{type:"pill"},text:{color:"#FFFFFF",weight:700,letterSpacing:1,align:"center"}}},{type:"text",id:"title",text:"title",variant:"title",style:{text:{size:40,weight:900,color:"#FFFFFF",align:"center",lineHeight:1.1}}},{type:"text",id:"subtitle",text:"subtitle",variant:"body",style:{text:{size:14,color:"#FFFFFFD9",align:"center"}}}],style:{width:"fill",padding:{top:32,right:24,bottom:28,left:24},gap:6}},{type:"text",id:"badge",name:"\u89D2\u6807",text:"badge",variant:"caption",style:{width:"fit",margin:{top:14,right:0,bottom:0,left:14},padding:{top:4,right:10,bottom:4,left:10},background:{type:"color",color:"#FFD84D"},shape:{type:"pill"},shadow:{x:0,y:4,blur:10,spread:0,color:"#00000026"},text:{color:"#3A1D00",weight:800,size:13}}}],style:{gap:0,padding:{top:0,right:0,bottom:0,left:0},background:{type:"linear",angle:135,stops:[{color:"#FF7A45",at:0},{color:"#E8336D",at:100}]}}},{type:"stack",id:"body",name:"\u4EF7\u683C\u4E0E\u6309\u94AE",direction:"vertical",align:"stretch",justify:"start",children:[{type:"stack",id:"price",name:"\u4EF7\u683C",direction:"horizontal",align:"end",justify:"center",children:[{type:"text",id:"newPrice",text:"newPrice",variant:"title",style:{text:{size:34,weight:800,color:"#E8336D",lineHeight:1}}},{type:"text",id:"period",text:"period",variant:"body",style:{text:{color:"muted",size:14,lineHeight:1.6}}},{type:"text",id:"oldPrice",text:"oldPrice",variant:"body",style:{text:{color:"muted",size:15,decoration:"line-through",lineHeight:1.6}}}],style:{gap:8,padding:{top:0,right:0,bottom:0,left:0}}},{type:"text",id:"then",text:"then",variant:"caption",style:{text:{color:"muted",align:"center"}}},{type:"button",id:"cta",label:"cta",variant:"primary",action:"claim",style:{width:"fill",height:52,background:{type:"linear",angle:90,stops:[{color:"#FF7A45",at:0},{color:"#E8336D",at:100}]},shape:{type:"pill"},shadow:{x:0,y:10,blur:24,spread:-6,color:"#E8336D66"},text:{size:17,weight:800,color:"#FFFFFF"}}},{type:"button",id:"later",label:"later",variant:"link",action:"dismiss",style:{width:"fill"}}],style:{gap:14,padding:{top:22,right:24,bottom:22,left:24}}}],style:{gap:0,padding:{top:0,right:0,bottom:0,left:0}}},{eyebrow:"\u9650\u65F6 48 \u5C0F\u65F6",title:"\u9996\u6708 7 \u6298",subtitle:"\u65B0\u7528\u6237\u4E13\u4EAB \xB7 \u9886\u53D6\u540E 3 \u5929\u5185\u6709\u6548",badge:"-30%",newPrice:"$20.30",period:"/\u9996\u6708",oldPrice:"$29",then:"\u4E4B\u540E\u6BCF\u6708 $29\uFF0C\u53EF\u968F\u65F6\u53D6\u6D88",cta:"\u7ACB\u5373\u9886\u53D6",later:"\u6682\u4E0D\u9700\u8981"},{eyebrow:"48 HOURS ONLY",title:"30% off",subtitle:"For new members \xB7 valid 3 days after claiming",badge:"-30%",newPrice:"$20.30",period:"/first month",oldPrice:"$29",then:"Then $29/month. Cancel anytime.",cta:"Claim offer",later:"Not now"},[{id:"claim",type:"event",event:"offer_claimed",properties:{discount:30},close:!0},Go]),theme:{...Om,primary:"#E8336D",radius:"lg"}}},{id:"feedback",label:"\u6536\u96C6\u53CD\u9988",description:"\u4E24\u4E2A\u9009\u9879\u6309\u94AE\uFF0C\u8BB0\u5F55\u7528\u6237\u7684\u9009\u62E9\u3002",document:ji("\u6EE1\u610F\u5EA6\u8C03\u67E5",Ur([{type:"text",id:"title",text:"title",variant:"heading",style:{text:{align:"center"}}},{type:"text",id:"body",text:"body",variant:"body",style:{text:{align:"center",color:"muted"}}},{type:"stack",id:"choices",name:"\u9009\u9879",direction:"horizontal",align:"stretch",justify:"center",children:[{type:"button",id:"yes",label:"yes",variant:"secondary",action:"positive",style:{width:"fill"}},{type:"button",id:"no",label:"no",variant:"secondary",action:"negative",style:{width:"fill"}}],style:{gap:8,padding:{top:0,right:0,bottom:0,left:0}}}]),{title:"\u8FD9\u4E2A\u529F\u80FD\u5BF9\u4F60\u6709\u5E2E\u52A9\u5417\uFF1F",body:"\u4F60\u7684\u53CD\u9988\u4F1A\u76F4\u63A5\u5F71\u54CD\u6211\u4EEC\u4E0B\u4E00\u6B65\u505A\u4EC0\u4E48\u3002",yes:"\u6709\u5E2E\u52A9",no:"\u6CA1\u5E2E\u52A9"},{title:"Was this feature helpful?",body:"Your answer shapes what we build next.",yes:"Yes",no:"No"},[{id:"positive",type:"event",event:"feedback_submitted",properties:{helpful:!0},close:!0},{id:"negative",type:"event",event:"feedback_submitted",properties:{helpful:!1},close:!0}])}];function Ko(e="blank"){let t=wm.find(n=>n.id===e)??wm[0];return structuredClone(t.document)}var QS=(e,t,n)=>({type:"stack",id:e,name:"Web \u81EA\u9002\u5E94\u5E03\u5C40",direction:"horizontal",align:"center",justify:"center",children:[{...Ur(t),id:`${e}_intro`,name:"\u4ECB\u7ECD",style:{width:480,gap:20,padding:{top:0,right:0,bottom:0,left:0}}},{...Ur(n),id:`${e}_detail`,name:"\u5185\u5BB9\u4E0E\u64CD\u4F5C",style:{width:400,gap:20,padding:{top:24,right:24,bottom:24,left:24},background:{type:"color",color:"surface"},shape:{type:"rect",radius:8}}}],style:{gap:40,padding:{top:40,right:24,bottom:40,left:24}}});function sj(e,t="blank"){let n=Ko(t);if(e==="popup"||(n.surface=e,n.presentation={type:"fullscreen"},e==="page"))return n;if(e==="paywall"){let r=Ko("upgrade");r.actions=r.actions.map(o=>o.id==="upgrade"&&o.type==="event"?{...o,event:"paywall.upgrade_clicked",properties:{},close:!1}:o),r.strings.locales["zh-CN"].cta="\u4E86\u89E3\u5347\u7EA7\u65B9\u6848",r.strings.locales.en.cta="Explore upgrade options",r.strings.locales["zh-CN"].body="\u4E3A\u4F60\u7684\u5DE5\u4F5C\u533A\u9009\u62E9\u9002\u5408\u7684\u529F\u80FD\u4E0E\u534F\u4F5C\u65B9\u5F0F\u3002",r.strings.locales.en.body="Find the right features and collaboration tools for your workspace.";let i=r.pages[0].root.children;return r.pages[0].root=QS("root",[...i.slice(0,2),{type:"text",id:"body",text:"body",variant:"body",style:{text:{color:"muted"}}}],i.slice(2)),{...r,surface:e,presentation:{type:"fullscreen"},name:"\u9AD8\u7EA7\u529F\u80FD\u4ED8\u8D39\u5899"}}return{...n,surface:e,presentation:{type:"fullscreen"}}}function Pm(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"},r=Ko();return{...r,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:{...r.pages[0].root,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 Ni=fe.number().int().min(0).max(1e4),mj=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:Ni,snapshotHash:fe.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:fe.iso.datetime({offset:!0})}),ZS=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:Ni,issued:Ni,skipped:Ni,remaining:Ni,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)),YS=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:fo.nullable()}).refine(e=>e.status==="issued"==(e.grantId!==null)&&e.status==="skipped"==(e.reason!==null)),fj=fe.strictObject({batch:ZS,recipients:fe.array(YS).max(50),nextPosition:fe.number().int().min(1).max(1e4).nullable()}),gj=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 B}from"zod";var vt=B.number().int().min(0),Di=B.iso.datetime({offset:!0}),Ho=B.strictObject({internalId:B.uuid(),version:B.number().int().positive()}),Cm=B.enum(["subscription_change_required","unsupported_operation_input"]),JS=B.enum([...Cm.options,"internal_error"]),_j=B.strictObject({productId:B.string().min(1),productName:B.string(),from:Ho,to:Ho,noBillingChanges:B.boolean(),counts:B.strictObject({customers:vt,movable:vt,blocked:vt,unsupported:vt,canceled:vt,custom:vt}),rows:B.array(B.strictObject({customerId:B.uuid(),customerKey:B.string().nullable(),name:B.string().nullable(),email:B.string().nullable(),holdings:B.number().int().positive(),outcome:B.enum(["move","blocked","unsupported"]),reason:Cm.nullable()})).max(50),nextCursor:B.uuid().nullable()}),XS=B.enum(["queued","running","succeeded","no_changes","failed","canceled"]),Em=B.enum(["running","succeeded","skipped","failed"]),Tm=B.strictObject({internalId:B.uuid(),id:B.string().min(1),productId:B.string().min(1),productName:B.string(),from:Ho,to:Ho,noBillingChanges:B.boolean(),retryFailed:B.boolean(),step:B.enum(["queued","received","get_customers","migrate_customers","finished","failed"]),snapshot:B.strictObject({total_customers:vt,canceled_customers:vt,custom_customers:vt,migration_customers:vt}),createdAt:Di,run:B.strictObject({id:B.uuid(),status:XS,errorMessage:B.string().nullable(),createdAt:Di,startedAt:Di.nullable(),finishedAt:Di.nullable()}).nullable(),totals:B.strictObject({succeeded:vt,skipped:vt,failed:vt,running:vt,blocked:vt,remaining:vt})}),e0=B.strictObject({customerId:B.uuid(),customerKey:B.string().nullable(),name:B.string().nullable(),email:B.string().nullable(),status:Em,skipReason:B.enum(["no_updates_needed","ineligible"]).nullable(),updatedAt:Di,error:B.strictObject({code:JS,message:B.string().nullable()}).nullable()}),yj=B.strictObject({migration:Tm,items:B.array(e0).max(50),nextCursor:B.uuid().nullable()}),Sj=B.array(Tm).max(20),xj=B.discriminatedUnion("action",[B.strictObject({action:B.literal("create"),requestId:B.uuid(),fromInternalId:B.uuid(),toInternalId:B.uuid()}),B.strictObject({action:B.enum(["process","retry","cancel"]),migrationId:B.uuid()})]),Ij=B.discriminatedUnion("action",[B.strictObject({action:B.literal("preview"),from:B.uuid(),to:B.uuid(),after:B.uuid().optional()}),B.strictObject({action:B.literal("read"),migrationId:B.uuid(),status:Em.optional(),after:B.uuid().optional()}),B.strictObject({action:B.literal("list"),productId:B.string().min(1).max(120)})]);import{z as ft}from"zod";var ic=ft.iso.datetime({offset:!0}),Rm=ft.strictObject({internalId:ft.uuid(),productId:ft.string().min(1),name:ft.string(),version:ft.number().int().positive()}),t0=ft.strictObject({id:ft.uuid(),status:ft.literal("scheduled"),effectiveAt:ic,createdAt:ic,entityId:ft.string().nullable(),to:Rm,from:Rm.extend({customerProductId:ft.uuid(),status:ft.enum(["active","past_due","trialing"]),endsAt:ic.nullable()}).nullable(),scheduleId:ft.uuid().nullable(),providerManaged:ft.boolean()}),wj=ft.array(t0).max(100),Oj=ft.strictObject({customerProductId:ft.uuid()});import{z as Fi}from"zod";var n0=Fi.url().refine(e=>new URL(e).protocol==="https:"),Ej=Fi.strictObject({requestId:Fi.uuid()}),Tj=Fi.strictObject({url:n0,createdAt:Fi.iso.datetime()});import{z as Ye}from"zod";var km=Ye.object({id:Ye.uuid(),key:Ye.string().nullable(),label:Ye.string().min(1).max(80),description:Ye.string().max(300),category:Ye.string().min(1).max(40),tags:Ye.array(Ye.string().max(30)).max(10),surface:$s,source:Ye.enum(["official","private"]),document:Tt,revision:Ye.number().int().positive(),archived_at:Ye.string().nullable(),created_at:Ye.string()}).strict(),Nj=Ye.object({projectId:Ye.uuid(),environmentId:Ye.uuid(),label:Ye.string().trim().min(1).max(80),description:Ye.string().trim().max(300),category:Ye.string().trim().min(1).max(40),document:Tt}).strict(),Dj=Ye.object({projectId:Ye.uuid(),environmentId:Ye.uuid(),id:Ye.uuid(),revision:Ye.number().int().positive()}).strict();import{z as q}from"zod";import{z as Ee}from"zod";var Ui=Ae;function jm(e){let t={};for(let[n,r]of Object.entries(e.results??{})){let i=n.split(".");if(i.some(a=>["__proto__","constructor","prototype"].includes(a)))throw new Error("Reserved result path");let o=t;for(let a of i.slice(0,-1)){Object.hasOwn(o,a)||(o[a]={});let s=o[a];if(!s||typeof s!="object"||Array.isArray(s))throw new Error("Ambiguous result path");o=s}o[i[i.length-1]]=r}return{...e.attributes,parameters:e.parameters,answers:e.answers,results:t}}function oc(e,t){return Ca(jm(t),e,t.savedGroups)}function Mi(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 nt}from"zod";var zo=nt.discriminatedUnion("kind",[nt.object({kind:nt.literal("ledger"),cursor:xo}).strict(),nt.object({kind:nt.literal("billing"),cursor:nt.uuid()}).strict()]),r0=nt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Li=nt.record(nt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),nt.union([nt.string().max(500),nt.boolean(),nt.array(nt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),i0=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function ac(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>ac(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||i0.test(n)||ac(r,t+1)))}var o0=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,sn=nt.record(r0,Ae).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!ac(e)&&!o0.test(JSON.stringify(e)),"Credentials cannot be screen parameters");function Vj(e){let t=Object.create(null);for(let[n,r]of new URL(e).searchParams)nt.string().max(500).parse(r),Object.hasOwn(t,n)||(t[n]=r);return sn.parse(t),t}var Nm=nt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),sc=nt.array(nt.object({key:Nm,componentId:Nm,required:nt.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.key)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),$j=nt.object({bindings:sc,answers:Li}).strict();import{z as fr}from"zod";var Mn=fr.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"),Wo=fr.discriminatedUnion("source",[fr.strictObject({source:fr.literal("literal"),value:Ae}),fr.strictObject({source:fr.enum(["parameter","answer","attribute","result"]),key:fr.string().min(1).max(255),path:Mn.optional()})]);function Qo(e,t){if(!t)return e;for(let n of Mn.parse(t).split(".")){if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function cc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=e.source==="parameter"?t.parameters:e.source==="answer"?t.answers:e.source==="attribute"?t.attributes:t.results??{};if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(Ae.parse(Qo(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=Mn.parse(i).split("."),s=n;for(let l=0;l<a.length-1;l++){let u=a[l];if(Array.isArray(s)&&(!/^(0|[1-9]\d*)$/.test(u)||Number(u)>s.length))throw new Error("Invalid array binding index");Object.hasOwn(s,u)||Reflect.set(s,u,/^(0|[1-9]\d*)$/.test(a[l+1])?[]:{});let d=Reflect.get(s,u);if(!d||typeof d!="object")throw new Error("Nested input requires an object or array");if(Array.isArray(d)!==/^(0|[1-9]\d*)$/.test(a[l+1]))throw new Error("Nested input container does not match its path");s=d}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,cc(o,t))}return n}var Zo=Ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Fm=Ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),Yo=sn.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),uc=Ee.record(Zo,Ee.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),a0=Wo,Um=Ee.strictObject({type:Ee.literal("external_task"),endpointId:Ee.uuid(),taskKey:Zo,inputs:Ee.record(Zo,a0).refine(e=>Object.keys(e).length<=20),outputs:uc}),Mm=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"),Xj={maxAttempts:4,retryDelaySeconds:5,backoff:"fixed",requestTimeoutSeconds:8,timeoutSeconds:120},e2=Ee.strictObject({outcome:Ee.enum(["success","failure"]),data:Yo});function t2(e,t){let n=Yo.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]):typeof n[r]!==i)))throw new Error("Task data does not match its declared outputs");return n}function n2(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=cc(i,t);return Yo.parse(n)}var r2=Ee.discriminatedUnion("operation",[Ee.strictObject({operation:Ee.literal("signal"),runId:Ee.uuid(),nodeId:Fm,eventName:Zo,eventId:Ee.uuid(),data:Yo}),Ee.strictObject({operation:Ee.literal("read_results"),runId:Ee.uuid()})]),i2=Ee.strictObject({scope:Fe,runId:Ee.uuid(),eventId:Ee.uuid(),accepted:Ee.boolean()}),s0=Ee.record(Fm,Ui),o2=Ee.strictObject({scope:Fe,runId:Ee.uuid(),results:s0});import{z as ge}from"zod";var lc=ge.discriminatedUnion("type",[ge.strictObject({type:ge.literal("literal"),value:Ae}),ge.strictObject({type:ge.literal("feature"),featureKey:ge.string().min(1).max(128)})]),c0=ge.strictObject({requestId:ge.uuid(),decisionId:ge.uuid(),customerId:ge.uuid(),externalUserId:ge.string().min(1).max(255).nullable(),versionId:ge.uuid(),receiptId:ge.uuid(),value:Ae}),dc={funnelId:ge.uuid(),requestId:ge.uuid(),customer:Nr,customerData:Dr.optional(),attributes:Ft.refine(e=>!["parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"parameters, answers and results are reserved flow namespaces")},d2=ge.discriminatedUnion("operation",[ge.strictObject({operation:ge.literal("decide"),...dc}).refine(pr,mr),ge.strictObject({operation:ge.literal("read_decision"),decisionId:ge.uuid()}),ge.strictObject({operation:ge.literal("feature_config"),funnelId:ge.uuid()}),ge.strictObject({operation:ge.literal("configuration"),funnelId:ge.uuid()}),ge.strictObject({operation:ge.literal("report_used"),decisionId:ge.uuid(),eventId:ge.uuid(),occurredAt:ge.iso.datetime({offset:!0}),reference:ge.string().min(1).max(128).optional()})]),p2=ge.strictObject({scope:Fe,decisionId:ge.uuid(),requestId:ge.uuid(),status:ge.enum(["pending","completed","failed"]),decision:c0.nullable()}).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"),m2=ge.strictObject({scope:Fe,decisionId:ge.uuid(),eventId:ge.uuid(),source:ge.literal("caller_reported")});import{z as Ht}from"zod";import{z as gt}from"zod";var Lm=gt.union([gt.string(),gt.number().finite(),gt.boolean(),gt.null()]),u0=gt.union([Lm,gt.array(Lm).min(1).max(20)]),l0=gt.record(Mn,u0).refine(e=>Object.keys(e).length<=10),pc=gt.strictObject({path:Mn,type:gt.enum(["string","number","boolean","strings"]),nullable:gt.boolean().optional(),aggregation:gt.enum(["count","exists"]).optional(),where:l0.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 b2(e,t){return Object.fromEntries(Object.entries(e).map(([n,r])=>{let i=pc.parse(r),o=Qo(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(([l,u])=>{let d=Qo(c,l);return Array.isArray(u)?u.some(p=>p===d):u===d}));return[n,i.aggregation==="count"?s.length:s.length>0]}let a=i.type==="strings"?gt.array(gt.string()):i.type==="string"?gt.string():i.type==="number"?gt.number().finite():gt.boolean();return[n,a.parse(o)]}))}var d0=["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"],mc=Ht.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),p0=Wo,Bm=Ht.discriminatedUnion("type",[Um,Ht.strictObject({type:Ht.literal("claim_offer"),couponId:Ht.uuid()}),Ht.strictObject({type:Ht.literal("event"),event:mc}),Ht.strictObject({type:Ht.literal("api"),operation:Ht.enum(d0),inputs:Ht.record(Mn,p0).refine(e=>Object.keys(e).length<=40),resultKey:mc,outputs:Ht.record(mc,pc).refine(e=>Object.keys(e).length<=20)})]);function v2(e,t){return Dm(e,t)}import{z as m0}from"zod";var hn=m0.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");var ze=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),f0=q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),zt={id:ze,name:q.string().trim().min(1).max(80),position:q.strictObject({x:q.number().finite(),y:q.number().finite()}).optional()},g0={success:ze,cancel:ze,unavailable:ze,failure:ze},fc=q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),gc=q.enum(["same_window","new_window"]),h0=q.discriminatedUnion("type",[q.strictObject({...zt,type:q.literal("entry"),next:ze}),q.strictObject({...zt,type:q.literal("screen"),screenId:ze,presentation:An,outputs:q.record(ze,ze),offering:q.discriminatedUnion("source",[q.strictObject({source:q.literal("result"),key:hn}),q.strictObject({source:q.literal("fixed"),versionId:q.uuid()})]).optional()}),q.strictObject({...zt,type:q.literal("offering"),configuration:q.discriminatedUnion("source",[q.strictObject({source:q.literal("fixed"),versionId:q.uuid()}),q.strictObject({source:q.literal("feature"),featureKey:q.string().min(1).max(128)})]),resultKey:hn,next:ze}),q.strictObject({...zt,type:q.literal("coupon"),couponId:q.uuid(),resultKey:hn,next:ze}),q.strictObject({...zt,type:q.literal("output"),value:q.discriminatedUnion("type",[...lc.options,q.strictObject({type:q.literal("result"),key:hn}),q.strictObject({type:q.literal("selection"),screenId:ze,offeringKey:hn})])}),q.strictObject({...zt,type:q.literal("condition"),cases:q.array(q.strictObject({condition:St,target:ze})).min(1).max(50),default:ze}),q.strictObject({...zt,type:q.literal("feature"),featureKey:q.string().min(1).max(128),next:ze}),q.strictObject({...zt,type:q.literal("split"),experimentId:q.uuid(),routes:q.record(f0,ze).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ze}),q.strictObject({...zt,type:q.literal("action"),...g0,execution:Mm,action:Bm}),q.strictObject({...zt,type:q.literal("external_page"),url:fc,openIn:gc,opened:ze,failed:ze}),q.strictObject({...zt,type:q.literal("end"),outcome:q.enum(["completed","closed","ineligible","failed"]),output:lc.optional()}),q.strictObject({...zt,type:q.literal("wait"),wait:q.discriminatedUnion("type",[q.strictObject({type:q.literal("duration"),delaySeconds:q.number().int().min(1).max(2592e3),elapsed:ze}),q.strictObject({type:q.literal("event"),eventName:ze,outputs:uc,timeoutSeconds:q.number().int().min(1).max(2592e3),received:ze,timeout:ze})])})]),hc=q.strictObject({version:q.literal(4),entry:ze,nodes:q.array(h0).min(1).max(et.flowNodes)}),bc=hc.superRefine((e,t)=>{b0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Mr(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":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 b0(e,t){let n=[],r=new Map(e.nodes.map(u=>[u.id,u])),i=(u,d,p)=>{n.push(u),t?.({message:u,reason:d,path:p?["nodes",e.nodes.indexOf(p)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(u=>u.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(u=>u.type==="screen").length>et.pages||e.nodes.filter(u=>!["screen","entry","end","output"].includes(u.type)).length>et.logicNodes)&&i("Flow node limit exceeded","budget");let o=new Set;for(let u of e.nodes){for(let d of Mr(u))d===e.entry&&i("An entry cannot be a transition target","entryTarget",u),r.has(d)||i(`Missing target ${d}`,"missingTarget",u);u.type==="screen"&&(o.has(u.screenId)&&i("Every screen has exactly one node owner","screenOwner",u),o.add(u.screenId))}let a=new Set,s=new Set,c=new Set;function l(u){if(a.has(u)){i("Flow edges must not form a cycle","cycle",r.get(u));return}if(!(s.has(u)||!r.has(u))){a.add(u),c.add(u);for(let d of Mr(r.get(u)))l(d);a.delete(u),s.add(u)}}l(e.entry);for(let u of e.nodes)c.has(u.id)||i("Every node must be reachable from Entry","unreachable",u);return[...new Set(n)]}function _0(e,t){let n=e.cases.findIndex(r=>oc(r.condition,t));return{ruleIndex:n<0?null:n,target:n<0?e.default:e.cases[n].target}}function F2(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))throw new Error("Invalid screen output");a=i.outputs[n.output],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=_0(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");if(a=n.variantId===null?i.notParticipating:i.routes[n.variantId],!a)throw new Error("Unknown native Variant key");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(-et.pages),status:"running"},entered:[a],routed:s}}import{z as F}from"zod";function cn(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[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[i+1]);)i++;let s=t.slice(a,i+1);if(!/[eE]/.test(s))continue;let[c,l]=s.split(/[eE]/),u=c.replace(/^-/,""),d=u.replace(".","").length,p=(u.includes(".")?u.indexOf("."):d)+Number(l),g=p<=0?2-p+d:p>=d?p:d+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}function qm(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,o=(s,c=!1)=>{let l=r.find(u=>s===u||c&&s.startsWith(u+"."));i.add(l??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 l of Mi(c.condition))l.startsWith("results.")&&o(l.slice(8),!0)}if(e.type==="screen"&&e.offering?.source==="result"&&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==="result"&&o(s.key);let a=e.type==="output"?e.value:e.type==="end"?e.output:null;return a?.type==="result"&&o(a.key),a?.type==="selection"&&o(a.offeringKey),[...i]}import{z as E}from"zod";var Lr=E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Jo=e=>E.record(E.string(),Ae).refine(t=>cn(t)<=e,"Funnel evidence exceeds its byte budget"),K2=E.enum(["presentation","timer","event","operation"]),yc=E.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Sc=E.discriminatedUnion("type",[E.strictObject({type:E.literal("flag"),key:E.string().min(1).max(128)}),E.strictObject({type:E.literal("experiment"),id:E.uuid()}),E.strictObject({type:E.literal("saved_group"),id:E.uuid()}),E.strictObject({type:E.literal("config"),key:E.string().min(1).max(128)}),E.strictObject({type:E.literal("constant"),key:E.string().min(1).max(128)}),E.strictObject({type:E.literal("paywall_version"),id:E.uuid()}),E.strictObject({type:E.literal("offering_version"),id:E.uuid()}),E.strictObject({type:E.literal("reward"),id:E.uuid()})]),H2=E.strictObject({schemaVersion:E.literal(1),kind:yc,selector:Sc.nullable(),context:Jo(131072),contract:E.strictObject({version:E.number().int().positive(),evaluator:E.string().min(1).max(128),policyRevision:E.number().int().nonnegative()})}).refine(e=>cn(e)<=131072,"Node input exceeds its byte budget"),z2=E.strictObject({schemaVersion:E.literal(1),kind:yc,outcome:E.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Jo(131072),route:E.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Jo(131072)}).refine(e=>cn(e)<=131072,"Node result exceeds its byte budget"),W2=E.strictObject({schemaVersion:E.literal(1),operations:E.record(Lr,E.strictObject({attempts:E.number().int().nonnegative(),maxAttempts:E.number().int().min(1).max(5),deadlineAt:E.iso.datetime({offset:!0}),retryAt:E.iso.datetime({offset:!0}).nullable(),error:E.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:E.strictObject({type:Lr,id:E.uuid()}).nullable()}))}).refine(e=>cn(e)<=65536,"Execution state exceeds its byte budget"),gr={receiptId:E.uuid()},_c=E.iso.datetime({offset:!0}),Q2=E.discriminatedUnion("type",[E.strictObject({type:E.literal("node_entered"),details:E.strictObject({kind:yc})}),E.strictObject({type:E.literal("presentation_shown"),details:E.strictObject({...gr,source:E.literal("client"),occurredAt:_c.optional()})}),E.strictObject({type:E.literal("decision_accepted"),details:E.strictObject(gr)}),E.strictObject({type:E.literal("signal_received"),details:E.strictObject({signalId:E.uuid(),nodeId:Lr,eventName:Lr,data:Jo(8192),source:E.literal("server"),occurredAt:_c})}),E.strictObject({type:E.literal("signal_consumed"),details:E.strictObject({...gr,signalId:E.uuid()})}),E.strictObject({type:E.literal("wait_elapsed"),details:E.strictObject(gr)}),E.strictObject({type:E.literal("wait_timeout"),details:E.strictObject(gr)}),E.strictObject({type:E.literal("operation_completed"),details:E.strictObject({...gr,operation:Lr,reference:E.strictObject({type:Lr,id:E.uuid()}).nullable()})}),E.strictObject({type:E.literal("execution_recovered"),details:E.strictObject({generation:E.number().int().positive(),reason:E.enum(["interrupted","expired_lease","delivery_failed"])})}),E.strictObject({type:E.literal("execution_failed"),details:E.strictObject({generation:E.number().int().positive(),code:E.string().regex(/^[a-z_]{1,64}$/)})}),E.strictObject({type:E.literal("run_completed"),details:E.strictObject({outcome:E.enum(["completed","ineligible","failed"])})}),E.strictObject({type:E.literal("run_closed"),details:E.strictObject({source:E.enum(["client","server","expiry"])})}),E.strictObject({type:E.literal("treatment_used"),details:E.strictObject({...gr,source:E.enum(["client","server"]),occurredAt:_c,reference:E.string().min(1).max(128).optional()})})]);var Wt=F.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),y0=F.discriminatedUnion("type",[F.strictObject({id:Wt,type:F.literal("owned"),document:Tt.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")}),F.strictObject({id:Wt,type:F.literal("paywall"),paywallVersionId:F.uuid()})]),Vm=F.strictObject({type:F.enum(["string","number","boolean","strings","json"]),nullable:F.boolean()}),vc={kind:F.literal("funnel"),schemaVersion:F.literal(3),screens:F.array(y0).max(et.pages),references:F.record(Wt,Sc).refine(e=>Object.keys(e).length<=500),inputs:F.array(F.strictObject({key:Wt,screenId:Wt,componentId:Wt,required:F.boolean()})).max(et.questions),variables:F.record(hn,Vm).refine(e=>Object.keys(e).length<=et.logicNodes),outputSchema:Vm,execution:F.strictObject({runTimeoutSeconds:F.number().int().min(1).max(2592e3),maxTransitions:F.number().int().min(1).max(1e4)})},Bt=F.strictObject({...vc,graph:hc});function Gm(e,t){let n=(g,f,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:f}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),o=(g,f)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===f);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(f=>g!==f&&f.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function l(g,f){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(f)]);let h=s.get(g)??new Set;h.add(f.id),s.set(g,h)}for(let[g,f]of e.graph.nodes.entries()){let h=["graph","nodes",g],I=f.type==="feature"?f.featureKey:f.type==="offering"&&f.configuration.source==="feature"?f.configuration.featureKey:f.type==="output"&&f.value.type==="feature"?f.value.featureKey:f.type==="end"&&f.output?.type==="feature"?f.output.featureKey:null;if(I&&!o("flag",I)&&n("Flag selectors require an explicit GB resource reference","feature",h),f.type==="feature"&&l(f.featureKey,f),(f.type==="offering"||f.type==="coupon")&&l(f.resultKey,f),f.type==="action"&&f.action.type==="api"&&l(f.action.resultKey,f),f.type==="action"&&f.action.type==="external_task")for(let v of Object.keys(f.action.outputs))l(`${f.id}.${v}`,f);if(f.type==="wait"&&f.wait.type==="event")for(let v of Object.keys(f.wait.outputs))l(`${f.id}.${v}`,f);if(f.type==="split"&&!o("experiment",f.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),f.type==="coupon"&&!o("reward",f.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),f.type==="action"&&f.action.type==="claim_offer"&&!o("reward",f.action.couponId)&&n("Coupon claims require a Reward reference","coupon",h),f.type==="offering"&&f.configuration.source==="fixed"&&!o("offering_version",f.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),f.type==="screen"){let v=i.get(f.screenId);if(f.offering?.source==="fixed"&&!o("offering_version",f.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),v?.type==="paywall"&&f.offering&&n("Paywall owns its fixed Offering Version","offering",h),v?.type==="paywall"&&!o("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),v?.type==="owned"){Rr(v.document).some(R=>!R.complete)&&n("Owned screens require complete local content","translations",h);let S=new Set(v.document.actions.map(R=>R.id));(S.size!==Object.keys(f.outputs).length||Object.keys(f.outputs).some(R=>!S.has(R)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),fn(v.document.pages[0].root,R=>{!f.offering&&(R.type==="plan_picker"||(R.type==="stack"||R.type==="button")&&R.bind?.plan||R.type==="customer_data"&&["customer_plans","credit_packs"].includes(R.data.source))&&n("Product presentation requires an Offering Version","offering",h),R.type==="customer_data"&&Object.values(R.data.outputs??{}).some(D=>!S.has(D))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}if(f.type==="end"&&["completed","ineligible"].includes(f.outcome)&&!f.output&&n("Completed and ineligible ends require a declared output","output",h),f.type==="end"&&f.output?.type==="literal"&&!$m(e.outputSchema,f.output.value)&&n("Terminal output does not match outputSchema","output",h),f.type==="output"&&f.value.type==="literal"&&!$m(e.outputSchema,f.value.value)&&n("Terminal output does not match outputSchema","output",h),f.type==="condition")for(let v of f.cases){for(let S of si(v.condition))o("saved_group",S)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let S of Mi(v.condition))S.startsWith("answers.")&&!e.inputs.some(R=>R.key===S.slice(8))&&n("Unknown answer reference","answer",h)}}for(let[g,f]of e.graph.nodes.entries())for(let h of qm(f,c)){let S=function(R){if(R===f.id)return!0;if(v.has(R))return!1;v.add(R);let D=e.graph.nodes.find(be=>be.id===R);return D?(I.has(R)?D.type==="action"?[D.cancel,D.unavailable,D.failure]:D.type==="wait"&&D.wait.type==="event"?[D.wait.timeout]:[]:Mr(D)).some(S):!1};var p=S;if(!Object.hasOwn(e.variables,h)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let I=s.get(h)??new Set,v=new Set;(!I.size||S(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}(new Set(e.inputs.map(g=>g.key)).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,f]of e.inputs.entries()){let h=i.get(f.screenId),I=h?.type==="owned"?ki(h.document,f.componentId):null;(I?.type!=="stack"||!I.interaction||!["input","toggle","select","multiselect","tabs"].includes(I.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g])}let u=0,d=0;for(let g of e.screens)g.type==="owned"&&(fn(g.document.pages[0].root,()=>{u++}),d+=g.document.actions.length);(u>et.components||d>et.actions||cn(e)>et.documentBytes)&&n("Funnel document exceeds its budget","budget")}var Km=F.strictObject({...vc,graph:bc}).superRefine(Gm),Hm=F.strictObject({...vc,graph:bc,displayName:F.string().trim().min(1).max(80)}).superRefine(Gm);function $m(e,t){return t===null?e.nullable:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type)}var xc=F.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),Xo={requestId:F.uuid(),nodeId:Wt,visit:F.number().int().nonnegative(),revision:F.number().int().nonnegative(),customerToken:xc.optional()},S0=F.discriminatedUnion("type",[F.strictObject({type:F.literal("screen"),output:Wt,answers:Li,selection:F.record(Wt,F.union([F.string().max(200),F.boolean()])).optional()}),F.strictObject({type:F.literal("paywall_quote"),actionId:Wt,productVersionId:F.uuid(),offerId:F.uuid().optional(),nativeOffer:Dn.optional()}),F.strictObject({type:F.literal("paywall_confirm"),operationId:F.uuid()}),F.strictObject({type:F.literal("paywall_cancel"),operationId:F.uuid()}),F.strictObject({type:F.literal("client_action"),receiptId:F.uuid(),outcome:F.enum(["success","cancel","failure","opened","failed"])})]),x0=F.object({nodeId:Wt,visit:F.number().int().nonnegative(),revision:F.number().int().nonnegative(),components:F.record(Wt,F.object({resourceKey:F.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:F.number().int().min(1).max(1e5),after:zo.nullable(),filter:F.enum(["all","purchase","refund","source","usage","debt","settlement"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Bi=F.discriminatedUnion("operation",[F.strictObject({operation:F.literal("start"),funnelId:F.uuid(),requestId:F.uuid(),customer:Nr.optional(),customerData:Dr.optional(),locale:F.string().min(1).max(35),parameters:sn}).refine(pr,mr),F.strictObject({operation:F.literal("get"),data:x0.optional(),purchase:F.strictObject({receiptId:F.uuid(),operationId:F.uuid()}).optional(),customerToken:xc.optional()}),F.strictObject({operation:F.literal("resume"),requestId:F.uuid(),customerToken:xc.optional()}),F.strictObject({operation:F.literal("submit"),...Xo,input:S0}),F.strictObject({operation:F.literal("back"),...Xo}),F.strictObject({operation:F.literal("shown"),...Xo}),F.strictObject({operation:F.literal("close"),...Xo})]);function Ic(e,t){if(e.hidden)return null;if(e.id===t)return e;if(e.type!=="stack")return null;for(let n of e.children){let r=Ic(n,t);if(r)return r}return null}function I0(e,t,n,r,i){let o=e.graph.nodes.find(l=>l.id===t);if(o?.type!=="screen")throw new Error("Input is only accepted on a screen");let a=e.screens.find(l=>l.id===o.screenId),s=e.inputs.filter(l=>l.screenId===o.screenId),c={...r};for(let[l,u]of Object.entries(n)){let d=s.find(f=>f.key===l);if(!d||a?.type!=="owned")throw new Error("Unknown screen input");let p=Ic(a.document.pages[0].root,d.componentId);if(p?.type!=="stack"||!p.interaction)throw new Error("Input is unavailable");let g=p.interaction;switch(g.type){case"input":if(typeof u!="string"||u.length>g.maxLength)throw new Error("Invalid input text");if(u&&g.keyboard==="email"&&!F.email().safeParse(u).success)throw new Error("Invalid email");if(u&&g.keyboard==="url"&&!F.url().safeParse(u).success)throw new Error("Invalid URL");break;case"toggle":if(typeof u!="boolean")throw new Error("Invalid toggle value");break;case"select":case"tabs":if(typeof u!="string"||!p.children.some(f=>f.id===u&&!f.hidden))throw new Error("Invalid selected option");break;case"multiselect":if(!Array.isArray(u)||new Set(u).size!==u.length||u.length>g.max||i&&u.length<g.min||u.some(f=>!p.children.some(h=>h.id===f&&!h.hidden)))throw new Error("Invalid selected options");break;default:throw new Error("Component cannot accept input")}c[l]=u}if(i)for(let l of s){let u=c[l.key];if(l.required&&(u===void 0||u===""||Array.isArray(u)&&u.length===0))throw new Error(`Required input: ${l.key}`);u!==void 0&&!Object.hasOwn(n,l.key)&&I0(e,t,{[l.key]:u},{},!1);let d=a?.type==="owned"?Ic(a.document.pages[0].root,l.componentId):null;if(d?.type==="stack"&&d.interaction?.type==="multiselect"&&Array.isArray(u)&&u.length<d.interaction.min)throw new Error("Not enough selected options")}return c}import{z as Se}from"zod";import{z as v0}from"zod";var Ac=v0.enum(["local","remote"]);var A0=Se.strictObject({id:Se.uuid(),projectId:Se.uuid(),environmentId:Se.uuid(),name:Se.string().min(1).max(80),revision:Se.number().int().nonnegative(),evaluationMode:Ac,evaluationRevision:Se.number().int().nonnegative(),state:Se.enum(["active","paused","archived"]),publishedVersionId:Se.uuid().nullable(),updatedAt:Se.iso.datetime({offset:!0}),draft:Bt}),yN=Se.strictObject({rows:Se.array(A0).max(200),nextCursor:Se.uuid().nullable()}),SN=Se.discriminatedUnion("action",[Se.strictObject({action:Se.literal("setEvaluationMode"),id:Se.uuid(),revision:Se.number().int().nonnegative(),evaluationMode:Ac}),Se.strictObject({action:Se.literal("create"),requestId:Se.uuid(),name:Se.string().trim().min(1).max(80),document:Bt}),Se.strictObject({action:Se.literal("save"),id:Se.uuid(),revision:Se.number().int().nonnegative(),name:Se.string().trim().min(1).max(80),document:Bt}),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")&&cn(e.document)>et.documentBytes&&t.addIssue({code:"custom",path:["document"],message:"Funnel document exceeds its byte budget"})});function xN(e){let t=e==="en",n=Pm("popup",e);return n.name=t?"Welcome":"\u6B22\u8FCE",n.pages[0].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"},Km.parse({schemaVersion:3,references:{},variables:{},outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",inputs:[],screens:[{id:"welcome",type:"owned",document:n}],graph:{version:4,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 re}from"zod";var Br=re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),wc=re.enum(["running","waiting","completed","closed","ineligible","failed"]),w0=re.discriminatedUnion("type",[re.strictObject({type:re.literal("wait"),receiptId:re.uuid(),kind:re.enum(["timer","event","operation"]),deadline:re.iso.datetime({offset:!0}).nullable(),eventName:Br.optional()}),re.strictObject({type:re.literal("open_url"),receiptId:re.uuid(),url:fc,openIn:gc}),re.strictObject({type:re.literal("event"),receiptId:re.uuid(),event:Br})]),O0=re.strictObject({type:re.literal("funnel"),id:re.uuid(),versionId:re.uuid()}),zm=re.strictObject({type:re.literal("render"),url:Am}),Wm={id:Br,presentation:An,outputs:re.array(Br).max(250),inputs:sc,offeringKey:hn.optional(),capabilities:No,customerData:vp,dataCursors:re.record(Br,zo.nullable())},P0=re.strictObject({...Wm,content:re.discriminatedUnion("type",[zm,re.strictObject({type:re.literal("document"),document:Tt})])}),Oc=re.strictObject({id:re.uuid(),source:O0,revision:re.number().int().nonnegative(),visit:re.number().int().nonnegative(),nodeId:Br,nodeType:re.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","output"]),status:wc,stopped:re.boolean(),canBack:re.boolean(),authenticated:re.boolean(),locale:re.string().min(1).max(35),answers:Li,parameters:sn,variables:re.record(re.string(),Ae),output:Ae.nullable(),screen:P0.nullable(),paywall:re.strictObject({receiptId:re.uuid(),resolution:Lo,quote:Ai.nullable(),operation:Or.nullable(),purchaseRequestId:re.uuid().nullable()}).nullable(),instruction:w0.nullable(),pendingRequest:re.strictObject({requestId:re.uuid(),authenticationRequired:re.boolean()}).nullable(),runExpiresAt:re.iso.datetime({offset:!0}),credentialExpiresAt:re.iso.datetime({offset:!0}).nullable()}),C0=Oc.extend({screen:re.strictObject({...Wm,content:zm}).nullable()}),Qm=re.strictObject({scope:Fe,run:C0,purchase:re.strictObject({receiptId:re.uuid(),quote:Ai.nullable(),operation:Or.nullable()}).optional(),runToken:re.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:re.uuid().optional()});import{z as kt}from"zod";import{z as ea}from"zod";var LN=ea.strictObject({operation:ea.literal("renew_run"),runId:ea.uuid(),customerId:ea.uuid()}),Zm=Qm.refine(e=>!!e.runToken,"Renewal returns a credential");var zN=kt.discriminatedUnion("operation",[kt.strictObject({operation:kt.literal("campaign_decide"),...dc}).refine(pr,mr),kt.strictObject({operation:kt.literal("campaign_start"),funnelId:kt.uuid(),requestId:kt.uuid(),customer:Nr,customerData:Dr.optional(),locale:kt.string().min(1).max(35),parameters:sn,cooldownSeconds:kt.number().int().min(1).max(2592e3)}).refine(pr,mr)]),WN=kt.union([kt.strictObject({scope:Fe,suppressed:kt.literal(!0),reason:kt.enum(["frequency","in_progress"]),retryAt:kt.iso.datetime({offset:!0})}),Zm]);import{z as qe}from"zod";function Ym(e,t){let n=new Set,r=new Set,i=new Set,o=[];function a(d){for(let p of si(d))s(p)}function s(d){i.has(d)||!Object.hasOwn(t.savedGroups,d)||(i.add(d),o.push(()=>{let p=t.savedGroups[d];!Array.isArray(p)&&p.type==="condition"&&a(p.condition)}))}function c(d){a(d.condition);for(let p of d.parentConditions??[])l(p.id),a(p.condition)}function l(d,p=!1){if(!Object.hasOwn(t.features,d)){if(p)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.push(()=>{for(let g of t.features[d].rules??[]){c(g);for(let f of g.tracks??[])c(f.experiment)}}))}function u(d){if(!Object.hasOwn(t.experiments,d))throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),o.push(()=>c(t.experiments[d])))}for(let d of e.graph.nodes){d.type==="feature"&&l(d.featureKey,!0),d.type==="split"&&u(d.experimentId),d.type==="condition"&&d.cases.forEach(g=>a(g.condition)),d.type==="offering"&&d.configuration.source==="feature"&&l(d.configuration.featureKey,!0);let p=d.type==="output"?d.value:d.type==="end"?d.output:null;p?.type==="feature"&&l(p.featureKey,!0)}for(let d=0;d<o.length;d++)o[d]();return{...t,features:Object.fromEntries([...n].map(d=>[d,t.features[d]])),experiments:Object.fromEntries([...r].map(d=>[d,t.experiments[d]])),savedGroups:Object.fromEntries([...i].map(d=>[d,t.savedGroups[d]]))}}var qi=qe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Xm=qe.strictObject({entry:qi,nodes:qe.array(qe.strictObject({id:qi,type:qe.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","output"]),outputs:qe.record(qe.string(),qi),resources:qe.strictObject({screenId:qi.optional(),paywallVersionId:qe.uuid().optional(),couponId:qe.uuid().optional(),experimentId:qe.uuid().optional(),featureKey:qe.string().optional(),offeringVersionId:qe.uuid().optional()})})).min(1).max(500)}),Jm={scope:Fe,funnelId:qe.uuid(),versionId:qe.uuid(),evaluationRevision:qe.number().int().nonnegative(),expiresAt:qe.iso.datetime({offset:!0}).nullable(),topology:Xm},E0=qe.discriminatedUnion("evaluationMode",[qe.strictObject({...Jm,evaluationMode:qe.literal("local"),growth:gn,conditions:qe.record(qi,qe.array(qe.strictObject({condition:St,port:qe.string()})))}),qe.strictObject({...Jm,evaluationMode:qe.literal("remote")})]);function T0(e){return Xm.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":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let i=e.screens.find(o=>o.id===t.screenId);i?.type==="paywall"&&(r.paywallVersionId=i.paywallVersionId)}break;case"condition":t.cases.forEach((i,o)=>{n[`case:${o}`]=i.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 i of["success","cancel","unavailable","failure"])n[i]=t[i];t.action.type==="claim_offer"&&(r.couponId=t.action.couponId);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}return t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r}})})}function iD(e){let t=Hm.parse(e.document),n=e.evaluationMode==="local"?gn.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:T0(t)};return E0.parse(e.evaluationMode==="remote"?r:{...r,growth:Ym(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}`}))]))})}import{z as L}from"zod";var tf={commands:et.flowNodes*4,receipts:et.flowNodes*2,requestBytes:et.documentBytes+2e6},qr=L.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ef={requestId:L.uuid(),nodeId:qr,visit:L.number().int().nonnegative(),revision:L.number().int().nonnegative()},R0=L.union([Bi.options[3].omit({customerToken:!0}),Bi.options[4].omit({customerToken:!0}),Bi.options[5].omit({customerToken:!0}),Bi.options[6].omit({customerToken:!0}),L.strictObject({operation:L.literal("wait"),...ef,result:L.enum(["elapsed","received","timeout"])}),L.strictObject({operation:L.literal("simulate"),...ef,outcome:L.enum(["success","cancel","failure","unavailable"])})]),Pc=L.enum(["success","cancel","failure","unavailable","pending"]),Cc=L.strictObject({seed:L.uuid(),now:L.iso.datetime({offset:!0}),locale:L.string().min(2).max(35),currency:W,parameters:sn,attributes:L.record(L.string(),Ui).refine(e=>Object.keys(e).length<=100),authenticated:L.boolean(),holdings:L.enum(["sample","empty"]),results:L.record(L.string(),Ae).optional(),outcomes:L.record(qr,Pc),variants:L.record(qr,L.string().min(1).max(128).nullable())}),Ec=L.strictObject({schemaVersion:L.literal(1),growth:gn,paywalls:L.record(L.uuid(),Mo),offerings:L.record(L.uuid(),Cr),surfaces:L.record(qr,Ae)}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=1e6,"Preview dependencies exceed their byte budget"),k0=L.array(L.strictObject({command:R0,authenticated:L.boolean(),outcome:Pc})).max(tf.commands),j0=L.discriminatedUnion("type",[L.strictObject({type:L.literal("draft"),document:Bt}),L.strictObject({type:L.literal("snapshot"),id:L.uuid()})]),bD=L.strictObject({previewId:L.uuid(),source:j0,scenario:Cc,journal:k0,dependencySnapshot:Ec.optional()}),_D=L.strictObject({mode:L.literal("simulation"),run:Oc,dependencySnapshot:Ec,traceTruncated:L.boolean(),trace:L.array(L.strictObject({nodeId:qr,visit:L.number().int().nonnegative(),type:L.enum(["entered","shown","assigned","feature_evaluated","action","closed","wait_elapsed","wait_timeout","wait_received"]),details:L.record(L.string(),L.union([L.string(),L.number(),L.boolean(),L.null()]))})).max(2e3),receipts:L.array(L.strictObject({id:L.uuid(),nodeId:qr,visit:L.number().int().nonnegative(),outcome:Pc})).max(tf.receipts)}),yD=L.strictObject({id:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),document:Bt,scenario:Cc,dependencySnapshot:Ec,expiresAt:L.iso.datetime({offset:!0})}),SD=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),requestId:L.uuid(),document:Bt,scenario:Cc}),L.strictObject({action:L.literal("revoke"),id:L.uuid()})]);import{z as Ie}from"zod";var vD=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 Tc={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 OD(e,t,n=[]){let r=Yn(t)??"en",[i,...o]=r.split("-"),a=i==="zh"&&!o.includes("Hans")&&o.some(f=>["Hant","TW","HK","MO"].includes(f))?"zh-Hant":i,s=Tc[a]??Tc.en,c=Tc[a]?r:"en",l=f=>new Intl.NumberFormat(c).format(f),u=f=>new Intl.DateTimeFormat(c,{dateStyle:"medium",timeStyle:"short",timeZone:"UTC"}).format(new Date(f))+" UTC",d=[e.appliesTo.type==="all"?s[0]:`${s[1]}${n.length?`: ${n.slice(0,3).join(", ")+(n.length>3?` (+${l(n.length-3)})`:"")}`:""}`,e.eligibility.firstPurchaseOnly?s[3]:s[2],Object.keys(e.eligibility.condition).length?`${s[4]}${nf(e.eligibility.condition)?`: ${nf(e.eligibility.condition)}`:""}`:null].filter(Boolean).join(" \xB7 "),p=[e.startsAt?`${s[5]}: ${u(e.startsAt)}`:null,e.endsAt?`${s[6]}: ${u(e.endsAt)}`:s[7]].filter(Boolean).join(" \xB7 "),g=[d,p,`${s[8]}: ${l(e.grantWindowHours)} ${s[9]}`,`${s[10]}: ${l(e.perCustomerLimit)}`,e.totalLimit===null?null:`${s[11]}: ${l(e.totalLimit)}`].filter(Boolean).join(" \xB7 ");return{eligibility:d,validity:p,terms:g}}function nf(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 Rc={"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 rf(e){return e.actions.map(t=>t.properties.templateKey).find(t=>typeof t=="string"&&t.startsWith("popup-coupon-"))}function TD(e,t){let n=rf(e);if(!n||!Object.hasOwn(Rc,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 RD(e){let t=rf(e),n=t?Rc[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 te}from"zod";var Qt=te.string().min(1).max(255),Ln=te.number().finite().nonnegative(),of=te.strictObject({properties:te.record(te.string().min(1).max(64),te.union([te.string().min(1).max(128),te.number().finite(),te.boolean()]).transform(String).pipe(te.string())).refine(e=>Object.keys(e).length>=1&&Object.keys(e).length<=4)}),N0=te.strictObject({feature_id:Qt,enabled:te.boolean().default(!1),threshold:te.number().finite(),quantity:te.number().finite().min(1),purchase_limit:te.strictObject({interval:te.enum(["hour","day","week","month"]),interval_count:te.number().finite().min(1).default(1),limit:te.number().finite().min(1)}).optional(),invoice_mode:te.boolean().optional()}),D0=te.strictObject({feature_id:Qt.optional(),enabled:te.boolean().default(!1),limit_type:te.enum(["absolute","usage_percentage"]).optional(),overage_limit:Ln.optional(),skip_overage_billing:te.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"),F0=te.strictObject({feature_id:Qt,enabled:te.boolean().default(!0),limit:Ln,interval:te.enum(["day","week","month","year"]),anchor:te.enum(["billing_cycle","utc"]).optional(),filter:of.optional()}),U0=te.strictObject({feature_id:Qt.optional(),enabled:te.boolean().default(!0),threshold:Ln,threshold_type:te.enum(["usage","usage_percentage","remaining","remaining_percentage"]),basis:te.enum(["balance","included","recurring","usage_limit"]).default("balance"),filter:of.optional(),name:te.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"),M0=te.strictObject({feature_id:Qt,enabled:te.boolean().default(!1)}),L0=te.strictObject({auto_topups:te.array(N0).nullable(),spend_limits:te.array(D0).nullable(),usage_limits:te.array(F0).nullable(),usage_alerts:te.array(U0).nullable(),overage_allowed:te.array(M0).nullable()}),DD=L0.omit({auto_topups:!0}),B0=jr,FD=te.strictObject({internal_id:te.uuid(),id:Qt.nullable(),project_id:te.uuid(),environment_id:te.uuid(),name:te.string().max(80).nullable(),email:te.string().max(254).nullable(),metadata:B0.nullable(),created_at:te.number().finite().nonnegative().max(864e13)}),UD=te.strictObject({id:Qt,internal_product_id:Qt,product_id:Qt.nullable(),status:te.enum(["scheduled","pending","active","past_due","expired","unknown","trialing","paused"]),canceled_at:Ln.nullable(),free_trial_id:Qt.nullable(),trial_ends_at:Ln.nullable(),starts_at:Ln.nullable(),access_starts_at:Ln.nullable(),ended_at:Ln.nullable(),product:te.strictObject({internal_id:Qt,id:Qt,name:te.string(),version:te.number().int().positive(),is_add_on:te.boolean()})});function qD(e,t,n=[]){let r={nodes:{}},i=t.startsWith("zh"),o=(s,c)=>i?s:c,a=(s,c,l,u,d=[])=>({id:s,label:c,value:l,status:u,detail:d,facts:[]});return Pt(e,s=>{if(s.type!=="customer_data")return;let c={...Ap(s.data.source),status:"ready",stale:!1,preview:!0};if(s.data.source==="credit_balance"){let l=s.data.resourceKey??n[0]?.key??"credits";c.resources=[{key:l,name:n.find(u=>u.key===l)?.label??o("\u521B\u4F5C\u79EF\u5206","Creative credits"),spendable:"3,840",available:"4,040",reserved:"200",expiry:o("1,200 \xB7 2026\u5E7411\u67081\u65E5","1,200 \xB7 November 1, 2026"),sources:[a("sample-monthly",o("\u4F1A\u5458\u6708\u5EA6\u79EF\u5206","Monthly membership credits"),"2,640",o("\u53EF\u7528","Available")),a("sample-pack",o("\u8D2D\u4E70\u79EF\u5206\u5305","Purchased credit pack"),"1,200",o("\u53EF\u7528","Available"))],sourceCount:2,sourcePage:1,hasNextSources:!1,hasPreviousSources:!1}]}else s.data.source==="credit_transactions"?(c.rows=[a("sample-usage-1",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67083\u65E5 09:42","Oct 3, 09:42")]),a("sample-usage-2",o("\u89C6\u9891\u751F\u6210","Video generation"),"",o("\u9884\u6263","Reserved"),[o("10\u67083\u65E5 09:30","Oct 3, 09:30")]),a("sample-usage-3",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u9000\u56DE","Refund"),[o("10\u67082\u65E5 16:10","Oct 2, 16:10")]),a("sample-usage-4",o("\u89C6\u9891\u751F\u6210","Video generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67082\u65E5 15:24","Oct 2, 15:24")]),a("sample-usage-5",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67082\u65E5 14:08","Oct 2, 14:08")])].slice(0,s.data.pageSize),c.rows.forEach((l,u)=>{l.facts=[{label:o("\u521B\u4F5C\u79EF\u5206","Creative credits"),value:["12","180","12","180","24"][u]}]})):s.data.source==="membership"?c.rows=[a("sample-plan",o("\u4E13\u4E1A\u7248 \xB7 \u6708\u4ED8","Pro \xB7 Monthly"),"",o("\u6709\u6548","Active"),[o("\u5F53\u524D\u5468\u671F\u7ED3\u675F \xB7 2026\u5E7411\u67081\u65E5","Current period ends \xB7 November 1, 2026")])]:s.data.source==="customer_plans"?c.rows=[a("sample-free",o("\u57FA\u7840\u7248","Starter"),o("\u514D\u8D39","Free"),o("\u53EF\u9009\u62E9","Available")),a("sample-pro",o("\u4E13\u4E1A\u7248","Pro"),o("$29 / \u6708","$29 / month"),o("\u5F53\u524D\u5957\u9910","Current plan")),a("sample-team",o("\u56E2\u961F\u7248","Team"),o("$79 / \u6708","$79 / month"),o("\u53EF\u9009\u62E9","Available"))].slice(0,s.data.pageSize):s.data.source==="billing_controls"?c.rows=[a("sample-control",o("\u6708\u5EA6\u7528\u91CF\u4E0A\u9650","Monthly usage limit"),"240 / 1,000",o("\u793A\u4F8B \xB7 \u672A\u6388\u6743\u4ED8\u6B3E","Sample \xB7 Payments not authorized"),[o("\u4EC5\u5C55\u793A\u793A\u4F8B\uFF0C\u9884\u89C8\u4E0D\u4F1A\u542F\u7528\u81EA\u52A8\u5145\u503C\u6216\u540E\u4ED8\u8D39\u3002","Preview does not authorize auto top-ups or postpaid billing.")])]:s.data.source==="billing"?c.rows=[{...a("sample-invoice","GROW-2026-001","$29.00",o("\u5DF2\u652F\u4ED8","Paid"),["October 1, 2026"]),billingActions:[{action:"invoice_open",label:o("\u67E5\u770B\u53D1\u7968","View invoice")}]}]:s.data.source==="credit_packs"?c.rows=[a("sample-pack-small",o("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12","",[o("1,200 \u79EF\u5206 \xB7 90 \u5929\u6709\u6548","1,200 credits \xB7 90 days validity")]),a("sample-pack-large",o("\u521B\u4F5C\u6269\u5C55\u5305","Creative expansion"),"$40","",[o("5,000 \u79EF\u5206 \xB7 180 \u5929\u6709\u6548","5,000 credits \xB7 180 days validity")])].slice(0,s.data.pageSize).map((l,u)=>({...l,...s.data.allowPurchase?{purchaseId:`10000000-0000-4000-8000-${String(u+1).padStart(12,"0")}`}:{}})):s.data.source==="credit_pack_orders"?c.rows=[a("sample-order",o("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12",o("\u5DF2\u4ED8\u6B3E","Paid"),["2026-10-01 12:30"])]:c.rows=[a("sample-offer",o("\u4F1A\u5458\u7EED\u8D39\u4F18\u60E0","Membership renewal offer"),"",o("\u53EF\u7528","Available"),[o("2026\u5E7411\u67081\u65E5\u5230\u671F","Expires November 1, 2026")])];r.nodes[s.id]=c}),r}import{z as Te}from"zod";import{z as pe}from"zod";var q0=pe.enum(["customer","coupon","audience"]),V0=pe.enum(["name","description","email","metadata","tags","config","status","terms","codes","content"]),ta=pe.object({baseRevision:pe.number().int().nonnegative(),latestRevision:pe.number().int().nonnegative(),mode:pe.enum(["merge","use_latest"]),decisions:pe.array(pe.object({field:V0,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),af=pe.number().int().nonnegative().nullable(),$0=pe.object({resource:q0,id:pe.uuid(),projectId:pe.uuid(),environmentId:pe.uuid(),fromRevision:af,toRevision:af,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:ta.safeExtend({source:pe.literal("client")}).nullable()}),G0=pe.object({createdAt:pe.iso.datetime({offset:!0}),id:pe.uuid()}).strict(),GD=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:$0})),nextCursor:G0.nullable()});var QD={type:"condition",condition:{}},ZD=Te.strictObject({id:Te.uuid(),name:Te.string().min(1).max(80),description:Te.string().max(500),config:po,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})}),YD=Te.discriminatedUnion("action",[Te.strictObject({action:Te.literal("save"),id:Te.uuid().nullable(),audit:ta.nullable().optional(),revision:Te.number().int().min(0),name:Te.string().trim().min(1).max(80),description:Te.string().max(500),config:po}),Te.strictObject({action:Te.literal("archive"),id:Te.uuid(),audit:ta.nullable().optional(),revision:Te.number().int().min(1)})]),K0=Te.object({id:Te.uuid(),name:Te.string().nullable(),external_user_id:Te.string(),attributes:Ft,created_at:Te.iso.datetime({offset:!0})}),JD=Te.object({customers:K0.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)});import{z as Vi}from"zod";var nF=Vi.object({defaultLocale:en,locales:Vi.record(en,Vi.object({name:Vi.string().max(80),description:Vi.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 rF(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=mo([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 sf="#172033",na="#667085",H0="#E2E6EE",z0="#2C3C96",Ct=e=>({top:e,right:e,bottom:e,left:e}),ht=e=>({type:"color",color:e}),qt=class{constructor(t,n={}){this.name=t;this.design=n}name;design;zh={};en={};text(t,n,r,i=13,o=na,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=H0){return{id:t,type:"divider",style:{background:ht(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":na,{text:{size:11,color:a?"#A9B4CB":na,letterSpacing:1.4,weight:600}}),this.text("heading",t,n,28,a?"#FFFFFF":sf),this.text("description",r,i,14,a?"#A9B4CB":na)],{gap:12,width:660,grow:!0}),...o?[o]:[]],{gap:32},!0)}document(t,n=!1){return Tt.parse({kind:"screen",schemaVersion:4,name:this.name,surface:"page",presentation:{type:"fullscreen"},theme:{primary:z0,background:n?"#101A30":"#F5F6FA",text:sf,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 ia="#19202E",W0="#667080",kc="#2C3C96",cf="#DDE2E9",uf="#F0F3FA",Q0=(e=72,t=ia)=>({text:{size:e,color:t,weight:600,font:"system"}}),ra=(e,t=1)=>({width:e,grow:t}),Z0={background:ht("#FFFFFF"),shape:{type:"rect",radius:10}};function Y0(e){return new qt(e,{theme:{background:"#FFFFFF",text:ia,primary:kc},width:1184,gap:32,padding:{top:24,right:24,bottom:40,left:24}})}function J0(e,t,n,r,i){let o=e.text("wordmark","GROW / \u8D26\u6237","GROW / ACCOUNT",13,kc,{text:{size:13,color:kc,weight:700,letterSpacing:.8}});return e.stack("page_header",[o,e.text("heading",t,n,40,ia,{text:{size:40,color:ia,weight:700,lineHeight:1.18,letterSpacing:-1.4}}),e.text("description",r,i,14,W0)],{gap:12,padding:{top:8,right:0,bottom:8,left:0}})}function lf(){let e="#FAF7F0",t="#302923",n="#A63C25",r="#73665A",i=new qt("\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 df(){let e="#182C4A",t="#596B83",n="#CCD6E4",r=new qt("\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:Ct(28),background:ht("#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:Ct(28),background:ht("#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:Ct(24),background:ht("#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:Ct(24),background:ht("#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:Ct(24),background:ht("#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 pf(){let e="#253F34",t="#F5F3EC",n="#5C6A60",r="#DBE8B8",i=new qt("\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,l=n)=>i.text(a,s,c,12,l,{text:{size:12,color:l,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:Ct(32),background:ht(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:Ct(28),background:ht(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 mf(){let e=Y0("\u521B\u4F5C\u5DE5\u4F5C\u533A");return e.document([J0(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,{...ra(784,2),...Q0(80)}),e.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!1,{...ra(328),background:ht(uf),padding:Ct(24),shape:{type:"rect",radius:10}})],{gap:48,padding:{top:12,right:0,bottom:8,left:0}},!0),e.rule("workspace_rule",cf),e.stack("studio_workspace",[e.widget("transactions","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",!1,ra(784,2)),e.stack("credit_shop",[e.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!0),e.rule("shop_rule",cf),e.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0)],{...ra(328),...Z0,padding:Ct(24),gap:24,background:ht(uf)})],{gap:48},!0)])}function ff(){return mf()}var bn=(e,t=1)=>({width:e,grow:t}),oa=(e=16)=>({shape:{type:"rect",radius:e}}),at=(e,t,n="system")=>({text:{color:e,...t?{size:t,font:n,weight:500}:{}}}),wn=(e,t,n=e)=>({top:e,right:t,bottom:n,left:t});function X0(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 ex(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 $i(e,t,n,r,i,o="system"){let a=e.stack("masthead",[X0(e,t,n,r,o),ex(e,"scope","\u4E2A\u4EBA\u8D26\u6237","PERSONAL ACCOUNT",i)],{gap:20},!0);return a.justify="between",a.align="center",a}function gf(e,t,n=!1,r=5){let i=e.widget("activity","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",n,at(t));return i.data.pageSize=r,i}function tx(){let e="#171D1A",t="#F2F5ED",n="#9EADA2",r="#D5E7B0",i=new qt("\u6697\u7EFF\u79EF\u5206\u53F0",{theme:{background:e,text:t,primary:e},width:1120,gap:32,padding:wn(32,24,48)});return i.document([$i(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,at(t,96)),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,at(t))],{...bn(680,2),gap:32,padding:wn(20,0,12)}),i.stack("purchase_sheet",[i.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!1,at(e))],{...bn(328),background:ht(r),padding:Ct(24),...oa(20)})],{gap:72},!0),i.rule("activity_rule","#354039"),gf(i,t,!1,4)])}function nx(){let e="#302C26",t="#7D766B",n="#D8D1C5",r=new qt("\u8D26\u6237\u6863\u6848",{theme:{background:"#F7F3EB",text:e,primary:"#84503B"},width:1080,gap:32,padding:wn(40,24,48)});return r.document([$i(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,at(e,96,"serif"))],{...bn(628,2),padding:wn(12,0),gap:24}),r.stack("membership_column",[r.widget("membership","membership","\u4F1A\u5458\u72B6\u6001","Membership",!1,at(e)),r.widget("offers","offer_history","\u8D26\u6237\u4F18\u60E0","Your offers",!0,at(e))],{...bn(356),gap:20,padding:wn(12,0)})],{gap:96},!0),r.rule("orders_rule",n),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Purchases",!1,at(e))])}function rx(){let e="#223E33",t="#687C70",n="#254A3B",r="#F7F9F5",i=new qt("\u4F1A\u5458\u7A7A\u95F4",{theme:{background:r,text:e,primary:n},width:1120,gap:32,padding:wn(32,24,48)});return i.document([$i(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,at("#F4F7F0"))],{...bn(640,2),gap:24,background:ht(n),padding:Ct(32),...oa(20)}),i.stack("credit_context",[i.widget("balance","credit_balance","\u8D26\u6237\u79EF\u5206","Account credits",!0,at(e,64))],{...bn(400),background:ht("#E9EFE5"),padding:Ct(28),...oa(20)})],{gap:24},!0),i.widget("plans","customer_plans","\u65B9\u6848\u4E0E\u4EF7\u683C","Plans & pricing",!1,at(e)),i.rule("offer_rule","#D5DFD3"),i.widget("offers","offer_history","\u6211\u7684\u4F18\u60E0","Your offers",!0,at(e))])}function ix(){let e="#23262B",t="#797E87",n="#DFE2E7",r=new qt("\u7528\u91CF\u8D26\u518C",{theme:{background:"#FFFFFF",text:e,primary:e},width:1160,gap:28,padding:wn(32,24,48)});return r.document([$i(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,{...bn(688,2),...at(e,56,"mono")}),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,{...bn(372),...at(e)})],{gap:72,padding:wn(4,0,8)},!0),r.rule("activity_rule",n),gf(r,e),r.rule("order_rule",n),r.widget("orders","credit_pack_orders","\u79EF\u5206\u8D2D\u4E70","Credit purchases",!0,at(e))])}function ox(){let e="#3F3029",t="#8B766A",n="#A34525",r=new qt("\u79EF\u5206\u8865\u7ED9",{theme:{background:"#FEFAF5",text:e,primary:n},width:1160,gap:32,padding:wn(32,24,48)});return r.document([$i(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,at(e,56)),r.rule("context_rule","#DBC5B5"),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,at(e))],{...bn(304),gap:28,padding:Ct(24),background:ht("#F1E5D9"),...oa(16)}),r.stack("purchase_catalog",[r.widget("packs","credit_packs","\u53EF\u8D2D\u4E70\u7684\u79EF\u5206\u5305","Available credit packs",!1,at(e))],{...bn(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,at(e))])}function hf(){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:tx},{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:nx},{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:rx},{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:ff},{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:ix},{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:ox}].map(({create:e,...t})=>({...t,document:e()}))}function ax(){return df()}function sx(){return lf()}function cx(){return pf()}function hF(){return[...hf(),{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:ax()},{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:sx()},{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:cx()}]}import{z as jt}from"zod";var bf=jt.object({id:jt.string().min(1).max(136),name:jt.string().min(1).max(128),type:jt.enum(["entry","condition","feature"])}).strict(),ux=jt.object({id:jt.uuid(),name:jt.string().min(1).max(80),status:jt.enum(["draft","published","archived"]),draftNodes:jt.array(bf).max(600),publishedNodes:jt.array(bf).max(600),runningVersions:jt.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"),yF=jt.object({rows:jt.array(ux).max(50),nextCursor:jt.uuid().nullable()}).strict();import{z as xe}from"zod";var At=xe.number().int().nonnegative(),_f=xe.strictObject({at:xe.iso.datetime({offset:!0}),id:xe.uuid()}),AF=xe.strictObject({versionId:xe.uuid().nullable(),from:xe.iso.datetime({offset:!0}).nullable(),to:xe.iso.datetime({offset:!0}).nullable(),after:_f.nullable()}).refine(e=>!e.from||!e.to||Date.parse(e.from)<Date.parse(e.to),"Time range must increase"),wF=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:At,completed:At,closed:At,failed:At,waiting:At,paid:At}),decisions:xe.strictObject({queries:At,completed:At,reportedUsed:At,pending:At,failed:At}),revenue:xe.array(xe.strictObject({currency:W,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:At,completed:At,shown:At,waiting:At})).max(1e4),recentRuns:xe.array(xe.strictObject({id:xe.uuid(),versionId:xe.uuid(),customerId:xe.uuid(),status:wc,nodeId:xe.string(),visit:At,createdAt:xe.iso.datetime({offset:!0}),updatedAt:xe.iso.datetime({offset:!0})})).max(100),nextCursor:_f.nullable()});import{z as Bn}from"zod";var TF=Bn.object({requestId:Bn.uuid(),coupon:jl,audienceId:Bn.uuid().nullable(),productVersionId:Bn.uuid().optional(),presentation:An,locale:Bn.enum(["en","zh-CN"])}).strict(),RF=Bn.object({couponId:Bn.uuid(),funnelId:Bn.uuid()}).strict();import{z as we}from"zod";var bt=we.number().int().nonnegative(),aa=we.string().regex(/^-?\d+$/),lx=we.object({currency:W,grossMinor:aa,refundMinor:aa,netMinor:aa,purchases:bt,refunds:bt}).strict(),DF=we.object({snapshotAt:we.iso.datetime({offset:!0}),customers:we.object({total:bt,created:bt,paid:bt}).strict(),memberships:we.object({active:bt,trial:bt,pastDue:bt,ended:bt}).strict(),runs:we.object({started:bt,completed:bt,closed:bt,paid:bt}).strict(),revenue:we.array(lx).max(100),unknownMoney:bt,funnels:we.array(we.object({id:we.uuid(),name:we.string(),started:bt,completed:bt,paid:bt}).strict()).max(50),daily:we.array(we.object({date:we.iso.date(),currency:W,netMinor:aa}).strict()).max(9e3)}).strict(),FF=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 _t}from"zod";var yf=_t.discriminatedUnion("provider",[_t.strictObject({provider:_t.literal("apple"),orderId:_t.uuid(),receiptId:_t.uuid(),signedTransaction:_t.string().min(1).max(131072)}),_t.strictObject({provider:_t.literal("google"),orderId:_t.uuid(),receiptId:_t.uuid(),purchaseToken:_t.string().min(1).max(16384)})]),Sf=_t.strictObject({orderId:_t.uuid(),receiptId:_t.uuid(),transactionIds:_t.array(_t.string().min(1).max(255)).min(1).max(50),membership:_t.boolean()});var $F=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:yf.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),GF=Zt.strictObject({scope:Fe,requestId:Zt.uuid(),orderId:Zt.uuid(),receiptId:Zt.uuid(),orderStatus:Zt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:Zt.boolean(),nativeCompletion:Sf.optional()});import{z as dx}from"zod";var px=km.extend({document:dx.union([Tt.refine(e=>e.pages.length===1,"Use a single owned screen template"),Bt.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 XF(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}}function mx(e,t){let n=structuredClone(px.parse(e).document);if(n.kind==="funnel"){let l=function(u){if(Array.isArray(u)){u.forEach(l);return}if(!u||typeof u!="object")return;let d=u;d.type==="experiment-ref"&&(d.experimentId=c),d.$savedGroup&&typeof d.$savedGroup=="object"&&(d.$savedGroup.id=c),typeof d.$inGroup=="string"&&(d.$inGroup=c),typeof d.$notInGroup=="string"&&(d.$notInGroup=c),Object.values(d).forEach(l)};var s=l;let c="00000000-0000-0000-0000-000000000000";for(let u of Object.values(n.references))"id"in u&&(u.id=c);for(let u of n.graph.nodes)u.type==="condition"&&u.cases.forEach(d=>l(d.condition));for(let u of n.screens)u.type==="owned"&&xf(u.document);return Bt.parse({...n,screens:n.screens.map(u=>u.type==="owned"?{...u,document:{...u.document,strings:{...u.document.strings,defaultLocale:Ks(u.document,[t])}}}:u),graph:{...n.graph,nodes:n.graph.nodes.map(u=>u.type==="split"?{...u,experimentId:"00000000-0000-0000-0000-000000000000"}:u.type==="offering"?{...u,configuration:u.configuration.source==="fixed"?{source:"fixed",versionId:c}:u.configuration}:u.type==="coupon"?{...u,couponId:c}:u)}})}let r={...n,strings:{...n.strings,defaultLocale:Ks(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={};r.actions=r.actions.map((c,l)=>{let u=`action_${l}`;return o[c.id]=c.close?"closed":"done",c.type==="open_url"?(o[c.id]=u,i.push({id:u,name:c.id,type:"output",value:{type:"literal",value:{intent:"open_url",url:c.url}}})):c.type==="claim_offer"&&(o[c.id]="unconnected"),{id:c.id,type:"event",event:c.id,properties:{},close:!1}}),xf(r),i.push({id:"screen",name:e.label,type:"screen",screenId:"screen",presentation:e.surface==="page"?{type:"inline"}:n.presentation,outputs:o});let a=new Set(i.flatMap(Mr));return Bt.parse({references:{},variables:{},outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",schemaVersion:3,inputs:(()=>{let c=[];return Pt(r,l=>{l.type==="stack"&&l.interaction&&["input","select","multiselect","toggle","tabs"].includes(l.interaction.type)&&c.push({key:`answer_${crypto.randomUUID().replaceAll("-","")}`,screenId:"screen",componentId:l.id,required:!1})}),c})(),screens:[{id:"screen",type:"owned",document:r}],graph:{version:4,entry:"entry",nodes:i.filter(c=>c.type!=="end"||a.has(c.id))}})}function eU(e,t,n){if(t.document.kind!=="screen")throw new Error("Choose a single screen template");let r=mx(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,p)=>+(p.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(([p,g])=>[p,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=Bt.parse({...e,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]}}),l=0,u=0;for(let d of c.screens)d.type==="owned"&&(Pt(d.document,()=>{l++}),u+=d.document.actions.length);if(l>et.components||u>et.actions||cn(c)>et.documentBytes)throw new Error("Template exceeds the flow capacity");return c}function xf(e){Pt(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 fx(e){return e.kind==="membership"&&["week","month","year"].includes(e.interval)}function nU(e){return e.kind==="topup"?"credit_pack":e.interval==="one_time"?"lifetime":"membership"}function If(e){return fx(e)?e.intervalCount??1:1}function rU(e,t){return e.interval===t.interval&&If(e)===If(t)}function iU(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],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 Ve}from"zod";var vf=Ve.enum(["membership","trial","topup","manual","rollover","seat"]),Af=Ve.enum(["scheduled","active","expired","revoked","unavailable"]),uU=Ve.strictObject({customerId:Ve.uuid().nullable(),entityId:Ve.uuid().nullable(),internal_feature_id:Ve.uuid().nullable(),reason:vf.nullable(),status:Af.nullable(),after:Ve.uuid().nullable(),limit:Ve.number().int().min(1).max(50)}),lU=Ve.strictObject({snapshotAt:Ve.iso.datetime({offset:!0}),rows:Ve.array(Ve.strictObject({id:Ve.uuid(),customerId:Ve.uuid(),fundingCustomerId:Ve.uuid(),entityId:Ve.uuid().nullable(),internal_feature_id:Ve.uuid(),key:Xt,name:Ve.string().min(1).max(120),kind:Ve.enum(["access","metered","credit"]),reason:vf,status:Af,unlimited:Ve.boolean(),granted:Ze,available:Ze,held:Ze,spent:Ze,revoked:Ze,transferred:Ze,startsAt:Ve.iso.datetime({offset:!0}).nullable(),expiresAt:Ve.iso.datetime({offset:!0}).nullable(),grantId:Ve.uuid().nullable(),membershipId:Ve.uuid().nullable(),seatPoolId:Ve.uuid().nullable()})).max(50),nextCursor:Ve.uuid().nullable()});import{z as Ke}from"zod";var wf=Ke.string().regex(/^[a-f0-9]{64}$/),gx=$o.omit({variations:!0,active:!0}).extend({changeId:wf,variations:Ke.array(Ke.strictObject({urlRedirect:Ke.string().max(2048)})).min(2).max(20)}),hU=Ke.strictObject({environmentId:Ke.uuid(),generation:wf,experiments:Ke.array(gx).max(100),savedGroups:tc}),hx=Ke.strictObject({eventUuid:Ke.uuid(),timestamp:Ke.iso.datetime({offset:!0}).optional(),deviceId:Ke.string().min(1).max(128),sessionId:Ke.string().min(1).max(128).optional(),url:Ke.url().max(2048),pageTitle:Ke.string().max(512).optional(),experimentKey:Ke.string().min(1).max(255),variationKey:Ke.string().min(1).max(64)}),bU=Ke.strictObject({events:Ke.array(hx).min(1).max(20)}),_U=Ke.strictObject({inserted:Ke.number().int().nonnegative(),duplicates:Ke.number().int().nonnegative(),rejected:Ke.array(Ke.strictObject({index:Ke.number().int().nonnegative(),reason:Ke.string()}))});import{z as V}from"zod";var Pf=V.strictObject({property:V.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/),datatype:V.enum(["boolean","string","number","enum","string[]","number[]","object","array","json"]),enumValues:V.array(V.string()).min(1).nullable(),format:V.enum(["","version","date","isoCountryCode"]),hashAttribute:V.boolean(),stored:V.boolean(),description:V.string().max(2e3),status:V.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"})}),Cf=V.strictObject({name:V.string().min(1).max(128),label:V.string().min(1).max(80),description:V.string().max(2e3),status:V.enum(["active","inactive"]),hashAttribute:V.string().min(1).max(128),seed:V.string().min(1).max(128)}),jc={id:V.uuid(),revision:V.number().int().positive()},AU=V.strictObject({groups:V.array(V.strictObject({id:V.uuid(),name:V.string(),type:V.enum(["condition","list"])})),experiments:V.array(V.strictObject({...jc,configuration:xr,archivedAt:V.iso.datetime({offset:!0}).nullable()})),namespaces:V.array(V.strictObject({...jc,configuration:Cf})),attributes:V.array(V.strictObject({...jc,configuration:Pf})),truncated:V.boolean()}),Nc={id:V.uuid().nullable(),revision:V.number().int().min(0)},wU=V.discriminatedUnion("resource",[V.strictObject({...Nc,resource:V.literal("experiment"),configuration:xr.safeExtend({archivedAt:V.iso.datetime({offset:!0}).nullable()})}),V.strictObject({...Nc,resource:V.literal("namespace"),configuration:Cf}),V.strictObject({...Nc,resource:V.literal("attribute"),configuration:Pf})]),OU=V.strictObject({operation:V.literal("evaluate"),attributes:Ft,condition:St.optional(),features:Ol,featureKey:V.string().min(1).max(128),customerId:V.uuid().nullable()}),PU=V.strictObject({experimentId:V.uuid(),participants:V.number().int().nonnegative(),cohorts:V.array(V.strictObject({variationKey:V.string().nullable(),participants:V.number().int().nonnegative()})),phases:V.array(V.strictObject({phaseIndex:V.number().int().nonnegative(),participants:V.number().int().nonnegative()})),stickyIdentities:V.number().int().nonnegative(),snapshotAt:V.iso.datetime()}),Of=V.strictObject({resource:V.enum(["group","experiment","coupon"]),id:V.uuid()}),CU=V.strictObject({rows:V.array(Of.extend({name:V.string(),status:V.string()})).max(50),total:V.number().int().nonnegative(),nextCursor:Of.nullable()});var sa=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function bx(e,t){let n=e.phases.at(-1),r=t.phases.at(-1),i=[];(!sa(n.condition,r.condition)||!sa(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,l])=>{let u=c;for(let[d,p]of[...r.namespace.ranges].sort((g,f)=>g[0]-f[0]))d<=u&&p>u&&(u=p);return u<l})&&i.push("namespaceRange"),(!sa(n.variationWeights,r.variationWeights)||!sa(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 RU(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(bx(e,t).disableSamePhase&&n.startsWith("same-phase"))throw Error("Start a new phase for these changes");return 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),o.phases[o.phases.length-1].dateEnded=r,o.phases.push({...a,name:a.name,reason:a.reason,dateStarted:r,dateEnded:null,seed:i})),xr.parse(o)}import{z as _x}from"zod";var NU=_x.enum(["owner","admin","developer","sales","member"]),yx=["organisation","customers","features","plans","rewards","balances","billing","migrations","analytics","apiKeys","platform"],Ef=yx.flatMap(e=>e==="analytics"?["analytics:read"]:[`${e}:read`,`${e}:write`]),Tf={owner:Ef,admin:Ef,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 DU(e,t){if(!e||!Object.hasOwn(Tf,e))return!1;let n=Tf[e];return n.includes(t)||t.endsWith(":read")&&n.includes(t.replace(/:read$/,":write"))}var UU=["boolean","metered","credit_system","ai_credit_system"];function MU(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,Gn=1e9,Dc="0123456789abcdef",la="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",da="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Fc={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Vr,maxE:Vr,crypto:!1},Nf,On,le=!0,ma="[DecimalError] ",$n=ma+"Invalid argument: ",Df=ma+"Precision limit exceeded",Ff=ma+"crypto unavailable",Uf="[object Decimal]",wt=Math.floor,st=Math.pow,Sx=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,xx=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Ix=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Mf=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,un=1e7,ie=7,vx=9007199254740991,Ax=la.length-1,Uc=da.length-1,T={toStringTag:Uf};T.absoluteValue=T.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),X(e)};T.ceil=function(){return X(new this.constructor(this),this.e+1,2)};T.clampedTo=T.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($n+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};T.comparedTo=T.cmp=function(e){var t,n,r,i,o=this,a=o.d,s=(e=new o.constructor(e)).d,c=o.s,l=e.s;if(!a||!s)return!c||!l?NaN:c!==l?c:a===s?0:!a^c<0?1:-1;if(!a[0]||!s[0])return a[0]?c:s[0]?-l:0;if(c!==l)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};T.cosine=T.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())+ie,r.rounding=1,n=wx(r,$f(r,n)),r.precision=e,r.rounding=t,X(On==2||On==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};T.cubeRoot=T.cbrt=function(){var e,t,n,r,i,o,a,s,c,l,u=this,d=u.constructor;if(!u.isFinite()||u.isZero())return new d(u);for(le=!1,o=u.s*st(u.s*u,1/3),!o||Math.abs(o)==1/0?(n=yt(u.d),e=u.e,(o=(e-n.length+1)%3)&&(n+=o==1||o==-2?"0":"00"),o=st(n,1/3),e=wt((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=u.s):r=new d(o.toString()),a=(e=d.precision)+3;;)if(s=r,c=s.times(s).times(s),l=c.plus(u),r=Le(l.plus(u).times(s),l.plus(c),a+2,1),yt(s.d).slice(0,a)===(n=yt(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(u))){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(u));break}return le=!0,X(r,e,d.rounding,t)};T.decimalPlaces=T.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-wt(this.e/ie))*ie,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};T.dividedBy=T.div=function(e){return Le(this,new this.constructor(e))};T.dividedToIntegerBy=T.divToInt=function(e){var t=this,n=t.constructor;return X(Le(t,new n(e),0,1,1),n.precision,n.rounding)};T.equals=T.eq=function(e){return this.cmp(e)===0};T.floor=function(){return X(new this.constructor(this),this.e+1,3)};T.greaterThan=T.gt=function(e){return this.cmp(e)>0};T.greaterThanOrEqualTo=T.gte=function(e){var t=this.cmp(e);return t==1||t===0};T.hyperbolicCosine=T.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/ga(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),o=$r(a,1,o.times(t),new a(1),!0);for(var c,l=e,u=new a(8);l--;)c=o.times(o),o=s.minus(c.times(u.minus(c.times(u))));return X(o,a.precision=n,a.rounding=r,!0)};T.hyperbolicSine=T.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=$r(o,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/ga(5,e)),i=$r(o,2,i,i,!0);for(var a,s=new o(5),c=new o(16),l=new o(20);e--;)a=i.times(i),i=i.times(s.plus(a.times(c.times(a).plus(l))))}return o.precision=t,o.rounding=n,X(i,t,n,!0)};T.hyperbolicTangent=T.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)};T.inverseCosine=T.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()?_n(t,r,i):new t(0):new t(NaN):e.isZero()?_n(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))};T.inverseHyperbolicCosine=T.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,le=!1,n=n.times(n).minus(1).sqrt().plus(n),le=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};T.inverseHyperbolicSine=T.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,le=!1,n=n.times(n).plus(1).sqrt().plus(n),le=!0,r.precision=e,r.rounding=t,n.ln())};T.inverseHyperbolicTangent=T.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)};T.inverseSine=T.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=_n(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)))};T.inverseTangent=T.atan=function(){var e,t,n,r,i,o,a,s,c,l=this,u=l.constructor,d=u.precision,p=u.rounding;if(l.isFinite()){if(l.isZero())return new u(l);if(l.abs().eq(1)&&d+4<=Uc)return a=_n(u,d+4,p).times(.25),a.s=l.s,a}else{if(!l.s)return new u(NaN);if(d+4<=Uc)return a=_n(u,d+4,p).times(.5),a.s=l.s,a}for(u.precision=s=d+10,u.rounding=1,n=Math.min(28,s/ie+2|0),e=n;e;--e)l=l.div(l.times(l).plus(1).sqrt().plus(1));for(le=!1,t=Math.ceil(s/ie),r=1,c=l.times(l),a=new u(l),i=l;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)),le=!0,X(a,u.precision=d,u.rounding=p,!0)};T.isFinite=function(){return!!this.d};T.isInteger=T.isInt=function(){return!!this.d&&wt(this.e/ie)>this.d.length-2};T.isNaN=function(){return!this.s};T.isNegative=T.isNeg=function(){return this.s<0};T.isPositive=T.isPos=function(){return this.s>0};T.isZero=function(){return!!this.d&&this.d[0]===0};T.lessThan=T.lt=function(e){return this.cmp(e)<0};T.lessThanOrEqualTo=T.lte=function(e){return this.cmp(e)<1};T.logarithm=T.log=function(e){var t,n,r,i,o,a,s,c,l=this,u=l.constructor,d=u.precision,p=u.rounding,g=5;if(e==null)e=new u(10),t=!0;else{if(e=new u(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new u(NaN);t=e.eq(10)}if(n=l.d,l.s<0||!n||!n[0]||l.eq(1))return new u(n&&!n[0]?-1/0:l.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(le=!1,s=d+g,a=Vn(l,s),r=t?pa(u,s+10):Vn(e,s),c=Le(a,r,s,1),Gi(c.d,i=d,p))do if(s+=10,a=Vn(l,s),r=t?pa(u,s+10):Vn(e,s),c=Le(a,r,s,1),!o){+yt(c.d).slice(i+1,i+15)+1==1e14&&(c=X(c,d+1,0));break}while(Gi(c.d,i+=10,p));return le=!0,X(c,d,p)};T.minus=T.sub=function(e){var t,n,r,i,o,a,s,c,l,u,d,p,g=this,f=g.constructor;if(e=new f(e),!g.d||!e.d)return!g.s||!e.s?e=new f(NaN):g.d?e.s=-e.s:e=new f(e.d||g.s!==e.s?g:NaN),e;if(g.s!=e.s)return e.s=-e.s,g.plus(e);if(l=g.d,p=e.d,s=f.precision,c=f.rounding,!l[0]||!p[0]){if(p[0])e.s=-e.s;else if(l[0])e=new f(g);else return new f(c===3?-0:0);return le?X(e,s,c):e}if(n=wt(e.e/ie),u=wt(g.e/ie),l=l.slice(),o=u-n,o){for(d=o<0,d?(t=l,o=-o,a=p.length):(t=p,n=u,a=l.length),r=Math.max(Math.ceil(s/ie),a)+2,o>r&&(o=r,t.length=1),t.reverse(),r=o;r--;)t.push(0);t.reverse()}else{for(r=l.length,a=p.length,d=r<a,d&&(a=r),r=0;r<a;r++)if(l[r]!=p[r]){d=l[r]<p[r];break}o=0}for(d&&(t=l,l=p,p=t,e.s=-e.s),a=l.length,r=p.length-a;r>0;--r)l[a++]=0;for(r=p.length;r>o;){if(l[--r]<p[r]){for(i=r;i&&l[--i]===0;)l[i]=un-1;--l[i],l[r]+=un}l[r]-=p[r]}for(;l[--a]===0;)l.pop();for(;l[0]===0;l.shift())--n;return l[0]?(e.d=l,e.e=fa(l,n),le?X(e,s,c):e):new f(c===3?-0:0)};T.modulo=T.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):(le=!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),le=!0,n.minus(t))};T.naturalExponential=T.exp=function(){return Mc(this)};T.naturalLogarithm=T.ln=function(){return Vn(this)};T.negated=T.neg=function(){var e=new this.constructor(this);return e.s=-e.s,X(e)};T.plus=T.add=function(e){var t,n,r,i,o,a,s,c,l,u,d=this,p=d.constructor;if(e=new p(e),!d.d||!e.d)return!d.s||!e.s?e=new p(NaN):d.d||(e=new p(e.d||d.s===e.s?d:NaN)),e;if(d.s!=e.s)return e.s=-e.s,d.minus(e);if(l=d.d,u=e.d,s=p.precision,c=p.rounding,!l[0]||!u[0])return u[0]||(e=new p(d)),le?X(e,s,c):e;if(o=wt(d.e/ie),r=wt(e.e/ie),l=l.slice(),i=o-r,i){for(i<0?(n=l,i=-i,a=u.length):(n=u,r=o,a=l.length),o=Math.ceil(s/ie),a=o>a?o+1:a+1,i>a&&(i=a,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(a=l.length,i=u.length,a-i<0&&(i=a,n=u,u=l,l=n),t=0;i;)t=(l[--i]=l[i]+u[i]+t)/un|0,l[i]%=un;for(t&&(l.unshift(t),++r),a=l.length;l[--a]==0;)l.pop();return e.d=l,e.e=fa(l,r),le?X(e,s,c):e};T.precision=T.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error($n+e);return n.d?(t=Lf(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};T.round=function(){var e=this,t=e.constructor;return X(new t(e),e.e+1,t.rounding)};T.sine=T.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())+ie,r.rounding=1,n=Px(r,$f(r,n)),r.precision=e,r.rounding=t,X(On>2?n.neg():n,e,t,!0)):new r(NaN)};T.squareRoot=T.sqrt=function(){var e,t,n,r,i,o,a=this,s=a.d,c=a.e,l=a.s,u=a.constructor;if(l!==1||!s||!s[0])return new u(!l||l<0&&(!s||s[0])?NaN:s?a:1/0);for(le=!1,l=Math.sqrt(+a),l==0||l==1/0?(t=yt(s),(t.length+c)%2==0&&(t+="0"),l=Math.sqrt(t),c=wt((c+1)/2)-(c<0||c%2),l==1/0?t="5e"+c:(t=l.toExponential(),t=t.slice(0,t.indexOf("e")+1)+c),r=new u(t)):r=new u(l.toString()),n=(c=u.precision)+3;;)if(o=r,r=o.plus(Le(a,o,n+2,1)).times(.5),yt(o.d).slice(0,n)===(t=yt(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 le=!0,X(r,c,u.rounding,e)};T.tangent=T.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(On==2||On==4?n.neg():n,e,t,!0)):new r(NaN)};T.times=T.mul=function(e){var t,n,r,i,o,a,s,c,l,u=this,d=u.constructor,p=u.d,g=(e=new d(e)).d;if(e.s*=u.s,!p||!p[0]||!g||!g[0])return new d(!e.s||p&&!p[0]&&!g||g&&!g[0]&&!p?NaN:!p||!g?e.s/0:e.s*0);for(n=wt(u.e/ie)+wt(e.e/ie),c=p.length,l=g.length,c<l&&(o=p,p=g,g=o,a=c,c=l,l=a),o=[],a=c+l,r=a;r--;)o.push(0);for(r=l;--r>=0;){for(t=0,i=c+r;i>r;)s=o[i]+g[r]*p[i-r-1]+t,o[i--]=s%un|0,t=s/un|0;o[i]=(o[i]+t)%un|0}for(;!o[--a];)o.pop();return t?++n:o.shift(),e.d=o,e.e=fa(o,n),le?X(e,d.precision,d.rounding):e};T.toBinary=function(e,t){return Lc(this,2,e,t)};T.toDecimalPlaces=T.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(Nt(e,0,Gn),t===void 0?t=r.rounding:Nt(t,0,8),X(n,e+n.e+1,t))};T.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=yn(r,!0):(Nt(e,0,Gn),t===void 0?t=i.rounding:Nt(t,0,8),r=X(new i(r),e+1,t),n=yn(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};T.toFixed=function(e,t){var n,r,i=this,o=i.constructor;return e===void 0?n=yn(i):(Nt(e,0,Gn),t===void 0?t=o.rounding:Nt(t,0,8),r=X(new o(i),e+i.e+1,t),n=yn(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};T.toFraction=function(e){var t,n,r,i,o,a,s,c,l,u,d,p,g=this,f=g.d,h=g.constructor;if(!f)return new h(g);if(l=n=new h(1),r=c=new h(0),t=new h(r),o=t.e=Lf(f)-g.e-1,a=o%ie,t.d[0]=st(10,a<0?ie+a:a),e==null)e=o>0?t:l;else{if(s=new h(e),!s.isInt()||s.lt(l))throw Error($n+s);e=s.gt(t)?o>0?t:l:s}for(le=!1,s=new h(yt(f)),u=h.precision,h.precision=o=f.length*ie*2;d=Le(s,t,0,1,1),i=n.plus(d.times(r)),i.cmp(e)!=1;)n=r,r=i,i=l,l=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(l)),n=n.plus(i.times(r)),c.s=l.s=g.s,p=Le(l,r,o,1).minus(g).abs().cmp(Le(c,n,o,1).minus(g).abs())<1?[l,r]:[c,n],h.precision=u,le=!0,p};T.toHexadecimal=T.toHex=function(e,t){return Lc(this,16,e,t)};T.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:Nt(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]?(le=!1,n=Le(n,e,0,t,1).times(e),le=!0,X(n)):(e.s=n.s,n=e),n};T.toNumber=function(){return+this};T.toOctal=function(e,t){return Lc(this,8,e,t)};T.toPower=T.pow=function(e){var t,n,r,i,o,a,s=this,c=s.constructor,l=+(e=new c(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new c(st(+s,l));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=wt(e.e/ie),t>=e.d.length-1&&(n=l<0?-l:l)<=vx)return i=Bf(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=st(+s,l),t=n==0||!isFinite(n)?wt(l*(Math.log("0."+yt(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):(le=!1,c.rounding=s.s=1,n=Math.min(12,(t+"").length),i=Mc(e.times(Vn(s,r+n)),r),i.d&&(i=X(i,r+5,1),Gi(i.d,r,o)&&(t=r+10,i=X(Mc(e.times(Vn(s,t+n)),t),t+5,1),+yt(i.d).slice(r+1,r+15)+1==1e14&&(i=X(i,r+1,0)))),i.s=a,le=!0,c.rounding=o,X(i,r,o))};T.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=yn(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(Nt(e,1,Gn),t===void 0?t=i.rounding:Nt(t,0,8),r=X(new i(r),e,t),n=yn(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};T.toSignificantDigits=T.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(Nt(e,1,Gn),t===void 0?t=r.rounding:Nt(t,0,8)),X(new r(n),e,t)};T.toString=function(){var e=this,t=e.constructor,n=yn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};T.truncated=T.trunc=function(){return X(new this.constructor(this),this.e+1,1)};T.valueOf=T.toJSON=function(){var e=this,t=e.constructor,n=yn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function yt(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=ie-r.length,n&&(o+=qn(n)),o+=r;a=e[t],r=a+"",n=ie-r.length,n&&(o+=qn(n))}else if(a===0)return"0";for(;a%10===0;)a/=10;return o+a}function Nt(e,t,n){if(e!==~~e||e<t||e>n)throw Error($n+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+=ie,i=0):(i=Math.ceil((t+1)/ie),t%=ie),o=st(10,ie-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)==st(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)==st(10,t-3)-1,a}function ca(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]+=Dc.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 wx(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/ga(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=$r(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 l,u,d,p,g,f,h,I,v,S,R,D,P,be,tt,We,je,ue,$,De,Q=r.constructor,dt=r.s==i.s?1:-1,me=r.d,ce=i.d;if(!me||!me[0]||!ce||!ce[0])return new Q(!r.s||!i.s||(me?ce&&me[0]==ce[0]:!ce)?NaN:me&&me[0]==0||!ce?dt*0:dt/0);for(c?(g=1,u=r.e-i.e):(c=un,g=ie,u=wt(r.e/g)-wt(i.e/g)),$=ce.length,je=me.length,v=new Q(dt),S=v.d=[],d=0;ce[d]==(me[d]||0);d++);if(ce[d]>(me[d]||0)&&u--,o==null?(be=o=Q.precision,a=Q.rounding):s?be=o+(r.e-i.e)+1:be=o,be<0)S.push(1),f=!0;else{if(be=be/g+2|0,d=0,$==1){for(p=0,ce=ce[0],be++;(d<je||p)&&be--;d++)tt=p*c+(me[d]||0),S[d]=tt/ce|0,p=tt%ce|0;f=p||d<je}else{for(p=c/(ce[0]+1)|0,p>1&&(ce=e(ce,p,c),me=e(me,p,c),$=ce.length,je=me.length),We=$,R=me.slice(0,$),D=R.length;D<$;)R[D++]=0;De=ce.slice(),De.unshift(0),ue=ce[0],ce[1]>=c/2&&++ue;do p=0,l=t(ce,R,$,D),l<0?(P=R[0],$!=D&&(P=P*c+(R[1]||0)),p=P/ue|0,p>1?(p>=c&&(p=c-1),h=e(ce,p,c),I=h.length,D=R.length,l=t(h,R,I,D),l==1&&(p--,n(h,$<I?De:ce,I,c))):(p==0&&(l=p=1),h=ce.slice()),I=h.length,I<D&&h.unshift(0),n(R,h,D,c),l==-1&&(D=R.length,l=t(ce,R,$,D),l<1&&(p++,n(R,$<D?De:ce,D,c))),D=R.length):l===0&&(p++,R=[0]),S[d++]=p,l&&R[0]?R[D++]=me[We]||0:(R=[me[We]],D=1);while((We++<je||R[0]!==void 0)&&be--);f=R[0]!==void 0}S[0]||S.shift()}if(g==1)v.e=u,Nf=f;else{for(d=1,p=S[0];p>=10;p/=10)d++;v.e=d+u*g-1,X(v,s?o+v.e+1:o,a,f)}return v}})();function X(e,t,n,r){var i,o,a,s,c,l,u,d,p,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+=ie,a=t,u=d[p=0],c=u/st(10,i-a-1)%10|0;else if(p=Math.ceil((o+1)/ie),s=d.length,p>=s)if(r){for(;s++<=p;)d.push(0);u=c=0,i=1,o%=ie,a=o-ie+1}else break e;else{for(u=s=d[p],i=1;s>=10;s/=10)i++;o%=ie,a=o-ie+i,c=a<0?0:u/st(10,i-a-1)%10|0}if(r=r||t<0||d[p+1]!==void 0||(a<0?u:u%st(10,i-a-1)),l=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?u/st(10,i-a):0:d[p-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,l?(t-=e.e+1,d[0]=st(10,(ie-t%ie)%ie),e.e=-t||0):d[0]=e.e=0,e;if(o==0?(d.length=p,s=1,p--):(d.length=p+1,s=st(10,ie-o),d[p]=a>0?(u/st(10,i-a)%st(10,a)|0)*s:0),l)for(;;)if(p==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]==un&&(d[0]=1));break}else{if(d[p]+=s,d[p]!=un)break;d[p--]=0,s=1}for(o=d.length;d[--o]===0;)d.pop()}return le&&(e.e>g.maxE?(e.d=null,e.e=NaN):e.e<g.minE&&(e.e=0,e.d=[0])),e}function yn(e,t,n){if(!e.isFinite())return Vf(e);var r,i=e.e,o=yt(e.d),a=o.length;return t?(n&&(r=n-a)>0?o=o.charAt(0)+"."+o.slice(1)+qn(r):a>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(e.e<0?"e":"e+")+e.e):i<0?(o="0."+qn(-i-1)+o,n&&(r=n-a)>0&&(o+=qn(r))):i>=a?(o+=qn(i+1-a),n&&(r=n-i-1)>0&&(o=o+"."+qn(r))):((r=i+1)<a&&(o=o.slice(0,r)+"."+o.slice(r)),n&&(r=n-a)>0&&(i+1===a&&(o+="."),o+=qn(r))),o}function fa(e,t){var n=e[0];for(t*=ie;n>=10;n/=10)t++;return t}function pa(e,t,n){if(t>Ax)throw le=!0,n&&(e.precision=n),Error(Df);return X(new e(la),t,1,!0)}function _n(e,t,n){if(t>Uc)throw Error(Df);return X(new e(da),t,n,!0)}function Lf(e){var t=e.length-1,n=t*ie+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 qn(e){for(var t="";e--;)t+="0";return t}function Bf(e,t,n,r){var i,o=new e(1),a=Math.ceil(r/ie+4);for(le=!1;;){if(n%2&&(o=o.times(t),kf(o.d,a)&&(i=!0)),n=wt(n/2),n===0){n=o.d.length-1,i&&o.d[n]===0&&++o.d[n];break}t=t.times(t),kf(t.d,a)}return le=!0,o}function Rf(e){return e.d[e.d.length-1]&1}function qf(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 Mc(e,t){var n,r,i,o,a,s,c,l=0,u=0,d=0,p=e.constructor,g=p.rounding,f=p.precision;if(!e.d||!e.d[0]||e.e>17)return new p(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(le=!1,c=f):c=t,s=new p(.03125);e.e>-2;)e=e.times(s),d+=5;for(r=Math.log(st(2,d))/Math.LN10*2+5|0,c+=r,n=o=a=new p(1),p.precision=c;;){if(o=X(o.times(e),c,1),n=n.times(++u),s=a.plus(Le(o,n,c,1)),yt(s.d).slice(0,c)===yt(a.d).slice(0,c)){for(i=d;i--;)a=X(a.times(a),c,1);if(t==null)if(l<3&&Gi(a.d,c-r,g,l))p.precision=c+=10,n=o=s=new p(1),u=0,l++;else return X(a,p.precision=f,g,le=!0);else return p.precision=f,a}a=s}}function Vn(e,t){var n,r,i,o,a,s,c,l,u,d,p,g=1,f=10,h=e,I=h.d,v=h.constructor,S=v.rounding,R=v.precision;if(h.s<0||!I||!I[0]||!h.e&&I[0]==1&&I.length==1)return new v(I&&!I[0]?-1/0:h.s!=1?NaN:I?0:h);if(t==null?(le=!1,u=R):u=t,v.precision=u+=f,n=yt(I),r=n.charAt(0),Math.abs(o=h.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)h=h.times(e),n=yt(h.d),r=n.charAt(0),g++;o=h.e,r>1?(h=new v("0."+n),o++):h=new v(r+"."+n.slice(1))}else return l=pa(v,u+2,R).times(o+""),h=Vn(new v(r+"."+n.slice(1)),u-f).plus(l),v.precision=R,t==null?X(h,R,S,le=!0):h;for(d=h,c=a=h=Le(h.minus(1),h.plus(1),u,1),p=X(h.times(h),u,1),i=3;;){if(a=X(a.times(p),u,1),l=c.plus(Le(a,new v(i),u,1)),yt(l.d).slice(0,u)===yt(c.d).slice(0,u))if(c=c.times(2),o!==0&&(c=c.plus(pa(v,u+2,R).times(o+""))),c=Le(c,new v(g),u,1),t==null)if(Gi(c.d,u-f,S,s))v.precision=u+=f,l=a=h=Le(d.minus(1),d.plus(1),u,1),p=X(h.times(h),u,1),i=s=1;else return X(c,v.precision=R,S,le=!0);else return v.precision=R,c;c=l,i+=2}}function Vf(e){return String(e.s*e.s/0)}function ua(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)%ie,n<0&&(r+=ie),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=ie;r<i;)e.d.push(+t.slice(r,r+=ie));t=t.slice(r),r=ie-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),le&&(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 Ox(e,t){var n,r,i,o,a,s,c,l,u;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),Mf.test(t))return ua(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(xx.test(t))n=16,t=t.toLowerCase();else if(Sx.test(t))n=2;else if(Ix.test(t))n=8;else throw Error($n+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=Bf(r,new r(n),o,o*2)),l=ca(t,n,un),u=l.length-1,o=u;l[o]===0;--o)l.pop();return o<0?new r(e.s*0):(e.e=fa(l,u),e.d=l,le=!1,a&&(e=Le(e,i,s*4)),c&&(e=e.times(Math.abs(c)<54?st(2,c):ln.pow(2,c))),le=!0,e)}function Px(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:$r(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/ga(5,n)),t=$r(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 $r(e,t,n,r,i){var o,a,s,c,l=1,u=e.precision,d=Math.ceil(u/ie);for(le=!1,c=n.times(n),s=new e(r);;){if(a=Le(s.times(c),new e(t++*t++),u,1),s=i?r.plus(a):r.minus(a),r=Le(a.times(c),new e(t++*t++),u,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,l++}return le=!0,a.d.length=d+1,a}function ga(e,t){for(var n=e;--t;)n*=e;return n}function $f(e,t){var n,r=t.s<0,i=_n(e,e.precision,1),o=i.times(.5);if(t=t.abs(),t.lte(o))return On=r?4:1,t;if(n=t.divToInt(i),n.isZero())On=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(o))return On=Rf(n)?r?2:3:r?4:1,t;On=Rf(n)?r?1:4:r?3:2}return t.minus(i).abs()}function Lc(e,t,n,r){var i,o,a,s,c,l,u,d,p,g=e.constructor,f=n!==void 0;if(f?(Nt(n,1,Gn),r===void 0?r=g.rounding:Nt(r,0,8)):(n=g.precision,r=g.rounding),!e.isFinite())u=Vf(e);else{for(u=yn(e),a=u.indexOf("."),f?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,a>=0&&(u=u.replace(".",""),p=new g(1),p.e=u.length-a,p.d=ca(yn(p),10,i),p.e=p.d.length),d=ca(u,10,i),o=c=d.length;d[--c]==0;)d.pop();if(!d[0])u=f?"0p+0":"0";else{if(a<0?o--:(e=new g(e),e.d=d,e.e=o,e=Le(e,p,n,r,0,i),d=e.d,o=e.e,l=Nf),a=d[n],s=i/2,l=l||d[n+1]!==void 0,l=r<4?(a!==void 0||l)&&(r===0||r===(e.s<0?3:2)):a>s||a===s&&(r===4||l||r===6&&d[n-1]&1||r===(e.s<0?8:7)),d.length=n,l)for(;++d[--n]>i-1;)d[n]=0,n||(++o,d.unshift(1));for(c=d.length;!d[c-1];--c);for(a=0,u="";a<c;a++)u+=Dc.charAt(d[a]);if(f){if(c>1)if(t==16||t==8){for(a=t==16?4:3,--c;c%a;c++)u+="0";for(d=ca(u,i,t),c=d.length;!d[c-1];--c);for(a=1,u="1.";a<c;a++)u+=Dc.charAt(d[a])}else u=u.charAt(0)+"."+u.slice(1);u=u+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)u="0"+u;u="0."+u}else if(++o>c)for(o-=c;o--;)u+="0";else o<c&&(u=u.slice(0,o)+"."+u.slice(o))}u=(t==16?"0x":t==2?"0b":t==8?"0o":"")+u}return e.s<0?"-"+u:u}function kf(e,t){if(e.length>t)return e.length=t,!0}function Cx(e){return new this(e).abs()}function Ex(e){return new this(e).acos()}function Tx(e){return new this(e).acosh()}function Rx(e,t){return new this(e).plus(t)}function kx(e){return new this(e).asin()}function jx(e){return new this(e).asinh()}function Nx(e){return new this(e).atan()}function Dx(e){return new this(e).atanh()}function Fx(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=_n(this,o,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?_n(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=_n(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=_n(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 Ux(e){return new this(e).cbrt()}function Mx(e){return X(e=new this(e),e.e+1,2)}function Lx(e,t,n){return new this(e).clamp(t,n)}function Bx(e){if(!e||typeof e!="object")throw Error(ma+"Object expected");var t,n,r,i=e.defaults===!0,o=["precision",1,Gn,"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]=Fc[n]),(r=e[n])!==void 0)if(wt(r)===r&&r>=o[t+1]&&r<=o[t+2])this[n]=r;else throw Error($n+n+": "+r);if(n="crypto",i&&(this[n]=Fc[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(Ff);else this[n]=!1;else throw Error($n+n+": "+r);return this}function qx(e){return new this(e).cos()}function Vx(e){return new this(e).cosh()}function Gf(e){var t,n,r;function i(o){var a,s,c,l=this;if(!(l instanceof i))return new i(o);if(l.constructor=i,jf(o)){l.s=o.s,le?!o.d||o.e>i.maxE?(l.e=NaN,l.d=null):o.e<i.minE?(l.e=0,l.d=[0]):(l.e=o.e,l.d=o.d.slice()):(l.e=o.e,l.d=o.d?o.d.slice():o.d);return}if(c=typeof o,c==="number"){if(o===0){l.s=1/o<0?-1:1,l.e=0,l.d=[0];return}if(o<0?(o=-o,l.s=-1):l.s=1,o===~~o&&o<1e7){for(a=0,s=o;s>=10;s/=10)a++;le?a>i.maxE?(l.e=NaN,l.d=null):a<i.minE?(l.e=0,l.d=[0]):(l.e=a,l.d=[o]):(l.e=a,l.d=[o]);return}if(o*0!==0){o||(l.s=NaN),l.e=NaN,l.d=null;return}return ua(l,o.toString())}if(c==="string")return(s=o.charCodeAt(0))===45?(o=o.slice(1),l.s=-1):(s===43&&(o=o.slice(1)),l.s=1),Mf.test(o)?ua(l,o):Ox(l,o);if(c==="bigint")return o<0?(o=-o,l.s=-1):l.s=1,ua(l,o.toString());throw Error($n+o)}if(i.prototype=T,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=Bx,i.clone=Gf,i.isDecimal=jf,i.abs=Cx,i.acos=Ex,i.acosh=Tx,i.add=Rx,i.asin=kx,i.asinh=jx,i.atan=Nx,i.atanh=Dx,i.atan2=Fx,i.cbrt=Ux,i.ceil=Mx,i.clamp=Lx,i.cos=qx,i.cosh=Vx,i.div=$x,i.exp=Gx,i.floor=Kx,i.hypot=Hx,i.ln=zx,i.log=Wx,i.log10=Zx,i.log2=Qx,i.max=Yx,i.min=Jx,i.mod=Xx,i.mul=eI,i.pow=tI,i.random=nI,i.round=rI,i.sign=iI,i.sin=oI,i.sinh=aI,i.sqrt=sI,i.sub=cI,i.sum=uI,i.tan=lI,i.tanh=dI,i.trunc=pI,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 $x(e,t){return new this(e).div(t)}function Gx(e){return new this(e).exp()}function Kx(e){return X(e=new this(e),e.e+1,3)}function Hx(){var e,t,n=new this(0);for(le=!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 le=!0,new this(1/0);n=t}return le=!0,n.sqrt()}function jf(e){return e instanceof ln||e&&e.toStringTag===Uf||!1}function zx(e){return new this(e).ln()}function Wx(e,t){return new this(e).log(t)}function Qx(e){return new this(e).log(2)}function Zx(e){return new this(e).log(10)}function Yx(){return qf(this,arguments,-1)}function Jx(){return qf(this,arguments,1)}function Xx(e,t){return new this(e).mod(t)}function eI(e,t){return new this(e).mul(t)}function tI(e,t){return new this(e).pow(t)}function nI(e){var t,n,r,i,o=0,a=new this(1),s=[];if(e===void 0?e=this.precision:Nt(e,1,Gn),r=Math.ceil(e/ie),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(Ff);else for(;o<r;)s[o++]=Math.random()*1e7|0;for(r=s[--o],e%=ie,r&&e&&(i=st(10,ie-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-=ie)s.shift();for(r=1,i=s[0];i>=10;i/=10)r++;r<ie&&(n-=ie-r)}return a.e=n,a.d=s,a}function rI(e){return X(e=new this(e),e.e+1,this.rounding)}function iI(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function oI(e){return new this(e).sin()}function aI(e){return new this(e).sinh()}function sI(e){return new this(e).sqrt()}function cI(e,t){return new this(e).sub(t)}function uI(){var e=0,t=arguments,n=new this(t[e]);for(le=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return le=!0,X(n,this.precision,this.rounding)}function lI(e){return new this(e).tan()}function dI(e){return new this(e).tanh()}function pI(e){return X(e=new this(e),e.e+1,1)}T[Symbol.for("nodejs.util.inspect.custom")]=T.toString;T[Symbol.toStringTag]="Decimal";var ln=T.constructor=Gf(Fc);la=new ln(la);da=new ln(da);var{PAYLOAD_BYTES:mI}={PAYLOAD_BYTES:20},{KSUID_EPOCH:fI}={KSUID_EPOCH:14e8},{getRandomBytes:gI}={getRandomBytes:({size:t})=>{let n=new Uint8Array(t);return globalThis.crypto.getRandomValues(n),n}},{ALPHABET:hI}={ALPHABET:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},{ENCODED_LENGTH:bI}={ENCODED_LENGTH:27},{base62Encode:_I}=(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 l=s*256+o[c];o[c]=Math.floor(l/62),s=l%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("")}}))(hI),{generateKsuid:Kf}=((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 l=n({size:16});s.set(l,4);let u=r({bytes:s,padTo:i});return`${a}${u}`}}))(mI,fI,gI,_I,bI);var Hf={randomSync:()=>({string:Kf({})})};import{z as ve}from"zod/v4";var yI=202,SI=502,xI=400,II=409,vI=100,AI=201,wI=417;var OI=403,PI=504,CI=410,EI=505,TI=418,RI=419,kI=507,jI=500,NI=411,DI=423,FI=420,UI=405,MI=301,LI=302,BI=207,qI=300,VI=511,$I=204,GI=203,KI=406,HI=404,zI=501,WI=304,QI=200,ZI=206,YI=402,JI=308,XI=412,ev=428,tv=102,nv=407,rv=431,iv=408,ov=413,av=414,sv=416,cv=205,uv=303,lv=503,dv=101,pv=307,mv=429,fv=401,gv=422,hv=415,bv=305,zf={ACCEPTED:yI,BAD_GATEWAY:SI,BAD_REQUEST:xI,CONFLICT:II,CONTINUE:vI,CREATED:AI,EXPECTATION_FAILED:wI,FORBIDDEN:OI,GATEWAY_TIMEOUT:PI,GONE:CI,HTTP_VERSION_NOT_SUPPORTED:EI,IM_A_TEAPOT:TI,INSUFFICIENT_SPACE_ON_RESOURCE:RI,INSUFFICIENT_STORAGE:kI,INTERNAL_SERVER_ERROR:jI,LENGTH_REQUIRED:NI,LOCKED:DI,METHOD_FAILURE:FI,METHOD_NOT_ALLOWED:UI,MOVED_PERMANENTLY:MI,MOVED_TEMPORARILY:LI,MULTI_STATUS:BI,MULTIPLE_CHOICES:qI,NETWORK_AUTHENTICATION_REQUIRED:VI,NO_CONTENT:$I,NON_AUTHORITATIVE_INFORMATION:GI,NOT_ACCEPTABLE:KI,NOT_FOUND:HI,NOT_IMPLEMENTED:zI,NOT_MODIFIED:WI,OK:QI,PARTIAL_CONTENT:ZI,PAYMENT_REQUIRED:YI,PERMANENT_REDIRECT:JI,PRECONDITION_FAILED:XI,PRECONDITION_REQUIRED:ev,PROCESSING:tv,PROXY_AUTHENTICATION_REQUIRED:nv,REQUEST_HEADER_FIELDS_TOO_LARGE:rv,REQUEST_TIMEOUT:iv,REQUEST_TOO_LONG:ov,REQUEST_URI_TOO_LONG:av,REQUESTED_RANGE_NOT_SATISFIABLE:sv,RESET_CONTENT:cv,SEE_OTHER:uv,SERVICE_UNAVAILABLE:lv,SWITCHING_PROTOCOLS:dv,TEMPORARY_REDIRECT:pv,TOO_MANY_REQUESTS:mv,UNAUTHORIZED:fv,UNPROCESSABLE_ENTITY:gv,UNSUPPORTED_MEDIA_TYPE:hv,USE_PROXY:bv};var Wf={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"},Qf={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 _v(e){var t=Wf[e.toString()];if(!t)throw new Error("Status code does not exist: "+e);return t}function Zf(e){var t=Qf[e];if(!t)throw new Error("Reason phrase does not exist: "+e);return t}var Yf=_v;var Kn;(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"})(Kn||(Kn={}));var ha=function(){return ha=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},ha.apply(this,arguments)},YU=ha(ha({},zf),{getStatusCode:Zf,getStatusText:Yf});var{generateId:Gr}=(e=>({generateId:n=>n?`${n}_${e.randomSync().string}`:e.randomSync().string}))(Hf),{BILLING_CONTROL_KEYS:ba}={BILLING_CONTROL_KEYS:["auto_topups","spend_limits","usage_limits","usage_alerts","overage_allowed"]},{PurchaseLimitInterval:yv}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{entToPrice:Jf}={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:Ot}=(()=>{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:_a}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{Infinite:Ki}={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: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}})(),{fixedCurrenciesToApi:Sv}={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:xv}={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:Bc}={TierInfinite:"inf"},{FeatureUsageType:Hn}=(()=>{var e;return(function(t){t.Single="single_use",t.Continuous="continuous_use"})(e||(e={})),{FeatureUsageType:e}})(),{PriceType:Hr}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Usage="usage"})(e||(e={})),{PriceType:e}})(),{BillingType:zr}=(()=>{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:Hi}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:zn}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProductItemFeatureType:Cn}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{UsageModel:Wr}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{InternalError:Iv}=(()=>{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:Xf}=((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}}))(Ot,Cn),{billingControlsFromColumns:eg}=(e=>({billingControlsFromColumns:n=>n?Object.fromEntries(e.flatMap(r=>n[r]==null?[]:[[r,n[r]]])):{}}))(ba),{nullish:Qr}={nullish:t=>t==null},{RecaseError:Dt}=(()=>{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:Vt}={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:vv}=((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})}}))(Dt,Vt),{notNullish:Zr}=(e=>({notNullish:n=>!e(n)}))(Qr),{keyToTitle:tg}={keyToTitle:t=>t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())},{AggregateType:Av}=(()=>{var e;return(function(t){t.Sum="sum"})(e||(e={})),{AggregateType:e}})(),{ProductItemType:wv}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ApiFeatureType:Ov}=(()=>{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:qc}=(()=>{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:ng}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Pv}={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:Cv}=(e=>({COMMON_SET:new Set(e)}))(ng),{hasNoDuplicateCurrencies:rg}={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:ig}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{TierBehavior:ya}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{OnIncrease:Yr}=(()=>{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:zi}=(()=>{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:Vc}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:Ev}=(()=>{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:Tv}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Rv}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:og}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(ve),{flatCreditRateShape:ag}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(ve),{CreditTierSchema:kv}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(ve),{CreditMultiplierSchema:jv}=((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"})}))(ve,og),{MarkupEntrySchema:sg}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(ve),{ModelMarkupsSchema:Nv}=((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()}))(ve,sg),{isFeaturePriceItem:$c}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(Zr),{notNullish:hr}={notNullish:t=>t!=null},{isAiCreditSystem:Gc}=(e=>({isAiCreditSystem:n=>n===e.AiCreditSystem}))(Ot),{VIOLATION_MESSAGES:Dv}={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:Fv}={sameSpecificity:(t,n)=>Object.keys(t.match).length===Object.keys(n.match).length&&(t.priority??null)===(n.priority??null)},{matchesCanCoexist:cg}={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:Uv}={formatCreditMatch:t=>Object.entries(t).map(([n,r])=>`${n}=${r}`).join(", ")},{validateMultiplierShape:Mv}={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:Lv}={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:Bv}=((e,t)=>({worstCaseRate:({multipliers:r,cheapestRate:i})=>r.reduce((o,a)=>{let s=[];for(let l of r){let u=l.factor!==void 0&&l.factor<1||l.add!==void 0&&l.add<0,d=s.every(p=>e(p.match,l.match));(u||l===a)&&e(a.match,l.match)&&d&&s.push(l)}let c=s.reduce((l,u)=>l.mul(u.factor!==void 0&&u.factor<1?u.factor:1).add(u.add!==void 0&&u.add<0?u.add:0),new t(i));return t.min(o,c)},new t(i))}))(cg,ln),{validateCreditSystemSchemaReferences:qv}=((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 l of c){let u=l.metered_feature_id;if(!u||u===s)continue;let d=a.find(p=>p.id===u);if(d){if(d.type===e.CreditSystem)throw new t({message:`Credit system schema cannot reference another credit system (${u}). 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 ${u}. 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 ${u}. Only consumable (single-use) metered features are allowed.`,code:n.InvalidFeature,statusCode:400})}}}}))(Ot,Dt,Vt,Hn),{isPriceItem:Kc}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(Zr,Qr),{isFeatureItem:Sa}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)}))(Zr,Qr),{itemToBillingInterval:Wn}=((e,t)=>({itemToBillingInterval:({item:r})=>{let i=r.price_interval??r.interval;return e(i)?t.OneOff:i}}))(Yt,Pn),{rolloverConfigToIssue:Vv}={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:xa}=((e,t,n)=>({itemToEntInterval:({item:i})=>e(i.interval)||i.feature_type===n.ContinuousUse?t.Lifetime:i.interval}))(Yt,Kr,Cn),{itemToEntIntervalCount:Ia}={itemToEntIntervalCount:({item:t})=>t.interval_count??1},{itemToBillingIntervalCount:Jr}={itemToBillingIntervalCount:({item:t})=>t.price_interval_count??t.interval_count??1},{isFeatureItem:va}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price===0)&&t(r.tiers)}))(hr,Yt),{toKey:ug}={toKey:t=>t.toLowerCase()},{priceOwnedStripePriceId:$v}=(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:Hc}=((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()}))}))(ve,Ki),{IgnoredFixedPriceMetadataSchema:Gv}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(ve),{hasCatalogCurrencies:Kv}={hasCatalogCurrencies:t=>Object.keys(t??{}).length>0},{usageTiersToComparisonShape:Hv}={usageTiersToComparisonShape:t=>t.map((n,r)=>({amount:n.amount,flat_amount:n.flat_amount??0,to:r===t.length-1?null:n.to}))},{normalizedAllocatedBillingBehavior:zv}=(e=>({normalizedAllocatedBillingBehavior:n=>n.allocated_billing_behavior??(n.should_prorate?e.Prorated:e.Arrear)}))(zn),{getResetUsage:lg}=((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}}))(Qr,Sa,$c,Hn),{hasUnlimitedAllowanceType:Wv}=(e=>({hasUnlimitedAllowanceType:n=>n.allowance_type===e.Unlimited}))(_a),{normalizedEntitlementInterval:dg}=(e=>({normalizedEntitlementInterval:n=>n.interval??e.Lifetime}))(Kr),{normalizedEntitlementIntervalCount:Qv}=((e,t)=>({normalizedEntitlementIntervalCount:r=>e(r)===t.Lifetime?1:r.interval_count??1}))(dg,Kr),{normalizeOptionalId:Zv}={normalizeOptionalId:t=>t||null},{rolloversAreSame:Yv}=(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}))(Vc),{deterministicStringify:zc}=(()=>{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:Jv}={MARKUP_FIELDS:["markup","input_cost","output_cost"]},{expiriesAreSame:Xv}={expiriesAreSame:(t,n)=>(t.expiry_duration??null)===(n.expiry_duration??null)&&(t.expiry_length??null)==(n.expiry_length??null)},{itemToFeature:pg}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{isFeaturePriceItem:Xr}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(hr),{ProductErrorCode:e1}={ProductErrorCode:{ProductNotFound:"product_not_found",ProductAlreadyExists:"product_already_exists",InvalidProductItem:"invalid_product_item"}},{buildUsagePriceCurrencies:t1}=(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,l)=>{let u=(r[l]?.additional_currencies??[]).find(d=>e(d.currency)===s);return{to:c.to,amount:u?.amount??0,...u?.flat_amount!==void 0?{flat_amount:u.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}}}))(ug),{itemToFeature:n1}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{shouldProrate:r1}=((e,t)=>({shouldProrate:r=>r?r===e.ProrateNextCycle||r===e.ProrateImmediately||r===t.ProrateImmediately||r===t.ProrateNextCycle:!0}))(Yr,zi),{getBillingType:i1}=((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}}))(Hr,Pn,zr,Hi),{stripeResourceFields:o1}={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:a1}={PREVIEW_STRIPE_PRICE_ID_PREFIX:"price_PREVIEW_"},{PREVIEW_STRIPE_PRODUCT_ID_PREFIX:s1}={PREVIEW_STRIPE_PRODUCT_ID_PREFIX:"prod_PREVIEW_"},{normalizeOptionalId:c1}={normalizeOptionalId:t=>t||null},{stripeProductOnlyFields:u1}={stripeProductOnlyFields:["stripe_product_id","stripe_meter_id"]},{copyField:l1}=(e=>({copyField:({fromConfig:n,toConfig:r,field:i})=>!e(r[i])||e(n[i])?!1:(r[i]=n[i],!0)}))(Yt),{stripeResourceFields:d1}={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:p1}={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(l=>l.id===c.feature_id)})),customPrices:[...t,...r],customEnts:[...n,...i],features:s})},{validateLicenseBillingMode:m1}=((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})}}))(Dt,Vt),{PlanItemMatchPrecision:f1}=(()=>{var e;return(function(t){t.FeatureBillingMethodCadence="feature_billing_method_cadence",t.FeatureCadence="feature_cadence"})(e||(e={})),{PlanItemMatchPrecision:e}})(),{catalogPlanItemIdentity:g1}={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:h1}={applyPrice:(t,n)=>n===void 0?t:n===null?null:{...n}},{planItemMatchesFilter:b1}={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:_1}={isFreeNonResetEntitlement:t=>t.price==null&&t.reset==null},{toApiPlanItemPrice:y1}={toApiPlanItemPrice:t=>t?{...t,billing_units:t.billing_units??1,max_purchase:t.max_purchase??null}:null},{toApiPlanItemRollover:S1}={toApiPlanItemRollover:t=>{if(t)return{...t,max:t.max??null}}},{applyFreeTrial:x1}={applyFreeTrial:(t,n)=>{if(n===void 0)return t;if(n!==null)return{...n}}},{applyLicenseUpsert:I1}={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:mg}=(()=>{var e;return(function(t){t.Identity="identity",t.IdentityAndIncluded="identity_and_included"})(e||(e={})),{PlanItemFilterPrecision:e}})(),{additionalCurrenciesCompatible:Wc}={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:v1}={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:A1}=(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)})}))(Wc),{rolloversEqual:w1}={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:O1}={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:P1}=(e=>({creditSchemaFingerprint:n=>e(Object.fromEntries((n??[]).map(r=>[r.metered_feature_id,{...r,billing_units:r.billing_units??1}])))}))(zc),{toCreatePlanItemParams:C1}={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:E1}=(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}}))(mg),{FreeTrialDuration:T1}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{arraysEqual:R1}={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:k1}={normalizeIntervalCount:({interval:t,intervalCount:n})=>t?n??1:n??""},{hasLicenseCustomize:fg}={hasLicenseCustomize:t=>t!=null&&(t.price!==void 0||t.add_items!==void 0||t.remove_items!==void 0)},{byLicensePlanId:j1}={byLicensePlanId:(t,n)=>t.license_plan_id.localeCompare(n.license_plan_id)},{variantSettingKeys:N1}={variantSettingKeys:["name","description","group","add_on","config","billing_controls","metadata"]},{valuesEqual:D1}={valuesEqual:(t,n)=>JSON.stringify(t)===JSON.stringify(n)},{omitVariantOwnedSettings:oM}={omitVariantOwnedSettings:({name:t,...n})=>n},{isFreeProductV2:F1}=(e=>({isFreeProductV2:({items:n})=>n.every(r=>e(r.price)&&e(r.tiers))}))(Yt),{isPriceItem:Aa}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(hr,Yt),{isDefaultTrialV2:aM}=(e=>({isDefaultTrialV2:({freeTrial:n,items:r,isDefault:i})=>n?n.card_required===!1&&i&&!e({items:r}):!1}))(F1),{variantSettingsFields:U1}={variantSettingsFields:["description","group","is_add_on","is_default","config","billing_controls","metadata"]},{sortDeep:gg}=(()=>{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:M1}={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:L1}={propagatedSettingFields:["description","group","is_add_on","config","billing_controls","metadata"]},{licenseParentTargetKey:B1}={licenseParentTargetKey:({planId:t,version:n})=>`${t}@${n}`},{STRIPE_ZERO_DECIMAL_CURRENCIES:hg}={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:q1}={STRIPE_THREE_DECIMAL_CURRENCIES:new Set(["bhd","jod","kwd","omr","tnd"])},{currencyInputDecimals:bg}=(e=>({currencyInputDecimals:n=>e.has((n??"usd").toLowerCase())?0:2}))(hg),{entIntervalToValue:V1}=((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)}}))(ln,Kr),{intervalToValue:$1}=(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)}))(Pn),{normalizeIncludedUsage:_g}={normalizeIncludedUsage:t=>t??0},{rolloversAreSame:yg}={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:G1}=((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)}))(Yr,zi),{itemToExplicitAllocatedBillingBehavior:K1}=((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)}))(hr,zn),{additionalCurrenciesAreSame:Qc}={additionalCurrenciesAreSame:(t,n)=>{let r=t??[],i=n??[];if(r.length!==i.length)return!1;let o=(c,l)=>c.currency.localeCompare(l.currency),a=[...r].sort(o),s=[...i].sort(o);return a.every((c,l)=>c.currency===s[l].currency&&(c.amount??null)===(s[l].amount??null)&&(c.flat_amount??null)===(s[l].flat_amount??null))}},{itemPricingTiers:H1}={itemPricingTiers:t=>t.tiers?.length?t.tiers:t.price!=null?[{amount:t.price,to:"inf"}]:null},{priceItemsAreSame:z1}=((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}}))(Wn,Jr,Qc),{calculateProrationAmount:W1}=(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),l=s.div(c).mul(o);return l.lte(0)&&!a?0:l.toNumber()}}))(ln),{getResetUsage:Q1}=((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,va,Xr,Hn),{compareDetails:Z1}={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:Y1}={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:J1}=(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}}))(ba),{sortControls:X1}={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:eA}={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:tA}={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:nA}={prodOptionsAreSame:({curProduct:t,newProduct:n})=>t.is_default===n.is_default&&t.is_add_on===n.is_add_on},{PurchaseLimitIntervalEnum:rA}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(ve,yv),{entToItemInterval:Sg}=(e=>({entToItemInterval:({entInterval:n})=>!n||n===e.Lifetime?null:n}))(Kr),{billingToItemInterval:xg}=(e=>({billingToItemInterval:({billingInterval:n})=>n===e.OneOff?null:n}))(Pn),{isContUseFeature:Ig}=(e=>({isContUseFeature:({feature:n})=>n.config?.usage_type===e.Continuous}))(Hn),{getBillingType:Zc}=((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}}))(Hr,Pn,zr,Hi),{isAllocatedPrice:vg}=((e,t)=>({isAllocatedPrice:r=>r?e(r.config)===t.InArrearProrated:!1}))(Zc,zr),{priceToEnt:Yc}=(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}})(Iv),{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)}))(Zr,Qr),{constructBooleanFeature:iA}=((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})}))(Gr,tg,Ot),{constructMeteredFeature:oA}=((e,t,n,r)=>({constructMeteredFeature:({featureId:o,name:a,orgId:s,env:c,usageType:l,eventNames:u=[]})=>({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:l},archived:!1,event_names:u,model_markups:null})}))(Gr,tg,Ot,Av),{ApiFeatureV0Schema:aA}=((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."})})}))(ve,Ov),{CURRENCY_CODES:sA}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(ng,Pv,Cv),{RolloverConfigSchema:cA}=((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()})}))(ve,Vc),{EntitlementExpirySchema:uA}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(ve,Ev),{CreditDimensionNameSchema:lA}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(ve,Tv,Rv),{CreditDimensionBaseSchema:dA}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(ve,og),{graduatedCreditRateShape:wg}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(ve,kv),{ProviderMarkupsSchema:pA}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(ve,sg),{isAnyCreditSystem:mA}=((e,t)=>({isAnyCreditSystem:r=>r===e.CreditSystem||t(r)}))(Ot,Gc),{findCreditTierViolations:fA}=(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}}))(Dv),{findAmbiguousCreditDimensions:gA}=((e,t)=>({findAmbiguousCreditDimensions:r=>{let i=Object.entries(r),o=[];for(let[a,[s,c]]of i.entries())for(let[l,u]of i.slice(a+1))e(c,u)&&t(c.match,u.match)&&o.push({names:[s,l],example:{...c.match,...u.match}});return o}}))(Fv,cg),{validateMultipliersKeepRatesNonNegative:hA}=((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.`)}}))(Lv,Bv),{buildFixedPriceCurrencies:bA}=(e=>({buildFixedPriceCurrencies:n=>{if(!n?.length)return;let r={};for(let{currency:i,amount:o}of n)r[e(i)]={amount:o};return r}}))(ug),{PriceCurrencyConfigSchema:Og}=((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()})}))(ve,Hc),{baseCurrenciesAreCompatible:_A}=(e=>({baseCurrenciesAreCompatible:({base1:n,base2:r,currencies1:i,currencies2:o})=>(n??null)===(r??null)||e(i)!==e(o)}))(Kv),{tiersAreSame:Pg}=(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})}}))(Hv),{UsagePriceConfigSchema:yA}=((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()})}))(ve,Hi,Hc,Pn,Og,zn),{toFeature:SA}=((e,t,n,r,i,o,a)=>({toFeature:({item:c,orgId:l,internalFeatureId:u,internalProductId:d,isCustom:p,newVersion:g,feature:f,curEnt:h})=>{let I=f?.type===e.Boolean,v=t({item:c,feature:f}),S={id:c.entitlement_id||h?.id||n("ent"),org_id:l,created_at:c.created_at||Date.now(),is_custom:p,internal_product_id:d||null,internal_feature_id:u,feature_id:c.feature_id,allowance:c.included_usage===r?null:c.included_usage,allowance_type:I?null:c.included_usage===r?i.Unlimited:i.Fixed,interval:I?null:o({item:c}),interval_count:a({item:c}),carry_from_previous:!v,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(p||g)&&(S={...S,id:n("ent"),created_at:Date.now()}),{price:null,ent:S}}}))(Ot,lg,Gr,Ki,_a,xa,Ia),{creditDimensionRulesEqual:xA}=(e=>({creditDimensionRulesEqual:({left:n,right:r})=>e(n.dimensions??{})===e(r.dimensions??{})&&e(n.multipliers??{})===e(r.multipliers??{})}))(zc),{markupRecordsAreSame:IA}=(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)))}))(Jv),{itemToUsageType:vA}=((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}}))(pg,Ot,Cn),{itemToUsageType:AA}=((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}}))(n1,Ot,Cn),{isPreviewStripeId:wA}=((e,t)=>({isPreviewStripeId:({stripeId:r})=>r?.startsWith(e)===!0||r?.startsWith(t)===!0}))(a1,s1),{findPairedEntitlement:OA}=(e=>({findPairedEntitlement:({price:n,entitlements:r})=>e({price:n,entitlements:r})}))(Yc),{isConsumablePrice:PA}=((e,t)=>({isConsumablePrice:r=>r?e(r.config)===t.UsageInArrear:!1}))(Zc,zr),{validateLicenseLink:sM}=((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})}}))(m1,Dt,Vt),{evaluateCatalogItemIdentity:CA}=(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 l of c.split("."))a=a!==null&&typeof a=="object"?a[l]: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}}))(g1),{removeItems:EA}=(e=>({removeItems:(n,r)=>n.filter(i=>!r.some(o=>e({item:i,filter:o})))}))(b1),{toApiPlanItem:TA}=((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)})}))(y1,S1),{applyLicenses:RA}=(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}}))(I1),{pricesEqual:Cg}=(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)}))(Wc),{itemPricesEqual:kA}=((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)}}))(ya,Wc,A1),{featureOverridesEqual:jA}=((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??{})}))(P1,zc),{freeTrialsEqual:NA}=(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")}))(T1),{planItemFiltersEqual:DA}=(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)}))(k1),{toUpsertLicense:FA}=(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}:{}})}))(fg),{getVariantSettingsPatch:cM}=((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}}))(N1,D1),{isOneOffProductV2:uM}=((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)}}))(Aa,Xr,Wn,Pn),{canonicalizeBillingControls:UA}=(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))}}))(gg),{ProductConfigSchema:MA}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(ve,M1),{shouldApplyVariantUpdates:lM}=(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)}))(L1),{resolveLicenseParentTargets:dM}=((e,t,n)=>({resolveLicenseParentTargets:({contexts:i,targets:o,childPlanId:a})=>{let s=new Map(i.map(u=>[e({planId:u.parent.id,version:u.parent.version}),u])),c=new Set,l=[];for(let u of o){let d=e({planId:u.plan_id,version:u.version});if(c.has(d))throw new t({message:`Parent plan target ${d} was selected more than once.`,code:n.InvalidPropagationTarget,statusCode:400});let p=s.get(d);if(!p)throw new t({message:`Plan ${u.plan_id} v${u.version} does not offer ${a} as a license.`,code:n.InvalidPropagationTarget,statusCode:400});c.add(d),l.push(p)}return l}}))(B1,Dt,Vt),{stripeMinorUnitFactor:wa}=((e,t)=>({stripeMinorUnitFactor:r=>{let i=(r??"usd").toLowerCase();return e.has(i)?1:t.has(i)?1e3:100}}))(hg,q1),{entIntervalsSame:LA}=(e=>({entIntervalsSame:({intervalA:n,intervalB:r})=>{let i=e(n.interval,n.intervalCount),o=e(r.interval,r.intervalCount);return i.eq(o)}}))(V1),{intervalsDifferent:BA}=((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,$1),{allocatedBillingBehaviorAreSame:qA}=(e=>({allocatedBillingBehaviorAreSame:({item1:n,item2:r})=>{let i=e(n),o=e(r);return i===o}}))(K1),{tiersAreSame:VA}=(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))}))(Qc),{itemToPriceOrTiers:$A}=(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}}}))(W1),{normalizeBillingControls:GA}=((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)]]:[]}))}}))(J1,ba,X1),{AutoTopupPurchaseLimitSchema:KA}=((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."})})}))(ve,rA),{toFeatureItem:HA}=((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}}}))(Ot,_a,Ki,Sg),{toPriceItem:zA}=((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}}}))(xg,Sv),{isPayPerUsePrice:Eg}=((e,t)=>({isPayPerUsePrice:({price:r})=>{let i=e(r.config);return i===t.UsageInArrear||i===t.InArrearProrated}}))(Zc,zr),{createFeaturesFromItems:WA}=((e,t,n,r,i,o,a,s,c,l)=>({createFeaturesFromItems:({items:d,curFeatures:p,orgId:g,env:f})=>{let h=[];for(let I of d){if(!I.feature_id)continue;let v=p.find(S=>S.id===I.feature_id);if(v){if(e(I.feature_type))continue;if(I.feature_type===t.Static){if(I.feature_type===t.Static&&v.type!==n.Boolean)throw new r({message:`Feature ${I.feature_id} already exists but is not a static feature`,code:i.InvalidRequest,statusCode:400})}else if(I.feature_type!==v.config?.usage_type)throw new r({message:`Feature ${I.feature_id} already exists but is not a ${I.feature_type} feature`,code:i.InvalidRequest,statusCode:400});continue}if(o(I.feature_id),a(I)){let S=s({featureId:I.feature_id,orgId:g,env:f});h.push(S)}else{if(!I.feature_type)throw new r({message:`Feature type is required for ${I.feature_id}. Either 'continuous_use' or 'single_use'`,code:i.InvalidRequest,statusCode:400});let S=c({featureId:I.feature_id,orgId:g,env:f,usageType:I.feature_type===t.ContinuousUse?l.Continuous:l.Single});h.push(S)}}return{allFeatures:[...p,...h],newFeatures:h}}}))(Qr,Cn,Ot,Dt,Vt,vv,Ag,iA,oA,Hn),{SUPPORTED_SET:QA}=(e=>({SUPPORTED_SET:new Set(e)}))(sA),{CreditDimensionSchema:ZA}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(ve,dA,ag,wg),{FeatureMarkupsOverrideSchema:YA}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(ve,pA,Nv),{validateCreditRate:Tg}=(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}}))(fA),{validateDimensionsAreSeparable:JA}=((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.`)}}))(gA,Uv),{validateCreditMultipliers:XA}=((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})}}))(Mv,hA),{FixedPriceConfigSchema:ew}=((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})}))(ve,Pn,Og,Hc,Gv),{currenciesAreCompatible:tw}=(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}}))(Pg),{creditSchemaItemsAreSame:nw}=(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)}))(xA),{markupOverridesAreSame:rw}=(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)}))(IA),{resolveAllocatedBillingBehavior:iw}=((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}}))(hr,zn,Eg,vg),{itemCanBeProrated:ow}=((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}}))(AA,Cn,Wr),{priceHasPreviewStripeId:aw}=((e,t)=>({priceHasPreviewStripeId:({price:r})=>{let i=r.config;return e.some(o=>t({stripeId:i[o]}))}}))(o1,wA),{buildPlanItemKey:sw}=((e,t)=>({buildPlanItemKey:({item:r,matchPrecision:i=e.FeatureBillingMethodCadence})=>{let o=t({item:r});return i===e.FeatureCadence&&o.splice(1,1),o.join("|")}}))(f1,CA),{itemsEqual:Rg}=((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)}))(kA,w1,O1,jA),{licenseCustomizesAreSame:cw}=((e,t,n,r)=>({licenseCustomizesAreSame:({left:o,right:a})=>{let s=o??{},c=a??{},l={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(l).some(Boolean)}}))(Cg,R1,Rg,DA),{normalizeVariantSettingValue:uw}=((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}}))(UA,MA,gg),{intervalsSame:lw}=(e=>({intervalsSame:({intervalA:n,intervalB:r})=>!e({intervalA:n,intervalB:r})}))(BA),{sanitizeItems:dw}=((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}),l={...s,reset_usage_when_enabled:t({item:s,feature:a.find(u=>u.id===s.feature_id)}),...c};return l.config||(l.config={on_increase:n.ProrateImmediately,on_decrease:r.ProrateImmediately}),l})}))($A,Q1,Yr,zi),{compareBillingControls:pw}=(e=>({compareBillingControls:({newBillingControls:n,curBillingControls:r})=>e(n)===e(r)}))(GA),{AutoTopupSchema:mw}=((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."})})}))(ve,KA),{toFeaturePriceItem:fw}=((e,t,n,r,i,o,a,s,c,l,u)=>({toFeaturePriceItem:({ent:p,price:g})=>{let f=g.config,h=e(f.currencies,f.usage_tiers.length),I=f.usage_tiers.map((R,D)=>({amount:R.amount,to:R.to===-1?t:R.to,flat_amount:R.flat_amount,...h?.[D]?.length?{additional_currencies:h[D]}:{}})),v={};return g.proration_config&&(v={...g.proration_config}),n({feature:p.feature})&&r({price:g})&&(v.allocated_billing_behavior=f.allocated_billing_behavior??(i(g)?o.Prorated:o.Arrear)),p.rollover&&(v.rollover=p.rollover),p.expiry_duration&&p.expiry_length!=null&&(v.expiry={duration:p.expiry_duration,length:p.expiry_length}),p.feature_override&&(v.feature_override=p.feature_override),f.threshold_billing&&(v.threshold_billing=f.threshold_billing),{feature_id:p.feature.id,feature_type:p.feature.config?.usage_type||a.SingleUse,included_usage:p.allowance,interval:s({entInterval:p.interval}),interval_count:p.interval_count??1,price_interval:c({billingInterval:f.interval}),price_interval_count:f.interval_count??1,price:null,tiers:I,base_currency:f.base_currency??void 0,billing_units:f.billing_units,tier_behavior:g.tier_behavior??null,entity_feature_id:p.entity_feature_id,pooled:p.pooled??!1,reset_usage_when_enabled:!p.carry_from_previous,usage_model:f.bill_when===l.StartOfPeriod||f.bill_when===l.InAdvance?u.Prepaid:u.PayPerUse,created_at:p.created_at,entitlement_id:p.id,price_id:g.id,price_config:g.config,config:Object.keys(v).length>0?v:void 0,usage_limit:p.usage_limit}}}))(xv,Bc,Ig,Eg,vg,zn,Cn,Sg,xg,Hi,Wr),{isValidCurrencyCode:Jc}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(QA),{CreditSchemaItemBaseSchema:kg}=((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()})}))(ve,lA,ZA,jv),{GraduatedCreditSchemaItemSchema:gw}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(kg,wg),{validateCreditDimensionRules:hw}=((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})}}))(Tg,JA,XA),{pricesAreSame:Oa}=((e,t,n,r,i,o,a,s)=>({pricesAreSame:(l,u,d=!1)=>{let p=l.config,g=u.config;if(p.type!==g.type)return!1;if(p.type===e.Fixed){let D=t.parse(p),P=t.parse(g),be={amount:D.amount!==P.amount,interval:D.interval!==P.interval,intervalCount:(D.interval_count??1)!==(P.interval_count??1),baseCurrency:!n({base1:D.base_currency,base2:P.base_currency,currencies1:D.currencies,currencies2:P.currencies}),currencies:!r(D.currencies,P.currencies)};return!Object.values(be).some(Boolean)}let f=i.parse(p),h=i.parse(g),I={shouldProrate:(f.should_prorate??!1)!==(h.should_prorate??!1),allocatedBillingBehavior:o(f)!==o(h),billWhen:f.bill_when!==h.bill_when,billingUnits:(f.billing_units??1)!==(h.billing_units??1),thresholdBilling:f.threshold_billing?.threshold!==h.threshold_billing?.threshold,interval:f.interval!==h.interval,intervalCount:(f.interval_count??1)!==(h.interval_count??1),internalFeatureId:f.internal_feature_id!==h.internal_feature_id,featureId:f.feature_id!==h.feature_id,usageTiers:!a(f.usage_tiers,h.usage_tiers),baseCurrency:!n({base1:f.base_currency,base2:h.base_currency,currencies1:f.currencies,currencies2:h.currencies}),currencies:!r(f.currencies,h.currencies)},v=f.usage_tiers.length<=1&&h.usage_tiers.length<=1,S={onIncrease:l.proration_config?.on_increase!=u.proration_config?.on_increase,onDecrease:l.proration_config?.on_decrease!=u.proration_config?.on_decrease,tierBehavior:!v&&(l.tier_behavior??s.Graduated)!==(u.tier_behavior??s.Graduated)},R=Object.values(I).some(Boolean)||Object.values(S).some(Boolean);return R&&d&&console.log("Prices are different",{configDiffs:I,prorationDiffs:S}),!R}}))(Hr,ew,_A,tw,yA,zv,Pg,ya),{creditSchemasAreSame:bw}=(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})}))(nw),{itemToAllocatedBillingBehavior:_w}=((e,t,n,r,i,o,a,s,c)=>({itemToAllocatedBillingBehavior:({item:u,features:d,curPrice:p})=>{if(!(e({item:u,features:d})===t.ContinuousUse&&n(u)&&u.usage_model!==r.Prepaid))return null;let h=i({item:u,curPrice:p});if(h===o.Arrear){if(a(u.config?.on_increase)||a(u.config?.on_decrease))throw new s({message:`on_increase / on_decrease are not supported for allocated arrear billing (feature: ${u.feature_id})`,code:c.InvalidProductItem,statusCode:400});if(a(u.config?.rollover))throw new s({message:`rollover is not supported for allocated arrear billing because the balance never resets (feature: ${u.feature_id})`,code:c.InvalidProductItem,statusCode:400})}return h}}))(vA,Cn,Xr,Wr,iw,zn,hr,Dt,e1),{composeMatchKey:Wi}=(e=>({composeMatchKey:n=>e({item:n})}))(sw),{applyItems:yw}=((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 l of s)t(l)&&c.add(n(l));for(let l of a.add_items){let u=n(l);t(l)&&c.has(u)||(s.push(r(l)),t(l)&&c.add(u))}}return s}}))(EA,_1,Wi,TA),{dedupeItemsByMatchKey:Sw}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let o=e(i);return r.has(o)?!1:(r.add(o),!0)})}}))(Wi),{planLicensesAreSame:xw}=(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)}}))(cw),{dedupeItemsByMatchKey:Iw}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let o=e(i);return r.has(o)?!1:(r.add(o),!0)})}}))(Wi),{validateVariantSettingsUpdate:pM}=((e,t,n,r)=>({validateVariantSettingsUpdate:({allowVariantSettingsUpdate:o,fullProduct:a,currentProduct:s,updates:c})=>{if(o||a.base_internal_product_id==null)return;let l=e.find(u=>c[u]===void 0?!1:t({field:u,value:c[u]})!==t({field:u,value:s[u]}));if(l)throw new n({message:`Cannot update ${l} directly on a variant plan.`,code:r.InvalidPropagationTarget,statusCode:400})}}))(U1,uw,Dt,Vt),{findSimilarItem:Xc}=((e,t,n,r,i,o,a,s,c)=>({findSimilarItem:({item:u,items:d})=>e(u)?d.find(p=>e(p)&&p.feature_id===u.feature_id&&p.entity_feature_id==u.entity_feature_id&&t({intervalA:{interval:n({item:p}),intervalCount:r({item:p})},intervalB:{interval:n({item:u}),intervalCount:r({item:u})}})):i(u)?d.find(p=>i(p)&&p.feature_id===u.feature_id&&p.entity_feature_id==u.entity_feature_id&&o({intervalA:{interval:a({item:p}),intervalCount:s({item:p})},intervalB:{interval:a({item:u}),intervalCount:s({item:u})}})&&u.usage_model==p.usage_model):c(u)?d.find(p=>c(p)&&p.price==u.price&&a({item:p})==a({item:u})&&s({item:p})==s({item:u})):null}))(va,LA,xa,Ia,Xr,lw,Wn,Jr,Aa),{stripAutoTopupCountsForStorage:vw}=(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}))}))(mw),{toProductItem:jg}=((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,HA,zA,fw),{CurrencyCodeSchema:Ng}=((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')."})}))(ve,Jc),{AdditionalCurrencyPriceSchema:Aw}=((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."})})}))(ve,Ng),{FlatCreditSchemaItemSchema:ww}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(kg,ag),{validateCreditSystem:Ow}=((e,t,n,r,i,o,a,s)=>({validateCreditSystem:(l,u=e.CreditSystem)=>{let d=Array.isArray(l?.schema)?l.schema:[],p=S=>{throw new t({message:S,code:n.InvalidFeature,statusCode:r.BAD_REQUEST})};!i(u)&&d.length===0&&p("At least one metered feature is required for credit system"),i(u)&&d.length>0&&p("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),f=Array.from(new Set(g));g.length!==f.length&&p("Credit system contains multiple of the same metered_feature_id");let h={...l,schema:d,usage_type:o.Single},I=h.default_markup;if(I!=null){let S=Number(I);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});h.default_markup=S}let v=h.provider_markups;if(v!=null)for(let[S,R]of Object.entries(v)){let D=Number(R?.markup);if(!S||Number.isNaN(D)||D<-100)throw new t({message:"Provider markups must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});R.markup=D}for(let S of h.schema){if(S.feature_amount!==void 0){let R=Number(S.feature_amount);(!Number.isFinite(R)||R<=0)&&p("Billing units must be greater than zero."),S.feature_amount=R}a({rate:S,invalidCreditSystem:p}),s({schemaItem:S,invalidCreditSystem:p})}return h}}))(Ot,Dt,Vt,Kn,Gc,Hn,Tg,hw),{stripePriceIdForInitializedPrice:Dg}=((e,t,n)=>({stripePriceIdForInitializedPrice:({requestedStripePriceId:i,currentPrice:o,newPrice:a})=>{if(!e(i)&&(!o||i!==t({price:o})||n(o,a)))return i}}))(Yt,$v,Oa),{featureOverridesAreSame:eu}=((e,t)=>({featureOverridesAreSame:({override1:r,override2:i})=>e({schema1:r?.schema,schema2:i?.schema})&&t({markups1:r?.markups,markups2:i?.markups})}))(bw,rw),{applyDiff:Fg}=((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}}}))(h1,yw,x1,RA),{diffPlanLicenses:Pw}=((e,t,n,r)=>({diffPlanLicenses:({from:o,to:a,includeAdds:s=!1,includeRemoves:c=!1})=>{let l=new Map((o??[]).map(g=>[g.license_plan_id,g])),u=new Map((a??[]).map(g=>[g.license_plan_id,g])),d=[];for(let g of u.values()){let f=l.get(g.license_plan_id);!f&&!s||f&&e({left:f,right:g})||d.push(t({license:g,clearCustomize:f!=null&&n(f.customize)&&!n(g.customize)}))}let p=c?[...l.keys()].filter(g=>!u.has(g)).map(g=>({license_plan_id:g})):[];return{...d.length>0?{upsert_licenses:d.sort(r)}:{},...p.length>0?{remove_licenses:p.sort(r)}:{}}}}))(xw,FA,fg,j1),{applyDiffToVariantPlan:mM}=((e,t)=>({applyDiffToVariantPlan:({plan:r,diff:i,settingsPatch:o={}})=>{let a=e({base:r,diff:i});return{...r,...a,...o,items:t(a.items)}}}))(Fg,Iw),{mapToProductItems:Ug}=((e,t,n,r)=>({mapToProductItems:({prices:o,entitlements:a,features:s})=>{let c=[];o??=[],a??=[];for(let l of a){let u=e({ent:l,prices:o}),d=t({ent:l,price:u});c.push(d)}for(let l of o)n({price:l,entitlements:a})||c.push(t({price:l}));for(let l of c)s.find(d=>d.id===l.feature_id)&&(l.feature_type=r({item:l,features:s}));return c}}))(Jf,jg,Yc,Xf),{featureItemsAreSame:Cw}=((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(l=>l.condition);return!c&&a&&console.log("Feature items different:",Object.values(s).filter(l=>!l.condition).map(l=>l.message)),c}}))(_g,yg,eu),{featurePriceItemsAreSame:Ew}=((e,t,n,r,i,o,a,s,c,l)=>({featurePriceItemsAreSame:({item1:d,item2:p,logDifferences:g=!1})=>{let f={included_usage:{condition:e(d.included_usage)==e(p.included_usage),message:`Included usage different: ${d.included_usage} != ${p.included_usage}`},usage_limit:{condition:d.usage_limit==p.usage_limit,message:`Usage limit different: ${d.usage_limit} !== ${p.usage_limit}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(p.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${p.reset_usage_when_enabled}`},proration_config:{condition:t({config1:d.config||void 0,config2:p.config||void 0}),message:`Proration config different: ${JSON.stringify(d.config)} !== ${JSON.stringify(p.config)}`},allocated_billing_behavior:{condition:n({item1:d,item2:p}),message:`Allocated billing behavior different: ${d.config?.allocated_billing_behavior} !== ${p.config?.allocated_billing_behavior}`},rollover_config:{condition:r({rollover1:d.config?.rollover||void 0,rollover2:p.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(d.config?.rollover)} !== ${JSON.stringify(p.config?.rollover)}`},feature_override:{condition:i({override1:d.config?.feature_override,override2:p.config?.feature_override}),message:`Feature override different: ${JSON.stringify(d.config?.feature_override)} !== ${JSON.stringify(p.config?.feature_override)}`},threshold_billing:{condition:(d.config?.threshold_billing?.threshold??null)===(p.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(d.config?.threshold_billing)} !== ${JSON.stringify(p.config?.threshold_billing)}`},entity_feature_id:{condition:d.entity_feature_id==p.entity_feature_id,message:`Entity feature ID different: ${d.entity_feature_id} != ${p.entity_feature_id}`},pooled:{condition:(d.pooled??!1)===(p.pooled??!1),message:`Pooled different: ${d.pooled} != ${p.pooled}`}},h={feature_id:{condition:d.feature_id===p.feature_id,message:`Feature ID different: ${d.feature_id} != ${p.feature_id}`},interval:{condition:o({item:d})==o({item:p}),message:`Billing interval different: ${o({item:d})} != ${o({item:p})}`},interval_count:{condition:a({item:d})==a({item:p}),message:`Billing interval count different: ${a({item:d})} != ${a({item:p})}`},usage_model:{condition:d.usage_model===p.usage_model,message:`Usage model different: ${d.usage_model} != ${p.usage_model}`},pricing:{condition:s(c(d),c(p)),message:`Pricing different: ${JSON.stringify(c(d))} != ${JSON.stringify(c(p))}`},additional_currencies:{condition:l(d.additional_currencies,p.additional_currencies),message:"Additional currencies different"},tier_behavior:{condition:(c(d)?.length??0)<=1&&(c(p)?.length??0)<=1?!0:d.tier_behavior==p.tier_behavior,message:`Tiers type different: ${d.tier_behavior} != ${p.tier_behavior}`},billing_units:{condition:d.billing_units==p.billing_units,message:`Billing units different: ${d.billing_units} !== ${p.billing_units}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(p.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${p.reset_usage_when_enabled}`}},I=Object.values(h).every(S=>S.condition)&&Object.values(f).every(S=>S.condition),v=Object.values(h).some(S=>!S.condition);return!I&&g&&console.log("Feature price items different:",Object.values(f).filter(S=>!S.condition).map(S=>S.message),Object.values(h).filter(S=>!S.condition).map(S=>S.message)),{same:I,pricesChanged:v}}}))(_g,G1,qA,yg,eu,Wn,Jr,VA,H1,Qc),{pickBillingControlColumns:Tw}=((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}}))(ba,vw),{mapToProductV2:fM}=((e,t,n,r,i)=>({mapToProductV2:({product:a,features:s})=>{let c=[];for(let u of a.entitlements){let d=e({ent:u,prices:a.prices});c.push(t({ent:u,price:d}))}for(let u of a.prices)n({price:u,entitlements:a.entitlements})||c.push(t({price:u}));s||(s=a.entitlements.map(u=>u.feature));for(let u of c)u.feature_type=r({item:u,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??{}}}}))(Jf,jg,Yc,Xf,eg),{AdditionalCurrencyTierSchema:Rw}=((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"]})}))(ve,Ng),{AdditionalCurrencyPriceArraySchema:kw}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(ve,Aw,rg,ig),{CreditSchemaItemSchema:jw}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(ve,ww,gw),{validateItemFeatureOverride:Nw}=((e,t,n,r,i,o,a,s,c)=>({validateItemFeatureOverride:({item:u,feature:d,features:p})=>{let g=u.config?.feature_override;if(!g)return;let f=I=>{throw new e({message:`${I} (feature: ${u.feature_id})`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})};if(!(d&&r(d.type))){f("feature_override is only supported on credit system items");return}if(g.schema&&d.type!==i.CreditSystem&&f("feature_override.credit_schema is not supported on AI credit system items"),g.markups&&!o(d.type)&&f("feature_override.markups is only supported on AI credit system items"),!g.schema)return;let h={schema:g.schema,usage_type:a.Single};s(h,d.type),c({config:h,allFeatures:p});for(let I of g.schema)if(!p.find(S=>S.id===I.metered_feature_id))throw new e({message:`feature_override on ${d.id} references unknown feature ${I.metered_feature_id}`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})}}))(Dt,Vt,Kn,mA,Ot,Gc,Hn,Ow,qv),{toPrice:Dw}=((e,t,n,r,i,o,a)=>({toPrice:({item:c,orgId:l,internalProductId:u,isCustom:d,newVersion:p,curPrice:g})=>{let f={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},h=i(c.additional_currencies);h&&(f.currencies=h);let I=c.base_currency??(h?g?.config?.base_currency:void 0);I&&(f.base_currency=I);let v={id:c.price_id||g?.id||o("pr"),created_at:c.created_at||Date.now(),org_id:l,internal_product_id:u,is_custom:d,config:f,proration_config:null};return(d||p)&&(v={...v,id:o("pr"),created_at:Date.now()}),f.stripe_price_id=a({requestedStripePriceId:c.stripe_price_id,currentPrice:g,newPrice:v}),{price:v,ent:null}}}))(Hr,Zr,Wn,Jr,bA,Gr,Dg),{entsAreSame:tu}=((e,t,n,r,i,o,a)=>({entsAreSame:(c,l)=>{if(c.internal_feature_id!==l.internal_feature_id||e(c)!==e(l))return!1;let u=e(c),d={interval:t(c)!==t(l),intervalCount:n(c)!==n(l),allowance:!u&&c.allowance!=l.allowance,carryFromPrevious:(c.carry_from_previous??!1)!==(l.carry_from_previous??!1),entityFeatureId:r(c.entity_feature_id)!==r(l.entity_feature_id),pooled:(c.pooled??!1)!==(l.pooled??!1),usageLimit:c.usage_limit!=l.usage_limit,rollover:!i({rollover1:c.rollover,rollover2:l.rollover}),featureOverride:!o({override1:c.feature_override,override2:l.feature_override}),expiry:!a(c,l)};return!Object.values(d).some(Boolean)}}))(Wv,dg,Qv,Zv,Yv,eu,Xv),{toFeatureAndPrice:Fw}=((e,t,n,r,i,o,a,s,c,l,u,d,p,g,f,h,I,v,S,R,D,P,be,tt,We,je,ue,$)=>({toFeatureAndPrice:({item:Q,orgId:dt,internalFeatureId:me,internalProductId:ce,isCustom:$t,curPrice:Qe,curEnt:Gt,newVersion:En,features:Jt})=>{let Bg=e({item:Q,feature:Jt.find(Et=>Et.id===Q.feature_id)}),Pa=t({item:Q,features:Jt,curPrice:Qe}),iu=Pa===n.Arrear,br={id:Q.entitlement_id||Gt?.id||r("ent"),org_id:dt,created_at:Q.created_at||Date.now(),is_custom:$t,internal_product_id:ce,internal_feature_id:me,feature_id:Q.feature_id,allowance:Q.included_usage||0,allowance_type:i.Fixed,interval:o({item:Q}),interval_count:a({item:Q}),carry_from_previous:!Bg,entity_feature_id:Q.entity_feature_id,pooled:Q.pooled??!1,usage_limit:Q.usage_limit||null,rollover:Q.config?.rollover,expiry_duration:Q.config?.expiry?.duration,expiry_length:Q.config?.expiry?.length,feature_override:Q.config?.feature_override};(!Gt||$t&&!s(Gt,br)||En)&&(br={...br,id:r("ent"),created_at:Date.now()});let qg=o({item:Q}),ei={type:c.Usage,bill_when:Q.usage_model===l.Prepaid?u.StartOfPeriod:u.EndOfPeriod,billing_units:Q.billing_units||1,...Q.config?.threshold_billing?{threshold_billing:Q.config.threshold_billing}:{},should_prorate:qg===d.Lifetime&&!iu,...Pa?{allocated_billing_behavior:Pa}:{},internal_feature_id:me,feature_id:Q.feature_id,usage_tiers:p(Q.price)?[{amount:Q.price,to:g}]:Q.tiers?.map(Et=>({to:Et.to,amount:Et.amount??0,...Et.flat_amount!=null?{flat_amount:Et.flat_amount}:{}})),interval:f({item:Q}),interval_count:h({item:Q}),stripe_price_id:void 0},ou=I({baseTiers:ei.usage_tiers,itemTiers:Q.tiers,flatCurrencies:Q.additional_currencies});ou&&(ei.currencies=ou,ei.base_currency=Q.base_currency??Qe?.config?.base_currency??void 0);let Vg=v({item:Q,features:Jt})&&!iu,au=null;if(Vg){let Et=Q.config?.on_increase||S.ProrateImmediately,Qn=Q.config?.on_decrease||R.Prorate;(D(Qn)||Qn===R.Prorate)&&(Qn=Et===S.ProrateImmediately||Et===S.BillImmediately?R.ProrateImmediately:R.ProrateNextCycle),au={on_increase:Et,on_decrease:Qn}}let Sn={id:Q.price_id||Qe?.id||r("pr"),created_at:Q.created_at||Date.now(),org_id:dt,internal_product_id:ce,is_custom:$t,config:ei,entitlement_id:br.id,proration_config:au,tier_behavior:Q.tier_behavior??null},su=P(Sn.config);if((su===be.UsageInArrear||su===be.InArrearProrated)&&Sn.config.interval===tt.OneOff)throw new We({message:`Usage prices cannot be one-off if not set to prepaid (feature: ${Q.feature_id})`,code:je.InvalidPrice,statusCode:400});let $g=Qe&&!ue(Qe,Sn,!0)||Gt&&!s(Gt,br);if(Qe&&($g||En)){let Et=Sn.config,Qn=Qe.config;Et.stripe_meter_id=Qn.stripe_meter_id,Et.stripe_product_id=Qn.stripe_product_id,Sn.config=Et}return($t||En)&&(Sn={...Sn,id:r("pr"),created_at:Date.now()}),ei.stripe_price_id=$({requestedStripePriceId:Q.stripe_price_id,currentPrice:Qe,newPrice:Sn}),{price:Sn,ent:br}}}))(lg,_w,zn,Gr,_a,xa,Ia,tu,Hr,Wr,Hi,Kr,Zr,Bc,Wn,Jr,t1,ow,Yr,zi,r1,i1,zr,Pn,Dt,Vt,Oa,Dg),{getPriceStripeReuseLevel:Uw}=((e,t,n,r,i,o)=>({getPriceStripeReuseLevel:({newPrice:s,candidatePrice:c,newEntitlements:l,candidateEntitlements:u})=>{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 h=r({price:s,entitlements:l}),I=r({price:c,entitlements:u});if(!h&&!I)return"full";if(!h||!I)return"none";if(i(I,h))return"full"}if(s.config?.type!==n.Usage)return"none";let d=s.config,p=c.config;if(d.feature_id!==p.feature_id)return"none";let g=r({price:s,entitlements:l}),f=r({price:c,entitlements:u});return!g&&!f?"stripeProductOnly":!g||!f||o(g.entity_feature_id)!==o(f.entity_feature_id)?"none":"stripeProductOnly"}}))(aw,Oa,Hr,OA,tu,c1),{applyLicenseCustomizeToBasePlan:gM}=((e,t,n)=>({applyLicenseCustomizeToBasePlan:({basePlan:i,customize:o})=>{let a=new Set((o.add_items??[]).map(l=>e(l))),s={...i,items:i.items.filter(l=>!a.has(e(l)))},c=t({base:s,diff:o});return{...s,...c,items:n(c.items)}}}))(Wi,Fg,Sw),{diffPlanV1:Mw}=((e,t,n,r,i,o,a,s,c)=>({diffPlanV1:({from:u,to:d,includeAdds:p=!1,includeRemoves:g=!1,filterPrecision:f=e.Identity})=>{let h={};t(u.price,d.price)||(h.price=d.price===null?null:n(d.price));let I=new Map(u.items.map(D=>[r(D),D])),v=new Map(d.items.map(D=>[r(D),D])),S=[];for(let D of d.items){let P=I.get(r(D));(!P||!i(P,D))&&S.push(o(D))}S.length>0&&(h.add_items=S);let R=[];for(let D of u.items){let P=v.get(r(D));(!P||!i(D,P))&&R.push(a({item:D,filterPrecision:f}))}if(R.length>0&&(h.remove_items=R),!s(u.free_trial,d.free_trial))if(d.free_trial==null)h.free_trial=null;else{let{on_end:D,...P}=d.free_trial;h.free_trial=D==null?P:{...P,on_end:D}}return Object.assign(h,c({from:u.licenses,to:d.licenses,includeAdds:p,includeRemoves:g})),h}}))(mg,Cg,v1,Wi,Rg,C1,E1,NA,Pw),{currentItemsOf:Mg}=(e=>({currentItemsOf:({currentFullProduct:n,features:r})=>e({prices:n.prices,entitlements:n.entitlements,features:r})}))(Ug),{itemsAreSame:Lg}=((e,t,n,r,i,o,a,s)=>({itemsAreSame:({item1:l,item2:u,features:d,logDifferences:p=!1})=>{let g=!1,f=!1;if(e(l)){if(!e(u))return{same:!1,pricesChanged:!0};g=t({item1:l,item2:u,logDifferences:p}),f=!1}if(n(l)){if(!n(u))return{same:!1,pricesChanged:!0};let{same:h,pricesChanged:I}=r({item1:l,item2:u,logDifferences:p});g=h,i({item:l,features:d||[]})?.config?.usage_type===o.Continuous?f=!0:f=I}return a(l)&&(g=s({item1:l,item2:u,logDifferences:p}),g||(f=!0)),{same:g,pricesChanged:!g&&f}}}))(va,Cw,Xr,Ew,pg,Hn,Aa,z1),{productsAreSame:hM}=((e,t,n,r,i,o,a,s,c,l,u,d,p)=>({productsAreSame:({newProductV1:f,newProductV2:h,curProductV1:I,curProductV2:v,features:S})=>{if(!f&&!h)throw new Error("productsAreSame error: product1 not provided");if(!I&&!v)throw new Error("productsAreSame error: product2 not provided");let R=h?.items||e({prices:f?.prices||[],entitlements:f?.entitlements||[],features:S}),D=v?.items||e({prices:I?.prices||[],entitlements:I?.entitlements||[],features:S});R=t({items:R,features:S}),D=t({items:D,features:S});let P=!0,be=!1,tt=!0,We=!0,je=!0,ue=[],$=[];tt=n({newProductV2:h,curProductV2:v}),We=r({newConfig:h?.config,curConfig:v?.config}),je=i({newBillingControls:h?.billing_controls??(f?o(f):void 0),curBillingControls:v?.billing_controls??(I?o(I):void 0)});let De=a({newMetadata:h?.metadata,curMetadata:v?.metadata});R.length!==D.length&&(P=!1),R.length!==D.length&&(P=!1);for(let Qe of R){let Gt=s({item:Qe,items:D});if(!Gt){(c(Qe)||l(Qe))&&(be=!0),P=!1,ue.push(Qe);continue}let{same:En,pricesChanged:Jt}=u({item1:Qe,item2:Gt,features:S,logDifferences:!1});En||(P=!1,ue.push(Qe)),Jt&&(be=!0)}for(let Qe of D)s({item:Qe,items:R})||(P=!1,(c(Qe)||l(Qe))&&(be=!0),$.push(Qe));let Q=I?.free_trial||v?.free_trial,dt=f?.free_trial||h?.free_trial,me=d({ft1:Q,ft2:dt}),ce=p({curProduct:v||I,newProduct:h||f});return{itemsSame:P,freeTrialsSame:me,onlyEntsChanged:!be,newItems:ue,removedItems:$,detailsSame:tt,optionsSame:ce,configSame:We,billingControlsSame:je,metadataSame:De,same:P&&tt&&me&&We&&De&&je}}}))(Ug,dw,Z1,Y1,pw,eg,eA,Xc,Xr,Aa,Lg,tA,nA),{constructProduct:bM}=((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??{}})}))(Gr,Tw),{AdditionalCurrencyTierArraySchema:Lw}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(ve,Rw,rg,ig),{FeatureConfigOverrideSchema:Bw}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(ve,jw,YA),{itemToPriceAndEnt:qw}=((e,t,n,r,i,o,a,s,c,l)=>({itemToPriceAndEnt:({item:d,orgId:p,internalProductId:g,feature:f,curPrice:h,curEnt:I,isCustom:v,newVersion:S,features:R})=>{let D=null,P=null,be=null,tt=null,We=null,je=null;if(e(d)){let{price:ue}=t({item:d,orgId:p,internalProductId:g,isCustom:v,newVersion:S,curPrice:h});!h||S?D=ue:n(h,ue,!0)?We=h:be=ue}else if(r(d)){if(!f)throw new i({message:`Feature ${d.feature_id} not found`,code:o.InvalidRequest});let ue=f?.type===a.Boolean,{ent:$}=s({item:d,orgId:p,internalFeatureId:f.internal_id,internalProductId:g,isCustom:v,newVersion:S,feature:f,curEnt:I});!I||S?P=$:c(I,$)?je=I:tt=$}else{if(!f)throw new i({message:`Feature ${d.feature_id} not found`,code:o.InvalidRequest});let{price:ue,ent:$}=l({item:d,orgId:p,internalFeatureId:f.internal_id,internalProductId:g,isCustom:v,curPrice:h,curEnt:I,newVersion:S,features:R}),De=I&&c(I,$);!h||S?D=ue:!De||!n(h,ue,!1)?be=ue:We=h,!I||S?P=$:De?je=I:tt=$}return{newPrice:D,newEnt:P,updatedPrice:be,updatedEnt:tt,samePrice:We,sameEnt:je}}}))(Kc,Dw,Oa,Sa,Dt,Vt,Ot,SA,tu,Fw),{copyStripeResourcesToMatchingPrice:Vw}=((e,t,n,r,i)=>({copyStripeResourcesToMatchingPrice:({targetPrice:a,candidatePrices:s,targetEntitlements:c,candidateEntitlements:l})=>{let u=s.map(v=>({candidatePrice:v,level:e({newPrice:a,candidatePrice:v,newEntitlements:c,candidateEntitlements:l})})),d=u.find(v=>v.level==="full"),g=(d??u.find(v=>v.level==="stripeProductOnly"))?.candidatePrice,f=d?.candidatePrice,h=a.config,I=[];if(g){let v=g.config;for(let S of t)S==="stripe_meter_id"&&(!n(a)||!n(g))||r({fromConfig:v,toConfig:h,field:S})&&I.push(S)}if(f){let v=f.config;for(let S of i)t.includes(S)||r({fromConfig:v,toConfig:h,field:S})&&I.push(S)}return{copiedFields:I}}}))(Uw,u1,PA,l1,d1),{getApiPlanDiff:_M}=(e=>({getApiPlanDiff:({from:n,to:r})=>e({from:n,to:r})}))(Mw),{backfillExistingItemIds:$w}=((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})}}))(Mg,Xc),{PriceTierSchema:Gw}=((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}))}))(ve,Bc,Lw),{ProductItemConfigSchema:Kw}=((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()})}))(ve,zn,Yr,zi,cA,uA,Bw),{carryForwardStripeResources:Hw}=(e=>({carryForwardStripeResources:({targetPrices:n,targetEntitlements:r,candidatePrices:i,candidateEntitlements:o})=>{for(let a of n)e({targetPrice:a,candidatePrices:i,targetEntitlements:r,candidateEntitlements:o})}}))(Vw),{resolveInPlaceEdit:yM}=((e,t,n,r)=>({resolveInPlaceEdit:async({db:o,items:a,currentFullProduct:s,features:c})=>{let l=e({items:a,currentFullProduct:s,features:c}),u=t({currentFullProduct:s,features:c}),d=[],p=[];for(let h of u){let I=n({item:h,items:l}),v=!I,S=I&&!r({item1:I,item2:h,features:c}).same;(v||S)&&(h.entitlement_id&&d.push(h.entitlement_id),h.price_id&&p.push(h.price_id))}let g=new Set([...d,...p]),f=l.map(h=>{let I=h.entitlement_id&&g.has(h.entitlement_id),v=h.price_id&&g.has(h.price_id);return I||v?{...h,entitlement_id:void 0,price_id:void 0}:h});return{retiredEntitlementIds:d,retiredPriceIds:p,items:f,curPrices:s.prices.filter(h=>!g.has(h.id)),curEnts:s.entitlements.filter(h=>!g.has(h.id))}}}))($w,Mg,Xc,Lg),{ProductItemSchema:zw}=((e,t,n,r,i,o,a,s,c,l,u)=>({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(p=>{if(p==="")throw new Error("Interval cannot be empty.");return p},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(l).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:u.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})})}))(ve,wv,Cn,aA,Ki,qc,Wr,Gw,kw,ya,Kw),{validateProductItem:Ww}=((e,t,n,r,i,o,a,s,c,l,u,d,p,g,f,h,I,v,S,R)=>({validateProductItem:({item:P,features:be,multiCurrencyEnabled:tt,validateRollover:We})=>{P=e.parse(P);let je=be.find(me=>me.id===P.feature_id);if(t(P.feature_id)&&t(P.price)&&t(P.tiers))throw new n({message:"Either 'feature_id', 'price', or both should be set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let ue=P.pooled&&je?.type===o.Boolean,$=a(P)||s(P.included_usage)&&P.included_usage!==0||s(P.interval)||s(P.config?.rollover);if(ue&&$)throw new n({message:"Pooled boolean items cannot include balance or pricing fields",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(c({item:P,feature:je,features:be}),a(P)&&P.included_usage===l)throw new n({message:"Unlimited items cannot include pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(P.pooled&&a(P)&&P.usage_model===u.PayPerUse)throw new n({message:"Pooled items cannot use usage-based pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(s(P.price)&&s(P.tiers))throw new n({message:"Either 'price' or 'tiers' should be set, not both",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let De=(P.additional_currencies?.length??0)>0||(P.tiers?.some(me=>(me.additional_currencies?.length??0)>0)??!1);if(De&&!tt)throw new n({message:"Multi-currency is not enabled for this organization",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(De&&t(P.base_currency))throw new n({message:"'base_currency' is required when 'additional_currencies' are set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if((P.additional_currencies?.length??0)>0){if(s(P.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(P.price)&&P.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(P)&&P.price&&P.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(P)||p(P)){if(typeof P.included_usage!="number"&&P.included_usage!==l&&s(P.included_usage))throw new n({message:`Included usage for feature ${P.feature_id} must be a number or '${l}'`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(t(P.included_usage)&&(P.included_usage=0),typeof P.included_usage=="number"&&P.included_usage<0)throw new n({message:"Included usage must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(a(P)||d(P)){let me=g({item:P});if(String(me)===f.Day||String(me)===f.Minute||String(me)===f.Hour)throw new n({message:"Price can't have day, minute or hour interval",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(a(P)&&t(P.usage_model))throw new n({message:`Usage model is required for priced features. Please select one for the feature ${P.feature_id}`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(a(P)&&P.tiers){if(P.included_usage===l)throw new n({message:`Included usage can't be '${l}' for tiered prices`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(P.billing_units&&P.billing_units<=0)throw new n({message:"Billing units must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(P.tier_behavior===h.VolumeBased&&P.tiers.length>1&&P.usage_model!==u.Prepaid)throw new n({message:"Volume-based pricing is only supported for prepaid items",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(P.tiers.some(ce=>ce.flat_amount!=null&&ce.flat_amount>0)){if(P.tier_behavior!==h.VolumeBased)throw new n({message:"flat_amount on tiers is only supported for volume-based pricing",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(P.tiers.length<=1)throw new n({message:"flat_amount is not supported on single-tier pricing",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(P.tiers.some(ce=>ce.flat_amount!=null&&ce.flat_amount<0))throw new n({message:"flat_amount must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(P.usage_model===u.Prepaid&&P.config?.on_increase===I.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(P.config?.expiry&&je&&(je.type===o.Boolean||v({feature:je})))throw new n({message:`expiry is only supported on consumable features (feature: ${P.feature_id})`,code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(!P.config?.rollover)return;let Q=P.config.rollover;if(Q.duration===S.Forever&&(Q.length=0),!We)return;if(P.included_usage===l)throw new n({message:"Unlimited items cannot have rollover",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let dt=R({rollover:Q});if(dt)throw new n({message:dt,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(Q.duration===S.Month&&(typeof Q.length!="number"||Q.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(P.usage_limit)&&P.usage_limit<=0)throw new n({message:"Usage limit must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}}))(zw,Yt,Dt,Vt,Kn,Ot,$c,hr,Nw,Ki,Wr,Kc,Sa,Wn,qc,ya,Yr,Ig,Vc,Vv),{validateProductItems:Qw}=((e,t,n,r,i,o,a,s,c,l,u,d,p,g,f)=>({validateProductItems:({newItems:I,features:v,orgId:S,env:R,multiCurrencyEnabled:D,validateRollover:P=!0})=>{let{allFeatures:be,newFeatures:tt}=e({items:I,curFeatures:v,orgId:S,env:R});v=be;for(let ue=0;ue<I.length;ue++){t({item:I[ue],features:v,multiCurrencyEnabled:D,validateRollover:P});let $=v.find(De=>De.id===I[ue].feature_id);$&&$.type===n.Metered&&(I[ue].feature_type=$.config?.usage_type)}for(let ue=0;ue<I.length;ue++){let $=I[ue],De=r({item:$}),Q=i({item:$});if(o($)&&I.find((ce,$t)=>ce.feature_id===$.feature_id&&$t!==ue&&$.entity_feature_id===ce.entity_feature_id))throw new a({message:`Feature ${$.feature_id} is duplicated`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});let dt=I.find((me,ce)=>me.feature_id===$.feature_id&&ce!==ue&&r({item:me})===De&&i({item:me})===Q&&me.entity_feature_id===$.entity_feature_id);if(dt){if(l(dt)&&l($))throw new a({message:`You're trying to create two items for the same feature (${$.feature_id}) with the same interval. Please make them into one item.`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if($.usage_model&&$.usage_model===dt?.usage_model)throw new a({message:`You're trying to add the same feature (${$.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(u($)&&I.find((ce,$t)=>d({item:ce})===d({item:$})&&p({item:ce})===p({item:$})&&$t!==ue))throw new a({message:"Can't have two fixed prices with the same interval",code:s.InvalidInputs,statusCode:c.BAD_REQUEST})}}let We=I.some(ue=>(u(ue)||g(ue))&&String(d({item:ue}))===f.Week),je=I.some(ue=>(u(ue)||g(ue))&&String(d({item:ue}))===f.Month);if(We&&je)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(I.filter(u).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:be,newFeatures:tt}}}))(WA,Ww,Ot,xa,Ia,Ag,Dt,Vt,Kn,Sa,Kc,Wn,Jr,$c,qc),{handleNewProductItems:SM}=((e,t,n,r,i)=>({handleNewProductItems:async({db:a,curPrices:s,curEnts:c,newItems:l,features:u,product:d,logger:p,isCustom:g,newVersion:f,saveToDb:h=!0,multiCurrencyEnabled:I})=>{if(!l)return{prices:[],entitlements:[],customPrices:[],customEnts:[],features:u};let{allFeatures:v,newFeatures:S}=e({newItems:l,features:u,orgId:d.org_id,env:d.env,multiCurrencyEnabled:I,validateRollover:!g});u=v;let R=[],D=[],P=[],be=[],tt=s.filter($=>{let De=l.find(Q=>Q.price_id===$.id);return De?t(De):!0}),We=c.filter($=>!l.some(De=>De.entitlement_id===$.id)),je=[],ue=[];for(let $ of l){let De=u.find(Jt=>Jt.id===$.feature_id),Q=c.find(Jt=>Jt.id===$.entitlement_id),dt=s.find(Jt=>Jt.id===$.price_id),{newPrice:me,newEnt:ce,updatedPrice:$t,updatedEnt:Qe,samePrice:Gt,sameEnt:En}=n({item:$,orgId:d.org_id,internalProductId:d.internal_id,feature:De,curPrice:dt,curEnt:Q,isCustom:g,newVersion:f,features:u});me&&R.push(me),ce&&D.push(ce),$t&&P.push($t),Qe&&be.push(Qe),Gt&&je.push(Gt),En&&ue.push(En)}return r({targetPrices:[...R,...P],targetEntitlements:[...D,...be,...ue],candidatePrices:s,candidateEntitlements:c}),(g||f)&&h?{...i({newPrices:R,newEnts:D,updatedPrices:P,updatedEnts:be,samePrices:je,sameEnts:ue,features:u}),samePrices:je,sameEnts:ue,newFeatures:S,retiredPriceIds:tt.map($=>$.id),retiredEntitlementIds:We.map($=>$.id)}:{prices:[...R,...P],entitlements:[...D,...be].map($=>({...$,feature:u.find(De=>De.id===$.feature_id)})),customPrices:[],customEnts:[],features:u,samePrices:je,sameEnts:ue,newFeatures:S,retiredPriceIds:tt.map($=>$.id),retiredEntitlementIds:We.map($=>$.id)}}}))(Qw,va,qw,Hw,p1);var Zw=ln.clone({precision:40});function nu(e){if(!Jc(e))throw new Error("A supported explicit currency is required");return e.toLowerCase()}function ru(e){let t=new Zw(e);if(!t.isFinite())throw new Error("Amount must be finite");return t}function AM(e,t){let n=nu(t),i=ru(e).toDecimalPlaces(bg(n),ln.ROUND_HALF_CEIL).mul(wa(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 wM(e,t){let n=nu(t),r=ru(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(wa(n)).toString()}function OM(e,t){let n=ru(e).mul(wa(nu(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()}export{qb as a,ol as b,Qa as c,cl as d,co as e,Gb as f,Za as g,Kb as h,ul as i,Ya as j,hO as k,Hb as l,ll as m,bO as n,dl as o,_O as p,ai as q,Xa as r,uo as s,Rn as t,W as u,Zn as v,vO as w,AO as x,ml as y,CO as z,fl as A,Qb as B,Zb as C,EO as D,es as E,ct as F,Y as G,lo as H,Xt as I,Je as J,yl as K,Jb as L,Xb as M,e_ as N,FO as O,ns as P,rs as Q,is as R,t_ as S,n_ as T,Sl as U,r_ as V,$O as W,as as X,Fe as Y,pn as Z,XO as _,xl as $,eP as aa,Il as ba,i_ as ca,vl as da,tP as ea,nP as fa,o_ as ga,Al as ha,ss as ia,rP as ja,iP as ka,Ae as la,Ft as ma,St as na,po as oa,si as pa,s_ as qa,u_ as ra,l_ as sa,Ol as ta,d_ as ua,xr as va,dP as wa,Pl as xa,pP as ya,p_ as za,m_ as Aa,f_ as Ba,mP as Ca,fP as Da,en as Ea,Yn as Fa,mo as Ga,b_ as Ha,bP as Ia,xP as Ja,__ as Ka,y_ as La,Rl as Ma,PP as Na,Ir as Oa,tn as Pa,kl as Qa,S_ as Ra,jl as Sa,CP as Ta,EP as Ua,TP as Va,RP as Wa,kP as Xa,jP as Ya,ms as Za,fo as _a,Ml as $a,ci as ab,vr as bb,I_ as cb,v_ as db,A_ as eb,w_ as fb,kn as gb,Ll as hb,Bl as ib,ql as jb,Vl as kb,go as lb,$l as mb,Gl as nb,Kl as ob,Hl as pb,P_ as qb,zl as rb,C_ as sb,E_ as tb,T_ as ub,Wl as vb,fs as wb,R_ as xb,li as yb,Ql as zb,Zl as Ab,Yl as Bb,k_ as Cb,Jl as Db,Xl as Eb,pi as Fb,mi as Gb,Xn as Hb,ho as Ib,hs as Jb,j_ as Kb,td as Lb,nd as Mb,fi as Nb,bo as Ob,rd as Pb,JP as Qb,XP as Rb,eC as Sb,tC as Tb,N_ as Ub,nC as Vb,rC as Wb,_s as Xb,sC as Yb,cC as Zb,gi as _b,dC as $b,pC as ac,D_ as bc,F_ as cc,id as dc,mC as ec,U_ as fc,fC as gc,M_ as hc,od as ic,L_ as jc,gC as kc,hC as lc,bC as mc,sd as nc,B_ as oc,yC as pc,ad as qc,q_ as rc,ud as sc,Ss as tc,$_ as uc,SC as vc,er as wc,xC as xc,IC as yc,G_ as zc,K_ as Ac,H_ as Bc,z_ as Cc,OC as Dc,PC as Ec,ld as Fc,xs as Gc,DC as Hc,FC as Ic,W_ as Jc,BC as Kc,qC as Lc,_o as Mc,yi as Nc,Is as Oc,nr as Pc,fd as Qc,yo as Rc,gd as Sc,Si as Tc,Q_ as Uc,_d as Vc,vs as Wc,yd as Xc,Sd as Yc,xd as Zc,Z_ as _c,Id as $c,As as ad,vd as bd,rE as cd,Ad as dd,iE as ed,oE as fd,So as gd,wd as hd,xi as id,Ze as jd,Od as kd,Pd as ld,xo as md,Cd as nd,ty as od,Ed as pd,Rd as qd,kd as rd,Ps as sd,ny as td,jd as ud,yE as vd,Nd as wd,Dd as xd,IE as yd,vE as zd,ry as Ad,iy as Bd,Dn as Cd,Fd as Dd,oy as Ed,ay as Fd,Cs as Gd,Ld as Hd,or as Id,cy as Jd,uy as Kd,qd as Ld,Ai as Md,Or as Nd,vo as Od,Vd as Pd,$d as Qd,Es as Rd,ly as Sd,dy as Td,py as Ud,Gd as Vd,Ts as Wd,Kd as Xd,Hd as Yd,zd as Zd,Ao as _d,BE as $d,qE as ae,Wd as be,wo as ce,my as de,Oi as ee,Oo as fe,Qd as ge,gy as he,ks as ie,zE as je,Yd as ke,Jd as le,hy as me,js as ne,ep as oe,tp as pe,Co as qe,Eo as re,by as se,_y as te,yy as ue,np as ve,rp as we,ip as xe,op as ye,ap as ze,sp as Ae,cp as Be,up as Ce,Pr as De,Fn as Ee,lp as Fe,xy as Ge,Ds as He,ar as Ie,fT as Je,Ms as Ke,Iy as Le,vy as Me,Pi as Ne,Ay as Oe,Oy as Pe,Py as Qe,Ci as Re,bT as Se,To as Te,Us as Ue,Cy as Ve,pp as We,mp as Xe,Ey as Ye,_T as Ze,yT as _e,fp as $e,Ty as af,ST as bf,Ry as cf,Cr as df,ko as ef,jo as ff,hp as gf,ET as hf,bp as if,Tr as jf,_p as kf,ky as lf,Ls as mf,yp as nf,No as of,Do as pf,Fo as qf,DT as rf,FT as sf,jy as tf,Sp as uf,xp as vf,Dy as wf,vp as xf,BT as yf,Ap as zf,Bs as Af,wp as Bf,$T as Cf,Fy as Df,an as Ef,Ti as Ff,Me as Gf,Uy as Hf,My as If,Vs as Jf,Op as Kf,Ri as Lf,Pp as Mf,Ly as Nf,By as Of,Ep as Pf,qy as Qf,Vy as Rf,$y as Sf,Gy as Tf,Ky as Uf,sr as Vf,Hy as Wf,zy as Xf,Wy as Yf,Qy as Zf,Zy as _f,Yy as $f,Jy as ag,Xy as bg,eS as cg,tS as dg,nS as eg,rS as fg,Tp as gg,iS as hg,aS as ig,sS as jg,$s as kg,JT as lg,cS as mg,XT as ng,Pt as og,eR as pg,Tt as qg,fn as rg,Gs as sg,lS as tg,Rr as ug,tR as vg,mS as wg,Ks as xg,nR as yg,fS as zg,ki as Ag,rR as Bg,iR as Cg,Rp as Dg,An as Eg,hS as Fg,Uo as Gg,Mo as Hg,yS as Ig,SS as Jg,kp as Kg,gR as Lg,hR as Mg,bR as Ng,_R as Og,jp as Pg,Lo as Qg,Dp as Rg,Hs as Sg,Fp as Tg,Up as Ug,Mp as Vg,Bp as Wg,Lp as Xg,zs as Yg,xS as Zg,DR as _g,IS as $g,qp as ah,vS as bh,dr as ch,Vp as dh,Gp as eh,Kp as fh,Hp as gh,zp as hh,Wp as ih,AS as jh,Qp as kh,wS as lh,OS as mh,PS as nh,CS as oh,Jp as ph,Zs as qh,em as rh,ES as sh,TS as th,QR as uh,ZR as vh,YR as wh,nm as xh,rm as yh,im as zh,om as Ah,am as Bh,sm as Ch,JR as Dh,XR as Eh,kS as Fh,jS as Gh,ek as Hh,tk as Ih,Ys as Jh,jr as Kh,Vo as Lh,um as Mh,Nr as Nh,Dr as Oh,pr as Ph,mr as Qh,Fr as Rh,lm as Sh,NS as Th,DS as Uh,Js as Vh,dm as Wh,pm as Xh,mm as Yh,$o as Zh,ec as _h,LS as $h,BS as ai,tc as bi,gn as ci,gm as di,hm as ei,qS as fi,bm as gi,_m as hi,ym as ii,VS as ji,Wk as ki,M as li,$S as mi,GS as ni,KS as oi,Qk as pi,U as qi,Zk as ri,rc as si,vm as ti,Am as ui,tj as vi,nj as wi,rj as xi,et as yi,oj as zi,Om as Ai,wm as Bi,Ko as Ci,sj as Di,Pm as Ei,mj as Fi,ZS as Gi,YS as Hi,fj as Ii,gj as Ji,Cm as Ki,JS as Li,_j as Mi,XS as Ni,Em as Oi,Tm as Pi,e0 as Qi,yj as Ri,Sj as Si,xj as Ti,Ij as Ui,t0 as Vi,wj as Wi,Oj as Xi,Ej as Yi,Tj as Zi,km as _i,Nj as $i,Dj as aj,Ui as bj,jm as cj,oc as dj,Mi as ej,zo as fj,Li as gj,sn as hj,Vj as ij,sc as jj,$j as kj,Mn as lj,Wo as mj,Qo as nj,cc as oj,Dm as pj,Yo as qj,uc as rj,a0 as sj,Um as tj,Mm as uj,Xj as vj,e2 as wj,t2 as xj,n2 as yj,r2 as zj,i2 as Aj,s0 as Bj,o2 as Cj,lc as Dj,c0 as Ej,dc as Fj,d2 as Gj,p2 as Hj,m2 as Ij,u0 as Jj,l0 as Kj,pc as Lj,b2 as Mj,d0 as Nj,p0 as Oj,Bm as Pj,v2 as Qj,fc as Rj,gc as Sj,h0 as Tj,hc as Uj,bc as Vj,Mr as Wj,b0 as Xj,_0 as Yj,F2 as Zj,qm as _j,K2 as $j,yc as ak,Sc as bk,H2 as ck,z2 as dk,W2 as ek,Q2 as fk,y0 as gk,Vm as hk,Bt as ik,Km as jk,Hm as kk,$m as lk,S0 as mk,x0 as nk,Bi as ok,I0 as pk,Ac as qk,A0 as rk,yN as sk,SN as tk,xN as uk,wc as vk,w0 as wk,O0 as xk,Oc as yk,Qm as zk,LN as Ak,Zm as Bk,zN as Ck,WN as Dk,Xm as Ek,E0 as Fk,T0 as Gk,iD as Hk,tf as Ik,R0 as Jk,Pc as Kk,Cc as Lk,Ec as Mk,k0 as Nk,j0 as Ok,bD as Pk,_D as Qk,yD as Rk,SD as Sk,vD as Tk,OD as Uk,rf as Vk,TD as Wk,RD as Xk,N0 as Yk,D0 as Zk,F0 as _k,U0 as $k,M0 as al,L0 as bl,DD as cl,B0 as dl,FD as el,UD as fl,qD as gl,q0 as hl,V0 as il,ta as jl,$0 as kl,G0 as ll,GD as ml,QD as nl,ZD as ol,YD as pl,K0 as ql,JD as rl,nF as sl,rF as tl,ax as ul,sx as vl,cx as wl,hF as xl,bf as yl,ux as zl,yF as Al,_f as Bl,AF as Cl,wF as Dl,TF as El,RF as Fl,lx as Gl,DF as Hl,FF as Il,yf as Jl,Sf as Kl,$F as Ll,GF as Ml,px as Nl,XF as Ol,mx as Pl,eU as Ql,fx as Rl,nU as Sl,If as Tl,rU as Ul,iU as Vl,vf as Wl,Af as Xl,uU as Yl,lU as Zl,gx as _l,hU as $l,hx as am,bU as bm,_U as cm,Pf as dm,Cf as em,AU as fm,wU as gm,OU as hm,PU as im,Of as jm,CU as km,bx as lm,RU as mm,NU as nm,yx as om,Tf as pm,DU as qm,UU as rm,MU as sm,AM as tm,wM as um,OM as vm};