@tinkerlandai/longplay-sdk 0.10.66 → 0.10.69

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 (93) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +2 -2
  3. package/dist/check-response-754GDUOJ.js +1 -0
  4. package/dist/{chunk-O5YYORDW.js → chunk-26QYDE7V.js} +1 -1
  5. package/dist/chunk-2BSDXKQS.js +1 -0
  6. package/dist/{chunk-SAPICYY3.js → chunk-2SSOV3OG.js} +1 -1
  7. package/dist/{chunk-N5HX3K5J.js → chunk-2ZMIM4MO.js} +1 -1
  8. package/dist/{chunk-AD35L6BX.js → chunk-3NV6NBQB.js} +1 -1
  9. package/dist/{chunk-MNICOIQ6.js → chunk-44ZJPQM6.js} +1 -1
  10. package/dist/{chunk-K675GO7R.js → chunk-57ZXT7AS.js} +1 -1
  11. package/dist/chunk-5MOJUGMA.js +1 -0
  12. package/dist/{chunk-RNCUAYLQ.js → chunk-5NCQOJR2.js} +1 -1
  13. package/dist/chunk-5U7LC2NL.js +1 -0
  14. package/dist/{chunk-IGE2UMXG.js → chunk-6C3ARFEL.js} +1 -1
  15. package/dist/{chunk-A22QPPNY.js → chunk-6GY2YT3U.js} +1 -1
  16. package/dist/{chunk-C5FSL4XH.js → chunk-BGCCW5QX.js} +2 -2
  17. package/dist/{chunk-JBN6ADWQ.js → chunk-CQ5EQNQA.js} +1 -1
  18. package/dist/{chunk-PQ4ISW55.js → chunk-CWBBW6QS.js} +1 -1
  19. package/dist/{chunk-PNX7Y2K3.js → chunk-DXNTXCSI.js} +1 -1
  20. package/dist/{chunk-OKPWZZZW.js → chunk-DZYMD4MJ.js} +1 -1
  21. package/dist/{chunk-FUP5JVDE.js → chunk-ECUGL7AO.js} +1 -1
  22. package/dist/{chunk-56YCOGQZ.js → chunk-EJSTRCBQ.js} +1 -1
  23. package/dist/{chunk-47FCHF3Y.js → chunk-EQ64JD4L.js} +1 -1
  24. package/dist/chunk-F5ABUGHD.js +1 -0
  25. package/dist/{chunk-EYTP23EK.js → chunk-G3YIPDT6.js} +1 -1
  26. package/dist/{chunk-M6MXJHJ5.js → chunk-GBUGEL6M.js} +1 -1
  27. package/dist/chunk-JAH62B6J.js +1 -0
  28. package/dist/{chunk-Q523TPZM.js → chunk-JW4MSBYN.js} +1 -1
  29. package/dist/{chunk-7EENIOSJ.js → chunk-KJTHMRSH.js} +1 -1
  30. package/dist/{chunk-KVLOMX2G.js → chunk-LBYMDTGD.js} +1 -1
  31. package/dist/{chunk-7OJIW75D.js → chunk-LUVTP4VU.js} +1 -1
  32. package/dist/{chunk-7D5462NE.js → chunk-MT4OQFDI.js} +1 -1
  33. package/dist/{chunk-74T76RE4.js → chunk-NEW77IDA.js} +1 -1
  34. package/dist/{chunk-G2OLUFYT.js → chunk-NNJ7W4KY.js} +1 -1
  35. package/dist/{chunk-ZWNWVMCH.js → chunk-Q4GG33R5.js} +1 -1
  36. package/dist/{chunk-5WFI36LF.js → chunk-QTXHF27F.js} +1 -1
  37. package/dist/{chunk-DCMA7W7N.js → chunk-RMR64P6V.js} +1 -1
  38. package/dist/{chunk-E3FUZSTM.js → chunk-SGOVJD5P.js} +1 -1
  39. package/dist/{chunk-HT5SLWWG.js → chunk-ST7XO45I.js} +1 -1
  40. package/dist/{chunk-YUL23NAW.js → chunk-T5SCW4IA.js} +1 -1
  41. package/dist/{chunk-XIBJF5E6.js → chunk-TFPLIX5E.js} +1 -1
  42. package/dist/{chunk-OFG3SGEX.js → chunk-TYJWRPJY.js} +1 -1
  43. package/dist/{chunk-YA5YKHDE.js → chunk-UFTKCFNI.js} +1 -1
  44. package/dist/{chunk-RHILCVPZ.js → chunk-UIR5CBCC.js} +1 -1
  45. package/dist/{chunk-TXVLJFZG.js → chunk-ULED3B5P.js} +1 -1
  46. package/dist/{chunk-QPVA644N.js → chunk-USH4WN6W.js} +1 -1
  47. package/dist/{chunk-45MWDZ42.js → chunk-VMYLTNDS.js} +1 -1
  48. package/dist/{chunk-3Q3DZEP3.js → chunk-WVTKVQLZ.js} +1 -1
  49. package/dist/{chunk-GE6RSO2C.js → chunk-YDPF2ZZW.js} +1 -1
  50. package/dist/{chunk-46USIMCJ.js → chunk-ZRU7WONE.js} +1 -1
  51. package/dist/{content-WWME7E27.js → content-66BI72XB.js} +1 -1
  52. package/dist/{funnel-host-purchase-XIGJ7P7M.js → funnel-host-purchase-YPAWZLXP.js} +1 -1
  53. package/dist/{funnel-host-recovery-paywall-POMEY6I2.js → funnel-host-recovery-paywall-KHBGMNS5.js} +1 -1
  54. package/dist/funnel-paywall-copies-A76T5V7B.js +1 -0
  55. package/dist/funnel-paywall-prerender-PNJXR4VC.js +1 -0
  56. package/dist/funnel-route-prediction-KFUCAJLL.js +1 -0
  57. package/dist/funnel-route-source-WEYKNM2C.js +1 -0
  58. package/dist/funnel-runtime-host-RWU52BJ7.js +1 -0
  59. package/dist/index.d.ts +10 -6
  60. package/dist/index.js +1 -1
  61. package/dist/merchant-bridge-contracts-RWNJHBTR.js +1 -0
  62. package/dist/native-shell.js +1 -1
  63. package/dist/openrouter.js +1 -1
  64. package/dist/operation-contracts-NNWS467N.js +1 -0
  65. package/dist/page.js +1 -1
  66. package/dist/paywall-BSY67NQL.js +1 -0
  67. package/dist/paywall-content-RAB5S6KB.js +1 -0
  68. package/dist/paywall-session-CRIGHMOQ.js +1 -0
  69. package/dist/popup.js +1 -1
  70. package/dist/react-native.js +1 -1
  71. package/dist/screen-renderer-H3FBGJZB.js +1 -0
  72. package/dist/server.js +1 -1
  73. package/dist/visual.js +1 -1
  74. package/package.json +1 -1
  75. package/dist/check-response-WOTPYNDN.js +0 -1
  76. package/dist/chunk-7NKBMAOB.js +0 -1
  77. package/dist/chunk-MUCDKWMP.js +0 -1
  78. package/dist/chunk-MUP7FNNY.js +0 -1
  79. package/dist/chunk-OT55LG4U.js +0 -1
  80. package/dist/chunk-ZLSZBGJG.js +0 -1
  81. package/dist/funnel-paywall-copies-DUZ3YX67.js +0 -1
  82. package/dist/funnel-paywall-prerender-5NU457SR.js +0 -1
  83. package/dist/funnel-route-prediction-EW3HVH46.js +0 -1
  84. package/dist/funnel-route-source-YVFAFCVG.js +0 -1
  85. package/dist/funnel-runtime-host-J2HWW5IN.js +0 -1
  86. package/dist/merchant-bridge-contracts-PNRVNTCN.js +0 -1
  87. package/dist/operation-contracts-6ORJSGYH.js +0 -1
  88. package/dist/paywall-YRB7LQUS.js +0 -1
  89. package/dist/paywall-content-QLJIOFR3.js +0 -1
  90. package/dist/paywall-session-Q6ZYXUOU.js +0 -1
  91. package/dist/screen-renderer-P6U5UBFX.js +0 -1
  92. /package/dist/{chunk-C5FSL4XH.js.LEGAL.txt → chunk-BGCCW5QX.js.LEGAL.txt} +0 -0
  93. /package/dist/{chunk-YLH3AYCK.js → chunk-S7NHVERO.js} +0 -0
