@tinkerlandai/longplay-sdk 0.10.17 → 0.10.18
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/CHANGELOG.md +4 -0
- package/dist/chunk-4ZUMMPHV.js +1 -0
- package/dist/{chunk-3DGJ2X3U.js → chunk-6HWNW6FJ.js} +1 -1
- package/dist/{chunk-T5YZS64H.js → chunk-E4LUW6KP.js} +1 -1
- package/dist/{chunk-7LIABANC.js → chunk-JVQVQHV2.js} +1 -1
- package/dist/{chunk-DM2WGIRX.js → chunk-KYXX676W.js} +1 -1
- package/dist/{chunk-FVX3AVDI.js → chunk-LHBBSD77.js} +1 -1
- package/dist/chunk-N4HZ55YU.js +1 -0
- package/dist/{chunk-MILFPPP4.js → chunk-OMHZBCS3.js} +1 -1
- package/dist/{chunk-F2CMJYA5.js → chunk-P6HCD5OQ.js} +1 -1
- package/dist/{chunk-OUBGSIYR.js → chunk-VVW2J2GL.js} +1 -1
- package/dist/{content-PWGLNXLT.js → content-DLYNJIEB.js} +1 -1
- package/dist/funnel-runtime-host-FVOUCR35.js +1 -0
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-HFX3OZFM.js → paywall-6Q3VLXXL.js} +1 -1
- package/dist/react-native.js +1 -1
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-C4EMRGWJ.js +0 -1
- package/dist/chunk-FBLAWSUN.js +0 -1
- package/dist/funnel-runtime-host-DJ7UXHAW.js +0 -1
|
@@ -3,4 +3,4 @@ ${t}
|
|
|
3
3
|
POST
|
|
4
4
|
${Ka}
|
|
5
5
|
${n}
|
|
6
|
-
${e}`)}async function ts(e){let t=Oi.parse(e);return crypto.subtle.importKey("raw",Ya(t.signingSecret),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function th(e,t,n,r=Date.now()){let o=String(Math.floor(r/1e3)),a=new Uint8Array(await crypto.subtle.sign("HMAC",await ts(t),es(e,n,o))),l=btoa(String.fromCharCode(...a)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");return{[Xa]:t.keyId,[Qa]:`t=${o},v1=${l}`}}async function nh(e,t,n,r,o=Date.now()){try{if(t.get(Xa)!==n.keyId)return!1;let a=/^t=([0-9]{1,12}),v1=([A-Za-z0-9_-]{43})$/.exec(t.get(Qa)??"");return!a||Math.abs(o/1e3-Number(a[1]))>300?!1:await crypto.subtle.verify("HMAC",await ts(n),Ya(a[2]),es(e,r,a[1]))}catch{return!1}}var ns={"zh-Hans":{merchandise:"\u51CF {discount}\uFF08\u5355\u6B21\u4F7F\u7528\uFF09",once:"\u9996\u671F\u51CF {discount}",repeating:"\u524D {months} \u4E2A\u6708\u6BCF\u6708\u51CF {discount}",forever:"\u6BCF\u671F\u51CF {discount}"},"zh-Hant":{merchandise:"\u6E1B {discount}\uFF08\u55AE\u6B21\u4F7F\u7528\uFF09",once:"\u9996\u671F\u6E1B {discount}",repeating:"\u524D {months} \u500B\u6708\u6BCF\u6708\u6E1B {discount}",forever:"\u6BCF\u671F\u6E1B {discount}"},en:{merchandise:"{discount} off \xB7 one use",once:"{discount} off your first payment",repeating:"{discount} off each month for the first {months} months",repeatingOne:"{discount} off the first month",forever:"{discount} off every payment"},ja:{merchandise:"{discount} \u5272\u5F15\uFF081\u56DE\u306E\u307F\uFF09",once:"\u521D\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15",repeating:"\u6700\u521D\u306E {months} \u304B\u6708\u9593\u3001\u6BCE\u6708 {discount} \u5272\u5F15",forever:"\u6BCE\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15"},ko:{merchandise:"{discount} \uD560\uC778 \xB7 1\uD68C \uC0AC\uC6A9",once:"\uCCAB \uACB0\uC81C {discount} \uD560\uC778",repeating:"\uCCAB {months}\uAC1C\uC6D4 \uB3D9\uC548 \uB9E4\uC6D4 {discount} \uD560\uC778",forever:"\uB9E4 \uACB0\uC81C {discount} \uD560\uC778"},es:{merchandise:"{discount} de descuento \xB7 un uso",once:"{discount} de descuento en el primer pago",repeating:"{discount} de descuento cada mes durante los primeros {months} meses",forever:"{discount} de descuento en cada pago",repeatingOne:"{discount} de descuento durante el primer mes"},fr:{merchandise:"{discount} de r\xE9duction \xB7 une utilisation",once:"{discount} de r\xE9duction sur le premier paiement",repeating:"{discount} de r\xE9duction par mois pendant les {months} premiers mois",forever:"{discount} de r\xE9duction sur chaque paiement",repeatingOne:"{discount} de r\xE9duction pendant le premier mois"},de:{merchandise:"{discount} Rabatt \xB7 einmalig",once:"{discount} Rabatt auf die erste Zahlung",repeating:"{discount} Rabatt pro Monat f\xFCr die ersten {months} Monate",forever:"{discount} Rabatt auf jede Zahlung",repeatingOne:"{discount} Rabatt im ersten Monat"},pt:{merchandise:"{discount} de desconto \xB7 um uso",once:"{discount} de desconto no primeiro pagamento",repeating:"{discount} de desconto por m\xEAs nos primeiros {months} meses",forever:"{discount} de desconto em cada pagamento",repeatingOne:"{discount} de desconto no primeiro m\xEAs"},it:{merchandise:"{discount} di sconto \xB7 un utilizzo",once:"{discount} di sconto sul primo pagamento",repeating:"{discount} di sconto al mese per i primi {months} mesi",forever:"{discount} di sconto su ogni pagamento",repeatingOne:"{discount} di sconto per il primo mese"},ru:{merchandise:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \xB7 \u043E\u0434\u043D\u043E \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435",once:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043F\u0435\u0440\u0432\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436",repeating:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043A\u0430\u0436\u0434\u044B\u0439 \u043C\u0435\u0441\u044F\u0446 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",repeatingOne:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u0432 \u043F\u0435\u0440\u0432\u044B\u0439 \u043C\u0435\u0441\u044F\u0446",forever:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043A\u0430\u0436\u0434\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436"},vi:{merchandise:"Gi\u1EA3m {discount} \xB7 d\xF9ng m\u1ED9t l\u1EA7n",once:"Gi\u1EA3m {discount} cho l\u1EA7n thanh to\xE1n \u0111\u1EA7u ti\xEAn",repeating:"Gi\u1EA3m {discount} m\u1ED7i th\xE1ng trong {months} th\xE1ng \u0111\u1EA7u",forever:"Gi\u1EA3m {discount} cho m\u1ED7i l\u1EA7n thanh to\xE1n"},th:{merchandise:"\u0E25\u0E14 {discount} \xB7 \u0E43\u0E0A\u0E49\u0E44\u0E14\u0E49\u0E04\u0E23\u0E31\u0E49\u0E07\u0E40\u0E14\u0E35\u0E22\u0E27",once:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E04\u0E23\u0E31\u0E49\u0E07\u0E41\u0E23\u0E01",repeating:"\u0E25\u0E14 {discount} \u0E15\u0E48\u0E2D\u0E40\u0E14\u0E37\u0E2D\u0E19\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",forever:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E17\u0E38\u0E01\u0E04\u0E23\u0E31\u0E49\u0E07"},id:{merchandise:"Diskon {discount} \xB7 sekali pakai",once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{merchandise:"\u062E\u0635\u0645 {discount} \xB7 \u0627\u0633\u062A\u062E\u062F\u0627\u0645 \u0648\u0627\u062D\u062F",once:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u062F\u0641\u0639\u0629 \u0627\u0644\u0623\u0648\u0644\u0649",repeating:"\u062E\u0635\u0645 {discount} \u0634\u0647\u0631\u064A\u064B\u0627 \u0644\u0645\u062F\u0629 {period}",forever:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0643\u0644 \u062F\u0641\u0639\u0629"}};function ji(e){let t=ya(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(a=>["TW","HK","MO"].includes(a))?"zh-Hant":"zh-Hans":n[0]??"en",o=ns[r];return o?{locale:t,copy:o}:{locale:"en",copy:ns.en}}function Ol(e,t,n="zh-CN"){let r=li(t);return ma(e,t,ji(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function jl(e,t="zh-CN"){let n=ji(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(e.percentOff/100):Ol(e.amountOffCents,e.currency,n)}var rs={zh:"\u524D {months} \u4E2A\u6708\u5185\u5F00\u51FA\u7684\u8D26\u5355\u51CF {discount}","zh-Hant":"\u524D {months} \u500B\u6708\u5167\u958B\u51FA\u7684\u5E33\u55AE\u6E1B {discount}",en:"{discount} off invoices issued within the first {months} months",ja:"\u6700\u521D\u306E {months} \u304B\u6708\u4EE5\u5185\u306E\u8ACB\u6C42\u304C {discount} \u5272\u5F15",ko:"\uCCAB {months}\uAC1C\uC6D4 \uB0B4 \uCCAD\uAD6C\uC11C {discount} \uD560\uC778",es:"{discount} de descuento en facturas emitidas durante los primeros {months} meses",fr:"{discount} de r\xE9duction sur les factures \xE9mises pendant les {months} premiers mois",de:"{discount} Rabatt auf Rechnungen innerhalb der ersten {months} Monate",pt:"{discount} de desconto nas faturas emitidas nos primeiros {months} meses",it:"{discount} di sconto sulle fatture emesse nei primi {months} mesi",ru:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u0441\u0447\u0435\u0442\u0430 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",vi:"Gi\u1EA3m {discount} cho h\xF3a \u0111\u01A1n trong {months} th\xE1ng \u0111\u1EA7u",th:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E43\u0E1A\u0E41\u0E08\u0E49\u0E07\u0E2B\u0E19\u0E35\u0E49\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",id:"Diskon {discount} untuk tagihan dalam {months} bulan pertama",ar:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u0641\u0648\u0627\u062A\u064A\u0631 \u0627\u0644\u0635\u0627\u062F\u0631\u0629 \u062E\u0644\u0627\u0644 \u0623\u0648\u0644 {period}"};function ah(e,t="zh-CN",n="month"){let r=ji(t),o=jl(e.discount,r.locale);if(e.appliesTo?.type==="merchandise")return r.copy.merchandise.replace("{discount}",o);let a=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",l=r.locale.split("-")[0]??"en",p=l==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":l,d=e.duration.type==="repeating"&&n!=="month"?rs[p]??rs.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],v=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return d.replace("{discount}",o).replace("{months}",a).replace("{period}",v)}import{z as W}from"zod";import{z as De}from"zod";var we=De.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),Ai=De.strictObject({type:De.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:De.boolean(),enum:De.array(De.string().max(255)).min(1).max(100).optional()}),nn=Ai.extend({type:De.enum([...Ai.shape.type.options,"array"]),items:Ai.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),rn=nn.safeExtend({source:De.discriminatedUnion("type",[De.strictObject({type:De.literal("input")}),De.strictObject({type:De.literal("node")}),De.strictObject({type:De.enum(["parameter","attribute"]),key:we})])}),Al=De.record(we,rn),xr=De.record(we,we).refine(e=>Object.keys(e).length<=20);function Xe(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>Xe(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&De.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function wi(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&wi(e.items,t.items)}function En(e,t){let n={};for(let[r,o]of Object.entries(e)){let a=o.source,l=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,p=a.type==="parameter"||a.type==="attribute"?a.key:r,d=Object.hasOwn(l,p),v=l[p];if(a.type==="attribute"&&p.includes(".")&&(!d||p.startsWith("merchandise."))){v=l,d=!0;for(let h of p.split(".")){if(!v||typeof v!="object"||!Object.hasOwn(v,h)||Array.isArray(v)&&(!/^(0|[1-9]\d*)$/.test(h)||Number(h)>=v.length)){d=!1;break}v=v[h]}}if(!(!d||v===void 0)){if(!Xe(o,v))throw new Error(`Invalid variable value: ${r}`);n[r]=v}}return n}function Dt(e,t){let n={};for(let[r,o]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,o))throw new Error("Node outputs cannot overwrite one another");n[o]=t[r]}return n}function _i(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[o,a]of Object.entries(n))if(!r.has(o)||e[o]?.source.type!=="node"||!Xe(e[o],a))throw new Error(`Invalid node variable write: ${o}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as zt}from"zod";var ot=zt.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),lt=zt.discriminatedUnion("source",[zt.strictObject({source:zt.literal("literal"),value:te}),zt.strictObject({source:zt.literal("variable"),key:zt.string().min(1).max(255),path:ot.optional()})]);function is(e,t){if(!t)return e;for(let n of ot.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Pi(e,t){if(e.source==="literal")return structuredClone(e.value);let n=En(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(te.parse(is(n[e.key],e.path)))}function Ci(e,t){let n=[...t].sort((o,a)=>a.length-o.length).find(o=>e===o||e.startsWith(o+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!ot.safeParse(r).success?null:{key:n,path:r}}function ki(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return ht(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Ea))]}function Sr(e){return ki(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function Ze(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let o=0;o<t.length;o++){let a=t.charAt(o);if(r)a==="\\"?o++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let l=o;for(;o+1<t.length&&/[0-9.eE+-]/.test(t.charAt(o+1));)o++;let p=t.slice(l,o+1);if(!/[eE]/.test(p))continue;let[d="",v]=p.split(/[eE]/),h=d.replace(/^-/,""),T=h.replace(".","").length,$=(h.includes(".")?h.indexOf("."):T)+Number(v),C=$<=0?2-$+T:$>=T?$:T+1;n+=C+(d.startsWith("-")?1:0)-p.length}}return n}var Ot=W.enum(["page","popup","banner"]),wl=3e5,os=W.strictObject({type:W.enum(["string","number","boolean","strings","json"]),nullable:W.boolean()}),_l=W.strictObject({inputs:W.record(Cn,os.extend({required:W.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:W.record(Cn,os).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Pl=W.strictObject({kind:Ot,schemaVersion:W.literal(1),name:W.string().trim().min(1).max(80),screen:Le,contract:_l}),vr=Pl.superRefine((e,t)=>{let n=(o,a)=>t.addIssue({code:"custom",message:o,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(o=>o.type!=="event"&&o.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(o=>o.type==="event").map(o=>o.id));(Object.keys(e.contract.outputs).some(o=>!r.has(o))||[...r].some(o=>!Object.hasOwn(e.contract.outputs,o)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),Ze(e)>wl&&n("Content document exceeds its byte budget",[])});function Cl(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var kl=vr.superRefine((e,t)=>{for(let n of Sr(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],o=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!Cl(o,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}It(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),as=W.strictObject({id:W.uuid(),kind:Ot,projectId:W.uuid(),environmentId:W.uuid(),name:W.string(),revision:W.number().int().nonnegative(),status:W.enum(["draft","published","archived"]),publishedVersionId:W.uuid().nullable(),createdAt:W.iso.datetime({offset:!0}),updatedAt:W.iso.datetime({offset:!0})}),jh=as.extend({draft:vr}),Ah=W.strictObject({rows:W.array(as).max(200),nextCursor:W.uuid().nullable()}),Ri=W.strictObject({id:W.uuid(),kind:Ot,resourceId:W.uuid(),projectId:W.uuid(),environmentId:W.uuid(),version:W.number().int().positive(),sourceRevision:W.number().int().nonnegative(),document:kl,createdAt:W.iso.datetime({offset:!0})}),wh=Ri.omit({document:!0}),_h=W.discriminatedUnion("action",[W.strictObject({action:W.literal("create"),kind:Ot,id:W.uuid(),document:vr}),W.strictObject({action:W.literal("save"),kind:Ot,id:W.uuid(),revision:W.number().int().nonnegative(),document:vr}),W.strictObject({action:W.enum(["publish","archive"]),kind:Ot,id:W.uuid(),revision:W.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as on}from"zod";var Ir=on.strictObject({items:on.array(on.strictObject({productVersionId:on.string().min(1).max(200),label:on.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:on.string().min(1).max(200).nullable(),grouping:Ta.optional()});function Rh(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(o=>o.versionId===r&&o.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}import{z as Ei}from"zod";var Rl=Ei.enum(["sandbox","live"]),me=Ei.object({projectId:Ei.string().min(1),environment:Rl}).strict();import{z as ue}from"zod";var Mn=ue.number().int().min(1).max(Number.MAX_SAFE_INTEGER),ss=ue.enum(["unknown","denied","provisional","granted"]),cs=ue.enum(["ios","android"]),Or=ue.strictObject({installationId:ue.uuid(),publicKey:ue.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:ue.iso.datetime({offset:!0}),signature:ue.string().regex(/^[A-Za-z0-9_-]{86}$/)}),Mi=ue.string().regex(/^[a-f0-9]{64}$/),us=Or.extend({sequence:Mn,platform:cs,credentialDigest:Mi}),ps=Or.extend({credentialDigest:Mi}),zh=Or.extend({sequence:Mn,platform:cs}),jr=Or.extend({sequence:Mn,credentialDigest:Mi,connectionId:ue.uuid().nullable(),kind:ue.enum(["fcm_token","apns_token"]).nullable(),token:ue.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:ss}),Bh=jr,qh=jr.extend({challenge:ue.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),Fh=ue.strictObject({requested:ue.literal(!0),expiresAt:ue.iso.datetime({offset:!0})}),Ar=ue.strictObject({installationId:ue.uuid(),bound:ue.boolean(),identitySeq:Mn,bindingGeneration:Mn,addressSeq:ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:ue.uuid().nullable(),addressStatus:ue.enum(["active","invalid"]).nullable(),permission:ss}),Ti=ue.strictObject({channel:ue.enum(["email","sms","voice","push"]),state:ue.enum(["unknown","allowed","denied"]),revision:ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:ue.iso.datetime({offset:!0}).nullable()}),Nh=ue.strictObject({state:ue.enum(["allowed","denied"]),revision:ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Uh(e,t,n){let r=["indiana_push_v1",e,t.projectId,t.environment,n.installationId,n.publicKey,n.issuedAt];e==="bind"?r.push(n.sequence,n.platform,n.credentialDigest):e==="detach"?r.push(n.sequence,n.platform):e==="read"?r.push(n.credentialDigest):r.push(n.sequence,n.credentialDigest,n.connectionId,n.kind,n.token,n.permission),e==="recovery_confirm"&&r.push(n.challenge);let o=JSON.stringify(r);if([...o].some(a=>a.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(o,a=>a.charCodeAt(0))}var $h="X-Indiana-Protocol",Gh="X-Indiana-SDK-Version";var Kh={current:"0.10"};import{z as an}from"zod";var wr=an.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"),Jh=an.object({amountCents:an.number().int().min(0).max(1e8),currency:oe,interval:an.enum(["free","month","year"]),currencyOptions:an.partialRecord(oe,an.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");import{z as y}from"zod";var El=y.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),ds=y.enum(["single_use","continuous_use"]),Di=y.record(y.string(),y.union([y.string(),y.number(),y.boolean()]).transform(String).pipe(y.string())),ls=y.string().min(1).max(64).refine(e=>!e.includes("::")),fs={credit_amount:y.number(),tier_behavior:y.never().optional(),tiers:y.never().optional()},gs={credit_amount:y.never().optional(),tier_behavior:y.literal("graduated"),tiers:y.array(y.strictObject({to:y.union([y.number(),y.literal("inf")]),credit_amount:y.number()}))},Ml=y.union([y.strictObject({match:Di,priority:y.number().int().optional(),...fs}),y.strictObject({match:Di,priority:y.number().int().optional(),...gs})]),Tl=y.strictObject({match:Di,factor:y.number().positive().optional(),add:y.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),ms={metered_feature_id:y.string(),feature_amount:y.number().optional(),dimensions:y.record(ls,Ml).optional(),multipliers:y.record(ls,Tl).optional()},zi=y.union([y.strictObject({...ms,...fs}),y.strictObject({...ms,...gs})]),Pr=y.number().min(-100),hs=y.record(y.string(),y.strictObject({markup:Pr})).nullish(),Cr=y.record(y.string().regex(/.+\/.+/),y.strictObject({markup:Pr.optional(),input_cost:y.number().min(0).optional(),output_cost:y.number().min(0).optional()})).nullish(),Dl=y.strictObject({default_markup:Pr.optional(),provider_markups:hs,model_markups:Cr}),Xh=y.strictObject({schema:y.array(zi).optional(),markups:Dl.optional()}),zl=y.strictObject({filters:y.array(y.strictObject({property:y.string(),operator:y.string(),value:y.array(y.string())})),aggregate:y.strictObject({type:y.string(),property:y.string().nullable()}),usage_type:ds}),bs=y.strictObject({schema:y.array(zi).min(1).refine(e=>new Set(e.map(t=>t.metered_feature_id)).size===e.length,"Credit rates must name each metered feature once"),invoice_credit:y.boolean().optional(),usage_type:ds.default("single_use").overwrite(()=>"single_use"),default_markup:Pr.optional(),provider_markups:hs}),Bi=bs.safeExtend({schema:y.array(zi).length(0)}),_r={id:El,name:y.string().min(1),display:y.strictObject({singular:y.string().optional(),plural:y.string().optional()}).nullish(),event_names:y.array(y.string()).default([]),model_markups:Cr,stripe_meter:y.strictObject({id:y.string(),event_name:y.string()}).nullish(),stripe_product_id:y.string().nullish()},qi=e=>y.discriminatedUnion("type",[y.strictObject({..._r,...e,type:y.literal("boolean"),config:y.null()}),y.strictObject({..._r,...e,type:y.literal("metered"),config:zl}),y.strictObject({..._r,...e,type:y.literal("credit_system"),config:bs}),y.strictObject({..._r,...e,type:y.literal("ai_credit_system"),config:Bi})]),Yh=qi({}),Bl=y.strictObject({id:y.boolean(),type:y.boolean(),usage_type:y.boolean()}),ql={internal_id:y.uuid(),org_id:y.uuid(),created_at:y.number(),env:y.enum(["sandbox","live"]),archived:y.boolean(),project_id:y.uuid(),environment_id:y.uuid(),revision:y.number().int().nonnegative(),update_rules:Bl},ys=qi(ql),eb=y.strictObject({rows:y.array(ys).max(200),nextCursor:y.uuid().nullable()}),tb=y.strictObject({features:y.array(ys).max(500),limited:y.boolean()}),nb=y.union([qi({action:y.literal("save"),internal_id:y.uuid().nullable(),revision:y.number().int().nonnegative()}),y.strictObject({action:y.enum(["archive","restore","delete"]),internal_id:y.uuid(),revision:y.number().int().nonnegative()})]);import{z as s}from"zod";import{z as M}from"zod";import{z as ke}from"zod";function jt(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,l){if(n(a))for(let[p,d]of Object.entries(a))p==="$elemMatch"?o(d,l):p==="$not"?r(d,l):p==="$all"&&Array.isArray(d)&&d.forEach(v=>r(v,l))}function o(a,l=""){if(n(a)){for(let[p,d]of Object.entries(a))if(["$and","$or","$nor"].includes(p)&&Array.isArray(d))d.forEach(v=>o(v,l));else if(p==="$not")o(d,l);else if(p==="$savedGroup"&&n(d))typeof d.attributeKey=="string"&&t.add(d.attributeKey);else if(!p.startsWith("$")){let v=l?`${l}.${p}`:p;t.add(v),r(d,v)}}}return o(e),[...t]}var Fl=ke.enum(["active","inactive"]),Nl=ke.preprocess((e,t)=>{let n=0;function r(o,a){if(!(++n>1e4||a>20)){if(Array.isArray(o))o.forEach(l=>r(l,a+1));else if(o&&typeof o=="object")for(let[l,p]of Object.entries(o))["__proto__","constructor","prototype"].includes(l)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(p,a+1)}}return r(e,0),e},Ke),Ul=ke.strictObject({id:ke.string().trim().min(1).max(255),name:ke.string().trim().min(1).max(255),status:Fl,metadata:Nl}),cb=Ul.extend({internal_id:ke.uuid(),project_id:ke.uuid(),environment_id:ke.uuid(),created_at:ke.iso.datetime({offset:!0}),updated_at:ke.iso.datetime({offset:!0})}),Ss=ke.union([ke.strictObject({id:ke.string().trim().min(1).max(255)}),ke.strictObject({internalId:ke.uuid()})]),ub=ke.enum(["customer","merchandise","context"]),pb=ke.enum(["system","stored","request"]),lb=ke.enum(["customer","merchandise","mixed"]),xs=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Fi(e,t={},n=new Set){if(jt(e).some(xs))return!0;for(let r of vt(e)){if(n.has(r))continue;n.add(r);let o=t[r];if(o?.type==="list"&&xs(o.attributeKey)||o?.type==="condition"&&Fi(o.condition,t,n))return!0}return!1}var bb=M.enum(["draft","active","paused","archived"]),At=M.discriminatedUnion("type",[M.object({type:M.literal("percent"),percentOff:M.number().min(1).max(100).multipleOf(.01)}).strict(),M.object({type:M.literal("amount"),amountOffCents:M.number().int().min(1).max(1e8),currency:oe}).strict()]),He=M.discriminatedUnion("type",[M.object({type:M.literal("once")}).strict(),M.object({type:M.literal("repeating"),months:M.number().int().min(1).max(36)}).strict(),M.object({type:M.literal("forever")}).strict()]),vs=[M.object({type:M.literal("all")}).strict(),M.object({type:M.literal("plans"),planIds:M.array(M.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Vl=M.discriminatedUnion("type",[...vs,M.strictObject({type:M.literal("merchandise"),scope:M.discriminatedUnion("type",[M.strictObject({type:M.literal("all")}),M.strictObject({type:M.literal("selected"),merchandiseIds:M.array(M.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),M.strictObject({type:M.literal("condition"),condition:it})])})]),Ni=M.discriminatedUnion("type",[...vs,M.strictObject({type:M.literal("merchandise"),scope:M.strictObject({type:M.enum(["all","selected","condition"])})})]),$l=M.strictObject({firstPurchaseOnly:M.boolean(),condition:it}),yb=M.object({name:M.string().trim().min(1).max(80),description:M.string().max(500),discount:At,duration:He,appliesTo:Vl,eligibility:$l,selfClaimEnabled:M.boolean().default(!1),startsAt:M.iso.datetime().nullable(),endsAt:M.iso.datetime().nullable(),totalLimit:M.number().int().min(1).max(1e6).nullable(),perCustomerLimit:M.number().int().min(1).max(10),grantWindowHours:M.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!Fi(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"]}),xb=M.object({code:M.string().trim().transform(e=>e.toUpperCase()).pipe(M.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:M.number().int().min(1).max(1e6).nullable(),expiresAt:M.iso.datetime().nullable(),firstPurchaseOnly:M.boolean(),minimumAmountCents:M.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:oe.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Tn=M.object({id:M.uuid(),couponId:M.uuid(),status:M.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:M.iso.datetime(),expiresAt:M.iso.datetime(),coupon:M.object({name:M.string(),discount:At,duration:He,appliesTo:Ni}).strict()}).strict(),Is=M.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var _s=s.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Ui=s.string().regex(/^(0|[1-9]\d{0,14})$/),sn=s.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Gl=s.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Dn=Gl,yt=ye.refine(e=>/[1-9]/.test(e)),qe=s.iso.datetime({offset:!0}),kr=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},Kl=s.array(s.object({upTo:yt.nullable(),unitAmountMinor:_s,flatAmountMinor:s.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&kr(t.upTo)>kr(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Ll=s.discriminatedUnion("kind",[s.object({kind:s.literal("flat"),units:yt,unitAmountMinor:_s}).strict(),s.object({kind:s.enum(["graduated","volume"]),units:yt,tiers:Kl}).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"),Zl=s.strictObject({interval:s.enum(["month","year"]),count:s.number().int().min(1).max(12),anchor:s.enum(["membership","calendar"])}),zn=s.object({currency:oe,pricing:Ll,billingCycle:Zl.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Os={requestId:s.uuid(),productVersionId:s.uuid(),internal_feature_id:s.uuid(),currency:oe},Ps=s.strictObject({interval:s.enum(["hour","day","week","month"]),intervalCount:s.number().int().min(1).max(12),limit:s.number().int().min(1).max(1e6)}),Cs=s.discriminatedUnion("kind",[s.object({...Os,kind:s.literal("auto_topup"),threshold:mi,quantity:yt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Ps.optional()}).strict(),s.object({...Os,kind:s.literal("postpaid"),maxAmountMinorPerPeriod:Dn,maxOutstandingMinor:Dn}).strict()]),js={productVersionId:s.uuid(),internal_feature_id:s.uuid(),currency:oe},ks=s.discriminatedUnion("kind",[s.object({...js,kind:s.literal("auto_topup"),threshold:mi,quantity:yt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Ps.optional(),purchaseAmountMinor:Dn,purchaseUnits:yt}).strict(),s.object({...js,kind:s.literal("postpaid"),maxAmountMinorPerPeriod:Dn,maxOutstandingMinor:Dn,cashPrice:zn}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Rr=s.object({id:s.uuid(),terms:ks,status:s.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"),Rs=s.object({authorizationId:s.uuid(),terms:ks,setupUrl:s.url().nullable()}).strict(),Es=s.object({authorizationId:s.uuid(),accepted:s.literal(!0)}).strict(),Ms=s.object({authorizationId:s.uuid(),requestId:s.uuid()}).strict(),Ts=s.object({internal_feature_id:s.uuid(),entityId:s.uuid().nullable(),interval:s.enum(["day","week","month","year"]),anchor:s.enum(["billing_cycle","utc"]).optional(),basis:s.enum(["usage","credits"]),filter:ft.optional(),limit:ye.nullable(),thresholds:s.array(s.number().positive().max(1)).max(8),includedThresholds:s.array(s.number().positive().max(1)).max(8).optional(),absoluteThresholds:s.array(yt).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let o=r[n-1];return n===0||o!==void 0&&t>o})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let o=r[n-1];return n===0||o!==void 0&&kr(t)>kr(o)}),"Notification thresholds must increase"),Hl=Ts.safeExtend({requestId:s.uuid()}),As={control:s.literal("overage"),requestId:s.uuid(),internal_feature_id:s.uuid(),entityId:s.uuid().nullable()},Jl=s.discriminatedUnion("action",[s.strictObject({...As,action:s.literal("set"),allowed:s.boolean().nullable(),overageLimit:ye.nullable(),skipOverageBilling:s.boolean()}),s.strictObject({...As,action:s.literal("remove")})]),Ds=s.union([Hl,Jl]),Wl=s.strictObject({internal_feature_id:s.uuid(),entityId:s.uuid().nullable(),allowed:s.boolean().nullable(),overageLimit:ye.nullable(),skipOverageBilling:s.boolean(),interval:s.enum(["day","week","month","year"]),startsAt:qe,endsAt:qe,used:s.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:s.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:s.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Ql=s.object({internal_feature_id:s.uuid(),entityId:s.uuid().nullable(),interval:s.enum(["day","week","month","year"]),anchor:s.enum(["billing_cycle","utc"]).optional(),basis:s.enum(["usage","credits"]),filter:ft.optional(),startsAt:qe,endsAt:qe,used:rt,reserved:rt,limit:ye.nullable(),thresholds:s.array(s.number().positive().max(1)).max(8),notifiedThresholds:s.array(s.number().positive().max(1)).max(1024),includedThresholds:s.array(s.number().positive().max(1)).max(8).optional(),includedAllowance:s.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:s.array(s.number().positive().max(1)).max(1024).optional(),absoluteThresholds:s.array(yt).max(8).optional(),notifiedAbsoluteThresholds:s.array(yt).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||ye.safeParse(e.used).success&&ye.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Xl=s.object({authorizationId:s.uuid(),status:s.enum(["idle","pending","blocked"]),taskId:s.uuid().nullable(),invoiceId:s.uuid().nullable(),hostedInvoiceUrl:s.url().nullable(),purchaseCount:s.number().int().nonnegative(),purchaseWindowEndsAt:qe.nullable(),attemptCount:s.number().int().nonnegative(),failedAttemptCount:s.number().int().nonnegative(),suspendedAt:qe.nullable(),nextAttemptAt:qe.nullable(),failureReason:s.string().min(1).max(240).nullable()}).strict(),zs=s.object({internal_feature_id:s.uuid().optional(),entityId:s.uuid().optional()}).strict(),Vi=s.object({authorizations:s.array(Rr).max(100),limits:s.array(Ts).max(100),overages:s.array(Wl).max(100).optional(),windows:s.array(Ql).max(200),autoTopups:s.array(Xl).max(100),limited:s.boolean()}).strict(),Yl=s.object({id:s.uuid(),internal_feature_id:s.uuid(),productVersionId:s.uuid(),authorizationId:s.uuid(),entityId:s.uuid().nullable(),units:ye,amountMinor:sn,cashPrice:zn}).strict(),Bn=s.object({id:s.uuid(),sourceKind:s.enum(["product","usage","manual"]),providerInvoiceId:s.string().min(1).max(240).nullable(),status:s.enum(["accruing","open","pending","paid","failed","void"]),currency:oe,startsAt:qe.nullable(),endsAt:qe.nullable(),amountMinor:s.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:s.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Ui,paidAmountMinor:Ui,refundedAmountMinor:Ui,createdAt:qe,hostedInvoiceUrl:s.url().nullable(),adjustment:s.object({originalInvoiceId:s.uuid(),amountMinor:s.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:qe.nullable(),reason:s.string().min(1).max(500).optional()}).strict().nullable(),lines:s.array(Yl).max(100),linesLimited:s.boolean()}).strict(),Bs=s.object({invoiceId:s.uuid(),accepted:s.literal(!0)}).strict(),qs=s.strictObject({requestId:s.uuid(),originalInvoiceId:s.uuid(),amountMinor:s.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:s.string().trim().min(1).max(500)}),Fs=s.object({after:s.uuid().nullable(),limit:s.number().int().min(1).max(100)}).strict(),Ns=s.object({rows:s.array(Bn).max(100),nextCursor:s.uuid().nullable()}).strict(),ws=s.strictObject({id:s.string(),coupon:s.string(),start:s.number().nonnegative(),end:s.number().nullable()}),em=s.strictObject({subscriptionId:s.string(),customerId:s.string(),accountId:s.string(),sourceItems:s.array(s.strictObject({id:s.string(),price_id:s.string(),quantity:s.number().int(),discounts:s.array(ws).optional()})).max(100),items:s.array(s.strictObject({id:s.string(),price:s.string(),quantity:s.number().int(),discounts:s.array(s.strictObject({coupon:s.string().optional(),terms:s.strictObject({id:s.string(),name:s.string().optional(),percent_off:s.number().optional(),amount_off:s.number().optional(),currency:s.string().optional(),duration:s.enum(["once","forever","repeating"]),duration_in_months:s.number().optional()}).optional(),discount:s.string().optional(),receipt:ws.optional()})).max(20)})).max(100)}),Us=s.strictObject({membershipId:s.uuid(),requestId:s.uuid(),grantIds:s.array(s.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Vs=s.strictObject({membershipId:s.uuid(),operationId:s.uuid(),status:s.enum(["pending","effective"]),execution:em.nullable(),grants:s.array(s.strictObject({id:s.uuid(),couponId:s.uuid(),name:s.string(),discount:At,duration:He,startedAt:qe.nullable()})).max(20)});import{z as qn}from"zod";var $s=qn.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Gs=qn.number().int().min(1).max(1e3),Er=qn.object({cap:ye.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:qn.number().positive().max(1e4).nullable(),cycles:qn.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as wt}from"zod";var Ks=wt.strictObject({itemKey:wt.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:wt.uuid(),includedAmount:wt.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:wt.number().int().min(0).max(1e4),terms:fa,pricing:da.optional(),unitAmountMinor:wt.number().int().min(0).max(1e8),productId:wt.string().min(1).max(255).nullable(),priceId:wt.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{ga(e.includedAmount,e.terms.units,e.quantity),or({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as re}from"zod";var Bt=re.iso.datetime({offset:!0}),Ls=ye.refine(e=>/[1-9]/.test(e)),Zs=re.strictObject({interval:$s.exclude(["lifetime"]),count:Gs}),tm=re.strictObject({action:re.literal("create"),requestId:re.uuid(),internal_feature_id:re.uuid(),entityId:re.uuid().nullable(),amount:Ls.nullable(),expiresAt:Bt.nullable(),reset:Zs.nullable(),rollover:Er.nullable(),nextResetAt:Bt.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"),Hs=re.discriminatedUnion("action",[tm,re.strictObject({action:re.literal("update"),requestId:re.uuid(),grantId:re.uuid(),revision:re.number().int().nonnegative(),amount:Ls.nullable(),expiresAt:Bt.nullable(),rollover:Er.nullable(),nextResetAt:Bt.nullable()}),re.strictObject({action:re.enum(["add","subtract","set_remaining"]),requestId:re.uuid(),grantId:re.uuid(),revision:re.number().int().nonnegative(),amount:ye}),re.strictObject({action:re.literal("revoke"),requestId:re.uuid(),grantId:re.uuid(),revision:re.number().int().nonnegative()})]),$i=re.strictObject({id:re.uuid(),internal_feature_id:re.uuid(),entityId:re.uuid().nullable(),amount:ye.nullable(),reset:Zs.nullable(),rollover:Er.nullable(),nextResetAt:Bt.nullable(),startsAt:Bt,expiresAt:Bt.nullable(),revision:re.number().int().nonnegative(),revoked:re.boolean(),available:rt,held:rt,spent:rt}),Js=re.strictObject({customerId:re.uuid(),after:re.uuid().nullable(),limit:re.number().int().min(1).max(100)}),Ws=re.strictObject({rows:re.array($i).max(100),nextCursor:re.uuid().nullable()});import{z as D}from"zod";var mt=D.iso.datetime({offset:!0}),Qs=D.strictObject({invoiceId:D.uuid(),after:D.string().min(1).max(180).nullable(),limit:D.number().int().min(1).max(100)}),nm=D.strictObject({kind:D.literal("product"),key:D.string(),productVersionId:D.uuid(),productName:D.string(),itemKey:D.string(),entityId:D.uuid().nullable(),quantity:D.number().positive(),subtotalMinor:D.string().regex(/^-?\d+$/),discountMinor:D.string().regex(/^\d+$/),taxMinor:D.string().regex(/^-?\d+$/).nullable(),totalMinor:D.string().regex(/^-?\d+$/),startsAt:mt.nullable(),endsAt:mt.nullable(),providerLineId:D.string().nullable(),providerItemId:D.string()}),Xs=D.strictObject({invoice:Bn,items:D.array(D.discriminatedUnion("kind",[nm,D.strictObject({kind:D.literal("invoice_credit"),key:D.string(),internal_feature_id:D.uuid(),internal_credit_feature_id:D.uuid(),name:D.string(),units:ye,reserved:ye,amountMinor:sn,grossAmountMinor:sn,creditsAppliedMinor:sn,properties:ft,cashPrice:zn,providerItemId:D.string().nullable(),creditProviderItemId:D.string().nullable()}),D.strictObject({kind:D.literal("usage"),key:D.string(),internal_feature_id:D.uuid(),name:D.string(),units:ye,reserved:ye,amountMinor:sn,cashPrice:zn})])).max(100),nextCursor:D.string().min(1).max(180).nullable()}),rm=D.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Gi=D.strictObject({from:mt,to:mt,entityId:D.uuid().optional(),snapshotAt:mt.nullable(),after:D.strictObject({at:mt,id:D.uuid(),position:D.number().int().nonnegative()}).nullable(),limit:D.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),Ys=D.strictObject({customerId:D.uuid(),entityId:D.uuid().nullable(),from:mt,to:mt,snapshotAt:mt,totals:D.array(D.strictObject({internal_credit_feature_id:D.uuid(),name:D.string(),consumed:rt,refunded:rt,net:rm})).max(1e3),rows:D.array(D.strictObject({operationId:D.uuid(),position:D.number().int().nonnegative(),kind:D.enum(["consume","confirm","refund"]),originalId:D.uuid().nullable(),occurredAt:mt,internal_feature_id:D.uuid(),entitlementName:D.string(),sourceId:D.uuid(),internal_credit_feature_id:D.uuid(),creditName:D.string(),units:Sa,amount:rt,pricing:D.array(xa).max(12),properties:ft})).max(100),nextCursor:Gi.shape.after});import{z as U}from"zod";var tc=U.object({customerId:U.uuid()}).strict(),nc=U.discriminatedUnion("action",[U.object({customerId:U.uuid(),requestId:U.uuid(),action:U.literal("assign"),poolId:U.uuid(),memberCustomerId:U.uuid()}).strict(),U.strictObject({customerId:U.uuid(),requestId:U.uuid(),action:U.literal("assign_entity"),poolId:U.uuid(),entityId:U.uuid()}),U.object({customerId:U.uuid(),requestId:U.uuid(),action:U.literal("release"),poolId:U.uuid(),slotId:U.uuid()}).strict()]),Fn=U.number().int().nonnegative(),Ki=U.iso.datetime({offset:!0}),Li=U.strictObject({internalId:U.uuid(),id:U.string(),name:U.string().nullable(),version:U.number().int().positive()}),ec=U.enum(["active","past_due"]),Zi=U.strictObject({customerId:U.uuid(),licenses:U.array(U.strictObject({id:U.uuid(),linkId:U.uuid(),parent:U.strictObject({customerProductId:U.uuid(),status:ec,product:Li}),product:Li,planLicense:U.strictObject({id:U.uuid(),prepaidOnly:U.boolean(),isCustom:U.boolean()}).nullable(),granted:Fn,included:Fn,paidQuantity:Fn,usage:Fn,remaining:Fn,createdAt:Ki}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:U.array(U.strictObject({id:U.uuid(),linkId:U.uuid(),status:ec,product:Li,entity:U.strictObject({internalId:U.uuid(),id:U.string().nullable(),name:U.string().nullable()}).nullable(),beneficiary:U.strictObject({internalId:U.uuid(),id:U.string().nullable(),name:U.string().nullable()}).nullable(),startedAt:Ki.nullable(),endedAt:Ki.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:U.boolean()});import{z as N}from"zod";var Nn=N.enum(["email","sms","voice","push"]),Kb=N.enum(["resend","twilio","fcm","apns"]);var Lb=N.string().regex(/^\+[1-9]\d{1,14}$/),im=N.enum(["email_recipient","sms_segment","voice_second","push_device"]);var om=N.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),am=N.strictObject({subject:om,html:N.string().min(1).max(131072).optional(),text:N.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),sm=N.strictObject({body:N.string().min(1).max(1600).refine(e=>e.trim().length>0)}),cm=N.strictObject({text:N.string().trim().min(1).max(4e3),language:N.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:N.number().int().min(1).max(900)}),um=N.record(N.string().min(1).max(64),N.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),pm=N.strictObject({title:N.string().trim().min(1).max(200),body:N.string().trim().min(1).max(2e3),url:N.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:um.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),rc=N.discriminatedUnion("channel",[N.strictObject({channel:N.literal("email"),content:am}),N.strictObject({channel:N.literal("sms"),content:sm}),N.strictObject({channel:N.literal("voice"),content:cm}),N.strictObject({channel:N.literal("push"),content:pm})]),ic=N.strictObject({requestId:N.uuid(),customerId:N.uuid(),connectionId:N.uuid().optional(),message:rc,expiresAt:N.iso.datetime({offset:!0})}),lm=N.array(N.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),mm=N.discriminatedUnion("kind",[N.strictObject({kind:N.literal("all")}),N.strictObject({kind:N.literal("customers"),customerIds:lm})]),Zb=N.strictObject({name:N.string().trim().min(1).max(120),connectionId:N.uuid().optional(),message:rc,audience:mm,frequencyLimit:N.number().int().min(1).max(100)}),oc=N.strictObject({requestId:N.uuid(),channel:Nn,state:N.enum(["allowed","denied"]),expectedRevision:N.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),ac=N.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),sc=N.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),Hb=N.strictObject({meter:im,estimatedUnits:N.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:N.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as cc}from"zod";var cn={funnelId:cc.uuid().optional(),funnelVersionId:cc.uuid().optional()};import{z as Mr}from"zod";var Tr=Mr.strictObject({runId:Mr.uuid(),bindingId:Mr.uuid(),receiptId:Mr.uuid()});import{z as xe}from"zod";import{z as se}from"zod";import{z as ge}from"zod";var ty=ge.discriminatedUnion("action",[ge.strictObject({action:ge.literal("create"),couponId:ge.uuid(),productBindingId:ge.uuid(),storeOfferId:ge.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:ge.enum(["introductory","promotional"])}),ge.strictObject({action:ge.literal("set_enabled"),id:ge.uuid(),revision:ge.number().int().nonnegative(),enabled:ge.boolean()})]),ny=ge.array(ge.strictObject({id:ge.uuid(),couponId:ge.uuid(),productBindingId:ge.uuid(),storeOfferId:ge.string().min(1).max(255).nullable(),storeOfferType:ge.enum(["introductory","promotional"]),enabled:ge.boolean(),revision:ge.number().int().nonnegative()})).max(500),un=ge.strictObject({offerKind:ge.enum(["none","introductory","promotional"]),offerId:ge.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:ge.number().int().min(0).max(1e8),trialDays:ge.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"})}),ry=ge.record(ge.uuid(),un).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Hi=se.object({type:se.literal("native_purchase"),receiptId:se.uuid(),orderId:se.uuid(),productVersionId:se.uuid(),provider:se.enum(["apple","google"]),productId:se.string().min(1).max(255),productKind:Pa,replacement:se.strictObject({sourceOrderId:se.uuid(),sourceProductId:se.string().min(1).max(255),policy:se.enum(["apple_store","google_full_price"]),sourceAccountTokens:se.array(se.uuid()).max(50)}).nullable(),appAccountToken:se.uuid().optional(),obfuscatedAccountId:se.string().min(1).max(64).optional(),obfuscatedProfileId:se.uuid().optional(),basePlanId:se.string().min(1).max(255).optional(),offerId:se.string().min(1).max(255).optional(),offerKind:se.enum(["none","introductory","promotional"]),currency:oe,catalogAmountMinor:se.number().int().nonnegative().max(1e8),discountMinor:se.number().int().nonnegative().max(1e8),trialDays:se.number().int().min(1).max(730).nullable(),seatBundle:se.array(se.strictObject({key:se.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:se.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:se.strictObject({offerId:se.string().min(1).max(255),keyId:se.string().min(1).max(255),nonce:se.uuid(),signature:se.string().min(1).max(1024),timestamp:se.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(o=>o.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as i}from"zod";import{z as Q}from"zod/v4";import{z as dm}from"zod/v4";var fm=dm.registry(),{BillingInterval:uc}=(()=>{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:gm}=(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')."})})}))(Q),{withSpecDefault:hm}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:o})=>(e.add(n,{description:o,default:r}),n)}))(fm),{COMMON:pc}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:bm}={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:ym}=(e=>({COMMON_SET:new Set(e)}))(pc),{hasNoDuplicateCurrencies:lc}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let o=r.toLowerCase();if(n.has(o))return!1;n.add(o)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:mc}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:xm}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(Q),{Infinite:Sm}={Infinite:"inf"},{TierBehavior:vm}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:dc}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Im}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Om}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:jm}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Am}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Q),{ApiCreditTierSchema:fc}=(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."})})}))(Q),{VIOLATION_MESSAGES:wm}={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:gc}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Q),{ModelMarkupsSchema:_m}=((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()}))(Q,gc),{InvoiceUsageEntrySchema:Pm}=(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()}))(Q),{AttachDiscountSchema:hc}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(Q),{CustomLineItemSchema:Cm}=(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."})})}))(Q),{UnixMsTimestampSchema:km}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(Q),{CreateInvoicePreviewLineSchema:Rm}=(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()})}))(Q),{ReissueInvoiceParamsSchema:bc}=(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."})})}))(Q),{InvoiceModeParamsSchema:qt}=(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."})}))(Q),{InvoiceTemplateSchema:Em}=(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."})})}))(Q),{BasePriceSchema:Mm}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(Q,uc,gm),{CURRENCY_CODES:Tm}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(o=>!n.has(o)).sort()]}))(pc,bm,ym),{ApiPriceProcessorsSchema:yc}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(Q,xm),{AllocatedBillingFieldSchema:Dm}=((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'."})}))(Q,Im),{CreditDimensionNameSchema:zm}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(o=>!o.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Q,Om,jm),{ApiCreditMatchSchema:xc}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Am),{findCreditTierViolations:Bm}=(e=>({findCreditTierViolations:n=>{let r=[],o=(l,p)=>r.push({index:l,reason:p,message:e[p]}),a=0;for(let[l,p]of n.entries()){let d=l===n.length-1;if(p==="inf"){d||o(l,"non_final_infinity");continue}(!Number.isFinite(p)||p<=a)&&o(l,"not_increasing"),a=p,d&&o(l,"final_not_infinity")}return r}}))(wm),{ApiCreditMultiplierSchema:qm}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(Q,xc),{ProviderMarkupsSchema:Fm}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Q,gc),{InvoiceFeatureQuantitySchema:Sc}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(o=>o.quantity!==void 0!=(o.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(Q,dc,Pm),{CreateInvoicePreviewSchema:Ji}=((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()})}))(Q,Rm),{SUPPORTED_SET:Nm}=(e=>({SUPPORTED_SET:new Set(e)}))(Tm),{ApiCreditDimensionBaseSchema:Um}=((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."})})}))(Q,xc),{refineGraduatedTiers:vc}=(e=>({refineGraduatedTiers:(n,r)=>{let o=e(n.tiers.map(a=>a.to));for(let{index:a,message:l}of o)r.addIssue({code:"custom",message:l,path:["tiers",a,"to"]})}}))(Bm),{ApiFeatureMarkupsOverrideSchema:Vm}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(Q,Fm,_m),{isValidCurrencyCode:$m}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Nm),{ApiCreditDimensionSchema:Gm}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(Q,Um,fc,vc),{CurrencyCodeSchema:Ic}=((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')."})}))(Q,$m),{AdditionalCurrencyTierSchema:Km}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(Q,Ic),{ApiCreditSchemaItemBaseSchema:Oc}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(Q,zm,Gm,qm),{ApiFlatCreditSchemaItemSchema:Lm}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Oc,Q),{AdditionalCurrencyPriceSchema:Zm}=((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."})})}))(Q,Ic),{AdditionalCurrencyTierArraySchema:Hm}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Q,Km,lc,mc),{ApiGraduatedCreditSchemaItemSchema:Jm}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Oc,Q,fc,vc),{AdditionalCurrencyPriceArraySchema:jc}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Q,Zm,lc,mc),{ApiUsageTierWithCurrenciesSchema:Wm}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(o=>o.amount!==void 0||o.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(o=>({...o,amount:o.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(Q,Sm,Hm),{ApiCreditSchemaItemSchema:Qm}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(Q,Jm,Lm),{BasePriceParamsSchema:Xm}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(Mm,hm,Q,jc),{PlanItemPriceParamsSchema:Ym}=((e,t,n,r,o,a,l)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(d=>d??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(o).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:l,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(Q,jc,Wm,vm,uc,dc,Dm),{ApiFeatureOverrideSchema:ed}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(Q,Qm,Vm),{InvoiceBasePriceParamsSchema:Ac}=((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()}))(Xm,yc),{InvoiceItemPriceParamsSchema:td}=((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()}))(Ym,yc),{InvoiceLicenseQuantitySchema:nd}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(Q,Ac,Sc),{InvoiceCustomizeItemSchema:rd}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(Q,td,ed),{InvoiceCustomizeSchema:id}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(Q,Ac,rd),{InvoicePlanParamsSchema:od}=((e,t,n,r,o)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(o).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()}))(Q,id,Sc,nd,hc),{CreateInvoiceParamsSchema:pn}=((e,t,n,r,o)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:o.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:o.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(l=>l.period_start===void 0==(l.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(l=>l.period_start===void 0||l.period_end===void 0||l.period_end>l.period_start,{message:"period_end must be after period_start."})}))(Q,od,Cm,hc,km);var Pc=i.strictObject({requestId:i.uuid(),predecessorOperationId:i.uuid().optional(),invoiceMode:qt.optional(),entityId:i.uuid().optional(),billingSubscriptionId:i.uuid().optional(),newBillingSubscription:i.literal(!0).optional(),offerId:i.uuid().optional(),nativeOffer:un.optional(),plans:i.array(i.strictObject({productVersionId:i.uuid(),seatQuantities:i.record(wr,i.number().int().min(0).max(1e4)).optional(),featureQuantities:i.record(i.uuid(),i.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:i.enum(["stripe","apple","google","merchant"]),currency:oe}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Nt=i.strictObject({operationId:i.uuid()}),Re=i.number().int().min(0).max(1e8),ad=i.strictObject({lineId:i.uuid(),productVersionId:i.uuid(),productName:i.string().min(1).max(80),interval:i.enum(["free","week","month","year","one_time"]),intervalCount:i.number().int().min(1).max(156).optional(),baseAmountMinor:Re,seats:i.array(i.strictObject({key:wr,quantity:i.number().int().min(0).max(1e4),includedQuantity:i.number().int().min(0).max(1e4),maximumQuantity:i.number().int().min(0).max(1e4),unitAmountMinor:Re})).max(20),prepaid:i.array(Ks).max(100).optional(),catalogAmountMinor:Re,trial:i.strictObject({days:i.number().int().min(1).max(730),cardRequired:i.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+or({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Cc=i.string().regex(/^[A-Za-z0-9_-]{1,200}$/),sd=i.strictObject({id:Cc,name:i.string().min(1).max(40),percent_off:i.number().gt(0).max(100).optional(),amount_off:i.number().int().positive().optional(),currency:i.string().regex(/^[a-z]{3}$/).optional(),duration:i.enum(["once","repeating","forever"]),duration_in_months:i.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"),cd=i.strictObject({subscriptionId:i.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:i.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:i.array(i.strictObject({id:i.string(),price_id:i.string(),quantity:i.number().int().nonnegative(),discounts:i.array(i.strictObject({id:i.string(),coupon:i.string(),start:i.number(),end:i.number().nullable()})).optional()})).min(1).max(100),prorationDate:i.number().int().nonnegative(),amountMinor:i.number().int().positive(),periodStartMs:i.number(),periodEndMs:i.number()}),kc=i.strictObject({invoiceMode:qt.optional(),append:cd.optional(),provider:i.literal("stripe"),executor:i.enum(["indiana","merchant"]),accountId:i.string().regex(/^acct_[A-Za-z0-9]+$/),mode:i.enum(["payment","subscription"]),lineItems:i.array(i.strictObject({price:i.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:i.number().int().min(1).max(1e4),priceId:i.uuid(),productName:i.string().min(1).max(80),amountMinor:i.number().int().min(0).max(1e8),currency:i.string().regex(/^[a-z]{3}$/),interval:i.enum(["week","month","year","one_off"]),intervalCount:i.number().int().min(1).max(52),slot:i.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:i.strictObject({mode:i.enum(["graduated","volume"]),tiers:i.array(i.strictObject({upTo:i.number().int().min(1).max(1e6).nullable(),unitAmountMinor:i.number().int().min(0).max(1e8),flatAmountMinor:i.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:i.array(i.strictObject({coupon:Cc,terms:sd})).max(1),trialPeriodDays:i.number().int().min(1).max(730).nullable(),metadata:i.strictObject({grooveCheckoutId:i.uuid(),grooveCustomerId:i.uuid()}),expiresAt:i.iso.datetime({offset:!0})}),ln=i.strictObject({operationId:i.uuid(),entityId:i.uuid().nullable(),billingSubscriptionId:i.uuid().nullable(),discount:i.strictObject({offerId:i.uuid(),couponId:i.uuid(),discount:At,duration:He,amountMinor:Re,allocations:i.array(i.strictObject({productVersionId:i.uuid(),amountMinor:Re})).min(1).max(20),expiresAt:i.iso.datetime({offset:!0})}).nullable(),charge:i.strictObject({effectiveAt:i.iso.datetime({offset:!0}),periodEndsAt:i.iso.datetime({offset:!0}),debitMinor:Re,discountMinor:Re,taxMinor:Re,totalMinor:Re}).nullable(),expiresAt:i.iso.datetime({offset:!0}),provider:i.enum(["stripe","apple","google","merchant"]),nativeOffer:un.optional(),currency:oe,lines:i.array(ad).min(1).max(20),catalogAmountMinor:Re,automaticTax:i.boolean(),execution:i.union([kc,dr]).nullable()}).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),mn=i.strictObject({operationId:i.uuid(),orderId:i.uuid(),append:i.boolean().optional(),invoiceMode:i.boolean().optional(),status:i.enum(["pending","complete","cancelled","failed"]),executor:i.enum(["indiana","merchant"]),checkoutUrl:i.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:i.union([kc,dr]).nullable(),currency:oe,catalogAmountMinor:Re,taxMinor:Re,totalMinor:i.number().int().min(0).max(2e8).nullable(),quoteFinalized:i.boolean(),nativePurchase:Hi.nullable(),confirmedAt:i.iso.datetime({offset:!0}).nullable().optional(),quote:ln.optional(),merchantExecution:Mt.nullable().optional(),problem:kn.nullable().optional(),authority:yr.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),zr=i.strictObject({enabled:i.literal(!0),featureIds:i.array(i.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Rc=i.strictObject({requestId:i.uuid(),invoiceMode:qt.optional(),membershipId:i.uuid(),carryOverBalances:zr.optional(),carryOverUsages:zr.optional(),membershipIds:i.array(i.uuid()).min(1).max(20).optional(),prorationBehavior:i.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:i.enum(["immediate","renewal","store"]),change:i.discriminatedUnion("type",[i.strictObject({type:i.literal("plan"),productVersionId:i.uuid()}),i.strictObject({type:i.literal("seats"),licenseKey:wr,quantity:i.number().int().min(0).max(1e4)}),i.strictObject({type:i.literal("quantity"),internal_feature_id:i.uuid(),quantity:i.number().int().min(0).max(1e4)}),i.strictObject({type:i.literal("cancel")}),i.strictObject({type:i.literal("uncancel")}),i.strictObject({type:i.literal("billing_cycle"),billingCycleAnchor:i.union([i.literal("now"),i.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"),Dr=i.string().regex(/^price_[A-Za-z0-9]+$/),wc=i.strictObject({grooveUpdateId:i.uuid(),grooveCustomerId:i.uuid()}),_c=i.strictObject({price:Dr.nullable(),priceId:i.uuid().optional(),quantity:i.number().int().min(0).max(1e4)}),Ec=i.strictObject({provider:i.literal("stripe"),invoiceMode:qt.optional(),executor:i.enum(["indiana","merchant"]),accountId:i.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:i.string().regex(/^sub_[A-Za-z0-9]+$/),action:i.enum(["update","cancel","schedule","release"]),update:i.strictObject({items:i.array(_c).max(20),remove:i.array(Dr).max(20),restoreItems:i.array(i.strictObject({price:Dr,quantity:i.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:i.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:i.number().int().positive().optional(),paymentBehavior:i.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:i.boolean().optional(),clearCancelAt:i.literal(!0).optional(),billingCycleAnchorNow:i.literal(!0).optional(),metadata:wc}).nullable(),cancel:i.strictObject({prorate:i.literal(!1),invoiceNow:i.literal(!1)}).nullable(),schedule:i.strictObject({currentItems:i.array(i.strictObject({price:Dr,quantity:i.number().int().min(0).max(1e4)})).max(20),nextItems:i.array(_c).min(1).max(20),switchAt:i.number().int().positive(),interval:i.enum(["week","month","year"]),intervalCount:i.number().int().min(1).max(52),resetBillingCycleAnchor:i.literal(!0).optional(),metadata:wc}).nullable(),release:i.strictObject({schedule:i.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:i.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"),Br=i.strictObject({carryOverBalances:zr.optional(),carryOverUsages:zr.optional(),operationId:i.uuid(),membershipId:i.uuid(),productVersionId:i.uuid(),timing:i.enum(["immediate","renewal"]),effectiveAt:i.iso.datetime({offset:!0}),expiresAt:i.iso.datetime({offset:!0}),currency:oe,creditMinor:Re,debitMinor:Re,discountMinor:Re,taxMinor:Re,totalMinor:Re,retainedProductVersionIds:i.array(i.uuid()).max(19),execution:i.union([Ec,fr])}),ud=i.strictObject({operationId:i.uuid(),invoiceMode:i.boolean().optional(),membershipId:i.uuid(),productVersionId:i.uuid(),status:i.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:i.enum(["immediate","renewal"]),effectiveAt:i.iso.datetime({offset:!0}),checkoutUrl:i.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:i.enum(["indiana","merchant"]),execution:i.union([Ec,fr]).nullable(),confirmedAt:i.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Mt.nullable().optional(),problem:kn.nullable().optional(),quote:Br.optional(),authority:yr.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),pd=i.strictObject({operationId:i.uuid(),membershipId:i.uuid(),productVersionId:i.uuid(),timing:i.literal("store"),effectiveAt:i.null(),expiresAt:i.iso.datetime({offset:!0}),currency:oe,creditMinor:i.null(),debitMinor:i.null(),discountMinor:i.null(),taxMinor:i.null(),totalMinor:i.null(),retainedProductVersionIds:i.array(i.uuid()).max(19),store:i.strictObject({provider:i.enum(["apple","google"]),productId:i.string().min(1).max(255),catalogAmountMinor:Re,policy:i.enum(["apple_store","google_full_price"])})}),ld=i.strictObject({operationId:i.uuid(),membershipId:i.uuid(),productVersionId:i.uuid(),status:i.enum(["prepared","pending","effective","cancelled","failed"]),timing:i.literal("store"),effectiveAt:i.iso.datetime({offset:!0}).nullable(),checkoutUrl:i.null(),nativePurchase:Hi.nullable()}),Mc=i.union([Br,pd]),Wi=i.union([ud,ld]),Un=i.number().int().positive().max(2e8),Ft=i.number().int().min(0).max(2e8),Tc=i.strictObject({requestId:i.uuid(),invoiceId:i.uuid(),mode:i.enum(["full","partial"]),amountMinor:Un.optional(),entitlementAction:i.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Dc=i.strictObject({provider:i.literal("stripe"),executor:i.enum(["indiana","merchant"]),accountId:i.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:i.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Un,currency:i.string().regex(/^[a-z]{3}$/),metadata:i.strictObject({indianaRefundId:i.uuid()}),idempotencyKey:i.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:i.array(i.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Qi=i.strictObject({operationId:i.uuid(),invoiceId:i.uuid(),providerInvoiceId:i.string().min(1).max(200),currency:oe,paidMinor:Ft,refundedMinor:Ft,pendingMinor:Ft,amountMinor:Un,mode:i.enum(["full","partial"]),entitlementAction:i.enum(["retain","revoke"]),revokes:i.strictObject({customerProductIds:i.array(i.uuid()).max(100),subscriptionIds:i.array(i.string().min(1).max(200)).max(20)}),execution:i.union([Dc,gr]),expiresAt:i.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),qr=i.strictObject({operationId:i.uuid(),invoiceId:i.uuid(),providerInvoiceId:i.string().min(1).max(200),status:i.enum(["quoted","pending","succeeded","failed","expired"]),executor:i.enum(["indiana","merchant"]),currency:oe,amountMinor:Un,mode:i.enum(["full","partial"]),entitlementAction:i.enum(["retain","revoke"]),refundId:i.string().min(1).max(200).nullable(),quote:Qi.optional(),execution:i.union([Dc,gr]).nullable(),confirmedAt:i.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Mt.nullable().optional(),problem:kn.nullable().optional(),authority:yr.optional(),failureReason:i.string().min(1).max(200).nullable(),createdAt:i.iso.datetime({offset:!0}),completedAt:i.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"),Oy=i.strictObject({invoiceId:i.uuid(),currency:oe,paidMinor:Ft,refundedMinor:Ft,pendingMinor:Ft,refundableMinor:Ft,executor:i.enum(["indiana","merchant"]).nullable(),canRefund:i.boolean(),operations:i.array(qr).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),jy=i.strictObject({requestId:i.uuid(),mode:i.enum(["full","partial"]),amountMinor:Un.optional(),entitlementAction:i.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 zc=xe.strictObject({requestId:xe.uuid(),targets:xe.array(xe.strictObject({membershipId:xe.uuid(),action:xe.enum(["cancel","uncancel"]),timing:xe.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"),Fr=xe.strictObject({batchId:xe.uuid()}),md=xe.strictObject({operationId:xe.uuid(),membershipIds:xe.array(xe.uuid()).min(1).max(20),provider:xe.enum(["stripe","apple","google"]),action:xe.enum(["cancel","uncancel"]),timing:xe.enum(["immediate","renewal"]),status:xe.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Br.nullable(),managementUrl:xe.url().nullable(),failureCode:xe.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Vn=xe.strictObject({batchId:xe.uuid(),ready:xe.boolean(),status:xe.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:xe.iso.datetime({offset:!0}),acceptedAt:xe.iso.datetime({offset:!0}).nullable(),groups:xe.array(md).min(1).max(100)});import{z as ne}from"zod";var dd=ne.string().trim().min(1).max(240),Xi={requestId:ne.uuid(),reason:dd},Nr=ne.discriminatedUnion("action",[ne.strictObject({...Xi,action:ne.literal("start"),productVersionId:ne.uuid(),entityId:ne.uuid().optional(),days:ne.number().int().min(1).max(730).optional()}),ne.strictObject({...Xi,action:ne.literal("extend"),membershipId:ne.uuid(),days:ne.number().int().min(1).max(730)}),ne.strictObject({...Xi,action:ne.literal("end"),membershipId:ne.uuid()})]),Bc=ne.strictObject({operationId:ne.uuid()}),qc=ne.iso.datetime({offset:!0}),fd=ne.strictObject({provider:ne.literal("stripe"),executor:ne.enum(["indiana","merchant"]),accountId:ne.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:ne.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:ne.union([ne.literal("now"),qc]),prorationBehavior:ne.literal("none")}),Yi=ne.strictObject({operationId:ne.uuid(),action:ne.enum(["start","extend","end"]),status:ne.enum(["pending","effective"]),managedBy:ne.enum(["indiana","stripe"]),membershipIds:ne.array(ne.uuid()).min(1).max(20),endsAt:qc.nullable(),execution:fd.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"),ky=ne.strictObject({groupId:ne.uuid(),productVersionId:ne.uuid(),enabled:ne.boolean()});import{z as de}from"zod";var Fc=de.strictObject({requestId:de.uuid(),currency:oe,makeDefault:de.boolean()}),Nc=de.strictObject({setupId:de.uuid()}),gd=de.strictObject({provider:de.literal("stripe"),executor:de.literal("merchant"),accountId:de.string().regex(/^acct_[A-Za-z0-9]+$/),mode:de.literal("setup"),currency:de.string().regex(/^[a-z]{3}$/),customer:de.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:de.uuid(),metadata:de.strictObject({grooveProjectId:de.uuid(),grooveEnvironmentId:de.uuid(),grooveCustomerId:de.uuid(),groovePaymentSetupId:de.uuid()}),setDefaultPaymentMethod:de.boolean(),expiresAt:de.iso.datetime({offset:!0})}),eo=de.strictObject({id:de.uuid(),provider:de.literal("stripe"),status:de.enum(["prepared","complete","expired"]),currency:oe,makeDefault:de.boolean(),url:de.url().nullable(),createdAt:de.iso.datetime({offset:!0}),expiresAt:de.iso.datetime({offset:!0}),completedAt:de.iso.datetime({offset:!0}).nullable(),execution:gd.nullable()});import{z as Ee}from"zod";var Uc=Ee.union([Ee.string(),Ee.number(),Ee.boolean(),Ee.null()]),Vc=Ee.strictObject({customerId:Ee.uuid()}),$c=Ee.strictObject({customerId:Ee.uuid(),provider:Ee.literal("stripe"),checkedAt:Ee.iso.datetime({offset:!0}),status:Ee.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ee.number().int().nonnegative(),differences:Ee.array(Ee.strictObject({subscriptionId:Ee.string().startsWith("sub_"),itemId:Ee.string().nullable(),field:Ee.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Uc,actual:Uc})).max(1e4)});import{z as J}from"zod";var Ur=J.iso.datetime({offset:!0}),Vr=J.strictObject({createdAt:Ur,id:J.uuid()}),$r=J.strictObject({customerId:J.uuid().optional(),entityId:J.uuid().optional(),productId:J.string().min(1).max(256).optional(),provider:J.enum(["stripe","apple","google","merchant","free"]).optional(),status:J.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Vr.optional(),limit:J.number().int().min(1).max(100).optional()}),to={id:J.uuid(),customerId:J.uuid(),entityId:J.uuid().nullable(),productId:J.string().min(1).max(256),productVersionId:J.uuid(),name:J.string().min(1).max(120),provider:J.enum(["stripe","apple","google","merchant","free"]),createdAt:Ur},hd=J.strictObject({...to,status:J.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:J.boolean(),billingSubscriptionId:J.uuid().nullable()}),bd=J.strictObject({...to,status:J.enum(["active","ended","refunded"]),orderId:J.uuid().nullable(),transactionId:J.uuid().nullable(),currency:oe.nullable(),amountMinor:J.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),yd=J.strictObject({...to,status:J.enum(["blocked","resolved"]),conflict:J.strictObject({detectedAt:Ur,blockingMembershipIds:J.array(J.uuid()).min(1).max(100),transactionId:J.uuid()}),resolvedAt:Ur.nullable()}),Gc=$r.extend({status:J.enum(["blocked","resolved"]).optional()}),Kc=J.strictObject({customerId:J.uuid(),orderId:J.uuid()}),Lc=J.strictObject({orderId:J.uuid(),status:J.enum(["blocked","resolved"])}),Zc=J.strictObject({items:J.array(hd).max(100),nextCursor:Vr.nullable()}),Hc=J.strictObject({items:J.array(bd).max(100),nextCursor:Vr.nullable()}),Jc=J.strictObject({items:J.array(yd).max(100),nextCursor:Vr.nullable()});import{z as he}from"zod";var Wc=he.union([he.strictObject({intent:he.literal("read"),requestId:he.uuid(),purchaseIntentId:he.uuid()}),he.strictObject({requestId:he.uuid(),provider:he.literal("apple"),purchaseIntentId:he.uuid(),productId:he.string().min(1).max(255).optional(),signedTransaction:he.string().min(1).max(131072)}),he.strictObject({requestId:he.uuid(),provider:he.literal("google"),purchaseIntentId:he.uuid(),productId:he.string().min(1).max(255).optional(),purchaseToken:he.string().min(1).max(16384)})]),Qc=he.strictObject({requestId:he.uuid(),orderId:he.uuid(),purchaseIntentId:he.uuid(),status:he.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:oe,refunded:he.boolean(),completion:he.strictObject({transactionIds:he.array(he.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:he.boolean()}).nullable()});import{z as O}from"zod";var ro=O.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),xd=O.record(O.string(),O.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),Sd=3,$n=20,vd=Sd*$n,no=O.strictObject({type:O.literal("product"),productId:ro}),Xc={type:O.literal("group"),key:O.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:O.string().trim().min(1).max(80)},Id=O.discriminatedUnion("type",[no,O.strictObject({...Xc,items:O.array(no).max($n)})]),Od=O.discriminatedUnion("type",[no,O.strictObject({...Xc,items:O.array(Id).max($n)})]),jd=O.array(Od).max($n).superRefine((e,t)=>{let n=new Set,r=new Set,o=0;function a(l){for(let p of l){o++;let d=p.type==="product"?n:r,v=p.type==="product"?p.productId:p.key;d.has(v)&&t.addIssue({code:"custom",message:p.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),d.add(v),p.type==="group"&&a(p.items)}}a(e),(n.size>$n||o>vd)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function io(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:io(t))}var dn=O.strictObject({lookupKey:O.string().trim().min(1).max(200),displayName:O.string().trim().min(1).max(1500),items:jd,metadata:xd}),Ad=O.strictObject({product:O.record(O.string(),O.json()),prices:O.array(O.record(O.string(),O.json())),entitlements:O.array(O.record(O.string(),O.json())),freeTrials:O.array(O.record(O.string(),O.json())),licenses:O.array(O.record(O.string(),O.json()))}),Yc=dn.extend({id:O.uuid(),projectId:O.uuid(),environmentId:O.uuid(),state:O.enum(["active","archived"]),isCurrent:O.boolean(),revision:O.number().int().nonnegative(),publishedVersionId:O.uuid().nullable(),createdAt:O.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"})}),eu=O.strictObject({id:O.uuid(),offeringId:O.uuid(),projectId:O.uuid(),environmentId:O.uuid(),version:O.number().int().positive(),document:dn,productEvidence:O.record(ro,Ad),createdAt:O.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=io(e.document);(!n.length||Pd(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),wd=O.strictObject({rows:O.array(Yc).max(200),versions:O.array(eu).max(500)}),Gy=O.discriminatedUnion("action",[O.strictObject({action:O.literal("create"),document:dn}),O.strictObject({action:O.literal("save"),id:O.uuid(),revision:O.number().int().nonnegative(),document:dn}),O.strictObject({action:O.enum(["publish","set_current","archive","restore"]),id:O.uuid(),revision:O.number().int().nonnegative()})]),Ky=O.strictObject({record:Yc,version:eu.nullable()}),tu=O.discriminatedUnion("type",[O.strictObject({type:O.literal("current")}),O.strictObject({type:O.literal("id"),id:O.uuid()}),O.strictObject({type:O.literal("lookup_key"),lookupKey:O.string().min(1).max(200)}),O.strictObject({type:O.literal("version"),versionId:O.uuid()})]),_d=O.strictObject({internalId:ro,id:O.string(),name:O.string().nullable(),version:O.number().int().positive(),archived:O.boolean()}),Ly=wd.extend({products:O.array(_d).max(500),pagination:O.strictObject({rows:O.string().nullable(),versions:O.string().nullable(),products:O.string().nullable()}).optional()});function Pd(e){let t=[];io(e).length||t.push("Select at least one Product before publishing");function n(r){for(let o of r)o.type==="group"&&(o.items.length||t.push("Every published group requires a Product"),n(o.items))}return n(e.items),t}import{z as Gr}from"zod";var nu=Gr.strictObject({id:Gr.uuid(),offeringId:Gr.uuid(),version:Gr.number().int().positive(),document:dn});import{z as _e}from"zod";import{z as V}from"zod";var oo=V.discriminatedUnion("type",[V.strictObject({type:V.literal("event"),event:V.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),V.strictObject({type:V.literal("open_url"),url:V.url().refine(e=>new URL(e).protocol==="https:")})]),Cd=Le,kd=V.discriminatedUnion("type",[V.object({type:V.literal("checkout"),product:pr}).strict(),V.object({type:V.literal("close")}).strict(),V.object({type:V.literal("action"),action:oo}).strict()]),fn=V.object({schemaVersion:V.literal(3),kind:V.literal("paywall"),name:V.string().trim().min(1).max(80),presentation:gt,requirement:Qt.optional(),products:Ir,offeringVersionId:V.uuid().nullable(),offeringId:V.uuid(),screen:Cd,buttons:V.record(V.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),kd)}).strict(),ix=fn.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of Ed(e))t.addIssue({code:"custom",message:r});for(let r of Rd(e))t.addIssue({code:"custom",message:r});It(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function Rd(e){let t=e.products.items.map(a=>a.productVersionId),n=Ma(e.screen),r=new Set,o=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&o.push("products"),e.offeringVersionId||o.push("offering"),e.products.grouping&&(!Da(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(l=>l.tierId===a.id)))&&o.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let l=a.product;if(l.type==="fixed")r.add(l.productVersionId);else{l.allowedProductVersionIds.forEach(v=>r.add(v));let p=!1,d=n[l.pickerId];d&&(p=!0,(l.allowedProductVersionIds.some(v=>!d.ids.includes(v))||d.ids.some(v=>!l.allowedProductVersionIds.includes(v)))&&o.push("picker")),ht(e.screen,v=>{if(v.id!==l.pickerId||v.type!=="plan_picker")return;p=!0,(JSON.stringify(v.planIds)!==JSON.stringify(t)||JSON.stringify(l.allowedProductVersionIds)!==JSON.stringify(t)||v.defaultPlan!==e.products.defaultProductVersionId)&&o.push("picker");let h=v.grouping?{tiers:v.grouping.tiers,assignments:v.grouping.assignments}:void 0;JSON.stringify(h)!==JSON.stringify(e.products.grouping)&&o.push("grouping")}),p||o.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&o.push("purchase"),ht(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&o.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&o.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(l=>!t.includes(l)))&&o.push("binding")}),[...new Set(o)]}function Ed(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let p of e.screen.pages)r.set(p.id,[]),Yt(p.root,d=>{let v=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(v){let h=e.screen.actions.find($=>$.id===v);h?.type==="navigate"&&r.get(p.id).push(h.pageId);let T=e.buttons[v];p.id!==n.id&&T&&T.type!=="close"&&t.push(`purchaseScreen:${d.id}`)}p.id!==n.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&t.push(`packageScreen:${d.id}`)});let o=new Set;function a(p){if(!o.has(p)){o.add(p);for(let d of r.get(p)??[])a(d)}}let l=e.screen.initialPageId??e.screen.pages[0]?.id;l?a(l):t.push("initialPage");for(let p of e.screen.pages)o.has(p.id)||t.push(`unreachableScreen:${p.id}`);return[...new Set(t)]}var ru=V.object({id:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),revision:V.number().int().nonnegative(),state:V.enum(["active","archived"]),publishedVersionId:V.uuid().nullable(),updatedAt:V.iso.datetime({offset:!0}),draft:fn}).strict(),ox=V.object({rows:V.array(ru).max(200),nextCursor:V.uuid().nullable()}).strict(),ax=ru.omit({draft:!0}).extend({name:V.string(),productCount:V.number().int().nonnegative()}).strict(),sx=V.discriminatedUnion("action",[V.object({action:V.literal("save"),id:V.uuid().nullable(),revision:V.number().int().nonnegative(),document:fn}).strict(),V.object({action:V.enum(["publish","archive"]),id:V.uuid(),revision:V.number().int().nonnegative()}).strict()]),cx=V.object({paywalls:V.array(V.object({id:V.uuid(),paywallId:V.uuid(),version:V.number().int().positive(),name:V.string().min(1).max(80),presentation:gt,buttons:fn.shape.buttons}).strict()).max(500),limited:V.boolean()}).strict();import{z as Y}from"zod";import{z as Fe}from"zod";var gn=Fe.string().regex(/^[a-f0-9]{64}$/),Md=Ra.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),iu=Fe.strictObject({couponDigests:Fe.record(Fe.uuid(),gn),variables:Fe.record(Jt,Fe.record(Fe.uuid(),Fe.partialRecord(Fe.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Fe.string()))),locales:Fe.record(Jt,Xt.extend({nodes:Fe.record(Fe.string(),Fe.strictObject({base:Md})),plans:Fe.object({}).strict(),pickers:Fe.object({}).strict()}).omit({paywall:!0}))});import{z as ce}from"zod";import{z as Kr}from"zod";var ao=Kr.strictObject({eventsEnabled:Kr.boolean(),experimentViewsEnabled:Kr.boolean(),featureUsageEnabled:Kr.boolean()}),gx=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function hx(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as w}from"zod";var so=w.tuple([w.number().min(0).max(1),w.number().min(0).max(1)]).refine(([e,t])=>e<=t),Td=w.strictObject({attribute:w.string().optional(),seed:w.string(),hashVersion:w.literal(2),ranges:w.array(so).max(100)}),Dd=w.strictObject({id:w.string().min(1).max(255),condition:it,gate:w.boolean().optional()}),zd=w.strictObject({key:w.string().optional(),name:w.string().optional(),passthrough:w.boolean().optional()}),ou={condition:it.optional(),parentConditions:w.array(Dd).max(100).optional(),weights:w.array(w.number().min(0).max(1)).max(20).optional(),coverage:w.number().min(0).max(1).optional(),hashAttribute:w.string().optional(),fallbackAttribute:w.string().optional(),hashVersion:w.literal(2).optional(),disableStickyBucketing:w.boolean().optional(),bucketVersion:w.number().int().nonnegative().optional(),minBucketVersion:w.number().int().nonnegative().optional(),filters:w.array(Td).max(100).optional(),ranges:w.array(so).max(20).optional(),meta:w.array(zd).max(20).optional(),seed:w.string().optional(),name:w.string().optional(),phase:w.string().optional()},hn=w.strictObject({...ou,key:w.string().min(1).max(255),variations:w.tuple([te,te]).rest(te).refine(e=>e.length<=20),urlPatterns:w.array(w.strictObject({include:w.boolean(),type:w.enum(["regex","simple"]),pattern:w.string()})).max(100).optional(),force:w.number().int().nonnegative().optional(),active:w.boolean().optional(),persistQueryString:w.boolean().optional()}),co=w.strictObject({value:te,variationId:w.number().int(),key:w.string(),name:w.string().optional(),bucket:w.number().optional(),passthrough:w.boolean().optional(),inExperiment:w.boolean(),hashUsed:w.boolean().optional(),hashAttribute:w.string(),hashValue:w.string(),featureId:w.string().nullable(),stickyBucketUsed:w.boolean().optional()}),Bd=w.strictObject({...ou,id:w.string().max(255).optional(),force:te.optional(),variations:w.array(te).min(2).max(20).optional(),key:w.string().optional(),range:so.optional(),tracks:w.array(w.strictObject({experiment:hn,result:co})).max(100).optional()}),qd=w.strictObject({defaultValue:te.optional(),rules:w.array(Bd).max(500).optional()}),Gn=w.record(w.string(),w.union([w.strictObject({type:w.literal("hashed"),attributeKey:w.string(),values:w.array(w.string().regex(/^[a-f0-9]{64}$/))}),w.strictObject({type:w.literal("list"),attributeKey:w.string(),values:w.array(w.union([w.string(),w.number()]))}),w.strictObject({type:w.literal("condition"),condition:it})])),_t=w.strictObject({scope:me,generation:w.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:w.iso.datetime({offset:!0}),expiresAt:w.iso.datetime({offset:!0}).nullable(),features:w.record(w.string(),qd),savedGroups:Gn,experiments:w.record(w.uuid(),hn)});var uo=_t.extend({analyticsConfig:ao,remoteFeatures:ce.array(ce.string().min(1).max(255)).max(500)}),Fd=uo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),au=ce.strictObject({attributes:Ke,features:ce.array(ce.string().min(1).max(255)).max(500).optional(),customerId:ce.uuid().optional()}),Nd=ce.strictObject({value:te,source:ce.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ce.boolean(),off:ce.boolean(),ruleId:ce.string(),experimentResult:co.optional()}),su=ce.strictObject({generation:_t.shape.generation,evaluatedAt:_t.shape.evaluatedAt,expiresAt:_t.shape.expiresAt,features:ce.record(ce.string(),Nd),merchandiseContext:ce.strictObject({merchandiseId:ce.uuid(),merchandise:Ke}).optional()}),cu=ce.strictObject({customerId:ce.uuid().optional(),events:ce.array(ce.strictObject({eventUuid:ce.uuid(),timestamp:ce.iso.datetime({offset:!0}),name:ce.string().min(1).max(255),merchandise:Ss.optional(),properties:ce.record(ce.string(),te).default({}),deviceId:ce.string().min(1).max(255).optional(),sessionId:ce.string().min(1).max(255).optional()})).min(1).max(100)}),uu=ce.strictObject({inserted:ce.number().int().nonnegative(),duplicates:ce.number().int().nonnegative(),rejected:ce.number().int().nonnegative(),skipped:ce.number().int().nonnegative(),analyticsConfig:ao});import{z as j}from"zod";import{z as Ud}from"zod";var po=Ud.enum(["funnel-run/1","funnel-process/1"]),lo="funnel-process/1";function mo(e,t=[]){let n=[];ht(e,o=>{o.hidden&&n.push("Hidden components must not be delivered"),t.includes(o.type)&&n.push(`Node type ${o.type} cannot be delivered`)});let r=new Set(gi(e).map(o=>o.key));for(let[o,a]of Object.entries(e.strings.locales))for(let l of Object.keys(a))r.has(l)||n.push(`Unused string ${l} must not be delivered (${o})`);return n}function pu(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>pu(t)??[])}}function Vd(e){let t=e.pages.map(o=>{let a=pu(o.root);return a?.type==="stack"?{...o,root:a}:{...o,root:{type:"stack",id:o.root.id,...o.root.name===void 0?{}:{name:o.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(gi({pages:t}).map(o=>o.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([o,a])=>[o,Object.fromEntries(Object.entries(a).filter(([l])=>n.has(l)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function lu(e,t=[]){let n=Le.parse(structuredClone(Vd(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let o=mo(n,t);if(o.length)throw new Error(o.join("; "));return n}import{z as P}from"zod";import{z as x}from"zod";import{z as Ie}from"zod";var Lr=Ie.strictObject({schemaVersion:Ie.literal(1),renderKey:Ie.string().min(1).max(256),routeTemplate:Ie.string().startsWith("/").max(2048),selectors:Ie.array(Ie.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:Ie.array(Ie.number().int().min(0)).min(1),absent:Ie.array(Ie.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),mu=Ie.strictObject({renderKey:Ie.string().min(1).max(256),routeKey:Ie.string().min(1).max(256),stateKey:Ie.string().min(1).max(256),documentKey:Ie.string().min(1).max(256),documentHash:Ie.string().regex(/^[a-f0-9]{64}$/),compositionKey:Ie.string().min(1).max(256),entryMode:Ie.enum(["hard","soft"]),match:Ie.strictObject({present:Ie.array(Ie.number().int().min(0)),absent:Ie.array(Ie.number().int().min(0))})});import{z as Ut}from"zod";var $d=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],fo="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Gd=Ut.string().regex(new RegExp(`^${fo}/${fo}/${fo}/manifest\\.json$`)),du=Ut.strictObject({kind:Ut.literal("gcs-resumable"),url:Ut.url(),bucket:Ut.enum($d),objectKey:Gd,byteLength:Ut.number().int().positive(),expiresAt:Ut.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,o=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!o.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var Oe=x.string().min(1).max(256),Je=x.string().regex(/^[a-f0-9]{64}$/),Zr=x.strictObject({versionId:x.uuid(),manifestDigest:Je,sourceGraphDigest:Je,pageKey:Oe,stateKey:Oe,documentKey:Oe,documentHash:Je,elementKey:Oe.optional(),nodeId:Oe.optional(),contentHash:Je.optional(),renderKey:Oe.optional()}),fu=x.strictObject({pageKey:Oe,documentKey:Oe,expectedDocumentHash:Je,renderKey:Oe.optional(),nodeId:Oe,elementKey:Oe,expectedContentHash:Je,property:x.enum(["text","fontSize","color"]),value:x.union([x.string().max(4e3),x.number().finite()])}),gu=x.strictObject({versionId:x.uuid(),manifestDigest:Je,sourceGraphDigest:Je,pageKey:Oe,stateKey:Oe,documentKey:Oe,documentHash:Je,renderKey:Oe.optional(),patches:x.array(fu.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),Kd=/^[a-z][a-z0-9-]{0,39}$/,Kn=x.string().regex(Kd),ho=x.enum(["web","ios","android"]),Fx=x.discriminatedUnion("action",[x.strictObject({action:x.literal("register"),requestId:x.uuid(),client:Kn,platform:ho,label:x.string().trim().min(1).max(100),sha256:Je,bytes:x.number().int().min(1),transferBytes:x.number().int().min(1)}),x.strictObject({action:x.literal("complete"),versionId:x.uuid()}),x.strictObject({action:x.literal("current"),versionId:x.uuid(),expectedCurrent:x.uuid().nullable()}),x.strictObject({action:x.literal("delivery"),enabled:x.boolean()}),x.strictObject({action:x.literal("changes"),versionId:x.uuid(),experimentId:x.uuid(),variationId:Oe,changesetId:x.uuid().nullable(),expectedRevision:Je.nullable(),editorUrl:x.string().url().max(2048),patches:x.array(fu).max(200)})]),bo=x.strictObject({id:x.uuid(),projectId:x.uuid(),environmentId:x.uuid(),clientKey:Kn,platform:ho,label:x.string(),sha256:Je,bytes:x.number().int().positive(),objectKey:x.string(),state:x.enum(["uploading","ready","rejected"]),isCurrent:x.boolean(),revision:x.number().int().nonnegative(),createdAt:x.string(),expiresAt:x.string(),readyAt:x.string().nullable(),summary:x.record(x.string(),x.json()),routeTree:x.json().nullable(),validation:x.record(x.string(),x.json())}),Ld=x.strictObject({key:Kn,platform:ho,currentId:x.uuid().nullable()}),Nx=x.strictObject({rows:x.array(bo).max(100),nextCursor:x.uuid().nullable(),clients:x.array(Ld).max(20)}),go=x.strictObject({storedBytes:x.number().int().nonnegative(),reservedBytes:x.number().int().nonnegative(),chargedBytes:x.number().int().nonnegative(),versions:x.number().int().nonnegative(),objects:x.number().int().nonnegative(),orphanObjects:x.number().int().nonnegative(),missingReadyObjects:x.number().int().nonnegative(),unknownObjectSizes:x.number().int().nonnegative(),byteLimit:x.number().int().positive(),versionLimit:x.number().int().positive(),remainingBytes:x.number().int().nonnegative()}),Ux=x.strictObject({asOf:x.iso.datetime({offset:!0}),reclamation:x.literal("manual-review-required"),buckets:x.strictObject({source:go,runtime:go,previews:go})}),Vx=x.strictObject({version:bo,actorId:x.uuid(),claims:x.record(x.string(),x.json())}),$x=x.strictObject({version:bo,upload:du.nullable()}),Gx=x.object({format:x.literal("indiana-route-state-index"),schemaVersion:x.literal(3),routes:x.array(x.object({routeKey:Oe,path:x.string(),documentKey:Oe,documentHash:Je,initialStateKey:Oe,initialRenderKey:Oe})),renders:x.array(mu)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),Kx=x.strictObject({rows:x.array(x.object({id:x.uuid(),name:x.string(),status:x.string(),variations:x.array(x.object({id:Oe,key:Oe,name:x.string().optional()}).loose())}).loose()),limited:x.boolean()}),Lx=x.strictObject({enabled:x.boolean(),allowedOrigins:x.array(x.string())});import{z as bn}from"zod";var hu=bn.strictObject({id:bn.uuid(),name:bn.string().trim().min(1).max(80),client:Kn,source:Zr,event:bn.enum(["screen_enter","button_click"]),cooldownSeconds:bn.number().int().min(0).max(2592e3),behavior:bn.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as pe}from"zod";var yo=te,Zd=["parameters","answers","results","variables"];function xo(e){return Zd.some(t=>e===t||e.startsWith(t+"."))}function So(e){let t={};for(let[r,o]of Object.entries(En(e.declarations,e))){let a=r.split(".");if(a.some(d=>["__proto__","constructor","prototype"].includes(d)))throw new Error("Reserved result path");let l=t;for(let d of a.slice(0,-1)){Object.hasOwn(l,d)||(l[d]={});let v=l[d];if(!v||typeof v!="object"||Array.isArray(v))throw new Error("Ambiguous result path");l=v}let p=a.at(-1);if(p===void 0)throw new Error("Empty result path");l[p]=o}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!xo(r))),variables:t}}import{z as Hd}from"zod";var Hr=Hd.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var vo=pe.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),bu=pe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),yu=ut.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Io=pe.record(vo,pe.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),Jd=lt,xu=pe.strictObject({type:pe.literal("external_task"),endpointId:pe.uuid(),taskKey:vo,inputs:pe.record(vo,Jd).refine(e=>Object.keys(e).length<=20),outputs:Io}),Su=pe.strictObject({maxAttempts:pe.number().int().min(1).max(5),retryDelaySeconds:pe.number().int().min(1).max(30),backoff:pe.enum(["fixed","exponential"]),requestTimeoutSeconds:pe.number().int().min(1).max(10),timeoutSeconds:pe.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var uS=pe.strictObject({outcome:pe.enum(["success","failure"]),data:yu});var pS=pe.discriminatedUnion("operation",[pe.strictObject({operation:pe.literal("signal"),runId:pe.uuid(),nodeId:bu,eventName:Hr,eventId:pe.uuid(),data:yu}),pe.strictObject({operation:pe.literal("read_results"),runId:pe.uuid()})]),lS=pe.strictObject({scope:me,runId:pe.uuid(),eventId:pe.uuid(),accepted:pe.boolean()}),Wd=pe.record(bu,yo),mS=pe.strictObject({scope:me,runId:pe.uuid(),results:Wd});var at={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},vu="00000000-0000-0000-0000-000000000000";import{z as k}from"zod";import{z as fe}from"zod";var yS=fe.enum(["local","remote"]),Oo=fe.strictObject({port:fe.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:te.optional(),sticky:fe.array(fe.strictObject({expected:cr.nullable(),next:cr})).max(100),exposures:fe.array(te).max(100),features:fe.array(te).max(100)}),Iu=fe.strictObject({type:fe.literal("evaluate"),receiptId:fe.uuid(),environmentId:fe.uuid(),policyRevision:fe.number().int().nonnegative(),attributes:Ke,sticky:fe.record(fe.string(),cr)}),Ou=Iu.extend({runId:fe.uuid(),versionId:fe.uuid(),nodeId:fe.string().min(1).max(64),visit:fe.number().int().nonnegative(),revision:fe.number().int().nonnegative()}),jo=Iu.omit({type:!0,receiptId:!0}).extend({type:fe.literal("evaluate_segment")}),ju=fe.strictObject({nodeId:fe.string().min(1).max(64),result:Oo}),Au=jo.extend({runId:fe.uuid(),versionId:fe.uuid(),nodeId:fe.string().min(1).max(64),visit:fe.number().int().nonnegative(),revision:fe.number().int().nonnegative(),parameters:ut,answers:Et,variables:fe.record(fe.string(),te)});import{z as F}from"zod";var Ao=F.array(F.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),Jr=F.intersection(Ke,F.looseObject({tags:Ao.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Wr=F.string().trim().max(80),Qr=F.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Xr=F.union([F.email().max(254),F.literal("")]),Yr=F.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),wu=F.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),_u=F.object({externalUserId:wu.optional(),name:Wr.default(""),email:Xr.default(""),phone:Qr.optional(),attributes:Jr.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),xt=F.discriminatedUnion("type",[F.strictObject({type:F.literal("id"),value:F.uuid()}),F.strictObject({type:F.literal("externalUserId"),value:wu})]),Pt=F.strictObject({name:Wr.optional(),email:Xr.optional(),phone:Qr.optional(),attributes:Jr.optional(),fingerprint:Yr.optional()}),Vt=e=>!e.customerData||e.customer?.type==="externalUserId",$t="customerData requires an externalUserId customer",yn=F.object({id:F.uuid(),externalUserId:F.string().min(1).max(255).nullable(),name:Wr,email:Xr,phone:Qr.optional(),attributes:Jr,createdAt:F.iso.datetime()}).strict(),Pu=F.object({customer:yn,changed:F.boolean(),replayed:F.boolean()}).strict(),Qd=F.discriminatedUnion("type",[F.object({type:F.literal("id"),value:F.uuid()}).strict(),F.object({type:F.literal("externalUserId"),value:F.string().trim().min(1).max(255)}).strict()]),Xd=F.object({name:Wr.optional(),email:Xr.optional(),phone:Qr.optional(),attributes:Jr.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:F.array(F.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:F.strictObject({add:Ao,remove:Ao}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),wo=F.object({lookup:Qd}).strict(),Cu=wo.extend({requestId:F.uuid(),patch:Xd}).strict(),ku=F.object({search:F.string().trim().max(200).default(""),tag:F.string().trim().max(40).default(""),planId:F.string().max(200).default(""),versionId:F.string().max(200).default(""),holdingStatus:F.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:F.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:F.union([F.iso.datetime(),F.literal("")]).default(""),createdUntil:F.union([F.iso.datetime(),F.literal("")]).default(""),offset:F.coerce.number().int().min(0).max(1e5).default(0),limit:F.coerce.number().int().min(1).max(100).default(50)}).strict(),Ru=F.object({customers:yn.array(),hasMore:F.boolean(),total:F.number().int().nonnegative().nullable(),evaluatedAt:F.iso.datetime()}).strict();var Ln=k.discriminatedUnion("type",[k.strictObject({type:k.literal("literal"),value:te}),k.strictObject({type:k.literal("variable"),key:we,path:ot.optional()}),k.strictObject({type:k.literal("feature"),featureKey:k.string().min(1).max(128)})]),Yd=k.strictObject({requestId:k.uuid(),decisionId:k.uuid(),customerId:k.uuid(),externalUserId:k.string().min(1).max(255).nullable(),versionId:k.uuid(),receiptId:k.uuid(),value:te}),_o={funnelId:k.uuid(),requestId:k.uuid(),customer:xt,customerData:Pt.optional(),attributes:Ke.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},kS=k.discriminatedUnion("operation",[k.strictObject({operation:k.literal("decide"),..._o}).refine(Vt,$t),k.strictObject({operation:k.literal("read_decision"),decisionId:k.uuid()}),k.strictObject({operation:k.literal("evaluate_decision"),decisionId:k.uuid(),requestId:k.uuid(),nodeId:k.string().min(1).max(64),visit:k.number().int().nonnegative(),revision:k.number().int().nonnegative(),receiptId:k.uuid(),policyRevision:k.number().int().nonnegative(),generation:k.string().min(1).max(256),result:Oo}),k.strictObject({operation:k.literal("feature_config"),funnelId:k.uuid()}),k.strictObject({operation:k.literal("commit_decision_segment"),decisionId:k.uuid(),requestId:k.uuid(),nodeId:k.string().min(1).max(64),visit:k.number().int().nonnegative(),revision:k.number().int().nonnegative(),policyRevision:k.number().int().nonnegative(),generation:k.string().min(1).max(256),steps:k.array(ju).max(32),boundary:k.strictObject({nodeId:k.string().min(1).max(64),visit:k.number().int().nonnegative()}).optional()}),k.strictObject({operation:k.literal("segment_configuration"),funnelId:k.uuid(),versionId:k.uuid()}),k.strictObject({operation:k.literal("configuration"),funnelId:k.uuid(),versionId:k.uuid().optional()}),k.strictObject({operation:k.literal("local_configuration"),funnelId:k.uuid()}),k.strictObject({operation:k.literal("report_used"),decisionId:k.uuid(),eventId:k.uuid(),occurredAt:k.iso.datetime({offset:!0}),reference:k.string().min(1).max(128).optional()})]),RS=k.strictObject({scope:me,decisionId:k.uuid(),requestId:k.uuid(),status:k.enum(["pending","completed","failed"]),decision:Yd.nullable(),evaluation:k.discriminatedUnion("type",[Ou,Au]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),ES=k.strictObject({scope:me,decisionId:k.uuid(),eventId:k.uuid(),source:k.literal("caller_reported")});import{z as Me}from"zod";var Eu=Me.strictObject({type:Me.literal("bundle"),paywall:lt.optional(),offering:lt.optional(),coupons:lt,data:lt}),ef=e=>Me.strictObject({type:Me.literal(e),id:Me.uuid()}),qS=Me.strictObject({type:Me.literal("bundle"),paywallVersionId:Me.uuid().optional(),offeringVersionId:Me.uuid().optional(),couponIds:Me.array(Me.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:te});var FS=Me.strictObject({type:Me.literal("bundle"),offering:ef("offering_version").nullable(),paywall:Me.strictObject({versionId:Me.uuid(),paywallId:Me.uuid(),offeringVersionId:Me.uuid()}).nullable(),coupons:Me.array(Tn).max(20),data:te});import{z as st}from"zod";import{z as Ye}from"zod";var Mu=Ye.union([Ye.string(),Ye.number().finite(),Ye.boolean(),Ye.null()]),tf=Ye.union([Mu,Ye.array(Mu).min(1).max(20)]),nf=Ye.record(ot,tf).refine(e=>Object.keys(e).length<=10),Tu=Ye.strictObject({path:ot,type:Ye.enum(["string","number","boolean","strings"]),nullable:Ye.boolean().optional(),aggregation:Ye.enum(["count","exists"]).optional(),where:nf.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var rf=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],Du=st.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),of=lt,zu=st.discriminatedUnion("type",[xu,st.strictObject({type:st.literal("claim_offer"),coupon:lt}),st.strictObject({type:st.literal("event"),event:Du}),st.strictObject({type:st.literal("api"),operation:st.enum(rf),inputs:st.record(ot,of).refine(e=>Object.keys(e).length<=40),outputs:st.record(Du,Tu).refine(e=>Object.keys(e).length<=20)})]);var Se=Hr,af=P.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),We={id:Se,name:P.string().trim().min(1).max(80),position:P.strictObject({x:P.number().finite(),y:P.number().finite()}).optional()},sf={success:Se,cancel:Se,unavailable:Se,failure:Se},Po=P.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Co=P.enum(["same_window","new_window"]),cf=P.discriminatedUnion("type",[P.strictObject({...We,type:P.literal("entry"),next:Se,triggers:P.array(hu).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),P.strictObject({...We,type:P.literal("screen"),screenId:Se,presentation:gt,outputs:P.record(Se,Se),offering:P.discriminatedUnion("source",[P.strictObject({source:P.literal("variable"),key:we}),P.strictObject({source:P.literal("fixed"),versionId:P.uuid()})]).optional()}),P.strictObject({...We,type:P.literal("offering"),configuration:P.discriminatedUnion("source",[P.strictObject({source:P.literal("fixed"),versionId:P.uuid()}),P.strictObject({source:P.literal("feature"),featureKey:P.string().min(1).max(128)})]),writes:P.strictObject({value:we}),next:Se}),P.strictObject({...We,type:P.literal("coupon"),couponId:P.uuid(),writes:P.strictObject({value:we}),next:Se}),P.strictObject({...We,type:P.literal("coupons"),couponIds:P.array(P.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:P.strictObject({value:we}),next:Se}),P.strictObject({...We,type:P.literal("output"),value:P.discriminatedUnion("type",[...Ln.options,Eu,P.strictObject({type:P.literal("selection"),screenId:Se,offeringKey:we})])}),P.strictObject({...We,type:P.literal("condition"),cases:P.array(P.strictObject({condition:it,target:Se})).min(1).max(50),default:Se}),P.strictObject({...We,type:P.literal("feature"),featureKey:P.string().min(1).max(128),writes:P.strictObject({value:we}),next:Se}),P.strictObject({...We,type:P.literal("split"),experimentId:P.uuid(),applyPageExperiment:P.literal(!0).optional(),routes:P.record(af,Se).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:Se}),P.strictObject({...We,type:P.literal("action"),...sf,execution:Su,action:zu,writes:xr.optional()}),P.strictObject({...We,type:P.literal("external_page"),appManifest:Zr.optional(),url:Po,openIn:Co,opened:Se,failed:Se}),P.strictObject({...We,type:P.literal("end"),outcome:P.enum(["completed","closed","ineligible","failed"]),output:Ln.optional()}),P.strictObject({...We,type:P.literal("wait"),writes:xr.optional(),wait:P.discriminatedUnion("type",[P.strictObject({type:P.literal("duration"),delaySeconds:P.number().int().min(1).max(2592e3),elapsed:Se}),P.strictObject({type:P.literal("event"),eventName:Se,outputs:Io,timeoutSeconds:P.number().int().min(1).max(2592e3),received:Se,timeout:Se})])})]),ko=P.strictObject({version:P.literal(5),entry:Se,nodes:P.array(cf).min(1).max(at.flowNodes)}),Ro=ko.superRefine((e,t)=>{uf(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function ei(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function uf(e,t){let n=[],r=new Map(e.nodes.map(h=>[h.id,h])),o=(h,T,$)=>{n.push(h),t?.({message:h,reason:T,path:$?["nodes",e.nodes.indexOf($)]:[]})};r.size!==e.nodes.length&&o("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(h=>h.type==="entry").length!==1)&&o("A flow has exactly one entry node","entry"),(e.nodes.filter(h=>h.type==="screen").length>at.pages||e.nodes.filter(h=>!["screen","entry","end","output"].includes(h.type)).length>at.logicNodes)&&o("Flow node limit exceeded","budget");let a=new Set;for(let h of e.nodes){for(let T of ei(h))T===e.entry&&o("An entry cannot be a transition target","entryTarget",h),r.has(T)||o(`Missing target ${T}`,"missingTarget",h);h.type==="screen"&&(a.has(h.screenId)&&o("Every screen has exactly one node owner","screenOwner",h),a.add(h.screenId))}let l=new Set,p=new Set,d=new Set;function v(h){if(l.has(h)){o("Flow edges must not form a cycle","cycle",r.get(h));return}if(!(p.has(h)||!r.has(h))){l.add(h),d.add(h);for(let T of ei(r.get(h)))v(T);l.delete(h),p.add(h)}}v(e.entry);for(let h of e.nodes)d.has(h.id)||o("Every node must be reachable from Entry","unreachable",h);return[...new Set(n)]}var Eo={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Bu(e,t,n){let r=[...t].sort((p,d)=>d.length-p.length),o=new Set,a=(p,d=!1)=>{let v=r.find(h=>p===h||d&&p.startsWith(h+"."));o.add(v??p)};if(e.type==="condition"){let p=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let d of e.cases.slice(0,p+1))for(let v of jt(d.condition))v.startsWith("variables.")&&a(v.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let p of Object.values(e.action.inputs))p.source==="variable"&&a(p.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let l=e.type==="output"?e.value:e.type==="end"?e.output:null;if(l?.type==="variable"&&a(l.key),l?.type==="bundle")for(let p of[l.paywall,l.offering,l.coupons,l.data])p?.source==="variable"&&a(p.key);return l?.type==="selection"&&a(l.offeringKey),[...o]}import{z as S}from"zod";var xn=S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ti=e=>S.record(S.string(),te).refine(t=>Ze(t)<=e,"Funnel evidence exceeds its byte budget"),hv=S.enum(["local_segment","evaluation","presentation","timer","event","operation"]),To=S.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Do=S.discriminatedUnion("type",[S.strictObject({type:S.literal("flag"),key:S.string().min(1).max(128)}),S.strictObject({type:S.literal("experiment"),id:S.uuid()}),S.strictObject({type:S.literal("saved_group"),id:S.uuid()}),S.strictObject({type:S.literal("config"),key:S.string().min(1).max(128)}),S.strictObject({type:S.literal("constant"),key:S.string().min(1).max(128)}),S.strictObject({type:S.literal("paywall_version"),id:S.uuid()}),S.strictObject({type:S.literal("offering_version"),id:S.uuid()}),S.strictObject({type:S.literal("reward"),id:S.uuid()})]),Zn=S.strictObject({schemaVersion:S.literal(1),kind:To,selector:Do.nullable(),context:ti(131072),contract:S.strictObject({version:S.number().int().positive(),evaluator:S.string().min(1).max(128),policyRevision:S.number().int().nonnegative()})}).refine(e=>Ze(e)<=131072,"Node input exceeds its byte budget"),qu=S.strictObject({schemaVersion:S.literal(1),kind:To,outcome:S.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ti(131072),route:S.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ti(131072)}).refine(e=>Ze(e)<=131072,"Node result exceeds its byte budget"),bv=S.strictObject({schemaVersion:S.literal(1),operations:S.record(xn,S.strictObject({attempts:S.number().int().nonnegative(),maxAttempts:S.number().int().min(1).max(5),deadlineAt:S.iso.datetime({offset:!0}),retryAt:S.iso.datetime({offset:!0}).nullable(),error:S.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:S.strictObject({type:xn,id:S.uuid()}).nullable()}))}).refine(e=>Ze(e)<=65536,"Execution state exceeds its byte budget"),Gt={receiptId:S.uuid()},Mo=S.iso.datetime({offset:!0}),yv=S.discriminatedUnion("type",[S.strictObject({type:S.literal("node_entered"),details:S.strictObject({kind:To})}),S.strictObject({type:S.literal("presentation_shown"),details:S.strictObject({...Gt,source:S.literal("client"),occurredAt:Mo.optional()})}),S.strictObject({type:S.literal("decision_accepted"),details:S.strictObject(Gt)}),S.strictObject({type:S.literal("signal_received"),details:S.strictObject({signalId:S.uuid(),nodeId:xn,eventName:xn,data:ti(8192),source:S.literal("server"),occurredAt:Mo})}),S.strictObject({type:S.literal("signal_consumed"),details:S.strictObject({...Gt,signalId:S.uuid()})}),S.strictObject({type:S.literal("wait_elapsed"),details:S.strictObject(Gt)}),S.strictObject({type:S.literal("wait_timeout"),details:S.strictObject(Gt)}),S.strictObject({type:S.literal("operation_completed"),details:S.strictObject({...Gt,operation:xn,reference:S.strictObject({type:xn,id:S.uuid()}).nullable()})}),S.strictObject({type:S.literal("execution_recovered"),details:S.strictObject({generation:S.number().int().positive(),reason:S.enum(["interrupted","expired_lease","delivery_failed"])})}),S.strictObject({type:S.literal("execution_failed"),details:S.strictObject({generation:S.number().int().positive(),code:S.string().regex(/^[a-z_]{1,64}$/)})}),S.strictObject({type:S.literal("run_completed"),details:S.strictObject({outcome:S.enum(["completed","ineligible","failed"])})}),S.strictObject({type:S.literal("run_closed"),details:S.strictObject({source:S.enum(["client","server","expiry"])})}),S.strictObject({type:S.literal("treatment_used"),details:S.strictObject({...Gt,source:S.enum(["client","server"]),occurredAt:Mo,reference:S.string().min(1).max(128).optional()})})]);var et=j.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),pf=j.discriminatedUnion("type",[j.strictObject({id:et,type:j.literal("owned"),publicData:iu.optional(),document:Le.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),j.strictObject({id:et,type:j.literal("paywall"),paywallVersionId:j.uuid()})]),zo={executionContract:po.optional(),kind:j.literal("funnel"),schemaVersion:j.literal(4),screens:j.array(pf).max(at.pages),references:j.record(et,Do).refine(e=>Object.keys(e).length<=500),inputs:j.array(j.strictObject({variable:et,screenId:et,componentId:et,required:j.boolean()})).max(at.questions),variables:j.record(we,rn).refine(e=>Object.keys(e).length<=at.logicNodes),outputSchema:nn,execution:j.strictObject({runTimeoutSeconds:j.number().int().min(1).max(Eo.runTimeoutSeconds),maxTransitions:j.number().int().min(1).max(Eo.maxTransitions)})},qv=j.strictObject({...zo,graph:ko});function lf(e,t){let n=!1,r=(o,a)=>{let l=o.type==="stack"||o.type==="button"?o.bind?.coupon??a:a;o.type==="text"&&Object.values(e.strings.locales).some(p=>p[o.text]?.includes("{{offer."))&&!(l&&t(l))&&(n=!0),o.type==="stack"&&o.children.forEach(p=>r(p,l))};for(let o of e.pages)r(o.root);return n}function ri(e){return Array.isArray(e)?e.some(ri):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===vu:ri(n))}function mf(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,o]of e.screens.entries()){if(o.type!=="owned")continue;let a;try{a=lu(o.document)}catch(l){t.push({message:l instanceof Error?l.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[l,p]of e.inputs.entries())p.screenId===o.id&&!hi(a,p.componentId)&&t.push({message:`Local Funnel input ${p.variable} targets hidden component ${p.componentId} on screen ${p.screenId}`,reason:"inputBinding",path:["inputs",l]})}for(let[r,o]of e.graph.nodes.entries()){let a=["graph","nodes",r],l=o.type==="screen"?e.screens.find(p=>p.id===o.screenId):void 0;l?.type==="owned"&&(l.document.actions.some(p=>typeof p.properties.templateKey=="string"&&p.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),lf(l.document,p=>n.has(p))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(o.type==="output"&&o.value.type==="literal"&&ri(o.value.value)||o.type==="end"&&o.output?.type==="literal"&&ri(o.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Fu(e,t){for(let{message:n,reason:r,path:o}of mf(e))t.addIssue({code:"custom",message:n,path:o,params:{reason:r}})}function Nu(e,t){let n=(C,u,b=[])=>t.addIssue({code:"custom",message:C,path:b,params:{reason:u}}),r=Object.values(e.references),o=new Map(e.screens.map(C=>[C.id,C])),a=(C,u)=>r.some(b=>b.type===C&&("id"in b?b.id:b.key)===u);o.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let l=e.graph.nodes.filter(C=>C.type==="screen");(l.length!==o.size||l.some(C=>!o.has(C.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let p=new Map,d=Object.keys(e.variables);d.some(C=>d.some(u=>C!==u&&u.startsWith(C+".")))&&n("Variable paths must not overlap","variable");function v(C,u){Object.hasOwn(e.variables,C)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(u)]);let b=p.get(C)??new Set;b.add(u.id),p.set(C,b)}for(let[C,u]of e.graph.nodes.entries()){let b=["graph","nodes",C],Z=u.type==="feature"?u.featureKey:u.type==="offering"&&u.configuration.source==="feature"?u.configuration.featureKey:u.type==="output"&&u.value.type==="feature"?u.value.featureKey:u.type==="end"&&u.output?.type==="feature"?u.output.featureKey:null;Z&&!a("flag",Z)&&n("Flag selectors require an explicit GB resource reference","feature",b);let E=u.type==="feature"||u.type==="offering"||u.type==="coupon"||u.type==="coupons"||u.type==="action"&&u.action.type==="api"?["value"]:u.type==="action"&&u.action.type==="external_task"?Object.keys(u.action.outputs):u.type==="wait"&&u.wait.type==="event"?Object.keys(u.wait.outputs):[],ae="writes"in u?u.writes??{}:{};(E.length!==Object.keys(ae).length||E.some(L=>!Object.hasOwn(ae,L))||new Set(Object.values(ae)).size!==Object.values(ae).length)&&n("Node writes must map every named output exactly once","variable",b);for(let[L,ee]of Object.entries(ae)){v(ee,u);let le=e.variables[ee],H=u.type==="offering"?"offering_version":u.type==="coupon"?"reward":u.type==="action"&&u.action.type==="api"?"json":u.type==="action"&&u.action.type==="external_task"?u.action.outputs[L]:u.type==="wait"&&u.wait.type==="event"?u.wait.outputs[L]:void 0;(le?.source.type!=="node"||H&&le.type!==H)&&n("Node writer source or output type does not match declaration","variable",b)}if(u.type==="coupons"){let L=e.variables[u.writes.value];(L?.type!=="array"||L.items?.type!=="reward"||L.items.nullable||L.nullable)&&n("Coupons output requires a non-null Reward array","variable",b);for(let ee of u.couponIds)a("reward",ee)||n("Coupons require Reward references","coupon",b)}if(u.type==="split"&&!a("experiment",u.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",b),u.type==="coupon"&&!a("reward",u.couponId)&&n("Coupon selectors require a Reward reference","coupon",b),u.type==="action"&&u.action.type==="claim_offer"&&u.action.coupon.source==="literal"){let L=u.action.coupon.value;(!L||typeof L!="object"||Array.isArray(L)||L.type!=="reward"||typeof L.id!="string"||Object.keys(L).length!==2||!a("reward",L.id))&&n("Coupon claims require a Reward reference","coupon",b)}if(u.type==="offering"&&u.configuration.source==="fixed"&&!a("offering_version",u.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",b),u.type==="screen"&&u.offering?.source==="variable"&&e.variables[u.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",b),u.type==="action"&&u.action.type==="claim_offer"&&u.action.coupon.source==="variable"&&(e.variables[u.action.coupon.key]?.type!=="reward"||u.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",b),u.type==="screen"){let L=o.get(u.screenId);if(u.offering?.source==="fixed"&&!a("offering_version",u.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",b),L?.type==="paywall"&&u.offering&&n("Paywall owns its fixed Offering Version","offering",b),L?.type==="paywall"&&!a("paywall_version",L.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",b),L?.type==="owned"){let ee=L.document.pages[0];if(!ee){n("Owned screen requires a page","screen",b);continue}It(L.document).some(H=>!H.complete)&&n("Owned screens require complete local content","translations",b);let le=new Set(L.document.actions.map(H=>H.id));(le.size!==Object.keys(u.outputs).length||Object.keys(u.outputs).some(H=>!le.has(H)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",b),Yt(ee.root,H=>{!u.offering&&(H.type==="plan_picker"||(H.type==="stack"||H.type==="button")&&H.bind?.plan||H.type==="customer_data"&&["customer_plans","credit_packs"].includes(H.data.source))&&n("Product presentation requires an Offering Version","offering",b),H.type==="customer_data"&&Object.values(H.data.outputs??{}).some(St=>St!==void 0&&!le.has(St))&&n("Customer components require declared screen outcomes","componentOutput",b)})}}u.type==="end"&&["completed","ineligible"].includes(u.outcome)&&!u.output&&n("Completed and ineligible ends require a declared output","output",b),u.type==="end"&&u.output?.type==="literal"&&!Xe(e.outputSchema,u.output.value)&&n("Terminal output does not match outputSchema","output",b),u.type==="output"&&u.value.type==="literal"&&!Xe(e.outputSchema,u.value.value)&&n("Terminal output does not match outputSchema","output",b);let Ce=u.type==="output"?u.value:u.type==="end"?u.output:void 0;if(Ce?.type==="variable"&&!Ce.path){let L=e.variables[Ce.key];L&&!wi(L,e.outputSchema)&&n("Variable output does not match outputSchema","output",b)}if(u.type==="screen"){let L=o.get(u.screenId);if(L?.type==="owned")for(let ee of ki(L.document))(/^(input|params)\./.test(ee)||ee.startsWith("variables.")&&!Ci(ee.slice(10),d))&&n("Screen values must reference registered variables","variable",b)}if(u.type==="condition")for(let L of u.cases){for(let ee of vt(L.condition))a("saved_group",ee)||n("Conditions require explicit Saved Group references","savedGroup",b);for(let ee of jt(L.condition))ee.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",b)}if(u.type==="output"&&u.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",b);for(let[L,ee]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let le=u.value[L];if(le)if(le.source==="literal"){let H=L==="coupons"?le.value:[le.value];(!Array.isArray(H)||H.length>20||H.some(St=>!Xe({type:ee,nullable:!1},St)||!a(ee,St.id))||L==="coupons"&&new Set(H.map(St=>St.id)).size!==H.length)&&n("Bundle requires distinct scoped resource references",L==="coupons"?"coupon":L==="paywall"?"paywall":"offering",[...b,"value",L])}else{let H=e.variables[le.key];(le.path||!H||H.nullable||(L==="coupons"?H.type!=="array"||H.items?.type!=="reward"||H.items.nullable:H.type!==ee))&&n("Bundle binding type does not match its slot","output",b)}}}}for(let[C,u]of e.graph.nodes.entries()){let b=u.type==="screen"?o.get(u.screenId):void 0,Z=[...Bu(u,d),...b?.type==="owned"?Sr(b.document).map(E=>Ci(E,d)?.key??E):[]];for(let E of new Set(Z)){let ee=function(le){if(le===u.id)return!0;if(L.has(le))return!1;L.add(le);let H=e.graph.nodes.find(tl=>tl.id===le);return H?(Ce.has(le)?H.type==="action"?[H.cancel,H.unavailable,H.failure]:H.type==="wait"&&H.wait.type==="event"?[H.wait.timeout]:[]:ei(H)).some(ee):!1};var $=ee;if(!Object.hasOwn(e.variables,E)){n("Consumed variable is undeclared","variable",["graph","nodes",C]);continue}let ae=e.variables[E];if(u.type==="screen"&&ae.source.type==="input"&&e.inputs.some(le=>le.screenId===u.screenId&&le.variable===E)||ae.source.type==="parameter"||ae.source.type==="attribute")continue;let Ce=ae.source.type==="input"?new Set(e.inputs.filter(le=>le.variable===E&&le.required).flatMap(le=>l.filter(H=>H.screenId===le.screenId).map(H=>H.id))):p.get(E)??new Set,L=new Set;(!Ce.size||ee(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",C])}}(new Set(e.inputs.map(C=>C.variable)).size!==e.inputs.length||new Set(e.inputs.map(C=>`${C.screenId}:${C.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[C,u]of e.inputs.entries()){e.variables[u.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",C]);let b=o.get(u.screenId),Z=b?.type==="owned"?hi(b.document,u.componentId):null;if((Z?.type!=="stack"||!Z.interaction||!["input","toggle","select","multiselect","tabs"].includes(Z.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",C]),Z?.type==="stack"&&Z.interaction){let E=Z.interaction.type==="toggle"?"boolean":Z.interaction.type==="multiselect"?"strings":"string";e.variables[u.variable]?.type!==E&&n("Input variable type does not match component","inputBinding",["inputs",C]);let ae=e.variables[u.variable]?.enum;ae&&!Z.children.filter(Ce=>!Ce.hidden).every(Ce=>ae.includes(Ce.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",C])}}for(let[C,u]of Object.entries(e.variables))u.enum&&u.type!=="string"&&n("Only string variables support enum","variable",["variables",C]),u.source.type==="input"&&!e.inputs.some(b=>b.variable===C)&&n("Input variable requires a component binding","inputBinding",["variables",C]);let h=0,T=0;for(let C of e.screens)if(C.type==="owned"){for(let u of C.document.pages)Yt(u.root,()=>{h++});T+=C.document.actions.length}(h>at.components||T>at.actions||Ze(e)>at.documentBytes)&&n("Funnel document exceeds its budget","budget")}var df=j.strictObject({...zo,graph:Ro}).superRefine(Nu),Ct=j.strictObject({...zo,graph:Ro,displayName:j.string().trim().min(1).max(80)}).superRefine(Nu),Fv=Ct.superRefine(Fu),Nv=df.superRefine(Fu),ni=j.string().regex(pt),Hn={requestId:j.uuid(),nodeId:et,visit:j.number().int().nonnegative(),revision:j.number().int().nonnegative(),customerToken:ni.optional()},ff=j.discriminatedUnion("type",[j.strictObject({type:j.literal("screen"),output:et,answers:Et,selection:j.record(et,j.union([j.string().max(200),j.boolean(),j.number().int().min(0).max(1e4)])).optional()}),j.strictObject({type:j.literal("paywall_quote"),featureQuantities:j.record(j.uuid(),j.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:et,productVersionId:j.uuid(),offerId:j.uuid().optional(),nativeOffer:un.optional(),predecessor:j.strictObject({operationId:j.uuid().nullable(),generation:j.number().int().positive()}).optional()}),j.strictObject({type:j.literal("paywall_confirm"),operationId:j.uuid()}),j.strictObject({type:j.literal("paywall_cancel"),operationId:j.uuid()}),j.strictObject({type:j.literal("client_action"),receiptId:j.uuid(),outcome:j.enum(["success","cancel","failure","opened","failed"])})]),gf=j.object({nodeId:et,visit:j.number().int().nonnegative(),revision:j.number().int().nonnegative(),components:j.record(et,j.object({resourceKey:j.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:j.number().int().min(1).max(1e5),after:lr.nullable(),filter:j.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),tt=j.discriminatedUnion("operation",[j.strictObject({operation:j.literal("start"),funnelId:j.uuid(),requestId:j.uuid(),customer:xt.optional(),customerData:Pt.optional(),locale:j.string().min(1).max(35),parameters:ut}).refine(Vt,$t),j.strictObject({operation:j.literal("get"),settlementRequestId:j.uuid().optional(),data:gf.optional(),purchase:j.strictObject({receiptId:j.uuid(),operationId:j.uuid()}).optional(),customerToken:ni.optional()}),j.strictObject({operation:j.literal("resume"),requestId:j.uuid(),customerToken:ni.optional()}),j.strictObject({operation:j.literal("submit"),...Hn,input:ff}),j.strictObject({operation:j.literal("back"),...Hn}),j.strictObject({operation:j.literal("shown"),...Hn}),j.strictObject({operation:j.literal("close"),...Hn}),j.strictObject({operation:j.literal("commit_segment"),...Hn,policyRevision:j.number().int().nonnegative(),generation:j.string().min(1).max(256)}),j.strictObject({operation:j.literal("review"),receiptId:j.uuid().optional(),customerToken:ni.optional()})]);function ii(e,t){let n=new Set,r=new Set,o=new Set,a=[],l=new Map,p=new Map,d=new Map;function v(u){for(let b of vt(u))h(b)}function h(u){if(o.has(u)||!Object.hasOwn(t.savedGroups,u))return;let b=t.savedGroups[u];b&&(o.add(u),d.set(u,b),a.push(()=>{!Array.isArray(b)&&b.type==="condition"&&v(b.condition)}))}function T(u){for(let b of["hashAttribute","fallbackAttribute"])if(u[b]!==void 0&&xo(u[b]))throw new Error(`Funnel GB ${b} uses a reserved flow namespace`);v(u.condition);for(let b of u.parentConditions??[])$(b.id),v(b.condition)}function $(u,b=!1){let Z=Object.hasOwn(t.features,u)?t.features[u]:void 0;if(!Z){if(b)throw new Error("Required GB Feature is unavailable");return}n.has(u)||(n.add(u),l.set(u,Z),a.push(()=>{for(let E of Z.rules??[]){T(E);for(let ae of E.tracks??[])T(ae.experiment)}}))}function C(u){let b=Object.hasOwn(t.experiments,u)?t.experiments[u]:void 0;if(!b)throw new Error("Required GB Experiment is unavailable");r.has(u)||(r.add(u),p.set(u,b),a.push(()=>T(b)))}for(let u of e.graph.nodes){u.type==="feature"&&$(u.featureKey,!0),u.type==="split"&&C(u.experimentId),u.type==="condition"&&u.cases.forEach(Z=>v(Z.condition)),u.type==="offering"&&u.configuration.source==="feature"&&$(u.configuration.featureKey,!0);let b=u.type==="output"?u.value:u.type==="end"?u.output:null;b?.type==="feature"&&$(b.featureKey,!0)}for(let u of a)u();return{...t,features:Object.fromEntries(l),experiments:Object.fromEntries(p),savedGroups:Object.fromEntries(d)}}import{z as B}from"zod";import{z as Jn}from"zod";var Uu=Jn.object({defaultLocale:Jt,locales:Jn.record(Jt,Jn.object({name:Jn.string().max(80),description:Jn.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var hf=["customer_data","coupon_code"],Vu=B.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),bf=B.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),oi=(e,t)=>new Set(e.map(t)).size===e.length,yf=B.strictObject({currency:oe,amountMinor:B.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),xf=B.strictObject({featureId:B.uuid(),name:B.string().trim().min(1).max(120),allowance:B.string().max(40).nullable(),access:B.boolean()}),Sf=B.strictObject({stripe:B.strictObject({prices:B.array(yf).min(1).max(50)}).optional(),apple:B.strictObject({productIds:B.array(Vu).min(1).max(10)}).optional(),google:B.strictObject({products:B.array(B.strictObject({productId:Vu,basePlanId:bf.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!oi(e.stripe.prices,n=>n.currency)||e.apple&&!oi(e.apple.productIds,n=>n)||e.google&&!oi(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),vf=B.strictObject({name:B.string().trim().min(1).max(80),interval:B.enum(["free","week","month","year","one_time"]),intervalCount:B.number().int().min(1).max(100),trial:B.strictObject({days:B.number().int().min(1).max(730),cardRequired:B.boolean()}).nullable(),benefits:B.array(xf).max(50).refine(e=>oi(e,t=>t.featureId),"Duplicate benefit"),channels:Sf,prepaid:B.array(_a).max(100).optional()}),If=B.strictObject({digest:gn,content:B.strictObject({discount:At,duration:He,appliesTo:Ni,displayCopy:Uu.nullable(),firstPurchaseOnly:B.boolean(),qualificationRequired:B.boolean(),startsAt:B.iso.datetime().nullable(),endsAt:B.iso.datetime().nullable(),grantWindowHours:B.number().int().positive(),perCustomerLimit:B.number().int().positive()})}),Of=B.discriminatedUnion("type",[B.strictObject({type:B.literal("checkout"),product:pr}),B.strictObject({type:B.literal("close")}),B.strictObject({type:B.literal("action"),action:oo})]),$u=B.strictObject({kind:B.literal("paywall"),formatVersion:B.literal(1),name:B.string().trim().min(1).max(80),offeringVersionId:B.uuid(),presentation:gt,screen:Le,products:Ir,catalog:B.record(B.uuid(),vf),buttons:B.record(Cn,Of),coupons:B.record(B.uuid(),If)}).superRefine((e,t)=>{let n=b=>t.addIssue({code:"custom",message:b}),{screen:r}=e;Ba(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),mo(r,hf).forEach(n),It(r).some(b=>!b.complete)&&n("Every published locale must be complete");let o=new Set,a=new Set,l=new Set;ht(r,b=>{let Z="bind"in b?b.bind:void 0;Z?.promotionCode&&n("Promotion codes must not be published"),Z?.plan&&o.add(Z.plan),Z?.coupon&&a.add(Z.coupon),b.type==="plan_picker"&&(b.planIds?.forEach(E=>o.add(E)),b.defaultPlan&&o.add(b.defaultPlan)),b.type==="text"&&b.feature&&l.add(b.feature.id)});let p=e.products.items.map(b=>b.productVersionId),d=Object.keys(e.catalog);(p.length!==d.length||p.some(b=>!Object.hasOwn(e.catalog,b)))&&n("Catalog must contain exactly the displayed Products");let v=new Set(p);e.products.defaultProductVersionId!==null&&!v.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let b of o)v.has(b)||n("Screen references a Product that is not displayed");for(let b of Object.values(e.catalog))!b.channels.stripe&&!b.channels.apple&&!b.channels.google&&n("A displayed Product needs at least one sales channel");let h=new Set(Object.values(e.catalog).flatMap(b=>b.benefits.map(Z=>Z.featureId)));for(let b of l)h.has(b)||n("Feature text must read a displayed benefit");let T=r.actions.filter(b=>b.type!=="navigate");r.actions.some(b=>b.type!=="event"&&b.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==T.length||T.some(b=>!Object.hasOwn(e.buttons,b.id)))&&n("Buttons must match the screen's actions");let C=!1;for(let b of Object.values(e.buttons)){if(b.type!=="checkout")continue;C=!0,(b.product.type==="fixed"?[b.product.productVersionId]:b.product.allowedProductVersionIds).some(E=>!v.has(E))&&n("Checkout may only sell displayed Products")}C||n("A Paywall needs a checkout button");let u=Object.keys(e.coupons);(u.length!==a.size||u.some(b=>!a.has(b)))&&n("Coupons must be exactly the bound Coupons")}),Gu=B.strictObject({state:B.enum(["published","archived"]),controlRevision:B.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:B.uuid(),versions:B.record(B.uuid(),B.strictObject({version:B.number().int().positive(),artifact:B.string().min(1),sourceDigest:B.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var jf={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Bo=Y.string().regex(/^[a-f0-9]{64}$/),qo=Y.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Af=me.extend({environmentId:Y.uuid()}),Ku=Y.strictObject({features:Y.array(Y.string()).max(500),experiments:Y.record(Y.uuid(),Y.array(Y.string()).max(20)),savedGroups:Y.array(Y.string()).max(1e3)}),Uo=Y.strictObject({kind:Y.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Y.number().int().positive(),url:Y.string().min(1).max(2048),sha256:Bo,byteLength:Y.number().int().positive().max(jf.maxArtifactBytes),generation:Bo.optional()}),wf=Y.strictObject({state:Y.enum(["active","paused","archived"]),controlRevision:qo,evaluationMode:Y.enum(["local","remote"]),evaluationRevision:qo,currentVersionId:Y.uuid(),versions:Y.record(Y.uuid(),Y.strictObject({artifact:Y.string(),dependencies:Ku,definitionDigest:gn.optional(),couponDigests:Y.record(Y.uuid(),gn).optional()}))}),bI=Y.strictObject({kind:Y.literal("sdk_configuration"),schemaVersion:Y.literal(1),scope:Af,revision:qo,generation:Bo,policy:Y.strictObject({refreshIntervalSeconds:Y.number().positive().max(15),maxControlAgeSeconds:Y.number().positive().max(60)}),gb:Y.strictObject({features:Y.string().nullable(),pageExperiments:Y.string().nullable()}),artifacts:Y.record(Y.string(),Uo),funnels:Y.record(Y.uuid(),wf),paywalls:Y.record(Y.uuid(),Gu).optional()}).superRefine((e,t)=>{let n=(r,o)=>{r!==null&&e.artifacts[r]?.kind!==o&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let o of Object.values(r.versions))n(o.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let o of Object.values(r.versions))n(o.artifact,"funnel")}});function Fo(e){if(Array.isArray(e))return`[${e.map(Fo).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Fo(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function _f(e){return ar(sr(typeof e=="string"?new TextEncoder().encode(e):e))}function yI(e){return _f(Fo(e))}var No=class extends Error{constructor(n,r){super(n);this.dependency=r}dependency};function xI(e,t){let n=h=>h.type==="feature"?h.featureKey:h.type==="end"&&h.output?.type==="feature"?h.output.featureKey:h.type==="output"&&h.value.type==="feature"?h.value.featureKey:void 0,r=(h,T)=>e.graph.nodes.find($=>h==="experiment"?$.type==="split"&&$.experimentId===T:h==="feature"&&n($)===T)?.name,o=(h,T,$=r(T.type,T.resource))=>new No(h,{...T,...$?{step:$}:{}});for(let h of Object.values(e.references)){let T=h.type==="flag"?!Object.hasOwn(t.features,h.key)||t.remoteFeatures.includes(h.key)?{type:"feature",resource:h.key}:null:h.type==="experiment"?Object.hasOwn(t.experiments,h.id)?null:{type:"experiment",resource:h.id}:h.type==="saved_group"&&!Object.hasOwn(t.savedGroups,h.id)?{type:"saved_group",resource:h.id}:null;if(T)throw o("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...T})}let a=ii(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),l=new Set(t.remoteFeatures);for(let h of e.graph.nodes){let T=n(h);if(!T)continue;let $=a.features[T],C=h.type==="feature"?e.variables[h.writes.value]:e.outputSchema,u={type:"feature",resource:T};if(!$||!C)throw o("Required public Feature declaration is unavailable",{reason:"unavailable",...u},h.name);if([$.defaultValue,...($.rules??[]).flatMap(Z=>[...Object.hasOwn(Z,"force")?[Z.force]:[],...Z.variations??[],...(Z.tracks??[]).flatMap(E=>E.experiment.variations)])].some(Z=>Z===void 0||!Xe(C,Z)))throw o("GB Feature values violate the Funnel type contract",{reason:"value_type",...u},h.name)}let p=new Set,d=(h,T)=>{for(let $ of vt(h)){if(p.has($))continue;let C=t.savedGroups[$];if(!C)throw o("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:$},T);p.add($),!Array.isArray(C)&&C.type==="condition"&&d(C.condition,T)}},v=(h,T)=>{if(l.has(h)||!t.features[h])throw o("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:h},T)};for(let h of e.graph.nodes)if(h.type==="condition")for(let T of h.cases)d(T.condition,h.name);for(let[h,T]of Object.entries(a.features)){let $=r("feature",h);for(let C of T.rules??[]){d(C.condition,$);for(let u of[...C.parentConditions??[],...(C.tracks??[]).flatMap(b=>b.experiment.parentConditions??[])])v(u.id,$),d(u.condition,$);for(let u of C.tracks??[])d(u.experiment.condition,$)}}for(let[h,T]of Object.entries(a.experiments)){let $=r("experiment",h);d(T.condition,$);for(let C of T.parentConditions??[])v(C.id,$),d(C.condition,$)}for(let h of e.graph.nodes)if(h.type==="split"){let T=a.experiments[h.experimentId],$={type:"experiment",resource:h.experimentId};if(!T)throw o("Local Funnel requires a public Experiment",{reason:"unavailable",...$},h.name);for(let C of T.variations)if(typeof C!="string"||!Object.hasOwn(h.routes,C))throw o("Experiment variation has no declared Funnel route",{reason:"variation_route",...$},h.name)}return Ku.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([h,T])=>[h,T.variations.map(String)])),savedGroups:[...p].sort()})}function SI(e){return Ct.parse(e)}var Lu=_e.strictObject({processContext:Tr.optional(),...cn,selector:_e.discriminatedUnion("type",[_e.strictObject({type:_e.literal("paywall"),paywallId:_e.uuid()}),_e.strictObject({type:_e.literal("version"),versionId:_e.uuid()})]),customerId:_e.uuid().optional(),commerce:ur,locale:_e.string().min(1).max(35),requirement:Qt.optional()}),Wn=_e.strictObject({id:_e.uuid(),paywallId:_e.uuid(),version:_e.number().int().positive(),document:fn.omit({requirement:!0,offeringId:!0}),offering:_e.strictObject({id:_e.uuid()}),content:_e.strictObject({environmentId:_e.uuid(),offeringVersionId:_e.uuid(),artifact:Uo.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Xt,check:Pn.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Qn=_e.strictObject(Wn.shape).omit({document:!0,offering:!0}).extend({content:Wn.shape.content.unwrap()});function EI(e,t){let n=$u.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[o,a]of Object.entries(n.catalog)){let l=r.plans[o],p=a.channels.stripe?.prices.find(d=>d.currency===l?.currency);l&&p&&Object.assign(l,{amountMinor:p.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return Wn.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Ne}from"zod";var Zu={requestId:Ne.uuid(),sourceId:Ne.uuid(),expectedAvailable:Wt},Hu=Ne.discriminatedUnion("action",[Ne.strictObject({...Zu,action:Ne.enum(["add","subtract","set_remaining"]),amount:ye}),Ne.strictObject({...Zu,action:Ne.literal("edit"),granted:ye,expiresAt:Ne.iso.datetime({offset:!0}).nullable(),nextResetAt:Ne.iso.datetime({offset:!0}).nullable(),expectedRevision:Ne.number().int().nonnegative()})]),Vo=Ne.strictObject({sourceId:Ne.uuid(),available:Wt,held:Wt,spent:Wt,adjustmentGrantId:Ne.uuid().nullable()}),Ju=Vo.extend({granted:Wt,expiresAt:Ne.iso.datetime({offset:!0}).nullable(),nextResetAt:Ne.iso.datetime({offset:!0}).nullable(),revision:Ne.number().int().nonnegative()});import{z as Qe}from"zod";var Wu=Qe.discriminatedUnion("action",[Qe.object({action:Qe.literal("upsert"),externalId:Qe.string().min(1).max(128),name:Qe.string().trim().min(1).max(80)}).strict(),Qe.object({action:Qe.literal("archive"),entityId:Qe.uuid()}).strict()]),Qu=Qe.object({id:Qe.uuid(),externalId:Qe.string().min(1).max(128),name:Qe.string().min(1).max(80),archived:Qe.boolean()}).strict();import{z as ze}from"zod";import{z as Lt}from"zod";var Yu=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Xu=Lt.string().regex(/.+\/.+/),$o=Lt.number().min(-100),Kt=Lt.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),Pf=Lt.strictObject({input:Kt,output:Kt,cache_read:Kt.optional(),cache_write:Kt.optional(),reasoning:Kt.optional(),input_audio:Kt.optional(),output_audio:Kt.optional()}),Go=(e,t)=>Lt.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),UI=Lt.strictObject({defaultMarkup:$o,providerMarkups:Go(Lt.string().min(1),$o),modelMarkups:Go(Xu,$o),customModels:Go(Xu,Pf.partial())});import{z as K}from"zod";var Zt=K.iso.datetime({offset:!0}),kt=K.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Cf=K.discriminatedUnion("kind",[K.object({kind:K.literal("absolute"),from:Zt,to:Zt}).strict(),K.object({kind:K.literal("last_days"),days:K.union([K.literal(1),K.literal(7),K.literal(30),K.literal(90)])}).strict(),K.object({kind:K.literal("billing_cycles"),membershipId:K.uuid(),count:K.number().int().min(1).max(12),includeCurrent:K.boolean()}).strict()]),ep=K.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),kf=K.object({key:K.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:K.array(K.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Ht=K.object({range:Cf,timezone:ep,filterBy:K.array(kf).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:K.enum(["hour","day","week","month"]),internal_feature_id:K.uuid().nullable(),entityId:K.uuid().nullable(),topN:K.number().int().min(1).max(50).nullable(),groupBy:K.union([K.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),K.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:K.object({bucket:Zt,group:K.string().max(240),isOther:K.boolean(),internal_feature_id:K.uuid(),resourceId:K.uuid()}).strict().nullable(),limit:K.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),tp=K.object({from:Zt,to:Zt,interval:K.enum(["hour","day","week","month"]),timezone:ep,rows:K.array(K.object({bucket:Zt,group:K.string().max(240),isOther:K.boolean(),internal_feature_id:K.uuid(),resourceId:K.uuid(),consumedUnits:kt,refundedUnits:kt,reservedUnits:kt,charged:kt,refunded:kt,reserved:kt,netUnits:kt,netCharged:kt}).strict()).max(100),nextCursor:K.object({bucket:Zt,group:K.string().max(240),isOther:K.boolean(),internal_feature_id:K.uuid(),resourceId:K.uuid()}).strict().nullable()}).strict();var Sn=ze.string().regex(/^(0|[1-9]\d{0,29})$/),np=ze.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Ko=ze.strictObject({bucket:ze.iso.datetime({offset:!0}),group:ze.string().max(240),isOther:ze.boolean(),internal_feature_id:ze.uuid()}),rp=ze.strictObject({...Ht.shape,groupBy:ze.union([ze.enum(["customer","entity","entitlement"]),ze.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Ko.nullable()}).superRefine((e,t)=>{let n=Ht.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),ip=ze.strictObject({from:ze.iso.datetime({offset:!0}),to:ze.iso.datetime({offset:!0}),interval:Ht.shape.interval,timezone:Ht.shape.timezone,rows:ze.array(ze.strictObject({...Ko.shape,eventCount:Sn,units:np,tokenEventCount:Sn,tokens:ze.strictObject(Object.fromEntries(Yu.map(e=>[e,Sn]))),totalTokens:Sn,providerCostEventCount:Sn,providerCostUsd:np,invalidTelemetryEventCount:Sn})).max(100),nextCursor:Ko.nullable()});import{z as je}from"zod";var op=je.object({requestId:je.uuid(),items:je.array(je.object({customerId:je.uuid(),command:wn.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"),ap=je.object({batchId:je.uuid(),after:je.number().int().min(-1).max(999),limit:je.number().int().min(1).max(100)}).strict(),sp=je.object({batchId:je.uuid(),status:je.enum(["queued","complete"]),total:je.number().int().min(1).max(1e3),processed:je.number().int().min(0).max(1e3),items:je.array(je.object({position:je.number().int().min(0).max(999),customerId:je.uuid(),idempotencyKey:je.string().min(1).max(120),status:je.enum(["queued","accepted","rejected","failed"]),receipt:_n.nullable(),errorCode:je.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:je.number().int().min(0).max(999).nullable()}).strict();import{z as f}from"zod";var Rf=f.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),cp=f.enum(["draft","active","paused","archived"]),up=f.string().min(1).max(256),pp=f.array(up).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Ef=f.strictObject({duration:f.enum(["day","week","month","year"]),length:f.number().int().min(1).max(3660)}),Mf=f.strictObject({internal_feature_id:f.uuid(),allowance:f.number().nonnegative().max(1e15).nullable(),expiry:Ef.nullable()}),Tf=f.discriminatedUnion("type",[f.strictObject({type:f.literal("feature_grant"),grants:f.array(Mf).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),f.strictObject({type:f.literal("free_product"),productId:up,duration:He}),f.strictObject({type:f.literal("invoice_credits"),amount:f.number().positive().max(1e8),duration:He,rollover:f.boolean(),productIds:pp})]),Df=f.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),lp=f.object({key:Df,name:f.string().trim().min(1).max(80),configuration:Tf}).strict(),mp=f.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Lo=f.object({code:mp,maxUses:f.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:f.boolean()}).strict(),dp=f.object({key:f.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:f.string().trim().min(1).max(80),rewardId:f.uuid(),redeemOn:f.enum(["customer_creation","checkout"]),receivedBy:f.enum(["referrer","all"]),maxRedemptions:f.number().int().min(1).max(1e6).nullable(),productIds:pp,excludeTrial:f.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),fp={id:f.uuid(),projectId:f.uuid(),environmentId:f.uuid(),revision:f.number().int().nonnegative(),status:cp,createdAt:f.iso.datetime({offset:!0}),updatedAt:f.iso.datetime({offset:!0})},zf=lp.extend(fp).strict(),Bf=dp.safeExtend(fp).strict(),t0=f.strictObject({id:f.uuid(),key:f.string(),name:f.string(),type:Rf,status:cp}),n0=f.discriminatedUnion("action",[f.object({action:f.literal("save"),id:f.uuid().nullable(),revision:f.number().int().nonnegative(),input:lp}).strict(),f.object({action:f.enum(["activate","pause","resume","archive","delete"]),id:f.uuid(),revision:f.number().int().nonnegative()}).strict()]),r0=f.discriminatedUnion("action",[f.object({action:f.literal("save"),id:f.uuid().nullable(),revision:f.number().int().nonnegative(),input:dp}).strict(),f.object({action:f.enum(["activate","pause","resume","archive","delete"]),id:f.uuid(),revision:f.number().int().nonnegative()}).strict()]),gp=f.object({id:f.uuid(),rewardId:f.uuid(),programId:f.uuid().nullable(),customerId:f.uuid(),referrerId:f.uuid().nullable(),status:f.enum(["pending","applied","unavailable"]),result:f.record(f.string(),f.unknown()).nullable(),createdAt:f.iso.datetime({offset:!0})}).strict(),hp=f.object({code:mp,requestId:f.uuid()}).strict(),bp=f.strictObject({redemptionId:f.uuid(),currency:oe,requestId:f.uuid(),accepted:f.literal(!0)}),qf=f.strictObject({type:f.literal("checkout"),orderId:f.uuid(),productVersionId:f.uuid(),currency:oe,duration:He,renewalAmountMinor:f.number().int().positive().max(1e8),status:f.enum(["created","pending","trialing","paid","cancelled","failed"]),url:f.url().nullable()}),yp=f.discriminatedUnion("type",[qf,f.strictObject({type:f.literal("subscription"),operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),currency:oe,duration:He,renewalAmountMinor:f.number().int().positive().max(1e8),status:f.enum(["pending","running","applied","failed"])})]),xp=f.object({programId:f.uuid(),requestId:f.uuid()}).strict(),Sp=f.object({id:f.uuid(),programId:f.uuid(),code:Lo.shape.code,createdAt:f.iso.datetime({offset:!0})}).strict(),i0=f.object({rows:f.array(zf).max(100),nextCursor:f.uuid().nullable()}).strict(),o0=f.object({rows:f.array(Bf).max(100),nextCursor:f.uuid().nullable()}).strict(),Ff=Lo.extend({id:f.uuid(),redemptions:f.number().int().nonnegative()}).strict(),Nf=f.strictObject({id:f.uuid(),programId:f.uuid().nullable(),customerId:f.uuid().nullable(),referrerId:f.uuid().nullable(),code:f.string().nullable(),status:f.enum(["pending","triggered","applied"]),createdAt:f.iso.datetime({offset:!0})}),a0=f.object({codes:f.array(Ff).max(100),redemptions:f.array(Nf).max(100),customers:f.record(f.uuid(),f.string()),codesCursor:f.uuid().nullable(),redemptionsCursor:f.uuid().nullable()}).strict(),s0=f.discriminatedUnion("action",[f.object({action:f.literal("create"),rewardId:f.uuid(),revision:f.number().int().nonnegative(),input:Lo}).strict(),f.object({action:f.literal("remove"),rewardId:f.uuid(),revision:f.number().int().nonnegative(),codeId:f.uuid()}).strict()]);import{z as c}from"zod";import{z as R}from"zod";var dt={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Xn=e=>new Set(e).size===e.length,Zo=R.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Uf=R.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Yn=R.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),Vf=R.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),vp=R.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var Ip=R.strictObject({id:R.uuid(),repo:Uf,platform:R.enum(["github","gitlab","bitbucket"]),branches:R.array(Yn).min(1).max(4).refine(Xn),workflow:R.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:R.array(R.uuid()).min(1).max(4).refine(Xn),include:R.array(vp).min(1).max(16),exclude:R.array(vp).max(16),methods:R.array(R.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Xn),maxAgeHours:R.number().int().min(1).max(720)}),Op=Ip.extend({revision:R.number().int().positive()}),p0=R.strictObject({repository:Ip,expectedRevision:R.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),jp=R.strictObject({repositoryId:R.uuid(),branch:Yn}),$f=R.array(Zo).max(dt.keys).refine(Xn),Ap=R.strictObject({repository:Op.omit({keyIds:!0}),branch:Yn,keys:$f,keySetHash:R.string().regex(/^[a-f0-9]{64}$/)}),Gf=R.strictObject({filePath:Vf,startingLineNumber:R.number().int().min(1).max(1e7)}),Ho=R.strictObject({protocol:R.literal(1),repositoryId:R.uuid(),branch:Yn,workflow:R.string().max(200),configurationRevision:R.number().int().positive(),keySetHash:R.string().regex(/^[a-f0-9]{64}$/),commit:R.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:R.uuid(),runNumber:R.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:R.number().int().min(1).max(1e4),scannerVersion:R.literal("1"),scannedAt:R.iso.datetime({offset:!0}),coverage:R.strictObject({complete:R.literal(!0),files:R.number().int().min(0).max(dt.files),sourceBytes:R.number().int().min(0).max(dt.sourceBytes),unresolvedCalls:R.number().int().min(0).max(1e6),unsupportedFiles:R.number().int().min(0).max(dt.files)}),features:R.array(R.strictObject({key:Zo,refs:R.array(Gf).max(dt.referencesPerKey)})).max(dt.keys)}).superRefine((e,t)=>{Xn(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>dt.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Jo=R.strictObject({scanId:R.uuid(),commit:R.string(),receivedAt:R.string(),references:R.number().int().nonnegative(),removedReferences:R.number().int().nonnegative()}),Kf=Jo.extend({repositoryId:R.uuid(),branch:Yn,workflow:R.string(),digest:R.string(),configurationRevision:R.number().int().positive(),runNumber:R.number().int().positive(),runAttempt:R.number().int().positive(),scannedAt:R.string(),keySetHash:R.string(),coverage:Ho.shape.coverage}),Lf=R.strictObject({repositories:R.array(Op).max(dt.repositories),scans:R.array(Kf).max(dt.repositories*dt.branches)}),Zf=R.strictObject({key:Zo,references:R.number().int().nonnegative(),coveredTargets:R.number().int().nonnegative(),expiredTargets:R.number().int().nonnegative(),uncertainTargets:R.number().int().nonnegative()}),l0=R.strictObject({available:R.boolean().default(!0),settings:Lf,expectedTargets:R.number().int().min(0).max(80),features:R.array(Zf).max(2001),truncated:R.boolean()});import{z as X}from"zod";var Ge=X.string().min(1).max(200),ai=X.iso.datetime({offset:!0}),er=X.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Wo=X.number().int().min(0).max(1e12),Pp=X.number().int().min(1).max(1e12),wp={...Ve,type:X.literal("coupon.redeemed"),grantId:X.uuid()},_p={...Ve,type:X.literal("usage.observed"),merchantTransactionId:Ge,resource:Ge,unit:Ge,quantity:Pp},Hf=X.strictObject({...Ve,type:X.literal("fulfillment.updated"),operationId:X.uuid(),merchantFulfillmentId:Ge,status:X.enum(["pending","applied","failed"])}),Jf=X.strictObject({...Ve,type:X.literal("benefit.claimed"),merchantBenefitId:Ge,resource:Ge,unit:Ge,quantity:Pp,expiresAt:ai.nullable(),revision:er}),Wf=X.strictObject({...Ve,type:X.literal("benefit.closed"),merchantBenefitId:Ge,status:X.enum(["failed","expired","canceled"]),revision:er}),Qf=X.strictObject({...Ve,type:X.literal("benefit.updated"),merchantBenefitId:Ge,status:X.enum(["active","expired","revoked"]),remainingQuantity:Wo.nullable(),expiresAt:ai.nullable(),revision:er}),Xf=X.strictObject({...Ve,type:X.literal("authorization.updated"),merchantAuthorizationId:Ge,kind:X.literal("auto_topup"),status:X.enum(["pending","effective","revoked","failed"]),termsReference:Ge.nullable(),revision:er}),Yf=X.strictObject({...Ve,type:X.literal("balance.observed"),resource:Ge,unit:Ge,availableQuantity:Wo,reservedQuantity:Wo,periodStartsAt:ai.nullable(),periodEndsAt:ai.nullable(),revision:er}),Cp=X.union([X.discriminatedUnion("type",[...$a,Hf,Jf,Wf,Qf,Xf,Yf]),X.strictObject({...wp,productVersionId:X.uuid(),subscriptionId:X.string().trim().min(1).max(255)}),X.strictObject({...wp,merchandiseId:X.uuid()}),X.strictObject({..._p,operation:X.literal("consume")}),X.strictObject({..._p,operation:X.literal("reverse"),reversalOf:Ge})]),kp=X.strictObject({id:X.uuid(),eventId:X.string().min(1).max(200),source:X.literal("merchant"),providerVerified:X.literal(!1),outcome:X.string().min(1).max(100)});import{z}from"zod";var Rp=bc,eg=Rp.extend({invoice_id:Rp.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Qo=z.strictObject({name:z.string().trim().min(1).max(255),memo:z.string().max(1e4).nullable().optional(),footer:z.string().max(1e4).nullable().optional(),net_terms_days:z.number().int().positive().nullable().optional()}),tg=Qo.extend({id:z.string().min(1).max(255),created_at:z.number().nullable()}),Ep=z.strictObject({items:z.array(tg).max(50),nextCursor:z.uuid().nullable()}),y0=z.discriminatedUnion("action",[z.strictObject({action:z.literal("create"),requestId:z.uuid(),values:Qo}),z.strictObject({action:z.literal("update"),id:z.string().min(1).max(255),values:Qo}),z.strictObject({action:z.literal("delete"),id:z.string().min(1).max(255)})]),Mp=z.discriminatedUnion("action",[z.strictObject({action:z.literal("create"),requestId:z.uuid(),params:pn}),z.strictObject({action:z.enum(["finalize","send","pay","void"]),requestId:z.uuid(),invoiceId:z.uuid()}),z.strictObject({action:z.literal("reissue"),requestId:z.uuid(),invoiceId:z.uuid(),params:eg})]),Xo=z.strictObject({id:z.uuid(),customerId:z.uuid(),providerInvoiceId:z.string().nullable(),status:z.enum(["draft","open","paid","void","uncollectible"]),currency:z.string(),totalMinor:z.string().regex(/^-?\d+$/),paidMinor:z.string().regex(/^\d+$/),refundedMinor:z.string().regex(/^\d+$/),hostedInvoiceUrl:z.url().nullable(),createdAt:z.number(),collectionMethod:z.enum(["send_invoice","charge_automatically"]).nullable()}),Tp=Xo.extend({lines:z.array(z.strictObject({id:z.uuid(),description:z.string(),amountMinor:z.string().regex(/^-?\d+$/),netAmountMinor:z.string().regex(/^-?\d+$/),quantity:z.number().nullable(),periodStart:z.number().nullable(),periodEnd:z.number().nullable()})).max(1e3)}),vn=z.strictObject({taskId:z.uuid(),status:z.enum(["ready","running","done","dead"]),invoice:Xo.nullable(),errorCode:z.string().nullable()}),Dp=z.strictObject({items:z.array(Xo).max(50),nextCursor:z.uuid().nullable(),operations:z.array(vn).max(50),operationsLimited:z.boolean()});var ng=c.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"]),zp={scope:me,permissions:c.array(ng),expiresAt:c.iso.datetime().nullable()},uO=c.discriminatedUnion("kind",[c.object({...zp,kind:c.literal("server"),keyId:c.string().min(1)}),c.object({...zp,kind:c.literal("customer"),customerId:c.string().min(1),identityKind:c.enum(["identified","guest"]),expiresAt:c.iso.datetime()})]),A=c.object({requestId:c.uuid(),scope:me}).strict(),rg=_u.safeExtend({fingerprint:Yr.optional()}).strict(),ig=A.extend({customer:yn,created:c.boolean()});function Bp(){return A.extend({offer:Tn.nullable(),reason:Is.nullable()})}var I={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:ic,response:A.extend({message:c.object({messageId:c.uuid(),channel:Nn,acceptedAt:c.iso.datetime({offset:!0}),status:c.enum(["accepted","sending","completed","canceled"]),replayed:c.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:c.strictObject({messageId:c.uuid()}),response:A.extend({message:c.object({id:c.uuid(),channel:Nn,status:c.enum(["accepted","sending","completed","canceled"]),deliveries:c.array(c.object({id:c.uuid(),status:ac,attempts:c.number().int().nonnegative(),receipts:c.array(c.object({kind:sc,occurredAt:c.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:us,response:A.extend({installation:Ar})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:ps,response:A.extend({installation:Ar})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:jr,response:A.extend({installation:Ar})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:c.strictObject({channel:Nn}),response:A.extend({preference:Ti})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:oc,response:A.extend({preference:Ti})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:c.strictObject({cursor:c.uuid().optional()}),response:A.extend({templates:Ep})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:c.strictObject({customerId:c.uuid(),params:pn}),response:A.extend({preview:Ji})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:c.strictObject({customerId:c.uuid(),requestId:c.uuid(),params:pn}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:A.extend({operation:vn})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:c.strictObject({customerId:c.uuid(),command:Mp}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:A.extend({operation:vn})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:c.strictObject({customerId:c.uuid(),taskId:c.uuid()}),response:A.extend({operation:vn})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:c.strictObject({customerId:c.uuid(),cursor:c.uuid().optional()}),response:A.extend({invoices:Dp})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:c.strictObject({customerId:c.uuid(),invoiceId:c.uuid()}),response:A.extend({invoice:Tp})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:jp,response:A.extend({config:Ap})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Ho,response:A.extend({receipt:Jo})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:c.strictObject({}),response:A.extend({payload:uo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:au,response:A.merge(su)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:cu,response:A.merge(uu)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:c.strictObject({customerId:c.uuid(),sourceId:c.uuid()}),response:A.extend({balance:Ju})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:c.strictObject({customerId:c.uuid(),command:Hu}),response:A.extend({balance:Vo})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:c.strictObject({internal_feature_id:c.uuid(),customerId:c.uuid().optional(),entityId:c.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:A.extend({internal_feature_id:c.uuid(),config:Bi,model_markups:Cr})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:c.strictObject({customerId:c.uuid(),query:Ia}),response:A.extend({usage:fi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:c.strictObject({customerId:c.uuid(),command:Oa}),response:A.extend({usage:fi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:c.strictObject({customerId:c.uuid(),command:Hs}),response:A.extend({grant:$i})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Js,response:A.extend({grants:Ws})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:c.union(Wc.options.map(e=>e.extend({customerId:c.uuid().optional(),customerToken:c.string().regex(pt).optional()}))),response:A.extend({operation:Qc})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Fc.extend({customerId:c.uuid().optional()}),response:A.extend({setup:eo})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Nc.extend({customerId:c.uuid().optional()}),response:A.extend({setup:eo})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:zc.safeExtend({customerId:c.uuid()}),response:A.extend({batch:Vn})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Fr.extend({customerId:c.uuid()}),response:A.extend({batch:Vn})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Fr.extend({customerId:c.uuid()}),response:A.extend({batch:Vn})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Fr.extend({customerId:c.uuid()}),response:A.extend({batch:Vn})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:c.discriminatedUnion("action",[Nr.options[0].extend({customerId:c.uuid()}),Nr.options[1].extend({customerId:c.uuid()}),Nr.options[2].extend({customerId:c.uuid()})]),response:A.extend({trial:Yi})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Bc.extend({customerId:c.uuid()}),response:A.extend({trial:Yi})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:$r,response:A.extend({subscriptions:Zc})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:$r,response:A.extend({purchases:Hc})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Gc,response:A.extend({conflicts:Jc})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Kc,response:A.extend({resolution:Lc})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Vc,response:A.extend({verification:$c})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Pc.safeExtend({...cn,customerId:c.uuid().optional()}),response:A.extend({quote:ln})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Cp,response:A.extend({record:kp})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Nt.extend({customerId:c.uuid().optional(),intent:c.enum(["confirm","cancel"]).optional()}),response:A.extend({operation:mn})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Nt.extend({customerId:c.uuid().optional()}),response:A.extend({operation:mn})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Rc.safeExtend({customerId:c.uuid().optional()}),response:A.extend({quote:Mc})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Nt.extend({customerId:c.uuid().optional(),intent:c.enum(["confirm","cancel"]).optional()}),response:A.extend({operation:Wi})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Nt.extend({customerId:c.uuid().optional()}),response:A.extend({operation:Wi})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Tc.safeExtend({customerId:c.uuid()}),response:A.extend({quote:Qi})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Nt.extend({customerId:c.uuid()}),response:A.extend({operation:qr})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Nt.extend({customerId:c.uuid()}),response:A.extend({operation:qr})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:zs,response:A.extend({controls:Vi})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Cs,response:A.extend({prepared:Rs})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Es,response:A.extend({authorization:Rr})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Us,response:A.extend({coupons:Vs})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Ms,response:A.extend({authorization:Rr})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Fs,response:A.extend({invoices:Ns})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:qs.extend({customerId:c.uuid()}),response:A.extend({operation:vn})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Bs,response:A.extend({invoice:Bn})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:c.object({customerId:c.uuid(),command:Ds}).strict(),response:A.extend({controls:Vi})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:c.object({customerId:c.uuid(),command:Wu}).strict(),response:A.extend({entity:Qu})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:c.strictObject({customerId:c.uuid().nullable(),query:rp}),response:A.extend({analytics:ip})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:c.object({customerId:c.uuid().nullable(),query:Ht}).strict(),response:A.extend({analytics:tp})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:op,response:A.extend({batchId:c.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:ap,response:A.extend({batch:sp})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Ca.extend({customerId:c.string().min(1).optional()}),response:A.extend({check:Pn})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:c.strictObject({kind:Ot,selector:c.discriminatedUnion("type",[c.strictObject({type:c.literal("resource"),id:c.uuid()}),c.strictObject({type:c.literal("version"),id:c.uuid()})]),customerId:c.string().min(1).optional()}),response:A.extend({content:Ri})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Lu,response:A.extend({paywall:Qn})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:c.strictObject({processContext:Tr.optional(),...cn,selector:tu,customerId:c.string().min(1).optional(),commerce:ur,requirement:Qt.optional()}),response:A.extend({offering:nu,candidates:c.array(ka).max(20),availability:c.array(c.strictObject({productVersionId:c.uuid(),available:c.boolean(),reason:c.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:Pn.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:c.object({customerId:c.uuid().optional(),entityId:c.uuid().optional()}).strict(),response:A.extend({holdings:ja})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:c.object({customerId:c.uuid().optional(),query:Aa}).strict(),response:A.extend({ledger:wa})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Qs.extend({customerId:c.uuid().optional()}),response:A.extend({detail:Xs})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Gi.safeExtend({customerId:c.uuid().optional()}),response:A.extend({statement:Ys})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:c.object({customerId:c.uuid().optional(),command:wn.options[0]}).strict(),response:A.extend({quote:va})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:c.strictObject({customerId:c.uuid(),command:c.union([c.strictObject({eventName:c.string().min(1),quantity:ye.optional(),properties:ft.optional(),entityId:c.uuid().optional(),idempotencyKey:c.string().min(1).max(120)}),c.strictObject({internal_feature_id:c.uuid(),quantity:ye.optional(),properties:ft.optional(),entityId:c.uuid().optional(),idempotencyKey:c.string().min(1).max(120)})])}),response:A.extend({receipts:c.array(_n).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:c.object({customerId:c.uuid(),command:wn.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:A.extend({receipt:_n})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:hp,response:A.extend({redemption:gp})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:xp,response:A.extend({referralCode:Sp})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:bp,response:A.extend({checkout:yp})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:tc,response:A.extend({seats:Zi})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:nc,response:A.extend({seats:Zi})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:rg,response:ig},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:wo,response:A.extend({customer:yn})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:ku,response:A.extend(Ru.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Cu,response:A.extend(Pu.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:c.object({customerId:c.uuid()}).strict(),response:A.extend(en.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:c.strictObject({}),response:A.extend(en.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:c.strictObject({customerId:c.uuid(),sessionId:c.uuid().optional()}),response:A.extend({revoked:c.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:c.strictObject({guestToken:c.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Yr.optional()}),response:A.extend({customerId:c.uuid(),guestToken:c.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:c.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:c.strictObject({guestToken:c.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:A.extend(en.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:c.strictObject({guestToken:c.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:c.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:c.uuid()}),response:A.extend({customer:yn,switched:c.boolean(),replayed:c.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:c.strictObject({code:c.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:c.uuid()}),response:Bp()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:c.object({}).strict(),response:A.extend({offers:c.array(Tn)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:c.object({customerId:c.string().min(1).max(255).optional(),couponId:c.uuid(),...cn,requestId:c.uuid(),couponContentDigest:c.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Bp()}},pO={recordMerchantEvent:I.recordMerchantEvent,sendMessage:I.sendMessage,readMessage:I.readMessage,bindPushInstallation:I.bindPushInstallation,readPushInstallation:I.readPushInstallation,updatePushAddress:I.updatePushAddress,readMessagingPreference:I.readMessagingPreference,setMessagingPreference:I.setMessagingPreference,listInvoiceTemplates:I.listInvoiceTemplates,previewInvoice:I.previewInvoice,createInvoice:I.createInvoice,manageInvoice:I.manageInvoice,readInvoiceOperation:I.readInvoiceOperation,listInvoices:I.listInvoices,getInvoice:I.getInvoice,getCodeReferenceConfig:I.getCodeReferenceConfig,submitCodeReferences:I.submitCodeReferences,getFeatures:I.getFeatures,evaluateFeatures:I.evaluateFeatures,trackEvents:I.trackEvents,setupPayment:I.setupPayment,readPaymentSetup:I.readPaymentSetup,previewSubscriptionBatch:I.previewSubscriptionBatch,confirmSubscriptionBatch:I.confirmSubscriptionBatch,readSubscriptionBatch:I.readSubscriptionBatch,abandonSubscriptionBatch:I.abandonSubscriptionBatch,manageSubscriptionTrial:I.manageSubscriptionTrial,readSubscriptionTrial:I.readSubscriptionTrial,listSubscriptions:I.listSubscriptions,listPurchases:I.listPurchases,listSubscriptionConflicts:I.listSubscriptionConflicts,retrySubscriptionConflict:I.retrySubscriptionConflict,readAiPricing:I.readAiPricing,readUsage:I.readUsage,setUsage:I.setUsage,previewRefund:I.previewRefund,refund:I.refund,readRefund:I.readRefund,previewUpdate:I.previewUpdate,update:I.update,readSubscriptionUpdate:I.readSubscriptionUpdate,restoreNativePurchase:I.restoreNativePurchase,verifySubscriptions:I.verifySubscriptions,previewAttach:I.previewAttach,attach:I.attach,readSubscriptionOperation:I.readSubscriptionOperation,manageBalanceGrant:I.manageBalanceGrant,readBalanceSource:I.readBalanceSource,adjustBalance:I.adjustBalance,listBalanceGrants:I.listBalanceGrants,readBillingControls:I.readBillingControls,prepareBillingAuthorization:I.prepareBillingAuthorization,confirmBillingAuthorization:I.confirmBillingAuthorization,setBillingCoupons:I.setBillingCoupons,revokeBillingAuthorization:I.revokeBillingAuthorization,listBillingInvoices:I.listBillingInvoices,confirmBillingAdjustment:I.confirmBillingAdjustment,prepareBillingAdjustment:I.prepareBillingAdjustment,manageBillingLimits:I.manageBillingLimits,createCustomer:I.createCustomer,getCustomer:I.getCustomer,listCustomers:I.listCustomers,updateCustomer:I.updateCustomer,createSession:I.createSession,refreshSession:I.refreshSession,revokeSessions:I.revokeSessions,createGuestCustomer:I.createGuestCustomer,resumeGuestSession:I.resumeGuestSession,claimGuestCustomer:I.claimGuestCustomer,checkEntitlement:I.checkEntitlement,resolveOffering:I.resolveOffering,resolveContent:I.resolveContent,resolvePaywall:I.resolvePaywall,readHoldings:I.readHoldings,readLedger:I.readLedger,readBillingInvoice:I.readBillingInvoice,readCreditStatement:I.readCreditStatement,quoteBalance:I.quoteBalance,trackUsage:I.trackUsage,mutateBalance:I.mutateBalance,manageUsageEntity:I.manageUsageEntity,readUsageAnalytics:I.readUsageAnalytics,readCreditAnalytics:I.readCreditAnalytics,submitUsageBatch:I.submitUsageBatch,readUsageBatch:I.readUsageBatch,listOffers:I.listOffers,grantOffer:I.grantOffer,redeemCoupon:I.redeemCoupon,redeemReward:I.redeemReward,createReferralCode:I.createReferralCode,claimRewardProduct:I.claimRewardProduct,readSeats:I.readSeats,manageSeat:I.manageSeat};import{z as Yo}from"zod";var tr=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function ea(e,t,n){let r={},o,a,l,p="next",d;switch(e.type){case"entry":d=e.next;break;case"condition":{let v=e.cases.findIndex(h=>di(t.attributes??{},h.condition,t.savedGroups??{}));p=v<0?"default":`case:${v}`,d=v<0?e.default:e.cases[v].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new tr("Required GB Feature is unavailable");o=An(e.featureKey,t),l=o.value,Object.assign(r,Dt(e,{value:l})),d=e.next;break;case"split":{let v=n[e.experimentId];if(!v)throw new tr("Required GB Experiment is unavailable");if(a=ba(v,t),l=a.value,p=a.inExperiment&&!a.passthrough&&typeof l=="string"?l:"notParticipating",d=p==="notParticipating"?e.notParticipating:e.routes[p],!d)throw new tr("Experiment Variation has no published route");break}case"offering":{let v=e.configuration.source==="fixed"?e.configuration.versionId:An(e.configuration.featureKey,t).value;l={type:"offering_version",id:Yo.uuid().parse(v)},Object.assign(r,Dt(e,{value:l})),d=e.next;break}case"coupon":case"coupons":l=e.type==="coupons"?e.couponIds.map(v=>({type:"reward",id:v})):{type:"reward",id:e.couponId},Object.assign(r,Dt(e,{value:l})),d=e.next;break}return{port:p,target:d,projections:r,...l===void 0?{}:{value:l},...o?{feature:o}:{},...a?{experiment:a}:{}}}function yO(e,t,n){Yo.uuid().parse(e),Yo.number().int().nonnegative().parse(t);let r=ar(sr(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as _}from"zod";var Rt=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),og=_.enum(["running","waiting","completed","closed","ineligible","failed"]),ta=_.discriminatedUnion("type",[jo,_.strictObject({type:_.literal("wait"),receiptId:_.uuid(),kind:_.enum(["timer","event","operation"]),deadline:_.iso.datetime({offset:!0}).nullable(),eventName:Rt.optional()}),_.strictObject({type:_.literal("open_url"),receiptId:_.uuid(),url:Po,openIn:Co}),_.strictObject({type:_.literal("event"),receiptId:_.uuid(),event:Rt})]),ag=_.strictObject({type:_.literal("funnel"),id:_.uuid(),versionId:_.uuid()}),sg={id:Rt,presentation:gt,outputs:_.array(Rt).max(250),inputs:bi,values:_.record(_.string(),te).optional(),offeringKey:we.optional(),capabilities:Xt,customerData:za,dataCursors:_.record(Rt,lr.nullable())},cg=_.strictObject({...sg,content:_.strictObject({type:_.literal("document"),document:Le})}),nr=_.strictObject({id:_.uuid(),source:ag,revision:_.number().int().nonnegative(),visit:_.number().int().nonnegative(),nodeId:Rt,nodeType:_.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:og,stopped:_.boolean(),canBack:_.boolean(),authenticated:_.boolean(),locale:_.string().min(1).max(35),answers:Et,parameters:ut,variables:_.record(_.string(),te),output:te.nullable(),screen:cg.nullable(),paywall:_.strictObject({receiptId:_.uuid(),resolution:_.union([Wn,Qn]),quote:ln.nullable(),operation:mn.nullable(),purchaseRequestId:_.uuid().nullable(),selectionGeneration:_.number().int().nonnegative().optional(),canReselect:_.boolean().optional()}).nullable(),instruction:ta.nullable(),pendingRequest:_.strictObject({requestId:_.uuid(),authenticationRequired:_.boolean()}).nullable(),runExpiresAt:_.iso.datetime({offset:!0}),credentialExpiresAt:_.iso.datetime({offset:!0}).nullable()}),In=_.strictObject({scope:me,run:nr,settlement:_.strictObject({requestId:_.uuid(),state:_.enum(["pending","unknown","settled"]),operationId:_.uuid().nullable(),receiptId:_.uuid().nullable().optional()}).optional(),purchase:_.strictObject({receiptId:_.uuid(),quote:ln.nullable(),operation:mn.nullable(),canReselect:_.boolean().optional()}).optional(),review:_.strictObject({activeOperationId:_.uuid().nullable(),pages:_.array(_.strictObject({receiptId:_.uuid(),nodeId:Rt,visit:_.number().int().nonnegative()})).max(100),page:_.strictObject({receiptId:_.uuid(),nodeId:Rt,visit:_.number().int().nonnegative(),document:Le,answers:Et,inputs:bi,values:_.record(_.string(),te).optional()}).nullable(),coupons:_.array(_.strictObject({grantId:_.uuid(),status:_.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:_.string().nullable()})).max(100),purchases:_.array(_.strictObject({receiptId:_.uuid(),operationId:_.uuid(),status:_.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:_.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:_.uuid().optional()}),qp=In.extend({run:nr.extend({paywall:nr.shape.paywall.unwrap().extend({resolution:Qn}).nullable()})});var TO="X-Indiana-Server-Key";import{z as q}from"zod";import{z as G}from"zod";import{z as Pe}from"zod";var ug=Pe.strictObject({selector:Pe.string().min(1).max(2048),action:Pe.enum(["set","append","remove"]),attribute:Pe.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:Pe.string().max(5e4).optional(),parentSelector:Pe.string().max(2048).optional(),insertBeforeSelector:Pe.string().max(2048).optional()}),pg=Pe.strictObject({variation:Pe.string().min(1).max(128),description:Pe.string().max(2e3).default(""),css:Pe.string().max(1e5).default(""),js:Pe.string().max(1e5).default(""),domMutations:Pe.array(ug).max(200).default([]),iam:gu.optional(),renderGuard:Lr.optional()}),na=pg.omit({variation:!0,description:!0,iam:!0}),lg=hn.omit({variations:!0,active:!0}).extend({changeId:Pe.string().regex(/^[a-f0-9]{64}$/),variations:Pe.tuple([na,na]).rest(na).refine(e=>e.length<=20)}),Fp=Pe.strictObject({trackExposures:Pe.boolean(),environmentId:Pe.uuid(),generation:Pe.string().regex(/^[a-f0-9]{64}$/),experiments:Pe.array(lg).max(100),savedGroups:Gn});var rr=G.string().regex(/^[a-f0-9]{64}$/),LO=G.strictObject({iam:rr,executionContracts:G.union([G.tuple([G.literal("funnel-run/1")]),G.tuple([G.literal("funnel-process/1")])]).default(["funnel-run/1"])}),mg=G.strictObject({release:rr,render:Lr,button:G.strictObject({selector:G.string().min(1).max(512),elementKey:G.string().min(1).max(256),tag:G.enum(["button","a","input"])}).nullable()}),ZO=G.strictObject({scope:me.extend({environmentId:G.uuid()}),release:rr,validatedAt:G.iso.datetime({offset:!0}),validUntil:G.iso.datetime({offset:!0}),entries:G.array(G.strictObject({id:G.uuid(),funnelId:G.uuid(),versionId:G.uuid(),event:G.enum(["screen_enter","button_click"]),target:mg})).max(4e3)}),Np=G.strictObject({operation:G.literal("entry_start"),funnelId:G.uuid(),versionId:G.uuid(),entryId:G.uuid(),release:rr,requestId:G.uuid(),locale:G.string().min(1).max(35).default("en")}),Up=G.strictObject({scope:me,suppressed:G.literal(!0),reason:G.enum(["frequency","in_progress"]),retryAt:G.iso.datetime({offset:!0}).nullable()}),HO=G.strictObject({experimentId:G.uuid(),splitNodeId:G.string().min(1).max(128)}),dg=G.strictObject({experimentId:G.uuid(),experimentKey:G.string().min(1).max(128),variationKey:G.string().min(1).max(128),inExperiment:G.boolean(),generation:G.string().min(1).max(256)}),Vp=G.strictObject({operation:G.literal("page_experiments"),release:rr,usedReceiptIds:G.array(G.uuid()).max(20).default([]),customerToken:G.string().regex(pt).optional()}),JO=G.strictObject({scope:me,runId:G.uuid(),assignments:G.array(dg.extend({receiptId:G.uuid()})).max(100),payload:Fp});var ct=q.literal(lo),fg=q.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),ra=q.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),$p=q.discriminatedUnion("type",[q.strictObject({type:q.literal("guest"),guestToken:ra}),q.strictObject({type:q.literal("customer"),customer:xt,customerData:Pt.optional()})]),ia=q.strictObject({id:q.uuid(),runId:q.uuid(),customerId:q.uuid(),requestId:q.uuid(),acceptedAt:q.iso.datetime({offset:!0})}),gg=q.strictObject({participantId:q.uuid(),startedAs:q.enum(["guest","identified"]),binding:ia.omit({runId:!0,requestId:!0}).nullable()}),hg=q.union([ta,q.strictObject({type:q.literal("authentication_required"),reason:q.enum(["customer_required","customer_experiment_required"]),nodeId:q.string().min(1).max(64),visit:q.number().int().nonnegative()})]),bg=nr.omit({authenticated:!0}).extend({identity:gg,instruction:hg.nullable()}),yg=q.discriminatedUnion("operation",[tt.options[2].omit({customerToken:!0}),tt.options[3].omit({customerToken:!0}),tt.options[4].omit({customerToken:!0}),tt.options[5].omit({customerToken:!0}),tt.options[6].omit({customerToken:!0}),tt.options[7].omit({customerToken:!0})]),si={contract:ct,customerToken:q.string().regex(pt)},Gp={contract:ct,requestId:q.uuid(),runToken:fg,externalUserId:xt.options[1].shape.value},Kp=q.discriminatedUnion("operation",[q.strictObject({contract:ct,operation:q.literal("describe")}),q.strictObject({contract:ct,operation:q.literal("start"),source:$p,funnelId:tt.options[0].shape.funnelId,requestId:q.uuid(),locale:tt.options[0].shape.locale,parameters:tt.options[0].shape.parameters}),Np.omit({operation:!0}).extend({contract:ct,operation:q.literal("entry_start"),source:$p}),q.strictObject({...Gp,operation:q.literal("bind_customer"),guestToken:ra,claimRequestId:q.uuid(),expectedBindingId:q.null()}),q.strictObject({...Gp,operation:q.literal("binding_status"),guestToken:ra.optional()}),tt.options[1].omit({operation:!0,customerToken:!0}).extend({...si,operation:q.literal("get"),settlementBindingId:q.uuid().nullable().optional()}),tt.options[8].omit({operation:!0,customerToken:!0}).extend({...si,operation:q.literal("review")}),Vp.omit({customerToken:!0}).extend(si),q.strictObject({...si,operation:q.literal("command"),identity:q.strictObject({bindingId:q.uuid().nullable()}),command:yg})]),xg=In.omit({run:!0}).extend({contract:ct,run:bg,settlement:In.shape.settlement.unwrap().extend({accepted:q.boolean().nullable().optional()}).optional()}),oj=Up.extend({contract:ct}),aj=q.discriminatedUnion("operation",[Kp.options[1].omit({contract:!0,source:!0,requestId:!0}),Kp.options[2].omit({contract:!0,source:!0,requestId:!0})]),sj=xg.extend({binding:ia,outcome:q.enum(["bound","already_bound"]),replayed:q.boolean()}),cj=q.discriminatedUnion("state",[q.strictObject({contract:ct,scope:me,state:q.literal("not_accepted")}),q.strictObject({contract:ct,scope:me,state:q.literal("conflict")}),q.strictObject({contract:ct,scope:me,state:q.literal("bound"),binding:ia})]),uj=q.strictObject({contract:ct,scope:me,keyId:q.uuid(),operations:q.array(q.string()).max(20)});import{z as $e}from"zod";import{z as ci}from"zod";var fj=ci.strictObject({operation:ci.literal("renew_run"),runId:ci.uuid(),customerId:ci.uuid()}),Lp=In.refine(e=>!!e.runToken,"Renewal returns a credential"),Zp=qp.refine(e=>!!e.runToken,"Renewal returns a credential");var Ij=$e.discriminatedUnion("operation",[$e.strictObject({operation:$e.literal("campaign_decide"),..._o}).refine(Vt,$t),$e.strictObject({operation:$e.literal("campaign_start"),funnelId:$e.uuid(),requestId:$e.uuid(),customer:xt,customerData:Pt.optional(),locale:$e.string().min(1).max(35),parameters:ut,cooldownSeconds:$e.number().int().min(1).max(2592e3)}).refine(Vt,$t)]),Sg=$e.union([$e.strictObject({scope:me,suppressed:$e.literal(!0),reason:$e.enum(["frequency","in_progress"]),retryAt:$e.iso.datetime({offset:!0})}),Lp]),Oj=$e.union([Sg.options[0],Zp]);import{z as ie}from"zod";var On=ie.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Jp=ie.strictObject({entry:On,nodes:ie.array(ie.strictObject({id:On,type:ie.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:ie.record(ie.string(),On),writes:ie.record(we,we),resources:ie.strictObject({screenId:On.optional(),paywallVersionId:ie.uuid().optional(),couponId:ie.uuid().optional(),couponIds:ie.array(ie.uuid()).max(20).optional(),experimentId:ie.uuid().optional(),featureKey:ie.string().optional(),offeringVersionId:ie.uuid().optional()})})).min(1).max(500)}),Hp={scope:me,funnelId:ie.uuid(),versionId:ie.uuid(),evaluationRevision:ie.number().int().nonnegative(),expiresAt:ie.iso.datetime({offset:!0}).nullable(),topology:Jp},jn=ie.discriminatedUnion("evaluationMode",[ie.strictObject({...Hp,evaluationMode:ie.literal("local"),growth:_t,conditions:ie.record(On,ie.array(ie.strictObject({condition:it,port:ie.string()})))}),ie.strictObject({...Hp,evaluationMode:ie.literal("remote")})]),vg=jn.options[0].extend({evaluation:ie.strictObject({maxTransitions:ie.number().int().min(1).max(1e4),variables:ie.record(we,rn),outputSchema:nn,terminals:ie.record(On,ie.strictObject({outcome:ie.enum(["completed","closed","ineligible","failed"]),output:Ln.nullable()}))})});function Ig(e){return Jp.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(l=>l.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,l)=>{n[`case:${l}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=ie.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function Og(e){let t=Ct.parse(e.document),n=e.evaluationMode==="local"?_t.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:Ig(t)};return jn.parse(e.evaluationMode==="remote"?r:{...r,growth:ii(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((a,l)=>({condition:a.condition,port:`case:${l}`}))]))})}function Mj(e){let t=Og(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ct.parse(e.document);return vg.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}import{z as nt}from"zod";import{z as Be}from"zod";var Wp=Be.discriminatedUnion("provider",[Be.strictObject({provider:Be.literal("apple"),orderId:Be.uuid(),receiptId:Be.uuid(),signedTransaction:Be.string().min(1).max(131072)}),Be.strictObject({provider:Be.literal("google"),orderId:Be.uuid(),receiptId:Be.uuid(),purchaseToken:Be.string().min(1).max(16384)})]),Qp=Be.strictObject({orderId:Be.uuid(),receiptId:Be.uuid(),transactionIds:Be.array(Be.string().min(1).max(255)).min(1).max(50),membership:Be.boolean()});var Uj=nt.strictObject({operation:nt.literal("native_receipt"),requestId:nt.uuid(),customerToken:nt.string().regex(pt),orderId:nt.uuid(),receiptId:nt.uuid(),nativeEvidence:Wp.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),Vj=nt.strictObject({scope:me,requestId:nt.uuid(),orderId:nt.uuid(),receiptId:nt.uuid(),orderStatus:nt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:nt.boolean(),nativeCompletion:Qp.optional()});import{z as be}from"zod";var Xp=be.string().regex(/^[a-f0-9]{64}$/),jg=hn.omit({variations:!0,active:!0}).extend({changeId:Xp,variations:be.array(be.strictObject({urlRedirect:be.string().max(2048)})).min(2).max(20)}),Lj=be.strictObject({environmentId:be.uuid(),trackExposures:be.boolean(),generation:Xp,experiments:be.array(jg).max(100),savedGroups:Gn}),Ag=be.strictObject({eventUuid:be.uuid(),timestamp:be.iso.datetime({offset:!0}).optional(),deviceId:be.string().min(1).max(128),sessionId:be.string().min(1).max(128).optional(),url:be.url().max(2048),pageTitle:be.string().max(512).optional(),experimentKey:be.string().min(1).max(255),variationKey:be.string().min(1).max(64)}),Zj=be.strictObject({events:be.array(Ag).min(1).max(20)}),Hj=be.strictObject({inserted:be.number().int().nonnegative(),duplicates:be.number().int().nonnegative(),skipped:be.number().int().nonnegative(),rejected:be.array(be.strictObject({index:be.number().int().nonnegative(),reason:be.string()}))});import{z as ve}from"zod";var aa=32,wg=522240;function sa(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var _g=ve.strictObject({nodeId:ve.string().min(1).max(64),visit:ve.number().int().nonnegative(),revision:ve.number().int().nonnegative()}),oa=ve.record(ve.string(),te),Pg=ve.strictObject({id:ve.uuid(),nodeId:ve.string().min(1).max(64),visit:ve.number().int().nonnegative(),input:ve.strictObject({schemaVersion:Zn.shape.schemaVersion,kind:Zn.shape.kind,selector:Zn.shape.selector,contract:Zn.shape.contract}),context:oa,removed:ve.array(ve.string()).max(100),attributes:oa,removedAttributes:ve.array(ve.string()).max(100),result:qu,offeringVersionId:ve.uuid().nullable(),events:ve.strictObject({entered:ve.string().regex(/^[1-9][0-9]{0,18}$/),decision:ve.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),eA=ve.strictObject({schemaVersion:ve.literal(1),mode:ve.enum(["local","remote"]),versionId:ve.uuid(),generation:ve.number().int().positive(),base:_g,context:oa,steps:ve.array(Pg).min(1).max(aa)}).refine(e=>Ze(e)<=wg,"Segment exceeds its byte budget");var Cg=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function ir(e){return Array.isArray(e)?e.some(ir):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&ir(n):!Cg.test(t))}function Yp(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(p=>p.id===t.screenId&&p.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(p=>ir(p.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(p=>p.id===t.screenId):null]);for(let[p,d]of Object.entries(e.variables))if(d.source.type==="attribute"&&d.source.key!=="funnelParticipantId"&&(a.includes(`variables.${p}`)||a.includes(JSON.stringify(p))))return"customer_required";if(t.type==="split"){let p=n.experiments?.[t.experimentId];if((p?.hashAttribute??"id")!=="funnelParticipantId"||ir(p?.condition)||p?.parentConditions?.length)return"customer_experiment_required"}let l=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return l&&n.features?.[l]?.rules?.some(p=>(p.hashAttribute??"id")!=="funnelParticipantId"||ir(p.condition)||p.parentConditions?.length)?"customer_experiment_required":null}var ca=class extends Error{constructor(n,r){super(r);this.code=n;this.name="FunnelLocalCalculationError"}code},ui=(e,t)=>new ca(e,t),kg=e=>({experiments:e.experiments,features:e.features});function Rg(e,t=ui){let n=new Map(e.topology.nodes.map(l=>[l.id,l])),r=ha(e.growth.savedGroups),o=kg(e.growth);function a(l,p){if(!Object.hasOwn(e.growth.features,l))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return An(l,p).value}return{nodes:n,savedGroups:r,features:o.features,feature:a,evaluate(l,p){let d=n.get(l);if(!d)throw t("NOT_FOUND","Funnel node is unavailable");let v,h;if(d.type==="condition"){let $=e.conditions[d.id];if(!$)throw t("INVALID_RESPONSE","Local condition rules are unavailable");v=ea({id:d.id,name:d.id,type:"condition",cases:$.map(C=>({condition:C.condition,target:d.outputs[C.port]})),default:d.outputs.default},p,o.experiments).port}else if(d.type==="feature"){if(!d.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");h=a(d.resources.featureKey,p),v="next"}else if(d.type==="split"){if(!(d.resources.experimentId?e.growth.experiments[d.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let C=ea({id:d.id,name:d.id,type:"split",experimentId:d.resources.experimentId,routes:d.outputs,notParticipating:d.outputs.notParticipating},p,o.experiments);h=C.value,v=C.port}else if(["offering","end","output"].includes(d.type)&&d.resources.featureKey)h=a(d.resources.featureKey,p),v=d.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let T=d.outputs[v]??(v==="value"?d.id:void 0);if(!T)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:l,port:v,target:T,...h===void 0?{}:{value:h}}}}}function dA(e,t,n,r=ui){return ua(e,r)(t,n)}function ua(e,t){let n=jn.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let a=Rg(n,t);return(l,p)=>(o(),Eg(a,l,p))}function Eg(e,t,n){let r=Ke.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:a,onExperimentViewed:l}=n,p={attributes:r,...o?{saveStickyBucketAssignmentDoc:d=>o(structuredClone(d))}:{},...a?{onFeatureUsage:(d,v)=>a(d,structuredClone(v))}:{},...l?{onExperimentViewed:(d,v)=>l(structuredClone(d),structuredClone(v))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,p)}function fA(e,t,n,r=ui){return el(ua(e,r),t,n)}function el(e,t,n){let r=[],o=[],a=[],l=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(p){let d=r.findIndex(T=>T.next.attributeName===p.attributeName&&T.next.attributeValue===p.attributeValue),v=p.attributeName+"||"+p.attributeValue,h={expected:n.sticky[v]??null,next:p};d<0?r.push(h):r[d]=h},onExperimentViewed(p,d){d.inExperiment&&d.hashUsed&&!d.passthrough&&o.push(te.parse({key:p.key,variationId:d.variationId,keyUsed:d.key,hashAttribute:d.hashAttribute,hashValue:d.hashValue}))},onFeatureUsage(p,d){a.push(te.parse({feature:p,value:d.value,source:d.source,...d.ruleId?{ruleId:d.ruleId}:{}}))}});return{port:l.port,...l.value===void 0?{}:{value:l.value},sticky:r,exposures:o,features:a}}function gA(e,t,n,r=ui){let o=n,a=new Map(t.graph.nodes.map(Z=>[Z.id,Z])),l=structuredClone(n.variables),p=structuredClone(o.sticky),d=[],v=n.nodeId,h=n.visit,T=!1,$,C=Z=>Yp(t,Z,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),u=Z=>($??=ua(e,r),el($,Z,{attributes:So({declarations:t.variables,attributes:o.attributes,parameters:n.parameters,answers:n.answers,results:l,savedGroups:{}}),sticky:p}));for(let Z=0;Z<aa;Z++){let E=a.get(v);if(!E||!sa(E)||C(E))break;if(h>=t.execution.maxTransitions&&(h>t.execution.maxTransitions||E.type!=="end"&&E.type!=="output")){if(!d.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let ae,Ce;if(["condition","feature","split"].includes(E.type)||E.type==="offering"&&E.configuration.source==="feature")ae=u(E.id),E.type==="offering"&&(ae.value={type:"offering_version",id:String(ae.value)}),E.type==="condition"?Ce=ae.port==="default"?E.default:E.cases[Number(ae.port.slice(5))]?.target:E.type==="split"?Ce=ae.port==="notParticipating"?E.notParticipating:E.routes[ae.port]:(E.type==="feature"||E.type==="offering")&&(Ce=E.next);else if(ae={port:"next",sticky:[],exposures:[],features:[]},(E.type==="entry"||E.type==="coupon"||E.type==="coupons")&&(Ce=E.next),E.type==="offering"&&E.configuration.source==="fixed"&&(ae.value={type:"offering_version",id:E.configuration.versionId},Ce=E.next),E.type==="end"||E.type==="output"){let ee=E.type==="end"?E.output:E.value;if(ae=ee?.type==="feature"?u(E.id):{...ae,port:"value",value:ee?.type==="literal"?ee.value:ee?.type==="variable"?Pi({source:"variable",key:ee.key,...ee.path?{path:ee.path}:{}},{declarations:t.variables,answers:n.answers,results:l,parameters:n.parameters,attributes:o.attributes,savedGroups:{}}):null},ee&&(ae.value===void 0||!Xe(t.outputSchema,ae.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let L=[...d,{nodeId:v,result:ae}];if(Ze({steps:L})>6e4){if(!d.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(d.push({nodeId:v,result:ae}),E.type==="feature"||E.type==="offering"||E.type==="coupon"||E.type==="coupons"){let ee=E.type==="coupons"?E.couponIds.map(H=>({type:"reward",id:H})):E.type==="coupon"?{type:"reward",id:E.couponId}:ae.value;if(ee===void 0)throw r("INVALID_RESPONSE","Node output is missing");let le=Dt(E,{value:ee});_i(t.variables,E,le),Object.assign(l,le)}for(let ee of ae.sticky)p[`${ee.next.attributeName}||${ee.next.attributeValue}`]=structuredClone(ee.next);if(E.type==="end"||E.type==="output"){T=!0;break}if(!Ce)throw r("INVALID_RESPONSE","Local pure exit is unavailable");v=Ce,h++}let b=a.get(v);return{steps:d,...!T&&b&&(!sa(b)||C(b))?{boundary:{nodeId:v,visit:h}}:{}}}import{z as Mg}from"zod";var SA=Mg.strictObject({document:Ct,configuration:jn.options[0]});var B_={name:"@tinkerlandai/longplay-sdk",version:"0.10.17",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var q_="https://api.longplayai.com";export{me as a,zh as b,Bh as c,qh as d,Fh as e,Ar as f,Uh as g,$h as h,Gh as i,Kh as j,Bg as k,qg as l,Ua as m,pt as n,en as o,tn as p,Ka as q,Kg as r,Lg as s,dl as t,Ja as u,Jg as v,gl as w,hl as x,bl as y,hr as z,yr as A,Ii as B,Sl as C,Wg as D,vl as E,Qg as F,Xg as G,Xa as H,th as I,nh as J,Ol as K,jl as L,ah as M,Xe as N,_i as O,Pi as P,Ri as Q,Rh as R,hx as S,_t as T,uo as U,Fd as V,su as W,lo as X,So as Y,pS as Z,lS as _,mS as $,kS as aa,RS as ba,ES as ca,tt as da,$u as ea,jf as fa,Af as ga,bI as ha,Fo as ia,_f as ja,yI as ka,xI as la,SI as ma,Qn as na,EI as oa,Yu as pa,Xu as qa,$o as ra,Pf as sa,UI as ta,I as ua,yO as va,ag as wa,In as xa,qp as ya,TO as za,mg as Aa,ZO as Ba,Np as Ca,Up as Da,Vp as Ea,JO as Fa,Kp as Ga,xg as Ha,oj as Ia,aj as Ja,sj as Ka,cj as La,uj as Ma,fj as Na,Lp as Oa,Ij as Pa,Oj as Qa,jn as Ra,vg as Sa,Og as Ta,Mj as Ua,Uj as Va,Vj as Wa,Lj as Xa,Rg as Ya,dA as Za,fA as _a,gA as $a,SA as ab,B_ as bb,q_ as cb};
|
|
6
|
+
${e}`)}async function ts(e){let t=Oi.parse(e);return crypto.subtle.importKey("raw",Ya(t.signingSecret),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function th(e,t,n,r=Date.now()){let o=String(Math.floor(r/1e3)),a=new Uint8Array(await crypto.subtle.sign("HMAC",await ts(t),es(e,n,o))),l=btoa(String.fromCharCode(...a)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");return{[Xa]:t.keyId,[Qa]:`t=${o},v1=${l}`}}async function nh(e,t,n,r,o=Date.now()){try{if(t.get(Xa)!==n.keyId)return!1;let a=/^t=([0-9]{1,12}),v1=([A-Za-z0-9_-]{43})$/.exec(t.get(Qa)??"");return!a||Math.abs(o/1e3-Number(a[1]))>300?!1:await crypto.subtle.verify("HMAC",await ts(n),Ya(a[2]),es(e,r,a[1]))}catch{return!1}}var ns={"zh-Hans":{merchandise:"\u51CF {discount}\uFF08\u5355\u6B21\u4F7F\u7528\uFF09",once:"\u9996\u671F\u51CF {discount}",repeating:"\u524D {months} \u4E2A\u6708\u6BCF\u6708\u51CF {discount}",forever:"\u6BCF\u671F\u51CF {discount}"},"zh-Hant":{merchandise:"\u6E1B {discount}\uFF08\u55AE\u6B21\u4F7F\u7528\uFF09",once:"\u9996\u671F\u6E1B {discount}",repeating:"\u524D {months} \u500B\u6708\u6BCF\u6708\u6E1B {discount}",forever:"\u6BCF\u671F\u6E1B {discount}"},en:{merchandise:"{discount} off \xB7 one use",once:"{discount} off your first payment",repeating:"{discount} off each month for the first {months} months",repeatingOne:"{discount} off the first month",forever:"{discount} off every payment"},ja:{merchandise:"{discount} \u5272\u5F15\uFF081\u56DE\u306E\u307F\uFF09",once:"\u521D\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15",repeating:"\u6700\u521D\u306E {months} \u304B\u6708\u9593\u3001\u6BCE\u6708 {discount} \u5272\u5F15",forever:"\u6BCE\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15"},ko:{merchandise:"{discount} \uD560\uC778 \xB7 1\uD68C \uC0AC\uC6A9",once:"\uCCAB \uACB0\uC81C {discount} \uD560\uC778",repeating:"\uCCAB {months}\uAC1C\uC6D4 \uB3D9\uC548 \uB9E4\uC6D4 {discount} \uD560\uC778",forever:"\uB9E4 \uACB0\uC81C {discount} \uD560\uC778"},es:{merchandise:"{discount} de descuento \xB7 un uso",once:"{discount} de descuento en el primer pago",repeating:"{discount} de descuento cada mes durante los primeros {months} meses",forever:"{discount} de descuento en cada pago",repeatingOne:"{discount} de descuento durante el primer mes"},fr:{merchandise:"{discount} de r\xE9duction \xB7 une utilisation",once:"{discount} de r\xE9duction sur le premier paiement",repeating:"{discount} de r\xE9duction par mois pendant les {months} premiers mois",forever:"{discount} de r\xE9duction sur chaque paiement",repeatingOne:"{discount} de r\xE9duction pendant le premier mois"},de:{merchandise:"{discount} Rabatt \xB7 einmalig",once:"{discount} Rabatt auf die erste Zahlung",repeating:"{discount} Rabatt pro Monat f\xFCr die ersten {months} Monate",forever:"{discount} Rabatt auf jede Zahlung",repeatingOne:"{discount} Rabatt im ersten Monat"},pt:{merchandise:"{discount} de desconto \xB7 um uso",once:"{discount} de desconto no primeiro pagamento",repeating:"{discount} de desconto por m\xEAs nos primeiros {months} meses",forever:"{discount} de desconto em cada pagamento",repeatingOne:"{discount} de desconto no primeiro m\xEAs"},it:{merchandise:"{discount} di sconto \xB7 un utilizzo",once:"{discount} di sconto sul primo pagamento",repeating:"{discount} di sconto al mese per i primi {months} mesi",forever:"{discount} di sconto su ogni pagamento",repeatingOne:"{discount} di sconto per il primo mese"},ru:{merchandise:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \xB7 \u043E\u0434\u043D\u043E \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435",once:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043F\u0435\u0440\u0432\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436",repeating:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043A\u0430\u0436\u0434\u044B\u0439 \u043C\u0435\u0441\u044F\u0446 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",repeatingOne:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u0432 \u043F\u0435\u0440\u0432\u044B\u0439 \u043C\u0435\u0441\u044F\u0446",forever:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043A\u0430\u0436\u0434\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436"},vi:{merchandise:"Gi\u1EA3m {discount} \xB7 d\xF9ng m\u1ED9t l\u1EA7n",once:"Gi\u1EA3m {discount} cho l\u1EA7n thanh to\xE1n \u0111\u1EA7u ti\xEAn",repeating:"Gi\u1EA3m {discount} m\u1ED7i th\xE1ng trong {months} th\xE1ng \u0111\u1EA7u",forever:"Gi\u1EA3m {discount} cho m\u1ED7i l\u1EA7n thanh to\xE1n"},th:{merchandise:"\u0E25\u0E14 {discount} \xB7 \u0E43\u0E0A\u0E49\u0E44\u0E14\u0E49\u0E04\u0E23\u0E31\u0E49\u0E07\u0E40\u0E14\u0E35\u0E22\u0E27",once:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E04\u0E23\u0E31\u0E49\u0E07\u0E41\u0E23\u0E01",repeating:"\u0E25\u0E14 {discount} \u0E15\u0E48\u0E2D\u0E40\u0E14\u0E37\u0E2D\u0E19\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",forever:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E17\u0E38\u0E01\u0E04\u0E23\u0E31\u0E49\u0E07"},id:{merchandise:"Diskon {discount} \xB7 sekali pakai",once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{merchandise:"\u062E\u0635\u0645 {discount} \xB7 \u0627\u0633\u062A\u062E\u062F\u0627\u0645 \u0648\u0627\u062D\u062F",once:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u062F\u0641\u0639\u0629 \u0627\u0644\u0623\u0648\u0644\u0649",repeating:"\u062E\u0635\u0645 {discount} \u0634\u0647\u0631\u064A\u064B\u0627 \u0644\u0645\u062F\u0629 {period}",forever:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0643\u0644 \u062F\u0641\u0639\u0629"}};function ji(e){let t=ya(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(a=>["TW","HK","MO"].includes(a))?"zh-Hant":"zh-Hans":n[0]??"en",o=ns[r];return o?{locale:t,copy:o}:{locale:"en",copy:ns.en}}function Ol(e,t,n="zh-CN"){let r=li(t);return ma(e,t,ji(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function jl(e,t="zh-CN"){let n=ji(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(e.percentOff/100):Ol(e.amountOffCents,e.currency,n)}var rs={zh:"\u524D {months} \u4E2A\u6708\u5185\u5F00\u51FA\u7684\u8D26\u5355\u51CF {discount}","zh-Hant":"\u524D {months} \u500B\u6708\u5167\u958B\u51FA\u7684\u5E33\u55AE\u6E1B {discount}",en:"{discount} off invoices issued within the first {months} months",ja:"\u6700\u521D\u306E {months} \u304B\u6708\u4EE5\u5185\u306E\u8ACB\u6C42\u304C {discount} \u5272\u5F15",ko:"\uCCAB {months}\uAC1C\uC6D4 \uB0B4 \uCCAD\uAD6C\uC11C {discount} \uD560\uC778",es:"{discount} de descuento en facturas emitidas durante los primeros {months} meses",fr:"{discount} de r\xE9duction sur les factures \xE9mises pendant les {months} premiers mois",de:"{discount} Rabatt auf Rechnungen innerhalb der ersten {months} Monate",pt:"{discount} de desconto nas faturas emitidas nos primeiros {months} meses",it:"{discount} di sconto sulle fatture emesse nei primi {months} mesi",ru:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u0441\u0447\u0435\u0442\u0430 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",vi:"Gi\u1EA3m {discount} cho h\xF3a \u0111\u01A1n trong {months} th\xE1ng \u0111\u1EA7u",th:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E43\u0E1A\u0E41\u0E08\u0E49\u0E07\u0E2B\u0E19\u0E35\u0E49\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",id:"Diskon {discount} untuk tagihan dalam {months} bulan pertama",ar:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u0641\u0648\u0627\u062A\u064A\u0631 \u0627\u0644\u0635\u0627\u062F\u0631\u0629 \u062E\u0644\u0627\u0644 \u0623\u0648\u0644 {period}"};function ah(e,t="zh-CN",n="month"){let r=ji(t),o=jl(e.discount,r.locale);if(e.appliesTo?.type==="merchandise")return r.copy.merchandise.replace("{discount}",o);let a=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",l=r.locale.split("-")[0]??"en",p=l==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":l,d=e.duration.type==="repeating"&&n!=="month"?rs[p]??rs.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],v=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return d.replace("{discount}",o).replace("{months}",a).replace("{period}",v)}import{z as W}from"zod";import{z as De}from"zod";var we=De.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),Ai=De.strictObject({type:De.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:De.boolean(),enum:De.array(De.string().max(255)).min(1).max(100).optional()}),nn=Ai.extend({type:De.enum([...Ai.shape.type.options,"array"]),items:Ai.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),rn=nn.safeExtend({source:De.discriminatedUnion("type",[De.strictObject({type:De.literal("input")}),De.strictObject({type:De.literal("node")}),De.strictObject({type:De.enum(["parameter","attribute"]),key:we})])}),Al=De.record(we,rn),xr=De.record(we,we).refine(e=>Object.keys(e).length<=20);function Xe(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>Xe(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&De.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function wi(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&wi(e.items,t.items)}function En(e,t){let n={};for(let[r,o]of Object.entries(e)){let a=o.source,l=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,p=a.type==="parameter"||a.type==="attribute"?a.key:r,d=Object.hasOwn(l,p),v=l[p];if(a.type==="attribute"&&p.includes(".")&&(!d||p.startsWith("merchandise."))){v=l,d=!0;for(let h of p.split(".")){if(!v||typeof v!="object"||!Object.hasOwn(v,h)||Array.isArray(v)&&(!/^(0|[1-9]\d*)$/.test(h)||Number(h)>=v.length)){d=!1;break}v=v[h]}}if(!(!d||v===void 0)){if(!Xe(o,v))throw new Error(`Invalid variable value: ${r}`);n[r]=v}}return n}function Dt(e,t){let n={};for(let[r,o]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,o))throw new Error("Node outputs cannot overwrite one another");n[o]=t[r]}return n}function _i(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[o,a]of Object.entries(n))if(!r.has(o)||e[o]?.source.type!=="node"||!Xe(e[o],a))throw new Error(`Invalid node variable write: ${o}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as zt}from"zod";var ot=zt.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),lt=zt.discriminatedUnion("source",[zt.strictObject({source:zt.literal("literal"),value:te}),zt.strictObject({source:zt.literal("variable"),key:zt.string().min(1).max(255),path:ot.optional()})]);function is(e,t){if(!t)return e;for(let n of ot.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Pi(e,t){if(e.source==="literal")return structuredClone(e.value);let n=En(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(te.parse(is(n[e.key],e.path)))}function Ci(e,t){let n=[...t].sort((o,a)=>a.length-o.length).find(o=>e===o||e.startsWith(o+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!ot.safeParse(r).success?null:{key:n,path:r}}function ki(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return ht(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Ea))]}function Sr(e){return ki(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function Ze(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let o=0;o<t.length;o++){let a=t.charAt(o);if(r)a==="\\"?o++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let l=o;for(;o+1<t.length&&/[0-9.eE+-]/.test(t.charAt(o+1));)o++;let p=t.slice(l,o+1);if(!/[eE]/.test(p))continue;let[d="",v]=p.split(/[eE]/),h=d.replace(/^-/,""),T=h.replace(".","").length,$=(h.includes(".")?h.indexOf("."):T)+Number(v),C=$<=0?2-$+T:$>=T?$:T+1;n+=C+(d.startsWith("-")?1:0)-p.length}}return n}var Ot=W.enum(["page","popup","banner"]),wl=3e5,os=W.strictObject({type:W.enum(["string","number","boolean","strings","json"]),nullable:W.boolean()}),_l=W.strictObject({inputs:W.record(Cn,os.extend({required:W.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:W.record(Cn,os).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Pl=W.strictObject({kind:Ot,schemaVersion:W.literal(1),name:W.string().trim().min(1).max(80),screen:Le,contract:_l}),vr=Pl.superRefine((e,t)=>{let n=(o,a)=>t.addIssue({code:"custom",message:o,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(o=>o.type!=="event"&&o.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(o=>o.type==="event").map(o=>o.id));(Object.keys(e.contract.outputs).some(o=>!r.has(o))||[...r].some(o=>!Object.hasOwn(e.contract.outputs,o)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),Ze(e)>wl&&n("Content document exceeds its byte budget",[])});function Cl(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var kl=vr.superRefine((e,t)=>{for(let n of Sr(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],o=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!Cl(o,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}It(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),as=W.strictObject({id:W.uuid(),kind:Ot,projectId:W.uuid(),environmentId:W.uuid(),name:W.string(),revision:W.number().int().nonnegative(),status:W.enum(["draft","published","archived"]),publishedVersionId:W.uuid().nullable(),createdAt:W.iso.datetime({offset:!0}),updatedAt:W.iso.datetime({offset:!0})}),jh=as.extend({draft:vr}),Ah=W.strictObject({rows:W.array(as).max(200),nextCursor:W.uuid().nullable()}),Ri=W.strictObject({id:W.uuid(),kind:Ot,resourceId:W.uuid(),projectId:W.uuid(),environmentId:W.uuid(),version:W.number().int().positive(),sourceRevision:W.number().int().nonnegative(),document:kl,createdAt:W.iso.datetime({offset:!0})}),wh=Ri.omit({document:!0}),_h=W.discriminatedUnion("action",[W.strictObject({action:W.literal("create"),kind:Ot,id:W.uuid(),document:vr}),W.strictObject({action:W.literal("save"),kind:Ot,id:W.uuid(),revision:W.number().int().nonnegative(),document:vr}),W.strictObject({action:W.enum(["publish","archive"]),kind:Ot,id:W.uuid(),revision:W.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as on}from"zod";var Ir=on.strictObject({items:on.array(on.strictObject({productVersionId:on.string().min(1).max(200),label:on.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:on.string().min(1).max(200).nullable(),grouping:Ta.optional()});function Rh(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(o=>o.versionId===r&&o.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}import{z as Ei}from"zod";var Rl=Ei.enum(["sandbox","live"]),me=Ei.object({projectId:Ei.string().min(1),environment:Rl}).strict();import{z as ue}from"zod";var Mn=ue.number().int().min(1).max(Number.MAX_SAFE_INTEGER),ss=ue.enum(["unknown","denied","provisional","granted"]),cs=ue.enum(["ios","android"]),Or=ue.strictObject({installationId:ue.uuid(),publicKey:ue.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:ue.iso.datetime({offset:!0}),signature:ue.string().regex(/^[A-Za-z0-9_-]{86}$/)}),Mi=ue.string().regex(/^[a-f0-9]{64}$/),us=Or.extend({sequence:Mn,platform:cs,credentialDigest:Mi}),ps=Or.extend({credentialDigest:Mi}),zh=Or.extend({sequence:Mn,platform:cs}),jr=Or.extend({sequence:Mn,credentialDigest:Mi,connectionId:ue.uuid().nullable(),kind:ue.enum(["fcm_token","apns_token"]).nullable(),token:ue.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:ss}),Bh=jr,qh=jr.extend({challenge:ue.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),Fh=ue.strictObject({requested:ue.literal(!0),expiresAt:ue.iso.datetime({offset:!0})}),Ar=ue.strictObject({installationId:ue.uuid(),bound:ue.boolean(),identitySeq:Mn,bindingGeneration:Mn,addressSeq:ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:ue.uuid().nullable(),addressStatus:ue.enum(["active","invalid"]).nullable(),permission:ss}),Ti=ue.strictObject({channel:ue.enum(["email","sms","voice","push"]),state:ue.enum(["unknown","allowed","denied"]),revision:ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:ue.iso.datetime({offset:!0}).nullable()}),Nh=ue.strictObject({state:ue.enum(["allowed","denied"]),revision:ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Uh(e,t,n){let r=["indiana_push_v1",e,t.projectId,t.environment,n.installationId,n.publicKey,n.issuedAt];e==="bind"?r.push(n.sequence,n.platform,n.credentialDigest):e==="detach"?r.push(n.sequence,n.platform):e==="read"?r.push(n.credentialDigest):r.push(n.sequence,n.credentialDigest,n.connectionId,n.kind,n.token,n.permission),e==="recovery_confirm"&&r.push(n.challenge);let o=JSON.stringify(r);if([...o].some(a=>a.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(o,a=>a.charCodeAt(0))}var $h="X-Indiana-Protocol",Gh="X-Indiana-SDK-Version";var Kh={current:"0.10"};import{z as an}from"zod";var wr=an.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"),Jh=an.object({amountCents:an.number().int().min(0).max(1e8),currency:oe,interval:an.enum(["free","month","year"]),currencyOptions:an.partialRecord(oe,an.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");import{z as y}from"zod";var El=y.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),ds=y.enum(["single_use","continuous_use"]),Di=y.record(y.string(),y.union([y.string(),y.number(),y.boolean()]).transform(String).pipe(y.string())),ls=y.string().min(1).max(64).refine(e=>!e.includes("::")),fs={credit_amount:y.number(),tier_behavior:y.never().optional(),tiers:y.never().optional()},gs={credit_amount:y.never().optional(),tier_behavior:y.literal("graduated"),tiers:y.array(y.strictObject({to:y.union([y.number(),y.literal("inf")]),credit_amount:y.number()}))},Ml=y.union([y.strictObject({match:Di,priority:y.number().int().optional(),...fs}),y.strictObject({match:Di,priority:y.number().int().optional(),...gs})]),Tl=y.strictObject({match:Di,factor:y.number().positive().optional(),add:y.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),ms={metered_feature_id:y.string(),feature_amount:y.number().optional(),dimensions:y.record(ls,Ml).optional(),multipliers:y.record(ls,Tl).optional()},zi=y.union([y.strictObject({...ms,...fs}),y.strictObject({...ms,...gs})]),Pr=y.number().min(-100),hs=y.record(y.string(),y.strictObject({markup:Pr})).nullish(),Cr=y.record(y.string().regex(/.+\/.+/),y.strictObject({markup:Pr.optional(),input_cost:y.number().min(0).optional(),output_cost:y.number().min(0).optional()})).nullish(),Dl=y.strictObject({default_markup:Pr.optional(),provider_markups:hs,model_markups:Cr}),Xh=y.strictObject({schema:y.array(zi).optional(),markups:Dl.optional()}),zl=y.strictObject({filters:y.array(y.strictObject({property:y.string(),operator:y.string(),value:y.array(y.string())})),aggregate:y.strictObject({type:y.string(),property:y.string().nullable()}),usage_type:ds}),bs=y.strictObject({schema:y.array(zi).min(1).refine(e=>new Set(e.map(t=>t.metered_feature_id)).size===e.length,"Credit rates must name each metered feature once"),invoice_credit:y.boolean().optional(),usage_type:ds.default("single_use").overwrite(()=>"single_use"),default_markup:Pr.optional(),provider_markups:hs}),Bi=bs.safeExtend({schema:y.array(zi).length(0)}),_r={id:El,name:y.string().min(1),display:y.strictObject({singular:y.string().optional(),plural:y.string().optional()}).nullish(),event_names:y.array(y.string()).default([]),model_markups:Cr,stripe_meter:y.strictObject({id:y.string(),event_name:y.string()}).nullish(),stripe_product_id:y.string().nullish()},qi=e=>y.discriminatedUnion("type",[y.strictObject({..._r,...e,type:y.literal("boolean"),config:y.null()}),y.strictObject({..._r,...e,type:y.literal("metered"),config:zl}),y.strictObject({..._r,...e,type:y.literal("credit_system"),config:bs}),y.strictObject({..._r,...e,type:y.literal("ai_credit_system"),config:Bi})]),Yh=qi({}),Bl=y.strictObject({id:y.boolean(),type:y.boolean(),usage_type:y.boolean()}),ql={internal_id:y.uuid(),org_id:y.uuid(),created_at:y.number(),env:y.enum(["sandbox","live"]),archived:y.boolean(),project_id:y.uuid(),environment_id:y.uuid(),revision:y.number().int().nonnegative(),update_rules:Bl},ys=qi(ql),eb=y.strictObject({rows:y.array(ys).max(200),nextCursor:y.uuid().nullable()}),tb=y.strictObject({features:y.array(ys).max(500),limited:y.boolean()}),nb=y.union([qi({action:y.literal("save"),internal_id:y.uuid().nullable(),revision:y.number().int().nonnegative()}),y.strictObject({action:y.enum(["archive","restore","delete"]),internal_id:y.uuid(),revision:y.number().int().nonnegative()})]);import{z as s}from"zod";import{z as M}from"zod";import{z as ke}from"zod";function jt(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,l){if(n(a))for(let[p,d]of Object.entries(a))p==="$elemMatch"?o(d,l):p==="$not"?r(d,l):p==="$all"&&Array.isArray(d)&&d.forEach(v=>r(v,l))}function o(a,l=""){if(n(a)){for(let[p,d]of Object.entries(a))if(["$and","$or","$nor"].includes(p)&&Array.isArray(d))d.forEach(v=>o(v,l));else if(p==="$not")o(d,l);else if(p==="$savedGroup"&&n(d))typeof d.attributeKey=="string"&&t.add(d.attributeKey);else if(!p.startsWith("$")){let v=l?`${l}.${p}`:p;t.add(v),r(d,v)}}}return o(e),[...t]}var Fl=ke.enum(["active","inactive"]),Nl=ke.preprocess((e,t)=>{let n=0;function r(o,a){if(!(++n>1e4||a>20)){if(Array.isArray(o))o.forEach(l=>r(l,a+1));else if(o&&typeof o=="object")for(let[l,p]of Object.entries(o))["__proto__","constructor","prototype"].includes(l)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(p,a+1)}}return r(e,0),e},Ke),Ul=ke.strictObject({id:ke.string().trim().min(1).max(255),name:ke.string().trim().min(1).max(255),status:Fl,metadata:Nl}),cb=Ul.extend({internal_id:ke.uuid(),project_id:ke.uuid(),environment_id:ke.uuid(),created_at:ke.iso.datetime({offset:!0}),updated_at:ke.iso.datetime({offset:!0})}),Ss=ke.union([ke.strictObject({id:ke.string().trim().min(1).max(255)}),ke.strictObject({internalId:ke.uuid()})]),ub=ke.enum(["customer","merchandise","context"]),pb=ke.enum(["system","stored","request"]),lb=ke.enum(["customer","merchandise","mixed"]),xs=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Fi(e,t={},n=new Set){if(jt(e).some(xs))return!0;for(let r of vt(e)){if(n.has(r))continue;n.add(r);let o=t[r];if(o?.type==="list"&&xs(o.attributeKey)||o?.type==="condition"&&Fi(o.condition,t,n))return!0}return!1}var bb=M.enum(["draft","active","paused","archived"]),At=M.discriminatedUnion("type",[M.object({type:M.literal("percent"),percentOff:M.number().min(1).max(100).multipleOf(.01)}).strict(),M.object({type:M.literal("amount"),amountOffCents:M.number().int().min(1).max(1e8),currency:oe}).strict()]),He=M.discriminatedUnion("type",[M.object({type:M.literal("once")}).strict(),M.object({type:M.literal("repeating"),months:M.number().int().min(1).max(36)}).strict(),M.object({type:M.literal("forever")}).strict()]),vs=[M.object({type:M.literal("all")}).strict(),M.object({type:M.literal("plans"),planIds:M.array(M.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Vl=M.discriminatedUnion("type",[...vs,M.strictObject({type:M.literal("merchandise"),scope:M.discriminatedUnion("type",[M.strictObject({type:M.literal("all")}),M.strictObject({type:M.literal("selected"),merchandiseIds:M.array(M.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),M.strictObject({type:M.literal("condition"),condition:it})])})]),Ni=M.discriminatedUnion("type",[...vs,M.strictObject({type:M.literal("merchandise"),scope:M.strictObject({type:M.enum(["all","selected","condition"])})})]),$l=M.strictObject({firstPurchaseOnly:M.boolean(),condition:it}),yb=M.object({name:M.string().trim().min(1).max(80),description:M.string().max(500),discount:At,duration:He,appliesTo:Vl,eligibility:$l,selfClaimEnabled:M.boolean().default(!1),startsAt:M.iso.datetime().nullable(),endsAt:M.iso.datetime().nullable(),totalLimit:M.number().int().min(1).max(1e6).nullable(),perCustomerLimit:M.number().int().min(1).max(10),grantWindowHours:M.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!Fi(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"]}),xb=M.object({code:M.string().trim().transform(e=>e.toUpperCase()).pipe(M.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:M.number().int().min(1).max(1e6).nullable(),expiresAt:M.iso.datetime().nullable(),firstPurchaseOnly:M.boolean(),minimumAmountCents:M.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:oe.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Tn=M.object({id:M.uuid(),couponId:M.uuid(),status:M.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:M.iso.datetime(),expiresAt:M.iso.datetime(),coupon:M.object({name:M.string(),discount:At,duration:He,appliesTo:Ni}).strict()}).strict(),Is=M.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var _s=s.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Ui=s.string().regex(/^(0|[1-9]\d{0,14})$/),sn=s.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Gl=s.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Dn=Gl,yt=ye.refine(e=>/[1-9]/.test(e)),qe=s.iso.datetime({offset:!0}),kr=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},Kl=s.array(s.object({upTo:yt.nullable(),unitAmountMinor:_s,flatAmountMinor:s.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&kr(t.upTo)>kr(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Ll=s.discriminatedUnion("kind",[s.object({kind:s.literal("flat"),units:yt,unitAmountMinor:_s}).strict(),s.object({kind:s.enum(["graduated","volume"]),units:yt,tiers:Kl}).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"),Zl=s.strictObject({interval:s.enum(["month","year"]),count:s.number().int().min(1).max(12),anchor:s.enum(["membership","calendar"])}),zn=s.object({currency:oe,pricing:Ll,billingCycle:Zl.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Os={requestId:s.uuid(),productVersionId:s.uuid(),internal_feature_id:s.uuid(),currency:oe},Ps=s.strictObject({interval:s.enum(["hour","day","week","month"]),intervalCount:s.number().int().min(1).max(12),limit:s.number().int().min(1).max(1e6)}),Cs=s.discriminatedUnion("kind",[s.object({...Os,kind:s.literal("auto_topup"),threshold:mi,quantity:yt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Ps.optional()}).strict(),s.object({...Os,kind:s.literal("postpaid"),maxAmountMinorPerPeriod:Dn,maxOutstandingMinor:Dn}).strict()]),js={productVersionId:s.uuid(),internal_feature_id:s.uuid(),currency:oe},ks=s.discriminatedUnion("kind",[s.object({...js,kind:s.literal("auto_topup"),threshold:mi,quantity:yt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Ps.optional(),purchaseAmountMinor:Dn,purchaseUnits:yt}).strict(),s.object({...js,kind:s.literal("postpaid"),maxAmountMinorPerPeriod:Dn,maxOutstandingMinor:Dn,cashPrice:zn}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Rr=s.object({id:s.uuid(),terms:ks,status:s.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"),Rs=s.object({authorizationId:s.uuid(),terms:ks,setupUrl:s.url().nullable()}).strict(),Es=s.object({authorizationId:s.uuid(),accepted:s.literal(!0)}).strict(),Ms=s.object({authorizationId:s.uuid(),requestId:s.uuid()}).strict(),Ts=s.object({internal_feature_id:s.uuid(),entityId:s.uuid().nullable(),interval:s.enum(["day","week","month","year"]),anchor:s.enum(["billing_cycle","utc"]).optional(),basis:s.enum(["usage","credits"]),filter:ft.optional(),limit:ye.nullable(),thresholds:s.array(s.number().positive().max(1)).max(8),includedThresholds:s.array(s.number().positive().max(1)).max(8).optional(),absoluteThresholds:s.array(yt).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let o=r[n-1];return n===0||o!==void 0&&t>o})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let o=r[n-1];return n===0||o!==void 0&&kr(t)>kr(o)}),"Notification thresholds must increase"),Hl=Ts.safeExtend({requestId:s.uuid()}),As={control:s.literal("overage"),requestId:s.uuid(),internal_feature_id:s.uuid(),entityId:s.uuid().nullable()},Jl=s.discriminatedUnion("action",[s.strictObject({...As,action:s.literal("set"),allowed:s.boolean().nullable(),overageLimit:ye.nullable(),skipOverageBilling:s.boolean()}),s.strictObject({...As,action:s.literal("remove")})]),Ds=s.union([Hl,Jl]),Wl=s.strictObject({internal_feature_id:s.uuid(),entityId:s.uuid().nullable(),allowed:s.boolean().nullable(),overageLimit:ye.nullable(),skipOverageBilling:s.boolean(),interval:s.enum(["day","week","month","year"]),startsAt:qe,endsAt:qe,used:s.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:s.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:s.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Ql=s.object({internal_feature_id:s.uuid(),entityId:s.uuid().nullable(),interval:s.enum(["day","week","month","year"]),anchor:s.enum(["billing_cycle","utc"]).optional(),basis:s.enum(["usage","credits"]),filter:ft.optional(),startsAt:qe,endsAt:qe,used:rt,reserved:rt,limit:ye.nullable(),thresholds:s.array(s.number().positive().max(1)).max(8),notifiedThresholds:s.array(s.number().positive().max(1)).max(1024),includedThresholds:s.array(s.number().positive().max(1)).max(8).optional(),includedAllowance:s.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:s.array(s.number().positive().max(1)).max(1024).optional(),absoluteThresholds:s.array(yt).max(8).optional(),notifiedAbsoluteThresholds:s.array(yt).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||ye.safeParse(e.used).success&&ye.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Xl=s.object({authorizationId:s.uuid(),status:s.enum(["idle","pending","blocked"]),taskId:s.uuid().nullable(),invoiceId:s.uuid().nullable(),hostedInvoiceUrl:s.url().nullable(),purchaseCount:s.number().int().nonnegative(),purchaseWindowEndsAt:qe.nullable(),attemptCount:s.number().int().nonnegative(),failedAttemptCount:s.number().int().nonnegative(),suspendedAt:qe.nullable(),nextAttemptAt:qe.nullable(),failureReason:s.string().min(1).max(240).nullable()}).strict(),zs=s.object({internal_feature_id:s.uuid().optional(),entityId:s.uuid().optional()}).strict(),Vi=s.object({authorizations:s.array(Rr).max(100),limits:s.array(Ts).max(100),overages:s.array(Wl).max(100).optional(),windows:s.array(Ql).max(200),autoTopups:s.array(Xl).max(100),limited:s.boolean()}).strict(),Yl=s.object({id:s.uuid(),internal_feature_id:s.uuid(),productVersionId:s.uuid(),authorizationId:s.uuid(),entityId:s.uuid().nullable(),units:ye,amountMinor:sn,cashPrice:zn}).strict(),Bn=s.object({id:s.uuid(),sourceKind:s.enum(["product","usage","manual"]),providerInvoiceId:s.string().min(1).max(240).nullable(),status:s.enum(["accruing","open","pending","paid","failed","void"]),currency:oe,startsAt:qe.nullable(),endsAt:qe.nullable(),amountMinor:s.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:s.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Ui,paidAmountMinor:Ui,refundedAmountMinor:Ui,createdAt:qe,hostedInvoiceUrl:s.url().nullable(),adjustment:s.object({originalInvoiceId:s.uuid(),amountMinor:s.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:qe.nullable(),reason:s.string().min(1).max(500).optional()}).strict().nullable(),lines:s.array(Yl).max(100),linesLimited:s.boolean()}).strict(),Bs=s.object({invoiceId:s.uuid(),accepted:s.literal(!0)}).strict(),qs=s.strictObject({requestId:s.uuid(),originalInvoiceId:s.uuid(),amountMinor:s.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:s.string().trim().min(1).max(500)}),Fs=s.object({after:s.uuid().nullable(),limit:s.number().int().min(1).max(100)}).strict(),Ns=s.object({rows:s.array(Bn).max(100),nextCursor:s.uuid().nullable()}).strict(),ws=s.strictObject({id:s.string(),coupon:s.string(),start:s.number().nonnegative(),end:s.number().nullable()}),em=s.strictObject({subscriptionId:s.string(),customerId:s.string(),accountId:s.string(),sourceItems:s.array(s.strictObject({id:s.string(),price_id:s.string(),quantity:s.number().int(),discounts:s.array(ws).optional()})).max(100),items:s.array(s.strictObject({id:s.string(),price:s.string(),quantity:s.number().int(),discounts:s.array(s.strictObject({coupon:s.string().optional(),terms:s.strictObject({id:s.string(),name:s.string().optional(),percent_off:s.number().optional(),amount_off:s.number().optional(),currency:s.string().optional(),duration:s.enum(["once","forever","repeating"]),duration_in_months:s.number().optional()}).optional(),discount:s.string().optional(),receipt:ws.optional()})).max(20)})).max(100)}),Us=s.strictObject({membershipId:s.uuid(),requestId:s.uuid(),grantIds:s.array(s.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Vs=s.strictObject({membershipId:s.uuid(),operationId:s.uuid(),status:s.enum(["pending","effective"]),execution:em.nullable(),grants:s.array(s.strictObject({id:s.uuid(),couponId:s.uuid(),name:s.string(),discount:At,duration:He,startedAt:qe.nullable()})).max(20)});import{z as qn}from"zod";var $s=qn.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Gs=qn.number().int().min(1).max(1e3),Er=qn.object({cap:ye.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:qn.number().positive().max(1e4).nullable(),cycles:qn.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as wt}from"zod";var Ks=wt.strictObject({itemKey:wt.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:wt.uuid(),includedAmount:wt.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:wt.number().int().min(0).max(1e4),terms:fa,pricing:da.optional(),unitAmountMinor:wt.number().int().min(0).max(1e8),productId:wt.string().min(1).max(255).nullable(),priceId:wt.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{ga(e.includedAmount,e.terms.units,e.quantity),or({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as re}from"zod";var Bt=re.iso.datetime({offset:!0}),Ls=ye.refine(e=>/[1-9]/.test(e)),Zs=re.strictObject({interval:$s.exclude(["lifetime"]),count:Gs}),tm=re.strictObject({action:re.literal("create"),requestId:re.uuid(),internal_feature_id:re.uuid(),entityId:re.uuid().nullable(),amount:Ls.nullable(),expiresAt:Bt.nullable(),reset:Zs.nullable(),rollover:Er.nullable(),nextResetAt:Bt.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"),Hs=re.discriminatedUnion("action",[tm,re.strictObject({action:re.literal("update"),requestId:re.uuid(),grantId:re.uuid(),revision:re.number().int().nonnegative(),amount:Ls.nullable(),expiresAt:Bt.nullable(),rollover:Er.nullable(),nextResetAt:Bt.nullable()}),re.strictObject({action:re.enum(["add","subtract","set_remaining"]),requestId:re.uuid(),grantId:re.uuid(),revision:re.number().int().nonnegative(),amount:ye}),re.strictObject({action:re.literal("revoke"),requestId:re.uuid(),grantId:re.uuid(),revision:re.number().int().nonnegative()})]),$i=re.strictObject({id:re.uuid(),internal_feature_id:re.uuid(),entityId:re.uuid().nullable(),amount:ye.nullable(),reset:Zs.nullable(),rollover:Er.nullable(),nextResetAt:Bt.nullable(),startsAt:Bt,expiresAt:Bt.nullable(),revision:re.number().int().nonnegative(),revoked:re.boolean(),available:rt,held:rt,spent:rt}),Js=re.strictObject({customerId:re.uuid(),after:re.uuid().nullable(),limit:re.number().int().min(1).max(100)}),Ws=re.strictObject({rows:re.array($i).max(100),nextCursor:re.uuid().nullable()});import{z as D}from"zod";var mt=D.iso.datetime({offset:!0}),Qs=D.strictObject({invoiceId:D.uuid(),after:D.string().min(1).max(180).nullable(),limit:D.number().int().min(1).max(100)}),nm=D.strictObject({kind:D.literal("product"),key:D.string(),productVersionId:D.uuid(),productName:D.string(),itemKey:D.string(),entityId:D.uuid().nullable(),quantity:D.number().positive(),subtotalMinor:D.string().regex(/^-?\d+$/),discountMinor:D.string().regex(/^\d+$/),taxMinor:D.string().regex(/^-?\d+$/).nullable(),totalMinor:D.string().regex(/^-?\d+$/),startsAt:mt.nullable(),endsAt:mt.nullable(),providerLineId:D.string().nullable(),providerItemId:D.string()}),Xs=D.strictObject({invoice:Bn,items:D.array(D.discriminatedUnion("kind",[nm,D.strictObject({kind:D.literal("invoice_credit"),key:D.string(),internal_feature_id:D.uuid(),internal_credit_feature_id:D.uuid(),name:D.string(),units:ye,reserved:ye,amountMinor:sn,grossAmountMinor:sn,creditsAppliedMinor:sn,properties:ft,cashPrice:zn,providerItemId:D.string().nullable(),creditProviderItemId:D.string().nullable()}),D.strictObject({kind:D.literal("usage"),key:D.string(),internal_feature_id:D.uuid(),name:D.string(),units:ye,reserved:ye,amountMinor:sn,cashPrice:zn})])).max(100),nextCursor:D.string().min(1).max(180).nullable()}),rm=D.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Gi=D.strictObject({from:mt,to:mt,entityId:D.uuid().optional(),snapshotAt:mt.nullable(),after:D.strictObject({at:mt,id:D.uuid(),position:D.number().int().nonnegative()}).nullable(),limit:D.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),Ys=D.strictObject({customerId:D.uuid(),entityId:D.uuid().nullable(),from:mt,to:mt,snapshotAt:mt,totals:D.array(D.strictObject({internal_credit_feature_id:D.uuid(),name:D.string(),consumed:rt,refunded:rt,net:rm})).max(1e3),rows:D.array(D.strictObject({operationId:D.uuid(),position:D.number().int().nonnegative(),kind:D.enum(["consume","confirm","refund"]),originalId:D.uuid().nullable(),occurredAt:mt,internal_feature_id:D.uuid(),entitlementName:D.string(),sourceId:D.uuid(),internal_credit_feature_id:D.uuid(),creditName:D.string(),units:Sa,amount:rt,pricing:D.array(xa).max(12),properties:ft})).max(100),nextCursor:Gi.shape.after});import{z as U}from"zod";var tc=U.object({customerId:U.uuid()}).strict(),nc=U.discriminatedUnion("action",[U.object({customerId:U.uuid(),requestId:U.uuid(),action:U.literal("assign"),poolId:U.uuid(),memberCustomerId:U.uuid()}).strict(),U.strictObject({customerId:U.uuid(),requestId:U.uuid(),action:U.literal("assign_entity"),poolId:U.uuid(),entityId:U.uuid()}),U.object({customerId:U.uuid(),requestId:U.uuid(),action:U.literal("release"),poolId:U.uuid(),slotId:U.uuid()}).strict()]),Fn=U.number().int().nonnegative(),Ki=U.iso.datetime({offset:!0}),Li=U.strictObject({internalId:U.uuid(),id:U.string(),name:U.string().nullable(),version:U.number().int().positive()}),ec=U.enum(["active","past_due"]),Zi=U.strictObject({customerId:U.uuid(),licenses:U.array(U.strictObject({id:U.uuid(),linkId:U.uuid(),parent:U.strictObject({customerProductId:U.uuid(),status:ec,product:Li}),product:Li,planLicense:U.strictObject({id:U.uuid(),prepaidOnly:U.boolean(),isCustom:U.boolean()}).nullable(),granted:Fn,included:Fn,paidQuantity:Fn,usage:Fn,remaining:Fn,createdAt:Ki}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:U.array(U.strictObject({id:U.uuid(),linkId:U.uuid(),status:ec,product:Li,entity:U.strictObject({internalId:U.uuid(),id:U.string().nullable(),name:U.string().nullable()}).nullable(),beneficiary:U.strictObject({internalId:U.uuid(),id:U.string().nullable(),name:U.string().nullable()}).nullable(),startedAt:Ki.nullable(),endedAt:Ki.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:U.boolean()});import{z as N}from"zod";var Nn=N.enum(["email","sms","voice","push"]),Kb=N.enum(["resend","twilio","fcm","apns"]);var Lb=N.string().regex(/^\+[1-9]\d{1,14}$/),im=N.enum(["email_recipient","sms_segment","voice_second","push_device"]);var om=N.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),am=N.strictObject({subject:om,html:N.string().min(1).max(131072).optional(),text:N.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),sm=N.strictObject({body:N.string().min(1).max(1600).refine(e=>e.trim().length>0)}),cm=N.strictObject({text:N.string().trim().min(1).max(4e3),language:N.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:N.number().int().min(1).max(900)}),um=N.record(N.string().min(1).max(64),N.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),pm=N.strictObject({title:N.string().trim().min(1).max(200),body:N.string().trim().min(1).max(2e3),url:N.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:um.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),rc=N.discriminatedUnion("channel",[N.strictObject({channel:N.literal("email"),content:am}),N.strictObject({channel:N.literal("sms"),content:sm}),N.strictObject({channel:N.literal("voice"),content:cm}),N.strictObject({channel:N.literal("push"),content:pm})]),ic=N.strictObject({requestId:N.uuid(),customerId:N.uuid(),connectionId:N.uuid().optional(),message:rc,expiresAt:N.iso.datetime({offset:!0})}),lm=N.array(N.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),mm=N.discriminatedUnion("kind",[N.strictObject({kind:N.literal("all")}),N.strictObject({kind:N.literal("customers"),customerIds:lm})]),Zb=N.strictObject({name:N.string().trim().min(1).max(120),connectionId:N.uuid().optional(),message:rc,audience:mm,frequencyLimit:N.number().int().min(1).max(100)}),oc=N.strictObject({requestId:N.uuid(),channel:Nn,state:N.enum(["allowed","denied"]),expectedRevision:N.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),ac=N.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),sc=N.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),Hb=N.strictObject({meter:im,estimatedUnits:N.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:N.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as cc}from"zod";var cn={funnelId:cc.uuid().optional(),funnelVersionId:cc.uuid().optional()};import{z as Mr}from"zod";var Tr=Mr.strictObject({runId:Mr.uuid(),bindingId:Mr.uuid(),receiptId:Mr.uuid()});import{z as xe}from"zod";import{z as se}from"zod";import{z as ge}from"zod";var ty=ge.discriminatedUnion("action",[ge.strictObject({action:ge.literal("create"),couponId:ge.uuid(),productBindingId:ge.uuid(),storeOfferId:ge.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:ge.enum(["introductory","promotional"])}),ge.strictObject({action:ge.literal("set_enabled"),id:ge.uuid(),revision:ge.number().int().nonnegative(),enabled:ge.boolean()})]),ny=ge.array(ge.strictObject({id:ge.uuid(),couponId:ge.uuid(),productBindingId:ge.uuid(),storeOfferId:ge.string().min(1).max(255).nullable(),storeOfferType:ge.enum(["introductory","promotional"]),enabled:ge.boolean(),revision:ge.number().int().nonnegative()})).max(500),un=ge.strictObject({offerKind:ge.enum(["none","introductory","promotional"]),offerId:ge.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:ge.number().int().min(0).max(1e8),trialDays:ge.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"})}),ry=ge.record(ge.uuid(),un).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Hi=se.object({type:se.literal("native_purchase"),receiptId:se.uuid(),orderId:se.uuid(),productVersionId:se.uuid(),provider:se.enum(["apple","google"]),productId:se.string().min(1).max(255),productKind:Pa,replacement:se.strictObject({sourceOrderId:se.uuid(),sourceProductId:se.string().min(1).max(255),policy:se.enum(["apple_store","google_full_price"]),sourceAccountTokens:se.array(se.uuid()).max(50)}).nullable(),appAccountToken:se.uuid().optional(),obfuscatedAccountId:se.string().min(1).max(64).optional(),obfuscatedProfileId:se.uuid().optional(),basePlanId:se.string().min(1).max(255).optional(),offerId:se.string().min(1).max(255).optional(),offerKind:se.enum(["none","introductory","promotional"]),currency:oe,catalogAmountMinor:se.number().int().nonnegative().max(1e8),discountMinor:se.number().int().nonnegative().max(1e8),trialDays:se.number().int().min(1).max(730).nullable(),seatBundle:se.array(se.strictObject({key:se.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:se.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:se.strictObject({offerId:se.string().min(1).max(255),keyId:se.string().min(1).max(255),nonce:se.uuid(),signature:se.string().min(1).max(1024),timestamp:se.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(o=>o.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as i}from"zod";import{z as Q}from"zod/v4";import{z as dm}from"zod/v4";var fm=dm.registry(),{BillingInterval:uc}=(()=>{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:gm}=(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')."})})}))(Q),{withSpecDefault:hm}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:o})=>(e.add(n,{description:o,default:r}),n)}))(fm),{COMMON:pc}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:bm}={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:ym}=(e=>({COMMON_SET:new Set(e)}))(pc),{hasNoDuplicateCurrencies:lc}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let o=r.toLowerCase();if(n.has(o))return!1;n.add(o)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:mc}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:xm}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(Q),{Infinite:Sm}={Infinite:"inf"},{TierBehavior:vm}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:dc}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Im}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Om}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:jm}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Am}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Q),{ApiCreditTierSchema:fc}=(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."})})}))(Q),{VIOLATION_MESSAGES:wm}={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:gc}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Q),{ModelMarkupsSchema:_m}=((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()}))(Q,gc),{InvoiceUsageEntrySchema:Pm}=(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()}))(Q),{AttachDiscountSchema:hc}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(Q),{CustomLineItemSchema:Cm}=(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."})})}))(Q),{UnixMsTimestampSchema:km}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(Q),{CreateInvoicePreviewLineSchema:Rm}=(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()})}))(Q),{ReissueInvoiceParamsSchema:bc}=(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."})})}))(Q),{InvoiceModeParamsSchema:qt}=(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."})}))(Q),{InvoiceTemplateSchema:Em}=(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."})})}))(Q),{BasePriceSchema:Mm}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(Q,uc,gm),{CURRENCY_CODES:Tm}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(o=>!n.has(o)).sort()]}))(pc,bm,ym),{ApiPriceProcessorsSchema:yc}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(Q,xm),{AllocatedBillingFieldSchema:Dm}=((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'."})}))(Q,Im),{CreditDimensionNameSchema:zm}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(o=>!o.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Q,Om,jm),{ApiCreditMatchSchema:xc}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Am),{findCreditTierViolations:Bm}=(e=>({findCreditTierViolations:n=>{let r=[],o=(l,p)=>r.push({index:l,reason:p,message:e[p]}),a=0;for(let[l,p]of n.entries()){let d=l===n.length-1;if(p==="inf"){d||o(l,"non_final_infinity");continue}(!Number.isFinite(p)||p<=a)&&o(l,"not_increasing"),a=p,d&&o(l,"final_not_infinity")}return r}}))(wm),{ApiCreditMultiplierSchema:qm}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(Q,xc),{ProviderMarkupsSchema:Fm}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Q,gc),{InvoiceFeatureQuantitySchema:Sc}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(o=>o.quantity!==void 0!=(o.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(Q,dc,Pm),{CreateInvoicePreviewSchema:Ji}=((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()})}))(Q,Rm),{SUPPORTED_SET:Nm}=(e=>({SUPPORTED_SET:new Set(e)}))(Tm),{ApiCreditDimensionBaseSchema:Um}=((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."})})}))(Q,xc),{refineGraduatedTiers:vc}=(e=>({refineGraduatedTiers:(n,r)=>{let o=e(n.tiers.map(a=>a.to));for(let{index:a,message:l}of o)r.addIssue({code:"custom",message:l,path:["tiers",a,"to"]})}}))(Bm),{ApiFeatureMarkupsOverrideSchema:Vm}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(Q,Fm,_m),{isValidCurrencyCode:$m}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Nm),{ApiCreditDimensionSchema:Gm}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(Q,Um,fc,vc),{CurrencyCodeSchema:Ic}=((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')."})}))(Q,$m),{AdditionalCurrencyTierSchema:Km}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(Q,Ic),{ApiCreditSchemaItemBaseSchema:Oc}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(Q,zm,Gm,qm),{ApiFlatCreditSchemaItemSchema:Lm}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Oc,Q),{AdditionalCurrencyPriceSchema:Zm}=((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."})})}))(Q,Ic),{AdditionalCurrencyTierArraySchema:Hm}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Q,Km,lc,mc),{ApiGraduatedCreditSchemaItemSchema:Jm}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Oc,Q,fc,vc),{AdditionalCurrencyPriceArraySchema:jc}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Q,Zm,lc,mc),{ApiUsageTierWithCurrenciesSchema:Wm}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(o=>o.amount!==void 0||o.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(o=>({...o,amount:o.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(Q,Sm,Hm),{ApiCreditSchemaItemSchema:Qm}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(Q,Jm,Lm),{BasePriceParamsSchema:Xm}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(Mm,hm,Q,jc),{PlanItemPriceParamsSchema:Ym}=((e,t,n,r,o,a,l)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(d=>d??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(o).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:l,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(Q,jc,Wm,vm,uc,dc,Dm),{ApiFeatureOverrideSchema:ed}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(Q,Qm,Vm),{InvoiceBasePriceParamsSchema:Ac}=((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()}))(Xm,yc),{InvoiceItemPriceParamsSchema:td}=((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()}))(Ym,yc),{InvoiceLicenseQuantitySchema:nd}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(Q,Ac,Sc),{InvoiceCustomizeItemSchema:rd}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(Q,td,ed),{InvoiceCustomizeSchema:id}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(Q,Ac,rd),{InvoicePlanParamsSchema:od}=((e,t,n,r,o)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(o).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()}))(Q,id,Sc,nd,hc),{CreateInvoiceParamsSchema:pn}=((e,t,n,r,o)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:o.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:o.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(l=>l.period_start===void 0==(l.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(l=>l.period_start===void 0||l.period_end===void 0||l.period_end>l.period_start,{message:"period_end must be after period_start."})}))(Q,od,Cm,hc,km);var Pc=i.strictObject({requestId:i.uuid(),predecessorOperationId:i.uuid().optional(),invoiceMode:qt.optional(),entityId:i.uuid().optional(),billingSubscriptionId:i.uuid().optional(),newBillingSubscription:i.literal(!0).optional(),offerId:i.uuid().optional(),nativeOffer:un.optional(),plans:i.array(i.strictObject({productVersionId:i.uuid(),seatQuantities:i.record(wr,i.number().int().min(0).max(1e4)).optional(),featureQuantities:i.record(i.uuid(),i.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:i.enum(["stripe","apple","google","merchant"]),currency:oe}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Nt=i.strictObject({operationId:i.uuid()}),Re=i.number().int().min(0).max(1e8),ad=i.strictObject({lineId:i.uuid(),productVersionId:i.uuid(),productName:i.string().min(1).max(80),interval:i.enum(["free","week","month","year","one_time"]),intervalCount:i.number().int().min(1).max(156).optional(),baseAmountMinor:Re,seats:i.array(i.strictObject({key:wr,quantity:i.number().int().min(0).max(1e4),includedQuantity:i.number().int().min(0).max(1e4),maximumQuantity:i.number().int().min(0).max(1e4),unitAmountMinor:Re})).max(20),prepaid:i.array(Ks).max(100).optional(),catalogAmountMinor:Re,trial:i.strictObject({days:i.number().int().min(1).max(730),cardRequired:i.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+or({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Cc=i.string().regex(/^[A-Za-z0-9_-]{1,200}$/),sd=i.strictObject({id:Cc,name:i.string().min(1).max(40),percent_off:i.number().gt(0).max(100).optional(),amount_off:i.number().int().positive().optional(),currency:i.string().regex(/^[a-z]{3}$/).optional(),duration:i.enum(["once","repeating","forever"]),duration_in_months:i.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"),cd=i.strictObject({subscriptionId:i.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:i.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:i.array(i.strictObject({id:i.string(),price_id:i.string(),quantity:i.number().int().nonnegative(),discounts:i.array(i.strictObject({id:i.string(),coupon:i.string(),start:i.number(),end:i.number().nullable()})).optional()})).min(1).max(100),prorationDate:i.number().int().nonnegative(),amountMinor:i.number().int().positive(),periodStartMs:i.number(),periodEndMs:i.number()}),kc=i.strictObject({invoiceMode:qt.optional(),append:cd.optional(),provider:i.literal("stripe"),executor:i.enum(["indiana","merchant"]),accountId:i.string().regex(/^acct_[A-Za-z0-9]+$/),mode:i.enum(["payment","subscription"]),lineItems:i.array(i.strictObject({price:i.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:i.number().int().min(1).max(1e4),priceId:i.uuid(),productName:i.string().min(1).max(80),amountMinor:i.number().int().min(0).max(1e8),currency:i.string().regex(/^[a-z]{3}$/),interval:i.enum(["week","month","year","one_off"]),intervalCount:i.number().int().min(1).max(52),slot:i.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:i.strictObject({mode:i.enum(["graduated","volume"]),tiers:i.array(i.strictObject({upTo:i.number().int().min(1).max(1e6).nullable(),unitAmountMinor:i.number().int().min(0).max(1e8),flatAmountMinor:i.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:i.array(i.strictObject({coupon:Cc,terms:sd})).max(1),trialPeriodDays:i.number().int().min(1).max(730).nullable(),metadata:i.strictObject({grooveCheckoutId:i.uuid(),grooveCustomerId:i.uuid()}),expiresAt:i.iso.datetime({offset:!0})}),ln=i.strictObject({operationId:i.uuid(),entityId:i.uuid().nullable(),billingSubscriptionId:i.uuid().nullable(),discount:i.strictObject({offerId:i.uuid(),couponId:i.uuid(),discount:At,duration:He,amountMinor:Re,allocations:i.array(i.strictObject({productVersionId:i.uuid(),amountMinor:Re})).min(1).max(20),expiresAt:i.iso.datetime({offset:!0})}).nullable(),charge:i.strictObject({effectiveAt:i.iso.datetime({offset:!0}),periodEndsAt:i.iso.datetime({offset:!0}),debitMinor:Re,discountMinor:Re,taxMinor:Re,totalMinor:Re}).nullable(),expiresAt:i.iso.datetime({offset:!0}),provider:i.enum(["stripe","apple","google","merchant"]),nativeOffer:un.optional(),currency:oe,lines:i.array(ad).min(1).max(20),catalogAmountMinor:Re,automaticTax:i.boolean(),execution:i.union([kc,dr]).nullable()}).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),mn=i.strictObject({operationId:i.uuid(),orderId:i.uuid(),append:i.boolean().optional(),invoiceMode:i.boolean().optional(),status:i.enum(["pending","complete","cancelled","failed"]),executor:i.enum(["indiana","merchant"]),checkoutUrl:i.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:i.union([kc,dr]).nullable(),currency:oe,catalogAmountMinor:Re,taxMinor:Re,totalMinor:i.number().int().min(0).max(2e8).nullable(),quoteFinalized:i.boolean(),nativePurchase:Hi.nullable(),confirmedAt:i.iso.datetime({offset:!0}).nullable().optional(),quote:ln.optional(),merchantExecution:Mt.nullable().optional(),problem:kn.nullable().optional(),authority:yr.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),zr=i.strictObject({enabled:i.literal(!0),featureIds:i.array(i.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Rc=i.strictObject({requestId:i.uuid(),invoiceMode:qt.optional(),membershipId:i.uuid(),carryOverBalances:zr.optional(),carryOverUsages:zr.optional(),membershipIds:i.array(i.uuid()).min(1).max(20).optional(),prorationBehavior:i.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:i.enum(["immediate","renewal","store"]),change:i.discriminatedUnion("type",[i.strictObject({type:i.literal("plan"),productVersionId:i.uuid()}),i.strictObject({type:i.literal("seats"),licenseKey:wr,quantity:i.number().int().min(0).max(1e4)}),i.strictObject({type:i.literal("quantity"),internal_feature_id:i.uuid(),quantity:i.number().int().min(0).max(1e4)}),i.strictObject({type:i.literal("cancel")}),i.strictObject({type:i.literal("uncancel")}),i.strictObject({type:i.literal("billing_cycle"),billingCycleAnchor:i.union([i.literal("now"),i.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"),Dr=i.string().regex(/^price_[A-Za-z0-9]+$/),wc=i.strictObject({grooveUpdateId:i.uuid(),grooveCustomerId:i.uuid()}),_c=i.strictObject({price:Dr.nullable(),priceId:i.uuid().optional(),quantity:i.number().int().min(0).max(1e4)}),Ec=i.strictObject({provider:i.literal("stripe"),invoiceMode:qt.optional(),executor:i.enum(["indiana","merchant"]),accountId:i.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:i.string().regex(/^sub_[A-Za-z0-9]+$/),action:i.enum(["update","cancel","schedule","release"]),update:i.strictObject({items:i.array(_c).max(20),remove:i.array(Dr).max(20),restoreItems:i.array(i.strictObject({price:Dr,quantity:i.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:i.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:i.number().int().positive().optional(),paymentBehavior:i.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:i.boolean().optional(),clearCancelAt:i.literal(!0).optional(),billingCycleAnchorNow:i.literal(!0).optional(),metadata:wc}).nullable(),cancel:i.strictObject({prorate:i.literal(!1),invoiceNow:i.literal(!1)}).nullable(),schedule:i.strictObject({currentItems:i.array(i.strictObject({price:Dr,quantity:i.number().int().min(0).max(1e4)})).max(20),nextItems:i.array(_c).min(1).max(20),switchAt:i.number().int().positive(),interval:i.enum(["week","month","year"]),intervalCount:i.number().int().min(1).max(52),resetBillingCycleAnchor:i.literal(!0).optional(),metadata:wc}).nullable(),release:i.strictObject({schedule:i.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:i.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"),Br=i.strictObject({carryOverBalances:zr.optional(),carryOverUsages:zr.optional(),operationId:i.uuid(),membershipId:i.uuid(),productVersionId:i.uuid(),timing:i.enum(["immediate","renewal"]),effectiveAt:i.iso.datetime({offset:!0}),expiresAt:i.iso.datetime({offset:!0}),currency:oe,creditMinor:Re,debitMinor:Re,discountMinor:Re,taxMinor:Re,totalMinor:Re,retainedProductVersionIds:i.array(i.uuid()).max(19),execution:i.union([Ec,fr])}),ud=i.strictObject({operationId:i.uuid(),invoiceMode:i.boolean().optional(),membershipId:i.uuid(),productVersionId:i.uuid(),status:i.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:i.enum(["immediate","renewal"]),effectiveAt:i.iso.datetime({offset:!0}),checkoutUrl:i.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:i.enum(["indiana","merchant"]),execution:i.union([Ec,fr]).nullable(),confirmedAt:i.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Mt.nullable().optional(),problem:kn.nullable().optional(),quote:Br.optional(),authority:yr.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),pd=i.strictObject({operationId:i.uuid(),membershipId:i.uuid(),productVersionId:i.uuid(),timing:i.literal("store"),effectiveAt:i.null(),expiresAt:i.iso.datetime({offset:!0}),currency:oe,creditMinor:i.null(),debitMinor:i.null(),discountMinor:i.null(),taxMinor:i.null(),totalMinor:i.null(),retainedProductVersionIds:i.array(i.uuid()).max(19),store:i.strictObject({provider:i.enum(["apple","google"]),productId:i.string().min(1).max(255),catalogAmountMinor:Re,policy:i.enum(["apple_store","google_full_price"])})}),ld=i.strictObject({operationId:i.uuid(),membershipId:i.uuid(),productVersionId:i.uuid(),status:i.enum(["prepared","pending","effective","cancelled","failed"]),timing:i.literal("store"),effectiveAt:i.iso.datetime({offset:!0}).nullable(),checkoutUrl:i.null(),nativePurchase:Hi.nullable()}),Mc=i.union([Br,pd]),Wi=i.union([ud,ld]),Un=i.number().int().positive().max(2e8),Ft=i.number().int().min(0).max(2e8),Tc=i.strictObject({requestId:i.uuid(),invoiceId:i.uuid(),mode:i.enum(["full","partial"]),amountMinor:Un.optional(),entitlementAction:i.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Dc=i.strictObject({provider:i.literal("stripe"),executor:i.enum(["indiana","merchant"]),accountId:i.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:i.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Un,currency:i.string().regex(/^[a-z]{3}$/),metadata:i.strictObject({indianaRefundId:i.uuid()}),idempotencyKey:i.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:i.array(i.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Qi=i.strictObject({operationId:i.uuid(),invoiceId:i.uuid(),providerInvoiceId:i.string().min(1).max(200),currency:oe,paidMinor:Ft,refundedMinor:Ft,pendingMinor:Ft,amountMinor:Un,mode:i.enum(["full","partial"]),entitlementAction:i.enum(["retain","revoke"]),revokes:i.strictObject({customerProductIds:i.array(i.uuid()).max(100),subscriptionIds:i.array(i.string().min(1).max(200)).max(20)}),execution:i.union([Dc,gr]),expiresAt:i.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),qr=i.strictObject({operationId:i.uuid(),invoiceId:i.uuid(),providerInvoiceId:i.string().min(1).max(200),status:i.enum(["quoted","pending","succeeded","failed","expired"]),executor:i.enum(["indiana","merchant"]),currency:oe,amountMinor:Un,mode:i.enum(["full","partial"]),entitlementAction:i.enum(["retain","revoke"]),refundId:i.string().min(1).max(200).nullable(),quote:Qi.optional(),execution:i.union([Dc,gr]).nullable(),confirmedAt:i.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Mt.nullable().optional(),problem:kn.nullable().optional(),authority:yr.optional(),failureReason:i.string().min(1).max(200).nullable(),createdAt:i.iso.datetime({offset:!0}),completedAt:i.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"),Oy=i.strictObject({invoiceId:i.uuid(),currency:oe,paidMinor:Ft,refundedMinor:Ft,pendingMinor:Ft,refundableMinor:Ft,executor:i.enum(["indiana","merchant"]).nullable(),canRefund:i.boolean(),operations:i.array(qr).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),jy=i.strictObject({requestId:i.uuid(),mode:i.enum(["full","partial"]),amountMinor:Un.optional(),entitlementAction:i.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 zc=xe.strictObject({requestId:xe.uuid(),targets:xe.array(xe.strictObject({membershipId:xe.uuid(),action:xe.enum(["cancel","uncancel"]),timing:xe.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"),Fr=xe.strictObject({batchId:xe.uuid()}),md=xe.strictObject({operationId:xe.uuid(),membershipIds:xe.array(xe.uuid()).min(1).max(20),provider:xe.enum(["stripe","apple","google"]),action:xe.enum(["cancel","uncancel"]),timing:xe.enum(["immediate","renewal"]),status:xe.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Br.nullable(),managementUrl:xe.url().nullable(),failureCode:xe.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Vn=xe.strictObject({batchId:xe.uuid(),ready:xe.boolean(),status:xe.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:xe.iso.datetime({offset:!0}),acceptedAt:xe.iso.datetime({offset:!0}).nullable(),groups:xe.array(md).min(1).max(100)});import{z as ne}from"zod";var dd=ne.string().trim().min(1).max(240),Xi={requestId:ne.uuid(),reason:dd},Nr=ne.discriminatedUnion("action",[ne.strictObject({...Xi,action:ne.literal("start"),productVersionId:ne.uuid(),entityId:ne.uuid().optional(),days:ne.number().int().min(1).max(730).optional()}),ne.strictObject({...Xi,action:ne.literal("extend"),membershipId:ne.uuid(),days:ne.number().int().min(1).max(730)}),ne.strictObject({...Xi,action:ne.literal("end"),membershipId:ne.uuid()})]),Bc=ne.strictObject({operationId:ne.uuid()}),qc=ne.iso.datetime({offset:!0}),fd=ne.strictObject({provider:ne.literal("stripe"),executor:ne.enum(["indiana","merchant"]),accountId:ne.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:ne.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:ne.union([ne.literal("now"),qc]),prorationBehavior:ne.literal("none")}),Yi=ne.strictObject({operationId:ne.uuid(),action:ne.enum(["start","extend","end"]),status:ne.enum(["pending","effective"]),managedBy:ne.enum(["indiana","stripe"]),membershipIds:ne.array(ne.uuid()).min(1).max(20),endsAt:qc.nullable(),execution:fd.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"),ky=ne.strictObject({groupId:ne.uuid(),productVersionId:ne.uuid(),enabled:ne.boolean()});import{z as de}from"zod";var Fc=de.strictObject({requestId:de.uuid(),currency:oe,makeDefault:de.boolean()}),Nc=de.strictObject({setupId:de.uuid()}),gd=de.strictObject({provider:de.literal("stripe"),executor:de.literal("merchant"),accountId:de.string().regex(/^acct_[A-Za-z0-9]+$/),mode:de.literal("setup"),currency:de.string().regex(/^[a-z]{3}$/),customer:de.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:de.uuid(),metadata:de.strictObject({grooveProjectId:de.uuid(),grooveEnvironmentId:de.uuid(),grooveCustomerId:de.uuid(),groovePaymentSetupId:de.uuid()}),setDefaultPaymentMethod:de.boolean(),expiresAt:de.iso.datetime({offset:!0})}),eo=de.strictObject({id:de.uuid(),provider:de.literal("stripe"),status:de.enum(["prepared","complete","expired"]),currency:oe,makeDefault:de.boolean(),url:de.url().nullable(),createdAt:de.iso.datetime({offset:!0}),expiresAt:de.iso.datetime({offset:!0}),completedAt:de.iso.datetime({offset:!0}).nullable(),execution:gd.nullable()});import{z as Ee}from"zod";var Uc=Ee.union([Ee.string(),Ee.number(),Ee.boolean(),Ee.null()]),Vc=Ee.strictObject({customerId:Ee.uuid()}),$c=Ee.strictObject({customerId:Ee.uuid(),provider:Ee.literal("stripe"),checkedAt:Ee.iso.datetime({offset:!0}),status:Ee.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ee.number().int().nonnegative(),differences:Ee.array(Ee.strictObject({subscriptionId:Ee.string().startsWith("sub_"),itemId:Ee.string().nullable(),field:Ee.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Uc,actual:Uc})).max(1e4)});import{z as J}from"zod";var Ur=J.iso.datetime({offset:!0}),Vr=J.strictObject({createdAt:Ur,id:J.uuid()}),$r=J.strictObject({customerId:J.uuid().optional(),entityId:J.uuid().optional(),productId:J.string().min(1).max(256).optional(),provider:J.enum(["stripe","apple","google","merchant","free"]).optional(),status:J.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Vr.optional(),limit:J.number().int().min(1).max(100).optional()}),to={id:J.uuid(),customerId:J.uuid(),entityId:J.uuid().nullable(),productId:J.string().min(1).max(256),productVersionId:J.uuid(),name:J.string().min(1).max(120),provider:J.enum(["stripe","apple","google","merchant","free"]),createdAt:Ur},hd=J.strictObject({...to,status:J.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:J.boolean(),billingSubscriptionId:J.uuid().nullable()}),bd=J.strictObject({...to,status:J.enum(["active","ended","refunded"]),orderId:J.uuid().nullable(),transactionId:J.uuid().nullable(),currency:oe.nullable(),amountMinor:J.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),yd=J.strictObject({...to,status:J.enum(["blocked","resolved"]),conflict:J.strictObject({detectedAt:Ur,blockingMembershipIds:J.array(J.uuid()).min(1).max(100),transactionId:J.uuid()}),resolvedAt:Ur.nullable()}),Gc=$r.extend({status:J.enum(["blocked","resolved"]).optional()}),Kc=J.strictObject({customerId:J.uuid(),orderId:J.uuid()}),Lc=J.strictObject({orderId:J.uuid(),status:J.enum(["blocked","resolved"])}),Zc=J.strictObject({items:J.array(hd).max(100),nextCursor:Vr.nullable()}),Hc=J.strictObject({items:J.array(bd).max(100),nextCursor:Vr.nullable()}),Jc=J.strictObject({items:J.array(yd).max(100),nextCursor:Vr.nullable()});import{z as he}from"zod";var Wc=he.union([he.strictObject({intent:he.literal("read"),requestId:he.uuid(),purchaseIntentId:he.uuid()}),he.strictObject({requestId:he.uuid(),provider:he.literal("apple"),purchaseIntentId:he.uuid(),productId:he.string().min(1).max(255).optional(),signedTransaction:he.string().min(1).max(131072)}),he.strictObject({requestId:he.uuid(),provider:he.literal("google"),purchaseIntentId:he.uuid(),productId:he.string().min(1).max(255).optional(),purchaseToken:he.string().min(1).max(16384)})]),Qc=he.strictObject({requestId:he.uuid(),orderId:he.uuid(),purchaseIntentId:he.uuid(),status:he.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:oe,refunded:he.boolean(),completion:he.strictObject({transactionIds:he.array(he.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:he.boolean()}).nullable()});import{z as O}from"zod";var ro=O.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),xd=O.record(O.string(),O.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),Sd=3,$n=20,vd=Sd*$n,no=O.strictObject({type:O.literal("product"),productId:ro}),Xc={type:O.literal("group"),key:O.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:O.string().trim().min(1).max(80)},Id=O.discriminatedUnion("type",[no,O.strictObject({...Xc,items:O.array(no).max($n)})]),Od=O.discriminatedUnion("type",[no,O.strictObject({...Xc,items:O.array(Id).max($n)})]),jd=O.array(Od).max($n).superRefine((e,t)=>{let n=new Set,r=new Set,o=0;function a(l){for(let p of l){o++;let d=p.type==="product"?n:r,v=p.type==="product"?p.productId:p.key;d.has(v)&&t.addIssue({code:"custom",message:p.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),d.add(v),p.type==="group"&&a(p.items)}}a(e),(n.size>$n||o>vd)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function io(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:io(t))}var dn=O.strictObject({lookupKey:O.string().trim().min(1).max(200),displayName:O.string().trim().min(1).max(1500),items:jd,metadata:xd}),Ad=O.strictObject({product:O.record(O.string(),O.json()),prices:O.array(O.record(O.string(),O.json())),entitlements:O.array(O.record(O.string(),O.json())),freeTrials:O.array(O.record(O.string(),O.json())),licenses:O.array(O.record(O.string(),O.json()))}),Yc=dn.extend({id:O.uuid(),projectId:O.uuid(),environmentId:O.uuid(),state:O.enum(["active","archived"]),isCurrent:O.boolean(),revision:O.number().int().nonnegative(),publishedVersionId:O.uuid().nullable(),createdAt:O.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"})}),eu=O.strictObject({id:O.uuid(),offeringId:O.uuid(),projectId:O.uuid(),environmentId:O.uuid(),version:O.number().int().positive(),document:dn,productEvidence:O.record(ro,Ad),createdAt:O.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=io(e.document);(!n.length||Pd(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),wd=O.strictObject({rows:O.array(Yc).max(200),versions:O.array(eu).max(500)}),Gy=O.discriminatedUnion("action",[O.strictObject({action:O.literal("create"),document:dn}),O.strictObject({action:O.literal("save"),id:O.uuid(),revision:O.number().int().nonnegative(),document:dn}),O.strictObject({action:O.enum(["publish","set_current","archive","restore"]),id:O.uuid(),revision:O.number().int().nonnegative()})]),Ky=O.strictObject({record:Yc,version:eu.nullable()}),tu=O.discriminatedUnion("type",[O.strictObject({type:O.literal("current")}),O.strictObject({type:O.literal("id"),id:O.uuid()}),O.strictObject({type:O.literal("lookup_key"),lookupKey:O.string().min(1).max(200)}),O.strictObject({type:O.literal("version"),versionId:O.uuid()})]),_d=O.strictObject({internalId:ro,id:O.string(),name:O.string().nullable(),version:O.number().int().positive(),archived:O.boolean()}),Ly=wd.extend({products:O.array(_d).max(500),pagination:O.strictObject({rows:O.string().nullable(),versions:O.string().nullable(),products:O.string().nullable()}).optional()});function Pd(e){let t=[];io(e).length||t.push("Select at least one Product before publishing");function n(r){for(let o of r)o.type==="group"&&(o.items.length||t.push("Every published group requires a Product"),n(o.items))}return n(e.items),t}import{z as Gr}from"zod";var nu=Gr.strictObject({id:Gr.uuid(),offeringId:Gr.uuid(),version:Gr.number().int().positive(),document:dn});import{z as _e}from"zod";import{z as V}from"zod";var oo=V.discriminatedUnion("type",[V.strictObject({type:V.literal("event"),event:V.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),V.strictObject({type:V.literal("open_url"),url:V.url().refine(e=>new URL(e).protocol==="https:")})]),Cd=Le,kd=V.discriminatedUnion("type",[V.object({type:V.literal("checkout"),product:pr}).strict(),V.object({type:V.literal("close")}).strict(),V.object({type:V.literal("action"),action:oo}).strict()]),fn=V.object({schemaVersion:V.literal(3),kind:V.literal("paywall"),name:V.string().trim().min(1).max(80),presentation:gt,requirement:Qt.optional(),products:Ir,offeringVersionId:V.uuid().nullable(),offeringId:V.uuid(),screen:Cd,buttons:V.record(V.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),kd)}).strict(),ix=fn.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of Ed(e))t.addIssue({code:"custom",message:r});for(let r of Rd(e))t.addIssue({code:"custom",message:r});It(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function Rd(e){let t=e.products.items.map(a=>a.productVersionId),n=Ma(e.screen),r=new Set,o=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&o.push("products"),e.offeringVersionId||o.push("offering"),e.products.grouping&&(!Da(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(l=>l.tierId===a.id)))&&o.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let l=a.product;if(l.type==="fixed")r.add(l.productVersionId);else{l.allowedProductVersionIds.forEach(v=>r.add(v));let p=!1,d=n[l.pickerId];d&&(p=!0,(l.allowedProductVersionIds.some(v=>!d.ids.includes(v))||d.ids.some(v=>!l.allowedProductVersionIds.includes(v)))&&o.push("picker")),ht(e.screen,v=>{if(v.id!==l.pickerId||v.type!=="plan_picker")return;p=!0,(JSON.stringify(v.planIds)!==JSON.stringify(t)||JSON.stringify(l.allowedProductVersionIds)!==JSON.stringify(t)||v.defaultPlan!==e.products.defaultProductVersionId)&&o.push("picker");let h=v.grouping?{tiers:v.grouping.tiers,assignments:v.grouping.assignments}:void 0;JSON.stringify(h)!==JSON.stringify(e.products.grouping)&&o.push("grouping")}),p||o.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&o.push("purchase"),ht(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&o.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&o.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(l=>!t.includes(l)))&&o.push("binding")}),[...new Set(o)]}function Ed(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let p of e.screen.pages)r.set(p.id,[]),Yt(p.root,d=>{let v=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(v){let h=e.screen.actions.find($=>$.id===v);h?.type==="navigate"&&r.get(p.id).push(h.pageId);let T=e.buttons[v];p.id!==n.id&&T&&T.type!=="close"&&t.push(`purchaseScreen:${d.id}`)}p.id!==n.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&t.push(`packageScreen:${d.id}`)});let o=new Set;function a(p){if(!o.has(p)){o.add(p);for(let d of r.get(p)??[])a(d)}}let l=e.screen.initialPageId??e.screen.pages[0]?.id;l?a(l):t.push("initialPage");for(let p of e.screen.pages)o.has(p.id)||t.push(`unreachableScreen:${p.id}`);return[...new Set(t)]}var ru=V.object({id:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),revision:V.number().int().nonnegative(),state:V.enum(["active","archived"]),publishedVersionId:V.uuid().nullable(),updatedAt:V.iso.datetime({offset:!0}),draft:fn}).strict(),ox=V.object({rows:V.array(ru).max(200),nextCursor:V.uuid().nullable()}).strict(),ax=ru.omit({draft:!0}).extend({name:V.string(),productCount:V.number().int().nonnegative()}).strict(),sx=V.discriminatedUnion("action",[V.object({action:V.literal("save"),id:V.uuid().nullable(),revision:V.number().int().nonnegative(),document:fn}).strict(),V.object({action:V.enum(["publish","archive"]),id:V.uuid(),revision:V.number().int().nonnegative()}).strict()]),cx=V.object({paywalls:V.array(V.object({id:V.uuid(),paywallId:V.uuid(),version:V.number().int().positive(),name:V.string().min(1).max(80),presentation:gt,buttons:fn.shape.buttons}).strict()).max(500),limited:V.boolean()}).strict();import{z as Y}from"zod";import{z as Fe}from"zod";var gn=Fe.string().regex(/^[a-f0-9]{64}$/),Md=Ra.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),iu=Fe.strictObject({couponDigests:Fe.record(Fe.uuid(),gn),variables:Fe.record(Jt,Fe.record(Fe.uuid(),Fe.partialRecord(Fe.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Fe.string()))),locales:Fe.record(Jt,Xt.extend({nodes:Fe.record(Fe.string(),Fe.strictObject({base:Md})),plans:Fe.object({}).strict(),pickers:Fe.object({}).strict()}).omit({paywall:!0}))});import{z as ce}from"zod";import{z as Kr}from"zod";var ao=Kr.strictObject({eventsEnabled:Kr.boolean(),experimentViewsEnabled:Kr.boolean(),featureUsageEnabled:Kr.boolean()}),gx=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function hx(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as w}from"zod";var so=w.tuple([w.number().min(0).max(1),w.number().min(0).max(1)]).refine(([e,t])=>e<=t),Td=w.strictObject({attribute:w.string().optional(),seed:w.string(),hashVersion:w.literal(2),ranges:w.array(so).max(100)}),Dd=w.strictObject({id:w.string().min(1).max(255),condition:it,gate:w.boolean().optional()}),zd=w.strictObject({key:w.string().optional(),name:w.string().optional(),passthrough:w.boolean().optional()}),ou={condition:it.optional(),parentConditions:w.array(Dd).max(100).optional(),weights:w.array(w.number().min(0).max(1)).max(20).optional(),coverage:w.number().min(0).max(1).optional(),hashAttribute:w.string().optional(),fallbackAttribute:w.string().optional(),hashVersion:w.literal(2).optional(),disableStickyBucketing:w.boolean().optional(),bucketVersion:w.number().int().nonnegative().optional(),minBucketVersion:w.number().int().nonnegative().optional(),filters:w.array(Td).max(100).optional(),ranges:w.array(so).max(20).optional(),meta:w.array(zd).max(20).optional(),seed:w.string().optional(),name:w.string().optional(),phase:w.string().optional()},hn=w.strictObject({...ou,key:w.string().min(1).max(255),variations:w.tuple([te,te]).rest(te).refine(e=>e.length<=20),urlPatterns:w.array(w.strictObject({include:w.boolean(),type:w.enum(["regex","simple"]),pattern:w.string()})).max(100).optional(),force:w.number().int().nonnegative().optional(),active:w.boolean().optional(),persistQueryString:w.boolean().optional()}),co=w.strictObject({value:te,variationId:w.number().int(),key:w.string(),name:w.string().optional(),bucket:w.number().optional(),passthrough:w.boolean().optional(),inExperiment:w.boolean(),hashUsed:w.boolean().optional(),hashAttribute:w.string(),hashValue:w.string(),featureId:w.string().nullable(),stickyBucketUsed:w.boolean().optional()}),Bd=w.strictObject({...ou,id:w.string().max(255).optional(),force:te.optional(),variations:w.array(te).min(2).max(20).optional(),key:w.string().optional(),range:so.optional(),tracks:w.array(w.strictObject({experiment:hn,result:co})).max(100).optional()}),qd=w.strictObject({defaultValue:te.optional(),rules:w.array(Bd).max(500).optional()}),Gn=w.record(w.string(),w.union([w.strictObject({type:w.literal("hashed"),attributeKey:w.string(),values:w.array(w.string().regex(/^[a-f0-9]{64}$/))}),w.strictObject({type:w.literal("list"),attributeKey:w.string(),values:w.array(w.union([w.string(),w.number()]))}),w.strictObject({type:w.literal("condition"),condition:it})])),_t=w.strictObject({scope:me,generation:w.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:w.iso.datetime({offset:!0}),expiresAt:w.iso.datetime({offset:!0}).nullable(),features:w.record(w.string(),qd),savedGroups:Gn,experiments:w.record(w.uuid(),hn)});var uo=_t.extend({analyticsConfig:ao,remoteFeatures:ce.array(ce.string().min(1).max(255)).max(500)}),Fd=uo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),au=ce.strictObject({attributes:Ke,features:ce.array(ce.string().min(1).max(255)).max(500).optional(),customerId:ce.uuid().optional()}),Nd=ce.strictObject({value:te,source:ce.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ce.boolean(),off:ce.boolean(),ruleId:ce.string(),experimentResult:co.optional()}),su=ce.strictObject({generation:_t.shape.generation,evaluatedAt:_t.shape.evaluatedAt,expiresAt:_t.shape.expiresAt,features:ce.record(ce.string(),Nd),merchandiseContext:ce.strictObject({merchandiseId:ce.uuid(),merchandise:Ke}).optional()}),cu=ce.strictObject({customerId:ce.uuid().optional(),events:ce.array(ce.strictObject({eventUuid:ce.uuid(),timestamp:ce.iso.datetime({offset:!0}),name:ce.string().min(1).max(255),merchandise:Ss.optional(),properties:ce.record(ce.string(),te).default({}),deviceId:ce.string().min(1).max(255).optional(),sessionId:ce.string().min(1).max(255).optional()})).min(1).max(100)}),uu=ce.strictObject({inserted:ce.number().int().nonnegative(),duplicates:ce.number().int().nonnegative(),rejected:ce.number().int().nonnegative(),skipped:ce.number().int().nonnegative(),analyticsConfig:ao});import{z as j}from"zod";import{z as Ud}from"zod";var po=Ud.enum(["funnel-run/1","funnel-process/1"]),lo="funnel-process/1";function mo(e,t=[]){let n=[];ht(e,o=>{o.hidden&&n.push("Hidden components must not be delivered"),t.includes(o.type)&&n.push(`Node type ${o.type} cannot be delivered`)});let r=new Set(gi(e).map(o=>o.key));for(let[o,a]of Object.entries(e.strings.locales))for(let l of Object.keys(a))r.has(l)||n.push(`Unused string ${l} must not be delivered (${o})`);return n}function pu(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>pu(t)??[])}}function Vd(e){let t=e.pages.map(o=>{let a=pu(o.root);return a?.type==="stack"?{...o,root:a}:{...o,root:{type:"stack",id:o.root.id,...o.root.name===void 0?{}:{name:o.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(gi({pages:t}).map(o=>o.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([o,a])=>[o,Object.fromEntries(Object.entries(a).filter(([l])=>n.has(l)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function lu(e,t=[]){let n=Le.parse(structuredClone(Vd(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let o=mo(n,t);if(o.length)throw new Error(o.join("; "));return n}import{z as P}from"zod";import{z as x}from"zod";import{z as Ie}from"zod";var Lr=Ie.strictObject({schemaVersion:Ie.literal(1),renderKey:Ie.string().min(1).max(256),routeTemplate:Ie.string().startsWith("/").max(2048),selectors:Ie.array(Ie.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:Ie.array(Ie.number().int().min(0)).min(1),absent:Ie.array(Ie.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),mu=Ie.strictObject({renderKey:Ie.string().min(1).max(256),routeKey:Ie.string().min(1).max(256),stateKey:Ie.string().min(1).max(256),documentKey:Ie.string().min(1).max(256),documentHash:Ie.string().regex(/^[a-f0-9]{64}$/),compositionKey:Ie.string().min(1).max(256),entryMode:Ie.enum(["hard","soft"]),match:Ie.strictObject({present:Ie.array(Ie.number().int().min(0)),absent:Ie.array(Ie.number().int().min(0))})});import{z as Ut}from"zod";var $d=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],fo="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Gd=Ut.string().regex(new RegExp(`^${fo}/${fo}/${fo}/manifest\\.json$`)),du=Ut.strictObject({kind:Ut.literal("gcs-resumable"),url:Ut.url(),bucket:Ut.enum($d),objectKey:Gd,byteLength:Ut.number().int().positive(),expiresAt:Ut.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,o=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!o.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var Oe=x.string().min(1).max(256),Je=x.string().regex(/^[a-f0-9]{64}$/),Zr=x.strictObject({versionId:x.uuid(),manifestDigest:Je,sourceGraphDigest:Je,pageKey:Oe,stateKey:Oe,documentKey:Oe,documentHash:Je,elementKey:Oe.optional(),nodeId:Oe.optional(),contentHash:Je.optional(),renderKey:Oe.optional()}),fu=x.strictObject({pageKey:Oe,documentKey:Oe,expectedDocumentHash:Je,renderKey:Oe.optional(),nodeId:Oe,elementKey:Oe,expectedContentHash:Je,property:x.enum(["text","fontSize","color"]),value:x.union([x.string().max(4e3),x.number().finite()])}),gu=x.strictObject({versionId:x.uuid(),manifestDigest:Je,sourceGraphDigest:Je,pageKey:Oe,stateKey:Oe,documentKey:Oe,documentHash:Je,renderKey:Oe.optional(),patches:x.array(fu.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),Kd=/^[a-z][a-z0-9-]{0,39}$/,Kn=x.string().regex(Kd),ho=x.enum(["web","ios","android"]),Fx=x.discriminatedUnion("action",[x.strictObject({action:x.literal("register"),requestId:x.uuid(),client:Kn,platform:ho,label:x.string().trim().min(1).max(100),sha256:Je,bytes:x.number().int().min(1),transferBytes:x.number().int().min(1)}),x.strictObject({action:x.literal("complete"),versionId:x.uuid()}),x.strictObject({action:x.literal("current"),versionId:x.uuid(),expectedCurrent:x.uuid().nullable()}),x.strictObject({action:x.literal("delivery"),enabled:x.boolean()}),x.strictObject({action:x.literal("changes"),versionId:x.uuid(),experimentId:x.uuid(),variationId:Oe,changesetId:x.uuid().nullable(),expectedRevision:Je.nullable(),editorUrl:x.string().url().max(2048),patches:x.array(fu).max(200)})]),bo=x.strictObject({id:x.uuid(),projectId:x.uuid(),environmentId:x.uuid(),clientKey:Kn,platform:ho,label:x.string(),sha256:Je,bytes:x.number().int().positive(),objectKey:x.string(),state:x.enum(["uploading","ready","rejected"]),isCurrent:x.boolean(),revision:x.number().int().nonnegative(),createdAt:x.string(),expiresAt:x.string(),readyAt:x.string().nullable(),summary:x.record(x.string(),x.json()),routeTree:x.json().nullable(),validation:x.record(x.string(),x.json())}),Ld=x.strictObject({key:Kn,platform:ho,currentId:x.uuid().nullable()}),Nx=x.strictObject({rows:x.array(bo).max(100),nextCursor:x.uuid().nullable(),clients:x.array(Ld).max(20)}),go=x.strictObject({storedBytes:x.number().int().nonnegative(),reservedBytes:x.number().int().nonnegative(),chargedBytes:x.number().int().nonnegative(),versions:x.number().int().nonnegative(),objects:x.number().int().nonnegative(),orphanObjects:x.number().int().nonnegative(),missingReadyObjects:x.number().int().nonnegative(),unknownObjectSizes:x.number().int().nonnegative(),byteLimit:x.number().int().positive(),versionLimit:x.number().int().positive(),remainingBytes:x.number().int().nonnegative()}),Ux=x.strictObject({asOf:x.iso.datetime({offset:!0}),reclamation:x.literal("manual-review-required"),buckets:x.strictObject({source:go,runtime:go,previews:go})}),Vx=x.strictObject({version:bo,actorId:x.uuid(),claims:x.record(x.string(),x.json())}),$x=x.strictObject({version:bo,upload:du.nullable()}),Gx=x.object({format:x.literal("indiana-route-state-index"),schemaVersion:x.literal(3),routes:x.array(x.object({routeKey:Oe,path:x.string(),documentKey:Oe,documentHash:Je,initialStateKey:Oe,initialRenderKey:Oe})),renders:x.array(mu)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),Kx=x.strictObject({rows:x.array(x.object({id:x.uuid(),name:x.string(),status:x.string(),variations:x.array(x.object({id:Oe,key:Oe,name:x.string().optional()}).loose())}).loose()),limited:x.boolean()}),Lx=x.strictObject({enabled:x.boolean(),allowedOrigins:x.array(x.string())});import{z as bn}from"zod";var hu=bn.strictObject({id:bn.uuid(),name:bn.string().trim().min(1).max(80),client:Kn,source:Zr,event:bn.enum(["screen_enter","button_click"]),cooldownSeconds:bn.number().int().min(0).max(2592e3),behavior:bn.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as pe}from"zod";var yo=te,Zd=["parameters","answers","results","variables"];function xo(e){return Zd.some(t=>e===t||e.startsWith(t+"."))}function So(e){let t={};for(let[r,o]of Object.entries(En(e.declarations,e))){let a=r.split(".");if(a.some(d=>["__proto__","constructor","prototype"].includes(d)))throw new Error("Reserved result path");let l=t;for(let d of a.slice(0,-1)){Object.hasOwn(l,d)||(l[d]={});let v=l[d];if(!v||typeof v!="object"||Array.isArray(v))throw new Error("Ambiguous result path");l=v}let p=a.at(-1);if(p===void 0)throw new Error("Empty result path");l[p]=o}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!xo(r))),variables:t}}import{z as Hd}from"zod";var Hr=Hd.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var vo=pe.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),bu=pe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),yu=ut.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Io=pe.record(vo,pe.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),Jd=lt,xu=pe.strictObject({type:pe.literal("external_task"),endpointId:pe.uuid(),taskKey:vo,inputs:pe.record(vo,Jd).refine(e=>Object.keys(e).length<=20),outputs:Io}),Su=pe.strictObject({maxAttempts:pe.number().int().min(1).max(5),retryDelaySeconds:pe.number().int().min(1).max(30),backoff:pe.enum(["fixed","exponential"]),requestTimeoutSeconds:pe.number().int().min(1).max(10),timeoutSeconds:pe.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var uS=pe.strictObject({outcome:pe.enum(["success","failure"]),data:yu});var pS=pe.discriminatedUnion("operation",[pe.strictObject({operation:pe.literal("signal"),runId:pe.uuid(),nodeId:bu,eventName:Hr,eventId:pe.uuid(),data:yu}),pe.strictObject({operation:pe.literal("read_results"),runId:pe.uuid()})]),lS=pe.strictObject({scope:me,runId:pe.uuid(),eventId:pe.uuid(),accepted:pe.boolean()}),Wd=pe.record(bu,yo),mS=pe.strictObject({scope:me,runId:pe.uuid(),results:Wd});var at={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},vu="00000000-0000-0000-0000-000000000000";import{z as k}from"zod";import{z as fe}from"zod";var yS=fe.enum(["local","remote"]),Oo=fe.strictObject({port:fe.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:te.optional(),sticky:fe.array(fe.strictObject({expected:cr.nullable(),next:cr})).max(100),exposures:fe.array(te).max(100),features:fe.array(te).max(100)}),Iu=fe.strictObject({type:fe.literal("evaluate"),receiptId:fe.uuid(),environmentId:fe.uuid(),policyRevision:fe.number().int().nonnegative(),attributes:Ke,sticky:fe.record(fe.string(),cr)}),Ou=Iu.extend({runId:fe.uuid(),versionId:fe.uuid(),nodeId:fe.string().min(1).max(64),visit:fe.number().int().nonnegative(),revision:fe.number().int().nonnegative()}),jo=Iu.omit({type:!0,receiptId:!0}).extend({type:fe.literal("evaluate_segment")}),ju=fe.strictObject({nodeId:fe.string().min(1).max(64),result:Oo}),Au=jo.extend({runId:fe.uuid(),versionId:fe.uuid(),nodeId:fe.string().min(1).max(64),visit:fe.number().int().nonnegative(),revision:fe.number().int().nonnegative(),parameters:ut,answers:Et,variables:fe.record(fe.string(),te)});import{z as F}from"zod";var Ao=F.array(F.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),Jr=F.intersection(Ke,F.looseObject({tags:Ao.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Wr=F.string().trim().max(80),Qr=F.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Xr=F.union([F.email().max(254),F.literal("")]),Yr=F.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),wu=F.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),_u=F.object({externalUserId:wu.optional(),name:Wr.default(""),email:Xr.default(""),phone:Qr.optional(),attributes:Jr.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),xt=F.discriminatedUnion("type",[F.strictObject({type:F.literal("id"),value:F.uuid()}),F.strictObject({type:F.literal("externalUserId"),value:wu})]),Pt=F.strictObject({name:Wr.optional(),email:Xr.optional(),phone:Qr.optional(),attributes:Jr.optional(),fingerprint:Yr.optional()}),Vt=e=>!e.customerData||e.customer?.type==="externalUserId",$t="customerData requires an externalUserId customer",yn=F.object({id:F.uuid(),externalUserId:F.string().min(1).max(255).nullable(),name:Wr,email:Xr,phone:Qr.optional(),attributes:Jr,createdAt:F.iso.datetime()}).strict(),Pu=F.object({customer:yn,changed:F.boolean(),replayed:F.boolean()}).strict(),Qd=F.discriminatedUnion("type",[F.object({type:F.literal("id"),value:F.uuid()}).strict(),F.object({type:F.literal("externalUserId"),value:F.string().trim().min(1).max(255)}).strict()]),Xd=F.object({name:Wr.optional(),email:Xr.optional(),phone:Qr.optional(),attributes:Jr.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:F.array(F.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:F.strictObject({add:Ao,remove:Ao}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),wo=F.object({lookup:Qd}).strict(),Cu=wo.extend({requestId:F.uuid(),patch:Xd}).strict(),ku=F.object({search:F.string().trim().max(200).default(""),tag:F.string().trim().max(40).default(""),planId:F.string().max(200).default(""),versionId:F.string().max(200).default(""),holdingStatus:F.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:F.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:F.union([F.iso.datetime(),F.literal("")]).default(""),createdUntil:F.union([F.iso.datetime(),F.literal("")]).default(""),offset:F.coerce.number().int().min(0).max(1e5).default(0),limit:F.coerce.number().int().min(1).max(100).default(50)}).strict(),Ru=F.object({customers:yn.array(),hasMore:F.boolean(),total:F.number().int().nonnegative().nullable(),evaluatedAt:F.iso.datetime()}).strict();var Ln=k.discriminatedUnion("type",[k.strictObject({type:k.literal("literal"),value:te}),k.strictObject({type:k.literal("variable"),key:we,path:ot.optional()}),k.strictObject({type:k.literal("feature"),featureKey:k.string().min(1).max(128)})]),Yd=k.strictObject({requestId:k.uuid(),decisionId:k.uuid(),customerId:k.uuid(),externalUserId:k.string().min(1).max(255).nullable(),versionId:k.uuid(),receiptId:k.uuid(),value:te}),_o={funnelId:k.uuid(),requestId:k.uuid(),customer:xt,customerData:Pt.optional(),attributes:Ke.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},kS=k.discriminatedUnion("operation",[k.strictObject({operation:k.literal("decide"),..._o}).refine(Vt,$t),k.strictObject({operation:k.literal("read_decision"),decisionId:k.uuid()}),k.strictObject({operation:k.literal("evaluate_decision"),decisionId:k.uuid(),requestId:k.uuid(),nodeId:k.string().min(1).max(64),visit:k.number().int().nonnegative(),revision:k.number().int().nonnegative(),receiptId:k.uuid(),policyRevision:k.number().int().nonnegative(),generation:k.string().min(1).max(256),result:Oo}),k.strictObject({operation:k.literal("feature_config"),funnelId:k.uuid()}),k.strictObject({operation:k.literal("commit_decision_segment"),decisionId:k.uuid(),requestId:k.uuid(),nodeId:k.string().min(1).max(64),visit:k.number().int().nonnegative(),revision:k.number().int().nonnegative(),policyRevision:k.number().int().nonnegative(),generation:k.string().min(1).max(256),steps:k.array(ju).max(32),boundary:k.strictObject({nodeId:k.string().min(1).max(64),visit:k.number().int().nonnegative()}).optional()}),k.strictObject({operation:k.literal("segment_configuration"),funnelId:k.uuid(),versionId:k.uuid()}),k.strictObject({operation:k.literal("configuration"),funnelId:k.uuid(),versionId:k.uuid().optional()}),k.strictObject({operation:k.literal("local_configuration"),funnelId:k.uuid()}),k.strictObject({operation:k.literal("report_used"),decisionId:k.uuid(),eventId:k.uuid(),occurredAt:k.iso.datetime({offset:!0}),reference:k.string().min(1).max(128).optional()})]),RS=k.strictObject({scope:me,decisionId:k.uuid(),requestId:k.uuid(),status:k.enum(["pending","completed","failed"]),decision:Yd.nullable(),evaluation:k.discriminatedUnion("type",[Ou,Au]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),ES=k.strictObject({scope:me,decisionId:k.uuid(),eventId:k.uuid(),source:k.literal("caller_reported")});import{z as Me}from"zod";var Eu=Me.strictObject({type:Me.literal("bundle"),paywall:lt.optional(),offering:lt.optional(),coupons:lt,data:lt}),ef=e=>Me.strictObject({type:Me.literal(e),id:Me.uuid()}),qS=Me.strictObject({type:Me.literal("bundle"),paywallVersionId:Me.uuid().optional(),offeringVersionId:Me.uuid().optional(),couponIds:Me.array(Me.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:te});var FS=Me.strictObject({type:Me.literal("bundle"),offering:ef("offering_version").nullable(),paywall:Me.strictObject({versionId:Me.uuid(),paywallId:Me.uuid(),offeringVersionId:Me.uuid()}).nullable(),coupons:Me.array(Tn).max(20),data:te});import{z as st}from"zod";import{z as Ye}from"zod";var Mu=Ye.union([Ye.string(),Ye.number().finite(),Ye.boolean(),Ye.null()]),tf=Ye.union([Mu,Ye.array(Mu).min(1).max(20)]),nf=Ye.record(ot,tf).refine(e=>Object.keys(e).length<=10),Tu=Ye.strictObject({path:ot,type:Ye.enum(["string","number","boolean","strings"]),nullable:Ye.boolean().optional(),aggregation:Ye.enum(["count","exists"]).optional(),where:nf.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var rf=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],Du=st.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),of=lt,zu=st.discriminatedUnion("type",[xu,st.strictObject({type:st.literal("claim_offer"),coupon:lt}),st.strictObject({type:st.literal("event"),event:Du}),st.strictObject({type:st.literal("api"),operation:st.enum(rf),inputs:st.record(ot,of).refine(e=>Object.keys(e).length<=40),outputs:st.record(Du,Tu).refine(e=>Object.keys(e).length<=20)})]);var Se=Hr,af=P.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),We={id:Se,name:P.string().trim().min(1).max(80),position:P.strictObject({x:P.number().finite(),y:P.number().finite()}).optional()},sf={success:Se,cancel:Se,unavailable:Se,failure:Se},Po=P.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Co=P.enum(["same_window","new_window"]),cf=P.discriminatedUnion("type",[P.strictObject({...We,type:P.literal("entry"),next:Se,triggers:P.array(hu).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),P.strictObject({...We,type:P.literal("screen"),screenId:Se,presentation:gt,outputs:P.record(Se,Se),offering:P.discriminatedUnion("source",[P.strictObject({source:P.literal("variable"),key:we}),P.strictObject({source:P.literal("fixed"),versionId:P.uuid()})]).optional()}),P.strictObject({...We,type:P.literal("offering"),configuration:P.discriminatedUnion("source",[P.strictObject({source:P.literal("fixed"),versionId:P.uuid()}),P.strictObject({source:P.literal("feature"),featureKey:P.string().min(1).max(128)})]),writes:P.strictObject({value:we}),next:Se}),P.strictObject({...We,type:P.literal("coupon"),couponId:P.uuid(),writes:P.strictObject({value:we}),next:Se}),P.strictObject({...We,type:P.literal("coupons"),couponIds:P.array(P.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:P.strictObject({value:we}),next:Se}),P.strictObject({...We,type:P.literal("output"),value:P.discriminatedUnion("type",[...Ln.options,Eu,P.strictObject({type:P.literal("selection"),screenId:Se,offeringKey:we})])}),P.strictObject({...We,type:P.literal("condition"),cases:P.array(P.strictObject({condition:it,target:Se})).min(1).max(50),default:Se}),P.strictObject({...We,type:P.literal("feature"),featureKey:P.string().min(1).max(128),writes:P.strictObject({value:we}),next:Se}),P.strictObject({...We,type:P.literal("split"),experimentId:P.uuid(),applyPageExperiment:P.literal(!0).optional(),routes:P.record(af,Se).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:Se}),P.strictObject({...We,type:P.literal("action"),...sf,execution:Su,action:zu,writes:xr.optional()}),P.strictObject({...We,type:P.literal("external_page"),appManifest:Zr.optional(),url:Po,openIn:Co,opened:Se,failed:Se}),P.strictObject({...We,type:P.literal("end"),outcome:P.enum(["completed","closed","ineligible","failed"]),output:Ln.optional()}),P.strictObject({...We,type:P.literal("wait"),writes:xr.optional(),wait:P.discriminatedUnion("type",[P.strictObject({type:P.literal("duration"),delaySeconds:P.number().int().min(1).max(2592e3),elapsed:Se}),P.strictObject({type:P.literal("event"),eventName:Se,outputs:Io,timeoutSeconds:P.number().int().min(1).max(2592e3),received:Se,timeout:Se})])})]),ko=P.strictObject({version:P.literal(5),entry:Se,nodes:P.array(cf).min(1).max(at.flowNodes)}),Ro=ko.superRefine((e,t)=>{uf(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function ei(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function uf(e,t){let n=[],r=new Map(e.nodes.map(h=>[h.id,h])),o=(h,T,$)=>{n.push(h),t?.({message:h,reason:T,path:$?["nodes",e.nodes.indexOf($)]:[]})};r.size!==e.nodes.length&&o("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(h=>h.type==="entry").length!==1)&&o("A flow has exactly one entry node","entry"),(e.nodes.filter(h=>h.type==="screen").length>at.pages||e.nodes.filter(h=>!["screen","entry","end","output"].includes(h.type)).length>at.logicNodes)&&o("Flow node limit exceeded","budget");let a=new Set;for(let h of e.nodes){for(let T of ei(h))T===e.entry&&o("An entry cannot be a transition target","entryTarget",h),r.has(T)||o(`Missing target ${T}`,"missingTarget",h);h.type==="screen"&&(a.has(h.screenId)&&o("Every screen has exactly one node owner","screenOwner",h),a.add(h.screenId))}let l=new Set,p=new Set,d=new Set;function v(h){if(l.has(h)){o("Flow edges must not form a cycle","cycle",r.get(h));return}if(!(p.has(h)||!r.has(h))){l.add(h),d.add(h);for(let T of ei(r.get(h)))v(T);l.delete(h),p.add(h)}}v(e.entry);for(let h of e.nodes)d.has(h.id)||o("Every node must be reachable from Entry","unreachable",h);return[...new Set(n)]}var Eo={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Bu(e,t,n){let r=[...t].sort((p,d)=>d.length-p.length),o=new Set,a=(p,d=!1)=>{let v=r.find(h=>p===h||d&&p.startsWith(h+"."));o.add(v??p)};if(e.type==="condition"){let p=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let d of e.cases.slice(0,p+1))for(let v of jt(d.condition))v.startsWith("variables.")&&a(v.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let p of Object.values(e.action.inputs))p.source==="variable"&&a(p.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let l=e.type==="output"?e.value:e.type==="end"?e.output:null;if(l?.type==="variable"&&a(l.key),l?.type==="bundle")for(let p of[l.paywall,l.offering,l.coupons,l.data])p?.source==="variable"&&a(p.key);return l?.type==="selection"&&a(l.offeringKey),[...o]}import{z as S}from"zod";var xn=S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ti=e=>S.record(S.string(),te).refine(t=>Ze(t)<=e,"Funnel evidence exceeds its byte budget"),hv=S.enum(["local_segment","evaluation","presentation","timer","event","operation"]),To=S.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Do=S.discriminatedUnion("type",[S.strictObject({type:S.literal("flag"),key:S.string().min(1).max(128)}),S.strictObject({type:S.literal("experiment"),id:S.uuid()}),S.strictObject({type:S.literal("saved_group"),id:S.uuid()}),S.strictObject({type:S.literal("config"),key:S.string().min(1).max(128)}),S.strictObject({type:S.literal("constant"),key:S.string().min(1).max(128)}),S.strictObject({type:S.literal("paywall_version"),id:S.uuid()}),S.strictObject({type:S.literal("offering_version"),id:S.uuid()}),S.strictObject({type:S.literal("reward"),id:S.uuid()})]),Zn=S.strictObject({schemaVersion:S.literal(1),kind:To,selector:Do.nullable(),context:ti(131072),contract:S.strictObject({version:S.number().int().positive(),evaluator:S.string().min(1).max(128),policyRevision:S.number().int().nonnegative()})}).refine(e=>Ze(e)<=131072,"Node input exceeds its byte budget"),qu=S.strictObject({schemaVersion:S.literal(1),kind:To,outcome:S.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ti(131072),route:S.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ti(131072)}).refine(e=>Ze(e)<=131072,"Node result exceeds its byte budget"),bv=S.strictObject({schemaVersion:S.literal(1),operations:S.record(xn,S.strictObject({attempts:S.number().int().nonnegative(),maxAttempts:S.number().int().min(1).max(5),deadlineAt:S.iso.datetime({offset:!0}),retryAt:S.iso.datetime({offset:!0}).nullable(),error:S.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:S.strictObject({type:xn,id:S.uuid()}).nullable()}))}).refine(e=>Ze(e)<=65536,"Execution state exceeds its byte budget"),Gt={receiptId:S.uuid()},Mo=S.iso.datetime({offset:!0}),yv=S.discriminatedUnion("type",[S.strictObject({type:S.literal("node_entered"),details:S.strictObject({kind:To})}),S.strictObject({type:S.literal("presentation_shown"),details:S.strictObject({...Gt,source:S.literal("client"),occurredAt:Mo.optional()})}),S.strictObject({type:S.literal("decision_accepted"),details:S.strictObject(Gt)}),S.strictObject({type:S.literal("signal_received"),details:S.strictObject({signalId:S.uuid(),nodeId:xn,eventName:xn,data:ti(8192),source:S.literal("server"),occurredAt:Mo})}),S.strictObject({type:S.literal("signal_consumed"),details:S.strictObject({...Gt,signalId:S.uuid()})}),S.strictObject({type:S.literal("wait_elapsed"),details:S.strictObject(Gt)}),S.strictObject({type:S.literal("wait_timeout"),details:S.strictObject(Gt)}),S.strictObject({type:S.literal("operation_completed"),details:S.strictObject({...Gt,operation:xn,reference:S.strictObject({type:xn,id:S.uuid()}).nullable()})}),S.strictObject({type:S.literal("execution_recovered"),details:S.strictObject({generation:S.number().int().positive(),reason:S.enum(["interrupted","expired_lease","delivery_failed"])})}),S.strictObject({type:S.literal("execution_failed"),details:S.strictObject({generation:S.number().int().positive(),code:S.string().regex(/^[a-z_]{1,64}$/)})}),S.strictObject({type:S.literal("run_completed"),details:S.strictObject({outcome:S.enum(["completed","ineligible","failed"])})}),S.strictObject({type:S.literal("run_closed"),details:S.strictObject({source:S.enum(["client","server","expiry"])})}),S.strictObject({type:S.literal("treatment_used"),details:S.strictObject({...Gt,source:S.enum(["client","server"]),occurredAt:Mo,reference:S.string().min(1).max(128).optional()})})]);var et=j.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),pf=j.discriminatedUnion("type",[j.strictObject({id:et,type:j.literal("owned"),publicData:iu.optional(),document:Le.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),j.strictObject({id:et,type:j.literal("paywall"),paywallVersionId:j.uuid()})]),zo={executionContract:po.optional(),kind:j.literal("funnel"),schemaVersion:j.literal(4),screens:j.array(pf).max(at.pages),references:j.record(et,Do).refine(e=>Object.keys(e).length<=500),inputs:j.array(j.strictObject({variable:et,screenId:et,componentId:et,required:j.boolean()})).max(at.questions),variables:j.record(we,rn).refine(e=>Object.keys(e).length<=at.logicNodes),outputSchema:nn,execution:j.strictObject({runTimeoutSeconds:j.number().int().min(1).max(Eo.runTimeoutSeconds),maxTransitions:j.number().int().min(1).max(Eo.maxTransitions)})},qv=j.strictObject({...zo,graph:ko});function lf(e,t){let n=!1,r=(o,a)=>{let l=o.type==="stack"||o.type==="button"?o.bind?.coupon??a:a;o.type==="text"&&Object.values(e.strings.locales).some(p=>p[o.text]?.includes("{{offer."))&&!(l&&t(l))&&(n=!0),o.type==="stack"&&o.children.forEach(p=>r(p,l))};for(let o of e.pages)r(o.root);return n}function ri(e){return Array.isArray(e)?e.some(ri):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===vu:ri(n))}function mf(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,o]of e.screens.entries()){if(o.type!=="owned")continue;let a;try{a=lu(o.document)}catch(l){t.push({message:l instanceof Error?l.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[l,p]of e.inputs.entries())p.screenId===o.id&&!hi(a,p.componentId)&&t.push({message:`Local Funnel input ${p.variable} targets hidden component ${p.componentId} on screen ${p.screenId}`,reason:"inputBinding",path:["inputs",l]})}for(let[r,o]of e.graph.nodes.entries()){let a=["graph","nodes",r],l=o.type==="screen"?e.screens.find(p=>p.id===o.screenId):void 0;l?.type==="owned"&&(l.document.actions.some(p=>typeof p.properties.templateKey=="string"&&p.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),lf(l.document,p=>n.has(p))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(o.type==="output"&&o.value.type==="literal"&&ri(o.value.value)||o.type==="end"&&o.output?.type==="literal"&&ri(o.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Fu(e,t){for(let{message:n,reason:r,path:o}of mf(e))t.addIssue({code:"custom",message:n,path:o,params:{reason:r}})}function Nu(e,t){let n=(C,u,b=[])=>t.addIssue({code:"custom",message:C,path:b,params:{reason:u}}),r=Object.values(e.references),o=new Map(e.screens.map(C=>[C.id,C])),a=(C,u)=>r.some(b=>b.type===C&&("id"in b?b.id:b.key)===u);o.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let l=e.graph.nodes.filter(C=>C.type==="screen");(l.length!==o.size||l.some(C=>!o.has(C.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let p=new Map,d=Object.keys(e.variables);d.some(C=>d.some(u=>C!==u&&u.startsWith(C+".")))&&n("Variable paths must not overlap","variable");function v(C,u){Object.hasOwn(e.variables,C)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(u)]);let b=p.get(C)??new Set;b.add(u.id),p.set(C,b)}for(let[C,u]of e.graph.nodes.entries()){let b=["graph","nodes",C],Z=u.type==="feature"?u.featureKey:u.type==="offering"&&u.configuration.source==="feature"?u.configuration.featureKey:u.type==="output"&&u.value.type==="feature"?u.value.featureKey:u.type==="end"&&u.output?.type==="feature"?u.output.featureKey:null;Z&&!a("flag",Z)&&n("Flag selectors require an explicit GB resource reference","feature",b);let E=u.type==="feature"||u.type==="offering"||u.type==="coupon"||u.type==="coupons"||u.type==="action"&&u.action.type==="api"?["value"]:u.type==="action"&&u.action.type==="external_task"?Object.keys(u.action.outputs):u.type==="wait"&&u.wait.type==="event"?Object.keys(u.wait.outputs):[],ae="writes"in u?u.writes??{}:{};(E.length!==Object.keys(ae).length||E.some(L=>!Object.hasOwn(ae,L))||new Set(Object.values(ae)).size!==Object.values(ae).length)&&n("Node writes must map every named output exactly once","variable",b);for(let[L,ee]of Object.entries(ae)){v(ee,u);let le=e.variables[ee],H=u.type==="offering"?"offering_version":u.type==="coupon"?"reward":u.type==="action"&&u.action.type==="api"?"json":u.type==="action"&&u.action.type==="external_task"?u.action.outputs[L]:u.type==="wait"&&u.wait.type==="event"?u.wait.outputs[L]:void 0;(le?.source.type!=="node"||H&&le.type!==H)&&n("Node writer source or output type does not match declaration","variable",b)}if(u.type==="coupons"){let L=e.variables[u.writes.value];(L?.type!=="array"||L.items?.type!=="reward"||L.items.nullable||L.nullable)&&n("Coupons output requires a non-null Reward array","variable",b);for(let ee of u.couponIds)a("reward",ee)||n("Coupons require Reward references","coupon",b)}if(u.type==="split"&&!a("experiment",u.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",b),u.type==="coupon"&&!a("reward",u.couponId)&&n("Coupon selectors require a Reward reference","coupon",b),u.type==="action"&&u.action.type==="claim_offer"&&u.action.coupon.source==="literal"){let L=u.action.coupon.value;(!L||typeof L!="object"||Array.isArray(L)||L.type!=="reward"||typeof L.id!="string"||Object.keys(L).length!==2||!a("reward",L.id))&&n("Coupon claims require a Reward reference","coupon",b)}if(u.type==="offering"&&u.configuration.source==="fixed"&&!a("offering_version",u.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",b),u.type==="screen"&&u.offering?.source==="variable"&&e.variables[u.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",b),u.type==="action"&&u.action.type==="claim_offer"&&u.action.coupon.source==="variable"&&(e.variables[u.action.coupon.key]?.type!=="reward"||u.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",b),u.type==="screen"){let L=o.get(u.screenId);if(u.offering?.source==="fixed"&&!a("offering_version",u.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",b),L?.type==="paywall"&&u.offering&&n("Paywall owns its fixed Offering Version","offering",b),L?.type==="paywall"&&!a("paywall_version",L.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",b),L?.type==="owned"){let ee=L.document.pages[0];if(!ee){n("Owned screen requires a page","screen",b);continue}It(L.document).some(H=>!H.complete)&&n("Owned screens require complete local content","translations",b);let le=new Set(L.document.actions.map(H=>H.id));(le.size!==Object.keys(u.outputs).length||Object.keys(u.outputs).some(H=>!le.has(H)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",b),Yt(ee.root,H=>{!u.offering&&(H.type==="plan_picker"||(H.type==="stack"||H.type==="button")&&H.bind?.plan||H.type==="customer_data"&&["customer_plans","credit_packs"].includes(H.data.source))&&n("Product presentation requires an Offering Version","offering",b),H.type==="customer_data"&&Object.values(H.data.outputs??{}).some(St=>St!==void 0&&!le.has(St))&&n("Customer components require declared screen outcomes","componentOutput",b)})}}u.type==="end"&&["completed","ineligible"].includes(u.outcome)&&!u.output&&n("Completed and ineligible ends require a declared output","output",b),u.type==="end"&&u.output?.type==="literal"&&!Xe(e.outputSchema,u.output.value)&&n("Terminal output does not match outputSchema","output",b),u.type==="output"&&u.value.type==="literal"&&!Xe(e.outputSchema,u.value.value)&&n("Terminal output does not match outputSchema","output",b);let Ce=u.type==="output"?u.value:u.type==="end"?u.output:void 0;if(Ce?.type==="variable"&&!Ce.path){let L=e.variables[Ce.key];L&&!wi(L,e.outputSchema)&&n("Variable output does not match outputSchema","output",b)}if(u.type==="screen"){let L=o.get(u.screenId);if(L?.type==="owned")for(let ee of ki(L.document))(/^(input|params)\./.test(ee)||ee.startsWith("variables.")&&!Ci(ee.slice(10),d))&&n("Screen values must reference registered variables","variable",b)}if(u.type==="condition")for(let L of u.cases){for(let ee of vt(L.condition))a("saved_group",ee)||n("Conditions require explicit Saved Group references","savedGroup",b);for(let ee of jt(L.condition))ee.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",b)}if(u.type==="output"&&u.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",b);for(let[L,ee]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let le=u.value[L];if(le)if(le.source==="literal"){let H=L==="coupons"?le.value:[le.value];(!Array.isArray(H)||H.length>20||H.some(St=>!Xe({type:ee,nullable:!1},St)||!a(ee,St.id))||L==="coupons"&&new Set(H.map(St=>St.id)).size!==H.length)&&n("Bundle requires distinct scoped resource references",L==="coupons"?"coupon":L==="paywall"?"paywall":"offering",[...b,"value",L])}else{let H=e.variables[le.key];(le.path||!H||H.nullable||(L==="coupons"?H.type!=="array"||H.items?.type!=="reward"||H.items.nullable:H.type!==ee))&&n("Bundle binding type does not match its slot","output",b)}}}}for(let[C,u]of e.graph.nodes.entries()){let b=u.type==="screen"?o.get(u.screenId):void 0,Z=[...Bu(u,d),...b?.type==="owned"?Sr(b.document).map(E=>Ci(E,d)?.key??E):[]];for(let E of new Set(Z)){let ee=function(le){if(le===u.id)return!0;if(L.has(le))return!1;L.add(le);let H=e.graph.nodes.find(tl=>tl.id===le);return H?(Ce.has(le)?H.type==="action"?[H.cancel,H.unavailable,H.failure]:H.type==="wait"&&H.wait.type==="event"?[H.wait.timeout]:[]:ei(H)).some(ee):!1};var $=ee;if(!Object.hasOwn(e.variables,E)){n("Consumed variable is undeclared","variable",["graph","nodes",C]);continue}let ae=e.variables[E];if(u.type==="screen"&&ae.source.type==="input"&&e.inputs.some(le=>le.screenId===u.screenId&&le.variable===E)||ae.source.type==="parameter"||ae.source.type==="attribute")continue;let Ce=ae.source.type==="input"?new Set(e.inputs.filter(le=>le.variable===E&&le.required).flatMap(le=>l.filter(H=>H.screenId===le.screenId).map(H=>H.id))):p.get(E)??new Set,L=new Set;(!Ce.size||ee(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",C])}}(new Set(e.inputs.map(C=>C.variable)).size!==e.inputs.length||new Set(e.inputs.map(C=>`${C.screenId}:${C.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[C,u]of e.inputs.entries()){e.variables[u.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",C]);let b=o.get(u.screenId),Z=b?.type==="owned"?hi(b.document,u.componentId):null;if((Z?.type!=="stack"||!Z.interaction||!["input","toggle","select","multiselect","tabs"].includes(Z.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",C]),Z?.type==="stack"&&Z.interaction){let E=Z.interaction.type==="toggle"?"boolean":Z.interaction.type==="multiselect"?"strings":"string";e.variables[u.variable]?.type!==E&&n("Input variable type does not match component","inputBinding",["inputs",C]);let ae=e.variables[u.variable]?.enum;ae&&!Z.children.filter(Ce=>!Ce.hidden).every(Ce=>ae.includes(Ce.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",C])}}for(let[C,u]of Object.entries(e.variables))u.enum&&u.type!=="string"&&n("Only string variables support enum","variable",["variables",C]),u.source.type==="input"&&!e.inputs.some(b=>b.variable===C)&&n("Input variable requires a component binding","inputBinding",["variables",C]);let h=0,T=0;for(let C of e.screens)if(C.type==="owned"){for(let u of C.document.pages)Yt(u.root,()=>{h++});T+=C.document.actions.length}(h>at.components||T>at.actions||Ze(e)>at.documentBytes)&&n("Funnel document exceeds its budget","budget")}var df=j.strictObject({...zo,graph:Ro}).superRefine(Nu),Ct=j.strictObject({...zo,graph:Ro,displayName:j.string().trim().min(1).max(80)}).superRefine(Nu),Fv=Ct.superRefine(Fu),Nv=df.superRefine(Fu),ni=j.string().regex(pt),Hn={requestId:j.uuid(),nodeId:et,visit:j.number().int().nonnegative(),revision:j.number().int().nonnegative(),customerToken:ni.optional()},ff=j.discriminatedUnion("type",[j.strictObject({type:j.literal("screen"),output:et,answers:Et,selection:j.record(et,j.union([j.string().max(200),j.boolean(),j.number().int().min(0).max(1e4)])).optional()}),j.strictObject({type:j.literal("paywall_quote"),featureQuantities:j.record(j.uuid(),j.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:et,productVersionId:j.uuid(),offerId:j.uuid().optional(),nativeOffer:un.optional(),predecessor:j.strictObject({operationId:j.uuid().nullable(),generation:j.number().int().positive()}).optional()}),j.strictObject({type:j.literal("paywall_confirm"),operationId:j.uuid()}),j.strictObject({type:j.literal("paywall_cancel"),operationId:j.uuid()}),j.strictObject({type:j.literal("client_action"),receiptId:j.uuid(),outcome:j.enum(["success","cancel","failure","opened","failed"])})]),gf=j.object({nodeId:et,visit:j.number().int().nonnegative(),revision:j.number().int().nonnegative(),components:j.record(et,j.object({resourceKey:j.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:j.number().int().min(1).max(1e5),after:lr.nullable(),filter:j.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),tt=j.discriminatedUnion("operation",[j.strictObject({operation:j.literal("start"),funnelId:j.uuid(),requestId:j.uuid(),customer:xt.optional(),customerData:Pt.optional(),locale:j.string().min(1).max(35),parameters:ut}).refine(Vt,$t),j.strictObject({operation:j.literal("get"),settlementRequestId:j.uuid().optional(),data:gf.optional(),purchase:j.strictObject({receiptId:j.uuid(),operationId:j.uuid()}).optional(),customerToken:ni.optional()}),j.strictObject({operation:j.literal("resume"),requestId:j.uuid(),customerToken:ni.optional()}),j.strictObject({operation:j.literal("submit"),...Hn,input:ff}),j.strictObject({operation:j.literal("back"),...Hn}),j.strictObject({operation:j.literal("shown"),...Hn}),j.strictObject({operation:j.literal("close"),...Hn}),j.strictObject({operation:j.literal("commit_segment"),...Hn,policyRevision:j.number().int().nonnegative(),generation:j.string().min(1).max(256)}),j.strictObject({operation:j.literal("review"),receiptId:j.uuid().optional(),customerToken:ni.optional()})]);function ii(e,t){let n=new Set,r=new Set,o=new Set,a=[],l=new Map,p=new Map,d=new Map;function v(u){for(let b of vt(u))h(b)}function h(u){if(o.has(u)||!Object.hasOwn(t.savedGroups,u))return;let b=t.savedGroups[u];b&&(o.add(u),d.set(u,b),a.push(()=>{!Array.isArray(b)&&b.type==="condition"&&v(b.condition)}))}function T(u){for(let b of["hashAttribute","fallbackAttribute"])if(u[b]!==void 0&&xo(u[b]))throw new Error(`Funnel GB ${b} uses a reserved flow namespace`);v(u.condition);for(let b of u.parentConditions??[])$(b.id),v(b.condition)}function $(u,b=!1){let Z=Object.hasOwn(t.features,u)?t.features[u]:void 0;if(!Z){if(b)throw new Error("Required GB Feature is unavailable");return}n.has(u)||(n.add(u),l.set(u,Z),a.push(()=>{for(let E of Z.rules??[]){T(E);for(let ae of E.tracks??[])T(ae.experiment)}}))}function C(u){let b=Object.hasOwn(t.experiments,u)?t.experiments[u]:void 0;if(!b)throw new Error("Required GB Experiment is unavailable");r.has(u)||(r.add(u),p.set(u,b),a.push(()=>T(b)))}for(let u of e.graph.nodes){u.type==="feature"&&$(u.featureKey,!0),u.type==="split"&&C(u.experimentId),u.type==="condition"&&u.cases.forEach(Z=>v(Z.condition)),u.type==="offering"&&u.configuration.source==="feature"&&$(u.configuration.featureKey,!0);let b=u.type==="output"?u.value:u.type==="end"?u.output:null;b?.type==="feature"&&$(b.featureKey,!0)}for(let u of a)u();return{...t,features:Object.fromEntries(l),experiments:Object.fromEntries(p),savedGroups:Object.fromEntries(d)}}import{z as B}from"zod";import{z as Jn}from"zod";var Uu=Jn.object({defaultLocale:Jt,locales:Jn.record(Jt,Jn.object({name:Jn.string().max(80),description:Jn.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var hf=["customer_data","coupon_code"],Vu=B.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),bf=B.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),oi=(e,t)=>new Set(e.map(t)).size===e.length,yf=B.strictObject({currency:oe,amountMinor:B.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),xf=B.strictObject({featureId:B.uuid(),name:B.string().trim().min(1).max(120),allowance:B.string().max(40).nullable(),access:B.boolean()}),Sf=B.strictObject({stripe:B.strictObject({prices:B.array(yf).min(1).max(50)}).optional(),apple:B.strictObject({productIds:B.array(Vu).min(1).max(10)}).optional(),google:B.strictObject({products:B.array(B.strictObject({productId:Vu,basePlanId:bf.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!oi(e.stripe.prices,n=>n.currency)||e.apple&&!oi(e.apple.productIds,n=>n)||e.google&&!oi(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),vf=B.strictObject({name:B.string().trim().min(1).max(80),interval:B.enum(["free","week","month","year","one_time"]),intervalCount:B.number().int().min(1).max(100),trial:B.strictObject({days:B.number().int().min(1).max(730),cardRequired:B.boolean()}).nullable(),benefits:B.array(xf).max(50).refine(e=>oi(e,t=>t.featureId),"Duplicate benefit"),channels:Sf,prepaid:B.array(_a).max(100).optional()}),If=B.strictObject({digest:gn,content:B.strictObject({discount:At,duration:He,appliesTo:Ni,displayCopy:Uu.nullable(),firstPurchaseOnly:B.boolean(),qualificationRequired:B.boolean(),startsAt:B.iso.datetime().nullable(),endsAt:B.iso.datetime().nullable(),grantWindowHours:B.number().int().positive(),perCustomerLimit:B.number().int().positive()})}),Of=B.discriminatedUnion("type",[B.strictObject({type:B.literal("checkout"),product:pr}),B.strictObject({type:B.literal("close")}),B.strictObject({type:B.literal("action"),action:oo})]),$u=B.strictObject({kind:B.literal("paywall"),formatVersion:B.literal(1),name:B.string().trim().min(1).max(80),offeringVersionId:B.uuid(),presentation:gt,screen:Le,products:Ir,catalog:B.record(B.uuid(),vf),buttons:B.record(Cn,Of),coupons:B.record(B.uuid(),If)}).superRefine((e,t)=>{let n=b=>t.addIssue({code:"custom",message:b}),{screen:r}=e;Ba(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),mo(r,hf).forEach(n),It(r).some(b=>!b.complete)&&n("Every published locale must be complete");let o=new Set,a=new Set,l=new Set;ht(r,b=>{let Z="bind"in b?b.bind:void 0;Z?.promotionCode&&n("Promotion codes must not be published"),Z?.plan&&o.add(Z.plan),Z?.coupon&&a.add(Z.coupon),b.type==="plan_picker"&&(b.planIds?.forEach(E=>o.add(E)),b.defaultPlan&&o.add(b.defaultPlan)),b.type==="text"&&b.feature&&l.add(b.feature.id)});let p=e.products.items.map(b=>b.productVersionId),d=Object.keys(e.catalog);(p.length!==d.length||p.some(b=>!Object.hasOwn(e.catalog,b)))&&n("Catalog must contain exactly the displayed Products");let v=new Set(p);e.products.defaultProductVersionId!==null&&!v.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let b of o)v.has(b)||n("Screen references a Product that is not displayed");for(let b of Object.values(e.catalog))!b.channels.stripe&&!b.channels.apple&&!b.channels.google&&n("A displayed Product needs at least one sales channel");let h=new Set(Object.values(e.catalog).flatMap(b=>b.benefits.map(Z=>Z.featureId)));for(let b of l)h.has(b)||n("Feature text must read a displayed benefit");let T=r.actions.filter(b=>b.type!=="navigate");r.actions.some(b=>b.type!=="event"&&b.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==T.length||T.some(b=>!Object.hasOwn(e.buttons,b.id)))&&n("Buttons must match the screen's actions");let C=!1;for(let b of Object.values(e.buttons)){if(b.type!=="checkout")continue;C=!0,(b.product.type==="fixed"?[b.product.productVersionId]:b.product.allowedProductVersionIds).some(E=>!v.has(E))&&n("Checkout may only sell displayed Products")}C||n("A Paywall needs a checkout button");let u=Object.keys(e.coupons);(u.length!==a.size||u.some(b=>!a.has(b)))&&n("Coupons must be exactly the bound Coupons")}),Gu=B.strictObject({state:B.enum(["published","archived"]),controlRevision:B.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:B.uuid(),versions:B.record(B.uuid(),B.strictObject({version:B.number().int().positive(),artifact:B.string().min(1),sourceDigest:B.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var jf={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Bo=Y.string().regex(/^[a-f0-9]{64}$/),qo=Y.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Af=me.extend({environmentId:Y.uuid()}),Ku=Y.strictObject({features:Y.array(Y.string()).max(500),experiments:Y.record(Y.uuid(),Y.array(Y.string()).max(20)),savedGroups:Y.array(Y.string()).max(1e3)}),Uo=Y.strictObject({kind:Y.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Y.number().int().positive(),url:Y.string().min(1).max(2048),sha256:Bo,byteLength:Y.number().int().positive().max(jf.maxArtifactBytes),generation:Bo.optional()}),wf=Y.strictObject({state:Y.enum(["active","paused","archived"]),controlRevision:qo,evaluationMode:Y.enum(["local","remote"]),evaluationRevision:qo,currentVersionId:Y.uuid(),versions:Y.record(Y.uuid(),Y.strictObject({artifact:Y.string(),dependencies:Ku,definitionDigest:gn.optional(),couponDigests:Y.record(Y.uuid(),gn).optional()}))}),bI=Y.strictObject({kind:Y.literal("sdk_configuration"),schemaVersion:Y.literal(1),scope:Af,revision:qo,generation:Bo,policy:Y.strictObject({refreshIntervalSeconds:Y.number().positive().max(15),maxControlAgeSeconds:Y.number().positive().max(60)}),gb:Y.strictObject({features:Y.string().nullable(),pageExperiments:Y.string().nullable()}),artifacts:Y.record(Y.string(),Uo),funnels:Y.record(Y.uuid(),wf),paywalls:Y.record(Y.uuid(),Gu).optional()}).superRefine((e,t)=>{let n=(r,o)=>{r!==null&&e.artifacts[r]?.kind!==o&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let o of Object.values(r.versions))n(o.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let o of Object.values(r.versions))n(o.artifact,"funnel")}});function Fo(e){if(Array.isArray(e))return`[${e.map(Fo).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Fo(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function _f(e){return ar(sr(typeof e=="string"?new TextEncoder().encode(e):e))}function yI(e){return _f(Fo(e))}var No=class extends Error{constructor(n,r){super(n);this.dependency=r}dependency};function xI(e,t){let n=h=>h.type==="feature"?h.featureKey:h.type==="end"&&h.output?.type==="feature"?h.output.featureKey:h.type==="output"&&h.value.type==="feature"?h.value.featureKey:void 0,r=(h,T)=>e.graph.nodes.find($=>h==="experiment"?$.type==="split"&&$.experimentId===T:h==="feature"&&n($)===T)?.name,o=(h,T,$=r(T.type,T.resource))=>new No(h,{...T,...$?{step:$}:{}});for(let h of Object.values(e.references)){let T=h.type==="flag"?!Object.hasOwn(t.features,h.key)||t.remoteFeatures.includes(h.key)?{type:"feature",resource:h.key}:null:h.type==="experiment"?Object.hasOwn(t.experiments,h.id)?null:{type:"experiment",resource:h.id}:h.type==="saved_group"&&!Object.hasOwn(t.savedGroups,h.id)?{type:"saved_group",resource:h.id}:null;if(T)throw o("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...T})}let a=ii(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),l=new Set(t.remoteFeatures);for(let h of e.graph.nodes){let T=n(h);if(!T)continue;let $=a.features[T],C=h.type==="feature"?e.variables[h.writes.value]:e.outputSchema,u={type:"feature",resource:T};if(!$||!C)throw o("Required public Feature declaration is unavailable",{reason:"unavailable",...u},h.name);if([$.defaultValue,...($.rules??[]).flatMap(Z=>[...Object.hasOwn(Z,"force")?[Z.force]:[],...Z.variations??[],...(Z.tracks??[]).flatMap(E=>E.experiment.variations)])].some(Z=>Z===void 0||!Xe(C,Z)))throw o("GB Feature values violate the Funnel type contract",{reason:"value_type",...u},h.name)}let p=new Set,d=(h,T)=>{for(let $ of vt(h)){if(p.has($))continue;let C=t.savedGroups[$];if(!C)throw o("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:$},T);p.add($),!Array.isArray(C)&&C.type==="condition"&&d(C.condition,T)}},v=(h,T)=>{if(l.has(h)||!t.features[h])throw o("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:h},T)};for(let h of e.graph.nodes)if(h.type==="condition")for(let T of h.cases)d(T.condition,h.name);for(let[h,T]of Object.entries(a.features)){let $=r("feature",h);for(let C of T.rules??[]){d(C.condition,$);for(let u of[...C.parentConditions??[],...(C.tracks??[]).flatMap(b=>b.experiment.parentConditions??[])])v(u.id,$),d(u.condition,$);for(let u of C.tracks??[])d(u.experiment.condition,$)}}for(let[h,T]of Object.entries(a.experiments)){let $=r("experiment",h);d(T.condition,$);for(let C of T.parentConditions??[])v(C.id,$),d(C.condition,$)}for(let h of e.graph.nodes)if(h.type==="split"){let T=a.experiments[h.experimentId],$={type:"experiment",resource:h.experimentId};if(!T)throw o("Local Funnel requires a public Experiment",{reason:"unavailable",...$},h.name);for(let C of T.variations)if(typeof C!="string"||!Object.hasOwn(h.routes,C))throw o("Experiment variation has no declared Funnel route",{reason:"variation_route",...$},h.name)}return Ku.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([h,T])=>[h,T.variations.map(String)])),savedGroups:[...p].sort()})}function SI(e){return Ct.parse(e)}var Lu=_e.strictObject({processContext:Tr.optional(),...cn,selector:_e.discriminatedUnion("type",[_e.strictObject({type:_e.literal("paywall"),paywallId:_e.uuid()}),_e.strictObject({type:_e.literal("version"),versionId:_e.uuid()})]),customerId:_e.uuid().optional(),commerce:ur,locale:_e.string().min(1).max(35),requirement:Qt.optional()}),Wn=_e.strictObject({id:_e.uuid(),paywallId:_e.uuid(),version:_e.number().int().positive(),document:fn.omit({requirement:!0,offeringId:!0}),offering:_e.strictObject({id:_e.uuid()}),content:_e.strictObject({environmentId:_e.uuid(),offeringVersionId:_e.uuid(),artifact:Uo.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Xt,check:Pn.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Qn=_e.strictObject(Wn.shape).omit({document:!0,offering:!0}).extend({content:Wn.shape.content.unwrap()});function EI(e,t){let n=$u.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[o,a]of Object.entries(n.catalog)){let l=r.plans[o],p=a.channels.stripe?.prices.find(d=>d.currency===l?.currency);l&&p&&Object.assign(l,{amountMinor:p.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return Wn.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Ne}from"zod";var Zu={requestId:Ne.uuid(),sourceId:Ne.uuid(),expectedAvailable:Wt},Hu=Ne.discriminatedUnion("action",[Ne.strictObject({...Zu,action:Ne.enum(["add","subtract","set_remaining"]),amount:ye}),Ne.strictObject({...Zu,action:Ne.literal("edit"),granted:ye,expiresAt:Ne.iso.datetime({offset:!0}).nullable(),nextResetAt:Ne.iso.datetime({offset:!0}).nullable(),expectedRevision:Ne.number().int().nonnegative()})]),Vo=Ne.strictObject({sourceId:Ne.uuid(),available:Wt,held:Wt,spent:Wt,adjustmentGrantId:Ne.uuid().nullable()}),Ju=Vo.extend({granted:Wt,expiresAt:Ne.iso.datetime({offset:!0}).nullable(),nextResetAt:Ne.iso.datetime({offset:!0}).nullable(),revision:Ne.number().int().nonnegative()});import{z as Qe}from"zod";var Wu=Qe.discriminatedUnion("action",[Qe.object({action:Qe.literal("upsert"),externalId:Qe.string().min(1).max(128),name:Qe.string().trim().min(1).max(80)}).strict(),Qe.object({action:Qe.literal("archive"),entityId:Qe.uuid()}).strict()]),Qu=Qe.object({id:Qe.uuid(),externalId:Qe.string().min(1).max(128),name:Qe.string().min(1).max(80),archived:Qe.boolean()}).strict();import{z as ze}from"zod";import{z as Lt}from"zod";var Yu=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Xu=Lt.string().regex(/.+\/.+/),$o=Lt.number().min(-100),Kt=Lt.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),Pf=Lt.strictObject({input:Kt,output:Kt,cache_read:Kt.optional(),cache_write:Kt.optional(),reasoning:Kt.optional(),input_audio:Kt.optional(),output_audio:Kt.optional()}),Go=(e,t)=>Lt.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),UI=Lt.strictObject({defaultMarkup:$o,providerMarkups:Go(Lt.string().min(1),$o),modelMarkups:Go(Xu,$o),customModels:Go(Xu,Pf.partial())});import{z as K}from"zod";var Zt=K.iso.datetime({offset:!0}),kt=K.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Cf=K.discriminatedUnion("kind",[K.object({kind:K.literal("absolute"),from:Zt,to:Zt}).strict(),K.object({kind:K.literal("last_days"),days:K.union([K.literal(1),K.literal(7),K.literal(30),K.literal(90)])}).strict(),K.object({kind:K.literal("billing_cycles"),membershipId:K.uuid(),count:K.number().int().min(1).max(12),includeCurrent:K.boolean()}).strict()]),ep=K.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),kf=K.object({key:K.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:K.array(K.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Ht=K.object({range:Cf,timezone:ep,filterBy:K.array(kf).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:K.enum(["hour","day","week","month"]),internal_feature_id:K.uuid().nullable(),entityId:K.uuid().nullable(),topN:K.number().int().min(1).max(50).nullable(),groupBy:K.union([K.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),K.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:K.object({bucket:Zt,group:K.string().max(240),isOther:K.boolean(),internal_feature_id:K.uuid(),resourceId:K.uuid()}).strict().nullable(),limit:K.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),tp=K.object({from:Zt,to:Zt,interval:K.enum(["hour","day","week","month"]),timezone:ep,rows:K.array(K.object({bucket:Zt,group:K.string().max(240),isOther:K.boolean(),internal_feature_id:K.uuid(),resourceId:K.uuid(),consumedUnits:kt,refundedUnits:kt,reservedUnits:kt,charged:kt,refunded:kt,reserved:kt,netUnits:kt,netCharged:kt}).strict()).max(100),nextCursor:K.object({bucket:Zt,group:K.string().max(240),isOther:K.boolean(),internal_feature_id:K.uuid(),resourceId:K.uuid()}).strict().nullable()}).strict();var Sn=ze.string().regex(/^(0|[1-9]\d{0,29})$/),np=ze.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Ko=ze.strictObject({bucket:ze.iso.datetime({offset:!0}),group:ze.string().max(240),isOther:ze.boolean(),internal_feature_id:ze.uuid()}),rp=ze.strictObject({...Ht.shape,groupBy:ze.union([ze.enum(["customer","entity","entitlement"]),ze.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Ko.nullable()}).superRefine((e,t)=>{let n=Ht.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),ip=ze.strictObject({from:ze.iso.datetime({offset:!0}),to:ze.iso.datetime({offset:!0}),interval:Ht.shape.interval,timezone:Ht.shape.timezone,rows:ze.array(ze.strictObject({...Ko.shape,eventCount:Sn,units:np,tokenEventCount:Sn,tokens:ze.strictObject(Object.fromEntries(Yu.map(e=>[e,Sn]))),totalTokens:Sn,providerCostEventCount:Sn,providerCostUsd:np,invalidTelemetryEventCount:Sn})).max(100),nextCursor:Ko.nullable()});import{z as je}from"zod";var op=je.object({requestId:je.uuid(),items:je.array(je.object({customerId:je.uuid(),command:wn.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"),ap=je.object({batchId:je.uuid(),after:je.number().int().min(-1).max(999),limit:je.number().int().min(1).max(100)}).strict(),sp=je.object({batchId:je.uuid(),status:je.enum(["queued","complete"]),total:je.number().int().min(1).max(1e3),processed:je.number().int().min(0).max(1e3),items:je.array(je.object({position:je.number().int().min(0).max(999),customerId:je.uuid(),idempotencyKey:je.string().min(1).max(120),status:je.enum(["queued","accepted","rejected","failed"]),receipt:_n.nullable(),errorCode:je.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:je.number().int().min(0).max(999).nullable()}).strict();import{z as f}from"zod";var Rf=f.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),cp=f.enum(["draft","active","paused","archived"]),up=f.string().min(1).max(256),pp=f.array(up).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Ef=f.strictObject({duration:f.enum(["day","week","month","year"]),length:f.number().int().min(1).max(3660)}),Mf=f.strictObject({internal_feature_id:f.uuid(),allowance:f.number().nonnegative().max(1e15).nullable(),expiry:Ef.nullable()}),Tf=f.discriminatedUnion("type",[f.strictObject({type:f.literal("feature_grant"),grants:f.array(Mf).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),f.strictObject({type:f.literal("free_product"),productId:up,duration:He}),f.strictObject({type:f.literal("invoice_credits"),amount:f.number().positive().max(1e8),duration:He,rollover:f.boolean(),productIds:pp})]),Df=f.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),lp=f.object({key:Df,name:f.string().trim().min(1).max(80),configuration:Tf}).strict(),mp=f.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Lo=f.object({code:mp,maxUses:f.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:f.boolean()}).strict(),dp=f.object({key:f.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:f.string().trim().min(1).max(80),rewardId:f.uuid(),redeemOn:f.enum(["customer_creation","checkout"]),receivedBy:f.enum(["referrer","all"]),maxRedemptions:f.number().int().min(1).max(1e6).nullable(),productIds:pp,excludeTrial:f.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),fp={id:f.uuid(),projectId:f.uuid(),environmentId:f.uuid(),revision:f.number().int().nonnegative(),status:cp,createdAt:f.iso.datetime({offset:!0}),updatedAt:f.iso.datetime({offset:!0})},zf=lp.extend(fp).strict(),Bf=dp.safeExtend(fp).strict(),t0=f.strictObject({id:f.uuid(),key:f.string(),name:f.string(),type:Rf,status:cp}),n0=f.discriminatedUnion("action",[f.object({action:f.literal("save"),id:f.uuid().nullable(),revision:f.number().int().nonnegative(),input:lp}).strict(),f.object({action:f.enum(["activate","pause","resume","archive","delete"]),id:f.uuid(),revision:f.number().int().nonnegative()}).strict()]),r0=f.discriminatedUnion("action",[f.object({action:f.literal("save"),id:f.uuid().nullable(),revision:f.number().int().nonnegative(),input:dp}).strict(),f.object({action:f.enum(["activate","pause","resume","archive","delete"]),id:f.uuid(),revision:f.number().int().nonnegative()}).strict()]),gp=f.object({id:f.uuid(),rewardId:f.uuid(),programId:f.uuid().nullable(),customerId:f.uuid(),referrerId:f.uuid().nullable(),status:f.enum(["pending","applied","unavailable"]),result:f.record(f.string(),f.unknown()).nullable(),createdAt:f.iso.datetime({offset:!0})}).strict(),hp=f.object({code:mp,requestId:f.uuid()}).strict(),bp=f.strictObject({redemptionId:f.uuid(),currency:oe,requestId:f.uuid(),accepted:f.literal(!0)}),qf=f.strictObject({type:f.literal("checkout"),orderId:f.uuid(),productVersionId:f.uuid(),currency:oe,duration:He,renewalAmountMinor:f.number().int().positive().max(1e8),status:f.enum(["created","pending","trialing","paid","cancelled","failed"]),url:f.url().nullable()}),yp=f.discriminatedUnion("type",[qf,f.strictObject({type:f.literal("subscription"),operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),currency:oe,duration:He,renewalAmountMinor:f.number().int().positive().max(1e8),status:f.enum(["pending","running","applied","failed"])})]),xp=f.object({programId:f.uuid(),requestId:f.uuid()}).strict(),Sp=f.object({id:f.uuid(),programId:f.uuid(),code:Lo.shape.code,createdAt:f.iso.datetime({offset:!0})}).strict(),i0=f.object({rows:f.array(zf).max(100),nextCursor:f.uuid().nullable()}).strict(),o0=f.object({rows:f.array(Bf).max(100),nextCursor:f.uuid().nullable()}).strict(),Ff=Lo.extend({id:f.uuid(),redemptions:f.number().int().nonnegative()}).strict(),Nf=f.strictObject({id:f.uuid(),programId:f.uuid().nullable(),customerId:f.uuid().nullable(),referrerId:f.uuid().nullable(),code:f.string().nullable(),status:f.enum(["pending","triggered","applied"]),createdAt:f.iso.datetime({offset:!0})}),a0=f.object({codes:f.array(Ff).max(100),redemptions:f.array(Nf).max(100),customers:f.record(f.uuid(),f.string()),codesCursor:f.uuid().nullable(),redemptionsCursor:f.uuid().nullable()}).strict(),s0=f.discriminatedUnion("action",[f.object({action:f.literal("create"),rewardId:f.uuid(),revision:f.number().int().nonnegative(),input:Lo}).strict(),f.object({action:f.literal("remove"),rewardId:f.uuid(),revision:f.number().int().nonnegative(),codeId:f.uuid()}).strict()]);import{z as c}from"zod";import{z as R}from"zod";var dt={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Xn=e=>new Set(e).size===e.length,Zo=R.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Uf=R.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Yn=R.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),Vf=R.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),vp=R.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var Ip=R.strictObject({id:R.uuid(),repo:Uf,platform:R.enum(["github","gitlab","bitbucket"]),branches:R.array(Yn).min(1).max(4).refine(Xn),workflow:R.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:R.array(R.uuid()).min(1).max(4).refine(Xn),include:R.array(vp).min(1).max(16),exclude:R.array(vp).max(16),methods:R.array(R.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Xn),maxAgeHours:R.number().int().min(1).max(720)}),Op=Ip.extend({revision:R.number().int().positive()}),p0=R.strictObject({repository:Ip,expectedRevision:R.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),jp=R.strictObject({repositoryId:R.uuid(),branch:Yn}),$f=R.array(Zo).max(dt.keys).refine(Xn),Ap=R.strictObject({repository:Op.omit({keyIds:!0}),branch:Yn,keys:$f,keySetHash:R.string().regex(/^[a-f0-9]{64}$/)}),Gf=R.strictObject({filePath:Vf,startingLineNumber:R.number().int().min(1).max(1e7)}),Ho=R.strictObject({protocol:R.literal(1),repositoryId:R.uuid(),branch:Yn,workflow:R.string().max(200),configurationRevision:R.number().int().positive(),keySetHash:R.string().regex(/^[a-f0-9]{64}$/),commit:R.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:R.uuid(),runNumber:R.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:R.number().int().min(1).max(1e4),scannerVersion:R.literal("1"),scannedAt:R.iso.datetime({offset:!0}),coverage:R.strictObject({complete:R.literal(!0),files:R.number().int().min(0).max(dt.files),sourceBytes:R.number().int().min(0).max(dt.sourceBytes),unresolvedCalls:R.number().int().min(0).max(1e6),unsupportedFiles:R.number().int().min(0).max(dt.files)}),features:R.array(R.strictObject({key:Zo,refs:R.array(Gf).max(dt.referencesPerKey)})).max(dt.keys)}).superRefine((e,t)=>{Xn(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>dt.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Jo=R.strictObject({scanId:R.uuid(),commit:R.string(),receivedAt:R.string(),references:R.number().int().nonnegative(),removedReferences:R.number().int().nonnegative()}),Kf=Jo.extend({repositoryId:R.uuid(),branch:Yn,workflow:R.string(),digest:R.string(),configurationRevision:R.number().int().positive(),runNumber:R.number().int().positive(),runAttempt:R.number().int().positive(),scannedAt:R.string(),keySetHash:R.string(),coverage:Ho.shape.coverage}),Lf=R.strictObject({repositories:R.array(Op).max(dt.repositories),scans:R.array(Kf).max(dt.repositories*dt.branches)}),Zf=R.strictObject({key:Zo,references:R.number().int().nonnegative(),coveredTargets:R.number().int().nonnegative(),expiredTargets:R.number().int().nonnegative(),uncertainTargets:R.number().int().nonnegative()}),l0=R.strictObject({available:R.boolean().default(!0),settings:Lf,expectedTargets:R.number().int().min(0).max(80),features:R.array(Zf).max(2001),truncated:R.boolean()});import{z as X}from"zod";var Ge=X.string().min(1).max(200),ai=X.iso.datetime({offset:!0}),er=X.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Wo=X.number().int().min(0).max(1e12),Pp=X.number().int().min(1).max(1e12),wp={...Ve,type:X.literal("coupon.redeemed"),grantId:X.uuid()},_p={...Ve,type:X.literal("usage.observed"),merchantTransactionId:Ge,resource:Ge,unit:Ge,quantity:Pp},Hf=X.strictObject({...Ve,type:X.literal("fulfillment.updated"),operationId:X.uuid(),merchantFulfillmentId:Ge,status:X.enum(["pending","applied","failed"])}),Jf=X.strictObject({...Ve,type:X.literal("benefit.claimed"),merchantBenefitId:Ge,resource:Ge,unit:Ge,quantity:Pp,expiresAt:ai.nullable(),revision:er}),Wf=X.strictObject({...Ve,type:X.literal("benefit.closed"),merchantBenefitId:Ge,status:X.enum(["failed","expired","canceled"]),revision:er}),Qf=X.strictObject({...Ve,type:X.literal("benefit.updated"),merchantBenefitId:Ge,status:X.enum(["active","expired","revoked"]),remainingQuantity:Wo.nullable(),expiresAt:ai.nullable(),revision:er}),Xf=X.strictObject({...Ve,type:X.literal("authorization.updated"),merchantAuthorizationId:Ge,kind:X.literal("auto_topup"),status:X.enum(["pending","effective","revoked","failed"]),termsReference:Ge.nullable(),revision:er}),Yf=X.strictObject({...Ve,type:X.literal("balance.observed"),resource:Ge,unit:Ge,availableQuantity:Wo,reservedQuantity:Wo,periodStartsAt:ai.nullable(),periodEndsAt:ai.nullable(),revision:er}),Cp=X.union([X.discriminatedUnion("type",[...$a,Hf,Jf,Wf,Qf,Xf,Yf]),X.strictObject({...wp,productVersionId:X.uuid(),subscriptionId:X.string().trim().min(1).max(255)}),X.strictObject({...wp,merchandiseId:X.uuid()}),X.strictObject({..._p,operation:X.literal("consume")}),X.strictObject({..._p,operation:X.literal("reverse"),reversalOf:Ge})]),kp=X.strictObject({id:X.uuid(),eventId:X.string().min(1).max(200),source:X.literal("merchant"),providerVerified:X.literal(!1),outcome:X.string().min(1).max(100)});import{z}from"zod";var Rp=bc,eg=Rp.extend({invoice_id:Rp.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Qo=z.strictObject({name:z.string().trim().min(1).max(255),memo:z.string().max(1e4).nullable().optional(),footer:z.string().max(1e4).nullable().optional(),net_terms_days:z.number().int().positive().nullable().optional()}),tg=Qo.extend({id:z.string().min(1).max(255),created_at:z.number().nullable()}),Ep=z.strictObject({items:z.array(tg).max(50),nextCursor:z.uuid().nullable()}),y0=z.discriminatedUnion("action",[z.strictObject({action:z.literal("create"),requestId:z.uuid(),values:Qo}),z.strictObject({action:z.literal("update"),id:z.string().min(1).max(255),values:Qo}),z.strictObject({action:z.literal("delete"),id:z.string().min(1).max(255)})]),Mp=z.discriminatedUnion("action",[z.strictObject({action:z.literal("create"),requestId:z.uuid(),params:pn}),z.strictObject({action:z.enum(["finalize","send","pay","void"]),requestId:z.uuid(),invoiceId:z.uuid()}),z.strictObject({action:z.literal("reissue"),requestId:z.uuid(),invoiceId:z.uuid(),params:eg})]),Xo=z.strictObject({id:z.uuid(),customerId:z.uuid(),providerInvoiceId:z.string().nullable(),status:z.enum(["draft","open","paid","void","uncollectible"]),currency:z.string(),totalMinor:z.string().regex(/^-?\d+$/),paidMinor:z.string().regex(/^\d+$/),refundedMinor:z.string().regex(/^\d+$/),hostedInvoiceUrl:z.url().nullable(),createdAt:z.number(),collectionMethod:z.enum(["send_invoice","charge_automatically"]).nullable()}),Tp=Xo.extend({lines:z.array(z.strictObject({id:z.uuid(),description:z.string(),amountMinor:z.string().regex(/^-?\d+$/),netAmountMinor:z.string().regex(/^-?\d+$/),quantity:z.number().nullable(),periodStart:z.number().nullable(),periodEnd:z.number().nullable()})).max(1e3)}),vn=z.strictObject({taskId:z.uuid(),status:z.enum(["ready","running","done","dead"]),invoice:Xo.nullable(),errorCode:z.string().nullable()}),Dp=z.strictObject({items:z.array(Xo).max(50),nextCursor:z.uuid().nullable(),operations:z.array(vn).max(50),operationsLimited:z.boolean()});var ng=c.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"]),zp={scope:me,permissions:c.array(ng),expiresAt:c.iso.datetime().nullable()},uO=c.discriminatedUnion("kind",[c.object({...zp,kind:c.literal("server"),keyId:c.string().min(1)}),c.object({...zp,kind:c.literal("customer"),customerId:c.string().min(1),identityKind:c.enum(["identified","guest"]),expiresAt:c.iso.datetime()})]),A=c.object({requestId:c.uuid(),scope:me}).strict(),rg=_u.safeExtend({fingerprint:Yr.optional()}).strict(),ig=A.extend({customer:yn,created:c.boolean()});function Bp(){return A.extend({offer:Tn.nullable(),reason:Is.nullable()})}var I={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:ic,response:A.extend({message:c.object({messageId:c.uuid(),channel:Nn,acceptedAt:c.iso.datetime({offset:!0}),status:c.enum(["accepted","sending","completed","canceled"]),replayed:c.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:c.strictObject({messageId:c.uuid()}),response:A.extend({message:c.object({id:c.uuid(),channel:Nn,status:c.enum(["accepted","sending","completed","canceled"]),deliveries:c.array(c.object({id:c.uuid(),status:ac,attempts:c.number().int().nonnegative(),receipts:c.array(c.object({kind:sc,occurredAt:c.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:us,response:A.extend({installation:Ar})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:ps,response:A.extend({installation:Ar})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:jr,response:A.extend({installation:Ar})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:c.strictObject({channel:Nn}),response:A.extend({preference:Ti})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:oc,response:A.extend({preference:Ti})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:c.strictObject({cursor:c.uuid().optional()}),response:A.extend({templates:Ep})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:c.strictObject({customerId:c.uuid(),params:pn}),response:A.extend({preview:Ji})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:c.strictObject({customerId:c.uuid(),requestId:c.uuid(),params:pn}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:A.extend({operation:vn})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:c.strictObject({customerId:c.uuid(),command:Mp}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:A.extend({operation:vn})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:c.strictObject({customerId:c.uuid(),taskId:c.uuid()}),response:A.extend({operation:vn})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:c.strictObject({customerId:c.uuid(),cursor:c.uuid().optional()}),response:A.extend({invoices:Dp})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:c.strictObject({customerId:c.uuid(),invoiceId:c.uuid()}),response:A.extend({invoice:Tp})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:jp,response:A.extend({config:Ap})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Ho,response:A.extend({receipt:Jo})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:c.strictObject({}),response:A.extend({payload:uo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:au,response:A.merge(su)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:cu,response:A.merge(uu)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:c.strictObject({customerId:c.uuid(),sourceId:c.uuid()}),response:A.extend({balance:Ju})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:c.strictObject({customerId:c.uuid(),command:Hu}),response:A.extend({balance:Vo})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:c.strictObject({internal_feature_id:c.uuid(),customerId:c.uuid().optional(),entityId:c.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:A.extend({internal_feature_id:c.uuid(),config:Bi,model_markups:Cr})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:c.strictObject({customerId:c.uuid(),query:Ia}),response:A.extend({usage:fi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:c.strictObject({customerId:c.uuid(),command:Oa}),response:A.extend({usage:fi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:c.strictObject({customerId:c.uuid(),command:Hs}),response:A.extend({grant:$i})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Js,response:A.extend({grants:Ws})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:c.union(Wc.options.map(e=>e.extend({customerId:c.uuid().optional(),customerToken:c.string().regex(pt).optional()}))),response:A.extend({operation:Qc})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Fc.extend({customerId:c.uuid().optional()}),response:A.extend({setup:eo})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Nc.extend({customerId:c.uuid().optional()}),response:A.extend({setup:eo})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:zc.safeExtend({customerId:c.uuid()}),response:A.extend({batch:Vn})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Fr.extend({customerId:c.uuid()}),response:A.extend({batch:Vn})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Fr.extend({customerId:c.uuid()}),response:A.extend({batch:Vn})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Fr.extend({customerId:c.uuid()}),response:A.extend({batch:Vn})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:c.discriminatedUnion("action",[Nr.options[0].extend({customerId:c.uuid()}),Nr.options[1].extend({customerId:c.uuid()}),Nr.options[2].extend({customerId:c.uuid()})]),response:A.extend({trial:Yi})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Bc.extend({customerId:c.uuid()}),response:A.extend({trial:Yi})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:$r,response:A.extend({subscriptions:Zc})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:$r,response:A.extend({purchases:Hc})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Gc,response:A.extend({conflicts:Jc})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Kc,response:A.extend({resolution:Lc})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Vc,response:A.extend({verification:$c})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Pc.safeExtend({...cn,customerId:c.uuid().optional()}),response:A.extend({quote:ln})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Cp,response:A.extend({record:kp})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Nt.extend({customerId:c.uuid().optional(),intent:c.enum(["confirm","cancel"]).optional()}),response:A.extend({operation:mn})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Nt.extend({customerId:c.uuid().optional()}),response:A.extend({operation:mn})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Rc.safeExtend({customerId:c.uuid().optional()}),response:A.extend({quote:Mc})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Nt.extend({customerId:c.uuid().optional(),intent:c.enum(["confirm","cancel"]).optional()}),response:A.extend({operation:Wi})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Nt.extend({customerId:c.uuid().optional()}),response:A.extend({operation:Wi})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Tc.safeExtend({customerId:c.uuid()}),response:A.extend({quote:Qi})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Nt.extend({customerId:c.uuid()}),response:A.extend({operation:qr})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Nt.extend({customerId:c.uuid()}),response:A.extend({operation:qr})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:zs,response:A.extend({controls:Vi})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Cs,response:A.extend({prepared:Rs})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Es,response:A.extend({authorization:Rr})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Us,response:A.extend({coupons:Vs})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Ms,response:A.extend({authorization:Rr})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Fs,response:A.extend({invoices:Ns})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:qs.extend({customerId:c.uuid()}),response:A.extend({operation:vn})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Bs,response:A.extend({invoice:Bn})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:c.object({customerId:c.uuid(),command:Ds}).strict(),response:A.extend({controls:Vi})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:c.object({customerId:c.uuid(),command:Wu}).strict(),response:A.extend({entity:Qu})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:c.strictObject({customerId:c.uuid().nullable(),query:rp}),response:A.extend({analytics:ip})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:c.object({customerId:c.uuid().nullable(),query:Ht}).strict(),response:A.extend({analytics:tp})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:op,response:A.extend({batchId:c.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:ap,response:A.extend({batch:sp})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Ca.extend({customerId:c.string().min(1).optional()}),response:A.extend({check:Pn})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:c.strictObject({kind:Ot,selector:c.discriminatedUnion("type",[c.strictObject({type:c.literal("resource"),id:c.uuid()}),c.strictObject({type:c.literal("version"),id:c.uuid()})]),customerId:c.string().min(1).optional()}),response:A.extend({content:Ri})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Lu,response:A.extend({paywall:Qn})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:c.strictObject({processContext:Tr.optional(),...cn,selector:tu,customerId:c.string().min(1).optional(),commerce:ur,requirement:Qt.optional()}),response:A.extend({offering:nu,candidates:c.array(ka).max(20),availability:c.array(c.strictObject({productVersionId:c.uuid(),available:c.boolean(),reason:c.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:Pn.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:c.object({customerId:c.uuid().optional(),entityId:c.uuid().optional()}).strict(),response:A.extend({holdings:ja})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:c.object({customerId:c.uuid().optional(),query:Aa}).strict(),response:A.extend({ledger:wa})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Qs.extend({customerId:c.uuid().optional()}),response:A.extend({detail:Xs})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Gi.safeExtend({customerId:c.uuid().optional()}),response:A.extend({statement:Ys})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:c.object({customerId:c.uuid().optional(),command:wn.options[0]}).strict(),response:A.extend({quote:va})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:c.strictObject({customerId:c.uuid(),command:c.union([c.strictObject({eventName:c.string().min(1),quantity:ye.optional(),properties:ft.optional(),entityId:c.uuid().optional(),idempotencyKey:c.string().min(1).max(120)}),c.strictObject({internal_feature_id:c.uuid(),quantity:ye.optional(),properties:ft.optional(),entityId:c.uuid().optional(),idempotencyKey:c.string().min(1).max(120)})])}),response:A.extend({receipts:c.array(_n).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:c.object({customerId:c.uuid(),command:wn.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:A.extend({receipt:_n})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:hp,response:A.extend({redemption:gp})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:xp,response:A.extend({referralCode:Sp})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:bp,response:A.extend({checkout:yp})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:tc,response:A.extend({seats:Zi})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:nc,response:A.extend({seats:Zi})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:rg,response:ig},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:wo,response:A.extend({customer:yn})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:ku,response:A.extend(Ru.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Cu,response:A.extend(Pu.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:c.object({customerId:c.uuid()}).strict(),response:A.extend(en.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:c.strictObject({}),response:A.extend(en.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:c.strictObject({customerId:c.uuid(),sessionId:c.uuid().optional()}),response:A.extend({revoked:c.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:c.strictObject({guestToken:c.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Yr.optional()}),response:A.extend({customerId:c.uuid(),guestToken:c.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:c.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:c.strictObject({guestToken:c.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:A.extend(en.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:c.strictObject({guestToken:c.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:c.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:c.uuid()}),response:A.extend({customer:yn,switched:c.boolean(),replayed:c.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:c.strictObject({code:c.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:c.uuid()}),response:Bp()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:c.object({}).strict(),response:A.extend({offers:c.array(Tn)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:c.object({customerId:c.string().min(1).max(255).optional(),couponId:c.uuid(),...cn,requestId:c.uuid(),couponContentDigest:c.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Bp()}},pO={recordMerchantEvent:I.recordMerchantEvent,sendMessage:I.sendMessage,readMessage:I.readMessage,bindPushInstallation:I.bindPushInstallation,readPushInstallation:I.readPushInstallation,updatePushAddress:I.updatePushAddress,readMessagingPreference:I.readMessagingPreference,setMessagingPreference:I.setMessagingPreference,listInvoiceTemplates:I.listInvoiceTemplates,previewInvoice:I.previewInvoice,createInvoice:I.createInvoice,manageInvoice:I.manageInvoice,readInvoiceOperation:I.readInvoiceOperation,listInvoices:I.listInvoices,getInvoice:I.getInvoice,getCodeReferenceConfig:I.getCodeReferenceConfig,submitCodeReferences:I.submitCodeReferences,getFeatures:I.getFeatures,evaluateFeatures:I.evaluateFeatures,trackEvents:I.trackEvents,setupPayment:I.setupPayment,readPaymentSetup:I.readPaymentSetup,previewSubscriptionBatch:I.previewSubscriptionBatch,confirmSubscriptionBatch:I.confirmSubscriptionBatch,readSubscriptionBatch:I.readSubscriptionBatch,abandonSubscriptionBatch:I.abandonSubscriptionBatch,manageSubscriptionTrial:I.manageSubscriptionTrial,readSubscriptionTrial:I.readSubscriptionTrial,listSubscriptions:I.listSubscriptions,listPurchases:I.listPurchases,listSubscriptionConflicts:I.listSubscriptionConflicts,retrySubscriptionConflict:I.retrySubscriptionConflict,readAiPricing:I.readAiPricing,readUsage:I.readUsage,setUsage:I.setUsage,previewRefund:I.previewRefund,refund:I.refund,readRefund:I.readRefund,previewUpdate:I.previewUpdate,update:I.update,readSubscriptionUpdate:I.readSubscriptionUpdate,restoreNativePurchase:I.restoreNativePurchase,verifySubscriptions:I.verifySubscriptions,previewAttach:I.previewAttach,attach:I.attach,readSubscriptionOperation:I.readSubscriptionOperation,manageBalanceGrant:I.manageBalanceGrant,readBalanceSource:I.readBalanceSource,adjustBalance:I.adjustBalance,listBalanceGrants:I.listBalanceGrants,readBillingControls:I.readBillingControls,prepareBillingAuthorization:I.prepareBillingAuthorization,confirmBillingAuthorization:I.confirmBillingAuthorization,setBillingCoupons:I.setBillingCoupons,revokeBillingAuthorization:I.revokeBillingAuthorization,listBillingInvoices:I.listBillingInvoices,confirmBillingAdjustment:I.confirmBillingAdjustment,prepareBillingAdjustment:I.prepareBillingAdjustment,manageBillingLimits:I.manageBillingLimits,createCustomer:I.createCustomer,getCustomer:I.getCustomer,listCustomers:I.listCustomers,updateCustomer:I.updateCustomer,createSession:I.createSession,refreshSession:I.refreshSession,revokeSessions:I.revokeSessions,createGuestCustomer:I.createGuestCustomer,resumeGuestSession:I.resumeGuestSession,claimGuestCustomer:I.claimGuestCustomer,checkEntitlement:I.checkEntitlement,resolveOffering:I.resolveOffering,resolveContent:I.resolveContent,resolvePaywall:I.resolvePaywall,readHoldings:I.readHoldings,readLedger:I.readLedger,readBillingInvoice:I.readBillingInvoice,readCreditStatement:I.readCreditStatement,quoteBalance:I.quoteBalance,trackUsage:I.trackUsage,mutateBalance:I.mutateBalance,manageUsageEntity:I.manageUsageEntity,readUsageAnalytics:I.readUsageAnalytics,readCreditAnalytics:I.readCreditAnalytics,submitUsageBatch:I.submitUsageBatch,readUsageBatch:I.readUsageBatch,listOffers:I.listOffers,grantOffer:I.grantOffer,redeemCoupon:I.redeemCoupon,redeemReward:I.redeemReward,createReferralCode:I.createReferralCode,claimRewardProduct:I.claimRewardProduct,readSeats:I.readSeats,manageSeat:I.manageSeat};import{z as Yo}from"zod";var tr=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function ea(e,t,n){let r={},o,a,l,p="next",d;switch(e.type){case"entry":d=e.next;break;case"condition":{let v=e.cases.findIndex(h=>di(t.attributes??{},h.condition,t.savedGroups??{}));p=v<0?"default":`case:${v}`,d=v<0?e.default:e.cases[v].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new tr("Required GB Feature is unavailable");o=An(e.featureKey,t),l=o.value,Object.assign(r,Dt(e,{value:l})),d=e.next;break;case"split":{let v=n[e.experimentId];if(!v)throw new tr("Required GB Experiment is unavailable");if(a=ba(v,t),l=a.value,p=a.inExperiment&&!a.passthrough&&typeof l=="string"?l:"notParticipating",d=p==="notParticipating"?e.notParticipating:e.routes[p],!d)throw new tr("Experiment Variation has no published route");break}case"offering":{let v=e.configuration.source==="fixed"?e.configuration.versionId:An(e.configuration.featureKey,t).value;l={type:"offering_version",id:Yo.uuid().parse(v)},Object.assign(r,Dt(e,{value:l})),d=e.next;break}case"coupon":case"coupons":l=e.type==="coupons"?e.couponIds.map(v=>({type:"reward",id:v})):{type:"reward",id:e.couponId},Object.assign(r,Dt(e,{value:l})),d=e.next;break}return{port:p,target:d,projections:r,...l===void 0?{}:{value:l},...o?{feature:o}:{},...a?{experiment:a}:{}}}function yO(e,t,n){Yo.uuid().parse(e),Yo.number().int().nonnegative().parse(t);let r=ar(sr(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as _}from"zod";var Rt=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),og=_.enum(["running","waiting","completed","closed","ineligible","failed"]),ta=_.discriminatedUnion("type",[jo,_.strictObject({type:_.literal("wait"),receiptId:_.uuid(),kind:_.enum(["timer","event","operation"]),deadline:_.iso.datetime({offset:!0}).nullable(),eventName:Rt.optional()}),_.strictObject({type:_.literal("open_url"),receiptId:_.uuid(),url:Po,openIn:Co}),_.strictObject({type:_.literal("event"),receiptId:_.uuid(),event:Rt})]),ag=_.strictObject({type:_.literal("funnel"),id:_.uuid(),versionId:_.uuid()}),sg={id:Rt,presentation:gt,outputs:_.array(Rt).max(250),inputs:bi,values:_.record(_.string(),te).optional(),offeringKey:we.optional(),capabilities:Xt,customerData:za,dataCursors:_.record(Rt,lr.nullable())},cg=_.strictObject({...sg,content:_.strictObject({type:_.literal("document"),document:Le})}),nr=_.strictObject({id:_.uuid(),source:ag,revision:_.number().int().nonnegative(),visit:_.number().int().nonnegative(),nodeId:Rt,nodeType:_.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:og,stopped:_.boolean(),canBack:_.boolean(),authenticated:_.boolean(),locale:_.string().min(1).max(35),answers:Et,parameters:ut,variables:_.record(_.string(),te),output:te.nullable(),screen:cg.nullable(),paywall:_.strictObject({receiptId:_.uuid(),resolution:_.union([Wn,Qn]),quote:ln.nullable(),operation:mn.nullable(),purchaseRequestId:_.uuid().nullable(),selectionGeneration:_.number().int().nonnegative().optional(),canReselect:_.boolean().optional()}).nullable(),instruction:ta.nullable(),pendingRequest:_.strictObject({requestId:_.uuid(),authenticationRequired:_.boolean()}).nullable(),runExpiresAt:_.iso.datetime({offset:!0}),credentialExpiresAt:_.iso.datetime({offset:!0}).nullable()}),In=_.strictObject({scope:me,run:nr,settlement:_.strictObject({requestId:_.uuid(),state:_.enum(["pending","unknown","settled"]),operationId:_.uuid().nullable(),receiptId:_.uuid().nullable().optional()}).optional(),purchase:_.strictObject({receiptId:_.uuid(),quote:ln.nullable(),operation:mn.nullable(),canReselect:_.boolean().optional()}).optional(),review:_.strictObject({activeOperationId:_.uuid().nullable(),pages:_.array(_.strictObject({receiptId:_.uuid(),nodeId:Rt,visit:_.number().int().nonnegative()})).max(100),page:_.strictObject({receiptId:_.uuid(),nodeId:Rt,visit:_.number().int().nonnegative(),document:Le,answers:Et,inputs:bi,values:_.record(_.string(),te).optional()}).nullable(),coupons:_.array(_.strictObject({grantId:_.uuid(),status:_.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:_.string().nullable()})).max(100),purchases:_.array(_.strictObject({receiptId:_.uuid(),operationId:_.uuid(),status:_.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:_.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:_.uuid().optional()}),qp=In.extend({run:nr.extend({paywall:nr.shape.paywall.unwrap().extend({resolution:Qn}).nullable()})});var TO="X-Indiana-Server-Key";import{z as q}from"zod";import{z as G}from"zod";import{z as Pe}from"zod";var ug=Pe.strictObject({selector:Pe.string().min(1).max(2048),action:Pe.enum(["set","append","remove"]),attribute:Pe.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:Pe.string().max(5e4).optional(),parentSelector:Pe.string().max(2048).optional(),insertBeforeSelector:Pe.string().max(2048).optional()}),pg=Pe.strictObject({variation:Pe.string().min(1).max(128),description:Pe.string().max(2e3).default(""),css:Pe.string().max(1e5).default(""),js:Pe.string().max(1e5).default(""),domMutations:Pe.array(ug).max(200).default([]),iam:gu.optional(),renderGuard:Lr.optional()}),na=pg.omit({variation:!0,description:!0,iam:!0}),lg=hn.omit({variations:!0,active:!0}).extend({changeId:Pe.string().regex(/^[a-f0-9]{64}$/),variations:Pe.tuple([na,na]).rest(na).refine(e=>e.length<=20)}),Fp=Pe.strictObject({trackExposures:Pe.boolean(),environmentId:Pe.uuid(),generation:Pe.string().regex(/^[a-f0-9]{64}$/),experiments:Pe.array(lg).max(100),savedGroups:Gn});var rr=G.string().regex(/^[a-f0-9]{64}$/),LO=G.strictObject({iam:rr,executionContracts:G.union([G.tuple([G.literal("funnel-run/1")]),G.tuple([G.literal("funnel-process/1")])]).default(["funnel-run/1"])}),mg=G.strictObject({release:rr,render:Lr,button:G.strictObject({selector:G.string().min(1).max(512),elementKey:G.string().min(1).max(256),tag:G.enum(["button","a","input"])}).nullable()}),ZO=G.strictObject({scope:me.extend({environmentId:G.uuid()}),release:rr,validatedAt:G.iso.datetime({offset:!0}),validUntil:G.iso.datetime({offset:!0}),entries:G.array(G.strictObject({id:G.uuid(),funnelId:G.uuid(),versionId:G.uuid(),event:G.enum(["screen_enter","button_click"]),target:mg})).max(4e3)}),Np=G.strictObject({operation:G.literal("entry_start"),funnelId:G.uuid(),versionId:G.uuid(),entryId:G.uuid(),release:rr,requestId:G.uuid(),locale:G.string().min(1).max(35).default("en")}),Up=G.strictObject({scope:me,suppressed:G.literal(!0),reason:G.enum(["frequency","in_progress"]),retryAt:G.iso.datetime({offset:!0}).nullable()}),HO=G.strictObject({experimentId:G.uuid(),splitNodeId:G.string().min(1).max(128)}),dg=G.strictObject({experimentId:G.uuid(),experimentKey:G.string().min(1).max(128),variationKey:G.string().min(1).max(128),inExperiment:G.boolean(),generation:G.string().min(1).max(256)}),Vp=G.strictObject({operation:G.literal("page_experiments"),release:rr,usedReceiptIds:G.array(G.uuid()).max(20).default([]),customerToken:G.string().regex(pt).optional()}),JO=G.strictObject({scope:me,runId:G.uuid(),assignments:G.array(dg.extend({receiptId:G.uuid()})).max(100),payload:Fp});var ct=q.literal(lo),fg=q.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),ra=q.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),$p=q.discriminatedUnion("type",[q.strictObject({type:q.literal("guest"),guestToken:ra}),q.strictObject({type:q.literal("customer"),customer:xt,customerData:Pt.optional()})]),ia=q.strictObject({id:q.uuid(),runId:q.uuid(),customerId:q.uuid(),requestId:q.uuid(),acceptedAt:q.iso.datetime({offset:!0})}),gg=q.strictObject({participantId:q.uuid(),startedAs:q.enum(["guest","identified"]),binding:ia.omit({runId:!0,requestId:!0}).nullable()}),hg=q.union([ta,q.strictObject({type:q.literal("authentication_required"),reason:q.enum(["customer_required","customer_experiment_required"]),nodeId:q.string().min(1).max(64),visit:q.number().int().nonnegative()})]),bg=nr.omit({authenticated:!0}).extend({identity:gg,instruction:hg.nullable()}),yg=q.discriminatedUnion("operation",[tt.options[2].omit({customerToken:!0}),tt.options[3].omit({customerToken:!0}),tt.options[4].omit({customerToken:!0}),tt.options[5].omit({customerToken:!0}),tt.options[6].omit({customerToken:!0}),tt.options[7].omit({customerToken:!0})]),si={contract:ct,customerToken:q.string().regex(pt)},Gp={contract:ct,requestId:q.uuid(),runToken:fg,externalUserId:xt.options[1].shape.value},Kp=q.discriminatedUnion("operation",[q.strictObject({contract:ct,operation:q.literal("describe")}),q.strictObject({contract:ct,operation:q.literal("start"),source:$p,funnelId:tt.options[0].shape.funnelId,requestId:q.uuid(),locale:tt.options[0].shape.locale,parameters:tt.options[0].shape.parameters}),Np.omit({operation:!0}).extend({contract:ct,operation:q.literal("entry_start"),source:$p}),q.strictObject({...Gp,operation:q.literal("bind_customer"),guestToken:ra,claimRequestId:q.uuid(),expectedBindingId:q.null()}),q.strictObject({...Gp,operation:q.literal("binding_status"),guestToken:ra.optional()}),tt.options[1].omit({operation:!0,customerToken:!0}).extend({...si,operation:q.literal("get"),settlementBindingId:q.uuid().nullable().optional()}),tt.options[8].omit({operation:!0,customerToken:!0}).extend({...si,operation:q.literal("review")}),Vp.omit({customerToken:!0}).extend(si),q.strictObject({...si,operation:q.literal("command"),identity:q.strictObject({bindingId:q.uuid().nullable()}),command:yg})]),xg=In.omit({run:!0}).extend({contract:ct,run:bg,settlement:In.shape.settlement.unwrap().extend({accepted:q.boolean().nullable().optional()}).optional()}),oj=Up.extend({contract:ct}),aj=q.discriminatedUnion("operation",[Kp.options[1].omit({contract:!0,source:!0,requestId:!0}),Kp.options[2].omit({contract:!0,source:!0,requestId:!0})]),sj=xg.extend({binding:ia,outcome:q.enum(["bound","already_bound"]),replayed:q.boolean()}),cj=q.discriminatedUnion("state",[q.strictObject({contract:ct,scope:me,state:q.literal("not_accepted")}),q.strictObject({contract:ct,scope:me,state:q.literal("conflict")}),q.strictObject({contract:ct,scope:me,state:q.literal("bound"),binding:ia})]),uj=q.strictObject({contract:ct,scope:me,keyId:q.uuid(),operations:q.array(q.string()).max(20)});import{z as $e}from"zod";import{z as ci}from"zod";var fj=ci.strictObject({operation:ci.literal("renew_run"),runId:ci.uuid(),customerId:ci.uuid()}),Lp=In.refine(e=>!!e.runToken,"Renewal returns a credential"),Zp=qp.refine(e=>!!e.runToken,"Renewal returns a credential");var Ij=$e.discriminatedUnion("operation",[$e.strictObject({operation:$e.literal("campaign_decide"),..._o}).refine(Vt,$t),$e.strictObject({operation:$e.literal("campaign_start"),funnelId:$e.uuid(),requestId:$e.uuid(),customer:xt,customerData:Pt.optional(),locale:$e.string().min(1).max(35),parameters:ut,cooldownSeconds:$e.number().int().min(1).max(2592e3)}).refine(Vt,$t)]),Sg=$e.union([$e.strictObject({scope:me,suppressed:$e.literal(!0),reason:$e.enum(["frequency","in_progress"]),retryAt:$e.iso.datetime({offset:!0})}),Lp]),Oj=$e.union([Sg.options[0],Zp]);import{z as ie}from"zod";var On=ie.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Jp=ie.strictObject({entry:On,nodes:ie.array(ie.strictObject({id:On,type:ie.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:ie.record(ie.string(),On),writes:ie.record(we,we),resources:ie.strictObject({screenId:On.optional(),paywallVersionId:ie.uuid().optional(),couponId:ie.uuid().optional(),couponIds:ie.array(ie.uuid()).max(20).optional(),experimentId:ie.uuid().optional(),featureKey:ie.string().optional(),offeringVersionId:ie.uuid().optional()})})).min(1).max(500)}),Hp={scope:me,funnelId:ie.uuid(),versionId:ie.uuid(),evaluationRevision:ie.number().int().nonnegative(),expiresAt:ie.iso.datetime({offset:!0}).nullable(),topology:Jp},jn=ie.discriminatedUnion("evaluationMode",[ie.strictObject({...Hp,evaluationMode:ie.literal("local"),growth:_t,conditions:ie.record(On,ie.array(ie.strictObject({condition:it,port:ie.string()})))}),ie.strictObject({...Hp,evaluationMode:ie.literal("remote")})]),vg=jn.options[0].extend({evaluation:ie.strictObject({maxTransitions:ie.number().int().min(1).max(1e4),variables:ie.record(we,rn),outputSchema:nn,terminals:ie.record(On,ie.strictObject({outcome:ie.enum(["completed","closed","ineligible","failed"]),output:Ln.nullable()}))})});function Ig(e){return Jp.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(l=>l.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,l)=>{n[`case:${l}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=ie.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function Og(e){let t=Ct.parse(e.document),n=e.evaluationMode==="local"?_t.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:Ig(t)};return jn.parse(e.evaluationMode==="remote"?r:{...r,growth:ii(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((a,l)=>({condition:a.condition,port:`case:${l}`}))]))})}function Mj(e){let t=Og(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ct.parse(e.document);return vg.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}import{z as nt}from"zod";import{z as Be}from"zod";var Wp=Be.discriminatedUnion("provider",[Be.strictObject({provider:Be.literal("apple"),orderId:Be.uuid(),receiptId:Be.uuid(),signedTransaction:Be.string().min(1).max(131072)}),Be.strictObject({provider:Be.literal("google"),orderId:Be.uuid(),receiptId:Be.uuid(),purchaseToken:Be.string().min(1).max(16384)})]),Qp=Be.strictObject({orderId:Be.uuid(),receiptId:Be.uuid(),transactionIds:Be.array(Be.string().min(1).max(255)).min(1).max(50),membership:Be.boolean()});var Uj=nt.strictObject({operation:nt.literal("native_receipt"),requestId:nt.uuid(),customerToken:nt.string().regex(pt),orderId:nt.uuid(),receiptId:nt.uuid(),nativeEvidence:Wp.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),Vj=nt.strictObject({scope:me,requestId:nt.uuid(),orderId:nt.uuid(),receiptId:nt.uuid(),orderStatus:nt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:nt.boolean(),nativeCompletion:Qp.optional()});import{z as be}from"zod";var Xp=be.string().regex(/^[a-f0-9]{64}$/),jg=hn.omit({variations:!0,active:!0}).extend({changeId:Xp,variations:be.array(be.strictObject({urlRedirect:be.string().max(2048)})).min(2).max(20)}),Lj=be.strictObject({environmentId:be.uuid(),trackExposures:be.boolean(),generation:Xp,experiments:be.array(jg).max(100),savedGroups:Gn}),Ag=be.strictObject({eventUuid:be.uuid(),timestamp:be.iso.datetime({offset:!0}).optional(),deviceId:be.string().min(1).max(128),sessionId:be.string().min(1).max(128).optional(),url:be.url().max(2048),pageTitle:be.string().max(512).optional(),experimentKey:be.string().min(1).max(255),variationKey:be.string().min(1).max(64)}),Zj=be.strictObject({events:be.array(Ag).min(1).max(20)}),Hj=be.strictObject({inserted:be.number().int().nonnegative(),duplicates:be.number().int().nonnegative(),skipped:be.number().int().nonnegative(),rejected:be.array(be.strictObject({index:be.number().int().nonnegative(),reason:be.string()}))});import{z as ve}from"zod";var aa=32,wg=522240;function sa(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var _g=ve.strictObject({nodeId:ve.string().min(1).max(64),visit:ve.number().int().nonnegative(),revision:ve.number().int().nonnegative()}),oa=ve.record(ve.string(),te),Pg=ve.strictObject({id:ve.uuid(),nodeId:ve.string().min(1).max(64),visit:ve.number().int().nonnegative(),input:ve.strictObject({schemaVersion:Zn.shape.schemaVersion,kind:Zn.shape.kind,selector:Zn.shape.selector,contract:Zn.shape.contract}),context:oa,removed:ve.array(ve.string()).max(100),attributes:oa,removedAttributes:ve.array(ve.string()).max(100),result:qu,offeringVersionId:ve.uuid().nullable(),events:ve.strictObject({entered:ve.string().regex(/^[1-9][0-9]{0,18}$/),decision:ve.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),eA=ve.strictObject({schemaVersion:ve.literal(1),mode:ve.enum(["local","remote"]),versionId:ve.uuid(),generation:ve.number().int().positive(),base:_g,context:oa,steps:ve.array(Pg).min(1).max(aa)}).refine(e=>Ze(e)<=wg,"Segment exceeds its byte budget");var Cg=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function ir(e){return Array.isArray(e)?e.some(ir):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&ir(n):!Cg.test(t))}function Yp(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(p=>p.id===t.screenId&&p.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(p=>ir(p.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(p=>p.id===t.screenId):null]);for(let[p,d]of Object.entries(e.variables))if(d.source.type==="attribute"&&d.source.key!=="funnelParticipantId"&&(a.includes(`variables.${p}`)||a.includes(JSON.stringify(p))))return"customer_required";if(t.type==="split"){let p=n.experiments?.[t.experimentId];if((p?.hashAttribute??"id")!=="funnelParticipantId"||ir(p?.condition)||p?.parentConditions?.length)return"customer_experiment_required"}let l=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return l&&n.features?.[l]?.rules?.some(p=>(p.hashAttribute??"id")!=="funnelParticipantId"||ir(p.condition)||p.parentConditions?.length)?"customer_experiment_required":null}var ca=class extends Error{constructor(n,r){super(r);this.code=n;this.name="FunnelLocalCalculationError"}code},ui=(e,t)=>new ca(e,t),kg=e=>({experiments:e.experiments,features:e.features});function Rg(e,t=ui){let n=new Map(e.topology.nodes.map(l=>[l.id,l])),r=ha(e.growth.savedGroups),o=kg(e.growth);function a(l,p){if(!Object.hasOwn(e.growth.features,l))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return An(l,p).value}return{nodes:n,savedGroups:r,features:o.features,feature:a,evaluate(l,p){let d=n.get(l);if(!d)throw t("NOT_FOUND","Funnel node is unavailable");let v,h;if(d.type==="condition"){let $=e.conditions[d.id];if(!$)throw t("INVALID_RESPONSE","Local condition rules are unavailable");v=ea({id:d.id,name:d.id,type:"condition",cases:$.map(C=>({condition:C.condition,target:d.outputs[C.port]})),default:d.outputs.default},p,o.experiments).port}else if(d.type==="feature"){if(!d.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");h=a(d.resources.featureKey,p),v="next"}else if(d.type==="split"){if(!(d.resources.experimentId?e.growth.experiments[d.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let C=ea({id:d.id,name:d.id,type:"split",experimentId:d.resources.experimentId,routes:d.outputs,notParticipating:d.outputs.notParticipating},p,o.experiments);h=C.value,v=C.port}else if(["offering","end","output"].includes(d.type)&&d.resources.featureKey)h=a(d.resources.featureKey,p),v=d.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let T=d.outputs[v]??(v==="value"?d.id:void 0);if(!T)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:l,port:v,target:T,...h===void 0?{}:{value:h}}}}}function dA(e,t,n,r=ui){return ua(e,r)(t,n)}function ua(e,t){let n=jn.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let a=Rg(n,t);return(l,p)=>(o(),Eg(a,l,p))}function Eg(e,t,n){let r=Ke.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:a,onExperimentViewed:l}=n,p={attributes:r,...o?{saveStickyBucketAssignmentDoc:d=>o(structuredClone(d))}:{},...a?{onFeatureUsage:(d,v)=>a(d,structuredClone(v))}:{},...l?{onExperimentViewed:(d,v)=>l(structuredClone(d),structuredClone(v))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,p)}function fA(e,t,n,r=ui){return el(ua(e,r),t,n)}function el(e,t,n){let r=[],o=[],a=[],l=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(p){let d=r.findIndex(T=>T.next.attributeName===p.attributeName&&T.next.attributeValue===p.attributeValue),v=p.attributeName+"||"+p.attributeValue,h={expected:n.sticky[v]??null,next:p};d<0?r.push(h):r[d]=h},onExperimentViewed(p,d){d.inExperiment&&d.hashUsed&&!d.passthrough&&o.push(te.parse({key:p.key,variationId:d.variationId,keyUsed:d.key,hashAttribute:d.hashAttribute,hashValue:d.hashValue}))},onFeatureUsage(p,d){a.push(te.parse({feature:p,value:d.value,source:d.source,...d.ruleId?{ruleId:d.ruleId}:{}}))}});return{port:l.port,...l.value===void 0?{}:{value:l.value},sticky:r,exposures:o,features:a}}function gA(e,t,n,r=ui){let o=n,a=new Map(t.graph.nodes.map(Z=>[Z.id,Z])),l=structuredClone(n.variables),p=structuredClone(o.sticky),d=[],v=n.nodeId,h=n.visit,T=!1,$,C=Z=>Yp(t,Z,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),u=Z=>($??=ua(e,r),el($,Z,{attributes:So({declarations:t.variables,attributes:o.attributes,parameters:n.parameters,answers:n.answers,results:l,savedGroups:{}}),sticky:p}));for(let Z=0;Z<aa;Z++){let E=a.get(v);if(!E||!sa(E)||C(E))break;if(h>=t.execution.maxTransitions&&(h>t.execution.maxTransitions||E.type!=="end"&&E.type!=="output")){if(!d.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let ae,Ce;if(["condition","feature","split"].includes(E.type)||E.type==="offering"&&E.configuration.source==="feature")ae=u(E.id),E.type==="offering"&&(ae.value={type:"offering_version",id:String(ae.value)}),E.type==="condition"?Ce=ae.port==="default"?E.default:E.cases[Number(ae.port.slice(5))]?.target:E.type==="split"?Ce=ae.port==="notParticipating"?E.notParticipating:E.routes[ae.port]:(E.type==="feature"||E.type==="offering")&&(Ce=E.next);else if(ae={port:"next",sticky:[],exposures:[],features:[]},(E.type==="entry"||E.type==="coupon"||E.type==="coupons")&&(Ce=E.next),E.type==="offering"&&E.configuration.source==="fixed"&&(ae.value={type:"offering_version",id:E.configuration.versionId},Ce=E.next),E.type==="end"||E.type==="output"){let ee=E.type==="end"?E.output:E.value;if(ae=ee?.type==="feature"?u(E.id):{...ae,port:"value",value:ee?.type==="literal"?ee.value:ee?.type==="variable"?Pi({source:"variable",key:ee.key,...ee.path?{path:ee.path}:{}},{declarations:t.variables,answers:n.answers,results:l,parameters:n.parameters,attributes:o.attributes,savedGroups:{}}):null},ee&&(ae.value===void 0||!Xe(t.outputSchema,ae.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let L=[...d,{nodeId:v,result:ae}];if(Ze({steps:L})>6e4){if(!d.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(d.push({nodeId:v,result:ae}),E.type==="feature"||E.type==="offering"||E.type==="coupon"||E.type==="coupons"){let ee=E.type==="coupons"?E.couponIds.map(H=>({type:"reward",id:H})):E.type==="coupon"?{type:"reward",id:E.couponId}:ae.value;if(ee===void 0)throw r("INVALID_RESPONSE","Node output is missing");let le=Dt(E,{value:ee});_i(t.variables,E,le),Object.assign(l,le)}for(let ee of ae.sticky)p[`${ee.next.attributeName}||${ee.next.attributeValue}`]=structuredClone(ee.next);if(E.type==="end"||E.type==="output"){T=!0;break}if(!Ce)throw r("INVALID_RESPONSE","Local pure exit is unavailable");v=Ce,h++}let b=a.get(v);return{steps:d,...!T&&b&&(!sa(b)||C(b))?{boundary:{nodeId:v,visit:h}}:{}}}import{z as Mg}from"zod";var SA=Mg.strictObject({document:Ct,configuration:jn.options[0]});var B_={name:"@tinkerlandai/longplay-sdk",version:"0.10.18",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var q_="https://api.longplayai.com";export{me as a,zh as b,Bh as c,qh as d,Fh as e,Ar as f,Uh as g,$h as h,Gh as i,Kh as j,Bg as k,qg as l,Ua as m,pt as n,en as o,tn as p,Ka as q,Kg as r,Lg as s,dl as t,Ja as u,Jg as v,gl as w,hl as x,bl as y,hr as z,yr as A,Ii as B,Sl as C,Wg as D,vl as E,Qg as F,Xg as G,Xa as H,th as I,nh as J,Ol as K,jl as L,ah as M,Xe as N,_i as O,Pi as P,Ri as Q,Rh as R,hx as S,_t as T,uo as U,Fd as V,su as W,lo as X,So as Y,pS as Z,lS as _,mS as $,kS as aa,RS as ba,ES as ca,tt as da,$u as ea,jf as fa,Af as ga,bI as ha,Fo as ia,_f as ja,yI as ka,xI as la,SI as ma,Qn as na,EI as oa,Yu as pa,Xu as qa,$o as ra,Pf as sa,UI as ta,I as ua,yO as va,ag as wa,In as xa,qp as ya,TO as za,mg as Aa,ZO as Ba,Np as Ca,Up as Da,Vp as Ea,JO as Fa,Kp as Ga,xg as Ha,oj as Ia,aj as Ja,sj as Ka,cj as La,uj as Ma,fj as Na,Lp as Oa,Ij as Pa,Oj as Qa,jn as Ra,vg as Sa,Og as Ta,Mj as Ua,Uj as Va,Vj as Wa,Lj as Xa,Rg as Ya,dA as Za,fA as _a,gA as $a,SA as ab,B_ as bb,q_ as cb};
|