@tinkerlandai/indiana-react-native 0.8.4 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +289 -248
- package/dist/index.d.ts +289 -248
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var dn=Object.defineProperty;var om=Object.getOwnPropertyDescriptor;var sm=Object.getOwnPropertyNames;var cm=Object.prototype.hasOwnProperty;var um=(e,t,r)=>t in e?dn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var lm=(e,t)=>{for(var r in t)dn(e,r,{get:t[r],enumerable:!0})},dm=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sm(t))!cm.call(e,i)&&i!==r&&dn(e,i,{get:()=>t[i],enumerable:!(n=om(t,i))||n.enumerable});return e};var mm=e=>dm(dn({},"__esModule",{value:!0}),e);var Ot=(e,t,r)=>um(e,typeof t!="symbol"?t+"":t,r);var fy={};lm(fy,{IndianaError:()=>B,createIndianaReactNative:()=>am});module.exports=mm(fy);var mn=require("zod"),pm=mn.z.enum(["sandbox","live"]),Ne=mn.z.object({projectId:mn.z.string().min(1),environment:pm}).strict();var me=require("zod"),Cr=me.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Io=me.z.enum(["unknown","denied","provisional","granted"]),vo=me.z.enum(["ios","android"]),pn=me.z.strictObject({installationId:me.z.uuid(),publicKey:me.z.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:me.z.iso.datetime({offset:!0}),signature:me.z.string().regex(/^[A-Za-z0-9_-]{86}$/)}),fi=me.z.string().regex(/^[a-f0-9]{64}$/),Po=pn.extend({sequence:Cr,platform:vo,credentialDigest:fi}),Co=pn.extend({credentialDigest:fi}),Oo=pn.extend({sequence:Cr,platform:vo}),fn=pn.extend({sequence:Cr,credentialDigest:fi,connectionId:me.z.uuid().nullable(),kind:me.z.enum(["fcm_token","apns_token"]).nullable(),token:me.z.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Io}),wo=fn,Eo=fn.extend({challenge:me.z.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),hi=me.z.strictObject({requested:me.z.literal(!0),expiresAt:me.z.iso.datetime({offset:!0})}),Ft=me.z.strictObject({installationId:me.z.uuid(),bound:me.z.boolean(),identitySeq:Cr,bindingGeneration:Cr,addressSeq:me.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:me.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:me.z.uuid().nullable(),addressStatus:me.z.enum(["active","invalid"]).nullable(),permission:Io}),Ai=me.z.strictObject({channel:me.z.enum(["email","sms","voice","push"]),state:me.z.enum(["unknown","allowed","denied"]),revision:me.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:me.z.iso.datetime({offset:!0}).nullable()}),gy=me.z.strictObject({state:me.z.enum(["allowed","denied"]),revision:me.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function jo(e,t,r){let n=["indiana_push_v1",e,t.projectId,t.environment,r.installationId,r.publicKey,r.issuedAt];e==="bind"?n.push(r.sequence,r.platform,r.credentialDigest):e==="detach"?n.push(r.sequence,r.platform):e==="read"?n.push(r.credentialDigest):n.push(r.sequence,r.credentialDigest,r.connectionId,r.kind,r.token,r.permission),e==="recovery_confirm"&&n.push(r.challenge);let i=JSON.stringify(n);if([...i].some(o=>o.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(i,o=>o.charCodeAt(0))}var Me=require("zod"),$t=Me.z.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"]),yy=Me.z.enum([...$t.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),Sy=Me.z.enum([...$t.options,"stale_revision"]),fm=Me.z.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"]),hm=Me.z.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),To={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"}};var Ro={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function Am(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(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(Ro,e)){let n=Ro[e];return{retryable:n==="retry_same_request",recovery:n}}let r=$t.safeParse(e);return r.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:To[r.data].recovery}:{retryable:!1,recovery:"contact_support"}}function ko(e,t){let r=$t.safeParse(e);if(r.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):To[r.data].status===t;let n={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(n,e)&&(n[e]?.includes(t)??!1)}function gm(e,t=Date.now()){if(e===null)return;let r=e.trim();if(/^\d+$/.test(r)){let i=Number(r);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(r))return;let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):void 0}var Do=Me.z.object({retryable:Me.z.boolean(),recovery:fm,reason:hm.optional(),retryAfterSeconds:Me.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),gi=Me.z.object({requestId:Me.z.uuid().optional(),error:Me.z.object({code:Me.z.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:Me.z.string(),...Do.partial().shape})}),_y=Me.z.object({error:gi.shape.error.extend({requestId:Me.z.uuid().optional()})}),xy=Me.z.object({error:Me.z.string(),code:Me.z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:Me.z.uuid(),...Do.shape});function hn(e,t,r={}){let n=Am(e,t),i=r.reason==="RESULT_UNKNOWN"?"recover_operation":r.recovery??n.recovery,o=n.retryable&&r.retryable!==!1&&i!=="recover_operation",a=o?gm(r.retryAfter??null):void 0;return{...n,retryable:o,recovery:i,...a===void 0?{}:{retryAfterSeconds:a},...r.reason?{reason:r.reason}:{}}}var bi="X-Indiana-Protocol",No="X-Indiana-SDK-Version";var yi={current:"0.8",unversioned:"0.2",releases:[{protocol:"0.2",firstReleasedAt:"2026-10-16T04:05:43.170Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.2.0",integrity:"sha512-kyzHFrt+zuS2hfDZsknCE3AIA9EZXakCDhorO0Ayn2wTpITbm32GMaqVFyhlPufDhkjkV4C0UvXJMyLT5FWIoQ==",sha256:"7e20dd8df9c5e965f67bcdad6c95bf0d0aa5e61a372e5ece88173e32190a1c4c"}]},{protocol:"0.3",firstReleasedAt:"2026-10-16T16:18:04.572Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.3.0",integrity:"sha512-jrh4DH2DBYL5tRkr9BNBVIgD1ts0hUPx8+AhiNkkt2uWV27R8tXGRCW1HBLOw2bfomyuIsAXBAY6niJfjkazCg==",sha256:"33f7ca369d509c44df95c5c8b94775c2afe9d8e3a94163275fe59754739e6815"},{version:"0.3.1",integrity:"sha512-Ifp24kv236advquxa78jx49XKz9oKsg5zZZvFMkId4+KxsylsGxHS44fqYJL/b84PVHl3DLuc+Ru2btdLEctIw==",sha256:"4cc047fe94477e77c5403ce47afea0db2806bd4c3cb94a2dd48c453b4e942163"}]},{protocol:"0.4",firstReleasedAt:"2026-10-18T12:44:12.148Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.4.0",integrity:"sha512-QYuxMdw63RzPLkqmFRc7xv8VWYKYWG+KuKM+f5ZeRX879n6sKyr38bxkMiozFXT+kvH0lDfTF73uJPY2yQX1pQ==",sha256:"ef22d0f6a89897bfbaf71487c4e805997528c8dbad2921ab5c90ed3aa0c01244"}]},{protocol:"0.5",firstReleasedAt:"2026-10-19T08:12:17.954Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.5.0",integrity:"sha512-tzdmoHdvaSoDIvGmg+JpmzE+o1kv7DXpSyvNUSuBj5rHX2pD1GDsMf7ioudUVT5MiKaBDVVtJVE+GpxMOBBLLA==",sha256:"d8b1909bebe1bca0c8c029a68b71477e06ba0c9317c3a2b4bf657951ae3449ca"}]},{protocol:"0.6",firstReleasedAt:"2026-10-21T11:41:57.832Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.6.0",integrity:"sha512-M4szAkM52gqiGPZbtpdhoAvYW2uNRQ2aRw0mdnpr2ErTnuG2i1++76fHjo0qiEMSlePdqu99T1Smecp/FZ2//g==",sha256:"141b058b485fb17b416a2f7961ca55e2da413c9afb7ff22f9fdec2561890bd82"},{version:"0.6.1",integrity:"sha512-KbZUP4XCRblj4mF//JG9t4AAMHSP7uENTi7edxJE55QZjvxH4n1/ypWtKZq32xgt9qGu9o3iZzL8tcHoM3B7Ng==",sha256:"e87930eaec7735629e27e930a462dcecb65fdc4e396cc8ab075845a4f4d22396"},{version:"0.6.2",integrity:"sha512-CUXfh46gSh1S7cdgStI3NAzRROlCQxOcvna2KKlDWFq8L7DXtcILLBOKw5Y1e+QQdDPsXGrsMVBOwIJxFyoIlw==",sha256:"dee5f6e605133ec6c509f390fafdf1d0cb66984a02bea0bb5c05828276c64a15"},{version:"0.6.3",integrity:"sha512-MJXbEoZdLym8a7IHUhY9Oh6eXaSRZPdkwYmfGvfsu5O/kTzfIg+OJuaNrFHYzK76msTxR76IMtQ1R45/FddGdg==",sha256:"fcff156ee9ae90a0f5c906721c8e12715f5fd7a97bca494d64a4303283ec633a"},{version:"0.6.4",integrity:"sha512-djTPwCCgNbp/dt0pFnwEgutZExBZ//wmA2GnObRtXydGrzfi8Z9W7RdeGUFvufblJaGAmcWwVqUgmzEi9SLyjA==",sha256:"bd8e53823728b1e45a27e187c538dcb18af005f24e55120d0cc6b5a618a033f7"}]},{protocol:"0.7",firstReleasedAt:"2026-10-23T09:15:53.572Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.7.0",integrity:"sha512-u2LstlzE8IVFy2dUf/sI9sybNRx3lMF32pjLmeEIFqTdcOXRGdH8GCg5927FwavBpRaWO4a7icmrhYiEjGuYWQ==",sha256:"bb3c3666cbba4ea5018f09e9d050b5db1f71e7a222cdde59c5a93f5ee4a52958"}]},{protocol:"0.8",firstReleasedAt:"2026-10-24T09:44:23.748Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.8.0",integrity:"sha512-w94iNQZo2xG9nVKJ4DcXJ3CpLa7sX8GUQlrIlgWAb+P1x99aXg/pnTeYk+rMaOstO5X/x13eB4xufVcbr8tN+Q==",sha256:"81613ce691331768f0849608fdffc5c78257c763e7cefad9236c4f0351a869ad"},{version:"0.8.1",integrity:"sha512-B07LLUiHHSy6Kxmjg47TBdnpSt7y+Z9tkN3TBBFclY7Fr+AH39Vaavz6eguzxCgb1uSiFQquJONWiKLvEcez+Q==",sha256:"619724c8bc8d8e219ea1ed74b8b4195457e25e92697cdc43b864876fcc004ffe"},{version:"0.8.3",integrity:"sha512-enKlzcLIydk3t3Z74FVXQODv9SNrhq7hfQ0Rcpd6SHBBbfiqFX0h6tWkHJifnJBrTVxAwCNG5aRvZY9x0Hxw1A==",sha256:"63270b8893be90624344ce628cc8d6e3b60cf65d214c9ec7586e71b35ca0dff8"}]}]};var Mo=require("zod"),An=["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"],Q=Mo.z.enum(An);function Uo(e){let t=Q.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}var bt=require("zod");var qo=bt.z.partialRecord(bt.z.enum(An),bt.z.number().int().min(1).max(1e8)),bm=bt.z.strictObject({currency:bt.z.enum(An),automaticTax:bt.z.boolean()}),ym=bt.z.strictObject({projectId:bt.z.uuid(),environmentId:bt.z.uuid()}),wy=ym.extend({settings:bm});var N=require("zod");var lt=require("zod");var Sm=lt.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),Lo=lt.z.number().int().min(0).max(1e4),Si=lt.z.object({key:Sm,featureId:lt.z.uuid(),planVersionId:lt.z.uuid(),includedQuantity:Lo,maximumQuantity:Lo,unitAmountCents:lt.z.number().int().min(0).max(1e8),currency:Q,currencyOptions:qo.optional(),stripePriceId:lt.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),pooledResources:lt.z.array(lt.z.string().regex(/^(?:[a-z][a-z0-9_]{0,63}|pool:[0-9a-f-]{36})$/)).max(100),requireAssignment:lt.z.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");var ue=require("zod");var Fe=require("zod");var Ce=require("zod"),Xe=Ce.z.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),Z=Ce.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),gn=Ce.z.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}),_i=Z.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Bo=Ce.z.string().min(1).max(64),Gt=Ce.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Vo=Ce.z.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Ue=Ce.z.record(Bo,Ce.z.union([Ce.z.string().max(120),Ce.z.number().finite(),Ce.z.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,r])=>[t,String(r)]))),Fo=Ce.z.record(Bo,Ce.z.union([Ce.z.string().max(120),Ce.z.number().finite(),Ce.z.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),lr=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[r,n=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");let i=BigInt(r)*BigInt("1000000")+BigInt(n.padEnd(6,"0"));return t?-i:i},$o=Ce.z.array(Ce.z.object({upTo:_i.nullable(),cost:Z}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,r)=>{let n=e[r-1]?.upTo;return t.upTo!==null&&(r===0||n!=null&&lr(t.upTo)>lr(n))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),_m=Ce.z.object({key:Vo,match:Fo,priority:Ce.z.number().int().default(0),cost:Z.optional(),tiers:$o.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),xm=Ce.z.object({key:Vo,match:Fo,factor:_i.optional(),add:gn.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"})),Im=Ce.z.object({units:_i.default("1"),cost:Z,tiers:$o.optional(),dimensions:Ce.z.array(_m).max(12).optional(),multipliers:Ce.z.array(xm).max(4).optional()}).strict().superRefine((e,t)=>{let r=e.dimensions??[],n=e.multipliers??[];(new Set(r.map(a=>a.key)).size!==r.length||new Set(n.map(a=>a.key)).size!==n.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[a,c]of r.entries())for(let d of r.slice(a+1))Object.keys(c.match).length===Object.keys(d.match).length&&c.priority===d.priority&&!Object.keys(c.match).some(p=>d.match[p]!==void 0&&d.match[p]!==c.match[p])&&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),...r.flatMap(a=>[...a.cost===void 0?[]:[a.cost],...(a.tiers??[]).map(c=>c.cost)])],o=lr(e.units);for(let a of i)for(let c=0;c<1<<n.length;c++){let d=n.filter((ye,R)=>c&1<<R);if(d.some((ye,R)=>d.slice(R+1).some(Re=>Object.keys(ye.match).some(G=>Re.match[G]!==void 0&&Re.match[G]!==ye.match[G]))))continue;let p=lr(a),y=BigInt("1"),j=BigInt("0");for(let[ye,R]of n.entries())c&1<<ye&&(p*=lr(R.factor??"1"),y*=BigInt("1000000"),j+=lr(R.add??"0"));let $=(p+j*y)*BigInt("1000000"),ie=y*o;($<BigInt("0")||$%ie!==BigInt("0")||$/ie>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"})}}),ky=Im.safeExtend({featureKey:Gt});var xi=Fe.z.object({days:Fe.z.number().int().min(1).max(730),cardRequired:Fe.z.boolean(),featureAllowances:Fe.z.record(Fe.z.uuid(),Fe.z.number().int().min(0).max(1e9)),creditAmounts:Fe.z.record(Fe.z.uuid(),Z)}).strict(),Ii=Fe.z.object({id:Fe.z.uuid(),planVersionId:Fe.z.uuid(),slot:Fe.z.string(),cardRequired:Fe.z.boolean(),status:Fe.z.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:Fe.z.iso.datetime().nullable(),endsAt:Fe.z.iso.datetime().nullable(),createdAt:Fe.z.iso.datetime()}).strict();var vi=ue.z.object({group:ue.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).default("main"),kind:ue.z.enum(["main","addon"]).default("main")}).strict(),vm=ue.z.enum(["immediate","end_of_cycle"]),Pm=ue.z.enum(["attach","change","cancel","resume","cancel_change"]),Go=ue.z.object({id:ue.z.uuid(),subscriptionId:ue.z.uuid().nullable(),targetPlanVersionId:ue.z.uuid().nullable(),action:Pm,timing:vm,status:ue.z.enum(["preparing","payment_pending","scheduled","completed","canceled","failed"]),effectiveAt:ue.z.iso.datetime().nullable(),createdAt:ue.z.iso.datetime()}),Cm=ue.z.object({id:ue.z.uuid(),planVersionId:ue.z.uuid(),planId:ue.z.uuid(),basePlanId:ue.z.uuid().nullable(),name:ue.z.string(),group:ue.z.string(),kind:ue.z.enum(["main","addon"]),source:ue.z.enum(["subscription","assignment","license","apple","google"]),status:ue.z.string(),accessEnabled:ue.z.boolean(),startsAt:ue.z.iso.datetime().nullable(),endsAt:ue.z.iso.datetime().nullable(),cancelAtPeriodEnd:ue.z.boolean(),scheduledChange:Go.nullable(),trial:Ii.nullable().optional()}),qy=ue.z.object({customerId:ue.z.uuid(),evaluatedAt:ue.z.iso.datetime(),holdings:ue.z.array(Cm),changes:ue.z.array(Go),trials:ue.z.array(Ii).optional()});var yt=N.z.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"),Hy=N.z.record(N.z.string().min(1).max(80),N.z.union([N.z.string().max(500),N.z.number().finite(),N.z.boolean(),N.z.null()])).refine(e=>Object.keys(e).length<=30,"\u6700\u591A 30 \u4E2A\u5C5E\u6027"),Ho=N.z.object({key:yt,name:N.z.string().trim().min(1).max(80),description:N.z.string().trim().max(240),type:N.z.enum(["boolean","metered"]),usageType:N.z.enum(["consumable","non_consumable"]).optional()}),Ky=Ho.extend({...Ne.shape,id:N.z.string().min(1),archived:N.z.boolean(),createdAt:N.z.iso.datetime()}),Ko=N.z.object({amountCents:N.z.number().int().min(0).max(1e8),currency:Q,interval:N.z.enum(["free","month","year"]),currencyOptions:N.z.partialRecord(Q,N.z.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"),Om=N.z.object({featureId:N.z.string().min(1),allowance:N.z.number().int().min(0).max(1e9).nullable(),pooled:N.z.boolean().optional()}),Zo=N.z.object({name:N.z.string().trim().min(1).max(80),description:N.z.string().trim().max(240),price:Ko,membership:vi.optional(),trial:xi.nullable().optional(),licenses:N.z.array(Si).max(20).optional(),items:N.z.array(Om).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")}),Zy=N.z.object({key:yt,config:Zo}),Wy=Ne.extend({id:N.z.string().min(1),key:yt,draft:Zo,status:N.z.enum(["draft","published","archived"]),publishedVersionId:N.z.string().nullable(),isDefault:N.z.boolean(),updatedAt:N.z.iso.datetime()}),wm=Ho.pick({key:!0,name:!0,type:!0}).extend({featureId:N.z.string(),allowance:N.z.number().int().min(0).max(1e9).nullable(),pooled:N.z.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"),Wo=Ne.extend({id:N.z.string().min(1),planId:N.z.string().min(1),variant:N.z.object({basePlanId:N.z.uuid(),baseVersionId:N.z.uuid()}).nullable(),version:N.z.number().int().positive(),name:N.z.string(),description:N.z.string(),price:Ko,membership:vi.optional(),trial:xi.nullable().optional(),licenses:N.z.array(Si).optional(),items:N.z.array(wm),publishedAt:N.z.iso.datetime()}).strict(),Pi=N.z.object({startsAt:N.z.iso.datetime(),endsAt:N.z.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"),Qy=Ne.extend({id:N.z.string(),customerId:N.z.string(),planVersionId:N.z.string(),assignedAt:N.z.iso.datetime(),source:N.z.literal("demo"),validity:Pi.nullable().default(null),used:N.z.record(N.z.string(),N.z.number().int().min(0))}),Yy=Ne.extend({id:N.z.string(),customerId:N.z.string(),at:N.z.iso.datetime(),message:N.z.string()});var A=require("zod/v4");var Qo=require("zod/v4"),Yo=Qo.z.registry();var{AppEnv:bn}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:Jo}={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:Em}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:jm}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(A.z),{ResetInterval:Or}=(()=>{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:Rm}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:Tm}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:km}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:Dm}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:Nm}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(A.z),{BALANCE_BASES:Mm}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:Xo}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:Ci}=(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.z),{ProductMetadataSchema:dr}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(A.z),{findDuplicate:Um}={findDuplicate:t=>{let r=new Set;for(let n of t){if(r.has(n))return n;r.add(n)}}},{BillingInterval:kt}=(()=>{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:Oi}=(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.z),{withSpecDefault:wr}=(e=>({withSpecDefault:({schema:r,defaultValue:n,description:i})=>(e.add(r,{description:i,default:n}),r)}))(Yo),{COMMON:zo}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:qm}={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:Lm}=(e=>({COMMON_SET:new Set(e)}))(zo),{hasNoDuplicateCurrencies:es}={hasNoDuplicateCurrencies:t=>{let r=new Set;for(let{currency:n}of t){let i=n.toLowerCase();if(r.has(i))return!1;r.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:ts}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:wi}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(A.z),{Infinite:yn}={Infinite:"inf"},{TierBehavior:Er}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Sn}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:rs}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:Bm}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:_n}=(()=>{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:xn}=(()=>{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:Ei}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:ns}=(()=>{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:Vm}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Fm}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:ji}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(A.z),{ApiCreditTierSchema:is}=(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.z),{VIOLATION_MESSAGES:$m}={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:as}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(A.z),{ModelMarkupsSchema:Ri}=((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.z,as),{additionalCurrencyPlanItemIssues:os}={additionalCurrencyPlanItemIssues:t=>{if(!t)return[];let r=[];t.additional_currencies&&t.additional_currencies.length>0&&(typeof t.amount!="number"||(t.tiers?.length??0)>0)&&r.push("price.additional_currencies requires a flat 'amount'; tiered prices carry per-currency amounts on each tier.");let n=t.tiers;if(n&&n.length>0){let i=a=>(a.additional_currencies??[]).map(c=>c.currency.toLowerCase()),o=new Set(n.flatMap(i));o.size>0&&(n.every(c=>{let d=new Set(i(c));return d.size===o.size&&[...o].every(p=>d.has(p))})||r.push("Each additional currency must be present on every tier or none."))}return r}},{PlanItemFilterSchema:Ti}=((e,t,r,n,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(r),e.enum(n)]).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.z,Sn,kt,Or,wi),{UpdatePlanItemParamsV1Schema:Gm}=((e,t,r)=>({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(r).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.z,Ti,Or),{FreeTrialDuration:jr}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:Hm}=((e,t)=>({laneParam:({schema:n,description:i})=>e({schema:t.array(n).optional(),defaultValue:[],description:i})}))(wr,A.z),{findDuplicateInControls:Km}={findDuplicateInControls:({controlKey:t,controls:r,rule:n})=>{let i=new Set;for(let[o,a]of r.entries()){let c=n.identityOf(a);if(c!==void 0){if(i.has(c))return{code:"custom",message:n.message,input:a[n.field],path:[t,o,n.field]};i.add(c)}}}},{featureIdIdentity:Zm}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:ss}={usageLimitFilterKey:t=>t?.properties?Object.entries(t.properties).map(([r,n])=>[r,String(n)]).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${r}=${n}`).join("&"):""},{usageAlertIdentity:Wm}=((e,t)=>({usageAlertIdentity:n=>[n.feature_id??"",n.basis??e,t(n.filter),n.threshold_type,n.threshold].join("|")}))(Xo,ss),{RemovePlanLicenseSchema:Qm}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(A.z),{ApiStripePriceProcessorSchema:Ym}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(A.z),{ApiFeatureType:Jm}=(()=>{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:Xm}=(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.z),{ApiRevenueCatProductSchema:zm}=(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.z),{TrialOnEnd:In}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:ep}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:tp}=(()=>{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:rp}=(()=>{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:np}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(A.z),{UsageWindowScopeSchema:ip}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(A.z),{EntInterval:cs}=(()=>{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:ap}=(()=>{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:op}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(A.z),{FreeTrialSchema:sp}=((e,t,r)=>({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(r).nullish()})}))(A.z,jr,In),{BillingType:cp}=(()=>{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:ki}=((e,t)=>({UsageTierSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional()}).refine(n=>n.amount!==void 0||n.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(n=>({...n,amount:n.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional()}))}))(A.z,yn),{IgnoredFixedPriceMetadataSchema:up}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(r=>typeof r=="string"?null:r,e.null().or(e.undefined()))}))(A.z),{BillWhen:lp}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:us}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:dp}=((e,t,r)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(r).default(r.ProrateImmediately)})}))(A.z,_n,xn),{AllowanceType:mp}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:ls}=((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.z,Ei),{CreditDimensionBaseSchema:pp}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(A.z,ji),{flatCreditRateShape:ds}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(A.z),{CreditTierSchema:fp}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(A.z),{CreditMultiplierSchema:hp}=((e,t)=>({CreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional(),add:e.number().optional()}).refine(n=>n.factor!==void 0||n.add!==void 0,{message:"A multiplier needs a factor or an add"})}))(A.z,ji),{idRegex:vn}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:ms}={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:Ap}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:gp}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{ProductItemInterval:bp}=(()=>{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:yp}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:Sp}={TierInfinite:"inf"},{CreateFreeTrialSchema:ps}=((e,t,r)=>({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(r).nullish()})}))(A.z,jr,In),{ProductConfigParamsSchema:Di}=((e,t,r)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:r})})}))(A.z,wr,Jo),{CREATE_PRODUCT_EXAMPLE:_p}={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:xp}=((e,t,r)=>({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(r).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.z,jr,In),{CreateProductSchema:eS}=(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.z),{isUsageLimitBasisAlert:Ip}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:fs}=(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.z),{RewardType:hs}=(()=>{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:As}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:gs}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(A.z,As),{RewardTriggerEvent:vp}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:Pp}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:Pn}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(A.z,Jo),{PurchaseLimitIntervalEnum:Cp}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(A.z,Em),{DbSpendLimitSchema:Ni}=((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(n=>n.overage_limit===void 0&&n.skip_overage_billing===void 0||n.feature_id!==void 0,{message:"feature_id is required when overage_limit or skip_overage_billing is provided",path:["feature_id"]})}))(A.z,jm),{USAGE_LIMIT_INTERVALS:Op}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(Or),{UsageLimitAnchorSchema:bs}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(A.z,Rm),{UsageLimitFilterValueSchema:wp}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(A.z,km),{USAGE_ALERT_BASES:Ep}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(Mm),{licensePatchIssues:jp}=(e=>({licensePatchIssues:({upsertLicenses:r=[]})=>{let n=e(r.map(i=>i.license_plan_id));return n===void 0?[]:[{message:`Duplicate license ${n} in upsert_licenses`,path:["upsert_licenses"]}]}}))(Um),{BasePriceSchema:Rp}=((e,t,r)=>({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:r.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(A.z,kt,Oi),{CURRENCY_CODES:Tp}=((e,t,r)=>({CURRENCY_CODES:[...e,...t.filter(i=>!r.has(i)).sort()]}))(zo,qm,Lm),{AllocatedBillingFieldSchema:ys}=((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.z,rs),{EntitlementExpirySchema:Cn}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(A.z,ns),{CreditDimensionNameSchema:Ss}=((e,t,r)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(r),{message:`Dimension names cannot contain "${r}"`})}))(A.z,Vm,Fm),{ApiCreditMatchSchema:_s}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(ji),{findCreditTierViolations:kp}=(e=>({findCreditTierViolations:r=>{let n=[],i=(a,c)=>n.push({index:a,reason:c,message:e[c]}),o=0;for(let[a,c]of r.entries()){let d=a===r.length-1;if(c==="inf"){d||i(a,"non_final_infinity");continue}(!Number.isFinite(c)||c<=o)&&i(a,"not_increasing"),o=c,d&&i(a,"final_not_infinity")}return n}}))($m),{ApiCreditMultiplierSchema:Dp}=((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(n=>n.factor!==void 0||n.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(A.z,_s),{ProviderMarkupsSchema:xs}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(A.z,as),{planItemParamsIssues:Np}=((e,t,r,n,i)=>({planItemParamsIssues:a=>{let c=[],d=a.reset?.interval,p=a.price?.interval,y=a.reset?.interval_count??1,j=a.price?.interval_count??1;if(d&&p&&(String(d)!==String(p)||y!==j)&&a.price?.billing_method!==e.Prepaid&&c.push({message:"reset.interval and price.interval can only differ for prepaid prices.",input:a}),a.threshold_billing&&(!a.price||a.unlimited)&&c.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)||c.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&&c.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&&c.push({message:"expiry is not supported on pooled items; pooled balances have no per-purchase lifetime.",input:a.expiry}),a.expiry.length<=0&&c.push({message:"expiry.length must be greater than 0",input:a.expiry})),a.price){a.threshold_billing&&a.price.billing_method!==e.UsageBased&&c.push({message:"threshold_billing requires a finite usage-based price",input:a.threshold_billing});let{amount:ie,tiers:ye}=a.price;a.threshold_billing&&ye?.length&&c.push({message:"threshold_billing currently requires a flat usage price",input:a.threshold_billing});let R=a.price.billing_method===e.UsageBased&&a.price.allocated_billing===r.ProratedLegacy;a.proration&&a.price.billing_method!==e.Prepaid&&!R&&c.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:a.proration});let Re=typeof ie=="number",G=Array.isArray(ye)&&ye.length>0;Re||G?Re&&G&&c.push({message:"'amount' and 'tiers' cannot both be defined in 'price'.",input:a.price}):c.push({message:"If 'price' is present, either 'amount' or 'tiers' must be defined.",input:a.price})}if(a.price?.tiers){let ie=a.price.tiers.some(ye=>ye.flat_amount&&ye.flat_amount>0);ie&&a.price.tier_behavior!==n.VolumeBased&&c.push({message:"flat_amount on tiers is only supported for volume-based pricing.",input:a.price}),ie&&a.price.tiers.length<=1&&c.push({message:"flat_amount is not supported on single-tier pricing.",input:a.price}),a.price.tiers.some(ye=>ye.flat_amount!=null&&ye.flat_amount<0)&&c.push({message:"flat_amount must be 0 or greater.",input:a.price}),a.price?.tier_behavior===n.VolumeBased&&a.price?.billing_method!==e.Prepaid&&c.push({message:"volume-based pricing is only supported for prepaid features.",input:a.price}),a.price?.tiers.length===0?c.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&&c.push({message:"tiers[0].to must be greater than included.",input:a.price})}for(let ie of i(a.price))c.push({message:ie,input:a.price});return c}}))(Sn,kt,rs,Er,os),{FreeTrialParamsV1Schema:Mi}=((e,t,r)=>({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:r({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.z,jr,wr),{duplicateCheck:Mp}=(e=>({duplicateCheck:({controlKey:r,...n})=>i=>e({controlKey:r,controls:i[r]??[],rule:n})}))(Km),{usageLimitIdentity:Ui}=(e=>({usageLimitIdentity:r=>`${r.feature_id}|${e(r.filter)}`}))(ss),{ApiPriceProcessorsSchema:Is}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(A.z,Ym),{ApiFeatureV0Schema:vs}=((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.z,Jm),{ApiRevenueCatPlanProcessorSchema:Up}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(A.z,zm),{ApiFreeTrialV2Schema:qp}=((e,t,r)=>({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(r).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.z,jr,In),{CustomerEligibilitySchema:Lp}=((e,t,r,n)=>({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(r).meta({description:"The action that would occur if this plan were attached to the customer."}),scenario:e.enum(n).optional().meta({description:"Legacy attach scenario. Internal use only.",internal:!0})})}))(A.z,ep,tp,rp),{UsageWindowLimitSchema:tS}=((e,t,r,n,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:r,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(n),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.z,np,ip,cs,bs),{FeatureSchema:Bp}=((e,t,r,n,i)=>({FeatureSchema:e.object({internal_id:e.string(),org_id:e.string(),created_at:e.number().nullable(),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(r,{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:n.nullish(),stripe_meter:i.nullish(),stripe_product_id:e.string().nullish()})}))(A.z,bn,ap,Ri,op),{PriceCurrencyConfigSchema:Ps}=((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.z,ki),{UsagePriceConfigSchema:Vp}=((e,t,r,n,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(r),interval:e.enum(n),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.z,lp,ki,kt,Ps,us),{graduatedCreditRateShape:Cs}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(A.z,fp),{FeatureMarkupsOverrideSchema:Fp}=((e,t,r)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:r})}))(A.z,xs,Ri),{usageAlertTargetLimitIdentity:$p}=(e=>({usageAlertTargetLimitIdentity:r=>e({feature_id:r.feature_id??"",filter:r.filter})}))(Ui),{DiscountConfigSchema:Os}=((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.z,As),{RewardEntitlementSchema:ws}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(A.z,Cn),{UpdateRewardSchema:rS}=((e,t,r,n,i,o)=>({UpdateRewardSchema:e.object({name:e.string().nullish(),promo_codes:e.array(t).optional(),id:e.string().optional(),type:e.nativeEnum(r).optional(),discount_config:n.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(o).nullish()})}))(A.z,fs,hs,Os,gs,ws),{CreateRewardProgram:nS}=((e,t,r)=>({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(r)})}))(A.z,vp,Pp),{AutoTopupPurchaseLimitSchema:Es}=((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.z,Cp),{UsageLimitFilterSchema:js}=((e,t,r,n)=>({UsageLimitFilterSchema:e.object({properties:e.record(e.string().min(1).max(t),r).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>n)&&o.issues.push({code:"custom",message:`filter.properties must have between 1 and ${n} keys`,input:o.value})})})}))(A.z,Tm,wp,Dm),{UsageAlertBasisSchema:Gp}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(A.z,Ep),{refineCustomizePlanV1Schema:Rs}=(e=>({refineCustomizePlanV1Schema:(r,{includeItems:n=!0,includeFreeTrial:i=!0,includeUpdateItems:o=!0,includeLicenses:a=!0}={})=>{let c=["price",n&&"items","add_items","remove_items",o&&"update_items",i&&"free_trial","billing_controls",a&&"upsert_licenses",a&&"remove_licenses"].filter(Boolean),d=p=>p==="update_items"?"deprecated update_items":p;return r.refine(p=>c.some(y=>p[y]!==void 0),{message:`When using customize, at least one of ${c.map(d).join(", ")} must be provided`}).superRefine((p,y)=>{if(a)for(let j of e({upsertLicenses:p.upsert_licenses}))y.addIssue({code:"custom",...j})}).refine(p=>!(p.items!==void 0&&(p.add_items!==void 0||p.remove_items!==void 0||o&&p.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`})}}))(jp),{SUPPORTED_SET:Hp}=(e=>({SUPPORTED_SET:new Set(e)}))(Tp),{ApiCreditDimensionBaseSchema:Kp}=((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.z,_s),{refineGraduatedTiers:Ts}=(e=>({refineGraduatedTiers:(r,n)=>{let i=e(r.tiers.map(o=>o.to));for(let{index:o,message:a}of i)n.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(kp),{ApiFeatureMarkupsOverrideSchema:Zp}=((e,t,r)=>({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:r.meta({description:"Per-model markup overrides for customers on this plan."})})}))(A.z,xs,Ri),{AutoTopupPurchaseLimitParamsSchema:Wp}=((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."})})}))(Es,A.z),{DUPLICATE_CHECKS:Qp}=((e,t,r,n)=>({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:r,field:"feature_id",message:"Only one usage limit entry is allowed per feature_id and filter"}),e({controlKey:"usage_alerts",identityOf:n,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"})]}))(Mp,Zm,Ui,Wm),{ApiPlanProcessorsSchema:Yp}=((e,t,r)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:r.nullish()}).meta({"x-atmn-mapping":!0})}))(A.z,Xm,Up),{FixedPriceConfigSchema:Jp}=((e,t,r,n,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(),r).nullish(),billing_units:e.number().nullish(),usage_tiers:e.array(n).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.z,kt,Ps,ki,up),{CreditDimensionSchema:Xp}=((e,t,r,n)=>({CreditDimensionSchema:e.union([t.extend(r),t.extend(n)])}))(A.z,pp,ds,Cs),{filterUnresolvableUsageLimitAlerts:zp}=((e,t,r)=>({filterUnresolvableUsageLimitAlerts:({usageAlerts:i,usageLimitLists:o})=>{let a=new Set(o.flatMap(c=>(c??[]).map(e)));return i.flatMap((c,d)=>t(c)&&!a.has(r(c))?[{index:d,usageAlert:c}]:[])}}))(Ui,Ip,$p),{CreateRewardSchema:iS}=((e,t,r,n,i,o)=>({CreateRewardSchema:e.object({name:e.string(),promo_codes:e.array(t),id:e.string(),type:e.nativeEnum(r).nullish(),discount_config:n.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(o).nullish()}).refine(c=>c.type!==r.FeatureGrant?!0:c.entitlements&&c.entitlements.length>0,{message:"Feature grant rewards require at least one entitlement"}).refine(c=>c.type!==r.FeatureGrant?!0:c.promo_codes.some(d=>d.code.length>0),{message:"Feature grant rewards require at least one promo code"})}))(A.z,fs,hs,Os,gs,ws),{AutoTopupSchema:qi}=((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.z,Es),{DbUsageLimitSchema:Li}=((e,t,r,n)=>({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:r.optional().meta({description:"Window alignment. 'billing_cycle' phases the interval to the customer's renewal time; 'utc' aligns to the UTC calendar."}),filter:n.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.z,Op,bs,js),{DbUsageAlertSchema:Bi}=((e,t,r,n,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:r.default(n).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:c,threshold_type:d,threshold:p,basis:y,filter:j}=a.value;d==="remaining_percentage"&&p>100&&a.issues.push({code:"custom",input:p,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),y==="usage_limit"&&!c&&a.issues.push({code:"custom",input:c,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),j&&y!=="usage_limit"&&a.issues.push({code:"custom",input:j,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(A.z,Nm,Gp,Xo,js),{isValidCurrencyCode:ef}=(e=>({isValidCurrencyCode:r=>!!r&&e.has(r.toLowerCase())}))(Hp),{ApiCreditDimensionSchema:tf}=((e,t,r,n)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(r).min(1)}).strict().superRefine(n),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(A.z,Kp,is,Ts),{AutoTopupParamsSchema:rf}=((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."})})}))(qi,Wp),{findDuplicateBillingControlIssue:nf}=(e=>({findDuplicateBillingControlIssue:r=>{for(let n of e){let i=n(r);if(i)return i}}}))(Qp),{CustomerBillingControlsSchema:Vi}=((e,t,r,n,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(r).optional().meta({description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:e.array(n).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.z,qi,Ni,Li,Bi,Ci),{PriceSchema:af}=((e,t,r,n,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(r).nullish(),is_custom:e.boolean().optional(),config:n.or(i),entitlement_id:e.string().nullish(),proration_config:o.nullable()})}))(A.z,cp,Er,Jp,Vp,dp),{CreditSchemaItemBaseSchema:ks}=((e,t,r,n)=>({CreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(t,r).optional(),multipliers:e.record(t,n).optional()})}))(A.z,Ss,Xp,hp),{GraduatedCreditSchemaItemSchema:of}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(ks,Cs),{UpdateProductSchema:aS}=((e,t,r)=>({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:r.optional()})}))(A.z,Pn,Vi),{DbBillingControlsSchema:sf}=((e,t,r,n,i,o)=>({DbBillingControlsSchema:e.object({auto_topups:e.array(t).nullish(),spend_limits:e.array(r).nullish(),usage_limits:e.array(n).nullish(),usage_alerts:e.array(i).nullish(),overage_allowed:e.array(o).nullish()})}))(A.z,qi,Ni,Li,Bi,Ci),{CurrencyCodeSchema:Ds}=((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.z,ef),{AdditionalCurrencyTierSchema:cf}=((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(n=>n.amount!==void 0||n.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(A.z,Ds),{ApiCreditSchemaItemBaseSchema:Ns}=((e,t,r,n)=>({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,r).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,n).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(A.z,Ss,tf,Dp),{ApiFlatCreditSchemaItemSchema:uf}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Ns,A.z),{rejectDuplicateBillingControls:lf}=(e=>({rejectDuplicateBillingControls:r=>{let n=e(r.value);n&&r.issues.push(n)}}))(nf),{FlatCreditSchemaItemSchema:df}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(ks,ds),{ProductSchema:mf}=((e,t,r,n,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:r.default(()=>({ignore_past_due:!1})),...n.shape,metadata:i.default(()=>({}))})}))(A.z,bn,Pn,sf,dr),{AdditionalCurrencyPriceSchema:pf}=((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.z,Ds),{AdditionalCurrencyTierArraySchema:Ms}=((e,t,r,n)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(r,{message:n})}))(A.z,cf,es,ts),{ApiGraduatedCreditSchemaItemSchema:ff}=((e,t,r,n)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(r).min(1)}).strict().superRefine(n)}))(Ns,A.z,is,Ts),{CustomerBillingControlsParamsSchema:On}=((e,t,r,n,i,o,a,c)=>({CustomerBillingControlsParamsSchema:e.object({auto_topups:t({schema:r,description:"List of auto top-up configurations per feature."}),spend_limits:t({schema:n,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(c)}))(A.z,Hm,rf,Ni,Li,Bi,Ci,lf),{CreditSchemaItemSchema:hf}=((e,t,r)=>({CreditSchemaItemSchema:e.union([t,r])}))(A.z,df,of),{PriceTierSchema:Af}=((e,t,r)=>({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:r.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.z,Sp,Ms),{PlanBillingControlsParamsSchema:gf}=((e,t)=>({PlanBillingControlsParamsSchema:e.check(n=>{let i=t({usageAlerts:n.value.usage_alerts??[],usageLimitLists:[n.value.usage_limits??[]]});for(let{index:o,usageAlert:a}of i)n.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"]})})}))(On,zp),{AdditionalCurrencyPriceArraySchema:Rr}=((e,t,r,n)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(r,{message:n})}))(A.z,pf,es,ts),{ApiUsageTierWithCurrenciesSchema:Us}=((e,t,r)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:r.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:r.optional()}))}))(A.z,yn,Ms),{ApiCreditSchemaItemSchema:bf}=((e,t,r)=>({ApiCreditSchemaItemSchema:e.union([t,r])}))(A.z,ff,uf),{FeatureConfigOverrideSchema:qs}=((e,t,r)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:r.optional()})}))(A.z,hf,Fp),{ProductItemConfigSchema:yf}=((e,t,r,n,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(r).nullish(),on_decrease:e.enum(n).nullish(),rollover:i.nullish(),expiry:o.nullish(),feature_override:a.nullish()})}))(A.z,us,_n,xn,ls,Cn,qs),{BasePriceParamsSchema:wn}=((e,t,r,n)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:r.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:n.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:r.string().optional().meta({internal:!0}),entitlement_id:r.string().optional().meta({internal:!0}),price_id:r.string().optional().meta({internal:!0}),stripe_price_id:r.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."})}))(Rp,wr,A.z,Rr),{PlanItemPriceParamsSchema:Sf}=((e,t,r,n,i,o,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(d=>d??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(r).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(n).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.z,Rr,Us,Er,kt,Sn,ys),{ApiFeatureOverrideSchema:Ls}=((e,t,r)=>({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:r.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.z,bf,Zp),{ApiPlanItemV1Schema:_f}=((e,t,r,n,i,o,a,c,d,p,y,j,$,ie,ye,R,Re)=>({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(r).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:n.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(c).meta({description:"'prepaid' for features like seats where customers pay upfront, 'usage_based' for pay-as-you-go after included usage."}),allocated_billing:d,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:p.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:y.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(j).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($).optional().meta({description:"How to handle billing when quantity increases mid-cycle."}),on_decrease:e.enum(ie).optional().meta({description:"How to handle credits when quantity decreases mid-cycle."})}).optional().meta({internal:!0}),expiry:ye.nullish().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:R.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(L=>{let z=L.value.reset?.interval,xe=L.value.price?.interval,ce=L.value.reset?.interval_count??1,je=L.value.price?.interval_count??1;if(z&&xe&&(String(z)!==String(xe)||ce!==je)&&L.value.price?.billing_method!==c.Prepaid&&L.issues.push({code:"custom",message:"reset.interval and price.interval can only differ for prepaid prices.",input:L.value}),L.value!==void 0&&L.value.price!==void 0&&L.value.price!==null){L.value.price.amount&&L.value.price.tiers&&L.value.price.tiers.length>0&&L.issues.push({code:"custom",message:"Price amount and tiers are mutually exclusive.",input:L.value});for(let st of Re(L.value.price))L.issues.push({code:"custom",message:st,input:L.value.price})}})}))(A.z,vs,Or,Rr,Us,Er,kt,Sn,ys,Is,Oi,Ei,_n,xn,Cn,Ls,os),{EntitlementSchema:xf}=((e,t,r,n,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(r).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(n).nullish(),expiry_length:e.number().nullish(),rollover:i.nullish(),feature_override:o.nullish()})}))(A.z,mp,cs,ns,ls,qs),{ProductItemSchema:Bs}=((e,t,r,n,i,o,a,c,d,p,y)=>({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(r).nullish().meta({internal:!0}),feature:n.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($=>{if($==="")throw new Error("Interval cannot be empty.");return $},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(c).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:d.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(p).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:y.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.z,Ap,gp,vs,yn,bp,yp,Af,Rr,Er,yf),{ProductV2Schema:Vs}=((e,t,r,n,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:r.nullish(),items:e.array(n),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.z,bn,xp,Bs,Pn,Vi,dr),{PlanItemParamsObjectSchema:If}=((e,t,r,n,i,o,a,c,d,p,y)=>({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(r).meta({description:"Interval at which balance resets (e.g. 'month', 'year'). For consumable features only."}),interval_count:n({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(c).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(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 config for unused units. If set, unused included units carry over."}),expiry:p.optional().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:y.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.z,wi,Or,wr,Sf,Bm,_n,xn,Ei,Cn,Ls),{FullProductWithoutLicensesSchema:oS}=((e,t,r,n,i,o)=>({FullProductWithoutLicensesSchema:e.extend({description:t.string().nullable().optional().default(null),prices:t.array(r),entitlements:t.array(n.extend({feature:i})),free_trial:o.nullish(),free_trials:t.array(o).nullish(),free_trial_ids:t.array(t.string()).nullish()})}))(mf,A.z,af,xf,Bp,sp),{CreateProductItemParamsSchema:Fs}=((e,t,r,n)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(r.literal(n)).nullish()})}))(Bs,wi,A.z,yn),{CreatePlanItemParamsV1Schema:Fi}=((e,t)=>({CreatePlanItemParamsV1Schema:e.check(n=>{for(let{message:i,input:o}of t(n.value))n.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."})}))(If,Np),{LicenseCustomizeSchema:$s}=((e,t,r,n)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(r).optional(),remove_items:e.array(n).optional()})}))(A.z,wn,Fi,Ti),{PlanLicenseParamsSchema:$i}=((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.z,$s),{UpdateProductV2ParamsSchema:sS}=((e,t,r,n,i,o,a,c,d)=>({UpdateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).optional().meta({description:r.id}),name:e.string().refine(y=>y.length>0,{message:"name must be a non-empty string"}).optional().meta({description:r.name}),is_add_on:e.boolean().optional().meta({description:r.is_add_on}),is_default:e.boolean().optional().meta({description:r.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:r.description}),group:e.string().nonempty().nullable().optional().meta({description:r.group}),archived:e.boolean().optional().meta({description:r.archived}),items:e.array(n).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:r.free_trial}),config:a.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:c.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:d.optional().meta({description:r.metadata})})}))(A.z,vn,ms,Fs,$i,ps,Di,On,dr),{CreatePlanParamsV1Schema:vf}=((e,t,r,n,i,o,a,c,d)=>({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:r.optional().meta({description:"Base recurring price for the plan. Omit for free or usage-only plans."}),items:e.array(n).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:c.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:d.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.z,vn,wn,Fi,$i,Mi,Di,gf,dr),{UpdatePlanParamsV1Schema:cS}=((e,t,r,n,i)=>({UpdatePlanParamsV1Schema:e.partial().extend({group:e.shape.group.removeDefault().optional(),version:t.number().optional(),archived:t.boolean().default(!1).optional(),price:r.nullable().optional().meta({description:"The price of the plan. Set to null to remove the base price."}),free_trial:n.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."})})}))(vf,A.z,wn,Mi,vn),{CustomizePlanLicenseSchema:Gi}=((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.z,$s),{CreateProductV2ParamsSchema:uS}=((e,t,r,n,i,o,a,c,d,p)=>({CreateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).meta({description:r.id}),name:e.string().refine(j=>j.length>0,{message:"name must be a non-empty string"}).meta({description:r.name}),description:e.string().nullish().meta({description:r.description}),is_add_on:e.boolean().default(!1).meta({description:r.is_add_on}),is_default:e.boolean().default(!1).meta({description:r.is_default}),group:e.string().nullable().default("").meta({description:r.group}),items:e.array(n).optional().meta({description:r.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:r.free_trial}),config:a.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:c.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:d.optional().meta({description:r.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:[p]})}))(A.z,vn,ms,Fs,$i,ps,Di,On,dr,_p),{CustomizePlanV1BaseSchema:Gs}=((e,t,r,n,i,o,a,c,d)=>({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(r).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(r).optional().meta({description:"Items to add to the plan."}),remove_items:e.array(n).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(c).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(d).optional().meta({description:"License links to drop, keyed by license_plan_id. Parallel to remove_items."})})}))(A.z,wn,Fi,Ti,Gm,Mi,On,Gi,Qm),{VariantCustomizeSchema:Pf}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(Rs,Gs),{DiffedCustomizePlanV1Schema:lS}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(Rs,Gs),{ApiPlanV1Schema:dS}=((e,t,r,n,i,o,a,c,d,p,y,j,$,ie)=>({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(r).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:n.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:c.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(d).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:p.meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:y.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:j.meta({description:"Arbitrary key-value metadata defined by you for your own use. Shared across all versions of the plan."}),customer_eligibility:$.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:ie.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.z,Rr,kt,Oi,Is,_f,Yp,qp,bn,Pn,Vi,dr,Lp,Pf);var S=require("zod"),Cf=S.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Zs=S.z.enum(["single_use","continuous_use"]),Hi=S.z.record(S.z.string(),S.z.union([S.z.string(),S.z.number(),S.z.boolean()]).transform(String).pipe(S.z.string())),Hs=S.z.string().min(1).max(64).refine(e=>!e.includes("::")),Ws={credit_amount:S.z.number(),tier_behavior:S.z.never().optional(),tiers:S.z.never().optional()},Qs={credit_amount:S.z.never().optional(),tier_behavior:S.z.literal("graduated"),tiers:S.z.array(S.z.strictObject({to:S.z.union([S.z.number(),S.z.literal("inf")]),credit_amount:S.z.number()}))},Of=S.z.union([S.z.strictObject({match:Hi,priority:S.z.number().int().optional(),...Ws}),S.z.strictObject({match:Hi,priority:S.z.number().int().optional(),...Qs})]),wf=S.z.strictObject({match:Hi,factor:S.z.number().positive().optional(),add:S.z.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Ks={metered_feature_id:S.z.string(),feature_amount:S.z.number().optional(),dimensions:S.z.record(Hs,Of).optional(),multipliers:S.z.record(Hs,wf).optional()},Ki=S.z.union([S.z.strictObject({...Ks,...Ws}),S.z.strictObject({...Ks,...Qs})]),jn=S.z.number().min(-100),Ys=S.z.record(S.z.string(),S.z.strictObject({markup:jn})).nullish(),Rn=S.z.record(S.z.string().regex(/.+\/.+/),S.z.strictObject({markup:jn.optional(),input_cost:S.z.number().min(0).optional(),output_cost:S.z.number().min(0).optional()})).nullish(),Ef=S.z.strictObject({default_markup:jn.optional(),provider_markups:Ys,model_markups:Rn}),Zi=S.z.strictObject({schema:S.z.array(Ki).optional(),markups:Ef.optional()}),jf=S.z.strictObject({filters:S.z.array(S.z.strictObject({property:S.z.string(),operator:S.z.string(),value:S.z.array(S.z.string())})),aggregate:S.z.strictObject({type:S.z.string(),property:S.z.string().nullable()}),usage_type:Zs}),Js=S.z.strictObject({schema:S.z.array(Ki).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:S.z.boolean().optional(),usage_type:Zs.default("single_use").overwrite(()=>"single_use"),default_markup:jn.optional(),provider_markups:Ys}),Wi=Js.safeExtend({schema:S.z.array(Ki).length(0)}),En={id:Cf,name:S.z.string().min(1),display:S.z.strictObject({singular:S.z.string().optional(),plural:S.z.string().optional()}).nullish(),event_names:S.z.array(S.z.string()).default([]),model_markups:Rn,stripe_meter:S.z.strictObject({id:S.z.string(),event_name:S.z.string()}).nullish(),stripe_product_id:S.z.string().nullish()},Qi=e=>S.z.discriminatedUnion("type",[S.z.strictObject({...En,...e,type:S.z.literal("boolean"),config:S.z.null()}),S.z.strictObject({...En,...e,type:S.z.literal("metered"),config:jf}),S.z.strictObject({...En,...e,type:S.z.literal("credit_system"),config:Js}),S.z.strictObject({...En,...e,type:S.z.literal("ai_credit_system"),config:Wi})]),pS=Qi({}),Rf=S.z.strictObject({id:S.z.boolean(),type:S.z.boolean(),usage_type:S.z.boolean()}),Tf={internal_id:S.z.uuid(),org_id:S.z.uuid(),created_at:S.z.number(),env:S.z.enum(["sandbox","live"]),archived:S.z.boolean(),project_id:S.z.uuid(),environment_id:S.z.uuid(),revision:S.z.number().int().nonnegative(),update_rules:Rf},Xs=Qi(Tf),fS=S.z.strictObject({rows:S.z.array(Xs).max(200),nextCursor:S.z.uuid().nullable()}),zs=S.z.strictObject({features:S.z.array(Xs).max(500),limited:S.z.boolean()}),hS=S.z.union([Qi({action:S.z.literal("save"),internal_id:S.z.uuid().nullable(),revision:S.z.number().int().nonnegative()}),S.z.strictObject({action:S.z.enum(["archive","restore","delete"]),internal_id:S.z.uuid(),revision:S.z.number().int().nonnegative()})]);var Ht=require("zod"),ec=Ht.z.number().int().min(0).max(1e8),Tr=Ht.z.strictObject({kind:Ht.z.enum(["graduated","volume"]),tiers:Ht.z.array(Ht.z.strictObject({upTo:Ht.z.number().int().min(1).max(1e4).nullable(),unitAmountMinor:ec,flatAmountMinor:ec.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,r)=>{let n=e.tiers[r-1]?.upTo;return t.upTo!==null&&(r===0||n!=null&&t.upTo>n)}),"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 Yi(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let r=e.pricing?Tr.parse(e.pricing):void 0;if(t===0)return 0;let n=0n,i=0;if(!r)n=BigInt(e.amountMinor)*BigInt(t);else for(let o of r.tiers){let a=o.upTo??1e4;if(r.kind==="volume"){if(t<=a){n=BigInt(t)*BigInt(o.unitAmountMinor)+BigInt(o.flatAmountMinor??0);break}}else t>i&&(n+=BigInt(Math.min(t,a)-i)*BigInt(o.unitAmountMinor));i=a}if(n>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(n)}function Tn(e){return Yi({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var P=require("zod");var l=require("zod");var T=require("zod");var Le=require("zod");var g=require("zod");var Qe=g.z.json().superRefine((e,t)=>{let r=0;function n(i,o){if(++r>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=>n(a,o+1));else if(i&&typeof i=="object")for(let[a,c]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"}),n(c,o+1)}n(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),St=g.z.record(g.z.string().min(1).max(128),Qe).superRefine((e,t)=>{(!Qe.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(r=>Object.hasOwn(e,r)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),kf=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"]),dt=St.superRefine((e,t)=>{function r(n){if(Array.isArray(n))n.forEach(r);else if(n&&typeof n=="object")for(let[i,o]of Object.entries(n)){if(i==="$savedGroup"&&!g.z.strictObject({id:g.z.uuid(),attributeKey:g.z.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("$")&&!kf.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,c)=>String.fromCharCode(Number.parseInt(c,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"})}}r(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"}),r(e)}),Df=g.z.discriminatedUnion("type",[g.z.strictObject({type:g.z.literal("condition"),condition:dt}),g.z.strictObject({type:g.z.literal("list"),attributeKey:g.z.string().min(1).max(128),values:g.z.array(g.z.union([g.z.string(),g.z.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 Xi(e){let t=new Set;function r(n){if(Array.isArray(n))n.forEach(r);else if(n&&typeof n=="object")for(let[i,o]of Object.entries(n))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)||r(o)}return r(e),[...t]}var Nf=g.z.record(g.z.uuid(),Df).superRefine((e,t)=>{let r=new Set,n=new Set;function i(o){if(r.has(o)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(n.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}r.add(o),a.type==="condition"&&Xi(a.condition).forEach(i),r.delete(o),n.add(o)}Object.keys(e).forEach(i)}),zi=g.z.tuple([g.z.number().min(0).max(1),g.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),tc=g.z.strictObject({attribute:g.z.string().optional(),seed:g.z.string().min(1),hashVersion:g.z.literal(2),ranges:g.z.array(zi).min(1).max(100)}),Mf=g.z.strictObject({id:g.z.string().min(1).max(128),condition:dt,gate:g.z.boolean().optional()}),Ji={id:g.z.string().max(128).optional(),condition:dt.optional(),parentConditions:g.z.array(Mf).max(50).optional(),filters:g.z.array(tc).max(20).optional()},Uf=g.z.union([g.z.strictObject({...Ji}),g.z.strictObject({...Ji,force:Qe,coverage:g.z.number().min(0).max(1).optional(),range:zi.optional(),seed:g.z.string().min(1).optional(),hashAttribute:g.z.string().optional(),hashVersion:g.z.literal(2).optional()}),g.z.strictObject({...Ji,type:g.z.literal("experiment-ref"),experimentId:g.z.uuid(),values:g.z.record(g.z.string().min(1),Qe),meta:g.z.record(g.z.string().min(1),g.z.strictObject({passthrough:g.z.boolean()})).optional()})]),qf=g.z.strictObject({defaultValue:Qe,rules:g.z.array(Uf).max(100)}),bS=g.z.record(g.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),qf).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let r=new Set,n=new Set;function i(o){if(r.has(o)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${o}`});return}if(n.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${o}`});return}r.add(o);for(let c of a.rules)for(let d of c.parentConditions??[])i(d.id);r.delete(o),n.add(o)}Object.keys(e).forEach(i)}),Lf=g.z.strictObject({name:g.z.string().max(80),reason:g.z.string().max(500),dateStarted:g.z.iso.datetime({offset:!0}),dateEnded:g.z.iso.datetime({offset:!0}).nullable(),coverage:g.z.number().min(0).max(1),variationWeights:g.z.array(g.z.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,r)=>t+r,0)-1)<=.01),condition:dt,savedGroups:g.z.array(g.z.strictObject({match:g.z.enum(["any","all","none"]),ids:g.z.array(g.z.uuid()).min(1)})).max(50),namespace:g.z.strictObject({id:g.z.uuid(),ranges:g.z.array(zi).min(1)}).nullable(),seed:g.z.string().min(1).max(128)}),Bf=g.z.strictObject({key:g.z.string().min(1).max(128),name:g.z.string().min(1).max(80),hypothesis:g.z.string().max(2e3),status:g.z.enum(["draft","running","stopped"]),hashAttribute:g.z.string().min(1).max(128),fallbackAttribute:g.z.string().max(128).nullable(),hashVersion:g.z.literal(2),disableStickyBucketing:g.z.boolean(),bucketVersion:g.z.number().int().min(0).max(1e3),minBucketVersion:g.z.number().int().min(0).max(1e3),variations:g.z.array(g.z.strictObject({id:g.z.string().min(1),key:g.z.string().min(1),name:g.z.string().max(80),description:g.z.string().max(500)})).min(2).max(20),phases:g.z.array(Lf).min(1).max(100),releasedVariationId:g.z.string().nullable(),excludeFromPayload:g.z.boolean(),statusSchedule:g.z.strictObject({startAt:g.z.iso.datetime({offset:!0}).nullable(),stopAt:g.z.iso.datetime({offset:!0}).nullable(),stopAfter:g.z.strictObject({value:g.z.number().int().positive().max(36500),unit:g.z.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((r,n)=>{if(n===0)return!1;let i=e.phases[n-1];return!i?.dateEnded||Date.parse(r.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(r.dateStarted)})||new Set(e.variations.map(r=>r.key)).size!==e.variations.length||new Set(e.variations.map(r=>r.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(r=>r.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(r=>r.dateEnded&&Date.parse(r.dateStarted)>=Date.parse(r.dateEnded)||r.namespace?.ranges.some(([n,i],o,a)=>n>=i||a.some(([c,d],p)=>p!==o&&n<d&&c<i)))||e.phases.some(r=>r.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var Vf=Bf.safeExtend({filters:g.z.array(tc).optional()}),Ff=g.z.strictObject({experiments:g.z.record(g.z.uuid(),Vf),savedGroups:Nf}),$f=g.z.strictObject({attributeName:g.z.string(),attributeValue:g.z.string(),assignments:g.z.record(g.z.string(),g.z.string())}),yS=g.z.strictObject({snapshot:Ff,attributes:St,results:St,stickyBucketAssignmentDocs:g.z.record(g.z.string(),$f)}),SS=g.z.strictObject({variantKey:g.z.string().nullable(),bucketVersion:g.z.number().int().min(0),source:g.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:g.z.number().min(0).max(1).optional(),stickyBucketUsed:g.z.boolean().optional(),hashUsed:g.z.boolean().optional()});function rc(e){let t=new Set,r=o=>o!==null&&typeof o=="object"&&!Array.isArray(o);function n(o,a){if(r(o))for(let[c,d]of Object.entries(o))c==="$elemMatch"?i(d,a):c==="$not"?n(d,a):c==="$all"&&Array.isArray(d)&&d.forEach(p=>n(p,a))}function i(o,a=""){if(r(o)){for(let[c,d]of Object.entries(o))if(["$and","$or","$nor"].includes(c)&&Array.isArray(d))d.forEach(p=>i(p,a));else if(c==="$not")i(d,a);else if(c==="$savedGroup"&&r(d))typeof d.attributeKey=="string"&&t.add(d.attributeKey);else if(!c.startsWith("$")){let p=a?`${a}.${c}`:c;t.add(p),n(d,p)}}}return i(e),[...t]}var Gf=Le.z.enum(["active","inactive"]),Hf=Le.z.preprocess((e,t)=>{let r=0;function n(i,o){if(!(++r>1e4||o>20)){if(Array.isArray(i))i.forEach(a=>n(a,o+1));else if(i&&typeof i=="object")for(let[a,c]of Object.entries(i))["__proto__","constructor","prototype"].includes(a)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),n(c,o+1)}}return n(e,0),e},St),Kf=Le.z.strictObject({id:Le.z.string().trim().min(1).max(255),name:Le.z.string().trim().min(1).max(255),status:Gf,metadata:Hf}),PS=Kf.extend({internal_id:Le.z.uuid(),project_id:Le.z.uuid(),environment_id:Le.z.uuid(),created_at:Le.z.iso.datetime({offset:!0}),updated_at:Le.z.iso.datetime({offset:!0})}),ic=Le.z.union([Le.z.strictObject({id:Le.z.string().trim().min(1).max(255)}),Le.z.strictObject({internalId:Le.z.uuid()})]),CS=Le.z.enum(["customer","merchandise","context"]),OS=Le.z.enum(["system","stored","request"]),wS=Le.z.enum(["customer","merchandise","mixed"]),nc=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function ea(e,t={},r=new Set){if(rc(e).some(nc))return!0;for(let n of Xi(e)){if(r.has(n))continue;r.add(n);let i=t[n];if(i?.type==="list"&&nc(i.attributeKey)||i?.type==="condition"&&ea(i.condition,t,r))return!0}return!1}var ac=require("zod"),Zf=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,mt=ac.z.string().max(16).regex(Zf,"\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");var DS=T.z.enum(["draft","active","paused","archived"]),Dt=T.z.discriminatedUnion("type",[T.z.object({type:T.z.literal("percent"),percentOff:T.z.number().int().min(1).max(100)}).strict(),T.z.object({type:T.z.literal("amount"),amountOffCents:T.z.number().int().min(1).max(1e8),currency:Q}).strict()]),tt=T.z.discriminatedUnion("type",[T.z.object({type:T.z.literal("once")}).strict(),T.z.object({type:T.z.literal("repeating"),months:T.z.number().int().min(1).max(36)}).strict(),T.z.object({type:T.z.literal("forever")}).strict()]),oc=[T.z.object({type:T.z.literal("all")}).strict(),T.z.object({type:T.z.literal("plans"),planIds:T.z.array(T.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Wf=T.z.discriminatedUnion("type",[...oc,T.z.strictObject({type:T.z.literal("merchandise"),scope:T.z.discriminatedUnion("type",[T.z.strictObject({type:T.z.literal("all")}),T.z.strictObject({type:T.z.literal("selected"),merchandiseIds:T.z.array(T.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),T.z.strictObject({type:T.z.literal("condition"),condition:dt})])})]),ta=T.z.discriminatedUnion("type",[...oc,T.z.strictObject({type:T.z.literal("merchandise"),scope:T.z.strictObject({type:T.z.enum(["all","selected","condition"])})})]),Qf=T.z.strictObject({firstPurchaseOnly:T.z.boolean(),condition:dt}),NS=T.z.object({name:T.z.string().trim().min(1).max(80),description:T.z.string().max(500),discount:Dt,duration:tt,appliesTo:Wf,eligibility:Qf,selfClaimEnabled:T.z.boolean().default(!1),startsAt:T.z.iso.datetime().nullable(),endsAt:T.z.iso.datetime().nullable(),totalLimit:T.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:T.z.number().int().min(1).max(10),grantWindowHours:T.z.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!ea(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),MS=T.z.object({code:T.z.string().trim().transform(e=>e.toUpperCase()).pipe(T.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:T.z.number().int().min(1).max(1e6).nullable(),expiresAt:T.z.iso.datetime().nullable(),firstPurchaseOnly:T.z.boolean(),minimumAmountCents:T.z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Q.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var ra=T.z.object({id:T.z.uuid(),couponId:T.z.uuid(),status:T.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:T.z.iso.datetime(),expiresAt:T.z.iso.datetime(),coupon:T.z.object({name:T.z.string(),discount:Dt,duration:tt,appliesTo:ta}).strict()}).strict(),sc=T.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var mc=l.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),na=l.z.string().regex(/^(0|[1-9]\d{0,14})$/),mr=l.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Yf=l.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),kr=Yf,wt=Z.refine(e=>/[1-9]/.test(e)),Ye=l.z.iso.datetime({offset:!0}),Kt=e=>{let[t,r=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(r.padEnd(6,"0"))},Jf=l.z.array(l.z.object({upTo:wt.nullable(),unitAmountMinor:mc,flatAmountMinor:l.z.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,r)=>{let n=e[r-1]?.upTo;return t.upTo!==null&&(r===0||n!=null&&Kt(t.upTo)>Kt(n))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Xf=l.z.discriminatedUnion("kind",[l.z.object({kind:l.z.literal("flat"),units:wt,unitAmountMinor:mc}).strict(),l.z.object({kind:l.z.enum(["graduated","volume"]),units:wt,tiers:Jf}).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"),zf=l.z.strictObject({interval:l.z.enum(["month","year"]),count:l.z.number().int().min(1).max(12),anchor:l.z.enum(["membership","calendar"])}),Nt=l.z.object({currency:Q,pricing:Xf,billingCycle:zf.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function pc(e){return e.pricing.kind==="flat"&&Kt(e.pricing.units)>0n&&Kt(e.pricing.unitAmountMinor)===Kt(e.pricing.units)*BigInt(10**Uo(e.currency))}var cc={requestId:l.z.uuid(),productVersionId:l.z.uuid(),internal_feature_id:l.z.uuid(),currency:Q},fc=l.z.strictObject({interval:l.z.enum(["hour","day","week","month"]),intervalCount:l.z.number().int().min(1).max(12),limit:l.z.number().int().min(1).max(1e6)}),hc=l.z.discriminatedUnion("kind",[l.z.object({...cc,kind:l.z.literal("auto_topup"),threshold:gn,quantity:wt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:fc.optional()}).strict(),l.z.object({...cc,kind:l.z.literal("postpaid"),maxAmountMinorPerPeriod:kr,maxOutstandingMinor:kr}).strict()]),uc={productVersionId:l.z.uuid(),internal_feature_id:l.z.uuid(),currency:Q},Ac=l.z.discriminatedUnion("kind",[l.z.object({...uc,kind:l.z.literal("auto_topup"),threshold:gn,quantity:wt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:fc.optional(),purchaseAmountMinor:kr,purchaseUnits:wt}).strict(),l.z.object({...uc,kind:l.z.literal("postpaid"),maxAmountMinorPerPeriod:kr,maxOutstandingMinor:kr,cashPrice:Nt}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),kn=l.z.object({id:l.z.uuid(),terms:Ac,status:l.z.enum(["prepared","active","revoked","blocked"]),createdAt:Ye,acceptedAt:Ye.nullable(),effectiveAt:Ye.nullable(),revokedAt:Ye.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"),gc=l.z.object({authorizationId:l.z.uuid(),terms:Ac,setupUrl:l.z.url().nullable()}).strict(),bc=l.z.object({authorizationId:l.z.uuid(),accepted:l.z.literal(!0)}).strict(),yc=l.z.object({authorizationId:l.z.uuid(),requestId:l.z.uuid()}).strict(),Sc=l.z.object({internal_feature_id:l.z.uuid(),entityId:l.z.uuid().nullable(),interval:l.z.enum(["day","week","month","year"]),anchor:l.z.enum(["billing_cycle","utc"]).optional(),basis:l.z.enum(["usage","credits"]),filter:Ue.optional(),limit:Z.nullable(),thresholds:l.z.array(l.z.number().positive().max(1)).max(8),includedThresholds:l.z.array(l.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:l.z.array(wt).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,r)=>{let n=e.thresholds[r-1];return r===0||n!==void 0&&t>n})&&(e.includedThresholds??[]).every((t,r,n)=>{let i=n[r-1];return r===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,r,n)=>{let i=n[r-1];return r===0||i!==void 0&&Kt(t)>Kt(i)}),"Notification thresholds must increase"),eh=Sc.safeExtend({requestId:l.z.uuid()}),lc={control:l.z.literal("overage"),requestId:l.z.uuid(),internal_feature_id:l.z.uuid(),entityId:l.z.uuid().nullable()},th=l.z.discriminatedUnion("action",[l.z.strictObject({...lc,action:l.z.literal("set"),allowed:l.z.boolean().nullable(),overageLimit:Z.nullable(),skipOverageBilling:l.z.boolean()}),l.z.strictObject({...lc,action:l.z.literal("remove")})]),_c=l.z.union([eh,th]),rh=l.z.strictObject({internal_feature_id:l.z.uuid(),entityId:l.z.uuid().nullable(),allowed:l.z.boolean().nullable(),overageLimit:Z.nullable(),skipOverageBilling:l.z.boolean(),interval:l.z.enum(["day","week","month","year"]),startsAt:Ye,endsAt:Ye,used:l.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:l.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:l.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),nh=l.z.object({internal_feature_id:l.z.uuid(),entityId:l.z.uuid().nullable(),interval:l.z.enum(["day","week","month","year"]),anchor:l.z.enum(["billing_cycle","utc"]).optional(),basis:l.z.enum(["usage","credits"]),filter:Ue.optional(),startsAt:Ye,endsAt:Ye,used:Xe,reserved:Xe,limit:Z.nullable(),thresholds:l.z.array(l.z.number().positive().max(1)).max(8),notifiedThresholds:l.z.array(l.z.number().positive().max(1)).max(1024),includedThresholds:l.z.array(l.z.number().positive().max(1)).max(8).optional(),includedAllowance:l.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:l.z.array(l.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:l.z.array(wt).max(8).optional(),notifiedAbsoluteThresholds:l.z.array(wt).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||Z.safeParse(e.used).success&&Z.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),ih=l.z.object({authorizationId:l.z.uuid(),status:l.z.enum(["idle","pending","blocked"]),taskId:l.z.uuid().nullable(),invoiceId:l.z.uuid().nullable(),hostedInvoiceUrl:l.z.url().nullable(),purchaseCount:l.z.number().int().nonnegative(),purchaseWindowEndsAt:Ye.nullable(),attemptCount:l.z.number().int().nonnegative(),failedAttemptCount:l.z.number().int().nonnegative(),suspendedAt:Ye.nullable(),nextAttemptAt:Ye.nullable(),failureReason:l.z.string().min(1).max(240).nullable()}).strict(),xc=l.z.object({internal_feature_id:l.z.uuid().optional(),entityId:l.z.uuid().optional()}).strict(),ia=l.z.object({authorizations:l.z.array(kn).max(100),limits:l.z.array(Sc).max(100),overages:l.z.array(rh).max(100).optional(),windows:l.z.array(nh).max(200),autoTopups:l.z.array(ih).max(100),limited:l.z.boolean()}).strict(),ah=l.z.object({id:l.z.uuid(),internal_feature_id:l.z.uuid(),productVersionId:l.z.uuid(),authorizationId:l.z.uuid(),entityId:l.z.uuid().nullable(),units:Z,amountMinor:mr,cashPrice:Nt}).strict(),Dr=l.z.object({id:l.z.uuid(),sourceKind:l.z.enum(["product","usage","manual"]),providerInvoiceId:l.z.string().min(1).max(240).nullable(),status:l.z.enum(["accruing","open","pending","paid","failed","void"]),currency:Q,startsAt:Ye.nullable(),endsAt:Ye.nullable(),amountMinor:l.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:l.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:na,paidAmountMinor:na,refundedAmountMinor:na,createdAt:Ye,hostedInvoiceUrl:l.z.url().nullable(),adjustment:l.z.object({originalInvoiceId:l.z.uuid(),amountMinor:l.z.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:Ye.nullable()}).strict().nullable(),lines:l.z.array(ah).max(100),linesLimited:l.z.boolean()}).strict(),Ic=l.z.object({invoiceId:l.z.uuid(),accepted:l.z.literal(!0)}).strict(),vc=l.z.object({after:l.z.uuid().nullable(),limit:l.z.number().int().min(1).max(100)}).strict(),Pc=l.z.object({rows:l.z.array(Dr).max(100),nextCursor:l.z.uuid().nullable()}).strict(),dc=l.z.strictObject({id:l.z.string(),coupon:l.z.string(),start:l.z.number().nonnegative(),end:l.z.number().nullable()}),oh=l.z.strictObject({subscriptionId:l.z.string(),customerId:l.z.string(),accountId:l.z.string(),sourceItems:l.z.array(l.z.strictObject({id:l.z.string(),price_id:l.z.string(),quantity:l.z.number().int(),discounts:l.z.array(dc).optional()})).max(100),items:l.z.array(l.z.strictObject({id:l.z.string(),price:l.z.string(),quantity:l.z.number().int(),discounts:l.z.array(l.z.strictObject({coupon:l.z.string().optional(),terms:l.z.strictObject({id:l.z.string(),name:l.z.string().optional(),percent_off:l.z.number().optional(),amount_off:l.z.number().optional(),currency:l.z.string().optional(),duration:l.z.enum(["once","forever","repeating"]),duration_in_months:l.z.number().optional()}).optional(),discount:l.z.string().optional(),receipt:dc.optional()})).max(20)})).max(100)}),Cc=l.z.strictObject({membershipId:l.z.uuid(),requestId:l.z.uuid(),grantIds:l.z.array(l.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Oc=l.z.strictObject({membershipId:l.z.uuid(),operationId:l.z.uuid(),status:l.z.enum(["pending","effective"]),execution:oh.nullable(),grants:l.z.array(l.z.strictObject({id:l.z.uuid(),couponId:l.z.uuid(),name:l.z.string(),discount:Dt,duration:tt,startedAt:Ye.nullable()})).max(20)});var pr=require("zod");var Nr=pr.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Mr=pr.z.number().int().min(1).max(1e3),Zt=pr.z.object({cap:Z.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:pr.z.number().positive().max(1e4).nullable(),cycles:pr.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var aa={key:yt,name:P.z.string().trim().min(1).max(80),description:P.z.string().trim().max(240)},wc=Z.refine(e=>/[1-9]/.test(e)),Dn=P.z.array(P.z.object({currency:Q,amountMinor:P.z.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"),oa=P.z.strictObject({units:wc,prices:P.z.array(P.z.strictObject({currency:Q,amountMinor:P.z.number().int().min(0).max(1e8),pricing:Tr.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:P.z.number().int().min(0).max(1e4),maximumQuantity:P.z.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 r of[e.maximumQuantity,...t.pricing?.tiers.flatMap(n=>n.upTo===null?[]:[n.upTo,n.upTo+1])??[]])r<=e.maximumQuantity&&Yi({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},r);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit"),sh=P.z.discriminatedUnion("kind",[P.z.object({kind:P.z.literal("access"),internal_feature_id:P.z.uuid()}).strict(),P.z.object({kind:P.z.literal("metered"),internal_feature_id:P.z.uuid(),usageUnit:P.z.enum(["count","micro_usd"]),amount:Z.nullable(),reset:Nr,resetCount:Mr,pooled:P.z.boolean(),rollover:Zt.nullable().optional(),cashPrice:Nt.nullable().optional(),prepaidPrice:oa.optional(),feature_override:Zi.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 ca(e.amount,e.prepaidPrice.units,e.prepaidPrice.maximumQuantity),!0}catch{return!1}},"The maximum purchased allowance must fit the quantity ledger"),P.z.object({kind:P.z.literal("credit"),internal_feature_id:P.z.uuid(),amount:Z,reset:Nr,resetCount:Mr,rollover:Zt.nullable(),pooled:P.z.boolean(),feature_override:Zi.nullish(),cashPrice:Nt.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&pc(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")]),sa=P.z.array(sh).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),Ec=P.z.object({days:P.z.number().int().min(1).max(730),cardRequired:P.z.boolean(),allowances:sa}).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"),jc=P.z.object({key:yt,internal_feature_id:P.z.uuid(),productVersionId:P.z.uuid(),includedQuantity:P.z.number().int().min(0).max(1e4),maximumQuantity:P.z.number().int().min(0).max(1e4),prices:Dn,pooled_internal_feature_ids:P.z.array(P.z.uuid()).max(100),requireAssignment:P.z.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"),Rc=P.z.discriminatedUnion("kind",[P.z.object({...aa,kind:P.z.literal("membership"),groupId:P.z.uuid(),membershipType:P.z.enum(["main","addon"]),interval:P.z.enum(["free","week","month","year","one_time"]),intervalCount:P.z.number().int().min(1).max(156).optional(),prices:Dn,allowances:sa,trial:Ec.nullable(),licenses:P.z.array(jc).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(r=>r.kind==="metered"&&r.prepaidPrice?.prices.some(n=>n.currency===t.currency&&n.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(r=>e.prices.some(n=>n.currency===r.currency))),"Purchased features require a paid plan and all its published currencies"),P.z.object({...aa,kind:P.z.literal("topup"),interval:P.z.literal("one_time"),prices:Dn,internal_feature_id:P.z.uuid(),amount:wc,expiresDays:P.z.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),ch=P.z.object({interval:P.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:P.z.number().int().min(1).max(156).nullable().optional(),prices:Dn.optional(),allowances:P.z.object({upsert:sa,remove:P.z.array(P.z.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:Ec.nullable().optional(),licenses:P.z.array(jc).max(20).optional()}).strict(),uh=P.z.object({...aa,kind:P.z.literal("variant"),baseProductVersionId:P.z.uuid(),overrides:ch}).strict(),XS=P.z.union([Rc,uh]);var zS=P.z.object({products:P.z.array(P.z.object({id:P.z.uuid(),productId:P.z.string().min(1),name:P.z.string(),kind:P.z.enum(["membership","topup"]),version:P.z.number().int().positive()}).strict()).max(500),limited:P.z.boolean()}).strict(),lh=Vs.and(P.z.object({internal_id:P.z.uuid(),revision:P.z.number().int().nonnegative(),licenses:P.z.array(Gi)})),e0=P.z.strictObject({rows:P.z.array(lh).max(200),nextCursor:P.z.uuid().nullable()}),t0=P.z.object({groups:P.z.array(P.z.object({id:P.z.uuid(),name:P.z.string(),defaultProductVersionId:P.z.uuid().nullable()}).strict()).max(500),features:zs.shape.features,products:P.z.array(P.z.object({id:P.z.uuid(),productId:P.z.uuid(),version:P.z.number().int().positive(),configuration:Rc,baseProductVersionId:P.z.uuid().nullable()}).strict()).max(500),limited:P.z.boolean()}).strict();function ca(e,t,r){let n=a=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(a))throw new Error("Invalid quantity");let[c,d=""]=a.split(".");if(c===void 0||c==="")throw new Error("Invalid decimal value");return BigInt(c)*1000000n+BigInt(d.padEnd(6,"0"))};if(!Number.isSafeInteger(r)||r<0||r>1e4)throw new Error("Invalid purchased quantity");let i=n(e)+n(t)*BigInt(r);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 Et=require("zod");var Tc=Et.z.strictObject({itemKey:Et.z.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:Et.z.uuid(),includedAmount:Et.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Et.z.number().int().min(0).max(1e4),terms:oa,pricing:Tr.optional(),unitAmountMinor:Et.z.number().int().min(0).max(1e8),productId:Et.z.string().min(1).max(255).nullable(),priceId:Et.z.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{ca(e.includedAmount,e.terms.units,e.quantity),Tn({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var k=require("zod");var Wt=Z.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Ur=k.z.string().min(1).max(120),Nn=k.z.enum(["cap","overflow"]),rt=(e,t)=>{let[r,n=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");return BigInt(r)*10n**BigInt(t)+BigInt(n.padEnd(t,"0"))},qr=e=>{try{return e()}catch{return!1}},Lr=k.z.discriminatedUnion("operation",[k.z.object({operation:k.z.literal("quote"),overageBehavior:Nn.optional(),internal_feature_id:k.z.uuid(),entityId:k.z.uuid().optional(),quantity:Wt,properties:Ue}).strict(),k.z.object({operation:k.z.literal("consume"),overageBehavior:Nn.optional(),occurredAt:k.z.iso.datetime({offset:!0}).optional(),internal_feature_id:k.z.uuid(),entityId:k.z.uuid().optional(),quantity:Z,properties:Ue,idempotencyKey:Ur}).strict(),k.z.object({operation:k.z.literal("reserve"),occurredAt:k.z.iso.datetime({offset:!0}).optional(),internal_feature_id:k.z.uuid(),entityId:k.z.uuid().optional(),quantity:Wt,properties:Ue,idempotencyKey:Ur,expiresInSeconds:k.z.number().int().min(1).max(86400)}).strict(),k.z.object({operation:k.z.literal("confirm"),operationId:k.z.uuid(),quantity:Wt,properties:Ue.optional(),idempotencyKey:Ur}).strict(),k.z.object({operation:k.z.literal("refund"),operationId:k.z.uuid(),quantity:Wt,idempotencyKey:Ur}).strict(),k.z.object({operation:k.z.literal("release"),operationId:k.z.uuid(),idempotencyKey:Ur}).strict()]),ua=k.z.object({internal_credit_feature_id:k.z.uuid().nullable(),internal_metered_feature_id:k.z.uuid(),dimension:k.z.string().min(1).max(64),counterKey:k.z.string().min(1).max(240),cycleStart:k.z.iso.datetime({offset:!0}),unitCost:Z,units:Wt,amount:Xe,tier:k.z.number().int().min(1).max(12).nullable()}).strict(),Qt=k.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function kc(e,t){let r=e.reduce((n,i)=>n+rt(i.units,12),0n)-rt(t,12);return e.some(n=>n.funding==="balance")?r>=-100n&&r<=100n:r===0n}var Dc=k.z.discriminatedUnion("funding",[k.z.strictObject({funding:k.z.literal("balance"),sourceId:k.z.uuid(),rolloverId:k.z.uuid().nullable(),units:Qt.refine(e=>/[1-9]/.test(e)),amount:Xe}),k.z.strictObject({funding:k.z.literal("unbilled"),units:Qt.refine(e=>/[1-9]/.test(e))}),k.z.object({funding:k.z.literal("prepaid"),sourceId:k.z.uuid(),units:Wt,amount:Xe,pricing:k.z.array(ua).min(1).max(12)}).strict().refine(e=>qr(()=>e.pricing.reduce((t,r)=>t+rt(r.units,6),0n)===rt(e.units,6)&&e.pricing.reduce((t,r)=>t+rt(r.amount,12),0n)===rt(e.amount,12)&&e.pricing.every(t=>rt(t.unitCost,6)*rt(t.units,6)===rt(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),k.z.object({funding:k.z.literal("postpaid"),invoiceLineId:k.z.uuid().nullable(),units:Wt,authorizationId:k.z.uuid()}).strict()]),Mn=k.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Nc=k.z.object({allowed:k.z.boolean(),internal_feature_id:k.z.uuid(),quantity:Z,requestedQuantity:Z.optional(),overageBehavior:Nn.optional(),reason:Mn.nullable(),allocations:k.z.array(Dc).max(500)}).strict().refine(e=>qr(()=>e.allowed?e.reason===null&&kc(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>qr(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&rt(e.requestedQuantity,6)>=rt(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Br=k.z.object({id:k.z.uuid(),internal_feature_id:k.z.uuid(),kind:k.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:k.z.uuid().nullable(),quantity:Z,requestedQuantity:Z.optional(),overageBehavior:Nn.optional(),accepted:k.z.boolean(),reason:k.z.enum([...Mn.options,"expired"]).nullable(),createdAt:k.z.iso.datetime({offset:!0}),reservationStatus:k.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:k.z.iso.datetime({offset:!0}).nullable(),allocations:k.z.array(Dc).max(500)}).strict().refine(e=>qr(()=>e.accepted?e.reason===null&&kc(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>qr(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&rt(e.requestedQuantity,6)>=rt(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");var oe=require("zod");var Yt=oe.z.iso.datetime({offset:!0}),Mc=Z.refine(e=>/[1-9]/.test(e)),Uc=oe.z.strictObject({interval:Nr.exclude(["lifetime"]),count:Mr}),dh=oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),internal_feature_id:oe.z.uuid(),entityId:oe.z.uuid().nullable(),amount:Mc.nullable(),expiresAt:Yt.nullable(),reset:Uc.nullable(),rollover:Zt.nullable(),nextResetAt:Yt.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),qc=oe.z.discriminatedUnion("action",[dh,oe.z.strictObject({action:oe.z.literal("update"),requestId:oe.z.uuid(),grantId:oe.z.uuid(),revision:oe.z.number().int().nonnegative(),amount:Mc.nullable(),expiresAt:Yt.nullable(),rollover:Zt.nullable(),nextResetAt:Yt.nullable()}),oe.z.strictObject({action:oe.z.enum(["add","subtract","set_remaining"]),requestId:oe.z.uuid(),grantId:oe.z.uuid(),revision:oe.z.number().int().nonnegative(),amount:Z}),oe.z.strictObject({action:oe.z.literal("revoke"),requestId:oe.z.uuid(),grantId:oe.z.uuid(),revision:oe.z.number().int().nonnegative()})]),la=oe.z.strictObject({id:oe.z.uuid(),internal_feature_id:oe.z.uuid(),entityId:oe.z.uuid().nullable(),amount:Z.nullable(),reset:Uc.nullable(),rollover:Zt.nullable(),nextResetAt:Yt.nullable(),startsAt:Yt,expiresAt:Yt.nullable(),revision:oe.z.number().int().nonnegative(),revoked:oe.z.boolean(),available:Xe,held:Xe,spent:Xe}),Lc=oe.z.strictObject({customerId:oe.z.uuid(),after:oe.z.uuid().nullable(),limit:oe.z.number().int().min(1).max(100)}),Bc=oe.z.strictObject({rows:oe.z.array(la).max(100),nextCursor:oe.z.uuid().nullable()});var M=require("zod");var _t=M.z.iso.datetime({offset:!0}),Vc=M.z.strictObject({invoiceId:M.z.uuid(),after:M.z.string().min(1).max(180).nullable(),limit:M.z.number().int().min(1).max(100)}),mh=M.z.strictObject({kind:M.z.literal("product"),key:M.z.string(),productVersionId:M.z.uuid(),productName:M.z.string(),itemKey:M.z.string(),entityId:M.z.uuid().nullable(),quantity:M.z.number().int().positive(),subtotalMinor:M.z.string().regex(/^-?\d+$/),discountMinor:M.z.string().regex(/^\d+$/),taxMinor:M.z.string().regex(/^-?\d+$/).nullable(),totalMinor:M.z.string().regex(/^-?\d+$/),startsAt:_t.nullable(),endsAt:_t.nullable(),providerLineId:M.z.string().nullable(),providerItemId:M.z.string()}),Fc=M.z.strictObject({invoice:Dr,items:M.z.array(M.z.discriminatedUnion("kind",[mh,M.z.strictObject({kind:M.z.literal("invoice_credit"),key:M.z.string(),internal_feature_id:M.z.uuid(),internal_credit_feature_id:M.z.uuid(),name:M.z.string(),units:Z,reserved:Z,amountMinor:mr,grossAmountMinor:mr,creditsAppliedMinor:mr,properties:Ue,cashPrice:Nt,providerItemId:M.z.string().nullable(),creditProviderItemId:M.z.string().nullable()}),M.z.strictObject({kind:M.z.literal("usage"),key:M.z.string(),internal_feature_id:M.z.uuid(),name:M.z.string(),units:Z,reserved:Z,amountMinor:mr,cashPrice:Nt})])).max(100),nextCursor:M.z.string().min(1).max(180).nullable()}),ph=M.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),da=M.z.strictObject({from:_t,to:_t,entityId:M.z.uuid().optional(),snapshotAt:_t.nullable(),after:M.z.strictObject({at:_t,id:M.z.uuid(),position:M.z.number().int().nonnegative()}).nullable(),limit:M.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"),$c=M.z.strictObject({customerId:M.z.uuid(),entityId:M.z.uuid().nullable(),from:_t,to:_t,snapshotAt:_t,totals:M.z.array(M.z.strictObject({internal_credit_feature_id:M.z.uuid(),name:M.z.string(),consumed:Xe,refunded:Xe,net:ph})).max(1e3),rows:M.z.array(M.z.strictObject({operationId:M.z.uuid(),position:M.z.number().int().nonnegative(),kind:M.z.enum(["consume","confirm","refund"]),originalId:M.z.uuid().nullable(),occurredAt:_t,internal_feature_id:M.z.uuid(),entitlementName:M.z.string(),sourceId:M.z.uuid(),internal_credit_feature_id:M.z.uuid(),creditName:M.z.string(),units:Qt,amount:Xe,pricing:M.z.array(ua).max(12),properties:Ue})).max(100),nextCursor:da.shape.after});var b=require("zod");var at=require("zod");var fh=at.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),hh=at.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Un=at.z.strictObject({internal_feature_id:at.z.uuid(),entityId:at.z.uuid().nullable()}),Gc=Un.extend({quantity:Z,expectedRevision:at.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:at.z.string().min(1).max(120),properties:Ue.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Vr=Un.extend({operationId:at.z.uuid().nullable(),usage:Z,capacity:fh.nullable(),remaining:hh.nullable(),withinLimit:at.z.boolean(),revision:at.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:at.z.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let r=n=>{let i=n.startsWith("-"),[o,a=""]=(i?n.slice(1):n).split(".");if(o===void 0||o==="")throw new Error("Invalid decimal value");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||r(e.remaining)!==r(e.capacity)-r(e.usage)||e.withinLimit!==r(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 Je=b.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),pt=b.z.iso.datetime({offset:!0}),Ah=b.z.enum(["access","metered","credit"]),Fr={internal_feature_id:b.z.uuid(),key:Gt,name:b.z.string().min(1).max(120),kind:Ah},Hc=b.z.object({customerId:b.z.uuid(),snapshotAt:pt,memberships:b.z.array(b.z.object({id:b.z.uuid(),productId:b.z.string().min(1).max(255),productVersionId:b.z.uuid(),billingProductVersionId:b.z.uuid(),version:b.z.number().int().positive(),key:b.z.string().min(1).max(64),name:b.z.string().min(1).max(120),groupId:b.z.string().max(255).nullable(),membershipType:b.z.enum(["main","addon"]),status:b.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:b.z.boolean(),accessEnabled:b.z.boolean(),renewalChange:b.z.object({productVersionId:b.z.uuid(),name:b.z.string().min(1).max(120),version:b.z.number().int().positive(),effectiveAt:pt,benefitsAppliedAt:pt.nullable(),timing:b.z.enum(["immediate","renewal"]),changeKind:b.z.enum(["plan","seats","quantity"]),feature:b.z.strictObject({internal_feature_id:b.z.uuid(),name:b.z.string().min(1).max(80),fromQuantity:b.z.number().int().min(0).max(1e4),toQuantity:b.z.number().int().min(0).max(1e4)}).optional(),seat:b.z.object({key:b.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:b.z.number().int().min(0).max(1e4),toQuantity:b.z.number().int().min(0).max(1e4)}).strict().nullable(),status:b.z.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:b.z.object({phase:b.z.enum(["paid","trial"]),startsAt:pt,endsAt:pt.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:b.z.boolean(),balances:b.z.array(b.z.object({...Fr,usageType:b.z.enum(["consumable","non_consumable"]).nullable(),accessible:b.z.boolean(),unlimited:b.z.boolean(),available:Je,held:Je,debt:Je,nextExpiresAt:pt.nullable(),usage:Vr.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:b.z.boolean()}).strict(),Kc=b.z.enum(["source","usage","transaction","invoice","debt","settlement"]),Zc=b.z.object({at:pt,id:b.z.uuid(),type:Kc}).strict(),Wc=b.z.object({type:Kc.nullable(),resourceKey:Gt.optional(),kind:b.z.enum(["purchase","refund"]).optional(),topup:b.z.boolean().optional(),from:b.z.iso.date().nullable(),to:b.z.iso.date().nullable(),after:Zc.nullable(),limit:b.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),fr={id:b.z.uuid(),occurredAt:pt},gh=b.z.discriminatedUnion("type",[b.z.strictObject({...fr,type:b.z.literal("invoice"),status:b.z.string().min(1).max(80),paid:Je,refunded:Je,currency:Q,externalId:b.z.string().nullable()}),b.z.object({...fr,...Fr,type:b.z.literal("source"),reason:b.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Je,unlimited:b.z.boolean(),status:b.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:pt,expiresAt:pt.nullable(),orderId:b.z.uuid().nullable(),parentSourceId:b.z.uuid().nullable()}).strict(),b.z.object({...fr,type:b.z.literal("usage"),internal_feature_id:b.z.uuid(),name:b.z.string().min(1).max(120),kind:b.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:b.z.uuid().nullable(),quantity:Z,accepted:b.z.boolean(),reason:b.z.enum([...Mn.options,"expired"]).nullable(),properties:Ue,reservationStatus:b.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:pt.nullable(),charges:b.z.array(b.z.discriminatedUnion("funding",[b.z.strictObject({funding:b.z.literal("balance"),sourceId:b.z.uuid(),rolloverId:b.z.uuid().nullable(),units:Qt,amount:Je}),b.z.strictObject({funding:b.z.literal("unbilled"),units:Qt}),b.z.object({...Fr,funding:b.z.literal("prepaid"),amount:Je}).strict(),b.z.object({funding:b.z.literal("postpaid"),invoiceId:b.z.uuid(),invoiceLineId:b.z.uuid(),authorizationId:b.z.uuid(),units:Z,currency:Q}).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"),b.z.object({...fr,type:b.z.literal("transaction"),purpose:b.z.enum(["product","invoice"]),productVersionId:b.z.uuid().nullable(),productName:b.z.string().min(1).max(120).nullable(),productVersion:b.z.number().int().positive().nullable(),invoiceId:b.z.uuid().nullable(),orderId:b.z.uuid(),originalId:b.z.uuid().nullable(),kind:b.z.enum(["purchase","refund"]),amountMinor:b.z.number().int().nonnegative().max(2e8).nullable(),currency:Q.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"),b.z.object({...fr,...Fr,type:b.z.literal("debt"),sourceId:b.z.uuid(),transactionId:b.z.uuid(),amount:Je}).strict(),b.z.object({...fr,...Fr,type:b.z.literal("settlement"),sourceId:b.z.uuid(),debtId:b.z.uuid(),kind:b.z.enum(["payment","usage_refund","payment_return"]),amount:Je}).strict()]),Qc=b.z.object({customerId:b.z.uuid(),rows:b.z.array(gh).max(50),nextCursor:Zc.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");var K=require("zod"),Jc=K.z.object({customerId:K.z.uuid()}).strict(),Xc=K.z.discriminatedUnion("action",[K.z.object({customerId:K.z.uuid(),requestId:K.z.uuid(),action:K.z.literal("assign"),poolId:K.z.uuid(),memberCustomerId:K.z.uuid()}).strict(),K.z.strictObject({customerId:K.z.uuid(),requestId:K.z.uuid(),action:K.z.literal("assign_entity"),poolId:K.z.uuid(),entityId:K.z.uuid()}),K.z.object({customerId:K.z.uuid(),requestId:K.z.uuid(),action:K.z.literal("release"),poolId:K.z.uuid(),slotId:K.z.uuid()}).strict()]),$r=K.z.number().int().nonnegative(),ma=K.z.iso.datetime({offset:!0}),pa=K.z.strictObject({internalId:K.z.uuid(),id:K.z.string(),name:K.z.string().nullable(),version:K.z.number().int().positive()}),Yc=K.z.enum(["active","past_due"]),fa=K.z.strictObject({customerId:K.z.uuid(),licenses:K.z.array(K.z.strictObject({id:K.z.uuid(),linkId:K.z.uuid(),parent:K.z.strictObject({customerProductId:K.z.uuid(),status:Yc,product:pa}),product:pa,planLicense:K.z.strictObject({id:K.z.uuid(),prepaidOnly:K.z.boolean(),isCustom:K.z.boolean()}).nullable(),granted:$r,included:$r,paidQuantity:$r,usage:$r,remaining:$r,createdAt:ma}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:K.z.array(K.z.strictObject({id:K.z.uuid(),linkId:K.z.uuid(),status:Yc,product:pa,entity:K.z.strictObject({internalId:K.z.uuid(),id:K.z.string().nullable(),name:K.z.string().nullable()}).nullable(),beneficiary:K.z.strictObject({internalId:K.z.uuid(),id:K.z.string().nullable(),name:K.z.string().nullable()}).nullable(),startedAt:ma.nullable(),endedAt:ma.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:K.z.boolean()});var H=require("zod"),Gr=H.z.enum(["email","sms","voice","push"]),I0=H.z.enum(["resend","twilio","fcm","apns"]);var v0=H.z.string().regex(/^\+[1-9]\d{1,14}$/),bh=H.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var yh=H.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Sh=H.z.strictObject({subject:yh,html:H.z.string().min(1).max(131072).optional(),text:H.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),_h=H.z.strictObject({body:H.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),xh=H.z.strictObject({text:H.z.string().trim().min(1).max(4e3),language:H.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:H.z.number().int().min(1).max(900)}),Ih=H.z.record(H.z.string().min(1).max(64),H.z.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),vh=H.z.strictObject({title:H.z.string().trim().min(1).max(200),body:H.z.string().trim().min(1).max(2e3),url:H.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:Ih.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),zc=H.z.discriminatedUnion("channel",[H.z.strictObject({channel:H.z.literal("email"),content:Sh}),H.z.strictObject({channel:H.z.literal("sms"),content:_h}),H.z.strictObject({channel:H.z.literal("voice"),content:xh}),H.z.strictObject({channel:H.z.literal("push"),content:vh})]),eu=H.z.strictObject({requestId:H.z.uuid(),customerId:H.z.uuid(),connectionId:H.z.uuid().optional(),message:zc,expiresAt:H.z.iso.datetime({offset:!0})}),Ph=H.z.array(H.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),Ch=H.z.discriminatedUnion("kind",[H.z.strictObject({kind:H.z.literal("all")}),H.z.strictObject({kind:H.z.literal("customers"),customerIds:Ph})]),P0=H.z.strictObject({name:H.z.string().trim().min(1).max(120),connectionId:H.z.uuid().optional(),message:zc,audience:Ch,frequencyLimit:H.z.number().int().min(1).max(100)}),tu=H.z.strictObject({requestId:H.z.uuid(),channel:Gr,state:H.z.enum(["allowed","denied"]),expectedRevision:H.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),ru=H.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),nu=H.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),C0=H.z.strictObject({meter:bh,estimatedUnits:H.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:H.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var ee=require("zod");var Y=require("zod");var ve=require("zod");var ou=require("zod");var Jt=require("zod"),iu=Jt.z.enum(["stripe","apple","google"]),au=Jt.z.enum(["membership","credit_pack","lifetime"]),w0=Jt.z.enum(["active","grace","suspended","inactive","revoked"]),E0=Jt.z.strictObject({currency:Jt.z.string().regex(/^[A-Z]{3}$/),micros:Jt.z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var hr=ou.z.object({provider:iu,currency:Q}).strict();var Mt=ve.z.strictObject({internal_feature_id:ve.z.uuid(),quantity:Z.refine(e=>/[1-9]/.test(e)),properties:Ue,entityId:ve.z.uuid().optional()}),su=ve.z.strictObject({requirement:Mt,commerce:hr.optional(),paywallId:ve.z.uuid().optional()}),Oh=ve.z.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),ha=ve.z.strictObject({productId:ve.z.string().min(1),productVersionId:ve.z.string().min(1),name:ve.z.string().min(1).max(120),action:ve.z.enum(["purchase","upgrade","addon","topup"]),membershipId:ve.z.string().min(1).nullable(),currency:Q,amountMinor:ve.z.string().regex(/^(0|[1-9]\d{0,8})$/),interval:ve.z.enum(["free","week","month","year","one_time"]),intervalCount:ve.z.number().int().min(1).max(156)}),Xt=ve.z.strictObject({internal_feature_id:ve.z.string().min(1),name:ve.z.string().min(1).max(120),kind:ve.z.enum(["access","metered","credit"]),quantity:Z,allowed:ve.z.boolean(),reason:Oh.nullable(),preview:ve.z.strictObject({scenario:ve.z.enum(["feature_flag","usage_limit"]),candidates:ve.z.array(ha).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(r=>r.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),U0=ve.z.strictObject({paywallId:ve.z.uuid(),requirement:Mt});var Aa=Y.z.object({plan:Y.z.string().min(1).max(200).optional(),coupon:Y.z.uuid().optional(),promotionCode:Y.z.uuid().optional(),picker:Y.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),qn=Y.z.object({text:Y.z.string().optional(),label:Y.z.string().optional(),alt:Y.z.string().optional(),html:Y.z.string().max(32768).optional(),price:Y.z.object({current:Y.z.string(),original:Y.z.string().nullable(),period:Y.z.string()}).optional(),code:Y.z.string().optional(),countdownAt:Y.z.iso.datetime().optional(),planId:Y.z.string().min(1).max(200).optional(),planVersionId:Y.z.string().min(1).max(200).optional(),currency:Q.optional(),couponId:Y.z.uuid().optional(),offerId:Y.z.uuid().optional(),unavailable:Y.z.boolean().optional(),unavailableReason:Y.z.string().optional(),missing:Y.z.array(Y.z.string()).optional()}).strict(),Ln=Y.z.object({paywall:Xt.optional(),nodes:Y.z.record(Y.z.string(),Y.z.object({base:qn,picker:Y.z.string().optional(),byPlan:Y.z.record(Y.z.string(),qn).optional()}).strict()),plans:Y.z.record(Y.z.string(),Y.z.object({id:Y.z.string().min(1).max(200),versionId:Y.z.string().min(1).max(200),available:Y.z.boolean(),name:Y.z.string(),price:Y.z.string(),period:Y.z.string(),currency:Q.optional()}).strict()),pickers:Y.z.record(Y.z.string(),Y.z.object({options:Y.z.array(Y.z.string().min(1).max(200)).max(20),selected:Y.z.string().min(1).max(200).nullable()}).strict()),diagnostics:Y.z.array(Y.z.object({nodeId:Y.z.string(),message:Y.z.string()}).strict())}).strict();function cu(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var m=require("zod");function wh(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function uu(e){let t={};function r(n){var i;if(wh(n)){let o=t[i=n.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let c of n.children){let d=c.type==="stack"?c.bind?.plan:void 0;d&&!o.ids.includes(d)&&o.ids.push(d)}let a=n.children[n.interaction.defaultIndex];!o.defaultId&&a?.type==="stack"&&(o.defaultId=a.bind?.plan??null)}n.type==="stack"&&n.children.forEach(r)}return e.pages.forEach(n=>r(n.root)),t}var xt=require("zod"),lu=xt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Bn=xt.z.strictObject({tiers:xt.z.array(xt.z.strictObject({id:lu,name:xt.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:xt.z.array(xt.z.strictObject({productVersionId:xt.z.string().min(1).max(200),tierId:lu,period:xt.z.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let r=e.tiers.map(n=>n.id);(new Set(r).size!==r.length||new Set(e.assignments.map(n=>n.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(n=>`${n.tierId}:${n.period}`)).size!==e.assignments.length||e.assignments.some(n=>!r.includes(n.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Vn(e,t){return e.assignments.length===t.length&&e.assignments.every(r=>t.includes(r.productVersionId))}var V=require("zod");var Eh=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],du=V.z.enum(Eh),mu=V.z.object({source:du,layout:V.z.enum(["full","compact"]),resourceKey:Gt.optional(),pageSize:V.z.number().int().min(1).max(50),showSources:V.z.boolean(),allowPurchase:V.z.boolean(),outputs:V.z.object({billing_adjustment:V.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:V.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:V.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:V.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:V.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:V.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"})}),Be=V.z.string().max(2e3),pu=V.z.object({id:V.z.string().max(100),label:Be,detail:V.z.array(Be).max(12),value:Be.optional(),status:Be.optional(),facts:V.z.array(V.z.object({label:Be,value:Be}).strict()).max(1e3),purchaseId:V.z.uuid().optional(),invoiceUrl:V.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:V.z.array(V.z.strictObject({action:V.z.literal("invoice_open"),label:Be})).max(1).optional(),membershipActions:V.z.array(V.z.object({value:V.z.string().max(100),label:Be}).strict()).max(3).optional()}).strict(),jh=V.z.object({key:Gt,name:Be,spendable:Be,reserved:Be,available:Be,expiry:Be.nullable(),sources:V.z.array(pu).max(50),sourceCount:V.z.number().int().nonnegative(),sourcePage:V.z.number().int().positive(),hasNextSources:V.z.boolean(),hasPreviousSources:V.z.boolean()}).strict(),Rh=V.z.object({source:du,status:V.z.enum(["idle","loading","ready","error"]),stale:V.z.boolean(),preview:V.z.boolean(),errorCode:V.z.string().max(80).optional(),errorMessage:Be.optional(),resources:V.z.array(jh).max(500),rows:V.z.array(pu).max(50),hasNext:V.z.boolean(),hasPrevious:V.z.boolean(),page:V.z.number().int().positive(),filter:V.z.string().max(40),updatedAt:V.z.iso.datetime().optional(),buyingId:V.z.uuid().optional(),membershipBusy:V.z.boolean().optional(),billingBusy:V.z.boolean().optional(),membershipReview:V.z.object({title:Be,note:Be,facts:V.z.array(V.z.object({label:Be,value:Be}).strict()).max(100)}).strict().optional(),membershipResult:Be.optional()}).strict(),H0=V.z.object({nodes:V.z.record(V.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Rh)}).strict(),K0=V.z.object({nodeId:V.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:V.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:V.z.string().max(100).optional()}).strict();var kh=4,ht={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Kr=m.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),pe=m.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Dh=m.z.enum(["none","xs","sm","md","lg","xl"]),Nh=m.z.enum(["none","sm","md","lg","full"]),ga=m.z.string().regex(/^#[0-9a-fA-F]{6}$/),Au=m.z.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"),ba=m.z.union([Au,m.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),m.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),m.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),fu=m.z.object({primary:ga,background:ga,text:ga,radius:Nh,font:m.z.enum(["system","serif","rounded","mono"])}).strict(),Zr=m.z.union([m.z.enum(["primary","text","muted","background","surface"]),m.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),he=(e,t)=>m.z.number().int().min(e).max(t),hu=m.z.union([m.z.enum(["fit","fill"]),he(1,1200)]),Mh=m.z.object({top:he(0,200),right:he(0,200),bottom:he(0,200),left:he(0,200)}).strict(),Uh=m.z.object({top:he(-100,200),right:he(-100,200),bottom:he(-100,200),left:he(-100,200)}).strict(),gu=m.z.object({x:he(0,100),y:he(0,100)}).strict(),qh=m.z.discriminatedUnion("type",[m.z.object({type:m.z.literal("color"),color:Zr}).strict(),m.z.object({type:m.z.literal("linear"),angle:he(0,360),stops:m.z.array(m.z.object({color:Zr,at:he(0,100)}).strict()).min(2).max(4)}).strict(),m.z.object({type:m.z.literal("image"),src:ba,fit:m.z.enum(["cover","contain"]),position:gu.optional()}).strict()]),Lh=m.z.discriminatedUnion("type",[m.z.object({type:m.z.literal("rect"),radius:m.z.union([he(0,200),m.z.object({topLeft:he(0,200),topRight:he(0,200),bottomRight:he(0,200),bottomLeft:he(0,200)}).strict()])}).strict(),m.z.object({type:m.z.literal("pill")}).strict()]),Bh=m.z.object({width:he(0,12),color:Zr,style:m.z.enum(["solid","dashed"])}).strict(),Vh=m.z.object({x:he(-40,40),y:he(-40,40),blur:he(0,80),spread:he(-20,40),color:Zr}).strict(),Fh=m.z.object({font:m.z.enum(["system","serif","rounded","mono"]),size:he(8,96),weight:m.z.number().int().min(100).max(900).multipleOf(100),lineHeight:m.z.number().min(.8).max(3),letterSpacing:m.z.number().min(-5).max(20),color:Zr,align:m.z.enum(["start","center","end"]),italic:m.z.boolean(),decoration:m.z.enum(["none","underline","line-through"]),transform:m.z.enum(["none","uppercase"])}).strict().partial(),zt=m.z.object({width:hu,height:hu,padding:Mh,margin:Uh,gap:he(0,120),grow:m.z.union([m.z.boolean(),m.z.number().min(0).max(12)]),background:qh,opacity:m.z.number().min(0).max(1),clipContent:m.z.boolean(),shape:Lh,border:Bh,shadow:Vh,text:Fh}).strict().partial(),nt={id:Kr,name:m.z.string().trim().min(1).max(60).optional(),hidden:m.z.boolean().optional(),style:zt.optional(),fallback:pe.optional()},$h=m.z.object({...nt,type:m.z.literal("text"),productField:m.z.enum(["name","price","trial","period"]).optional(),feature:m.z.object({id:m.z.uuid(),field:m.z.enum(["name","allowance"])}).strict().optional(),text:pe,variant:m.z.enum(["title","heading","body","caption"])}).strict(),Gh=m.z.object({...nt,type:m.z.literal("image"),src:ba,localizedSrc:m.z.record(mt,ba).optional(),alt:pe,aspect:m.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:m.z.enum(["cover","contain"]),position:gu.optional()}).strict(),Hh=m.z.object({...nt,type:m.z.literal("button"),label:pe,variant:m.z.enum(["primary","secondary","link"]),action:pe,purpose:m.z.enum(["purchase","navigation","close"]).optional(),bind:Aa.optional()}).strict(),Kh=m.z.object({...nt,type:m.z.literal("divider")}).strict(),Zh=m.z.object({...nt,type:m.z.literal("customer_data"),title:pe,data:mu}).strict(),Wh=m.z.object({...nt,type:m.z.literal("spacer"),size:Dh}).strict(),Qh=m.z.object({...nt,type:m.z.literal("custom_html"),html:m.z.record(mt,m.z.string().max(ht.customHtml)),css:m.z.string().max(ht.customCss)}).strict(),Yh=m.z.object({...nt,type:m.z.literal("price"),fallback:pe,parts:m.z.object({current:zt.optional(),original:zt.optional(),period:zt.optional()}).strict().optional()}).strict(),Jh=m.z.object({...nt,type:m.z.literal("coupon_code"),label:pe,fallback:pe}).strict(),Xh=m.z.object({...nt,type:m.z.literal("countdown"),source:m.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:m.z.iso.datetime().optional(),granularity:m.z.enum(["day","hour","minute","second"]),expired:pe,fallback:pe}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),zh=m.z.object({...nt,type:m.z.literal("plan_picker"),label:pe,fallback:pe,planIds:m.z.array(m.z.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:m.z.string().min(1).max(200).optional(),grouping:Bn.safeExtend({monthLabel:pe,yearLabel:pe,unavailableLabel:pe}).optional(),states:m.z.object({selected:zt.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Vn(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),eA=m.z.discriminatedUnion("type",[m.z.object({type:m.z.literal("input"),label:pe,keyboard:m.z.enum(["text","email","tel","url"]),maxLength:he(1,500)}).strict(),m.z.object({type:m.z.literal("multiselect"),label:pe,min:he(0,50),max:he(1,50)}).strict(),m.z.object({type:m.z.literal("select"),label:pe,defaultIndex:he(0,49),purpose:m.z.enum(["option","product","tier"]).optional(),pickerId:Kr.optional(),selectedStyle:zt.optional()}).strict(),m.z.object({type:m.z.literal("tabs"),label:pe,defaultIndex:he(0,49),purpose:m.z.literal("tier").optional()}).strict(),m.z.object({type:m.z.literal("toggle"),label:pe,defaultEnabled:m.z.boolean()}).strict(),m.z.object({type:m.z.literal("carousel"),label:pe}).strict()]),ft={...nt,type:m.z.literal("stack"),direction:m.z.enum(["vertical","horizontal","overlay"]),align:m.z.enum(["start","center","end","stretch"]),justify:m.z.enum(["start","center","end","between"]),productSlot:m.z.object({index:he(0,19),period:m.z.enum(["month","year"]).optional(),requireBinding:m.z.boolean().optional()}).strict().optional(),interaction:eA.optional(),states:m.z.object({selected:zt.optional()}).strict().optional(),purpose:m.z.literal("benefits").optional(),purchaseAction:pe.optional(),buttonVariant:m.z.enum(["primary","secondary","link"]).optional(),bind:Aa.optional()},bu=m.z.lazy(()=>m.z.object({...nt,type:ft.type,direction:ft.direction,align:ft.align,justify:ft.justify,children:m.z.array(tA).max(ht.children),productSlot:ft.productSlot,interaction:ft.interaction,states:ft.states,purpose:ft.purpose,purchaseAction:ft.purchaseAction,buttonVariant:ft.buttonVariant,bind:ft.bind}).strict()),tA=m.z.lazy(()=>m.z.union([bu,$h,Gh,Hh,Kh,Wh,Qh,Yh,Jh,Xh,zh,Zh])),rA=m.z.union([m.z.string().max(500),m.z.number().finite(),m.z.boolean(),m.z.null()]),Hr={id:pe,event:pe,properties:m.z.record(pe,rA).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},nA=m.z.discriminatedUnion("type",[m.z.object({...Hr,type:m.z.literal("navigate"),close:m.z.literal(!1),pageId:Kr}).strict(),m.z.object({...Hr,type:m.z.literal("event"),close:m.z.boolean()}).strict(),m.z.object({...Hr,type:m.z.literal("close"),close:m.z.literal(!0)}).strict(),m.z.object({...Hr,type:m.z.literal("open_url"),close:m.z.boolean(),url:Au}).strict(),m.z.object({...Hr,type:m.z.literal("claim_offer"),close:m.z.boolean(),couponId:m.z.uuid()}).strict()]),iA=m.z.object({defaultLocale:mt,locales:m.z.record(mt,m.z.record(pe,m.z.string().max(ht.stringLength)))}).strict(),aA=m.z.enum(["popup","paywall","onboarding","page","banner"]);var oA=m.z.discriminatedUnion("type",[m.z.object({type:m.z.literal("modal"),size:m.z.enum(["sm","md","lg"])}).strict(),m.z.object({type:m.z.literal("sheet"),size:m.z.enum(["sm","md","lg"])}).strict(),m.z.object({type:m.z.literal("fullscreen")}).strict(),m.z.object({type:m.z.literal("inline")}).strict()]);var sA=m.z.object({kind:m.z.literal("screen"),schemaVersion:m.z.literal(kh),name:m.z.string().trim().min(1).max(80),surface:aA,initialPageId:Kr.optional(),presentation:oA,theme:fu,pages:m.z.array(m.z.object({id:Kr,name:m.z.string().trim().min(1).max(60),root:bu,theme:fu.optional(),editorPosition:m.z.object({x:m.z.number().finite().min(-1e5).max(1e5),y:m.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(ht.pages),strings:iA,actions:m.z.array(nA).max(ht.actions)}).strict();function ot(e,t){for(let r of e.pages)Wr(r.root,t)}var er=sA.superRefine((e,t)=>{let r=ht;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(y=>y.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let y of e.actions)y.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(j=>j.id===y.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>r.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${r.pages} \u4E2A`}),e.actions.length>r.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${r.actions} \u4E2A`});let n=y=>t.addIssue({code:"custom",message:y}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||n("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>ht.locales&&n(`\u6700\u591A ${ht.locales} \u79CD\u8BED\u8A00`);let o=new Set;for(let y of e.actions)o.has(y.id)&&n(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${y.id}`),o.add(y.id);let a=new Set;for(let y of e.pages)["next","back"].includes(y.id)&&n(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${y.id}`),a.has(y.id)&&n(`\u9875\u9762 id \u91CD\u590D\uFF1A${y.id}`),a.add(y.id);let c=new Set,d=0,p=!1;ot(e,(y,j)=>{if(d++,j>ht.depth&&(p=!0),c.has(y.id)&&n(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${y.id}`),c.add(y.id),y.type==="button"&&!o.has(y.action)&&n(`\u6309\u94AE ${y.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${y.action}`),y.type==="custom_html")for(let $ of Object.keys(y.html))i.includes($)||n(`\u81EA\u5B9A\u4E49 HTML ${y.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${$}`);if(y.type==="image")for(let $ of Object.keys(y.localizedSrc??{}))i.includes($)||n(`\u56FE\u7247 ${y.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${$}`)}),d>r.nodes&&n(`\u7EC4\u4EF6\u6700\u591A ${r.nodes} \u4E2A`),p&&n(`\u5C42\u7EA7\u6700\u591A ${ht.depth} \u5C42`)});function Wr(e,t,r=1,n=null){if(t(e,r,n)!==!1&&e.type==="stack")for(let i of e.children)Wr(i,t,r+1,e)}function ya(e){let t=[],r=new Set;return ot(e,n=>{let i=(o,a,c)=>{r.has(o)||(r.add(o),t.push({key:o,nodeId:n.id,nodeType:n.type,field:a,required:c}))};n.type==="stack"&&n.interaction&&i(n.interaction.label,"label",!0),n.fallback&&i(n.fallback,"text",!0),n.type==="text"&&i(n.text,"text",!0),n.type==="customer_data"&&i(n.title,"title",!0),(n.type==="plan_picker"||n.type==="coupon_code")&&i(n.label,"label",!0),n.type==="plan_picker"&&n.grouping&&(i(n.grouping.monthLabel,"label",!0),i(n.grouping.yearLabel,"label",!0),i(n.grouping.unavailableLabel,"text",!0)),n.type==="countdown"&&i(n.expired,"text",!0),n.type==="button"&&i(n.label,"label",!0),n.type==="image"&&(i(`image:${n.id}`,"src",!1),i(n.alt,"alt",!1)),n.type==="custom_html"&&i(`html:${n.id}`,"html",!0)}),t}function cA(e,t,r){if(t.field==="html"){let n;return ot(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(n=i.html[r])}),n}if(t.field==="src"){let n=lA(e,t.nodeId);return n?.type==="image"?n.localizedSrc?.[r]??(r===e.strings.defaultLocale?n.src:void 0):void 0}return e.strings.locales[r]?.[t.key]}function Ar(e){let t=ya(e).filter(n=>n.required);return Object.keys(e.strings.locales).sort((n,i)=>n===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(n=>{let i=t.filter(o=>!cA(e,o,n)?.trim()).map(o=>o.key);return{locale:n,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function uA(e,t){let r=null;return Wr(e,n=>{if(r)return!1;n.id===t&&(r=n)}),r}function lA(e,t){for(let r of e.pages){let n=uA(r.root,t);if(n)return n}return null}function dA(e){let t=Object.values(e.strings.locales).flatMap(r=>Object.values(r));return ot(e,r=>{r.type==="custom_html"&&t.push(...Object.values(r.html))}),[...new Set(t.flatMap(cu))]}function yu(e){return dA(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function Su(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let r=new TextEncoder().encode(t).length,n=!1;for(let i=0;i<t.length;i++){let o=t.charAt(i);if(n)o==="\\"?i++:o==='"'&&(n=!1);else if(o==='"')n=!0;else if(o===":"||o===",")r++;else if(o==="-"||o>="0"&&o<="9"){let a=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let c=t.slice(a,i+1);if(!/[eE]/.test(c))continue;let[d="",p]=c.split(/[eE]/),y=d.replace(/^-/,""),j=y.replace(".","").length,$=(y.includes(".")?y.indexOf("."):j)+Number(p),ie=$<=0?2-$+j:$>=j?$:j+1;r+=ie+(d.startsWith("-")?1:0)-c.length}}return r}var Ut=ee.z.enum(["page","popup","banner"]),mA=3e5,_u=ee.z.strictObject({type:ee.z.enum(["string","number","boolean","strings","json"]),nullable:ee.z.boolean()}),pA=ee.z.strictObject({inputs:ee.z.record(pe,_u.extend({required:ee.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:ee.z.record(pe,_u).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),fA=ee.z.strictObject({kind:Ut,schemaVersion:ee.z.literal(1),name:ee.z.string().trim().min(1).max(80),screen:er,contract:pA}),Fn=fA.superRefine((e,t)=>{let r=(i,o)=>t.addIssue({code:"custom",message:i,path:o});e.screen.surface!==e.kind&&r("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&r("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&r("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&r("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&r("Content actions must emit host intents or navigate locally",["screen","actions"]);let n=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!n.has(i))||[...n].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&r("Every event needs exactly one output declaration",["contract","outputs"]),Su(e)>mA&&r("Content document exceeds its byte budget",[])});function hA(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(r=>typeof r=="string")}}var AA=Fn.superRefine((e,t)=>{for(let r of yu(e.screen))Object.keys(e.contract.inputs).some(n=>r===n||r.startsWith(n+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let r of e.screen.actions){if(r.type!=="event")continue;let n=e.contract.outputs[r.id],i=Object.hasOwn(r.properties,"value")?r.properties.value:r.properties;n&&!hA(i,n)&&t.addIssue({code:"custom",path:["contract","outputs",r.id],message:"Action value differs from its declared type"})}Ar(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),xu=ee.z.strictObject({id:ee.z.uuid(),kind:Ut,projectId:ee.z.uuid(),environmentId:ee.z.uuid(),name:ee.z.string(),revision:ee.z.number().int().nonnegative(),status:ee.z.enum(["draft","published","archived"]),publishedVersionId:ee.z.uuid().nullable(),createdAt:ee.z.iso.datetime({offset:!0}),updatedAt:ee.z.iso.datetime({offset:!0})}),c_=xu.extend({draft:Fn}),u_=ee.z.strictObject({rows:ee.z.array(xu).max(200),nextCursor:ee.z.uuid().nullable()}),Sa=ee.z.strictObject({id:ee.z.uuid(),kind:Ut,resourceId:ee.z.uuid(),projectId:ee.z.uuid(),environmentId:ee.z.uuid(),version:ee.z.number().int().positive(),sourceRevision:ee.z.number().int().nonnegative(),document:AA,createdAt:ee.z.iso.datetime({offset:!0})}),l_=Sa.omit({document:!0}),d_=ee.z.discriminatedUnion("action",[ee.z.strictObject({action:ee.z.literal("create"),kind:Ut,id:ee.z.uuid(),document:Fn}),ee.z.strictObject({action:ee.z.literal("save"),kind:Ut,id:ee.z.uuid(),revision:ee.z.number().int().nonnegative(),document:Fn}),ee.z.strictObject({action:ee.z.enum(["publish","archive"]),kind:Ut,id:ee.z.uuid(),revision:ee.z.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});var _a=require("zod"),gr={funnelId:_a.z.uuid().optional(),funnelVersionId:_a.z.uuid().optional()};var Ie=require("zod");var le=require("zod");var Se=require("zod"),f_=Se.z.discriminatedUnion("action",[Se.z.strictObject({action:Se.z.literal("create"),couponId:Se.z.uuid(),productBindingId:Se.z.uuid(),storeOfferId:Se.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Se.z.enum(["introductory","promotional"])}),Se.z.strictObject({action:Se.z.literal("set_enabled"),id:Se.z.uuid(),revision:Se.z.number().int().nonnegative(),enabled:Se.z.boolean()})]),h_=Se.z.array(Se.z.strictObject({id:Se.z.uuid(),couponId:Se.z.uuid(),productBindingId:Se.z.uuid(),storeOfferId:Se.z.string().min(1).max(255).nullable(),storeOfferType:Se.z.enum(["introductory","promotional"]),enabled:Se.z.boolean(),revision:Se.z.number().int().nonnegative()})).max(500),$n=Se.z.strictObject({offerKind:Se.z.enum(["none","introductory","promotional"]),offerId:Se.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Se.z.number().int().min(0).max(1e8),trialDays:Se.z.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"})}),A_=Se.z.record(Se.z.uuid(),$n).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var xa=le.z.object({type:le.z.literal("native_purchase"),receiptId:le.z.uuid(),orderId:le.z.uuid(),productVersionId:le.z.uuid(),provider:le.z.enum(["apple","google"]),productId:le.z.string().min(1).max(255),productKind:au,replacement:le.z.strictObject({sourceOrderId:le.z.uuid(),sourceProductId:le.z.string().min(1).max(255),policy:le.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:le.z.array(le.z.uuid()).max(50)}).nullable(),appAccountToken:le.z.uuid().optional(),obfuscatedAccountId:le.z.string().min(1).max(64).optional(),obfuscatedProfileId:le.z.uuid().optional(),basePlanId:le.z.string().min(1).max(255).optional(),offerId:le.z.string().min(1).max(255).optional(),offerKind:le.z.enum(["none","introductory","promotional"]),currency:Q,catalogAmountMinor:le.z.number().int().nonnegative().max(1e8),discountMinor:le.z.number().int().nonnegative().max(1e8),trialDays:le.z.number().int().min(1).max(730).nullable(),seatBundle:le.z.array(le.z.strictObject({key:le.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:le.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:le.z.strictObject({offerId:le.z.string().min(1).max(255),keyId:le.z.string().min(1).max(255),nonce:le.z.uuid(),signature:le.z.string().min(1).max(1024),timestamp:le.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let r=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(r?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!r&&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||(r?!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"})});var s=require("zod");var re=require("zod/v4"),Iu=require("zod/v4"),gA=Iu.z.registry(),{BillingInterval:vu}=(()=>{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:bA}=(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')."})})}))(re.z),{withSpecDefault:yA}=(e=>({withSpecDefault:({schema:r,defaultValue:n,description:i})=>(e.add(r,{description:i,default:n}),r)}))(gA),{COMMON:Pu}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:SA}={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:_A}=(e=>({COMMON_SET:new Set(e)}))(Pu),{hasNoDuplicateCurrencies:Cu}={hasNoDuplicateCurrencies:t=>{let r=new Set;for(let{currency:n}of t){let i=n.toLowerCase();if(r.has(i))return!1;r.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:Ou}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:xA}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(re.z),{Infinite:IA}={Infinite:"inf"},{TierBehavior:vA}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:wu}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:PA}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:CA}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:OA}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:wA}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(re.z),{ApiCreditTierSchema:Eu}=(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."})})}))(re.z),{VIOLATION_MESSAGES:EA}={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:ju}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(re.z),{ModelMarkupsSchema:jA}=((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()}))(re.z,ju),{InvoiceUsageEntrySchema:RA}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(re.z),{AttachDiscountSchema:Ru}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(r=>r.reward_id||r.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(re.z),{CustomLineItemSchema:TA}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(re.z),{UnixMsTimestampSchema:kA}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(re.z),{CreateInvoicePreviewLineSchema:DA}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(re.z),{ReissueInvoiceParamsSchema:Ia}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(re.z),{InvoiceModeParamsSchema:tr}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(re.z),{InvoiceTemplateSchema:NA}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(re.z),{BasePriceSchema:MA}=((e,t,r)=>({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:r.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(re.z,vu,bA),{CURRENCY_CODES:UA}=((e,t,r)=>({CURRENCY_CODES:[...e,...t.filter(i=>!r.has(i)).sort()]}))(Pu,SA,_A),{ApiPriceProcessorsSchema:Tu}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(re.z,xA),{AllocatedBillingFieldSchema:qA}=((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'."})}))(re.z,PA),{CreditDimensionNameSchema:LA}=((e,t,r)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(r),{message:`Dimension names cannot contain "${r}"`})}))(re.z,CA,OA),{ApiCreditMatchSchema:ku}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(wA),{findCreditTierViolations:BA}=(e=>({findCreditTierViolations:r=>{let n=[],i=(a,c)=>n.push({index:a,reason:c,message:e[c]}),o=0;for(let[a,c]of r.entries()){let d=a===r.length-1;if(c==="inf"){d||i(a,"non_final_infinity");continue}(!Number.isFinite(c)||c<=o)&&i(a,"not_increasing"),o=c,d&&i(a,"final_not_infinity")}return n}}))(EA),{ApiCreditMultiplierSchema:VA}=((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(n=>n.factor!==void 0||n.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(re.z,ku),{ProviderMarkupsSchema:FA}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(re.z,ju),{InvoiceFeatureQuantitySchema:Du}=((e,t,r)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(r).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(re.z,wu,RA),{CreateInvoicePreviewSchema:va}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(re.z,DA),{SUPPORTED_SET:$A}=(e=>({SUPPORTED_SET:new Set(e)}))(UA),{ApiCreditDimensionBaseSchema:GA}=((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."})})}))(re.z,ku),{refineGraduatedTiers:Nu}=(e=>({refineGraduatedTiers:(r,n)=>{let i=e(r.tiers.map(o=>o.to));for(let{index:o,message:a}of i)n.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(BA),{ApiFeatureMarkupsOverrideSchema:HA}=((e,t,r)=>({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:r.meta({description:"Per-model markup overrides for customers on this plan."})})}))(re.z,FA,jA),{isValidCurrencyCode:KA}=(e=>({isValidCurrencyCode:r=>!!r&&e.has(r.toLowerCase())}))($A),{ApiCreditDimensionSchema:ZA}=((e,t,r,n)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(r).min(1)}).strict().superRefine(n),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(re.z,GA,Eu,Nu),{CurrencyCodeSchema:Mu}=((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')."})}))(re.z,KA),{AdditionalCurrencyTierSchema:WA}=((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(n=>n.amount!==void 0||n.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(re.z,Mu),{ApiCreditSchemaItemBaseSchema:Uu}=((e,t,r,n)=>({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,r).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,n).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(re.z,LA,ZA,VA),{ApiFlatCreditSchemaItemSchema:QA}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Uu,re.z),{AdditionalCurrencyPriceSchema:YA}=((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."})})}))(re.z,Mu),{AdditionalCurrencyTierArraySchema:JA}=((e,t,r,n)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(r,{message:n})}))(re.z,WA,Cu,Ou),{ApiGraduatedCreditSchemaItemSchema:XA}=((e,t,r,n)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(r).min(1)}).strict().superRefine(n)}))(Uu,re.z,Eu,Nu),{AdditionalCurrencyPriceArraySchema:qu}=((e,t,r,n)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(r,{message:n})}))(re.z,YA,Cu,Ou),{ApiUsageTierWithCurrenciesSchema:zA}=((e,t,r)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:r.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:r.optional()}))}))(re.z,IA,JA),{ApiCreditSchemaItemSchema:eg}=((e,t,r)=>({ApiCreditSchemaItemSchema:e.union([t,r])}))(re.z,XA,QA),{BasePriceParamsSchema:tg}=((e,t,r,n)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:r.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:n.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:r.string().optional().meta({internal:!0}),entitlement_id:r.string().optional().meta({internal:!0}),price_id:r.string().optional().meta({internal:!0}),stripe_price_id:r.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."})}))(MA,yA,re.z,qu),{PlanItemPriceParamsSchema:rg}=((e,t,r,n,i,o,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(d=>d??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(r).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(n).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."})})}))(re.z,qu,zA,vA,vu,wu,qA),{ApiFeatureOverrideSchema:ng}=((e,t,r)=>({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:r.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."})})}))(re.z,eg,HA),{InvoiceBasePriceParamsSchema:Lu}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(tg,Tu),{InvoiceItemPriceParamsSchema:ig}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(rg,Tu),{InvoiceLicenseQuantitySchema:ag}=((e,t,r)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(r).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(re.z,Lu,Du),{InvoiceCustomizeItemSchema:og}=((e,t,r)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:r.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(re.z,ig,ng),{InvoiceCustomizeSchema:sg}=((e,t,r)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(r).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(re.z,Lu,og),{InvoicePlanParamsSchema:cg}=((e,t,r,n,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(r).optional(),license_quantities:e.array(n).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(re.z,sg,Du,ag,Ru),{CreateInvoiceParamsSchema:br}=((e,t,r,n,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(r).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(n).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(a=>a.period_start===void 0==(a.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(a=>a.period_start===void 0||a.period_end===void 0||a.period_end>a.period_start,{message:"period_end must be after period_start."})}))(re.z,cg,TA,Ru,kA);var Fu=s.z.strictObject({requestId:s.z.uuid(),predecessorOperationId:s.z.uuid().optional(),invoiceMode:tr.optional(),entityId:s.z.uuid().optional(),billingSubscriptionId:s.z.uuid().optional(),newBillingSubscription:s.z.literal(!0).optional(),offerId:s.z.uuid().optional(),nativeOffer:$n.optional(),plans:s.z.array(s.z.strictObject({productVersionId:s.z.uuid(),seatQuantities:s.z.record(yt,s.z.number().int().min(0).max(1e4)).optional(),featureQuantities:s.z.record(s.z.uuid(),s.z.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:s.z.enum(["stripe","apple","google"]),currency:Q}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(e.provider==="stripe"||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||e.provider!=="stripe"&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||e.provider==="stripe"&&!e.billingSubscriptionId,"A new billing subscription requires Stripe and no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),nr=s.z.strictObject({operationId:s.z.uuid()}),$e=s.z.number().int().min(0).max(1e8),ug=s.z.strictObject({lineId:s.z.uuid(),productVersionId:s.z.uuid(),productName:s.z.string().min(1).max(80),interval:s.z.enum(["free","week","month","year","one_time"]),intervalCount:s.z.number().int().min(1).max(156).optional(),baseAmountMinor:$e,seats:s.z.array(s.z.strictObject({key:yt,quantity:s.z.number().int().min(0).max(1e4),includedQuantity:s.z.number().int().min(0).max(1e4),maximumQuantity:s.z.number().int().min(0).max(1e4),unitAmountMinor:$e})).max(20),prepaid:s.z.array(Tc).max(100).optional(),catalogAmountMinor:$e,trial:s.z.strictObject({days:s.z.number().int().min(1).max(730),cardRequired:s.z.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,r)=>t+r.unitAmountMinor*(r.quantity-r.includedQuantity),0)+(e.prepaid??[]).reduce((t,r)=>t+Tn({quantity:r.quantity,unitAmountMinor:r.unitAmountMinor,...r.pricing===void 0?{}:{pricing:r.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),$u=s.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),lg=s.z.strictObject({id:$u,name:s.z.string().min(1).max(40),percent_off:s.z.number().gt(0).max(100).optional(),amount_off:s.z.number().int().positive().optional(),currency:s.z.string().regex(/^[a-z]{3}$/).optional(),duration:s.z.enum(["once","repeating","forever"]),duration_in_months:s.z.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"),dg=s.z.strictObject({subscriptionId:s.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:s.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:s.z.array(s.z.strictObject({id:s.z.string(),price_id:s.z.string(),quantity:s.z.number().int().nonnegative(),discounts:s.z.array(s.z.strictObject({id:s.z.string(),coupon:s.z.string(),start:s.z.number(),end:s.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:s.z.number().int().nonnegative(),amountMinor:s.z.number().int().positive(),periodStartMs:s.z.number(),periodEndMs:s.z.number()}),Gu=s.z.strictObject({invoiceMode:tr.optional(),append:dg.optional(),provider:s.z.literal("stripe"),executor:s.z.enum(["indiana","merchant"]),accountId:s.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:s.z.enum(["payment","subscription"]),lineItems:s.z.array(s.z.strictObject({price:s.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:s.z.number().int().min(1).max(1e4),priceId:s.z.uuid(),productName:s.z.string().min(1).max(80),amountMinor:s.z.number().int().min(0).max(1e8),currency:s.z.string().regex(/^[a-z]{3}$/),interval:s.z.enum(["week","month","year","one_off"]),intervalCount:s.z.number().int().min(1).max(52),slot:s.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:s.z.strictObject({mode:s.z.enum(["graduated","volume"]),tiers:s.z.array(s.z.strictObject({upTo:s.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:s.z.number().int().min(0).max(1e8),flatAmountMinor:s.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:s.z.array(s.z.strictObject({coupon:$u,terms:lg})).max(1),trialPeriodDays:s.z.number().int().min(1).max(730).nullable(),metadata:s.z.strictObject({grooveCheckoutId:s.z.uuid(),grooveCustomerId:s.z.uuid()}),expiresAt:s.z.iso.datetime({offset:!0})}),Hu=s.z.strictObject({operationId:s.z.uuid(),entityId:s.z.uuid().nullable(),billingSubscriptionId:s.z.uuid().nullable(),discount:s.z.strictObject({offerId:s.z.uuid(),couponId:s.z.uuid(),discount:Dt,duration:tt,amountMinor:$e,allocations:s.z.array(s.z.strictObject({productVersionId:s.z.uuid(),amountMinor:$e})).min(1).max(20),expiresAt:s.z.iso.datetime({offset:!0})}).nullable(),charge:s.z.strictObject({effectiveAt:s.z.iso.datetime({offset:!0}),periodEndsAt:s.z.iso.datetime({offset:!0}),debitMinor:$e,discountMinor:$e,taxMinor:$e,totalMinor:$e}).nullable(),expiresAt:s.z.iso.datetime({offset:!0}),provider:s.z.enum(["stripe","apple","google"]),nativeOffer:$n.optional(),currency:Q,lines:s.z.array(ug).min(1).max(20),catalogAmountMinor:$e,automaticTax:s.z.boolean(),execution:Gu.nullable()}).refine(e=>e.provider==="stripe"?e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once")):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(e.provider==="stripe"||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,r)=>{let n=e.lines[r];return n!==void 0&&t.productVersionId===n.productVersionId&&t.amountMinor<=n.catalogAmountMinor})&&e.discount.allocations.reduce((t,r)=>t+r.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,r)=>t+r.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),Pa=s.z.strictObject({operationId:s.z.uuid(),orderId:s.z.uuid(),append:s.z.boolean().optional(),invoiceMode:s.z.boolean().optional(),status:s.z.enum(["pending","complete","cancelled","failed"]),executor:s.z.enum(["indiana","merchant"]),checkoutUrl:s.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:Gu.nullable(),currency:Q,catalogAmountMinor:$e,taxMinor:$e,totalMinor:s.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:s.z.boolean(),nativePurchase:xa.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"),Hn=s.z.strictObject({enabled:s.z.literal(!0),featureIds:s.z.array(s.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Ku=s.z.strictObject({requestId:s.z.uuid(),invoiceMode:tr.optional(),membershipId:s.z.uuid(),carryOverBalances:Hn.optional(),carryOverUsages:Hn.optional(),membershipIds:s.z.array(s.z.uuid()).min(1).max(20).optional(),prorationBehavior:s.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:s.z.enum(["immediate","renewal","store"]),change:s.z.discriminatedUnion("type",[s.z.strictObject({type:s.z.literal("plan"),productVersionId:s.z.uuid()}),s.z.strictObject({type:s.z.literal("seats"),licenseKey:yt,quantity:s.z.number().int().min(0).max(1e4)}),s.z.strictObject({type:s.z.literal("quantity"),internal_feature_id:s.z.uuid(),quantity:s.z.number().int().min(0).max(1e4)}),s.z.strictObject({type:s.z.literal("cancel")}),s.z.strictObject({type:s.z.literal("uncancel")}),s.z.strictObject({type:s.z.literal("billing_cycle"),billingCycleAnchor:s.z.union([s.z.literal("now"),s.z.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Gn=s.z.string().regex(/^price_[A-Za-z0-9]+$/),Bu=s.z.strictObject({grooveUpdateId:s.z.uuid(),grooveCustomerId:s.z.uuid()}),Vu=s.z.strictObject({price:Gn.nullable(),priceId:s.z.uuid().optional(),quantity:s.z.number().int().min(0).max(1e4)}),Zu=s.z.strictObject({provider:s.z.literal("stripe"),invoiceMode:tr.optional(),executor:s.z.enum(["indiana","merchant"]),accountId:s.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:s.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:s.z.enum(["update","cancel","schedule","release"]),update:s.z.strictObject({items:s.z.array(Vu).max(20),remove:s.z.array(Gn).max(20),restoreItems:s.z.array(s.z.strictObject({price:Gn,quantity:s.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:s.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:s.z.number().int().positive().optional(),paymentBehavior:s.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:s.z.boolean().optional(),clearCancelAt:s.z.literal(!0).optional(),billingCycleAnchorNow:s.z.literal(!0).optional(),metadata:Bu}).nullable(),cancel:s.z.strictObject({prorate:s.z.literal(!1),invoiceNow:s.z.literal(!1)}).nullable(),schedule:s.z.strictObject({currentItems:s.z.array(s.z.strictObject({price:Gn,quantity:s.z.number().int().min(0).max(1e4)})).max(20),nextItems:s.z.array(Vu).min(1).max(20),switchAt:s.z.number().int().positive(),interval:s.z.enum(["week","month","year"]),intervalCount:s.z.number().int().min(1).max(52),resetBillingCycleAnchor:s.z.literal(!0).optional(),metadata:Bu}).nullable(),release:s.z.strictObject({schedule:s.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:s.z.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"),Ca=s.z.strictObject({carryOverBalances:Hn.optional(),carryOverUsages:Hn.optional(),operationId:s.z.uuid(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),timing:s.z.enum(["immediate","renewal"]),effectiveAt:s.z.iso.datetime({offset:!0}),expiresAt:s.z.iso.datetime({offset:!0}),currency:Q,creditMinor:$e,debitMinor:$e,discountMinor:$e,taxMinor:$e,totalMinor:$e,retainedProductVersionIds:s.z.array(s.z.uuid()).max(19),execution:Zu}),mg=s.z.strictObject({operationId:s.z.uuid(),invoiceMode:s.z.boolean().optional(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),status:s.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:s.z.enum(["immediate","renewal"]),effectiveAt:s.z.iso.datetime({offset:!0}),checkoutUrl:s.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:s.z.enum(["indiana","merchant"]),execution:Zu.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),pg=s.z.strictObject({operationId:s.z.uuid(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),timing:s.z.literal("store"),effectiveAt:s.z.null(),expiresAt:s.z.iso.datetime({offset:!0}),currency:Q,creditMinor:s.z.null(),debitMinor:s.z.null(),discountMinor:s.z.null(),taxMinor:s.z.null(),totalMinor:s.z.null(),retainedProductVersionIds:s.z.array(s.z.uuid()).max(19),store:s.z.strictObject({provider:s.z.enum(["apple","google"]),productId:s.z.string().min(1).max(255),catalogAmountMinor:$e,policy:s.z.enum(["apple_store","google_full_price"])})}),fg=s.z.strictObject({operationId:s.z.uuid(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),status:s.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:s.z.literal("store"),effectiveAt:s.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:s.z.null(),nativePurchase:xa.nullable()}),Wu=s.z.union([Ca,pg]),Oa=s.z.union([mg,fg]),Qr=s.z.number().int().positive().max(2e8),rr=s.z.number().int().min(0).max(2e8),Qu=s.z.strictObject({requestId:s.z.uuid(),invoiceId:s.z.uuid(),mode:s.z.enum(["full","partial"]),amountMinor:Qr.optional(),entitlementAction:s.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Yu=s.z.strictObject({provider:s.z.literal("stripe"),executor:s.z.enum(["indiana","merchant"]),accountId:s.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:s.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Qr,currency:s.z.string().regex(/^[a-z]{3}$/),metadata:s.z.strictObject({indianaRefundId:s.z.uuid()}),idempotencyKey:s.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:s.z.array(s.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Ju=s.z.strictObject({operationId:s.z.uuid(),invoiceId:s.z.uuid(),providerInvoiceId:s.z.string().regex(/^in_[A-Za-z0-9]+$/),currency:Q,paidMinor:rr,refundedMinor:rr,pendingMinor:rr,amountMinor:Qr,mode:s.z.enum(["full","partial"]),entitlementAction:s.z.enum(["retain","revoke"]),revokes:s.z.strictObject({customerProductIds:s.z.array(s.z.uuid()).max(100),subscriptionIds:s.z.array(s.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:Yu,expiresAt:s.z.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"),Kn=s.z.strictObject({operationId:s.z.uuid(),invoiceId:s.z.uuid(),providerInvoiceId:s.z.string().regex(/^in_[A-Za-z0-9]+$/),status:s.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:s.z.enum(["indiana","merchant"]),currency:Q,amountMinor:Qr,mode:s.z.enum(["full","partial"]),entitlementAction:s.z.enum(["retain","revoke"]),refundId:s.z.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:Yu.nullable(),failureReason:s.z.string().min(1).max(200).nullable(),createdAt:s.z.iso.datetime({offset:!0}),completedAt:s.z.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"),j_=s.z.strictObject({invoiceId:s.z.uuid(),currency:Q,paidMinor:rr,refundedMinor:rr,pendingMinor:rr,refundableMinor:rr,executor:s.z.enum(["indiana","merchant"]).nullable(),canRefund:s.z.boolean(),operations:s.z.array(Kn).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),R_=s.z.strictObject({requestId:s.z.uuid(),mode:s.z.enum(["full","partial"]),amountMinor:Qr.optional(),entitlementAction:s.z.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 Xu=Ie.z.strictObject({requestId:Ie.z.uuid(),targets:Ie.z.array(Ie.z.strictObject({membershipId:Ie.z.uuid(),action:Ie.z.enum(["cancel","uncancel"]),timing:Ie.z.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"),Zn=Ie.z.strictObject({batchId:Ie.z.uuid()}),hg=Ie.z.strictObject({operationId:Ie.z.uuid(),membershipIds:Ie.z.array(Ie.z.uuid()).min(1).max(20),provider:Ie.z.enum(["stripe","apple","google"]),action:Ie.z.enum(["cancel","uncancel"]),timing:Ie.z.enum(["immediate","renewal"]),status:Ie.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Ca.nullable(),managementUrl:Ie.z.url().nullable(),failureCode:Ie.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Yr=Ie.z.strictObject({batchId:Ie.z.uuid(),ready:Ie.z.boolean(),status:Ie.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:Ie.z.iso.datetime({offset:!0}),acceptedAt:Ie.z.iso.datetime({offset:!0}).nullable(),groups:Ie.z.array(hg).min(1).max(100)});var ae=require("zod"),Ag=ae.z.string().trim().min(1).max(240),wa={requestId:ae.z.uuid(),reason:Ag},Wn=ae.z.discriminatedUnion("action",[ae.z.strictObject({...wa,action:ae.z.literal("start"),productVersionId:ae.z.uuid(),entityId:ae.z.uuid().optional(),days:ae.z.number().int().min(1).max(730).optional()}),ae.z.strictObject({...wa,action:ae.z.literal("extend"),membershipId:ae.z.uuid(),days:ae.z.number().int().min(1).max(730)}),ae.z.strictObject({...wa,action:ae.z.literal("end"),membershipId:ae.z.uuid()})]),zu=ae.z.strictObject({operationId:ae.z.uuid()}),el=ae.z.iso.datetime({offset:!0}),gg=ae.z.strictObject({provider:ae.z.literal("stripe"),executor:ae.z.enum(["indiana","merchant"]),accountId:ae.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:ae.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:ae.z.union([ae.z.literal("now"),el]),prorationBehavior:ae.z.literal("none")}),Ea=ae.z.strictObject({operationId:ae.z.uuid(),action:ae.z.enum(["start","extend","end"]),status:ae.z.enum(["pending","effective"]),managedBy:ae.z.enum(["indiana","stripe"]),membershipIds:ae.z.array(ae.z.uuid()).min(1).max(20),endsAt:el.nullable(),execution:gg.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"),N_=ae.z.strictObject({groupId:ae.z.uuid(),productVersionId:ae.z.uuid(),enabled:ae.z.boolean()});var be=require("zod");var tl=be.z.strictObject({requestId:be.z.uuid(),currency:Q,makeDefault:be.z.boolean()}),rl=be.z.strictObject({setupId:be.z.uuid()}),bg=be.z.strictObject({provider:be.z.literal("stripe"),executor:be.z.literal("merchant"),accountId:be.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:be.z.literal("setup"),currency:be.z.string().regex(/^[a-z]{3}$/),customer:be.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:be.z.uuid(),metadata:be.z.strictObject({grooveProjectId:be.z.uuid(),grooveEnvironmentId:be.z.uuid(),grooveCustomerId:be.z.uuid(),groovePaymentSetupId:be.z.uuid()}),setDefaultPaymentMethod:be.z.boolean(),expiresAt:be.z.iso.datetime({offset:!0})}),ja=be.z.strictObject({id:be.z.uuid(),provider:be.z.literal("stripe"),status:be.z.enum(["prepared","complete","expired"]),currency:Q,makeDefault:be.z.boolean(),url:be.z.url().nullable(),createdAt:be.z.iso.datetime({offset:!0}),expiresAt:be.z.iso.datetime({offset:!0}),completedAt:be.z.iso.datetime({offset:!0}).nullable(),execution:bg.nullable()});var Ve=require("zod"),nl=Ve.z.union([Ve.z.string(),Ve.z.number(),Ve.z.boolean(),Ve.z.null()]),il=Ve.z.strictObject({customerId:Ve.z.uuid()}),al=Ve.z.strictObject({customerId:Ve.z.uuid(),provider:Ve.z.literal("stripe"),checkedAt:Ve.z.iso.datetime({offset:!0}),status:Ve.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ve.z.number().int().nonnegative(),differences:Ve.z.array(Ve.z.strictObject({subscriptionId:Ve.z.string().startsWith("sub_"),itemId:Ve.z.string().nullable(),field:Ve.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:nl,actual:nl})).max(1e4)});var X=require("zod");var Qn=X.z.iso.datetime({offset:!0}),Yn=X.z.strictObject({createdAt:Qn,id:X.z.uuid()}),Jn=X.z.strictObject({customerId:X.z.uuid().optional(),entityId:X.z.uuid().optional(),productId:X.z.string().min(1).max(256).optional(),provider:X.z.enum(["stripe","apple","google","free"]).optional(),status:X.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Yn.optional(),limit:X.z.number().int().min(1).max(100).optional()}),Ra={id:X.z.uuid(),customerId:X.z.uuid(),entityId:X.z.uuid().nullable(),productId:X.z.string().min(1).max(256),productVersionId:X.z.uuid(),name:X.z.string().min(1).max(120),provider:X.z.enum(["stripe","apple","google","free"]),createdAt:Qn},yg=X.z.strictObject({...Ra,status:X.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:X.z.boolean(),billingSubscriptionId:X.z.uuid().nullable()}),Sg=X.z.strictObject({...Ra,status:X.z.enum(["active","ended","refunded"]),orderId:X.z.uuid().nullable(),transactionId:X.z.uuid().nullable(),currency:Q.nullable(),amountMinor:X.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),_g=X.z.strictObject({...Ra,status:X.z.enum(["blocked","resolved"]),conflict:X.z.strictObject({detectedAt:Qn,blockingMembershipIds:X.z.array(X.z.uuid()).min(1).max(100),transactionId:X.z.uuid()}),resolvedAt:Qn.nullable()}),ol=Jn.extend({status:X.z.enum(["blocked","resolved"]).optional()}),sl=X.z.strictObject({customerId:X.z.uuid(),orderId:X.z.uuid()}),cl=X.z.strictObject({orderId:X.z.uuid(),status:X.z.enum(["blocked","resolved"])}),ul=X.z.strictObject({items:X.z.array(yg).max(100),nextCursor:Yn.nullable()}),ll=X.z.strictObject({items:X.z.array(Sg).max(100),nextCursor:Yn.nullable()}),dl=X.z.strictObject({items:X.z.array(_g).max(100),nextCursor:Yn.nullable()});var _e=require("zod");var ml=_e.z.union([_e.z.strictObject({intent:_e.z.literal("read"),requestId:_e.z.uuid(),purchaseIntentId:_e.z.uuid()}),_e.z.strictObject({requestId:_e.z.uuid(),provider:_e.z.literal("apple"),purchaseIntentId:_e.z.uuid(),productId:_e.z.string().min(1).max(255).optional(),signedTransaction:_e.z.string().min(1).max(131072)}),_e.z.strictObject({requestId:_e.z.uuid(),provider:_e.z.literal("google"),purchaseIntentId:_e.z.uuid(),productId:_e.z.string().min(1).max(255).optional(),purchaseToken:_e.z.string().min(1).max(16384)})]),pl=_e.z.strictObject({requestId:_e.z.uuid(),orderId:_e.z.uuid(),purchaseIntentId:_e.z.uuid(),status:_e.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Q,refunded:_e.z.boolean(),completion:_e.z.strictObject({transactionIds:_e.z.array(_e.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:_e.z.boolean()}).nullable()});var C=require("zod"),ka=C.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),xg=C.z.record(C.z.string(),C.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),Ig=3,Jr=20,vg=Ig*Jr,Ta=C.z.strictObject({type:C.z.literal("product"),productId:ka}),fl={type:C.z.literal("group"),key:C.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:C.z.string().trim().min(1).max(80)},Pg=C.z.discriminatedUnion("type",[Ta,C.z.strictObject({...fl,items:C.z.array(Ta).max(Jr)})]),Cg=C.z.discriminatedUnion("type",[Ta,C.z.strictObject({...fl,items:C.z.array(Pg).max(Jr)})]),Og=C.z.array(Cg).max(Jr).superRefine((e,t)=>{let r=new Set,n=new Set,i=0;function o(a){for(let c of a){i++;let d=c.type==="product"?r:n,p=c.type==="product"?c.productId:c.key;d.has(p)&&t.addIssue({code:"custom",message:c.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),d.add(p),c.type==="group"&&o(c.items)}}o(e),(r.size>Jr||i>vg)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Da(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Da(t))}var yr=C.z.strictObject({lookupKey:C.z.string().trim().min(1).max(200),displayName:C.z.string().trim().min(1).max(1500),items:Og,metadata:xg}),wg=C.z.strictObject({product:C.z.record(C.z.string(),C.z.json()),prices:C.z.array(C.z.record(C.z.string(),C.z.json())),entitlements:C.z.array(C.z.record(C.z.string(),C.z.json())),freeTrials:C.z.array(C.z.record(C.z.string(),C.z.json())),licenses:C.z.array(C.z.record(C.z.string(),C.z.json()))}),hl=yr.extend({id:C.z.uuid(),projectId:C.z.uuid(),environmentId:C.z.uuid(),state:C.z.enum(["active","archived"]),isCurrent:C.z.boolean(),revision:C.z.number().int().nonnegative(),publishedVersionId:C.z.uuid().nullable(),createdAt:C.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),Al=C.z.strictObject({id:C.z.uuid(),offeringId:C.z.uuid(),projectId:C.z.uuid(),environmentId:C.z.uuid(),version:C.z.number().int().positive(),document:yr,productEvidence:C.z.record(ka,wg),createdAt:C.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let r=Da(e.document);(!r.length||Rg(e.document).length>0||Object.keys(e.productEvidence).length!==r.length||r.some(n=>!Object.hasOwn(e.productEvidence,n)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),Eg=C.z.strictObject({rows:C.z.array(hl).max(200),versions:C.z.array(Al).max(500)}),G_=C.z.discriminatedUnion("action",[C.z.strictObject({action:C.z.literal("create"),document:yr}),C.z.strictObject({action:C.z.literal("save"),id:C.z.uuid(),revision:C.z.number().int().nonnegative(),document:yr}),C.z.strictObject({action:C.z.enum(["publish","set_current","archive","restore"]),id:C.z.uuid(),revision:C.z.number().int().nonnegative()})]),H_=C.z.strictObject({record:hl,version:Al.nullable()}),gl=C.z.discriminatedUnion("type",[C.z.strictObject({type:C.z.literal("current")}),C.z.strictObject({type:C.z.literal("id"),id:C.z.uuid()}),C.z.strictObject({type:C.z.literal("lookup_key"),lookupKey:C.z.string().min(1).max(200)}),C.z.strictObject({type:C.z.literal("version"),versionId:C.z.uuid()})]),jg=C.z.strictObject({internalId:ka,id:C.z.string(),name:C.z.string().nullable(),version:C.z.number().int().positive(),archived:C.z.boolean()}),K_=Eg.extend({products:C.z.array(jg).max(500)});function Rg(e){let t=[];Da(e).length||t.push("Select at least one Product before publishing");function r(n){for(let i of n)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),r(i.items))}return r(e.items),t}var Xr=require("zod");var bl=Xr.z.strictObject({id:Xr.z.uuid(),offeringId:Xr.z.uuid(),version:Xr.z.number().int().positive(),document:yr});var De=require("zod");var W=require("zod");var ir=require("zod");var Xn=ir.z.strictObject({items:ir.z.array(ir.z.strictObject({productVersionId:ir.z.string().min(1).max(200),label:ir.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:ir.z.string().min(1).max(200).nullable(),grouping:Bn.optional()});var ke=require("zod"),Tg=ke.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),zn=ke.z.discriminatedUnion("type",[ke.z.object({type:ke.z.literal("fixed"),productVersionId:ke.z.string().min(1).max(200)}).strict(),ke.z.object({type:ke.z.literal("picker"),pickerId:Tg,allowedProductVersionIds:ke.z.array(ke.z.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")]),zr=ke.z.discriminatedUnion("type",[ke.z.object({type:ke.z.literal("modal"),size:ke.z.enum(["sm","md","lg"])}).strict(),ke.z.object({type:ke.z.literal("sheet"),size:ke.z.enum(["sm","md","lg"])}).strict(),ke.z.object({type:ke.z.literal("fullscreen")}).strict(),ke.z.object({type:ke.z.literal("inline")}).strict()]);var Na=W.z.discriminatedUnion("type",[W.z.strictObject({type:W.z.literal("event"),event:W.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),W.z.strictObject({type:W.z.literal("open_url"),url:W.z.url().refine(e=>new URL(e).protocol==="https:")})]),kg=er,Dg=W.z.discriminatedUnion("type",[W.z.object({type:W.z.literal("checkout"),product:zn}).strict(),W.z.object({type:W.z.literal("close")}).strict(),W.z.object({type:W.z.literal("action"),action:Na}).strict()]),Sr=W.z.object({schemaVersion:W.z.literal(3),kind:W.z.literal("paywall"),name:W.z.string().trim().min(1).max(80),presentation:zr,requirement:Mt.optional(),products:Xn,offeringVersionId:W.z.uuid().nullable(),offeringId:W.z.uuid(),screen:kg,buttons:W.z.record(W.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Dg)}).strict(),ax=Sr.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(n=>!["event","navigate"].includes(n.type)||n.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let n of Mg(e))t.addIssue({code:"custom",message:n});for(let n of Ng(e))t.addIssue({code:"custom",message:n});Ar(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(n=>n.type!=="navigate").length||e.screen.actions.some(n=>n.type!=="navigate"&&!Object.hasOwn(e.buttons,n.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(n=>n.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function Ng(e){let t=e.products.items.map(o=>o.productVersionId),r=uu(e.screen),n=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!Vn(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")n.add(a.productVersionId);else{a.allowedProductVersionIds.forEach(p=>n.add(p));let c=!1,d=r[a.pickerId];d&&(c=!0,(a.allowedProductVersionIds.some(p=>!d.ids.includes(p))||d.ids.some(p=>!a.allowedProductVersionIds.includes(p)))&&i.push("picker")),ot(e.screen,p=>{if(p.id!==a.pickerId||p.type!=="plan_picker")return;c=!0,(JSON.stringify(p.planIds)!==JSON.stringify(t)||JSON.stringify(a.allowedProductVersionIds)!==JSON.stringify(t)||p.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let y=p.grouping?{tiers:p.grouping.tiers,assignments:p.grouping.assignments}:void 0;JSON.stringify(y)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),c||i.push("picker")}}return(!n.size||[...n].some(o=>!t.includes(o)))&&i.push("purchase"),ot(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 Mg(e){let t=[],r=e.screen.pages.at(-1),n=new Map;for(let c of e.screen.pages)n.set(c.id,[]),Wr(c.root,d=>{let p=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(p){let y=e.screen.actions.find($=>$.id===p);y?.type==="navigate"&&n.get(c.id).push(y.pageId);let j=e.buttons[p];c.id!==r.id&&j&&j.type!=="close"&&t.push(`purchaseScreen:${d.id}`)}c.id!==r.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&t.push(`packageScreen:${d.id}`)});let i=new Set;function o(c){if(!i.has(c)){i.add(c);for(let d of n.get(c)??[])o(d)}}let a=e.screen.initialPageId??e.screen.pages[0]?.id;a?o(a):t.push("initialPage");for(let c of e.screen.pages)i.has(c.id)||t.push(`unreachableScreen:${c.id}`);return[...new Set(t)]}var yl=W.z.object({id:W.z.uuid(),projectId:W.z.uuid(),environmentId:W.z.uuid(),revision:W.z.number().int().nonnegative(),state:W.z.enum(["active","archived"]),publishedVersionId:W.z.uuid().nullable(),updatedAt:W.z.iso.datetime({offset:!0}),draft:Sr}).strict(),ox=W.z.object({rows:W.z.array(yl).max(200),nextCursor:W.z.uuid().nullable()}).strict(),sx=yl.omit({draft:!0}).extend({name:W.z.string(),productCount:W.z.number().int().nonnegative()}).strict(),cx=W.z.discriminatedUnion("action",[W.z.object({action:W.z.literal("save"),id:W.z.uuid().nullable(),revision:W.z.number().int().nonnegative(),document:Sr}).strict(),W.z.object({action:W.z.enum(["publish","archive"]),id:W.z.uuid(),revision:W.z.number().int().nonnegative()}).strict()]),ux=W.z.object({paywalls:W.z.array(W.z.object({id:W.z.uuid(),paywallId:W.z.uuid(),version:W.z.number().int().positive(),name:W.z.string().min(1).max(80),presentation:zr,buttons:Sr.shape.buttons}).strict()).max(500),limited:W.z.boolean()}).strict();var ne=require("zod");var Ke=require("zod");var _r=Ke.z.string().regex(/^[a-f0-9]{64}$/),Ug=qn.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),px=Ke.z.strictObject({couponDigests:Ke.z.record(Ke.z.uuid(),_r),variables:Ke.z.record(mt,Ke.z.record(Ke.z.uuid(),Ke.z.partialRecord(Ke.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Ke.z.string()))),locales:Ke.z.record(mt,Ln.extend({nodes:Ke.z.record(Ke.z.string(),Ke.z.strictObject({base:Ug})),plans:Ke.z.object({}).strict(),pickers:Ke.z.object({}).strict()}).omit({paywall:!0}))});var de=require("zod");var en=require("zod"),Ma=en.z.strictObject({eventsEnabled:en.z.boolean(),experimentViewsEnabled:en.z.boolean(),featureUsageEnabled:en.z.boolean()}),hx=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});var O=require("zod");var Ua=O.z.tuple([O.z.number().min(0).max(1),O.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),qg=O.z.strictObject({attribute:O.z.string().optional(),seed:O.z.string(),hashVersion:O.z.literal(2),ranges:O.z.array(Ua).max(100)}),Lg=O.z.strictObject({id:O.z.string().min(1).max(255),condition:dt,gate:O.z.boolean().optional()}),Bg=O.z.strictObject({key:O.z.string().optional(),name:O.z.string().optional(),passthrough:O.z.boolean().optional()}),Sl={condition:dt.optional(),parentConditions:O.z.array(Lg).max(100).optional(),weights:O.z.array(O.z.number().min(0).max(1)).max(20).optional(),coverage:O.z.number().min(0).max(1).optional(),hashAttribute:O.z.string().optional(),fallbackAttribute:O.z.string().optional(),hashVersion:O.z.literal(2).optional(),disableStickyBucketing:O.z.boolean().optional(),bucketVersion:O.z.number().int().nonnegative().optional(),minBucketVersion:O.z.number().int().nonnegative().optional(),filters:O.z.array(qg).max(100).optional(),ranges:O.z.array(Ua).max(20).optional(),meta:O.z.array(Bg).max(20).optional(),seed:O.z.string().optional(),name:O.z.string().optional(),phase:O.z.string().optional()},_l=O.z.strictObject({...Sl,key:O.z.string().min(1).max(255),variations:O.z.tuple([Qe,Qe]).rest(Qe).refine(e=>e.length<=20),urlPatterns:O.z.array(O.z.strictObject({include:O.z.boolean(),type:O.z.enum(["regex","simple"]),pattern:O.z.string()})).max(100).optional(),force:O.z.number().int().nonnegative().optional(),active:O.z.boolean().optional(),persistQueryString:O.z.boolean().optional()}),qa=O.z.strictObject({value:Qe,variationId:O.z.number().int(),key:O.z.string(),name:O.z.string().optional(),bucket:O.z.number().optional(),passthrough:O.z.boolean().optional(),inExperiment:O.z.boolean(),hashUsed:O.z.boolean().optional(),hashAttribute:O.z.string(),hashValue:O.z.string(),featureId:O.z.string().nullable(),stickyBucketUsed:O.z.boolean().optional()}),Vg=O.z.strictObject({...Sl,id:O.z.string().max(255).optional(),force:Qe.optional(),variations:O.z.array(Qe).min(2).max(20).optional(),key:O.z.string().optional(),range:Ua.optional(),tracks:O.z.array(O.z.strictObject({experiment:_l,result:qa})).max(100).optional()}),Fg=O.z.strictObject({defaultValue:Qe.optional(),rules:O.z.array(Vg).max(500).optional()}),$g=O.z.record(O.z.string(),O.z.union([O.z.strictObject({type:O.z.literal("hashed"),attributeKey:O.z.string(),values:O.z.array(O.z.string().regex(/^[a-f0-9]{64}$/))}),O.z.strictObject({type:O.z.literal("list"),attributeKey:O.z.string(),values:O.z.array(O.z.union([O.z.string(),O.z.number()]))}),O.z.strictObject({type:O.z.literal("condition"),condition:dt})])),tn=O.z.strictObject({scope:Ne,generation:O.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:O.z.iso.datetime({offset:!0}),expiresAt:O.z.iso.datetime({offset:!0}).nullable(),features:O.z.record(O.z.string(),Fg),savedGroups:$g,experiments:O.z.record(O.z.uuid(),_l)});var La=tn.extend({analyticsConfig:Ma,remoteFeatures:de.z.array(de.z.string().min(1).max(255)).max(500)}),Ix=La.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let r of e.remoteFeatures)Object.hasOwn(e.features,r)&&t.addIssue({code:"custom",path:["features",r],message:"Remote Feature definitions cannot be public"});for(let[r,n]of Object.entries(e.savedGroups))n.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",r],message:"Raw Saved Group lists cannot be public"})}),xl=de.z.strictObject({attributes:St,features:de.z.array(de.z.string().min(1).max(255)).max(500).optional(),customerId:de.z.uuid().optional()}),Gg=de.z.strictObject({value:Qe,source:de.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:de.z.boolean(),off:de.z.boolean(),ruleId:de.z.string(),experimentResult:qa.optional()}),Il=de.z.strictObject({generation:tn.shape.generation,evaluatedAt:tn.shape.evaluatedAt,expiresAt:tn.shape.expiresAt,features:de.z.record(de.z.string(),Gg),merchandiseContext:de.z.strictObject({merchandiseId:de.z.uuid(),merchandise:St}).optional()}),vl=de.z.strictObject({customerId:de.z.uuid().optional(),events:de.z.array(de.z.strictObject({eventUuid:de.z.uuid(),timestamp:de.z.iso.datetime({offset:!0}),name:de.z.string().min(1).max(255),merchandise:ic.optional(),properties:de.z.record(de.z.string(),Qe).default({}),deviceId:de.z.string().min(1).max(255).optional(),sessionId:de.z.string().min(1).max(255).optional()})).min(1).max(100)}),Pl=de.z.strictObject({inserted:de.z.number().int().nonnegative(),duplicates:de.z.number().int().nonnegative(),rejected:de.z.number().int().nonnegative(),skipped:de.z.number().int().nonnegative(),analyticsConfig:Ma});function Cl(e,t=[]){let r=[];ot(e,i=>{i.hidden&&r.push("Hidden components must not be delivered"),t.includes(i.type)&&r.push(`Node type ${i.type} cannot be delivered`)});let n=new Set(ya(e).map(i=>i.key));for(let[i,o]of Object.entries(e.strings.locales))for(let a of Object.keys(o))n.has(a)||r.push(`Unused string ${a} must not be delivered (${i})`);return r}var F=require("zod");var Ba=F.z.array(F.z.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"),ei=F.z.intersection(St,F.z.looseObject({tags:Ba.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),ti=F.z.string().trim().max(80),ri=F.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),ni=F.z.union([F.z.email().max(254),F.z.literal("")]),ii=F.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Ol=F.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),wl=F.z.object({externalUserId:Ol.optional(),name:ti.default(""),email:ni.default(""),phone:ri.optional(),attributes:ei.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Ex=F.z.discriminatedUnion("type",[F.z.strictObject({type:F.z.literal("id"),value:F.z.uuid()}),F.z.strictObject({type:F.z.literal("externalUserId"),value:Ol})]),jx=F.z.strictObject({name:ti.optional(),email:ni.optional(),phone:ri.optional(),attributes:ei.optional(),fingerprint:ii.optional()});var xr=F.z.object({id:F.z.uuid(),externalUserId:F.z.string().min(1).max(255).nullable(),name:ti,email:ni,phone:ri.optional(),attributes:ei,createdAt:F.z.iso.datetime()}).strict(),El=F.z.object({customer:xr,changed:F.z.boolean(),replayed:F.z.boolean()}).strict(),Hg=F.z.discriminatedUnion("type",[F.z.object({type:F.z.literal("id"),value:F.z.uuid()}).strict(),F.z.object({type:F.z.literal("externalUserId"),value:F.z.string().trim().min(1).max(255)}).strict()]),Kg=F.z.object({name:ti.optional(),email:ni.optional(),phone:ri.optional(),attributes:ei.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:F.z.array(F.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:F.z.strictObject({add:Ba,remove:Ba}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Va=F.z.object({lookup:Hg}).strict(),jl=Va.extend({requestId:F.z.uuid(),patch:Kg}).strict(),Rl=F.z.object({search:F.z.string().trim().max(200).default(""),tag:F.z.string().trim().max(40).default(""),planId:F.z.string().max(200).default(""),versionId:F.z.string().max(200).default(""),holdingStatus:F.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:F.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:F.z.union([F.z.iso.datetime(),F.z.literal("")]).default(""),createdUntil:F.z.union([F.z.iso.datetime(),F.z.literal("")]).default(""),offset:F.z.coerce.number().int().min(0).max(1e5).default(0),limit:F.z.coerce.number().int().min(1).max(100).default(50)}).strict(),Tl=F.z.object({customers:xr.array(),hasMore:F.z.boolean(),total:F.z.number().int().nonnegative().nullable(),evaluatedAt:F.z.iso.datetime()}).strict();var q=require("zod");var Ir=require("zod");var kl=Ir.z.object({defaultLocale:mt,locales:Ir.z.record(mt,Ir.z.object({name:Ir.z.string().max(80),description:Ir.z.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let r=Object.keys(e.locales);(!r.length||r.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var Zg=["customer_data","coupon_code"],Wg=q.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Dl=q.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),ai=(e,t)=>new Set(e.map(t)).size===e.length,Qg=q.z.strictObject({currency:Q,amountMinor:q.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Yg=q.z.strictObject({featureId:q.z.uuid(),name:q.z.string().trim().min(1).max(120),allowance:q.z.string().max(40).nullable(),access:q.z.boolean()}),Jg=q.z.strictObject({stripe:q.z.strictObject({prices:q.z.array(Qg).min(1).max(50)}).optional(),apple:q.z.strictObject({productIds:q.z.array(Wg).min(1).max(10)}).optional(),google:q.z.strictObject({products:q.z.array(q.z.strictObject({productId:Dl,basePlanId:Dl.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!ai(e.stripe.prices,r=>r.currency)||e.apple&&!ai(e.apple.productIds,r=>r)||e.google&&!ai(e.google.products,r=>`${r.productId}:${r.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),Xg=q.z.strictObject({name:q.z.string().trim().min(1).max(80),interval:q.z.enum(["free","week","month","year","one_time"]),intervalCount:q.z.number().int().min(1).max(100),trial:q.z.strictObject({days:q.z.number().int().min(1).max(730),cardRequired:q.z.boolean()}).nullable(),benefits:q.z.array(Yg).max(50).refine(e=>ai(e,t=>t.featureId),"Duplicate benefit"),channels:Jg}),zg=q.z.strictObject({digest:_r,content:q.z.strictObject({discount:Dt,duration:tt,appliesTo:ta,displayCopy:kl.nullable(),firstPurchaseOnly:q.z.boolean(),qualificationRequired:q.z.boolean(),startsAt:q.z.iso.datetime().nullable(),endsAt:q.z.iso.datetime().nullable(),grantWindowHours:q.z.number().int().positive(),perCustomerLimit:q.z.number().int().positive()})}),eb=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("checkout"),product:zn}),q.z.strictObject({type:q.z.literal("close")}),q.z.strictObject({type:q.z.literal("action"),action:Na})]),$x=q.z.strictObject({kind:q.z.literal("paywall"),formatVersion:q.z.literal(1),name:q.z.string().trim().min(1).max(80),offeringVersionId:q.z.uuid(),presentation:zr,screen:er,products:Xn,catalog:q.z.record(q.z.uuid(),Xg),buttons:q.z.record(pe,eb),coupons:q.z.record(q.z.uuid(),zg)}).superRefine((e,t)=>{let r=R=>t.addIssue({code:"custom",message:R}),{screen:n}=e;n.surface!=="paywall"&&r("Screen must be a Paywall"),Cl(n,Zg).forEach(r),Ar(n).some(R=>!R.complete)&&r("Every published locale must be complete");let i=new Set,o=new Set,a=new Set;ot(n,R=>{let Re="bind"in R?R.bind:void 0;Re?.promotionCode&&r("Promotion codes must not be published"),Re?.plan&&i.add(Re.plan),Re?.coupon&&o.add(Re.coupon),R.type==="plan_picker"&&(R.planIds?.forEach(G=>i.add(G)),R.defaultPlan&&i.add(R.defaultPlan)),R.type==="text"&&R.feature&&a.add(R.feature.id)});let c=e.products.items.map(R=>R.productVersionId),d=Object.keys(e.catalog);(c.length!==d.length||c.some(R=>!Object.hasOwn(e.catalog,R)))&&r("Catalog must contain exactly the displayed Products");let p=new Set(c);e.products.defaultProductVersionId!==null&&!p.has(e.products.defaultProductVersionId)&&r("Default Product must be displayed");for(let R of i)p.has(R)||r("Screen references a Product that is not displayed");for(let R of Object.values(e.catalog))!R.channels.stripe&&!R.channels.apple&&!R.channels.google&&r("A displayed Product needs at least one sales channel");let y=new Set(Object.values(e.catalog).flatMap(R=>R.benefits.map(Re=>Re.featureId)));for(let R of a)y.has(R)||r("Feature text must read a displayed benefit");let j=n.actions.filter(R=>R.type!=="navigate");n.actions.some(R=>R.type!=="event"&&R.type!=="navigate")&&r("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==j.length||j.some(R=>!Object.hasOwn(e.buttons,R.id)))&&r("Buttons must match the screen's actions");let ie=!1;for(let R of Object.values(e.buttons)){if(R.type!=="checkout")continue;ie=!0,(R.product.type==="fixed"?[R.product.productVersionId]:R.product.allowedProductVersionIds).some(G=>!p.has(G))&&r("Checkout may only sell displayed Products")}ie||r("A Paywall needs a checkout button");let ye=Object.keys(e.coupons);(ye.length!==o.size||ye.some(R=>!o.has(R)))&&r("Coupons must be exactly the bound Coupons")}),Nl=q.z.strictObject({state:q.z.enum(["published","archived"]),controlRevision:q.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:q.z.uuid(),versions:q.z.record(q.z.uuid(),q.z.strictObject({version:q.z.number().int().positive(),artifact:q.z.string().min(1),sourceDigest:q.z.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var tb={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Fa=ne.z.string().regex(/^[a-f0-9]{64}$/),$a=ne.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),rb=Ne.extend({environmentId:ne.z.uuid()}),nb=ne.z.strictObject({features:ne.z.array(ne.z.string()).max(500),experiments:ne.z.record(ne.z.uuid(),ne.z.array(ne.z.string()).max(20)),savedGroups:ne.z.array(ne.z.string()).max(1e3)}),Ga=ne.z.strictObject({kind:ne.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:ne.z.number().int().positive(),url:ne.z.string().min(1).max(2048),sha256:Fa,byteLength:ne.z.number().int().positive().max(tb.maxArtifactBytes),generation:Fa.optional()}),ib=ne.z.strictObject({state:ne.z.enum(["active","paused","archived"]),controlRevision:$a,evaluationMode:ne.z.enum(["local","remote"]),evaluationRevision:$a,currentVersionId:ne.z.uuid(),versions:ne.z.record(ne.z.uuid(),ne.z.strictObject({artifact:ne.z.string(),dependencies:nb,definitionDigest:_r.optional(),couponDigests:ne.z.record(ne.z.uuid(),_r).optional()}))}),Wx=ne.z.strictObject({kind:ne.z.literal("sdk_configuration"),schemaVersion:ne.z.literal(1),scope:rb,revision:$a,generation:Fa,policy:ne.z.strictObject({refreshIntervalSeconds:ne.z.number().positive().max(15),maxControlAgeSeconds:ne.z.number().positive().max(60)}),gb:ne.z.strictObject({features:ne.z.string().nullable(),pageExperiments:ne.z.string().nullable()}),artifacts:ne.z.record(ne.z.string(),Ga),funnels:ne.z.record(ne.z.uuid(),ib),paywalls:ne.z.record(ne.z.uuid(),Nl).optional()}).superRefine((e,t)=>{let r=(n,i)=>{n!==null&&e.artifacts[n]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};r(e.gb.features,"gb_features"),r(e.gb.pageExperiments,"gb_page_experiments");for(let n of Object.values(e.paywalls??{}))for(let i of Object.values(n.versions))r(i.artifact,"paywall");for(let n of Object.values(e.funnels)){n.evaluationMode==="remote"&&Object.keys(n.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),n.evaluationMode==="local"&&!n.versions[n.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(n.versions))r(i.artifact,"funnel")}});var Ul=De.z.strictObject({...gr,selector:De.z.discriminatedUnion("type",[De.z.strictObject({type:De.z.literal("paywall"),paywallId:De.z.uuid()}),De.z.strictObject({type:De.z.literal("version"),versionId:De.z.uuid()})]),customerId:De.z.uuid().optional(),commerce:hr,locale:De.z.string().min(1).max(35),requirement:Mt.optional()}),Ml=De.z.strictObject({id:De.z.uuid(),paywallId:De.z.uuid(),version:De.z.number().int().positive(),document:Sr.omit({requirement:!0,offeringId:!0}),offering:De.z.strictObject({id:De.z.uuid()}),content:De.z.strictObject({environmentId:De.z.uuid(),offeringVersionId:De.z.uuid(),artifact:Ga.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Ln,check:Xt.nullable()}).superRefine((e,t)=>{let r=new Set(e.document.products.items.map(n=>n.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(n=>!r.has(n.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),ql=De.z.strictObject(Ml.shape).omit({document:!0,offering:!0}).extend({content:Ml.shape.content.unwrap()});var Ze=require("zod");var Ll={requestId:Ze.z.uuid(),sourceId:Ze.z.uuid(),expectedAvailable:Je},Bl=Ze.z.discriminatedUnion("action",[Ze.z.strictObject({...Ll,action:Ze.z.enum(["add","subtract","set_remaining"]),amount:Z}),Ze.z.strictObject({...Ll,action:Ze.z.literal("edit"),granted:Z,expiresAt:Ze.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Ze.z.iso.datetime({offset:!0}).nullable(),expectedRevision:Ze.z.number().int().nonnegative()})]),Ha=Ze.z.strictObject({sourceId:Ze.z.uuid(),available:Je,held:Je,spent:Je,adjustmentGrantId:Ze.z.uuid().nullable()}),Vl=Ha.extend({granted:Je,expiresAt:Ze.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Ze.z.iso.datetime({offset:!0}).nullable(),revision:Ze.z.number().int().nonnegative()});var ze=require("zod"),Fl=ze.z.discriminatedUnion("action",[ze.z.object({action:ze.z.literal("upsert"),externalId:ze.z.string().min(1).max(128),name:ze.z.string().trim().min(1).max(80)}).strict(),ze.z.object({action:ze.z.literal("archive"),entityId:ze.z.uuid()}).strict()]),$l=ze.z.object({id:ze.z.uuid(),externalId:ze.z.string().min(1).max(128),name:ze.z.string().min(1).max(80),archived:ze.z.boolean()}).strict();var Ge=require("zod");var qt=require("zod"),Hl=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Gl=qt.z.string().regex(/.+\/.+/),Ka=qt.z.number().min(-100),ar=qt.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),ab=qt.z.strictObject({input:ar,output:ar,cache_read:ar.optional(),cache_write:ar.optional(),reasoning:ar.optional(),input_audio:ar.optional(),output_audio:ar.optional()}),Za=(e,t)=>qt.z.record(e,t).refine(r=>Object.keys(r).length<=100,"At most 100 AI overrides"),sI=qt.z.strictObject({defaultMarkup:Ka,providerMarkups:Za(qt.z.string().min(1),Ka),modelMarkups:Za(Gl,Ka),customModels:Za(Gl,ab.partial())});var J=require("zod"),or=J.z.iso.datetime({offset:!0}),Lt=J.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),ob=J.z.discriminatedUnion("kind",[J.z.object({kind:J.z.literal("absolute"),from:or,to:or}).strict(),J.z.object({kind:J.z.literal("last_days"),days:J.z.union([J.z.literal(1),J.z.literal(7),J.z.literal(30),J.z.literal(90)])}).strict(),J.z.object({kind:J.z.literal("billing_cycles"),membershipId:J.z.uuid(),count:J.z.number().int().min(1).max(12),includeCurrent:J.z.boolean()}).strict()]),Kl=J.z.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),sb=J.z.object({key:J.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:J.z.array(J.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),sr=J.z.object({range:ob,timezone:Kl,filterBy:J.z.array(sb).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:J.z.enum(["hour","day","week","month"]),internal_feature_id:J.z.uuid().nullable(),entityId:J.z.uuid().nullable(),topN:J.z.number().int().min(1).max(50).nullable(),groupBy:J.z.union([J.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),J.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:J.z.object({bucket:or,group:J.z.string().max(240),isOther:J.z.boolean(),internal_feature_id:J.z.uuid(),resourceId:J.z.uuid()}).strict().nullable(),limit:J.z.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let r=Date.parse(e.range.to)-Date.parse(e.range.from);(r<=0||r>366*864e5||e.interval==="hour"&&r>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Zl=J.z.object({from:or,to:or,interval:J.z.enum(["hour","day","week","month"]),timezone:Kl,rows:J.z.array(J.z.object({bucket:or,group:J.z.string().max(240),isOther:J.z.boolean(),internal_feature_id:J.z.uuid(),resourceId:J.z.uuid(),consumedUnits:Lt,refundedUnits:Lt,reservedUnits:Lt,charged:Lt,refunded:Lt,reserved:Lt,netUnits:Lt,netCharged:Lt}).strict()).max(100),nextCursor:J.z.object({bucket:or,group:J.z.string().max(240),isOther:J.z.boolean(),internal_feature_id:J.z.uuid(),resourceId:J.z.uuid()}).strict().nullable()}).strict();var vr=Ge.z.string().regex(/^(0|[1-9]\d{0,29})$/),Wl=Ge.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Wa=Ge.z.strictObject({bucket:Ge.z.iso.datetime({offset:!0}),group:Ge.z.string().max(240),isOther:Ge.z.boolean(),internal_feature_id:Ge.z.uuid()}),Ql=Ge.z.strictObject({...sr.shape,groupBy:Ge.z.union([Ge.z.enum(["customer","entity","entitlement"]),Ge.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Wa.nullable()}).superRefine((e,t)=>{let r=sr.safeParse({...e,after:null});if(!r.success)for(let n of r.error.issues)t.addIssue({code:"custom",path:n.path,message:n.message})}),Yl=Ge.z.strictObject({from:Ge.z.iso.datetime({offset:!0}),to:Ge.z.iso.datetime({offset:!0}),interval:sr.shape.interval,timezone:sr.shape.timezone,rows:Ge.z.array(Ge.z.strictObject({...Wa.shape,eventCount:vr,units:Wl,tokenEventCount:vr,tokens:Ge.z.strictObject(Object.fromEntries(Hl.map(e=>[e,vr]))),totalTokens:vr,providerCostEventCount:vr,providerCostUsd:Wl,invalidTelemetryEventCount:vr})).max(100),nextCursor:Wa.nullable()});var Oe=require("zod");var Jl=Oe.z.object({requestId:Oe.z.uuid(),items:Oe.z.array(Oe.z.object({customerId:Oe.z.uuid(),command:Lr.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"),Xl=Oe.z.object({batchId:Oe.z.uuid(),after:Oe.z.number().int().min(-1).max(999),limit:Oe.z.number().int().min(1).max(100)}).strict(),zl=Oe.z.object({batchId:Oe.z.uuid(),status:Oe.z.enum(["queued","complete"]),total:Oe.z.number().int().min(1).max(1e3),processed:Oe.z.number().int().min(0).max(1e3),items:Oe.z.array(Oe.z.object({position:Oe.z.number().int().min(0).max(999),customerId:Oe.z.uuid(),idempotencyKey:Oe.z.string().min(1).max(120),status:Oe.z.enum(["queued","accepted","rejected","failed"]),receipt:Br.nullable(),errorCode:Oe.z.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:Oe.z.number().int().min(0).max(999).nullable()}).strict();var h=require("zod");var cb=h.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),ed=h.z.enum(["draft","active","paused","archived"]),td=h.z.string().min(1).max(256),rd=h.z.array(td).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),ub=h.z.strictObject({duration:h.z.enum(["day","week","month","year"]),length:h.z.number().int().min(1).max(3660)}),lb=h.z.strictObject({internal_feature_id:h.z.uuid(),allowance:h.z.number().nonnegative().max(1e15).nullable(),expiry:ub.nullable()}),db=h.z.discriminatedUnion("type",[h.z.strictObject({type:h.z.literal("feature_grant"),grants:h.z.array(lb).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),h.z.strictObject({type:h.z.literal("free_product"),productId:td,duration:tt}),h.z.strictObject({type:h.z.literal("invoice_credits"),amount:h.z.number().positive().max(1e8),duration:tt,rollover:h.z.boolean(),productIds:rd})]),mb=h.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),nd=h.z.object({key:mb,name:h.z.string().trim().min(1).max(80),configuration:db}).strict(),id=h.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Qa=h.z.object({code:id,maxUses:h.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:h.z.boolean()}).strict(),ad=h.z.object({key:h.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:h.z.string().trim().min(1).max(80),rewardId:h.z.uuid(),redeemOn:h.z.enum(["customer_creation","checkout"]),receivedBy:h.z.enum(["referrer","all"]),maxRedemptions:h.z.number().int().min(1).max(1e6).nullable(),productIds:rd,excludeTrial:h.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),od={id:h.z.uuid(),projectId:h.z.uuid(),environmentId:h.z.uuid(),revision:h.z.number().int().nonnegative(),status:ed,createdAt:h.z.iso.datetime({offset:!0}),updatedAt:h.z.iso.datetime({offset:!0})},pb=nd.extend(od).strict(),fb=ad.safeExtend(od).strict(),gI=h.z.strictObject({id:h.z.uuid(),key:h.z.string(),name:h.z.string(),type:cb,status:ed}),bI=h.z.discriminatedUnion("action",[h.z.object({action:h.z.literal("save"),id:h.z.uuid().nullable(),revision:h.z.number().int().nonnegative(),input:nd}).strict(),h.z.object({action:h.z.enum(["activate","pause","resume","archive","delete"]),id:h.z.uuid(),revision:h.z.number().int().nonnegative()}).strict()]),yI=h.z.discriminatedUnion("action",[h.z.object({action:h.z.literal("save"),id:h.z.uuid().nullable(),revision:h.z.number().int().nonnegative(),input:ad}).strict(),h.z.object({action:h.z.enum(["activate","pause","resume","archive","delete"]),id:h.z.uuid(),revision:h.z.number().int().nonnegative()}).strict()]),sd=h.z.object({id:h.z.uuid(),rewardId:h.z.uuid(),programId:h.z.uuid().nullable(),customerId:h.z.uuid(),referrerId:h.z.uuid().nullable(),status:h.z.enum(["pending","applied","unavailable"]),result:h.z.record(h.z.string(),h.z.unknown()).nullable(),createdAt:h.z.iso.datetime({offset:!0})}).strict(),cd=h.z.object({code:id,requestId:h.z.uuid()}).strict(),ud=h.z.strictObject({redemptionId:h.z.uuid(),currency:Q,requestId:h.z.uuid(),accepted:h.z.literal(!0)}),hb=h.z.strictObject({type:h.z.literal("checkout"),orderId:h.z.uuid(),productVersionId:h.z.uuid(),currency:Q,duration:tt,renewalAmountMinor:h.z.number().int().positive().max(1e8),status:h.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:h.z.url().nullable()}),ld=h.z.discriminatedUnion("type",[hb,h.z.strictObject({type:h.z.literal("subscription"),operationId:h.z.uuid(),membershipId:h.z.uuid(),productVersionId:h.z.uuid(),currency:Q,duration:tt,renewalAmountMinor:h.z.number().int().positive().max(1e8),status:h.z.enum(["pending","running","applied","failed"])})]),dd=h.z.object({programId:h.z.uuid(),requestId:h.z.uuid()}).strict(),md=h.z.object({id:h.z.uuid(),programId:h.z.uuid(),code:Qa.shape.code,createdAt:h.z.iso.datetime({offset:!0})}).strict(),SI=h.z.object({rows:h.z.array(pb).max(100),nextCursor:h.z.uuid().nullable()}).strict(),_I=h.z.object({rows:h.z.array(fb).max(100),nextCursor:h.z.uuid().nullable()}).strict(),Ab=Qa.extend({id:h.z.uuid(),redemptions:h.z.number().int().nonnegative()}).strict(),gb=h.z.strictObject({id:h.z.uuid(),programId:h.z.uuid().nullable(),customerId:h.z.uuid().nullable(),referrerId:h.z.uuid().nullable(),code:h.z.string().nullable(),status:h.z.enum(["pending","triggered","applied"]),createdAt:h.z.iso.datetime({offset:!0})}),xI=h.z.object({codes:h.z.array(Ab).max(100),redemptions:h.z.array(gb).max(100),customers:h.z.record(h.z.uuid(),h.z.string()),codesCursor:h.z.uuid().nullable(),redemptionsCursor:h.z.uuid().nullable()}).strict(),II=h.z.discriminatedUnion("action",[h.z.object({action:h.z.literal("create"),rewardId:h.z.uuid(),revision:h.z.number().int().nonnegative(),input:Qa}).strict(),h.z.object({action:h.z.literal("remove"),rewardId:h.z.uuid(),revision:h.z.number().int().nonnegative(),codeId:h.z.uuid()}).strict()]);var u=require("zod");var E=require("zod"),It={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},rn=e=>new Set(e).size===e.length,Ya=E.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),bb=E.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),nn=E.z.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),yb=E.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),pd=E.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var fd=E.z.strictObject({id:E.z.uuid(),repo:bb,platform:E.z.enum(["github","gitlab","bitbucket"]),branches:E.z.array(nn).min(1).max(4).refine(rn),workflow:E.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:E.z.array(E.z.uuid()).min(1).max(4).refine(rn),include:E.z.array(pd).min(1).max(16),exclude:E.z.array(pd).max(16),methods:E.z.array(E.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(rn),maxAgeHours:E.z.number().int().min(1).max(720)}),hd=fd.extend({revision:E.z.number().int().positive()}),PI=E.z.strictObject({repository:fd,expectedRevision:E.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Ad=E.z.strictObject({repositoryId:E.z.uuid(),branch:nn}),Sb=E.z.array(Ya).max(It.keys).refine(rn),gd=E.z.strictObject({repository:hd.omit({keyIds:!0}),branch:nn,keys:Sb,keySetHash:E.z.string().regex(/^[a-f0-9]{64}$/)}),_b=E.z.strictObject({filePath:yb,startingLineNumber:E.z.number().int().min(1).max(1e7)}),Ja=E.z.strictObject({protocol:E.z.literal(1),repositoryId:E.z.uuid(),branch:nn,workflow:E.z.string().max(200),configurationRevision:E.z.number().int().positive(),keySetHash:E.z.string().regex(/^[a-f0-9]{64}$/),commit:E.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:E.z.uuid(),runNumber:E.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:E.z.number().int().min(1).max(1e4),scannerVersion:E.z.literal("1"),scannedAt:E.z.iso.datetime({offset:!0}),coverage:E.z.strictObject({complete:E.z.literal(!0),files:E.z.number().int().min(0).max(It.files),sourceBytes:E.z.number().int().min(0).max(It.sourceBytes),unresolvedCalls:E.z.number().int().min(0).max(1e6),unsupportedFiles:E.z.number().int().min(0).max(It.files)}),features:E.z.array(E.z.strictObject({key:Ya,refs:E.z.array(_b).max(It.referencesPerKey)})).max(It.keys)}).superRefine((e,t)=>{rn(e.features.map(r=>r.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((r,n)=>r+n.refs.length,0)>It.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Xa=E.z.strictObject({scanId:E.z.uuid(),commit:E.z.string(),receivedAt:E.z.string(),references:E.z.number().int().nonnegative(),removedReferences:E.z.number().int().nonnegative()}),xb=Xa.extend({repositoryId:E.z.uuid(),branch:nn,workflow:E.z.string(),digest:E.z.string(),configurationRevision:E.z.number().int().positive(),runNumber:E.z.number().int().positive(),runAttempt:E.z.number().int().positive(),scannedAt:E.z.string(),keySetHash:E.z.string(),coverage:Ja.shape.coverage}),Ib=E.z.strictObject({repositories:E.z.array(hd).max(It.repositories),scans:E.z.array(xb).max(It.repositories*It.branches)}),vb=E.z.strictObject({key:Ya,references:E.z.number().int().nonnegative(),coveredTargets:E.z.number().int().nonnegative(),expiredTargets:E.z.number().int().nonnegative(),uncertainTargets:E.z.number().int().nonnegative()}),CI=E.z.strictObject({available:E.z.boolean().default(!0),settings:Ib,expectedTargets:E.z.number().int().min(0).max(80),features:E.z.array(vb).max(2001),truncated:E.z.boolean()});var We=require("zod"),yd={customerId:We.z.uuid(),eventId:We.z.string().trim().min(1).max(200),grantId:We.z.uuid(),occurredAt:We.z.iso.datetime({offset:!0})},Sd=We.z.strictObject({...yd,productVersionId:We.z.uuid(),subscriptionId:We.z.string().trim().min(1).max(255)}),_d=We.z.strictObject({...yd,merchandiseId:We.z.uuid()}),xd=We.z.union([Sd,_d]),bd={id:We.z.uuid(),couponId:We.z.uuid(),status:We.z.literal("redeemed"),source:We.z.literal("merchant"),recordedAt:We.z.iso.datetime({offset:!0})},Id=We.z.union([Sd.extend(bd),_d.extend(bd)]);var U=require("zod");var za=U.z.strictObject({name:U.z.string().trim().min(1).max(255),memo:U.z.string().max(1e4).nullable().optional(),footer:U.z.string().max(1e4).nullable().optional(),net_terms_days:U.z.number().int().positive().nullable().optional()}),Pb=za.extend({id:U.z.string().min(1).max(255),created_at:U.z.number().nullable()}),vd=U.z.strictObject({items:U.z.array(Pb).max(50),nextCursor:U.z.uuid().nullable()}),jI=U.z.discriminatedUnion("action",[U.z.strictObject({action:U.z.literal("create"),requestId:U.z.uuid(),values:za}),U.z.strictObject({action:U.z.literal("update"),id:U.z.string().min(1).max(255),values:za}),U.z.strictObject({action:U.z.literal("delete"),id:U.z.string().min(1).max(255)})]),Pd=U.z.discriminatedUnion("action",[U.z.strictObject({action:U.z.literal("create"),requestId:U.z.uuid(),params:br}),U.z.strictObject({action:U.z.enum(["finalize","send","pay","void"]),requestId:U.z.uuid(),invoiceId:U.z.uuid()}),U.z.strictObject({action:U.z.literal("reissue"),requestId:U.z.uuid(),invoiceId:U.z.uuid(),params:Ia})]),eo=U.z.strictObject({id:U.z.uuid(),customerId:U.z.uuid(),providerInvoiceId:U.z.string().nullable(),status:U.z.enum(["draft","open","paid","void","uncollectible"]),currency:U.z.string(),totalMinor:U.z.string().regex(/^-?\d+$/),paidMinor:U.z.string().regex(/^\d+$/),refundedMinor:U.z.string().regex(/^\d+$/),hostedInvoiceUrl:U.z.url().nullable(),createdAt:U.z.number(),collectionMethod:U.z.enum(["send_invoice","charge_automatically"]).nullable()}),Cd=eo.extend({lines:U.z.array(U.z.strictObject({id:U.z.uuid(),description:U.z.string(),amountMinor:U.z.string().regex(/^-?\d+$/),netAmountMinor:U.z.string().regex(/^-?\d+$/),quantity:U.z.number().nullable(),periodStart:U.z.number().nullable(),periodEnd:U.z.number().nullable()})).max(1e3)}),an=U.z.strictObject({taskId:U.z.uuid(),status:U.z.enum(["ready","running","done","dead"]),invoice:eo.nullable(),errorCode:U.z.string().nullable()}),Od=U.z.strictObject({items:U.z.array(eo).max(50),nextCursor:U.z.uuid().nullable(),operations:U.z.array(an).max(50),operationsLimited:U.z.boolean()});var Cb=u.z.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),wd={scope:Ne,permissions:u.z.array(Cb),expiresAt:u.z.iso.datetime().nullable()},bv=u.z.discriminatedUnion("kind",[u.z.object({...wd,kind:u.z.literal("server"),keyId:u.z.string().min(1)}),u.z.object({...wd,kind:u.z.literal("customer"),customerId:u.z.string().min(1),identityKind:u.z.enum(["identified","guest"]),expiresAt:u.z.iso.datetime()})]),v=u.z.object({requestId:u.z.uuid(),scope:Ne}).strict(),Ob=wl.safeExtend({fingerprint:ii.optional()}).strict(),wb=v.extend({customer:xr,created:u.z.boolean()}),Eb=u.z.enum(["unassigned","unknown","scheduled","active","expired"]),yv=u.z.object({customerId:u.z.string().min(1),evaluatedAt:u.z.iso.datetime(),status:Eb,validity:Pi.nullable(),planVersion:Wo.nullable(),holdings:u.z.array(u.z.object({id:u.z.uuid(),planVersionId:u.z.uuid(),source:u.z.enum(["subscription","assignment","license","license_pool","entity_pool"])})).optional(),entitlements:u.z.array(u.z.object({featureId:u.z.string(),featureKey:u.z.string(),featureName:u.z.string(),type:u.z.enum(["boolean","metered"]),allowance:u.z.number().int().nonnegative().nullable(),used:u.z.number().finite().nonnegative(),remaining:u.z.number().finite().nonnegative().nullable(),allowed:u.z.boolean(),sources:u.z.array(u.z.object({holdingId:u.z.uuid(),planVersionId:u.z.uuid(),group:u.z.string(),kind:u.z.enum(["main","addon"]),allowance:u.z.number().nullable()})).optional()}))});function Ed(){return v.extend({offer:ra.nullable(),reason:sc.nullable()})}var _={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:eu,response:v.extend({message:u.z.object({messageId:u.z.uuid(),channel:Gr,acceptedAt:u.z.iso.datetime({offset:!0}),status:u.z.enum(["accepted","sending","completed","canceled"]),replayed:u.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:u.z.strictObject({messageId:u.z.uuid()}),response:v.extend({message:u.z.object({id:u.z.uuid(),channel:Gr,status:u.z.enum(["accepted","sending","completed","canceled"]),deliveries:u.z.array(u.z.object({id:u.z.uuid(),status:ru,attempts:u.z.number().int().nonnegative(),receipts:u.z.array(u.z.object({kind:nu,occurredAt:u.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Po,response:v.extend({installation:Ft})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Co,response:v.extend({installation:Ft})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:fn,response:v.extend({installation:Ft})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:u.z.strictObject({channel:Gr}),response:v.extend({preference:Ai})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:tu,response:v.extend({preference:Ai})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:u.z.strictObject({cursor:u.z.uuid().optional()}),response:v.extend({templates:vd})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),params:br}),response:v.extend({preview:va})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),requestId:u.z.uuid(),params:br}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:v.extend({operation:an})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),command:Pd}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:v.extend({operation:an})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),taskId:u.z.uuid()}),response:v.extend({operation:an})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),cursor:u.z.uuid().optional()}),response:v.extend({invoices:Od})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),invoiceId:u.z.uuid()}),response:v.extend({invoice:Cd})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Ad,response:v.extend({config:gd})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Ja,response:v.extend({receipt:Xa})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:u.z.strictObject({}),response:v.extend({payload:La})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:xl,response:v.merge(Il)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:vl,response:v.merge(Pl)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),sourceId:u.z.uuid()}),response:v.extend({balance:Vl})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),command:Bl}),response:v.extend({balance:Ha})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:u.z.strictObject({internal_feature_id:u.z.uuid(),customerId:u.z.uuid().optional(),entityId:u.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:v.extend({internal_feature_id:u.z.uuid(),config:Wi,model_markups:Rn})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),query:Un}),response:v.extend({usage:Vr})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),command:Gc}),response:v.extend({usage:Vr})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),command:qc}),response:v.extend({grant:la})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Lc,response:v.extend({grants:Bc})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:u.z.union(ml.options.map(e=>e.extend({customerId:u.z.uuid().optional(),customerToken:u.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/).optional()}))),response:v.extend({operation:pl})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:tl.extend({customerId:u.z.uuid().optional()}),response:v.extend({setup:ja})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:rl.extend({customerId:u.z.uuid().optional()}),response:v.extend({setup:ja})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Xu.safeExtend({customerId:u.z.uuid()}),response:v.extend({batch:Yr})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Zn.extend({customerId:u.z.uuid()}),response:v.extend({batch:Yr})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Zn.extend({customerId:u.z.uuid()}),response:v.extend({batch:Yr})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Zn.extend({customerId:u.z.uuid()}),response:v.extend({batch:Yr})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:u.z.discriminatedUnion("action",[Wn.options[0].extend({customerId:u.z.uuid()}),Wn.options[1].extend({customerId:u.z.uuid()}),Wn.options[2].extend({customerId:u.z.uuid()})]),response:v.extend({trial:Ea})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:zu.extend({customerId:u.z.uuid()}),response:v.extend({trial:Ea})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Jn,response:v.extend({subscriptions:ul})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Jn,response:v.extend({purchases:ll})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:ol,response:v.extend({conflicts:dl})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:sl,response:v.extend({resolution:cl})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:il,response:v.extend({verification:al})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Fu.safeExtend({...gr,customerId:u.z.uuid().optional()}),response:v.extend({quote:Hu})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:nr.extend({customerId:u.z.uuid().optional(),intent:u.z.enum(["confirm","cancel"]).optional()}),response:v.extend({operation:Pa})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:nr.extend({customerId:u.z.uuid().optional()}),response:v.extend({operation:Pa})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Ku.safeExtend({customerId:u.z.uuid().optional()}),response:v.extend({quote:Wu})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:nr.extend({customerId:u.z.uuid().optional(),intent:u.z.enum(["confirm","cancel"]).optional()}),response:v.extend({operation:Oa})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:nr.extend({customerId:u.z.uuid().optional()}),response:v.extend({operation:Oa})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Qu.safeExtend({customerId:u.z.uuid()}),response:v.extend({quote:Ju})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:nr.extend({customerId:u.z.uuid()}),response:v.extend({operation:Kn})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:nr.extend({customerId:u.z.uuid()}),response:v.extend({operation:Kn})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:xc,response:v.extend({controls:ia})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:hc,response:v.extend({prepared:gc})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:bc,response:v.extend({authorization:kn})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Cc,response:v.extend({coupons:Oc})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:yc,response:v.extend({authorization:kn})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:vc,response:v.extend({invoices:Pc})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Ic,response:v.extend({invoice:Dr})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:u.z.object({customerId:u.z.uuid(),command:_c}).strict(),response:v.extend({controls:ia})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:u.z.object({customerId:u.z.uuid(),command:Fl}).strict(),response:v.extend({entity:$l})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:u.z.strictObject({customerId:u.z.uuid().nullable(),query:Ql}),response:v.extend({analytics:Yl})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:u.z.object({customerId:u.z.uuid().nullable(),query:sr}).strict(),response:v.extend({analytics:Zl})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Jl,response:v.extend({batchId:u.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Xl,response:v.extend({batch:zl})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:su.extend({customerId:u.z.string().min(1).optional()}),response:v.extend({check:Xt})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:u.z.strictObject({kind:Ut,selector:u.z.discriminatedUnion("type",[u.z.strictObject({type:u.z.literal("resource"),id:u.z.uuid()}),u.z.strictObject({type:u.z.literal("version"),id:u.z.uuid()})]),customerId:u.z.string().min(1).optional()}),response:v.extend({content:Sa})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Ul,response:v.extend({paywall:ql})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:u.z.strictObject({...gr,selector:gl,customerId:u.z.string().min(1).optional(),commerce:hr,requirement:Mt.optional()}),response:v.extend({offering:bl,candidates:u.z.array(ha).max(20),availability:u.z.array(u.z.strictObject({productVersionId:u.z.uuid(),available:u.z.boolean(),reason:u.z.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:Xt.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:u.z.object({customerId:u.z.uuid().optional(),entityId:u.z.uuid().optional()}).strict(),response:v.extend({holdings:Hc})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:u.z.object({customerId:u.z.uuid().optional(),query:Wc}).strict(),response:v.extend({ledger:Qc})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Vc.extend({customerId:u.z.uuid().optional()}),response:v.extend({detail:Fc})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:da.safeExtend({customerId:u.z.uuid().optional()}),response:v.extend({statement:$c})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:u.z.object({customerId:u.z.uuid().optional(),command:Lr.options[0]}).strict(),response:v.extend({quote:Nc})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),command:u.z.union([u.z.strictObject({eventName:u.z.string().min(1),quantity:Z.optional(),properties:Ue.optional(),entityId:u.z.uuid().optional(),idempotencyKey:u.z.string().min(1).max(120)}),u.z.strictObject({internal_feature_id:u.z.uuid(),quantity:Z.optional(),properties:Ue.optional(),entityId:u.z.uuid().optional(),idempotencyKey:u.z.string().min(1).max(120)})])}),response:v.extend({receipts:u.z.array(Br).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:u.z.object({customerId:u.z.uuid(),command:Lr.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:v.extend({receipt:Br})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:cd,response:v.extend({redemption:sd})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:dd,response:v.extend({referralCode:md})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:ud,response:v.extend({checkout:ld})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Jc,response:v.extend({seats:fa})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Xc,response:v.extend({seats:fa})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:Ob,response:wb},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Va,response:v.extend({customer:xr})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Rl,response:v.extend(Tl.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:jl,response:v.extend(El.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:u.z.object({customerId:u.z.uuid()}).strict(),response:v.extend({customerToken:u.z.string().min(1),expiresAt:u.z.iso.datetime(),sessionId:u.z.uuid()})},renewSession:{method:"POST",path:"customer-sessions/renew",permission:"sessions:create",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),customerToken:u.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/)}),response:v.extend({customerToken:u.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:u.z.uuid(),expiresAt:u.z.iso.datetime()})},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:u.z.strictObject({customerId:u.z.uuid(),sessionId:u.z.uuid().optional()}),response:v.extend({revoked:u.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:u.z.strictObject({guestToken:u.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ii.optional()}),response:v.extend({customerId:u.z.uuid(),guestToken:u.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:u.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:u.z.strictObject({guestToken:u.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:v.extend({customerId:u.z.uuid(),customerToken:u.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:u.z.uuid(),expiresAt:u.z.iso.datetime()})},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:u.z.strictObject({guestToken:u.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:u.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:u.z.uuid()}),response:v.extend({customer:xr,switched:u.z.boolean(),replayed:u.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:u.z.strictObject({code:u.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:u.z.uuid()}),response:Ed()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:u.z.object({}).strict(),response:v.extend({offers:u.z.array(ra)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:u.z.object({customerId:u.z.string().min(1).max(255).optional(),couponId:u.z.uuid(),...gr,requestId:u.z.uuid(),couponContentDigest:u.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Ed()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:xd,response:v.extend({receipt:Id})}},Sv={sendMessage:_.sendMessage,readMessage:_.readMessage,bindPushInstallation:_.bindPushInstallation,readPushInstallation:_.readPushInstallation,updatePushAddress:_.updatePushAddress,readMessagingPreference:_.readMessagingPreference,setMessagingPreference:_.setMessagingPreference,listInvoiceTemplates:_.listInvoiceTemplates,previewInvoice:_.previewInvoice,createInvoice:_.createInvoice,manageInvoice:_.manageInvoice,readInvoiceOperation:_.readInvoiceOperation,listInvoices:_.listInvoices,getInvoice:_.getInvoice,getCodeReferenceConfig:_.getCodeReferenceConfig,submitCodeReferences:_.submitCodeReferences,getFeatures:_.getFeatures,evaluateFeatures:_.evaluateFeatures,trackEvents:_.trackEvents,setupPayment:_.setupPayment,readPaymentSetup:_.readPaymentSetup,previewSubscriptionBatch:_.previewSubscriptionBatch,confirmSubscriptionBatch:_.confirmSubscriptionBatch,readSubscriptionBatch:_.readSubscriptionBatch,abandonSubscriptionBatch:_.abandonSubscriptionBatch,manageSubscriptionTrial:_.manageSubscriptionTrial,readSubscriptionTrial:_.readSubscriptionTrial,listSubscriptions:_.listSubscriptions,listPurchases:_.listPurchases,listSubscriptionConflicts:_.listSubscriptionConflicts,retrySubscriptionConflict:_.retrySubscriptionConflict,readAiPricing:_.readAiPricing,readUsage:_.readUsage,setUsage:_.setUsage,previewRefund:_.previewRefund,refund:_.refund,readRefund:_.readRefund,previewUpdate:_.previewUpdate,update:_.update,readSubscriptionUpdate:_.readSubscriptionUpdate,restoreNativePurchase:_.restoreNativePurchase,verifySubscriptions:_.verifySubscriptions,previewAttach:_.previewAttach,attach:_.attach,readSubscriptionOperation:_.readSubscriptionOperation,manageBalanceGrant:_.manageBalanceGrant,readBalanceSource:_.readBalanceSource,adjustBalance:_.adjustBalance,listBalanceGrants:_.listBalanceGrants,readBillingControls:_.readBillingControls,prepareBillingAuthorization:_.prepareBillingAuthorization,confirmBillingAuthorization:_.confirmBillingAuthorization,setBillingCoupons:_.setBillingCoupons,revokeBillingAuthorization:_.revokeBillingAuthorization,listBillingInvoices:_.listBillingInvoices,confirmBillingAdjustment:_.confirmBillingAdjustment,manageBillingLimits:_.manageBillingLimits,createCustomer:_.createCustomer,getCustomer:_.getCustomer,listCustomers:_.listCustomers,updateCustomer:_.updateCustomer,createSession:_.createSession,renewSession:_.renewSession,revokeSessions:_.revokeSessions,createGuestCustomer:_.createGuestCustomer,resumeGuestSession:_.resumeGuestSession,claimGuestCustomer:_.claimGuestCustomer,checkEntitlement:_.checkEntitlement,resolveOffering:_.resolveOffering,resolveContent:_.resolveContent,resolvePaywall:_.resolvePaywall,readHoldings:_.readHoldings,readLedger:_.readLedger,readBillingInvoice:_.readBillingInvoice,readCreditStatement:_.readCreditStatement,quoteBalance:_.quoteBalance,trackUsage:_.trackUsage,mutateBalance:_.mutateBalance,manageUsageEntity:_.manageUsageEntity,readUsageAnalytics:_.readUsageAnalytics,readCreditAnalytics:_.readCreditAnalytics,submitUsageBatch:_.submitUsageBatch,readUsageBatch:_.readUsageBatch,listOffers:_.listOffers,grantOffer:_.grantOffer,recordCouponRedemption:_.recordCouponRedemption,redeemCoupon:_.redeemCoupon,redeemReward:_.redeemReward,createReferralCode:_.createReferralCode,claimRewardProduct:_.claimRewardProduct,readSeats:_.readSeats,manageSeat:_.manageSeat};var B=class extends Error{constructor(r,n,i,o,a){super(n);Ot(this,"code",r);Ot(this,"status",i);Ot(this,"requestId",o);Ot(this,"retryable");Ot(this,"recovery");Ot(this,"retryAfterSeconds");Ot(this,"reason");this.name="IndianaError",this.reason=a?.reason;let c=hn(r,i??0,{...a,retryAfter:a?.retryAfterSeconds===void 0?void 0:String(a.retryAfterSeconds)});this.retryable=c.retryable,this.recovery=c.recovery,this.retryAfterSeconds=c.retryAfterSeconds}};var on=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new B("INVALID_STATE","Installation sequence exhausted");return e+1},jb=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function jt(e,t){return e.transaction(r=>{if(!Number.isSafeInteger(r.identitySeq)||r.identitySeq<0||!Number.isSafeInteger(r.addressSeq)||r.addressSeq<0||r.detachSeq!==null&&(!Number.isSafeInteger(r.detachSeq)||r.detachSeq<1||r.detachSeq>r.identitySeq))throw new B("INVALID_STATE","Installation journal is invalid");return t({...r})})}function jd(e,t,r){let n=null,i=0,o=0,a=0,c=Promise.resolve();if(e&&(!r||Ne.parse(e.scope).projectId!==r.projectId||e.scope.environment!==r.environment))throw new B("SCOPE_MISMATCH","Push installation belongs to another scope");let d=()=>{if(!e)throw new B("NOT_CONFIGURED","Configure this client's native Push host first");return e},p=G=>{if(G!==i)throw new B("IDENTITY_CHANGED","Identity changed during Push operation")};async function y(G){let L=d();if(!L.sha256&&!globalThis.crypto?.subtle)throw new B("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let z=L.sha256?await L.sha256(Uint8Array.from(G,xe=>xe.charCodeAt(0))):await jb(G);if(!/^[a-f0-9]{64}$/.test(z))throw new B("INVALID_STATE","Push credential digest is invalid");return z}function j(G){let L=Ft.parse(G);if(L.installationId.toLowerCase()!==d().installationId.toLowerCase())throw new B("INVALID_RESPONSE","Push response belongs to another installation");return L}async function $(G,L){let z=d(),xe={installationId:z.installationId,publicKey:z.publicKey,issuedAt:new Date().toISOString(),...L},ce=await z.sign(jo(G,z.scope,xe));return{...xe,signature:ce}}async function ie(){let G=d(),L=i,z=n,xe=jt(G,He=>He),ce;if(xe.detachSeq!==null){let He=xe.detachSeq,Te=Oo.parse(await $("detach",{sequence:He,platform:G.platform}));try{let se=await t.request("push/installations/detach",{...G.scope,...Te},"POST",{installationDetach:!0});if(!se||typeof se!="object"||!("installation"in se))throw new B("INVALID_RESPONSE","Push detach acknowledgement is invalid");let ct=j(se.installation);if(ct.bound||ct.identitySeq!==He)throw new B("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(se){if(se instanceof B&&se.status===404)ce=se;else if(!(se instanceof B)||se.status!==412)throw se}ce||jt(G,se=>({...se,detachSeq:se.detachSeq===He?null:se.detachSeq}))}if(p(L),!z){if(ce)throw ce;return null}let je=_.bindPushInstallation,et=je.request.parse(await $("bind",{sequence:a,platform:G.platform,credentialDigest:await y(z)}));p(L);let st=je.response.parse(await t.request(je.path,et));p(L);let Rt=j(st.installation);if(!Rt.bound||Rt.identitySeq!==a)throw new B("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return ce&&xe.detachSeq!==null&&a>xe.detachSeq&&jt(G,He=>({...He,detachSeq:He.detachSeq===xe.detachSeq?null:He.detachSeq})),Rt}async function ye(){d();let G=i,L=n;if(!L)throw new B("NOT_IDENTIFIED","Identify before reading this installation");let z=_.readPushInstallation,xe=z.request.parse(await $("read",{credentialDigest:await y(L)}));p(G);let ce=z.response.parse(await t.request(z.path,xe));return p(G),j(ce.installation)}function R(G=ie){let L=c.catch(()=>{}).then(G);return c=L,L.catch(z=>{try{e?.onError?.(z instanceof Error?z:new Error("Push synchronization failed"))}catch{}}),L}async function Re(G,L,z){let xe=d(),ce=L.identity,je=L.observation,et=n;if(p(ce),je!==o)throw new B("INVALID_STATE","Push observation changed during recovery");if(!et)throw new B("NOT_IDENTIFIED","Identify before recovering a Push address");if(!G.connectionId||!G.kind||!G.token||!["granted","provisional"].includes(G.permission))throw new B("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await R(async()=>{if(p(ce),await ie(),p(ce),je!==o)throw new B("INVALID_STATE","Push observation changed during recovery");let st=jt(xe,ct=>z?ct:{...ct,addressSeq:on(ct.addressSeq)}),He=await $(z?"recovery_confirm":"recovery_request",{...G,sequence:st.addressSeq,credentialDigest:await y(et),...z?{challenge:z}:{}}),Te=z?Eo.parse(He):wo.parse(He);if(p(ce),je!==o)throw new B("INVALID_STATE","Push observation changed during recovery");let se=await t.request(`push/installations/recovery/${z?"confirm":"request"}`,Te);if(p(ce),je!==o||jt(xe,ct=>ct).addressSeq!==st.addressSeq)throw new B("INVALID_STATE","Push observation changed during recovery");if(z){let ct=_.updatePushAddress.response.parse(se),ut=j(ct.installation);if(!ut.bound||ut.identitySeq!==a||ut.addressSeq!==st.addressSeq||ut.connectionId!==G.connectionId||ut.addressStatus!=="active")throw new B("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return ut}if(!se||typeof se!="object"||!("recovery"in se))throw new B("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return hi.parse(se.recovery)})}return{recoveryObserver(){d();let G={identity:i,observation:++o};return{async request(L){return hi.parse(await Re(L,G))},async confirm(L,z){return Ft.parse(await Re(z,G,L))}}},identify(G){if(!e)return;a=jt(e,z=>({...z,identitySeq:on(z.identitySeq)})).identitySeq,n=G,i++,o++},reset(){if(e)try{jt(e,G=>{let L=on(G.identitySeq);return{...G,identitySeq:L,detachSeq:L}})}finally{n=null,i++,o++}},start(){e&&R()},async sync(){return await R()},read:ye,async recover(){let G=d(),L=i,z=a;return o++,await R(async()=>{p(L);let xe=await ye();return p(L),a=jt(G,je=>{if(je.identitySeq!==z)throw new B("IDENTITY_CHANGED","A newer installation intent exists");return{...je,identitySeq:on(Math.max(je.identitySeq,xe.identitySeq)),addressSeq:Math.max(je.addressSeq,xe.addressSeq)}}).identitySeq,await ie()})},tokenObserver(){d();let G=++o,L=i;return async z=>{if(G!==o||L!==i)return null;let xe=d(),ce=n;if(!ce)throw new B("NOT_IDENTIFIED","Identify before registering a Push token");if(await R(),p(L),G!==o)return null;let je=jt(xe,He=>({...He,addressSeq:on(He.addressSeq)})),et=_.updatePushAddress,st=et.request.parse(await $("address",{...z,sequence:je.addressSeq,credentialDigest:await y(ce)}));if(p(L),G!==o)return null;let Rt=et.response.parse(await t.request(et.path,st));return p(L),j(Rt.installation)}}}}function ge(e){return typeof e=="string"?e:String(e)}var Rb=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Tb(e){return e.replace(Rb,"$1\uFFFD")}function io(e,t){if(typeof e!="object"||e==null){let r="";throw r+="The provided value is not an object",new TypeError(r)}return e}function Ld(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let r=t.call(e);if(!r||typeof r!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return r}}function Rd(e){let t;if(Array.isArray(e)){let r=e.map(ge);if(r.length===2)return r}else if((t=Ld(e))!=null){let r=io(t.next()),n=io(t.next());if(!r.done&&!n.done)return[ge(r.value),ge(n.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Td="0123456789ABCDEF",kb=/(?:%[0-9A-Fa-f]{2})+/g;function vt(e){return`%${Td[e>>4&15]}${Td[15&e]}`}function Bd(e,t,r=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?r&&e===32?"+":t(e)?vt(e):String.fromCharCode(e):e<=2047?vt(192|e>>6)+vt(128|63&e):e<=65535?vt(224|e>>12)+vt(128|e>>6&63)+vt(128|63&e):vt(240|e>>18)+vt(128|e>>12&63)+vt(128|e>>6&63)+vt(128|63&e)}function ao(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function oo(e,t=!1){let r=0;for(;r<e.length;r++){let n=e.charCodeAt(r);if(n===37||t&&n===43)break}return r===e.length?e:(t?e.replace(/\+/g," "):e).replace(kb,n=>{try{return decodeURIComponent(n)}catch{return"\uFFFD".repeat(n.length/3)}})}function un(e){return e<=31||e>126}function Db(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return un(e)}}function fo(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return un(e)}}function Nb(e){return fo(e)||e===39}function so(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return fo(e)}}function li(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return so(e)}}function kd(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(r){switch(r){case 36:case 37:case 38:case 43:case 44:return!0;default:return li(r)}})(e)}}function Vd(e,t){return Bd(e=e||0,t)}function Pt(e,t,r=!1){let n=0;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o>=128||r&&o===32||t(o))break}if(n===e.length)return e;let i=e.slice(0,n);for(;n<e.length;n++){let o=e.charCodeAt(n),a=o;if(o>=55296&&o<=56319&&n+1<e.length){let c=e.charCodeAt(n+1);c>=56320&&c<=57343&&(a=(o-55296<<10)+c-56320+65536,n++)}i+=Bd(a,t,r)}return i}function ho(e){let t=[],r=0,n=0;for(;n<=e.length;){if(n=e.indexOf("&",r),n<0&&(n=e.length),n!==r){let i=e.slice(r,n),o=i.indexOf("=");o<0&&(o=i.length),t.push([oo(i.slice(0,o),!0),oo(i.slice(o+1),!0)])}if(r=n+1,n===e.length)break}return t}function co(e){let t="";for(let r=0;r<e.length;r++){let n=Pt(e[r][0],kd,!0),i=Pt(e[r][1],kd,!0);t+=r!==0?`&${n}=${i}`:`${n}=${i}`}return t}var Mb=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],Ub=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],qb=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],Lb=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function Bb(e){for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(r>65535&&t++,r<=32||r===37||r===127||r>=55296&&r<=57343||r>=128&&r<=159||r>=64976&&r<=65007||!(65534&~r)||r===65533)return!0}return!1}var[Vb,Fb,$b,Dd]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,r,n]){return[t,r.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(n),i=>i.charCodeAt(0))]});function Gb(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function Fd(e,t){for(let r=0;r<e.length;r+=2)if(t>=e[r]&&t<=e[r+1])return!0;return!1}function sn(e,t){let[r,n,i]=e,o=t>>8;for(let d=0;d<r.length;d+=2)if(o>=r[d]&&o<=r[d+1])return!0;let a=n.indexOf(o);if(a<0)return!1;let c=255&t;return!!(i[32*a+(c>>3)]&1<<(7&c))}function Hb(e){let t=Array.from(e,r=>r.codePointAt(0));for(let r=0;r<t.length;r++){let n=t[r];if(n!==8204&&n!==8205||r>0&&Fd(Lb,t[r-1]))continue;if(n===8205)return!1;let i=r-1;for(;i>=0&&sn(Dd,t[i]);)i--;let o=r+1;for(;o<t.length&&sn(Dd,t[o]);)o++;if(!(i>=0&&o<t.length&&sn(Fb,t[i])&&sn($b,t[o])))return!1}return!0}var Kb=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,Zb=/\p{Script=Latin}/u;function Wb(e){return!Kb.test(e)||!Zb.test(e)}var Bt=36,si=1,uo=26,Qb=38,Yb=700,Jb=72,Xb=128,zb=2147483647;function Nd(e){return String.fromCharCode(e+22+75*+(e<26))}function ey(e,t,r){let n=0;for(e=r?Math.floor(e/Yb):e>>1,e+=Math.floor(e/t);e>(Bt-si)*uo>>1;n+=Bt)e=Math.floor(e/(Bt-si));return Math.floor(n+(Bt-si+1)*e/(e+Qb))}function ty(e){let t=Array.from(e,d=>d.codePointAt(0)),r="",n=0;for(let d=0;d<t.length;d++){let p=t[d];p<128&&(r+=String.fromCharCode(p),n++)}let i=n;i&&(r+="-");let o=Xb,a=0,c=Jb;for(;n<t.length;){let d=zb;for(let p=0;p<t.length;p++){let y=t[p];y>=o&&y<d&&(d=y)}a+=(d-o)*(n+1),o=d;for(let p=0;p<t.length;p++){let y=t[p];if(y<o&&a++,y===o){let j=a;for(let $=Bt;;$+=Bt){let ie=$<=c?si:$>=c+uo?uo:$-c;if(j<ie)break;r+=Nd(ie+(j-ie)%(Bt-ie)),j=Math.floor((j-ie)/(Bt-ie))}r+=Nd(j),c=ey(a,n+1,n===i),a=0,n++}}a++,o++}return r}function to(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let r=0;for(let n=0;n<e.length;n++){let i=ao(e.charCodeAt(n));if(i>=t||i<0)return-1;r=r*t+i}return r}function Md(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function $d(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Gd(e){return e.length===2&&$d(e.codePointAt(0),e.codePointAt(1))}function Ud(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function we(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Hd(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function lo(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(n){let i=[0,0,0,0,0,0,0,0],o=null,a=0,c=0,d=Array.from(n,p=>p.codePointAt(0));if(d[c]===58){if(d[c+1]!==58)return null;c+=2,a++,o=a}for(;c<d.length;){if(a===8)return null;if(d[c]===58){if(o!==null)return null;c++,a++,o=a;continue}let p=0,y=0,j=0;for(;j<4&&(p=ao(d[c]))>=0;)y=(y<<4)+p,c++,j++;if(d[c]===46){if(j===0||a>6)return null;c-=j;let $=0;for(;d[c]!==void 0;){let ie=0;if($>0)if(d[c]===46&&$<4)c++;else return null;if(d[c]==null||d[c]<48||d[c]>57)return null;for(;d[c]>=48&&d[c]<=57;){if(ie=10*ie+ao(d[c]),ie>255)return null;c++}i[a]=256*i[a]+ie,$++,$%2==0&&a++}if($!==4)return null;break}else if(d[c]===58){if(d[++c]===void 0)return null}else if(d[c]!==void 0)return null;i[a]=y,a++}if(o!==null){let p=a-o;for(a=7;a!==0&&p>0;){let y=i[o+p-1];i[o+p-1]=i[a],i[a]=y,a--,p--}}else if(o===null&&a!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(n){return Ud(n)?null:Pt(n,un)})(e);{let r=(function(i){let o=!1,a=!1;for(let d=0;d<i.length;d++){let p=i.charCodeAt(d);if(p<=32||p===37||p===127)return null;if(p>=128){o=!0;break}p>=65&&p<=90&&(a=!0)}if(!o)return i!==""?a?i.toLowerCase():i:null;if((function(p){for(let y of p){let j=y.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(y)&&!Fd(Mb,j)||sn(Vb,j))return!0}return!1})(i))return null;let c=(i=(function(p){let y="";for(let j of p){let $=j.codePointAt(0);if($!==8204&&$!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(j))continue;let ie=Gb(j,$);if(ie){y+=ie;continue}let ye=Ub.indexOf($);y+=ye<0?j:qb[ye]}return y})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let d=0;d<c.length;d++){let p=c[d];if(p==="")continue;let y=/[^\0-\x7f]/.test(p);if(Bb(p)||y&&(/^\p{Mark}/u.test(p)||!Hb(p)||!Wb(p)||p.startsWith("xn--")))return null;y&&(c[d]=`xn--${ty(p)}`)}return(i=c.join("."))!==""?i:null})(e.indexOf("%")===-1?e:oo(e));return r===null||Ud(r)?null:(function(i){let o=i.length,a=i.lastIndexOf(".",o-2)+1;if(i.charCodeAt(o-1)===46&&o--,o<=a)return!1;if(to(i.slice(a,o))>=0)return!0;for(;a<o;a++){let c=i.charCodeAt(a);if(c<48||c>57)return!1}return!0})(r)?(function(i){let o=i.split("."),a=o.length;if(o[a-1]||a--,a>4)return null;let c=0;for(let p=0;p<a-1;p++){let y=to(o[p]);if(y<0||y>255)return null;c+=y*(1<<8*(3-p))}let d=to(o[a-1]);return d<0||d>=256**(5-a)?null:(c+=d,c)})(r):r}}function mo(e){return typeof e=="number"?(function(r){let i="";return i+=`${(r>>>24&255).toString(10)}.`,i+=`${(r>>>16&255).toString(10)}.`,i+=`${(r>>>8&255).toString(10)}.`,i+=(r&255).toString(10),i})(e):Array.isArray(e)?`[${(function(r){let n=(function(c){let d=-1,p=-1,y=1,j=0;for(let $=0;$<c.length;++$)c[$]!==0?(j>y&&(d=p,y=j),p=-1,j=0):(p===-1&&(p=$),++j);return j>y?p:d})(r),i="",o=!1;for(let a=0;a<=7;++a)if(!(o&&r[a]===0)){if(o&&(o=!1),n===a){i+=a===0?"::":":",o=!0;continue}i+=r[a].toString(16),a!==7&&(i+=":")}return i})(e)}]`:e}function Kd(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(r){return/^[A-Za-z]:$/u.test(r)})(e.path[0]))&&e.path.pop()}function Zd(e){return e.username!==""||e.password!==""}function ro(e){return e.host===null||e.host===""||e.scheme==="file"}var f=0,x="",te="",fe=null,I,ci=!1,ui=!1,cr=!1,Ee;function it(e,t,r,n){t||(e=(function(a){let c=0,d=a.length;for(;c<d&&!(a.charCodeAt(c)>32);++c);for(;d>c&&!(a.charCodeAt(d-1)>32);--d);return a.substring(c,d)})(e)),e=(function(a){let c=0;for(;c<a.length;c++){let p=a.charCodeAt(c);if(p===9||p===10||p===13)break}if(c===a.length)return a;let d=a.slice(0,c);for(;c<a.length;c++){let p=a.charCodeAt(c);p!==9&&p!==10&&p!==13&&(d+=a[c])}return d})(e),f=0,x=e,te="",fe=r||null,I=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},ci=!1,ui=!1,cr=!1,Ee=n||0;let i=ry;switch(n){case 3:case 4:i=di;break;case 5:i=go;break;case 6:i=ur;break;case 7:i=Vt;break;case 8:i=Ct}return i(w(e,f))!==1?I:null}function D(e,t){return f+=f===e?At(t):1,f<=x.length}function w(e,t){return t<e.length?e.codePointAt(t):void 0}function At(e){return e!=null&&e>65535?2:1}function Wd(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var ry=e=>{let t=f;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let r=f+1;for(e=x.charCodeAt(r);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)r++,e=x.charCodeAt(r);return te=x.slice(f,r).toLowerCase(),f=r,ny(r<x.length?e:void 0)}else return Ee?1:(--f,D(t,e)?Qd(w(x,f)):0)},ny=e=>{let t=f;if(e===58){if(Ee){if(we(I.scheme)!==we(te))return 0;if((Zd(I)||I.port!==null)&&te==="file")return 0;if(I.scheme==="file"&&I.host==="")return 0}return I.scheme=te,Ee?(I.port===Hd(I.scheme)&&(I.port=null),0):(te="",I.scheme==="file"?D(t,e)?bo(w(x,f)):0:we(I.scheme)&&fe!==null&&fe.scheme===I.scheme?D(t,e)?iy(w(x,f)):0:we(I.scheme)?D(t,e)?oy(w(x,f)):0:w(x,f+1)===47?(f++,D(t,e)?ay(w(x,f)):0):(I.path=[""],I.opaquePath=!0,D(t,e)?Jd(w(x,f)):0))}else return Ee?1:(te="",f=-1,D(t,e)?Qd(w(x,f)):0)},Qd=e=>{let t=f;return fe===null||fe.opaquePath&&e!==35?1:fe.opaquePath&&e===35?(I.scheme=fe.scheme,I.path=fe.path.slice(),I.opaquePath=fe.opaquePath,I.query=fe.query,I.fragment="",D(t,e)?Ct(w(x,f)):0):fe.scheme==="file"?(f--,D(t,e)?bo(w(x,f)):0):(f--,D(t,e)?Ao(w(x,f)):0)},iy=e=>{let t=f;return e===47&&w(x,f+1)===47?(++f,D(t,e)?pi(w(x,f)):0):(f--,D(t,e)?Ao(w(x,f)):0)},ay=e=>{let t=f;return e===47?D(t,e)?Pr(w(x,f)):0:(f--,D(t,e)?gt(w(x,f)):0)},Ao=e=>{let t=f;return I.scheme=fe.scheme,e===47||we(I.scheme)&&e===92?D(t,e)?qd(w(x,f)):0:(I.username=fe.username,I.password=fe.password,I.host=fe.host,I.port=fe.port,I.path=fe.path.slice(),I.query=fe.query,e===63?(I.query="",D(t,e)?Vt(w(x,f)):0):e===35?(I.fragment="",D(t,e)?Ct(w(x,f)):0):e!=null?(I.query=null,I.path.pop(),f--,D(t,e)?gt(w(x,f)):0):D(t,e)?Ao(w(x,f)):0)},qd=e=>{let t=f;return we(I.scheme)&&(e===47||e===92)?D(t,e)?pi(w(x,f)):0:e===47?D(t,e)?Pr(w(x,f)):0:(I.username=fe.username,I.password=fe.password,I.host=fe.host,I.port=fe.port,f--,D(t,e)?gt(w(x,f)):0)},oy=e=>{let t=f;return e===47&&w(x,f+1)===47?f++:f--,D(t,e)?pi(w(x,f)):0},pi=e=>{let t=f;return e!==47&&e!==92?(f--,D(t,e)?Pr(w(x,f)):0):D(t,e)?pi(w(x,f)):0},Pr=e=>{let t=f;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!we(I.scheme))){let r=f+At(e);for(;r<x.length;){let n=w(x,r);if(n==null||n===64||n===35||n===47||n===63||n===92&&we(I.scheme))break;r+=At(n)}return te+=x.slice(f,r),f=r-1,D(t,e)?Pr(w(x,f)):0}if(e===64){ci&&(te=`%40${te}`),ci=!0;for(let r=0;r<te.length;r++){let n=te.codePointAt(r);if(n===58&&!ui){ui=!0;continue}let i=Vd(n,li);ui?I.password+=i:I.username+=i,n!=null&&n>65535&&r++}return te="",D(t,e)?Pr(w(x,f)):0}else return e==null||e===35||e===47||e===63||e===92&&we(I.scheme)?ci&&te===""?1:(f-=te.length+1,te="",D(t,e)?di(w(x,f)):0):(te+=Wd(e),D(t,e)?Pr(w(x,f)):0)},di=e=>{let t=f;if(Ee&&I.scheme==="file")return f--,D(t,e)?yo(w(x,f)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!we(I.scheme))){let r=f+At(e);for(e===91?cr=!0:e===93&&(cr=!1);r<x.length;){let n=w(x,r);if(n==null||!cr&&n===58||n===35||n===47||n===63||n===92&&we(I.scheme))break;n===91?cr=!0:n===93&&(cr=!1),r+=At(n)}return te+=x.slice(f,r),f=r-1,D(t,e)?di(w(x,f)):0}else if(e===58&&!cr){if(te===""||Ee===4)return 1;let r=lo(te,!we(I.scheme));return r===null?1:(I.host=mo(r),te="",D(t,e)?go(w(x,f)):0)}else if(e==null||e===35||e===47||e===63||e===92&&we(I.scheme)){if(f--,we(I.scheme)&&te==="")return 1;if(Ee&&te===""&&(Zd(I)||I.port!==null))return 1;let r=lo(te,!we(I.scheme));return r===null?1:(I.host=mo(r),te="",Ee?0:D(t,e)?ur(w(x,f)):0)}else return te+=Wd(e),D(t,e)?di(w(x,f)):0},go=e=>{let t=f;if(e!=null&&e>=48&&e<=57){let r=f+1;for(;r<x.length;){let n=x.charCodeAt(r);if(n<48||n>57)break;r++}return te+=x.slice(f,r),f=r-1,D(t,e)?go(w(x,f)):0}else if(Ee||e==null||e===35||e===47||e===63||e===92&&we(I.scheme)){if(te!==""){let r=parseInt(te,10);if(r>65535)return 1;if(I.port=r===Hd(I.scheme)?null:r,te="",Ee)return 0}return Ee?1:(f--,D(t,e)?ur(w(x,f)):0)}else return 1};function Yd(e,t){let r=e.length-t;if(r<2)return!1;if($d(w(e,t),w(e,t+1))){if(r===2)return!0;{let n=w(e,t+2);return n===47||n===92||n===63||n===35}}else return!1}var bo=e=>{let t=f;return I.scheme="file",I.host="",e===47||e===92?D(t,e)?sy(w(x,f)):0:fe?.scheme==="file"?(I.host=fe.host,I.path=fe.path.slice(),I.opaquePath=fe.opaquePath,I.query=fe.query,e===63?(I.query="",D(t,e)?Vt(w(x,f)):0):e===35?(I.fragment="",D(t,e)?Ct(w(x,f)):0):e!=null?(I.query=null,Yd(x,f)?I.path=[]:Kd(I),f--,D(t,e)?gt(w(x,f)):0):D(t,e)?bo(w(x,f)):0):(f--,D(t,e)?gt(w(x,f)):0)},sy=e=>{let t=f;return e===47||e===92?D(t,e)?yo(w(x,f)):0:(fe!==null&&fe.scheme==="file"&&(!Yd(x,f)&&(function(n){if(n.length===2){let i=n.codePointAt(0),o=n.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&o===58}else return!1})(fe.path[0])&&I.path.push(fe.path[0]),I.host=fe.host),f--,D(t,e)?gt(w(x,f)):0)},yo=e=>{let t=f;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let r=f+At(e);for(;r<x.length;){let n=w(x,r);if(n==null||n===47||n===92||n===63||n===35)break;r+=At(n)}return te+=x.slice(f,r),f=r-1,D(t,e)?yo(w(x,f)):0}else if(e==null||e===47||e===92||e===63||e===35){if(f--,!Ee&&Gd(te))return D(t,e)?gt(w(x,f)):0;if(te==="")return I.host="",Ee?0:D(t,e)?ur(w(x,f)):0;{let r=lo(te,!we(I.scheme));return r===null?1:(r==="localhost"&&(r=""),I.host=mo(r),te="",Ee?0:D(t,e)?ur(w(x,f)):0)}}return 1},ur=e=>{let t=f;return we(I.scheme)?(e!==92&&e!==47&&f--,D(t,e)?gt(w(x,f)):0):!Ee&&e===63?(I.query="",D(t,e)?Vt(w(x,f)):0):!Ee&&e===35?(I.fragment="",D(t,e)?Ct(w(x,f)):0):e!=null?(e!==47&&f--,D(t,e)?gt(w(x,f)):0):(Ee&&I.host===null&&I.path.push(""),D(t,e)?ur(w(x,f)):0)},gt=e=>{let t=f;if(e!=null&&e!==47&&(!we(I.scheme)||e!==92)&&(Ee||e!==63&&e!==35)){let r=f+At(e);for(;r<x.length;){let n=w(x,r);if(n==null||n===47||we(I.scheme)&&n===92||!Ee&&(n===63||n===35))break;r+=At(n)}te+=Pt(x.slice(f,r),so),f=r,e=w(x,r)}if(e==null||e===47||we(I.scheme)&&e===92||!Ee&&(e===63||e===35)){let r=we(I.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(te)?(Kd(I),e!==47&&!r&&I.path.push("")):Md(te)&&e!==47&&!r?I.path.push(""):Md(te)||(I.scheme==="file"&&I.path.length===0&&Gd(te)&&(te=`${te[0]}:`),I.path.push(te)),te="",e===63?(I.query="",D(t,e)?Vt(w(x,f)):0):e===35?(I.fragment="",D(t,e)?Ct(w(x,f)):0):D(t,e)?gt(w(x,f)):0}else return te+=Vd(e,so),D(t,e)?gt(w(x,f)):0},Jd=e=>{let t=f;if(e===63)return I.query="",D(t,e)?Vt(w(x,f)):0;if(e===35)return I.fragment="",D(t,e)?Ct(w(x,f)):0;if(e!=null){let r=f+At(e);for(;r<x.length;){let i=w(x,r);if(i===63||i===35)break;r+=At(i)}let n=x.slice(f,r);if(r<x.length&&n.charCodeAt(n.length-1)===32?I.path[0]+=Pt(n.slice(0,-1),un)+"%20":I.path[0]+=Pt(n,un),f=r,(e=w(x,r))===63)return I.query="",D(t,e)?Vt(w(x,f)):0;if(e===35)return I.fragment="",D(t,e)?Ct(w(x,f)):0}return D(t,e)?Jd(w(x,f)):0},Vt=e=>{let t=f,r=f;if(e!=null){if(Ee)r=x.length;else{let i=x.indexOf("#",f);r=i===-1?x.length:i}let n=we(I.scheme)?Nb:fo;I.query+=Pt(x.slice(f,r),n)}return f=r,w(x,r)===35&&!Ee?(I.fragment="",D(t,e)?Ct(w(x,f)):0):D(t,e)?Vt(w(x,f)):0},Ct=e=>{let t=f;return e!=null&&(I.fragment+=Pt(x.slice(f),Db),f=x.length),D(t,e)?Ct(w(x,f)):0};function po(e){if(e.opaquePath)return e.path[0];{let t="";for(let r of e.path)t+=`/${r}`;return t}}function Xd(e){switch(e.scheme){case"blob":{let t=it(po(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Xd(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(r){let n=`${r.scheme}://`;return n+=r.host,r.port!==null&&(n+=`:${r.port}`),n})(e);default:return"null"}}var Ae=Symbol("URLImpl"),ln=class e{constructor(t,r){if(t===void 0&&r===void 0)throw new TypeError('The "url" argument must be specified.');t=ge(t),r!=null&&(r=ge(r));let n=null;if(r!=null&&(n=it(r,null,null,0),n==null))throw new TypeError(`Invalid base URL: ${r}`);let i=it(t,null,n,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[Ae]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,r){t=ge(t),r!==void 0&&(r=ge(r));try{return new e(t,r)}catch{return null}}static canParse(t,r){t=ge(t),r!==void 0&&(r=ge(r));let n=null;return r!=null&&(n=it(r,null,null,0),n==null)?!1:it(t,null,n,0)!=null}get href(){return(function(r){let n=`${r.scheme}:`;return r.host!==null&&(n+="//",(r.username!==""||r.password!=="")&&(n+=r.username,r.password!==""&&(n+=`:${r.password}`),n+="@"),n+=r.host,r.port!==null&&(n+=`:${r.port}`)),r.host===null&&!r.opaquePath&&r.path.length>1&&r.path[0]===""&&(n+="/."),n+=po(r),r.query!==null&&(n+=`?${r.query}`),r.fragment!==null&&(n+=`#${r.fragment}`),n})(this[Ae].url)}set href(t){let r=it(t=ge(t),null,null,0);if(r==null)throw new TypeError(`Invalid URL: ${t}`);this[Ae].url=r,this[Ae].query&&no(this[Ae].query,r.query)}get origin(){return Xd(this[Ae].url)}get protocol(){return`${this[Ae].url.scheme}:`}set protocol(t){it(`${t=ge(t)}:`,this[Ae].url,null,2)}get username(){return this[Ae].url.username}set username(t){t=ge(t),ro(this[Ae].url)||(function(n,i){n.username=Pt(i,li)})(this[Ae].url,t)}get password(){return this[Ae].url.password}set password(t){t=ge(t),ro(this[Ae].url)||(function(n,i){n.password=Pt(i,li)})(this[Ae].url,t)}get host(){let{url:t}=this[Ae];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=ge(t),this[Ae].url.opaquePath||it(t,this[Ae].url,null,3)}get hostname(){let{url:t}=this[Ae];return t.host!=null?t.host:""}set hostname(t){t=ge(t),this[Ae].url.opaquePath||it(t,this[Ae].url,null,4)}get port(){let{url:t}=this[Ae];return t.port!=null?`${t.port}`:""}set port(t){t=ge(t);let{url:r}=this[Ae];ro(r)||(t?it(t,r,null,5):r.port=null)}get pathname(){return po(this[Ae].url)}set pathname(t){t=ge(t);let{url:r}=this[Ae];r.opaquePath||(r.path=[],it(t,r,null,6))}get search(){let{url:t}=this[Ae];return t.query?`?${t.query}`:""}set search(t){t=ge(t);let{url:r,query:n}=this[Ae];if(!t)r.query=null,n&&no(n,null);else{let i=t[0]==="?"?t.substring(1):t;r.query="",it(i,r,null,7),n&&no(n,r.query)}}get searchParams(){let t=this[Ae],r=t.query;return r==null&&(r=t.query=(function(i,o){let a=new mi;return a[Pe].url=i,a[Pe].serialized=o==null,o&&(a[Pe].list=ho(o)),a})(this,t.url.query)),r}get hash(){let{url:t}=this[Ae];return t.fragment?`#${t.fragment}`:""}set hash(t){t=ge(t);let{url:r}=this[Ae];if(!t)r.fragment=null;else{let n=t[0]==="#"?t.substring(1):t;r.fragment="",it(n,r,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(ln.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var Pe=Symbol("URLSearchParamsImpl"),cy=Symbol.dispose||Symbol.for("dispose");function no(e,t){t?e[Pe].list=ho(t):e[Pe].list.length=0,e[Pe].serialized=t==null}function oi(e){if(e.url){let t=co(e.list);(function(n,i){n[Ae].url.query=i})(e.url,t||null),e.serialized=!0}}var uy=typeof Iterator<"u"?Iterator:Object,cn=class extends uy{constructor(t,r){super(),this[Pe]={ptr:t,map:r,index:0}}next(){let t=this[Pe];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[cy](){}},mi=class{constructor(t){let r=this[Pe]={list:[],url:null,serialized:!0},n;if(Array.isArray(t))for(let i=0;i<t.length;i++)r.list.push(Rd(t[i]));else if((n=Ld(t))!=null){let i;for(;!(i=io(n.next())).done;)r.list.push(Rd(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let o=0;o<i.length;o++){let a=i[o],c=Tb(a),d=ge(t[a]),p=r.list.find(y=>y[0]===c);p?p[1]=d:r.list.push([c,d])}}else if(t!==void 0){let i=ge(t);i=i[0]==="?"?i.substring(1):i,r.list=ho(i)}}get size(){return this[Pe].list.length}append(t,r){t=ge(t),r=ge(r),this[Pe].list.push([t,r]);let n=this[Pe];n.url&&n.serialized?(function(o,a){let c=o[Ae].url;c.query=c.query?`${c.query}&${a}`:a})(n.url,co([[t,r]])):oi(n)}delete(t,r){t=ge(t),r=r!=null?ge(r):void 0;let{list:n}=this[Pe],i=0;for(;i<n.length;)n[i][0]===t&&(r==null||n[i][1]===r)?n.splice(i,1):i++;oi(this[Pe])}get(t){t=ge(t);let{list:r}=this[Pe];for(let n=0;n<r.length;n++)if(r[n][0]===t)return r[n][1];return null}getAll(t){t=ge(t);let r=[],{list:n}=this[Pe];for(let i=0;i<n.length;i++)n[i][0]===t&&r.push(n[i][1]);return r}has(t,r){t=ge(t),r=r!=null?ge(r):void 0;let{list:n}=this[Pe];for(let i=0;i<n.length;i++)if(n[i][0]===t&&(r==null||n[i][1]===r))return!0;return!1}set(t,r){t=ge(t),r=ge(r);let{list:n}=this[Pe],i=!1,o=!1,a=0;for(;a<n.length;)n[a][0]===t?i?(n.splice(a,1),o=!0):(i=!0,n[a][1]!==r&&(n[a][1]=r,o=!0),a++):a++;i||(n.push([t,r]),o=!0),o&&oi(this[Pe])}sort(){this[Pe].list.sort((t,r)=>t[0]<r[0]?-1:t[0]>r[0]?1:0),oi(this[Pe])}forEach(t,r){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:n}=this[Pe];for(let i=0;i<n.length;i++)t.call(r,n[i][1],n[i][0],this)}entries(){return new cn(this[Pe],t=>t)}keys(){return new cn(this[Pe],t=>t[0])}values(){return new cn(this[Pe],t=>t[1])}toString(){return co(this[Pe].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(mi.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var zd={name:"@tinkerlandai/indiana-sdk",version:"0.8.4",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var em="https://api.tinker.cash";var tm=Symbol("IndianaNoContent");function rm(e,t,r=URL){let n=e.configuration?.scope,i=e.scope??(n&&{projectId:n.projectId,environment:n.environment}),o=i?Ne.parse(i):void 0;if(o&&n&&(o.projectId!==n.projectId||o.environment!==n.environment))throw new B("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=new r(e.baseUrl??em);if(a.username||a.password||a.search||a.hash)throw new B("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))throw new B("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let c=e.fetch??globalThis.fetch.bind(globalThis),d=e.timeoutMs??1e4;if(!Number.isFinite(d)||d<1||d>12e4)throw new B("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,y=0,j=null,$=new Set;function ie(){y+=1,p=null,j=null;for(let R of $)R.abort();$.clear()}async function ye(R,Re={},G="POST",L={}){let z=L.installationDetach===!0;if(z&&(R!=="push/installations/detach"||G!=="POST"))throw new B("INVALID_REQUEST","Installation authority only detaches this installation");if(!p&&!z)throw new B("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let xe=y,ce=new AbortController;z||$.add(ce);let je=()=>!z&&xe!==y?new B("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new B("TIMEOUT","Indiana request timed out"),et,st=new Promise((Te,se)=>{et=()=>se(je()),ce.signal.addEventListener("abort",et,{once:!0})}),Rt=setTimeout(()=>ce.abort(),d),He=async()=>{let Te=await c(`${a.href.replace(/\/$/,"")}/api/v1/${R}`,{method:G,headers:{"Content-Type":"application/json",...z?{}:{Authorization:`Bearer ${p}`},[bi]:yi.current,[No]:zd.version,...o?{"X-Indiana-Project":o.projectId,"X-Indiana-Environment":o.environment}:{}},body:G==="POST"?JSON.stringify(Re):void 0,signal:ce.signal,credentials:"omit",cache:"no-store",redirect:"error",...L.keepalive?{keepalive:!0}:{}});if(ce.signal.aborted)throw je();let se;try{se=Te.status===204?tm:await Te.json()}catch{throw ce.signal.aborted?je():new B(Te.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Te.status,Te.headers.get("X-Request-Id")??void 0)}if(ce.signal.aborted)throw je();if(!z&&xe!==y)throw new B("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Te.ok){let qe=gi.safeParse(se),Tt=qe.success&&(!$t.safeParse(qe.data.error.code).success||ko(qe.data.error.code,Te.status)),_o=Tt?qe.data.error.code:"HTTP_ERROR",xo=hn(_o,Te.status,{retryAfter:Te.headers.get("Retry-After"),recovery:Tt?qe.data.error.recovery:void 0,reason:Tt?qe.data.error.reason:void 0});throw new B(_o,Tt?qe.data.error.message:"Indiana request failed",Te.status,Te.headers.get("X-Request-Id")??(qe.success?qe.data.requestId:void 0),{...xo,...qe.success&&qe.data.error.retryable===!1?{retryable:!1}:{},...xo.retryAfterSeconds===void 0&&qe.success&&qe.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:qe.data.error.retryAfterSeconds}:{}})}if(Te.headers.get(bi)!==yi.current)throw new B("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(o&&se!==tm){let qe=se&&typeof se=="object"&&"scope"in se?se:se&&typeof se=="object"&&"configuration"in se?se.configuration:null;if(!qe||typeof qe!="object"||!("scope"in qe))throw new B("INVALID_RESPONSE","Response is missing its App/environment scope");let Tt=Ne.safeParse(qe.scope);if(!Tt.success||Tt.data.projectId!==o.projectId||Tt.data.environment!==o.environment)throw new B("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let ut=Te.headers.get("X-Indiana-Telemetry-Subject");if(ut){if(!/^[a-f0-9]{64}$/.test(ut))throw new B("INVALID_RESPONSE","Invalid telemetry identity");j!==ut&&(j=ut,t?.(j))}return se};try{return await Promise.race([He(),st])}catch(Te){throw!z&&xe!==y?new B("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Te instanceof B?Te:new B(ce.signal.aborted?"TIMEOUT":"NETWORK_ERROR",ce.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(Rt),ce.signal.removeEventListener("abort",et),$.delete(ce)}}return{subjectKey:()=>j,identify(R){if(!R.trim()||/\s/.test(R)||R.length>4096)throw new B("INVALID_TOKEN","A nonempty server-issued token is required");ie(),p=R},reset:ie,request:ye}}var im=require("zod");function nm(e,t,r,n){try{return e.parse(t)}catch(i){throw n&&i instanceof im.ZodError?new B(r,n):i}}async function So(e,t,r,n={},i){let o=typeof n=="function"?{}:n,a=nm(t.request,r,"INVALID_REQUEST",o.request),c=await e(t.path,a,t.method,i),d=typeof n=="function"?n:n.parseResponse;return d?d(t.response,c):nm(t.response,c,"INVALID_RESPONSE",o.response)}var dy=_.trackUsage.request.shape.command,my=_.trackUsage.response,py=_.checkEntitlement.request.omit({customerId:!0}).strict();function am(e){let t=Ne.parse(e.scope),r=rm({...e,scope:t},void 0,ln),n=jd(e.push,r,t),i=0,o=!1;return{messaging:{async preference(a){let c=_.readMessagingPreference;return c.response.parse(await r.request(c.path,c.request.parse({channel:a}))).preference},async setPreference(a){let c=_.setMessagingPreference;return c.response.parse(await r.request(c.path,c.request.parse(a))).preference}},push:{sync:n.sync,read:n.read,recover:n.recover,tokenObserver:n.tokenObserver,recoveryObserver:n.recoveryObserver,async preference(){let a=_.readMessagingPreference;return a.response.parse(await r.request(a.path,{channel:"push"})).preference},async setPreference(a){let c=_.setMessagingPreference;return c.response.parse(await r.request(c.path,c.request.parse({...a,channel:"push"}))).preference}},identify(a){if(!/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(a))throw new B("INVALID_TOKEN","A Customer Token is required");n.identify(a),i++,r.identify(a),o=!0,n.start()},reset(){try{n.reset()}finally{i++,o=!1,r.reset(),n.start()}},async readHoldings(){let a=_.readHoldings;return So(r.request,a,{})},async checkEntitlement(a){let c=_.checkEntitlement;return So(r.request,{...c,request:py},a)},async trackUsage(a){if(!o)throw new B("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new B("INVALID_REQUEST","Configure your authenticated backend usageReporter");let c=dy.parse(a),d=i,p;try{p=await e.usageReporter(c)}catch(j){throw d!==i?new B("IDENTITY_CHANGED","Customer identity changed during usage reporting"):j}if(d!==i)throw new B("IDENTITY_CHANGED","Customer identity changed during usage reporting");let y=my.parse(p);if(y.scope.projectId!==t.projectId||y.scope.environment!==t.environment)throw new B("INVALID_RESPONSE","Usage response scope differs");return y}}}
|
|
1
|
+
"use strict";var mn=Object.defineProperty;var Xd=Object.getOwnPropertyDescriptor;var Jd=Object.getOwnPropertyNames;var zd=Object.prototype.hasOwnProperty;var em=(e,t,r)=>t in e?mn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var tm=(e,t)=>{for(var r in t)mn(e,r,{get:t[r],enumerable:!0})},rm=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Jd(t))!zd.call(e,i)&&i!==r&&mn(e,i,{get:()=>t[i],enumerable:!(n=Xd(t,i))||n.enumerable});return e};var nm=e=>rm(mn({},"__esModule",{value:!0}),e);var wt=(e,t,r)=>em(e,typeof t!="symbol"?t+"":t,r);var Xb={};tm(Xb,{IndianaError:()=>R,createIndianaReactNative:()=>Yd});module.exports=nm(Xb);var pn=require("zod"),im=pn.z.enum(["sandbox","live"]),Xe=pn.z.object({projectId:pn.z.string().min(1),environment:im}).strict();var ue=require("zod"),Cr=ue.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),yo=ue.z.enum(["unknown","denied","provisional","granted"]),So=ue.z.enum(["ios","android"]),fn=ue.z.strictObject({installationId:ue.z.uuid(),publicKey:ue.z.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:ue.z.iso.datetime({offset:!0}),signature:ue.z.string().regex(/^[A-Za-z0-9_-]{86}$/)}),hi=ue.z.string().regex(/^[a-f0-9]{64}$/),_o=fn.extend({sequence:Cr,platform:So,credentialDigest:hi}),xo=fn.extend({credentialDigest:hi}),Io=fn.extend({sequence:Cr,platform:So}),hn=fn.extend({sequence:Cr,credentialDigest:hi,connectionId:ue.z.uuid().nullable(),kind:ue.z.enum(["fcm_token","apns_token"]).nullable(),token:ue.z.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:yo}),vo=hn,Po=hn.extend({challenge:ue.z.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),Ai=ue.z.strictObject({requested:ue.z.literal(!0),expiresAt:ue.z.iso.datetime({offset:!0})}),qt=ue.z.strictObject({installationId:ue.z.uuid(),bound:ue.z.boolean(),identitySeq:Cr,bindingGeneration:Cr,addressSeq:ue.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:ue.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:ue.z.uuid().nullable(),addressStatus:ue.z.enum(["active","invalid"]).nullable(),permission:yo}),gi=ue.z.strictObject({channel:ue.z.enum(["email","sms","voice","push"]),state:ue.z.enum(["unknown","allowed","denied"]),revision:ue.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:ue.z.iso.datetime({offset:!0}).nullable()}),ty=ue.z.strictObject({state:ue.z.enum(["allowed","denied"]),revision:ue.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Co(e,t,r){let n=["indiana_push_v1",e,t.projectId,t.environment,r.installationId,r.publicKey,r.issuedAt];e==="bind"?n.push(r.sequence,r.platform,r.credentialDigest):e==="detach"?n.push(r.sequence,r.platform):e==="read"?n.push(r.credentialDigest):n.push(r.sequence,r.credentialDigest,r.connectionId,r.kind,r.token,r.permission),e==="recovery_confirm"&&n.push(r.challenge);let i=JSON.stringify(n);if([...i].some(o=>o.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(i,o=>o.charCodeAt(0))}var De=require("zod"),Lt=De.z.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"]),ny=De.z.enum([...Lt.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),iy=De.z.enum([...Lt.options,"stale_revision"]),am=De.z.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"]),om=De.z.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Oo={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"}};var wo={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function sm(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(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(wo,e)){let n=wo[e];return{retryable:n==="retry_same_request",recovery:n}}let r=Lt.safeParse(e);return r.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Oo[r.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Eo(e,t){let r=Lt.safeParse(e);if(r.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):Oo[r.data].status===t;let n={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(n,e)&&(n[e]?.includes(t)??!1)}function cm(e,t=Date.now()){if(e===null)return;let r=e.trim();if(/^\d+$/.test(r)){let i=Number(r);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(r))return;let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):void 0}var jo=De.z.object({retryable:De.z.boolean(),recovery:am,reason:om.optional(),retryAfterSeconds:De.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),bi=De.z.object({requestId:De.z.uuid().optional(),error:De.z.object({code:De.z.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:De.z.string(),...jo.partial().shape})}),ay=De.z.object({error:bi.shape.error.extend({requestId:De.z.uuid().optional()})}),oy=De.z.object({error:De.z.string(),code:De.z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:De.z.uuid(),...jo.shape});function An(e,t,r={}){let n=sm(e,t),i=r.reason==="RESULT_UNKNOWN"?"recover_operation":r.recovery??n.recovery,o=n.retryable&&r.retryable!==!1&&i!=="recover_operation",a=o?cm(r.retryAfter??null):void 0;return{...n,retryable:o,recovery:i,...a===void 0?{}:{retryAfterSeconds:a},...r.reason?{reason:r.reason}:{}}}var yi="X-Indiana-Protocol",To="X-Indiana-SDK-Version";var Si={current:"0.9",unversioned:"0.2",releases:[{protocol:"0.9",firstReleasedAt:null,noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[]},{protocol:"0.2",firstReleasedAt:"2026-10-16T04:05:43.170Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.2.0",integrity:"sha512-kyzHFrt+zuS2hfDZsknCE3AIA9EZXakCDhorO0Ayn2wTpITbm32GMaqVFyhlPufDhkjkV4C0UvXJMyLT5FWIoQ==",sha256:"7e20dd8df9c5e965f67bcdad6c95bf0d0aa5e61a372e5ece88173e32190a1c4c"}]},{protocol:"0.3",firstReleasedAt:"2026-10-16T16:18:04.572Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.3.0",integrity:"sha512-jrh4DH2DBYL5tRkr9BNBVIgD1ts0hUPx8+AhiNkkt2uWV27R8tXGRCW1HBLOw2bfomyuIsAXBAY6niJfjkazCg==",sha256:"33f7ca369d509c44df95c5c8b94775c2afe9d8e3a94163275fe59754739e6815"},{version:"0.3.1",integrity:"sha512-Ifp24kv236advquxa78jx49XKz9oKsg5zZZvFMkId4+KxsylsGxHS44fqYJL/b84PVHl3DLuc+Ru2btdLEctIw==",sha256:"4cc047fe94477e77c5403ce47afea0db2806bd4c3cb94a2dd48c453b4e942163"}]},{protocol:"0.4",firstReleasedAt:"2026-10-18T12:44:12.148Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.4.0",integrity:"sha512-QYuxMdw63RzPLkqmFRc7xv8VWYKYWG+KuKM+f5ZeRX879n6sKyr38bxkMiozFXT+kvH0lDfTF73uJPY2yQX1pQ==",sha256:"ef22d0f6a89897bfbaf71487c4e805997528c8dbad2921ab5c90ed3aa0c01244"}]},{protocol:"0.5",firstReleasedAt:"2026-10-19T08:12:17.954Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.5.0",integrity:"sha512-tzdmoHdvaSoDIvGmg+JpmzE+o1kv7DXpSyvNUSuBj5rHX2pD1GDsMf7ioudUVT5MiKaBDVVtJVE+GpxMOBBLLA==",sha256:"d8b1909bebe1bca0c8c029a68b71477e06ba0c9317c3a2b4bf657951ae3449ca"}]},{protocol:"0.6",firstReleasedAt:"2026-10-21T11:41:57.832Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.6.0",integrity:"sha512-M4szAkM52gqiGPZbtpdhoAvYW2uNRQ2aRw0mdnpr2ErTnuG2i1++76fHjo0qiEMSlePdqu99T1Smecp/FZ2//g==",sha256:"141b058b485fb17b416a2f7961ca55e2da413c9afb7ff22f9fdec2561890bd82"},{version:"0.6.1",integrity:"sha512-KbZUP4XCRblj4mF//JG9t4AAMHSP7uENTi7edxJE55QZjvxH4n1/ypWtKZq32xgt9qGu9o3iZzL8tcHoM3B7Ng==",sha256:"e87930eaec7735629e27e930a462dcecb65fdc4e396cc8ab075845a4f4d22396"},{version:"0.6.2",integrity:"sha512-CUXfh46gSh1S7cdgStI3NAzRROlCQxOcvna2KKlDWFq8L7DXtcILLBOKw5Y1e+QQdDPsXGrsMVBOwIJxFyoIlw==",sha256:"dee5f6e605133ec6c509f390fafdf1d0cb66984a02bea0bb5c05828276c64a15"},{version:"0.6.3",integrity:"sha512-MJXbEoZdLym8a7IHUhY9Oh6eXaSRZPdkwYmfGvfsu5O/kTzfIg+OJuaNrFHYzK76msTxR76IMtQ1R45/FddGdg==",sha256:"fcff156ee9ae90a0f5c906721c8e12715f5fd7a97bca494d64a4303283ec633a"},{version:"0.6.4",integrity:"sha512-djTPwCCgNbp/dt0pFnwEgutZExBZ//wmA2GnObRtXydGrzfi8Z9W7RdeGUFvufblJaGAmcWwVqUgmzEi9SLyjA==",sha256:"bd8e53823728b1e45a27e187c538dcb18af005f24e55120d0cc6b5a618a033f7"}]},{protocol:"0.7",firstReleasedAt:"2026-10-23T09:15:53.572Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.7.0",integrity:"sha512-u2LstlzE8IVFy2dUf/sI9sybNRx3lMF32pjLmeEIFqTdcOXRGdH8GCg5927FwavBpRaWO4a7icmrhYiEjGuYWQ==",sha256:"bb3c3666cbba4ea5018f09e9d050b5db1f71e7a222cdde59c5a93f5ee4a52958"}]},{protocol:"0.8",firstReleasedAt:"2026-10-24T09:44:23.748Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.8.0",integrity:"sha512-w94iNQZo2xG9nVKJ4DcXJ3CpLa7sX8GUQlrIlgWAb+P1x99aXg/pnTeYk+rMaOstO5X/x13eB4xufVcbr8tN+Q==",sha256:"81613ce691331768f0849608fdffc5c78257c763e7cefad9236c4f0351a869ad"},{version:"0.8.1",integrity:"sha512-B07LLUiHHSy6Kxmjg47TBdnpSt7y+Z9tkN3TBBFclY7Fr+AH39Vaavz6eguzxCgb1uSiFQquJONWiKLvEcez+Q==",sha256:"619724c8bc8d8e219ea1ed74b8b4195457e25e92697cdc43b864876fcc004ffe"},{version:"0.8.3",integrity:"sha512-enKlzcLIydk3t3Z74FVXQODv9SNrhq7hfQ0Rcpd6SHBBbfiqFX0h6tWkHJifnJBrTVxAwCNG5aRvZY9x0Hxw1A==",sha256:"63270b8893be90624344ce628cc8d6e3b60cf65d214c9ec7586e71b35ca0dff8"},{version:"0.8.4",integrity:"sha512-pvhQawFj4vv8zLefCMtm4YusAGVxEGpc6OMnO0fM3Y2knnonOC8JBtO/NadEPZA2hb0Rggo0hbrVgNC4mDFBhw==",sha256:"ed8476a40a937875628439a3f5bab056f94a8e3efcb78abd19fd504a4737ddda"},{version:"0.8.5",integrity:"sha512-d89LuMdv8L4hbAv0DeDbT3gPpfZsjdmadd5/zTwd4RwsfiihY7H+RMVjgfciic7BxnT7ZiI94JfsJLqdBBMa1w==",sha256:"0cc92920d29a4279a9c12a0542584f401605dce6e56e39f94ed369dcb02138ec"}]}]};var Ro=require("zod"),um=["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"],J=Ro.z.enum(um);function ko(e){let t=J.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}var Bt=require("zod");var Ft=Bt.z.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"),dy=Bt.z.object({amountCents:Bt.z.number().int().min(0).max(1e8),currency:J,interval:Bt.z.enum(["free","month","year"]),currencyOptions:Bt.z.partialRecord(J,Bt.z.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");var g=require("zod/v4");var Do=require("zod/v4"),No=Do.z.registry();var{AppEnv:gn}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:Mo}={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:lm}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:dm}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(g.z),{ResetInterval:wr}=(()=>{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:mm}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:pm}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:fm}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:hm}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:Am}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(g.z),{BALANCE_BASES:gm}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:Uo}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:_i}=(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."})})}))(g.z),{ProductMetadataSchema:cr}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(g.z),{findDuplicate:bm}={findDuplicate:t=>{let r=new Set;for(let n of t){if(r.has(n))return n;r.add(n)}}},{BillingInterval:Ot}=(()=>{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:xi}=(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')."})})}))(g.z),{withSpecDefault:Or}=(e=>({withSpecDefault:({schema:r,defaultValue:n,description:i})=>(e.add(r,{description:i,default:n}),r)}))(No),{COMMON:qo}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:ym}={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:Sm}=(e=>({COMMON_SET:new Set(e)}))(qo),{hasNoDuplicateCurrencies:Lo}={hasNoDuplicateCurrencies:t=>{let r=new Set;for(let{currency:n}of t){let i=n.toLowerCase();if(r.has(i))return!1;r.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:Bo}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:Ii}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(g.z),{Infinite:bn}={Infinite:"inf"},{TierBehavior:Er}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:yn}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Fo}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:_m}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:Sn}=(()=>{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:_n}=(()=>{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:vi}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:Vo}=(()=>{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:xm}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Im}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Pi}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(g.z),{ApiCreditTierSchema:$o}=(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."})})}))(g.z),{VIOLATION_MESSAGES:vm}={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:Go}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(g.z),{ModelMarkupsSchema:Ci}=((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()}))(g.z,Go),{additionalCurrencyPlanItemIssues:Ho}={additionalCurrencyPlanItemIssues:t=>{if(!t)return[];let r=[];t.additional_currencies&&t.additional_currencies.length>0&&(typeof t.amount!="number"||(t.tiers?.length??0)>0)&&r.push("price.additional_currencies requires a flat 'amount'; tiered prices carry per-currency amounts on each tier.");let n=t.tiers;if(n&&n.length>0){let i=a=>(a.additional_currencies??[]).map(c=>c.currency.toLowerCase()),o=new Set(n.flatMap(i));o.size>0&&(n.every(c=>{let l=new Set(i(c));return l.size===o.size&&[...o].every(p=>l.has(p))})||r.push("Each additional currency must be present on every tier or none."))}return r}},{PlanItemFilterSchema:wi}=((e,t,r,n,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(r),e.enum(n)]).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)."})}))(g.z,yn,Ot,wr,Ii),{UpdatePlanItemParamsV1Schema:Pm}=((e,t,r)=>({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(r).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})}))(g.z,wi,wr),{FreeTrialDuration:jr}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:Cm}=((e,t)=>({laneParam:({schema:n,description:i})=>e({schema:t.array(n).optional(),defaultValue:[],description:i})}))(Or,g.z),{findDuplicateInControls:wm}={findDuplicateInControls:({controlKey:t,controls:r,rule:n})=>{let i=new Set;for(let[o,a]of r.entries()){let c=n.identityOf(a);if(c!==void 0){if(i.has(c))return{code:"custom",message:n.message,input:a[n.field],path:[t,o,n.field]};i.add(c)}}}},{featureIdIdentity:Om}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:Ko}={usageLimitFilterKey:t=>t?.properties?Object.entries(t.properties).map(([r,n])=>[r,String(n)]).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${r}=${n}`).join("&"):""},{usageAlertIdentity:Em}=((e,t)=>({usageAlertIdentity:n=>[n.feature_id??"",n.basis??e,t(n.filter),n.threshold_type,n.threshold].join("|")}))(Uo,Ko),{RemovePlanLicenseSchema:jm}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(g.z),{ApiStripePriceProcessorSchema:Tm}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(g.z),{ApiFeatureType:Rm}=(()=>{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:km}=(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."})})}))(g.z),{ApiRevenueCatProductSchema:Dm}=(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."})})}))(g.z),{TrialOnEnd:xn}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:Nm}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:Mm}=(()=>{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:Um}=(()=>{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:qm}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(g.z),{UsageWindowScopeSchema:Lm}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(g.z),{EntInterval:Wo}=(()=>{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:Bm}=(()=>{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:Fm}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(g.z),{FreeTrialSchema:Vm}=((e,t,r)=>({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(r).nullish()})}))(g.z,jr,xn),{BillingType:$m}=(()=>{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:Oi}=((e,t)=>({UsageTierSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional()}).refine(n=>n.amount!==void 0||n.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(n=>({...n,amount:n.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional()}))}))(g.z,bn),{IgnoredFixedPriceMetadataSchema:Gm}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(r=>typeof r=="string"?null:r,e.null().or(e.undefined()))}))(g.z),{BillWhen:Hm}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:Zo}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:Km}=((e,t,r)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(r).default(r.ProrateImmediately)})}))(g.z,Sn,_n),{AllowanceType:Wm}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:Qo}=((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()})}))(g.z,vi),{CreditDimensionBaseSchema:Zm}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(g.z,Pi),{flatCreditRateShape:Yo}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(g.z),{CreditTierSchema:Qm}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(g.z),{CreditMultiplierSchema:Ym}=((e,t)=>({CreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional(),add:e.number().optional()}).refine(n=>n.factor!==void 0||n.add!==void 0,{message:"A multiplier needs a factor or an add"})}))(g.z,Pi),{idRegex:In}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:Xo}={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:Xm}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:Jm}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{ProductItemInterval:zm}=(()=>{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:ep}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:tp}={TierInfinite:"inf"},{CreateFreeTrialSchema:Jo}=((e,t,r)=>({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(r).nullish()})}))(g.z,jr,xn),{ProductConfigParamsSchema:Ei}=((e,t,r)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:r})})}))(g.z,Or,Mo),{CREATE_PRODUCT_EXAMPLE:rp}={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:np}=((e,t,r)=>({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(r).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."})})}))(g.z,jr,xn),{CreateProductSchema:hy}=(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("")})}))(g.z),{isUsageLimitBasisAlert:ip}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:zo}=(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()})}))(g.z),{RewardType:es}=(()=>{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:ts}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:rs}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(g.z,ts),{RewardTriggerEvent:ap}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:op}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:vn}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(g.z,Mo),{PurchaseLimitIntervalEnum:sp}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(g.z,lm),{DbSpendLimitSchema:ji}=((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(n=>n.overage_limit===void 0&&n.skip_overage_billing===void 0||n.feature_id!==void 0,{message:"feature_id is required when overage_limit or skip_overage_billing is provided",path:["feature_id"]})}))(g.z,dm),{USAGE_LIMIT_INTERVALS:cp}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(wr),{UsageLimitAnchorSchema:ns}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(g.z,mm),{UsageLimitFilterValueSchema:up}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(g.z,fm),{USAGE_ALERT_BASES:lp}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(gm),{licensePatchIssues:dp}=(e=>({licensePatchIssues:({upsertLicenses:r=[]})=>{let n=e(r.map(i=>i.license_plan_id));return n===void 0?[]:[{message:`Duplicate license ${n} in upsert_licenses`,path:["upsert_licenses"]}]}}))(bm),{BasePriceSchema:mp}=((e,t,r)=>({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:r.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(g.z,Ot,xi),{CURRENCY_CODES:pp}=((e,t,r)=>({CURRENCY_CODES:[...e,...t.filter(i=>!r.has(i)).sort()]}))(qo,ym,Sm),{AllocatedBillingFieldSchema:is}=((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'."})}))(g.z,Fo),{EntitlementExpirySchema:Pn}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(g.z,Vo),{CreditDimensionNameSchema:as}=((e,t,r)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(r),{message:`Dimension names cannot contain "${r}"`})}))(g.z,xm,Im),{ApiCreditMatchSchema:os}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Pi),{findCreditTierViolations:fp}=(e=>({findCreditTierViolations:r=>{let n=[],i=(a,c)=>n.push({index:a,reason:c,message:e[c]}),o=0;for(let[a,c]of r.entries()){let l=a===r.length-1;if(c==="inf"){l||i(a,"non_final_infinity");continue}(!Number.isFinite(c)||c<=o)&&i(a,"not_increasing"),o=c,l&&i(a,"final_not_infinity")}return n}}))(vm),{ApiCreditMultiplierSchema:hp}=((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(n=>n.factor!==void 0||n.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(g.z,os),{ProviderMarkupsSchema:ss}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(g.z,Go),{planItemParamsIssues:Ap}=((e,t,r,n,i)=>({planItemParamsIssues:a=>{let c=[],l=a.reset?.interval,p=a.price?.interval,A=a.reset?.interval_count??1,v=a.price?.interval_count??1;if(l&&p&&(String(l)!==String(p)||A!==v)&&a.price?.billing_method!==e.Prepaid&&c.push({message:"reset.interval and price.interval can only differ for prepaid prices.",input:a}),a.threshold_billing&&(!a.price||a.unlimited)&&c.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)||c.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&&c.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&&c.push({message:"expiry is not supported on pooled items; pooled balances have no per-purchase lifetime.",input:a.expiry}),a.expiry.length<=0&&c.push({message:"expiry.length must be greater than 0",input:a.expiry})),a.price){a.threshold_billing&&a.price.billing_method!==e.UsageBased&&c.push({message:"threshold_billing requires a finite usage-based price",input:a.threshold_billing});let{amount:U,tiers:ie}=a.price;a.threshold_billing&&ie?.length&&c.push({message:"threshold_billing currently requires a flat usage price",input:a.threshold_billing});let q=a.price.billing_method===e.UsageBased&&a.price.allocated_billing===r.ProratedLegacy;a.proration&&a.price.billing_method!==e.Prepaid&&!q&&c.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:a.proration});let Pe=typeof U=="number",Me=Array.isArray(ie)&&ie.length>0;Pe||Me?Pe&&Me&&c.push({message:"'amount' and 'tiers' cannot both be defined in 'price'.",input:a.price}):c.push({message:"If 'price' is present, either 'amount' or 'tiers' must be defined.",input:a.price})}if(a.price?.tiers){let U=a.price.tiers.some(ie=>ie.flat_amount&&ie.flat_amount>0);U&&a.price.tier_behavior!==n.VolumeBased&&c.push({message:"flat_amount on tiers is only supported for volume-based pricing.",input:a.price}),U&&a.price.tiers.length<=1&&c.push({message:"flat_amount is not supported on single-tier pricing.",input:a.price}),a.price.tiers.some(ie=>ie.flat_amount!=null&&ie.flat_amount<0)&&c.push({message:"flat_amount must be 0 or greater.",input:a.price}),a.price?.tier_behavior===n.VolumeBased&&a.price?.billing_method!==e.Prepaid&&c.push({message:"volume-based pricing is only supported for prepaid features.",input:a.price}),a.price?.tiers.length===0?c.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&&c.push({message:"tiers[0].to must be greater than included.",input:a.price})}for(let U of i(a.price))c.push({message:U,input:a.price});return c}}))(yn,Ot,Fo,Er,Ho),{FreeTrialParamsV1Schema:Ti}=((e,t,r)=>({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:r({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."})}))(g.z,jr,Or),{duplicateCheck:gp}=(e=>({duplicateCheck:({controlKey:r,...n})=>i=>e({controlKey:r,controls:i[r]??[],rule:n})}))(wm),{usageLimitIdentity:Ri}=(e=>({usageLimitIdentity:r=>`${r.feature_id}|${e(r.filter)}`}))(Ko),{ApiPriceProcessorsSchema:cs}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(g.z,Tm),{ApiFeatureV0Schema:us}=((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."})})}))(g.z,Rm),{ApiRevenueCatPlanProcessorSchema:bp}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(g.z,Dm),{ApiFreeTrialV2Schema:yp}=((e,t,r)=>({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(r).nullish().meta({description:"Behavior when the trial ends. 'bill' charges the customer (default). 'revert' expires the trial and restores the customer's previous plan."})})}))(g.z,jr,xn),{CustomerEligibilitySchema:Sp}=((e,t,r,n)=>({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(r).meta({description:"The action that would occur if this plan were attached to the customer."}),scenario:e.enum(n).optional().meta({description:"Legacy attach scenario. Internal use only.",internal:!0})})}))(g.z,Nm,Mm,Um),{UsageWindowLimitSchema:Ay}=((e,t,r,n,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:r,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(n),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()})}))(g.z,qm,Lm,Wo,ns),{FeatureSchema:_p}=((e,t,r,n,i)=>({FeatureSchema:e.object({internal_id:e.string(),org_id:e.string(),created_at:e.number().nullable(),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(r,{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:n.nullish(),stripe_meter:i.nullish(),stripe_product_id:e.string().nullish()})}))(g.z,gn,Bm,Ci,Fm),{PriceCurrencyConfigSchema:ls}=((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()})}))(g.z,Oi),{UsagePriceConfigSchema:xp}=((e,t,r,n,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(r),interval:e.enum(n),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()})}))(g.z,Hm,Oi,Ot,ls,Zo),{graduatedCreditRateShape:ds}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(g.z,Qm),{FeatureMarkupsOverrideSchema:Ip}=((e,t,r)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:r})}))(g.z,ss,Ci),{usageAlertTargetLimitIdentity:vp}=(e=>({usageAlertTargetLimitIdentity:r=>e({feature_id:r.feature_id??"",filter:r.filter})}))(Ri),{DiscountConfigSchema:ms}=((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()})}))(g.z,ts),{RewardEntitlementSchema:ps}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(g.z,Pn),{UpdateRewardSchema:gy}=((e,t,r,n,i,o)=>({UpdateRewardSchema:e.object({name:e.string().nullish(),promo_codes:e.array(t).optional(),id:e.string().optional(),type:e.nativeEnum(r).optional(),discount_config:n.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(o).nullish()})}))(g.z,zo,es,ms,rs,ps),{CreateRewardProgram:by}=((e,t,r)=>({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(r)})}))(g.z,ap,op),{AutoTopupPurchaseLimitSchema:fs}=((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."})})}))(g.z,sp),{UsageLimitFilterSchema:hs}=((e,t,r,n)=>({UsageLimitFilterSchema:e.object({properties:e.record(e.string().min(1).max(t),r).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>n)&&o.issues.push({code:"custom",message:`filter.properties must have between 1 and ${n} keys`,input:o.value})})})}))(g.z,pm,up,hm),{UsageAlertBasisSchema:Pp}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(g.z,lp),{refineCustomizePlanV1Schema:As}=(e=>({refineCustomizePlanV1Schema:(r,{includeItems:n=!0,includeFreeTrial:i=!0,includeUpdateItems:o=!0,includeLicenses:a=!0}={})=>{let c=["price",n&&"items","add_items","remove_items",o&&"update_items",i&&"free_trial","billing_controls",a&&"upsert_licenses",a&&"remove_licenses"].filter(Boolean),l=p=>p==="update_items"?"deprecated update_items":p;return r.refine(p=>c.some(A=>p[A]!==void 0),{message:`When using customize, at least one of ${c.map(l).join(", ")} must be provided`}).superRefine((p,A)=>{if(a)for(let v of e({upsertLicenses:p.upsert_licenses}))A.addIssue({code:"custom",...v})}).refine(p=>!(p.items!==void 0&&(p.add_items!==void 0||p.remove_items!==void 0||o&&p.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`})}}))(dp),{SUPPORTED_SET:Cp}=(e=>({SUPPORTED_SET:new Set(e)}))(pp),{ApiCreditDimensionBaseSchema:wp}=((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."})})}))(g.z,os),{refineGraduatedTiers:gs}=(e=>({refineGraduatedTiers:(r,n)=>{let i=e(r.tiers.map(o=>o.to));for(let{index:o,message:a}of i)n.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(fp),{ApiFeatureMarkupsOverrideSchema:Op}=((e,t,r)=>({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:r.meta({description:"Per-model markup overrides for customers on this plan."})})}))(g.z,ss,Ci),{AutoTopupPurchaseLimitParamsSchema:Ep}=((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."})})}))(fs,g.z),{DUPLICATE_CHECKS:jp}=((e,t,r,n)=>({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:r,field:"feature_id",message:"Only one usage limit entry is allowed per feature_id and filter"}),e({controlKey:"usage_alerts",identityOf:n,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"})]}))(gp,Om,Ri,Em),{ApiPlanProcessorsSchema:Tp}=((e,t,r)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:r.nullish()}).meta({"x-atmn-mapping":!0})}))(g.z,km,bp),{FixedPriceConfigSchema:Rp}=((e,t,r,n,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(),r).nullish(),billing_units:e.number().nullish(),usage_tiers:e.array(n).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})}))(g.z,Ot,ls,Oi,Gm),{CreditDimensionSchema:kp}=((e,t,r,n)=>({CreditDimensionSchema:e.union([t.extend(r),t.extend(n)])}))(g.z,Zm,Yo,ds),{filterUnresolvableUsageLimitAlerts:Dp}=((e,t,r)=>({filterUnresolvableUsageLimitAlerts:({usageAlerts:i,usageLimitLists:o})=>{let a=new Set(o.flatMap(c=>(c??[]).map(e)));return i.flatMap((c,l)=>t(c)&&!a.has(r(c))?[{index:l,usageAlert:c}]:[])}}))(Ri,ip,vp),{CreateRewardSchema:yy}=((e,t,r,n,i,o)=>({CreateRewardSchema:e.object({name:e.string(),promo_codes:e.array(t),id:e.string(),type:e.nativeEnum(r).nullish(),discount_config:n.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(o).nullish()}).refine(c=>c.type!==r.FeatureGrant?!0:c.entitlements&&c.entitlements.length>0,{message:"Feature grant rewards require at least one entitlement"}).refine(c=>c.type!==r.FeatureGrant?!0:c.promo_codes.some(l=>l.code.length>0),{message:"Feature grant rewards require at least one promo code"})}))(g.z,zo,es,ms,rs,ps),{AutoTopupSchema:ki}=((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."})})}))(g.z,fs),{DbUsageLimitSchema:Di}=((e,t,r,n)=>({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:r.optional().meta({description:"Window alignment. 'billing_cycle' phases the interval to the customer's renewal time; 'utc' aligns to the UTC calendar."}),filter:n.optional().meta({description:"When set, only usage from events whose properties match counts toward this cap. Omit to count all usage of the feature."})})}))(g.z,cp,ns,hs),{DbUsageAlertSchema:Ni}=((e,t,r,n,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:r.default(n).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:c,threshold_type:l,threshold:p,basis:A,filter:v}=a.value;l==="remaining_percentage"&&p>100&&a.issues.push({code:"custom",input:p,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),A==="usage_limit"&&!c&&a.issues.push({code:"custom",input:c,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),v&&A!=="usage_limit"&&a.issues.push({code:"custom",input:v,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(g.z,Am,Pp,Uo,hs),{isValidCurrencyCode:Np}=(e=>({isValidCurrencyCode:r=>!!r&&e.has(r.toLowerCase())}))(Cp),{ApiCreditDimensionSchema:Mp}=((e,t,r,n)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(r).min(1)}).strict().superRefine(n),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(g.z,wp,$o,gs),{AutoTopupParamsSchema:Up}=((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."})})}))(ki,Ep),{findDuplicateBillingControlIssue:qp}=(e=>({findDuplicateBillingControlIssue:r=>{for(let n of e){let i=n(r);if(i)return i}}}))(jp),{CustomerBillingControlsSchema:Mi}=((e,t,r,n,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(r).optional().meta({description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:e.array(n).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."})})}))(g.z,ki,ji,Di,Ni,_i),{PriceSchema:Lp}=((e,t,r,n,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(r).nullish(),is_custom:e.boolean().optional(),config:n.or(i),entitlement_id:e.string().nullish(),proration_config:o.nullable()})}))(g.z,$m,Er,Rp,xp,Km),{CreditSchemaItemBaseSchema:bs}=((e,t,r,n)=>({CreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(t,r).optional(),multipliers:e.record(t,n).optional()})}))(g.z,as,kp,Ym),{GraduatedCreditSchemaItemSchema:Bp}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(bs,ds),{UpdateProductSchema:Sy}=((e,t,r)=>({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:r.optional()})}))(g.z,vn,Mi),{DbBillingControlsSchema:Fp}=((e,t,r,n,i,o)=>({DbBillingControlsSchema:e.object({auto_topups:e.array(t).nullish(),spend_limits:e.array(r).nullish(),usage_limits:e.array(n).nullish(),usage_alerts:e.array(i).nullish(),overage_allowed:e.array(o).nullish()})}))(g.z,ki,ji,Di,Ni,_i),{CurrencyCodeSchema:ys}=((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')."})}))(g.z,Np),{AdditionalCurrencyTierSchema:Vp}=((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(n=>n.amount!==void 0||n.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(g.z,ys),{ApiCreditSchemaItemBaseSchema:Ss}=((e,t,r,n)=>({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,r).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,n).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(g.z,as,Mp,hp),{ApiFlatCreditSchemaItemSchema:$p}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Ss,g.z),{rejectDuplicateBillingControls:Gp}=(e=>({rejectDuplicateBillingControls:r=>{let n=e(r.value);n&&r.issues.push(n)}}))(qp),{FlatCreditSchemaItemSchema:Hp}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(bs,Yo),{ProductSchema:Kp}=((e,t,r,n,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:r.default(()=>({ignore_past_due:!1})),...n.shape,metadata:i.default(()=>({}))})}))(g.z,gn,vn,Fp,cr),{AdditionalCurrencyPriceSchema:Wp}=((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."})})}))(g.z,ys),{AdditionalCurrencyTierArraySchema:_s}=((e,t,r,n)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(r,{message:n})}))(g.z,Vp,Lo,Bo),{ApiGraduatedCreditSchemaItemSchema:Zp}=((e,t,r,n)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(r).min(1)}).strict().superRefine(n)}))(Ss,g.z,$o,gs),{CustomerBillingControlsParamsSchema:Cn}=((e,t,r,n,i,o,a,c)=>({CustomerBillingControlsParamsSchema:e.object({auto_topups:t({schema:r,description:"List of auto top-up configurations per feature."}),spend_limits:t({schema:n,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(c)}))(g.z,Cm,Up,ji,Di,Ni,_i,Gp),{CreditSchemaItemSchema:Qp}=((e,t,r)=>({CreditSchemaItemSchema:e.union([t,r])}))(g.z,Hp,Bp),{PriceTierSchema:Yp}=((e,t,r)=>({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:r.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}))}))(g.z,tp,_s),{PlanBillingControlsParamsSchema:Xp}=((e,t)=>({PlanBillingControlsParamsSchema:e.check(n=>{let i=t({usageAlerts:n.value.usage_alerts??[],usageLimitLists:[n.value.usage_limits??[]]});for(let{index:o,usageAlert:a}of i)n.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"]})})}))(Cn,Dp),{AdditionalCurrencyPriceArraySchema:Tr}=((e,t,r,n)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(r,{message:n})}))(g.z,Wp,Lo,Bo),{ApiUsageTierWithCurrenciesSchema:xs}=((e,t,r)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:r.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:r.optional()}))}))(g.z,bn,_s),{ApiCreditSchemaItemSchema:Jp}=((e,t,r)=>({ApiCreditSchemaItemSchema:e.union([t,r])}))(g.z,Zp,$p),{FeatureConfigOverrideSchema:Is}=((e,t,r)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:r.optional()})}))(g.z,Qp,Ip),{ProductItemConfigSchema:zp}=((e,t,r,n,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(r).nullish(),on_decrease:e.enum(n).nullish(),rollover:i.nullish(),expiry:o.nullish(),feature_override:a.nullish()})}))(g.z,Zo,Sn,_n,Qo,Pn,Is),{BasePriceParamsSchema:wn}=((e,t,r,n)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:r.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:n.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:r.string().optional().meta({internal:!0}),entitlement_id:r.string().optional().meta({internal:!0}),price_id:r.string().optional().meta({internal:!0}),stripe_price_id:r.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."})}))(mp,Or,g.z,Tr),{PlanItemPriceParamsSchema:ef}=((e,t,r,n,i,o,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(l=>l??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(r).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(n).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."})})}))(g.z,Tr,xs,Er,Ot,yn,is),{ApiFeatureOverrideSchema:vs}=((e,t,r)=>({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:r.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."})})}))(g.z,Jp,Op),{ApiPlanItemV1Schema:tf}=((e,t,r,n,i,o,a,c,l,p,A,v,k,U,ie,q,Pe)=>({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(r).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:n.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(c).meta({description:"'prepaid' for features like seats where customers pay upfront, 'usage_based' for pay-as-you-go after included usage."}),allocated_billing:l,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:p.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:A.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(v).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(k).optional().meta({description:"How to handle billing when quantity increases mid-cycle."}),on_decrease:e.enum(U).optional().meta({description:"How to handle credits when quantity decreases mid-cycle."})}).optional().meta({internal:!0}),expiry:ie.nullish().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:q.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(j=>{let V=j.value.reset?.interval,X=j.value.price?.interval,he=j.value.reset?.interval_count??1,be=j.value.price?.interval_count??1;if(V&&X&&(String(V)!==String(X)||he!==be)&&j.value.price?.billing_method!==c.Prepaid&&j.issues.push({code:"custom",message:"reset.interval and price.interval can only differ for prepaid prices.",input:j.value}),j.value!==void 0&&j.value.price!==void 0&&j.value.price!==null){j.value.price.amount&&j.value.price.tiers&&j.value.price.tiers.length>0&&j.issues.push({code:"custom",message:"Price amount and tiers are mutually exclusive.",input:j.value});for(let Ve of Pe(j.value.price))j.issues.push({code:"custom",message:Ve,input:j.value.price})}})}))(g.z,us,wr,Tr,xs,Er,Ot,yn,is,cs,xi,vi,Sn,_n,Pn,vs,Ho),{EntitlementSchema:rf}=((e,t,r,n,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(r).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(n).nullish(),expiry_length:e.number().nullish(),rollover:i.nullish(),feature_override:o.nullish()})}))(g.z,Wm,Wo,Vo,Qo,Is),{ProductItemSchema:Ps}=((e,t,r,n,i,o,a,c,l,p,A)=>({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(r).nullish().meta({internal:!0}),feature:n.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(k=>{if(k==="")throw new Error("Interval cannot be empty.");return k},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(c).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:l.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(p).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:A.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})})}))(g.z,Xm,Jm,us,bn,zm,ep,Yp,Tr,Er,zp),{ProductV2Schema:Cs}=((e,t,r,n,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:r.nullish(),items:e.array(n),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()})}))(g.z,gn,np,Ps,vn,Mi,cr),{PlanItemParamsObjectSchema:nf}=((e,t,r,n,i,o,a,c,l,p,A)=>({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(r).meta({description:"Interval at which balance resets (e.g. 'month', 'year'). For consumable features only."}),interval_count:n({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(c).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(l).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:p.optional().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:A.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})})}))(g.z,Ii,wr,Or,ef,_m,Sn,_n,vi,Pn,vs),{FullProductWithoutLicensesSchema:_y}=((e,t,r,n,i,o)=>({FullProductWithoutLicensesSchema:e.extend({description:t.string().nullable().optional().default(null),prices:t.array(r),entitlements:t.array(n.extend({feature:i})),free_trial:o.nullish(),free_trials:t.array(o).nullish(),free_trial_ids:t.array(t.string()).nullish()})}))(Kp,g.z,Lp,rf,_p,Vm),{CreateProductItemParamsSchema:ws}=((e,t,r,n)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(r.literal(n)).nullish()})}))(Ps,Ii,g.z,bn),{CreatePlanItemParamsV1Schema:Ui}=((e,t)=>({CreatePlanItemParamsV1Schema:e.check(n=>{for(let{message:i,input:o}of t(n.value))n.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."})}))(nf,Ap),{LicenseCustomizeSchema:Os}=((e,t,r,n)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(r).optional(),remove_items:e.array(n).optional()})}))(g.z,wn,Ui,wi),{PlanLicenseParamsSchema:qi}=((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()})}))(g.z,Os),{UpdateProductV2ParamsSchema:xy}=((e,t,r,n,i,o,a,c,l)=>({UpdateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).optional().meta({description:r.id}),name:e.string().refine(A=>A.length>0,{message:"name must be a non-empty string"}).optional().meta({description:r.name}),is_add_on:e.boolean().optional().meta({description:r.is_add_on}),is_default:e.boolean().optional().meta({description:r.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:r.description}),group:e.string().nonempty().nullable().optional().meta({description:r.group}),archived:e.boolean().optional().meta({description:r.archived}),items:e.array(n).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:r.free_trial}),config:a.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:c.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:l.optional().meta({description:r.metadata})})}))(g.z,In,Xo,ws,qi,Jo,Ei,Cn,cr),{CreatePlanParamsV1Schema:af}=((e,t,r,n,i,o,a,c,l)=>({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:r.optional().meta({description:"Base recurring price for the plan. Omit for free or usage-only plans."}),items:e.array(n).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:c.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:l.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})})}))(g.z,In,wn,Ui,qi,Ti,Ei,Xp,cr),{UpdatePlanParamsV1Schema:Iy}=((e,t,r,n,i)=>({UpdatePlanParamsV1Schema:e.partial().extend({group:e.shape.group.removeDefault().optional(),version:t.number().optional(),archived:t.boolean().default(!1).optional(),price:r.nullable().optional().meta({description:"The price of the plan. Set to null to remove the base price."}),free_trial:n.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."})})}))(af,g.z,wn,Ti,In),{CustomizePlanLicenseSchema:Li}=((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()})}))(g.z,Os),{CreateProductV2ParamsSchema:vy}=((e,t,r,n,i,o,a,c,l,p)=>({CreateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).meta({description:r.id}),name:e.string().refine(v=>v.length>0,{message:"name must be a non-empty string"}).meta({description:r.name}),description:e.string().nullish().meta({description:r.description}),is_add_on:e.boolean().default(!1).meta({description:r.is_add_on}),is_default:e.boolean().default(!1).meta({description:r.is_default}),group:e.string().nullable().default("").meta({description:r.group}),items:e.array(n).optional().meta({description:r.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:r.free_trial}),config:a.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:c.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:l.optional().meta({description:r.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:[p]})}))(g.z,In,Xo,ws,qi,Jo,Ei,Cn,cr,rp),{CustomizePlanV1BaseSchema:Es}=((e,t,r,n,i,o,a,c,l)=>({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(r).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(r).optional().meta({description:"Items to add to the plan."}),remove_items:e.array(n).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(c).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(l).optional().meta({description:"License links to drop, keyed by license_plan_id. Parallel to remove_items."})})}))(g.z,wn,Ui,wi,Pm,Ti,Cn,Li,jm),{VariantCustomizeSchema:of}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(As,Es),{DiffedCustomizePlanV1Schema:Py}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(As,Es),{ApiPlanV1Schema:Cy}=((e,t,r,n,i,o,a,c,l,p,A,v,k,U)=>({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(r).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:n.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:c.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(l).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:p.meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:A.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:v.meta({description:"Arbitrary key-value metadata defined by you for your own use. Shared across all versions of the plan."}),customer_eligibility:k.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:U.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."})})}))(g.z,Tr,Ot,xi,cs,tf,Tp,yp,gn,vn,Mi,cr,Sp,of);var S=require("zod"),sf=S.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Rs=S.z.enum(["single_use","continuous_use"]),Bi=S.z.record(S.z.string(),S.z.union([S.z.string(),S.z.number(),S.z.boolean()]).transform(String).pipe(S.z.string())),js=S.z.string().min(1).max(64).refine(e=>!e.includes("::")),ks={credit_amount:S.z.number(),tier_behavior:S.z.never().optional(),tiers:S.z.never().optional()},Ds={credit_amount:S.z.never().optional(),tier_behavior:S.z.literal("graduated"),tiers:S.z.array(S.z.strictObject({to:S.z.union([S.z.number(),S.z.literal("inf")]),credit_amount:S.z.number()}))},cf=S.z.union([S.z.strictObject({match:Bi,priority:S.z.number().int().optional(),...ks}),S.z.strictObject({match:Bi,priority:S.z.number().int().optional(),...Ds})]),uf=S.z.strictObject({match:Bi,factor:S.z.number().positive().optional(),add:S.z.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Ts={metered_feature_id:S.z.string(),feature_amount:S.z.number().optional(),dimensions:S.z.record(js,cf).optional(),multipliers:S.z.record(js,uf).optional()},Fi=S.z.union([S.z.strictObject({...Ts,...ks}),S.z.strictObject({...Ts,...Ds})]),En=S.z.number().min(-100),Ns=S.z.record(S.z.string(),S.z.strictObject({markup:En})).nullish(),jn=S.z.record(S.z.string().regex(/.+\/.+/),S.z.strictObject({markup:En.optional(),input_cost:S.z.number().min(0).optional(),output_cost:S.z.number().min(0).optional()})).nullish(),lf=S.z.strictObject({default_markup:En.optional(),provider_markups:Ns,model_markups:jn}),Vi=S.z.strictObject({schema:S.z.array(Fi).optional(),markups:lf.optional()}),df=S.z.strictObject({filters:S.z.array(S.z.strictObject({property:S.z.string(),operator:S.z.string(),value:S.z.array(S.z.string())})),aggregate:S.z.strictObject({type:S.z.string(),property:S.z.string().nullable()}),usage_type:Rs}),Ms=S.z.strictObject({schema:S.z.array(Fi).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:S.z.boolean().optional(),usage_type:Rs.default("single_use").overwrite(()=>"single_use"),default_markup:En.optional(),provider_markups:Ns}),$i=Ms.safeExtend({schema:S.z.array(Fi).length(0)}),On={id:sf,name:S.z.string().min(1),display:S.z.strictObject({singular:S.z.string().optional(),plural:S.z.string().optional()}).nullish(),event_names:S.z.array(S.z.string()).default([]),model_markups:jn,stripe_meter:S.z.strictObject({id:S.z.string(),event_name:S.z.string()}).nullish(),stripe_product_id:S.z.string().nullish()},Gi=e=>S.z.discriminatedUnion("type",[S.z.strictObject({...On,...e,type:S.z.literal("boolean"),config:S.z.null()}),S.z.strictObject({...On,...e,type:S.z.literal("metered"),config:df}),S.z.strictObject({...On,...e,type:S.z.literal("credit_system"),config:Ms}),S.z.strictObject({...On,...e,type:S.z.literal("ai_credit_system"),config:$i})]),Oy=Gi({}),mf=S.z.strictObject({id:S.z.boolean(),type:S.z.boolean(),usage_type:S.z.boolean()}),pf={internal_id:S.z.uuid(),org_id:S.z.uuid(),created_at:S.z.number(),env:S.z.enum(["sandbox","live"]),archived:S.z.boolean(),project_id:S.z.uuid(),environment_id:S.z.uuid(),revision:S.z.number().int().nonnegative(),update_rules:mf},Us=Gi(pf),Ey=S.z.strictObject({rows:S.z.array(Us).max(200),nextCursor:S.z.uuid().nullable()}),qs=S.z.strictObject({features:S.z.array(Us).max(500),limited:S.z.boolean()}),jy=S.z.union([Gi({action:S.z.literal("save"),internal_id:S.z.uuid().nullable(),revision:S.z.number().int().nonnegative()}),S.z.strictObject({action:S.z.enum(["archive","restore","delete"]),internal_id:S.z.uuid(),revision:S.z.number().int().nonnegative()})]);var Vt=require("zod"),Ls=Vt.z.number().int().min(0).max(1e8),Rr=Vt.z.strictObject({kind:Vt.z.enum(["graduated","volume"]),tiers:Vt.z.array(Vt.z.strictObject({upTo:Vt.z.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Ls,flatAmountMinor:Ls.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,r)=>{let n=e.tiers[r-1]?.upTo;return t.upTo!==null&&(r===0||n!=null&&t.upTo>n)}),"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 Hi(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let r=e.pricing?Rr.parse(e.pricing):void 0;if(t===0)return 0;let n=0n,i=0;if(!r)n=BigInt(e.amountMinor)*BigInt(t);else for(let o of r.tiers){let a=o.upTo??1e4;if(r.kind==="volume"){if(t<=a){n=BigInt(t)*BigInt(o.unitAmountMinor)+BigInt(o.flatAmountMinor??0);break}}else t>i&&(n+=BigInt(Math.min(t,a)-i)*BigInt(o.unitAmountMinor));i=a}if(n>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(n)}function Tn(e){return Hi({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var C=require("zod");var u=require("zod");var D=require("zod");var Le=require("zod");var b=require("zod");var Ze=b.z.json().superRefine((e,t)=>{let r=0;function n(i,o){if(++r>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=>n(a,o+1));else if(i&&typeof i=="object")for(let[a,c]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"}),n(c,o+1)}n(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),At=b.z.record(b.z.string().min(1).max(128),Ze).superRefine((e,t)=>{(!Ze.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(r=>Object.hasOwn(e,r)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),ff=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"]),ut=At.superRefine((e,t)=>{function r(n){if(Array.isArray(n))n.forEach(r);else if(n&&typeof n=="object")for(let[i,o]of Object.entries(n)){if(i==="$savedGroup"&&!b.z.strictObject({id:b.z.uuid(),attributeKey:b.z.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("$")&&!ff.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,c)=>String.fromCharCode(Number.parseInt(c,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"})}}r(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"}),r(e)}),hf=b.z.discriminatedUnion("type",[b.z.strictObject({type:b.z.literal("condition"),condition:ut}),b.z.strictObject({type:b.z.literal("list"),attributeKey:b.z.string().min(1).max(128),values:b.z.array(b.z.union([b.z.string(),b.z.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 Wi(e){let t=new Set;function r(n){if(Array.isArray(n))n.forEach(r);else if(n&&typeof n=="object")for(let[i,o]of Object.entries(n))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)||r(o)}return r(e),[...t]}var Af=b.z.record(b.z.uuid(),hf).superRefine((e,t)=>{let r=new Set,n=new Set;function i(o){if(r.has(o)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(n.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}r.add(o),a.type==="condition"&&Wi(a.condition).forEach(i),r.delete(o),n.add(o)}Object.keys(e).forEach(i)}),Zi=b.z.tuple([b.z.number().min(0).max(1),b.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),Bs=b.z.strictObject({attribute:b.z.string().optional(),seed:b.z.string().min(1),hashVersion:b.z.literal(2),ranges:b.z.array(Zi).min(1).max(100)}),gf=b.z.strictObject({id:b.z.string().min(1).max(128),condition:ut,gate:b.z.boolean().optional()}),Ki={id:b.z.string().max(128).optional(),condition:ut.optional(),parentConditions:b.z.array(gf).max(50).optional(),filters:b.z.array(Bs).max(20).optional()},bf=b.z.union([b.z.strictObject({...Ki}),b.z.strictObject({...Ki,force:Ze,coverage:b.z.number().min(0).max(1).optional(),range:Zi.optional(),seed:b.z.string().min(1).optional(),hashAttribute:b.z.string().optional(),hashVersion:b.z.literal(2).optional()}),b.z.strictObject({...Ki,type:b.z.literal("experiment-ref"),experimentId:b.z.uuid(),values:b.z.record(b.z.string().min(1),Ze),meta:b.z.record(b.z.string().min(1),b.z.strictObject({passthrough:b.z.boolean()})).optional()})]),yf=b.z.strictObject({defaultValue:Ze,rules:b.z.array(bf).max(100)}),ky=b.z.record(b.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),yf).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let r=new Set,n=new Set;function i(o){if(r.has(o)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${o}`});return}if(n.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${o}`});return}r.add(o);for(let c of a.rules)for(let l of c.parentConditions??[])i(l.id);r.delete(o),n.add(o)}Object.keys(e).forEach(i)}),Sf=b.z.strictObject({name:b.z.string().max(80),reason:b.z.string().max(500),dateStarted:b.z.iso.datetime({offset:!0}),dateEnded:b.z.iso.datetime({offset:!0}).nullable(),coverage:b.z.number().min(0).max(1),variationWeights:b.z.array(b.z.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,r)=>t+r,0)-1)<=.01),condition:ut,savedGroups:b.z.array(b.z.strictObject({match:b.z.enum(["any","all","none"]),ids:b.z.array(b.z.uuid()).min(1)})).max(50),namespace:b.z.strictObject({id:b.z.uuid(),ranges:b.z.array(Zi).min(1)}).nullable(),seed:b.z.string().min(1).max(128)}),_f=b.z.strictObject({key:b.z.string().min(1).max(128),name:b.z.string().min(1).max(80),hypothesis:b.z.string().max(2e3),status:b.z.enum(["draft","running","stopped"]),hashAttribute:b.z.string().min(1).max(128),fallbackAttribute:b.z.string().max(128).nullable(),hashVersion:b.z.literal(2),disableStickyBucketing:b.z.boolean(),bucketVersion:b.z.number().int().min(0).max(1e3),minBucketVersion:b.z.number().int().min(0).max(1e3),variations:b.z.array(b.z.strictObject({id:b.z.string().min(1),key:b.z.string().min(1),name:b.z.string().max(80),description:b.z.string().max(500)})).min(2).max(20),phases:b.z.array(Sf).min(1).max(100),releasedVariationId:b.z.string().nullable(),excludeFromPayload:b.z.boolean(),statusSchedule:b.z.strictObject({startAt:b.z.iso.datetime({offset:!0}).nullable(),stopAt:b.z.iso.datetime({offset:!0}).nullable(),stopAfter:b.z.strictObject({value:b.z.number().int().positive().max(36500),unit:b.z.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((r,n)=>{if(n===0)return!1;let i=e.phases[n-1];return!i?.dateEnded||Date.parse(r.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(r.dateStarted)})||new Set(e.variations.map(r=>r.key)).size!==e.variations.length||new Set(e.variations.map(r=>r.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(r=>r.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(r=>r.dateEnded&&Date.parse(r.dateStarted)>=Date.parse(r.dateEnded)||r.namespace?.ranges.some(([n,i],o,a)=>n>=i||a.some(([c,l],p)=>p!==o&&n<l&&c<i)))||e.phases.some(r=>r.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var xf=_f.safeExtend({filters:b.z.array(Bs).optional()}),If=b.z.strictObject({experiments:b.z.record(b.z.uuid(),xf),savedGroups:Af}),vf=b.z.strictObject({attributeName:b.z.string(),attributeValue:b.z.string(),assignments:b.z.record(b.z.string(),b.z.string())}),Dy=b.z.strictObject({snapshot:If,attributes:At,results:At,stickyBucketAssignmentDocs:b.z.record(b.z.string(),vf)}),Ny=b.z.strictObject({variantKey:b.z.string().nullable(),bucketVersion:b.z.number().int().min(0),source:b.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:b.z.number().min(0).max(1).optional(),stickyBucketUsed:b.z.boolean().optional(),hashUsed:b.z.boolean().optional()});function Fs(e){let t=new Set,r=o=>o!==null&&typeof o=="object"&&!Array.isArray(o);function n(o,a){if(r(o))for(let[c,l]of Object.entries(o))c==="$elemMatch"?i(l,a):c==="$not"?n(l,a):c==="$all"&&Array.isArray(l)&&l.forEach(p=>n(p,a))}function i(o,a=""){if(r(o)){for(let[c,l]of Object.entries(o))if(["$and","$or","$nor"].includes(c)&&Array.isArray(l))l.forEach(p=>i(p,a));else if(c==="$not")i(l,a);else if(c==="$savedGroup"&&r(l))typeof l.attributeKey=="string"&&t.add(l.attributeKey);else if(!c.startsWith("$")){let p=a?`${a}.${c}`:c;t.add(p),n(l,p)}}}return i(e),[...t]}var Pf=Le.z.enum(["active","inactive"]),Cf=Le.z.preprocess((e,t)=>{let r=0;function n(i,o){if(!(++r>1e4||o>20)){if(Array.isArray(i))i.forEach(a=>n(a,o+1));else if(i&&typeof i=="object")for(let[a,c]of Object.entries(i))["__proto__","constructor","prototype"].includes(a)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),n(c,o+1)}}return n(e,0),e},At),wf=Le.z.strictObject({id:Le.z.string().trim().min(1).max(255),name:Le.z.string().trim().min(1).max(255),status:Pf,metadata:Cf}),By=wf.extend({internal_id:Le.z.uuid(),project_id:Le.z.uuid(),environment_id:Le.z.uuid(),created_at:Le.z.iso.datetime({offset:!0}),updated_at:Le.z.iso.datetime({offset:!0})}),$s=Le.z.union([Le.z.strictObject({id:Le.z.string().trim().min(1).max(255)}),Le.z.strictObject({internalId:Le.z.uuid()})]),Fy=Le.z.enum(["customer","merchandise","context"]),Vy=Le.z.enum(["system","stored","request"]),$y=Le.z.enum(["customer","merchandise","mixed"]),Vs=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Qi(e,t={},r=new Set){if(Fs(e).some(Vs))return!0;for(let n of Wi(e)){if(r.has(n))continue;r.add(n);let i=t[n];if(i?.type==="list"&&Vs(i.attributeKey)||i?.type==="condition"&&Qi(i.condition,t,r))return!0}return!1}var Gs=require("zod"),Of=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,lt=Gs.z.string().max(16).regex(Of,"\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");var Qy=D.z.enum(["draft","active","paused","archived"]),Et=D.z.discriminatedUnion("type",[D.z.object({type:D.z.literal("percent"),percentOff:D.z.number().int().min(1).max(100)}).strict(),D.z.object({type:D.z.literal("amount"),amountOffCents:D.z.number().int().min(1).max(1e8),currency:J}).strict()]),tt=D.z.discriminatedUnion("type",[D.z.object({type:D.z.literal("once")}).strict(),D.z.object({type:D.z.literal("repeating"),months:D.z.number().int().min(1).max(36)}).strict(),D.z.object({type:D.z.literal("forever")}).strict()]),Hs=[D.z.object({type:D.z.literal("all")}).strict(),D.z.object({type:D.z.literal("plans"),planIds:D.z.array(D.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Ef=D.z.discriminatedUnion("type",[...Hs,D.z.strictObject({type:D.z.literal("merchandise"),scope:D.z.discriminatedUnion("type",[D.z.strictObject({type:D.z.literal("all")}),D.z.strictObject({type:D.z.literal("selected"),merchandiseIds:D.z.array(D.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),D.z.strictObject({type:D.z.literal("condition"),condition:ut})])})]),Yi=D.z.discriminatedUnion("type",[...Hs,D.z.strictObject({type:D.z.literal("merchandise"),scope:D.z.strictObject({type:D.z.enum(["all","selected","condition"])})})]),jf=D.z.strictObject({firstPurchaseOnly:D.z.boolean(),condition:ut}),Yy=D.z.object({name:D.z.string().trim().min(1).max(80),description:D.z.string().max(500),discount:Et,duration:tt,appliesTo:Ef,eligibility:jf,selfClaimEnabled:D.z.boolean().default(!1),startsAt:D.z.iso.datetime().nullable(),endsAt:D.z.iso.datetime().nullable(),totalLimit:D.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:D.z.number().int().min(1).max(10),grantWindowHours:D.z.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!Qi(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),Xy=D.z.object({code:D.z.string().trim().transform(e=>e.toUpperCase()).pipe(D.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:D.z.number().int().min(1).max(1e6).nullable(),expiresAt:D.z.iso.datetime().nullable(),firstPurchaseOnly:D.z.boolean(),minimumAmountCents:D.z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:J.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Xi=D.z.object({id:D.z.uuid(),couponId:D.z.uuid(),status:D.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:D.z.iso.datetime(),expiresAt:D.z.iso.datetime(),coupon:D.z.object({name:D.z.string(),discount:Et,duration:tt,appliesTo:Yi}).strict()}).strict(),Ks=D.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var ve=require("zod"),Je=ve.z.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),Z=ve.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Rn=ve.z.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}),Ji=Z.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ws=ve.z.string().min(1).max(64),$t=ve.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Zs=ve.z.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Ne=ve.z.record(Ws,ve.z.union([ve.z.string().max(120),ve.z.number().finite(),ve.z.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,r])=>[t,String(r)]))),Qs=ve.z.record(Ws,ve.z.union([ve.z.string().max(120),ve.z.number().finite(),ve.z.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),ur=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[r,n=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");let i=BigInt(r)*BigInt("1000000")+BigInt(n.padEnd(6,"0"));return t?-i:i},Ys=ve.z.array(ve.z.object({upTo:Ji.nullable(),cost:Z}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,r)=>{let n=e[r-1]?.upTo;return t.upTo!==null&&(r===0||n!=null&&ur(t.upTo)>ur(n))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),Tf=ve.z.object({key:Zs,match:Qs,priority:ve.z.number().int().default(0),cost:Z.optional(),tiers:Ys.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),Rf=ve.z.object({key:Zs,match:Qs,factor:Ji.optional(),add:Rn.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"})),kf=ve.z.object({units:Ji.default("1"),cost:Z,tiers:Ys.optional(),dimensions:ve.z.array(Tf).max(12).optional(),multipliers:ve.z.array(Rf).max(4).optional()}).strict().superRefine((e,t)=>{let r=e.dimensions??[],n=e.multipliers??[];(new Set(r.map(a=>a.key)).size!==r.length||new Set(n.map(a=>a.key)).size!==n.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[a,c]of r.entries())for(let l of r.slice(a+1))Object.keys(c.match).length===Object.keys(l.match).length&&c.priority===l.priority&&!Object.keys(c.match).some(p=>l.match[p]!==void 0&&l.match[p]!==c.match[p])&&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),...r.flatMap(a=>[...a.cost===void 0?[]:[a.cost],...(a.tiers??[]).map(c=>c.cost)])],o=ur(e.units);for(let a of i)for(let c=0;c<1<<n.length;c++){let l=n.filter((ie,q)=>c&1<<q);if(l.some((ie,q)=>l.slice(q+1).some(Pe=>Object.keys(ie.match).some(Me=>Pe.match[Me]!==void 0&&Pe.match[Me]!==ie.match[Me]))))continue;let p=ur(a),A=BigInt("1"),v=BigInt("0");for(let[ie,q]of n.entries())c&1<<ie&&(p*=ur(q.factor??"1"),A*=BigInt("1000000"),v+=ur(q.add??"0"));let k=(p+v*A)*BigInt("1000000"),U=A*o;(k<BigInt("0")||k%U!==BigInt("0")||k/U>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"})}}),zy=kf.safeExtend({featureKey:$t});var tc=u.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),zi=u.z.string().regex(/^(0|[1-9]\d{0,14})$/),lr=u.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Df=u.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),kr=Df,It=Z.refine(e=>/[1-9]/.test(e)),Qe=u.z.iso.datetime({offset:!0}),Gt=e=>{let[t,r=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(r.padEnd(6,"0"))},Nf=u.z.array(u.z.object({upTo:It.nullable(),unitAmountMinor:tc,flatAmountMinor:u.z.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,r)=>{let n=e[r-1]?.upTo;return t.upTo!==null&&(r===0||n!=null&&Gt(t.upTo)>Gt(n))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Mf=u.z.discriminatedUnion("kind",[u.z.object({kind:u.z.literal("flat"),units:It,unitAmountMinor:tc}).strict(),u.z.object({kind:u.z.enum(["graduated","volume"]),units:It,tiers:Nf}).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"),Uf=u.z.strictObject({interval:u.z.enum(["month","year"]),count:u.z.number().int().min(1).max(12),anchor:u.z.enum(["membership","calendar"])}),jt=u.z.object({currency:J,pricing:Mf,billingCycle:Uf.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function rc(e){return e.pricing.kind==="flat"&&Gt(e.pricing.units)>0n&&Gt(e.pricing.unitAmountMinor)===Gt(e.pricing.units)*BigInt(10**ko(e.currency))}var Xs={requestId:u.z.uuid(),productVersionId:u.z.uuid(),internal_feature_id:u.z.uuid(),currency:J},nc=u.z.strictObject({interval:u.z.enum(["hour","day","week","month"]),intervalCount:u.z.number().int().min(1).max(12),limit:u.z.number().int().min(1).max(1e6)}),ic=u.z.discriminatedUnion("kind",[u.z.object({...Xs,kind:u.z.literal("auto_topup"),threshold:Rn,quantity:It.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:nc.optional()}).strict(),u.z.object({...Xs,kind:u.z.literal("postpaid"),maxAmountMinorPerPeriod:kr,maxOutstandingMinor:kr}).strict()]),Js={productVersionId:u.z.uuid(),internal_feature_id:u.z.uuid(),currency:J},ac=u.z.discriminatedUnion("kind",[u.z.object({...Js,kind:u.z.literal("auto_topup"),threshold:Rn,quantity:It.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:nc.optional(),purchaseAmountMinor:kr,purchaseUnits:It}).strict(),u.z.object({...Js,kind:u.z.literal("postpaid"),maxAmountMinorPerPeriod:kr,maxOutstandingMinor:kr,cashPrice:jt}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),kn=u.z.object({id:u.z.uuid(),terms:ac,status:u.z.enum(["prepared","active","revoked","blocked"]),createdAt:Qe,acceptedAt:Qe.nullable(),effectiveAt:Qe.nullable(),revokedAt:Qe.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"),oc=u.z.object({authorizationId:u.z.uuid(),terms:ac,setupUrl:u.z.url().nullable()}).strict(),sc=u.z.object({authorizationId:u.z.uuid(),accepted:u.z.literal(!0)}).strict(),cc=u.z.object({authorizationId:u.z.uuid(),requestId:u.z.uuid()}).strict(),uc=u.z.object({internal_feature_id:u.z.uuid(),entityId:u.z.uuid().nullable(),interval:u.z.enum(["day","week","month","year"]),anchor:u.z.enum(["billing_cycle","utc"]).optional(),basis:u.z.enum(["usage","credits"]),filter:Ne.optional(),limit:Z.nullable(),thresholds:u.z.array(u.z.number().positive().max(1)).max(8),includedThresholds:u.z.array(u.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:u.z.array(It).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,r)=>{let n=e.thresholds[r-1];return r===0||n!==void 0&&t>n})&&(e.includedThresholds??[]).every((t,r,n)=>{let i=n[r-1];return r===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,r,n)=>{let i=n[r-1];return r===0||i!==void 0&&Gt(t)>Gt(i)}),"Notification thresholds must increase"),qf=uc.safeExtend({requestId:u.z.uuid()}),zs={control:u.z.literal("overage"),requestId:u.z.uuid(),internal_feature_id:u.z.uuid(),entityId:u.z.uuid().nullable()},Lf=u.z.discriminatedUnion("action",[u.z.strictObject({...zs,action:u.z.literal("set"),allowed:u.z.boolean().nullable(),overageLimit:Z.nullable(),skipOverageBilling:u.z.boolean()}),u.z.strictObject({...zs,action:u.z.literal("remove")})]),lc=u.z.union([qf,Lf]),Bf=u.z.strictObject({internal_feature_id:u.z.uuid(),entityId:u.z.uuid().nullable(),allowed:u.z.boolean().nullable(),overageLimit:Z.nullable(),skipOverageBilling:u.z.boolean(),interval:u.z.enum(["day","week","month","year"]),startsAt:Qe,endsAt:Qe,used:u.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:u.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:u.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Ff=u.z.object({internal_feature_id:u.z.uuid(),entityId:u.z.uuid().nullable(),interval:u.z.enum(["day","week","month","year"]),anchor:u.z.enum(["billing_cycle","utc"]).optional(),basis:u.z.enum(["usage","credits"]),filter:Ne.optional(),startsAt:Qe,endsAt:Qe,used:Je,reserved:Je,limit:Z.nullable(),thresholds:u.z.array(u.z.number().positive().max(1)).max(8),notifiedThresholds:u.z.array(u.z.number().positive().max(1)).max(1024),includedThresholds:u.z.array(u.z.number().positive().max(1)).max(8).optional(),includedAllowance:u.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:u.z.array(u.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:u.z.array(It).max(8).optional(),notifiedAbsoluteThresholds:u.z.array(It).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||Z.safeParse(e.used).success&&Z.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Vf=u.z.object({authorizationId:u.z.uuid(),status:u.z.enum(["idle","pending","blocked"]),taskId:u.z.uuid().nullable(),invoiceId:u.z.uuid().nullable(),hostedInvoiceUrl:u.z.url().nullable(),purchaseCount:u.z.number().int().nonnegative(),purchaseWindowEndsAt:Qe.nullable(),attemptCount:u.z.number().int().nonnegative(),failedAttemptCount:u.z.number().int().nonnegative(),suspendedAt:Qe.nullable(),nextAttemptAt:Qe.nullable(),failureReason:u.z.string().min(1).max(240).nullable()}).strict(),dc=u.z.object({internal_feature_id:u.z.uuid().optional(),entityId:u.z.uuid().optional()}).strict(),ea=u.z.object({authorizations:u.z.array(kn).max(100),limits:u.z.array(uc).max(100),overages:u.z.array(Bf).max(100).optional(),windows:u.z.array(Ff).max(200),autoTopups:u.z.array(Vf).max(100),limited:u.z.boolean()}).strict(),$f=u.z.object({id:u.z.uuid(),internal_feature_id:u.z.uuid(),productVersionId:u.z.uuid(),authorizationId:u.z.uuid(),entityId:u.z.uuid().nullable(),units:Z,amountMinor:lr,cashPrice:jt}).strict(),Dr=u.z.object({id:u.z.uuid(),sourceKind:u.z.enum(["product","usage","manual"]),providerInvoiceId:u.z.string().min(1).max(240).nullable(),status:u.z.enum(["accruing","open","pending","paid","failed","void"]),currency:J,startsAt:Qe.nullable(),endsAt:Qe.nullable(),amountMinor:u.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:u.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:zi,paidAmountMinor:zi,refundedAmountMinor:zi,createdAt:Qe,hostedInvoiceUrl:u.z.url().nullable(),adjustment:u.z.object({originalInvoiceId:u.z.uuid(),amountMinor:u.z.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:Qe.nullable()}).strict().nullable(),lines:u.z.array($f).max(100),linesLimited:u.z.boolean()}).strict(),mc=u.z.object({invoiceId:u.z.uuid(),accepted:u.z.literal(!0)}).strict(),pc=u.z.object({after:u.z.uuid().nullable(),limit:u.z.number().int().min(1).max(100)}).strict(),fc=u.z.object({rows:u.z.array(Dr).max(100),nextCursor:u.z.uuid().nullable()}).strict(),ec=u.z.strictObject({id:u.z.string(),coupon:u.z.string(),start:u.z.number().nonnegative(),end:u.z.number().nullable()}),Gf=u.z.strictObject({subscriptionId:u.z.string(),customerId:u.z.string(),accountId:u.z.string(),sourceItems:u.z.array(u.z.strictObject({id:u.z.string(),price_id:u.z.string(),quantity:u.z.number().int(),discounts:u.z.array(ec).optional()})).max(100),items:u.z.array(u.z.strictObject({id:u.z.string(),price:u.z.string(),quantity:u.z.number().int(),discounts:u.z.array(u.z.strictObject({coupon:u.z.string().optional(),terms:u.z.strictObject({id:u.z.string(),name:u.z.string().optional(),percent_off:u.z.number().optional(),amount_off:u.z.number().optional(),currency:u.z.string().optional(),duration:u.z.enum(["once","forever","repeating"]),duration_in_months:u.z.number().optional()}).optional(),discount:u.z.string().optional(),receipt:ec.optional()})).max(20)})).max(100)}),hc=u.z.strictObject({membershipId:u.z.uuid(),requestId:u.z.uuid(),grantIds:u.z.array(u.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Ac=u.z.strictObject({membershipId:u.z.uuid(),operationId:u.z.uuid(),status:u.z.enum(["pending","effective"]),execution:Gf.nullable(),grants:u.z.array(u.z.strictObject({id:u.z.uuid(),couponId:u.z.uuid(),name:u.z.string(),discount:Et,duration:tt,startedAt:Qe.nullable()})).max(20)});var dr=require("zod");var Nr=dr.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Mr=dr.z.number().int().min(1).max(1e3),Ht=dr.z.object({cap:Z.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:dr.z.number().positive().max(1e4).nullable(),cycles:dr.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var ta={key:Ft,name:C.z.string().trim().min(1).max(80),description:C.z.string().trim().max(240)},gc=Z.refine(e=>/[1-9]/.test(e)),Dn=C.z.array(C.z.object({currency:J,amountMinor:C.z.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"),ra=C.z.strictObject({units:gc,prices:C.z.array(C.z.strictObject({currency:J,amountMinor:C.z.number().int().min(0).max(1e8),pricing:Rr.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:C.z.number().int().min(0).max(1e4),maximumQuantity:C.z.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 r of[e.maximumQuantity,...t.pricing?.tiers.flatMap(n=>n.upTo===null?[]:[n.upTo,n.upTo+1])??[]])r<=e.maximumQuantity&&Hi({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},r);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit"),Hf=C.z.discriminatedUnion("kind",[C.z.object({kind:C.z.literal("access"),internal_feature_id:C.z.uuid()}).strict(),C.z.object({kind:C.z.literal("metered"),internal_feature_id:C.z.uuid(),usageUnit:C.z.enum(["count","micro_usd"]),amount:Z.nullable(),reset:Nr,resetCount:Mr,pooled:C.z.boolean(),rollover:Ht.nullable().optional(),cashPrice:jt.nullable().optional(),prepaidPrice:ra.optional(),feature_override:Vi.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 ia(e.amount,e.prepaidPrice.units,e.prepaidPrice.maximumQuantity),!0}catch{return!1}},"The maximum purchased allowance must fit the quantity ledger"),C.z.object({kind:C.z.literal("credit"),internal_feature_id:C.z.uuid(),amount:Z,reset:Nr,resetCount:Mr,rollover:Ht.nullable(),pooled:C.z.boolean(),feature_override:Vi.nullish(),cashPrice:jt.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&rc(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")]),na=C.z.array(Hf).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),bc=C.z.object({days:C.z.number().int().min(1).max(730),cardRequired:C.z.boolean(),allowances:na}).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"),yc=C.z.object({key:Ft,internal_feature_id:C.z.uuid(),productVersionId:C.z.uuid(),includedQuantity:C.z.number().int().min(0).max(1e4),maximumQuantity:C.z.number().int().min(0).max(1e4),prices:Dn,pooled_internal_feature_ids:C.z.array(C.z.uuid()).max(100),requireAssignment:C.z.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"),Sc=C.z.discriminatedUnion("kind",[C.z.object({...ta,kind:C.z.literal("membership"),groupId:C.z.uuid(),membershipType:C.z.enum(["main","addon"]),interval:C.z.enum(["free","week","month","year","one_time"]),intervalCount:C.z.number().int().min(1).max(156).optional(),prices:Dn,allowances:na,trial:bc.nullable(),licenses:C.z.array(yc).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(r=>r.kind==="metered"&&r.prepaidPrice?.prices.some(n=>n.currency===t.currency&&n.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(r=>e.prices.some(n=>n.currency===r.currency))),"Purchased features require a paid plan and all its published currencies"),C.z.object({...ta,kind:C.z.literal("topup"),interval:C.z.literal("one_time"),prices:Dn,internal_feature_id:C.z.uuid(),amount:gc,expiresDays:C.z.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),Kf=C.z.object({interval:C.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:C.z.number().int().min(1).max(156).nullable().optional(),prices:Dn.optional(),allowances:C.z.object({upsert:na,remove:C.z.array(C.z.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:bc.nullable().optional(),licenses:C.z.array(yc).max(20).optional()}).strict(),Wf=C.z.object({...ta,kind:C.z.literal("variant"),baseProductVersionId:C.z.uuid(),overrides:Kf}).strict(),hS=C.z.union([Sc,Wf]),AS=C.z.object({products:C.z.array(C.z.object({id:C.z.uuid(),productId:C.z.string().min(1),name:C.z.string(),kind:C.z.enum(["membership","topup"]),version:C.z.number().int().positive()}).strict()).max(500),limited:C.z.boolean()}).strict(),Zf=Cs.and(C.z.object({internal_id:C.z.uuid(),revision:C.z.number().int().nonnegative(),licenses:C.z.array(Li)})),gS=C.z.strictObject({rows:C.z.array(Zf).max(200),nextCursor:C.z.uuid().nullable()}),bS=C.z.object({groups:C.z.array(C.z.object({id:C.z.uuid(),name:C.z.string(),defaultProductVersionId:C.z.uuid().nullable()}).strict()).max(500),features:qs.shape.features,products:C.z.array(C.z.object({id:C.z.uuid(),productId:C.z.uuid(),version:C.z.number().int().positive(),configuration:Sc,baseProductVersionId:C.z.uuid().nullable()}).strict()).max(500),limited:C.z.boolean()}).strict();function ia(e,t,r){let n=a=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(a))throw new Error("Invalid quantity");let[c,l=""]=a.split(".");if(c===void 0||c==="")throw new Error("Invalid decimal value");return BigInt(c)*1000000n+BigInt(l.padEnd(6,"0"))};if(!Number.isSafeInteger(r)||r<0||r>1e4)throw new Error("Invalid purchased quantity");let i=n(e)+n(t)*BigInt(r);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 vt=require("zod");var _c=vt.z.strictObject({itemKey:vt.z.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:vt.z.uuid(),includedAmount:vt.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:vt.z.number().int().min(0).max(1e4),terms:ra,pricing:Rr.optional(),unitAmountMinor:vt.z.number().int().min(0).max(1e8),productId:vt.z.string().min(1).max(255).nullable(),priceId:vt.z.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{ia(e.includedAmount,e.terms.units,e.quantity),Tn({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var N=require("zod");var Kt=Z.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Ur=N.z.string().min(1).max(120),Nn=N.z.enum(["cap","overflow"]),rt=(e,t)=>{let[r,n=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");return BigInt(r)*10n**BigInt(t)+BigInt(n.padEnd(t,"0"))},qr=e=>{try{return e()}catch{return!1}},Lr=N.z.discriminatedUnion("operation",[N.z.object({operation:N.z.literal("quote"),overageBehavior:Nn.optional(),internal_feature_id:N.z.uuid(),entityId:N.z.uuid().optional(),quantity:Kt,properties:Ne}).strict(),N.z.object({operation:N.z.literal("consume"),overageBehavior:Nn.optional(),occurredAt:N.z.iso.datetime({offset:!0}).optional(),internal_feature_id:N.z.uuid(),entityId:N.z.uuid().optional(),quantity:Z,properties:Ne,idempotencyKey:Ur}).strict(),N.z.object({operation:N.z.literal("reserve"),occurredAt:N.z.iso.datetime({offset:!0}).optional(),internal_feature_id:N.z.uuid(),entityId:N.z.uuid().optional(),quantity:Kt,properties:Ne,idempotencyKey:Ur,expiresInSeconds:N.z.number().int().min(1).max(86400)}).strict(),N.z.object({operation:N.z.literal("confirm"),operationId:N.z.uuid(),quantity:Kt,properties:Ne.optional(),idempotencyKey:Ur}).strict(),N.z.object({operation:N.z.literal("refund"),operationId:N.z.uuid(),quantity:Kt,idempotencyKey:Ur}).strict(),N.z.object({operation:N.z.literal("release"),operationId:N.z.uuid(),idempotencyKey:Ur}).strict()]),aa=N.z.object({internal_credit_feature_id:N.z.uuid().nullable(),internal_metered_feature_id:N.z.uuid(),dimension:N.z.string().min(1).max(64),counterKey:N.z.string().min(1).max(240),cycleStart:N.z.iso.datetime({offset:!0}),unitCost:Z,units:Kt,amount:Je,tier:N.z.number().int().min(1).max(12).nullable()}).strict(),Wt=N.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function xc(e,t){let r=e.reduce((n,i)=>n+rt(i.units,12),0n)-rt(t,12);return e.some(n=>n.funding==="balance")?r>=-100n&&r<=100n:r===0n}var Ic=N.z.discriminatedUnion("funding",[N.z.strictObject({funding:N.z.literal("balance"),sourceId:N.z.uuid(),rolloverId:N.z.uuid().nullable(),units:Wt.refine(e=>/[1-9]/.test(e)),amount:Je}),N.z.strictObject({funding:N.z.literal("unbilled"),units:Wt.refine(e=>/[1-9]/.test(e))}),N.z.object({funding:N.z.literal("prepaid"),sourceId:N.z.uuid(),units:Kt,amount:Je,pricing:N.z.array(aa).min(1).max(12)}).strict().refine(e=>qr(()=>e.pricing.reduce((t,r)=>t+rt(r.units,6),0n)===rt(e.units,6)&&e.pricing.reduce((t,r)=>t+rt(r.amount,12),0n)===rt(e.amount,12)&&e.pricing.every(t=>rt(t.unitCost,6)*rt(t.units,6)===rt(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),N.z.object({funding:N.z.literal("postpaid"),invoiceLineId:N.z.uuid().nullable(),units:Kt,authorizationId:N.z.uuid()}).strict()]),Mn=N.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),vc=N.z.object({allowed:N.z.boolean(),internal_feature_id:N.z.uuid(),quantity:Z,requestedQuantity:Z.optional(),overageBehavior:Nn.optional(),reason:Mn.nullable(),allocations:N.z.array(Ic).max(500)}).strict().refine(e=>qr(()=>e.allowed?e.reason===null&&xc(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>qr(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&rt(e.requestedQuantity,6)>=rt(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Br=N.z.object({id:N.z.uuid(),internal_feature_id:N.z.uuid(),kind:N.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:N.z.uuid().nullable(),quantity:Z,requestedQuantity:Z.optional(),overageBehavior:Nn.optional(),accepted:N.z.boolean(),reason:N.z.enum([...Mn.options,"expired"]).nullable(),createdAt:N.z.iso.datetime({offset:!0}),reservationStatus:N.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:N.z.iso.datetime({offset:!0}).nullable(),allocations:N.z.array(Ic).max(500)}).strict().refine(e=>qr(()=>e.accepted?e.reason===null&&xc(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>qr(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&rt(e.requestedQuantity,6)>=rt(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");var oe=require("zod");var Zt=oe.z.iso.datetime({offset:!0}),Pc=Z.refine(e=>/[1-9]/.test(e)),Cc=oe.z.strictObject({interval:Nr.exclude(["lifetime"]),count:Mr}),Qf=oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),internal_feature_id:oe.z.uuid(),entityId:oe.z.uuid().nullable(),amount:Pc.nullable(),expiresAt:Zt.nullable(),reset:Cc.nullable(),rollover:Ht.nullable(),nextResetAt:Zt.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),wc=oe.z.discriminatedUnion("action",[Qf,oe.z.strictObject({action:oe.z.literal("update"),requestId:oe.z.uuid(),grantId:oe.z.uuid(),revision:oe.z.number().int().nonnegative(),amount:Pc.nullable(),expiresAt:Zt.nullable(),rollover:Ht.nullable(),nextResetAt:Zt.nullable()}),oe.z.strictObject({action:oe.z.enum(["add","subtract","set_remaining"]),requestId:oe.z.uuid(),grantId:oe.z.uuid(),revision:oe.z.number().int().nonnegative(),amount:Z}),oe.z.strictObject({action:oe.z.literal("revoke"),requestId:oe.z.uuid(),grantId:oe.z.uuid(),revision:oe.z.number().int().nonnegative()})]),oa=oe.z.strictObject({id:oe.z.uuid(),internal_feature_id:oe.z.uuid(),entityId:oe.z.uuid().nullable(),amount:Z.nullable(),reset:Cc.nullable(),rollover:Ht.nullable(),nextResetAt:Zt.nullable(),startsAt:Zt,expiresAt:Zt.nullable(),revision:oe.z.number().int().nonnegative(),revoked:oe.z.boolean(),available:Je,held:Je,spent:Je}),Oc=oe.z.strictObject({customerId:oe.z.uuid(),after:oe.z.uuid().nullable(),limit:oe.z.number().int().min(1).max(100)}),Ec=oe.z.strictObject({rows:oe.z.array(oa).max(100),nextCursor:oe.z.uuid().nullable()});var L=require("zod");var gt=L.z.iso.datetime({offset:!0}),jc=L.z.strictObject({invoiceId:L.z.uuid(),after:L.z.string().min(1).max(180).nullable(),limit:L.z.number().int().min(1).max(100)}),Yf=L.z.strictObject({kind:L.z.literal("product"),key:L.z.string(),productVersionId:L.z.uuid(),productName:L.z.string(),itemKey:L.z.string(),entityId:L.z.uuid().nullable(),quantity:L.z.number().int().positive(),subtotalMinor:L.z.string().regex(/^-?\d+$/),discountMinor:L.z.string().regex(/^\d+$/),taxMinor:L.z.string().regex(/^-?\d+$/).nullable(),totalMinor:L.z.string().regex(/^-?\d+$/),startsAt:gt.nullable(),endsAt:gt.nullable(),providerLineId:L.z.string().nullable(),providerItemId:L.z.string()}),Tc=L.z.strictObject({invoice:Dr,items:L.z.array(L.z.discriminatedUnion("kind",[Yf,L.z.strictObject({kind:L.z.literal("invoice_credit"),key:L.z.string(),internal_feature_id:L.z.uuid(),internal_credit_feature_id:L.z.uuid(),name:L.z.string(),units:Z,reserved:Z,amountMinor:lr,grossAmountMinor:lr,creditsAppliedMinor:lr,properties:Ne,cashPrice:jt,providerItemId:L.z.string().nullable(),creditProviderItemId:L.z.string().nullable()}),L.z.strictObject({kind:L.z.literal("usage"),key:L.z.string(),internal_feature_id:L.z.uuid(),name:L.z.string(),units:Z,reserved:Z,amountMinor:lr,cashPrice:jt})])).max(100),nextCursor:L.z.string().min(1).max(180).nullable()}),Xf=L.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),sa=L.z.strictObject({from:gt,to:gt,entityId:L.z.uuid().optional(),snapshotAt:gt.nullable(),after:L.z.strictObject({at:gt,id:L.z.uuid(),position:L.z.number().int().nonnegative()}).nullable(),limit:L.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"),Rc=L.z.strictObject({customerId:L.z.uuid(),entityId:L.z.uuid().nullable(),from:gt,to:gt,snapshotAt:gt,totals:L.z.array(L.z.strictObject({internal_credit_feature_id:L.z.uuid(),name:L.z.string(),consumed:Je,refunded:Je,net:Xf})).max(1e3),rows:L.z.array(L.z.strictObject({operationId:L.z.uuid(),position:L.z.number().int().nonnegative(),kind:L.z.enum(["consume","confirm","refund"]),originalId:L.z.uuid().nullable(),occurredAt:gt,internal_feature_id:L.z.uuid(),entitlementName:L.z.string(),sourceId:L.z.uuid(),internal_credit_feature_id:L.z.uuid(),creditName:L.z.string(),units:Wt,amount:Je,pricing:L.z.array(aa).max(12),properties:Ne})).max(100),nextCursor:sa.shape.after});var y=require("zod");var ot=require("zod");var Jf=ot.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),zf=ot.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Un=ot.z.strictObject({internal_feature_id:ot.z.uuid(),entityId:ot.z.uuid().nullable()}),kc=Un.extend({quantity:Z,expectedRevision:ot.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:ot.z.string().min(1).max(120),properties:Ne.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Fr=Un.extend({operationId:ot.z.uuid().nullable(),usage:Z,capacity:Jf.nullable(),remaining:zf.nullable(),withinLimit:ot.z.boolean(),revision:ot.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:ot.z.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let r=n=>{let i=n.startsWith("-"),[o,a=""]=(i?n.slice(1):n).split(".");if(o===void 0||o==="")throw new Error("Invalid decimal value");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||r(e.remaining)!==r(e.capacity)-r(e.usage)||e.withinLimit!==r(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 Ye=y.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),dt=y.z.iso.datetime({offset:!0}),eh=y.z.enum(["access","metered","credit"]),Vr={internal_feature_id:y.z.uuid(),key:$t,name:y.z.string().min(1).max(120),kind:eh},Dc=y.z.object({customerId:y.z.uuid(),snapshotAt:dt,memberships:y.z.array(y.z.object({id:y.z.uuid(),productId:y.z.string().min(1).max(255),productVersionId:y.z.uuid(),billingProductVersionId:y.z.uuid(),version:y.z.number().int().positive(),key:y.z.string().min(1).max(64),name:y.z.string().min(1).max(120),groupId:y.z.string().max(255).nullable(),membershipType:y.z.enum(["main","addon"]),status:y.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:y.z.boolean(),accessEnabled:y.z.boolean(),renewalChange:y.z.object({productVersionId:y.z.uuid(),name:y.z.string().min(1).max(120),version:y.z.number().int().positive(),effectiveAt:dt,benefitsAppliedAt:dt.nullable(),timing:y.z.enum(["immediate","renewal"]),changeKind:y.z.enum(["plan","seats","quantity"]),feature:y.z.strictObject({internal_feature_id:y.z.uuid(),name:y.z.string().min(1).max(80),fromQuantity:y.z.number().int().min(0).max(1e4),toQuantity:y.z.number().int().min(0).max(1e4)}).optional(),seat:y.z.object({key:y.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:y.z.number().int().min(0).max(1e4),toQuantity:y.z.number().int().min(0).max(1e4)}).strict().nullable(),status:y.z.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:y.z.object({phase:y.z.enum(["paid","trial"]),startsAt:dt,endsAt:dt.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:y.z.boolean(),balances:y.z.array(y.z.object({...Vr,usageType:y.z.enum(["consumable","non_consumable"]).nullable(),accessible:y.z.boolean(),unlimited:y.z.boolean(),available:Ye,held:Ye,debt:Ye,nextExpiresAt:dt.nullable(),usage:Fr.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:y.z.boolean()}).strict(),Nc=y.z.enum(["source","usage","transaction","invoice","debt","settlement"]),Mc=y.z.object({at:dt,id:y.z.uuid(),type:Nc}).strict(),Uc=y.z.object({type:Nc.nullable(),resourceKey:$t.optional(),kind:y.z.enum(["purchase","refund"]).optional(),topup:y.z.boolean().optional(),from:y.z.iso.date().nullable(),to:y.z.iso.date().nullable(),after:Mc.nullable(),limit:y.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),mr={id:y.z.uuid(),occurredAt:dt},th=y.z.discriminatedUnion("type",[y.z.strictObject({...mr,type:y.z.literal("invoice"),status:y.z.string().min(1).max(80),paid:Ye,refunded:Ye,currency:J,externalId:y.z.string().nullable()}),y.z.object({...mr,...Vr,type:y.z.literal("source"),reason:y.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Ye,unlimited:y.z.boolean(),status:y.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:dt,expiresAt:dt.nullable(),orderId:y.z.uuid().nullable(),parentSourceId:y.z.uuid().nullable()}).strict(),y.z.object({...mr,type:y.z.literal("usage"),internal_feature_id:y.z.uuid(),name:y.z.string().min(1).max(120),kind:y.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:y.z.uuid().nullable(),quantity:Z,accepted:y.z.boolean(),reason:y.z.enum([...Mn.options,"expired"]).nullable(),properties:Ne,reservationStatus:y.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:dt.nullable(),charges:y.z.array(y.z.discriminatedUnion("funding",[y.z.strictObject({funding:y.z.literal("balance"),sourceId:y.z.uuid(),rolloverId:y.z.uuid().nullable(),units:Wt,amount:Ye}),y.z.strictObject({funding:y.z.literal("unbilled"),units:Wt}),y.z.object({...Vr,funding:y.z.literal("prepaid"),amount:Ye}).strict(),y.z.object({funding:y.z.literal("postpaid"),invoiceId:y.z.uuid(),invoiceLineId:y.z.uuid(),authorizationId:y.z.uuid(),units:Z,currency:J}).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"),y.z.object({...mr,type:y.z.literal("transaction"),purpose:y.z.enum(["product","invoice"]),productVersionId:y.z.uuid().nullable(),productName:y.z.string().min(1).max(120).nullable(),productVersion:y.z.number().int().positive().nullable(),invoiceId:y.z.uuid().nullable(),orderId:y.z.uuid(),originalId:y.z.uuid().nullable(),kind:y.z.enum(["purchase","refund"]),amountMinor:y.z.number().int().nonnegative().max(2e8).nullable(),currency:J.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"),y.z.object({...mr,...Vr,type:y.z.literal("debt"),sourceId:y.z.uuid(),transactionId:y.z.uuid(),amount:Ye}).strict(),y.z.object({...mr,...Vr,type:y.z.literal("settlement"),sourceId:y.z.uuid(),debtId:y.z.uuid(),kind:y.z.enum(["payment","usage_refund","payment_return"]),amount:Ye}).strict()]),qc=y.z.object({customerId:y.z.uuid(),rows:y.z.array(th).max(50),nextCursor:Mc.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");var K=require("zod"),Bc=K.z.object({customerId:K.z.uuid()}).strict(),Fc=K.z.discriminatedUnion("action",[K.z.object({customerId:K.z.uuid(),requestId:K.z.uuid(),action:K.z.literal("assign"),poolId:K.z.uuid(),memberCustomerId:K.z.uuid()}).strict(),K.z.strictObject({customerId:K.z.uuid(),requestId:K.z.uuid(),action:K.z.literal("assign_entity"),poolId:K.z.uuid(),entityId:K.z.uuid()}),K.z.object({customerId:K.z.uuid(),requestId:K.z.uuid(),action:K.z.literal("release"),poolId:K.z.uuid(),slotId:K.z.uuid()}).strict()]),$r=K.z.number().int().nonnegative(),ca=K.z.iso.datetime({offset:!0}),ua=K.z.strictObject({internalId:K.z.uuid(),id:K.z.string(),name:K.z.string().nullable(),version:K.z.number().int().positive()}),Lc=K.z.enum(["active","past_due"]),la=K.z.strictObject({customerId:K.z.uuid(),licenses:K.z.array(K.z.strictObject({id:K.z.uuid(),linkId:K.z.uuid(),parent:K.z.strictObject({customerProductId:K.z.uuid(),status:Lc,product:ua}),product:ua,planLicense:K.z.strictObject({id:K.z.uuid(),prepaidOnly:K.z.boolean(),isCustom:K.z.boolean()}).nullable(),granted:$r,included:$r,paidQuantity:$r,usage:$r,remaining:$r,createdAt:ca}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:K.z.array(K.z.strictObject({id:K.z.uuid(),linkId:K.z.uuid(),status:Lc,product:ua,entity:K.z.strictObject({internalId:K.z.uuid(),id:K.z.string().nullable(),name:K.z.string().nullable()}).nullable(),beneficiary:K.z.strictObject({internalId:K.z.uuid(),id:K.z.string().nullable(),name:K.z.string().nullable()}).nullable(),startedAt:ca.nullable(),endedAt:ca.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:K.z.boolean()});var Tt=require("zod"),qn=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,pr=Tt.z.object({customerId:Tt.z.uuid(),sessionId:Tt.z.uuid(),accessToken:Tt.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Tt.z.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Tt.z.iso.datetime(),refreshExpiresAt:Tt.z.iso.datetime()});var H=require("zod"),Gr=H.z.enum(["email","sms","voice","push"]),FS=H.z.enum(["resend","twilio","fcm","apns"]);var VS=H.z.string().regex(/^\+[1-9]\d{1,14}$/),rh=H.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var nh=H.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),ih=H.z.strictObject({subject:nh,html:H.z.string().min(1).max(131072).optional(),text:H.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),ah=H.z.strictObject({body:H.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),oh=H.z.strictObject({text:H.z.string().trim().min(1).max(4e3),language:H.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:H.z.number().int().min(1).max(900)}),sh=H.z.record(H.z.string().min(1).max(64),H.z.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),ch=H.z.strictObject({title:H.z.string().trim().min(1).max(200),body:H.z.string().trim().min(1).max(2e3),url:H.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:sh.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Vc=H.z.discriminatedUnion("channel",[H.z.strictObject({channel:H.z.literal("email"),content:ih}),H.z.strictObject({channel:H.z.literal("sms"),content:ah}),H.z.strictObject({channel:H.z.literal("voice"),content:oh}),H.z.strictObject({channel:H.z.literal("push"),content:ch})]),$c=H.z.strictObject({requestId:H.z.uuid(),customerId:H.z.uuid(),connectionId:H.z.uuid().optional(),message:Vc,expiresAt:H.z.iso.datetime({offset:!0})}),uh=H.z.array(H.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),lh=H.z.discriminatedUnion("kind",[H.z.strictObject({kind:H.z.literal("all")}),H.z.strictObject({kind:H.z.literal("customers"),customerIds:uh})]),$S=H.z.strictObject({name:H.z.string().trim().min(1).max(120),connectionId:H.z.uuid().optional(),message:Vc,audience:lh,frequencyLimit:H.z.number().int().min(1).max(100)}),Gc=H.z.strictObject({requestId:H.z.uuid(),channel:Gr,state:H.z.enum(["allowed","denied"]),expectedRevision:H.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Hc=H.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Kc=H.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),GS=H.z.strictObject({meter:rh,estimatedUnits:H.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:H.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var ee=require("zod");var Q=require("zod");var xe=require("zod");var Qc=require("zod");var Qt=require("zod"),Wc=Qt.z.enum(["stripe","apple","google"]),Zc=Qt.z.enum(["membership","credit_pack","lifetime"]),KS=Qt.z.enum(["active","grace","suspended","inactive","revoked"]),WS=Qt.z.strictObject({currency:Qt.z.string().regex(/^[A-Z]{3}$/),micros:Qt.z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var fr=Qc.z.object({provider:Wc,currency:J}).strict();var Rt=xe.z.strictObject({internal_feature_id:xe.z.uuid(),quantity:Z.refine(e=>/[1-9]/.test(e)),properties:Ne,entityId:xe.z.uuid().optional()}),Yc=xe.z.strictObject({requirement:Rt,commerce:fr.optional(),paywallId:xe.z.uuid().optional()}),dh=xe.z.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),da=xe.z.strictObject({productId:xe.z.string().min(1),productVersionId:xe.z.string().min(1),name:xe.z.string().min(1).max(120),action:xe.z.enum(["purchase","upgrade","addon","topup"]),membershipId:xe.z.string().min(1).nullable(),currency:J,amountMinor:xe.z.string().regex(/^(0|[1-9]\d{0,8})$/),interval:xe.z.enum(["free","week","month","year","one_time"]),intervalCount:xe.z.number().int().min(1).max(156)}),Yt=xe.z.strictObject({internal_feature_id:xe.z.string().min(1),name:xe.z.string().min(1).max(120),kind:xe.z.enum(["access","metered","credit"]),quantity:Z,allowed:xe.z.boolean(),reason:dh.nullable(),preview:xe.z.strictObject({scenario:xe.z.enum(["feature_flag","usage_limit"]),candidates:xe.z.array(da).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(r=>r.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),t0=xe.z.strictObject({paywallId:xe.z.uuid(),requirement:Rt});var ma=Q.z.object({plan:Q.z.string().min(1).max(200).optional(),coupon:Q.z.uuid().optional(),promotionCode:Q.z.uuid().optional(),picker:Q.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Ln=Q.z.object({text:Q.z.string().optional(),label:Q.z.string().optional(),alt:Q.z.string().optional(),html:Q.z.string().max(32768).optional(),price:Q.z.object({current:Q.z.string(),original:Q.z.string().nullable(),period:Q.z.string()}).optional(),code:Q.z.string().optional(),countdownAt:Q.z.iso.datetime().optional(),planId:Q.z.string().min(1).max(200).optional(),planVersionId:Q.z.string().min(1).max(200).optional(),currency:J.optional(),couponId:Q.z.uuid().optional(),offerId:Q.z.uuid().optional(),unavailable:Q.z.boolean().optional(),unavailableReason:Q.z.string().optional(),missing:Q.z.array(Q.z.string()).optional()}).strict(),Bn=Q.z.object({paywall:Yt.optional(),nodes:Q.z.record(Q.z.string(),Q.z.object({base:Ln,picker:Q.z.string().optional(),byPlan:Q.z.record(Q.z.string(),Ln).optional()}).strict()),plans:Q.z.record(Q.z.string(),Q.z.object({id:Q.z.string().min(1).max(200),versionId:Q.z.string().min(1).max(200),available:Q.z.boolean(),name:Q.z.string(),price:Q.z.string(),period:Q.z.string(),currency:J.optional()}).strict()),pickers:Q.z.record(Q.z.string(),Q.z.object({options:Q.z.array(Q.z.string().min(1).max(200)).max(20),selected:Q.z.string().min(1).max(200).nullable()}).strict()),diagnostics:Q.z.array(Q.z.object({nodeId:Q.z.string(),message:Q.z.string()}).strict())}).strict();function Xc(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var d=require("zod");function mh(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Jc(e){let t={};function r(n){var i;if(mh(n)){let o=t[i=n.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let c of n.children){let l=c.type==="stack"?c.bind?.plan:void 0;l&&!o.ids.includes(l)&&o.ids.push(l)}let a=n.children[n.interaction.defaultIndex];!o.defaultId&&a?.type==="stack"&&(o.defaultId=a.bind?.plan??null)}n.type==="stack"&&n.children.forEach(r)}return e.pages.forEach(n=>r(n.root)),t}var bt=require("zod"),zc=bt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Fn=bt.z.strictObject({tiers:bt.z.array(bt.z.strictObject({id:zc,name:bt.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:bt.z.array(bt.z.strictObject({productVersionId:bt.z.string().min(1).max(200),tierId:zc,period:bt.z.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let r=e.tiers.map(n=>n.id);(new Set(r).size!==r.length||new Set(e.assignments.map(n=>n.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(n=>`${n.tierId}:${n.period}`)).size!==e.assignments.length||e.assignments.some(n=>!r.includes(n.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Vn(e,t){return e.assignments.length===t.length&&e.assignments.every(r=>t.includes(r.productVersionId))}var $=require("zod");var ph=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],eu=$.z.enum(ph),tu=$.z.object({source:eu,layout:$.z.enum(["full","compact"]),resourceKey:$t.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"})}),Be=$.z.string().max(2e3),ru=$.z.object({id:$.z.string().max(100),label:Be,detail:$.z.array(Be).max(12),value:Be.optional(),status:Be.optional(),facts:$.z.array($.z.object({label:Be,value:Be}).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:Be})).max(1).optional(),membershipActions:$.z.array($.z.object({value:$.z.string().max(100),label:Be}).strict()).max(3).optional()}).strict(),fh=$.z.object({key:$t,name:Be,spendable:Be,reserved:Be,available:Be,expiry:Be.nullable(),sources:$.z.array(ru).max(50),sourceCount:$.z.number().int().nonnegative(),sourcePage:$.z.number().int().positive(),hasNextSources:$.z.boolean(),hasPreviousSources:$.z.boolean()}).strict(),hh=$.z.object({source:eu,status:$.z.enum(["idle","loading","ready","error"]),stale:$.z.boolean(),preview:$.z.boolean(),errorCode:$.z.string().max(80).optional(),errorMessage:Be.optional(),resources:$.z.array(fh).max(500),rows:$.z.array(ru).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:Be,note:Be,facts:$.z.array($.z.object({label:Be,value:Be}).strict()).max(100)}).strict().optional(),membershipResult:Be.optional()}).strict(),u0=$.z.object({nodes:$.z.record($.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),hh)}).strict(),l0=$.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();var gh=4,pt={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Kr=d.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),le=d.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),bh=d.z.enum(["none","xs","sm","md","lg","xl"]),yh=d.z.enum(["none","sm","md","lg","full"]),pa=d.z.string().regex(/^#[0-9a-fA-F]{6}$/),au=d.z.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"),fa=d.z.union([au,d.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),d.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),d.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),nu=d.z.object({primary:pa,background:pa,text:pa,radius:yh,font:d.z.enum(["system","serif","rounded","mono"])}).strict(),Wr=d.z.union([d.z.enum(["primary","text","muted","background","surface"]),d.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),me=(e,t)=>d.z.number().int().min(e).max(t),iu=d.z.union([d.z.enum(["fit","fill"]),me(1,1200)]),Sh=d.z.object({top:me(0,200),right:me(0,200),bottom:me(0,200),left:me(0,200)}).strict(),_h=d.z.object({top:me(-100,200),right:me(-100,200),bottom:me(-100,200),left:me(-100,200)}).strict(),ou=d.z.object({x:me(0,100),y:me(0,100)}).strict(),xh=d.z.discriminatedUnion("type",[d.z.object({type:d.z.literal("color"),color:Wr}).strict(),d.z.object({type:d.z.literal("linear"),angle:me(0,360),stops:d.z.array(d.z.object({color:Wr,at:me(0,100)}).strict()).min(2).max(4)}).strict(),d.z.object({type:d.z.literal("image"),src:fa,fit:d.z.enum(["cover","contain"]),position:ou.optional()}).strict()]),Ih=d.z.discriminatedUnion("type",[d.z.object({type:d.z.literal("rect"),radius:d.z.union([me(0,200),d.z.object({topLeft:me(0,200),topRight:me(0,200),bottomRight:me(0,200),bottomLeft:me(0,200)}).strict()])}).strict(),d.z.object({type:d.z.literal("pill")}).strict()]),vh=d.z.object({width:me(0,12),color:Wr,style:d.z.enum(["solid","dashed"])}).strict(),Ph=d.z.object({x:me(-40,40),y:me(-40,40),blur:me(0,80),spread:me(-20,40),color:Wr}).strict(),Ch=d.z.object({font:d.z.enum(["system","serif","rounded","mono"]),size:me(8,96),weight:d.z.number().int().min(100).max(900).multipleOf(100),lineHeight:d.z.number().min(.8).max(3),letterSpacing:d.z.number().min(-5).max(20),color:Wr,align:d.z.enum(["start","center","end"]),italic:d.z.boolean(),decoration:d.z.enum(["none","underline","line-through"]),transform:d.z.enum(["none","uppercase"])}).strict().partial(),Xt=d.z.object({width:iu,height:iu,padding:Sh,margin:_h,gap:me(0,120),grow:d.z.union([d.z.boolean(),d.z.number().min(0).max(12)]),background:xh,opacity:d.z.number().min(0).max(1),clipContent:d.z.boolean(),shape:Ih,border:vh,shadow:Ph,text:Ch}).strict().partial(),nt={id:Kr,name:d.z.string().trim().min(1).max(60).optional(),hidden:d.z.boolean().optional(),style:Xt.optional(),fallback:le.optional()},wh=d.z.object({...nt,type:d.z.literal("text"),productField:d.z.enum(["name","price","trial","period"]).optional(),feature:d.z.object({id:d.z.uuid(),field:d.z.enum(["name","allowance"])}).strict().optional(),text:le,variant:d.z.enum(["title","heading","body","caption"])}).strict(),Oh=d.z.object({...nt,type:d.z.literal("image"),src:fa,localizedSrc:d.z.record(lt,fa).optional(),alt:le,aspect:d.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:d.z.enum(["cover","contain"]),position:ou.optional()}).strict(),Eh=d.z.object({...nt,type:d.z.literal("button"),label:le,variant:d.z.enum(["primary","secondary","link"]),action:le,purpose:d.z.enum(["purchase","navigation","close"]).optional(),bind:ma.optional()}).strict(),jh=d.z.object({...nt,type:d.z.literal("divider")}).strict(),Th=d.z.object({...nt,type:d.z.literal("customer_data"),title:le,data:tu}).strict(),Rh=d.z.object({...nt,type:d.z.literal("spacer"),size:bh}).strict(),kh=d.z.object({...nt,type:d.z.literal("custom_html"),html:d.z.record(lt,d.z.string().max(pt.customHtml)),css:d.z.string().max(pt.customCss)}).strict(),Dh=d.z.object({...nt,type:d.z.literal("price"),fallback:le,parts:d.z.object({current:Xt.optional(),original:Xt.optional(),period:Xt.optional()}).strict().optional()}).strict(),Nh=d.z.object({...nt,type:d.z.literal("coupon_code"),label:le,fallback:le}).strict(),Mh=d.z.object({...nt,type:d.z.literal("countdown"),source:d.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:d.z.iso.datetime().optional(),granularity:d.z.enum(["day","hour","minute","second"]),expired:le,fallback:le}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Uh=d.z.object({...nt,type:d.z.literal("plan_picker"),label:le,fallback:le,planIds:d.z.array(d.z.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:d.z.string().min(1).max(200).optional(),grouping:Fn.safeExtend({monthLabel:le,yearLabel:le,unavailableLabel:le}).optional(),states:d.z.object({selected:Xt.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Vn(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),qh=d.z.discriminatedUnion("type",[d.z.object({type:d.z.literal("input"),label:le,keyboard:d.z.enum(["text","email","tel","url"]),maxLength:me(1,500)}).strict(),d.z.object({type:d.z.literal("multiselect"),label:le,min:me(0,50),max:me(1,50)}).strict(),d.z.object({type:d.z.literal("select"),label:le,defaultIndex:me(0,49),purpose:d.z.enum(["option","product","tier"]).optional(),pickerId:Kr.optional(),selectedStyle:Xt.optional()}).strict(),d.z.object({type:d.z.literal("tabs"),label:le,defaultIndex:me(0,49),purpose:d.z.literal("tier").optional()}).strict(),d.z.object({type:d.z.literal("toggle"),label:le,defaultEnabled:d.z.boolean()}).strict(),d.z.object({type:d.z.literal("carousel"),label:le}).strict()]),mt={...nt,type:d.z.literal("stack"),direction:d.z.enum(["vertical","horizontal","overlay"]),align:d.z.enum(["start","center","end","stretch"]),justify:d.z.enum(["start","center","end","between"]),productSlot:d.z.object({index:me(0,19),period:d.z.enum(["month","year"]).optional(),requireBinding:d.z.boolean().optional()}).strict().optional(),interaction:qh.optional(),states:d.z.object({selected:Xt.optional()}).strict().optional(),purpose:d.z.literal("benefits").optional(),purchaseAction:le.optional(),buttonVariant:d.z.enum(["primary","secondary","link"]).optional(),bind:ma.optional()},su=d.z.lazy(()=>d.z.object({...nt,type:mt.type,direction:mt.direction,align:mt.align,justify:mt.justify,children:d.z.array(Lh).max(pt.children),productSlot:mt.productSlot,interaction:mt.interaction,states:mt.states,purpose:mt.purpose,purchaseAction:mt.purchaseAction,buttonVariant:mt.buttonVariant,bind:mt.bind}).strict()),Lh=d.z.lazy(()=>d.z.union([su,wh,Oh,Eh,jh,Rh,kh,Dh,Nh,Mh,Uh,Th])),Bh=d.z.union([d.z.string().max(500),d.z.number().finite(),d.z.boolean(),d.z.null()]),Hr={id:le,event:le,properties:d.z.record(le,Bh).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Fh=d.z.discriminatedUnion("type",[d.z.object({...Hr,type:d.z.literal("navigate"),close:d.z.literal(!1),pageId:Kr}).strict(),d.z.object({...Hr,type:d.z.literal("event"),close:d.z.boolean()}).strict(),d.z.object({...Hr,type:d.z.literal("close"),close:d.z.literal(!0)}).strict(),d.z.object({...Hr,type:d.z.literal("open_url"),close:d.z.boolean(),url:au}).strict(),d.z.object({...Hr,type:d.z.literal("claim_offer"),close:d.z.boolean(),couponId:d.z.uuid()}).strict()]),Vh=d.z.object({defaultLocale:lt,locales:d.z.record(lt,d.z.record(le,d.z.string().max(pt.stringLength)))}).strict(),$h=d.z.enum(["popup","paywall","onboarding","page","banner"]);var Gh=d.z.discriminatedUnion("type",[d.z.object({type:d.z.literal("modal"),size:d.z.enum(["sm","md","lg"])}).strict(),d.z.object({type:d.z.literal("sheet"),size:d.z.enum(["sm","md","lg"])}).strict(),d.z.object({type:d.z.literal("fullscreen")}).strict(),d.z.object({type:d.z.literal("inline")}).strict()]);var Hh=d.z.object({kind:d.z.literal("screen"),schemaVersion:d.z.literal(gh),name:d.z.string().trim().min(1).max(80),surface:$h,initialPageId:Kr.optional(),presentation:Gh,theme:nu,pages:d.z.array(d.z.object({id:Kr,name:d.z.string().trim().min(1).max(60),root:su,theme:nu.optional(),editorPosition:d.z.object({x:d.z.number().finite().min(-1e5).max(1e5),y:d.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(pt.pages),strings:Vh,actions:d.z.array(Fh).max(pt.actions)}).strict();function st(e,t){for(let r of e.pages)Zr(r.root,t)}var Jt=Hh.superRefine((e,t)=>{let r=pt;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(A=>A.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let A of e.actions)A.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(v=>v.id===A.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>r.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${r.pages} \u4E2A`}),e.actions.length>r.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${r.actions} \u4E2A`});let n=A=>t.addIssue({code:"custom",message:A}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||n("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>pt.locales&&n(`\u6700\u591A ${pt.locales} \u79CD\u8BED\u8A00`);let o=new Set;for(let A of e.actions)o.has(A.id)&&n(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${A.id}`),o.add(A.id);let a=new Set;for(let A of e.pages)["next","back"].includes(A.id)&&n(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${A.id}`),a.has(A.id)&&n(`\u9875\u9762 id \u91CD\u590D\uFF1A${A.id}`),a.add(A.id);let c=new Set,l=0,p=!1;st(e,(A,v)=>{if(l++,v>pt.depth&&(p=!0),c.has(A.id)&&n(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${A.id}`),c.add(A.id),A.type==="button"&&!o.has(A.action)&&n(`\u6309\u94AE ${A.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${A.action}`),A.type==="custom_html")for(let k of Object.keys(A.html))i.includes(k)||n(`\u81EA\u5B9A\u4E49 HTML ${A.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${k}`);if(A.type==="image")for(let k of Object.keys(A.localizedSrc??{}))i.includes(k)||n(`\u56FE\u7247 ${A.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${k}`)}),l>r.nodes&&n(`\u7EC4\u4EF6\u6700\u591A ${r.nodes} \u4E2A`),p&&n(`\u5C42\u7EA7\u6700\u591A ${pt.depth} \u5C42`)});function Zr(e,t,r=1,n=null){if(t(e,r,n)!==!1&&e.type==="stack")for(let i of e.children)Zr(i,t,r+1,e)}function ha(e){let t=[],r=new Set;return st(e,n=>{let i=(o,a,c)=>{r.has(o)||(r.add(o),t.push({key:o,nodeId:n.id,nodeType:n.type,field:a,required:c}))};n.type==="stack"&&n.interaction&&i(n.interaction.label,"label",!0),n.fallback&&i(n.fallback,"text",!0),n.type==="text"&&i(n.text,"text",!0),n.type==="customer_data"&&i(n.title,"title",!0),(n.type==="plan_picker"||n.type==="coupon_code")&&i(n.label,"label",!0),n.type==="plan_picker"&&n.grouping&&(i(n.grouping.monthLabel,"label",!0),i(n.grouping.yearLabel,"label",!0),i(n.grouping.unavailableLabel,"text",!0)),n.type==="countdown"&&i(n.expired,"text",!0),n.type==="button"&&i(n.label,"label",!0),n.type==="image"&&(i(`image:${n.id}`,"src",!1),i(n.alt,"alt",!1)),n.type==="custom_html"&&i(`html:${n.id}`,"html",!0)}),t}function Kh(e,t,r){if(t.field==="html"){let n;return st(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(n=i.html[r])}),n}if(t.field==="src"){let n=Zh(e,t.nodeId);return n?.type==="image"?n.localizedSrc?.[r]??(r===e.strings.defaultLocale?n.src:void 0):void 0}return e.strings.locales[r]?.[t.key]}function hr(e){let t=ha(e).filter(n=>n.required);return Object.keys(e.strings.locales).sort((n,i)=>n===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(n=>{let i=t.filter(o=>!Kh(e,o,n)?.trim()).map(o=>o.key);return{locale:n,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function Wh(e,t){let r=null;return Zr(e,n=>{if(r)return!1;n.id===t&&(r=n)}),r}function Zh(e,t){for(let r of e.pages){let n=Wh(r.root,t);if(n)return n}return null}function Qh(e){let t=Object.values(e.strings.locales).flatMap(r=>Object.values(r));return st(e,r=>{r.type==="custom_html"&&t.push(...Object.values(r.html))}),[...new Set(t.flatMap(Xc))]}function cu(e){return Qh(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function uu(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let r=new TextEncoder().encode(t).length,n=!1;for(let i=0;i<t.length;i++){let o=t.charAt(i);if(n)o==="\\"?i++:o==='"'&&(n=!1);else if(o==='"')n=!0;else if(o===":"||o===",")r++;else if(o==="-"||o>="0"&&o<="9"){let a=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let c=t.slice(a,i+1);if(!/[eE]/.test(c))continue;let[l="",p]=c.split(/[eE]/),A=l.replace(/^-/,""),v=A.replace(".","").length,k=(A.includes(".")?A.indexOf("."):v)+Number(p),U=k<=0?2-k+v:k>=v?k:v+1;r+=U+(l.startsWith("-")?1:0)-c.length}}return r}var kt=ee.z.enum(["page","popup","banner"]),Yh=3e5,lu=ee.z.strictObject({type:ee.z.enum(["string","number","boolean","strings","json"]),nullable:ee.z.boolean()}),Xh=ee.z.strictObject({inputs:ee.z.record(le,lu.extend({required:ee.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:ee.z.record(le,lu).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Jh=ee.z.strictObject({kind:kt,schemaVersion:ee.z.literal(1),name:ee.z.string().trim().min(1).max(80),screen:Jt,contract:Xh}),$n=Jh.superRefine((e,t)=>{let r=(i,o)=>t.addIssue({code:"custom",message:i,path:o});e.screen.surface!==e.kind&&r("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&r("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&r("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&r("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&r("Content actions must emit host intents or navigate locally",["screen","actions"]);let n=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!n.has(i))||[...n].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&r("Every event needs exactly one output declaration",["contract","outputs"]),uu(e)>Yh&&r("Content document exceeds its byte budget",[])});function zh(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(r=>typeof r=="string")}}var eA=$n.superRefine((e,t)=>{for(let r of cu(e.screen))Object.keys(e.contract.inputs).some(n=>r===n||r.startsWith(n+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let r of e.screen.actions){if(r.type!=="event")continue;let n=e.contract.outputs[r.id],i=Object.hasOwn(r.properties,"value")?r.properties.value:r.properties;n&&!zh(i,n)&&t.addIssue({code:"custom",path:["contract","outputs",r.id],message:"Action value differs from its declared type"})}hr(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),du=ee.z.strictObject({id:ee.z.uuid(),kind:kt,projectId:ee.z.uuid(),environmentId:ee.z.uuid(),name:ee.z.string(),revision:ee.z.number().int().nonnegative(),status:ee.z.enum(["draft","published","archived"]),publishedVersionId:ee.z.uuid().nullable(),createdAt:ee.z.iso.datetime({offset:!0}),updatedAt:ee.z.iso.datetime({offset:!0})}),C0=du.extend({draft:$n}),w0=ee.z.strictObject({rows:ee.z.array(du).max(200),nextCursor:ee.z.uuid().nullable()}),Aa=ee.z.strictObject({id:ee.z.uuid(),kind:kt,resourceId:ee.z.uuid(),projectId:ee.z.uuid(),environmentId:ee.z.uuid(),version:ee.z.number().int().positive(),sourceRevision:ee.z.number().int().nonnegative(),document:eA,createdAt:ee.z.iso.datetime({offset:!0})}),O0=Aa.omit({document:!0}),E0=ee.z.discriminatedUnion("action",[ee.z.strictObject({action:ee.z.literal("create"),kind:kt,id:ee.z.uuid(),document:$n}),ee.z.strictObject({action:ee.z.literal("save"),kind:kt,id:ee.z.uuid(),revision:ee.z.number().int().nonnegative(),document:$n}),ee.z.strictObject({action:ee.z.enum(["publish","archive"]),kind:kt,id:ee.z.uuid(),revision:ee.z.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});var ga=require("zod"),Ar={funnelId:ga.z.uuid().optional(),funnelVersionId:ga.z.uuid().optional()};var _e=require("zod");var se=require("zod");var ye=require("zod"),R0=ye.z.discriminatedUnion("action",[ye.z.strictObject({action:ye.z.literal("create"),couponId:ye.z.uuid(),productBindingId:ye.z.uuid(),storeOfferId:ye.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:ye.z.enum(["introductory","promotional"])}),ye.z.strictObject({action:ye.z.literal("set_enabled"),id:ye.z.uuid(),revision:ye.z.number().int().nonnegative(),enabled:ye.z.boolean()})]),k0=ye.z.array(ye.z.strictObject({id:ye.z.uuid(),couponId:ye.z.uuid(),productBindingId:ye.z.uuid(),storeOfferId:ye.z.string().min(1).max(255).nullable(),storeOfferType:ye.z.enum(["introductory","promotional"]),enabled:ye.z.boolean(),revision:ye.z.number().int().nonnegative()})).max(500),Gn=ye.z.strictObject({offerKind:ye.z.enum(["none","introductory","promotional"]),offerId:ye.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:ye.z.number().int().min(0).max(1e8),trialDays:ye.z.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"})}),D0=ye.z.record(ye.z.uuid(),Gn).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var ba=se.z.object({type:se.z.literal("native_purchase"),receiptId:se.z.uuid(),orderId:se.z.uuid(),productVersionId:se.z.uuid(),provider:se.z.enum(["apple","google"]),productId:se.z.string().min(1).max(255),productKind:Zc,replacement:se.z.strictObject({sourceOrderId:se.z.uuid(),sourceProductId:se.z.string().min(1).max(255),policy:se.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:se.z.array(se.z.uuid()).max(50)}).nullable(),appAccountToken:se.z.uuid().optional(),obfuscatedAccountId:se.z.string().min(1).max(64).optional(),obfuscatedProfileId:se.z.uuid().optional(),basePlanId:se.z.string().min(1).max(255).optional(),offerId:se.z.string().min(1).max(255).optional(),offerKind:se.z.enum(["none","introductory","promotional"]),currency:J,catalogAmountMinor:se.z.number().int().nonnegative().max(1e8),discountMinor:se.z.number().int().nonnegative().max(1e8),trialDays:se.z.number().int().min(1).max(730).nullable(),seatBundle:se.z.array(se.z.strictObject({key:se.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:se.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:se.z.strictObject({offerId:se.z.string().min(1).max(255),keyId:se.z.string().min(1).max(255),nonce:se.z.uuid(),signature:se.z.string().min(1).max(1024),timestamp:se.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let r=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(r?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!r&&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||(r?!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"})});var s=require("zod");var re=require("zod/v4"),mu=require("zod/v4"),tA=mu.z.registry(),{BillingInterval:pu}=(()=>{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:rA}=(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')."})})}))(re.z),{withSpecDefault:nA}=(e=>({withSpecDefault:({schema:r,defaultValue:n,description:i})=>(e.add(r,{description:i,default:n}),r)}))(tA),{COMMON:fu}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:iA}={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:aA}=(e=>({COMMON_SET:new Set(e)}))(fu),{hasNoDuplicateCurrencies:hu}={hasNoDuplicateCurrencies:t=>{let r=new Set;for(let{currency:n}of t){let i=n.toLowerCase();if(r.has(i))return!1;r.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:Au}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:oA}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(re.z),{Infinite:sA}={Infinite:"inf"},{TierBehavior:cA}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:gu}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:uA}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:lA}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:dA}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:mA}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(re.z),{ApiCreditTierSchema:bu}=(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."})})}))(re.z),{VIOLATION_MESSAGES:pA}={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:yu}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(re.z),{ModelMarkupsSchema:fA}=((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()}))(re.z,yu),{InvoiceUsageEntrySchema:hA}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(re.z),{AttachDiscountSchema:Su}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(r=>r.reward_id||r.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(re.z),{CustomLineItemSchema:AA}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(re.z),{UnixMsTimestampSchema:gA}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(re.z),{CreateInvoicePreviewLineSchema:bA}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(re.z),{ReissueInvoiceParamsSchema:ya}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(re.z),{InvoiceModeParamsSchema:zt}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(re.z),{InvoiceTemplateSchema:yA}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(re.z),{BasePriceSchema:SA}=((e,t,r)=>({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:r.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(re.z,pu,rA),{CURRENCY_CODES:_A}=((e,t,r)=>({CURRENCY_CODES:[...e,...t.filter(i=>!r.has(i)).sort()]}))(fu,iA,aA),{ApiPriceProcessorsSchema:_u}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(re.z,oA),{AllocatedBillingFieldSchema:xA}=((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'."})}))(re.z,uA),{CreditDimensionNameSchema:IA}=((e,t,r)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(r),{message:`Dimension names cannot contain "${r}"`})}))(re.z,lA,dA),{ApiCreditMatchSchema:xu}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(mA),{findCreditTierViolations:vA}=(e=>({findCreditTierViolations:r=>{let n=[],i=(a,c)=>n.push({index:a,reason:c,message:e[c]}),o=0;for(let[a,c]of r.entries()){let l=a===r.length-1;if(c==="inf"){l||i(a,"non_final_infinity");continue}(!Number.isFinite(c)||c<=o)&&i(a,"not_increasing"),o=c,l&&i(a,"final_not_infinity")}return n}}))(pA),{ApiCreditMultiplierSchema:PA}=((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(n=>n.factor!==void 0||n.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(re.z,xu),{ProviderMarkupsSchema:CA}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(re.z,yu),{InvoiceFeatureQuantitySchema:Iu}=((e,t,r)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(r).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(re.z,gu,hA),{CreateInvoicePreviewSchema:Sa}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(re.z,bA),{SUPPORTED_SET:wA}=(e=>({SUPPORTED_SET:new Set(e)}))(_A),{ApiCreditDimensionBaseSchema:OA}=((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."})})}))(re.z,xu),{refineGraduatedTiers:vu}=(e=>({refineGraduatedTiers:(r,n)=>{let i=e(r.tiers.map(o=>o.to));for(let{index:o,message:a}of i)n.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(vA),{ApiFeatureMarkupsOverrideSchema:EA}=((e,t,r)=>({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:r.meta({description:"Per-model markup overrides for customers on this plan."})})}))(re.z,CA,fA),{isValidCurrencyCode:jA}=(e=>({isValidCurrencyCode:r=>!!r&&e.has(r.toLowerCase())}))(wA),{ApiCreditDimensionSchema:TA}=((e,t,r,n)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(r).min(1)}).strict().superRefine(n),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(re.z,OA,bu,vu),{CurrencyCodeSchema:Pu}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(re.z,jA),{AdditionalCurrencyTierSchema:RA}=((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(n=>n.amount!==void 0||n.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(re.z,Pu),{ApiCreditSchemaItemBaseSchema:Cu}=((e,t,r,n)=>({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,r).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,n).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(re.z,IA,TA,PA),{ApiFlatCreditSchemaItemSchema:kA}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Cu,re.z),{AdditionalCurrencyPriceSchema:DA}=((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."})})}))(re.z,Pu),{AdditionalCurrencyTierArraySchema:NA}=((e,t,r,n)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(r,{message:n})}))(re.z,RA,hu,Au),{ApiGraduatedCreditSchemaItemSchema:MA}=((e,t,r,n)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(r).min(1)}).strict().superRefine(n)}))(Cu,re.z,bu,vu),{AdditionalCurrencyPriceArraySchema:wu}=((e,t,r,n)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(r,{message:n})}))(re.z,DA,hu,Au),{ApiUsageTierWithCurrenciesSchema:UA}=((e,t,r)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:r.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:r.optional()}))}))(re.z,sA,NA),{ApiCreditSchemaItemSchema:qA}=((e,t,r)=>({ApiCreditSchemaItemSchema:e.union([t,r])}))(re.z,MA,kA),{BasePriceParamsSchema:LA}=((e,t,r,n)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:r.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:n.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:r.string().optional().meta({internal:!0}),entitlement_id:r.string().optional().meta({internal:!0}),price_id:r.string().optional().meta({internal:!0}),stripe_price_id:r.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."})}))(SA,nA,re.z,wu),{PlanItemPriceParamsSchema:BA}=((e,t,r,n,i,o,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(l=>l??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(r).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(n).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."})})}))(re.z,wu,UA,cA,pu,gu,xA),{ApiFeatureOverrideSchema:FA}=((e,t,r)=>({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:r.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."})})}))(re.z,qA,EA),{InvoiceBasePriceParamsSchema:Ou}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(LA,_u),{InvoiceItemPriceParamsSchema:VA}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(BA,_u),{InvoiceLicenseQuantitySchema:$A}=((e,t,r)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(r).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(re.z,Ou,Iu),{InvoiceCustomizeItemSchema:GA}=((e,t,r)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:r.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(re.z,VA,FA),{InvoiceCustomizeSchema:HA}=((e,t,r)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(r).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(re.z,Ou,GA),{InvoicePlanParamsSchema:KA}=((e,t,r,n,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(r).optional(),license_quantities:e.array(n).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(re.z,HA,Iu,$A,Su),{CreateInvoiceParamsSchema:gr}=((e,t,r,n,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(r).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(n).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(a=>a.period_start===void 0==(a.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(a=>a.period_start===void 0||a.period_end===void 0||a.period_end>a.period_start,{message:"period_end must be after period_start."})}))(re.z,KA,AA,Su,gA);var Tu=s.z.strictObject({requestId:s.z.uuid(),predecessorOperationId:s.z.uuid().optional(),invoiceMode:zt.optional(),entityId:s.z.uuid().optional(),billingSubscriptionId:s.z.uuid().optional(),newBillingSubscription:s.z.literal(!0).optional(),offerId:s.z.uuid().optional(),nativeOffer:Gn.optional(),plans:s.z.array(s.z.strictObject({productVersionId:s.z.uuid(),seatQuantities:s.z.record(Ft,s.z.number().int().min(0).max(1e4)).optional(),featureQuantities:s.z.record(s.z.uuid(),s.z.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:s.z.enum(["stripe","apple","google"]),currency:J}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(e.provider==="stripe"||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||e.provider!=="stripe"&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||e.provider==="stripe"&&!e.billingSubscriptionId,"A new billing subscription requires Stripe and no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),tr=s.z.strictObject({operationId:s.z.uuid()}),$e=s.z.number().int().min(0).max(1e8),WA=s.z.strictObject({lineId:s.z.uuid(),productVersionId:s.z.uuid(),productName:s.z.string().min(1).max(80),interval:s.z.enum(["free","week","month","year","one_time"]),intervalCount:s.z.number().int().min(1).max(156).optional(),baseAmountMinor:$e,seats:s.z.array(s.z.strictObject({key:Ft,quantity:s.z.number().int().min(0).max(1e4),includedQuantity:s.z.number().int().min(0).max(1e4),maximumQuantity:s.z.number().int().min(0).max(1e4),unitAmountMinor:$e})).max(20),prepaid:s.z.array(_c).max(100).optional(),catalogAmountMinor:$e,trial:s.z.strictObject({days:s.z.number().int().min(1).max(730),cardRequired:s.z.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,r)=>t+r.unitAmountMinor*(r.quantity-r.includedQuantity),0)+(e.prepaid??[]).reduce((t,r)=>t+Tn({quantity:r.quantity,unitAmountMinor:r.unitAmountMinor,...r.pricing===void 0?{}:{pricing:r.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Ru=s.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),ZA=s.z.strictObject({id:Ru,name:s.z.string().min(1).max(40),percent_off:s.z.number().gt(0).max(100).optional(),amount_off:s.z.number().int().positive().optional(),currency:s.z.string().regex(/^[a-z]{3}$/).optional(),duration:s.z.enum(["once","repeating","forever"]),duration_in_months:s.z.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"),QA=s.z.strictObject({subscriptionId:s.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:s.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:s.z.array(s.z.strictObject({id:s.z.string(),price_id:s.z.string(),quantity:s.z.number().int().nonnegative(),discounts:s.z.array(s.z.strictObject({id:s.z.string(),coupon:s.z.string(),start:s.z.number(),end:s.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:s.z.number().int().nonnegative(),amountMinor:s.z.number().int().positive(),periodStartMs:s.z.number(),periodEndMs:s.z.number()}),ku=s.z.strictObject({invoiceMode:zt.optional(),append:QA.optional(),provider:s.z.literal("stripe"),executor:s.z.enum(["indiana","merchant"]),accountId:s.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:s.z.enum(["payment","subscription"]),lineItems:s.z.array(s.z.strictObject({price:s.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:s.z.number().int().min(1).max(1e4),priceId:s.z.uuid(),productName:s.z.string().min(1).max(80),amountMinor:s.z.number().int().min(0).max(1e8),currency:s.z.string().regex(/^[a-z]{3}$/),interval:s.z.enum(["week","month","year","one_off"]),intervalCount:s.z.number().int().min(1).max(52),slot:s.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:s.z.strictObject({mode:s.z.enum(["graduated","volume"]),tiers:s.z.array(s.z.strictObject({upTo:s.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:s.z.number().int().min(0).max(1e8),flatAmountMinor:s.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:s.z.array(s.z.strictObject({coupon:Ru,terms:ZA})).max(1),trialPeriodDays:s.z.number().int().min(1).max(730).nullable(),metadata:s.z.strictObject({grooveCheckoutId:s.z.uuid(),grooveCustomerId:s.z.uuid()}),expiresAt:s.z.iso.datetime({offset:!0})}),Du=s.z.strictObject({operationId:s.z.uuid(),entityId:s.z.uuid().nullable(),billingSubscriptionId:s.z.uuid().nullable(),discount:s.z.strictObject({offerId:s.z.uuid(),couponId:s.z.uuid(),discount:Et,duration:tt,amountMinor:$e,allocations:s.z.array(s.z.strictObject({productVersionId:s.z.uuid(),amountMinor:$e})).min(1).max(20),expiresAt:s.z.iso.datetime({offset:!0})}).nullable(),charge:s.z.strictObject({effectiveAt:s.z.iso.datetime({offset:!0}),periodEndsAt:s.z.iso.datetime({offset:!0}),debitMinor:$e,discountMinor:$e,taxMinor:$e,totalMinor:$e}).nullable(),expiresAt:s.z.iso.datetime({offset:!0}),provider:s.z.enum(["stripe","apple","google"]),nativeOffer:Gn.optional(),currency:J,lines:s.z.array(WA).min(1).max(20),catalogAmountMinor:$e,automaticTax:s.z.boolean(),execution:ku.nullable()}).refine(e=>e.provider==="stripe"?e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once")):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(e.provider==="stripe"||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,r)=>{let n=e.lines[r];return n!==void 0&&t.productVersionId===n.productVersionId&&t.amountMinor<=n.catalogAmountMinor})&&e.discount.allocations.reduce((t,r)=>t+r.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,r)=>t+r.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),_a=s.z.strictObject({operationId:s.z.uuid(),orderId:s.z.uuid(),append:s.z.boolean().optional(),invoiceMode:s.z.boolean().optional(),status:s.z.enum(["pending","complete","cancelled","failed"]),executor:s.z.enum(["indiana","merchant"]),checkoutUrl:s.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:ku.nullable(),currency:J,catalogAmountMinor:$e,taxMinor:$e,totalMinor:s.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:s.z.boolean(),nativePurchase:ba.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"),Kn=s.z.strictObject({enabled:s.z.literal(!0),featureIds:s.z.array(s.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Nu=s.z.strictObject({requestId:s.z.uuid(),invoiceMode:zt.optional(),membershipId:s.z.uuid(),carryOverBalances:Kn.optional(),carryOverUsages:Kn.optional(),membershipIds:s.z.array(s.z.uuid()).min(1).max(20).optional(),prorationBehavior:s.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:s.z.enum(["immediate","renewal","store"]),change:s.z.discriminatedUnion("type",[s.z.strictObject({type:s.z.literal("plan"),productVersionId:s.z.uuid()}),s.z.strictObject({type:s.z.literal("seats"),licenseKey:Ft,quantity:s.z.number().int().min(0).max(1e4)}),s.z.strictObject({type:s.z.literal("quantity"),internal_feature_id:s.z.uuid(),quantity:s.z.number().int().min(0).max(1e4)}),s.z.strictObject({type:s.z.literal("cancel")}),s.z.strictObject({type:s.z.literal("uncancel")}),s.z.strictObject({type:s.z.literal("billing_cycle"),billingCycleAnchor:s.z.union([s.z.literal("now"),s.z.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Hn=s.z.string().regex(/^price_[A-Za-z0-9]+$/),Eu=s.z.strictObject({grooveUpdateId:s.z.uuid(),grooveCustomerId:s.z.uuid()}),ju=s.z.strictObject({price:Hn.nullable(),priceId:s.z.uuid().optional(),quantity:s.z.number().int().min(0).max(1e4)}),Mu=s.z.strictObject({provider:s.z.literal("stripe"),invoiceMode:zt.optional(),executor:s.z.enum(["indiana","merchant"]),accountId:s.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:s.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:s.z.enum(["update","cancel","schedule","release"]),update:s.z.strictObject({items:s.z.array(ju).max(20),remove:s.z.array(Hn).max(20),restoreItems:s.z.array(s.z.strictObject({price:Hn,quantity:s.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:s.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:s.z.number().int().positive().optional(),paymentBehavior:s.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:s.z.boolean().optional(),clearCancelAt:s.z.literal(!0).optional(),billingCycleAnchorNow:s.z.literal(!0).optional(),metadata:Eu}).nullable(),cancel:s.z.strictObject({prorate:s.z.literal(!1),invoiceNow:s.z.literal(!1)}).nullable(),schedule:s.z.strictObject({currentItems:s.z.array(s.z.strictObject({price:Hn,quantity:s.z.number().int().min(0).max(1e4)})).max(20),nextItems:s.z.array(ju).min(1).max(20),switchAt:s.z.number().int().positive(),interval:s.z.enum(["week","month","year"]),intervalCount:s.z.number().int().min(1).max(52),resetBillingCycleAnchor:s.z.literal(!0).optional(),metadata:Eu}).nullable(),release:s.z.strictObject({schedule:s.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:s.z.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"),xa=s.z.strictObject({carryOverBalances:Kn.optional(),carryOverUsages:Kn.optional(),operationId:s.z.uuid(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),timing:s.z.enum(["immediate","renewal"]),effectiveAt:s.z.iso.datetime({offset:!0}),expiresAt:s.z.iso.datetime({offset:!0}),currency:J,creditMinor:$e,debitMinor:$e,discountMinor:$e,taxMinor:$e,totalMinor:$e,retainedProductVersionIds:s.z.array(s.z.uuid()).max(19),execution:Mu}),YA=s.z.strictObject({operationId:s.z.uuid(),invoiceMode:s.z.boolean().optional(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),status:s.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:s.z.enum(["immediate","renewal"]),effectiveAt:s.z.iso.datetime({offset:!0}),checkoutUrl:s.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:s.z.enum(["indiana","merchant"]),execution:Mu.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),XA=s.z.strictObject({operationId:s.z.uuid(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),timing:s.z.literal("store"),effectiveAt:s.z.null(),expiresAt:s.z.iso.datetime({offset:!0}),currency:J,creditMinor:s.z.null(),debitMinor:s.z.null(),discountMinor:s.z.null(),taxMinor:s.z.null(),totalMinor:s.z.null(),retainedProductVersionIds:s.z.array(s.z.uuid()).max(19),store:s.z.strictObject({provider:s.z.enum(["apple","google"]),productId:s.z.string().min(1).max(255),catalogAmountMinor:$e,policy:s.z.enum(["apple_store","google_full_price"])})}),JA=s.z.strictObject({operationId:s.z.uuid(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),status:s.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:s.z.literal("store"),effectiveAt:s.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:s.z.null(),nativePurchase:ba.nullable()}),Uu=s.z.union([xa,XA]),Ia=s.z.union([YA,JA]),Qr=s.z.number().int().positive().max(2e8),er=s.z.number().int().min(0).max(2e8),qu=s.z.strictObject({requestId:s.z.uuid(),invoiceId:s.z.uuid(),mode:s.z.enum(["full","partial"]),amountMinor:Qr.optional(),entitlementAction:s.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Lu=s.z.strictObject({provider:s.z.literal("stripe"),executor:s.z.enum(["indiana","merchant"]),accountId:s.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:s.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Qr,currency:s.z.string().regex(/^[a-z]{3}$/),metadata:s.z.strictObject({indianaRefundId:s.z.uuid()}),idempotencyKey:s.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:s.z.array(s.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Bu=s.z.strictObject({operationId:s.z.uuid(),invoiceId:s.z.uuid(),providerInvoiceId:s.z.string().regex(/^in_[A-Za-z0-9]+$/),currency:J,paidMinor:er,refundedMinor:er,pendingMinor:er,amountMinor:Qr,mode:s.z.enum(["full","partial"]),entitlementAction:s.z.enum(["retain","revoke"]),revokes:s.z.strictObject({customerProductIds:s.z.array(s.z.uuid()).max(100),subscriptionIds:s.z.array(s.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:Lu,expiresAt:s.z.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"),Wn=s.z.strictObject({operationId:s.z.uuid(),invoiceId:s.z.uuid(),providerInvoiceId:s.z.string().regex(/^in_[A-Za-z0-9]+$/),status:s.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:s.z.enum(["indiana","merchant"]),currency:J,amountMinor:Qr,mode:s.z.enum(["full","partial"]),entitlementAction:s.z.enum(["retain","revoke"]),refundId:s.z.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:Lu.nullable(),failureReason:s.z.string().min(1).max(200).nullable(),createdAt:s.z.iso.datetime({offset:!0}),completedAt:s.z.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"),Z0=s.z.strictObject({invoiceId:s.z.uuid(),currency:J,paidMinor:er,refundedMinor:er,pendingMinor:er,refundableMinor:er,executor:s.z.enum(["indiana","merchant"]).nullable(),canRefund:s.z.boolean(),operations:s.z.array(Wn).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),Q0=s.z.strictObject({requestId:s.z.uuid(),mode:s.z.enum(["full","partial"]),amountMinor:Qr.optional(),entitlementAction:s.z.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 Fu=_e.z.strictObject({requestId:_e.z.uuid(),targets:_e.z.array(_e.z.strictObject({membershipId:_e.z.uuid(),action:_e.z.enum(["cancel","uncancel"]),timing:_e.z.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"),Zn=_e.z.strictObject({batchId:_e.z.uuid()}),zA=_e.z.strictObject({operationId:_e.z.uuid(),membershipIds:_e.z.array(_e.z.uuid()).min(1).max(20),provider:_e.z.enum(["stripe","apple","google"]),action:_e.z.enum(["cancel","uncancel"]),timing:_e.z.enum(["immediate","renewal"]),status:_e.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:xa.nullable(),managementUrl:_e.z.url().nullable(),failureCode:_e.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Yr=_e.z.strictObject({batchId:_e.z.uuid(),ready:_e.z.boolean(),status:_e.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:_e.z.iso.datetime({offset:!0}),acceptedAt:_e.z.iso.datetime({offset:!0}).nullable(),groups:_e.z.array(zA).min(1).max(100)});var ae=require("zod"),eg=ae.z.string().trim().min(1).max(240),va={requestId:ae.z.uuid(),reason:eg},Qn=ae.z.discriminatedUnion("action",[ae.z.strictObject({...va,action:ae.z.literal("start"),productVersionId:ae.z.uuid(),entityId:ae.z.uuid().optional(),days:ae.z.number().int().min(1).max(730).optional()}),ae.z.strictObject({...va,action:ae.z.literal("extend"),membershipId:ae.z.uuid(),days:ae.z.number().int().min(1).max(730)}),ae.z.strictObject({...va,action:ae.z.literal("end"),membershipId:ae.z.uuid()})]),Vu=ae.z.strictObject({operationId:ae.z.uuid()}),$u=ae.z.iso.datetime({offset:!0}),tg=ae.z.strictObject({provider:ae.z.literal("stripe"),executor:ae.z.enum(["indiana","merchant"]),accountId:ae.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:ae.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:ae.z.union([ae.z.literal("now"),$u]),prorationBehavior:ae.z.literal("none")}),Pa=ae.z.strictObject({operationId:ae.z.uuid(),action:ae.z.enum(["start","extend","end"]),status:ae.z.enum(["pending","effective"]),managedBy:ae.z.enum(["indiana","stripe"]),membershipIds:ae.z.array(ae.z.uuid()).min(1).max(20),endsAt:$u.nullable(),execution:tg.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"),z0=ae.z.strictObject({groupId:ae.z.uuid(),productVersionId:ae.z.uuid(),enabled:ae.z.boolean()});var ge=require("zod");var Gu=ge.z.strictObject({requestId:ge.z.uuid(),currency:J,makeDefault:ge.z.boolean()}),Hu=ge.z.strictObject({setupId:ge.z.uuid()}),rg=ge.z.strictObject({provider:ge.z.literal("stripe"),executor:ge.z.literal("merchant"),accountId:ge.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:ge.z.literal("setup"),currency:ge.z.string().regex(/^[a-z]{3}$/),customer:ge.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:ge.z.uuid(),metadata:ge.z.strictObject({grooveProjectId:ge.z.uuid(),grooveEnvironmentId:ge.z.uuid(),grooveCustomerId:ge.z.uuid(),groovePaymentSetupId:ge.z.uuid()}),setDefaultPaymentMethod:ge.z.boolean(),expiresAt:ge.z.iso.datetime({offset:!0})}),Ca=ge.z.strictObject({id:ge.z.uuid(),provider:ge.z.literal("stripe"),status:ge.z.enum(["prepared","complete","expired"]),currency:J,makeDefault:ge.z.boolean(),url:ge.z.url().nullable(),createdAt:ge.z.iso.datetime({offset:!0}),expiresAt:ge.z.iso.datetime({offset:!0}),completedAt:ge.z.iso.datetime({offset:!0}).nullable(),execution:rg.nullable()});var Fe=require("zod"),Ku=Fe.z.union([Fe.z.string(),Fe.z.number(),Fe.z.boolean(),Fe.z.null()]),Wu=Fe.z.strictObject({customerId:Fe.z.uuid()}),Zu=Fe.z.strictObject({customerId:Fe.z.uuid(),provider:Fe.z.literal("stripe"),checkedAt:Fe.z.iso.datetime({offset:!0}),status:Fe.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Fe.z.number().int().nonnegative(),differences:Fe.z.array(Fe.z.strictObject({subscriptionId:Fe.z.string().startsWith("sub_"),itemId:Fe.z.string().nullable(),field:Fe.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Ku,actual:Ku})).max(1e4)});var z=require("zod");var Yn=z.z.iso.datetime({offset:!0}),Xn=z.z.strictObject({createdAt:Yn,id:z.z.uuid()}),Jn=z.z.strictObject({customerId:z.z.uuid().optional(),entityId:z.z.uuid().optional(),productId:z.z.string().min(1).max(256).optional(),provider:z.z.enum(["stripe","apple","google","free"]).optional(),status:z.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Xn.optional(),limit:z.z.number().int().min(1).max(100).optional()}),wa={id:z.z.uuid(),customerId:z.z.uuid(),entityId:z.z.uuid().nullable(),productId:z.z.string().min(1).max(256),productVersionId:z.z.uuid(),name:z.z.string().min(1).max(120),provider:z.z.enum(["stripe","apple","google","free"]),createdAt:Yn},ng=z.z.strictObject({...wa,status:z.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:z.z.boolean(),billingSubscriptionId:z.z.uuid().nullable()}),ig=z.z.strictObject({...wa,status:z.z.enum(["active","ended","refunded"]),orderId:z.z.uuid().nullable(),transactionId:z.z.uuid().nullable(),currency:J.nullable(),amountMinor:z.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),ag=z.z.strictObject({...wa,status:z.z.enum(["blocked","resolved"]),conflict:z.z.strictObject({detectedAt:Yn,blockingMembershipIds:z.z.array(z.z.uuid()).min(1).max(100),transactionId:z.z.uuid()}),resolvedAt:Yn.nullable()}),Qu=Jn.extend({status:z.z.enum(["blocked","resolved"]).optional()}),Yu=z.z.strictObject({customerId:z.z.uuid(),orderId:z.z.uuid()}),Xu=z.z.strictObject({orderId:z.z.uuid(),status:z.z.enum(["blocked","resolved"])}),Ju=z.z.strictObject({items:z.z.array(ng).max(100),nextCursor:Xn.nullable()}),zu=z.z.strictObject({items:z.z.array(ig).max(100),nextCursor:Xn.nullable()}),el=z.z.strictObject({items:z.z.array(ag).max(100),nextCursor:Xn.nullable()});var Se=require("zod");var tl=Se.z.union([Se.z.strictObject({intent:Se.z.literal("read"),requestId:Se.z.uuid(),purchaseIntentId:Se.z.uuid()}),Se.z.strictObject({requestId:Se.z.uuid(),provider:Se.z.literal("apple"),purchaseIntentId:Se.z.uuid(),productId:Se.z.string().min(1).max(255).optional(),signedTransaction:Se.z.string().min(1).max(131072)}),Se.z.strictObject({requestId:Se.z.uuid(),provider:Se.z.literal("google"),purchaseIntentId:Se.z.uuid(),productId:Se.z.string().min(1).max(255).optional(),purchaseToken:Se.z.string().min(1).max(16384)})]),rl=Se.z.strictObject({requestId:Se.z.uuid(),orderId:Se.z.uuid(),purchaseIntentId:Se.z.uuid(),status:Se.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:J,refunded:Se.z.boolean(),completion:Se.z.strictObject({transactionIds:Se.z.array(Se.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Se.z.boolean()}).nullable()});var w=require("zod"),Ea=w.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),og=w.z.record(w.z.string(),w.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),sg=3,Xr=20,cg=sg*Xr,Oa=w.z.strictObject({type:w.z.literal("product"),productId:Ea}),nl={type:w.z.literal("group"),key:w.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:w.z.string().trim().min(1).max(80)},ug=w.z.discriminatedUnion("type",[Oa,w.z.strictObject({...nl,items:w.z.array(Oa).max(Xr)})]),lg=w.z.discriminatedUnion("type",[Oa,w.z.strictObject({...nl,items:w.z.array(ug).max(Xr)})]),dg=w.z.array(lg).max(Xr).superRefine((e,t)=>{let r=new Set,n=new Set,i=0;function o(a){for(let c of a){i++;let l=c.type==="product"?r:n,p=c.type==="product"?c.productId:c.key;l.has(p)&&t.addIssue({code:"custom",message:c.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),l.add(p),c.type==="group"&&o(c.items)}}o(e),(r.size>Xr||i>cg)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function ja(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:ja(t))}var br=w.z.strictObject({lookupKey:w.z.string().trim().min(1).max(200),displayName:w.z.string().trim().min(1).max(1500),items:dg,metadata:og}),mg=w.z.strictObject({product:w.z.record(w.z.string(),w.z.json()),prices:w.z.array(w.z.record(w.z.string(),w.z.json())),entitlements:w.z.array(w.z.record(w.z.string(),w.z.json())),freeTrials:w.z.array(w.z.record(w.z.string(),w.z.json())),licenses:w.z.array(w.z.record(w.z.string(),w.z.json()))}),il=br.extend({id:w.z.uuid(),projectId:w.z.uuid(),environmentId:w.z.uuid(),state:w.z.enum(["active","archived"]),isCurrent:w.z.boolean(),revision:w.z.number().int().nonnegative(),publishedVersionId:w.z.uuid().nullable(),createdAt:w.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),al=w.z.strictObject({id:w.z.uuid(),offeringId:w.z.uuid(),projectId:w.z.uuid(),environmentId:w.z.uuid(),version:w.z.number().int().positive(),document:br,productEvidence:w.z.record(Ea,mg),createdAt:w.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let r=ja(e.document);(!r.length||hg(e.document).length>0||Object.keys(e.productEvidence).length!==r.length||r.some(n=>!Object.hasOwn(e.productEvidence,n)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),pg=w.z.strictObject({rows:w.z.array(il).max(200),versions:w.z.array(al).max(500)}),c_=w.z.discriminatedUnion("action",[w.z.strictObject({action:w.z.literal("create"),document:br}),w.z.strictObject({action:w.z.literal("save"),id:w.z.uuid(),revision:w.z.number().int().nonnegative(),document:br}),w.z.strictObject({action:w.z.enum(["publish","set_current","archive","restore"]),id:w.z.uuid(),revision:w.z.number().int().nonnegative()})]),u_=w.z.strictObject({record:il,version:al.nullable()}),ol=w.z.discriminatedUnion("type",[w.z.strictObject({type:w.z.literal("current")}),w.z.strictObject({type:w.z.literal("id"),id:w.z.uuid()}),w.z.strictObject({type:w.z.literal("lookup_key"),lookupKey:w.z.string().min(1).max(200)}),w.z.strictObject({type:w.z.literal("version"),versionId:w.z.uuid()})]),fg=w.z.strictObject({internalId:Ea,id:w.z.string(),name:w.z.string().nullable(),version:w.z.number().int().positive(),archived:w.z.boolean()}),l_=pg.extend({products:w.z.array(fg).max(500)});function hg(e){let t=[];ja(e).length||t.push("Select at least one Product before publishing");function r(n){for(let i of n)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),r(i.items))}return r(e.items),t}var Jr=require("zod");var sl=Jr.z.strictObject({id:Jr.z.uuid(),offeringId:Jr.z.uuid(),version:Jr.z.number().int().positive(),document:br});var ke=require("zod");var W=require("zod");var rr=require("zod");var zn=rr.z.strictObject({items:rr.z.array(rr.z.strictObject({productVersionId:rr.z.string().min(1).max(200),label:rr.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:rr.z.string().min(1).max(200).nullable(),grouping:Fn.optional()});var Re=require("zod"),Ag=Re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ei=Re.z.discriminatedUnion("type",[Re.z.object({type:Re.z.literal("fixed"),productVersionId:Re.z.string().min(1).max(200)}).strict(),Re.z.object({type:Re.z.literal("picker"),pickerId:Ag,allowedProductVersionIds:Re.z.array(Re.z.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")]),zr=Re.z.discriminatedUnion("type",[Re.z.object({type:Re.z.literal("modal"),size:Re.z.enum(["sm","md","lg"])}).strict(),Re.z.object({type:Re.z.literal("sheet"),size:Re.z.enum(["sm","md","lg"])}).strict(),Re.z.object({type:Re.z.literal("fullscreen")}).strict(),Re.z.object({type:Re.z.literal("inline")}).strict()]);var Ta=W.z.discriminatedUnion("type",[W.z.strictObject({type:W.z.literal("event"),event:W.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),W.z.strictObject({type:W.z.literal("open_url"),url:W.z.url().refine(e=>new URL(e).protocol==="https:")})]),gg=Jt,bg=W.z.discriminatedUnion("type",[W.z.object({type:W.z.literal("checkout"),product:ei}).strict(),W.z.object({type:W.z.literal("close")}).strict(),W.z.object({type:W.z.literal("action"),action:Ta}).strict()]),yr=W.z.object({schemaVersion:W.z.literal(3),kind:W.z.literal("paywall"),name:W.z.string().trim().min(1).max(80),presentation:zr,requirement:Rt.optional(),products:zn,offeringVersionId:W.z.uuid().nullable(),offeringId:W.z.uuid(),screen:gg,buttons:W.z.record(W.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),bg)}).strict(),I_=yr.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(n=>!["event","navigate"].includes(n.type)||n.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let n of Sg(e))t.addIssue({code:"custom",message:n});for(let n of yg(e))t.addIssue({code:"custom",message:n});hr(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(n=>n.type!=="navigate").length||e.screen.actions.some(n=>n.type!=="navigate"&&!Object.hasOwn(e.buttons,n.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(n=>n.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function yg(e){let t=e.products.items.map(o=>o.productVersionId),r=Jc(e.screen),n=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!Vn(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")n.add(a.productVersionId);else{a.allowedProductVersionIds.forEach(p=>n.add(p));let c=!1,l=r[a.pickerId];l&&(c=!0,(a.allowedProductVersionIds.some(p=>!l.ids.includes(p))||l.ids.some(p=>!a.allowedProductVersionIds.includes(p)))&&i.push("picker")),st(e.screen,p=>{if(p.id!==a.pickerId||p.type!=="plan_picker")return;c=!0,(JSON.stringify(p.planIds)!==JSON.stringify(t)||JSON.stringify(a.allowedProductVersionIds)!==JSON.stringify(t)||p.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let A=p.grouping?{tiers:p.grouping.tiers,assignments:p.grouping.assignments}:void 0;JSON.stringify(A)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),c||i.push("picker")}}return(!n.size||[...n].some(o=>!t.includes(o)))&&i.push("purchase"),st(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 Sg(e){let t=[],r=e.screen.pages.at(-1),n=new Map;for(let c of e.screen.pages)n.set(c.id,[]),Zr(c.root,l=>{let p=l.type==="button"?l.action:l.type==="stack"?l.purchaseAction:void 0;if(p){let A=e.screen.actions.find(k=>k.id===p);A?.type==="navigate"&&n.get(c.id).push(A.pageId);let v=e.buttons[p];c.id!==r.id&&v&&v.type!=="close"&&t.push(`purchaseScreen:${l.id}`)}c.id!==r.id&&(l.type==="plan_picker"||l.type==="stack"&&l.productSlot)&&t.push(`packageScreen:${l.id}`)});let i=new Set;function o(c){if(!i.has(c)){i.add(c);for(let l of n.get(c)??[])o(l)}}let a=e.screen.initialPageId??e.screen.pages[0]?.id;a?o(a):t.push("initialPage");for(let c of e.screen.pages)i.has(c.id)||t.push(`unreachableScreen:${c.id}`);return[...new Set(t)]}var cl=W.z.object({id:W.z.uuid(),projectId:W.z.uuid(),environmentId:W.z.uuid(),revision:W.z.number().int().nonnegative(),state:W.z.enum(["active","archived"]),publishedVersionId:W.z.uuid().nullable(),updatedAt:W.z.iso.datetime({offset:!0}),draft:yr}).strict(),v_=W.z.object({rows:W.z.array(cl).max(200),nextCursor:W.z.uuid().nullable()}).strict(),P_=cl.omit({draft:!0}).extend({name:W.z.string(),productCount:W.z.number().int().nonnegative()}).strict(),C_=W.z.discriminatedUnion("action",[W.z.object({action:W.z.literal("save"),id:W.z.uuid().nullable(),revision:W.z.number().int().nonnegative(),document:yr}).strict(),W.z.object({action:W.z.enum(["publish","archive"]),id:W.z.uuid(),revision:W.z.number().int().nonnegative()}).strict()]),w_=W.z.object({paywalls:W.z.array(W.z.object({id:W.z.uuid(),paywallId:W.z.uuid(),version:W.z.number().int().positive(),name:W.z.string().min(1).max(80),presentation:zr,buttons:yr.shape.buttons}).strict()).max(500),limited:W.z.boolean()}).strict();var ne=require("zod");var He=require("zod");var Sr=He.z.string().regex(/^[a-f0-9]{64}$/),_g=Ln.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),T_=He.z.strictObject({couponDigests:He.z.record(He.z.uuid(),Sr),variables:He.z.record(lt,He.z.record(He.z.uuid(),He.z.partialRecord(He.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),He.z.string()))),locales:He.z.record(lt,Bn.extend({nodes:He.z.record(He.z.string(),He.z.strictObject({base:_g})),plans:He.z.object({}).strict(),pickers:He.z.object({}).strict()}).omit({paywall:!0}))});var ce=require("zod");var en=require("zod"),Ra=en.z.strictObject({eventsEnabled:en.z.boolean(),experimentViewsEnabled:en.z.boolean(),featureUsageEnabled:en.z.boolean()}),k_=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});var O=require("zod");var ka=O.z.tuple([O.z.number().min(0).max(1),O.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),xg=O.z.strictObject({attribute:O.z.string().optional(),seed:O.z.string(),hashVersion:O.z.literal(2),ranges:O.z.array(ka).max(100)}),Ig=O.z.strictObject({id:O.z.string().min(1).max(255),condition:ut,gate:O.z.boolean().optional()}),vg=O.z.strictObject({key:O.z.string().optional(),name:O.z.string().optional(),passthrough:O.z.boolean().optional()}),ul={condition:ut.optional(),parentConditions:O.z.array(Ig).max(100).optional(),weights:O.z.array(O.z.number().min(0).max(1)).max(20).optional(),coverage:O.z.number().min(0).max(1).optional(),hashAttribute:O.z.string().optional(),fallbackAttribute:O.z.string().optional(),hashVersion:O.z.literal(2).optional(),disableStickyBucketing:O.z.boolean().optional(),bucketVersion:O.z.number().int().nonnegative().optional(),minBucketVersion:O.z.number().int().nonnegative().optional(),filters:O.z.array(xg).max(100).optional(),ranges:O.z.array(ka).max(20).optional(),meta:O.z.array(vg).max(20).optional(),seed:O.z.string().optional(),name:O.z.string().optional(),phase:O.z.string().optional()},ll=O.z.strictObject({...ul,key:O.z.string().min(1).max(255),variations:O.z.tuple([Ze,Ze]).rest(Ze).refine(e=>e.length<=20),urlPatterns:O.z.array(O.z.strictObject({include:O.z.boolean(),type:O.z.enum(["regex","simple"]),pattern:O.z.string()})).max(100).optional(),force:O.z.number().int().nonnegative().optional(),active:O.z.boolean().optional(),persistQueryString:O.z.boolean().optional()}),Da=O.z.strictObject({value:Ze,variationId:O.z.number().int(),key:O.z.string(),name:O.z.string().optional(),bucket:O.z.number().optional(),passthrough:O.z.boolean().optional(),inExperiment:O.z.boolean(),hashUsed:O.z.boolean().optional(),hashAttribute:O.z.string(),hashValue:O.z.string(),featureId:O.z.string().nullable(),stickyBucketUsed:O.z.boolean().optional()}),Pg=O.z.strictObject({...ul,id:O.z.string().max(255).optional(),force:Ze.optional(),variations:O.z.array(Ze).min(2).max(20).optional(),key:O.z.string().optional(),range:ka.optional(),tracks:O.z.array(O.z.strictObject({experiment:ll,result:Da})).max(100).optional()}),Cg=O.z.strictObject({defaultValue:Ze.optional(),rules:O.z.array(Pg).max(500).optional()}),wg=O.z.record(O.z.string(),O.z.union([O.z.strictObject({type:O.z.literal("hashed"),attributeKey:O.z.string(),values:O.z.array(O.z.string().regex(/^[a-f0-9]{64}$/))}),O.z.strictObject({type:O.z.literal("list"),attributeKey:O.z.string(),values:O.z.array(O.z.union([O.z.string(),O.z.number()]))}),O.z.strictObject({type:O.z.literal("condition"),condition:ut})])),tn=O.z.strictObject({scope:Xe,generation:O.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:O.z.iso.datetime({offset:!0}),expiresAt:O.z.iso.datetime({offset:!0}).nullable(),features:O.z.record(O.z.string(),Cg),savedGroups:wg,experiments:O.z.record(O.z.uuid(),ll)});var Na=tn.extend({analyticsConfig:Ra,remoteFeatures:ce.z.array(ce.z.string().min(1).max(255)).max(500)}),F_=Na.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let r of e.remoteFeatures)Object.hasOwn(e.features,r)&&t.addIssue({code:"custom",path:["features",r],message:"Remote Feature definitions cannot be public"});for(let[r,n]of Object.entries(e.savedGroups))n.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",r],message:"Raw Saved Group lists cannot be public"})}),dl=ce.z.strictObject({attributes:At,features:ce.z.array(ce.z.string().min(1).max(255)).max(500).optional(),customerId:ce.z.uuid().optional()}),Og=ce.z.strictObject({value:Ze,source:ce.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ce.z.boolean(),off:ce.z.boolean(),ruleId:ce.z.string(),experimentResult:Da.optional()}),ml=ce.z.strictObject({generation:tn.shape.generation,evaluatedAt:tn.shape.evaluatedAt,expiresAt:tn.shape.expiresAt,features:ce.z.record(ce.z.string(),Og),merchandiseContext:ce.z.strictObject({merchandiseId:ce.z.uuid(),merchandise:At}).optional()}),pl=ce.z.strictObject({customerId:ce.z.uuid().optional(),events:ce.z.array(ce.z.strictObject({eventUuid:ce.z.uuid(),timestamp:ce.z.iso.datetime({offset:!0}),name:ce.z.string().min(1).max(255),merchandise:$s.optional(),properties:ce.z.record(ce.z.string(),Ze).default({}),deviceId:ce.z.string().min(1).max(255).optional(),sessionId:ce.z.string().min(1).max(255).optional()})).min(1).max(100)}),fl=ce.z.strictObject({inserted:ce.z.number().int().nonnegative(),duplicates:ce.z.number().int().nonnegative(),rejected:ce.z.number().int().nonnegative(),skipped:ce.z.number().int().nonnegative(),analyticsConfig:Ra});function hl(e,t=[]){let r=[];st(e,i=>{i.hidden&&r.push("Hidden components must not be delivered"),t.includes(i.type)&&r.push(`Node type ${i.type} cannot be delivered`)});let n=new Set(ha(e).map(i=>i.key));for(let[i,o]of Object.entries(e.strings.locales))for(let a of Object.keys(o))n.has(a)||r.push(`Unused string ${a} must not be delivered (${i})`);return r}var G=require("zod");var Ma=G.z.array(G.z.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"),ti=G.z.intersection(At,G.z.looseObject({tags:Ma.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),ri=G.z.string().trim().max(80),ni=G.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),ii=G.z.union([G.z.email().max(254),G.z.literal("")]),ai=G.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Al=G.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),gl=G.z.object({externalUserId:Al.optional(),name:ri.default(""),email:ii.default(""),phone:ni.optional(),attributes:ti.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),W_=G.z.discriminatedUnion("type",[G.z.strictObject({type:G.z.literal("id"),value:G.z.uuid()}),G.z.strictObject({type:G.z.literal("externalUserId"),value:Al})]),Z_=G.z.strictObject({name:ri.optional(),email:ii.optional(),phone:ni.optional(),attributes:ti.optional(),fingerprint:ai.optional()});var _r=G.z.object({id:G.z.uuid(),externalUserId:G.z.string().min(1).max(255).nullable(),name:ri,email:ii,phone:ni.optional(),attributes:ti,createdAt:G.z.iso.datetime()}).strict(),bl=G.z.object({customer:_r,changed:G.z.boolean(),replayed:G.z.boolean()}).strict(),Eg=G.z.discriminatedUnion("type",[G.z.object({type:G.z.literal("id"),value:G.z.uuid()}).strict(),G.z.object({type:G.z.literal("externalUserId"),value:G.z.string().trim().min(1).max(255)}).strict()]),jg=G.z.object({name:ri.optional(),email:ii.optional(),phone:ni.optional(),attributes:ti.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:G.z.array(G.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:G.z.strictObject({add:Ma,remove:Ma}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Ua=G.z.object({lookup:Eg}).strict(),yl=Ua.extend({requestId:G.z.uuid(),patch:jg}).strict(),Sl=G.z.object({search:G.z.string().trim().max(200).default(""),tag:G.z.string().trim().max(40).default(""),planId:G.z.string().max(200).default(""),versionId:G.z.string().max(200).default(""),holdingStatus:G.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:G.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:G.z.union([G.z.iso.datetime(),G.z.literal("")]).default(""),createdUntil:G.z.union([G.z.iso.datetime(),G.z.literal("")]).default(""),offset:G.z.coerce.number().int().min(0).max(1e5).default(0),limit:G.z.coerce.number().int().min(1).max(100).default(50)}).strict(),_l=G.z.object({customers:_r.array(),hasMore:G.z.boolean(),total:G.z.number().int().nonnegative().nullable(),evaluatedAt:G.z.iso.datetime()}).strict();var F=require("zod");var xr=require("zod");var xl=xr.z.object({defaultLocale:lt,locales:xr.z.record(lt,xr.z.object({name:xr.z.string().max(80),description:xr.z.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let r=Object.keys(e.locales);(!r.length||r.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var Tg=["customer_data","coupon_code"],Rg=F.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Il=F.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),oi=(e,t)=>new Set(e.map(t)).size===e.length,kg=F.z.strictObject({currency:J,amountMinor:F.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Dg=F.z.strictObject({featureId:F.z.uuid(),name:F.z.string().trim().min(1).max(120),allowance:F.z.string().max(40).nullable(),access:F.z.boolean()}),Ng=F.z.strictObject({stripe:F.z.strictObject({prices:F.z.array(kg).min(1).max(50)}).optional(),apple:F.z.strictObject({productIds:F.z.array(Rg).min(1).max(10)}).optional(),google:F.z.strictObject({products:F.z.array(F.z.strictObject({productId:Il,basePlanId:Il.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!oi(e.stripe.prices,r=>r.currency)||e.apple&&!oi(e.apple.productIds,r=>r)||e.google&&!oi(e.google.products,r=>`${r.productId}:${r.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),Mg=F.z.strictObject({name:F.z.string().trim().min(1).max(80),interval:F.z.enum(["free","week","month","year","one_time"]),intervalCount:F.z.number().int().min(1).max(100),trial:F.z.strictObject({days:F.z.number().int().min(1).max(730),cardRequired:F.z.boolean()}).nullable(),benefits:F.z.array(Dg).max(50).refine(e=>oi(e,t=>t.featureId),"Duplicate benefit"),channels:Ng}),Ug=F.z.strictObject({digest:Sr,content:F.z.strictObject({discount:Et,duration:tt,appliesTo:Yi,displayCopy:xl.nullable(),firstPurchaseOnly:F.z.boolean(),qualificationRequired:F.z.boolean(),startsAt:F.z.iso.datetime().nullable(),endsAt:F.z.iso.datetime().nullable(),grantWindowHours:F.z.number().int().positive(),perCustomerLimit:F.z.number().int().positive()})}),qg=F.z.discriminatedUnion("type",[F.z.strictObject({type:F.z.literal("checkout"),product:ei}),F.z.strictObject({type:F.z.literal("close")}),F.z.strictObject({type:F.z.literal("action"),action:Ta})]),sx=F.z.strictObject({kind:F.z.literal("paywall"),formatVersion:F.z.literal(1),name:F.z.string().trim().min(1).max(80),offeringVersionId:F.z.uuid(),presentation:zr,screen:Jt,products:zn,catalog:F.z.record(F.z.uuid(),Mg),buttons:F.z.record(le,qg),coupons:F.z.record(F.z.uuid(),Ug)}).superRefine((e,t)=>{let r=q=>t.addIssue({code:"custom",message:q}),{screen:n}=e;n.surface!=="paywall"&&r("Screen must be a Paywall"),hl(n,Tg).forEach(r),hr(n).some(q=>!q.complete)&&r("Every published locale must be complete");let i=new Set,o=new Set,a=new Set;st(n,q=>{let Pe="bind"in q?q.bind:void 0;Pe?.promotionCode&&r("Promotion codes must not be published"),Pe?.plan&&i.add(Pe.plan),Pe?.coupon&&o.add(Pe.coupon),q.type==="plan_picker"&&(q.planIds?.forEach(Me=>i.add(Me)),q.defaultPlan&&i.add(q.defaultPlan)),q.type==="text"&&q.feature&&a.add(q.feature.id)});let c=e.products.items.map(q=>q.productVersionId),l=Object.keys(e.catalog);(c.length!==l.length||c.some(q=>!Object.hasOwn(e.catalog,q)))&&r("Catalog must contain exactly the displayed Products");let p=new Set(c);e.products.defaultProductVersionId!==null&&!p.has(e.products.defaultProductVersionId)&&r("Default Product must be displayed");for(let q of i)p.has(q)||r("Screen references a Product that is not displayed");for(let q of Object.values(e.catalog))!q.channels.stripe&&!q.channels.apple&&!q.channels.google&&r("A displayed Product needs at least one sales channel");let A=new Set(Object.values(e.catalog).flatMap(q=>q.benefits.map(Pe=>Pe.featureId)));for(let q of a)A.has(q)||r("Feature text must read a displayed benefit");let v=n.actions.filter(q=>q.type!=="navigate");n.actions.some(q=>q.type!=="event"&&q.type!=="navigate")&&r("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==v.length||v.some(q=>!Object.hasOwn(e.buttons,q.id)))&&r("Buttons must match the screen's actions");let U=!1;for(let q of Object.values(e.buttons)){if(q.type!=="checkout")continue;U=!0,(q.product.type==="fixed"?[q.product.productVersionId]:q.product.allowedProductVersionIds).some(Me=>!p.has(Me))&&r("Checkout may only sell displayed Products")}U||r("A Paywall needs a checkout button");let ie=Object.keys(e.coupons);(ie.length!==o.size||ie.some(q=>!o.has(q)))&&r("Coupons must be exactly the bound Coupons")}),vl=F.z.strictObject({state:F.z.enum(["published","archived"]),controlRevision:F.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:F.z.uuid(),versions:F.z.record(F.z.uuid(),F.z.strictObject({version:F.z.number().int().positive(),artifact:F.z.string().min(1),sourceDigest:F.z.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Lg={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},qa=ne.z.string().regex(/^[a-f0-9]{64}$/),La=ne.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Bg=Xe.extend({environmentId:ne.z.uuid()}),Fg=ne.z.strictObject({features:ne.z.array(ne.z.string()).max(500),experiments:ne.z.record(ne.z.uuid(),ne.z.array(ne.z.string()).max(20)),savedGroups:ne.z.array(ne.z.string()).max(1e3)}),Ba=ne.z.strictObject({kind:ne.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:ne.z.number().int().positive(),url:ne.z.string().min(1).max(2048),sha256:qa,byteLength:ne.z.number().int().positive().max(Lg.maxArtifactBytes),generation:qa.optional()}),Vg=ne.z.strictObject({state:ne.z.enum(["active","paused","archived"]),controlRevision:La,evaluationMode:ne.z.enum(["local","remote"]),evaluationRevision:La,currentVersionId:ne.z.uuid(),versions:ne.z.record(ne.z.uuid(),ne.z.strictObject({artifact:ne.z.string(),dependencies:Fg,definitionDigest:Sr.optional(),couponDigests:ne.z.record(ne.z.uuid(),Sr).optional()}))}),mx=ne.z.strictObject({kind:ne.z.literal("sdk_configuration"),schemaVersion:ne.z.literal(1),scope:Bg,revision:La,generation:qa,policy:ne.z.strictObject({refreshIntervalSeconds:ne.z.number().positive().max(15),maxControlAgeSeconds:ne.z.number().positive().max(60)}),gb:ne.z.strictObject({features:ne.z.string().nullable(),pageExperiments:ne.z.string().nullable()}),artifacts:ne.z.record(ne.z.string(),Ba),funnels:ne.z.record(ne.z.uuid(),Vg),paywalls:ne.z.record(ne.z.uuid(),vl).optional()}).superRefine((e,t)=>{let r=(n,i)=>{n!==null&&e.artifacts[n]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};r(e.gb.features,"gb_features"),r(e.gb.pageExperiments,"gb_page_experiments");for(let n of Object.values(e.paywalls??{}))for(let i of Object.values(n.versions))r(i.artifact,"paywall");for(let n of Object.values(e.funnels)){n.evaluationMode==="remote"&&Object.keys(n.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),n.evaluationMode==="local"&&!n.versions[n.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(n.versions))r(i.artifact,"funnel")}});var Cl=ke.z.strictObject({...Ar,selector:ke.z.discriminatedUnion("type",[ke.z.strictObject({type:ke.z.literal("paywall"),paywallId:ke.z.uuid()}),ke.z.strictObject({type:ke.z.literal("version"),versionId:ke.z.uuid()})]),customerId:ke.z.uuid().optional(),commerce:fr,locale:ke.z.string().min(1).max(35),requirement:Rt.optional()}),Pl=ke.z.strictObject({id:ke.z.uuid(),paywallId:ke.z.uuid(),version:ke.z.number().int().positive(),document:yr.omit({requirement:!0,offeringId:!0}),offering:ke.z.strictObject({id:ke.z.uuid()}),content:ke.z.strictObject({environmentId:ke.z.uuid(),offeringVersionId:ke.z.uuid(),artifact:Ba.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Bn,check:Yt.nullable()}).superRefine((e,t)=>{let r=new Set(e.document.products.items.map(n=>n.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(n=>!r.has(n.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),wl=ke.z.strictObject(Pl.shape).omit({document:!0,offering:!0}).extend({content:Pl.shape.content.unwrap()});var Ke=require("zod");var Ol={requestId:Ke.z.uuid(),sourceId:Ke.z.uuid(),expectedAvailable:Ye},El=Ke.z.discriminatedUnion("action",[Ke.z.strictObject({...Ol,action:Ke.z.enum(["add","subtract","set_remaining"]),amount:Z}),Ke.z.strictObject({...Ol,action:Ke.z.literal("edit"),granted:Z,expiresAt:Ke.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Ke.z.iso.datetime({offset:!0}).nullable(),expectedRevision:Ke.z.number().int().nonnegative()})]),Fa=Ke.z.strictObject({sourceId:Ke.z.uuid(),available:Ye,held:Ye,spent:Ye,adjustmentGrantId:Ke.z.uuid().nullable()}),jl=Fa.extend({granted:Ye,expiresAt:Ke.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Ke.z.iso.datetime({offset:!0}).nullable(),revision:Ke.z.number().int().nonnegative()});var et=require("zod"),Tl=et.z.discriminatedUnion("action",[et.z.object({action:et.z.literal("upsert"),externalId:et.z.string().min(1).max(128),name:et.z.string().trim().min(1).max(80)}).strict(),et.z.object({action:et.z.literal("archive"),entityId:et.z.uuid()}).strict()]),Rl=et.z.object({id:et.z.uuid(),externalId:et.z.string().min(1).max(128),name:et.z.string().min(1).max(80),archived:et.z.boolean()}).strict();var Ge=require("zod");var Dt=require("zod"),Dl=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],kl=Dt.z.string().regex(/.+\/.+/),Va=Dt.z.number().min(-100),nr=Dt.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),$g=Dt.z.strictObject({input:nr,output:nr,cache_read:nr.optional(),cache_write:nr.optional(),reasoning:nr.optional(),input_audio:nr.optional(),output_audio:nr.optional()}),$a=(e,t)=>Dt.z.record(e,t).refine(r=>Object.keys(r).length<=100,"At most 100 AI overrides"),Px=Dt.z.strictObject({defaultMarkup:Va,providerMarkups:$a(Dt.z.string().min(1),Va),modelMarkups:$a(kl,Va),customModels:$a(kl,$g.partial())});var Y=require("zod"),ir=Y.z.iso.datetime({offset:!0}),Nt=Y.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Gg=Y.z.discriminatedUnion("kind",[Y.z.object({kind:Y.z.literal("absolute"),from:ir,to:ir}).strict(),Y.z.object({kind:Y.z.literal("last_days"),days:Y.z.union([Y.z.literal(1),Y.z.literal(7),Y.z.literal(30),Y.z.literal(90)])}).strict(),Y.z.object({kind:Y.z.literal("billing_cycles"),membershipId:Y.z.uuid(),count:Y.z.number().int().min(1).max(12),includeCurrent:Y.z.boolean()}).strict()]),Nl=Y.z.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),Hg=Y.z.object({key:Y.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:Y.z.array(Y.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),ar=Y.z.object({range:Gg,timezone:Nl,filterBy:Y.z.array(Hg).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:Y.z.enum(["hour","day","week","month"]),internal_feature_id:Y.z.uuid().nullable(),entityId:Y.z.uuid().nullable(),topN:Y.z.number().int().min(1).max(50).nullable(),groupBy:Y.z.union([Y.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),Y.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Y.z.object({bucket:ir,group:Y.z.string().max(240),isOther:Y.z.boolean(),internal_feature_id:Y.z.uuid(),resourceId:Y.z.uuid()}).strict().nullable(),limit:Y.z.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let r=Date.parse(e.range.to)-Date.parse(e.range.from);(r<=0||r>366*864e5||e.interval==="hour"&&r>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Ml=Y.z.object({from:ir,to:ir,interval:Y.z.enum(["hour","day","week","month"]),timezone:Nl,rows:Y.z.array(Y.z.object({bucket:ir,group:Y.z.string().max(240),isOther:Y.z.boolean(),internal_feature_id:Y.z.uuid(),resourceId:Y.z.uuid(),consumedUnits:Nt,refundedUnits:Nt,reservedUnits:Nt,charged:Nt,refunded:Nt,reserved:Nt,netUnits:Nt,netCharged:Nt}).strict()).max(100),nextCursor:Y.z.object({bucket:ir,group:Y.z.string().max(240),isOther:Y.z.boolean(),internal_feature_id:Y.z.uuid(),resourceId:Y.z.uuid()}).strict().nullable()}).strict();var Ir=Ge.z.string().regex(/^(0|[1-9]\d{0,29})$/),Ul=Ge.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Ga=Ge.z.strictObject({bucket:Ge.z.iso.datetime({offset:!0}),group:Ge.z.string().max(240),isOther:Ge.z.boolean(),internal_feature_id:Ge.z.uuid()}),ql=Ge.z.strictObject({...ar.shape,groupBy:Ge.z.union([Ge.z.enum(["customer","entity","entitlement"]),Ge.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Ga.nullable()}).superRefine((e,t)=>{let r=ar.safeParse({...e,after:null});if(!r.success)for(let n of r.error.issues)t.addIssue({code:"custom",path:n.path,message:n.message})}),Ll=Ge.z.strictObject({from:Ge.z.iso.datetime({offset:!0}),to:Ge.z.iso.datetime({offset:!0}),interval:ar.shape.interval,timezone:ar.shape.timezone,rows:Ge.z.array(Ge.z.strictObject({...Ga.shape,eventCount:Ir,units:Ul,tokenEventCount:Ir,tokens:Ge.z.strictObject(Object.fromEntries(Dl.map(e=>[e,Ir]))),totalTokens:Ir,providerCostEventCount:Ir,providerCostUsd:Ul,invalidTelemetryEventCount:Ir})).max(100),nextCursor:Ga.nullable()});var Oe=require("zod");var Bl=Oe.z.object({requestId:Oe.z.uuid(),items:Oe.z.array(Oe.z.object({customerId:Oe.z.uuid(),command:Lr.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"),Fl=Oe.z.object({batchId:Oe.z.uuid(),after:Oe.z.number().int().min(-1).max(999),limit:Oe.z.number().int().min(1).max(100)}).strict(),Vl=Oe.z.object({batchId:Oe.z.uuid(),status:Oe.z.enum(["queued","complete"]),total:Oe.z.number().int().min(1).max(1e3),processed:Oe.z.number().int().min(0).max(1e3),items:Oe.z.array(Oe.z.object({position:Oe.z.number().int().min(0).max(999),customerId:Oe.z.uuid(),idempotencyKey:Oe.z.string().min(1).max(120),status:Oe.z.enum(["queued","accepted","rejected","failed"]),receipt:Br.nullable(),errorCode:Oe.z.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:Oe.z.number().int().min(0).max(999).nullable()}).strict();var h=require("zod");var Kg=h.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),$l=h.z.enum(["draft","active","paused","archived"]),Gl=h.z.string().min(1).max(256),Hl=h.z.array(Gl).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Wg=h.z.strictObject({duration:h.z.enum(["day","week","month","year"]),length:h.z.number().int().min(1).max(3660)}),Zg=h.z.strictObject({internal_feature_id:h.z.uuid(),allowance:h.z.number().nonnegative().max(1e15).nullable(),expiry:Wg.nullable()}),Qg=h.z.discriminatedUnion("type",[h.z.strictObject({type:h.z.literal("feature_grant"),grants:h.z.array(Zg).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),h.z.strictObject({type:h.z.literal("free_product"),productId:Gl,duration:tt}),h.z.strictObject({type:h.z.literal("invoice_credits"),amount:h.z.number().positive().max(1e8),duration:tt,rollover:h.z.boolean(),productIds:Hl})]),Yg=h.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Kl=h.z.object({key:Yg,name:h.z.string().trim().min(1).max(80),configuration:Qg}).strict(),Wl=h.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Ha=h.z.object({code:Wl,maxUses:h.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:h.z.boolean()}).strict(),Zl=h.z.object({key:h.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:h.z.string().trim().min(1).max(80),rewardId:h.z.uuid(),redeemOn:h.z.enum(["customer_creation","checkout"]),receivedBy:h.z.enum(["referrer","all"]),maxRedemptions:h.z.number().int().min(1).max(1e6).nullable(),productIds:Hl,excludeTrial:h.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Ql={id:h.z.uuid(),projectId:h.z.uuid(),environmentId:h.z.uuid(),revision:h.z.number().int().nonnegative(),status:$l,createdAt:h.z.iso.datetime({offset:!0}),updatedAt:h.z.iso.datetime({offset:!0})},Xg=Kl.extend(Ql).strict(),Jg=Zl.safeExtend(Ql).strict(),Nx=h.z.strictObject({id:h.z.uuid(),key:h.z.string(),name:h.z.string(),type:Kg,status:$l}),Mx=h.z.discriminatedUnion("action",[h.z.object({action:h.z.literal("save"),id:h.z.uuid().nullable(),revision:h.z.number().int().nonnegative(),input:Kl}).strict(),h.z.object({action:h.z.enum(["activate","pause","resume","archive","delete"]),id:h.z.uuid(),revision:h.z.number().int().nonnegative()}).strict()]),Ux=h.z.discriminatedUnion("action",[h.z.object({action:h.z.literal("save"),id:h.z.uuid().nullable(),revision:h.z.number().int().nonnegative(),input:Zl}).strict(),h.z.object({action:h.z.enum(["activate","pause","resume","archive","delete"]),id:h.z.uuid(),revision:h.z.number().int().nonnegative()}).strict()]),Yl=h.z.object({id:h.z.uuid(),rewardId:h.z.uuid(),programId:h.z.uuid().nullable(),customerId:h.z.uuid(),referrerId:h.z.uuid().nullable(),status:h.z.enum(["pending","applied","unavailable"]),result:h.z.record(h.z.string(),h.z.unknown()).nullable(),createdAt:h.z.iso.datetime({offset:!0})}).strict(),Xl=h.z.object({code:Wl,requestId:h.z.uuid()}).strict(),Jl=h.z.strictObject({redemptionId:h.z.uuid(),currency:J,requestId:h.z.uuid(),accepted:h.z.literal(!0)}),zg=h.z.strictObject({type:h.z.literal("checkout"),orderId:h.z.uuid(),productVersionId:h.z.uuid(),currency:J,duration:tt,renewalAmountMinor:h.z.number().int().positive().max(1e8),status:h.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:h.z.url().nullable()}),zl=h.z.discriminatedUnion("type",[zg,h.z.strictObject({type:h.z.literal("subscription"),operationId:h.z.uuid(),membershipId:h.z.uuid(),productVersionId:h.z.uuid(),currency:J,duration:tt,renewalAmountMinor:h.z.number().int().positive().max(1e8),status:h.z.enum(["pending","running","applied","failed"])})]),ed=h.z.object({programId:h.z.uuid(),requestId:h.z.uuid()}).strict(),td=h.z.object({id:h.z.uuid(),programId:h.z.uuid(),code:Ha.shape.code,createdAt:h.z.iso.datetime({offset:!0})}).strict(),qx=h.z.object({rows:h.z.array(Xg).max(100),nextCursor:h.z.uuid().nullable()}).strict(),Lx=h.z.object({rows:h.z.array(Jg).max(100),nextCursor:h.z.uuid().nullable()}).strict(),eb=Ha.extend({id:h.z.uuid(),redemptions:h.z.number().int().nonnegative()}).strict(),tb=h.z.strictObject({id:h.z.uuid(),programId:h.z.uuid().nullable(),customerId:h.z.uuid().nullable(),referrerId:h.z.uuid().nullable(),code:h.z.string().nullable(),status:h.z.enum(["pending","triggered","applied"]),createdAt:h.z.iso.datetime({offset:!0})}),Bx=h.z.object({codes:h.z.array(eb).max(100),redemptions:h.z.array(tb).max(100),customers:h.z.record(h.z.uuid(),h.z.string()),codesCursor:h.z.uuid().nullable(),redemptionsCursor:h.z.uuid().nullable()}).strict(),Fx=h.z.discriminatedUnion("action",[h.z.object({action:h.z.literal("create"),rewardId:h.z.uuid(),revision:h.z.number().int().nonnegative(),input:Ha}).strict(),h.z.object({action:h.z.literal("remove"),rewardId:h.z.uuid(),revision:h.z.number().int().nonnegative(),codeId:h.z.uuid()}).strict()]);var m=require("zod");var T=require("zod"),yt={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},rn=e=>new Set(e).size===e.length,Ka=T.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),rb=T.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),nn=T.z.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),nb=T.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),rd=T.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var nd=T.z.strictObject({id:T.z.uuid(),repo:rb,platform:T.z.enum(["github","gitlab","bitbucket"]),branches:T.z.array(nn).min(1).max(4).refine(rn),workflow:T.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:T.z.array(T.z.uuid()).min(1).max(4).refine(rn),include:T.z.array(rd).min(1).max(16),exclude:T.z.array(rd).max(16),methods:T.z.array(T.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(rn),maxAgeHours:T.z.number().int().min(1).max(720)}),id=nd.extend({revision:T.z.number().int().positive()}),$x=T.z.strictObject({repository:nd,expectedRevision:T.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),ad=T.z.strictObject({repositoryId:T.z.uuid(),branch:nn}),ib=T.z.array(Ka).max(yt.keys).refine(rn),od=T.z.strictObject({repository:id.omit({keyIds:!0}),branch:nn,keys:ib,keySetHash:T.z.string().regex(/^[a-f0-9]{64}$/)}),ab=T.z.strictObject({filePath:nb,startingLineNumber:T.z.number().int().min(1).max(1e7)}),Wa=T.z.strictObject({protocol:T.z.literal(1),repositoryId:T.z.uuid(),branch:nn,workflow:T.z.string().max(200),configurationRevision:T.z.number().int().positive(),keySetHash:T.z.string().regex(/^[a-f0-9]{64}$/),commit:T.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:T.z.uuid(),runNumber:T.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:T.z.number().int().min(1).max(1e4),scannerVersion:T.z.literal("1"),scannedAt:T.z.iso.datetime({offset:!0}),coverage:T.z.strictObject({complete:T.z.literal(!0),files:T.z.number().int().min(0).max(yt.files),sourceBytes:T.z.number().int().min(0).max(yt.sourceBytes),unresolvedCalls:T.z.number().int().min(0).max(1e6),unsupportedFiles:T.z.number().int().min(0).max(yt.files)}),features:T.z.array(T.z.strictObject({key:Ka,refs:T.z.array(ab).max(yt.referencesPerKey)})).max(yt.keys)}).superRefine((e,t)=>{rn(e.features.map(r=>r.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((r,n)=>r+n.refs.length,0)>yt.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Za=T.z.strictObject({scanId:T.z.uuid(),commit:T.z.string(),receivedAt:T.z.string(),references:T.z.number().int().nonnegative(),removedReferences:T.z.number().int().nonnegative()}),ob=Za.extend({repositoryId:T.z.uuid(),branch:nn,workflow:T.z.string(),digest:T.z.string(),configurationRevision:T.z.number().int().positive(),runNumber:T.z.number().int().positive(),runAttempt:T.z.number().int().positive(),scannedAt:T.z.string(),keySetHash:T.z.string(),coverage:Wa.shape.coverage}),sb=T.z.strictObject({repositories:T.z.array(id).max(yt.repositories),scans:T.z.array(ob).max(yt.repositories*yt.branches)}),cb=T.z.strictObject({key:Ka,references:T.z.number().int().nonnegative(),coveredTargets:T.z.number().int().nonnegative(),expiredTargets:T.z.number().int().nonnegative(),uncertainTargets:T.z.number().int().nonnegative()}),Gx=T.z.strictObject({available:T.z.boolean().default(!0),settings:sb,expectedTargets:T.z.number().int().min(0).max(80),features:T.z.array(cb).max(2001),truncated:T.z.boolean()});var We=require("zod"),cd={customerId:We.z.uuid(),eventId:We.z.string().trim().min(1).max(200),grantId:We.z.uuid(),occurredAt:We.z.iso.datetime({offset:!0})},ud=We.z.strictObject({...cd,productVersionId:We.z.uuid(),subscriptionId:We.z.string().trim().min(1).max(255)}),ld=We.z.strictObject({...cd,merchandiseId:We.z.uuid()}),dd=We.z.union([ud,ld]),sd={id:We.z.uuid(),couponId:We.z.uuid(),status:We.z.literal("redeemed"),source:We.z.literal("merchant"),recordedAt:We.z.iso.datetime({offset:!0})},md=We.z.union([ud.extend(sd),ld.extend(sd)]);var B=require("zod");var Qa=B.z.strictObject({name:B.z.string().trim().min(1).max(255),memo:B.z.string().max(1e4).nullable().optional(),footer:B.z.string().max(1e4).nullable().optional(),net_terms_days:B.z.number().int().positive().nullable().optional()}),ub=Qa.extend({id:B.z.string().min(1).max(255),created_at:B.z.number().nullable()}),pd=B.z.strictObject({items:B.z.array(ub).max(50),nextCursor:B.z.uuid().nullable()}),Zx=B.z.discriminatedUnion("action",[B.z.strictObject({action:B.z.literal("create"),requestId:B.z.uuid(),values:Qa}),B.z.strictObject({action:B.z.literal("update"),id:B.z.string().min(1).max(255),values:Qa}),B.z.strictObject({action:B.z.literal("delete"),id:B.z.string().min(1).max(255)})]),fd=B.z.discriminatedUnion("action",[B.z.strictObject({action:B.z.literal("create"),requestId:B.z.uuid(),params:gr}),B.z.strictObject({action:B.z.enum(["finalize","send","pay","void"]),requestId:B.z.uuid(),invoiceId:B.z.uuid()}),B.z.strictObject({action:B.z.literal("reissue"),requestId:B.z.uuid(),invoiceId:B.z.uuid(),params:ya})]),Ya=B.z.strictObject({id:B.z.uuid(),customerId:B.z.uuid(),providerInvoiceId:B.z.string().nullable(),status:B.z.enum(["draft","open","paid","void","uncollectible"]),currency:B.z.string(),totalMinor:B.z.string().regex(/^-?\d+$/),paidMinor:B.z.string().regex(/^\d+$/),refundedMinor:B.z.string().regex(/^\d+$/),hostedInvoiceUrl:B.z.url().nullable(),createdAt:B.z.number(),collectionMethod:B.z.enum(["send_invoice","charge_automatically"]).nullable()}),hd=Ya.extend({lines:B.z.array(B.z.strictObject({id:B.z.uuid(),description:B.z.string(),amountMinor:B.z.string().regex(/^-?\d+$/),netAmountMinor:B.z.string().regex(/^-?\d+$/),quantity:B.z.number().nullable(),periodStart:B.z.number().nullable(),periodEnd:B.z.number().nullable()})).max(1e3)}),an=B.z.strictObject({taskId:B.z.uuid(),status:B.z.enum(["ready","running","done","dead"]),invoice:Ya.nullable(),errorCode:B.z.string().nullable()}),Ad=B.z.strictObject({items:B.z.array(Ya).max(50),nextCursor:B.z.uuid().nullable(),operations:B.z.array(an).max(50),operationsLimited:B.z.boolean()});var lb=m.z.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),gd={scope:Xe,permissions:m.z.array(lb),expiresAt:m.z.iso.datetime().nullable()},UI=m.z.discriminatedUnion("kind",[m.z.object({...gd,kind:m.z.literal("server"),keyId:m.z.string().min(1)}),m.z.object({...gd,kind:m.z.literal("customer"),customerId:m.z.string().min(1),identityKind:m.z.enum(["identified","guest"]),expiresAt:m.z.iso.datetime()})]),P=m.z.object({requestId:m.z.uuid(),scope:Xe}).strict(),db=gl.safeExtend({fingerprint:ai.optional()}).strict(),mb=P.extend({customer:_r,created:m.z.boolean()});function bd(){return P.extend({offer:Xi.nullable(),reason:Ks.nullable()})}var _={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:$c,response:P.extend({message:m.z.object({messageId:m.z.uuid(),channel:Gr,acceptedAt:m.z.iso.datetime({offset:!0}),status:m.z.enum(["accepted","sending","completed","canceled"]),replayed:m.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:m.z.strictObject({messageId:m.z.uuid()}),response:P.extend({message:m.z.object({id:m.z.uuid(),channel:Gr,status:m.z.enum(["accepted","sending","completed","canceled"]),deliveries:m.z.array(m.z.object({id:m.z.uuid(),status:Hc,attempts:m.z.number().int().nonnegative(),receipts:m.z.array(m.z.object({kind:Kc,occurredAt:m.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:_o,response:P.extend({installation:qt})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:xo,response:P.extend({installation:qt})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:hn,response:P.extend({installation:qt})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:m.z.strictObject({channel:Gr}),response:P.extend({preference:gi})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Gc,response:P.extend({preference:gi})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:m.z.strictObject({cursor:m.z.uuid().optional()}),response:P.extend({templates:pd})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),params:gr}),response:P.extend({preview:Sa})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),requestId:m.z.uuid(),params:gr}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:P.extend({operation:an})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),command:fd}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:P.extend({operation:an})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),taskId:m.z.uuid()}),response:P.extend({operation:an})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),cursor:m.z.uuid().optional()}),response:P.extend({invoices:Ad})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),invoiceId:m.z.uuid()}),response:P.extend({invoice:hd})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:ad,response:P.extend({config:od})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Wa,response:P.extend({receipt:Za})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:m.z.strictObject({}),response:P.extend({payload:Na})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:dl,response:P.merge(ml)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:pl,response:P.merge(fl)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),sourceId:m.z.uuid()}),response:P.extend({balance:jl})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),command:El}),response:P.extend({balance:Fa})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:m.z.strictObject({internal_feature_id:m.z.uuid(),customerId:m.z.uuid().optional(),entityId:m.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:P.extend({internal_feature_id:m.z.uuid(),config:$i,model_markups:jn})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),query:Un}),response:P.extend({usage:Fr})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),command:kc}),response:P.extend({usage:Fr})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),command:wc}),response:P.extend({grant:oa})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Oc,response:P.extend({grants:Ec})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:m.z.union(tl.options.map(e=>e.extend({customerId:m.z.uuid().optional(),customerToken:m.z.string().regex(qn).optional()}))),response:P.extend({operation:rl})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Gu.extend({customerId:m.z.uuid().optional()}),response:P.extend({setup:Ca})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Hu.extend({customerId:m.z.uuid().optional()}),response:P.extend({setup:Ca})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Fu.safeExtend({customerId:m.z.uuid()}),response:P.extend({batch:Yr})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Zn.extend({customerId:m.z.uuid()}),response:P.extend({batch:Yr})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Zn.extend({customerId:m.z.uuid()}),response:P.extend({batch:Yr})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Zn.extend({customerId:m.z.uuid()}),response:P.extend({batch:Yr})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:m.z.discriminatedUnion("action",[Qn.options[0].extend({customerId:m.z.uuid()}),Qn.options[1].extend({customerId:m.z.uuid()}),Qn.options[2].extend({customerId:m.z.uuid()})]),response:P.extend({trial:Pa})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Vu.extend({customerId:m.z.uuid()}),response:P.extend({trial:Pa})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Jn,response:P.extend({subscriptions:Ju})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Jn,response:P.extend({purchases:zu})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Qu,response:P.extend({conflicts:el})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Yu,response:P.extend({resolution:Xu})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Wu,response:P.extend({verification:Zu})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Tu.safeExtend({...Ar,customerId:m.z.uuid().optional()}),response:P.extend({quote:Du})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:tr.extend({customerId:m.z.uuid().optional(),intent:m.z.enum(["confirm","cancel"]).optional()}),response:P.extend({operation:_a})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:tr.extend({customerId:m.z.uuid().optional()}),response:P.extend({operation:_a})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Nu.safeExtend({customerId:m.z.uuid().optional()}),response:P.extend({quote:Uu})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:tr.extend({customerId:m.z.uuid().optional(),intent:m.z.enum(["confirm","cancel"]).optional()}),response:P.extend({operation:Ia})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:tr.extend({customerId:m.z.uuid().optional()}),response:P.extend({operation:Ia})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:qu.safeExtend({customerId:m.z.uuid()}),response:P.extend({quote:Bu})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:tr.extend({customerId:m.z.uuid()}),response:P.extend({operation:Wn})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:tr.extend({customerId:m.z.uuid()}),response:P.extend({operation:Wn})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:dc,response:P.extend({controls:ea})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:ic,response:P.extend({prepared:oc})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:sc,response:P.extend({authorization:kn})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:hc,response:P.extend({coupons:Ac})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:cc,response:P.extend({authorization:kn})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:pc,response:P.extend({invoices:fc})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:mc,response:P.extend({invoice:Dr})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:m.z.object({customerId:m.z.uuid(),command:lc}).strict(),response:P.extend({controls:ea})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:m.z.object({customerId:m.z.uuid(),command:Tl}).strict(),response:P.extend({entity:Rl})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid().nullable(),query:ql}),response:P.extend({analytics:Ll})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:m.z.object({customerId:m.z.uuid().nullable(),query:ar}).strict(),response:P.extend({analytics:Ml})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Bl,response:P.extend({batchId:m.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Fl,response:P.extend({batch:Vl})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Yc.extend({customerId:m.z.string().min(1).optional()}),response:P.extend({check:Yt})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:m.z.strictObject({kind:kt,selector:m.z.discriminatedUnion("type",[m.z.strictObject({type:m.z.literal("resource"),id:m.z.uuid()}),m.z.strictObject({type:m.z.literal("version"),id:m.z.uuid()})]),customerId:m.z.string().min(1).optional()}),response:P.extend({content:Aa})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Cl,response:P.extend({paywall:wl})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:m.z.strictObject({...Ar,selector:ol,customerId:m.z.string().min(1).optional(),commerce:fr,requirement:Rt.optional()}),response:P.extend({offering:sl,candidates:m.z.array(da).max(20),availability:m.z.array(m.z.strictObject({productVersionId:m.z.uuid(),available:m.z.boolean(),reason:m.z.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:Yt.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:m.z.object({customerId:m.z.uuid().optional(),entityId:m.z.uuid().optional()}).strict(),response:P.extend({holdings:Dc})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:m.z.object({customerId:m.z.uuid().optional(),query:Uc}).strict(),response:P.extend({ledger:qc})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:jc.extend({customerId:m.z.uuid().optional()}),response:P.extend({detail:Tc})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:sa.safeExtend({customerId:m.z.uuid().optional()}),response:P.extend({statement:Rc})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:m.z.object({customerId:m.z.uuid().optional(),command:Lr.options[0]}).strict(),response:P.extend({quote:vc})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),command:m.z.union([m.z.strictObject({eventName:m.z.string().min(1),quantity:Z.optional(),properties:Ne.optional(),entityId:m.z.uuid().optional(),idempotencyKey:m.z.string().min(1).max(120)}),m.z.strictObject({internal_feature_id:m.z.uuid(),quantity:Z.optional(),properties:Ne.optional(),entityId:m.z.uuid().optional(),idempotencyKey:m.z.string().min(1).max(120)})])}),response:P.extend({receipts:m.z.array(Br).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:m.z.object({customerId:m.z.uuid(),command:Lr.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:P.extend({receipt:Br})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Xl,response:P.extend({redemption:Yl})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:ed,response:P.extend({referralCode:td})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Jl,response:P.extend({checkout:zl})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Bc,response:P.extend({seats:la})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Fc,response:P.extend({seats:la})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:db,response:mb},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Ua,response:P.extend({customer:_r})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Sl,response:P.extend(_l.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:yl,response:P.extend(bl.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:m.z.object({customerId:m.z.uuid()}).strict(),response:P.extend(pr.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:m.z.strictObject({}),response:P.extend(pr.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),sessionId:m.z.uuid().optional()}),response:P.extend({revoked:m.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:m.z.strictObject({guestToken:m.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ai.optional()}),response:P.extend({customerId:m.z.uuid(),guestToken:m.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:m.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:m.z.strictObject({guestToken:m.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:P.extend(pr.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:m.z.strictObject({guestToken:m.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:m.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:m.z.uuid()}),response:P.extend({customer:_r,switched:m.z.boolean(),replayed:m.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:m.z.strictObject({code:m.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:m.z.uuid()}),response:bd()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:m.z.object({}).strict(),response:P.extend({offers:m.z.array(Xi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:m.z.object({customerId:m.z.string().min(1).max(255).optional(),couponId:m.z.uuid(),...Ar,requestId:m.z.uuid(),couponContentDigest:m.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:bd()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:dd,response:P.extend({receipt:md})}},qI={sendMessage:_.sendMessage,readMessage:_.readMessage,bindPushInstallation:_.bindPushInstallation,readPushInstallation:_.readPushInstallation,updatePushAddress:_.updatePushAddress,readMessagingPreference:_.readMessagingPreference,setMessagingPreference:_.setMessagingPreference,listInvoiceTemplates:_.listInvoiceTemplates,previewInvoice:_.previewInvoice,createInvoice:_.createInvoice,manageInvoice:_.manageInvoice,readInvoiceOperation:_.readInvoiceOperation,listInvoices:_.listInvoices,getInvoice:_.getInvoice,getCodeReferenceConfig:_.getCodeReferenceConfig,submitCodeReferences:_.submitCodeReferences,getFeatures:_.getFeatures,evaluateFeatures:_.evaluateFeatures,trackEvents:_.trackEvents,setupPayment:_.setupPayment,readPaymentSetup:_.readPaymentSetup,previewSubscriptionBatch:_.previewSubscriptionBatch,confirmSubscriptionBatch:_.confirmSubscriptionBatch,readSubscriptionBatch:_.readSubscriptionBatch,abandonSubscriptionBatch:_.abandonSubscriptionBatch,manageSubscriptionTrial:_.manageSubscriptionTrial,readSubscriptionTrial:_.readSubscriptionTrial,listSubscriptions:_.listSubscriptions,listPurchases:_.listPurchases,listSubscriptionConflicts:_.listSubscriptionConflicts,retrySubscriptionConflict:_.retrySubscriptionConflict,readAiPricing:_.readAiPricing,readUsage:_.readUsage,setUsage:_.setUsage,previewRefund:_.previewRefund,refund:_.refund,readRefund:_.readRefund,previewUpdate:_.previewUpdate,update:_.update,readSubscriptionUpdate:_.readSubscriptionUpdate,restoreNativePurchase:_.restoreNativePurchase,verifySubscriptions:_.verifySubscriptions,previewAttach:_.previewAttach,attach:_.attach,readSubscriptionOperation:_.readSubscriptionOperation,manageBalanceGrant:_.manageBalanceGrant,readBalanceSource:_.readBalanceSource,adjustBalance:_.adjustBalance,listBalanceGrants:_.listBalanceGrants,readBillingControls:_.readBillingControls,prepareBillingAuthorization:_.prepareBillingAuthorization,confirmBillingAuthorization:_.confirmBillingAuthorization,setBillingCoupons:_.setBillingCoupons,revokeBillingAuthorization:_.revokeBillingAuthorization,listBillingInvoices:_.listBillingInvoices,confirmBillingAdjustment:_.confirmBillingAdjustment,manageBillingLimits:_.manageBillingLimits,createCustomer:_.createCustomer,getCustomer:_.getCustomer,listCustomers:_.listCustomers,updateCustomer:_.updateCustomer,createSession:_.createSession,refreshSession:_.refreshSession,revokeSessions:_.revokeSessions,createGuestCustomer:_.createGuestCustomer,resumeGuestSession:_.resumeGuestSession,claimGuestCustomer:_.claimGuestCustomer,checkEntitlement:_.checkEntitlement,resolveOffering:_.resolveOffering,resolveContent:_.resolveContent,resolvePaywall:_.resolvePaywall,readHoldings:_.readHoldings,readLedger:_.readLedger,readBillingInvoice:_.readBillingInvoice,readCreditStatement:_.readCreditStatement,quoteBalance:_.quoteBalance,trackUsage:_.trackUsage,mutateBalance:_.mutateBalance,manageUsageEntity:_.manageUsageEntity,readUsageAnalytics:_.readUsageAnalytics,readCreditAnalytics:_.readCreditAnalytics,submitUsageBatch:_.submitUsageBatch,readUsageBatch:_.readUsageBatch,listOffers:_.listOffers,grantOffer:_.grantOffer,recordCouponRedemption:_.recordCouponRedemption,redeemCoupon:_.redeemCoupon,redeemReward:_.redeemReward,createReferralCode:_.createReferralCode,claimRewardProduct:_.claimRewardProduct,readSeats:_.readSeats,manageSeat:_.manageSeat};var R=class extends Error{constructor(r,n,i,o,a){super(n);wt(this,"code",r);wt(this,"status",i);wt(this,"requestId",o);wt(this,"retryable");wt(this,"recovery");wt(this,"retryAfterSeconds");wt(this,"reason");this.name="IndianaError",this.reason=a?.reason;let c=An(r,i??0,{...a,retryAfter:a?.retryAfterSeconds===void 0?void 0:String(a.retryAfterSeconds)});this.retryable=c.retryable,this.recovery=c.recovery,this.retryAfterSeconds=c.retryAfterSeconds}};var on=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new R("INVALID_STATE","Installation sequence exhausted");return e+1},pb=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function Pt(e,t){return e.transaction(r=>{if(!Number.isSafeInteger(r.identitySeq)||r.identitySeq<0||!Number.isSafeInteger(r.addressSeq)||r.addressSeq<0||r.detachSeq!==null&&(!Number.isSafeInteger(r.detachSeq)||r.detachSeq<1||r.detachSeq>r.identitySeq))throw new R("INVALID_STATE","Installation journal is invalid");return t({...r})})}function yd(e,t,r){let n=null,i=0,o=0,a=0,c=Promise.resolve();if(e&&(!r||Xe.parse(e.scope).projectId!==r.projectId||e.scope.environment!==r.environment))throw new R("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(!e)throw new R("NOT_CONFIGURED","Configure this client's native Push host first");return e},p=j=>{if(j!==i)throw new R("IDENTITY_CHANGED","Identity changed during Push operation")};async function A(j){let V=l();if(!V.sha256&&!globalThis.crypto?.subtle)throw new R("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let X=V.sha256?await V.sha256(Uint8Array.from(j,he=>he.charCodeAt(0))):await pb(j);if(!/^[a-f0-9]{64}$/.test(X))throw new R("INVALID_STATE","Push credential digest is invalid");return X}function v(j){let V=qt.parse(j);if(V.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new R("INVALID_RESPONSE","Push response belongs to another installation");return V}async function k(j,V){let X=l(),he={installationId:X.installationId,publicKey:X.publicKey,issuedAt:new Date().toISOString(),...V},be=await X.sign(Co(j,X.scope,he));return{...he,signature:be}}let U=(j,V,X)=>t.requestWithCredential?t.requestWithCredential(j,V,X):t.request(j,V);async function ie(){let j=l(),V=i,X=n?await(t.session?.access()??n):null,he=Pt(j,Ue=>Ue),be;if(he.detachSeq!==null){let Ue=he.detachSeq,Pr=Io.parse(await k("detach",{sequence:Ue,platform:j.platform}));try{let we=await t.request("push/installations/detach",{...j.scope,...Pr},"POST",{installationDetach:!0});if(!we||typeof we!="object"||!("installation"in we))throw new R("INVALID_RESPONSE","Push detach acknowledgement is invalid");let at=v(we.installation);if(at.bound||at.identitySeq!==Ue)throw new R("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(we){if(we instanceof R&&we.status===404)be=we;else if(!(we instanceof R)||we.status!==412)throw we}be||Pt(j,we=>({...we,detachSeq:we.detachSeq===Ue?null:we.detachSeq}))}if(p(V),!X){if(be)throw be;return null}let Ae=_.bindPushInstallation,Ve=Ae.request.parse(await k("bind",{sequence:a,platform:j.platform,credentialDigest:await A(X)}));p(V);let Te=Ae.response.parse(await U(Ae.path,Ve,X));p(V);let ct=v(Te.installation);if(!ct.bound||ct.identitySeq!==a)throw new R("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return be&&he.detachSeq!==null&&a>he.detachSeq&&Pt(j,Ue=>({...Ue,detachSeq:Ue.detachSeq===he.detachSeq?null:Ue.detachSeq})),ct}async function q(){l();let j=i,V=n?await(t.session?.access()??n):null;if(!V)throw new R("NOT_IDENTIFIED","Identify before reading this installation");let X=_.readPushInstallation,he=X.request.parse(await k("read",{credentialDigest:await A(V)}));p(j);let be=X.response.parse(await U(X.path,he,V));return p(j),v(be.installation)}function Pe(j=ie){let V=c.catch(()=>{}).then(j);return c=V,V.catch(X=>{try{e?.onError?.(X instanceof Error?X:new Error("Push synchronization failed"))}catch{}}),V}async function Me(j,V,X){let he=l(),be=V.identity,Ae=V.observation,Ve=n?await(t.session?.access()??n):null;if(p(be),Ae!==o)throw new R("INVALID_STATE","Push observation changed during recovery");if(!Ve)throw new R("NOT_IDENTIFIED","Identify before recovering a Push address");if(!j.connectionId||!j.kind||!j.token||!["granted","provisional"].includes(j.permission))throw new R("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await Pe(async()=>{if(p(be),await ie(),p(be),Ae!==o)throw new R("INVALID_STATE","Push observation changed during recovery");let Te=Pt(he,at=>X?at:{...at,addressSeq:on(at.addressSeq)}),Ue=await k(X?"recovery_confirm":"recovery_request",{...j,sequence:Te.addressSeq,credentialDigest:await A(Ve),...X?{challenge:X}:{}}),Pr=X?Po.parse(Ue):vo.parse(Ue);if(p(be),Ae!==o)throw new R("INVALID_STATE","Push observation changed during recovery");let we=await U(`push/installations/recovery/${X?"confirm":"request"}`,Pr,Ve);if(p(be),Ae!==o||Pt(he,at=>at).addressSeq!==Te.addressSeq)throw new R("INVALID_STATE","Push observation changed during recovery");if(X){let at=_.updatePushAddress.response.parse(we),Ce=v(at.installation);if(!Ce.bound||Ce.identitySeq!==a||Ce.addressSeq!==Te.addressSeq||Ce.connectionId!==j.connectionId||Ce.addressStatus!=="active")throw new R("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return Ce}if(!we||typeof we!="object"||!("recovery"in we))throw new R("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Ai.parse(we.recovery)})}return{recoveryObserver(){l();let j={identity:i,observation:++o};return{async request(V){return Ai.parse(await Me(V,j))},async confirm(V,X){return qt.parse(await Me(X,j,V))}}},identify(j){if(!e)return;a=Pt(e,X=>({...X,identitySeq:on(X.identitySeq)})).identitySeq,n=j,i++,o++},reset(){if(e)try{Pt(e,j=>{let V=on(j.identitySeq);return{...j,identitySeq:V,detachSeq:V}})}finally{n=null,i++,o++}},start(){e&&Pe()},async sync(){return await Pe()},read:q,async recover(){let j=l(),V=i,X=a;return o++,await Pe(async()=>{p(V);let he=await q();return p(V),a=Pt(j,Ae=>{if(Ae.identitySeq!==X)throw new R("IDENTITY_CHANGED","A newer installation intent exists");return{...Ae,identitySeq:on(Math.max(Ae.identitySeq,he.identitySeq)),addressSeq:Math.max(Ae.addressSeq,he.addressSeq)}}).identitySeq,await ie()})},tokenObserver(){l();let j=++o,V=i;return async X=>{if(j!==o||V!==i)return null;let he=l(),be=n?await(t.session?.access()??n):null;if(!be)throw new R("NOT_IDENTIFIED","Identify before registering a Push token");if(await Pe(),p(V),j!==o)return null;let Ae=Pt(he,Ue=>({...Ue,addressSeq:on(Ue.addressSeq)})),Ve=_.updatePushAddress,Te=Ve.request.parse(await k("address",{...X,sequence:Ae.addressSeq,credentialDigest:await A(be)}));if(p(V),j!==o)return null;let ct=Ve.response.parse(await U(Ve.path,Te,be));return p(V),v(ct.installation)}}}}function Sd(e,t){return{messaging:{async preference(r){let n=_.readMessagingPreference;return n.response.parse(await e(n.path,n.request.parse({channel:r}))).preference},async setPreference(r){let n=_.setMessagingPreference;return n.response.parse(await e(n.path,n.request.parse(r))).preference}},push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){let r=_.readMessagingPreference;return r.response.parse(await e(r.path,{channel:"push"})).preference},async setPreference(r){let n=_.setMessagingPreference;return n.response.parse(await e(n.path,n.request.parse({...r,channel:"push"}))).preference}}}}function fe(e){return typeof e=="string"?e:String(e)}var fb=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function hb(e){return e.replace(fb,"$1\uFFFD")}function eo(e,t){if(typeof e!="object"||e==null){let r="";throw r+="The provided value is not an object",new TypeError(r)}return e}function Ed(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let r=t.call(e);if(!r||typeof r!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return r}}function _d(e){let t;if(Array.isArray(e)){let r=e.map(fe);if(r.length===2)return r}else if((t=Ed(e))!=null){let r=eo(t.next()),n=eo(t.next());if(!r.done&&!n.done)return[fe(r.value),fe(n.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var xd="0123456789ABCDEF",Ab=/(?:%[0-9A-Fa-f]{2})+/g;function St(e){return`%${xd[e>>4&15]}${xd[15&e]}`}function jd(e,t,r=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?r&&e===32?"+":t(e)?St(e):String.fromCharCode(e):e<=2047?St(192|e>>6)+St(128|63&e):e<=65535?St(224|e>>12)+St(128|e>>6&63)+St(128|63&e):St(240|e>>18)+St(128|e>>12&63)+St(128|e>>6&63)+St(128|63&e)}function to(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function ro(e,t=!1){let r=0;for(;r<e.length;r++){let n=e.charCodeAt(r);if(n===37||t&&n===43)break}return r===e.length?e:(t?e.replace(/\+/g," "):e).replace(Ab,n=>{try{return decodeURIComponent(n)}catch{return"\uFFFD".repeat(n.length/3)}})}function un(e){return e<=31||e>126}function gb(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return un(e)}}function uo(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return un(e)}}function bb(e){return uo(e)||e===39}function no(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return uo(e)}}function di(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return no(e)}}function Id(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(r){switch(r){case 36:case 37:case 38:case 43:case 44:return!0;default:return di(r)}})(e)}}function Td(e,t){return jd(e=e||0,t)}function _t(e,t,r=!1){let n=0;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o>=128||r&&o===32||t(o))break}if(n===e.length)return e;let i=e.slice(0,n);for(;n<e.length;n++){let o=e.charCodeAt(n),a=o;if(o>=55296&&o<=56319&&n+1<e.length){let c=e.charCodeAt(n+1);c>=56320&&c<=57343&&(a=(o-55296<<10)+c-56320+65536,n++)}i+=jd(a,t,r)}return i}function lo(e){let t=[],r=0,n=0;for(;n<=e.length;){if(n=e.indexOf("&",r),n<0&&(n=e.length),n!==r){let i=e.slice(r,n),o=i.indexOf("=");o<0&&(o=i.length),t.push([ro(i.slice(0,o),!0),ro(i.slice(o+1),!0)])}if(r=n+1,n===e.length)break}return t}function io(e){let t="";for(let r=0;r<e.length;r++){let n=_t(e[r][0],Id,!0),i=_t(e[r][1],Id,!0);t+=r!==0?`&${n}=${i}`:`${n}=${i}`}return t}var yb=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],Sb=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],_b=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],xb=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function Ib(e){for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(r>65535&&t++,r<=32||r===37||r===127||r>=55296&&r<=57343||r>=128&&r<=159||r>=64976&&r<=65007||!(65534&~r)||r===65533)return!0}return!1}var[vb,Pb,Cb,vd]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,r,n]){return[t,r.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(n),i=>i.charCodeAt(0))]});function wb(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function Rd(e,t){for(let r=0;r<e.length;r+=2)if(t>=e[r]&&t<=e[r+1])return!0;return!1}function sn(e,t){let[r,n,i]=e,o=t>>8;for(let l=0;l<r.length;l+=2)if(o>=r[l]&&o<=r[l+1])return!0;let a=n.indexOf(o);if(a<0)return!1;let c=255&t;return!!(i[32*a+(c>>3)]&1<<(7&c))}function Ob(e){let t=Array.from(e,r=>r.codePointAt(0));for(let r=0;r<t.length;r++){let n=t[r];if(n!==8204&&n!==8205||r>0&&Rd(xb,t[r-1]))continue;if(n===8205)return!1;let i=r-1;for(;i>=0&&sn(vd,t[i]);)i--;let o=r+1;for(;o<t.length&&sn(vd,t[o]);)o++;if(!(i>=0&&o<t.length&&sn(Pb,t[i])&&sn(Cb,t[o])))return!1}return!0}var Eb=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,jb=/\p{Script=Latin}/u;function Tb(e){return!Eb.test(e)||!jb.test(e)}var Mt=36,ci=1,ao=26,Rb=38,kb=700,Db=72,Nb=128,Mb=2147483647;function Pd(e){return String.fromCharCode(e+22+75*+(e<26))}function Ub(e,t,r){let n=0;for(e=r?Math.floor(e/kb):e>>1,e+=Math.floor(e/t);e>(Mt-ci)*ao>>1;n+=Mt)e=Math.floor(e/(Mt-ci));return Math.floor(n+(Mt-ci+1)*e/(e+Rb))}function qb(e){let t=Array.from(e,l=>l.codePointAt(0)),r="",n=0;for(let l=0;l<t.length;l++){let p=t[l];p<128&&(r+=String.fromCharCode(p),n++)}let i=n;i&&(r+="-");let o=Nb,a=0,c=Db;for(;n<t.length;){let l=Mb;for(let p=0;p<t.length;p++){let A=t[p];A>=o&&A<l&&(l=A)}a+=(l-o)*(n+1),o=l;for(let p=0;p<t.length;p++){let A=t[p];if(A<o&&a++,A===o){let v=a;for(let k=Mt;;k+=Mt){let U=k<=c?ci:k>=c+ao?ao:k-c;if(v<U)break;r+=Pd(U+(v-U)%(Mt-U)),v=Math.floor((v-U)/(Mt-U))}r+=Pd(v),c=Ub(a,n+1,n===i),a=0,n++}}a++,o++}return r}function Xa(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let r=0;for(let n=0;n<e.length;n++){let i=to(e.charCodeAt(n));if(i>=t||i<0)return-1;r=r*t+i}return r}function Cd(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function kd(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Dd(e){return e.length===2&&kd(e.codePointAt(0),e.codePointAt(1))}function wd(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function Ee(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Nd(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function oo(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(n){let i=[0,0,0,0,0,0,0,0],o=null,a=0,c=0,l=Array.from(n,p=>p.codePointAt(0));if(l[c]===58){if(l[c+1]!==58)return null;c+=2,a++,o=a}for(;c<l.length;){if(a===8)return null;if(l[c]===58){if(o!==null)return null;c++,a++,o=a;continue}let p=0,A=0,v=0;for(;v<4&&(p=to(l[c]))>=0;)A=(A<<4)+p,c++,v++;if(l[c]===46){if(v===0||a>6)return null;c-=v;let k=0;for(;l[c]!==void 0;){let U=0;if(k>0)if(l[c]===46&&k<4)c++;else return null;if(l[c]==null||l[c]<48||l[c]>57)return null;for(;l[c]>=48&&l[c]<=57;){if(U=10*U+to(l[c]),U>255)return null;c++}i[a]=256*i[a]+U,k++,k%2==0&&a++}if(k!==4)return null;break}else if(l[c]===58){if(l[++c]===void 0)return null}else if(l[c]!==void 0)return null;i[a]=A,a++}if(o!==null){let p=a-o;for(a=7;a!==0&&p>0;){let A=i[o+p-1];i[o+p-1]=i[a],i[a]=A,a--,p--}}else if(o===null&&a!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(n){return wd(n)?null:_t(n,un)})(e);{let r=(function(i){let o=!1,a=!1;for(let l=0;l<i.length;l++){let p=i.charCodeAt(l);if(p<=32||p===37||p===127)return null;if(p>=128){o=!0;break}p>=65&&p<=90&&(a=!0)}if(!o)return i!==""?a?i.toLowerCase():i:null;if((function(p){for(let A of p){let v=A.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(A)&&!Rd(yb,v)||sn(vb,v))return!0}return!1})(i))return null;let c=(i=(function(p){let A="";for(let v of p){let k=v.codePointAt(0);if(k!==8204&&k!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(v))continue;let U=wb(v,k);if(U){A+=U;continue}let ie=Sb.indexOf(k);A+=ie<0?v:_b[ie]}return A})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let l=0;l<c.length;l++){let p=c[l];if(p==="")continue;let A=/[^\0-\x7f]/.test(p);if(Ib(p)||A&&(/^\p{Mark}/u.test(p)||!Ob(p)||!Tb(p)||p.startsWith("xn--")))return null;A&&(c[l]=`xn--${qb(p)}`)}return(i=c.join("."))!==""?i:null})(e.indexOf("%")===-1?e:ro(e));return r===null||wd(r)?null:(function(i){let o=i.length,a=i.lastIndexOf(".",o-2)+1;if(i.charCodeAt(o-1)===46&&o--,o<=a)return!1;if(Xa(i.slice(a,o))>=0)return!0;for(;a<o;a++){let c=i.charCodeAt(a);if(c<48||c>57)return!1}return!0})(r)?(function(i){let o=i.split("."),a=o.length;if(o[a-1]||a--,a>4)return null;let c=0;for(let p=0;p<a-1;p++){let A=Xa(o[p]);if(A<0||A>255)return null;c+=A*(1<<8*(3-p))}let l=Xa(o[a-1]);return l<0||l>=256**(5-a)?null:(c+=l,c)})(r):r}}function so(e){return typeof e=="number"?(function(r){let i="";return i+=`${(r>>>24&255).toString(10)}.`,i+=`${(r>>>16&255).toString(10)}.`,i+=`${(r>>>8&255).toString(10)}.`,i+=(r&255).toString(10),i})(e):Array.isArray(e)?`[${(function(r){let n=(function(c){let l=-1,p=-1,A=1,v=0;for(let k=0;k<c.length;++k)c[k]!==0?(v>A&&(l=p,A=v),p=-1,v=0):(p===-1&&(p=k),++v);return v>A?p:l})(r),i="",o=!1;for(let a=0;a<=7;++a)if(!(o&&r[a]===0)){if(o&&(o=!1),n===a){i+=a===0?"::":":",o=!0;continue}i+=r[a].toString(16),a!==7&&(i+=":")}return i})(e)}]`:e}function Md(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(r){return/^[A-Za-z]:$/u.test(r)})(e.path[0]))&&e.path.pop()}function Ud(e){return e.username!==""||e.password!==""}function Ja(e){return e.host===null||e.host===""||e.scheme==="file"}var f=0,x="",te="",de=null,I,ui=!1,li=!1,or=!1,je;function it(e,t,r,n){t||(e=(function(a){let c=0,l=a.length;for(;c<l&&!(a.charCodeAt(c)>32);++c);for(;l>c&&!(a.charCodeAt(l-1)>32);--l);return a.substring(c,l)})(e)),e=(function(a){let c=0;for(;c<a.length;c++){let p=a.charCodeAt(c);if(p===9||p===10||p===13)break}if(c===a.length)return a;let l=a.slice(0,c);for(;c<a.length;c++){let p=a.charCodeAt(c);p!==9&&p!==10&&p!==13&&(l+=a[c])}return l})(e),f=0,x=e,te="",de=r||null,I=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},ui=!1,li=!1,or=!1,je=n||0;let i=Lb;switch(n){case 3:case 4:i=mi;break;case 5:i=po;break;case 6:i=sr;break;case 7:i=Ut;break;case 8:i=xt}return i(E(e,f))!==1?I:null}function M(e,t){return f+=f===e?ft(t):1,f<=x.length}function E(e,t){return t<e.length?e.codePointAt(t):void 0}function ft(e){return e!=null&&e>65535?2:1}function qd(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var Lb=e=>{let t=f;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let r=f+1;for(e=x.charCodeAt(r);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)r++,e=x.charCodeAt(r);return te=x.slice(f,r).toLowerCase(),f=r,Bb(r<x.length?e:void 0)}else return je?1:(--f,M(t,e)?Ld(E(x,f)):0)},Bb=e=>{let t=f;if(e===58){if(je){if(Ee(I.scheme)!==Ee(te))return 0;if((Ud(I)||I.port!==null)&&te==="file")return 0;if(I.scheme==="file"&&I.host==="")return 0}return I.scheme=te,je?(I.port===Nd(I.scheme)&&(I.port=null),0):(te="",I.scheme==="file"?M(t,e)?fo(E(x,f)):0:Ee(I.scheme)&&de!==null&&de.scheme===I.scheme?M(t,e)?Fb(E(x,f)):0:Ee(I.scheme)?M(t,e)?$b(E(x,f)):0:E(x,f+1)===47?(f++,M(t,e)?Vb(E(x,f)):0):(I.path=[""],I.opaquePath=!0,M(t,e)?Fd(E(x,f)):0))}else return je?1:(te="",f=-1,M(t,e)?Ld(E(x,f)):0)},Ld=e=>{let t=f;return de===null||de.opaquePath&&e!==35?1:de.opaquePath&&e===35?(I.scheme=de.scheme,I.path=de.path.slice(),I.opaquePath=de.opaquePath,I.query=de.query,I.fragment="",M(t,e)?xt(E(x,f)):0):de.scheme==="file"?(f--,M(t,e)?fo(E(x,f)):0):(f--,M(t,e)?mo(E(x,f)):0)},Fb=e=>{let t=f;return e===47&&E(x,f+1)===47?(++f,M(t,e)?fi(E(x,f)):0):(f--,M(t,e)?mo(E(x,f)):0)},Vb=e=>{let t=f;return e===47?M(t,e)?vr(E(x,f)):0:(f--,M(t,e)?ht(E(x,f)):0)},mo=e=>{let t=f;return I.scheme=de.scheme,e===47||Ee(I.scheme)&&e===92?M(t,e)?Od(E(x,f)):0:(I.username=de.username,I.password=de.password,I.host=de.host,I.port=de.port,I.path=de.path.slice(),I.query=de.query,e===63?(I.query="",M(t,e)?Ut(E(x,f)):0):e===35?(I.fragment="",M(t,e)?xt(E(x,f)):0):e!=null?(I.query=null,I.path.pop(),f--,M(t,e)?ht(E(x,f)):0):M(t,e)?mo(E(x,f)):0)},Od=e=>{let t=f;return Ee(I.scheme)&&(e===47||e===92)?M(t,e)?fi(E(x,f)):0:e===47?M(t,e)?vr(E(x,f)):0:(I.username=de.username,I.password=de.password,I.host=de.host,I.port=de.port,f--,M(t,e)?ht(E(x,f)):0)},$b=e=>{let t=f;return e===47&&E(x,f+1)===47?f++:f--,M(t,e)?fi(E(x,f)):0},fi=e=>{let t=f;return e!==47&&e!==92?(f--,M(t,e)?vr(E(x,f)):0):M(t,e)?fi(E(x,f)):0},vr=e=>{let t=f;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!Ee(I.scheme))){let r=f+ft(e);for(;r<x.length;){let n=E(x,r);if(n==null||n===64||n===35||n===47||n===63||n===92&&Ee(I.scheme))break;r+=ft(n)}return te+=x.slice(f,r),f=r-1,M(t,e)?vr(E(x,f)):0}if(e===64){ui&&(te=`%40${te}`),ui=!0;for(let r=0;r<te.length;r++){let n=te.codePointAt(r);if(n===58&&!li){li=!0;continue}let i=Td(n,di);li?I.password+=i:I.username+=i,n!=null&&n>65535&&r++}return te="",M(t,e)?vr(E(x,f)):0}else return e==null||e===35||e===47||e===63||e===92&&Ee(I.scheme)?ui&&te===""?1:(f-=te.length+1,te="",M(t,e)?mi(E(x,f)):0):(te+=qd(e),M(t,e)?vr(E(x,f)):0)},mi=e=>{let t=f;if(je&&I.scheme==="file")return f--,M(t,e)?ho(E(x,f)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!Ee(I.scheme))){let r=f+ft(e);for(e===91?or=!0:e===93&&(or=!1);r<x.length;){let n=E(x,r);if(n==null||!or&&n===58||n===35||n===47||n===63||n===92&&Ee(I.scheme))break;n===91?or=!0:n===93&&(or=!1),r+=ft(n)}return te+=x.slice(f,r),f=r-1,M(t,e)?mi(E(x,f)):0}else if(e===58&&!or){if(te===""||je===4)return 1;let r=oo(te,!Ee(I.scheme));return r===null?1:(I.host=so(r),te="",M(t,e)?po(E(x,f)):0)}else if(e==null||e===35||e===47||e===63||e===92&&Ee(I.scheme)){if(f--,Ee(I.scheme)&&te==="")return 1;if(je&&te===""&&(Ud(I)||I.port!==null))return 1;let r=oo(te,!Ee(I.scheme));return r===null?1:(I.host=so(r),te="",je?0:M(t,e)?sr(E(x,f)):0)}else return te+=qd(e),M(t,e)?mi(E(x,f)):0},po=e=>{let t=f;if(e!=null&&e>=48&&e<=57){let r=f+1;for(;r<x.length;){let n=x.charCodeAt(r);if(n<48||n>57)break;r++}return te+=x.slice(f,r),f=r-1,M(t,e)?po(E(x,f)):0}else if(je||e==null||e===35||e===47||e===63||e===92&&Ee(I.scheme)){if(te!==""){let r=parseInt(te,10);if(r>65535)return 1;if(I.port=r===Nd(I.scheme)?null:r,te="",je)return 0}return je?1:(f--,M(t,e)?sr(E(x,f)):0)}else return 1};function Bd(e,t){let r=e.length-t;if(r<2)return!1;if(kd(E(e,t),E(e,t+1))){if(r===2)return!0;{let n=E(e,t+2);return n===47||n===92||n===63||n===35}}else return!1}var fo=e=>{let t=f;return I.scheme="file",I.host="",e===47||e===92?M(t,e)?Gb(E(x,f)):0:de?.scheme==="file"?(I.host=de.host,I.path=de.path.slice(),I.opaquePath=de.opaquePath,I.query=de.query,e===63?(I.query="",M(t,e)?Ut(E(x,f)):0):e===35?(I.fragment="",M(t,e)?xt(E(x,f)):0):e!=null?(I.query=null,Bd(x,f)?I.path=[]:Md(I),f--,M(t,e)?ht(E(x,f)):0):M(t,e)?fo(E(x,f)):0):(f--,M(t,e)?ht(E(x,f)):0)},Gb=e=>{let t=f;return e===47||e===92?M(t,e)?ho(E(x,f)):0:(de!==null&&de.scheme==="file"&&(!Bd(x,f)&&(function(n){if(n.length===2){let i=n.codePointAt(0),o=n.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&o===58}else return!1})(de.path[0])&&I.path.push(de.path[0]),I.host=de.host),f--,M(t,e)?ht(E(x,f)):0)},ho=e=>{let t=f;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let r=f+ft(e);for(;r<x.length;){let n=E(x,r);if(n==null||n===47||n===92||n===63||n===35)break;r+=ft(n)}return te+=x.slice(f,r),f=r-1,M(t,e)?ho(E(x,f)):0}else if(e==null||e===47||e===92||e===63||e===35){if(f--,!je&&Dd(te))return M(t,e)?ht(E(x,f)):0;if(te==="")return I.host="",je?0:M(t,e)?sr(E(x,f)):0;{let r=oo(te,!Ee(I.scheme));return r===null?1:(r==="localhost"&&(r=""),I.host=so(r),te="",je?0:M(t,e)?sr(E(x,f)):0)}}return 1},sr=e=>{let t=f;return Ee(I.scheme)?(e!==92&&e!==47&&f--,M(t,e)?ht(E(x,f)):0):!je&&e===63?(I.query="",M(t,e)?Ut(E(x,f)):0):!je&&e===35?(I.fragment="",M(t,e)?xt(E(x,f)):0):e!=null?(e!==47&&f--,M(t,e)?ht(E(x,f)):0):(je&&I.host===null&&I.path.push(""),M(t,e)?sr(E(x,f)):0)},ht=e=>{let t=f;if(e!=null&&e!==47&&(!Ee(I.scheme)||e!==92)&&(je||e!==63&&e!==35)){let r=f+ft(e);for(;r<x.length;){let n=E(x,r);if(n==null||n===47||Ee(I.scheme)&&n===92||!je&&(n===63||n===35))break;r+=ft(n)}te+=_t(x.slice(f,r),no),f=r,e=E(x,r)}if(e==null||e===47||Ee(I.scheme)&&e===92||!je&&(e===63||e===35)){let r=Ee(I.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(te)?(Md(I),e!==47&&!r&&I.path.push("")):Cd(te)&&e!==47&&!r?I.path.push(""):Cd(te)||(I.scheme==="file"&&I.path.length===0&&Dd(te)&&(te=`${te[0]}:`),I.path.push(te)),te="",e===63?(I.query="",M(t,e)?Ut(E(x,f)):0):e===35?(I.fragment="",M(t,e)?xt(E(x,f)):0):M(t,e)?ht(E(x,f)):0}else return te+=Td(e,no),M(t,e)?ht(E(x,f)):0},Fd=e=>{let t=f;if(e===63)return I.query="",M(t,e)?Ut(E(x,f)):0;if(e===35)return I.fragment="",M(t,e)?xt(E(x,f)):0;if(e!=null){let r=f+ft(e);for(;r<x.length;){let i=E(x,r);if(i===63||i===35)break;r+=ft(i)}let n=x.slice(f,r);if(r<x.length&&n.charCodeAt(n.length-1)===32?I.path[0]+=_t(n.slice(0,-1),un)+"%20":I.path[0]+=_t(n,un),f=r,(e=E(x,r))===63)return I.query="",M(t,e)?Ut(E(x,f)):0;if(e===35)return I.fragment="",M(t,e)?xt(E(x,f)):0}return M(t,e)?Fd(E(x,f)):0},Ut=e=>{let t=f,r=f;if(e!=null){if(je)r=x.length;else{let i=x.indexOf("#",f);r=i===-1?x.length:i}let n=Ee(I.scheme)?bb:uo;I.query+=_t(x.slice(f,r),n)}return f=r,E(x,r)===35&&!je?(I.fragment="",M(t,e)?xt(E(x,f)):0):M(t,e)?Ut(E(x,f)):0},xt=e=>{let t=f;return e!=null&&(I.fragment+=_t(x.slice(f),gb),f=x.length),M(t,e)?xt(E(x,f)):0};function co(e){if(e.opaquePath)return e.path[0];{let t="";for(let r of e.path)t+=`/${r}`;return t}}function Vd(e){switch(e.scheme){case"blob":{let t=it(co(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Vd(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(r){let n=`${r.scheme}://`;return n+=r.host,r.port!==null&&(n+=`:${r.port}`),n})(e);default:return"null"}}var pe=Symbol("URLImpl"),ln=class e{constructor(t,r){if(t===void 0&&r===void 0)throw new TypeError('The "url" argument must be specified.');t=fe(t),r!=null&&(r=fe(r));let n=null;if(r!=null&&(n=it(r,null,null,0),n==null))throw new TypeError(`Invalid base URL: ${r}`);let i=it(t,null,n,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[pe]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,r){t=fe(t),r!==void 0&&(r=fe(r));try{return new e(t,r)}catch{return null}}static canParse(t,r){t=fe(t),r!==void 0&&(r=fe(r));let n=null;return r!=null&&(n=it(r,null,null,0),n==null)?!1:it(t,null,n,0)!=null}get href(){return(function(r){let n=`${r.scheme}:`;return r.host!==null&&(n+="//",(r.username!==""||r.password!=="")&&(n+=r.username,r.password!==""&&(n+=`:${r.password}`),n+="@"),n+=r.host,r.port!==null&&(n+=`:${r.port}`)),r.host===null&&!r.opaquePath&&r.path.length>1&&r.path[0]===""&&(n+="/."),n+=co(r),r.query!==null&&(n+=`?${r.query}`),r.fragment!==null&&(n+=`#${r.fragment}`),n})(this[pe].url)}set href(t){let r=it(t=fe(t),null,null,0);if(r==null)throw new TypeError(`Invalid URL: ${t}`);this[pe].url=r,this[pe].query&&za(this[pe].query,r.query)}get origin(){return Vd(this[pe].url)}get protocol(){return`${this[pe].url.scheme}:`}set protocol(t){it(`${t=fe(t)}:`,this[pe].url,null,2)}get username(){return this[pe].url.username}set username(t){t=fe(t),Ja(this[pe].url)||(function(n,i){n.username=_t(i,di)})(this[pe].url,t)}get password(){return this[pe].url.password}set password(t){t=fe(t),Ja(this[pe].url)||(function(n,i){n.password=_t(i,di)})(this[pe].url,t)}get host(){let{url:t}=this[pe];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=fe(t),this[pe].url.opaquePath||it(t,this[pe].url,null,3)}get hostname(){let{url:t}=this[pe];return t.host!=null?t.host:""}set hostname(t){t=fe(t),this[pe].url.opaquePath||it(t,this[pe].url,null,4)}get port(){let{url:t}=this[pe];return t.port!=null?`${t.port}`:""}set port(t){t=fe(t);let{url:r}=this[pe];Ja(r)||(t?it(t,r,null,5):r.port=null)}get pathname(){return co(this[pe].url)}set pathname(t){t=fe(t);let{url:r}=this[pe];r.opaquePath||(r.path=[],it(t,r,null,6))}get search(){let{url:t}=this[pe];return t.query?`?${t.query}`:""}set search(t){t=fe(t);let{url:r,query:n}=this[pe];if(!t)r.query=null,n&&za(n,null);else{let i=t[0]==="?"?t.substring(1):t;r.query="",it(i,r,null,7),n&&za(n,r.query)}}get searchParams(){let t=this[pe],r=t.query;return r==null&&(r=t.query=(function(i,o){let a=new pi;return a[Ie].url=i,a[Ie].serialized=o==null,o&&(a[Ie].list=lo(o)),a})(this,t.url.query)),r}get hash(){let{url:t}=this[pe];return t.fragment?`#${t.fragment}`:""}set hash(t){t=fe(t);let{url:r}=this[pe];if(!t)r.fragment=null;else{let n=t[0]==="#"?t.substring(1):t;r.fragment="",it(n,r,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(ln.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var Ie=Symbol("URLSearchParamsImpl"),Hb=Symbol.dispose||Symbol.for("dispose");function za(e,t){t?e[Ie].list=lo(t):e[Ie].list.length=0,e[Ie].serialized=t==null}function si(e){if(e.url){let t=io(e.list);(function(n,i){n[pe].url.query=i})(e.url,t||null),e.serialized=!0}}var Kb=typeof Iterator<"u"?Iterator:Object,cn=class extends Kb{constructor(t,r){super(),this[Ie]={ptr:t,map:r,index:0}}next(){let t=this[Ie];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[Hb](){}},pi=class{constructor(t){let r=this[Ie]={list:[],url:null,serialized:!0},n;if(Array.isArray(t))for(let i=0;i<t.length;i++)r.list.push(_d(t[i]));else if((n=Ed(t))!=null){let i;for(;!(i=eo(n.next())).done;)r.list.push(_d(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let o=0;o<i.length;o++){let a=i[o],c=hb(a),l=fe(t[a]),p=r.list.find(A=>A[0]===c);p?p[1]=l:r.list.push([c,l])}}else if(t!==void 0){let i=fe(t);i=i[0]==="?"?i.substring(1):i,r.list=lo(i)}}get size(){return this[Ie].list.length}append(t,r){t=fe(t),r=fe(r),this[Ie].list.push([t,r]);let n=this[Ie];n.url&&n.serialized?(function(o,a){let c=o[pe].url;c.query=c.query?`${c.query}&${a}`:a})(n.url,io([[t,r]])):si(n)}delete(t,r){t=fe(t),r=r!=null?fe(r):void 0;let{list:n}=this[Ie],i=0;for(;i<n.length;)n[i][0]===t&&(r==null||n[i][1]===r)?n.splice(i,1):i++;si(this[Ie])}get(t){t=fe(t);let{list:r}=this[Ie];for(let n=0;n<r.length;n++)if(r[n][0]===t)return r[n][1];return null}getAll(t){t=fe(t);let r=[],{list:n}=this[Ie];for(let i=0;i<n.length;i++)n[i][0]===t&&r.push(n[i][1]);return r}has(t,r){t=fe(t),r=r!=null?fe(r):void 0;let{list:n}=this[Ie];for(let i=0;i<n.length;i++)if(n[i][0]===t&&(r==null||n[i][1]===r))return!0;return!1}set(t,r){t=fe(t),r=fe(r);let{list:n}=this[Ie],i=!1,o=!1,a=0;for(;a<n.length;)n[a][0]===t?i?(n.splice(a,1),o=!0):(i=!0,n[a][1]!==r&&(n[a][1]=r,o=!0),a++):a++;i||(n.push([t,r]),o=!0),o&&si(this[Ie])}sort(){this[Ie].list.sort((t,r)=>t[0]<r[0]?-1:t[0]>r[0]?1:0),si(this[Ie])}forEach(t,r){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:n}=this[Ie];for(let i=0;i<n.length;i++)t.call(r,n[i][1],n[i][0],this)}entries(){return new cn(this[Ie],t=>t)}keys(){return new cn(this[Ie],t=>t[0])}values(){return new cn(this[Ie],t=>t[1])}toString(){return io(this[Ie].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(pi.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var $d={name:"@tinkerlandai/indiana-sdk",version:"0.9.1",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var Gd="https://api.tinker.cash";function Hd(e){let t,r,n=0,i,o=new Map,a=()=>{for(let v of o.keys())v()};function c(v,k){let U=++n;i=void 0,t=void 0,r=void 0;for(let ie of o.values())ie?.();U===n&&(t=v,r=k,a())}let l=()=>c();function p(v,k=!1){let U=pr.safeParse(v);if(!U.success||k&&Date.parse(U.data.expiresAt)<=Date.now()||Date.parse(U.data.refreshExpiresAt)<=Date.now()||Date.parse(U.data.refreshExpiresAt)<Date.parse(U.data.expiresAt))throw new R("INVALID_RESPONSE","Invalid customer session credentials");return U.data}async function A(){if(i)return i;let v=t,k=n;if(!v||Date.parse(v.refreshExpiresAt)<=Date.now())throw v&&l(),new R("UNAUTHENTICATED","Customer authentication is required",401);let U=(async()=>{try{let ie=await e(v.refreshToken);if(k!==n)throw new R("IDENTITY_CHANGED","Customer identity changed during refresh");let q=p(ie,!0);if(q.customerId!==v.customerId||q.sessionId!==v.sessionId)throw new R("SCOPE_MISMATCH","Refresh changed the customer session");return t=q,r=q.accessToken,{...q}}catch(ie){throw k!==n?new R("IDENTITY_CHANGED","Customer identity changed during refresh"):(ie instanceof R&&ie.status===401&&l(),ie)}})();i=U;try{return await U}finally{i===U&&(i=void 0)}}return{identify(v){let k=typeof v=="string"?void 0:p(v),U=typeof v=="string"?v:k.accessToken;if(!U.trim()||/\s/.test(U)||U.length>4096)throw new R("INVALID_TOKEN","A server-issued token is required");c(k,U)},reset:l,subscribeIdentity(v,k){return o.set(v,k),()=>{o.delete(v)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return A().then(()=>{if(!r)throw new R("NOT_IDENTIFIED","Customer authentication is required");return r});if(!r)throw new R("NOT_IDENTIFIED","Identify a customer session before making a request");return r},peek:()=>r,snapshot:()=>t&&{...t},refresh:A}}var Kd=Symbol("IndianaNoContent");function Wd(e,t,r=URL){let n=e.configuration?.scope,i=e.scope??(n&&{projectId:n.projectId,environment:n.environment}),o=i?Xe.parse(i):void 0;if(o&&n&&(o.projectId!==n.projectId||o.environment!==n.environment))throw new R("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=new r(e.baseUrl??Gd);if(a.username||a.password||a.search||a.hash)throw new R("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))throw new R("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let c=e.fetch??globalThis.fetch.bind(globalThis),l=e.timeoutMs??1e4;if(!Number.isFinite(l)||l<1||l>12e4)throw new R("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,A=0,v=null,k=new Set,U=e.session??Hd(async j=>{let V=await Me("customer-sessions/refresh",{},"POST",{},j);if(!V||typeof V!="object")throw new R("INVALID_RESPONSE","Invalid refresh response");let{requestId:X,scope:he,...be}=V;return be});function ie(){A+=1,p=null,v=null;for(let j of k)j.abort();k.clear()}let q=U.subscribeIdentity(ie);function Pe(){U.reset()}async function Me(j,V={},X="POST",he={},be){let Ae=he.installationDetach===!0;if(Ae&&(j!=="push/installations/detach"||X!=="POST"))throw new R("INVALID_REQUEST","Installation authority only detaches this installation");if(!be&&!p&&!Ae)throw new R("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let Ve=A,Te=new AbortController;Ae||k.add(Te);let ct=()=>!Ae&&Ve!==A?new R("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new R("TIMEOUT","Indiana request timed out"),Ue,Pr=new Promise((Ce,ze)=>{Ue=()=>ze(ct()),Te.signal.addEventListener("abort",Ue,{once:!0})}),we=setTimeout(()=>Te.abort(),l),at=async()=>{let Ce=await c(`${a.href.replace(/\/$/,"")}/api/v1/${j}`,{method:X,headers:{"Content-Type":"application/json",...Ae?{}:{Authorization:`Bearer ${be??p}`},[yi]:Si.current,[To]:$d.version,...o?{"X-Indiana-Project":o.projectId,"X-Indiana-Environment":o.environment}:{}},body:X==="POST"?JSON.stringify(V):void 0,signal:Te.signal,credentials:"omit",cache:"no-store",redirect:"error",...he.keepalive?{keepalive:!0}:{}});if(Te.signal.aborted)throw ct();let ze;try{ze=Ce.status===204?Kd:await Ce.json()}catch{throw Te.signal.aborted?ct():new R(Ce.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Ce.status,Ce.headers.get("X-Request-Id")??void 0)}if(Te.signal.aborted)throw ct();if(!Ae&&Ve!==A)throw new R("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Ce.ok){let qe=bi.safeParse(ze),Ct=qe.success&&(!Lt.safeParse(qe.data.error.code).success||Eo(qe.data.error.code,Ce.status)),go=Ct?qe.data.error.code:"HTTP_ERROR",bo=An(go,Ce.status,{retryAfter:Ce.headers.get("Retry-After"),recovery:Ct?qe.data.error.recovery:void 0,reason:Ct?qe.data.error.reason:void 0});throw new R(go,Ct?qe.data.error.message:"Indiana request failed",Ce.status,Ce.headers.get("X-Request-Id")??(qe.success?qe.data.requestId:void 0),{...bo,...qe.success&&qe.data.error.retryable===!1?{retryable:!1}:{},...bo.retryAfterSeconds===void 0&&qe.success&&qe.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:qe.data.error.retryAfterSeconds}:{}})}if(Ce.headers.get(yi)!==Si.current)throw new R("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(o&&ze!==Kd){let qe=ze&&typeof ze=="object"&&"scope"in ze?ze:ze&&typeof ze=="object"&&"configuration"in ze?ze.configuration:null;if(!qe||typeof qe!="object"||!("scope"in qe))throw new R("INVALID_RESPONSE","Response is missing its App/environment scope");let Ct=Xe.safeParse(qe.scope);if(!Ct.success||Ct.data.projectId!==o.projectId||Ct.data.environment!==o.environment)throw new R("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let dn=Ce.headers.get("X-Indiana-Telemetry-Subject");if(dn){if(!/^[a-f0-9]{64}$/.test(dn))throw new R("INVALID_RESPONSE","Invalid telemetry identity");v!==dn&&(v=dn,t?.(v))}return ze};try{return await Promise.race([at(),Pr])}catch(Ce){throw!Ae&&Ve!==A?new R("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Ce instanceof R?Ce:new R(Te.signal.aborted?"TIMEOUT":"NETWORK_ERROR",Te.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(we),Te.signal.removeEventListener("abort",Ue),k.delete(Te)}}return{session:U,requestWithCredential(j,V,X){return Me(j,V,"POST",{},X)},subjectKey:()=>v,identify(j){if(o&&typeof j=="object"&&"scope"in j){let V=Xe.safeParse(j.scope);if(!V.success||V.data.projectId!==o.projectId||V.data.environment!==o.environment)throw new R("SCOPE_MISMATCH","Customer session belongs to another App/environment")}U.identify(j),p=U.peek()??null},reset:Pe,dispose(){q(),ie()},request(j,V={},X="POST",he={}){if(he.installationDetach)return Me(j,V,X,he);let be=A;try{let Ae=U.access(),Ve=Te=>{if(be!==A)throw new R("IDENTITY_CHANGED","Customer identity changed before dispatch");return Me(j,V,X,he,Te)};return typeof Ae=="string"?Ve(Ae):Ae.then(Ve)}catch(Ae){return Promise.reject(Ae)}}}}var Qd=require("zod");function Zd(e,t,r,n){try{return e.parse(t)}catch(i){throw n&&i instanceof Qd.ZodError?new R(r,n):i}}async function Ao(e,t,r,n={},i){let o=typeof n=="function"?{}:n,a=Zd(t.request,r,"INVALID_REQUEST",o.request),c=await e(t.path,a,t.method,i),l=typeof n=="function"?n:n.parseResponse;return l?l(t.response,c):Zd(t.response,c,"INVALID_RESPONSE",o.response)}var Zb=_.trackUsage.request.shape.command,Qb=_.trackUsage.response,Yb=_.checkEntitlement.request.omit({customerId:!0}).strict();function Yd(e){let t=Xe.parse(e.scope),r=Wd({...e,scope:t},void 0,ln),n=yd(e.push,r,t),i=0,o=!1;return r.session.subscribeIdentity(()=>{i++,o=!!r.session.peek()}),{...Sd(r.request,n),session:r.session,identify(a){let c=typeof a=="string"?a:a.accessToken;if(!qn.test(c))throw new R("INVALID_TOKEN","A Customer Token is required");n.identify(c),r.identify(a),n.start()},reset(){try{n.reset()}finally{r.reset(),n.start()}},async readHoldings(){let a=_.readHoldings;return Ao(r.request,a,{})},async checkEntitlement(a){let c=_.checkEntitlement;return Ao(r.request,{...c,request:Yb},a)},async trackUsage(a){if(!o)throw new R("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new R("INVALID_REQUEST","Configure your authenticated backend usageReporter");let c=Zb.parse(a),l=i,p;try{p=await e.usageReporter(c)}catch(v){throw l!==i?new R("IDENTITY_CHANGED","Customer identity changed during usage reporting"):v}if(l!==i)throw new R("IDENTITY_CHANGED","Customer identity changed during usage reporting");let A=Qb.parse(p);if(A.scope.projectId!==t.projectId||A.scope.environment!==t.environment)throw new R("INVALID_RESPONSE","Usage response scope differs");return A}}}
|