@@ -1 +1 @@
1
- import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-RHILCVPZ.js";import{a as tt}from"./chunk-HT5SLWWG.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-FUP5JVDE.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-AD35L6BX.js";import{a as fe,b as Ze}from"./chunk-7D5462NE.js";import{a as le}from"./chunk-7EENIOSJ.js";import{e as de}from"./chunk-7OJIW75D.js";import{a as D}from"./chunk-46USIMCJ.js";import{h as ie}from"./chunk-XIBJF5E6.js";import{b as et}from"./chunk-3VUPVXAV.js";import{a as Qe}from"./chunk-5MRSFLQA.js";import{b as e}from"./chunk-YLH3AYCK.js";import{c as Fe,f as Pe}from"./chunk-VPT5MFDG.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-YVFAFCVG.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-YVFAFCVG.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
1
+ import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-UIR5CBCC.js";import{a as tt}from"./chunk-ST7XO45I.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-ECUGL7AO.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-3NV6NBQB.js";import{a as fe,b as Ze}from"./chunk-MT4OQFDI.js";import{a as le}from"./chunk-KJTHMRSH.js";import{e as de}from"./chunk-LUVTP4VU.js";import{a as D}from"./chunk-ZRU7WONE.js";import{h as ie}from"./chunk-TFPLIX5E.js";import{b as et}from"./chunk-3VUPVXAV.js";import{a as Qe}from"./chunk-5MRSFLQA.js";import{b as e}from"./chunk-S7NHVERO.js";import{c as Fe,f as Pe}from"./chunk-VPT5MFDG.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-WEYKNM2C.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-WEYKNM2C.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
@@ -0,0 +1 @@
1
+ import{a as kn,c as Rn,d as Lt,f as Ut,g as An,k as Sn}from"./chunk-6GY2YT3U.js";import{a as wn,b as Ye}from"./chunk-W32FI2A2.js";import{d as bn,e as Cn,f as Pn,g as vn,i as _t,j as ot,k as In,l as En,m as xn}from"./chunk-57ZXT7AS.js";import{a as hn,c as Ot,d as mn,e as yn}from"./chunk-LBYMDTGD.js";import{a as at,b as oe,d as Nt,f as Dt,j as gn}from"./chunk-CQ5EQNQA.js";import{b as Ee}from"./chunk-Q4GG33R5.js";import{B as _,C as it,D as Ge,E as _e,y as fn}from"./chunk-WVTKVQLZ.js";import{r as Le,t as Ue}from"./chunk-JW4MSBYN.js";import{i as pn}from"./chunk-EJSTRCBQ.js";import{c as be,j as We}from"./chunk-26QYDE7V.js";import{c as Tt}from"./chunk-DZYMD4MJ.js";import{a as k}from"./chunk-ZRU7WONE.js";import{a as z}from"./chunk-DSPLGTQI.js";async function Tn(H,a,x){if(!Ge(a))throw new k("INVALID_RESPONSE","A verified completed purchase is required");let T=H?We.parse(H):null;if(await x.onComplete?.(a),!T||!x.check)return;let F=We.parse(await x.check());if(F.internal_feature_id!==T.internal_feature_id||F.quantity!==T.quantity||T.observation!==void 0&&(F.observation===void 0||F.observation.requirementDigest!==T.observation.requirementDigest||F.observation.authority!==T.observation.authority||Tt(F.observation.subject)!==Tt(T.observation.subject)))throw new k("INVALID_RESPONSE","The access requirement changed");F.allowed&&await x.onAccessGranted?.(F)}function On(H){return Object.entries(H.document.buttons).filter(([,a])=>a.type==="checkout"&&a.product.type==="fixed"&&!Ee(a.product,{},H.capabilities)).map(([a])=>a)}function Nn(H,a){let x=_(a)?void 0:a.lines[0];if(!_(a)&&(a.lines.length!==1||!x))return;let T=_(a)?a.productVersionId:x.productVersionId,{screen:F,buttons:se}=H.document,M=new Map(_(a)?Object.entries(a.featureQuantities??{}):(x?.prepaid??[]).map(b=>[b.internal_feature_id,b.quantity]));function le(b,u){if(b.hidden)return!1;if(b.type==="plan_picker"&&H.capabilities.pickers[b.id]?.options.includes(T))return u[b.id]=T,!0;if(b.type==="quantity_picker"){let ne=M.get(b.internalFeatureId);return ne!==void 0&&(!b.bind?.plan||b.bind.plan===T)&&(u[b.id]=ne),!1}if(b.type==="button"&&b.action){let ne=se[b.action];return ne?.type==="checkout"&&ne.product.type==="fixed"&&ne.product.productVersionId===T}if(b.type!=="stack")return!1;let te=b.interaction,i=b.bind?.plan===T;for(let[ne,p]of b.children.entries()){let J={},L=le(p,J);if(te?.type==="toggle"||te?.type==="tabs"){if(!L)continue;return u[b.id]=te.type==="toggle"?ne===0:p.id,Object.assign(u,J),!0}Object.assign(u,J),L&&(i=!0,te?.type==="select"&&te.purpose==="product"&&te.pickerId&&p.type==="stack"&&p.bind?.plan===T&&(u[b.id]=p.id,u[te.pickerId]=T))}return i}for(let b of F.pages){let u={__page:b.id};if(le(b.root,u))return u}}var Bn="position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0";async function Pr(H,a,x){let T=a.focusAtReveal?()=>{}:_t(H.ownerDocument),F=()=>{M.finish("dismissed"),T()},se=()=>F(),M=In(H,a,"paywall",()=>{F(),z(a.onDismiss)},kn);a.signal?.throwIfAborted(),a.signal?.addEventListener("abort",se,{once:!0});let le=null,b,u,te;try{if(M.start(!0,a.loadingDocument?.screen.strings.defaultLocale,a.loadingDocument??null),M.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(le=a.check?We.parse(await M.wait(a.check(),ot)):null,le?.allowed)return M.finish("skipped"),a.signal?.removeEventListener("abort",se),T(),await a.onAccessGranted?.(le),{check:le,host:null};let[e,t]=await Promise.allSettled([M.wait(import("./screen-renderer-H3FBGJZB.js")),M.wait(a.start().then(r=>(M.cancelled&&r.destroy(),r)),ot)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;te=e.value,b=t.value,a.signal?.throwIfAborted(),b.signal?.throwIfAborted(),b.signal?.addEventListener("abort",se,{once:!0});let n=b.view??await M.wait(b.refresh(),ot);if(!n)throw new k("INVALID_RESPONSE","Paywall presentation is missing");b.signal?.throwIfAborted(),u=n}catch(e){throw M.finish("error",e),x?.retainedDialog?.release(),a.signal?.removeEventListener("abort",se),b?.signal?.removeEventListener("abort",se),b?.destroy(),T(),e}let i=b,{mountScreenPreview:ne}=te,p=H.ownerDocument,J=new AbortController,L=p.createElement("section"),pe=p.createElement("div"),W=p.createElement("div"),st=a.mountControls,ee=st?p.createElement("div"):void 0,d=p.createElement("p"),y=p.createElement("button"),ce=p.createElement("button"),O=p.createElement("button");(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&x?.hostPaywallTarget&&!x.retainedDialog&&u.document.presentation.type==="modal"&&(x.retainedDialog=vn(x.hostPaywallTarget));let ue=x?.retainedDialog,A=ue?.dialog??p.createElement("dialog"),Me=ue&&u.document.presentation.type==="inline"?{type:"modal",size:"md"}:u.document.presentation,re=Me.type==="inline"?W:p.createElement("div"),lt=i.locale||u.document.screen.strings.defaultLocale,o=lt.toLowerCase().startsWith("zh"),Dn=o?"正在处理…":"Processing…",_n=o?"正在准备报价…":"Preparing your price…",D=Rn(u.document.screen.theme);L.dataset.indianaPaywall="",L.setAttribute("aria-label",u.document.name),L.style.cssText=D.root,W.style.cssText=D.controls,d.style.cssText=D.message,d.setAttribute("role","status"),O.style.cssText=D.link,O.textContent=o?"关闭":"Close",y.style.cssText=D.secondary,y.textContent=o?"重试":"Retry",y.hidden=!0,ce.type="button",ce.style.cssText=D.primary,ce.textContent=o?"继续付款":"Continue payment",ce.hidden=!0,re.append(d,ce,y),W.append(O),ee&&(ee.style.cssText="flex:1 0 100%;min-width:0",ee.hidden=!0,W.prepend(ee)),re!==W&&(re.dataset.indianaPaywallStatus="",re.style.cssText="display:none;padding:0",L.append(re)),L.append(pe,W);let ct=()=>{let e=Mn();d.style.cssText=e?`${D.message};${Bn}`:D.message,zt();let t=c=>!c.hidden&&(c!==d||!!d.textContent&&!e);if(re!==W&&(re.style.cssText=!ie&&[...re.children].some(t)?`${D.controls};padding:12px 64px 12px 20px;flex-shrink:0`:e?"padding:0":"display:none;padding:0"),ee){let c=!ee.childElementCount&&!ee.textContent?.trim();ee.hidden!==c&&(ee.hidden=c)}let n=me??W,r=![...n.children].some(t),s=[...n.children].some(c=>c!==O&&t(c));n.style.cssText=r?D.controls.replace(/padding:[^;]+/,"padding:0"):s?`${D.controls};${D.pinned}`:D.controls,dt()},Mt=typeof MutationObserver>"u"?void 0:new MutationObserver(ct);Mt?.observe(L,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let Ln=Object.entries(u.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),N,Vt,Ve=!1,$t=JSON.stringify(u.capabilities),Q;function Ce(e){let t=On(e);if(Q||fe&&!ae||B&&(C||!Pe()||ge))return Ae(e).map(({actionId:r})=>r);if(bt()||!C&&Pe())return t;let n=C?wt(e):Ct(e);return[...new Set([...t,...Ae(e).map(({actionId:r})=>r).filter(r=>!n.includes(r))])]}function $e(e){if(w)return;let t=u.id!==e.id;u=e;let n=JSON.stringify(e.capabilities);if(t||n!==$t){let r=!v&&!i.quote&&!i.operation?at(e,K,Bt):K;t||JSON.stringify(r)!==JSON.stringify(K)?(K=r,N?.update(e.document.screen,lt,{capabilities:oe(e),unavailableActions:Ce(e),serverInput:{bindings:[],answers:{}},selection:K})):N?.updateCapabilities(oe(e),Ce(e)),$t=n}Vn(e),ve(),Xe()}let U,ut=0;function Ht(){return(me??W).getBoundingClientRect().height+(re===W?0:re.getBoundingClientRect().height)}function dt(){let e=p.defaultView;if(!U?.responsive||!e)return;let t=me??W,n=e.innerHeight-(U.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",ut=Math.max(1,n-Ht()),N?.resizeViewport?.(ut,e.innerWidth)}let w=!1,fe=!1,v=null,pt,ze=!1,Qt=!1,he=!1,ft,ht=!1,ie,me;function Un(){return fe||w||ie||ht?{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null}:Ot(i)}let I=()=>!w&&!ze&&!ie&&a.canInteract?.()!==!1,X,xe=!1,Re=!1,mt,f=null,de=null,Ke="",ye=()=>a.checkoutNavigation==="after_confirmation"&&!!(a.terminateCheckout||a.resumeCheckout),K={},Bt=new Set,ae,C;function yt(e){return!!e&&_(e)&&e.timing==="immediate"&&e.execution.provider==="merchant"}let gt=o?"正在确认付款…":"Confirming payment…",B=null,ge,Je,jt=!1,Pe=()=>a.allowNewPurchase!==!1||jt;function qt(){return JSON.stringify([u.id,u.capabilities])}function Ft(){let e=mt;return e&&e.read===a.prepareSubscriptionChange&&e.basis===qt()?e:void 0}function Xe(){let e=a.prepareSubscriptionChange;if(!e||!he||!I()||!Pe()||a.onPurchaseIntent||p.visibilityState==="hidden"||v||i.quote||i.operation||!Ae(u).length||Ft())return;let t=J.signal,n=new Promise(r=>{let s=()=>r(void 0);t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(()=>(t.throwIfAborted(),e(t))).then(c=>r(t.aborted?void 0:c),s).finally(()=>t.removeEventListener("abort",s))});mt={read:e,basis:qt(),result:n}}let Wt=()=>{p.visibilityState==="hidden"?mt=void 0:Xe()};p.addEventListener("visibilitychange",Wt),J.signal.addEventListener("abort",()=>p.removeEventListener("visibilitychange",Wt),{once:!0});function Ae(e){return Object.entries(e.document.buttons).flatMap(([t,n])=>n.type==="checkout"?[{actionId:t,policy:n}]:[])}function Gt(e){let t=C?.quote;return t?Ae(e).filter(({actionId:n,policy:r})=>Se(t,e,n,r.product,K)).map(({actionId:n})=>n):[]}function wt(e){return C?.phase==="payment"?Gt(e):[]}function bt(){return(C?C.phase==="payment":!Pe())&&(Pe()||!!a.prepareUpgradeReplacement)&&ye()&&!!a.terminateCheckout&&!!i.quote&&i.canReselect===!1&&!!i.operation&&R(i.operation).type==="checkout"}function Ct(e){let t=i.quote;return!ye()||B||!t||!i.operation||R(i.operation).type!=="checkout"?[]:Ae(e).filter(({actionId:n,policy:r})=>Se(t,e,n,r.product,K)).map(({actionId:n})=>n)}function ve(){let e=Q?[]:C?wt(u):Ct(u),t=a.allowNewPurchase===!1&&!!i.operation&&R(i.operation).type==="checkout";ce.hidden=!!Q||(C?C.phase!=="payment":!t)||e.length>0,zt(e)}function Yt(){if(!(ae===void 0||Q))return d.textContent?d.textContent:C?.phase==="checking"?gt:void 0}function Mn(){return!!N?.updateCheckoutControls&&!!d.textContent&&Yt()!==void 0}let Ze;function zt(e=Q?[]:C?wt(u):Ct(u)){if(!N?.updateCheckoutControls)return;let t=Yt(),n=ye()||!!C;if(!t&&!n&&Ze?.on!==N)return;let r={actions:Ae(u).map(({actionId:c})=>c),resume:t?[ae]:n?e:[],resumeLabel:t??(o?"继续付款":C?"Continue payment":"Continue checkout"),busy:ae},s=JSON.stringify(r);Ze?.on===N&&Ze.key===s||(Ze={on:N,key:s},N.updateCheckoutControls(r))}function Kt(){de?.remove(),de=null}async function et(){if(B)return;if(a.resumeCheckout&&i.operation){let t=i.operation.operationId;try{await a.resumeCheckout(t)}catch(n){if(!(n instanceof k&&n.code==="PURCHASE_PENDING"))throw n;let r=await i.read();if(!I())return;if(r.operationId!==t||R(r).type==="checkout")throw n;await V(r,!1)}return}let e=await i.read();if(R(e).type!=="checkout")return V(e,!1);I()&&(He.delete(e.operationId),await Qe(e))}function Pt(){ge?.destroy(),ge=void 0,Je=void 0}function Jt(){let e=B;if(!e||ge)return;let t=o?"仍在核对原订单,暂时无法更换套餐。":"We’re still checking the original purchase before changing plans.",n=Date.now()+6e5,r=wn({document:p,delay:()=>Date.now()<n?5e3:void 0,async run(){if(!I())return;let s=await i.read();if(ge!==r||!I())return;if(s.operationId!==e.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");let c=R(s);c.type==="native"?(Pt(),d.textContent=o?"原订单已关闭。你可以继续更换套餐。":"The original checkout is closed. You can continue changing plans.",y.textContent=o?"继续更换套餐":"Continue changing plans",f=()=>tt(),y.hidden=!1):(c.type==="complete"||c.type==="fulfillment"||c.type==="recording")&&(Pt(),B=null,y.hidden=!0,await V(s,!1))}});ge=r,Je=async()=>{try{await r.refresh()}finally{ge===r&&(d.textContent=t,y.hidden=!1)}},f=Je,y.textContent=o?"查询结果":"Check result",y.hidden=!1,d.textContent=t,r.schedule()}async function tt(e=!1){let t=B;if(!t)return;f=()=>tt(),C&&(y.textContent=o?"查询状态":"Check status"),y.hidden=!0;let n=Date.now()+2e4;for(;I();){let r=await i.read();if(r.operationId!==t.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");if(!I())break;let s=R(r);if(s.type==="native"){if(!Pe()&&a.prepareUpgradeReplacement){let c=await a.prepareUpgradeReplacement(t.operationId,t.intent);if(!I())return;jt=!0,$e(c)}B=null,C&&Te(C.quote),Kt(),v=t.selection,X=t.coupon,xe=!1,Re=!1,await qe();return}if(s.type==="complete"||s.type==="fulfillment"||s.type==="recording"){B=null,C?await ke(C.quote,r):await V(r,!1);return}if(e&&s.type==="checkout"){e=!1;try{await a.terminateCheckout(t.operationId)}catch(c){z(a.onError,c)}}if(Date.now()>=n){C&&s.type==="checkout"&&(B=null,await ke(C.quote,r));break}await Ye(1e3,p,J.signal)}!B||w||(C?(d.textContent=o?"仍在核对原升级单,暂时无法更换套餐。":"We’re still checking the original upgrade before changing plans.",y.hidden=!1):Jt())}async function Xt(e,t,n,r){if(f=()=>Xt(e,t,n,r),await a.beforeCheckoutReplacement?.(structuredClone(r)),!I())return;let s=i.operation;if(s?.operationId!==e||R(s).type!=="checkout"){f=null,s&&await V(s,!1);return}B={operationId:e,selection:t,coupon:n,intent:r},C&&(d.textContent=o?"正在切换套餐…":"Changing plan…",y.hidden=!0);let c=!1;try{await a.terminateCheckout(e)}catch(l){if(l instanceof k&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(l.code)){B=null,C&&(f=It,y.textContent=o?"查询状态":"Check status",y.hidden=!1),d.textContent=o?"请继续原订单,或等待它过期后再更换方案。":"Continue your original checkout, or wait for it to expire before changing plans.",z(a.onError,l);return}c=l instanceof k&&(l.status??0)>=500,z(a.onError,l)}I()&&await tt(c)}function vt(e,t,n,r,s){let c=oe(e).checkoutCoupons?.[t],l=c?c.products[n]:a.claimCoupon&&s?pn(e.capabilities,s,r):void 0;return l?.couponId&&l.planVersionId===n?{id:l.couponId,offerId:l.offerId}:void 0}function Vn(e){fe||v||i.quote||i.operation||Ke&&d.textContent===Ke||(d.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":o?"当前账号暂无可购买的方案。":"No plans are currently available for this account.")}let He=new Map,nt=!1;function Se(e,t,n,r,s,c){let l=_(e),m=!l&&e.lines.length===1?e.lines[0]:void 0,h=Ee(r,s,t.capabilities);if(!h||h!==(l?e.productVersionId:m?.productVersionId))return!1;let E=vt(t,n,h,s,c),q;try{q=Ue(t.document.screen,h,s,t.capabilities)}catch{return!1}if(l){let Z=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return Object.keys(q).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(q).every(([De,St])=>e.featureQuantities?.[De]===St)&&(!E||Z?.couponId===E.id&&(!E.offerId||Z.grantId===E.offerId))}if((E||oe(t).checkoutCoupons?.[n])&&(E?.id??null)!==(e.discount?.couponId??null))return!1;let G=Object.fromEntries((m?.prepaid??[]).map(Z=>[Z.internal_feature_id,Z.quantity]));return[...new Set([...Object.keys(q),...Object.keys(G)])].every(Z=>(q[Z]??0)===(G[Z]??0))}let R=e=>hn({quote:i.quote,operation:e,requestId:null,pending:!1,destroyed:w,canReselect:i.canReselect});async function Qe(e){let t=e.merchantExecution,n=R(e),r=n.type==="checkout"?n.checkoutUrl:e.checkoutUrl;if(!(!I()||!r||it(e)&&n.type!=="checkout"||a.checkoutNavigation==="after_confirmation"&&n.type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||He.get(e.operationId)===r)){He.set(e.operationId,r);try{a.onCheckoutUrl?await a.onCheckoutUrl(r):p.defaultView?.location.assign(r)}catch(s){throw He.delete(e.operationId),s}}}let we=(e,t=!1)=>{if(e instanceof Nt)f=null,d.textContent=e.customerMessage(o);else if(An(e))f=null,d.textContent=t?o?"当前无法在此购买,付款尚未开始。请联系商户。":"Purchases aren’t available here right now. Payment hasn’t started. Contact the merchant for help.":Ut(e,o);else if(t){let n=e instanceof k?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(f=null,d.textContent=o?"暂时无法为此套餐报价,付款尚未开始。":"Pricing for this plan is unavailable. Payment hasn’t started."):i.canReselect===!0&&!v?d.textContent=o?"未能取得报价,付款尚未开始。请重新选择套餐。":"We couldn’t prepare your price. Payment hasn’t started. Choose a plan again.":n==="COMMAND_PENDING"?d.textContent=o?"仍在准备报价,请重试以查看结果。":"Your price is still being prepared. Retry to check the result.":d.textContent=o?"未能取得报价,付款尚未开始。请重试。":"We couldn’t prepare your price. Payment hasn’t started. Try again."}else d.textContent=e instanceof k&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?Ut(e,o):e instanceof k?e.message:o?"操作未完成,请重试。":"This action couldn’t be completed. Try again.";y.hidden=f===null,Ke=d.textContent,t&&ae===void 0&&!U?.responsive&&d.scrollIntoView?.({block:"nearest"}),z(t&&x?.quoteError?x.quoteError:a.onError,e)},Be=new WeakMap;function je(e){fe=e,y.disabled=e,ce.disabled=e,N?.updateCapabilities?.(oe(u),Ce(u));for(let t of de?.querySelectorAll("button")??[])e?(Be.has(t)||Be.set(t,t.disabled),t.disabled=!0):Be.has(t)&&(t.disabled=Be.get(t),Be.delete(t)),Lt(t)}function Zt(){Q&&(d.textContent=Q.message,y.textContent=o?"重试":"Retry",y.disabled=!1,y.hidden=!Q.retry,ce.disabled=!0)}function kt(){d.textContent=o?"暂时无法操作,请稍后重试。":"This action is unavailable right now. Try again in a moment."}async function $n(e){if(a.beforeAction)try{await a.beforeAction()}catch(t){throw t instanceof Nt?(v=null,xe=!1,Re=!1,f=null):f=e,t}}async function j(e,t){if(fe||w||Q)return;if(!I()){kt();return}let n=e===qe,r=n?_n:Dn;ae=t!==void 0&&N?.updateCheckoutControls?t:void 0,d.textContent=r,je(!0),ve(),y.hidden=!0;try{if(e!==on&&e!==It&&e!==Et&&e!==Je&&(e!==et||!a.resumeCheckout)&&await $n(e),w||Q)return;if(!I()){f=e,y.hidden=!1,kt();return}await e()}catch(s){w||we(s,n)}finally{ae=void 0,je(!1),ve(),Q?Zt():d.textContent===r&&(d.textContent="")}}async function en(e){await Tn(le,e,a)}function Te(e,t){C=t?{quote:e,phase:t}:void 0,t==="checking"?(ae??=v?.actionId??Gt(u)[0],d.textContent=gt,f=It,y.textContent=o?"查询状态":"Check status",y.hidden=!0):ae=void 0,N?.updateCapabilities(oe(u),Ce(u)),ve()}function tn(e){return e instanceof k&&(e.code==="COMMAND_PENDING"||e.reason==="RESULT_UNKNOWN"||e.code==="NETWORK_ERROR"||e.code==="TIMEOUT"||e.status===429||(e.status??0)>=500)}function nn(e,t){Dt(e,{...t,featureQuantities:t.featureQuantities??{}},"Purchase operation changed")}async function It(){C&&await ke(C.quote)}async function ke(e,t){Te(e,"checking"),Ke="";let n=1e3;Ve=!0,z(a.onObservationChange,!0);try{for(let r=t;I();r=void 0){if(!r){try{r=await i.read()}catch(s){if(!tn(s))throw s}if(!I())return}if(r){nn(r,e);let s=R(r);if(s.type==="checkout"){Te(e,"payment"),d.textContent=o?"请先完成原订单的付款。":"Finish paying for this upgrade.",y.hidden=!1;return}if(s.type==="complete"){Te(e,"complete"),f=null;let c=u.capabilities.plans[e.productVersionId]?.name,l=e.merchantTerms?.subscriptionTerms?.items,m=l?.length===1?l[0].interval:void 0,h=m==="year"?o?"年付":"annual billing":m==="month"?o?"月付":"monthly billing":null;d.textContent=c?o?`已升级到 ${c}${h?" "+h:""}。`:`Upgraded to ${c}${h?" ("+h+")":""}.`:o?"已成功升级。":"Plan upgraded.",await en(r);return}if(s.type==="native"&&!_e(r)){Te(e),v=null,f=null,d.textContent=o?"付款没有成功,套餐未变更。请检查付款方式后重新选择套餐。":"Your payment didn’t go through, so your plan is unchanged. Check your payment method, then choose a plan again.",y.textContent=o?"重试":"Retry";return}if(r.problem&&!["RESULT_UNKNOWN","STATE_CHANGED"].includes(r.problem.reason??""))throw new k(r.problem.code,o?"暂时无法完成升级。":"The upgrade needs attention.",void 0,void 0,r.problem)}await Ye(n,p,J.signal),n=Math.min(n*1.5,15e3)}}finally{Ve=!1,z(a.onObservationChange,!1)}}async function Et(){let e=C?.quote;if(!e)return;let t=await i.read();if(nn(t,e),R(t).type!=="checkout")return ke(e,t);if(a.resumeCheckout){await a.resumeCheckout(t.operationId);return}He.delete(t.operationId),await Qe(t)}function rn(e){return Ot(i).type==="recording"||R(e).type==="recording"}function an(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],r=t?t.totalMinor:_(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),s=t?n.length===1&&n[0]?.amountMinor===r&&n[0]:!_(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],c=r===null?be(t.subtotalMinor-t.discountMinor,e.currency)+(o?" + 待确认税费":" + tax confirmed at checkout"):be(r,e.currency)+(s?Le(s.interval,o?"zh-CN":"en",s.intervalCount??1):""),l=_(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(m=>m.productName).join(", ");return{label:l?`${l} · ${c}`:c,recurring:s}}async function V(e,t=a.checkoutNavigation!=="after_confirmation"){if(w)return;if(!I()){f=async()=>V(await i.read()),y.hidden=!1;return}let n=e.quote??i.quote;if(yt(n)&&(e.confirmedAt||e.merchantExecution))return ke(n,e);if(d.textContent=Sn(e.status,o),rn(e)){let h=e.merchantExecution?.recordingStatus==="failed";d.textContent=h?o?"付款和商户处理已完成,但交易记录失败。请联系商户修复,勿重复购买。":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"付款和商户处理已完成,正在确认交易记录。请勿重复购买。":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",y.textContent=o?"查询记录":"Check recording",f=async()=>V(await i.read()),y.hidden=!1;return}if(e.problem&&R(e).type!=="native"){let h=e.problem;f=Oe,y.textContent=o?"检查并恢复原操作":"Check and recover original purchase",we(new k(h.code,h.reason==="RESULT_UNKNOWN"?o?"付款结果尚未确定,请恢复原操作,暂勿重复购买。":"The payment result is unknown. Recover the original purchase before buying again.":h.phase==="fulfillment"?o?"付款已记录,商户权益处理需要核对。":"Payment was recorded. Access fulfillment needs attention.":h.code==="CAPABILITY_UNAVAILABLE"?o?"商户尚不支持本次购买所需的完整能力,请处理后恢复原操作。":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":h.code==="NOT_CONFIGURED"?o?"付款服务连接需要处理,请联系商户后恢复原操作。":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"原购买操作需要处理,请查询或恢复此操作。":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,h));return}if((e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"||e.merchantExecution?.type==="subscription_change"&&e.merchantExecution.status==="applied")&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(d.textContent=o?"付款已记录,正在等待商户完成处理。":"Payment was recorded. Waiting for merchant fulfillment."),Ge(e)&&R(e).type==="complete"){f=null,await en(e);return}if(!_e(e)&&R(e).type!=="fulfillment"){if(i.canReselect===!1){d.textContent=o?"正在核对原购买结果":"Checking the original purchase result",y.textContent=o?"查询结果":"Check result",f=async()=>V(await i.read()),y.hidden=!1;return}e.status==="cancelled"?d.textContent=o?"这笔购买已取消,可以重新选择方案。":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(d.textContent=o?"这笔购买未能完成,可以重新选择方案。":"This purchase didn’t go through. Choose a plan to try again."),y.textContent=o?"重试":"Retry",f=null,v=null;return}if(!t&&R(e).type==="checkout"){if(B){Jt();return}if(ye()){d.textContent="",nt=!1,f=null,y.hidden=!0,N?.updateCapabilities?.(oe(u),Ce(u)),ve();return}let h=i.quote,E=h?.operationId===e.operationId?an(h).label:"";d.textContent=nt?E?o?`${E} 尚未付款。再次选择该方案即可继续付款。`:`${E} is still unpaid. Choose it again to continue paying.`:o?"之前的购买尚未付款。再次选择该方案即可继续付款。":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",nt=!1,f=null;return}await Qe(e);let r=Date.now(),s=r+6e5,c=2e3,l=R(e).type!=="checkout",m=()=>l&&Date.now()-r<15e3;Ve=!0,z(a.onObservationChange,!0);try{for(;!w&&Date.now()<s;){if(await Ye(m()?700:c,p,J.signal),w)return;if(!I()){f=async()=>V(await i.read()),y.hidden=!1;return}let h=await i.read();if(R(h).type==="checkout"&&(l=!1),!t&&R(h).type==="checkout"){await V(h,!1);return}if(!h.problem&&_e(h)&&await Qe(h),!_e(h)||h.problem||rn(h)){await V(h);return}m()||(c=Math.min(c*1.5,3e4))}}finally{Ve=!1,z(a.onObservationChange,!1)}f=async()=>V(await i.read()),y.hidden=!1}async function xt(e=!1){let t=await i.read();if(w)return;if(!I()){f=()=>xt(e),y.hidden=!1;return}let n=i.quote;if(n&&Dt(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&(it(t)?["prepared","quoted"].includes(t.status):t.status==="pending")&&(it(t)||t.quoteFinalized===!1)&&!t.confirmedAt&&!t.checkoutUrl&&!("nativePurchase"in t&&t.nativePurchase)&&!t.merchantExecution&&!t.problem&&!i.pendingCancellation){if(a.purchaseConfirmation!=="paywall"){e?await Oe():f=null;return}setTimeout(sn,0,n);return}await V(t,e||void 0)}async function on(){await xt()}async function Hn(e){d.textContent=gt;let t=Date.now()+12e3;for(;!w&&Date.now()<t&&(await Ye(1500,p,J.signal),!(w||!I()));){let n;try{n=await i.read()}catch{break}if(n.problem?.reason!=="RESULT_UNKNOWN")return n}return e}async function Oe(){if(i.quote&&!(Date.parse(i.quote.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");Kt();let e=i.quote;if(yt(e)){Te(e,"checking");let n;try{n=await i.confirm()}catch(r){if(!tn(r))throw r;return ke(e)}return ke(e,n)}f=Oe;let t=await i.confirm();if(!I()){f=Oe,y.hidden=!1;return}if(t.problem?.reason==="RESULT_UNKNOWN"&&(t=await Hn(t)),t.problem){await V(t);return}if(_e(t)){if(R(t).type==="checkout")await Qe(t);else if(t.execution&&t.execution.provider!=="merchant"||"nativePurchase"in t&&t.nativePurchase){if(!a.onPurchase)throw new k("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await a.onPurchase({operation:t,signal:J.signal})}}f=async()=>V(await i.read()),await V(t,!0)}function sn(e){if(w)return;de?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());d.textContent=t?o?"此报价已过期。请先取消,再重新选择。":"This quote has expired. Cancel it, then choose again.":"";let n=p.createElement("div"),r=p.createElement("button"),s=p.createElement("button"),c=p.createElement("div"),l=p.createElement("p"),m=e.merchantTerms,h=o?"zh-CN":"en",E=m?.subscriptionTerms?.items??[],q=m?m.subscriptionTerms?.trial?.days:_(e)?void 0:e.lines.find(g=>g.trial)?.trial?.days,G=_(e)?m?m.totalMinor:e.totalMinor:q===void 0?null:m?m.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(g=>g.trial)?0:null,Ne=(g,P)=>o?`${P} 天试用结束后 ${g}`:`Then ${g} after the ${P}-day trial`,{label:Z,recurring:De}=an(e),St=_(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(g=>g.productName).join(", "),un=G===null?"":`${o?"今天应付":"Due today"} ${be(G,e.currency)}`;l.textContent=un?[St,un].filter(Boolean).join(" · "):Z,r.textContent=_(e)?o?"确认变更":"Confirm change":o?"确认购买":"Confirm purchase",r.disabled=t,s.textContent=o?"取消":"Cancel",n.style.cssText=D.panel,l.style.cssText=D.summary,c.style.cssText=D.actions,r.style.cssText=D.primary,s.style.cssText=D.secondary,Lt(r),r.onclick=()=>{j(Oe)};let dn=async()=>{let g=await i.cancel();w||(n.remove(),de=null,await V(g))};s.onclick=()=>{f=dn,j(dn)};let Y=p.createElement("div");if(Y.style.cssText=D.terms,_(e)){for(let[P,S]of Object.entries(e.featureQuantities??{})){let $=i.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(Qn=>Qn.internalFeatureId===P),rt=p.createElement("p");rt.textContent=`${$?.name??P} · ${S} ${o?"份":"packs"}${$?` × ${$.terms.units}`:""}`,Y.append(rt)}for(let[P,S]of[[o?"原订阅抵扣":"Unused subscription credit",e.creditMinor],[o?"新套餐费用":"New plan charge",e.debitMinor],[o?"优惠减免":"Offer savings",m?.discountMinor??e.discountMinor],[o?"税费":"Tax",m?m.taxMinor:e.taxMinor]]){let $=p.createElement("p");$.textContent=`${P}: ${S===null?o?"结账时确认":"Confirmed at checkout":be(S,e.currency)}`,Y.append($)}let g=p.createElement("p");g.textContent=`${o?"生效时间":"Effective"}: ${e.effectiveAt}`,Y.append(g)}if(m){for(let P of E){if(G===null&&P===De)continue;let S=p.createElement("p"),$=be(P.amountMinor,e.currency)+Le(P.interval,h,P.intervalCount);S.textContent=G!==null&&q!==void 0?Ne($,q):$,P.amountAfterOfferMinor!==void 0&&(S.textContent+=` · ${o?"优惠结束后":"After the offer"} ${be(P.amountAfterOfferMinor,e.currency)}${Le(P.interval,h,P.intervalCount)}`),Y.append(S)}let g=m.subscriptionTerms?.trial;if(g){let P=p.createElement("p");P.textContent=o?`试用 ${g.days} 天;${g.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${g.days}; ${g.cardRequired?"a payment method is required":"no payment method is required"}`,Y.append(P)}for(let P of[...m.expectedEffects.map(S=>S.description),...m.requiredConsents.map(S=>S.summary)]){let S=p.createElement("p");S.textContent=P,Y.append(S)}}else if(!_(e)){for(let g of e.lines){if(G!==null||g!==De){let P=p.createElement("p"),S=`${be(g.catalogAmountMinor,e.currency)}${Le(g.interval,h,g.intervalCount??1)}`;P.textContent=G!==null&&g.trial?(e.lines.length>1?`${g.productName} · `:"")+Ne(S,g.trial.days):`${g.productName} · ${S}`,Y.append(P)}for(let P of g.prepaid??[]){let S=p.createElement("p"),$=i.view?.capabilities.plans[g.productVersionId]?.prepaid?.find(rt=>rt.internalFeatureId===P.internal_feature_id);S.textContent=`${$?.name??P.internal_feature_id} · ${P.quantity} ${o?"份":"packs"} × ${P.terms.units}`,$&&(S.textContent+=Le($.reset==="week"||$.reset==="month"||$.reset==="year"?$.reset:"one_time",h,$.resetCount)),Y.append(S)}if(g.trial){let P=p.createElement("p");P.textContent=o?`试用 ${g.trial.days} 天;${g.trial.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${g.trial.days}; ${g.trial.cardRequired?"a payment method is required":"no payment method is required"}`,Y.append(P)}}if(!e.charge){let g=p.createElement("p");g.textContent=o?"目录价格;最终金额以结账时税费和试用规则为准。":"Catalog price; the final charge depends on checkout taxes and trial terms.",Y.append(g)}}for(let g of Y.children)g.style.margin="0";c.append(r,s),n.append(l,...Y.childElementCount?[Y]:[],c),W.prepend(n),U?.responsive||n.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),de=n,fe&&je(!0),f=null}async function qe(){if(!v)return;if(f=qe,!xe){let n=i.view,r=n?.document.buttons[v.actionId],s=n&&r?.type==="checkout"?Ee(r.product,v.selection,n.capabilities):null;if(!n||!s)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!Re){let l=Ft(),m=l?await l.result:void 0;if(w)return;let h=a.resolveSubscriptionChange;if(h||m){let E={actionId:v.actionId,productVersionId:s,featureQuantities:Ue(n.document.screen,s,v.selection,n.capabilities)},q=m?[async()=>m(E)]:[],G=h?await h(E,...q):await q[0]?.();if(w)return;G!==void 0&&(v.subscriptionChange=fn.parse(G))}Re=!0}let c=X?.offerId;if(X&&!c){if(!a.claimCoupon)throw new k("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:l}=await a.claimCoupon(X.id,v.requestId);if(w)return;if(!l||l.couponId!==X.id||l.status!=="issued"||!(Date.parse(l.expiresAt)>Date.now()))throw v=null,X=void 0,f=async()=>{$e(await i.refresh()),f=null},new k("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");c=l.id}if(!X&&!n.document.screen.actions.some(l=>l.id===v?.actionId&&typeof l.properties.couponBinding=="string")&&(c=await a.resolveOfferId?.({actionId:v.actionId,productVersionId:s,featureQuantities:Ue(n.document.screen,s,v.selection,n.capabilities)})),w)return;c!==void 0&&(v.offerId=c),xe=!0}if(!I()){y.hidden=!1;return}let e;try{e=await i.preview(v)}catch(n){throw i.canReselect===!0&&(v=null,xe=!1,Re=!1,X=void 0,f=null),n}if(X&&(_(e)?(()=>{let n=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return n?.couponId!==X.id||n.grantId!==v.offerId})():e.discount?.couponId!==X.id||e.discount.offerId!==v.offerId))throw new k("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(w)return;let t=e.merchantTerms;if(a.purchaseConfirmation!=="paywall"||a.confirmOnHostedCheckout&&I()&&!_(e)&&e.provider==="merchant"&&e.billingSubscriptionId===null&&t?.request.action==="purchase"&&t.request.mode==="subscription"&&t.subscriptionTerms?.trial===null&&t.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){if(!I()){y.hidden=!1;return}if(!(Date.parse(e.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");let n=ae?"":o?"正在打开收银台…":"Opening checkout…";d.textContent=n;try{await Oe()}catch(r){w||we(r)}finally{d.textContent===n&&(d.textContent="")}return}sn(e)}function Ie(e="destroy",t=!1){if(w)return;w=!0;let n=pt;pt=void 0,z(n),a.signal?.removeEventListener("abort",se),i.signal?.removeEventListener("abort",se),M.finish("dismissed"),Vt?.(),Pt(),J.abort(),Mt?.disconnect(),N?.destroy(),i.destroy(),A.removeEventListener("cancel",cn),O.remove(),L.remove(),t||ln(),e==="dismiss"&&z(a.onDismiss)}function ln(){if(U?.destroy(),ue){ue.release();return}A.open&&A.close(),A.remove(),T()}F=Ie;async function Fe(){if(!he||w||ze||ie==="closing"||!ie&&!I())return;if(!x){Ie("dismiss");return}let e=p.createElement("p");e.setAttribute("role","status"),e.textContent=o?"正在关闭…":"Closing…",me||(me=p.createElement("div"),me.style.cssText=W.style.cssText,W.replaceWith(me),pe.inert=!0),O.hidden=!1,me.replaceChildren(e,O),ie="closing",O.setAttribute("aria-disabled","true"),O.focus({preventScroll:!0});try{await x.dismiss()}catch(t){w||z(a.onError,t)}w||(ie="retry",e.textContent=o?"未能确认关闭,请重试。":"Could not confirm closure. Try again.",O.textContent=o?"重试关闭":"Retry closing",O.removeAttribute("aria-label"),O.removeAttribute("aria-disabled"))}O.onclick=()=>{Fe()};function cn(e){e.preventDefault(),Fe()}A.addEventListener("cancel",cn),ce.onclick=()=>{j(C?Et:et)},y.onclick=()=>{if(Q){Q.retry?.();return}f&&j(f)};function Rt(e){M.finish("error",e),Ie()}function At(){if(!(!Qt||he||w||ze||U&&!I()))try{let e=t=>{a.focusAtReveal&&(T=_t(p)),N?.setHidden?.(!1),ft?.(),U&&(A.open||A.showModal(),U.responsive&&A.focus({preventScroll:!0}),!t&&a.loading!=="host"&&Cn(A,U.type,U.responsive)),t&&a.loading!=="host"&&typeof pe.animate=="function"&&!p.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&pe.animate([{opacity:.55},{opacity:1}],{duration:160,easing:"ease-out"}),he=!0,Xe()};x?x.present(t=>M.present(n=>e(t??n))):M.present(e)}catch(e){Rt(e),we(e)}}try{if(Me.type==="inline"?(ct(),ft=xn(L,H),H.append(L)):(A.setAttribute("aria-label",u.document.name),O.textContent="×",O.setAttribute("aria-label",o?"关闭":"Close"),Pn(O,u.document.screen.theme),O.hidden=gn(u.document),(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&ue?.content?ue.content.append(O,L):A.replaceChildren(O,L),ue||H.append(A),U=bn(A,{...u.document.screen,presentation:Me},dt),U.latch(),U.responsive&&(L.style.display="flex",L.style.flexDirection="column",L.style.maxHeight="100%",pe.style.overflow="clip",pe.style.minHeight="0"),ue||(ft=En(A))),st&&ee){let n=st(ee);if(typeof n=="function"&&(w?z(n):pt=n),w)throw new DOMException("Presentation cancelled","AbortError");ct()}N=ne(pe,{mode:"live",rendererUrl:"bundled",title:u.document.name,closeActions:Ln,onAuthoredClose(n){ie||w||(O.hidden=n)},hostPresentation:()=>U?.type??Me.type,reportContentHeight:U?.responsive,onResize:n=>{if(!U?.responsive)return;let r=Math.min(n,ut);pe.style.height=`${r}px`,U.setContentHeight(r+Ht())},onSelection(n){for(let[r,s]of Object.entries(n))typeof s=="number"&&typeof K[r]=="number"&&K[r]!==s&&Bt.add(r);K=n,ve(),Xe()},onAction(n,r={},s,c){if(!he||w||ie)return;let l=i.view,m=l?.document.buttons[n];if(!m)return;if(Q){m.type==="close"&&Fe();return}if(m.type==="close"&&x&&a.resumeCheckout&&i.operation&&mn(R(i.operation))){Fe();return}if(fe)return;if(!I()){kt();return}if(m.type==="close"){j(async()=>{x?.closeAction?await x.closeAction(n):await a.onAction?.(n),Ie(a.onAction?"action":"dismiss")});return}if(m.type==="action"){f=async()=>{if(m.action.type==="event"){if(!a.onEvent)throw new k("EVENT_HANDLER_REQUIRED","Provide the event handler");await a.onEvent(m.action.event)}else a.onOpenUrl?await a.onOpenUrl(m.action.url):p.defaultView?.location.assign(m.action.url);await a.onAction?.(n),f=null},j(f);return}if(ye()&&B){!ge&&B.selection.actionId===n&&j(()=>tt(!0),n);return}if(C){if(C.phase==="payment"&&l&&Se(C.quote,l,n,m.product,r,c)){j(Et,n);return}if(!bt())return}if(!Pe()&&!bt()){ye()&&l&&i.quote&&i.operation&&R(i.operation).type==="checkout"&&Se(i.quote,l,n,m.product,r,c)?j(et,n):d.textContent=o?"当前只能继续原订单。":"Only your original checkout is available.";return}if(de&&i.canReselect===!1){d.textContent=o?"请先确认或取消当前购买。":"Confirm or cancel the current purchase first.",U?.responsive||de.scrollIntoView?.({block:"nearest"}),de.querySelector("button")?.focus({preventScroll:!0});return}if(ye()&&a.terminateCheckout&&l&&i.quote&&i.operation&&i.canReselect===!1&&R(i.operation).type==="checkout"){if(Se(i.quote,l,n,m.product,r,c)){j(et,n);return}let E=Ee(m.product,r,l.capabilities),q;try{if(!E)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");q=Ue(l.document.screen,E,r,l.capabilities)}catch(De){we(De);return}let G=i.operation.operationId,Ne={actionId:n,requestId:crypto.randomUUID(),selection:structuredClone(r)},Z=vt(l,n,E,r,c);j(()=>Xt(G,Ne,Z,{actionId:n,productVersionId:E,selection:Ne.selection,featureQuantities:q}),n);return}if((i.quote||v)&&i.canReselect===!1){let E=!!l&&!!i.quote&&Se(i.quote,l,n,m.product,r,c);nt=!!i.quote&&!E,f=i.quote?()=>xt(E):qe,j(f,n);return}let h=l&&Ee(m.product,r,l.capabilities);if(!l||!h){we(new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(a.onPurchaseIntent){f=null,j(async()=>{let E={actionId:n,productVersionId:h,selection:structuredClone(r),featureQuantities:Ue(l.document.screen,h,r,l.capabilities)};ht=!0,await a.onPurchaseIntent(E)},n);return}if(v&&v.actionId!==n){we(new k("COMMAND_PENDING","Finish the current purchase"));return}v||(X=vt(l,n,h,r,c),v={requestId:crypto.randomUUID(),actionId:n,selection:structuredClone(r)},xe=!1,Re=!1),j(qe,n)},onEscape:()=>{Fe()},onError:n=>{let r=new Error(n);!he&&!w&&Rt(r),we(r)},onRendered:n=>{n&&A.setAttribute("aria-label",n),Qt=!0,At()}}),N.setHidden?.(!0),dt();let e=ye()&&!!i.quote&&!!i.operation&&R(i.operation).type==="checkout";K=i.quote?Nn(u,i.quote)??at(u,{}):at(u,{}),N.update(u.document.screen,lt,{capabilities:oe(u),unavailableActions:Ce(u),serverInput:{bindings:[],answers:{}},...Object.keys(K).length?{selection:K}:{}}),Vt=i.subscribe?.($e),$e(i.view??u),await M.wait(N.ready);let t=i.operation;(!e||yt(i.quote))&&(i.quote||t&&(t.confirmedAt||t.checkoutUrl||Ge(t)))&&(f=on,j(f))}catch(e){throw Rt(e),e}return{check:le,host:{get currentResolution(){return u},setPurchaseRecovery(e,t){Q={message:e,retry:t},N?.updateCapabilities?.(oe(u),Ce(u)),ve(),Zt()},get subscriptionUpgradeActive(){return C!==void 0},get observing(){return Ve},get recovery(){return Un()},async prepareFallback(){if(fe||w||ie||ht)return{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null};je(!0);try{let e=await yn(i);return e.type==="native"&&Ie(),e}finally{je(!1)}},setSuspended(e){ze=e,L.hidden=e,e&&A.open?A.close():!e&&!he?At():!e&&!w&&he&&Me.type!=="inline"&&!A.open&&A.showModal()},destroy:Ie,retainPurchaseDialog(){if(!(w||!A.open||!A.isConnected))return Ie("destroy",!0),{dialog:A,content:ue?.content,release:ln}},refresh:async()=>{if(!I()){if(i.view)return i.view;throw new k("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await i.refresh();return $e(e),At(),e}}}}export{Pr as a};
@@ -1 +1 @@
1
- import{C as K,b as U,d as D,v as _}from"./chunk-56YCOGQZ.js";import{a as z,c as F}from"./chunk-O5YYORDW.js";import{d as $}from"./chunk-7OJIW75D.js";import{i as C,j as m,l as O,m as g}from"./chunk-XIBJF5E6.js";import{b as e}from"./chunk-YLH3AYCK.js";var I=m.refine(t=>/[1-9]/.test(t),"Quantity must be positive"),j=e.string().min(1).max(120),R=e.enum(["cap","overflow"]),p=(t,n)=>{let[i,u=""]=t.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");return BigInt(i)*10n**BigInt(n)+BigInt(u.padEnd(n,"0"))},A=t=>{try{return t()}catch{return!1}},le=e.discriminatedUnion("operation",[e.object({operation:e.literal("quote"),overageBehavior:R.optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g}).strict(),e.object({operation:e.literal("consume"),overageBehavior:R.optional(),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:m,properties:g,idempotencyKey:j}).strict(),e.object({operation:e.literal("reserve"),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g,idempotencyKey:j,expiresInSeconds:e.number().int().min(1).max(86400)}).strict(),e.object({operation:e.literal("confirm"),operationId:e.uuid(),quantity:I,properties:g.optional(),idempotencyKey:j}).strict(),e.object({operation:e.literal("refund"),operationId:e.uuid(),quantity:I,idempotencyKey:j}).strict(),e.object({operation:e.literal("release"),operationId:e.uuid(),idempotencyKey:j}).strict()]),J=e.object({internal_credit_feature_id:e.uuid().nullable(),internal_metered_feature_id:e.uuid(),dimension:e.string().min(1).max(64),counterKey:e.string().min(1).max(240),cycleStart:e.iso.datetime({offset:!0}),unitCost:m,units:I,amount:C,tier:e.number().int().min(1).max(12).nullable()}).strict(),Q=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function N(t,n){let i=t.reduce((u,a)=>u+p(a.units,12),0n)-p(n,12);return t.some(u=>u.funding==="balance")?i>=-100n&&i<=100n:i===0n}var v=e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q.refine(t=>/[1-9]/.test(t)),amount:C}),e.strictObject({funding:e.literal("unbilled"),units:Q.refine(t=>/[1-9]/.test(t))}),e.object({funding:e.literal("prepaid"),sourceId:e.uuid(),units:I,amount:C,pricing:e.array(J).min(1).max(12)}).strict().refine(t=>A(()=>t.pricing.reduce((n,i)=>n+p(i.units,6),0n)===p(t.units,6)&&t.pricing.reduce((n,i)=>n+p(i.amount,12),0n)===p(t.amount,12)&&t.pricing.every(n=>p(n.unitCost,6)*p(n.units,6)===p(n.amount,12))),"Frozen pricing must conserve allocated units and amounts"),e.object({funding:e.literal("postpaid"),invoiceLineId:e.uuid().nullable(),units:I,authorizationId:e.uuid()}).strict()]),B=e.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),de=e.object({allowed:e.boolean(),internal_feature_id:e.uuid(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),reason:B.nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.allowed?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"A quote must conserve its accepted units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0&&/[1-9]/.test(t.quantity):t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Explicit overage behavior must retain the requested quantity"),me=e.object({id:e.uuid(),internal_feature_id:e.uuid(),kind:e.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),createdAt:e.iso.datetime({offset:!0}),reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:e.iso.datetime({offset:!0}).nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.accepted?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"An operation must conserve its requested units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0:t.kind==="consume"&&t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(t=>/[1-9]/.test(t.quantity)||t.kind==="consume","Only consumption can record a zero cost event").refine(t=>t.allocations.every(n=>n.funding!=="postpaid"||n.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(t=>t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null)&&(t.kind!=="reserve"||!t.accepted||t.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var X=e.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Y=e.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),T=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable()}),ye=T.extend({quantity:m,expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:e.string().min(1).max(120),properties:g.refine(t=>Object.keys(t).length<=13&&!Object.keys(t).some(n=>n.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),V=T.extend({operationId:e.uuid().nullable(),usage:m,capacity:X.nullable(),remaining:Y.nullable(),withinLimit:e.boolean(),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}).strict().superRefine((t,n)=>{let i=u=>{let a=u.startsWith("-"),[s,r=""]=(a?u.slice(1):u).split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(s)*10n**12n+BigInt(r.padEnd(12,"0")))};(t.capacity===null!=(t.remaining===null)||(t.capacity===null?!t.withinLimit:t.remaining===null||i(t.remaining)!==i(t.capacity)-i(t.usage)||t.withinLimit!==i(t.remaining)>=0n)||t.revision===0!=(t.operationId===null)||t.operationId===null!=(t.updatedAt===null))&&n.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var y=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),f=e.iso.datetime({offset:!0}),ee=e.enum(["access","metered","credit"]),q={internal_feature_id:e.uuid(),key:O,name:e.string().min(1).max(120),kind:ee},we=e.object({customerId:e.uuid(),snapshotAt:f,memberships:e.array(e.object({id:e.uuid(),productId:e.string().min(1).max(255),productVersionId:e.uuid(),billingProductVersionId:e.uuid(),version:e.number().int().positive(),key:e.string().min(1).max(64),name:e.string().min(1).max(120),groupId:e.string().max(255).nullable(),membershipType:e.enum(["main","addon"]),status:e.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:e.boolean(),accessEnabled:e.boolean(),renewalChange:e.object({productVersionId:e.uuid(),name:e.string().min(1).max(120),version:e.number().int().positive(),effectiveAt:f,benefitsAppliedAt:f.nullable(),timing:e.enum(["immediate","renewal"]),changeKind:e.enum(["plan","seats","quantity"]),feature:e.strictObject({internal_feature_id:e.uuid(),name:e.string().min(1).max(80),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).optional(),seat:e.object({key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).strict().nullable(),status:e.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(t=>t.changeKind==="seats"==(t.seat!==null)&&t.changeKind==="quantity"==(t.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:e.object({phase:e.enum(["paid","trial"]),startsAt:f,endsAt:f.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:e.boolean(),balances:e.array(e.object({...q,usageType:e.enum(["consumable","non_consumable"]).nullable(),accessible:e.boolean(),unlimited:e.boolean(),available:y,held:y,debt:y,nextExpiresAt:f.nullable(),usage:V.nullable()}).strict().refine(t=>t.kind==="metered"==(t.usageType!==null)&&(t.accessible||t.available==="0"&&t.held==="0")&&(t.usageType==="non_consumable"?t.usage!==null&&t.usage.internal_feature_id===t.internal_feature_id&&t.unlimited===(t.usage.capacity===null)&&t.available===(t.usage.remaining===null||t.usage.remaining.startsWith("-")?"0":t.usage.remaining)&&t.held==="0"&&t.debt==="0":t.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:e.boolean()}).strict(),Z=e.enum(["source","usage","transaction","invoice","debt","settlement"]),E=e.object({at:f,id:e.uuid(),type:Z}).strict(),ke=e.object({type:Z.nullable(),resourceKey:O.optional(),kind:e.enum(["purchase","refund"]).optional(),topup:e.boolean().optional(),from:e.iso.date().nullable(),to:e.iso.date().nullable(),after:E.nullable(),limit:e.number().int().min(1).max(50)}).strict().refine(t=>!t.from||!t.to||t.from<=t.to,"Date range is reversed"),w={id:e.uuid(),occurredAt:f},te=e.discriminatedUnion("type",[e.strictObject({...w,type:e.literal("invoice"),status:e.string().min(1).max(80),paid:y,refunded:y,currency:z,externalId:e.string().nullable()}),e.object({...w,...q,type:e.literal("source"),reason:e.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:y,unlimited:e.boolean(),status:e.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:f,expiresAt:f.nullable(),orderId:e.uuid().nullable(),parentSourceId:e.uuid().nullable()}).strict(),e.object({...w,type:e.literal("usage"),internal_feature_id:e.uuid(),name:e.string().min(1).max(120),kind:e.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),properties:g,reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:f.nullable(),charges:e.array(e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q,amount:y}),e.strictObject({funding:e.literal("unbilled"),units:Q}),e.object({...q,funding:e.literal("prepaid"),amount:y}).strict(),e.object({funding:e.literal("postpaid"),invoiceId:e.uuid(),invoiceLineId:e.uuid(),authorizationId:e.uuid(),units:m,currency:z}).strict()])).max(500)}).strict().refine(t=>(t.kind==="set_usage"||t.kind==="consume"&&t.quantity==="0"?t.accepted&&t.reason===null&&t.charges.length===0&&t.reservationStatus===null:t.accepted?t.reason===null&&t.charges.length>0:t.reason!==null&&t.charges.length===0)&&t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),e.object({...w,type:e.literal("transaction"),purpose:e.enum(["product","invoice"]),productVersionId:e.uuid().nullable(),productName:e.string().min(1).max(120).nullable(),productVersion:e.number().int().positive().nullable(),invoiceId:e.uuid().nullable(),orderId:e.uuid(),originalId:e.uuid().nullable(),kind:e.enum(["purchase","refund"]),amountMinor:e.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(t=>t.currency===null==(t.amountMinor===null)&&(t.purpose==="product"?t.productVersionId!==null&&t.productName!==null&&t.productVersion!==null&&t.invoiceId===null:t.productVersionId===null&&t.productName===null&&t.productVersion===null&&t.invoiceId!==null)&&t.kind==="refund"==(t.originalId!==null)&&(t.kind!=="refund"||t.amountMinor===null||t.amountMinor>0),"Payment fact provenance is incomplete"),e.object({...w,...q,type:e.literal("debt"),sourceId:e.uuid(),transactionId:e.uuid(),amount:y}).strict(),e.object({...w,...q,type:e.literal("settlement"),sourceId:e.uuid(),debtId:e.uuid(),kind:e.enum(["payment","usage_refund","payment_return"]),amount:y}).strict()]),je=e.object({customerId:e.uuid(),rows:e.array(te).max(50),nextCursor:E.nullable()}).strict().refine(t=>new Set(t.rows.map(n=>n.type+n.id)).size===t.rows.length,"A page cannot repeat a fact").refine(t=>{let n=t.rows.at(-1);return!t.nextCursor||!!(n&&n.id===t.nextCursor.id&&n.type===t.nextCursor.type&&n.occurredAt===t.nextCursor.at)},"Cursor must name the final displayed fact");var Ce=e.discriminatedUnion("kind",[e.object({kind:e.literal("ledger"),cursor:E}).strict(),e.object({kind:e.literal("billing"),cursor:e.uuid()}).strict()]),ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ie=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),e.union([e.string().max(500),e.boolean(),e.array(e.string().max(500)).max(50)])).refine(t=>Object.keys(t).length<=40,"Too many answers"),re=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function L(t,n=0){return n>20?!0:!!t&&typeof t=="object"&&(Array.isArray(t)?t.some(i=>L(i,n+1)):Object.entries(t).some(([i,u])=>["__proto__","constructor","prototype"].includes(i)||re.test(i)||L(u,n+1)))}var ae=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ze=e.record(ne,$).refine(t=>Object.keys(t).length<=20,"Too many parameters").refine(t=>!L(t)&&!ae.test(JSON.stringify(t)),"Credentials cannot be screen parameters");var W=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oe=e.array(e.object({variable:W,componentId:W,required:e.boolean()}).strict()).max(40).refine(t=>new Set(t.map(n=>n.variable)).size===t.length&&new Set(t.map(n=>n.componentId)).size===t.length,"Input bindings must be unique"),Re=e.object({bindings:oe,answers:ie,values:e.record(e.string(),$).optional()}).strict();function H(t,n,i=1){if(t==="free")return"";if(t==="one_time")return n.startsWith("zh")?" · 一次付款":" · one-time";let u=n.split("-")[0]??"en",a={zh:["/月","/年"],en:["/month","/year"],ja:["/月","/年"],ko:["/월","/년"],es:["/mes","/año"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/mês","/ano"],it:["/mese","/anno"],ar:["/شهر","/سنة"]},s={zh:"周",en:"week",ja:"週",ko:"주",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"أسبوع"},r=t==="week"?`/${s[u]??s.en}`:(a[u]??a.en)[t==="month"?0:1];return i===1?r:`/${i} ${r.slice(1)}${u==="en"?"s":""}`}function De(t,n){let i=[],u={};_(t,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker")return;let s=a.bind?.plan?[a.bind.plan]:[];a.bind?.picker&&_(t,r=>{if(r.type==="plan_picker"&&r.id===a.bind?.picker&&s.push(...r.planIds??[]),r.type==="stack"&&r.interaction?.type==="select"&&r.interaction.pickerId===a.bind?.picker)for(let o of r.children)o.type==="stack"&&o.bind?.plan&&s.push(o.bind.plan)}),s.length||i.push(`Quantity control ${a.id} needs a Product binding`);for(let r of new Set(s)){let o=n[r]?.prepaid?.find(c=>c.internalFeatureId===a.internalFeatureId)?.terms,d=u[r]??=new Set;(!o||d.has(a.internalFeatureId)||a.minimumQuantity<o.minimumQuantity||a.maximumQuantity>o.maximumQuantity)&&i.push(`Quantity control ${a.id} must match its Product's prepaid Feature and bounds`),d.add(a.internalFeatureId)}});for(let[a,s]of Object.entries(n))for(let r of s.prepaid??[])u[a]?.has(r.internalFeatureId)||i.push(`Product ${a} needs a quantity control for ${r.internalFeatureId}`);return i}function Ke(t,n,i,u){let a=u.plans[n];if(!a?.available)throw new Error("Selected Product is unavailable");let s={};if(_(t,r=>{if(r.hidden)return!1;if(r.type!=="quantity_picker"||r.hidden||(r.bind?.plan??(r.bind?.picker?i[r.bind.picker]:void 0))!==n)return;if(u.quantities?.[r.id]?.available===!1)throw new Error("This prepaid Feature is unavailable");let d=a.prepaid?.find(l=>l.internalFeatureId===r.internalFeatureId)?.terms,c=i[r.id];if(!d||typeof c!="number"||!Number.isSafeInteger(c)||c<Math.max(d.minimumQuantity,r.minimumQuantity)||c>Math.min(d.maximumQuantity,r.maximumQuantity)||(c-r.minimumQuantity)%r.step!==0||s[r.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");s[r.internalFeatureId]=c}),(a.prepaid??[]).some(r=>s[r.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return s}function ue(t,n,i){let u=t.terms.prices.find(a=>a.currency===n);if(!u||i<t.terms.minimumQuantity||i>t.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:U({quantity:i,unitAmountMinor:u.amountMinor,...u.pricing?{pricing:u.pricing}:{}}),allowance:D(t.includedAmount,t.terms.units,i)}}function Ne(t,n,i,u){let a=!1;if(_(t,o=>{o.type==="quantity_picker"&&(a=!0)}),!a)return n;let s=structuredClone(n);s.quantities={};let r=new Map;_(t,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker")return;let d=o.bind?.plan??(o.bind?.picker?i[o.bind.picker]??s.pickers[o.bind.picker]?.selected:void 0),c=typeof d=="string"?s.plans[d]:void 0,l=c?.prepaid?.find(G=>G.internalFeatureId===o.internalFeatureId),k=Math.max(o.minimumQuantity,l?.terms.minimumQuantity??0),x=Math.min(o.maximumQuantity,l?.terms.maximumQuantity??0),b=i[o.id]??o.defaultQuantity,h=typeof b=="number"&&Number.isSafeInteger(b)?b:o.defaultQuantity,S=!!l&&!!c?.available&&n.quantities?.[o.id]?.available!==!1&&h>=k&&h<=x&&(h-o.minimumQuantity)%o.step===0,P=s.quantities[o.id]={minimum:k,maximum:Math.max(k,x),step:o.step,value:h,label:"",available:S};if(!S||!l||!c?.currency||c.amountMinor===void 0)return;let M=ue(l,c.currency,h);P.label=`${new Intl.NumberFormat(u).format(Number(M.allowance))} ${l.name}${["week","month","year"].includes(l.reset)?H(l.reset,u,l.resetCount):l.reset==="lifetime"?"":` / ${l.resetCount} ${l.reset}`}`,M.amountMinor!==0&&r.set(String(d),(r.get(String(d))??c.amountMinor)+M.amountMinor)});for(let[o,d]of r){let c=s.plans[o];if(!c?.currency)continue;let l=F(d,c.currency,u);c.price=l;for(let[k,x]of Object.entries(s.nodes)){let b=K(t,k),h=S=>{if(S.price&&(S.price={...S.price,current:l,original:null}),b?.type==="text"){let P=t.strings.locales[u]?.[b.text]??t.strings.locales[t.strings.defaultLocale]?.[b.text];P?.includes("{{plan.price")&&(S.text=P.replace(/\{\{\s*plan.price\s*\}\}/g,l).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,F(Math.round(d/((c.interval==="year"?12:1)*(c.intervalCount??1))),c.currency,u)))}};x.byPlan?.[o]&&h(x.byPlan[o]),(x.base.planVersionId===o||b&&"bind"in b&&b.bind?.plan===o)&&h(x.base)}}return s}export{le as a,J as b,Q as c,de as d,me as e,T as f,ye as g,V as h,y as i,we as j,ke as k,je as l,Ce as m,ie as n,ze as o,oe as p,Re as q,H as r,De as s,Ke as t,Ne as u};
1
+ import{C as K,b as U,d as D,v as _}from"./chunk-EJSTRCBQ.js";import{a as z,c as F}from"./chunk-26QYDE7V.js";import{d as $}from"./chunk-LUVTP4VU.js";import{i as C,j as m,l as O,m as g}from"./chunk-TFPLIX5E.js";import{b as e}from"./chunk-S7NHVERO.js";var I=m.refine(t=>/[1-9]/.test(t),"Quantity must be positive"),j=e.string().min(1).max(120),R=e.enum(["cap","overflow"]),p=(t,n)=>{let[i,u=""]=t.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");return BigInt(i)*10n**BigInt(n)+BigInt(u.padEnd(n,"0"))},A=t=>{try{return t()}catch{return!1}},le=e.discriminatedUnion("operation",[e.object({operation:e.literal("quote"),overageBehavior:R.optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g}).strict(),e.object({operation:e.literal("consume"),overageBehavior:R.optional(),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:m,properties:g,idempotencyKey:j}).strict(),e.object({operation:e.literal("reserve"),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g,idempotencyKey:j,expiresInSeconds:e.number().int().min(1).max(86400)}).strict(),e.object({operation:e.literal("confirm"),operationId:e.uuid(),quantity:I,properties:g.optional(),idempotencyKey:j}).strict(),e.object({operation:e.literal("refund"),operationId:e.uuid(),quantity:I,idempotencyKey:j}).strict(),e.object({operation:e.literal("release"),operationId:e.uuid(),idempotencyKey:j}).strict()]),J=e.object({internal_credit_feature_id:e.uuid().nullable(),internal_metered_feature_id:e.uuid(),dimension:e.string().min(1).max(64),counterKey:e.string().min(1).max(240),cycleStart:e.iso.datetime({offset:!0}),unitCost:m,units:I,amount:C,tier:e.number().int().min(1).max(12).nullable()}).strict(),Q=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function N(t,n){let i=t.reduce((u,a)=>u+p(a.units,12),0n)-p(n,12);return t.some(u=>u.funding==="balance")?i>=-100n&&i<=100n:i===0n}var v=e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q.refine(t=>/[1-9]/.test(t)),amount:C}),e.strictObject({funding:e.literal("unbilled"),units:Q.refine(t=>/[1-9]/.test(t))}),e.object({funding:e.literal("prepaid"),sourceId:e.uuid(),units:I,amount:C,pricing:e.array(J).min(1).max(12)}).strict().refine(t=>A(()=>t.pricing.reduce((n,i)=>n+p(i.units,6),0n)===p(t.units,6)&&t.pricing.reduce((n,i)=>n+p(i.amount,12),0n)===p(t.amount,12)&&t.pricing.every(n=>p(n.unitCost,6)*p(n.units,6)===p(n.amount,12))),"Frozen pricing must conserve allocated units and amounts"),e.object({funding:e.literal("postpaid"),invoiceLineId:e.uuid().nullable(),units:I,authorizationId:e.uuid()}).strict()]),B=e.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),de=e.object({allowed:e.boolean(),internal_feature_id:e.uuid(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),reason:B.nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.allowed?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"A quote must conserve its accepted units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0&&/[1-9]/.test(t.quantity):t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Explicit overage behavior must retain the requested quantity"),me=e.object({id:e.uuid(),internal_feature_id:e.uuid(),kind:e.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),createdAt:e.iso.datetime({offset:!0}),reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:e.iso.datetime({offset:!0}).nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.accepted?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"An operation must conserve its requested units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0:t.kind==="consume"&&t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(t=>/[1-9]/.test(t.quantity)||t.kind==="consume","Only consumption can record a zero cost event").refine(t=>t.allocations.every(n=>n.funding!=="postpaid"||n.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(t=>t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null)&&(t.kind!=="reserve"||!t.accepted||t.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var X=e.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Y=e.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),T=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable()}),ye=T.extend({quantity:m,expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:e.string().min(1).max(120),properties:g.refine(t=>Object.keys(t).length<=13&&!Object.keys(t).some(n=>n.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),V=T.extend({operationId:e.uuid().nullable(),usage:m,capacity:X.nullable(),remaining:Y.nullable(),withinLimit:e.boolean(),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}).strict().superRefine((t,n)=>{let i=u=>{let a=u.startsWith("-"),[s,r=""]=(a?u.slice(1):u).split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(s)*10n**12n+BigInt(r.padEnd(12,"0")))};(t.capacity===null!=(t.remaining===null)||(t.capacity===null?!t.withinLimit:t.remaining===null||i(t.remaining)!==i(t.capacity)-i(t.usage)||t.withinLimit!==i(t.remaining)>=0n)||t.revision===0!=(t.operationId===null)||t.operationId===null!=(t.updatedAt===null))&&n.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var y=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),f=e.iso.datetime({offset:!0}),ee=e.enum(["access","metered","credit"]),q={internal_feature_id:e.uuid(),key:O,name:e.string().min(1).max(120),kind:ee},we=e.object({customerId:e.uuid(),snapshotAt:f,memberships:e.array(e.object({id:e.uuid(),productId:e.string().min(1).max(255),productVersionId:e.uuid(),billingProductVersionId:e.uuid(),version:e.number().int().positive(),key:e.string().min(1).max(64),name:e.string().min(1).max(120),groupId:e.string().max(255).nullable(),membershipType:e.enum(["main","addon"]),status:e.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:e.boolean(),accessEnabled:e.boolean(),renewalChange:e.object({productVersionId:e.uuid(),name:e.string().min(1).max(120),version:e.number().int().positive(),effectiveAt:f,benefitsAppliedAt:f.nullable(),timing:e.enum(["immediate","renewal"]),changeKind:e.enum(["plan","seats","quantity"]),feature:e.strictObject({internal_feature_id:e.uuid(),name:e.string().min(1).max(80),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).optional(),seat:e.object({key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).strict().nullable(),status:e.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(t=>t.changeKind==="seats"==(t.seat!==null)&&t.changeKind==="quantity"==(t.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:e.object({phase:e.enum(["paid","trial"]),startsAt:f,endsAt:f.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:e.boolean(),balances:e.array(e.object({...q,usageType:e.enum(["consumable","non_consumable"]).nullable(),accessible:e.boolean(),unlimited:e.boolean(),available:y,held:y,debt:y,nextExpiresAt:f.nullable(),usage:V.nullable()}).strict().refine(t=>t.kind==="metered"==(t.usageType!==null)&&(t.accessible||t.available==="0"&&t.held==="0")&&(t.usageType==="non_consumable"?t.usage!==null&&t.usage.internal_feature_id===t.internal_feature_id&&t.unlimited===(t.usage.capacity===null)&&t.available===(t.usage.remaining===null||t.usage.remaining.startsWith("-")?"0":t.usage.remaining)&&t.held==="0"&&t.debt==="0":t.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:e.boolean()}).strict(),Z=e.enum(["source","usage","transaction","invoice","debt","settlement"]),E=e.object({at:f,id:e.uuid(),type:Z}).strict(),ke=e.object({type:Z.nullable(),resourceKey:O.optional(),kind:e.enum(["purchase","refund"]).optional(),topup:e.boolean().optional(),from:e.iso.date().nullable(),to:e.iso.date().nullable(),after:E.nullable(),limit:e.number().int().min(1).max(50)}).strict().refine(t=>!t.from||!t.to||t.from<=t.to,"Date range is reversed"),w={id:e.uuid(),occurredAt:f},te=e.discriminatedUnion("type",[e.strictObject({...w,type:e.literal("invoice"),status:e.string().min(1).max(80),paid:y,refunded:y,currency:z,externalId:e.string().nullable()}),e.object({...w,...q,type:e.literal("source"),reason:e.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:y,unlimited:e.boolean(),status:e.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:f,expiresAt:f.nullable(),orderId:e.uuid().nullable(),parentSourceId:e.uuid().nullable()}).strict(),e.object({...w,type:e.literal("usage"),internal_feature_id:e.uuid(),name:e.string().min(1).max(120),kind:e.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),properties:g,reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:f.nullable(),charges:e.array(e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q,amount:y}),e.strictObject({funding:e.literal("unbilled"),units:Q}),e.object({...q,funding:e.literal("prepaid"),amount:y}).strict(),e.object({funding:e.literal("postpaid"),invoiceId:e.uuid(),invoiceLineId:e.uuid(),authorizationId:e.uuid(),units:m,currency:z}).strict()])).max(500)}).strict().refine(t=>(t.kind==="set_usage"||t.kind==="consume"&&t.quantity==="0"?t.accepted&&t.reason===null&&t.charges.length===0&&t.reservationStatus===null:t.accepted?t.reason===null&&t.charges.length>0:t.reason!==null&&t.charges.length===0)&&t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),e.object({...w,type:e.literal("transaction"),purpose:e.enum(["product","invoice"]),productVersionId:e.uuid().nullable(),productName:e.string().min(1).max(120).nullable(),productVersion:e.number().int().positive().nullable(),invoiceId:e.uuid().nullable(),orderId:e.uuid(),originalId:e.uuid().nullable(),kind:e.enum(["purchase","refund"]),amountMinor:e.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(t=>t.currency===null==(t.amountMinor===null)&&(t.purpose==="product"?t.productVersionId!==null&&t.productName!==null&&t.productVersion!==null&&t.invoiceId===null:t.productVersionId===null&&t.productName===null&&t.productVersion===null&&t.invoiceId!==null)&&t.kind==="refund"==(t.originalId!==null)&&(t.kind!=="refund"||t.amountMinor===null||t.amountMinor>0),"Payment fact provenance is incomplete"),e.object({...w,...q,type:e.literal("debt"),sourceId:e.uuid(),transactionId:e.uuid(),amount:y}).strict(),e.object({...w,...q,type:e.literal("settlement"),sourceId:e.uuid(),debtId:e.uuid(),kind:e.enum(["payment","usage_refund","payment_return"]),amount:y}).strict()]),je=e.object({customerId:e.uuid(),rows:e.array(te).max(50),nextCursor:E.nullable()}).strict().refine(t=>new Set(t.rows.map(n=>n.type+n.id)).size===t.rows.length,"A page cannot repeat a fact").refine(t=>{let n=t.rows.at(-1);return!t.nextCursor||!!(n&&n.id===t.nextCursor.id&&n.type===t.nextCursor.type&&n.occurredAt===t.nextCursor.at)},"Cursor must name the final displayed fact");var Ce=e.discriminatedUnion("kind",[e.object({kind:e.literal("ledger"),cursor:E}).strict(),e.object({kind:e.literal("billing"),cursor:e.uuid()}).strict()]),ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ie=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),e.union([e.string().max(500),e.boolean(),e.array(e.string().max(500)).max(50)])).refine(t=>Object.keys(t).length<=40,"Too many answers"),re=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function L(t,n=0){return n>20?!0:!!t&&typeof t=="object"&&(Array.isArray(t)?t.some(i=>L(i,n+1)):Object.entries(t).some(([i,u])=>["__proto__","constructor","prototype"].includes(i)||re.test(i)||L(u,n+1)))}var ae=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ze=e.record(ne,$).refine(t=>Object.keys(t).length<=20,"Too many parameters").refine(t=>!L(t)&&!ae.test(JSON.stringify(t)),"Credentials cannot be screen parameters");var W=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oe=e.array(e.object({variable:W,componentId:W,required:e.boolean()}).strict()).max(40).refine(t=>new Set(t.map(n=>n.variable)).size===t.length&&new Set(t.map(n=>n.componentId)).size===t.length,"Input bindings must be unique"),Re=e.object({bindings:oe,answers:ie,values:e.record(e.string(),$).optional()}).strict();function H(t,n,i=1){if(t==="free")return"";if(t==="one_time")return n.startsWith("zh")?" · 一次付款":" · one-time";let u=n.split("-")[0]??"en",a={zh:["/月","/年"],en:["/month","/year"],ja:["/月","/年"],ko:["/월","/년"],es:["/mes","/año"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/mês","/ano"],it:["/mese","/anno"],ar:["/شهر","/سنة"]},s={zh:"周",en:"week",ja:"週",ko:"주",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"أسبوع"},r=t==="week"?`/${s[u]??s.en}`:(a[u]??a.en)[t==="month"?0:1];return i===1?r:`/${i} ${r.slice(1)}${u==="en"?"s":""}`}function De(t,n){let i=[],u={};_(t,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker")return;let s=a.bind?.plan?[a.bind.plan]:[];a.bind?.picker&&_(t,r=>{if(r.type==="plan_picker"&&r.id===a.bind?.picker&&s.push(...r.planIds??[]),r.type==="stack"&&r.interaction?.type==="select"&&r.interaction.pickerId===a.bind?.picker)for(let o of r.children)o.type==="stack"&&o.bind?.plan&&s.push(o.bind.plan)}),s.length||i.push(`Quantity control ${a.id} needs a Product binding`);for(let r of new Set(s)){let o=n[r]?.prepaid?.find(c=>c.internalFeatureId===a.internalFeatureId)?.terms,d=u[r]??=new Set;(!o||d.has(a.internalFeatureId)||a.minimumQuantity<o.minimumQuantity||a.maximumQuantity>o.maximumQuantity)&&i.push(`Quantity control ${a.id} must match its Product's prepaid Feature and bounds`),d.add(a.internalFeatureId)}});for(let[a,s]of Object.entries(n))for(let r of s.prepaid??[])u[a]?.has(r.internalFeatureId)||i.push(`Product ${a} needs a quantity control for ${r.internalFeatureId}`);return i}function Ke(t,n,i,u){let a=u.plans[n];if(!a?.available)throw new Error("Selected Product is unavailable");let s={};if(_(t,r=>{if(r.hidden)return!1;if(r.type!=="quantity_picker"||r.hidden||(r.bind?.plan??(r.bind?.picker?i[r.bind.picker]:void 0))!==n)return;if(u.quantities?.[r.id]?.available===!1)throw new Error("This prepaid Feature is unavailable");let d=a.prepaid?.find(l=>l.internalFeatureId===r.internalFeatureId)?.terms,c=i[r.id];if(!d||typeof c!="number"||!Number.isSafeInteger(c)||c<Math.max(d.minimumQuantity,r.minimumQuantity)||c>Math.min(d.maximumQuantity,r.maximumQuantity)||(c-r.minimumQuantity)%r.step!==0||s[r.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");s[r.internalFeatureId]=c}),(a.prepaid??[]).some(r=>s[r.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return s}function ue(t,n,i){let u=t.terms.prices.find(a=>a.currency===n);if(!u||i<t.terms.minimumQuantity||i>t.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:U({quantity:i,unitAmountMinor:u.amountMinor,...u.pricing?{pricing:u.pricing}:{}}),allowance:D(t.includedAmount,t.terms.units,i)}}function Ne(t,n,i,u){let a=!1;if(_(t,o=>{o.type==="quantity_picker"&&(a=!0)}),!a)return n;let s=structuredClone(n);s.quantities={};let r=new Map;_(t,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker")return;let d=o.bind?.plan??(o.bind?.picker?i[o.bind.picker]??s.pickers[o.bind.picker]?.selected:void 0),c=typeof d=="string"?s.plans[d]:void 0,l=c?.prepaid?.find(G=>G.internalFeatureId===o.internalFeatureId),k=Math.max(o.minimumQuantity,l?.terms.minimumQuantity??0),x=Math.min(o.maximumQuantity,l?.terms.maximumQuantity??0),b=i[o.id]??o.defaultQuantity,h=typeof b=="number"&&Number.isSafeInteger(b)?b:o.defaultQuantity,S=!!l&&!!c?.available&&n.quantities?.[o.id]?.available!==!1&&h>=k&&h<=x&&(h-o.minimumQuantity)%o.step===0,P=s.quantities[o.id]={minimum:k,maximum:Math.max(k,x),step:o.step,value:h,label:"",available:S};if(!S||!l||!c?.currency||c.amountMinor===void 0)return;let M=ue(l,c.currency,h);P.label=`${new Intl.NumberFormat(u).format(Number(M.allowance))} ${l.name}${["week","month","year"].includes(l.reset)?H(l.reset,u,l.resetCount):l.reset==="lifetime"?"":` / ${l.resetCount} ${l.reset}`}`,M.amountMinor!==0&&r.set(String(d),(r.get(String(d))??c.amountMinor)+M.amountMinor)});for(let[o,d]of r){let c=s.plans[o];if(!c?.currency)continue;let l=F(d,c.currency,u);c.price=l;for(let[k,x]of Object.entries(s.nodes)){let b=K(t,k),h=S=>{if(S.price&&(S.price={...S.price,current:l,original:null}),b?.type==="text"){let P=t.strings.locales[u]?.[b.text]??t.strings.locales[t.strings.defaultLocale]?.[b.text];P?.includes("{{plan.price")&&(S.text=P.replace(/\{\{\s*plan.price\s*\}\}/g,l).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,F(Math.round(d/((c.interval==="year"?12:1)*(c.intervalCount??1))),c.currency,u)))}};x.byPlan?.[o]&&h(x.byPlan[o]),(x.base.planVersionId===o||b&&"bind"in b&&b.bind?.plan===o)&&h(x.base)}}return s}export{le as a,J as b,Q as c,de as d,me as e,T as f,ye as g,V as h,y as i,we as j,ke as k,je as l,Ce as m,ie as n,ze as o,oe as p,Re as q,H as r,De as s,Ke as t,Ne as u};
@@ -1 +1 @@
1
- import{b as e}from"./chunk-YLH3AYCK.js";var s=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,o=e.object({customerId:e.uuid(),sessionId:e.uuid(),accessToken:e.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:e.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:e.iso.datetime(),refreshExpiresAt:e.iso.datetime()});export{s as a,o as b};
1
+ import{b as e}from"./chunk-S7NHVERO.js";var s=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,o=e.object({customerId:e.uuid(),sessionId:e.uuid(),accessToken:e.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:e.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:e.iso.datetime(),refreshExpiresAt:e.iso.datetime()});export{s as a,o as b};
@@ -1 +1 @@
1
- import{C as d,D as u}from"./chunk-3Q3DZEP3.js";function f(r){let{quote:o,operation:e,requestId:s}=r,a={type:"recover",operationId:e?.operationId??o?.operationId??null,requestId:s};if(r.destroyed||r.pending)return a;if(!e)return o?{type:"cancel",operationId:o.operationId}:a;let t=e.merchantExecution;if(d(e)){if(t&&t.type!=="subscription_change")return a;if(t?.type==="subscription_change"){if(["applied","scheduled"].includes(t.status))return!["applied","not_applicable"].includes(t.fulfillmentStatus)||e.problem?.phase==="fulfillment"||t.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:t.recordingStatus==="accepted"&&u(e)&&!e.problem&&!t.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&!e.problem&&!t.problem&&t.nextAction?.type==="redirect"&&(!e.checkoutUrl||t.nextAction.url===e.checkoutUrl)&&Date.parse(t.nextAction.expiresAt)>Date.now()&&t.status==="pending")return{type:"checkout",operationId:e.operationId,checkoutUrl:t.nextAction.url}}if(!e.problem&&!t?.problem&&u(e)&&e.executor!=="merchant")return{type:"complete",operationId:e.operationId};if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let n=p=>!p||p.phase==="execution"&&p.reason==="STATE_CHANGED";return r.canReselect===!0&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&n(e.problem)&&n(t?.problem)&&(!t||t.status==="failed"&&t.recordingStatus==="accepted"&&t.fulfillmentStatus==="not_applicable")?{type:"native",operationId:e.operationId}:["prepared","quoted"].includes(e.status)&&!e.confirmedAt&&!t&&!e.checkoutUrl&&!e.problem?{type:"cancel",operationId:e.operationId}:a}if(t?.type==="purchase"){if(["succeeded","not_required"].includes(t.paymentStatus))return!["applied","not_applicable"].includes(t.fulfillmentStatus)||e.problem?.phase==="fulfillment"||t.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:t.recordingStatus==="accepted"&&e.status==="complete"&&!e.problem&&!t.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&!e.problem&&!t.problem&&t.checkoutUrl===e.checkoutUrl&&t.checkoutExpiresAt&&Date.parse(t.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(t.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&!e.nativePurchase&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let c=[e.problem,t?.problem],i=c.every(n=>!n||n.phase==="execution"&&n.reason!=="RESULT_UNKNOWN"),y=e.status==="cancelled"&&!c.some(Boolean)&&t?.type==="purchase"&&["pending","not_started","expired"].includes(t.paymentStatus)&&["not_started","not_applicable"].includes(t.fulfillmentStatus);return r.canReselect===!0&&i&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"||!t||t.type==="purchase"&&!["succeeded","not_required"].includes(t.paymentStatus)&&(y||t.recordingStatus==="accepted"&&t.fulfillmentStatus==="not_applicable"))?{type:"native",operationId:e.operationId}:!c.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:i&&r.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!t&&!e.quoteFinalized||t?.type==="purchase"&&["failed","expired"].includes(t.paymentStatus)&&t.fulfillmentStatus==="not_applicable"&&t.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&i&&!e.quoteFinalized&&!t&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:a}function h(r,o=!0){if(!r)return!1;let e=f({quote:r.quote??null,operation:r,requestId:null,pending:!1,destroyed:!1,canReselect:o});return e.type==="complete"||e.type==="native"}function l(r){return r.recovery??{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null}}function b(r){return!!(r?.operationId&&(r.type==="checkout"||r.type==="recover"||r.type==="fulfillment"||r.type==="recording"))}async function g(r){let o=l(r);if(o.type==="recover"&&r.quote)try{await r.read(),o=l(r)}catch{return o}if(o.type!=="cancel"&&!(o.type==="recover"&&r.pendingCancellation))return o;try{await r.cancel();let e=l(r);return e.type==="cancel"?{type:"recover",operationId:o.operationId,requestId:null}:e}catch{let e=l(r);return e.type==="recover"?e:{type:"recover",operationId:o.operationId,requestId:null}}}export{f as a,h as b,l as c,b as d,g as e};
1
+ import{C as d,D as u}from"./chunk-WVTKVQLZ.js";function f(r){let{quote:o,operation:e,requestId:s}=r,a={type:"recover",operationId:e?.operationId??o?.operationId??null,requestId:s};if(r.destroyed||r.pending)return a;if(!e)return o?{type:"cancel",operationId:o.operationId}:a;let t=e.merchantExecution;if(d(e)){if(t&&t.type!=="subscription_change")return a;if(t?.type==="subscription_change"){if(["applied","scheduled"].includes(t.status))return!["applied","not_applicable"].includes(t.fulfillmentStatus)||e.problem?.phase==="fulfillment"||t.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:t.recordingStatus==="accepted"&&u(e)&&!e.problem&&!t.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&!e.problem&&!t.problem&&t.nextAction?.type==="redirect"&&(!e.checkoutUrl||t.nextAction.url===e.checkoutUrl)&&Date.parse(t.nextAction.expiresAt)>Date.now()&&t.status==="pending")return{type:"checkout",operationId:e.operationId,checkoutUrl:t.nextAction.url}}if(!e.problem&&!t?.problem&&u(e)&&e.executor!=="merchant")return{type:"complete",operationId:e.operationId};if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let n=p=>!p||p.phase==="execution"&&p.reason==="STATE_CHANGED";return r.canReselect===!0&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&n(e.problem)&&n(t?.problem)&&(!t||t.status==="failed"&&t.recordingStatus==="accepted"&&t.fulfillmentStatus==="not_applicable")?{type:"native",operationId:e.operationId}:["prepared","quoted"].includes(e.status)&&!e.confirmedAt&&!t&&!e.checkoutUrl&&!e.problem?{type:"cancel",operationId:e.operationId}:a}if(t?.type==="purchase"){if(["succeeded","not_required"].includes(t.paymentStatus))return!["applied","not_applicable"].includes(t.fulfillmentStatus)||e.problem?.phase==="fulfillment"||t.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:t.recordingStatus==="accepted"&&e.status==="complete"&&!e.problem&&!t.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&!e.problem&&!t.problem&&t.checkoutUrl===e.checkoutUrl&&t.checkoutExpiresAt&&Date.parse(t.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(t.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&!e.nativePurchase&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let c=[e.problem,t?.problem],i=c.every(n=>!n||n.phase==="execution"&&n.reason!=="RESULT_UNKNOWN"),y=e.status==="cancelled"&&!c.some(Boolean)&&t?.type==="purchase"&&["pending","not_started","expired"].includes(t.paymentStatus)&&["not_started","not_applicable"].includes(t.fulfillmentStatus);return r.canReselect===!0&&i&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"||!t||t.type==="purchase"&&!["succeeded","not_required"].includes(t.paymentStatus)&&(y||t.recordingStatus==="accepted"&&t.fulfillmentStatus==="not_applicable"))?{type:"native",operationId:e.operationId}:!c.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:i&&r.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!t&&!e.quoteFinalized||t?.type==="purchase"&&["failed","expired"].includes(t.paymentStatus)&&t.fulfillmentStatus==="not_applicable"&&t.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&i&&!e.quoteFinalized&&!t&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:a}function h(r,o=!0){if(!r)return!1;let e=f({quote:r.quote??null,operation:r,requestId:null,pending:!1,destroyed:!1,canReselect:o});return e.type==="complete"||e.type==="native"}function l(r){return r.recovery??{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null}}function b(r){return!!(r?.operationId&&(r.type==="checkout"||r.type==="recover"||r.type==="fulfillment"||r.type==="recording"))}async function g(r){let o=l(r);if(o.type==="recover"&&r.quote)try{await r.read(),o=l(r)}catch{return o}if(o.type!=="cancel"&&!(o.type==="recover"&&r.pendingCancellation))return o;try{await r.cancel();let e=l(r);return e.type==="cancel"?{type:"recover",operationId:o.operationId,requestId:null}:e}catch{let e=l(r);return e.type==="recover"?e:{type:"recover",operationId:o.operationId,requestId:null}}}export{f as a,h as b,l as c,b as d,g as e};
@@ -1 +1 @@
1
- import{b as e}from"./chunk-YLH3AYCK.js";var y=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),z=e.discriminatedUnion("type",[e.object({type:e.literal("fixed"),productVersionId:e.string().min(1).max(200)}).strict(),e.object({type:e.literal("picker"),pickerId:y,allowedProductVersionIds:e.array(e.string().min(1).max(200)).min(1).max(20)}).strict().refine(t=>new Set(t.allowedProductVersionIds).size===t.allowedProductVersionIds.length,"Product choices must be unique")]),x=e.strictObject({min:e.number().finite().min(1).max(1800),max:e.number().finite().min(1).max(1800),viewport:e.number().finite().min(1).max(100)}).refine(t=>t.min<=t.max,"Desktop width range is reversed"),f={desktopWidth:x.optional(),mobile:e.enum(["sheet","fullscreen"]).optional(),backdrop:e.enum(["none","scrim","dim","strong-dim","blur"]).optional()},G=e.discriminatedUnion("type",[e.strictObject({type:e.literal("modal"),position:e.enum(["center","top","bottom"]).optional(),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("sheet"),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("fullscreen")}),e.strictObject({type:e.literal("inline")})]),V={sm:360,md:420,lg:560};var c=e.json().superRefine((t,i)=>{let s=0;function o(n,r){if(++s>1e4||r>20){i.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof n=="string"&&(n.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(n))&&i.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(n))n.forEach(a=>o(a,r+1));else if(n&&typeof n=="object")for(let[a,u]of Object.entries(n))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved JSON property"}),o(u,r+1)}o(t,0),new TextEncoder().encode(JSON.stringify(t)).byteLength>65536&&i.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),l=e.record(e.string().min(1).max(128),c).superRefine((t,i)=>{(!c.safeParse(t).success||Object.keys(t).length>128||new TextEncoder().encode(JSON.stringify(t)).byteLength>65536||["__proto__","constructor","prototype"].some(s=>Object.hasOwn(t,s)))&&i.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),S=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),d=l.superRefine((t,i)=>{function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o)){if(n==="$savedGroup"&&!e.strictObject({id:e.uuid(),attributeKey:e.string().min(1).max(128).optional()}).safeParse(r).success&&i.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!n.startsWith("$")&&n.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved attribute path"}),n.startsWith("$")&&!S.has(n)&&i.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${n}`}),["$regex","$regexi"].includes(n)&&typeof r=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(r)||[...r.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||n==="$regexi"&&/[^\x00-\x7f]/.test(r.replace(/\\u([0-9a-f]{4})/gi,(a,u)=>String.fromCharCode(Number.parseInt(u,16)))))&&i.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(r)}catch{i.addIssue({code:"custom",message:"Invalid regular expression"})}}s(r)}}typeof t.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(t.source)&&("operator"in t||"predicates"in t||"groupId"in t)&&i.addIssue({code:"custom",message:"Obsolete condition protocol"}),s(t)}),w=e.discriminatedUnion("type",[e.strictObject({type:e.literal("condition"),condition:d}),e.strictObject({type:e.literal("list"),attributeKey:e.string().min(1).max(128),values:e.array(e.union([e.string(),e.number().finite()])).max(1e5)})]).refine(t=>t.type!=="list"||new TextEncoder().encode(JSON.stringify(t.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function $(t){let i=new Set;function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o))n==="$savedGroup"&&r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.id=="string"?i.add(r.id):["$inGroup","$notInGroup"].includes(n)&&typeof r=="string"?i.add(r):["$eq","$ne","$in","$nin","$ini","$nini"].includes(n)||s(r)}return s(t),[...i]}var O=e.record(e.uuid(),w).superRefine((t,i)=>{let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:"Missing saved group dependency"});return}s.add(r),a.type==="condition"&&$(a.condition).forEach(n),s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),g=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,i])=>t<=i),h=e.strictObject({attribute:e.string().optional(),seed:e.string().min(1),hashVersion:e.literal(2),ranges:e.array(g).min(1).max(100)}),j=e.strictObject({id:e.string().min(1).max(128),condition:d,gate:e.boolean().optional()}),p={id:e.string().max(128).optional(),condition:d.optional(),parentConditions:e.array(j).max(50).optional(),filters:e.array(h).max(20).optional()},v=e.union([e.strictObject({...p}),e.strictObject({...p,force:c,coverage:e.number().min(0).max(1).optional(),range:g.optional(),seed:e.string().min(1).optional(),hashAttribute:e.string().optional(),hashVersion:e.literal(2).optional()}),e.strictObject({...p,type:e.literal("experiment-ref"),experimentId:e.uuid(),values:e.record(e.string().min(1),c),meta:e.record(e.string().min(1),e.strictObject({passthrough:e.boolean()})).optional()})]),k=e.strictObject({defaultValue:c,rules:e.array(v).max(100)}),U=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),k).superRefine((t,i)=>{Object.keys(t).length>100&&i.addIssue({code:"custom",message:"Too many Features"});let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:`Cyclic Feature dependency: ${r}`});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${r}`});return}s.add(r);for(let u of a.rules)for(let m of u.parentConditions??[])n(m.id);s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),F=e.strictObject({name:e.string().max(80),reason:e.string().max(500),dateStarted:e.iso.datetime({offset:!0}),dateEnded:e.iso.datetime({offset:!0}).nullable(),coverage:e.number().min(0).max(1),variationWeights:e.array(e.number().min(0).max(1)).min(2).max(20).refine(t=>Math.abs(t.reduce((i,s)=>i+s,0)-1)<=.01),condition:d,savedGroups:e.array(e.strictObject({match:e.enum(["any","all","none"]),ids:e.array(e.uuid()).min(1)})).max(50),namespace:e.strictObject({id:e.uuid(),ranges:e.array(g).min(1)}).nullable(),seed:e.string().min(1).max(128)}),A=e.strictObject({key:e.string().min(1).max(128),name:e.string().min(1).max(80),hypothesis:e.string().max(2e3),status:e.enum(["draft","running","stopped"]),hashAttribute:e.string().min(1).max(128),fallbackAttribute:e.string().max(128).nullable(),hashVersion:e.literal(2),disableStickyBucketing:e.boolean(),bucketVersion:e.number().int().min(0).max(1e3),minBucketVersion:e.number().int().min(0).max(1e3),variations:e.array(e.strictObject({id:e.string().min(1),key:e.string().min(1),name:e.string().max(80),description:e.string().max(500)})).min(2).max(20),phases:e.array(F).min(1).max(100),releasedVariationId:e.string().nullable(),excludeFromPayload:e.boolean(),statusSchedule:e.strictObject({startAt:e.iso.datetime({offset:!0}).nullable(),stopAt:e.iso.datetime({offset:!0}).nullable(),stopAfter:e.strictObject({value:e.number().int().positive().max(36500),unit:e.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((t,i)=>{(t.minBucketVersion>t.bucketVersion||t.statusSchedule?.stopAt&&t.statusSchedule?.stopAfter||t.phases.some((s,o)=>{if(o===0)return!1;let n=t.phases[o-1];return!n?.dateEnded||Date.parse(s.dateStarted)<Date.parse(n.dateStarted)||Date.parse(n.dateEnded)>Date.parse(s.dateStarted)})||new Set(t.variations.map(s=>s.key)).size!==t.variations.length||new Set(t.variations.map(s=>s.id)).size!==t.variations.length||t.releasedVariationId!==null&&!t.variations.some(s=>s.id===t.releasedVariationId)||t.statusSchedule?.startAt&&t.statusSchedule?.stopAt&&Date.parse(t.statusSchedule.startAt)>=Date.parse(t.statusSchedule.stopAt)||t.phases.some(s=>s.dateEnded&&Date.parse(s.dateStarted)>=Date.parse(s.dateEnded)||s.namespace?.ranges.some(([o,n],r,a)=>o>=n||a.some(([u,m],b)=>b!==r&&o<m&&u<n)))||t.phases.some(s=>s.variationWeights.length!==t.variations.length))&&i.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var I=A.safeExtend({filters:e.array(h).optional()}),D=e.strictObject({experiments:e.record(e.uuid(),I),savedGroups:O}),E=e.strictObject({attributeName:e.string(),attributeValue:e.string(),assignments:e.record(e.string(),e.string())}),M=e.strictObject({snapshot:D,attributes:l,results:l,stickyBucketAssignmentDocs:e.record(e.string(),E)}),W=e.strictObject({variantKey:e.string().nullable(),bucketVersion:e.number().int().min(0),source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:e.number().min(0).max(1).optional(),stickyBucketUsed:e.boolean().optional(),hashUsed:e.boolean().optional()});export{z as a,G as b,V as c,c as d,l as e,d as f,$ as g,E as h};
1
+ import{b as e}from"./chunk-S7NHVERO.js";var y=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),z=e.discriminatedUnion("type",[e.object({type:e.literal("fixed"),productVersionId:e.string().min(1).max(200)}).strict(),e.object({type:e.literal("picker"),pickerId:y,allowedProductVersionIds:e.array(e.string().min(1).max(200)).min(1).max(20)}).strict().refine(t=>new Set(t.allowedProductVersionIds).size===t.allowedProductVersionIds.length,"Product choices must be unique")]),x=e.strictObject({min:e.number().finite().min(1).max(1800),max:e.number().finite().min(1).max(1800),viewport:e.number().finite().min(1).max(100)}).refine(t=>t.min<=t.max,"Desktop width range is reversed"),f={desktopWidth:x.optional(),mobile:e.enum(["sheet","fullscreen"]).optional(),backdrop:e.enum(["none","scrim","dim","strong-dim","blur"]).optional()},G=e.discriminatedUnion("type",[e.strictObject({type:e.literal("modal"),position:e.enum(["center","top","bottom"]).optional(),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("sheet"),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("fullscreen")}),e.strictObject({type:e.literal("inline")})]),V={sm:360,md:420,lg:560};var c=e.json().superRefine((t,i)=>{let s=0;function o(n,r){if(++s>1e4||r>20){i.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof n=="string"&&(n.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(n))&&i.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(n))n.forEach(a=>o(a,r+1));else if(n&&typeof n=="object")for(let[a,u]of Object.entries(n))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved JSON property"}),o(u,r+1)}o(t,0),new TextEncoder().encode(JSON.stringify(t)).byteLength>65536&&i.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),l=e.record(e.string().min(1).max(128),c).superRefine((t,i)=>{(!c.safeParse(t).success||Object.keys(t).length>128||new TextEncoder().encode(JSON.stringify(t)).byteLength>65536||["__proto__","constructor","prototype"].some(s=>Object.hasOwn(t,s)))&&i.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),S=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),d=l.superRefine((t,i)=>{function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o)){if(n==="$savedGroup"&&!e.strictObject({id:e.uuid(),attributeKey:e.string().min(1).max(128).optional()}).safeParse(r).success&&i.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!n.startsWith("$")&&n.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved attribute path"}),n.startsWith("$")&&!S.has(n)&&i.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${n}`}),["$regex","$regexi"].includes(n)&&typeof r=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(r)||[...r.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||n==="$regexi"&&/[^\x00-\x7f]/.test(r.replace(/\\u([0-9a-f]{4})/gi,(a,u)=>String.fromCharCode(Number.parseInt(u,16)))))&&i.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(r)}catch{i.addIssue({code:"custom",message:"Invalid regular expression"})}}s(r)}}typeof t.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(t.source)&&("operator"in t||"predicates"in t||"groupId"in t)&&i.addIssue({code:"custom",message:"Obsolete condition protocol"}),s(t)}),w=e.discriminatedUnion("type",[e.strictObject({type:e.literal("condition"),condition:d}),e.strictObject({type:e.literal("list"),attributeKey:e.string().min(1).max(128),values:e.array(e.union([e.string(),e.number().finite()])).max(1e5)})]).refine(t=>t.type!=="list"||new TextEncoder().encode(JSON.stringify(t.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function $(t){let i=new Set;function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o))n==="$savedGroup"&&r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.id=="string"?i.add(r.id):["$inGroup","$notInGroup"].includes(n)&&typeof r=="string"?i.add(r):["$eq","$ne","$in","$nin","$ini","$nini"].includes(n)||s(r)}return s(t),[...i]}var O=e.record(e.uuid(),w).superRefine((t,i)=>{let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:"Missing saved group dependency"});return}s.add(r),a.type==="condition"&&$(a.condition).forEach(n),s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),g=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,i])=>t<=i),h=e.strictObject({attribute:e.string().optional(),seed:e.string().min(1),hashVersion:e.literal(2),ranges:e.array(g).min(1).max(100)}),j=e.strictObject({id:e.string().min(1).max(128),condition:d,gate:e.boolean().optional()}),p={id:e.string().max(128).optional(),condition:d.optional(),parentConditions:e.array(j).max(50).optional(),filters:e.array(h).max(20).optional()},v=e.union([e.strictObject({...p}),e.strictObject({...p,force:c,coverage:e.number().min(0).max(1).optional(),range:g.optional(),seed:e.string().min(1).optional(),hashAttribute:e.string().optional(),hashVersion:e.literal(2).optional()}),e.strictObject({...p,type:e.literal("experiment-ref"),experimentId:e.uuid(),values:e.record(e.string().min(1),c),meta:e.record(e.string().min(1),e.strictObject({passthrough:e.boolean()})).optional()})]),k=e.strictObject({defaultValue:c,rules:e.array(v).max(100)}),U=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),k).superRefine((t,i)=>{Object.keys(t).length>100&&i.addIssue({code:"custom",message:"Too many Features"});let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:`Cyclic Feature dependency: ${r}`});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${r}`});return}s.add(r);for(let u of a.rules)for(let m of u.parentConditions??[])n(m.id);s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),F=e.strictObject({name:e.string().max(80),reason:e.string().max(500),dateStarted:e.iso.datetime({offset:!0}),dateEnded:e.iso.datetime({offset:!0}).nullable(),coverage:e.number().min(0).max(1),variationWeights:e.array(e.number().min(0).max(1)).min(2).max(20).refine(t=>Math.abs(t.reduce((i,s)=>i+s,0)-1)<=.01),condition:d,savedGroups:e.array(e.strictObject({match:e.enum(["any","all","none"]),ids:e.array(e.uuid()).min(1)})).max(50),namespace:e.strictObject({id:e.uuid(),ranges:e.array(g).min(1)}).nullable(),seed:e.string().min(1).max(128)}),A=e.strictObject({key:e.string().min(1).max(128),name:e.string().min(1).max(80),hypothesis:e.string().max(2e3),status:e.enum(["draft","running","stopped"]),hashAttribute:e.string().min(1).max(128),fallbackAttribute:e.string().max(128).nullable(),hashVersion:e.literal(2),disableStickyBucketing:e.boolean(),bucketVersion:e.number().int().min(0).max(1e3),minBucketVersion:e.number().int().min(0).max(1e3),variations:e.array(e.strictObject({id:e.string().min(1),key:e.string().min(1),name:e.string().max(80),description:e.string().max(500)})).min(2).max(20),phases:e.array(F).min(1).max(100),releasedVariationId:e.string().nullable(),excludeFromPayload:e.boolean(),statusSchedule:e.strictObject({startAt:e.iso.datetime({offset:!0}).nullable(),stopAt:e.iso.datetime({offset:!0}).nullable(),stopAfter:e.strictObject({value:e.number().int().positive().max(36500),unit:e.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((t,i)=>{(t.minBucketVersion>t.bucketVersion||t.statusSchedule?.stopAt&&t.statusSchedule?.stopAfter||t.phases.some((s,o)=>{if(o===0)return!1;let n=t.phases[o-1];return!n?.dateEnded||Date.parse(s.dateStarted)<Date.parse(n.dateStarted)||Date.parse(n.dateEnded)>Date.parse(s.dateStarted)})||new Set(t.variations.map(s=>s.key)).size!==t.variations.length||new Set(t.variations.map(s=>s.id)).size!==t.variations.length||t.releasedVariationId!==null&&!t.variations.some(s=>s.id===t.releasedVariationId)||t.statusSchedule?.startAt&&t.statusSchedule?.stopAt&&Date.parse(t.statusSchedule.startAt)>=Date.parse(t.statusSchedule.stopAt)||t.phases.some(s=>s.dateEnded&&Date.parse(s.dateStarted)>=Date.parse(s.dateEnded)||s.namespace?.ranges.some(([o,n],r,a)=>o>=n||a.some(([u,m],b)=>b!==r&&o<m&&u<n)))||t.phases.some(s=>s.variationWeights.length!==t.variations.length))&&i.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var I=A.safeExtend({filters:e.array(h).optional()}),D=e.strictObject({experiments:e.record(e.uuid(),I),savedGroups:O}),E=e.strictObject({attributeName:e.string(),attributeValue:e.string(),assignments:e.record(e.string(),e.string())}),M=e.strictObject({snapshot:D,attributes:l,results:l,stickyBucketAssignmentDocs:e.record(e.string(),E)}),W=e.strictObject({variantKey:e.string().nullable(),bucketVersion:e.number().int().min(0),source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:e.number().min(0).max(1).optional(),stickyBucketUsed:e.boolean().optional(),hashUsed:e.boolean().optional()});export{z as a,G as b,V as c,c as d,l as e,d as f,$ as g,E as h};