@tinkerlandai/longplay-sdk 0.10.30 → 0.10.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/{ai-usage-E4c9NSJK.d.ts → ai-usage-T62xehqa.d.ts} +1 -1
  3. package/dist/{api-BpeJkr6U.d.ts → api-Do-6AyWa.d.ts} +24 -0
  4. package/dist/{chunk-JWPTJLAN.js → chunk-4XC34JBS.js} +1 -1
  5. package/dist/{chunk-BQLT2LDP.js → chunk-5HJYR6Z4.js} +1 -1
  6. package/dist/chunk-5UFRIIGC.js +1 -0
  7. package/dist/{chunk-TF2OFTYS.js → chunk-6KBCR7JJ.js} +1 -1
  8. package/dist/{chunk-JNSU2AP2.js → chunk-7MNJH5GB.js} +1 -1
  9. package/dist/{chunk-6BTJNSQQ.js → chunk-7QL4GF4C.js} +1 -1
  10. package/dist/{chunk-ACFQLHJR.js → chunk-BXPXJARS.js} +1 -1
  11. package/dist/{chunk-OHOROFWN.js → chunk-CZ2RY6RG.js} +1 -1
  12. package/dist/{chunk-B3KFE57L.js → chunk-EHDHWYVJ.js} +1 -1
  13. package/dist/{chunk-3TXBNPEP.js → chunk-EMVWUEW4.js} +1 -1
  14. package/dist/{chunk-U3QUHGQX.js → chunk-EMYZUBWL.js} +1 -1
  15. package/dist/{chunk-YXCEZAQL.js → chunk-EQPEUPMG.js} +1 -1
  16. package/dist/{chunk-XHQBABH6.js → chunk-EUVLXS2V.js} +1 -1
  17. package/dist/{chunk-23WNEOK4.js → chunk-FYQXSGRT.js} +1 -1
  18. package/dist/{chunk-U6ULFK7M.js → chunk-GLQXJMKL.js} +1 -1
  19. package/dist/{chunk-5N7QFF5M.js → chunk-HQITRRHF.js} +1 -1
  20. package/dist/{chunk-UWYL2QCF.js → chunk-HQPP76BS.js} +1 -1
  21. package/dist/{chunk-EZ5RCVVY.js → chunk-ILEDKSRQ.js} +1 -1
  22. package/dist/{chunk-DIMBCG2C.js → chunk-KHM6IHPJ.js} +1 -1
  23. package/dist/{chunk-FJGJQGYF.js → chunk-MIBRUDIS.js} +1 -1
  24. package/dist/{chunk-WRUW2UIJ.js → chunk-N7YXDSQL.js} +1 -1
  25. package/dist/{chunk-4ZVVG5LM.js → chunk-NAZU3EEJ.js} +1 -1
  26. package/dist/{chunk-XORU3PYW.js → chunk-P5K67CKS.js} +1 -1
  27. package/dist/{chunk-ITVSLSRM.js → chunk-R23IGK5U.js} +1 -1
  28. package/dist/chunk-R4FDIYMN.js +1 -0
  29. package/dist/{chunk-LZV4QJ5E.js → chunk-SCC3O2RD.js} +1 -1
  30. package/dist/{chunk-STPMMA64.js → chunk-SP5AQION.js} +1 -1
  31. package/dist/{chunk-QPHT6QHE.js → chunk-THMGTRXP.js} +1 -1
  32. package/dist/chunk-UESDHJRB.js +1 -0
  33. package/dist/{chunk-TMZGZAWM.js → chunk-UWLEGMWX.js} +1 -1
  34. package/dist/{chunk-J4VTKRH7.js → chunk-VYFSRHXM.js} +1 -1
  35. package/dist/{chunk-HJLGRW4A.js → chunk-X4W22IH6.js} +1 -1
  36. package/dist/{chunk-XRR5X74T.js → chunk-XH7RJPBV.js} +1 -1
  37. package/dist/{chunk-RBMOWJGE.js → chunk-Y3MQLWGD.js} +1 -1
  38. package/dist/chunk-ZGCKQWQ5.js +1 -0
  39. package/dist/chunk-ZIQENZDI.js +1 -0
  40. package/dist/{content-AU7IRQXV.js → content-YRQSNKN7.js} +1 -1
  41. package/dist/{funnel-host-purchase-NFYF2NY4.js → funnel-host-purchase-SWYFJOVN.js} +1 -1
  42. package/dist/{funnel-local-client-D7e3rP5-.d.ts → funnel-local-client-BeGBvi3z.d.ts} +66 -37
  43. package/dist/{funnel-process-client-BEPv6guV.d.ts → funnel-process-client-C6QKDZun.d.ts} +46 -46
  44. package/dist/funnel-runtime-host-J2PQHVSO.js +1 -0
  45. package/dist/index.d.ts +10 -10
  46. package/dist/index.js +1 -1
  47. package/dist/merchant-bridge-contracts-ZUQ6SGXZ.js +1 -0
  48. package/dist/native-shell.js +1 -1
  49. package/dist/openrouter.d.ts +2 -2
  50. package/dist/openrouter.js +1 -1
  51. package/dist/operation-contracts-443N2P3A.js +1 -0
  52. package/dist/page.js +1 -1
  53. package/dist/{paywall-L7M4VA3Z.js → paywall-RQ66UZLW.js} +1 -1
  54. package/dist/paywall-session-PPECL5XK.js +1 -0
  55. package/dist/popup.js +1 -1
  56. package/dist/react-native.d.ts +5 -5
  57. package/dist/react-native.js +1 -1
  58. package/dist/screen-renderer-NHLIJDCW.js +1 -0
  59. package/dist/server.d.ts +64 -52
  60. package/dist/server.js +1 -1
  61. package/dist/{visual-dom-32PB6MMP.js → visual-dom-6DCUZGPB.js} +1 -1
  62. package/dist/visual.js +1 -1
  63. package/package.json +1 -1
  64. package/dist/chunk-CLAZ7NVN.js +0 -1
  65. package/dist/chunk-SJSCROSL.js +0 -1
  66. package/dist/chunk-TJZESXCS.js +0 -1
  67. package/dist/chunk-U6BYOYEE.js +0 -1
  68. package/dist/chunk-XIP32WI7.js +0 -1
  69. package/dist/funnel-runtime-host-ANA2Y3WR.js +0 -1
  70. package/dist/merchant-bridge-contracts-LJKL7PNJ.js +0 -1
  71. package/dist/operation-contracts-SP2RZUT3.js +0 -1
  72. package/dist/paywall-session-KRYPLLPR.js +0 -1
  73. package/dist/screen-renderer-W5MP4KVG.js +0 -1
  74. /package/dist/{chunk-PWXN3W4Q.js → chunk-BID4UGWB.js} +0 -0
  75. /package/dist/{chunk-RFUXSC52.js → chunk-UKMEW5I7.js} +0 -0
  76. /package/dist/{chunk-ZY4XAKNQ.js → chunk-VF6QMMEA.js} +0 -0
@@ -1 +1 @@
1
- import{a as ge}from"./chunk-SJSCROSL.js";import{a as Le}from"./chunk-J4VTKRH7.js";import{D as Xe,F as be,G as Ye,K as H,L as J,M as Z,N as xe,O as et,R as Se,U as v,V as N,W as $,X as W,Y as Q,a as he,b as He,c as Je,ja as tt,ka as X,la as B,s as Ze,t as We,u as Qe}from"./chunk-WRUW2UIJ.js";import{h as U}from"./chunk-XIP32WI7.js";import{b as e}from"./chunk-ZY4XAKNQ.js";var nt={"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 ve(t){let r=Ye(t)??"en",n=r.split("-"),s=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(a=>["TW","HK","MO"].includes(a))?"zh-Hant":"zh-Hans":n[0]??"en",i=nt[s];return i?{locale:r,copy:i}:{locale:"en",copy:nt.en}}function Mt(t,r,n="zh-CN"){let s=He(r);return Je(t,r,ve(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:t%10**s===0?0:s,maximumFractionDigits:s})}function Tt(t,r="zh-CN"){let n=ve(r).locale;return t.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(t.percentOff/100):Mt(t.amountOffCents,t.currency,n)}var rt={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 Nn(t,r="zh-CN",n="month"){let s=ve(r),i=Tt(t.discount,s.locale);if(t.appliesTo?.type==="merchandise")return s.copy.merchandise.replace("{discount}",i);let a=t.duration.type==="repeating"?new Intl.NumberFormat(s.locale).format(t.duration.months):"",u=s.locale.split("-")[0]??"en",c=u==="zh"&&/(?:Hant|TW|HK|MO)/.test(s.locale)?"zh-Hant":u,f=t.duration.type==="repeating"&&n!=="month"?rt[c]??rt.en:t.duration.type==="repeating"&&t.duration.months===1?s.copy.repeatingOne??s.copy.repeating:s.copy[t.duration.type],g=t.duration.type==="repeating"?new Intl.NumberFormat(s.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(t.duration.months):"";return f.replace("{discount}",i).replace("{months}",a).replace("{period}",g)}var I=e.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(t=>t.split(".").every(r=>r.length>0&&!["__proto__","constructor","prototype"].includes(r)),"Reserved or empty variable path"),we=e.strictObject({type:e.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:e.boolean(),enum:e.array(e.string().max(255)).min(1).max(100).optional()}),Y=we.extend({type:e.enum([...we.shape.type.options,"array"]),items:we.optional()}).superRefine((t,r)=>{(t.type==="array"!=!!t.items||t.enum&&t.type!=="string"||t.items?.enum&&t.items.type!=="string")&&r.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),ee=Y.safeExtend({source:e.discriminatedUnion("type",[e.strictObject({type:e.literal("input")}),e.strictObject({type:e.literal("node")}),e.strictObject({type:e.enum(["parameter","attribute"]),key:I})])}),Mn=e.record(I,ee),Ie=e.record(I,I).refine(t=>Object.keys(t).length<=20);function P(t,r){return t?r===null?t.nullable:t.enum&&(typeof r!="string"||!t.enum.includes(r))?!1:t.type==="array"?Array.isArray(r)&&r.length<=100&&!!t.items&&r.every(n=>P(t.items,n)):["offering_version","reward","paywall_version"].includes(t.type)?typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===2&&r.type===t.type&&e.uuid().safeParse(r.id).success:t.type==="json"||(t.type==="strings"?Array.isArray(r)&&r.every(n=>typeof n=="string"):typeof r===t.type):!1}function Oe(t,r){return t.nullable&&!r.nullable?!1:r.type==="json"?!0:t.type!==r.type||r.enum&&(!t.enum||t.enum.some(n=>!r.enum.includes(n)))?!1:t.type!=="array"||!!t.items&&!!r.items&&Oe(t.items,r.items)}function te(t,r){let n={};for(let[s,i]of Object.entries(t)){let a=i.source,u=a.type==="input"?r.answers:a.type==="node"?r.results??{}:a.type==="parameter"?r.parameters:r.attributes,c=a.type==="parameter"||a.type==="attribute"?a.key:s,f=Object.hasOwn(u,c),g=u[c];if(a.type==="attribute"&&c.includes(".")&&(!f||c.startsWith("merchandise."))){g=u,f=!0;for(let l of c.split(".")){if(!g||typeof g!="object"||!Object.hasOwn(g,l)||Array.isArray(g)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=g.length)){f=!1;break}g=g[l]}}if(!(!f||g===void 0)){if(!P(i,g))throw new Error(`Invalid variable value: ${s}`);n[s]=g}}return n}function Tn(t,r){let n={};for(let[s,i]of Object.entries(t.writes??{})){if(!Object.hasOwn(r,s))throw new Error(`Node output is missing: ${s}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=r[s]}return n}function Un(t,r,n){let s=new Set(Object.values(r.writes??{}));for(let[i,a]of Object.entries(n))if(!s.has(i)||t[i]?.source.type!=="node"||!P(t[i],a))throw new Error(`Invalid node variable write: ${i}`);if(s.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var R=e.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(t=>t.split(".").every(r=>!["__proto__","constructor","prototype"].includes(r)),"Reserved value path"),E=e.discriminatedUnion("source",[e.strictObject({source:e.literal("literal"),value:v}),e.strictObject({source:e.literal("variable"),key:e.string().min(1).max(255),path:R.optional()})]);function it(t,r){if(!r)return t;for(let n of R.parse(r).split(".")){if(Array.isArray(t)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=t.length)return;t=t[Number(n)];continue}if(t===null||typeof t!="object"||!Object.hasOwn(t,n))return;t=Reflect.get(t,n)}return t}function Ut(t,r){if(t.source==="literal")return structuredClone(t.value);let n=te(r.declarations,r);if(!Object.hasOwn(n,t.key))throw new Error("Capability input is missing");return structuredClone(v.parse(it(n[t.key],t.path)))}function je(t,r){let n=[...r].sort((i,a)=>a.length-i.length).find(i=>t===i||t.startsWith(i+"."));if(!n)return null;let s=t===n?void 0:t.slice(n.length+1);return s&&!R.safeParse(s).success?null:{key:n,path:s}}function ke(t){let r=Object.values(t.strings.locales).flatMap(n=>Object.values(n));return H(t,n=>{n.type==="custom_html"&&r.push(...Object.values(n.html))}),[...new Set(r.flatMap(Qe))]}function ot(t){return ke(t).filter(r=>r.startsWith("variables.")).map(r=>r.slice(10))}function M(t){let r=JSON.stringify(t);if(r===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(r).length,s=!1;for(let i=0;i<r.length;i++){let a=r.charAt(i);if(s)a==="\\"?i++:a==='"'&&(s=!1);else if(a==='"')s=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let u=i;for(;i+1<r.length&&/[0-9.eE+-]/.test(r.charAt(i+1));)i++;let c=r.slice(u,i+1);if(!/[eE]/.test(c))continue;let[f="",g]=c.split(/[eE]/),l=f.replace(/^-/,""),w=l.replace(".","").length,K=(l.includes(".")?l.indexOf("."):w)+Number(g),y=K<=0?2-K+w:K>=w?K:w+1;n+=y+(f.startsWith("-")?1:0)-c.length}}return n}function F(t){let r=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function s(a,u){if(n(a))for(let[c,f]of Object.entries(a))c==="$elemMatch"?i(f,u):c==="$not"?s(f,u):c==="$all"&&Array.isArray(f)&&f.forEach(g=>s(g,u))}function i(a,u=""){if(n(a)){for(let[c,f]of Object.entries(a))if(["$and","$or","$nor"].includes(c)&&Array.isArray(f))f.forEach(g=>i(g,u));else if(c==="$not")i(f,u);else if(c==="$savedGroup"&&n(f))typeof f.attributeKey=="string"&&r.add(f.attributeKey);else if(!c.startsWith("$")){let g=u?`${u}.${c}`:c;r.add(g),s(f,g)}}}return i(t),[...r]}var Bt=e.enum(["active","inactive"]),Gt=e.preprocess((t,r)=>{let n=0;function s(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(u=>s(u,a+1));else if(i&&typeof i=="object")for(let[u,c]of Object.entries(i))["__proto__","constructor","prototype"].includes(u)&&r.addIssue({code:"custom",message:"Reserved merchandise attribute"}),s(c,a+1)}}return s(t,0),t},N),$t=e.strictObject({id:e.string().trim().min(1).max(255),name:e.string().trim().min(1).max(255),status:Bt,metadata:Gt}),rr=$t.extend({internal_id:e.uuid(),project_id:e.uuid(),environment_id:e.uuid(),created_at:e.iso.datetime({offset:!0}),updated_at:e.iso.datetime({offset:!0})}),ir=e.union([e.strictObject({id:e.string().trim().min(1).max(255)}),e.strictObject({internalId:e.uuid()})]),or=e.enum(["customer","merchandise","context"]),sr=e.enum(["system","stored","request"]),ar=e.enum(["customer","merchandise","mixed"]),st=t=>t==="merchandiseId"||t==="merchandise"||t.startsWith("merchandise.");function Ce(t,r={},n=new Set){if(F(t).some(st))return!0;for(let s of W(t)){if(n.has(s))continue;n.add(s);let i=r[s];if(i?.type==="list"&&st(i.attributeKey)||i?.type==="condition"&&Ce(i.condition,r,n))return!0}return!1}var fr=e.enum(["draft","active","paused","archived"]),at=e.discriminatedUnion("type",[e.object({type:e.literal("percent"),percentOff:e.number().min(1).max(100).multipleOf(.01)}).strict(),e.object({type:e.literal("amount"),amountOffCents:e.number().int().min(1).max(1e8),currency:he}).strict()]),ct=e.discriminatedUnion("type",[e.object({type:e.literal("once")}).strict(),e.object({type:e.literal("repeating"),months:e.number().int().min(1).max(36)}).strict(),e.object({type:e.literal("forever")}).strict()]),ut=[e.object({type:e.literal("all")}).strict(),e.object({type:e.literal("plans"),planIds:e.array(e.uuid()).min(1).max(50).refine(t=>new Set(t).size===t.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],qt=e.discriminatedUnion("type",[...ut,e.strictObject({type:e.literal("merchandise"),scope:e.discriminatedUnion("type",[e.strictObject({type:e.literal("all")}),e.strictObject({type:e.literal("selected"),merchandiseIds:e.array(e.uuid()).min(1).max(1e3).refine(t=>new Set(t).size===t.length,"Duplicate merchandise")}),e.strictObject({type:e.literal("condition"),condition:$})])})]),Lt=e.discriminatedUnion("type",[...ut,e.strictObject({type:e.literal("merchandise"),scope:e.strictObject({type:e.enum(["all","selected","condition"])})})]),Ht=e.strictObject({firstPurchaseOnly:e.boolean(),condition:$}),yr=e.object({name:e.string().trim().min(1).max(80),description:e.string().max(500),discount:at,duration:ct,nativeDiscountPolicy:ge.optional(),appliesTo:qt,eligibility:Ht,selfClaimEnabled:e.boolean().default(!1),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),totalLimit:e.number().int().min(1).max(1e6).nullable(),perCustomerLimit:e.number().int().min(1).max(10),grantWindowHours:e.number().int().min(1).max(2160)}).strict().refine(t=>!t.startsAt||!t.endsAt||Date.parse(t.endsAt)>Date.parse(t.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(t=>!Ce(t.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(t=>t.appliesTo.type!=="merchandise"||t.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(t=>t.appliesTo.type!=="merchandise"||!t.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),gr=e.object({code:e.string().trim().transform(t=>t.toUpperCase()).pipe(e.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:e.number().int().min(1).max(1e6).nullable(),expiresAt:e.iso.datetime().nullable(),firstPurchaseOnly:e.boolean(),minimumAmountCents:e.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:he.nullable()}).strict().refine(t=>t.minimumAmountCents===null==(t.minimumAmountCurrency===null),"Minimum amount requires its currency");var lt=e.object({id:e.uuid(),couponId:e.uuid(),status:e.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:e.iso.datetime(),expiresAt:e.iso.datetime(),coupon:e.object({name:e.string(),discount:at,duration:ct,nativeDiscountPolicy:ge.optional(),appliesTo:Lt}).strict()}).strict(),hr=e.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Jt=e.string().regex(/^[a-f0-9]{64}$/),Zt=Ze.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),pt=e.strictObject({couponDigests:e.record(e.uuid(),Jt),variables:e.record(be,e.record(e.uuid(),e.partialRecord(e.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),e.string()))),locales:e.record(be,We.extend({nodes:e.record(e.string(),e.strictObject({base:Zt})),plans:e.object({}).strict(),pickers:e.object({}).strict()}).omit({paywall:!0}))});var dt=e.enum(["funnel-run/1","funnel-process/1"]),Or="funnel-process/1";var Ae=v,Wt=["parameters","answers","results","variables"];function Qt(t){return Wt.some(r=>t===r||t.startsWith(r+"."))}function Xt(t){let r={};for(let[s,i]of Object.entries(te(t.declarations,t))){let a=s.split(".");if(a.some(f=>["__proto__","constructor","prototype"].includes(f)))throw new Error("Reserved result path");let u=r;for(let f of a.slice(0,-1)){Object.hasOwn(u,f)||(u[f]={});let g=u[f];if(!g||typeof g!="object"||Array.isArray(g))throw new Error("Ambiguous result path");u=g}let c=a.at(-1);if(c===void 0)throw new Error("Empty result path");u[c]=i}return{...Object.fromEntries(Object.entries(t.attributes).filter(([s])=>!Qt(s))),variables:r}}var ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var _e=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),mt=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),ft=B.refine(t=>new TextEncoder().encode(JSON.stringify(t)).byteLength<=8192,"Task data exceeds 8 KiB"),Re=e.record(_e,e.enum(["string","number","boolean","strings"])).refine(t=>Object.keys(t).length<=20,"Too many output fields"),Yt=E,yt=e.strictObject({type:e.literal("external_task"),endpointId:e.uuid(),taskKey:_e,inputs:e.record(_e,Yt).refine(t=>Object.keys(t).length<=20),outputs:Re}),gt=e.strictObject({maxAttempts:e.number().int().min(1).max(5),retryDelaySeconds:e.number().int().min(1).max(30),backoff:e.enum(["fixed","exponential"]),requestTimeoutSeconds:e.number().int().min(1).max(10),timeoutSeconds:e.number().int().min(1).max(300)}).refine(t=>t.requestTimeoutSeconds<=t.timeoutSeconds,"Request timeout exceeds action deadline");var Mr=e.strictObject({outcome:e.enum(["success","failure"]),data:ft});var Tr=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("signal"),runId:e.uuid(),nodeId:mt,eventName:ne,eventId:e.uuid(),data:ft}),e.strictObject({operation:e.literal("read_results"),runId:e.uuid()})]),Ur=e.strictObject({scope:U,runId:e.uuid(),eventId:e.uuid(),accepted:e.boolean()}),en=e.record(mt,Ae),Br=e.strictObject({scope:U,runId:e.uuid(),results:en});var tn=["id","externalUserId","createdAt","ageDays","subscription"],De=e.array(e.string().trim().min(1).max(40).refine(t=>!t.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(t=>new Set(t).size===t.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),re=e.intersection(N,e.looseObject({tags:De.optional()})).refine(t=>![...tn,"parameters","answers","results"].some(r=>Object.hasOwn(t,r)),"Reserved customer attribute"),ie=e.string().trim().max(80),oe=e.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),se=e.union([e.email().max(254),e.literal("")]),nn=e.string().trim().min(1).max(255).refine(t=>!/\p{Cc}/u.test(t),"Fingerprint must not contain control characters"),ht=e.string().trim().min(1).max(255).refine(t=>!t.startsWith("gg_guest_"),"Reserved guest identity namespace"),Lr=e.object({externalUserId:ht.optional(),name:ie.default(""),email:se.default(""),phone:oe.optional(),attributes:re.default({})}).strict().refine(t=>t.externalUserId!==void 0||t.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),ae=e.discriminatedUnion("type",[e.strictObject({type:e.literal("id"),value:e.uuid()}),e.strictObject({type:e.literal("externalUserId"),value:ht})]),ce=e.strictObject({name:ie.optional(),email:se.optional(),phone:oe.optional(),attributes:re.optional(),fingerprint:nn.optional()}),ue=t=>!t.customerData||t.customer?.type==="externalUserId",le="customerData requires an externalUserId customer",bt=e.object({id:e.uuid(),externalUserId:e.string().min(1).max(255).nullable(),name:ie,email:se,phone:oe.optional(),attributes:re,createdAt:e.iso.datetime()}).strict(),Hr=e.object({customer:bt,changed:e.boolean(),replayed:e.boolean()}).strict(),rn=e.discriminatedUnion("type",[e.object({type:e.literal("id"),value:e.uuid()}).strict(),e.object({type:e.literal("externalUserId"),value:e.string().trim().min(1).max(255)}).strict()]),on=e.object({name:ie.optional(),email:se.optional(),phone:oe.optional(),attributes:re.refine(t=>!Object.hasOwn(t,"tags"),"Use incremental tagChanges").optional(),removeAttributes:e.array(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(t=>!t.includes("tags")).optional(),tagChanges:e.strictObject({add:De,remove:De}).optional()}).strict().refine(t=>Object.keys(t).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),sn=e.object({lookup:rn}).strict(),Jr=sn.extend({requestId:e.uuid(),patch:on}).strict(),Zr=e.object({search:e.string().trim().max(200).default(""),tag:e.string().trim().max(40).default(""),planId:e.string().max(200).default(""),versionId:e.string().max(200).default(""),holdingStatus:e.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:e.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:e.union([e.iso.datetime(),e.literal("")]).default(""),createdUntil:e.union([e.iso.datetime(),e.literal("")]).default(""),offset:e.coerce.number().int().min(0).max(1e5).default(0),limit:e.coerce.number().int().min(1).max(100).default(50)}).strict(),Wr=e.object({customers:bt.array(),hasMore:e.boolean(),total:e.number().int().nonnegative().nullable(),evaluatedAt:e.iso.datetime()}).strict();var ti=e.enum(["local","remote"]),ze=e.strictObject({port:e.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:v.optional(),sticky:e.array(e.strictObject({expected:Q.nullable(),next:Q})).max(100),exposures:e.array(v).max(100),features:e.array(v).max(100)}),xt=e.strictObject({type:e.literal("evaluate"),receiptId:e.uuid(),environmentId:e.uuid(),policyRevision:e.number().int().nonnegative(),attributes:N,sticky:e.record(e.string(),Q)}),St=xt.extend({runId:e.uuid(),versionId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative()}),an=xt.omit({type:!0,receiptId:!0}).extend({type:e.literal("evaluate_segment")}),vt=e.strictObject({nodeId:e.string().min(1).max(64),result:ze}),wt=an.extend({runId:e.uuid(),versionId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),parameters:B,answers:X,variables:e.record(e.string(),v)});var Ee=e.discriminatedUnion("type",[e.strictObject({type:e.literal("literal"),value:v}),e.strictObject({type:e.literal("variable"),key:I,path:R.optional()}),e.strictObject({type:e.literal("feature"),featureKey:e.string().min(1).max(128)})]),cn=e.strictObject({requestId:e.uuid(),decisionId:e.uuid(),customerId:e.uuid(),externalUserId:e.string().min(1).max(255).nullable(),versionId:e.uuid(),receiptId:e.uuid(),value:v}),un={funnelId:e.uuid(),requestId:e.uuid(),customer:ae,customerData:ce.optional(),attributes:N.refine(t=>!["parameters","answers","results","variables"].some(r=>Object.hasOwn(t,r)),"parameters, answers, results and variables are reserved flow namespaces")},li=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("decide"),...un}).refine(ue,le),e.strictObject({operation:e.literal("read_decision"),decisionId:e.uuid()}),e.strictObject({operation:e.literal("evaluate_decision"),decisionId:e.uuid(),requestId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),receiptId:e.uuid(),policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256),result:ze}),e.strictObject({operation:e.literal("feature_config"),funnelId:e.uuid()}),e.strictObject({operation:e.literal("commit_decision_segment"),decisionId:e.uuid(),requestId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256),steps:e.array(vt).max(32),boundary:e.strictObject({nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()}).optional()}),e.strictObject({operation:e.literal("segment_configuration"),funnelId:e.uuid(),versionId:e.uuid()}),e.strictObject({operation:e.literal("configuration"),funnelId:e.uuid(),versionId:e.uuid().optional()}),e.strictObject({operation:e.literal("local_configuration"),funnelId:e.uuid()}),e.strictObject({operation:e.literal("report_used"),decisionId:e.uuid(),eventId:e.uuid(),occurredAt:e.iso.datetime({offset:!0}),reference:e.string().min(1).max(128).optional()})]),pi=e.strictObject({scope:U,decisionId:e.uuid(),requestId:e.uuid(),status:e.enum(["pending","completed","failed"]),decision:cn.nullable(),evaluation:e.discriminatedUnion("type",[St,wt]).optional()}).refine(t=>t.status==="completed"==(t.decision!==null)&&(!t.decision||t.decision.decisionId===t.decisionId&&t.decision.requestId===t.requestId),"Completed decisions carry their committed result"),di=e.strictObject({scope:U,decisionId:e.uuid(),eventId:e.uuid(),source:e.literal("caller_reported")});function ln(t,r=[]){let n=[];H(t,i=>{i.hidden&&n.push("Hidden components must not be delivered"),r.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let s=new Set(xe(t).map(i=>i.key));for(let[i,a]of Object.entries(t.strings.locales))for(let u of Object.keys(a))s.has(u)||n.push(`Unused string ${u} must not be delivered (${i})`);return n}function It(t){return t.hidden?null:t.type!=="stack"?t:{...t,children:t.children.flatMap(r=>It(r)??[])}}function pn(t){let r=t.pages.map(i=>{let a=It(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(xe({pages:r}).map(i=>i.key)),s=Object.fromEntries(Object.entries(t.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([u])=>n.has(u)))]));return{...t,pages:r,strings:{...t.strings,locales:s}}}function Ot(t,r=[]){let n=J.parse(structuredClone(pn(t))),s=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(s);for(let a of n.pages)if(!s(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=ln(n,r);if(i.length)throw new Error(i.join("; "));return n}var hi=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),couponId:e.uuid(),productBindingId:e.uuid(),storeOfferId:e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:e.enum(["introductory","promotional"])}),e.strictObject({action:e.literal("set_enabled"),id:e.uuid(),revision:e.number().int().nonnegative(),enabled:e.boolean()})]),bi=e.array(e.strictObject({id:e.uuid(),couponId:e.uuid(),productBindingId:e.uuid(),storeOfferId:e.string().min(1).max(255).nullable(),storeOfferType:e.enum(["introductory","promotional"]),enabled:e.boolean(),revision:e.number().int().nonnegative()})).max(500),Ke=e.strictObject({offerKind:e.enum(["none","introductory","promotional"]),offerId:e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:e.number().int().min(0).max(1e8),trialDays:e.number().int().min(1).max(730).nullable()}).superRefine((t,r)=>{(t.offerKind==="none"&&(t.offerId!==null||t.discountMinor!==0||t.trialDays!==null)||t.trialDays!==null&&t.discountMinor!==0)&&r.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),xi=e.record(e.uuid(),Ke).refine(t=>Object.keys(t).length<=20,"At most 20 native store selections");var wi=e.strictObject({schemaVersion:e.literal(1),renderKey:e.string().min(1).max(256),routeTemplate:e.string().startsWith("/").max(2048),selectors:e.array(e.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:e.array(e.number().int().min(0)).min(1),absent:e.array(e.number().int().min(0))}).superRefine((t,r)=>{let n=[...t.present,...t.absent];(new Set(t.selectors).size!==t.selectors.length||new Set(n).size!==n.length||n.length!==t.selectors.length||n.some(s=>s>=t.selectors.length))&&r.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),jt=e.strictObject({renderKey:e.string().min(1).max(256),routeKey:e.string().min(1).max(256),stateKey:e.string().min(1).max(256),documentKey:e.string().min(1).max(256),documentHash:e.string().regex(/^[a-f0-9]{64}$/),compositionKey:e.string().min(1).max(256),entryMode:e.enum(["hard","soft"]),match:e.strictObject({present:e.array(e.number().int().min(0)),absent:e.array(e.number().int().min(0))})});var dn=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Ve="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",mn=e.string().regex(new RegExp(`^${Ve}/${Ve}/${Ve}/manifest\\.json$`)),kt=e.strictObject({kind:e.literal("gcs-resumable"),url:e.url(),bucket:e.enum(dn),objectKey:mn,byteLength:e.number().int().positive(),expiresAt:e.iso.datetime()}).superRefine((t,r)=>{let n=new URL(t.url),s=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${t.bucket}/o`||[...s.keys()].some(a=>!i.includes(a)||s.getAll(a).length!==1)||s.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(s.get("upload_id")??"")||s.has("name")&&s.get("name")!==`app-manifests/${t.objectKey}`||s.has("upload_protocol")&&s.get("upload_protocol")!=="resumable"||s.has("ifGenerationMatch")&&s.get("ifGenerationMatch")!=="0")&&r.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var S=e.string().min(1).max(256),C=e.string().regex(/^[a-f0-9]{64}$/),pe=e.strictObject({versionId:e.uuid(),manifestDigest:C,sourceGraphDigest:C,pageKey:S,stateKey:S,documentKey:S,documentHash:C,elementKey:S.optional(),nodeId:S.optional(),contentHash:C.optional(),renderKey:S.optional()}),Ct=e.strictObject({pageKey:S,documentKey:S,expectedDocumentHash:C,renderKey:S.optional(),nodeId:S,elementKey:S,expectedContentHash:C,property:e.enum(["text","fontSize","color"]),value:e.union([e.string().max(4e3),e.number().finite()])}),_i=e.strictObject({versionId:e.uuid(),manifestDigest:C,sourceGraphDigest:C,pageKey:S,stateKey:S,documentKey:S,documentHash:C,renderKey:S.optional(),patches:e.array(Ct.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),fn=/^[a-z][a-z0-9-]{0,39}$/,q=e.string().regex(fn),Pe=e.enum(["web","ios","android"]),Ri=e.discriminatedUnion("action",[e.strictObject({action:e.literal("register"),requestId:e.uuid(),client:q,platform:Pe,label:e.string().trim().min(1).max(100),sha256:C,bytes:e.number().int().min(1),transferBytes:e.number().int().min(1)}),e.strictObject({action:e.literal("complete"),versionId:e.uuid()}),e.strictObject({action:e.literal("current"),versionId:e.uuid(),expectedCurrent:e.uuid().nullable()}),e.strictObject({action:e.literal("delivery"),enabled:e.boolean()}),e.strictObject({action:e.literal("changes"),versionId:e.uuid(),experimentId:e.uuid(),variationId:S,changesetId:e.uuid().nullable(),expectedRevision:C.nullable(),editorUrl:e.string().url().max(2048),patches:e.array(Ct).max(200)})]),Fe=e.strictObject({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),clientKey:q,platform:Pe,label:e.string(),sha256:C,bytes:e.number().int().positive(),objectKey:e.string(),state:e.enum(["uploading","ready","rejected"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),createdAt:e.string(),expiresAt:e.string(),readyAt:e.string().nullable(),summary:e.record(e.string(),e.json()),routeTree:e.json().nullable(),validation:e.record(e.string(),e.json())}),yn=e.strictObject({key:q,platform:Pe,currentId:e.uuid().nullable()}),Di=e.strictObject({rows:e.array(Fe).max(100),nextCursor:e.uuid().nullable(),clients:e.array(yn).max(20)}),Ne=e.strictObject({storedBytes:e.number().int().nonnegative(),reservedBytes:e.number().int().nonnegative(),chargedBytes:e.number().int().nonnegative(),versions:e.number().int().nonnegative(),objects:e.number().int().nonnegative(),orphanObjects:e.number().int().nonnegative(),missingReadyObjects:e.number().int().nonnegative(),unknownObjectSizes:e.number().int().nonnegative(),byteLimit:e.number().int().positive(),versionLimit:e.number().int().positive(),remainingBytes:e.number().int().nonnegative()}),zi=e.strictObject({asOf:e.iso.datetime({offset:!0}),reclamation:e.literal("manual-review-required"),buckets:e.strictObject({source:Ne,runtime:Ne,previews:Ne})}),Ei=e.strictObject({version:Fe,actorId:e.uuid(),claims:e.record(e.string(),e.json())}),Ki=e.strictObject({version:Fe,upload:kt.nullable()}),Vi=e.object({format:e.literal("indiana-route-state-index"),schemaVersion:e.literal(3),routes:e.array(e.object({routeKey:S,path:e.string(),documentKey:S,documentHash:C,initialStateKey:S,initialRenderKey:S})),renders:e.array(jt)}).loose().superRefine((t,r)=>{(!t.renders||t.routes.some(n=>!t.renders?.some(s=>s.renderKey===n.initialRenderKey&&s.routeKey===n.routeKey&&s.documentKey===n.documentKey&&s.stateKey===n.initialStateKey&&s.documentHash===n.documentHash&&s.entryMode==="hard")))&&r.addIssue({code:"custom",message:"Incomplete render catalog"})}),Ni=e.strictObject({rows:e.array(e.object({id:e.uuid(),name:e.string(),status:e.string(),variations:e.array(e.object({id:S,key:S,name:e.string().optional()}).loose())}).loose()),limited:e.boolean()}),Pi=e.strictObject({enabled:e.boolean(),allowedOrigins:e.array(e.string())});var At=e.strictObject({id:e.uuid(),name:e.string().trim().min(1).max(80),client:q,source:pe,event:e.enum(["screen_enter","button_click"]),cooldownSeconds:e.number().int().min(0).max(2592e3),behavior:e.literal("observe")}).superRefine((t,r)=>{t.event==="button_click"&&(!t.source.nodeId||!t.source.elementKey)&&r.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});var D={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},_t="00000000-0000-0000-0000-000000000000";var Rt=e.strictObject({type:e.literal("bundle"),paywall:E.optional(),offering:E.optional(),coupons:E,data:E}),gn=t=>e.strictObject({type:e.literal(t),id:e.uuid()}),Hi=e.strictObject({type:e.literal("bundle"),paywallVersionId:e.uuid().optional(),offeringVersionId:e.uuid().optional(),couponIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length),data:v});var Ji=e.strictObject({type:e.literal("bundle"),offering:gn("offering_version").nullable(),paywall:e.strictObject({versionId:e.uuid(),paywallId:e.uuid(),offeringVersionId:e.uuid()}).nullable(),coupons:e.array(lt).max(20),data:v});var Dt=e.union([e.string(),e.number().finite(),e.boolean(),e.null()]),hn=e.union([Dt,e.array(Dt).min(1).max(20)]),bn=e.record(R,hn).refine(t=>Object.keys(t).length<=10),zt=e.strictObject({path:R,type:e.enum(["string","number","boolean","strings"]),nullable:e.boolean().optional(),aggregation:e.enum(["count","exists"]).optional(),where:bn.optional()}).superRefine((t,r)=>{(t.aggregation==="count"&&t.type!=="number"||t.aggregation==="exists"&&t.type!=="boolean"||!t.aggregation&&t.where)&&r.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var xn=["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"],Et=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Sn=E,Kt=e.discriminatedUnion("type",[yt,e.strictObject({type:e.literal("claim_offer"),coupon:E}),e.strictObject({type:e.literal("event"),event:Et}),e.strictObject({type:e.literal("api"),operation:e.enum(xn),inputs:e.record(R,Sn).refine(t=>Object.keys(t).length<=40),outputs:e.record(Et,zt).refine(t=>Object.keys(t).length<=20)})]);var b=ne,vn=e.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),A={id:b,name:e.string().trim().min(1).max(80),position:e.strictObject({x:e.number().finite(),y:e.number().finite()}).optional()},wn={success:b,cancel:b,unavailable:b,failure:b},In=e.url().max(2048).refine(t=>{try{return new URL(t).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),On=e.enum(["same_window","new_window"]),jn=e.discriminatedUnion("type",[e.strictObject({...A,type:e.literal("entry"),next:b,triggers:e.array(At).max(20).refine(t=>new Set(t.map(r=>r.id)).size===t.length,"Entry trigger IDs must be unique").optional()}),e.strictObject({...A,type:e.literal("screen"),screenId:b,presentation:Xe,outputs:e.record(b,b),offering:e.discriminatedUnion("source",[e.strictObject({source:e.literal("variable"),key:I}),e.strictObject({source:e.literal("fixed"),versionId:e.uuid()})]).optional()}),e.strictObject({...A,type:e.literal("offering"),configuration:e.discriminatedUnion("source",[e.strictObject({source:e.literal("fixed"),versionId:e.uuid()}),e.strictObject({source:e.literal("feature"),featureKey:e.string().min(1).max(128)})]),writes:e.strictObject({value:I}),next:b}),e.strictObject({...A,type:e.literal("coupon"),couponId:e.uuid(),writes:e.strictObject({value:I}),next:b}),e.strictObject({...A,type:e.literal("coupons"),couponIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length),writes:e.strictObject({value:I}),next:b}),e.strictObject({...A,type:e.literal("output"),value:e.discriminatedUnion("type",[...Ee.options,Rt,e.strictObject({type:e.literal("selection"),screenId:b,offeringKey:I})])}),e.strictObject({...A,type:e.literal("condition"),cases:e.array(e.strictObject({condition:$,target:b})).min(1).max(50),default:b}),e.strictObject({...A,type:e.literal("feature"),featureKey:e.string().min(1).max(128),writes:e.strictObject({value:I}),next:b}),e.strictObject({...A,type:e.literal("split"),experimentId:e.uuid(),applyPageExperiment:e.literal(!0).optional(),routes:e.record(vn,b).refine(t=>Object.keys(t).length>=2&&Object.keys(t).length<=20),notParticipating:b}),e.strictObject({...A,type:e.literal("action"),...wn,execution:gt,action:Kt,writes:Ie.optional()}),e.strictObject({...A,type:e.literal("external_page"),appManifest:pe.optional(),url:In,openIn:On,opened:b,failed:b}),e.strictObject({...A,type:e.literal("end"),outcome:e.enum(["completed","closed","ineligible","failed"]),output:Ee.optional()}),e.strictObject({...A,type:e.literal("wait"),writes:Ie.optional(),wait:e.discriminatedUnion("type",[e.strictObject({type:e.literal("duration"),delaySeconds:e.number().int().min(1).max(2592e3),elapsed:b}),e.strictObject({type:e.literal("event"),eventName:b,outputs:Re,timeoutSeconds:e.number().int().min(1).max(2592e3),received:b,timeout:b})])})]),Me=e.strictObject({version:e.literal(5),entry:b,nodes:e.array(jn).min(1).max(D.flowNodes)}),Te=Me.superRefine((t,r)=>{kn(t,n=>r.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function de(t){switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[t.next];case"screen":return Object.values(t.outputs);case"condition":return[...t.cases.map(r=>r.target),t.default];case"split":return[...Object.values(t.routes),t.notParticipating];case"action":return[t.success,t.cancel,t.unavailable,t.failure];case"external_page":return[t.opened,t.failed];case"end":case"output":return[];case"wait":return t.wait.type==="duration"?[t.wait.elapsed]:[t.wait.received,t.wait.timeout]}}function kn(t,r){let n=[],s=new Map(t.nodes.map(l=>[l.id,l])),i=(l,w,K)=>{n.push(l),r?.({message:l,reason:w,path:K?["nodes",t.nodes.indexOf(K)]:[]})};s.size!==t.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(s.get(t.entry)?.type!=="entry"||t.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(t.nodes.filter(l=>l.type==="screen").length>D.pages||t.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>D.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of t.nodes){for(let w of de(l))w===t.entry&&i("An entry cannot be a transition target","entryTarget",l),s.has(w)||i(`Missing target ${w}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let u=new Set,c=new Set,f=new Set;function g(l){if(u.has(l)){i("Flow edges must not form a cycle","cycle",s.get(l));return}if(!(c.has(l)||!s.has(l))){u.add(l),f.add(l);for(let w of de(s.get(l)))g(w);u.delete(l),c.add(l)}}g(t.entry);for(let l of t.nodes)f.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}var Ue={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Vt(t,r,n){let s=[...r].sort((c,f)=>f.length-c.length),i=new Set,a=(c,f=!1)=>{let g=s.find(l=>c===l||f&&c.startsWith(l+"."));i.add(g??c)};if(t.type==="condition"){let c=n?.startsWith("case_")?Number(n.slice(5)):t.cases.length-1;for(let f of t.cases.slice(0,c+1))for(let g of F(f.condition))g.startsWith("variables.")&&a(g.slice(10),!0)}if(t.type==="screen"&&t.offering?.source==="variable"&&a(t.offering.key),t.type==="action"&&(t.action.type==="api"||t.action.type==="external_task"))for(let c of Object.values(t.action.inputs))c.source==="variable"&&a(c.key);t.type==="action"&&t.action.type==="claim_offer"&&t.action.coupon.source==="variable"&&a(t.action.coupon.key);let u=t.type==="output"?t.value:t.type==="end"?t.output:null;if(u?.type==="variable"&&a(u.key),u?.type==="bundle")for(let c of[u.paywall,u.offering,u.coupons,u.data])c?.source==="variable"&&a(c.key);return u?.type==="selection"&&a(u.offeringKey),[...i]}var G=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),me=t=>e.record(e.string(),v).refine(r=>M(r)<=t,"Funnel evidence exceeds its byte budget"),ko=e.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Ge=e.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),$e=e.discriminatedUnion("type",[e.strictObject({type:e.literal("flag"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("experiment"),id:e.uuid()}),e.strictObject({type:e.literal("saved_group"),id:e.uuid()}),e.strictObject({type:e.literal("config"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("constant"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("paywall_version"),id:e.uuid()}),e.strictObject({type:e.literal("offering_version"),id:e.uuid()}),e.strictObject({type:e.literal("reward"),id:e.uuid()})]),Co=e.strictObject({schemaVersion:e.literal(1),kind:Ge,selector:$e.nullable(),context:me(131072),contract:e.strictObject({version:e.number().int().positive(),evaluator:e.string().min(1).max(128),policyRevision:e.number().int().nonnegative()})}).refine(t=>M(t)<=131072,"Node input exceeds its byte budget"),Ao=e.strictObject({schemaVersion:e.literal(1),kind:Ge,outcome:e.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:me(131072),route:e.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:me(131072)}).refine(t=>M(t)<=131072,"Node result exceeds its byte budget"),_o=e.strictObject({schemaVersion:e.literal(1),operations:e.record(G,e.strictObject({attempts:e.number().int().nonnegative(),maxAttempts:e.number().int().min(1).max(5),deadlineAt:e.iso.datetime({offset:!0}),retryAt:e.iso.datetime({offset:!0}).nullable(),error:e.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:e.strictObject({type:G,id:e.uuid()}).nullable()}))}).refine(t=>M(t)<=65536,"Execution state exceeds its byte budget"),T={receiptId:e.uuid()},Be=e.iso.datetime({offset:!0}),Ro=e.discriminatedUnion("type",[e.strictObject({type:e.literal("node_entered"),details:e.strictObject({kind:Ge})}),e.strictObject({type:e.literal("presentation_shown"),details:e.strictObject({...T,source:e.literal("client"),occurredAt:Be.optional()})}),e.strictObject({type:e.literal("decision_accepted"),details:e.strictObject(T)}),e.strictObject({type:e.literal("signal_received"),details:e.strictObject({signalId:e.uuid(),nodeId:G,eventName:G,data:me(8192),source:e.literal("server"),occurredAt:Be})}),e.strictObject({type:e.literal("signal_consumed"),details:e.strictObject({...T,signalId:e.uuid()})}),e.strictObject({type:e.literal("wait_elapsed"),details:e.strictObject(T)}),e.strictObject({type:e.literal("wait_timeout"),details:e.strictObject(T)}),e.strictObject({type:e.literal("operation_completed"),details:e.strictObject({...T,operation:G,reference:e.strictObject({type:G,id:e.uuid()}).nullable()})}),e.strictObject({type:e.literal("execution_recovered"),details:e.strictObject({generation:e.number().int().positive(),reason:e.enum(["interrupted","expired_lease","delivery_failed"])})}),e.strictObject({type:e.literal("execution_failed"),details:e.strictObject({generation:e.number().int().positive(),code:e.string().regex(/^[a-z_]{1,64}$/)})}),e.strictObject({type:e.literal("run_completed"),details:e.strictObject({outcome:e.enum(["completed","ineligible","failed"])})}),e.strictObject({type:e.literal("run_closed"),details:e.strictObject({source:e.enum(["client","server","expiry"])})}),e.strictObject({type:e.literal("treatment_used"),details:e.strictObject({...T,source:e.enum(["client","server"]),occurredAt:Be,reference:e.string().min(1).max(128).optional()})})]);var _=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=e.discriminatedUnion("type",[e.strictObject({id:_,type:e.literal("owned"),publicData:pt.optional(),document:J.refine(t=>["page","popup","onboarding"].includes(t.surface)&&t.pages.length===1&&t.actions.every(r=>r.type==="event"&&!r.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),e.strictObject({id:_,type:e.literal("paywall"),paywallVersionId:e.uuid()})]),qe={executionContract:dt.optional(),kind:e.literal("funnel"),schemaVersion:e.literal(4),screens:e.array(Cn).max(D.pages),references:e.record(_,$e).refine(t=>Object.keys(t).length<=500),inputs:e.array(e.strictObject({variable:_,screenId:_,componentId:_,required:e.boolean()})).max(D.questions),variables:e.record(I,ee).refine(t=>Object.keys(t).length<=D.logicNodes),outputSchema:Y,execution:e.strictObject({runTimeoutSeconds:e.number().int().min(1).max(Ue.runTimeoutSeconds),maxTransitions:e.number().int().min(1).max(Ue.maxTransitions)})},Wo=e.strictObject({...qe,graph:Me});function An(t,r){let n=!1,s=(i,a)=>{let u=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(t.strings.locales).some(c=>c[i.text]?.includes("{{offer."))&&!(u&&r(u))&&(n=!0),i.type==="stack"&&i.children.forEach(c=>s(c,u))};for(let i of t.pages)s(i.root);return n}function ye(t){return Array.isArray(t)?t.some(ye):!t||typeof t!="object"?!1:Object.entries(t).some(([r,n])=>r==="productVersionId"?n===_t:ye(n))}function _n(t){let r=[],n=new Set(Object.values(t.references).flatMap(s=>s.type==="reward"?[s.id]:[]));for(let[s,i]of t.screens.entries()){if(i.type!=="owned")continue;let a;try{a=Ot(i.document)}catch(u){r.push({message:u instanceof Error?u.message:"Screen cannot be delivered",reason:"screen",path:["screens",s,"document"]});continue}for(let[u,c]of t.inputs.entries())c.screenId===i.id&&!Se(a,c.componentId)&&r.push({message:`Local Funnel input ${c.variable} targets hidden component ${c.componentId} on screen ${c.screenId}`,reason:"inputBinding",path:["inputs",u]})}for(let[s,i]of t.graph.nodes.entries()){let a=["graph","nodes",s],u=i.type==="screen"?t.screens.find(c=>c.id===i.screenId):void 0;u?.type==="owned"&&(u.document.actions.some(c=>typeof c.properties.templateKey=="string"&&c.properties.templateKey.startsWith("popup-coupon-"))&&r.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),An(u.document,c=>n.has(c))&&r.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&ye(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&ye(i.output.value))&&r.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return r}function Nt(t,r){for(let{message:n,reason:s,path:i}of _n(t))r.addIssue({code:"custom",message:n,path:i,params:{reason:s}})}function Pt(t,r){let n=(y,o,p=[])=>r.addIssue({code:"custom",message:y,path:p,params:{reason:o}}),s=Object.values(t.references),i=new Map(t.screens.map(y=>[y.id,y])),a=(y,o)=>s.some(p=>p.type===y&&("id"in p?p.id:p.key)===o);i.size!==t.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let u=t.graph.nodes.filter(y=>y.type==="screen");(u.length!==i.size||u.some(y=>!i.has(y.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let c=new Map,f=Object.keys(t.variables);f.some(y=>f.some(o=>y!==o&&o.startsWith(y+".")))&&n("Variable paths must not overlap","variable");function g(y,o){Object.hasOwn(t.variables,y)||n("Every produced variable needs a declaration","variable",["graph","nodes",t.graph.nodes.indexOf(o)]);let p=c.get(y)??new Set;p.add(o.id),c.set(y,p)}for(let[y,o]of t.graph.nodes.entries()){let p=["graph","nodes",y],O=o.type==="feature"?o.featureKey:o.type==="offering"&&o.configuration.source==="feature"?o.configuration.featureKey:o.type==="output"&&o.value.type==="feature"?o.value.featureKey:o.type==="end"&&o.output?.type==="feature"?o.output.featureKey:null;O&&!a("flag",O)&&n("Flag selectors require an explicit GB resource reference","feature",p);let j=o.type==="feature"||o.type==="offering"||o.type==="coupon"||o.type==="coupons"||o.type==="action"&&o.action.type==="api"?["value"]:o.type==="action"&&o.action.type==="external_task"?Object.keys(o.action.outputs):o.type==="wait"&&o.wait.type==="event"?Object.keys(o.wait.outputs):[],k="writes"in o?o.writes??{}:{};(j.length!==Object.keys(k).length||j.some(d=>!Object.hasOwn(k,d))||new Set(Object.values(k)).size!==Object.values(k).length)&&n("Node writes must map every named output exactly once","variable",p);for(let[d,x]of Object.entries(k)){g(x,o);let h=t.variables[x],m=o.type==="offering"?"offering_version":o.type==="coupon"?"reward":o.type==="action"&&o.action.type==="api"?"json":o.type==="action"&&o.action.type==="external_task"?o.action.outputs[d]:o.type==="wait"&&o.wait.type==="event"?o.wait.outputs[d]:void 0;(h?.source.type!=="node"||m&&h.type!==m)&&n("Node writer source or output type does not match declaration","variable",p)}if(o.type==="coupons"){let d=t.variables[o.writes.value];(d?.type!=="array"||d.items?.type!=="reward"||d.items.nullable||d.nullable)&&n("Coupons output requires a non-null Reward array","variable",p);for(let x of o.couponIds)a("reward",x)||n("Coupons require Reward references","coupon",p)}if(o.type==="split"&&!a("experiment",o.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",p),o.type==="coupon"&&!a("reward",o.couponId)&&n("Coupon selectors require a Reward reference","coupon",p),o.type==="action"&&o.action.type==="claim_offer"&&o.action.coupon.source==="literal"){let d=o.action.coupon.value;(!d||typeof d!="object"||Array.isArray(d)||d.type!=="reward"||typeof d.id!="string"||Object.keys(d).length!==2||!a("reward",d.id))&&n("Coupon claims require a Reward reference","coupon",p)}if(o.type==="offering"&&o.configuration.source==="fixed"&&!a("offering_version",o.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",p),o.type==="screen"&&o.offering?.source==="variable"&&t.variables[o.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",p),o.type==="action"&&o.action.type==="claim_offer"&&o.action.coupon.source==="variable"&&(t.variables[o.action.coupon.key]?.type!=="reward"||o.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",p),o.type==="screen"){let d=i.get(o.screenId);if(o.offering?.source==="fixed"&&!a("offering_version",o.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",p),d?.type==="paywall"&&o.offering&&n("Paywall owns its fixed Offering Version","offering",p),d?.type==="paywall"&&!a("paywall_version",d.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",p),d?.type==="owned"){let x=d.document.pages[0];if(!x){n("Owned screen requires a page","screen",p);continue}et(d.document).some(m=>!m.complete)&&n("Owned screens require complete local content","translations",p);let h=new Set(d.document.actions.map(m=>m.id));(h.size!==Object.keys(o.outputs).length||Object.keys(o.outputs).some(m=>!h.has(m)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",p),Z(x.root,m=>{!o.offering&&(m.type==="plan_picker"||(m.type==="stack"||m.type==="button")&&m.bind?.plan||m.type==="customer_data"&&["customer_plans","credit_packs"].includes(m.data.source))&&n("Product presentation requires an Offering Version","offering",p),m.type==="customer_data"&&Object.values(m.data.outputs??{}).some(V=>V!==void 0&&!h.has(V))&&n("Customer components require declared screen outcomes","componentOutput",p)})}}o.type==="end"&&["completed","ineligible"].includes(o.outcome)&&!o.output&&n("Completed and ineligible ends require a declared output","output",p),o.type==="end"&&o.output?.type==="literal"&&!P(t.outputSchema,o.output.value)&&n("Terminal output does not match outputSchema","output",p),o.type==="output"&&o.value.type==="literal"&&!P(t.outputSchema,o.value.value)&&n("Terminal output does not match outputSchema","output",p);let z=o.type==="output"?o.value:o.type==="end"?o.output:void 0;if(z?.type==="variable"&&!z.path){let d=t.variables[z.key];d&&!Oe(d,t.outputSchema)&&n("Variable output does not match outputSchema","output",p)}if(o.type==="screen"){let d=i.get(o.screenId);if(d?.type==="owned")for(let x of ke(d.document))(/^(input|params)\./.test(x)||x.startsWith("variables.")&&!je(x.slice(10),f))&&n("Screen values must reference registered variables","variable",p)}if(o.type==="condition")for(let d of o.cases){for(let x of W(d.condition))a("saved_group",x)||n("Conditions require explicit Saved Group references","savedGroup",p);for(let x of F(d.condition))x.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",p)}if(o.type==="output"&&o.value.type==="bundle"){t.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",p);for(let[d,x]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let h=o.value[d];if(h)if(h.source==="literal"){let m=d==="coupons"?h.value:[h.value];(!Array.isArray(m)||m.length>20||m.some(V=>!P({type:x,nullable:!1},V)||!a(x,V.id))||d==="coupons"&&new Set(m.map(V=>V.id)).size!==m.length)&&n("Bundle requires distinct scoped resource references",d==="coupons"?"coupon":d==="paywall"?"paywall":"offering",[...p,"value",d])}else{let m=t.variables[h.key];(h.path||!m||m.nullable||(d==="coupons"?m.type!=="array"||m.items?.type!=="reward"||m.items.nullable:m.type!==x))&&n("Bundle binding type does not match its slot","output",p)}}}}for(let[y,o]of t.graph.nodes.entries()){let p=o.type==="screen"?i.get(o.screenId):void 0,O=[...Vt(o,f),...p?.type==="owned"?ot(p.document).map(j=>je(j,f)?.key??j):[]];for(let j of new Set(O)){let x=function(h){if(h===o.id)return!0;if(d.has(h))return!1;d.add(h);let m=t.graph.nodes.find(Ft=>Ft.id===h);return m?(z.has(h)?m.type==="action"?[m.cancel,m.unavailable,m.failure]:m.type==="wait"&&m.wait.type==="event"?[m.wait.timeout]:[]:de(m)).some(x):!1};var K=x;if(!Object.hasOwn(t.variables,j)){n("Consumed variable is undeclared","variable",["graph","nodes",y]);continue}let k=t.variables[j];if(o.type==="screen"&&k.source.type==="input"&&t.inputs.some(h=>h.screenId===o.screenId&&h.variable===j)||k.source.type==="parameter"||k.source.type==="attribute")continue;let z=k.source.type==="input"?new Set(t.inputs.filter(h=>h.variable===j&&h.required).flatMap(h=>u.filter(m=>m.screenId===h.screenId).map(m=>m.id))):c.get(j)??new Set,d=new Set;(!z.size||x(t.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",y])}}(new Set(t.inputs.map(y=>y.variable)).size!==t.inputs.length||new Set(t.inputs.map(y=>`${y.screenId}:${y.componentId}`)).size!==t.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[y,o]of t.inputs.entries()){t.variables[o.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",y]);let p=i.get(o.screenId),O=p?.type==="owned"?Se(p.document,o.componentId):null;if((O?.type!=="stack"||!O.interaction||!["input","toggle","select","multiselect","tabs"].includes(O.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",y]),O?.type==="stack"&&O.interaction){let j=O.interaction.type==="toggle"?"boolean":O.interaction.type==="multiselect"?"strings":"string";t.variables[o.variable]?.type!==j&&n("Input variable type does not match component","inputBinding",["inputs",y]);let k=t.variables[o.variable]?.enum;k&&!O.children.filter(z=>!z.hidden).every(z=>k.includes(z.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",y])}}for(let[y,o]of Object.entries(t.variables))o.enum&&o.type!=="string"&&n("Only string variables support enum","variable",["variables",y]),o.source.type==="input"&&!t.inputs.some(p=>p.variable===y)&&n("Input variable requires a component binding","inputBinding",["variables",y]);let l=0,w=0;for(let y of t.screens)if(y.type==="owned"){for(let o of y.document.pages)Z(o.root,()=>{l++});w+=y.document.actions.length}(l>D.components||w>D.actions||M(t)>D.documentBytes)&&n("Funnel document exceeds its budget","budget")}var Rn=e.strictObject({...qe,graph:Te}).superRefine(Pt),Dn=e.strictObject({...qe,graph:Te,displayName:e.string().trim().min(1).max(80)}).superRefine(Pt),Qo=Dn.superRefine(Nt),Xo=Rn.superRefine(Nt),fe=e.string().regex(Le),L={requestId:e.uuid(),nodeId:_,visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),customerToken:fe.optional()},zn=e.discriminatedUnion("type",[e.strictObject({type:e.literal("screen"),output:_,answers:X,selection:e.record(_,e.union([e.string().max(200),e.boolean(),e.number().int().min(0).max(1e4)])).optional()}),e.strictObject({type:e.literal("paywall_quote"),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional(),actionId:_,productVersionId:e.uuid(),offerId:e.uuid().optional(),nativeOffer:Ke.optional(),predecessor:e.strictObject({operationId:e.uuid().nullable(),generation:e.number().int().positive()}).optional()}),e.strictObject({type:e.literal("paywall_confirm"),operationId:e.uuid()}),e.strictObject({type:e.literal("paywall_cancel"),operationId:e.uuid()}),e.strictObject({type:e.literal("client_action"),receiptId:e.uuid(),outcome:e.enum(["success","cancel","failure","opened","failed"])})]),En=e.object({nodeId:_,visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),components:e.record(_,e.object({resourceKey:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:e.number().int().min(1).max(1e5),after:tt.nullable(),filter:e.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(t=>Object.keys(t).length<=150)}).strict(),Yo=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("start"),funnelId:e.uuid(),requestId:e.uuid(),customer:ae.optional(),customerData:ce.optional(),locale:e.string().min(1).max(35),parameters:B}).refine(ue,le),e.strictObject({operation:e.literal("get"),settlementRequestId:e.uuid().optional(),data:En.optional(),purchase:e.strictObject({receiptId:e.uuid(),operationId:e.uuid()}).optional(),customerToken:fe.optional()}),e.strictObject({operation:e.literal("resume"),requestId:e.uuid(),customerToken:fe.optional()}),e.strictObject({operation:e.literal("submit"),...L,input:zn}),e.strictObject({operation:e.literal("back"),...L}),e.strictObject({operation:e.literal("shown"),...L}),e.strictObject({operation:e.literal("close"),...L}),e.strictObject({operation:e.literal("commit_segment"),...L,policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256)}),e.strictObject({operation:e.literal("review"),receiptId:e.uuid().optional(),customerToken:fe.optional()})]);export{I as a,Y as b,ee as c,P as d,Tn as e,Un as f,Ut as g,ot as h,M as i,Ke as j,ir as k,Mt as l,Tt as m,Nn as n,at as o,ct as p,Lt as q,lt as r,hr as s,Jt as t,Or as u,ln as v,wi as w,_i as x,Qt as y,Xt as z,Tr as A,Ur as B,Br as C,an as D,tn as E,nn as F,Lr as G,ae as H,ce as I,ue as J,le as K,bt as L,Hr as M,sn as N,Jr as O,Zr as P,Wr as Q,Ee as R,un as S,li as T,pi as U,di as V,In as W,On as X,Co as Y,Ao as Z,Dn as _,Yo as $};
1
+ import{a as ge}from"./chunk-ZGCKQWQ5.js";import{a as Le}from"./chunk-VYFSRHXM.js";import{D as Xe,F as be,G as Ye,K as H,L as J,M as Z,N as xe,O as et,R as Se,U as v,V as N,W as $,X as W,Y as Q,a as he,b as He,c as Je,ja as tt,ka as X,la as B,s as Ze,t as We,u as Qe}from"./chunk-N7YXDSQL.js";import{h as U}from"./chunk-R4FDIYMN.js";import{b as e}from"./chunk-VF6QMMEA.js";var nt={"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 ve(t){let r=Ye(t)??"en",n=r.split("-"),s=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(a=>["TW","HK","MO"].includes(a))?"zh-Hant":"zh-Hans":n[0]??"en",i=nt[s];return i?{locale:r,copy:i}:{locale:"en",copy:nt.en}}function Mt(t,r,n="zh-CN"){let s=He(r);return Je(t,r,ve(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:t%10**s===0?0:s,maximumFractionDigits:s})}function Tt(t,r="zh-CN"){let n=ve(r).locale;return t.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(t.percentOff/100):Mt(t.amountOffCents,t.currency,n)}var rt={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 Nn(t,r="zh-CN",n="month"){let s=ve(r),i=Tt(t.discount,s.locale);if(t.appliesTo?.type==="merchandise")return s.copy.merchandise.replace("{discount}",i);let a=t.duration.type==="repeating"?new Intl.NumberFormat(s.locale).format(t.duration.months):"",u=s.locale.split("-")[0]??"en",c=u==="zh"&&/(?:Hant|TW|HK|MO)/.test(s.locale)?"zh-Hant":u,f=t.duration.type==="repeating"&&n!=="month"?rt[c]??rt.en:t.duration.type==="repeating"&&t.duration.months===1?s.copy.repeatingOne??s.copy.repeating:s.copy[t.duration.type],g=t.duration.type==="repeating"?new Intl.NumberFormat(s.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(t.duration.months):"";return f.replace("{discount}",i).replace("{months}",a).replace("{period}",g)}var I=e.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(t=>t.split(".").every(r=>r.length>0&&!["__proto__","constructor","prototype"].includes(r)),"Reserved or empty variable path"),we=e.strictObject({type:e.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:e.boolean(),enum:e.array(e.string().max(255)).min(1).max(100).optional()}),Y=we.extend({type:e.enum([...we.shape.type.options,"array"]),items:we.optional()}).superRefine((t,r)=>{(t.type==="array"!=!!t.items||t.enum&&t.type!=="string"||t.items?.enum&&t.items.type!=="string")&&r.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),ee=Y.safeExtend({source:e.discriminatedUnion("type",[e.strictObject({type:e.literal("input")}),e.strictObject({type:e.literal("node")}),e.strictObject({type:e.enum(["parameter","attribute"]),key:I})])}),Mn=e.record(I,ee),Ie=e.record(I,I).refine(t=>Object.keys(t).length<=20);function P(t,r){return t?r===null?t.nullable:t.enum&&(typeof r!="string"||!t.enum.includes(r))?!1:t.type==="array"?Array.isArray(r)&&r.length<=100&&!!t.items&&r.every(n=>P(t.items,n)):["offering_version","reward","paywall_version"].includes(t.type)?typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===2&&r.type===t.type&&e.uuid().safeParse(r.id).success:t.type==="json"||(t.type==="strings"?Array.isArray(r)&&r.every(n=>typeof n=="string"):typeof r===t.type):!1}function Oe(t,r){return t.nullable&&!r.nullable?!1:r.type==="json"?!0:t.type!==r.type||r.enum&&(!t.enum||t.enum.some(n=>!r.enum.includes(n)))?!1:t.type!=="array"||!!t.items&&!!r.items&&Oe(t.items,r.items)}function te(t,r){let n={};for(let[s,i]of Object.entries(t)){let a=i.source,u=a.type==="input"?r.answers:a.type==="node"?r.results??{}:a.type==="parameter"?r.parameters:r.attributes,c=a.type==="parameter"||a.type==="attribute"?a.key:s,f=Object.hasOwn(u,c),g=u[c];if(a.type==="attribute"&&c.includes(".")&&(!f||c.startsWith("merchandise."))){g=u,f=!0;for(let l of c.split(".")){if(!g||typeof g!="object"||!Object.hasOwn(g,l)||Array.isArray(g)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=g.length)){f=!1;break}g=g[l]}}if(!(!f||g===void 0)){if(!P(i,g))throw new Error(`Invalid variable value: ${s}`);n[s]=g}}return n}function Tn(t,r){let n={};for(let[s,i]of Object.entries(t.writes??{})){if(!Object.hasOwn(r,s))throw new Error(`Node output is missing: ${s}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=r[s]}return n}function Un(t,r,n){let s=new Set(Object.values(r.writes??{}));for(let[i,a]of Object.entries(n))if(!s.has(i)||t[i]?.source.type!=="node"||!P(t[i],a))throw new Error(`Invalid node variable write: ${i}`);if(s.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var R=e.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(t=>t.split(".").every(r=>!["__proto__","constructor","prototype"].includes(r)),"Reserved value path"),E=e.discriminatedUnion("source",[e.strictObject({source:e.literal("literal"),value:v}),e.strictObject({source:e.literal("variable"),key:e.string().min(1).max(255),path:R.optional()})]);function it(t,r){if(!r)return t;for(let n of R.parse(r).split(".")){if(Array.isArray(t)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=t.length)return;t=t[Number(n)];continue}if(t===null||typeof t!="object"||!Object.hasOwn(t,n))return;t=Reflect.get(t,n)}return t}function Ut(t,r){if(t.source==="literal")return structuredClone(t.value);let n=te(r.declarations,r);if(!Object.hasOwn(n,t.key))throw new Error("Capability input is missing");return structuredClone(v.parse(it(n[t.key],t.path)))}function je(t,r){let n=[...r].sort((i,a)=>a.length-i.length).find(i=>t===i||t.startsWith(i+"."));if(!n)return null;let s=t===n?void 0:t.slice(n.length+1);return s&&!R.safeParse(s).success?null:{key:n,path:s}}function ke(t){let r=Object.values(t.strings.locales).flatMap(n=>Object.values(n));return H(t,n=>{n.type==="custom_html"&&r.push(...Object.values(n.html))}),[...new Set(r.flatMap(Qe))]}function ot(t){return ke(t).filter(r=>r.startsWith("variables.")).map(r=>r.slice(10))}function M(t){let r=JSON.stringify(t);if(r===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(r).length,s=!1;for(let i=0;i<r.length;i++){let a=r.charAt(i);if(s)a==="\\"?i++:a==='"'&&(s=!1);else if(a==='"')s=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let u=i;for(;i+1<r.length&&/[0-9.eE+-]/.test(r.charAt(i+1));)i++;let c=r.slice(u,i+1);if(!/[eE]/.test(c))continue;let[f="",g]=c.split(/[eE]/),l=f.replace(/^-/,""),w=l.replace(".","").length,K=(l.includes(".")?l.indexOf("."):w)+Number(g),y=K<=0?2-K+w:K>=w?K:w+1;n+=y+(f.startsWith("-")?1:0)-c.length}}return n}function F(t){let r=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function s(a,u){if(n(a))for(let[c,f]of Object.entries(a))c==="$elemMatch"?i(f,u):c==="$not"?s(f,u):c==="$all"&&Array.isArray(f)&&f.forEach(g=>s(g,u))}function i(a,u=""){if(n(a)){for(let[c,f]of Object.entries(a))if(["$and","$or","$nor"].includes(c)&&Array.isArray(f))f.forEach(g=>i(g,u));else if(c==="$not")i(f,u);else if(c==="$savedGroup"&&n(f))typeof f.attributeKey=="string"&&r.add(f.attributeKey);else if(!c.startsWith("$")){let g=u?`${u}.${c}`:c;r.add(g),s(f,g)}}}return i(t),[...r]}var Bt=e.enum(["active","inactive"]),Gt=e.preprocess((t,r)=>{let n=0;function s(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(u=>s(u,a+1));else if(i&&typeof i=="object")for(let[u,c]of Object.entries(i))["__proto__","constructor","prototype"].includes(u)&&r.addIssue({code:"custom",message:"Reserved merchandise attribute"}),s(c,a+1)}}return s(t,0),t},N),$t=e.strictObject({id:e.string().trim().min(1).max(255),name:e.string().trim().min(1).max(255),status:Bt,metadata:Gt}),rr=$t.extend({internal_id:e.uuid(),project_id:e.uuid(),environment_id:e.uuid(),created_at:e.iso.datetime({offset:!0}),updated_at:e.iso.datetime({offset:!0})}),ir=e.union([e.strictObject({id:e.string().trim().min(1).max(255)}),e.strictObject({internalId:e.uuid()})]),or=e.enum(["customer","merchandise","context"]),sr=e.enum(["system","stored","request"]),ar=e.enum(["customer","merchandise","mixed"]),st=t=>t==="merchandiseId"||t==="merchandise"||t.startsWith("merchandise.");function Ce(t,r={},n=new Set){if(F(t).some(st))return!0;for(let s of W(t)){if(n.has(s))continue;n.add(s);let i=r[s];if(i?.type==="list"&&st(i.attributeKey)||i?.type==="condition"&&Ce(i.condition,r,n))return!0}return!1}var fr=e.enum(["draft","active","paused","archived"]),at=e.discriminatedUnion("type",[e.object({type:e.literal("percent"),percentOff:e.number().min(1).max(100).multipleOf(.01)}).strict(),e.object({type:e.literal("amount"),amountOffCents:e.number().int().min(1).max(1e8),currency:he}).strict()]),ct=e.discriminatedUnion("type",[e.object({type:e.literal("once")}).strict(),e.object({type:e.literal("repeating"),months:e.number().int().min(1).max(36)}).strict(),e.object({type:e.literal("forever")}).strict()]),ut=[e.object({type:e.literal("all")}).strict(),e.object({type:e.literal("plans"),planIds:e.array(e.uuid()).min(1).max(50).refine(t=>new Set(t).size===t.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],qt=e.discriminatedUnion("type",[...ut,e.strictObject({type:e.literal("merchandise"),scope:e.discriminatedUnion("type",[e.strictObject({type:e.literal("all")}),e.strictObject({type:e.literal("selected"),merchandiseIds:e.array(e.uuid()).min(1).max(1e3).refine(t=>new Set(t).size===t.length,"Duplicate merchandise")}),e.strictObject({type:e.literal("condition"),condition:$})])})]),Lt=e.discriminatedUnion("type",[...ut,e.strictObject({type:e.literal("merchandise"),scope:e.strictObject({type:e.enum(["all","selected","condition"])})})]),Ht=e.strictObject({firstPurchaseOnly:e.boolean(),condition:$}),yr=e.object({name:e.string().trim().min(1).max(80),description:e.string().max(500),discount:at,duration:ct,nativeDiscountPolicy:ge.optional(),appliesTo:qt,eligibility:Ht,selfClaimEnabled:e.boolean().default(!1),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),totalLimit:e.number().int().min(1).max(1e6).nullable(),perCustomerLimit:e.number().int().min(1).max(10),grantWindowHours:e.number().int().min(1).max(2160)}).strict().refine(t=>!t.startsAt||!t.endsAt||Date.parse(t.endsAt)>Date.parse(t.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(t=>!Ce(t.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(t=>t.appliesTo.type!=="merchandise"||t.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(t=>t.appliesTo.type!=="merchandise"||!t.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),gr=e.object({code:e.string().trim().transform(t=>t.toUpperCase()).pipe(e.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:e.number().int().min(1).max(1e6).nullable(),expiresAt:e.iso.datetime().nullable(),firstPurchaseOnly:e.boolean(),minimumAmountCents:e.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:he.nullable()}).strict().refine(t=>t.minimumAmountCents===null==(t.minimumAmountCurrency===null),"Minimum amount requires its currency");var lt=e.object({id:e.uuid(),couponId:e.uuid(),status:e.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:e.iso.datetime(),expiresAt:e.iso.datetime(),coupon:e.object({name:e.string(),discount:at,duration:ct,nativeDiscountPolicy:ge.optional(),appliesTo:Lt}).strict()}).strict(),hr=e.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Jt=e.string().regex(/^[a-f0-9]{64}$/),Zt=Ze.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),pt=e.strictObject({couponDigests:e.record(e.uuid(),Jt),variables:e.record(be,e.record(e.uuid(),e.partialRecord(e.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),e.string()))),locales:e.record(be,We.extend({nodes:e.record(e.string(),e.strictObject({base:Zt})),plans:e.object({}).strict(),pickers:e.object({}).strict()}).omit({paywall:!0}))});var dt=e.enum(["funnel-run/1","funnel-process/1"]),Or="funnel-process/1";var Ae=v,Wt=["parameters","answers","results","variables"];function Qt(t){return Wt.some(r=>t===r||t.startsWith(r+"."))}function Xt(t){let r={};for(let[s,i]of Object.entries(te(t.declarations,t))){let a=s.split(".");if(a.some(f=>["__proto__","constructor","prototype"].includes(f)))throw new Error("Reserved result path");let u=r;for(let f of a.slice(0,-1)){Object.hasOwn(u,f)||(u[f]={});let g=u[f];if(!g||typeof g!="object"||Array.isArray(g))throw new Error("Ambiguous result path");u=g}let c=a.at(-1);if(c===void 0)throw new Error("Empty result path");u[c]=i}return{...Object.fromEntries(Object.entries(t.attributes).filter(([s])=>!Qt(s))),variables:r}}var ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var _e=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),mt=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),ft=B.refine(t=>new TextEncoder().encode(JSON.stringify(t)).byteLength<=8192,"Task data exceeds 8 KiB"),Re=e.record(_e,e.enum(["string","number","boolean","strings"])).refine(t=>Object.keys(t).length<=20,"Too many output fields"),Yt=E,yt=e.strictObject({type:e.literal("external_task"),endpointId:e.uuid(),taskKey:_e,inputs:e.record(_e,Yt).refine(t=>Object.keys(t).length<=20),outputs:Re}),gt=e.strictObject({maxAttempts:e.number().int().min(1).max(5),retryDelaySeconds:e.number().int().min(1).max(30),backoff:e.enum(["fixed","exponential"]),requestTimeoutSeconds:e.number().int().min(1).max(10),timeoutSeconds:e.number().int().min(1).max(300)}).refine(t=>t.requestTimeoutSeconds<=t.timeoutSeconds,"Request timeout exceeds action deadline");var Mr=e.strictObject({outcome:e.enum(["success","failure"]),data:ft});var Tr=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("signal"),runId:e.uuid(),nodeId:mt,eventName:ne,eventId:e.uuid(),data:ft}),e.strictObject({operation:e.literal("read_results"),runId:e.uuid()})]),Ur=e.strictObject({scope:U,runId:e.uuid(),eventId:e.uuid(),accepted:e.boolean()}),en=e.record(mt,Ae),Br=e.strictObject({scope:U,runId:e.uuid(),results:en});var tn=["id","externalUserId","createdAt","ageDays","subscription"],De=e.array(e.string().trim().min(1).max(40).refine(t=>!t.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(t=>new Set(t).size===t.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),re=e.intersection(N,e.looseObject({tags:De.optional()})).refine(t=>![...tn,"parameters","answers","results"].some(r=>Object.hasOwn(t,r)),"Reserved customer attribute"),ie=e.string().trim().max(80),oe=e.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),se=e.union([e.email().max(254),e.literal("")]),nn=e.string().trim().min(1).max(255).refine(t=>!/\p{Cc}/u.test(t),"Fingerprint must not contain control characters"),ht=e.string().trim().min(1).max(255).refine(t=>!t.startsWith("gg_guest_"),"Reserved guest identity namespace"),Lr=e.object({externalUserId:ht.optional(),name:ie.default(""),email:se.default(""),phone:oe.optional(),attributes:re.default({})}).strict().refine(t=>t.externalUserId!==void 0||t.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),ae=e.discriminatedUnion("type",[e.strictObject({type:e.literal("id"),value:e.uuid()}),e.strictObject({type:e.literal("externalUserId"),value:ht})]),ce=e.strictObject({name:ie.optional(),email:se.optional(),phone:oe.optional(),attributes:re.optional(),fingerprint:nn.optional()}),ue=t=>!t.customerData||t.customer?.type==="externalUserId",le="customerData requires an externalUserId customer",bt=e.object({id:e.uuid(),externalUserId:e.string().min(1).max(255).nullable(),name:ie,email:se,phone:oe.optional(),attributes:re,createdAt:e.iso.datetime()}).strict(),Hr=e.object({customer:bt,changed:e.boolean(),replayed:e.boolean()}).strict(),rn=e.discriminatedUnion("type",[e.object({type:e.literal("id"),value:e.uuid()}).strict(),e.object({type:e.literal("externalUserId"),value:e.string().trim().min(1).max(255)}).strict()]),on=e.object({name:ie.optional(),email:se.optional(),phone:oe.optional(),attributes:re.refine(t=>!Object.hasOwn(t,"tags"),"Use incremental tagChanges").optional(),removeAttributes:e.array(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(t=>!t.includes("tags")).optional(),tagChanges:e.strictObject({add:De,remove:De}).optional()}).strict().refine(t=>Object.keys(t).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),sn=e.object({lookup:rn}).strict(),Jr=sn.extend({requestId:e.uuid(),patch:on}).strict(),Zr=e.object({search:e.string().trim().max(200).default(""),tag:e.string().trim().max(40).default(""),planId:e.string().max(200).default(""),versionId:e.string().max(200).default(""),holdingStatus:e.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:e.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:e.union([e.iso.datetime(),e.literal("")]).default(""),createdUntil:e.union([e.iso.datetime(),e.literal("")]).default(""),offset:e.coerce.number().int().min(0).max(1e5).default(0),limit:e.coerce.number().int().min(1).max(100).default(50)}).strict(),Wr=e.object({customers:bt.array(),hasMore:e.boolean(),total:e.number().int().nonnegative().nullable(),evaluatedAt:e.iso.datetime()}).strict();var ti=e.enum(["local","remote"]),ze=e.strictObject({port:e.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:v.optional(),sticky:e.array(e.strictObject({expected:Q.nullable(),next:Q})).max(100),exposures:e.array(v).max(100),features:e.array(v).max(100)}),xt=e.strictObject({type:e.literal("evaluate"),receiptId:e.uuid(),environmentId:e.uuid(),policyRevision:e.number().int().nonnegative(),attributes:N,sticky:e.record(e.string(),Q)}),St=xt.extend({runId:e.uuid(),versionId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative()}),an=xt.omit({type:!0,receiptId:!0}).extend({type:e.literal("evaluate_segment")}),vt=e.strictObject({nodeId:e.string().min(1).max(64),result:ze}),wt=an.extend({runId:e.uuid(),versionId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),parameters:B,answers:X,variables:e.record(e.string(),v)});var Ee=e.discriminatedUnion("type",[e.strictObject({type:e.literal("literal"),value:v}),e.strictObject({type:e.literal("variable"),key:I,path:R.optional()}),e.strictObject({type:e.literal("feature"),featureKey:e.string().min(1).max(128)})]),cn=e.strictObject({requestId:e.uuid(),decisionId:e.uuid(),customerId:e.uuid(),externalUserId:e.string().min(1).max(255).nullable(),versionId:e.uuid(),receiptId:e.uuid(),value:v}),un={funnelId:e.uuid(),requestId:e.uuid(),customer:ae,customerData:ce.optional(),attributes:N.refine(t=>!["parameters","answers","results","variables"].some(r=>Object.hasOwn(t,r)),"parameters, answers, results and variables are reserved flow namespaces")},li=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("decide"),...un}).refine(ue,le),e.strictObject({operation:e.literal("read_decision"),decisionId:e.uuid()}),e.strictObject({operation:e.literal("evaluate_decision"),decisionId:e.uuid(),requestId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),receiptId:e.uuid(),policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256),result:ze}),e.strictObject({operation:e.literal("feature_config"),funnelId:e.uuid()}),e.strictObject({operation:e.literal("commit_decision_segment"),decisionId:e.uuid(),requestId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256),steps:e.array(vt).max(32),boundary:e.strictObject({nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()}).optional()}),e.strictObject({operation:e.literal("segment_configuration"),funnelId:e.uuid(),versionId:e.uuid()}),e.strictObject({operation:e.literal("configuration"),funnelId:e.uuid(),versionId:e.uuid().optional()}),e.strictObject({operation:e.literal("local_configuration"),funnelId:e.uuid()}),e.strictObject({operation:e.literal("report_used"),decisionId:e.uuid(),eventId:e.uuid(),occurredAt:e.iso.datetime({offset:!0}),reference:e.string().min(1).max(128).optional()})]),pi=e.strictObject({scope:U,decisionId:e.uuid(),requestId:e.uuid(),status:e.enum(["pending","completed","failed"]),decision:cn.nullable(),evaluation:e.discriminatedUnion("type",[St,wt]).optional()}).refine(t=>t.status==="completed"==(t.decision!==null)&&(!t.decision||t.decision.decisionId===t.decisionId&&t.decision.requestId===t.requestId),"Completed decisions carry their committed result"),di=e.strictObject({scope:U,decisionId:e.uuid(),eventId:e.uuid(),source:e.literal("caller_reported")});function ln(t,r=[]){let n=[];H(t,i=>{i.hidden&&n.push("Hidden components must not be delivered"),r.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let s=new Set(xe(t).map(i=>i.key));for(let[i,a]of Object.entries(t.strings.locales))for(let u of Object.keys(a))s.has(u)||n.push(`Unused string ${u} must not be delivered (${i})`);return n}function It(t){return t.hidden?null:t.type!=="stack"?t:{...t,children:t.children.flatMap(r=>It(r)??[])}}function pn(t){let r=t.pages.map(i=>{let a=It(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(xe({pages:r}).map(i=>i.key)),s=Object.fromEntries(Object.entries(t.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([u])=>n.has(u)))]));return{...t,pages:r,strings:{...t.strings,locales:s}}}function Ot(t,r=[]){let n=J.parse(structuredClone(pn(t))),s=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(s);for(let a of n.pages)if(!s(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=ln(n,r);if(i.length)throw new Error(i.join("; "));return n}var hi=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),couponId:e.uuid(),productBindingId:e.uuid(),storeOfferId:e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:e.enum(["introductory","promotional"])}),e.strictObject({action:e.literal("set_enabled"),id:e.uuid(),revision:e.number().int().nonnegative(),enabled:e.boolean()})]),bi=e.array(e.strictObject({id:e.uuid(),couponId:e.uuid(),productBindingId:e.uuid(),storeOfferId:e.string().min(1).max(255).nullable(),storeOfferType:e.enum(["introductory","promotional"]),enabled:e.boolean(),revision:e.number().int().nonnegative()})).max(500),Ke=e.strictObject({offerKind:e.enum(["none","introductory","promotional"]),offerId:e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:e.number().int().min(0).max(1e8),trialDays:e.number().int().min(1).max(730).nullable()}).superRefine((t,r)=>{(t.offerKind==="none"&&(t.offerId!==null||t.discountMinor!==0||t.trialDays!==null)||t.trialDays!==null&&t.discountMinor!==0)&&r.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),xi=e.record(e.uuid(),Ke).refine(t=>Object.keys(t).length<=20,"At most 20 native store selections");var wi=e.strictObject({schemaVersion:e.literal(1),renderKey:e.string().min(1).max(256),routeTemplate:e.string().startsWith("/").max(2048),selectors:e.array(e.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:e.array(e.number().int().min(0)).min(1),absent:e.array(e.number().int().min(0))}).superRefine((t,r)=>{let n=[...t.present,...t.absent];(new Set(t.selectors).size!==t.selectors.length||new Set(n).size!==n.length||n.length!==t.selectors.length||n.some(s=>s>=t.selectors.length))&&r.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),jt=e.strictObject({renderKey:e.string().min(1).max(256),routeKey:e.string().min(1).max(256),stateKey:e.string().min(1).max(256),documentKey:e.string().min(1).max(256),documentHash:e.string().regex(/^[a-f0-9]{64}$/),compositionKey:e.string().min(1).max(256),entryMode:e.enum(["hard","soft"]),match:e.strictObject({present:e.array(e.number().int().min(0)),absent:e.array(e.number().int().min(0))})});var dn=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Ve="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",mn=e.string().regex(new RegExp(`^${Ve}/${Ve}/${Ve}/manifest\\.json$`)),kt=e.strictObject({kind:e.literal("gcs-resumable"),url:e.url(),bucket:e.enum(dn),objectKey:mn,byteLength:e.number().int().positive(),expiresAt:e.iso.datetime()}).superRefine((t,r)=>{let n=new URL(t.url),s=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${t.bucket}/o`||[...s.keys()].some(a=>!i.includes(a)||s.getAll(a).length!==1)||s.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(s.get("upload_id")??"")||s.has("name")&&s.get("name")!==`app-manifests/${t.objectKey}`||s.has("upload_protocol")&&s.get("upload_protocol")!=="resumable"||s.has("ifGenerationMatch")&&s.get("ifGenerationMatch")!=="0")&&r.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var S=e.string().min(1).max(256),C=e.string().regex(/^[a-f0-9]{64}$/),pe=e.strictObject({versionId:e.uuid(),manifestDigest:C,sourceGraphDigest:C,pageKey:S,stateKey:S,documentKey:S,documentHash:C,elementKey:S.optional(),nodeId:S.optional(),contentHash:C.optional(),renderKey:S.optional()}),Ct=e.strictObject({pageKey:S,documentKey:S,expectedDocumentHash:C,renderKey:S.optional(),nodeId:S,elementKey:S,expectedContentHash:C,property:e.enum(["text","fontSize","color"]),value:e.union([e.string().max(4e3),e.number().finite()])}),_i=e.strictObject({versionId:e.uuid(),manifestDigest:C,sourceGraphDigest:C,pageKey:S,stateKey:S,documentKey:S,documentHash:C,renderKey:S.optional(),patches:e.array(Ct.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),fn=/^[a-z][a-z0-9-]{0,39}$/,q=e.string().regex(fn),Pe=e.enum(["web","ios","android"]),Ri=e.discriminatedUnion("action",[e.strictObject({action:e.literal("register"),requestId:e.uuid(),client:q,platform:Pe,label:e.string().trim().min(1).max(100),sha256:C,bytes:e.number().int().min(1),transferBytes:e.number().int().min(1)}),e.strictObject({action:e.literal("complete"),versionId:e.uuid()}),e.strictObject({action:e.literal("current"),versionId:e.uuid(),expectedCurrent:e.uuid().nullable()}),e.strictObject({action:e.literal("delivery"),enabled:e.boolean()}),e.strictObject({action:e.literal("changes"),versionId:e.uuid(),experimentId:e.uuid(),variationId:S,changesetId:e.uuid().nullable(),expectedRevision:C.nullable(),editorUrl:e.string().url().max(2048),patches:e.array(Ct).max(200)})]),Fe=e.strictObject({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),clientKey:q,platform:Pe,label:e.string(),sha256:C,bytes:e.number().int().positive(),objectKey:e.string(),state:e.enum(["uploading","ready","rejected"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),createdAt:e.string(),expiresAt:e.string(),readyAt:e.string().nullable(),summary:e.record(e.string(),e.json()),routeTree:e.json().nullable(),validation:e.record(e.string(),e.json())}),yn=e.strictObject({key:q,platform:Pe,currentId:e.uuid().nullable()}),Di=e.strictObject({rows:e.array(Fe).max(100),nextCursor:e.uuid().nullable(),clients:e.array(yn).max(20)}),Ne=e.strictObject({storedBytes:e.number().int().nonnegative(),reservedBytes:e.number().int().nonnegative(),chargedBytes:e.number().int().nonnegative(),versions:e.number().int().nonnegative(),objects:e.number().int().nonnegative(),orphanObjects:e.number().int().nonnegative(),missingReadyObjects:e.number().int().nonnegative(),unknownObjectSizes:e.number().int().nonnegative(),byteLimit:e.number().int().positive(),versionLimit:e.number().int().positive(),remainingBytes:e.number().int().nonnegative()}),zi=e.strictObject({asOf:e.iso.datetime({offset:!0}),reclamation:e.literal("manual-review-required"),buckets:e.strictObject({source:Ne,runtime:Ne,previews:Ne})}),Ei=e.strictObject({version:Fe,actorId:e.uuid(),claims:e.record(e.string(),e.json())}),Ki=e.strictObject({version:Fe,upload:kt.nullable()}),Vi=e.object({format:e.literal("indiana-route-state-index"),schemaVersion:e.literal(3),routes:e.array(e.object({routeKey:S,path:e.string(),documentKey:S,documentHash:C,initialStateKey:S,initialRenderKey:S})),renders:e.array(jt)}).loose().superRefine((t,r)=>{(!t.renders||t.routes.some(n=>!t.renders?.some(s=>s.renderKey===n.initialRenderKey&&s.routeKey===n.routeKey&&s.documentKey===n.documentKey&&s.stateKey===n.initialStateKey&&s.documentHash===n.documentHash&&s.entryMode==="hard")))&&r.addIssue({code:"custom",message:"Incomplete render catalog"})}),Ni=e.strictObject({rows:e.array(e.object({id:e.uuid(),name:e.string(),status:e.string(),variations:e.array(e.object({id:S,key:S,name:e.string().optional()}).loose())}).loose()),limited:e.boolean()}),Pi=e.strictObject({enabled:e.boolean(),allowedOrigins:e.array(e.string())});var At=e.strictObject({id:e.uuid(),name:e.string().trim().min(1).max(80),client:q,source:pe,event:e.enum(["screen_enter","button_click"]),cooldownSeconds:e.number().int().min(0).max(2592e3),behavior:e.literal("observe")}).superRefine((t,r)=>{t.event==="button_click"&&(!t.source.nodeId||!t.source.elementKey)&&r.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});var D={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},_t="00000000-0000-0000-0000-000000000000";var Rt=e.strictObject({type:e.literal("bundle"),paywall:E.optional(),offering:E.optional(),coupons:E,data:E}),gn=t=>e.strictObject({type:e.literal(t),id:e.uuid()}),Hi=e.strictObject({type:e.literal("bundle"),paywallVersionId:e.uuid().optional(),offeringVersionId:e.uuid().optional(),couponIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length),data:v});var Ji=e.strictObject({type:e.literal("bundle"),offering:gn("offering_version").nullable(),paywall:e.strictObject({versionId:e.uuid(),paywallId:e.uuid(),offeringVersionId:e.uuid()}).nullable(),coupons:e.array(lt).max(20),data:v});var Dt=e.union([e.string(),e.number().finite(),e.boolean(),e.null()]),hn=e.union([Dt,e.array(Dt).min(1).max(20)]),bn=e.record(R,hn).refine(t=>Object.keys(t).length<=10),zt=e.strictObject({path:R,type:e.enum(["string","number","boolean","strings"]),nullable:e.boolean().optional(),aggregation:e.enum(["count","exists"]).optional(),where:bn.optional()}).superRefine((t,r)=>{(t.aggregation==="count"&&t.type!=="number"||t.aggregation==="exists"&&t.type!=="boolean"||!t.aggregation&&t.where)&&r.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var xn=["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"],Et=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Sn=E,Kt=e.discriminatedUnion("type",[yt,e.strictObject({type:e.literal("claim_offer"),coupon:E}),e.strictObject({type:e.literal("event"),event:Et}),e.strictObject({type:e.literal("api"),operation:e.enum(xn),inputs:e.record(R,Sn).refine(t=>Object.keys(t).length<=40),outputs:e.record(Et,zt).refine(t=>Object.keys(t).length<=20)})]);var b=ne,vn=e.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),A={id:b,name:e.string().trim().min(1).max(80),position:e.strictObject({x:e.number().finite(),y:e.number().finite()}).optional()},wn={success:b,cancel:b,unavailable:b,failure:b},In=e.url().max(2048).refine(t=>{try{return new URL(t).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),On=e.enum(["same_window","new_window"]),jn=e.discriminatedUnion("type",[e.strictObject({...A,type:e.literal("entry"),next:b,triggers:e.array(At).max(20).refine(t=>new Set(t.map(r=>r.id)).size===t.length,"Entry trigger IDs must be unique").optional()}),e.strictObject({...A,type:e.literal("screen"),screenId:b,presentation:Xe,outputs:e.record(b,b),offering:e.discriminatedUnion("source",[e.strictObject({source:e.literal("variable"),key:I}),e.strictObject({source:e.literal("fixed"),versionId:e.uuid()})]).optional()}),e.strictObject({...A,type:e.literal("offering"),configuration:e.discriminatedUnion("source",[e.strictObject({source:e.literal("fixed"),versionId:e.uuid()}),e.strictObject({source:e.literal("feature"),featureKey:e.string().min(1).max(128)})]),writes:e.strictObject({value:I}),next:b}),e.strictObject({...A,type:e.literal("coupon"),couponId:e.uuid(),writes:e.strictObject({value:I}),next:b}),e.strictObject({...A,type:e.literal("coupons"),couponIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length),writes:e.strictObject({value:I}),next:b}),e.strictObject({...A,type:e.literal("output"),value:e.discriminatedUnion("type",[...Ee.options,Rt,e.strictObject({type:e.literal("selection"),screenId:b,offeringKey:I})])}),e.strictObject({...A,type:e.literal("condition"),cases:e.array(e.strictObject({condition:$,target:b})).min(1).max(50),default:b}),e.strictObject({...A,type:e.literal("feature"),featureKey:e.string().min(1).max(128),writes:e.strictObject({value:I}),next:b}),e.strictObject({...A,type:e.literal("split"),experimentId:e.uuid(),applyPageExperiment:e.literal(!0).optional(),routes:e.record(vn,b).refine(t=>Object.keys(t).length>=2&&Object.keys(t).length<=20),notParticipating:b}),e.strictObject({...A,type:e.literal("action"),...wn,execution:gt,action:Kt,writes:Ie.optional()}),e.strictObject({...A,type:e.literal("external_page"),appManifest:pe.optional(),url:In,openIn:On,opened:b,failed:b}),e.strictObject({...A,type:e.literal("end"),outcome:e.enum(["completed","closed","ineligible","failed"]),output:Ee.optional()}),e.strictObject({...A,type:e.literal("wait"),writes:Ie.optional(),wait:e.discriminatedUnion("type",[e.strictObject({type:e.literal("duration"),delaySeconds:e.number().int().min(1).max(2592e3),elapsed:b}),e.strictObject({type:e.literal("event"),eventName:b,outputs:Re,timeoutSeconds:e.number().int().min(1).max(2592e3),received:b,timeout:b})])})]),Me=e.strictObject({version:e.literal(5),entry:b,nodes:e.array(jn).min(1).max(D.flowNodes)}),Te=Me.superRefine((t,r)=>{kn(t,n=>r.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function de(t){switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[t.next];case"screen":return Object.values(t.outputs);case"condition":return[...t.cases.map(r=>r.target),t.default];case"split":return[...Object.values(t.routes),t.notParticipating];case"action":return[t.success,t.cancel,t.unavailable,t.failure];case"external_page":return[t.opened,t.failed];case"end":case"output":return[];case"wait":return t.wait.type==="duration"?[t.wait.elapsed]:[t.wait.received,t.wait.timeout]}}function kn(t,r){let n=[],s=new Map(t.nodes.map(l=>[l.id,l])),i=(l,w,K)=>{n.push(l),r?.({message:l,reason:w,path:K?["nodes",t.nodes.indexOf(K)]:[]})};s.size!==t.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(s.get(t.entry)?.type!=="entry"||t.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(t.nodes.filter(l=>l.type==="screen").length>D.pages||t.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>D.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of t.nodes){for(let w of de(l))w===t.entry&&i("An entry cannot be a transition target","entryTarget",l),s.has(w)||i(`Missing target ${w}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let u=new Set,c=new Set,f=new Set;function g(l){if(u.has(l)){i("Flow edges must not form a cycle","cycle",s.get(l));return}if(!(c.has(l)||!s.has(l))){u.add(l),f.add(l);for(let w of de(s.get(l)))g(w);u.delete(l),c.add(l)}}g(t.entry);for(let l of t.nodes)f.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}var Ue={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Vt(t,r,n){let s=[...r].sort((c,f)=>f.length-c.length),i=new Set,a=(c,f=!1)=>{let g=s.find(l=>c===l||f&&c.startsWith(l+"."));i.add(g??c)};if(t.type==="condition"){let c=n?.startsWith("case_")?Number(n.slice(5)):t.cases.length-1;for(let f of t.cases.slice(0,c+1))for(let g of F(f.condition))g.startsWith("variables.")&&a(g.slice(10),!0)}if(t.type==="screen"&&t.offering?.source==="variable"&&a(t.offering.key),t.type==="action"&&(t.action.type==="api"||t.action.type==="external_task"))for(let c of Object.values(t.action.inputs))c.source==="variable"&&a(c.key);t.type==="action"&&t.action.type==="claim_offer"&&t.action.coupon.source==="variable"&&a(t.action.coupon.key);let u=t.type==="output"?t.value:t.type==="end"?t.output:null;if(u?.type==="variable"&&a(u.key),u?.type==="bundle")for(let c of[u.paywall,u.offering,u.coupons,u.data])c?.source==="variable"&&a(c.key);return u?.type==="selection"&&a(u.offeringKey),[...i]}var G=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),me=t=>e.record(e.string(),v).refine(r=>M(r)<=t,"Funnel evidence exceeds its byte budget"),ko=e.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Ge=e.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),$e=e.discriminatedUnion("type",[e.strictObject({type:e.literal("flag"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("experiment"),id:e.uuid()}),e.strictObject({type:e.literal("saved_group"),id:e.uuid()}),e.strictObject({type:e.literal("config"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("constant"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("paywall_version"),id:e.uuid()}),e.strictObject({type:e.literal("offering_version"),id:e.uuid()}),e.strictObject({type:e.literal("reward"),id:e.uuid()})]),Co=e.strictObject({schemaVersion:e.literal(1),kind:Ge,selector:$e.nullable(),context:me(131072),contract:e.strictObject({version:e.number().int().positive(),evaluator:e.string().min(1).max(128),policyRevision:e.number().int().nonnegative()})}).refine(t=>M(t)<=131072,"Node input exceeds its byte budget"),Ao=e.strictObject({schemaVersion:e.literal(1),kind:Ge,outcome:e.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:me(131072),route:e.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:me(131072)}).refine(t=>M(t)<=131072,"Node result exceeds its byte budget"),_o=e.strictObject({schemaVersion:e.literal(1),operations:e.record(G,e.strictObject({attempts:e.number().int().nonnegative(),maxAttempts:e.number().int().min(1).max(5),deadlineAt:e.iso.datetime({offset:!0}),retryAt:e.iso.datetime({offset:!0}).nullable(),error:e.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:e.strictObject({type:G,id:e.uuid()}).nullable()}))}).refine(t=>M(t)<=65536,"Execution state exceeds its byte budget"),T={receiptId:e.uuid()},Be=e.iso.datetime({offset:!0}),Ro=e.discriminatedUnion("type",[e.strictObject({type:e.literal("node_entered"),details:e.strictObject({kind:Ge})}),e.strictObject({type:e.literal("presentation_shown"),details:e.strictObject({...T,source:e.literal("client"),occurredAt:Be.optional()})}),e.strictObject({type:e.literal("decision_accepted"),details:e.strictObject(T)}),e.strictObject({type:e.literal("signal_received"),details:e.strictObject({signalId:e.uuid(),nodeId:G,eventName:G,data:me(8192),source:e.literal("server"),occurredAt:Be})}),e.strictObject({type:e.literal("signal_consumed"),details:e.strictObject({...T,signalId:e.uuid()})}),e.strictObject({type:e.literal("wait_elapsed"),details:e.strictObject(T)}),e.strictObject({type:e.literal("wait_timeout"),details:e.strictObject(T)}),e.strictObject({type:e.literal("operation_completed"),details:e.strictObject({...T,operation:G,reference:e.strictObject({type:G,id:e.uuid()}).nullable()})}),e.strictObject({type:e.literal("execution_recovered"),details:e.strictObject({generation:e.number().int().positive(),reason:e.enum(["interrupted","expired_lease","delivery_failed"])})}),e.strictObject({type:e.literal("execution_failed"),details:e.strictObject({generation:e.number().int().positive(),code:e.string().regex(/^[a-z_]{1,64}$/)})}),e.strictObject({type:e.literal("run_completed"),details:e.strictObject({outcome:e.enum(["completed","ineligible","failed"])})}),e.strictObject({type:e.literal("run_closed"),details:e.strictObject({source:e.enum(["client","server","expiry"])})}),e.strictObject({type:e.literal("treatment_used"),details:e.strictObject({...T,source:e.enum(["client","server"]),occurredAt:Be,reference:e.string().min(1).max(128).optional()})})]);var _=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=e.discriminatedUnion("type",[e.strictObject({id:_,type:e.literal("owned"),publicData:pt.optional(),document:J.refine(t=>["page","popup","onboarding"].includes(t.surface)&&t.pages.length===1&&t.actions.every(r=>r.type==="event"&&!r.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),e.strictObject({id:_,type:e.literal("paywall"),paywallVersionId:e.uuid()})]),qe={executionContract:dt.optional(),kind:e.literal("funnel"),schemaVersion:e.literal(4),screens:e.array(Cn).max(D.pages),references:e.record(_,$e).refine(t=>Object.keys(t).length<=500),inputs:e.array(e.strictObject({variable:_,screenId:_,componentId:_,required:e.boolean()})).max(D.questions),variables:e.record(I,ee).refine(t=>Object.keys(t).length<=D.logicNodes),outputSchema:Y,execution:e.strictObject({runTimeoutSeconds:e.number().int().min(1).max(Ue.runTimeoutSeconds),maxTransitions:e.number().int().min(1).max(Ue.maxTransitions)})},Wo=e.strictObject({...qe,graph:Me});function An(t,r){let n=!1,s=(i,a)=>{let u=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(t.strings.locales).some(c=>c[i.text]?.includes("{{offer."))&&!(u&&r(u))&&(n=!0),i.type==="stack"&&i.children.forEach(c=>s(c,u))};for(let i of t.pages)s(i.root);return n}function ye(t){return Array.isArray(t)?t.some(ye):!t||typeof t!="object"?!1:Object.entries(t).some(([r,n])=>r==="productVersionId"?n===_t:ye(n))}function _n(t){let r=[],n=new Set(Object.values(t.references).flatMap(s=>s.type==="reward"?[s.id]:[]));for(let[s,i]of t.screens.entries()){if(i.type!=="owned")continue;let a;try{a=Ot(i.document)}catch(u){r.push({message:u instanceof Error?u.message:"Screen cannot be delivered",reason:"screen",path:["screens",s,"document"]});continue}for(let[u,c]of t.inputs.entries())c.screenId===i.id&&!Se(a,c.componentId)&&r.push({message:`Local Funnel input ${c.variable} targets hidden component ${c.componentId} on screen ${c.screenId}`,reason:"inputBinding",path:["inputs",u]})}for(let[s,i]of t.graph.nodes.entries()){let a=["graph","nodes",s],u=i.type==="screen"?t.screens.find(c=>c.id===i.screenId):void 0;u?.type==="owned"&&(u.document.actions.some(c=>typeof c.properties.templateKey=="string"&&c.properties.templateKey.startsWith("popup-coupon-"))&&r.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),An(u.document,c=>n.has(c))&&r.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&ye(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&ye(i.output.value))&&r.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return r}function Nt(t,r){for(let{message:n,reason:s,path:i}of _n(t))r.addIssue({code:"custom",message:n,path:i,params:{reason:s}})}function Pt(t,r){let n=(y,o,p=[])=>r.addIssue({code:"custom",message:y,path:p,params:{reason:o}}),s=Object.values(t.references),i=new Map(t.screens.map(y=>[y.id,y])),a=(y,o)=>s.some(p=>p.type===y&&("id"in p?p.id:p.key)===o);i.size!==t.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let u=t.graph.nodes.filter(y=>y.type==="screen");(u.length!==i.size||u.some(y=>!i.has(y.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let c=new Map,f=Object.keys(t.variables);f.some(y=>f.some(o=>y!==o&&o.startsWith(y+".")))&&n("Variable paths must not overlap","variable");function g(y,o){Object.hasOwn(t.variables,y)||n("Every produced variable needs a declaration","variable",["graph","nodes",t.graph.nodes.indexOf(o)]);let p=c.get(y)??new Set;p.add(o.id),c.set(y,p)}for(let[y,o]of t.graph.nodes.entries()){let p=["graph","nodes",y],O=o.type==="feature"?o.featureKey:o.type==="offering"&&o.configuration.source==="feature"?o.configuration.featureKey:o.type==="output"&&o.value.type==="feature"?o.value.featureKey:o.type==="end"&&o.output?.type==="feature"?o.output.featureKey:null;O&&!a("flag",O)&&n("Flag selectors require an explicit GB resource reference","feature",p);let j=o.type==="feature"||o.type==="offering"||o.type==="coupon"||o.type==="coupons"||o.type==="action"&&o.action.type==="api"?["value"]:o.type==="action"&&o.action.type==="external_task"?Object.keys(o.action.outputs):o.type==="wait"&&o.wait.type==="event"?Object.keys(o.wait.outputs):[],k="writes"in o?o.writes??{}:{};(j.length!==Object.keys(k).length||j.some(d=>!Object.hasOwn(k,d))||new Set(Object.values(k)).size!==Object.values(k).length)&&n("Node writes must map every named output exactly once","variable",p);for(let[d,x]of Object.entries(k)){g(x,o);let h=t.variables[x],m=o.type==="offering"?"offering_version":o.type==="coupon"?"reward":o.type==="action"&&o.action.type==="api"?"json":o.type==="action"&&o.action.type==="external_task"?o.action.outputs[d]:o.type==="wait"&&o.wait.type==="event"?o.wait.outputs[d]:void 0;(h?.source.type!=="node"||m&&h.type!==m)&&n("Node writer source or output type does not match declaration","variable",p)}if(o.type==="coupons"){let d=t.variables[o.writes.value];(d?.type!=="array"||d.items?.type!=="reward"||d.items.nullable||d.nullable)&&n("Coupons output requires a non-null Reward array","variable",p);for(let x of o.couponIds)a("reward",x)||n("Coupons require Reward references","coupon",p)}if(o.type==="split"&&!a("experiment",o.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",p),o.type==="coupon"&&!a("reward",o.couponId)&&n("Coupon selectors require a Reward reference","coupon",p),o.type==="action"&&o.action.type==="claim_offer"&&o.action.coupon.source==="literal"){let d=o.action.coupon.value;(!d||typeof d!="object"||Array.isArray(d)||d.type!=="reward"||typeof d.id!="string"||Object.keys(d).length!==2||!a("reward",d.id))&&n("Coupon claims require a Reward reference","coupon",p)}if(o.type==="offering"&&o.configuration.source==="fixed"&&!a("offering_version",o.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",p),o.type==="screen"&&o.offering?.source==="variable"&&t.variables[o.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",p),o.type==="action"&&o.action.type==="claim_offer"&&o.action.coupon.source==="variable"&&(t.variables[o.action.coupon.key]?.type!=="reward"||o.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",p),o.type==="screen"){let d=i.get(o.screenId);if(o.offering?.source==="fixed"&&!a("offering_version",o.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",p),d?.type==="paywall"&&o.offering&&n("Paywall owns its fixed Offering Version","offering",p),d?.type==="paywall"&&!a("paywall_version",d.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",p),d?.type==="owned"){let x=d.document.pages[0];if(!x){n("Owned screen requires a page","screen",p);continue}et(d.document).some(m=>!m.complete)&&n("Owned screens require complete local content","translations",p);let h=new Set(d.document.actions.map(m=>m.id));(h.size!==Object.keys(o.outputs).length||Object.keys(o.outputs).some(m=>!h.has(m)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",p),Z(x.root,m=>{!o.offering&&(m.type==="plan_picker"||(m.type==="stack"||m.type==="button")&&m.bind?.plan||m.type==="customer_data"&&["customer_plans","credit_packs"].includes(m.data.source))&&n("Product presentation requires an Offering Version","offering",p),m.type==="customer_data"&&Object.values(m.data.outputs??{}).some(V=>V!==void 0&&!h.has(V))&&n("Customer components require declared screen outcomes","componentOutput",p)})}}o.type==="end"&&["completed","ineligible"].includes(o.outcome)&&!o.output&&n("Completed and ineligible ends require a declared output","output",p),o.type==="end"&&o.output?.type==="literal"&&!P(t.outputSchema,o.output.value)&&n("Terminal output does not match outputSchema","output",p),o.type==="output"&&o.value.type==="literal"&&!P(t.outputSchema,o.value.value)&&n("Terminal output does not match outputSchema","output",p);let z=o.type==="output"?o.value:o.type==="end"?o.output:void 0;if(z?.type==="variable"&&!z.path){let d=t.variables[z.key];d&&!Oe(d,t.outputSchema)&&n("Variable output does not match outputSchema","output",p)}if(o.type==="screen"){let d=i.get(o.screenId);if(d?.type==="owned")for(let x of ke(d.document))(/^(input|params)\./.test(x)||x.startsWith("variables.")&&!je(x.slice(10),f))&&n("Screen values must reference registered variables","variable",p)}if(o.type==="condition")for(let d of o.cases){for(let x of W(d.condition))a("saved_group",x)||n("Conditions require explicit Saved Group references","savedGroup",p);for(let x of F(d.condition))x.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",p)}if(o.type==="output"&&o.value.type==="bundle"){t.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",p);for(let[d,x]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let h=o.value[d];if(h)if(h.source==="literal"){let m=d==="coupons"?h.value:[h.value];(!Array.isArray(m)||m.length>20||m.some(V=>!P({type:x,nullable:!1},V)||!a(x,V.id))||d==="coupons"&&new Set(m.map(V=>V.id)).size!==m.length)&&n("Bundle requires distinct scoped resource references",d==="coupons"?"coupon":d==="paywall"?"paywall":"offering",[...p,"value",d])}else{let m=t.variables[h.key];(h.path||!m||m.nullable||(d==="coupons"?m.type!=="array"||m.items?.type!=="reward"||m.items.nullable:m.type!==x))&&n("Bundle binding type does not match its slot","output",p)}}}}for(let[y,o]of t.graph.nodes.entries()){let p=o.type==="screen"?i.get(o.screenId):void 0,O=[...Vt(o,f),...p?.type==="owned"?ot(p.document).map(j=>je(j,f)?.key??j):[]];for(let j of new Set(O)){let x=function(h){if(h===o.id)return!0;if(d.has(h))return!1;d.add(h);let m=t.graph.nodes.find(Ft=>Ft.id===h);return m?(z.has(h)?m.type==="action"?[m.cancel,m.unavailable,m.failure]:m.type==="wait"&&m.wait.type==="event"?[m.wait.timeout]:[]:de(m)).some(x):!1};var K=x;if(!Object.hasOwn(t.variables,j)){n("Consumed variable is undeclared","variable",["graph","nodes",y]);continue}let k=t.variables[j];if(o.type==="screen"&&k.source.type==="input"&&t.inputs.some(h=>h.screenId===o.screenId&&h.variable===j)||k.source.type==="parameter"||k.source.type==="attribute")continue;let z=k.source.type==="input"?new Set(t.inputs.filter(h=>h.variable===j&&h.required).flatMap(h=>u.filter(m=>m.screenId===h.screenId).map(m=>m.id))):c.get(j)??new Set,d=new Set;(!z.size||x(t.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",y])}}(new Set(t.inputs.map(y=>y.variable)).size!==t.inputs.length||new Set(t.inputs.map(y=>`${y.screenId}:${y.componentId}`)).size!==t.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[y,o]of t.inputs.entries()){t.variables[o.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",y]);let p=i.get(o.screenId),O=p?.type==="owned"?Se(p.document,o.componentId):null;if((O?.type!=="stack"||!O.interaction||!["input","toggle","select","multiselect","tabs"].includes(O.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",y]),O?.type==="stack"&&O.interaction){let j=O.interaction.type==="toggle"?"boolean":O.interaction.type==="multiselect"?"strings":"string";t.variables[o.variable]?.type!==j&&n("Input variable type does not match component","inputBinding",["inputs",y]);let k=t.variables[o.variable]?.enum;k&&!O.children.filter(z=>!z.hidden).every(z=>k.includes(z.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",y])}}for(let[y,o]of Object.entries(t.variables))o.enum&&o.type!=="string"&&n("Only string variables support enum","variable",["variables",y]),o.source.type==="input"&&!t.inputs.some(p=>p.variable===y)&&n("Input variable requires a component binding","inputBinding",["variables",y]);let l=0,w=0;for(let y of t.screens)if(y.type==="owned"){for(let o of y.document.pages)Z(o.root,()=>{l++});w+=y.document.actions.length}(l>D.components||w>D.actions||M(t)>D.documentBytes)&&n("Funnel document exceeds its budget","budget")}var Rn=e.strictObject({...qe,graph:Te}).superRefine(Pt),Dn=e.strictObject({...qe,graph:Te,displayName:e.string().trim().min(1).max(80)}).superRefine(Pt),Qo=Dn.superRefine(Nt),Xo=Rn.superRefine(Nt),fe=e.string().regex(Le),L={requestId:e.uuid(),nodeId:_,visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),customerToken:fe.optional()},zn=e.discriminatedUnion("type",[e.strictObject({type:e.literal("screen"),output:_,answers:X,selection:e.record(_,e.union([e.string().max(200),e.boolean(),e.number().int().min(0).max(1e4)])).optional()}),e.strictObject({type:e.literal("paywall_quote"),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional(),actionId:_,productVersionId:e.uuid(),offerId:e.uuid().optional(),nativeOffer:Ke.optional(),predecessor:e.strictObject({operationId:e.uuid().nullable(),generation:e.number().int().positive()}).optional()}),e.strictObject({type:e.literal("paywall_confirm"),operationId:e.uuid()}),e.strictObject({type:e.literal("paywall_cancel"),operationId:e.uuid()}),e.strictObject({type:e.literal("client_action"),receiptId:e.uuid(),outcome:e.enum(["success","cancel","failure","opened","failed"])})]),En=e.object({nodeId:_,visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),components:e.record(_,e.object({resourceKey:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:e.number().int().min(1).max(1e5),after:tt.nullable(),filter:e.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(t=>Object.keys(t).length<=150)}).strict(),Yo=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("start"),funnelId:e.uuid(),requestId:e.uuid(),customer:ae.optional(),customerData:ce.optional(),locale:e.string().min(1).max(35),parameters:B}).refine(ue,le),e.strictObject({operation:e.literal("get"),settlementRequestId:e.uuid().optional(),data:En.optional(),purchase:e.strictObject({receiptId:e.uuid(),operationId:e.uuid()}).optional(),customerToken:fe.optional()}),e.strictObject({operation:e.literal("resume"),requestId:e.uuid(),customerToken:fe.optional()}),e.strictObject({operation:e.literal("submit"),...L,input:zn}),e.strictObject({operation:e.literal("back"),...L}),e.strictObject({operation:e.literal("shown"),...L}),e.strictObject({operation:e.literal("close"),...L}),e.strictObject({operation:e.literal("commit_segment"),...L,policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256)}),e.strictObject({operation:e.literal("review"),receiptId:e.uuid().optional(),customerToken:fe.optional()})]);export{I as a,Y as b,ee as c,P as d,Tn as e,Un as f,Ut as g,ot as h,M as i,Ke as j,ir as k,Mt as l,Tt as m,Nn as n,at as o,ct as p,Lt as q,lt as r,hr as s,Jt as t,Or as u,ln as v,wi as w,_i as x,Qt as y,Xt as z,Tr as A,Ur as B,Br as C,an as D,tn as E,nn as F,Lr as G,ae as H,ce as I,ue as J,le as K,bt as L,Hr as M,sn as N,Jr as O,Zr as P,Wr as Q,Ee as R,un as S,li as T,pi as U,di as V,In as W,On as X,Co as Y,Ao as Z,Dn as _,Yo as $};
@@ -0,0 +1 @@
1
+ import{b as r}from"./chunk-VF6QMMEA.js";var R=r.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),H=r.enum([...R.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),j=r.enum([...R.options,"stale_revision"]),v=r.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),x=r.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","IDENTITY_CONTEXT_CHANGED","CUSTOMER_BINDING_CONFLICT","RUN_CONTRACT_MISMATCH","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED","FUNNEL_PAUSED"]),y={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var S={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",CUSTOMER_SESSION_REQUIRED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",PURCHASE_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",PURCHASE_STORAGE_CONFLICT:"resolve_conflict",PURCHASE_STORAGE_INVALID:"recover_operation",EXECUTION_POLICY_REFUSED:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function g(e,o){if(e==="CONFLICT"&&o===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&o===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(S,e)){let n=S[e];return{retryable:n==="retry_same_request",recovery:n}}let t=R.safeParse(e);return t.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:y[t.data].recovery}:{retryable:!1,recovery:"contact_support"}}function z(e,o){let t=R.safeParse(e);if(t.success)return e==="CONFLICT"?[409,412,425].includes(o):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(o):e==="INVALID_REQUEST"?[400,405,415,422].includes(o):e==="NOT_CONFIGURED"?[501,503].includes(o):y[t.data].status===o;let n={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(n,e)&&(n[e]?.includes(o)??!1)}function b(e,o=Date.now()){if(e===null)return;let t=e.trim();if(/^\d+$/.test(t)){let a=Number(t);return Number.isSafeInteger(a)?a:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(t))return;let n=Date.parse(t);return Number.isFinite(n)?Math.max(0,Math.ceil((n-o)/1e3)):void 0}var L=r.object({retryable:r.boolean(),recovery:v,reason:x.optional(),retryAfterSeconds:r.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),P=r.object({requestId:r.uuid().optional(),error:r.object({code:r.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:r.string(),...L.partial().shape})}),Q=r.object({error:P.shape.error.extend({requestId:r.uuid().optional()})}),Y=r.object({error:r.string(),code:r.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:r.uuid(),...L.shape});function $(e,o,t={}){let n=g(e,o),a=t.reason==="RESULT_UNKNOWN"?"recover_operation":t.recovery??n.recovery,A=n.retryable&&t.retryable!==!1&&a!=="recover_operation",i=A?b(t.retryAfter??null):void 0;return{...n,retryable:A,recovery:a,...i===void 0?{}:{retryAfterSeconds:i},...t.reason?{reason:t.reason}:{}}}var V=r.enum(["sandbox","live"]),W=r.object({projectId:r.string().min(1),environment:V}).strict();var J=r.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),u=r.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),M=r.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let o=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return o==="-0"?"0":o}),p=u.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),C=r.string().min(1).max(64),B=r.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),D=r.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),ee=r.record(C,r.union([r.string().max(120),r.number().finite(),r.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([o,t])=>[o,String(t)]))),U=r.record(C,r.union([r.string().max(120),r.number().finite(),r.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),I=e=>{let o=e.startsWith("-");o&&(e=e.slice(1));let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");let a=BigInt(t)*BigInt("1000000")+BigInt(n.padEnd(6,"0"));return o?-a:a},h=r.array(r.object({upTo:p.nullable(),cost:u}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((o,t)=>{let n=e[t-1]?.upTo;return o.upTo!==null&&(t===0||n!=null&&I(o.upTo)>I(n))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),G=r.object({key:D,match:U,priority:r.number().int().default(0),cost:u.optional(),tiers:h.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),F=r.object({key:D,match:U,factor:p.optional(),add:M.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),q=r.object({units:p.default("1"),cost:u,tiers:h.optional(),dimensions:r.array(G).max(12).optional(),multipliers:r.array(F).max(4).optional()}).strict().superRefine((e,o)=>{let t=e.dimensions??[],n=e.multipliers??[];(new Set(t.map(i=>i.key)).size!==t.length||new Set(n.map(i=>i.key)).size!==n.length)&&o.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[i,s]of t.entries())for(let c of t.slice(i+1))Object.keys(s.match).length===Object.keys(c.match).length&&s.priority===c.priority&&!Object.keys(s.match).some(E=>c.match[E]!==void 0&&c.match[E]!==s.match[E])&&o.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let a=[e.cost,...(e.tiers??[]).map(i=>i.cost),...t.flatMap(i=>[...i.cost===void 0?[]:[i.cost],...(i.tiers??[]).map(s=>s.cost)])],A=I(e.units);for(let i of a)for(let s=0;s<1<<n.length;s++){let c=n.filter((N,_)=>s&1<<_);if(c.some((N,_)=>c.slice(_+1).some(d=>Object.keys(N.match).some(T=>d.match[T]!==void 0&&d.match[T]!==N.match[T]))))continue;let E=I(i),O=BigInt("1"),f=BigInt("0");for(let[N,_]of n.entries())s&1<<N&&(E*=I(_.factor??"1"),O*=BigInt("1000000"),f+=I(_.add??"0"));let l=(E+f*O)*BigInt("1000000"),m=O*A;(l<BigInt("0")||l%m!==BigInt("0")||l/m>BigInt("999999999999999999"))&&o.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),re=q.safeExtend({featureKey:B});export{R as a,v as b,x as c,z as d,P as e,$ as f,V as g,W as h,J as i,u as j,M as k,B as l,ee as m};
@@ -1 +1 @@
1
- import{a as G}from"./chunk-SJSCROSL.js";import{b as Z}from"./chunk-J4VTKRH7.js";import{a as j,b as Q,c as x}from"./chunk-FJGJQGYF.js";import{a as L,b as F,c as H,j as l}from"./chunk-XIP32WI7.js";import{b as e}from"./chunk-ZY4XAKNQ.js";var fe=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],K=e.enum(fe),W=e.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]);var o=e.string().min(1).max(200),c=e.iso.datetime({offset:!0}),i=e.number().int().nonnegative().max(1e8),y=e.string().regex(/^[A-Z]{3}$/),m=e.strictObject({priceId:e.uuid(),productVersionId:e.uuid(),productId:o,quantity:e.number().int().min(1).max(1e6),unitAmountMinor:i,totalMinor:i,interval:e.enum(["week","month","year","one_off"]),intervalCount:e.number().int().min(1).max(52),kind:e.enum(["fixed","prepaid","seat"]),tiers:e.strictObject({mode:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().positive().nullable(),unitAmountMinor:i,flatAmountMinor:i.optional()})).min(2).max(12)}).nullable()}),I=e.strictObject({grantId:e.uuid(),couponId:e.uuid(),amountMinor:i,applicationPolicy:G.optional(),applicableProductIds:e.array(o).min(1).max(100).optional(),terms:e.discriminatedUnion("type",[e.strictObject({type:e.literal("percent"),percentOff:e.number().gt(0).max(100)}),e.strictObject({type:e.literal("amount"),amountOffMinor:i,currency:y})]),duration:e.discriminatedUnion("type",[e.strictObject({type:e.literal("once")}),e.strictObject({type:e.literal("forever")}),e.strictObject({type:e.literal("repeating"),months:e.number().int().min(1).max(36)})])}),E={provider:e.literal("merchant"),executor:e.literal("merchant"),operationId:e.uuid(),customerId:e.uuid(),configurationRevision:e.number().int().nonnegative(),connectionRevision:e.number().int().nonnegative(),currency:y,expiresAt:c},ge=e.strictObject({...E,type:e.literal("purchase"),mode:e.enum(["payment","subscription"]),lineItems:e.array(m).min(1).max(100),catalogAmountMinor:i,nativeDiscountMinor:i.optional(),discount:I.nullable(),trialPeriodDays:e.number().int().min(1).max(730).nullable(),automaticTax:e.boolean()}).refine(t=>t.lineItems.reduce((n,r)=>n+r.totalMinor,0)===t.catalogAmountMinor&&(t.discount?.amountMinor??0)+(t.nativeDiscountMinor??0)<=t.catalogAmountMinor&&new Set(t.lineItems.map(n=>n.priceId)).size===t.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),S=e.strictObject({...E,type:e.literal("subscription_change"),subscriptionId:e.uuid(),merchantSubscriptionId:o,membershipId:e.uuid(),subscriptionAction:e.enum(["update","cancel","schedule","release"]),supersedesOperationId:e.uuid().nullable(),change:e.discriminatedUnion("type",[e.strictObject({type:e.literal("cancel")}),e.strictObject({type:e.literal("uncancel")}),e.strictObject({type:e.literal("plan"),productVersionId:e.uuid()}),e.strictObject({type:e.literal("seats"),licenseKey:o,quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("quantity"),internal_feature_id:e.uuid(),quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("billing_cycle"),billingCycleAnchor:e.union([e.literal("now"),e.number().int().positive()])})]),timing:e.enum(["immediate","renewal"]),effectiveAt:c,creditMinor:i,debitMinor:i,totalMinor:i,discountMinor:i,discount:I.nullable().optional(),taxMinor:i,proration:e.enum(["none","create_prorations","always_invoice"]),lineItems:e.array(m.extend({quantity:e.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:e.array(e.uuid()).max(100),sourceLineItems:e.array(m).min(1).max(100).optional()}),xe=e.strictObject({...E,type:e.literal("refund"),invoiceId:e.uuid(),merchantInvoiceId:o,amountMinor:i.refine(t=>t>0),mode:e.enum(["full","partial"]),entitlementAction:e.enum(["retain","revoke"]),cancelSubscriptions:e.array(o).max(100)}),Y=e.discriminatedUnion("type",[ge,S,xe]);function We(t){let n=new Set;if(t.type==="purchase")n.add(t.mode==="subscription"?"purchase.subscription":"purchase.one_time"),t.lineItems.some(r=>r.kind==="prepaid")&&n.add("purchase.prepaid"),t.lineItems.some(r=>r.kind==="seat")&&n.add("purchase.seats"),t.lineItems.some(r=>r.tiers!==null)&&n.add("purchase.tiered"),t.trialPeriodDays!==null&&n.add("purchase.trial"),t.automaticTax&&n.add("tax.automatic"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`);else if(t.type==="refund")n.add(`refund.${t.mode}`),t.entitlementAction==="revoke"&&n.add("refund.revoke");else{let r=t.change.type;r==="cancel"?n.add(`subscription.cancel.${t.timing}`):r==="uncancel"?n.add("subscription.resume"):r==="plan"?n.add(`subscription.plan.${t.timing}`):n.add(`subscription.${r}`),t.proration!=="none"&&n.add("subscription.proration"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`)}return[...n].sort()}function Xe(t){return t.type==="purchase"?t.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:t.type==="subscription_change"?["subscription.change.completed","subscription.change.closed","subscription.observed",...t.change.type==="cancel"||t.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...t.entitlementAction==="revoke"&&t.cancelSubscriptions.length?["subscription.observed"]:[]]}var ye=e.strictObject({phase:e.enum(["execution","payment","fulfillment","recording"]),code:L,reason:H.optional(),recovery:F,retryable:e.boolean()}).refine(t=>t.reason!=="RESULT_UNKNOWN"||!t.retryable&&t.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ie=e.strictObject({type:e.literal("redirect"),url:e.url().startsWith("https://"),expiresAt:c}),B={operationId:e.uuid(),customerId:e.uuid(),merchantExecutionId:o,fulfillmentStatus:e.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:e.enum(["not_ready","pending","accepted","failed"]),updatedAt:c,problem:ye.nullable(),pollAfterMs:e.number().int().min(1e3).max(6e4).nullable()},T=e.discriminatedUnion("type",[e.strictObject({...B,type:e.literal("purchase"),merchantOrderId:o.nullable(),paymentStatus:e.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:e.url().refine(t=>new URL(t).protocol==="https:").nullable(),checkoutExpiresAt:c.nullable()}).refine(t=>!t.checkoutUrl||["not_started","pending"].includes(t.paymentStatus)&&t.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),e.strictObject({...B,type:e.literal("subscription_change"),status:e.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:o,scheduledFor:c.nullable(),nextAction:Ie.optional()}).refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"A scheduled change retains its future effective time"),e.strictObject({...B,type:e.literal("refund"),status:e.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:o.nullable()}).refine(t=>t.status!=="succeeded"||t.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ee=e.discriminatedUnion("lookup",[e.strictObject({lookup:e.literal("found"),operationId:e.uuid(),customerId:e.uuid(),execution:T,readAt:c}),e.strictObject({lookup:e.literal("not_received"),operationId:e.uuid(),customerId:e.uuid(),execution:e.null(),readAt:c})]).refine(t=>!t.execution||t.execution.operationId===t.operationId&&t.execution.customerId===t.customerId,"Lookup must retain the original Customer and operation"),te=e.strictObject({merchantPriceId:o,productId:o,kind:e.enum(["fixed","prepaid"]),currency:y,unitAmountMinor:i,interval:e.enum(["one_off","day","week","month","year"]),intervalCount:e.number().int().min(1).max(100)}),X={merchantItemId:o,quantity:e.number().int().positive().max(1e6)},Se=t=>t.priceId??JSON.stringify(t.nativePrice),k=e.strictObject({merchantSubscriptionId:o,revision:e.number().int().positive(),status:e.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:c,periodEndsAt:c,cancelAtPeriodEnd:e.boolean(),hasDiscounts:e.boolean(),items:e.array(e.union([e.strictObject({...X,priceId:e.uuid()}),e.strictObject({...X,nativePrice:te})])).min(1).max(100)}).refine(t=>Date.parse(t.periodEndsAt)>Date.parse(t.periodStartsAt)&&new Set(t.items.map(Se)).size===t.items.length&&new Set(t.items.map(n=>n.merchantItemId)).size===t.items.length,"Subscription periods and Price identities must be unambiguous"),J={merchantLineId:o,quantity:e.number().int().nonnegative().max(1e6),subtotalMinor:e.number().int().min(-1e8).max(1e8),discountMinor:i,taxMinor:i,totalMinor:e.number().int().min(-1e8).max(2e8),periodStartsAt:c.nullable(),periodEndsAt:c.nullable()},R=e.strictObject({merchantInvoiceId:o,reason:e.enum(["renewal","adjustment"]).optional(),currency:y,subtotalMinor:i,discountMinor:i,taxMinor:i,totalMinor:i,paidMinor:i,periodStartsAt:c.nullable(),periodEndsAt:c.nullable(),lines:e.array(e.union([e.strictObject({...J,priceId:e.uuid()}),e.strictObject({...J,nativePrice:te})]).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&(t.subtotalMinor<0?t.discountMinor===0&&t.taxMinor===0:t.discountMinor<=t.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&t.discountMinor<=t.subtotalMinor&&t.paidMinor===t.totalMinor&&new Set(t.lines.map(n=>n.merchantLineId)).size===t.lines.length&&t.lines.reduce((n,r)=>n+r.subtotalMinor,0)===t.subtotalMinor&&t.lines.reduce((n,r)=>n+r.discountMinor,0)===t.discountMinor&&t.lines.reduce((n,r)=>n+r.taxMinor,0)===t.taxMinor&&t.lines.reduce((n,r)=>n+r.totalMinor,0)===t.totalMinor,"A paid Invoice retains the complete financial amounts"),p={eventId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:e.uuid(),occurredAt:c},Me=e.strictObject({...p,type:e.literal("purchase.completed"),operationId:e.uuid(),merchantOrderId:o,paymentStatus:e.enum(["paid","trialing","no_payment_required"]),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),_e=e.strictObject({...p,type:e.literal("purchase.closed"),operationId:e.uuid(),status:e.enum(["failed","expired","canceled"])}),Oe=e.strictObject({...p,type:e.literal("subscription.observed"),operationId:e.uuid().nullable(),subscription:k}),ve=e.strictObject({...p,type:e.literal("subscription.change.completed"),operationId:e.uuid(),status:e.enum(["scheduled","applied"]),scheduledFor:c.nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities"),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),Ae=e.strictObject({...p,type:e.literal("subscription.change.closed"),operationId:e.uuid(),merchantSubscriptionId:o,merchantInvoiceId:o.nullable(),status:e.enum(["failed","expired","canceled"])}),je=e.strictObject({...p,type:e.literal("invoice.paid"),merchantSubscriptionId:o.nullable(),invoice:R}),Pe=e.strictObject({...p,type:e.literal("refund.updated"),operationId:e.uuid().nullable(),merchantInvoiceId:o.optional(),merchantRefundId:o,status:e.enum(["pending","succeeded","failed"]),amountMinor:i.refine(t=>t>0),currency:y}),Je=[Me.refine(t=>t.paymentStatus!=="paid"||t.invoice!==null,"A paid purchase includes its Invoice"),_e,Oe.refine(t=>t.operationId===null||t.subscription.items.every(n=>"priceId"in n),"Native Price references cannot replace an operation's quoted Prices"),ve.refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),Ae,je,Pe.refine(t=>t.operationId!==null||t.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var z=e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}),rt=e.object({...z.shape,featureAllowances:e.record(e.uuid(),e.number().int().min(0).max(1e9)),creditAmounts:e.record(e.uuid(),l)}).strict(),it=e.object({id:e.uuid(),planVersionId:e.uuid(),slot:e.string(),cardRequired:e.boolean(),status:e.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),createdAt:e.iso.datetime()}).strict();var qe=e.number().int().positive().max(2e8),ne=e.number().int().min(0).max(2e8),re=t=>t.mode==="partial"==(t.amountMinor!==void 0),P=e.strictObject({mode:e.enum(["full","partial"]),amountMinor:qe.optional(),entitlementAction:e.enum(["retain","revoke"])});var a=e.string().min(1).max(200),b=e.iso.datetime({offset:!0}),f=ne,ie=f.maxValue,C=e.number().int().min(-ie).max(ie),q=e.string().regex(/^[A-Z]{3}$/),oe=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ae=e.array(a).max(100).refine(t=>new Set(t).size===t.length),Ce=e.strictObject({merchantProductId:a,merchantPriceId:a,productVersionId:e.uuid().optional(),quantity:l.refine(t=>/[1-9]/.test(t))}),w={subject:Q,operationId:e.uuid(),configurationRevision:oe,connectionRevision:oe,expiresAt:b},D=e.discriminatedUnion("action",[e.strictObject({...w,action:e.literal("purchase"),mode:e.enum(["payment","subscription"]),currency:q,items:e.array(Ce).min(1).max(100),offerRefs:ae}),e.strictObject({...w,action:e.literal("subscription_change"),currency:q,merchantSubscriptionId:a,change:S.shape.change,timing:S.shape.timing,proration:S.shape.proration,offerRefs:ae}),e.strictObject({...w,action:e.literal("refund"),currency:q,merchantInvoiceId:a,mode:P.shape.mode,amountMinor:P.shape.amountMinor,entitlementAction:P.shape.entitlementAction}).refine(re,"Only a partial refund chooses amountMinor")]),ht=e.strictObject({request:D,requestedAt:b,preparationAllowed:e.boolean()}).refine(t=>!t.preparationAllowed||Date.parse(t.requestedAt)<Date.parse(t.request.expiresAt),"Preparation authority must be within its original validity"),Be=e.strictObject({merchantLineId:a,merchantPriceId:a.nullable(),quantity:l.refine(t=>/[1-9]/.test(t)),subtotalMinor:C,discountMinor:f,taxMinor:f.nullable(),totalMinor:C.nullable()}).refine(t=>t.taxMinor===null==(t.totalMinor===null)&&(t.totalMinor===null||t.totalMinor===t.subtotalMinor-t.discountMinor+t.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),Ee=e.strictObject({items:e.array(e.strictObject({merchantPriceId:a,quantity:l.refine(t=>/[1-9]/.test(t)),interval:m.shape.interval.exclude(["one_off"]),intervalCount:m.shape.intervalCount,amountMinor:m.shape.totalMinor,amountAfterOfferMinor:m.shape.totalMinor.optional()})).min(1).max(100),trial:z.nullable(),discount:I.nullable().optional(),discountExpiresAt:b.nullable().optional(),initialAmountMinor:m.shape.totalMinor.optional()}),ce=e.strictObject({request:D,requestDigest:j,merchantQuoteId:a,quoteTermsDigest:j,termsVersion:a,sourceRevisions:e.array(e.strictObject({reference:a,revision:a})).max(100),observedAt:b,expiresAt:b,currency:q,automaticTax:e.boolean(),lines:e.array(Be).max(100),subscriptionTerms:Ee.nullable(),subtotalMinor:C,discountMinor:f,nativeDiscountMinor:f.optional(),discount:I.nullable().optional(),taxMinor:f.nullable(),totalMinor:C.nullable(),effectiveAt:b.nullable(),expectedEffects:e.array(e.strictObject({reference:a,kind:e.enum(["grant","revoke","change"]),description:e.string().min(1).max(1e3),quantity:l.nullable(),unit:a.nullable()}).refine(t=>t.quantity===null==(t.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:e.array(e.strictObject({reference:a,version:a,summary:e.string().min(1).max(1e3)})).max(20)}),U=ce.superRefine((t,n)=>{let{quoteTermsDigest:r,...u}=t,h=t.lines.every(s=>s.taxMinor!==null),A=t.request.action==="purchase"&&t.request.mode==="subscription"!=(t.subscriptionTerms!==null),be=t.subscriptionTerms!==null&&(t.request.action==="refund"||t.request.action==="subscription_change"&&t.request.change.type==="cancel");(t.requestDigest!==x(t.request)||t.quoteTermsDigest!==x(u)||t.currency!==t.request.currency||A||be||t.lines.length===0&&(t.request.action!=="subscription_change"||t.subtotalMinor!==0||t.discountMinor!==0||t.taxMinor!==0||t.totalMinor!==0)||Date.parse(t.observedAt)>=Date.parse(t.expiresAt)||Date.parse(t.expiresAt)>Date.parse(t.request.expiresAt)||new Set(t.lines.map(s=>s.merchantLineId)).size!==t.lines.length||new Set(t.sourceRevisions.map(s=>s.reference)).size!==t.sourceRevisions.length||new Set(t.requiredConsents.map(s=>s.reference)).size!==t.requiredConsents.length||t.subtotalMinor!==t.lines.reduce((s,g)=>s+g.subtotalMinor,0)||t.discountMinor!==t.lines.reduce((s,g)=>s+g.discountMinor,0)||t.taxMinor!==null!==h||!h&&!t.automaticTax||t.taxMinor===null!=(t.totalMinor===null)||h&&(t.taxMinor!==t.lines.reduce((s,g)=>s+g.taxMinor,0)||t.totalMinor!==t.subtotalMinor-t.discountMinor+t.taxMinor)||t.request.action!=="subscription_change"&&(t.subtotalMinor<0||t.totalMinor!==null&&t.totalMinor<0)||t.request.action==="refund"&&(t.taxMinor===null||t.totalMinor===null||t.totalMinor<=0||t.request.mode==="partial"&&t.totalMinor!==t.request.amountMinor))&&n.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function bt(t,n,r,u){return t.request.operationId===n&&t.request.action===r&&t.currency===u}function ft(t){return x(D.parse(t))}function gt(t){return x(ce.omit({quoteTermsDigest:!0}).parse(t))}var Te=e.strictObject({quoteTermsDigest:j,consents:e.array(e.strictObject({reference:a,version:a})).max(20)});function xt(t){return{quoteTermsDigest:t.quoteTermsDigest,consents:t.requiredConsents.map(({reference:n,version:r})=>({reference:n,version:r}))}}var ke=Te.extend({operationId:e.uuid()}).refine(t=>new Set(t.consents.map(n=>n.reference)).size===t.consents.length);function yt(t,n){let r=U.parse(t),u=ke.parse(n);return u.operationId===r.request.operationId&&u.quoteTermsDigest===r.quoteTermsDigest&&u.consents.length===r.requiredConsents.length&&r.requiredConsents.every(h=>u.consents.some(A=>A.reference===h.reference&&A.version===h.version))}var M=3,Ot="/integrations/indiana",vt="X-Indiana-Merchant-Bridge-Version",Re=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],ze=e.enum(Re),At={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},$=e.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),ue=e.string().regex(/^[A-Za-z0-9_-]{1,64}$/),we=e.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>"AEIMQUYcgkosw048".includes(t.at(-1)),"Use canonical base64url for a 32-byte key"),De=e.strictObject({keyId:ue,signingSecret:we}),Ue=e.string().max(300).superRefine((t,n)=>{try{let r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.port&&r.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(r.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(r.hostname))throw new Error("invalid origin")}catch{n.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(t=>new URL(t).origin),me=e.array(ze).max(10).refine(t=>new Set(t).size===t.length,"Capabilities must be unique"),V=e.strictObject({bridgeVersion:e.literal(M),projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),capabilities:me,catalog:e.enum(["endpoint","static","none"]),billingEvents:e.array(W).max(7),profiles:e.array(K).max(32).refine(t=>new Set(t).size===t.length,"Profiles must be unique")}).superRefine((t,n)=>{let r=u=>t.capabilities.includes(u);r("catalog")!==(t.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(r("billing_records")!==t.billingEvents.length>0||new Set(t.billingEvents).size!==t.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),de=e.strictObject({origin:Ue,requiredCapabilities:me}),$e=e.strictObject({revision:e.number().int().nonnegative(),checkedAt:e.iso.datetime(),outcome:e.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:e.strictObject({ping:e.enum(["passed","failed","not_checked"]),authentication:e.enum(["passed","failed","not_checked"]),catalog:e.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:V.nullable()}).superRefine((t,n)=>{t.outcome==="valid"!=(t.manifest!==null)&&n.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),jt=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),execution:e.enum(["indiana","record_only"]),accountId:e.string().nullable(),revision:e.number().int().nonnegative(),authentication:e.strictObject({keyId:ue}).nullable(),secretStoreConfigured:e.boolean().optional(),connection:de.nullable(),check:$e.nullable()});var se=e.strictObject({projectId:e.uuid(),environmentId:e.uuid()}),Pt=e.discriminatedUnion("action",[se.extend({action:e.literal("save"),revision:e.number().int().nonnegative(),connection:de,authentication:De.optional()}),se.extend({action:e.literal("check"),revision:e.number().int().nonnegative()})]),_=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"])});function qt(t){return e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:$,scope:_,data:t})}var le=e.strictObject({nativeUserId:e.string().min(1).max(128),session:Z.strict()}),pe=e.strictObject({nativeUserId:e.string().min(1).max(128),presentation:e.strictObject({customerId:e.uuid(),decisionId:e.uuid(),offeringVersionId:e.uuid(),paywallVersionId:e.uuid(),variant:e.string().min(1).max(128)}).nullable()}),he=e.strictObject({decisionId:e.uuid(),eventId:e.uuid()}),O=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),Ct=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:e.string().min(1).max(64),scope:_,error:e.strictObject({code:e.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:e.string().min(1).max(500),retryable:e.boolean(),recovery:e.string().min(1).max(80)})});var zt=e.strictObject({scope:_,operationId:e.uuid(),customerId:e.uuid(),confirmedAt:e.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:e.boolean(),instruction:Y,merchantTerms:U.optional()}).refine(t=>t.operationId===t.instruction.operationId&&t.customerId===t.instruction.customerId&&(!t.merchantTerms||t.merchantTerms.request.operationId===t.operationId&&t.merchantTerms.request.subject.customerId===t.customerId&&t.merchantTerms.request.action===t.instruction.type&&t.merchantTerms.currency===t.instruction.currency&&Object.entries(t.scope).every(([n,r])=>t.merchantTerms.request.subject.scope[n]===r)),"Authority must refer to the original Customer and operation"),N=T,d=e.string().min(1).max(120),Ve=e.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Ne=e.strictObject({revision:d,updatedAt:e.iso.datetime(),provider:e.literal("merchant"),items:e.array(e.strictObject({merchantProductId:d,productVersionId:e.uuid(),name:e.string().min(1).max(255),kind:e.enum(["subscription","credit_pack"]),merchantPriceId:d,currency:e.string().regex(/^[a-z]{3}$/),amountMinor:e.number().int().nonnegative().max(1e8),interval:e.enum(["one_time","month","year"]),intervalCount:e.literal(1),includedCredits:e.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:e.enum(["none","month"]),creditPolicyId:d,available:e.boolean()}).superRefine((t,n)=>{(t.kind==="credit_pack"&&(t.interval!=="one_time"||t.creditReset!=="none")||t.kind==="subscription"&&t.interval==="one_time"||t.available&&t.amountMinor===0)&&n.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Le=e.strictObject({customerId:e.uuid(),revision:e.string().min(1).max(128),observedAt:e.iso.datetime(),subscriptions:e.array(e.strictObject({merchantSubscriptionId:d,merchantProductId:d,productVersionId:e.uuid().nullable(),status:e.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:e.iso.datetime().nullable(),currentPeriodEndsAt:e.iso.datetime().nullable(),cancelAtPeriodEnd:e.boolean(),scheduledChange:e.strictObject({effectiveAt:e.iso.datetime(),merchantProductId:d}).nullable()})).max(100),purchaseHistory:e.strictObject({complete:e.boolean(),hasPaidPurchase:e.boolean(),lastPaidAt:e.iso.datetime().nullable()}),balances:e.array(e.strictObject({bucketId:d,key:d,available:Ve,expiresAt:e.iso.datetime().nullable(),nextResetAt:e.iso.datetime().nullable()})).max(100)}),v=e.strictObject({}),Fe={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":v,"session.create":v,"catalog.read":v,"customer.commerce.read":v,"presentation.resolve":v,"presentation.report":he,"purchase.execute":O,"operation.read":O,"subscription.change":O,"refund.execute":O},wt={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":V,"session.create":le,"catalog.read":Ne,"customer.commerce.read":Le,"presentation.resolve":pe,"presentation.report":e.strictObject({queued:e.literal(!0)}),"purchase.execute":N,"operation.read":ee,"subscription.change":N,"refund.execute":N},Dt=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),scope:_,command:$,data:e.unknown()}).superRefine((t,n)=>{Fe[t.command].safeParse(t.data).success||n.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});export{ge as a,S as b,xe as c,We as d,Xe as e,ye as f,T as g,ee as h,p as i,Je as j,z as k,qe as l,ne as m,re as n,P as o,ht as p,U as q,bt as r,ft as s,gt as t,Te as u,xt as v,yt as w,M as x,Ot as y,vt as z,Re as A,At as B,De as C,Ue as D,V as E,_ as F,qt as G,le as H,pe as I,he as J,O as K,Ct as L,zt as M,N,Le as O,Fe as P,wt as Q,Dt as R};
1
+ import{a as G}from"./chunk-ZGCKQWQ5.js";import{b as Z}from"./chunk-VYFSRHXM.js";import{a as j,b as Q,c as x}from"./chunk-MIBRUDIS.js";import{a as L,b as F,c as H,j as l}from"./chunk-R4FDIYMN.js";import{b as e}from"./chunk-VF6QMMEA.js";var fe=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],K=e.enum(fe),W=e.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]);var o=e.string().min(1).max(200),c=e.iso.datetime({offset:!0}),i=e.number().int().nonnegative().max(1e8),y=e.string().regex(/^[A-Z]{3}$/),m=e.strictObject({priceId:e.uuid(),productVersionId:e.uuid(),productId:o,quantity:e.number().int().min(1).max(1e6),unitAmountMinor:i,totalMinor:i,interval:e.enum(["week","month","year","one_off"]),intervalCount:e.number().int().min(1).max(52),kind:e.enum(["fixed","prepaid","seat"]),tiers:e.strictObject({mode:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().positive().nullable(),unitAmountMinor:i,flatAmountMinor:i.optional()})).min(2).max(12)}).nullable()}),I=e.strictObject({grantId:e.uuid(),couponId:e.uuid(),amountMinor:i,applicationPolicy:G.optional(),applicableProductIds:e.array(o).min(1).max(100).optional(),terms:e.discriminatedUnion("type",[e.strictObject({type:e.literal("percent"),percentOff:e.number().gt(0).max(100)}),e.strictObject({type:e.literal("amount"),amountOffMinor:i,currency:y})]),duration:e.discriminatedUnion("type",[e.strictObject({type:e.literal("once")}),e.strictObject({type:e.literal("forever")}),e.strictObject({type:e.literal("repeating"),months:e.number().int().min(1).max(36)})])}),E={provider:e.literal("merchant"),executor:e.literal("merchant"),operationId:e.uuid(),customerId:e.uuid(),configurationRevision:e.number().int().nonnegative(),connectionRevision:e.number().int().nonnegative(),currency:y,expiresAt:c},ge=e.strictObject({...E,type:e.literal("purchase"),mode:e.enum(["payment","subscription"]),lineItems:e.array(m).min(1).max(100),catalogAmountMinor:i,nativeDiscountMinor:i.optional(),discount:I.nullable(),trialPeriodDays:e.number().int().min(1).max(730).nullable(),automaticTax:e.boolean()}).refine(t=>t.lineItems.reduce((n,r)=>n+r.totalMinor,0)===t.catalogAmountMinor&&(t.discount?.amountMinor??0)+(t.nativeDiscountMinor??0)<=t.catalogAmountMinor&&new Set(t.lineItems.map(n=>n.priceId)).size===t.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),S=e.strictObject({...E,type:e.literal("subscription_change"),subscriptionId:e.uuid(),merchantSubscriptionId:o,membershipId:e.uuid(),subscriptionAction:e.enum(["update","cancel","schedule","release"]),supersedesOperationId:e.uuid().nullable(),change:e.discriminatedUnion("type",[e.strictObject({type:e.literal("cancel")}),e.strictObject({type:e.literal("uncancel")}),e.strictObject({type:e.literal("plan"),productVersionId:e.uuid()}),e.strictObject({type:e.literal("seats"),licenseKey:o,quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("quantity"),internal_feature_id:e.uuid(),quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("billing_cycle"),billingCycleAnchor:e.union([e.literal("now"),e.number().int().positive()])})]),timing:e.enum(["immediate","renewal"]),effectiveAt:c,creditMinor:i,debitMinor:i,totalMinor:i,discountMinor:i,discount:I.nullable().optional(),taxMinor:i,proration:e.enum(["none","create_prorations","always_invoice"]),lineItems:e.array(m.extend({quantity:e.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:e.array(e.uuid()).max(100),sourceLineItems:e.array(m).min(1).max(100).optional()}),xe=e.strictObject({...E,type:e.literal("refund"),invoiceId:e.uuid(),merchantInvoiceId:o,amountMinor:i.refine(t=>t>0),mode:e.enum(["full","partial"]),entitlementAction:e.enum(["retain","revoke"]),cancelSubscriptions:e.array(o).max(100)}),Y=e.discriminatedUnion("type",[ge,S,xe]);function We(t){let n=new Set;if(t.type==="purchase")n.add(t.mode==="subscription"?"purchase.subscription":"purchase.one_time"),t.lineItems.some(r=>r.kind==="prepaid")&&n.add("purchase.prepaid"),t.lineItems.some(r=>r.kind==="seat")&&n.add("purchase.seats"),t.lineItems.some(r=>r.tiers!==null)&&n.add("purchase.tiered"),t.trialPeriodDays!==null&&n.add("purchase.trial"),t.automaticTax&&n.add("tax.automatic"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`);else if(t.type==="refund")n.add(`refund.${t.mode}`),t.entitlementAction==="revoke"&&n.add("refund.revoke");else{let r=t.change.type;r==="cancel"?n.add(`subscription.cancel.${t.timing}`):r==="uncancel"?n.add("subscription.resume"):r==="plan"?n.add(`subscription.plan.${t.timing}`):n.add(`subscription.${r}`),t.proration!=="none"&&n.add("subscription.proration"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`)}return[...n].sort()}function Xe(t){return t.type==="purchase"?t.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:t.type==="subscription_change"?["subscription.change.completed","subscription.change.closed","subscription.observed",...t.change.type==="cancel"||t.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...t.entitlementAction==="revoke"&&t.cancelSubscriptions.length?["subscription.observed"]:[]]}var ye=e.strictObject({phase:e.enum(["execution","payment","fulfillment","recording"]),code:L,reason:H.optional(),recovery:F,retryable:e.boolean()}).refine(t=>t.reason!=="RESULT_UNKNOWN"||!t.retryable&&t.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ie=e.strictObject({type:e.literal("redirect"),url:e.url().startsWith("https://"),expiresAt:c}),B={operationId:e.uuid(),customerId:e.uuid(),merchantExecutionId:o,fulfillmentStatus:e.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:e.enum(["not_ready","pending","accepted","failed"]),updatedAt:c,problem:ye.nullable(),pollAfterMs:e.number().int().min(1e3).max(6e4).nullable()},T=e.discriminatedUnion("type",[e.strictObject({...B,type:e.literal("purchase"),merchantOrderId:o.nullable(),paymentStatus:e.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:e.url().refine(t=>new URL(t).protocol==="https:").nullable(),checkoutExpiresAt:c.nullable()}).refine(t=>!t.checkoutUrl||["not_started","pending"].includes(t.paymentStatus)&&t.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),e.strictObject({...B,type:e.literal("subscription_change"),status:e.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:o,scheduledFor:c.nullable(),nextAction:Ie.optional()}).refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"A scheduled change retains its future effective time"),e.strictObject({...B,type:e.literal("refund"),status:e.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:o.nullable()}).refine(t=>t.status!=="succeeded"||t.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ee=e.discriminatedUnion("lookup",[e.strictObject({lookup:e.literal("found"),operationId:e.uuid(),customerId:e.uuid(),execution:T,readAt:c}),e.strictObject({lookup:e.literal("not_received"),operationId:e.uuid(),customerId:e.uuid(),execution:e.null(),readAt:c})]).refine(t=>!t.execution||t.execution.operationId===t.operationId&&t.execution.customerId===t.customerId,"Lookup must retain the original Customer and operation"),te=e.strictObject({merchantPriceId:o,productId:o,kind:e.enum(["fixed","prepaid"]),currency:y,unitAmountMinor:i,interval:e.enum(["one_off","day","week","month","year"]),intervalCount:e.number().int().min(1).max(100)}),X={merchantItemId:o,quantity:e.number().int().positive().max(1e6)},Se=t=>t.priceId??JSON.stringify(t.nativePrice),k=e.strictObject({merchantSubscriptionId:o,revision:e.number().int().positive(),status:e.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:c,periodEndsAt:c,cancelAtPeriodEnd:e.boolean(),hasDiscounts:e.boolean(),items:e.array(e.union([e.strictObject({...X,priceId:e.uuid()}),e.strictObject({...X,nativePrice:te})])).min(1).max(100)}).refine(t=>Date.parse(t.periodEndsAt)>Date.parse(t.periodStartsAt)&&new Set(t.items.map(Se)).size===t.items.length&&new Set(t.items.map(n=>n.merchantItemId)).size===t.items.length,"Subscription periods and Price identities must be unambiguous"),J={merchantLineId:o,quantity:e.number().int().nonnegative().max(1e6),subtotalMinor:e.number().int().min(-1e8).max(1e8),discountMinor:i,taxMinor:i,totalMinor:e.number().int().min(-1e8).max(2e8),periodStartsAt:c.nullable(),periodEndsAt:c.nullable()},R=e.strictObject({merchantInvoiceId:o,reason:e.enum(["renewal","adjustment"]).optional(),currency:y,subtotalMinor:i,discountMinor:i,taxMinor:i,totalMinor:i,paidMinor:i,periodStartsAt:c.nullable(),periodEndsAt:c.nullable(),lines:e.array(e.union([e.strictObject({...J,priceId:e.uuid()}),e.strictObject({...J,nativePrice:te})]).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&(t.subtotalMinor<0?t.discountMinor===0&&t.taxMinor===0:t.discountMinor<=t.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&t.discountMinor<=t.subtotalMinor&&t.paidMinor===t.totalMinor&&new Set(t.lines.map(n=>n.merchantLineId)).size===t.lines.length&&t.lines.reduce((n,r)=>n+r.subtotalMinor,0)===t.subtotalMinor&&t.lines.reduce((n,r)=>n+r.discountMinor,0)===t.discountMinor&&t.lines.reduce((n,r)=>n+r.taxMinor,0)===t.taxMinor&&t.lines.reduce((n,r)=>n+r.totalMinor,0)===t.totalMinor,"A paid Invoice retains the complete financial amounts"),p={eventId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:e.uuid(),occurredAt:c},Me=e.strictObject({...p,type:e.literal("purchase.completed"),operationId:e.uuid(),merchantOrderId:o,paymentStatus:e.enum(["paid","trialing","no_payment_required"]),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),_e=e.strictObject({...p,type:e.literal("purchase.closed"),operationId:e.uuid(),status:e.enum(["failed","expired","canceled"])}),Oe=e.strictObject({...p,type:e.literal("subscription.observed"),operationId:e.uuid().nullable(),subscription:k}),ve=e.strictObject({...p,type:e.literal("subscription.change.completed"),operationId:e.uuid(),status:e.enum(["scheduled","applied"]),scheduledFor:c.nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities"),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),Ae=e.strictObject({...p,type:e.literal("subscription.change.closed"),operationId:e.uuid(),merchantSubscriptionId:o,merchantInvoiceId:o.nullable(),status:e.enum(["failed","expired","canceled"])}),je=e.strictObject({...p,type:e.literal("invoice.paid"),merchantSubscriptionId:o.nullable(),invoice:R}),Pe=e.strictObject({...p,type:e.literal("refund.updated"),operationId:e.uuid().nullable(),merchantInvoiceId:o.optional(),merchantRefundId:o,status:e.enum(["pending","succeeded","failed"]),amountMinor:i.refine(t=>t>0),currency:y}),Je=[Me.refine(t=>t.paymentStatus!=="paid"||t.invoice!==null,"A paid purchase includes its Invoice"),_e,Oe.refine(t=>t.operationId===null||t.subscription.items.every(n=>"priceId"in n),"Native Price references cannot replace an operation's quoted Prices"),ve.refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),Ae,je,Pe.refine(t=>t.operationId!==null||t.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var z=e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}),rt=e.object({...z.shape,featureAllowances:e.record(e.uuid(),e.number().int().min(0).max(1e9)),creditAmounts:e.record(e.uuid(),l)}).strict(),it=e.object({id:e.uuid(),planVersionId:e.uuid(),slot:e.string(),cardRequired:e.boolean(),status:e.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),createdAt:e.iso.datetime()}).strict();var qe=e.number().int().positive().max(2e8),ne=e.number().int().min(0).max(2e8),re=t=>t.mode==="partial"==(t.amountMinor!==void 0),P=e.strictObject({mode:e.enum(["full","partial"]),amountMinor:qe.optional(),entitlementAction:e.enum(["retain","revoke"])});var a=e.string().min(1).max(200),b=e.iso.datetime({offset:!0}),f=ne,ie=f.maxValue,C=e.number().int().min(-ie).max(ie),q=e.string().regex(/^[A-Z]{3}$/),oe=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ae=e.array(a).max(100).refine(t=>new Set(t).size===t.length),Ce=e.strictObject({merchantProductId:a,merchantPriceId:a,productVersionId:e.uuid().optional(),quantity:l.refine(t=>/[1-9]/.test(t))}),w={subject:Q,operationId:e.uuid(),configurationRevision:oe,connectionRevision:oe,expiresAt:b},D=e.discriminatedUnion("action",[e.strictObject({...w,action:e.literal("purchase"),mode:e.enum(["payment","subscription"]),currency:q,items:e.array(Ce).min(1).max(100),offerRefs:ae}),e.strictObject({...w,action:e.literal("subscription_change"),currency:q,merchantSubscriptionId:a,change:S.shape.change,timing:S.shape.timing,proration:S.shape.proration,offerRefs:ae}),e.strictObject({...w,action:e.literal("refund"),currency:q,merchantInvoiceId:a,mode:P.shape.mode,amountMinor:P.shape.amountMinor,entitlementAction:P.shape.entitlementAction}).refine(re,"Only a partial refund chooses amountMinor")]),ht=e.strictObject({request:D,requestedAt:b,preparationAllowed:e.boolean()}).refine(t=>!t.preparationAllowed||Date.parse(t.requestedAt)<Date.parse(t.request.expiresAt),"Preparation authority must be within its original validity"),Be=e.strictObject({merchantLineId:a,merchantPriceId:a.nullable(),quantity:l.refine(t=>/[1-9]/.test(t)),subtotalMinor:C,discountMinor:f,taxMinor:f.nullable(),totalMinor:C.nullable()}).refine(t=>t.taxMinor===null==(t.totalMinor===null)&&(t.totalMinor===null||t.totalMinor===t.subtotalMinor-t.discountMinor+t.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),Ee=e.strictObject({items:e.array(e.strictObject({merchantPriceId:a,quantity:l.refine(t=>/[1-9]/.test(t)),interval:m.shape.interval.exclude(["one_off"]),intervalCount:m.shape.intervalCount,amountMinor:m.shape.totalMinor,amountAfterOfferMinor:m.shape.totalMinor.optional()})).min(1).max(100),trial:z.nullable(),discount:I.nullable().optional(),discountExpiresAt:b.nullable().optional(),initialAmountMinor:m.shape.totalMinor.optional()}),ce=e.strictObject({request:D,requestDigest:j,merchantQuoteId:a,quoteTermsDigest:j,termsVersion:a,sourceRevisions:e.array(e.strictObject({reference:a,revision:a})).max(100),observedAt:b,expiresAt:b,currency:q,automaticTax:e.boolean(),lines:e.array(Be).max(100),subscriptionTerms:Ee.nullable(),subtotalMinor:C,discountMinor:f,nativeDiscountMinor:f.optional(),discount:I.nullable().optional(),taxMinor:f.nullable(),totalMinor:C.nullable(),effectiveAt:b.nullable(),expectedEffects:e.array(e.strictObject({reference:a,kind:e.enum(["grant","revoke","change"]),description:e.string().min(1).max(1e3),quantity:l.nullable(),unit:a.nullable()}).refine(t=>t.quantity===null==(t.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:e.array(e.strictObject({reference:a,version:a,summary:e.string().min(1).max(1e3)})).max(20)}),U=ce.superRefine((t,n)=>{let{quoteTermsDigest:r,...u}=t,h=t.lines.every(s=>s.taxMinor!==null),A=t.request.action==="purchase"&&t.request.mode==="subscription"!=(t.subscriptionTerms!==null),be=t.subscriptionTerms!==null&&(t.request.action==="refund"||t.request.action==="subscription_change"&&t.request.change.type==="cancel");(t.requestDigest!==x(t.request)||t.quoteTermsDigest!==x(u)||t.currency!==t.request.currency||A||be||t.lines.length===0&&(t.request.action!=="subscription_change"||t.subtotalMinor!==0||t.discountMinor!==0||t.taxMinor!==0||t.totalMinor!==0)||Date.parse(t.observedAt)>=Date.parse(t.expiresAt)||Date.parse(t.expiresAt)>Date.parse(t.request.expiresAt)||new Set(t.lines.map(s=>s.merchantLineId)).size!==t.lines.length||new Set(t.sourceRevisions.map(s=>s.reference)).size!==t.sourceRevisions.length||new Set(t.requiredConsents.map(s=>s.reference)).size!==t.requiredConsents.length||t.subtotalMinor!==t.lines.reduce((s,g)=>s+g.subtotalMinor,0)||t.discountMinor!==t.lines.reduce((s,g)=>s+g.discountMinor,0)||t.taxMinor!==null!==h||!h&&!t.automaticTax||t.taxMinor===null!=(t.totalMinor===null)||h&&(t.taxMinor!==t.lines.reduce((s,g)=>s+g.taxMinor,0)||t.totalMinor!==t.subtotalMinor-t.discountMinor+t.taxMinor)||t.request.action!=="subscription_change"&&(t.subtotalMinor<0||t.totalMinor!==null&&t.totalMinor<0)||t.request.action==="refund"&&(t.taxMinor===null||t.totalMinor===null||t.totalMinor<=0||t.request.mode==="partial"&&t.totalMinor!==t.request.amountMinor))&&n.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function bt(t,n,r,u){return t.request.operationId===n&&t.request.action===r&&t.currency===u}function ft(t){return x(D.parse(t))}function gt(t){return x(ce.omit({quoteTermsDigest:!0}).parse(t))}var Te=e.strictObject({quoteTermsDigest:j,consents:e.array(e.strictObject({reference:a,version:a})).max(20)});function xt(t){return{quoteTermsDigest:t.quoteTermsDigest,consents:t.requiredConsents.map(({reference:n,version:r})=>({reference:n,version:r}))}}var ke=Te.extend({operationId:e.uuid()}).refine(t=>new Set(t.consents.map(n=>n.reference)).size===t.consents.length);function yt(t,n){let r=U.parse(t),u=ke.parse(n);return u.operationId===r.request.operationId&&u.quoteTermsDigest===r.quoteTermsDigest&&u.consents.length===r.requiredConsents.length&&r.requiredConsents.every(h=>u.consents.some(A=>A.reference===h.reference&&A.version===h.version))}var M=3,Ot="/integrations/indiana",vt="X-Indiana-Merchant-Bridge-Version",Re=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],ze=e.enum(Re),At={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},$=e.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),ue=e.string().regex(/^[A-Za-z0-9_-]{1,64}$/),we=e.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>"AEIMQUYcgkosw048".includes(t.at(-1)),"Use canonical base64url for a 32-byte key"),De=e.strictObject({keyId:ue,signingSecret:we}),Ue=e.string().max(300).superRefine((t,n)=>{try{let r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.port&&r.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(r.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(r.hostname))throw new Error("invalid origin")}catch{n.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(t=>new URL(t).origin),me=e.array(ze).max(10).refine(t=>new Set(t).size===t.length,"Capabilities must be unique"),V=e.strictObject({bridgeVersion:e.literal(M),projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),capabilities:me,catalog:e.enum(["endpoint","static","none"]),billingEvents:e.array(W).max(7),profiles:e.array(K).max(32).refine(t=>new Set(t).size===t.length,"Profiles must be unique")}).superRefine((t,n)=>{let r=u=>t.capabilities.includes(u);r("catalog")!==(t.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(r("billing_records")!==t.billingEvents.length>0||new Set(t.billingEvents).size!==t.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),de=e.strictObject({origin:Ue,requiredCapabilities:me}),$e=e.strictObject({revision:e.number().int().nonnegative(),checkedAt:e.iso.datetime(),outcome:e.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:e.strictObject({ping:e.enum(["passed","failed","not_checked"]),authentication:e.enum(["passed","failed","not_checked"]),catalog:e.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:V.nullable()}).superRefine((t,n)=>{t.outcome==="valid"!=(t.manifest!==null)&&n.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),jt=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),execution:e.enum(["indiana","record_only"]),accountId:e.string().nullable(),revision:e.number().int().nonnegative(),authentication:e.strictObject({keyId:ue}).nullable(),secretStoreConfigured:e.boolean().optional(),connection:de.nullable(),check:$e.nullable()});var se=e.strictObject({projectId:e.uuid(),environmentId:e.uuid()}),Pt=e.discriminatedUnion("action",[se.extend({action:e.literal("save"),revision:e.number().int().nonnegative(),connection:de,authentication:De.optional()}),se.extend({action:e.literal("check"),revision:e.number().int().nonnegative()})]),_=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"])});function qt(t){return e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:$,scope:_,data:t})}var le=e.strictObject({nativeUserId:e.string().min(1).max(128),session:Z.strict()}),pe=e.strictObject({nativeUserId:e.string().min(1).max(128),presentation:e.strictObject({customerId:e.uuid(),decisionId:e.uuid(),offeringVersionId:e.uuid(),paywallVersionId:e.uuid(),variant:e.string().min(1).max(128)}).nullable()}),he=e.strictObject({decisionId:e.uuid(),eventId:e.uuid()}),O=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),Ct=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:e.string().min(1).max(64),scope:_,error:e.strictObject({code:e.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:e.string().min(1).max(500),retryable:e.boolean(),recovery:e.string().min(1).max(80)})});var zt=e.strictObject({scope:_,operationId:e.uuid(),customerId:e.uuid(),confirmedAt:e.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:e.boolean(),instruction:Y,merchantTerms:U.optional()}).refine(t=>t.operationId===t.instruction.operationId&&t.customerId===t.instruction.customerId&&(!t.merchantTerms||t.merchantTerms.request.operationId===t.operationId&&t.merchantTerms.request.subject.customerId===t.customerId&&t.merchantTerms.request.action===t.instruction.type&&t.merchantTerms.currency===t.instruction.currency&&Object.entries(t.scope).every(([n,r])=>t.merchantTerms.request.subject.scope[n]===r)),"Authority must refer to the original Customer and operation"),N=T,d=e.string().min(1).max(120),Ve=e.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Ne=e.strictObject({revision:d,updatedAt:e.iso.datetime(),provider:e.literal("merchant"),items:e.array(e.strictObject({merchantProductId:d,productVersionId:e.uuid(),name:e.string().min(1).max(255),kind:e.enum(["subscription","credit_pack"]),merchantPriceId:d,currency:e.string().regex(/^[a-z]{3}$/),amountMinor:e.number().int().nonnegative().max(1e8),interval:e.enum(["one_time","month","year"]),intervalCount:e.literal(1),includedCredits:e.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:e.enum(["none","month"]),creditPolicyId:d,available:e.boolean()}).superRefine((t,n)=>{(t.kind==="credit_pack"&&(t.interval!=="one_time"||t.creditReset!=="none")||t.kind==="subscription"&&t.interval==="one_time"||t.available&&t.amountMinor===0)&&n.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Le=e.strictObject({customerId:e.uuid(),revision:e.string().min(1).max(128),observedAt:e.iso.datetime(),subscriptions:e.array(e.strictObject({merchantSubscriptionId:d,merchantProductId:d,productVersionId:e.uuid().nullable(),status:e.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:e.iso.datetime().nullable(),currentPeriodEndsAt:e.iso.datetime().nullable(),cancelAtPeriodEnd:e.boolean(),scheduledChange:e.strictObject({effectiveAt:e.iso.datetime(),merchantProductId:d}).nullable()})).max(100),purchaseHistory:e.strictObject({complete:e.boolean(),hasPaidPurchase:e.boolean(),lastPaidAt:e.iso.datetime().nullable()}),balances:e.array(e.strictObject({bucketId:d,key:d,available:Ve,expiresAt:e.iso.datetime().nullable(),nextResetAt:e.iso.datetime().nullable()})).max(100)}),v=e.strictObject({}),Fe={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":v,"session.create":v,"catalog.read":v,"customer.commerce.read":v,"presentation.resolve":v,"presentation.report":he,"purchase.execute":O,"operation.read":O,"subscription.change":O,"refund.execute":O},wt={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":V,"session.create":le,"catalog.read":Ne,"customer.commerce.read":Le,"presentation.resolve":pe,"presentation.report":e.strictObject({queued:e.literal(!0)}),"purchase.execute":N,"operation.read":ee,"subscription.change":N,"refund.execute":N},Dt=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),scope:_,command:$,data:e.unknown()}).superRefine((t,n)=>{Fe[t.command].safeParse(t.data).success||n.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});export{ge as a,S as b,xe as c,We as d,Xe as e,ye as f,T as g,ee as h,p as i,Je as j,z as k,qe as l,ne as m,re as n,P as o,ht as p,U as q,bt as r,ft as s,gt as t,Te as u,xt as v,yt as w,M as x,Ot as y,vt as z,Re as A,At as B,De as C,Ue as D,V as E,_ as F,qt as G,le as H,pe as I,he as J,O as K,Ct as L,zt as M,N,Le as O,Fe as P,wt as Q,Dt as R};
@@ -1 +1 @@
1
- import{s as g,t as w}from"./chunk-QPHT6QHE.js";import{n as I,s as h}from"./chunk-4ZVVG5LM.js";import{a as y}from"./chunk-CLAZ7NVN.js";import{a}from"./chunk-HJLGRW4A.js";import{a as T}from"./chunk-3VUPVXAV.js";import{b as P}from"./chunk-OHOROFWN.js";import{a as f}from"./chunk-ZY4XAKNQ.js";function b(r,n,o){if(!["subscriptions/operations/read","subscriptions/updates/read","subscriptions/refunds/read"].includes(r))return;let e=n,c=o,s=c.operation;if(s.operationId!==e.operationId||[s.authority,s.merchantExecution].some(t=>t&&(t.operationId!==e.operationId||e.customerId!==void 0&&t.customerId!==e.customerId))||s.authority&&(s.authority.scope.projectId!==c.scope.projectId||s.authority.scope.environment!==c.scope.environment))throw new a("INVALID_RESPONSE","Original commerce operation changed")}function D(r){try{return structuredClone(r)}catch{return r}}async function q(r,n){let o=r.captureIdentity?.(),{apiOperations:e}=await import("./operation-contracts-SP2RZUT3.js");return o?.(),e[n]}function E(r,n,o,e){try{return r.parse(n)}catch(c){throw e&&c instanceof f?new a(o,e):c}}async function x(r,n,o,e={},c){let s=typeof e=="function"?{}:e,t=E(n.request,o,"INVALID_REQUEST",s.request);try{let i=await r(n.path,t,n.method,c),u=typeof e=="function"?e:e.parseResponse,d=u?u(n.response,i):E(n.response,i,"INVALID_RESPONSE",s.response);return b(n.path,t,d),d}catch(i){throw i instanceof a&&t!==null&&typeof t=="object"&&"requestId"in t&&typeof t.requestId=="string"&&(i.commandRequestId??=t.requestId),i}}function O(r,n){let o=typeof r=="string"?new TextEncoder().encode(r):r;return o.byteLength===n.byteLength&&h(o)===n.sha256}async function F(r,n){let o=g.parse(n),{artifact:e,environmentId:c}=o.content,s=new y(r.baseUrl??P).origin,t=new y(e.url,s);if(t.origin!==s||t.username||t.password||t.search||t.hash||t.pathname!==`/api/v1/configuration/${c}/artifacts/${e.sha256}`)throw new a("INVALID_RESPONSE","Public Paywall locator is not trusted");let i=new AbortController,u,d=new Promise((p,l)=>{u=setTimeout(()=>{let m=new a("TIMEOUT","Public Paywall read timed out");i.abort(m),l(m)},I.initializationMs)}),R=(async()=>{let p=await(r.fetch??globalThis.fetch)(t,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:i.signal});if(i.signal.aborted&&(p.body?.cancel().catch(()=>{}),i.signal.throwIfAborted()),!p.ok||!p.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(p.headers.get("content-length"))>e.byteLength)throw p.body?.cancel().catch(()=>{}),new a("INVALID_RESPONSE","Public Paywall is unavailable");let l=await T(p,e.byteLength,{signal:i.signal,error:m=>new a("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!O(l,e))throw new a("INVALID_RESPONSE","Public Paywall digest or size changed");return w(o,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([R,d])}finally{clearTimeout(u)}}export{D as a,q as b,x as c,O as d,F as e};
1
+ import{s as g,t as w}from"./chunk-THMGTRXP.js";import{n as I,s as h}from"./chunk-NAZU3EEJ.js";import{a as y}from"./chunk-ZIQENZDI.js";import{a}from"./chunk-X4W22IH6.js";import{a as T}from"./chunk-3VUPVXAV.js";import{b as P}from"./chunk-CZ2RY6RG.js";import{a as f}from"./chunk-VF6QMMEA.js";function b(r,n,o){if(!["subscriptions/operations/read","subscriptions/updates/read","subscriptions/refunds/read"].includes(r))return;let e=n,c=o,s=c.operation;if(s.operationId!==e.operationId||[s.authority,s.merchantExecution].some(t=>t&&(t.operationId!==e.operationId||e.customerId!==void 0&&t.customerId!==e.customerId))||s.authority&&(s.authority.scope.projectId!==c.scope.projectId||s.authority.scope.environment!==c.scope.environment))throw new a("INVALID_RESPONSE","Original commerce operation changed")}function D(r){try{return structuredClone(r)}catch{return r}}async function q(r,n){let o=r.captureIdentity?.(),{apiOperations:e}=await import("./operation-contracts-443N2P3A.js");return o?.(),e[n]}function E(r,n,o,e){try{return r.parse(n)}catch(c){throw e&&c instanceof f?new a(o,e):c}}async function x(r,n,o,e={},c){let s=typeof e=="function"?{}:e,t=E(n.request,o,"INVALID_REQUEST",s.request);try{let i=await r(n.path,t,n.method,c),u=typeof e=="function"?e:e.parseResponse,d=u?u(n.response,i):E(n.response,i,"INVALID_RESPONSE",s.response);return b(n.path,t,d),d}catch(i){throw i instanceof a&&t!==null&&typeof t=="object"&&"requestId"in t&&typeof t.requestId=="string"&&(i.commandRequestId??=t.requestId),i}}function O(r,n){let o=typeof r=="string"?new TextEncoder().encode(r):r;return o.byteLength===n.byteLength&&h(o)===n.sha256}async function F(r,n){let o=g.parse(n),{artifact:e,environmentId:c}=o.content,s=new y(r.baseUrl??P).origin,t=new y(e.url,s);if(t.origin!==s||t.username||t.password||t.search||t.hash||t.pathname!==`/api/v1/configuration/${c}/artifacts/${e.sha256}`)throw new a("INVALID_RESPONSE","Public Paywall locator is not trusted");let i=new AbortController,u,d=new Promise((p,l)=>{u=setTimeout(()=>{let m=new a("TIMEOUT","Public Paywall read timed out");i.abort(m),l(m)},I.initializationMs)}),R=(async()=>{let p=await(r.fetch??globalThis.fetch)(t,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:i.signal});if(i.signal.aborted&&(p.body?.cancel().catch(()=>{}),i.signal.throwIfAborted()),!p.ok||!p.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(p.headers.get("content-length"))>e.byteLength)throw p.body?.cancel().catch(()=>{}),new a("INVALID_RESPONSE","Public Paywall is unavailable");let l=await T(p,e.byteLength,{signal:i.signal,error:m=>new a("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!O(l,e))throw new a("INVALID_RESPONSE","Public Paywall digest or size changed");return w(o,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([R,d])}finally{clearTimeout(u)}}export{D as a,q as b,x as c,O as d,F as e};